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

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,1912 @@
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
+ // TODO remove this for 1.0
606
+ /**
607
+ * @param {string} property
608
+ * @param {string} replacement
609
+ */
610
+ const print_error = (property, replacement) => {
611
+ Object.defineProperty(props.page, property, {
612
+ get: () => {
613
+ throw new Error(`$page.${property} has been replaced by $page.url.${replacement}`);
614
+ }
615
+ });
616
+ };
617
+
618
+ print_error('origin', 'origin');
619
+ print_error('path', 'pathname');
620
+ print_error('query', 'searchParams');
621
+
622
+ // props_n (instead of props[n]) makes it easy to avoid
623
+ // unnecessary updates for layout components
624
+ for (let i = 0; i < branch.length; i += 1) {
625
+ props[`props_${i}`] = await branch[i].loaded.props;
626
+ }
627
+
628
+ let session_tracking_active = false;
629
+ const unsubscribe = session.subscribe(() => {
630
+ if (session_tracking_active) is_private = true;
631
+ });
632
+ session_tracking_active = true;
633
+
634
+ try {
635
+ rendered = options.root.render(props);
636
+ } finally {
637
+ unsubscribe();
638
+ }
639
+ } else {
640
+ rendered = { head: '', html: '', css: { code: '', map: null } };
641
+ }
642
+
643
+ const include_js = page_config.router || page_config.hydrate;
644
+ if (!include_js) js.clear();
645
+
646
+ // TODO strip the AMP stuff out of the build if not relevant
647
+ const links = options.amp
648
+ ? styles.size > 0 || rendered.css.code.length > 0
649
+ ? `<style amp-custom>${Array.from(styles).concat(rendered.css.code).join('\n')}</style>`
650
+ : ''
651
+ : [
652
+ // From https://web.dev/priority-hints/:
653
+ // Generally, preloads will load in the order the parser gets to them for anything above "Medium" priority
654
+ // Thus, we should list CSS first
655
+ ...Array.from(css).map((dep) => `<link rel="stylesheet" href="${options.prefix}${dep}">`),
656
+ ...Array.from(js).map((dep) => `<link rel="modulepreload" href="${options.prefix}${dep}">`)
657
+ ].join('\n\t\t');
658
+
659
+ /** @type {string} */
660
+ let init = '';
661
+
662
+ if (options.amp) {
663
+ init = `
664
+ <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>
665
+ <noscript><style amp-boilerplate>body{-webkit-animation:none;-moz-animation:none;-ms-animation:none;animation:none}</style></noscript>
666
+ <script async src="https://cdn.ampproject.org/v0.js"></script>`;
667
+ init += options.service_worker
668
+ ? '<script async custom-element="amp-install-serviceworker" src="https://cdn.ampproject.org/v0/amp-install-serviceworker-0.1.js"></script>'
669
+ : '';
670
+ } else if (include_js) {
671
+ // prettier-ignore
672
+ init = `<script type="module">
673
+ import { start } from ${s(options.prefix + options.manifest._.entry.file)};
674
+ start({
675
+ target: ${options.target ? `document.querySelector(${s(options.target)})` : 'document.body'},
676
+ paths: ${s(options.paths)},
677
+ session: ${try_serialize($session, (error) => {
678
+ throw new Error(`Failed to serialize session data: ${error.message}`);
679
+ })},
680
+ route: ${!!page_config.router},
681
+ spa: ${!page_config.ssr},
682
+ trailing_slash: ${s(options.trailing_slash)},
683
+ hydrate: ${page_config.ssr && page_config.hydrate ? `{
684
+ status: ${status},
685
+ error: ${serialize_error(error)},
686
+ nodes: [
687
+ ${(branch || [])
688
+ .map(({ node }) => `import(${s(options.prefix + node.entry)})`)
689
+ .join(',\n\t\t\t\t\t\t')}
690
+ ],
691
+ url: new URL(${s(url.href)}),
692
+ params: ${devalue(params)}
693
+ }` : 'null'}
694
+ });
695
+ </script>`;
696
+ }
697
+
698
+ if (options.service_worker && !options.amp) {
699
+ init += `<script>
700
+ if ('serviceWorker' in navigator) {
701
+ navigator.serviceWorker.register('${options.service_worker}');
702
+ }
703
+ </script>`;
704
+ }
705
+
706
+ const head = [
707
+ rendered.head,
708
+ styles.size && !options.amp
709
+ ? `<style data-svelte>${Array.from(styles).join('\n')}</style>`
710
+ : '',
711
+ links,
712
+ init
713
+ ].join('\n\n\t\t');
714
+
715
+ let body = rendered.html;
716
+ if (options.amp) {
717
+ if (options.service_worker) {
718
+ body += `<amp-install-serviceworker src="${options.service_worker}" layout="nodisplay"></amp-install-serviceworker>`;
719
+ }
720
+ } else {
721
+ body += serialized_data
722
+ .map(({ url, body, json }) => {
723
+ let attributes = `type="application/json" data-type="svelte-data" data-url=${escape_html_attr(
724
+ url
725
+ )}`;
726
+ if (body) attributes += ` data-body="${hash(body)}"`;
727
+
728
+ return `<script ${attributes}>${json}</script>`;
729
+ })
730
+ .join('\n\n\t');
731
+ }
732
+
733
+ /** @type {import('types/helper').ResponseHeaders} */
734
+ const headers = {
735
+ 'content-type': 'text/html'
736
+ };
737
+
738
+ if (maxage) {
739
+ headers['cache-control'] = `${is_private ? 'private' : 'public'}, max-age=${maxage}`;
740
+ }
741
+
742
+ if (!options.floc) {
743
+ headers['permissions-policy'] = 'interest-cohort=()';
744
+ }
745
+
746
+ return {
747
+ status,
748
+ headers,
749
+ body: options.template({ head, body })
750
+ };
751
+ }
752
+
753
+ /**
754
+ * @param {any} data
755
+ * @param {(error: Error) => void} [fail]
756
+ */
757
+ function try_serialize(data, fail) {
758
+ try {
759
+ return devalue(data);
760
+ } catch (err) {
761
+ if (fail) fail(coalesce_to_error(err));
762
+ return null;
763
+ }
764
+ }
765
+
766
+ // Ensure we return something truthy so the client will not re-render the page over the error
767
+
768
+ /** @param {(Error & {frame?: string} & {loc?: object}) | undefined | null} error */
769
+ function serialize_error(error) {
770
+ if (!error) return null;
771
+ let serialized = try_serialize(error);
772
+ if (!serialized) {
773
+ const { name, message, stack } = error;
774
+ serialized = try_serialize({ ...error, name, message, stack });
775
+ }
776
+ if (!serialized) {
777
+ serialized = '{}';
778
+ }
779
+ return serialized;
780
+ }
781
+
782
+ /**
783
+ * @param {import('types/page').LoadOutput} loaded
784
+ * @returns {import('types/internal').NormalizedLoadOutput}
785
+ */
786
+ function normalize(loaded) {
787
+ const has_error_status =
788
+ loaded.status && loaded.status >= 400 && loaded.status <= 599 && !loaded.redirect;
789
+ if (loaded.error || has_error_status) {
790
+ const status = loaded.status;
791
+
792
+ if (!loaded.error && has_error_status) {
793
+ return {
794
+ status: status || 500,
795
+ error: new Error()
796
+ };
797
+ }
798
+
799
+ const error = typeof loaded.error === 'string' ? new Error(loaded.error) : loaded.error;
800
+
801
+ if (!(error instanceof Error)) {
802
+ return {
803
+ status: 500,
804
+ error: new Error(
805
+ `"error" property returned from load() must be a string or instance of Error, received type "${typeof error}"`
806
+ )
807
+ };
808
+ }
809
+
810
+ if (!status || status < 400 || status > 599) {
811
+ console.warn('"error" returned from load() without a valid status code — defaulting to 500');
812
+ return { status: 500, error };
813
+ }
814
+
815
+ return { status, error };
816
+ }
817
+
818
+ if (loaded.redirect) {
819
+ if (!loaded.status || Math.floor(loaded.status / 100) !== 3) {
820
+ return {
821
+ status: 500,
822
+ error: new Error(
823
+ '"redirect" property returned from load() must be accompanied by a 3xx status code'
824
+ )
825
+ };
826
+ }
827
+
828
+ if (typeof loaded.redirect !== 'string') {
829
+ return {
830
+ status: 500,
831
+ error: new Error('"redirect" property returned from load() must be a string')
832
+ };
833
+ }
834
+ }
835
+
836
+ // TODO remove before 1.0
837
+ if (/** @type {any} */ (loaded).context) {
838
+ throw new Error(
839
+ 'You are returning "context" from a load function. ' +
840
+ '"context" was renamed to "stuff", please adjust your code accordingly.'
841
+ );
842
+ }
843
+
844
+ return /** @type {import('types/internal').NormalizedLoadOutput} */ (loaded);
845
+ }
846
+
847
+ const absolute = /^([a-z]+:)?\/?\//;
848
+ const scheme = /^[a-z]+:/;
849
+
850
+ /**
851
+ * @param {string} base
852
+ * @param {string} path
853
+ */
854
+ function resolve(base, path) {
855
+ if (scheme.test(path)) return path;
856
+
857
+ const base_match = absolute.exec(base);
858
+ const path_match = absolute.exec(path);
859
+
860
+ if (!base_match) {
861
+ throw new Error(`bad base path: "${base}"`);
862
+ }
863
+
864
+ const baseparts = path_match ? [] : base.slice(base_match[0].length).split('/');
865
+ const pathparts = path_match ? path.slice(path_match[0].length).split('/') : path.split('/');
866
+
867
+ baseparts.pop();
868
+
869
+ for (let i = 0; i < pathparts.length; i += 1) {
870
+ const part = pathparts[i];
871
+ if (part === '.') continue;
872
+ else if (part === '..') baseparts.pop();
873
+ else baseparts.push(part);
874
+ }
875
+
876
+ const prefix = (path_match && path_match[0]) || (base_match && base_match[0]) || '';
877
+
878
+ return `${prefix}${baseparts.join('/')}`;
879
+ }
880
+
881
+ /** @param {string} path */
882
+ function is_root_relative(path) {
883
+ return path[0] === '/' && path[1] !== '/';
884
+ }
885
+
886
+ /**
887
+ * @param {{
888
+ * request: import('types/hooks').ServerRequest;
889
+ * options: import('types/internal').SSRRenderOptions;
890
+ * state: import('types/internal').SSRRenderState;
891
+ * route: import('types/internal').SSRPage | null;
892
+ * url: URL;
893
+ * params: Record<string, string>;
894
+ * node: import('types/internal').SSRNode;
895
+ * $session: any;
896
+ * stuff: Record<string, any>;
897
+ * prerender_enabled: boolean;
898
+ * is_leaf: boolean;
899
+ * is_error: boolean;
900
+ * status?: number;
901
+ * error?: Error;
902
+ * }} opts
903
+ * @returns {Promise<import('./types').Loaded | undefined>} undefined for fallthrough
904
+ */
905
+ async function load_node({
906
+ request,
907
+ options,
908
+ state,
909
+ route,
910
+ url,
911
+ params,
912
+ node,
913
+ $session,
914
+ stuff,
915
+ prerender_enabled,
916
+ is_leaf,
917
+ is_error,
918
+ status,
919
+ error
920
+ }) {
921
+ const { module } = node;
922
+
923
+ let uses_credentials = false;
924
+
925
+ /**
926
+ * @type {Array<{
927
+ * url: string;
928
+ * body: string;
929
+ * json: string;
930
+ * }>}
931
+ */
932
+ const fetched = [];
933
+
934
+ /**
935
+ * @type {string[]}
936
+ */
937
+ let set_cookie_headers = [];
938
+
939
+ let loaded;
940
+
941
+ const url_proxy = new Proxy(url, {
942
+ get: (target, prop, receiver) => {
943
+ if (prerender_enabled && (prop === 'search' || prop === 'searchParams')) {
944
+ throw new Error('Cannot access query on a page with prerendering enabled');
945
+ }
946
+ return Reflect.get(target, prop, receiver);
947
+ }
948
+ });
949
+
950
+ if (module.load) {
951
+ /** @type {import('types/page').LoadInput | import('types/page').ErrorLoadInput} */
952
+ const load_input = {
953
+ url: url_proxy,
954
+ params,
955
+ get session() {
956
+ uses_credentials = true;
957
+ return $session;
958
+ },
959
+ /**
960
+ * @param {RequestInfo} resource
961
+ * @param {RequestInit} opts
962
+ */
963
+ fetch: async (resource, opts = {}) => {
964
+ /** @type {string} */
965
+ let requested;
966
+
967
+ if (typeof resource === 'string') {
968
+ requested = resource;
969
+ } else {
970
+ requested = resource.url;
971
+
972
+ opts = {
973
+ method: resource.method,
974
+ headers: resource.headers,
975
+ body: resource.body,
976
+ mode: resource.mode,
977
+ credentials: resource.credentials,
978
+ cache: resource.cache,
979
+ redirect: resource.redirect,
980
+ referrer: resource.referrer,
981
+ integrity: resource.integrity,
982
+ ...opts
983
+ };
984
+ }
985
+
986
+ opts.headers = new Headers(opts.headers);
987
+
988
+ const resolved = resolve(request.url.pathname, requested.split('?')[0]);
989
+
990
+ let response;
991
+
992
+ // handle fetch requests for static assets. e.g. prebaked data, etc.
993
+ // we need to support everything the browser's fetch supports
994
+ const prefix = options.paths.assets || options.paths.base;
995
+ const filename = (
996
+ resolved.startsWith(prefix) ? resolved.slice(prefix.length) : resolved
997
+ ).slice(1);
998
+ const filename_html = `${filename}/index.html`; // path may also match path/index.html
999
+
1000
+ const is_asset = options.manifest.assets.has(filename);
1001
+ const is_asset_html = options.manifest.assets.has(filename_html);
1002
+
1003
+ if (is_asset || is_asset_html) {
1004
+ const file = is_asset ? filename : filename_html;
1005
+
1006
+ if (options.read) {
1007
+ const type = is_asset
1008
+ ? options.manifest._.mime[filename.slice(filename.lastIndexOf('.'))]
1009
+ : 'text/html';
1010
+
1011
+ response = new Response(options.read(file), {
1012
+ headers: type ? { 'content-type': type } : {}
1013
+ });
1014
+ } else {
1015
+ response = await fetch(`${url.origin}/${file}`, /** @type {RequestInit} */ (opts));
1016
+ }
1017
+ } else if (is_root_relative(resolved)) {
1018
+ const relative = resolved;
1019
+
1020
+ // TODO: fix type https://github.com/node-fetch/node-fetch/issues/1113
1021
+ if (opts.credentials !== 'omit') {
1022
+ uses_credentials = true;
1023
+
1024
+ if (request.headers.cookie) {
1025
+ opts.headers.set('cookie', request.headers.cookie);
1026
+ }
1027
+
1028
+ if (request.headers.authorization && !opts.headers.has('authorization')) {
1029
+ opts.headers.set('authorization', request.headers.authorization);
1030
+ }
1031
+ }
1032
+
1033
+ if (opts.body && typeof opts.body !== 'string') {
1034
+ // per https://developer.mozilla.org/en-US/docs/Web/API/Request/Request, this can be a
1035
+ // Blob, BufferSource, FormData, URLSearchParams, USVString, or ReadableStream object.
1036
+ // non-string bodies are irksome to deal with, but luckily aren't particularly useful
1037
+ // in this context anyway, so we take the easy route and ban them
1038
+ throw new Error('Request body must be a string');
1039
+ }
1040
+
1041
+ const rendered = await respond(
1042
+ {
1043
+ url: new URL(requested, request.url),
1044
+ method: opts.method || 'GET',
1045
+ headers: Object.fromEntries(opts.headers),
1046
+ rawBody: opts.body == null ? null : new TextEncoder().encode(opts.body)
1047
+ },
1048
+ options,
1049
+ {
1050
+ fetched: requested,
1051
+ initiator: route
1052
+ }
1053
+ );
1054
+
1055
+ if (rendered) {
1056
+ if (state.prerender) {
1057
+ state.prerender.dependencies.set(relative, rendered);
1058
+ }
1059
+
1060
+ // Set-Cookie must be filtered out (done below) and that's the only header value that
1061
+ // can be an array so we know we have only simple values
1062
+ // https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie
1063
+ response = new Response(rendered.body, {
1064
+ status: rendered.status,
1065
+ headers: /** @type {Record<string, string>} */ (rendered.headers)
1066
+ });
1067
+ } else {
1068
+ // we can't load the endpoint from our own manifest,
1069
+ // so we need to make an actual HTTP request
1070
+ return fetch(new URL(requested, request.url).href, {
1071
+ method: opts.method || 'GET',
1072
+ headers: opts.headers
1073
+ });
1074
+ }
1075
+ } else {
1076
+ // external
1077
+ if (resolved.startsWith('//')) {
1078
+ throw new Error(
1079
+ `Cannot request protocol-relative URL (${requested}) in server-side fetch`
1080
+ );
1081
+ }
1082
+
1083
+ // external fetch
1084
+ // allow cookie passthrough for "same-origin"
1085
+ // if SvelteKit is serving my.domain.com:
1086
+ // - domain.com WILL NOT receive cookies
1087
+ // - my.domain.com WILL receive cookies
1088
+ // - api.domain.dom WILL NOT receive cookies
1089
+ // - sub.my.domain.com WILL receive cookies
1090
+ // ports do not affect the resolution
1091
+ // leading dot prevents mydomain.com matching domain.com
1092
+ if (
1093
+ `.${new URL(requested).hostname}`.endsWith(`.${request.url.hostname}`) &&
1094
+ opts.credentials !== 'omit'
1095
+ ) {
1096
+ uses_credentials = true;
1097
+ opts.headers.set('cookie', request.headers.cookie);
1098
+ }
1099
+
1100
+ const external_request = new Request(requested, /** @type {RequestInit} */ (opts));
1101
+ response = await options.hooks.externalFetch.call(null, external_request);
1102
+ }
1103
+
1104
+ if (response) {
1105
+ const proxy = new Proxy(response, {
1106
+ get(response, key, _receiver) {
1107
+ async function text() {
1108
+ const body = await response.text();
1109
+
1110
+ /** @type {import('types/helper').ResponseHeaders} */
1111
+ const headers = {};
1112
+ for (const [key, value] of response.headers) {
1113
+ if (key === 'set-cookie') {
1114
+ set_cookie_headers = set_cookie_headers.concat(value);
1115
+ } else if (key !== 'etag') {
1116
+ headers[key] = value;
1117
+ }
1118
+ }
1119
+
1120
+ if (!opts.body || typeof opts.body === 'string') {
1121
+ // prettier-ignore
1122
+ fetched.push({
1123
+ url: requested,
1124
+ body: /** @type {string} */ (opts.body),
1125
+ json: `{"status":${response.status},"statusText":${s(response.statusText)},"headers":${s(headers)},"body":"${escape_json_string_in_html(body)}"}`
1126
+ });
1127
+ }
1128
+
1129
+ return body;
1130
+ }
1131
+
1132
+ if (key === 'text') {
1133
+ return text;
1134
+ }
1135
+
1136
+ if (key === 'json') {
1137
+ return async () => {
1138
+ return JSON.parse(await text());
1139
+ };
1140
+ }
1141
+
1142
+ // TODO arrayBuffer?
1143
+
1144
+ return Reflect.get(response, key, response);
1145
+ }
1146
+ });
1147
+
1148
+ return proxy;
1149
+ }
1150
+
1151
+ return (
1152
+ response ||
1153
+ new Response('Not found', {
1154
+ status: 404
1155
+ })
1156
+ );
1157
+ },
1158
+ stuff: { ...stuff }
1159
+ };
1160
+
1161
+ if (options.dev) {
1162
+ // TODO remove this for 1.0
1163
+ Object.defineProperty(load_input, 'page', {
1164
+ get: () => {
1165
+ throw new Error('`page` in `load` functions has been replaced by `url` and `params`');
1166
+ }
1167
+ });
1168
+ }
1169
+
1170
+ if (is_error) {
1171
+ /** @type {import('types/page').ErrorLoadInput} */ (load_input).status = status;
1172
+ /** @type {import('types/page').ErrorLoadInput} */ (load_input).error = error;
1173
+ }
1174
+
1175
+ loaded = await module.load.call(null, load_input);
1176
+ } else {
1177
+ loaded = {};
1178
+ }
1179
+
1180
+ // if leaf node (i.e. page component) has a load function
1181
+ // that returns nothing, we fall through to the next one
1182
+ if (!loaded && is_leaf && !is_error) return;
1183
+
1184
+ if (!loaded) {
1185
+ throw new Error(`${node.entry} - load must return a value except for page fall through`);
1186
+ }
1187
+
1188
+ return {
1189
+ node,
1190
+ loaded: normalize(loaded),
1191
+ stuff: loaded.stuff || stuff,
1192
+ fetched,
1193
+ set_cookie_headers,
1194
+ uses_credentials
1195
+ };
1196
+ }
1197
+
1198
+ /**
1199
+ * @typedef {import('./types.js').Loaded} Loaded
1200
+ * @typedef {import('types/internal').SSRNode} SSRNode
1201
+ * @typedef {import('types/internal').SSRRenderOptions} SSRRenderOptions
1202
+ * @typedef {import('types/internal').SSRRenderState} SSRRenderState
1203
+ */
1204
+
1205
+ /**
1206
+ * @param {{
1207
+ * request: import('types/hooks').ServerRequest;
1208
+ * options: SSRRenderOptions;
1209
+ * state: SSRRenderState;
1210
+ * $session: any;
1211
+ * status: number;
1212
+ * error: Error;
1213
+ * }} opts
1214
+ */
1215
+ async function respond_with_error({ request, options, state, $session, status, error }) {
1216
+ const default_layout = await options.manifest._.nodes[0](); // 0 is always the root layout
1217
+ const default_error = await options.manifest._.nodes[1](); // 1 is always the root error
1218
+
1219
+ /** @type {Record<string, string>} */
1220
+ const params = {}; // error page has no params
1221
+
1222
+ // error pages don't fall through, so we know it's not undefined
1223
+ const loaded = /** @type {Loaded} */ (
1224
+ await load_node({
1225
+ request,
1226
+ options,
1227
+ state,
1228
+ route: null,
1229
+ url: request.url, // TODO this is redundant, no?
1230
+ params,
1231
+ node: default_layout,
1232
+ $session,
1233
+ stuff: {},
1234
+ prerender_enabled: is_prerender_enabled(options, default_error, state),
1235
+ is_leaf: false,
1236
+ is_error: false
1237
+ })
1238
+ );
1239
+
1240
+ const branch = [
1241
+ loaded,
1242
+ /** @type {Loaded} */ (
1243
+ await load_node({
1244
+ request,
1245
+ options,
1246
+ state,
1247
+ route: null,
1248
+ url: request.url,
1249
+ params,
1250
+ node: default_error,
1251
+ $session,
1252
+ stuff: loaded ? loaded.stuff : {},
1253
+ prerender_enabled: is_prerender_enabled(options, default_error, state),
1254
+ is_leaf: false,
1255
+ is_error: true,
1256
+ status,
1257
+ error
1258
+ })
1259
+ )
1260
+ ];
1261
+
1262
+ try {
1263
+ return await render_response({
1264
+ options,
1265
+ $session,
1266
+ page_config: {
1267
+ hydrate: options.hydrate,
1268
+ router: options.router,
1269
+ ssr: options.ssr
1270
+ },
1271
+ status,
1272
+ error,
1273
+ branch,
1274
+ url: request.url,
1275
+ params
1276
+ });
1277
+ } catch (err) {
1278
+ const error = coalesce_to_error(err);
1279
+
1280
+ options.handle_error(error, request);
1281
+
1282
+ return {
1283
+ status: 500,
1284
+ headers: {},
1285
+ body: error.stack
1286
+ };
1287
+ }
1288
+ }
1289
+
1290
+ /**
1291
+ * @param {SSRRenderOptions} options
1292
+ * @param {SSRNode} node
1293
+ * @param {SSRRenderState} state
1294
+ */
1295
+ function is_prerender_enabled(options, node, state) {
1296
+ return (
1297
+ options.prerender && (!!node.module.prerender || (!!state.prerender && state.prerender.all))
1298
+ );
1299
+ }
1300
+
1301
+ /**
1302
+ * @typedef {import('./types.js').Loaded} Loaded
1303
+ * @typedef {import('types/hooks').ServerResponse} ServerResponse
1304
+ * @typedef {import('types/internal').SSRNode} SSRNode
1305
+ * @typedef {import('types/internal').SSRRenderOptions} SSRRenderOptions
1306
+ * @typedef {import('types/internal').SSRRenderState} SSRRenderState
1307
+ */
1308
+
1309
+ /**
1310
+ * @param {{
1311
+ * request: import('types/hooks').ServerRequest;
1312
+ * options: SSRRenderOptions;
1313
+ * state: SSRRenderState;
1314
+ * $session: any;
1315
+ * route: import('types/internal').SSRPage;
1316
+ * params: Record<string, string>;
1317
+ * }} opts
1318
+ * @returns {Promise<ServerResponse | undefined>}
1319
+ */
1320
+ async function respond$1(opts) {
1321
+ const { request, options, state, $session, route } = opts;
1322
+
1323
+ /** @type {Array<SSRNode | undefined>} */
1324
+ let nodes;
1325
+
1326
+ try {
1327
+ nodes = await Promise.all(
1328
+ route.a.map((n) => options.manifest._.nodes[n] && options.manifest._.nodes[n]())
1329
+ );
1330
+ } catch (err) {
1331
+ const error = coalesce_to_error(err);
1332
+
1333
+ options.handle_error(error, request);
1334
+
1335
+ return await respond_with_error({
1336
+ request,
1337
+ options,
1338
+ state,
1339
+ $session,
1340
+ status: 500,
1341
+ error
1342
+ });
1343
+ }
1344
+
1345
+ // the leaf node will be present. only layouts may be undefined
1346
+ const leaf = /** @type {SSRNode} */ (nodes[nodes.length - 1]).module;
1347
+
1348
+ let page_config = get_page_config(leaf, options);
1349
+
1350
+ if (!leaf.prerender && state.prerender && !state.prerender.all) {
1351
+ // if the page has `export const prerender = true`, continue,
1352
+ // otherwise bail out at this point
1353
+ return {
1354
+ status: 204,
1355
+ headers: {}
1356
+ };
1357
+ }
1358
+
1359
+ /** @type {Array<Loaded>} */
1360
+ let branch = [];
1361
+
1362
+ /** @type {number} */
1363
+ let status = 200;
1364
+
1365
+ /** @type {Error|undefined} */
1366
+ let error;
1367
+
1368
+ /** @type {string[]} */
1369
+ let set_cookie_headers = [];
1370
+
1371
+ ssr: if (page_config.ssr) {
1372
+ let stuff = {};
1373
+
1374
+ for (let i = 0; i < nodes.length; i += 1) {
1375
+ const node = nodes[i];
1376
+
1377
+ /** @type {Loaded | undefined} */
1378
+ let loaded;
1379
+
1380
+ if (node) {
1381
+ try {
1382
+ loaded = await load_node({
1383
+ ...opts,
1384
+ url: request.url,
1385
+ node,
1386
+ stuff,
1387
+ prerender_enabled: is_prerender_enabled(options, node, state),
1388
+ is_leaf: i === nodes.length - 1,
1389
+ is_error: false
1390
+ });
1391
+
1392
+ if (!loaded) return;
1393
+
1394
+ set_cookie_headers = set_cookie_headers.concat(loaded.set_cookie_headers);
1395
+
1396
+ if (loaded.loaded.redirect) {
1397
+ return with_cookies(
1398
+ {
1399
+ status: loaded.loaded.status,
1400
+ headers: {
1401
+ location: encodeURI(loaded.loaded.redirect)
1402
+ }
1403
+ },
1404
+ set_cookie_headers
1405
+ );
1406
+ }
1407
+
1408
+ if (loaded.loaded.error) {
1409
+ ({ status, error } = loaded.loaded);
1410
+ }
1411
+ } catch (err) {
1412
+ const e = coalesce_to_error(err);
1413
+
1414
+ options.handle_error(e, request);
1415
+
1416
+ status = 500;
1417
+ error = e;
1418
+ }
1419
+
1420
+ if (loaded && !error) {
1421
+ branch.push(loaded);
1422
+ }
1423
+
1424
+ if (error) {
1425
+ while (i--) {
1426
+ if (route.b[i]) {
1427
+ const error_node = await options.manifest._.nodes[route.b[i]]();
1428
+
1429
+ /** @type {Loaded} */
1430
+ let node_loaded;
1431
+ let j = i;
1432
+ while (!(node_loaded = branch[j])) {
1433
+ j -= 1;
1434
+ }
1435
+
1436
+ try {
1437
+ // there's no fallthough on an error page, so we know it's not undefined
1438
+ const error_loaded = /** @type {import('./types').Loaded} */ (
1439
+ await load_node({
1440
+ ...opts,
1441
+ url: request.url,
1442
+ node: error_node,
1443
+ stuff: node_loaded.stuff,
1444
+ prerender_enabled: is_prerender_enabled(options, error_node, state),
1445
+ is_leaf: false,
1446
+ is_error: true,
1447
+ status,
1448
+ error
1449
+ })
1450
+ );
1451
+
1452
+ if (error_loaded.loaded.error) {
1453
+ continue;
1454
+ }
1455
+
1456
+ page_config = get_page_config(error_node.module, options);
1457
+ branch = branch.slice(0, j + 1).concat(error_loaded);
1458
+ break ssr;
1459
+ } catch (err) {
1460
+ const e = coalesce_to_error(err);
1461
+
1462
+ options.handle_error(e, request);
1463
+
1464
+ continue;
1465
+ }
1466
+ }
1467
+ }
1468
+
1469
+ // TODO backtrack until we find an __error.svelte component
1470
+ // that we can use as the leaf node
1471
+ // for now just return regular error page
1472
+ return with_cookies(
1473
+ await respond_with_error({
1474
+ request,
1475
+ options,
1476
+ state,
1477
+ $session,
1478
+ status,
1479
+ error
1480
+ }),
1481
+ set_cookie_headers
1482
+ );
1483
+ }
1484
+ }
1485
+
1486
+ if (loaded && loaded.loaded.stuff) {
1487
+ stuff = {
1488
+ ...stuff,
1489
+ ...loaded.loaded.stuff
1490
+ };
1491
+ }
1492
+ }
1493
+ }
1494
+
1495
+ try {
1496
+ return with_cookies(
1497
+ await render_response({
1498
+ ...opts,
1499
+ url: request.url,
1500
+ page_config,
1501
+ status,
1502
+ error,
1503
+ branch: branch.filter(Boolean)
1504
+ }),
1505
+ set_cookie_headers
1506
+ );
1507
+ } catch (err) {
1508
+ const error = coalesce_to_error(err);
1509
+
1510
+ options.handle_error(error, request);
1511
+
1512
+ return with_cookies(
1513
+ await respond_with_error({
1514
+ ...opts,
1515
+ status: 500,
1516
+ error
1517
+ }),
1518
+ set_cookie_headers
1519
+ );
1520
+ }
1521
+ }
1522
+
1523
+ /**
1524
+ * @param {import('types/internal').SSRComponent} leaf
1525
+ * @param {SSRRenderOptions} options
1526
+ */
1527
+ function get_page_config(leaf, options) {
1528
+ return {
1529
+ ssr: 'ssr' in leaf ? !!leaf.ssr : options.ssr,
1530
+ router: 'router' in leaf ? !!leaf.router : options.router,
1531
+ hydrate: 'hydrate' in leaf ? !!leaf.hydrate : options.hydrate
1532
+ };
1533
+ }
1534
+
1535
+ /**
1536
+ * @param {ServerResponse} response
1537
+ * @param {string[]} set_cookie_headers
1538
+ */
1539
+ function with_cookies(response, set_cookie_headers) {
1540
+ if (set_cookie_headers.length) {
1541
+ response.headers['set-cookie'] = set_cookie_headers;
1542
+ }
1543
+ return response;
1544
+ }
1545
+
1546
+ /**
1547
+ * @param {import('types/hooks').ServerRequest} request
1548
+ * @param {import('types/internal').SSRPage} route
1549
+ * @param {RegExpExecArray} match
1550
+ * @param {import('types/internal').SSRRenderOptions} options
1551
+ * @param {import('types/internal').SSRRenderState} state
1552
+ * @returns {Promise<import('types/hooks').ServerResponse | undefined>}
1553
+ */
1554
+ async function render_page(request, route, match, options, state) {
1555
+ if (state.initiator === route) {
1556
+ // infinite request cycle detected
1557
+ return {
1558
+ status: 404,
1559
+ headers: {},
1560
+ body: `Not found: ${request.url.pathname}`
1561
+ };
1562
+ }
1563
+
1564
+ const params = route.params ? decode_params(route.params(match)) : {};
1565
+
1566
+ const $session = await options.hooks.getSession(request);
1567
+
1568
+ const response = await respond$1({
1569
+ request,
1570
+ options,
1571
+ state,
1572
+ $session,
1573
+ route,
1574
+ params
1575
+ });
1576
+
1577
+ if (response) {
1578
+ return response;
1579
+ }
1580
+
1581
+ if (state.fetched) {
1582
+ // we came here because of a bad request in a `load` function.
1583
+ // rather than render the error page — which could lead to an
1584
+ // infinite loop, if the `load` belonged to the root layout,
1585
+ // we respond with a bare-bones 500
1586
+ return {
1587
+ status: 500,
1588
+ headers: {},
1589
+ body: `Bad request in load function: failed to fetch ${state.fetched}`
1590
+ };
1591
+ }
1592
+ }
1593
+
1594
+ function read_only_form_data() {
1595
+ /** @type {Map<string, string[]>} */
1596
+ const map = new Map();
1597
+
1598
+ return {
1599
+ /**
1600
+ * @param {string} key
1601
+ * @param {string} value
1602
+ */
1603
+ append(key, value) {
1604
+ if (map.has(key)) {
1605
+ (map.get(key) || []).push(value);
1606
+ } else {
1607
+ map.set(key, [value]);
1608
+ }
1609
+ },
1610
+
1611
+ data: new ReadOnlyFormData(map)
1612
+ };
1613
+ }
1614
+
1615
+ class ReadOnlyFormData {
1616
+ /** @type {Map<string, string[]>} */
1617
+ #map;
1618
+
1619
+ /** @param {Map<string, string[]>} map */
1620
+ constructor(map) {
1621
+ this.#map = map;
1622
+ }
1623
+
1624
+ /** @param {string} key */
1625
+ get(key) {
1626
+ const value = this.#map.get(key);
1627
+ return value && value[0];
1628
+ }
1629
+
1630
+ /** @param {string} key */
1631
+ getAll(key) {
1632
+ return this.#map.get(key);
1633
+ }
1634
+
1635
+ /** @param {string} key */
1636
+ has(key) {
1637
+ return this.#map.has(key);
1638
+ }
1639
+
1640
+ *[Symbol.iterator]() {
1641
+ for (const [key, value] of this.#map) {
1642
+ for (let i = 0; i < value.length; i += 1) {
1643
+ yield [key, value[i]];
1644
+ }
1645
+ }
1646
+ }
1647
+
1648
+ *entries() {
1649
+ for (const [key, value] of this.#map) {
1650
+ for (let i = 0; i < value.length; i += 1) {
1651
+ yield [key, value[i]];
1652
+ }
1653
+ }
1654
+ }
1655
+
1656
+ *keys() {
1657
+ for (const [key] of this.#map) yield key;
1658
+ }
1659
+
1660
+ *values() {
1661
+ for (const [, value] of this.#map) {
1662
+ for (let i = 0; i < value.length; i += 1) {
1663
+ yield value[i];
1664
+ }
1665
+ }
1666
+ }
1667
+ }
1668
+
1669
+ /**
1670
+ * @param {import('types/app').RawBody} raw
1671
+ * @param {import('types/helper').RequestHeaders} headers
1672
+ */
1673
+ function parse_body(raw, headers) {
1674
+ if (!raw) return raw;
1675
+
1676
+ const content_type = headers['content-type'];
1677
+ const [type, ...directives] = content_type ? content_type.split(/;\s*/) : [];
1678
+
1679
+ const text = () => new TextDecoder(headers['content-encoding'] || 'utf-8').decode(raw);
1680
+
1681
+ switch (type) {
1682
+ case 'text/plain':
1683
+ return text();
1684
+
1685
+ case 'application/json':
1686
+ return JSON.parse(text());
1687
+
1688
+ case 'application/x-www-form-urlencoded':
1689
+ return get_urlencoded(text());
1690
+
1691
+ case 'multipart/form-data': {
1692
+ const boundary = directives.find((directive) => directive.startsWith('boundary='));
1693
+ if (!boundary) throw new Error('Missing boundary');
1694
+ return get_multipart(text(), boundary.slice('boundary='.length));
1695
+ }
1696
+ default:
1697
+ return raw;
1698
+ }
1699
+ }
1700
+
1701
+ /** @param {string} text */
1702
+ function get_urlencoded(text) {
1703
+ const { data, append } = read_only_form_data();
1704
+
1705
+ text
1706
+ .replace(/\+/g, ' ')
1707
+ .split('&')
1708
+ .forEach((str) => {
1709
+ const [key, value] = str.split('=');
1710
+ append(decodeURIComponent(key), decodeURIComponent(value));
1711
+ });
1712
+
1713
+ return data;
1714
+ }
1715
+
1716
+ /**
1717
+ * @param {string} text
1718
+ * @param {string} boundary
1719
+ */
1720
+ function get_multipart(text, boundary) {
1721
+ const parts = text.split(`--${boundary}`);
1722
+
1723
+ if (parts[0] !== '' || parts[parts.length - 1].trim() !== '--') {
1724
+ throw new Error('Malformed form data');
1725
+ }
1726
+
1727
+ const { data, append } = read_only_form_data();
1728
+
1729
+ parts.slice(1, -1).forEach((part) => {
1730
+ const match = /\s*([\s\S]+?)\r\n\r\n([\s\S]*)\s*/.exec(part);
1731
+ if (!match) {
1732
+ throw new Error('Malformed form data');
1733
+ }
1734
+ const raw_headers = match[1];
1735
+ const body = match[2].trim();
1736
+
1737
+ let key;
1738
+
1739
+ /** @type {Record<string, string>} */
1740
+ const headers = {};
1741
+ raw_headers.split('\r\n').forEach((str) => {
1742
+ const [raw_header, ...raw_directives] = str.split('; ');
1743
+ let [name, value] = raw_header.split(': ');
1744
+
1745
+ name = name.toLowerCase();
1746
+ headers[name] = value;
1747
+
1748
+ /** @type {Record<string, string>} */
1749
+ const directives = {};
1750
+ raw_directives.forEach((raw_directive) => {
1751
+ const [name, value] = raw_directive.split('=');
1752
+ directives[name] = JSON.parse(value); // TODO is this right?
1753
+ });
1754
+
1755
+ if (name === 'content-disposition') {
1756
+ if (value !== 'form-data') throw new Error('Malformed form data');
1757
+
1758
+ if (directives.filename) {
1759
+ // TODO we probably don't want to do this automatically
1760
+ throw new Error('File upload is not yet implemented');
1761
+ }
1762
+
1763
+ if (directives.name) {
1764
+ key = directives.name;
1765
+ }
1766
+ }
1767
+ });
1768
+
1769
+ if (!key) throw new Error('Malformed form data');
1770
+
1771
+ append(key, body);
1772
+ });
1773
+
1774
+ return data;
1775
+ }
1776
+
1777
+ /** @type {import('@sveltejs/kit/ssr').Respond} */
1778
+ async function respond(incoming, options, state = {}) {
1779
+ if (incoming.url.pathname !== '/' && options.trailing_slash !== 'ignore') {
1780
+ const has_trailing_slash = incoming.url.pathname.endsWith('/');
1781
+
1782
+ if (
1783
+ (has_trailing_slash && options.trailing_slash === 'never') ||
1784
+ (!has_trailing_slash &&
1785
+ options.trailing_slash === 'always' &&
1786
+ !(incoming.url.pathname.split('/').pop() || '').includes('.'))
1787
+ ) {
1788
+ incoming.url.pathname = has_trailing_slash
1789
+ ? incoming.url.pathname.slice(0, -1)
1790
+ : incoming.url.pathname + '/';
1791
+
1792
+ if (incoming.url.search === '?') incoming.url.search = '';
1793
+
1794
+ return {
1795
+ status: 301,
1796
+ headers: {
1797
+ location: incoming.url.pathname + incoming.url.search
1798
+ }
1799
+ };
1800
+ }
1801
+ }
1802
+
1803
+ const headers = lowercase_keys(incoming.headers);
1804
+ const request = {
1805
+ ...incoming,
1806
+ headers,
1807
+ body: parse_body(incoming.rawBody, headers),
1808
+ params: {},
1809
+ locals: {}
1810
+ };
1811
+
1812
+ // TODO remove this for 1.0
1813
+ /**
1814
+ * @param {string} property
1815
+ * @param {string} replacement
1816
+ */
1817
+ const print_error = (property, replacement) => {
1818
+ Object.defineProperty(request, property, {
1819
+ get: () => {
1820
+ throw new Error(`request.${property} has been replaced by request.url.${replacement}`);
1821
+ }
1822
+ });
1823
+ };
1824
+
1825
+ print_error('origin', 'origin');
1826
+ print_error('path', 'pathname');
1827
+ print_error('query', 'searchParams');
1828
+
1829
+ try {
1830
+ return await options.hooks.handle({
1831
+ request,
1832
+ resolve: async (request) => {
1833
+ if (state.prerender && state.prerender.fallback) {
1834
+ return await render_response({
1835
+ url: request.url,
1836
+ params: request.params,
1837
+ options,
1838
+ $session: await options.hooks.getSession(request),
1839
+ page_config: { ssr: false, router: true, hydrate: true },
1840
+ status: 200,
1841
+ branch: []
1842
+ });
1843
+ }
1844
+
1845
+ const decoded = decodeURI(request.url.pathname).replace(options.paths.base, '');
1846
+
1847
+ for (const route of options.manifest._.routes) {
1848
+ const match = route.pattern.exec(decoded);
1849
+ if (!match) continue;
1850
+
1851
+ const response =
1852
+ route.type === 'endpoint'
1853
+ ? await render_endpoint(request, route, match)
1854
+ : await render_page(request, route, match, options, state);
1855
+
1856
+ if (response) {
1857
+ // inject ETags for 200 responses
1858
+ if (response.status === 200) {
1859
+ const cache_control = get_single_valued_header(response.headers, 'cache-control');
1860
+ if (!cache_control || !/(no-store|immutable)/.test(cache_control)) {
1861
+ let if_none_match_value = request.headers['if-none-match'];
1862
+ // ignore W/ prefix https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/If-None-Match#directives
1863
+ if (if_none_match_value?.startsWith('W/"')) {
1864
+ if_none_match_value = if_none_match_value.substring(2);
1865
+ }
1866
+
1867
+ const etag = `"${hash(response.body || '')}"`;
1868
+
1869
+ if (if_none_match_value === etag) {
1870
+ return {
1871
+ status: 304,
1872
+ headers: {}
1873
+ };
1874
+ }
1875
+
1876
+ response.headers['etag'] = etag;
1877
+ }
1878
+ }
1879
+
1880
+ return response;
1881
+ }
1882
+ }
1883
+
1884
+ // if this request came direct from the user, rather than
1885
+ // via a `fetch` in a `load`, render a 404 page
1886
+ if (!state.initiator) {
1887
+ const $session = await options.hooks.getSession(request);
1888
+ return await respond_with_error({
1889
+ request,
1890
+ options,
1891
+ state,
1892
+ $session,
1893
+ status: 404,
1894
+ error: new Error(`Not found: ${request.url.pathname}`)
1895
+ });
1896
+ }
1897
+ }
1898
+ });
1899
+ } catch (/** @type {unknown} */ err) {
1900
+ const e = coalesce_to_error(err);
1901
+
1902
+ options.handle_error(e, request);
1903
+
1904
+ return {
1905
+ status: 500,
1906
+ headers: {},
1907
+ body: options.dev ? e.stack : e.message
1908
+ };
1909
+ }
1910
+ }
1911
+
1912
+ export { respond };