@sveltejs/kit 1.0.0-next.23 → 1.0.0-next.230

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 (83) hide show
  1. package/README.md +12 -9
  2. package/assets/app/env.js +20 -0
  3. package/assets/app/navigation.js +81 -0
  4. package/assets/app/paths.js +1 -0
  5. package/assets/{runtime/app → app}/stores.js +19 -15
  6. package/assets/chunks/utils.js +13 -0
  7. package/assets/client/singletons.js +18 -0
  8. package/assets/client/start.js +1382 -0
  9. package/assets/components/error.svelte +19 -3
  10. package/assets/env.js +8 -0
  11. package/assets/paths.js +13 -0
  12. package/assets/server/index.js +1998 -0
  13. package/dist/chunks/cert.js +28154 -0
  14. package/dist/chunks/index.js +2391 -0
  15. package/dist/chunks/index2.js +807 -0
  16. package/dist/chunks/index3.js +648 -0
  17. package/dist/chunks/index4.js +109 -0
  18. package/dist/chunks/index5.js +754 -0
  19. package/dist/chunks/index6.js +830 -0
  20. package/dist/chunks/index7.js +15574 -0
  21. package/dist/chunks/index8.js +4207 -0
  22. package/dist/chunks/misc.js +3 -0
  23. package/dist/chunks/multipart-parser.js +449 -0
  24. package/dist/chunks/url.js +62 -0
  25. package/dist/cli.js +1039 -84
  26. package/dist/hooks.js +28 -0
  27. package/dist/install-fetch.js +6514 -0
  28. package/dist/node.js +51 -0
  29. package/package.json +93 -54
  30. package/svelte-kit.js +2 -0
  31. package/types/ambient-modules.d.ts +204 -0
  32. package/types/app.d.ts +45 -0
  33. package/types/config.d.ts +169 -0
  34. package/types/endpoint.d.ts +20 -0
  35. package/types/helper.d.ts +53 -0
  36. package/types/hooks.d.ts +55 -0
  37. package/types/index.d.ts +18 -0
  38. package/types/internal.d.ts +237 -0
  39. package/types/page.d.ts +73 -0
  40. package/CHANGELOG.md +0 -294
  41. package/assets/runtime/app/navigation.js +0 -23
  42. package/assets/runtime/app/navigation.js.map +0 -1
  43. package/assets/runtime/app/paths.js +0 -2
  44. package/assets/runtime/app/paths.js.map +0 -1
  45. package/assets/runtime/app/stores.js.map +0 -1
  46. package/assets/runtime/internal/singletons.js +0 -15
  47. package/assets/runtime/internal/singletons.js.map +0 -1
  48. package/assets/runtime/internal/start.js +0 -591
  49. package/assets/runtime/internal/start.js.map +0 -1
  50. package/assets/runtime/utils-85ebcc60.js +0 -18
  51. package/assets/runtime/utils-85ebcc60.js.map +0 -1
  52. package/dist/api.js +0 -44
  53. package/dist/api.js.map +0 -1
  54. package/dist/build.js +0 -246
  55. package/dist/build.js.map +0 -1
  56. package/dist/cli.js.map +0 -1
  57. package/dist/colors.js +0 -37
  58. package/dist/colors.js.map +0 -1
  59. package/dist/create_app.js +0 -578
  60. package/dist/create_app.js.map +0 -1
  61. package/dist/index.js +0 -367
  62. package/dist/index.js.map +0 -1
  63. package/dist/index2.js +0 -12044
  64. package/dist/index2.js.map +0 -1
  65. package/dist/index3.js +0 -547
  66. package/dist/index3.js.map +0 -1
  67. package/dist/index4.js +0 -73
  68. package/dist/index4.js.map +0 -1
  69. package/dist/index5.js +0 -464
  70. package/dist/index5.js.map +0 -1
  71. package/dist/index6.js +0 -729
  72. package/dist/index6.js.map +0 -1
  73. package/dist/logging.js +0 -43
  74. package/dist/logging.js.map +0 -1
  75. package/dist/package.js +0 -432
  76. package/dist/package.js.map +0 -1
  77. package/dist/renderer.js +0 -2391
  78. package/dist/renderer.js.map +0 -1
  79. package/dist/standard.js +0 -101
  80. package/dist/standard.js.map +0 -1
  81. package/dist/utils.js +0 -54
  82. package/dist/utils.js.map +0 -1
  83. package/svelte-kit +0 -3
@@ -0,0 +1,1998 @@
1
+ /**
2
+ * @param {Record<string, string | string[] | undefined>} headers
3
+ * @param {string} key
4
+ * @returns {string | undefined}
5
+ * @throws {Error}
6
+ */
7
+ function get_single_valued_header(headers, key) {
8
+ const value = headers[key];
9
+ if (Array.isArray(value)) {
10
+ if (value.length === 0) {
11
+ return undefined;
12
+ }
13
+ if (value.length > 1) {
14
+ throw new Error(
15
+ `Multiple headers provided for ${key}. Multiple may be provided only for set-cookie`
16
+ );
17
+ }
18
+ return value[0];
19
+ }
20
+ return value;
21
+ }
22
+
23
+ /** @param {Record<string, any>} obj */
24
+ function lowercase_keys(obj) {
25
+ /** @type {Record<string, any>} */
26
+ const clone = {};
27
+
28
+ for (const key in obj) {
29
+ clone[key.toLowerCase()] = obj[key];
30
+ }
31
+
32
+ return clone;
33
+ }
34
+
35
+ /** @param {Record<string, string>} params */
36
+ function decode_params(params) {
37
+ for (const key in params) {
38
+ // input has already been decoded by decodeURI
39
+ // now handle the rest that decodeURIComponent would do
40
+ params[key] = params[key]
41
+ .replace(/%23/g, '#')
42
+ .replace(/%3[Bb]/g, ';')
43
+ .replace(/%2[Cc]/g, ',')
44
+ .replace(/%2[Ff]/g, '/')
45
+ .replace(/%3[Ff]/g, '?')
46
+ .replace(/%3[Aa]/g, ':')
47
+ .replace(/%40/g, '@')
48
+ .replace(/%26/g, '&')
49
+ .replace(/%3[Dd]/g, '=')
50
+ .replace(/%2[Bb]/g, '+')
51
+ .replace(/%24/g, '$');
52
+ }
53
+
54
+ return params;
55
+ }
56
+
57
+ /** @param {string} body */
58
+ function error(body) {
59
+ return {
60
+ status: 500,
61
+ body,
62
+ headers: {}
63
+ };
64
+ }
65
+
66
+ /** @param {unknown} s */
67
+ function is_string(s) {
68
+ return typeof s === 'string' || s instanceof String;
69
+ }
70
+
71
+ const text_types = new Set([
72
+ 'application/xml',
73
+ 'application/json',
74
+ 'application/x-www-form-urlencoded',
75
+ 'multipart/form-data'
76
+ ]);
77
+
78
+ /**
79
+ * Decides how the body should be parsed based on its mime type. Should match what's in parse_body
80
+ *
81
+ * @param {string | undefined | null} content_type The `content-type` header of a request/response.
82
+ * @returns {boolean}
83
+ */
84
+ function is_text(content_type) {
85
+ if (!content_type) return true; // defaults to json
86
+ const type = content_type.split(';')[0].toLowerCase(); // get the mime type
87
+
88
+ return type.startsWith('text/') || type.endsWith('+xml') || text_types.has(type);
89
+ }
90
+
91
+ /**
92
+ * @param {import('types/hooks').ServerRequest} request
93
+ * @param {import('types/internal').SSREndpoint} route
94
+ * @param {RegExpExecArray} match
95
+ * @returns {Promise<import('types/hooks').ServerResponse | undefined>}
96
+ */
97
+ async function render_endpoint(request, route, match) {
98
+ const mod = await route.load();
99
+
100
+ /** @type {import('types/endpoint').RequestHandler} */
101
+ const handler = mod[request.method.toLowerCase().replace('delete', 'del')]; // 'delete' is a reserved word
102
+
103
+ if (!handler) {
104
+ return;
105
+ }
106
+
107
+ // we're mutating `request` so that we don't have to do { ...request, params }
108
+ // on the next line, since that breaks the getters that replace path, query and
109
+ // origin. We could revert that once we remove the getters
110
+ request.params = route.params ? decode_params(route.params(match)) : {};
111
+
112
+ const response = await handler(request);
113
+ const preface = `Invalid response from route ${request.url.pathname}`;
114
+
115
+ if (typeof response !== 'object') {
116
+ return error(`${preface}: expected an object, got ${typeof response}`);
117
+ }
118
+
119
+ if (response.fallthrough) {
120
+ return;
121
+ }
122
+
123
+ let { status = 200, body, headers = {} } = response;
124
+
125
+ headers = lowercase_keys(headers);
126
+ const type = get_single_valued_header(headers, 'content-type');
127
+
128
+ if (!is_text(type) && !(body instanceof Uint8Array || is_string(body))) {
129
+ return error(
130
+ `${preface}: body must be an instance of string or Uint8Array if content-type is not a supported textual content-type`
131
+ );
132
+ }
133
+
134
+ /** @type {import('types/hooks').StrictBody} */
135
+ let normalized_body;
136
+
137
+ // ensure the body is an object
138
+ if (
139
+ (typeof body === 'object' || typeof body === 'undefined') &&
140
+ !(body instanceof Uint8Array) &&
141
+ (!type || type.startsWith('application/json'))
142
+ ) {
143
+ headers = { ...headers, 'content-type': 'application/json; charset=utf-8' };
144
+ normalized_body = JSON.stringify(typeof body === 'undefined' ? {} : body);
145
+ } else {
146
+ normalized_body = /** @type {import('types/hooks').StrictBody} */ (body);
147
+ }
148
+
149
+ return { status, body: normalized_body, headers };
150
+ }
151
+
152
+ var chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_$';
153
+ var unsafeChars = /[<>\b\f\n\r\t\0\u2028\u2029]/g;
154
+ 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)$/;
155
+ var escaped = {
156
+ '<': '\\u003C',
157
+ '>': '\\u003E',
158
+ '/': '\\u002F',
159
+ '\\': '\\\\',
160
+ '\b': '\\b',
161
+ '\f': '\\f',
162
+ '\n': '\\n',
163
+ '\r': '\\r',
164
+ '\t': '\\t',
165
+ '\0': '\\0',
166
+ '\u2028': '\\u2028',
167
+ '\u2029': '\\u2029'
168
+ };
169
+ var objectProtoOwnPropertyNames = Object.getOwnPropertyNames(Object.prototype).sort().join('\0');
170
+ function devalue(value) {
171
+ var counts = new Map();
172
+ function walk(thing) {
173
+ if (typeof thing === 'function') {
174
+ throw new Error("Cannot stringify a function");
175
+ }
176
+ if (counts.has(thing)) {
177
+ counts.set(thing, counts.get(thing) + 1);
178
+ return;
179
+ }
180
+ counts.set(thing, 1);
181
+ if (!isPrimitive(thing)) {
182
+ var type = getType(thing);
183
+ switch (type) {
184
+ case 'Number':
185
+ case 'String':
186
+ case 'Boolean':
187
+ case 'Date':
188
+ case 'RegExp':
189
+ return;
190
+ case 'Array':
191
+ thing.forEach(walk);
192
+ break;
193
+ case 'Set':
194
+ case 'Map':
195
+ Array.from(thing).forEach(walk);
196
+ break;
197
+ default:
198
+ var proto = Object.getPrototypeOf(thing);
199
+ if (proto !== Object.prototype &&
200
+ proto !== null &&
201
+ Object.getOwnPropertyNames(proto).sort().join('\0') !== objectProtoOwnPropertyNames) {
202
+ throw new Error("Cannot stringify arbitrary non-POJOs");
203
+ }
204
+ if (Object.getOwnPropertySymbols(thing).length > 0) {
205
+ throw new Error("Cannot stringify POJOs with symbolic keys");
206
+ }
207
+ Object.keys(thing).forEach(function (key) { return walk(thing[key]); });
208
+ }
209
+ }
210
+ }
211
+ walk(value);
212
+ var names = new Map();
213
+ Array.from(counts)
214
+ .filter(function (entry) { return entry[1] > 1; })
215
+ .sort(function (a, b) { return b[1] - a[1]; })
216
+ .forEach(function (entry, i) {
217
+ names.set(entry[0], getName(i));
218
+ });
219
+ function stringify(thing) {
220
+ if (names.has(thing)) {
221
+ return names.get(thing);
222
+ }
223
+ if (isPrimitive(thing)) {
224
+ return stringifyPrimitive(thing);
225
+ }
226
+ var type = getType(thing);
227
+ switch (type) {
228
+ case 'Number':
229
+ case 'String':
230
+ case 'Boolean':
231
+ return "Object(" + stringify(thing.valueOf()) + ")";
232
+ case 'RegExp':
233
+ return "new RegExp(" + stringifyString(thing.source) + ", \"" + thing.flags + "\")";
234
+ case 'Date':
235
+ return "new Date(" + thing.getTime() + ")";
236
+ case 'Array':
237
+ var members = thing.map(function (v, i) { return i in thing ? stringify(v) : ''; });
238
+ var tail = thing.length === 0 || (thing.length - 1 in thing) ? '' : ',';
239
+ return "[" + members.join(',') + tail + "]";
240
+ case 'Set':
241
+ case 'Map':
242
+ return "new " + type + "([" + Array.from(thing).map(stringify).join(',') + "])";
243
+ default:
244
+ var obj = "{" + Object.keys(thing).map(function (key) { return safeKey(key) + ":" + stringify(thing[key]); }).join(',') + "}";
245
+ var proto = Object.getPrototypeOf(thing);
246
+ if (proto === null) {
247
+ return Object.keys(thing).length > 0
248
+ ? "Object.assign(Object.create(null)," + obj + ")"
249
+ : "Object.create(null)";
250
+ }
251
+ return obj;
252
+ }
253
+ }
254
+ var str = stringify(value);
255
+ if (names.size) {
256
+ var params_1 = [];
257
+ var statements_1 = [];
258
+ var values_1 = [];
259
+ names.forEach(function (name, thing) {
260
+ params_1.push(name);
261
+ if (isPrimitive(thing)) {
262
+ values_1.push(stringifyPrimitive(thing));
263
+ return;
264
+ }
265
+ var type = getType(thing);
266
+ switch (type) {
267
+ case 'Number':
268
+ case 'String':
269
+ case 'Boolean':
270
+ values_1.push("Object(" + stringify(thing.valueOf()) + ")");
271
+ break;
272
+ case 'RegExp':
273
+ values_1.push(thing.toString());
274
+ break;
275
+ case 'Date':
276
+ values_1.push("new Date(" + thing.getTime() + ")");
277
+ break;
278
+ case 'Array':
279
+ values_1.push("Array(" + thing.length + ")");
280
+ thing.forEach(function (v, i) {
281
+ statements_1.push(name + "[" + i + "]=" + stringify(v));
282
+ });
283
+ break;
284
+ case 'Set':
285
+ values_1.push("new Set");
286
+ statements_1.push(name + "." + Array.from(thing).map(function (v) { return "add(" + stringify(v) + ")"; }).join('.'));
287
+ break;
288
+ case 'Map':
289
+ values_1.push("new Map");
290
+ statements_1.push(name + "." + Array.from(thing).map(function (_a) {
291
+ var k = _a[0], v = _a[1];
292
+ return "set(" + stringify(k) + ", " + stringify(v) + ")";
293
+ }).join('.'));
294
+ break;
295
+ default:
296
+ values_1.push(Object.getPrototypeOf(thing) === null ? 'Object.create(null)' : '{}');
297
+ Object.keys(thing).forEach(function (key) {
298
+ statements_1.push("" + name + safeProp(key) + "=" + stringify(thing[key]));
299
+ });
300
+ }
301
+ });
302
+ statements_1.push("return " + str);
303
+ return "(function(" + params_1.join(',') + "){" + statements_1.join(';') + "}(" + values_1.join(',') + "))";
304
+ }
305
+ else {
306
+ return str;
307
+ }
308
+ }
309
+ function getName(num) {
310
+ var name = '';
311
+ do {
312
+ name = chars[num % chars.length] + name;
313
+ num = ~~(num / chars.length) - 1;
314
+ } while (num >= 0);
315
+ return reserved.test(name) ? name + "_" : name;
316
+ }
317
+ function isPrimitive(thing) {
318
+ return Object(thing) !== thing;
319
+ }
320
+ function stringifyPrimitive(thing) {
321
+ if (typeof thing === 'string')
322
+ return stringifyString(thing);
323
+ if (thing === void 0)
324
+ return 'void 0';
325
+ if (thing === 0 && 1 / thing < 0)
326
+ return '-0';
327
+ var str = String(thing);
328
+ if (typeof thing === 'number')
329
+ return str.replace(/^(-)?0\./, '$1.');
330
+ return str;
331
+ }
332
+ function getType(thing) {
333
+ return Object.prototype.toString.call(thing).slice(8, -1);
334
+ }
335
+ function escapeUnsafeChar(c) {
336
+ return escaped[c] || c;
337
+ }
338
+ function escapeUnsafeChars(str) {
339
+ return str.replace(unsafeChars, escapeUnsafeChar);
340
+ }
341
+ function safeKey(key) {
342
+ return /^[_$a-zA-Z][_$a-zA-Z0-9]*$/.test(key) ? key : escapeUnsafeChars(JSON.stringify(key));
343
+ }
344
+ function safeProp(key) {
345
+ return /^[_$a-zA-Z][_$a-zA-Z0-9]*$/.test(key) ? "." + key : "[" + escapeUnsafeChars(JSON.stringify(key)) + "]";
346
+ }
347
+ function stringifyString(str) {
348
+ var result = '"';
349
+ for (var i = 0; i < str.length; i += 1) {
350
+ var char = str.charAt(i);
351
+ var code = char.charCodeAt(0);
352
+ if (char === '"') {
353
+ result += '\\"';
354
+ }
355
+ else if (char in escaped) {
356
+ result += escaped[char];
357
+ }
358
+ else if (code >= 0xd800 && code <= 0xdfff) {
359
+ var next = str.charCodeAt(i + 1);
360
+ // If this is the beginning of a [high, low] surrogate pair,
361
+ // add the next two characters, otherwise escape
362
+ if (code <= 0xdbff && (next >= 0xdc00 && next <= 0xdfff)) {
363
+ result += char + str[++i];
364
+ }
365
+ else {
366
+ result += "\\u" + code.toString(16).toUpperCase();
367
+ }
368
+ }
369
+ else {
370
+ result += char;
371
+ }
372
+ }
373
+ result += '"';
374
+ return result;
375
+ }
376
+
377
+ function noop() { }
378
+ function safe_not_equal(a, b) {
379
+ return a != a ? b == b : a !== b || ((a && typeof a === 'object') || typeof a === 'function');
380
+ }
381
+ Promise.resolve();
382
+
383
+ const subscriber_queue = [];
384
+ /**
385
+ * Create a `Writable` store that allows both updating and reading by subscription.
386
+ * @param {*=}value initial value
387
+ * @param {StartStopNotifier=}start start and stop notifications for subscriptions
388
+ */
389
+ function writable(value, start = noop) {
390
+ let stop;
391
+ const subscribers = new Set();
392
+ function set(new_value) {
393
+ if (safe_not_equal(value, new_value)) {
394
+ value = new_value;
395
+ if (stop) { // store is ready
396
+ const run_queue = !subscriber_queue.length;
397
+ for (const subscriber of subscribers) {
398
+ subscriber[1]();
399
+ subscriber_queue.push(subscriber, value);
400
+ }
401
+ if (run_queue) {
402
+ for (let i = 0; i < subscriber_queue.length; i += 2) {
403
+ subscriber_queue[i][0](subscriber_queue[i + 1]);
404
+ }
405
+ subscriber_queue.length = 0;
406
+ }
407
+ }
408
+ }
409
+ }
410
+ function update(fn) {
411
+ set(fn(value));
412
+ }
413
+ function subscribe(run, invalidate = noop) {
414
+ const subscriber = [run, invalidate];
415
+ subscribers.add(subscriber);
416
+ if (subscribers.size === 1) {
417
+ stop = start(set) || noop;
418
+ }
419
+ run(value);
420
+ return () => {
421
+ subscribers.delete(subscriber);
422
+ if (subscribers.size === 0) {
423
+ stop();
424
+ stop = null;
425
+ }
426
+ };
427
+ }
428
+ return { set, update, subscribe };
429
+ }
430
+
431
+ /**
432
+ * @param {unknown} err
433
+ * @return {Error}
434
+ */
435
+ function coalesce_to_error(err) {
436
+ return err instanceof Error ||
437
+ (err && /** @type {any} */ (err).name && /** @type {any} */ (err).message)
438
+ ? /** @type {Error} */ (err)
439
+ : new Error(JSON.stringify(err));
440
+ }
441
+
442
+ /**
443
+ * Hash using djb2
444
+ * @param {import('types/hooks').StrictBody} value
445
+ */
446
+ function hash(value) {
447
+ let hash = 5381;
448
+ let i = value.length;
449
+
450
+ if (typeof value === 'string') {
451
+ while (i) hash = (hash * 33) ^ value.charCodeAt(--i);
452
+ } else {
453
+ while (i) hash = (hash * 33) ^ value[--i];
454
+ }
455
+
456
+ return (hash >>> 0).toString(36);
457
+ }
458
+
459
+ /** @type {Record<string, string>} */
460
+ const escape_json_string_in_html_dict = {
461
+ '"': '\\"',
462
+ '<': '\\u003C',
463
+ '>': '\\u003E',
464
+ '/': '\\u002F',
465
+ '\\': '\\\\',
466
+ '\b': '\\b',
467
+ '\f': '\\f',
468
+ '\n': '\\n',
469
+ '\r': '\\r',
470
+ '\t': '\\t',
471
+ '\0': '\\0',
472
+ '\u2028': '\\u2028',
473
+ '\u2029': '\\u2029'
474
+ };
475
+
476
+ /** @param {string} str */
477
+ function escape_json_string_in_html(str) {
478
+ return escape(
479
+ str,
480
+ escape_json_string_in_html_dict,
481
+ (code) => `\\u${code.toString(16).toUpperCase()}`
482
+ );
483
+ }
484
+
485
+ /** @type {Record<string, string>} */
486
+ const escape_html_attr_dict = {
487
+ '<': '&lt;',
488
+ '>': '&gt;',
489
+ '"': '&quot;'
490
+ };
491
+
492
+ /**
493
+ * use for escaping string values to be used html attributes on the page
494
+ * e.g.
495
+ * <script data-url="here">
496
+ *
497
+ * @param {string} str
498
+ * @returns string escaped string
499
+ */
500
+ function escape_html_attr(str) {
501
+ return '"' + escape(str, escape_html_attr_dict, (code) => `&#${code};`) + '"';
502
+ }
503
+
504
+ /**
505
+ *
506
+ * @param str {string} string to escape
507
+ * @param dict {Record<string, string>} dictionary of character replacements
508
+ * @param unicode_encoder {function(number): string} encoder to use for high unicode characters
509
+ * @returns {string}
510
+ */
511
+ function escape(str, dict, unicode_encoder) {
512
+ let result = '';
513
+
514
+ for (let i = 0; i < str.length; i += 1) {
515
+ const char = str.charAt(i);
516
+ const code = char.charCodeAt(0);
517
+
518
+ if (char in dict) {
519
+ result += dict[char];
520
+ } else if (code >= 0xd800 && code <= 0xdfff) {
521
+ const next = str.charCodeAt(i + 1);
522
+
523
+ // If this is the beginning of a [high, low] surrogate pair,
524
+ // add the next two characters, otherwise escape
525
+ if (code <= 0xdbff && next >= 0xdc00 && next <= 0xdfff) {
526
+ result += char + str[++i];
527
+ } else {
528
+ result += unicode_encoder(code);
529
+ }
530
+ } else {
531
+ result += char;
532
+ }
533
+ }
534
+
535
+ return result;
536
+ }
537
+
538
+ const s = JSON.stringify;
539
+
540
+ /** @param {URL} url */
541
+ function create_prerendering_url_proxy(url) {
542
+ return new Proxy(url, {
543
+ get: (target, prop, receiver) => {
544
+ if (prop === 'search' || prop === 'searchParams') {
545
+ throw new Error(`Cannot access url.${prop} on a page with prerendering enabled`);
546
+ }
547
+ return Reflect.get(target, prop, receiver);
548
+ }
549
+ });
550
+ }
551
+
552
+ // TODO rename this function/module
553
+
554
+ /**
555
+ * @param {{
556
+ * branch: Array<import('./types').Loaded>;
557
+ * options: import('types/internal').SSRRenderOptions;
558
+ * state: import('types/internal').SSRRenderState;
559
+ * $session: any;
560
+ * page_config: { hydrate: boolean, router: boolean };
561
+ * status: number;
562
+ * error?: Error;
563
+ * url: URL;
564
+ * params: Record<string, string>;
565
+ * ssr: boolean;
566
+ * stuff: Record<string, any>;
567
+ * }} opts
568
+ */
569
+ async function render_response({
570
+ branch,
571
+ options,
572
+ state,
573
+ $session,
574
+ page_config,
575
+ status,
576
+ error,
577
+ url,
578
+ params,
579
+ ssr,
580
+ stuff
581
+ }) {
582
+ const css = new Set(options.manifest._.entry.css);
583
+ const js = new Set(options.manifest._.entry.js);
584
+ /** @type {Map<string, string>} */
585
+ const styles = new Map();
586
+
587
+ /** @type {Array<{ url: string, body: string, json: string }>} */
588
+ const serialized_data = [];
589
+
590
+ let rendered;
591
+
592
+ let is_private = false;
593
+ let maxage;
594
+
595
+ if (error) {
596
+ error.stack = options.get_stack(error);
597
+ }
598
+
599
+ if (ssr) {
600
+ branch.forEach(({ node, loaded, fetched, uses_credentials }) => {
601
+ if (node.css) node.css.forEach((url) => css.add(url));
602
+ if (node.js) node.js.forEach((url) => js.add(url));
603
+ if (node.styles) Object.entries(node.styles).forEach(([k, v]) => styles.set(k, v));
604
+
605
+ // TODO probably better if `fetched` wasn't populated unless `hydrate`
606
+ if (fetched && page_config.hydrate) serialized_data.push(...fetched);
607
+
608
+ if (uses_credentials) is_private = true;
609
+
610
+ maxage = loaded.maxage;
611
+ });
612
+
613
+ const session = writable($session);
614
+
615
+ /** @type {Record<string, any>} */
616
+ const props = {
617
+ stores: {
618
+ page: writable(null),
619
+ navigating: writable(null),
620
+ session
621
+ },
622
+ page: {
623
+ url: state.prerender ? create_prerendering_url_proxy(url) : url,
624
+ params,
625
+ status,
626
+ error,
627
+ stuff
628
+ },
629
+ components: branch.map(({ node }) => node.module.default)
630
+ };
631
+
632
+ // TODO remove this for 1.0
633
+ /**
634
+ * @param {string} property
635
+ * @param {string} replacement
636
+ */
637
+ const print_error = (property, replacement) => {
638
+ Object.defineProperty(props.page, property, {
639
+ get: () => {
640
+ throw new Error(`$page.${property} has been replaced by $page.url.${replacement}`);
641
+ }
642
+ });
643
+ };
644
+
645
+ print_error('origin', 'origin');
646
+ print_error('path', 'pathname');
647
+ print_error('query', 'searchParams');
648
+
649
+ // props_n (instead of props[n]) makes it easy to avoid
650
+ // unnecessary updates for layout components
651
+ for (let i = 0; i < branch.length; i += 1) {
652
+ props[`props_${i}`] = await branch[i].loaded.props;
653
+ }
654
+
655
+ let session_tracking_active = false;
656
+ const unsubscribe = session.subscribe(() => {
657
+ if (session_tracking_active) is_private = true;
658
+ });
659
+ session_tracking_active = true;
660
+
661
+ try {
662
+ rendered = options.root.render(props);
663
+ } finally {
664
+ unsubscribe();
665
+ }
666
+ } else {
667
+ rendered = { head: '', html: '', css: { code: '', map: null } };
668
+ }
669
+
670
+ let { head, html: body } = rendered;
671
+
672
+ const inlined_style = Array.from(styles.values()).join('\n');
673
+
674
+ if (options.amp) {
675
+ head += `
676
+ <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>
677
+ <noscript><style amp-boilerplate>body{-webkit-animation:none;-moz-animation:none;-ms-animation:none;animation:none}</style></noscript>
678
+ <script async src="https://cdn.ampproject.org/v0.js"></script>
679
+
680
+ <style amp-custom>${inlined_style}\n${rendered.css.code}</style>`;
681
+
682
+ if (options.service_worker) {
683
+ head +=
684
+ '<script async custom-element="amp-install-serviceworker" src="https://cdn.ampproject.org/v0/amp-install-serviceworker-0.1.js"></script>';
685
+
686
+ body += `<amp-install-serviceworker src="${options.service_worker}" layout="nodisplay"></amp-install-serviceworker>`;
687
+ }
688
+ } else {
689
+ if (inlined_style) {
690
+ head += `\n\t<style${options.dev ? ' data-svelte' : ''}>${inlined_style}</style>`;
691
+ }
692
+ // prettier-ignore
693
+ head += Array.from(css)
694
+ .map((dep) => `\n\t<link${styles.has(dep) ? ' disabled' : ''} rel="stylesheet" href="${options.prefix + dep}">`)
695
+ .join('');
696
+
697
+ if (page_config.router || page_config.hydrate) {
698
+ head += Array.from(js)
699
+ .map((dep) => `\n\t<link rel="modulepreload" href="${options.prefix + dep}">`)
700
+ .join('');
701
+ // prettier-ignore
702
+ head += `
703
+ <script type="module">
704
+ import { start } from ${s(options.prefix + options.manifest._.entry.file)};
705
+ start({
706
+ target: ${options.target ? `document.querySelector(${s(options.target)})` : 'document.body'},
707
+ paths: ${s(options.paths)},
708
+ session: ${try_serialize($session, (error) => {
709
+ throw new Error(`Failed to serialize session data: ${error.message}`);
710
+ })},
711
+ route: ${!!page_config.router},
712
+ spa: ${!ssr},
713
+ trailing_slash: ${s(options.trailing_slash)},
714
+ hydrate: ${ssr && page_config.hydrate ? `{
715
+ status: ${status},
716
+ error: ${serialize_error(error)},
717
+ nodes: [
718
+ ${(branch || [])
719
+ .map(({ node }) => `import(${s(options.prefix + node.entry)})`)
720
+ .join(',\n\t\t\t\t\t\t')}
721
+ ],
722
+ url: new URL(${s(url.href)}),
723
+ params: ${devalue(params)}
724
+ }` : 'null'}
725
+ });
726
+ </script>${options.service_worker ? `
727
+ <script>
728
+ if ('serviceWorker' in navigator) {
729
+ navigator.serviceWorker.register('${options.service_worker}');
730
+ }
731
+ </script>` : ''}`;
732
+
733
+ body += serialized_data
734
+ .map(({ url, body, json }) => {
735
+ let attributes = `type="application/json" data-type="svelte-data" data-url=${escape_html_attr(
736
+ url
737
+ )}`;
738
+ if (body) attributes += ` data-body="${hash(body)}"`;
739
+
740
+ return `<script ${attributes}>${json}</script>`;
741
+ })
742
+ .join('\n\n\t');
743
+ }
744
+ }
745
+
746
+ /** @type {import('types/helper').ResponseHeaders} */
747
+ const headers = {
748
+ 'content-type': 'text/html'
749
+ };
750
+
751
+ if (maxage) {
752
+ headers['cache-control'] = `${is_private ? 'private' : 'public'}, max-age=${maxage}`;
753
+ }
754
+
755
+ if (!options.floc) {
756
+ headers['permissions-policy'] = 'interest-cohort=()';
757
+ }
758
+
759
+ const segments = url.pathname.slice(options.paths.base.length).split('/').slice(2);
760
+ const assets =
761
+ options.paths.assets || (segments.length > 0 ? segments.map(() => '..').join('/') : '.');
762
+
763
+ return {
764
+ status,
765
+ headers,
766
+ body: options.template({
767
+ head,
768
+ body,
769
+ assets
770
+ })
771
+ };
772
+ }
773
+
774
+ /**
775
+ * @param {any} data
776
+ * @param {(error: Error) => void} [fail]
777
+ */
778
+ function try_serialize(data, fail) {
779
+ try {
780
+ return devalue(data);
781
+ } catch (err) {
782
+ if (fail) fail(coalesce_to_error(err));
783
+ return null;
784
+ }
785
+ }
786
+
787
+ // Ensure we return something truthy so the client will not re-render the page over the error
788
+
789
+ /** @param {(Error & {frame?: string} & {loc?: object}) | undefined | null} error */
790
+ function serialize_error(error) {
791
+ if (!error) return null;
792
+ let serialized = try_serialize(error);
793
+ if (!serialized) {
794
+ const { name, message, stack } = error;
795
+ serialized = try_serialize({ ...error, name, message, stack });
796
+ }
797
+ if (!serialized) {
798
+ serialized = '{}';
799
+ }
800
+ return serialized;
801
+ }
802
+
803
+ /**
804
+ * @param {import('types/page').LoadOutput} loaded
805
+ * @returns {import('types/internal').NormalizedLoadOutput}
806
+ */
807
+ function normalize(loaded) {
808
+ const has_error_status =
809
+ loaded.status && loaded.status >= 400 && loaded.status <= 599 && !loaded.redirect;
810
+ if (loaded.error || has_error_status) {
811
+ const status = loaded.status;
812
+
813
+ if (!loaded.error && has_error_status) {
814
+ return {
815
+ status: status || 500,
816
+ error: new Error()
817
+ };
818
+ }
819
+
820
+ const error = typeof loaded.error === 'string' ? new Error(loaded.error) : loaded.error;
821
+
822
+ if (!(error instanceof Error)) {
823
+ return {
824
+ status: 500,
825
+ error: new Error(
826
+ `"error" property returned from load() must be a string or instance of Error, received type "${typeof error}"`
827
+ )
828
+ };
829
+ }
830
+
831
+ if (!status || status < 400 || status > 599) {
832
+ console.warn('"error" returned from load() without a valid status code — defaulting to 500');
833
+ return { status: 500, error };
834
+ }
835
+
836
+ return { status, error };
837
+ }
838
+
839
+ if (loaded.redirect) {
840
+ if (!loaded.status || Math.floor(loaded.status / 100) !== 3) {
841
+ return {
842
+ status: 500,
843
+ error: new Error(
844
+ '"redirect" property returned from load() must be accompanied by a 3xx status code'
845
+ )
846
+ };
847
+ }
848
+
849
+ if (typeof loaded.redirect !== 'string') {
850
+ return {
851
+ status: 500,
852
+ error: new Error('"redirect" property returned from load() must be a string')
853
+ };
854
+ }
855
+ }
856
+
857
+ // TODO remove before 1.0
858
+ if (/** @type {any} */ (loaded).context) {
859
+ throw new Error(
860
+ 'You are returning "context" from a load function. ' +
861
+ '"context" was renamed to "stuff", please adjust your code accordingly.'
862
+ );
863
+ }
864
+
865
+ return /** @type {import('types/internal').NormalizedLoadOutput} */ (loaded);
866
+ }
867
+
868
+ const absolute = /^([a-z]+:)?\/?\//;
869
+ const scheme = /^[a-z]+:/;
870
+
871
+ /**
872
+ * @param {string} base
873
+ * @param {string} path
874
+ */
875
+ function resolve(base, path) {
876
+ if (scheme.test(path)) return path;
877
+
878
+ const base_match = absolute.exec(base);
879
+ const path_match = absolute.exec(path);
880
+
881
+ if (!base_match) {
882
+ throw new Error(`bad base path: "${base}"`);
883
+ }
884
+
885
+ const baseparts = path_match ? [] : base.slice(base_match[0].length).split('/');
886
+ const pathparts = path_match ? path.slice(path_match[0].length).split('/') : path.split('/');
887
+
888
+ baseparts.pop();
889
+
890
+ for (let i = 0; i < pathparts.length; i += 1) {
891
+ const part = pathparts[i];
892
+ if (part === '.') continue;
893
+ else if (part === '..') baseparts.pop();
894
+ else baseparts.push(part);
895
+ }
896
+
897
+ const prefix = (path_match && path_match[0]) || (base_match && base_match[0]) || '';
898
+
899
+ return `${prefix}${baseparts.join('/')}`;
900
+ }
901
+
902
+ /** @param {string} path */
903
+ function is_root_relative(path) {
904
+ return path[0] === '/' && path[1] !== '/';
905
+ }
906
+
907
+ /**
908
+ * @param {{
909
+ * request: import('types/hooks').ServerRequest;
910
+ * options: import('types/internal').SSRRenderOptions;
911
+ * state: import('types/internal').SSRRenderState;
912
+ * route: import('types/internal').SSRPage | null;
913
+ * url: URL;
914
+ * params: Record<string, string>;
915
+ * node: import('types/internal').SSRNode;
916
+ * $session: any;
917
+ * stuff: Record<string, any>;
918
+ * is_error: boolean;
919
+ * status?: number;
920
+ * error?: Error;
921
+ * }} opts
922
+ * @returns {Promise<import('./types').Loaded | undefined>} undefined for fallthrough
923
+ */
924
+ async function load_node({
925
+ request,
926
+ options,
927
+ state,
928
+ route,
929
+ url,
930
+ params,
931
+ node,
932
+ $session,
933
+ stuff,
934
+ is_error,
935
+ status,
936
+ error
937
+ }) {
938
+ const { module } = node;
939
+
940
+ let uses_credentials = false;
941
+
942
+ /**
943
+ * @type {Array<{
944
+ * url: string;
945
+ * body: string;
946
+ * json: string;
947
+ * }>}
948
+ */
949
+ const fetched = [];
950
+
951
+ /**
952
+ * @type {string[]}
953
+ */
954
+ let set_cookie_headers = [];
955
+
956
+ let loaded;
957
+
958
+ if (module.load) {
959
+ /** @type {import('types/page').LoadInput | import('types/page').ErrorLoadInput} */
960
+ const load_input = {
961
+ url: state.prerender ? create_prerendering_url_proxy(url) : url,
962
+ params,
963
+ get session() {
964
+ uses_credentials = true;
965
+ return $session;
966
+ },
967
+ /**
968
+ * @param {RequestInfo} resource
969
+ * @param {RequestInit} opts
970
+ */
971
+ fetch: async (resource, opts = {}) => {
972
+ /** @type {string} */
973
+ let requested;
974
+
975
+ if (typeof resource === 'string') {
976
+ requested = resource;
977
+ } else {
978
+ requested = resource.url;
979
+
980
+ opts = {
981
+ method: resource.method,
982
+ headers: resource.headers,
983
+ body: resource.body,
984
+ mode: resource.mode,
985
+ credentials: resource.credentials,
986
+ cache: resource.cache,
987
+ redirect: resource.redirect,
988
+ referrer: resource.referrer,
989
+ integrity: resource.integrity,
990
+ ...opts
991
+ };
992
+ }
993
+
994
+ opts.headers = new Headers(opts.headers);
995
+
996
+ const resolved = resolve(request.url.pathname, requested.split('?')[0]);
997
+
998
+ let response;
999
+
1000
+ // handle fetch requests for static assets. e.g. prebaked data, etc.
1001
+ // we need to support everything the browser's fetch supports
1002
+ const prefix = options.paths.assets || options.paths.base;
1003
+ const filename = (
1004
+ resolved.startsWith(prefix) ? resolved.slice(prefix.length) : resolved
1005
+ ).slice(1);
1006
+ const filename_html = `${filename}/index.html`; // path may also match path/index.html
1007
+
1008
+ const is_asset = options.manifest.assets.has(filename);
1009
+ const is_asset_html = options.manifest.assets.has(filename_html);
1010
+
1011
+ if (is_asset || is_asset_html) {
1012
+ const file = is_asset ? filename : filename_html;
1013
+
1014
+ if (options.read) {
1015
+ const type = is_asset
1016
+ ? options.manifest._.mime[filename.slice(filename.lastIndexOf('.'))]
1017
+ : 'text/html';
1018
+
1019
+ response = new Response(options.read(file), {
1020
+ headers: type ? { 'content-type': type } : {}
1021
+ });
1022
+ } else {
1023
+ response = await fetch(`${url.origin}/${file}`, /** @type {RequestInit} */ (opts));
1024
+ }
1025
+ } else if (is_root_relative(resolved)) {
1026
+ const relative = resolved;
1027
+
1028
+ // TODO: fix type https://github.com/node-fetch/node-fetch/issues/1113
1029
+ if (opts.credentials !== 'omit') {
1030
+ uses_credentials = true;
1031
+
1032
+ if (request.headers.cookie) {
1033
+ opts.headers.set('cookie', request.headers.cookie);
1034
+ }
1035
+
1036
+ if (request.headers.authorization && !opts.headers.has('authorization')) {
1037
+ opts.headers.set('authorization', request.headers.authorization);
1038
+ }
1039
+ }
1040
+
1041
+ if (opts.body && typeof opts.body !== 'string') {
1042
+ // per https://developer.mozilla.org/en-US/docs/Web/API/Request/Request, this can be a
1043
+ // Blob, BufferSource, FormData, URLSearchParams, USVString, or ReadableStream object.
1044
+ // non-string bodies are irksome to deal with, but luckily aren't particularly useful
1045
+ // in this context anyway, so we take the easy route and ban them
1046
+ throw new Error('Request body must be a string');
1047
+ }
1048
+
1049
+ const rendered = await respond(
1050
+ {
1051
+ url: new URL(requested, request.url),
1052
+ method: opts.method || 'GET',
1053
+ headers: Object.fromEntries(opts.headers),
1054
+ rawBody: opts.body == null ? null : new TextEncoder().encode(opts.body)
1055
+ },
1056
+ options,
1057
+ {
1058
+ fetched: requested,
1059
+ initiator: route
1060
+ }
1061
+ );
1062
+
1063
+ if (rendered) {
1064
+ if (state.prerender) {
1065
+ state.prerender.dependencies.set(relative, rendered);
1066
+ }
1067
+
1068
+ // Set-Cookie must be filtered out (done below) and that's the only header value that
1069
+ // can be an array so we know we have only simple values
1070
+ // https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie
1071
+ response = new Response(rendered.body, {
1072
+ status: rendered.status,
1073
+ headers: /** @type {Record<string, string>} */ (rendered.headers)
1074
+ });
1075
+ } else {
1076
+ // we can't load the endpoint from our own manifest,
1077
+ // so we need to make an actual HTTP request
1078
+ return fetch(new URL(requested, request.url).href, {
1079
+ method: opts.method || 'GET',
1080
+ headers: opts.headers
1081
+ });
1082
+ }
1083
+ } else {
1084
+ // external
1085
+ if (resolved.startsWith('//')) {
1086
+ throw new Error(
1087
+ `Cannot request protocol-relative URL (${requested}) in server-side fetch`
1088
+ );
1089
+ }
1090
+
1091
+ // external fetch
1092
+ // allow cookie passthrough for "same-origin"
1093
+ // if SvelteKit is serving my.domain.com:
1094
+ // - domain.com WILL NOT receive cookies
1095
+ // - my.domain.com WILL receive cookies
1096
+ // - api.domain.dom WILL NOT receive cookies
1097
+ // - sub.my.domain.com WILL receive cookies
1098
+ // ports do not affect the resolution
1099
+ // leading dot prevents mydomain.com matching domain.com
1100
+ if (
1101
+ `.${new URL(requested).hostname}`.endsWith(`.${request.url.hostname}`) &&
1102
+ opts.credentials !== 'omit'
1103
+ ) {
1104
+ uses_credentials = true;
1105
+ opts.headers.set('cookie', request.headers.cookie);
1106
+ }
1107
+
1108
+ const external_request = new Request(requested, /** @type {RequestInit} */ (opts));
1109
+ response = await options.hooks.externalFetch.call(null, external_request);
1110
+ }
1111
+
1112
+ if (response) {
1113
+ const proxy = new Proxy(response, {
1114
+ get(response, key, _receiver) {
1115
+ async function text() {
1116
+ const body = await response.text();
1117
+
1118
+ /** @type {import('types/helper').ResponseHeaders} */
1119
+ const headers = {};
1120
+ for (const [key, value] of response.headers) {
1121
+ if (key === 'set-cookie') {
1122
+ set_cookie_headers = set_cookie_headers.concat(value);
1123
+ } else if (key !== 'etag') {
1124
+ headers[key] = value;
1125
+ }
1126
+ }
1127
+
1128
+ if (!opts.body || typeof opts.body === 'string') {
1129
+ // prettier-ignore
1130
+ fetched.push({
1131
+ url: requested,
1132
+ body: /** @type {string} */ (opts.body),
1133
+ json: `{"status":${response.status},"statusText":${s(response.statusText)},"headers":${s(headers)},"body":"${escape_json_string_in_html(body)}"}`
1134
+ });
1135
+ }
1136
+
1137
+ return body;
1138
+ }
1139
+
1140
+ if (key === 'text') {
1141
+ return text;
1142
+ }
1143
+
1144
+ if (key === 'json') {
1145
+ return async () => {
1146
+ return JSON.parse(await text());
1147
+ };
1148
+ }
1149
+
1150
+ // TODO arrayBuffer?
1151
+
1152
+ return Reflect.get(response, key, response);
1153
+ }
1154
+ });
1155
+
1156
+ return proxy;
1157
+ }
1158
+
1159
+ return (
1160
+ response ||
1161
+ new Response('Not found', {
1162
+ status: 404
1163
+ })
1164
+ );
1165
+ },
1166
+ stuff: { ...stuff }
1167
+ };
1168
+
1169
+ if (options.dev) {
1170
+ // TODO remove this for 1.0
1171
+ Object.defineProperty(load_input, 'page', {
1172
+ get: () => {
1173
+ throw new Error('`page` in `load` functions has been replaced by `url` and `params`');
1174
+ }
1175
+ });
1176
+ }
1177
+
1178
+ if (is_error) {
1179
+ /** @type {import('types/page').ErrorLoadInput} */ (load_input).status = status;
1180
+ /** @type {import('types/page').ErrorLoadInput} */ (load_input).error = error;
1181
+ }
1182
+
1183
+ loaded = await module.load.call(null, load_input);
1184
+
1185
+ if (!loaded) {
1186
+ throw new Error(`load function must return a value${options.dev ? ` (${node.entry})` : ''}`);
1187
+ }
1188
+ } else {
1189
+ loaded = {};
1190
+ }
1191
+
1192
+ if (loaded.fallthrough && !is_error) {
1193
+ return;
1194
+ }
1195
+
1196
+ return {
1197
+ node,
1198
+ loaded: normalize(loaded),
1199
+ stuff: loaded.stuff || stuff,
1200
+ fetched,
1201
+ set_cookie_headers,
1202
+ uses_credentials
1203
+ };
1204
+ }
1205
+
1206
+ /**
1207
+ * @typedef {import('./types.js').Loaded} Loaded
1208
+ * @typedef {import('types/internal').SSRRenderOptions} SSRRenderOptions
1209
+ * @typedef {import('types/internal').SSRRenderState} SSRRenderState
1210
+ */
1211
+
1212
+ /**
1213
+ * @param {{
1214
+ * request: import('types/hooks').ServerRequest;
1215
+ * options: SSRRenderOptions;
1216
+ * state: SSRRenderState;
1217
+ * $session: any;
1218
+ * status: number;
1219
+ * error: Error;
1220
+ * ssr: boolean;
1221
+ * }} opts
1222
+ */
1223
+ async function respond_with_error({
1224
+ request,
1225
+ options,
1226
+ state,
1227
+ $session,
1228
+ status,
1229
+ error,
1230
+ ssr
1231
+ }) {
1232
+ try {
1233
+ const default_layout = await options.manifest._.nodes[0](); // 0 is always the root layout
1234
+ const default_error = await options.manifest._.nodes[1](); // 1 is always the root error
1235
+
1236
+ /** @type {Record<string, string>} */
1237
+ const params = {}; // error page has no params
1238
+
1239
+ const layout_loaded = /** @type {Loaded} */ (
1240
+ await load_node({
1241
+ request,
1242
+ options,
1243
+ state,
1244
+ route: null,
1245
+ url: request.url, // TODO this is redundant, no?
1246
+ params,
1247
+ node: default_layout,
1248
+ $session,
1249
+ stuff: {},
1250
+ is_error: false
1251
+ })
1252
+ );
1253
+
1254
+ const error_loaded = /** @type {Loaded} */ (
1255
+ await load_node({
1256
+ request,
1257
+ options,
1258
+ state,
1259
+ route: null,
1260
+ url: request.url,
1261
+ params,
1262
+ node: default_error,
1263
+ $session,
1264
+ stuff: layout_loaded ? layout_loaded.stuff : {},
1265
+ is_error: true,
1266
+ status,
1267
+ error
1268
+ })
1269
+ );
1270
+
1271
+ return await render_response({
1272
+ options,
1273
+ state,
1274
+ $session,
1275
+ page_config: {
1276
+ hydrate: options.hydrate,
1277
+ router: options.router
1278
+ },
1279
+ stuff: error_loaded.stuff,
1280
+ status,
1281
+ error,
1282
+ branch: [layout_loaded, error_loaded],
1283
+ url: request.url,
1284
+ params,
1285
+ ssr
1286
+ });
1287
+ } catch (err) {
1288
+ const error = coalesce_to_error(err);
1289
+
1290
+ options.handle_error(error, request);
1291
+
1292
+ return {
1293
+ status: 500,
1294
+ headers: {},
1295
+ body: error.stack
1296
+ };
1297
+ }
1298
+ }
1299
+
1300
+ /**
1301
+ * @typedef {import('./types.js').Loaded} Loaded
1302
+ * @typedef {import('types/hooks').ServerResponse} ServerResponse
1303
+ * @typedef {import('types/internal').SSRNode} SSRNode
1304
+ * @typedef {import('types/internal').SSRRenderOptions} SSRRenderOptions
1305
+ * @typedef {import('types/internal').SSRRenderState} SSRRenderState
1306
+ */
1307
+
1308
+ /**
1309
+ * @param {{
1310
+ * request: import('types/hooks').ServerRequest;
1311
+ * options: SSRRenderOptions;
1312
+ * state: SSRRenderState;
1313
+ * $session: any;
1314
+ * route: import('types/internal').SSRPage;
1315
+ * params: Record<string, string>;
1316
+ * ssr: boolean;
1317
+ * }} opts
1318
+ * @returns {Promise<ServerResponse | undefined>}
1319
+ */
1320
+ async function respond$1(opts) {
1321
+ const { request, options, state, $session, route, ssr } = opts;
1322
+
1323
+ /** @type {Array<SSRNode | undefined>} */
1324
+ let nodes;
1325
+
1326
+ if (!ssr) {
1327
+ return await render_response({
1328
+ ...opts,
1329
+ branch: [],
1330
+ page_config: {
1331
+ hydrate: true,
1332
+ router: true
1333
+ },
1334
+ status: 200,
1335
+ url: request.url,
1336
+ stuff: {}
1337
+ });
1338
+ }
1339
+
1340
+ try {
1341
+ nodes = await Promise.all(
1342
+ route.a.map((n) => options.manifest._.nodes[n] && options.manifest._.nodes[n]())
1343
+ );
1344
+ } catch (err) {
1345
+ const error = coalesce_to_error(err);
1346
+
1347
+ options.handle_error(error, request);
1348
+
1349
+ return await respond_with_error({
1350
+ request,
1351
+ options,
1352
+ state,
1353
+ $session,
1354
+ status: 500,
1355
+ error,
1356
+ ssr
1357
+ });
1358
+ }
1359
+
1360
+ // the leaf node will be present. only layouts may be undefined
1361
+ const leaf = /** @type {SSRNode} */ (nodes[nodes.length - 1]).module;
1362
+
1363
+ let page_config = get_page_config(leaf, options);
1364
+
1365
+ if (!leaf.prerender && state.prerender && !state.prerender.all) {
1366
+ // if the page has `export const prerender = true`, continue,
1367
+ // otherwise bail out at this point
1368
+ return {
1369
+ status: 204,
1370
+ headers: {}
1371
+ };
1372
+ }
1373
+
1374
+ /** @type {Array<Loaded>} */
1375
+ let branch = [];
1376
+
1377
+ /** @type {number} */
1378
+ let status = 200;
1379
+
1380
+ /** @type {Error|undefined} */
1381
+ let error;
1382
+
1383
+ /** @type {string[]} */
1384
+ let set_cookie_headers = [];
1385
+
1386
+ let stuff = {};
1387
+
1388
+ ssr: if (ssr) {
1389
+ for (let i = 0; i < nodes.length; i += 1) {
1390
+ const node = nodes[i];
1391
+
1392
+ /** @type {Loaded | undefined} */
1393
+ let loaded;
1394
+
1395
+ if (node) {
1396
+ try {
1397
+ loaded = await load_node({
1398
+ ...opts,
1399
+ url: request.url,
1400
+ node,
1401
+ stuff,
1402
+ is_error: false
1403
+ });
1404
+
1405
+ if (!loaded) return;
1406
+
1407
+ set_cookie_headers = set_cookie_headers.concat(loaded.set_cookie_headers);
1408
+
1409
+ if (loaded.loaded.redirect) {
1410
+ return with_cookies(
1411
+ {
1412
+ status: loaded.loaded.status,
1413
+ headers: {
1414
+ location: encodeURI(loaded.loaded.redirect)
1415
+ }
1416
+ },
1417
+ set_cookie_headers
1418
+ );
1419
+ }
1420
+
1421
+ if (loaded.loaded.error) {
1422
+ ({ status, error } = loaded.loaded);
1423
+ }
1424
+ } catch (err) {
1425
+ const e = coalesce_to_error(err);
1426
+
1427
+ options.handle_error(e, request);
1428
+
1429
+ status = 500;
1430
+ error = e;
1431
+ }
1432
+
1433
+ if (loaded && !error) {
1434
+ branch.push(loaded);
1435
+ }
1436
+
1437
+ if (error) {
1438
+ while (i--) {
1439
+ if (route.b[i]) {
1440
+ const error_node = await options.manifest._.nodes[route.b[i]]();
1441
+
1442
+ /** @type {Loaded} */
1443
+ let node_loaded;
1444
+ let j = i;
1445
+ while (!(node_loaded = branch[j])) {
1446
+ j -= 1;
1447
+ }
1448
+
1449
+ try {
1450
+ const error_loaded = /** @type {import('./types').Loaded} */ (
1451
+ await load_node({
1452
+ ...opts,
1453
+ url: request.url,
1454
+ node: error_node,
1455
+ stuff: node_loaded.stuff,
1456
+ is_error: true,
1457
+ status,
1458
+ error
1459
+ })
1460
+ );
1461
+
1462
+ if (error_loaded.loaded.error) {
1463
+ continue;
1464
+ }
1465
+
1466
+ page_config = get_page_config(error_node.module, options);
1467
+ branch = branch.slice(0, j + 1).concat(error_loaded);
1468
+ stuff = { ...node_loaded.stuff, ...error_loaded.stuff };
1469
+ break ssr;
1470
+ } catch (err) {
1471
+ const e = coalesce_to_error(err);
1472
+
1473
+ options.handle_error(e, request);
1474
+
1475
+ continue;
1476
+ }
1477
+ }
1478
+ }
1479
+
1480
+ // TODO backtrack until we find an __error.svelte component
1481
+ // that we can use as the leaf node
1482
+ // for now just return regular error page
1483
+ return with_cookies(
1484
+ await respond_with_error({
1485
+ request,
1486
+ options,
1487
+ state,
1488
+ $session,
1489
+ status,
1490
+ error,
1491
+ ssr
1492
+ }),
1493
+ set_cookie_headers
1494
+ );
1495
+ }
1496
+ }
1497
+
1498
+ if (loaded && loaded.loaded.stuff) {
1499
+ stuff = {
1500
+ ...stuff,
1501
+ ...loaded.loaded.stuff
1502
+ };
1503
+ }
1504
+ }
1505
+ }
1506
+
1507
+ try {
1508
+ return with_cookies(
1509
+ await render_response({
1510
+ ...opts,
1511
+ stuff,
1512
+ url: request.url,
1513
+ page_config,
1514
+ status,
1515
+ error,
1516
+ branch: branch.filter(Boolean)
1517
+ }),
1518
+ set_cookie_headers
1519
+ );
1520
+ } catch (err) {
1521
+ const error = coalesce_to_error(err);
1522
+
1523
+ options.handle_error(error, request);
1524
+
1525
+ return with_cookies(
1526
+ await respond_with_error({
1527
+ ...opts,
1528
+ status: 500,
1529
+ error
1530
+ }),
1531
+ set_cookie_headers
1532
+ );
1533
+ }
1534
+ }
1535
+
1536
+ /**
1537
+ * @param {import('types/internal').SSRComponent} leaf
1538
+ * @param {SSRRenderOptions} options
1539
+ */
1540
+ function get_page_config(leaf, options) {
1541
+ // TODO remove for 1.0
1542
+ if ('ssr' in leaf) {
1543
+ throw new Error(
1544
+ '`export const ssr` has been removed — use the handle hook instead: https://kit.svelte.dev/docs#hooks-handle'
1545
+ );
1546
+ }
1547
+
1548
+ return {
1549
+ router: 'router' in leaf ? !!leaf.router : options.router,
1550
+ hydrate: 'hydrate' in leaf ? !!leaf.hydrate : options.hydrate
1551
+ };
1552
+ }
1553
+
1554
+ /**
1555
+ * @param {ServerResponse} response
1556
+ * @param {string[]} set_cookie_headers
1557
+ */
1558
+ function with_cookies(response, set_cookie_headers) {
1559
+ if (set_cookie_headers.length) {
1560
+ response.headers['set-cookie'] = set_cookie_headers;
1561
+ }
1562
+ return response;
1563
+ }
1564
+
1565
+ /**
1566
+ * @param {import('types/hooks').ServerRequest} request
1567
+ * @param {import('types/internal').SSRPage} route
1568
+ * @param {RegExpExecArray} match
1569
+ * @param {import('types/internal').SSRRenderOptions} options
1570
+ * @param {import('types/internal').SSRRenderState} state
1571
+ * @param {boolean} ssr
1572
+ * @returns {Promise<import('types/hooks').ServerResponse | undefined>}
1573
+ */
1574
+ async function render_page(request, route, match, options, state, ssr) {
1575
+ if (state.initiator === route) {
1576
+ // infinite request cycle detected
1577
+ return {
1578
+ status: 404,
1579
+ headers: {},
1580
+ body: `Not found: ${request.url.pathname}`
1581
+ };
1582
+ }
1583
+
1584
+ const params = route.params ? decode_params(route.params(match)) : {};
1585
+
1586
+ const $session = await options.hooks.getSession(request);
1587
+
1588
+ const response = await respond$1({
1589
+ request,
1590
+ options,
1591
+ state,
1592
+ $session,
1593
+ route,
1594
+ params,
1595
+ ssr
1596
+ });
1597
+
1598
+ if (response) {
1599
+ return response;
1600
+ }
1601
+
1602
+ if (state.fetched) {
1603
+ // we came here because of a bad request in a `load` function.
1604
+ // rather than render the error page — which could lead to an
1605
+ // infinite loop, if the `load` belonged to the root layout,
1606
+ // we respond with a bare-bones 500
1607
+ return {
1608
+ status: 500,
1609
+ headers: {},
1610
+ body: `Bad request in load function: failed to fetch ${state.fetched}`
1611
+ };
1612
+ }
1613
+ }
1614
+
1615
+ function read_only_form_data() {
1616
+ /** @type {Map<string, string[]>} */
1617
+ const map = new Map();
1618
+
1619
+ return {
1620
+ /**
1621
+ * @param {string} key
1622
+ * @param {string} value
1623
+ */
1624
+ append(key, value) {
1625
+ const existing_values = map.get(key);
1626
+ if (existing_values) {
1627
+ existing_values.push(value);
1628
+ } else {
1629
+ map.set(key, [value]);
1630
+ }
1631
+ },
1632
+
1633
+ data: new ReadOnlyFormData(map)
1634
+ };
1635
+ }
1636
+
1637
+ class ReadOnlyFormData {
1638
+ /** @type {Map<string, string[]>} */
1639
+ #map;
1640
+
1641
+ /** @param {Map<string, string[]>} map */
1642
+ constructor(map) {
1643
+ this.#map = map;
1644
+ }
1645
+
1646
+ /** @param {string} key */
1647
+ get(key) {
1648
+ const value = this.#map.get(key);
1649
+ if (!value) {
1650
+ return null;
1651
+ }
1652
+ return value[0];
1653
+ }
1654
+
1655
+ /** @param {string} key */
1656
+ getAll(key) {
1657
+ return this.#map.get(key) || [];
1658
+ }
1659
+
1660
+ /** @param {string} key */
1661
+ has(key) {
1662
+ return this.#map.has(key);
1663
+ }
1664
+
1665
+ *[Symbol.iterator]() {
1666
+ for (const [key, value] of this.#map) {
1667
+ for (let i = 0; i < value.length; i += 1) {
1668
+ yield [key, value[i]];
1669
+ }
1670
+ }
1671
+ }
1672
+
1673
+ *entries() {
1674
+ for (const [key, value] of this.#map) {
1675
+ for (let i = 0; i < value.length; i += 1) {
1676
+ yield [key, value[i]];
1677
+ }
1678
+ }
1679
+ }
1680
+
1681
+ *keys() {
1682
+ for (const [key] of this.#map) yield key;
1683
+ }
1684
+
1685
+ *values() {
1686
+ for (const [, value] of this.#map) {
1687
+ for (let i = 0; i < value.length; i += 1) {
1688
+ yield value[i];
1689
+ }
1690
+ }
1691
+ }
1692
+ }
1693
+
1694
+ /**
1695
+ * @param {import('types/app').RawBody} raw
1696
+ * @param {import('types/helper').RequestHeaders} headers
1697
+ */
1698
+ function parse_body(raw, headers) {
1699
+ if (!raw) return raw;
1700
+
1701
+ const content_type = headers['content-type'];
1702
+ const [type, ...directives] = content_type ? content_type.split(/;\s*/) : [];
1703
+
1704
+ const text = () => new TextDecoder(headers['content-encoding'] || 'utf-8').decode(raw);
1705
+
1706
+ switch (type) {
1707
+ case 'text/plain':
1708
+ return text();
1709
+
1710
+ case 'application/json':
1711
+ return JSON.parse(text());
1712
+
1713
+ case 'application/x-www-form-urlencoded':
1714
+ return get_urlencoded(text());
1715
+
1716
+ case 'multipart/form-data': {
1717
+ const boundary = directives.find((directive) => directive.startsWith('boundary='));
1718
+ if (!boundary) throw new Error('Missing boundary');
1719
+ return get_multipart(text(), boundary.slice('boundary='.length));
1720
+ }
1721
+ default:
1722
+ return raw;
1723
+ }
1724
+ }
1725
+
1726
+ /** @param {string} text */
1727
+ function get_urlencoded(text) {
1728
+ const { data, append } = read_only_form_data();
1729
+
1730
+ text
1731
+ .replace(/\+/g, ' ')
1732
+ .split('&')
1733
+ .forEach((str) => {
1734
+ const [key, value] = str.split('=');
1735
+ append(decodeURIComponent(key), decodeURIComponent(value));
1736
+ });
1737
+
1738
+ return data;
1739
+ }
1740
+
1741
+ /**
1742
+ * @param {string} text
1743
+ * @param {string} boundary
1744
+ */
1745
+ function get_multipart(text, boundary) {
1746
+ const parts = text.split(`--${boundary}`);
1747
+
1748
+ if (parts[0] !== '' || parts[parts.length - 1].trim() !== '--') {
1749
+ throw new Error('Malformed form data');
1750
+ }
1751
+
1752
+ const { data, append } = read_only_form_data();
1753
+
1754
+ parts.slice(1, -1).forEach((part) => {
1755
+ const match = /\s*([\s\S]+?)\r\n\r\n([\s\S]*)\s*/.exec(part);
1756
+ if (!match) {
1757
+ throw new Error('Malformed form data');
1758
+ }
1759
+ const raw_headers = match[1];
1760
+ const body = match[2].trim();
1761
+
1762
+ let key;
1763
+
1764
+ /** @type {Record<string, string>} */
1765
+ const headers = {};
1766
+ raw_headers.split('\r\n').forEach((str) => {
1767
+ const [raw_header, ...raw_directives] = str.split('; ');
1768
+ let [name, value] = raw_header.split(': ');
1769
+
1770
+ name = name.toLowerCase();
1771
+ headers[name] = value;
1772
+
1773
+ /** @type {Record<string, string>} */
1774
+ const directives = {};
1775
+ raw_directives.forEach((raw_directive) => {
1776
+ const [name, value] = raw_directive.split('=');
1777
+ directives[name] = JSON.parse(value); // TODO is this right?
1778
+ });
1779
+
1780
+ if (name === 'content-disposition') {
1781
+ if (value !== 'form-data') throw new Error('Malformed form data');
1782
+
1783
+ if (directives.filename) {
1784
+ // TODO we probably don't want to do this automatically
1785
+ throw new Error('File upload is not yet implemented');
1786
+ }
1787
+
1788
+ if (directives.name) {
1789
+ key = directives.name;
1790
+ }
1791
+ }
1792
+ });
1793
+
1794
+ if (!key) throw new Error('Malformed form data');
1795
+
1796
+ append(key, body);
1797
+ });
1798
+
1799
+ return data;
1800
+ }
1801
+
1802
+ /** @type {import('@sveltejs/kit/ssr').Respond} */
1803
+ async function respond(incoming, options, state = {}) {
1804
+ if (incoming.url.pathname !== '/' && options.trailing_slash !== 'ignore') {
1805
+ const has_trailing_slash = incoming.url.pathname.endsWith('/');
1806
+
1807
+ if (
1808
+ (has_trailing_slash && options.trailing_slash === 'never') ||
1809
+ (!has_trailing_slash &&
1810
+ options.trailing_slash === 'always' &&
1811
+ !(incoming.url.pathname.split('/').pop() || '').includes('.'))
1812
+ ) {
1813
+ incoming.url.pathname = has_trailing_slash
1814
+ ? incoming.url.pathname.slice(0, -1)
1815
+ : incoming.url.pathname + '/';
1816
+
1817
+ if (incoming.url.search === '?') incoming.url.search = '';
1818
+
1819
+ return {
1820
+ status: 301,
1821
+ headers: {
1822
+ location: incoming.url.pathname + incoming.url.search
1823
+ }
1824
+ };
1825
+ }
1826
+ }
1827
+
1828
+ const headers = lowercase_keys(incoming.headers);
1829
+ const request = {
1830
+ ...incoming,
1831
+ headers,
1832
+ body: parse_body(incoming.rawBody, headers),
1833
+ params: {},
1834
+ locals: {}
1835
+ };
1836
+
1837
+ const { parameter, allowed } = options.method_override;
1838
+ const method_override = incoming.url.searchParams.get(parameter)?.toUpperCase();
1839
+
1840
+ if (method_override) {
1841
+ if (request.method.toUpperCase() === 'POST') {
1842
+ if (allowed.includes(method_override)) {
1843
+ request.method = method_override;
1844
+ } else {
1845
+ const verb = allowed.length === 0 ? 'enabled' : 'allowed';
1846
+ const body = `${parameter}=${method_override} is not ${verb}. See https://kit.svelte.dev/docs#configuration-methodoverride`;
1847
+
1848
+ return {
1849
+ status: 400,
1850
+ headers: {},
1851
+ body
1852
+ };
1853
+ }
1854
+ } else {
1855
+ throw new Error(`${parameter}=${method_override} is only allowed with POST requests`);
1856
+ }
1857
+ }
1858
+
1859
+ // TODO remove this for 1.0
1860
+ /**
1861
+ * @param {string} property
1862
+ * @param {string} replacement
1863
+ */
1864
+ const print_error = (property, replacement) => {
1865
+ Object.defineProperty(request, property, {
1866
+ get: () => {
1867
+ throw new Error(`request.${property} has been replaced by request.url.${replacement}`);
1868
+ }
1869
+ });
1870
+ };
1871
+
1872
+ print_error('origin', 'origin');
1873
+ print_error('path', 'pathname');
1874
+ print_error('query', 'searchParams');
1875
+
1876
+ let ssr = true;
1877
+
1878
+ try {
1879
+ return await options.hooks.handle({
1880
+ request,
1881
+ resolve: async (request, opts) => {
1882
+ if (opts && 'ssr' in opts) ssr = /** @type {boolean} */ (opts.ssr);
1883
+
1884
+ if (state.prerender && state.prerender.fallback) {
1885
+ return await render_response({
1886
+ url: request.url,
1887
+ params: request.params,
1888
+ options,
1889
+ state,
1890
+ $session: await options.hooks.getSession(request),
1891
+ page_config: { router: true, hydrate: true },
1892
+ stuff: {},
1893
+ status: 200,
1894
+ branch: [],
1895
+ ssr: false
1896
+ });
1897
+ }
1898
+
1899
+ const decoded = decodeURI(request.url.pathname).replace(options.paths.base, '');
1900
+
1901
+ for (const route of options.manifest._.routes) {
1902
+ const match = route.pattern.exec(decoded);
1903
+ if (!match) continue;
1904
+
1905
+ const response =
1906
+ route.type === 'endpoint'
1907
+ ? await render_endpoint(request, route, match)
1908
+ : await render_page(request, route, match, options, state, ssr);
1909
+
1910
+ if (response) {
1911
+ // inject ETags for 200 responses
1912
+ if (response.status === 200) {
1913
+ const cache_control = get_single_valued_header(response.headers, 'cache-control');
1914
+ if (!cache_control || !/(no-store|immutable)/.test(cache_control)) {
1915
+ let if_none_match_value = request.headers['if-none-match'];
1916
+ // ignore W/ prefix https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/If-None-Match#directives
1917
+ if (if_none_match_value?.startsWith('W/"')) {
1918
+ if_none_match_value = if_none_match_value.substring(2);
1919
+ }
1920
+
1921
+ const etag = `"${hash(response.body || '')}"`;
1922
+
1923
+ if (if_none_match_value === etag) {
1924
+ /** @type {import('types/helper').ResponseHeaders} */
1925
+ const headers = { etag };
1926
+
1927
+ // https://datatracker.ietf.org/doc/html/rfc7232#section-4.1
1928
+ for (const key of [
1929
+ 'cache-control',
1930
+ 'content-location',
1931
+ 'date',
1932
+ 'expires',
1933
+ 'vary'
1934
+ ]) {
1935
+ if (key in response.headers) {
1936
+ headers[key] = /** @type {string} */ (response.headers[key]);
1937
+ }
1938
+ }
1939
+
1940
+ return {
1941
+ status: 304,
1942
+ headers
1943
+ };
1944
+ }
1945
+
1946
+ response.headers['etag'] = etag;
1947
+ }
1948
+ }
1949
+
1950
+ return response;
1951
+ }
1952
+ }
1953
+
1954
+ // if this request came direct from the user, rather than
1955
+ // via a `fetch` in a `load`, render a 404 page
1956
+ if (!state.initiator) {
1957
+ const $session = await options.hooks.getSession(request);
1958
+ return await respond_with_error({
1959
+ request,
1960
+ options,
1961
+ state,
1962
+ $session,
1963
+ status: 404,
1964
+ error: new Error(`Not found: ${request.url.pathname}`),
1965
+ ssr
1966
+ });
1967
+ }
1968
+ }
1969
+ });
1970
+ } catch (/** @type {unknown} */ e) {
1971
+ const error = coalesce_to_error(e);
1972
+
1973
+ options.handle_error(error, request);
1974
+
1975
+ try {
1976
+ const $session = await options.hooks.getSession(request);
1977
+ return await respond_with_error({
1978
+ request,
1979
+ options,
1980
+ state,
1981
+ $session,
1982
+ status: 500,
1983
+ error,
1984
+ ssr
1985
+ });
1986
+ } catch (/** @type {unknown} */ e) {
1987
+ const error = coalesce_to_error(e);
1988
+
1989
+ return {
1990
+ status: 500,
1991
+ headers: {},
1992
+ body: options.dev ? error.stack : error.message
1993
+ };
1994
+ }
1995
+ }
1996
+ }
1997
+
1998
+ export { respond };