@sveltejs/kit 1.0.0-next.22 → 1.0.0-next.223

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