@sveltejs/kit 1.0.0-next.20 → 1.0.0-next.200

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