@sveltejs/kit 1.0.0-next.21 → 1.0.0-next.210

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