@sveltejs/kit 1.0.0-next.208 → 1.0.0-next.209

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