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

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