@sveltejs/kit 1.0.0-next.39 → 1.0.0-next.390

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (41) hide show
  1. package/README.md +12 -9
  2. package/assets/app/env.js +13 -0
  3. package/assets/app/navigation.js +24 -0
  4. package/assets/app/paths.js +1 -0
  5. package/assets/{runtime/app → app}/stores.js +33 -29
  6. package/assets/client/singletons.js +13 -0
  7. package/assets/client/start.js +1836 -0
  8. package/assets/components/error.svelte +18 -2
  9. package/assets/env.js +8 -0
  10. package/assets/{runtime/chunks/paths.js → paths.js} +4 -3
  11. package/assets/server/index.js +3565 -0
  12. package/dist/chunks/error.js +682 -0
  13. package/dist/chunks/index.js +15292 -3067
  14. package/dist/chunks/index2.js +175 -548
  15. package/dist/chunks/multipart-parser.js +458 -0
  16. package/dist/chunks/sync.js +1007 -0
  17. package/dist/chunks/write_tsconfig.js +274 -0
  18. package/dist/cli.js +66 -514
  19. package/dist/hooks.js +28 -0
  20. package/dist/node/polyfills.js +17778 -0
  21. package/dist/node.js +348 -0
  22. package/dist/vite.js +3289 -0
  23. package/package.json +97 -64
  24. package/types/ambient.d.ts +328 -0
  25. package/types/index.d.ts +290 -0
  26. package/types/internal.d.ts +327 -0
  27. package/types/private.d.ts +235 -0
  28. package/CHANGELOG.md +0 -405
  29. package/assets/runtime/app/env.js +0 -5
  30. package/assets/runtime/app/navigation.js +0 -41
  31. package/assets/runtime/app/paths.js +0 -1
  32. package/assets/runtime/chunks/utils.js +0 -19
  33. package/assets/runtime/internal/singletons.js +0 -23
  34. package/assets/runtime/internal/start.js +0 -770
  35. package/dist/chunks/index3.js +0 -246
  36. package/dist/chunks/index4.js +0 -517
  37. package/dist/chunks/index5.js +0 -761
  38. package/dist/chunks/index6.js +0 -322
  39. package/dist/chunks/standard.js +0 -99
  40. package/dist/chunks/utils.js +0 -83
  41. package/dist/ssr.js +0 -2523
@@ -0,0 +1,3565 @@
1
+ /** @param {Partial<import('types').ResponseHeaders> | undefined} object */
2
+ function to_headers(object) {
3
+ const headers = new Headers();
4
+
5
+ if (object) {
6
+ for (const key in object) {
7
+ const value = object[key];
8
+ if (!value) continue;
9
+
10
+ if (Array.isArray(value)) {
11
+ value.forEach((value) => {
12
+ headers.append(key, /** @type {string} */ (value));
13
+ });
14
+ } else {
15
+ headers.set(key, /** @type {string} */ (value));
16
+ }
17
+ }
18
+ }
19
+
20
+ return headers;
21
+ }
22
+
23
+ /**
24
+ * Given an Accept header and a list of possible content types, pick
25
+ * the most suitable one to respond with
26
+ * @param {string} accept
27
+ * @param {string[]} types
28
+ */
29
+ function negotiate(accept, types) {
30
+ /** @type {Array<{ type: string, subtype: string, q: number, i: number }>} */
31
+ const parts = [];
32
+
33
+ accept.split(',').forEach((str, i) => {
34
+ const match = /([^/]+)\/([^;]+)(?:;q=([0-9.]+))?/.exec(str);
35
+
36
+ // no match equals invalid header — ignore
37
+ if (match) {
38
+ const [, type, subtype, q = '1'] = match;
39
+ parts.push({ type, subtype, q: +q, i });
40
+ }
41
+ });
42
+
43
+ parts.sort((a, b) => {
44
+ if (a.q !== b.q) {
45
+ return b.q - a.q;
46
+ }
47
+
48
+ if ((a.subtype === '*') !== (b.subtype === '*')) {
49
+ return a.subtype === '*' ? 1 : -1;
50
+ }
51
+
52
+ if ((a.type === '*') !== (b.type === '*')) {
53
+ return a.type === '*' ? 1 : -1;
54
+ }
55
+
56
+ return a.i - b.i;
57
+ });
58
+
59
+ let accepted;
60
+ let min_priority = Infinity;
61
+
62
+ for (const mimetype of types) {
63
+ const [type, subtype] = mimetype.split('/');
64
+ const priority = parts.findIndex(
65
+ (part) =>
66
+ (part.type === type || part.type === '*') &&
67
+ (part.subtype === subtype || part.subtype === '*')
68
+ );
69
+
70
+ if (priority !== -1 && priority < min_priority) {
71
+ accepted = mimetype;
72
+ min_priority = priority;
73
+ }
74
+ }
75
+
76
+ return accepted;
77
+ }
78
+
79
+ /**
80
+ * Hash using djb2
81
+ * @param {import('types').StrictBody} value
82
+ */
83
+ function hash(value) {
84
+ let hash = 5381;
85
+ let i = value.length;
86
+
87
+ if (typeof value === 'string') {
88
+ while (i) hash = (hash * 33) ^ value.charCodeAt(--i);
89
+ } else {
90
+ while (i) hash = (hash * 33) ^ value[--i];
91
+ }
92
+
93
+ return (hash >>> 0).toString(36);
94
+ }
95
+
96
+ /** @param {Record<string, any>} obj */
97
+ function lowercase_keys(obj) {
98
+ /** @type {Record<string, any>} */
99
+ const clone = {};
100
+
101
+ for (const key in obj) {
102
+ clone[key.toLowerCase()] = obj[key];
103
+ }
104
+
105
+ return clone;
106
+ }
107
+
108
+ /** @param {any} body */
109
+ function is_pojo(body) {
110
+ if (typeof body !== 'object') return false;
111
+
112
+ if (body) {
113
+ if (body instanceof Uint8Array) return false;
114
+ if (body instanceof ReadableStream) return false;
115
+
116
+ // if body is a node Readable, throw an error
117
+ // TODO remove this for 1.0
118
+ if (body._readableState && typeof body.pipe === 'function') {
119
+ throw new Error('Node streams are no longer supported — use a ReadableStream instead');
120
+ }
121
+ }
122
+
123
+ return true;
124
+ }
125
+
126
+ /**
127
+ * Serialize an error into a JSON string, by copying its `name`, `message`
128
+ * and (in dev) `stack`, plus any custom properties, plus recursively
129
+ * serialized `cause` properties. This is necessary because
130
+ * `JSON.stringify(error) === '{}'`
131
+ * @param {Error} error
132
+ * @param {(error: Error) => string | undefined} get_stack
133
+ */
134
+ function serialize_error(error, get_stack) {
135
+ return JSON.stringify(clone_error(error, get_stack));
136
+ }
137
+
138
+ /**
139
+ * @param {Error} error
140
+ * @param {(error: Error) => string | undefined} get_stack
141
+ */
142
+ function clone_error(error, get_stack) {
143
+ const {
144
+ name,
145
+ message,
146
+ stack,
147
+ // @ts-expect-error i guess typescript doesn't know about error.cause yet
148
+ cause,
149
+ ...custom
150
+ } = error;
151
+
152
+ /** @type {Record<string, any>} */
153
+ const object = { name, message, stack: get_stack(error) };
154
+
155
+ if (cause) object.cause = clone_error(cause, get_stack);
156
+
157
+ for (const key in custom) {
158
+ // @ts-expect-error
159
+ object[key] = custom[key];
160
+ }
161
+
162
+ return object;
163
+ }
164
+
165
+ // TODO: Remove for 1.0
166
+ /** @param {Record<string, any>} mod */
167
+ function check_method_names(mod) {
168
+ ['get', 'post', 'put', 'patch', 'del'].forEach((m) => {
169
+ if (m in mod) {
170
+ const replacement = m === 'del' ? 'DELETE' : m.toUpperCase();
171
+ throw Error(
172
+ `Endpoint method "${m}" has changed to "${replacement}". See https://github.com/sveltejs/kit/discussions/5359 for more information.`
173
+ );
174
+ }
175
+ });
176
+ }
177
+
178
+ /** @type {import('types').SSRErrorPage} */
179
+ const GENERIC_ERROR = {
180
+ id: '__error'
181
+ };
182
+
183
+ /** @param {string} body */
184
+ function error(body) {
185
+ return new Response(body, {
186
+ status: 500
187
+ });
188
+ }
189
+
190
+ /** @param {unknown} s */
191
+ function is_string(s) {
192
+ return typeof s === 'string' || s instanceof String;
193
+ }
194
+
195
+ const text_types = new Set([
196
+ 'application/xml',
197
+ 'application/json',
198
+ 'application/x-www-form-urlencoded',
199
+ 'multipart/form-data'
200
+ ]);
201
+
202
+ const bodyless_status_codes = new Set([101, 204, 205, 304]);
203
+
204
+ /**
205
+ * Decides how the body should be parsed based on its mime type
206
+ *
207
+ * @param {string | undefined | null} content_type The `content-type` header of a request/response.
208
+ * @returns {boolean}
209
+ */
210
+ function is_text(content_type) {
211
+ if (!content_type) return true; // defaults to json
212
+ const type = content_type.split(';')[0].toLowerCase(); // get the mime type
213
+
214
+ return type.startsWith('text/') || type.endsWith('+xml') || text_types.has(type);
215
+ }
216
+
217
+ /**
218
+ * @param {import('types').RequestEvent} event
219
+ * @param {{ [method: string]: import('types').RequestHandler }} mod
220
+ * @param {import('types').SSROptions} options
221
+ * @returns {Promise<Response>}
222
+ */
223
+ async function render_endpoint(event, mod, options) {
224
+ const { method } = event.request;
225
+
226
+ check_method_names(mod);
227
+
228
+ /** @type {import('types').RequestHandler} */
229
+ let handler = mod[method];
230
+
231
+ if (!handler && method === 'HEAD') {
232
+ handler = mod.GET;
233
+ }
234
+
235
+ if (!handler) {
236
+ const allowed = [];
237
+
238
+ for (const method in ['GET', 'POST', 'PUT', 'PATCH', 'DELETE']) {
239
+ if (mod[method]) allowed.push(method);
240
+ }
241
+
242
+ if (mod.GET || mod.HEAD) allowed.push('HEAD');
243
+
244
+ return event.request.headers.get('x-sveltekit-load')
245
+ ? // TODO would be nice to avoid these requests altogether,
246
+ // by noting whether or not page endpoints export `get`
247
+ new Response(undefined, {
248
+ status: 204
249
+ })
250
+ : new Response(`${method} method not allowed`, {
251
+ status: 405,
252
+ headers: {
253
+ // https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/405
254
+ // "The server must generate an Allow header field in a 405 status code response"
255
+ allow: allowed.join(', ')
256
+ }
257
+ });
258
+ }
259
+
260
+ const response = await handler(event);
261
+ const preface = `Invalid response from route ${event.url.pathname}`;
262
+
263
+ if (typeof response !== 'object') {
264
+ return error(`${preface}: expected an object, got ${typeof response}`);
265
+ }
266
+
267
+ // TODO remove for 1.0
268
+ // @ts-expect-error
269
+ if (response.fallthrough) {
270
+ throw new Error(
271
+ 'fallthrough is no longer supported. Use matchers instead: https://kit.svelte.dev/docs/routing#advanced-routing-matching'
272
+ );
273
+ }
274
+
275
+ const { status = 200, body = {} } = response;
276
+ const headers =
277
+ response.headers instanceof Headers
278
+ ? new Headers(response.headers)
279
+ : to_headers(response.headers);
280
+
281
+ const type = headers.get('content-type');
282
+
283
+ if (
284
+ !is_text(type) &&
285
+ !(body instanceof Uint8Array || body instanceof ReadableStream || is_string(body))
286
+ ) {
287
+ return error(
288
+ `${preface}: body must be an instance of string, Uint8Array or ReadableStream if content-type is not a supported textual content-type`
289
+ );
290
+ }
291
+
292
+ /** @type {import('types').StrictBody} */
293
+ let normalized_body;
294
+
295
+ if (is_pojo(body) && (!type || type.startsWith('application/json'))) {
296
+ headers.set('content-type', 'application/json; charset=utf-8');
297
+ normalized_body =
298
+ body instanceof Error ? serialize_error(body, options.get_stack) : JSON.stringify(body);
299
+ } else {
300
+ normalized_body = /** @type {import('types').StrictBody} */ (body);
301
+ }
302
+
303
+ if (
304
+ (typeof normalized_body === 'string' || normalized_body instanceof Uint8Array) &&
305
+ !headers.has('etag')
306
+ ) {
307
+ const cache_control = headers.get('cache-control');
308
+ if (!cache_control || !/(no-store|immutable)/.test(cache_control)) {
309
+ headers.set('etag', `"${hash(normalized_body)}"`);
310
+ }
311
+ }
312
+
313
+ return new Response(
314
+ method !== 'HEAD' && !bodyless_status_codes.has(status) ? normalized_body : undefined,
315
+ {
316
+ status,
317
+ headers
318
+ }
319
+ );
320
+ }
321
+
322
+ var chars$1 = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_$';
323
+ var unsafeChars = /[<>\b\f\n\r\t\0\u2028\u2029]/g;
324
+ 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)$/;
325
+ var escaped = {
326
+ '<': '\\u003C',
327
+ '>': '\\u003E',
328
+ '/': '\\u002F',
329
+ '\\': '\\\\',
330
+ '\b': '\\b',
331
+ '\f': '\\f',
332
+ '\n': '\\n',
333
+ '\r': '\\r',
334
+ '\t': '\\t',
335
+ '\0': '\\0',
336
+ '\u2028': '\\u2028',
337
+ '\u2029': '\\u2029'
338
+ };
339
+ var objectProtoOwnPropertyNames = Object.getOwnPropertyNames(Object.prototype).sort().join('\0');
340
+ function devalue(value) {
341
+ var counts = new Map();
342
+ function walk(thing) {
343
+ if (typeof thing === 'function') {
344
+ throw new Error("Cannot stringify a function");
345
+ }
346
+ if (counts.has(thing)) {
347
+ counts.set(thing, counts.get(thing) + 1);
348
+ return;
349
+ }
350
+ counts.set(thing, 1);
351
+ if (!isPrimitive(thing)) {
352
+ var type = getType(thing);
353
+ switch (type) {
354
+ case 'Number':
355
+ case 'String':
356
+ case 'Boolean':
357
+ case 'Date':
358
+ case 'RegExp':
359
+ return;
360
+ case 'Array':
361
+ thing.forEach(walk);
362
+ break;
363
+ case 'Set':
364
+ case 'Map':
365
+ Array.from(thing).forEach(walk);
366
+ break;
367
+ default:
368
+ var proto = Object.getPrototypeOf(thing);
369
+ if (proto !== Object.prototype &&
370
+ proto !== null &&
371
+ Object.getOwnPropertyNames(proto).sort().join('\0') !== objectProtoOwnPropertyNames) {
372
+ throw new Error("Cannot stringify arbitrary non-POJOs");
373
+ }
374
+ if (Object.getOwnPropertySymbols(thing).length > 0) {
375
+ throw new Error("Cannot stringify POJOs with symbolic keys");
376
+ }
377
+ Object.keys(thing).forEach(function (key) { return walk(thing[key]); });
378
+ }
379
+ }
380
+ }
381
+ walk(value);
382
+ var names = new Map();
383
+ Array.from(counts)
384
+ .filter(function (entry) { return entry[1] > 1; })
385
+ .sort(function (a, b) { return b[1] - a[1]; })
386
+ .forEach(function (entry, i) {
387
+ names.set(entry[0], getName(i));
388
+ });
389
+ function stringify(thing) {
390
+ if (names.has(thing)) {
391
+ return names.get(thing);
392
+ }
393
+ if (isPrimitive(thing)) {
394
+ return stringifyPrimitive(thing);
395
+ }
396
+ var type = getType(thing);
397
+ switch (type) {
398
+ case 'Number':
399
+ case 'String':
400
+ case 'Boolean':
401
+ return "Object(" + stringify(thing.valueOf()) + ")";
402
+ case 'RegExp':
403
+ return "new RegExp(" + stringifyString(thing.source) + ", \"" + thing.flags + "\")";
404
+ case 'Date':
405
+ return "new Date(" + thing.getTime() + ")";
406
+ case 'Array':
407
+ var members = thing.map(function (v, i) { return i in thing ? stringify(v) : ''; });
408
+ var tail = thing.length === 0 || (thing.length - 1 in thing) ? '' : ',';
409
+ return "[" + members.join(',') + tail + "]";
410
+ case 'Set':
411
+ case 'Map':
412
+ return "new " + type + "([" + Array.from(thing).map(stringify).join(',') + "])";
413
+ default:
414
+ var obj = "{" + Object.keys(thing).map(function (key) { return safeKey(key) + ":" + stringify(thing[key]); }).join(',') + "}";
415
+ var proto = Object.getPrototypeOf(thing);
416
+ if (proto === null) {
417
+ return Object.keys(thing).length > 0
418
+ ? "Object.assign(Object.create(null)," + obj + ")"
419
+ : "Object.create(null)";
420
+ }
421
+ return obj;
422
+ }
423
+ }
424
+ var str = stringify(value);
425
+ if (names.size) {
426
+ var params_1 = [];
427
+ var statements_1 = [];
428
+ var values_1 = [];
429
+ names.forEach(function (name, thing) {
430
+ params_1.push(name);
431
+ if (isPrimitive(thing)) {
432
+ values_1.push(stringifyPrimitive(thing));
433
+ return;
434
+ }
435
+ var type = getType(thing);
436
+ switch (type) {
437
+ case 'Number':
438
+ case 'String':
439
+ case 'Boolean':
440
+ values_1.push("Object(" + stringify(thing.valueOf()) + ")");
441
+ break;
442
+ case 'RegExp':
443
+ values_1.push(thing.toString());
444
+ break;
445
+ case 'Date':
446
+ values_1.push("new Date(" + thing.getTime() + ")");
447
+ break;
448
+ case 'Array':
449
+ values_1.push("Array(" + thing.length + ")");
450
+ thing.forEach(function (v, i) {
451
+ statements_1.push(name + "[" + i + "]=" + stringify(v));
452
+ });
453
+ break;
454
+ case 'Set':
455
+ values_1.push("new Set");
456
+ statements_1.push(name + "." + Array.from(thing).map(function (v) { return "add(" + stringify(v) + ")"; }).join('.'));
457
+ break;
458
+ case 'Map':
459
+ values_1.push("new Map");
460
+ statements_1.push(name + "." + Array.from(thing).map(function (_a) {
461
+ var k = _a[0], v = _a[1];
462
+ return "set(" + stringify(k) + ", " + stringify(v) + ")";
463
+ }).join('.'));
464
+ break;
465
+ default:
466
+ values_1.push(Object.getPrototypeOf(thing) === null ? 'Object.create(null)' : '{}');
467
+ Object.keys(thing).forEach(function (key) {
468
+ statements_1.push("" + name + safeProp(key) + "=" + stringify(thing[key]));
469
+ });
470
+ }
471
+ });
472
+ statements_1.push("return " + str);
473
+ return "(function(" + params_1.join(',') + "){" + statements_1.join(';') + "}(" + values_1.join(',') + "))";
474
+ }
475
+ else {
476
+ return str;
477
+ }
478
+ }
479
+ function getName(num) {
480
+ var name = '';
481
+ do {
482
+ name = chars$1[num % chars$1.length] + name;
483
+ num = ~~(num / chars$1.length) - 1;
484
+ } while (num >= 0);
485
+ return reserved.test(name) ? name + "_" : name;
486
+ }
487
+ function isPrimitive(thing) {
488
+ return Object(thing) !== thing;
489
+ }
490
+ function stringifyPrimitive(thing) {
491
+ if (typeof thing === 'string')
492
+ return stringifyString(thing);
493
+ if (thing === void 0)
494
+ return 'void 0';
495
+ if (thing === 0 && 1 / thing < 0)
496
+ return '-0';
497
+ var str = String(thing);
498
+ if (typeof thing === 'number')
499
+ return str.replace(/^(-)?0\./, '$1.');
500
+ return str;
501
+ }
502
+ function getType(thing) {
503
+ return Object.prototype.toString.call(thing).slice(8, -1);
504
+ }
505
+ function escapeUnsafeChar(c) {
506
+ return escaped[c] || c;
507
+ }
508
+ function escapeUnsafeChars(str) {
509
+ return str.replace(unsafeChars, escapeUnsafeChar);
510
+ }
511
+ function safeKey(key) {
512
+ return /^[_$a-zA-Z][_$a-zA-Z0-9]*$/.test(key) ? key : escapeUnsafeChars(JSON.stringify(key));
513
+ }
514
+ function safeProp(key) {
515
+ return /^[_$a-zA-Z][_$a-zA-Z0-9]*$/.test(key) ? "." + key : "[" + escapeUnsafeChars(JSON.stringify(key)) + "]";
516
+ }
517
+ function stringifyString(str) {
518
+ var result = '"';
519
+ for (var i = 0; i < str.length; i += 1) {
520
+ var char = str.charAt(i);
521
+ var code = char.charCodeAt(0);
522
+ if (char === '"') {
523
+ result += '\\"';
524
+ }
525
+ else if (char in escaped) {
526
+ result += escaped[char];
527
+ }
528
+ else if (code >= 0xd800 && code <= 0xdfff) {
529
+ var next = str.charCodeAt(i + 1);
530
+ // If this is the beginning of a [high, low] surrogate pair,
531
+ // add the next two characters, otherwise escape
532
+ if (code <= 0xdbff && (next >= 0xdc00 && next <= 0xdfff)) {
533
+ result += char + str[++i];
534
+ }
535
+ else {
536
+ result += "\\u" + code.toString(16).toUpperCase();
537
+ }
538
+ }
539
+ else {
540
+ result += char;
541
+ }
542
+ }
543
+ result += '"';
544
+ return result;
545
+ }
546
+
547
+ function noop() { }
548
+ function safe_not_equal(a, b) {
549
+ return a != a ? b == b : a !== b || ((a && typeof a === 'object') || typeof a === 'function');
550
+ }
551
+ Promise.resolve();
552
+
553
+ const subscriber_queue = [];
554
+ /**
555
+ * Creates a `Readable` store that allows reading by subscription.
556
+ * @param value initial value
557
+ * @param {StartStopNotifier}start start and stop notifications for subscriptions
558
+ */
559
+ function readable(value, start) {
560
+ return {
561
+ subscribe: writable(value, start).subscribe
562
+ };
563
+ }
564
+ /**
565
+ * Create a `Writable` store that allows both updating and reading by subscription.
566
+ * @param {*=}value initial value
567
+ * @param {StartStopNotifier=}start start and stop notifications for subscriptions
568
+ */
569
+ function writable(value, start = noop) {
570
+ let stop;
571
+ const subscribers = new Set();
572
+ function set(new_value) {
573
+ if (safe_not_equal(value, new_value)) {
574
+ value = new_value;
575
+ if (stop) { // store is ready
576
+ const run_queue = !subscriber_queue.length;
577
+ for (const subscriber of subscribers) {
578
+ subscriber[1]();
579
+ subscriber_queue.push(subscriber, value);
580
+ }
581
+ if (run_queue) {
582
+ for (let i = 0; i < subscriber_queue.length; i += 2) {
583
+ subscriber_queue[i][0](subscriber_queue[i + 1]);
584
+ }
585
+ subscriber_queue.length = 0;
586
+ }
587
+ }
588
+ }
589
+ }
590
+ function update(fn) {
591
+ set(fn(value));
592
+ }
593
+ function subscribe(run, invalidate = noop) {
594
+ const subscriber = [run, invalidate];
595
+ subscribers.add(subscriber);
596
+ if (subscribers.size === 1) {
597
+ stop = start(set) || noop;
598
+ }
599
+ run(value);
600
+ return () => {
601
+ subscribers.delete(subscriber);
602
+ if (subscribers.size === 0) {
603
+ stop();
604
+ stop = null;
605
+ }
606
+ };
607
+ }
608
+ return { set, update, subscribe };
609
+ }
610
+
611
+ /**
612
+ * @param {unknown} err
613
+ * @return {Error}
614
+ */
615
+ function coalesce_to_error(err) {
616
+ return err instanceof Error ||
617
+ (err && /** @type {any} */ (err).name && /** @type {any} */ (err).message)
618
+ ? /** @type {Error} */ (err)
619
+ : new Error(JSON.stringify(err));
620
+ }
621
+
622
+ /**
623
+ * Inside a script element, only `</script` and `<!--` hold special meaning to the HTML parser.
624
+ *
625
+ * The first closes the script element, so everything after is treated as raw HTML.
626
+ * The second disables further parsing until `-->`, so the script element might be unexpectedly
627
+ * kept open until until an unrelated HTML comment in the page.
628
+ *
629
+ * U+2028 LINE SEPARATOR and U+2029 PARAGRAPH SEPARATOR are escaped for the sake of pre-2018
630
+ * browsers.
631
+ *
632
+ * @see tests for unsafe parsing examples.
633
+ * @see https://html.spec.whatwg.org/multipage/scripting.html#restrictions-for-contents-of-script-elements
634
+ * @see https://html.spec.whatwg.org/multipage/syntax.html#cdata-rcdata-restrictions
635
+ * @see https://html.spec.whatwg.org/multipage/parsing.html#script-data-state
636
+ * @see https://html.spec.whatwg.org/multipage/parsing.html#script-data-double-escaped-state
637
+ * @see https://github.com/tc39/proposal-json-superset
638
+ * @type {Record<string, string>}
639
+ */
640
+ const render_json_payload_script_dict = {
641
+ '<': '\\u003C',
642
+ '\u2028': '\\u2028',
643
+ '\u2029': '\\u2029'
644
+ };
645
+
646
+ const render_json_payload_script_regex = new RegExp(
647
+ `[${Object.keys(render_json_payload_script_dict).join('')}]`,
648
+ 'g'
649
+ );
650
+
651
+ /**
652
+ * Generates a raw HTML string containing a safe script element carrying JSON data and associated attributes.
653
+ *
654
+ * It escapes all the special characters needed to guarantee the element is unbroken, but care must
655
+ * be taken to ensure it is inserted in the document at an acceptable position for a script element,
656
+ * and that the resulting string isn't further modified.
657
+ *
658
+ * Attribute names must be type-checked so we don't need to escape them.
659
+ *
660
+ * @param {import('types').PayloadScriptAttributes} attrs A list of attributes to be added to the element.
661
+ * @param {import('types').JSONValue} payload The data to be carried by the element. Must be serializable to JSON.
662
+ * @returns {string} The raw HTML of a script element carrying the JSON payload.
663
+ * @example const html = render_json_payload_script({ type: 'data', url: '/data.json' }, { foo: 'bar' });
664
+ */
665
+ function render_json_payload_script(attrs, payload) {
666
+ const safe_payload = JSON.stringify(payload).replace(
667
+ render_json_payload_script_regex,
668
+ (match) => render_json_payload_script_dict[match]
669
+ );
670
+
671
+ let safe_attrs = '';
672
+ for (const [key, value] of Object.entries(attrs)) {
673
+ if (value === undefined) continue;
674
+ safe_attrs += ` sveltekit:data-${key}=${escape_html_attr(value)}`;
675
+ }
676
+
677
+ return `<script type="application/json"${safe_attrs}>${safe_payload}</script>`;
678
+ }
679
+
680
+ /**
681
+ * When inside a double-quoted attribute value, only `&` and `"` hold special meaning.
682
+ * @see https://html.spec.whatwg.org/multipage/parsing.html#attribute-value-(double-quoted)-state
683
+ * @type {Record<string, string>}
684
+ */
685
+ const escape_html_attr_dict = {
686
+ '&': '&amp;',
687
+ '"': '&quot;'
688
+ };
689
+
690
+ const escape_html_attr_regex = new RegExp(
691
+ // special characters
692
+ `[${Object.keys(escape_html_attr_dict).join('')}]|` +
693
+ // high surrogate without paired low surrogate
694
+ '[\\ud800-\\udbff](?![\\udc00-\\udfff])|' +
695
+ // a valid surrogate pair, the only match with 2 code units
696
+ // we match it so that we can match unpaired low surrogates in the same pass
697
+ // TODO: use lookbehind assertions once they are widely supported: (?<![\ud800-udbff])[\udc00-\udfff]
698
+ '[\\ud800-\\udbff][\\udc00-\\udfff]|' +
699
+ // unpaired low surrogate (see previous match)
700
+ '[\\udc00-\\udfff]',
701
+ 'g'
702
+ );
703
+
704
+ /**
705
+ * Formats a string to be used as an attribute's value in raw HTML.
706
+ *
707
+ * It escapes unpaired surrogates (which are allowed in js strings but invalid in HTML), escapes
708
+ * characters that are special in attributes, and surrounds the whole string in double-quotes.
709
+ *
710
+ * @param {string} str
711
+ * @returns {string} Escaped string surrounded by double-quotes.
712
+ * @example const html = `<tag data-value=${escape_html_attr('value')}>...</tag>`;
713
+ */
714
+ function escape_html_attr(str) {
715
+ const escaped_str = str.replace(escape_html_attr_regex, (match) => {
716
+ if (match.length === 2) {
717
+ // valid surrogate pair
718
+ return match;
719
+ }
720
+
721
+ return escape_html_attr_dict[match] ?? `&#${match.charCodeAt(0)};`;
722
+ });
723
+
724
+ return `"${escaped_str}"`;
725
+ }
726
+
727
+ const s = JSON.stringify;
728
+
729
+ const encoder = new TextEncoder();
730
+
731
+ /**
732
+ * SHA-256 hashing function adapted from https://bitwiseshiftleft.github.io/sjcl
733
+ * modified and redistributed under BSD license
734
+ * @param {string} data
735
+ */
736
+ function sha256(data) {
737
+ if (!key[0]) precompute();
738
+
739
+ const out = init.slice(0);
740
+ const array = encode$1(data);
741
+
742
+ for (let i = 0; i < array.length; i += 16) {
743
+ const w = array.subarray(i, i + 16);
744
+
745
+ let tmp;
746
+ let a;
747
+ let b;
748
+
749
+ let out0 = out[0];
750
+ let out1 = out[1];
751
+ let out2 = out[2];
752
+ let out3 = out[3];
753
+ let out4 = out[4];
754
+ let out5 = out[5];
755
+ let out6 = out[6];
756
+ let out7 = out[7];
757
+
758
+ /* Rationale for placement of |0 :
759
+ * If a value can overflow is original 32 bits by a factor of more than a few
760
+ * million (2^23 ish), there is a possibility that it might overflow the
761
+ * 53-bit mantissa and lose precision.
762
+ *
763
+ * To avoid this, we clamp back to 32 bits by |'ing with 0 on any value that
764
+ * propagates around the loop, and on the hash state out[]. I don't believe
765
+ * that the clamps on out4 and on out0 are strictly necessary, but it's close
766
+ * (for out4 anyway), and better safe than sorry.
767
+ *
768
+ * The clamps on out[] are necessary for the output to be correct even in the
769
+ * common case and for short inputs.
770
+ */
771
+
772
+ for (let i = 0; i < 64; i++) {
773
+ // load up the input word for this round
774
+
775
+ if (i < 16) {
776
+ tmp = w[i];
777
+ } else {
778
+ a = w[(i + 1) & 15];
779
+
780
+ b = w[(i + 14) & 15];
781
+
782
+ tmp = w[i & 15] =
783
+ (((a >>> 7) ^ (a >>> 18) ^ (a >>> 3) ^ (a << 25) ^ (a << 14)) +
784
+ ((b >>> 17) ^ (b >>> 19) ^ (b >>> 10) ^ (b << 15) ^ (b << 13)) +
785
+ w[i & 15] +
786
+ w[(i + 9) & 15]) |
787
+ 0;
788
+ }
789
+
790
+ tmp =
791
+ tmp +
792
+ out7 +
793
+ ((out4 >>> 6) ^ (out4 >>> 11) ^ (out4 >>> 25) ^ (out4 << 26) ^ (out4 << 21) ^ (out4 << 7)) +
794
+ (out6 ^ (out4 & (out5 ^ out6))) +
795
+ key[i]; // | 0;
796
+
797
+ // shift register
798
+ out7 = out6;
799
+ out6 = out5;
800
+ out5 = out4;
801
+
802
+ out4 = (out3 + tmp) | 0;
803
+
804
+ out3 = out2;
805
+ out2 = out1;
806
+ out1 = out0;
807
+
808
+ out0 =
809
+ (tmp +
810
+ ((out1 & out2) ^ (out3 & (out1 ^ out2))) +
811
+ ((out1 >>> 2) ^
812
+ (out1 >>> 13) ^
813
+ (out1 >>> 22) ^
814
+ (out1 << 30) ^
815
+ (out1 << 19) ^
816
+ (out1 << 10))) |
817
+ 0;
818
+ }
819
+
820
+ out[0] = (out[0] + out0) | 0;
821
+ out[1] = (out[1] + out1) | 0;
822
+ out[2] = (out[2] + out2) | 0;
823
+ out[3] = (out[3] + out3) | 0;
824
+ out[4] = (out[4] + out4) | 0;
825
+ out[5] = (out[5] + out5) | 0;
826
+ out[6] = (out[6] + out6) | 0;
827
+ out[7] = (out[7] + out7) | 0;
828
+ }
829
+
830
+ const bytes = new Uint8Array(out.buffer);
831
+ reverse_endianness(bytes);
832
+
833
+ return base64(bytes);
834
+ }
835
+
836
+ /** The SHA-256 initialization vector */
837
+ const init = new Uint32Array(8);
838
+
839
+ /** The SHA-256 hash key */
840
+ const key = new Uint32Array(64);
841
+
842
+ /** Function to precompute init and key. */
843
+ function precompute() {
844
+ /** @param {number} x */
845
+ function frac(x) {
846
+ return (x - Math.floor(x)) * 0x100000000;
847
+ }
848
+
849
+ let prime = 2;
850
+
851
+ for (let i = 0; i < 64; prime++) {
852
+ let is_prime = true;
853
+
854
+ for (let factor = 2; factor * factor <= prime; factor++) {
855
+ if (prime % factor === 0) {
856
+ is_prime = false;
857
+
858
+ break;
859
+ }
860
+ }
861
+
862
+ if (is_prime) {
863
+ if (i < 8) {
864
+ init[i] = frac(prime ** (1 / 2));
865
+ }
866
+
867
+ key[i] = frac(prime ** (1 / 3));
868
+
869
+ i++;
870
+ }
871
+ }
872
+ }
873
+
874
+ /** @param {Uint8Array} bytes */
875
+ function reverse_endianness(bytes) {
876
+ for (let i = 0; i < bytes.length; i += 4) {
877
+ const a = bytes[i + 0];
878
+ const b = bytes[i + 1];
879
+ const c = bytes[i + 2];
880
+ const d = bytes[i + 3];
881
+
882
+ bytes[i + 0] = d;
883
+ bytes[i + 1] = c;
884
+ bytes[i + 2] = b;
885
+ bytes[i + 3] = a;
886
+ }
887
+ }
888
+
889
+ /** @param {string} str */
890
+ function encode$1(str) {
891
+ const encoded = encoder.encode(str);
892
+ const length = encoded.length * 8;
893
+
894
+ // result should be a multiple of 512 bits in length,
895
+ // with room for a 1 (after the data) and two 32-bit
896
+ // words containing the original input bit length
897
+ const size = 512 * Math.ceil((length + 65) / 512);
898
+ const bytes = new Uint8Array(size / 8);
899
+ bytes.set(encoded);
900
+
901
+ // append a 1
902
+ bytes[encoded.length] = 0b10000000;
903
+
904
+ reverse_endianness(bytes);
905
+
906
+ // add the input bit length
907
+ const words = new Uint32Array(bytes.buffer);
908
+ words[words.length - 2] = Math.floor(length / 0x100000000); // this will always be zero for us
909
+ words[words.length - 1] = length;
910
+
911
+ return words;
912
+ }
913
+
914
+ /*
915
+ Based on https://gist.github.com/enepomnyaschih/72c423f727d395eeaa09697058238727
916
+
917
+ MIT License
918
+ Copyright (c) 2020 Egor Nepomnyaschih
919
+ Permission is hereby granted, free of charge, to any person obtaining a copy
920
+ of this software and associated documentation files (the "Software"), to deal
921
+ in the Software without restriction, including without limitation the rights
922
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
923
+ copies of the Software, and to permit persons to whom the Software is
924
+ furnished to do so, subject to the following conditions:
925
+ The above copyright notice and this permission notice shall be included in all
926
+ copies or substantial portions of the Software.
927
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
928
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
929
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
930
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
931
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
932
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
933
+ SOFTWARE.
934
+ */
935
+ const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'.split('');
936
+
937
+ /** @param {Uint8Array} bytes */
938
+ function base64(bytes) {
939
+ const l = bytes.length;
940
+
941
+ let result = '';
942
+ let i;
943
+
944
+ for (i = 2; i < l; i += 3) {
945
+ result += chars[bytes[i - 2] >> 2];
946
+ result += chars[((bytes[i - 2] & 0x03) << 4) | (bytes[i - 1] >> 4)];
947
+ result += chars[((bytes[i - 1] & 0x0f) << 2) | (bytes[i] >> 6)];
948
+ result += chars[bytes[i] & 0x3f];
949
+ }
950
+
951
+ if (i === l + 1) {
952
+ // 1 octet yet to write
953
+ result += chars[bytes[i - 2] >> 2];
954
+ result += chars[(bytes[i - 2] & 0x03) << 4];
955
+ result += '==';
956
+ }
957
+
958
+ if (i === l) {
959
+ // 2 octets yet to write
960
+ result += chars[bytes[i - 2] >> 2];
961
+ result += chars[((bytes[i - 2] & 0x03) << 4) | (bytes[i - 1] >> 4)];
962
+ result += chars[(bytes[i - 1] & 0x0f) << 2];
963
+ result += '=';
964
+ }
965
+
966
+ return result;
967
+ }
968
+
969
+ const array = new Uint8Array(16);
970
+
971
+ function generate_nonce() {
972
+ crypto.getRandomValues(array);
973
+ return base64(array);
974
+ }
975
+
976
+ const quoted = new Set([
977
+ 'self',
978
+ 'unsafe-eval',
979
+ 'unsafe-hashes',
980
+ 'unsafe-inline',
981
+ 'none',
982
+ 'strict-dynamic',
983
+ 'report-sample'
984
+ ]);
985
+
986
+ const crypto_pattern = /^(nonce|sha\d\d\d)-/;
987
+
988
+ // CSP and CSP Report Only are extremely similar with a few caveats
989
+ // the easiest/DRYest way to express this is with some private encapsulation
990
+ class BaseProvider {
991
+ /** @type {boolean} */
992
+ #use_hashes;
993
+
994
+ /** @type {boolean} */
995
+ #script_needs_csp;
996
+
997
+ /** @type {boolean} */
998
+ #style_needs_csp;
999
+
1000
+ /** @type {import('types').CspDirectives} */
1001
+ #directives;
1002
+
1003
+ /** @type {import('types').Csp.Source[]} */
1004
+ #script_src;
1005
+
1006
+ /** @type {import('types').Csp.Source[]} */
1007
+ #style_src;
1008
+
1009
+ /** @type {string} */
1010
+ #nonce;
1011
+
1012
+ /**
1013
+ * @param {boolean} use_hashes
1014
+ * @param {import('types').CspDirectives} directives
1015
+ * @param {string} nonce
1016
+ * @param {boolean} dev
1017
+ */
1018
+ constructor(use_hashes, directives, nonce, dev) {
1019
+ this.#use_hashes = use_hashes;
1020
+ this.#directives = dev ? { ...directives } : directives; // clone in dev so we can safely mutate
1021
+
1022
+ const d = this.#directives;
1023
+
1024
+ if (dev) {
1025
+ // remove strict-dynamic in dev...
1026
+ // TODO reinstate this if we can figure out how to make strict-dynamic work
1027
+ // if (d['default-src']) {
1028
+ // d['default-src'] = d['default-src'].filter((name) => name !== 'strict-dynamic');
1029
+ // if (d['default-src'].length === 0) delete d['default-src'];
1030
+ // }
1031
+
1032
+ // if (d['script-src']) {
1033
+ // d['script-src'] = d['script-src'].filter((name) => name !== 'strict-dynamic');
1034
+ // if (d['script-src'].length === 0) delete d['script-src'];
1035
+ // }
1036
+
1037
+ const effective_style_src = d['style-src'] || d['default-src'];
1038
+
1039
+ // ...and add unsafe-inline so we can inject <style> elements
1040
+ if (effective_style_src && !effective_style_src.includes('unsafe-inline')) {
1041
+ d['style-src'] = [...effective_style_src, 'unsafe-inline'];
1042
+ }
1043
+ }
1044
+
1045
+ this.#script_src = [];
1046
+ this.#style_src = [];
1047
+
1048
+ const effective_script_src = d['script-src'] || d['default-src'];
1049
+ const effective_style_src = d['style-src'] || d['default-src'];
1050
+
1051
+ this.#script_needs_csp =
1052
+ !!effective_script_src &&
1053
+ effective_script_src.filter((value) => value !== 'unsafe-inline').length > 0;
1054
+
1055
+ this.#style_needs_csp =
1056
+ !dev &&
1057
+ !!effective_style_src &&
1058
+ effective_style_src.filter((value) => value !== 'unsafe-inline').length > 0;
1059
+
1060
+ this.script_needs_nonce = this.#script_needs_csp && !this.#use_hashes;
1061
+ this.style_needs_nonce = this.#style_needs_csp && !this.#use_hashes;
1062
+ this.#nonce = nonce;
1063
+ }
1064
+
1065
+ /** @param {string} content */
1066
+ add_script(content) {
1067
+ if (this.#script_needs_csp) {
1068
+ if (this.#use_hashes) {
1069
+ this.#script_src.push(`sha256-${sha256(content)}`);
1070
+ } else if (this.#script_src.length === 0) {
1071
+ this.#script_src.push(`nonce-${this.#nonce}`);
1072
+ }
1073
+ }
1074
+ }
1075
+
1076
+ /** @param {string} content */
1077
+ add_style(content) {
1078
+ if (this.#style_needs_csp) {
1079
+ if (this.#use_hashes) {
1080
+ this.#style_src.push(`sha256-${sha256(content)}`);
1081
+ } else if (this.#style_src.length === 0) {
1082
+ this.#style_src.push(`nonce-${this.#nonce}`);
1083
+ }
1084
+ }
1085
+ }
1086
+
1087
+ /**
1088
+ * @param {boolean} [is_meta]
1089
+ */
1090
+ get_header(is_meta = false) {
1091
+ const header = [];
1092
+
1093
+ // due to browser inconsistencies, we can't append sources to default-src
1094
+ // (specifically, Firefox appears to not ignore nonce-{nonce} directives
1095
+ // on default-src), so we ensure that script-src and style-src exist
1096
+
1097
+ const directives = { ...this.#directives };
1098
+
1099
+ if (this.#style_src.length > 0) {
1100
+ directives['style-src'] = [
1101
+ ...(directives['style-src'] || directives['default-src'] || []),
1102
+ ...this.#style_src
1103
+ ];
1104
+ }
1105
+
1106
+ if (this.#script_src.length > 0) {
1107
+ directives['script-src'] = [
1108
+ ...(directives['script-src'] || directives['default-src'] || []),
1109
+ ...this.#script_src
1110
+ ];
1111
+ }
1112
+
1113
+ for (const key in directives) {
1114
+ if (is_meta && (key === 'frame-ancestors' || key === 'report-uri' || key === 'sandbox')) {
1115
+ // these values cannot be used with a <meta> tag
1116
+ // TODO warn?
1117
+ continue;
1118
+ }
1119
+
1120
+ // @ts-expect-error gimme a break typescript, `key` is obviously a member of internal_directives
1121
+ const value = /** @type {string[] | true} */ (directives[key]);
1122
+
1123
+ if (!value) continue;
1124
+
1125
+ const directive = [key];
1126
+ if (Array.isArray(value)) {
1127
+ value.forEach((value) => {
1128
+ if (quoted.has(value) || crypto_pattern.test(value)) {
1129
+ directive.push(`'${value}'`);
1130
+ } else {
1131
+ directive.push(value);
1132
+ }
1133
+ });
1134
+ }
1135
+
1136
+ header.push(directive.join(' '));
1137
+ }
1138
+
1139
+ return header.join('; ');
1140
+ }
1141
+ }
1142
+
1143
+ class CspProvider extends BaseProvider {
1144
+ get_meta() {
1145
+ const content = escape_html_attr(this.get_header(true));
1146
+ return `<meta http-equiv="content-security-policy" content=${content}>`;
1147
+ }
1148
+ }
1149
+
1150
+ class CspReportOnlyProvider extends BaseProvider {
1151
+ /**
1152
+ * @param {boolean} use_hashes
1153
+ * @param {import('types').CspDirectives} directives
1154
+ * @param {string} nonce
1155
+ * @param {boolean} dev
1156
+ */
1157
+ constructor(use_hashes, directives, nonce, dev) {
1158
+ super(use_hashes, directives, nonce, dev);
1159
+
1160
+ if (Object.values(directives).filter((v) => !!v).length > 0) {
1161
+ // If we're generating content-security-policy-report-only,
1162
+ // if there are any directives, we need a report-uri or report-to (or both)
1163
+ // else it's just an expensive noop.
1164
+ const has_report_to = directives['report-to']?.length ?? 0 > 0;
1165
+ const has_report_uri = directives['report-uri']?.length ?? 0 > 0;
1166
+ if (!has_report_to && !has_report_uri) {
1167
+ throw Error(
1168
+ '`content-security-policy-report-only` must be specified with either the `report-to` or `report-uri` directives, or both'
1169
+ );
1170
+ }
1171
+ }
1172
+ }
1173
+ }
1174
+
1175
+ class Csp {
1176
+ /** @readonly */
1177
+ nonce = generate_nonce();
1178
+
1179
+ /** @type {CspProvider} */
1180
+ csp_provider;
1181
+
1182
+ /** @type {CspReportOnlyProvider} */
1183
+ report_only_provider;
1184
+
1185
+ /**
1186
+ * @param {import('./types').CspConfig} config
1187
+ * @param {import('./types').CspOpts} opts
1188
+ */
1189
+ constructor({ mode, directives, reportOnly }, { prerender, dev }) {
1190
+ const use_hashes = mode === 'hash' || (mode === 'auto' && prerender);
1191
+ this.csp_provider = new CspProvider(use_hashes, directives, this.nonce, dev);
1192
+ this.report_only_provider = new CspReportOnlyProvider(use_hashes, reportOnly, this.nonce, dev);
1193
+ }
1194
+
1195
+ get script_needs_nonce() {
1196
+ return this.csp_provider.script_needs_nonce || this.report_only_provider.script_needs_nonce;
1197
+ }
1198
+
1199
+ get style_needs_nonce() {
1200
+ return this.csp_provider.style_needs_nonce || this.report_only_provider.style_needs_nonce;
1201
+ }
1202
+
1203
+ /** @param {string} content */
1204
+ add_script(content) {
1205
+ this.csp_provider.add_script(content);
1206
+ this.report_only_provider.add_script(content);
1207
+ }
1208
+
1209
+ /** @param {string} content */
1210
+ add_style(content) {
1211
+ this.csp_provider.add_style(content);
1212
+ this.report_only_provider.add_style(content);
1213
+ }
1214
+ }
1215
+
1216
+ const absolute = /^([a-z]+:)?\/?\//;
1217
+ const scheme = /^[a-z]+:/;
1218
+
1219
+ /**
1220
+ * @param {string} base
1221
+ * @param {string} path
1222
+ */
1223
+ function resolve(base, path) {
1224
+ if (scheme.test(path)) return path;
1225
+
1226
+ const base_match = absolute.exec(base);
1227
+ const path_match = absolute.exec(path);
1228
+
1229
+ if (!base_match) {
1230
+ throw new Error(`bad base path: "${base}"`);
1231
+ }
1232
+
1233
+ const baseparts = path_match ? [] : base.slice(base_match[0].length).split('/');
1234
+ const pathparts = path_match ? path.slice(path_match[0].length).split('/') : path.split('/');
1235
+
1236
+ baseparts.pop();
1237
+
1238
+ for (let i = 0; i < pathparts.length; i += 1) {
1239
+ const part = pathparts[i];
1240
+ if (part === '.') continue;
1241
+ else if (part === '..') baseparts.pop();
1242
+ else baseparts.push(part);
1243
+ }
1244
+
1245
+ const prefix = (path_match && path_match[0]) || (base_match && base_match[0]) || '';
1246
+
1247
+ return `${prefix}${baseparts.join('/')}`;
1248
+ }
1249
+
1250
+ /** @param {string} path */
1251
+ function is_root_relative(path) {
1252
+ return path[0] === '/' && path[1] !== '/';
1253
+ }
1254
+
1255
+ /**
1256
+ * @param {string} path
1257
+ * @param {import('types').TrailingSlash} trailing_slash
1258
+ */
1259
+ function normalize_path(path, trailing_slash) {
1260
+ if (path === '/' || trailing_slash === 'ignore') return path;
1261
+
1262
+ if (trailing_slash === 'never') {
1263
+ return path.endsWith('/') ? path.slice(0, -1) : path;
1264
+ } else if (trailing_slash === 'always' && !path.endsWith('/')) {
1265
+ return path + '/';
1266
+ }
1267
+
1268
+ return path;
1269
+ }
1270
+
1271
+ /** @param {Record<string, string>} params */
1272
+ function decode_params(params) {
1273
+ for (const key in params) {
1274
+ // input has already been decoded by decodeURI
1275
+ // now handle the rest that decodeURIComponent would do
1276
+ params[key] = params[key]
1277
+ .replace(/%23/g, '#')
1278
+ .replace(/%3[Bb]/g, ';')
1279
+ .replace(/%2[Cc]/g, ',')
1280
+ .replace(/%2[Ff]/g, '/')
1281
+ .replace(/%3[Ff]/g, '?')
1282
+ .replace(/%3[Aa]/g, ':')
1283
+ .replace(/%40/g, '@')
1284
+ .replace(/%26/g, '&')
1285
+ .replace(/%3[Dd]/g, '=')
1286
+ .replace(/%2[Bb]/g, '+')
1287
+ .replace(/%24/g, '$');
1288
+ }
1289
+
1290
+ return params;
1291
+ }
1292
+
1293
+ class LoadURL extends URL {
1294
+ /** @returns {string} */
1295
+ get hash() {
1296
+ throw new Error(
1297
+ 'url.hash is inaccessible from load. Consider accessing hash from the page store within the script tag of your component.'
1298
+ );
1299
+ }
1300
+ }
1301
+
1302
+ class PrerenderingURL extends URL {
1303
+ /** @returns {string} */
1304
+ get search() {
1305
+ throw new Error('Cannot access url.search on a page with prerendering enabled');
1306
+ }
1307
+
1308
+ /** @returns {URLSearchParams} */
1309
+ get searchParams() {
1310
+ throw new Error('Cannot access url.searchParams on a page with prerendering enabled');
1311
+ }
1312
+ }
1313
+
1314
+ // TODO rename this function/module
1315
+
1316
+ const updated = {
1317
+ ...readable(false),
1318
+ check: () => false
1319
+ };
1320
+
1321
+ /**
1322
+ * Creates the HTML response.
1323
+ * @param {{
1324
+ * branch: Array<import('./types').Loaded>;
1325
+ * options: import('types').SSROptions;
1326
+ * state: import('types').SSRState;
1327
+ * $session: any;
1328
+ * page_config: { hydrate: boolean, router: boolean };
1329
+ * status: number;
1330
+ * error: Error | null;
1331
+ * event: import('types').RequestEvent;
1332
+ * resolve_opts: import('types').RequiredResolveOptions;
1333
+ * stuff: Record<string, any>;
1334
+ * }} opts
1335
+ */
1336
+ async function render_response({
1337
+ branch,
1338
+ options,
1339
+ state,
1340
+ $session,
1341
+ page_config,
1342
+ status,
1343
+ error = null,
1344
+ event,
1345
+ resolve_opts,
1346
+ stuff
1347
+ }) {
1348
+ if (state.prerendering) {
1349
+ if (options.csp.mode === 'nonce') {
1350
+ throw new Error('Cannot use prerendering if config.kit.csp.mode === "nonce"');
1351
+ }
1352
+
1353
+ if (options.template_contains_nonce) {
1354
+ throw new Error('Cannot use prerendering if page template contains %sveltekit.nonce%');
1355
+ }
1356
+ }
1357
+
1358
+ const { entry } = options.manifest._;
1359
+
1360
+ const stylesheets = new Set(entry.stylesheets);
1361
+ const modulepreloads = new Set(entry.imports);
1362
+
1363
+ /** @type {Map<string, string>} */
1364
+ // TODO if we add a client entry point one day, we will need to include inline_styles with the entry, otherwise stylesheets will be linked even if they are below inlineStyleThreshold
1365
+ const inline_styles = new Map();
1366
+
1367
+ /** @type {Array<import('./types').Fetched>} */
1368
+ const serialized_data = [];
1369
+
1370
+ let shadow_props;
1371
+
1372
+ let rendered;
1373
+
1374
+ let is_private = false;
1375
+ /** @type {import('types').NormalizedLoadOutputCache | undefined} */
1376
+ let cache;
1377
+
1378
+ const stack = error?.stack;
1379
+
1380
+ if (options.dev && error) {
1381
+ error.stack = options.get_stack(error);
1382
+ }
1383
+
1384
+ if (resolve_opts.ssr) {
1385
+ const leaf = /** @type {import('./types.js').Loaded} */ (branch.at(-1));
1386
+
1387
+ if (leaf.loaded.status) {
1388
+ // explicit status returned from `load` or a page endpoint trumps
1389
+ // initial status
1390
+ status = leaf.loaded.status;
1391
+ }
1392
+
1393
+ for (const { node, props, loaded, fetched, uses_credentials } of branch) {
1394
+ if (node.imports) {
1395
+ node.imports.forEach((url) => modulepreloads.add(url));
1396
+ }
1397
+
1398
+ if (node.stylesheets) {
1399
+ node.stylesheets.forEach((url) => stylesheets.add(url));
1400
+ }
1401
+
1402
+ if (node.inline_styles) {
1403
+ Object.entries(await node.inline_styles()).forEach(([k, v]) => inline_styles.set(k, v));
1404
+ }
1405
+
1406
+ // TODO probably better if `fetched` wasn't populated unless `hydrate`
1407
+ if (fetched && page_config.hydrate) serialized_data.push(...fetched);
1408
+ if (props) shadow_props = props;
1409
+
1410
+ cache = loaded?.cache;
1411
+ is_private = cache?.private ?? uses_credentials;
1412
+ }
1413
+
1414
+ const session = writable($session);
1415
+ // Even if $session isn't accessed, it still ends up serialized in the rendered HTML
1416
+ is_private = is_private || (cache?.private ?? (!!$session && Object.keys($session).length > 0));
1417
+
1418
+ /** @type {Record<string, any>} */
1419
+ const props = {
1420
+ stores: {
1421
+ page: writable(null),
1422
+ navigating: writable(null),
1423
+ session,
1424
+ updated
1425
+ },
1426
+ /** @type {import('types').Page} */
1427
+ page: {
1428
+ error,
1429
+ params: event.params,
1430
+ routeId: event.routeId,
1431
+ status,
1432
+ stuff,
1433
+ url: state.prerendering ? new PrerenderingURL(event.url) : event.url
1434
+ },
1435
+ components: branch.map(({ node }) => node.module.default)
1436
+ };
1437
+
1438
+ // TODO remove this for 1.0
1439
+ /**
1440
+ * @param {string} property
1441
+ * @param {string} replacement
1442
+ */
1443
+ const print_error = (property, replacement) => {
1444
+ Object.defineProperty(props.page, property, {
1445
+ get: () => {
1446
+ throw new Error(`$page.${property} has been replaced by $page.url.${replacement}`);
1447
+ }
1448
+ });
1449
+ };
1450
+
1451
+ print_error('origin', 'origin');
1452
+ print_error('path', 'pathname');
1453
+ print_error('query', 'searchParams');
1454
+
1455
+ // props_n (instead of props[n]) makes it easy to avoid
1456
+ // unnecessary updates for layout components
1457
+ for (let i = 0; i < branch.length; i += 1) {
1458
+ props[`props_${i}`] = await branch[i].loaded.props;
1459
+ }
1460
+
1461
+ rendered = options.root.render(props);
1462
+ } else {
1463
+ rendered = { head: '', html: '', css: { code: '', map: null } };
1464
+ }
1465
+
1466
+ let { head, html: body } = rendered;
1467
+
1468
+ const csp = new Csp(options.csp, {
1469
+ dev: options.dev,
1470
+ prerender: !!state.prerendering
1471
+ });
1472
+
1473
+ const target = hash(body);
1474
+
1475
+ // prettier-ignore
1476
+ const init_app = `
1477
+ import { start } from ${s(options.prefix + entry.file)};
1478
+ start({
1479
+ target: document.querySelector('[data-sveltekit-hydrate="${target}"]').parentNode,
1480
+ paths: ${s(options.paths)},
1481
+ session: ${try_serialize($session, (error) => {
1482
+ throw new Error(`Failed to serialize session data: ${error.message}`);
1483
+ })},
1484
+ route: ${!!page_config.router},
1485
+ spa: ${!resolve_opts.ssr},
1486
+ trailing_slash: ${s(options.trailing_slash)},
1487
+ hydrate: ${resolve_opts.ssr && page_config.hydrate ? `{
1488
+ status: ${status},
1489
+ error: ${error && serialize_error(error, e => e.stack)},
1490
+ nodes: [${branch.map(({ node }) => node.index).join(', ')}],
1491
+ params: ${devalue(event.params)},
1492
+ routeId: ${s(event.routeId)}
1493
+ }` : 'null'}
1494
+ });
1495
+ `;
1496
+
1497
+ // we use an anonymous function instead of an arrow function to support
1498
+ // older browsers (https://github.com/sveltejs/kit/pull/5417)
1499
+ const init_service_worker = `
1500
+ if ('serviceWorker' in navigator) {
1501
+ addEventListener('load', function () {
1502
+ navigator.serviceWorker.register('${options.service_worker}');
1503
+ });
1504
+ }
1505
+ `;
1506
+
1507
+ if (inline_styles.size > 0) {
1508
+ const content = Array.from(inline_styles.values()).join('\n');
1509
+
1510
+ const attributes = [];
1511
+ if (options.dev) attributes.push(' data-sveltekit');
1512
+ if (csp.style_needs_nonce) attributes.push(` nonce="${csp.nonce}"`);
1513
+
1514
+ csp.add_style(content);
1515
+
1516
+ head += `\n\t<style${attributes.join('')}>${content}</style>`;
1517
+ }
1518
+
1519
+ // prettier-ignore
1520
+ head += Array.from(stylesheets)
1521
+ .map((dep) => {
1522
+ const attributes = [
1523
+ 'rel="stylesheet"',
1524
+ `href="${options.prefix + dep}"`
1525
+ ];
1526
+
1527
+ if (csp.style_needs_nonce) {
1528
+ attributes.push(`nonce="${csp.nonce}"`);
1529
+ }
1530
+
1531
+ if (inline_styles.has(dep)) {
1532
+ // don't load stylesheets that are already inlined
1533
+ // include them in disabled state so that Vite can detect them and doesn't try to add them
1534
+ attributes.push('disabled', 'media="(max-width: 0)"');
1535
+ }
1536
+
1537
+ return `\n\t<link ${attributes.join(' ')}>`;
1538
+ })
1539
+ .join('');
1540
+
1541
+ if (page_config.router || page_config.hydrate) {
1542
+ head += Array.from(modulepreloads)
1543
+ .map((dep) => `\n\t<link rel="modulepreload" href="${options.prefix + dep}">`)
1544
+ .join('');
1545
+
1546
+ const attributes = ['type="module"', `data-sveltekit-hydrate="${target}"`];
1547
+
1548
+ csp.add_script(init_app);
1549
+
1550
+ if (csp.script_needs_nonce) {
1551
+ attributes.push(`nonce="${csp.nonce}"`);
1552
+ }
1553
+
1554
+ body += `\n\t\t<script ${attributes.join(' ')}>${init_app}</script>`;
1555
+
1556
+ body += serialized_data
1557
+ .map(({ url, body, response }) =>
1558
+ render_json_payload_script(
1559
+ { type: 'data', url, body: typeof body === 'string' ? hash(body) : undefined },
1560
+ response
1561
+ )
1562
+ )
1563
+ .join('\n\t');
1564
+
1565
+ if (shadow_props) {
1566
+ body += render_json_payload_script({ type: 'props' }, shadow_props);
1567
+ }
1568
+ }
1569
+
1570
+ if (options.service_worker) {
1571
+ // always include service worker unless it's turned off explicitly
1572
+ csp.add_script(init_service_worker);
1573
+
1574
+ head += `
1575
+ <script${csp.script_needs_nonce ? ` nonce="${csp.nonce}"` : ''}>${init_service_worker}</script>`;
1576
+ }
1577
+
1578
+ if (state.prerendering) {
1579
+ const http_equiv = [];
1580
+
1581
+ const csp_headers = csp.csp_provider.get_meta();
1582
+ if (csp_headers) {
1583
+ http_equiv.push(csp_headers);
1584
+ }
1585
+
1586
+ if (cache) {
1587
+ http_equiv.push(`<meta http-equiv="cache-control" content="max-age=${cache.maxage}">`);
1588
+ }
1589
+
1590
+ if (http_equiv.length > 0) {
1591
+ head = http_equiv.join('\n') + head;
1592
+ }
1593
+ }
1594
+
1595
+ const segments = event.url.pathname.slice(options.paths.base.length).split('/').slice(2);
1596
+ const assets =
1597
+ options.paths.assets || (segments.length > 0 ? segments.map(() => '..').join('/') : '.');
1598
+
1599
+ const html = await resolve_opts.transformPage({
1600
+ html: options.template({ head, body, assets, nonce: /** @type {string} */ (csp.nonce) })
1601
+ });
1602
+
1603
+ const headers = new Headers({
1604
+ 'content-type': 'text/html',
1605
+ etag: `"${hash(html)}"`
1606
+ });
1607
+
1608
+ if (cache) {
1609
+ headers.set('cache-control', `${is_private ? 'private' : 'public'}, max-age=${cache.maxage}`);
1610
+ }
1611
+
1612
+ if (!state.prerendering) {
1613
+ const csp_header = csp.csp_provider.get_header();
1614
+ if (csp_header) {
1615
+ headers.set('content-security-policy', csp_header);
1616
+ }
1617
+ const report_only_header = csp.report_only_provider.get_header();
1618
+ if (report_only_header) {
1619
+ headers.set('content-security-policy-report-only', report_only_header);
1620
+ }
1621
+ }
1622
+
1623
+ if (options.dev && error) {
1624
+ // reset stack, otherwise it may be 'fixed' a second time
1625
+ error.stack = stack;
1626
+ }
1627
+
1628
+ return new Response(html, {
1629
+ status,
1630
+ headers
1631
+ });
1632
+ }
1633
+
1634
+ /**
1635
+ * @param {any} data
1636
+ * @param {(error: Error) => void} [fail]
1637
+ */
1638
+ function try_serialize(data, fail) {
1639
+ try {
1640
+ return devalue(data);
1641
+ } catch (err) {
1642
+ if (fail) fail(coalesce_to_error(err));
1643
+ return null;
1644
+ }
1645
+ }
1646
+
1647
+ /*!
1648
+ * cookie
1649
+ * Copyright(c) 2012-2014 Roman Shtylman
1650
+ * Copyright(c) 2015 Douglas Christopher Wilson
1651
+ * MIT Licensed
1652
+ */
1653
+
1654
+ /**
1655
+ * Module exports.
1656
+ * @public
1657
+ */
1658
+
1659
+ var parse_1 = parse$1;
1660
+ var serialize_1 = serialize;
1661
+
1662
+ /**
1663
+ * Module variables.
1664
+ * @private
1665
+ */
1666
+
1667
+ var __toString = Object.prototype.toString;
1668
+
1669
+ /**
1670
+ * RegExp to match field-content in RFC 7230 sec 3.2
1671
+ *
1672
+ * field-content = field-vchar [ 1*( SP / HTAB ) field-vchar ]
1673
+ * field-vchar = VCHAR / obs-text
1674
+ * obs-text = %x80-FF
1675
+ */
1676
+
1677
+ var fieldContentRegExp = /^[\u0009\u0020-\u007e\u0080-\u00ff]+$/;
1678
+
1679
+ /**
1680
+ * Parse a cookie header.
1681
+ *
1682
+ * Parse the given cookie header string into an object
1683
+ * The object has the various cookies as keys(names) => values
1684
+ *
1685
+ * @param {string} str
1686
+ * @param {object} [options]
1687
+ * @return {object}
1688
+ * @public
1689
+ */
1690
+
1691
+ function parse$1(str, options) {
1692
+ if (typeof str !== 'string') {
1693
+ throw new TypeError('argument str must be a string');
1694
+ }
1695
+
1696
+ var obj = {};
1697
+ var opt = options || {};
1698
+ var dec = opt.decode || decode;
1699
+
1700
+ var index = 0;
1701
+ while (index < str.length) {
1702
+ var eqIdx = str.indexOf('=', index);
1703
+
1704
+ // no more cookie pairs
1705
+ if (eqIdx === -1) {
1706
+ break
1707
+ }
1708
+
1709
+ var endIdx = str.indexOf(';', index);
1710
+
1711
+ if (endIdx === -1) {
1712
+ endIdx = str.length;
1713
+ } else if (endIdx < eqIdx) {
1714
+ // backtrack on prior semicolon
1715
+ index = str.lastIndexOf(';', eqIdx - 1) + 1;
1716
+ continue
1717
+ }
1718
+
1719
+ var key = str.slice(index, eqIdx).trim();
1720
+
1721
+ // only assign once
1722
+ if (undefined === obj[key]) {
1723
+ var val = str.slice(eqIdx + 1, endIdx).trim();
1724
+
1725
+ // quoted values
1726
+ if (val.charCodeAt(0) === 0x22) {
1727
+ val = val.slice(1, -1);
1728
+ }
1729
+
1730
+ obj[key] = tryDecode(val, dec);
1731
+ }
1732
+
1733
+ index = endIdx + 1;
1734
+ }
1735
+
1736
+ return obj;
1737
+ }
1738
+
1739
+ /**
1740
+ * Serialize data into a cookie header.
1741
+ *
1742
+ * Serialize the a name value pair into a cookie string suitable for
1743
+ * http headers. An optional options object specified cookie parameters.
1744
+ *
1745
+ * serialize('foo', 'bar', { httpOnly: true })
1746
+ * => "foo=bar; httpOnly"
1747
+ *
1748
+ * @param {string} name
1749
+ * @param {string} val
1750
+ * @param {object} [options]
1751
+ * @return {string}
1752
+ * @public
1753
+ */
1754
+
1755
+ function serialize(name, val, options) {
1756
+ var opt = options || {};
1757
+ var enc = opt.encode || encode;
1758
+
1759
+ if (typeof enc !== 'function') {
1760
+ throw new TypeError('option encode is invalid');
1761
+ }
1762
+
1763
+ if (!fieldContentRegExp.test(name)) {
1764
+ throw new TypeError('argument name is invalid');
1765
+ }
1766
+
1767
+ var value = enc(val);
1768
+
1769
+ if (value && !fieldContentRegExp.test(value)) {
1770
+ throw new TypeError('argument val is invalid');
1771
+ }
1772
+
1773
+ var str = name + '=' + value;
1774
+
1775
+ if (null != opt.maxAge) {
1776
+ var maxAge = opt.maxAge - 0;
1777
+
1778
+ if (isNaN(maxAge) || !isFinite(maxAge)) {
1779
+ throw new TypeError('option maxAge is invalid')
1780
+ }
1781
+
1782
+ str += '; Max-Age=' + Math.floor(maxAge);
1783
+ }
1784
+
1785
+ if (opt.domain) {
1786
+ if (!fieldContentRegExp.test(opt.domain)) {
1787
+ throw new TypeError('option domain is invalid');
1788
+ }
1789
+
1790
+ str += '; Domain=' + opt.domain;
1791
+ }
1792
+
1793
+ if (opt.path) {
1794
+ if (!fieldContentRegExp.test(opt.path)) {
1795
+ throw new TypeError('option path is invalid');
1796
+ }
1797
+
1798
+ str += '; Path=' + opt.path;
1799
+ }
1800
+
1801
+ if (opt.expires) {
1802
+ var expires = opt.expires;
1803
+
1804
+ if (!isDate(expires) || isNaN(expires.valueOf())) {
1805
+ throw new TypeError('option expires is invalid');
1806
+ }
1807
+
1808
+ str += '; Expires=' + expires.toUTCString();
1809
+ }
1810
+
1811
+ if (opt.httpOnly) {
1812
+ str += '; HttpOnly';
1813
+ }
1814
+
1815
+ if (opt.secure) {
1816
+ str += '; Secure';
1817
+ }
1818
+
1819
+ if (opt.priority) {
1820
+ var priority = typeof opt.priority === 'string'
1821
+ ? opt.priority.toLowerCase()
1822
+ : opt.priority;
1823
+
1824
+ switch (priority) {
1825
+ case 'low':
1826
+ str += '; Priority=Low';
1827
+ break
1828
+ case 'medium':
1829
+ str += '; Priority=Medium';
1830
+ break
1831
+ case 'high':
1832
+ str += '; Priority=High';
1833
+ break
1834
+ default:
1835
+ throw new TypeError('option priority is invalid')
1836
+ }
1837
+ }
1838
+
1839
+ if (opt.sameSite) {
1840
+ var sameSite = typeof opt.sameSite === 'string'
1841
+ ? opt.sameSite.toLowerCase() : opt.sameSite;
1842
+
1843
+ switch (sameSite) {
1844
+ case true:
1845
+ str += '; SameSite=Strict';
1846
+ break;
1847
+ case 'lax':
1848
+ str += '; SameSite=Lax';
1849
+ break;
1850
+ case 'strict':
1851
+ str += '; SameSite=Strict';
1852
+ break;
1853
+ case 'none':
1854
+ str += '; SameSite=None';
1855
+ break;
1856
+ default:
1857
+ throw new TypeError('option sameSite is invalid');
1858
+ }
1859
+ }
1860
+
1861
+ return str;
1862
+ }
1863
+
1864
+ /**
1865
+ * URL-decode string value. Optimized to skip native call when no %.
1866
+ *
1867
+ * @param {string} str
1868
+ * @returns {string}
1869
+ */
1870
+
1871
+ function decode (str) {
1872
+ return str.indexOf('%') !== -1
1873
+ ? decodeURIComponent(str)
1874
+ : str
1875
+ }
1876
+
1877
+ /**
1878
+ * URL-encode value.
1879
+ *
1880
+ * @param {string} str
1881
+ * @returns {string}
1882
+ */
1883
+
1884
+ function encode (val) {
1885
+ return encodeURIComponent(val)
1886
+ }
1887
+
1888
+ /**
1889
+ * Determine if value is a Date.
1890
+ *
1891
+ * @param {*} val
1892
+ * @private
1893
+ */
1894
+
1895
+ function isDate (val) {
1896
+ return __toString.call(val) === '[object Date]' ||
1897
+ val instanceof Date
1898
+ }
1899
+
1900
+ /**
1901
+ * Try decoding a string using a decoding function.
1902
+ *
1903
+ * @param {string} str
1904
+ * @param {function} decode
1905
+ * @private
1906
+ */
1907
+
1908
+ function tryDecode(str, decode) {
1909
+ try {
1910
+ return decode(str);
1911
+ } catch (e) {
1912
+ return str;
1913
+ }
1914
+ }
1915
+
1916
+ var setCookie = {exports: {}};
1917
+
1918
+ var defaultParseOptions = {
1919
+ decodeValues: true,
1920
+ map: false,
1921
+ silent: false,
1922
+ };
1923
+
1924
+ function isNonEmptyString(str) {
1925
+ return typeof str === "string" && !!str.trim();
1926
+ }
1927
+
1928
+ function parseString(setCookieValue, options) {
1929
+ var parts = setCookieValue.split(";").filter(isNonEmptyString);
1930
+ var nameValue = parts.shift().split("=");
1931
+ var name = nameValue.shift();
1932
+ var value = nameValue.join("="); // everything after the first =, joined by a "=" if there was more than one part
1933
+
1934
+ options = options
1935
+ ? Object.assign({}, defaultParseOptions, options)
1936
+ : defaultParseOptions;
1937
+
1938
+ try {
1939
+ value = options.decodeValues ? decodeURIComponent(value) : value; // decode cookie value
1940
+ } catch (e) {
1941
+ console.error(
1942
+ "set-cookie-parser encountered an error while decoding a cookie with value '" +
1943
+ value +
1944
+ "'. Set options.decodeValues to false to disable this feature.",
1945
+ e
1946
+ );
1947
+ }
1948
+
1949
+ var cookie = {
1950
+ name: name, // grab everything before the first =
1951
+ value: value,
1952
+ };
1953
+
1954
+ parts.forEach(function (part) {
1955
+ var sides = part.split("=");
1956
+ var key = sides.shift().trimLeft().toLowerCase();
1957
+ var value = sides.join("=");
1958
+ if (key === "expires") {
1959
+ cookie.expires = new Date(value);
1960
+ } else if (key === "max-age") {
1961
+ cookie.maxAge = parseInt(value, 10);
1962
+ } else if (key === "secure") {
1963
+ cookie.secure = true;
1964
+ } else if (key === "httponly") {
1965
+ cookie.httpOnly = true;
1966
+ } else if (key === "samesite") {
1967
+ cookie.sameSite = value;
1968
+ } else {
1969
+ cookie[key] = value;
1970
+ }
1971
+ });
1972
+
1973
+ return cookie;
1974
+ }
1975
+
1976
+ function parse(input, options) {
1977
+ options = options
1978
+ ? Object.assign({}, defaultParseOptions, options)
1979
+ : defaultParseOptions;
1980
+
1981
+ if (!input) {
1982
+ if (!options.map) {
1983
+ return [];
1984
+ } else {
1985
+ return {};
1986
+ }
1987
+ }
1988
+
1989
+ if (input.headers && input.headers["set-cookie"]) {
1990
+ // fast-path for node.js (which automatically normalizes header names to lower-case
1991
+ input = input.headers["set-cookie"];
1992
+ } else if (input.headers) {
1993
+ // slow-path for other environments - see #25
1994
+ var sch =
1995
+ input.headers[
1996
+ Object.keys(input.headers).find(function (key) {
1997
+ return key.toLowerCase() === "set-cookie";
1998
+ })
1999
+ ];
2000
+ // warn if called on a request-like object with a cookie header rather than a set-cookie header - see #34, 36
2001
+ if (!sch && input.headers.cookie && !options.silent) {
2002
+ console.warn(
2003
+ "Warning: set-cookie-parser appears to have been called on a request object. It is designed to parse Set-Cookie headers from responses, not Cookie headers from requests. Set the option {silent: true} to suppress this warning."
2004
+ );
2005
+ }
2006
+ input = sch;
2007
+ }
2008
+ if (!Array.isArray(input)) {
2009
+ input = [input];
2010
+ }
2011
+
2012
+ options = options
2013
+ ? Object.assign({}, defaultParseOptions, options)
2014
+ : defaultParseOptions;
2015
+
2016
+ if (!options.map) {
2017
+ return input.filter(isNonEmptyString).map(function (str) {
2018
+ return parseString(str, options);
2019
+ });
2020
+ } else {
2021
+ var cookies = {};
2022
+ return input.filter(isNonEmptyString).reduce(function (cookies, str) {
2023
+ var cookie = parseString(str, options);
2024
+ cookies[cookie.name] = cookie;
2025
+ return cookies;
2026
+ }, cookies);
2027
+ }
2028
+ }
2029
+
2030
+ /*
2031
+ Set-Cookie header field-values are sometimes comma joined in one string. This splits them without choking on commas
2032
+ that are within a single set-cookie field-value, such as in the Expires portion.
2033
+
2034
+ This is uncommon, but explicitly allowed - see https://tools.ietf.org/html/rfc2616#section-4.2
2035
+ Node.js does this for every header *except* set-cookie - see https://github.com/nodejs/node/blob/d5e363b77ebaf1caf67cd7528224b651c86815c1/lib/_http_incoming.js#L128
2036
+ React Native's fetch does this for *every* header, including set-cookie.
2037
+
2038
+ Based on: https://github.com/google/j2objc/commit/16820fdbc8f76ca0c33472810ce0cb03d20efe25
2039
+ Credits to: https://github.com/tomball for original and https://github.com/chrusart for JavaScript implementation
2040
+ */
2041
+ function splitCookiesString(cookiesString) {
2042
+ if (Array.isArray(cookiesString)) {
2043
+ return cookiesString;
2044
+ }
2045
+ if (typeof cookiesString !== "string") {
2046
+ return [];
2047
+ }
2048
+
2049
+ var cookiesStrings = [];
2050
+ var pos = 0;
2051
+ var start;
2052
+ var ch;
2053
+ var lastComma;
2054
+ var nextStart;
2055
+ var cookiesSeparatorFound;
2056
+
2057
+ function skipWhitespace() {
2058
+ while (pos < cookiesString.length && /\s/.test(cookiesString.charAt(pos))) {
2059
+ pos += 1;
2060
+ }
2061
+ return pos < cookiesString.length;
2062
+ }
2063
+
2064
+ function notSpecialChar() {
2065
+ ch = cookiesString.charAt(pos);
2066
+
2067
+ return ch !== "=" && ch !== ";" && ch !== ",";
2068
+ }
2069
+
2070
+ while (pos < cookiesString.length) {
2071
+ start = pos;
2072
+ cookiesSeparatorFound = false;
2073
+
2074
+ while (skipWhitespace()) {
2075
+ ch = cookiesString.charAt(pos);
2076
+ if (ch === ",") {
2077
+ // ',' is a cookie separator if we have later first '=', not ';' or ','
2078
+ lastComma = pos;
2079
+ pos += 1;
2080
+
2081
+ skipWhitespace();
2082
+ nextStart = pos;
2083
+
2084
+ while (pos < cookiesString.length && notSpecialChar()) {
2085
+ pos += 1;
2086
+ }
2087
+
2088
+ // currently special character
2089
+ if (pos < cookiesString.length && cookiesString.charAt(pos) === "=") {
2090
+ // we found cookies separator
2091
+ cookiesSeparatorFound = true;
2092
+ // pos is inside the next cookie, so back up and return it.
2093
+ pos = nextStart;
2094
+ cookiesStrings.push(cookiesString.substring(start, lastComma));
2095
+ start = pos;
2096
+ } else {
2097
+ // in param ',' or param separator ';',
2098
+ // we continue from that comma
2099
+ pos = lastComma + 1;
2100
+ }
2101
+ } else {
2102
+ pos += 1;
2103
+ }
2104
+ }
2105
+
2106
+ if (!cookiesSeparatorFound || pos >= cookiesString.length) {
2107
+ cookiesStrings.push(cookiesString.substring(start, cookiesString.length));
2108
+ }
2109
+ }
2110
+
2111
+ return cookiesStrings;
2112
+ }
2113
+
2114
+ setCookie.exports = parse;
2115
+ setCookie.exports.parse = parse;
2116
+ var parseString_1 = setCookie.exports.parseString = parseString;
2117
+ var splitCookiesString_1 = setCookie.exports.splitCookiesString = splitCookiesString;
2118
+
2119
+ /**
2120
+ * @param {import('types').LoadOutput | void} loaded
2121
+ * @returns {import('types').NormalizedLoadOutput}
2122
+ */
2123
+ function normalize(loaded) {
2124
+ if (!loaded) {
2125
+ return {};
2126
+ }
2127
+
2128
+ // TODO remove for 1.0
2129
+ // @ts-expect-error
2130
+ if (loaded.fallthrough) {
2131
+ throw new Error(
2132
+ 'fallthrough is no longer supported. Use matchers instead: https://kit.svelte.dev/docs/routing#advanced-routing-matching'
2133
+ );
2134
+ }
2135
+
2136
+ // TODO remove for 1.0
2137
+ if ('maxage' in loaded) {
2138
+ throw new Error('maxage should be replaced with cache: { maxage }');
2139
+ }
2140
+
2141
+ const has_error_status =
2142
+ loaded.status && loaded.status >= 400 && loaded.status <= 599 && !loaded.redirect;
2143
+ if (loaded.error || has_error_status) {
2144
+ const status = loaded.status;
2145
+
2146
+ if (!loaded.error && has_error_status) {
2147
+ return {
2148
+ status: status || 500,
2149
+ error: new Error(`${status}`)
2150
+ };
2151
+ }
2152
+
2153
+ const error = typeof loaded.error === 'string' ? new Error(loaded.error) : loaded.error;
2154
+
2155
+ if (!(error instanceof Error)) {
2156
+ return {
2157
+ status: 500,
2158
+ error: new Error(
2159
+ `"error" property returned from load() must be a string or instance of Error, received type "${typeof error}"`
2160
+ )
2161
+ };
2162
+ }
2163
+
2164
+ if (!status || status < 400 || status > 599) {
2165
+ console.warn('"error" returned from load() without a valid status code — defaulting to 500');
2166
+ return { status: 500, error };
2167
+ }
2168
+
2169
+ return { status, error };
2170
+ }
2171
+
2172
+ if (loaded.redirect) {
2173
+ if (!loaded.status || Math.floor(loaded.status / 100) !== 3) {
2174
+ throw new Error(
2175
+ '"redirect" property returned from load() must be accompanied by a 3xx status code'
2176
+ );
2177
+ }
2178
+
2179
+ if (typeof loaded.redirect !== 'string') {
2180
+ throw new Error('"redirect" property returned from load() must be a string');
2181
+ }
2182
+ }
2183
+
2184
+ if (loaded.dependencies) {
2185
+ if (
2186
+ !Array.isArray(loaded.dependencies) ||
2187
+ loaded.dependencies.some((dep) => typeof dep !== 'string')
2188
+ ) {
2189
+ throw new Error('"dependencies" property returned from load() must be of type string[]');
2190
+ }
2191
+ }
2192
+
2193
+ // TODO remove before 1.0
2194
+ if (/** @type {any} */ (loaded).context) {
2195
+ throw new Error(
2196
+ 'You are returning "context" from a load function. ' +
2197
+ '"context" was renamed to "stuff", please adjust your code accordingly.'
2198
+ );
2199
+ }
2200
+
2201
+ return /** @type {import('types').NormalizedLoadOutput} */ (loaded);
2202
+ }
2203
+
2204
+ /**
2205
+ * @param {string} hostname
2206
+ * @param {string} [constraint]
2207
+ */
2208
+ function domain_matches(hostname, constraint) {
2209
+ if (!constraint) return true;
2210
+
2211
+ const normalized = constraint[0] === '.' ? constraint.slice(1) : constraint;
2212
+
2213
+ if (hostname === normalized) return true;
2214
+ return hostname.endsWith('.' + normalized);
2215
+ }
2216
+
2217
+ /**
2218
+ * @param {string} path
2219
+ * @param {string} [constraint]
2220
+ */
2221
+ function path_matches(path, constraint) {
2222
+ if (!constraint) return true;
2223
+
2224
+ const normalized = constraint.endsWith('/') ? constraint.slice(0, -1) : constraint;
2225
+
2226
+ if (path === normalized) return true;
2227
+ return path.startsWith(normalized + '/');
2228
+ }
2229
+
2230
+ /**
2231
+ * Calls the user's `load` function.
2232
+ * @param {{
2233
+ * event: import('types').RequestEvent;
2234
+ * options: import('types').SSROptions;
2235
+ * state: import('types').SSRState;
2236
+ * route: import('types').SSRPage | import('types').SSRErrorPage;
2237
+ * node: import('types').SSRNode;
2238
+ * $session: any;
2239
+ * stuff: Record<string, any>;
2240
+ * is_error: boolean;
2241
+ * is_leaf: boolean;
2242
+ * status?: number;
2243
+ * error?: Error;
2244
+ * }} opts
2245
+ * @returns {Promise<import('./types').Loaded>}
2246
+ */
2247
+ async function load_node({
2248
+ event,
2249
+ options,
2250
+ state,
2251
+ route,
2252
+ node,
2253
+ $session,
2254
+ stuff,
2255
+ is_error,
2256
+ is_leaf,
2257
+ status,
2258
+ error
2259
+ }) {
2260
+ const { module } = node;
2261
+
2262
+ let uses_credentials = false;
2263
+
2264
+ /** @type {Array<import('./types').Fetched>} */
2265
+ const fetched = [];
2266
+
2267
+ const cookies = parse_1(event.request.headers.get('cookie') || '');
2268
+
2269
+ /** @type {import('set-cookie-parser').Cookie[]} */
2270
+ const new_cookies = [];
2271
+
2272
+ /** @type {import('types').NormalizedLoadOutput} */
2273
+ let loaded;
2274
+
2275
+ const should_prerender = node.module.prerender ?? options.prerender.default;
2276
+
2277
+ /** @type {import('types').ShadowData} */
2278
+ const shadow = is_leaf
2279
+ ? await load_shadow_data(
2280
+ /** @type {import('types').SSRPage} */ (route),
2281
+ event,
2282
+ options,
2283
+ should_prerender
2284
+ )
2285
+ : {};
2286
+
2287
+ if (shadow.cookies) {
2288
+ shadow.cookies.forEach((header) => {
2289
+ new_cookies.push(parseString_1(header));
2290
+ });
2291
+ }
2292
+
2293
+ if (shadow.error) {
2294
+ loaded = {
2295
+ error: shadow.error
2296
+ };
2297
+ } else if (shadow.redirect) {
2298
+ loaded = {
2299
+ redirect: shadow.redirect
2300
+ };
2301
+ } else if (module.load) {
2302
+ /** @type {import('types').LoadEvent} */
2303
+ const load_input = {
2304
+ url: state.prerendering ? new PrerenderingURL(event.url) : new LoadURL(event.url),
2305
+ params: event.params,
2306
+ props: shadow.body || {},
2307
+ routeId: event.routeId,
2308
+ get session() {
2309
+ if (node.module.prerender ?? options.prerender.default) {
2310
+ throw Error(
2311
+ 'Attempted to access session from a prerendered page. Session would never be populated.'
2312
+ );
2313
+ }
2314
+ uses_credentials = true;
2315
+ return $session;
2316
+ },
2317
+ /**
2318
+ * @param {RequestInfo} resource
2319
+ * @param {RequestInit} opts
2320
+ */
2321
+ fetch: async (resource, opts = {}) => {
2322
+ /** @type {string} */
2323
+ let requested;
2324
+
2325
+ if (typeof resource === 'string') {
2326
+ requested = resource;
2327
+ } else {
2328
+ requested = resource.url;
2329
+
2330
+ opts = {
2331
+ method: resource.method,
2332
+ headers: resource.headers,
2333
+ body: resource.body,
2334
+ mode: resource.mode,
2335
+ credentials: resource.credentials,
2336
+ cache: resource.cache,
2337
+ redirect: resource.redirect,
2338
+ referrer: resource.referrer,
2339
+ integrity: resource.integrity,
2340
+ ...opts
2341
+ };
2342
+ }
2343
+
2344
+ opts.headers = new Headers(opts.headers);
2345
+
2346
+ // merge headers from request
2347
+ for (const [key, value] of event.request.headers) {
2348
+ if (
2349
+ key !== 'authorization' &&
2350
+ key !== 'connection' &&
2351
+ key !== 'cookie' &&
2352
+ key !== 'host' &&
2353
+ key !== 'if-none-match' &&
2354
+ !opts.headers.has(key)
2355
+ ) {
2356
+ opts.headers.set(key, value);
2357
+ }
2358
+ }
2359
+
2360
+ const resolved = resolve(event.url.pathname, requested.split('?')[0]);
2361
+
2362
+ /** @type {Response} */
2363
+ let response;
2364
+
2365
+ /** @type {import('types').PrerenderDependency} */
2366
+ let dependency;
2367
+
2368
+ // handle fetch requests for static assets. e.g. prebaked data, etc.
2369
+ // we need to support everything the browser's fetch supports
2370
+ const prefix = options.paths.assets || options.paths.base;
2371
+ const filename = decodeURIComponent(
2372
+ resolved.startsWith(prefix) ? resolved.slice(prefix.length) : resolved
2373
+ ).slice(1);
2374
+ const filename_html = `${filename}/index.html`; // path may also match path/index.html
2375
+
2376
+ const is_asset = options.manifest.assets.has(filename);
2377
+ const is_asset_html = options.manifest.assets.has(filename_html);
2378
+
2379
+ if (is_asset || is_asset_html) {
2380
+ const file = is_asset ? filename : filename_html;
2381
+
2382
+ if (options.read) {
2383
+ const type = is_asset
2384
+ ? options.manifest.mimeTypes[filename.slice(filename.lastIndexOf('.'))]
2385
+ : 'text/html';
2386
+
2387
+ response = new Response(options.read(file), {
2388
+ headers: type ? { 'content-type': type } : {}
2389
+ });
2390
+ } else {
2391
+ response = await fetch(
2392
+ `${event.url.origin}/${file}`,
2393
+ /** @type {RequestInit} */ (opts)
2394
+ );
2395
+ }
2396
+ } else if (is_root_relative(resolved)) {
2397
+ if (opts.credentials !== 'omit') {
2398
+ uses_credentials = true;
2399
+
2400
+ const authorization = event.request.headers.get('authorization');
2401
+
2402
+ // combine cookies from the initiating request with any that were
2403
+ // added via set-cookie
2404
+ const combined_cookies = { ...cookies };
2405
+
2406
+ for (const cookie of new_cookies) {
2407
+ if (!domain_matches(event.url.hostname, cookie.domain)) continue;
2408
+ if (!path_matches(resolved, cookie.path)) continue;
2409
+
2410
+ combined_cookies[cookie.name] = cookie.value;
2411
+ }
2412
+
2413
+ const cookie = Object.entries(combined_cookies)
2414
+ .map(([name, value]) => `${name}=${value}`)
2415
+ .join('; ');
2416
+
2417
+ if (cookie) {
2418
+ opts.headers.set('cookie', cookie);
2419
+ }
2420
+
2421
+ if (authorization && !opts.headers.has('authorization')) {
2422
+ opts.headers.set('authorization', authorization);
2423
+ }
2424
+ }
2425
+
2426
+ if (opts.body && typeof opts.body !== 'string') {
2427
+ // per https://developer.mozilla.org/en-US/docs/Web/API/Request/Request, this can be a
2428
+ // Blob, BufferSource, FormData, URLSearchParams, USVString, or ReadableStream object.
2429
+ // non-string bodies are irksome to deal with, but luckily aren't particularly useful
2430
+ // in this context anyway, so we take the easy route and ban them
2431
+ throw new Error('Request body must be a string');
2432
+ }
2433
+
2434
+ response = await respond(
2435
+ new Request(new URL(requested, event.url).href, { ...opts }),
2436
+ options,
2437
+ {
2438
+ ...state,
2439
+ initiator: route
2440
+ }
2441
+ );
2442
+
2443
+ if (state.prerendering) {
2444
+ dependency = { response, body: null };
2445
+ state.prerendering.dependencies.set(resolved, dependency);
2446
+ }
2447
+ } else {
2448
+ // external
2449
+ if (resolved.startsWith('//')) {
2450
+ requested = event.url.protocol + requested;
2451
+ }
2452
+
2453
+ // external fetch
2454
+ // allow cookie passthrough for "same-origin"
2455
+ // if SvelteKit is serving my.domain.com:
2456
+ // - domain.com WILL NOT receive cookies
2457
+ // - my.domain.com WILL receive cookies
2458
+ // - api.domain.dom WILL NOT receive cookies
2459
+ // - sub.my.domain.com WILL receive cookies
2460
+ // ports do not affect the resolution
2461
+ // leading dot prevents mydomain.com matching domain.com
2462
+ if (
2463
+ `.${new URL(requested).hostname}`.endsWith(`.${event.url.hostname}`) &&
2464
+ opts.credentials !== 'omit'
2465
+ ) {
2466
+ uses_credentials = true;
2467
+
2468
+ const cookie = event.request.headers.get('cookie');
2469
+ if (cookie) opts.headers.set('cookie', cookie);
2470
+ }
2471
+
2472
+ // we need to delete the connection header, as explained here:
2473
+ // https://github.com/nodejs/undici/issues/1470#issuecomment-1140798467
2474
+ // TODO this may be a case for being selective about which headers we let through
2475
+ opts.headers.delete('connection');
2476
+
2477
+ const external_request = new Request(requested, /** @type {RequestInit} */ (opts));
2478
+ response = await options.hooks.externalFetch.call(null, external_request);
2479
+ }
2480
+
2481
+ const set_cookie = response.headers.get('set-cookie');
2482
+ if (set_cookie) {
2483
+ new_cookies.push(
2484
+ ...splitCookiesString_1(set_cookie)
2485
+ .map((str) => parseString_1(str))
2486
+ );
2487
+ }
2488
+
2489
+ const proxy = new Proxy(response, {
2490
+ get(response, key, _receiver) {
2491
+ async function text() {
2492
+ const body = await response.text();
2493
+
2494
+ /** @type {import('types').ResponseHeaders} */
2495
+ const headers = {};
2496
+ for (const [key, value] of response.headers) {
2497
+ // TODO skip others besides set-cookie and etag?
2498
+ if (key !== 'set-cookie' && key !== 'etag') {
2499
+ headers[key] = value;
2500
+ }
2501
+ }
2502
+
2503
+ if (!opts.body || typeof opts.body === 'string') {
2504
+ const status_number = Number(response.status);
2505
+ if (isNaN(status_number)) {
2506
+ throw new Error(
2507
+ `response.status is not a number. value: "${
2508
+ response.status
2509
+ }" type: ${typeof response.status}`
2510
+ );
2511
+ }
2512
+
2513
+ fetched.push({
2514
+ url: requested,
2515
+ body: opts.body,
2516
+ response: {
2517
+ status: status_number,
2518
+ statusText: response.statusText,
2519
+ headers,
2520
+ body
2521
+ }
2522
+ });
2523
+ }
2524
+
2525
+ if (dependency) {
2526
+ dependency.body = body;
2527
+ }
2528
+
2529
+ return body;
2530
+ }
2531
+
2532
+ if (key === 'arrayBuffer') {
2533
+ return async () => {
2534
+ const buffer = await response.arrayBuffer();
2535
+
2536
+ if (dependency) {
2537
+ dependency.body = new Uint8Array(buffer);
2538
+ }
2539
+
2540
+ // TODO should buffer be inlined into the page (albeit base64'd)?
2541
+ // any conditions in which it shouldn't be?
2542
+
2543
+ return buffer;
2544
+ };
2545
+ }
2546
+
2547
+ if (key === 'text') {
2548
+ return text;
2549
+ }
2550
+
2551
+ if (key === 'json') {
2552
+ return async () => {
2553
+ return JSON.parse(await text());
2554
+ };
2555
+ }
2556
+
2557
+ // TODO arrayBuffer?
2558
+
2559
+ return Reflect.get(response, key, response);
2560
+ }
2561
+ });
2562
+
2563
+ return proxy;
2564
+ },
2565
+ stuff: { ...stuff },
2566
+ status: (is_error ? status : shadow.status) ?? null,
2567
+ error: is_error ? error ?? null : null
2568
+ };
2569
+
2570
+ if (options.dev) {
2571
+ // TODO remove this for 1.0
2572
+ Object.defineProperty(load_input, 'page', {
2573
+ get: () => {
2574
+ throw new Error('`page` in `load` functions has been replaced by `url` and `params`');
2575
+ }
2576
+ });
2577
+ }
2578
+
2579
+ loaded = normalize(await module.load.call(null, load_input));
2580
+ } else if (shadow.body) {
2581
+ loaded = {
2582
+ props: shadow.body
2583
+ };
2584
+ } else {
2585
+ loaded = {};
2586
+ }
2587
+
2588
+ loaded.status = loaded.status ?? shadow.status;
2589
+
2590
+ // generate __data.json files when prerendering
2591
+ if (shadow.body && state.prerendering) {
2592
+ const pathname = `${event.url.pathname.replace(/\/$/, '')}/__data.json`;
2593
+
2594
+ const dependency = {
2595
+ response: new Response(undefined),
2596
+ body: JSON.stringify(shadow.body)
2597
+ };
2598
+
2599
+ state.prerendering.dependencies.set(pathname, dependency);
2600
+ }
2601
+
2602
+ return {
2603
+ node,
2604
+ props: shadow.body,
2605
+ loaded,
2606
+ stuff: loaded.stuff || stuff,
2607
+ fetched,
2608
+ set_cookie_headers: new_cookies.map((new_cookie) => {
2609
+ const { name, value, ...options } = new_cookie;
2610
+ // @ts-expect-error
2611
+ return serialize_1(name, value, options);
2612
+ }),
2613
+ uses_credentials
2614
+ };
2615
+ }
2616
+
2617
+ /**
2618
+ *
2619
+ * @param {import('types').SSRPage} route
2620
+ * @param {import('types').RequestEvent} event
2621
+ * @param {import('types').SSROptions} options
2622
+ * @param {boolean} prerender
2623
+ * @returns {Promise<import('types').ShadowData>}
2624
+ */
2625
+ async function load_shadow_data(route, event, options, prerender) {
2626
+ if (!route.shadow) return {};
2627
+
2628
+ try {
2629
+ const mod = await route.shadow();
2630
+
2631
+ check_method_names(mod);
2632
+
2633
+ if (prerender && (mod.POST || mod.PUT || mod.DELETE || mod.PATCH)) {
2634
+ throw new Error('Cannot prerender pages that have endpoints with mutative methods');
2635
+ }
2636
+
2637
+ const { method } = event.request;
2638
+ const is_get = method === 'HEAD' || method === 'GET';
2639
+ const handler = method === 'HEAD' ? mod.HEAD || mod.GET : mod[method];
2640
+
2641
+ if (!handler && !is_get) {
2642
+ return {
2643
+ status: 405,
2644
+ error: new Error(`${method} method not allowed`)
2645
+ };
2646
+ }
2647
+
2648
+ /** @type {import('types').ShadowData} */
2649
+ const data = {
2650
+ status: undefined,
2651
+ cookies: [],
2652
+ body: {}
2653
+ };
2654
+
2655
+ if (!is_get) {
2656
+ const { status, headers, body } = validate_shadow_output(await handler(event));
2657
+ add_cookies(/** @type {string[]} */ (data.cookies), headers);
2658
+ data.status = status;
2659
+
2660
+ // explicit errors cause an error page...
2661
+ if (body instanceof Error) {
2662
+ if (status < 400) {
2663
+ data.status = 500;
2664
+ data.error = new Error('A non-error status code was returned with an error body');
2665
+ } else {
2666
+ data.error = body;
2667
+ }
2668
+
2669
+ return data;
2670
+ }
2671
+
2672
+ // ...redirects are respected...
2673
+ if (status >= 300 && status < 400) {
2674
+ data.redirect = /** @type {string} */ (
2675
+ headers instanceof Headers ? headers.get('location') : headers.location
2676
+ );
2677
+ return data;
2678
+ }
2679
+
2680
+ // ...but 4xx and 5xx status codes _don't_ result in the error page
2681
+ // rendering for non-GET requests — instead, we allow the page
2682
+ // to render with any validation errors etc that were returned
2683
+ data.body = body;
2684
+ }
2685
+
2686
+ const get = (method === 'HEAD' && mod.HEAD) || mod.GET;
2687
+ if (get) {
2688
+ const { status, headers, body } = validate_shadow_output(await get(event));
2689
+ add_cookies(/** @type {string[]} */ (data.cookies), headers);
2690
+
2691
+ if (body instanceof Error) {
2692
+ if (status < 400) {
2693
+ data.status = 500;
2694
+ data.error = new Error('A non-error status code was returned with an error body');
2695
+ } else {
2696
+ data.status = status;
2697
+ data.error = body;
2698
+ }
2699
+
2700
+ return data;
2701
+ }
2702
+
2703
+ if (status >= 400) {
2704
+ data.status = status;
2705
+ data.error = new Error('Failed to load data');
2706
+ return data;
2707
+ }
2708
+
2709
+ if (status >= 300) {
2710
+ data.status = status;
2711
+ data.redirect = /** @type {string} */ (
2712
+ headers instanceof Headers ? headers.get('location') : headers.location
2713
+ );
2714
+ return data;
2715
+ }
2716
+
2717
+ data.body = { ...body, ...data.body };
2718
+ }
2719
+
2720
+ return data;
2721
+ } catch (e) {
2722
+ const error = coalesce_to_error(e);
2723
+ options.handle_error(error, event);
2724
+
2725
+ return {
2726
+ status: 500,
2727
+ error
2728
+ };
2729
+ }
2730
+ }
2731
+
2732
+ /**
2733
+ * @param {string[]} target
2734
+ * @param {Partial<import('types').ResponseHeaders>} headers
2735
+ */
2736
+ function add_cookies(target, headers) {
2737
+ const cookies = headers['set-cookie'];
2738
+ if (cookies) {
2739
+ if (Array.isArray(cookies)) {
2740
+ target.push(...cookies);
2741
+ } else {
2742
+ target.push(/** @type {string} */ (cookies));
2743
+ }
2744
+ }
2745
+ }
2746
+
2747
+ /**
2748
+ * @param {import('types').ShadowEndpointOutput} result
2749
+ */
2750
+ function validate_shadow_output(result) {
2751
+ // TODO remove for 1.0
2752
+ // @ts-expect-error
2753
+ if (result.fallthrough) {
2754
+ throw new Error(
2755
+ 'fallthrough is no longer supported. Use matchers instead: https://kit.svelte.dev/docs/routing#advanced-routing-matching'
2756
+ );
2757
+ }
2758
+
2759
+ const { status = 200, body = {} } = result;
2760
+ let headers = result.headers || {};
2761
+
2762
+ if (headers instanceof Headers) {
2763
+ if (headers.has('set-cookie')) {
2764
+ throw new Error(
2765
+ 'Endpoint request handler cannot use Headers interface with Set-Cookie headers'
2766
+ );
2767
+ }
2768
+ } else {
2769
+ headers = lowercase_keys(/** @type {Record<string, string>} */ (headers));
2770
+ }
2771
+
2772
+ if (!is_pojo(body)) {
2773
+ throw new Error(
2774
+ 'Body returned from endpoint request handler must be a plain object or an Error'
2775
+ );
2776
+ }
2777
+
2778
+ return { status, headers, body };
2779
+ }
2780
+
2781
+ /**
2782
+ * @typedef {import('./types.js').Loaded} Loaded
2783
+ * @typedef {import('types').SSROptions} SSROptions
2784
+ * @typedef {import('types').SSRState} SSRState
2785
+ */
2786
+
2787
+ /**
2788
+ * @param {{
2789
+ * event: import('types').RequestEvent;
2790
+ * options: SSROptions;
2791
+ * state: SSRState;
2792
+ * $session: any;
2793
+ * status: number;
2794
+ * error: Error;
2795
+ * resolve_opts: import('types').RequiredResolveOptions;
2796
+ * }} opts
2797
+ */
2798
+ async function respond_with_error({
2799
+ event,
2800
+ options,
2801
+ state,
2802
+ $session,
2803
+ status,
2804
+ error,
2805
+ resolve_opts
2806
+ }) {
2807
+ try {
2808
+ const branch = [];
2809
+ let stuff = {};
2810
+
2811
+ if (resolve_opts.ssr) {
2812
+ const default_layout = await options.manifest._.nodes[0](); // 0 is always the root layout
2813
+ const default_error = await options.manifest._.nodes[1](); // 1 is always the root error
2814
+
2815
+ const layout_loaded = /** @type {Loaded} */ (
2816
+ await load_node({
2817
+ event,
2818
+ options,
2819
+ state,
2820
+ route: GENERIC_ERROR,
2821
+ node: default_layout,
2822
+ $session,
2823
+ stuff: {},
2824
+ is_error: false,
2825
+ is_leaf: false
2826
+ })
2827
+ );
2828
+
2829
+ if (layout_loaded.loaded.error) {
2830
+ throw layout_loaded.loaded.error;
2831
+ }
2832
+
2833
+ const error_loaded = /** @type {Loaded} */ (
2834
+ await load_node({
2835
+ event,
2836
+ options,
2837
+ state,
2838
+ route: GENERIC_ERROR,
2839
+ node: default_error,
2840
+ $session,
2841
+ stuff: layout_loaded ? layout_loaded.stuff : {},
2842
+ is_error: true,
2843
+ is_leaf: false,
2844
+ status,
2845
+ error
2846
+ })
2847
+ );
2848
+
2849
+ branch.push(layout_loaded, error_loaded);
2850
+ stuff = error_loaded.stuff;
2851
+ }
2852
+
2853
+ return await render_response({
2854
+ options,
2855
+ state,
2856
+ $session,
2857
+ page_config: {
2858
+ hydrate: options.hydrate,
2859
+ router: options.router
2860
+ },
2861
+ stuff,
2862
+ status,
2863
+ error,
2864
+ branch,
2865
+ event,
2866
+ resolve_opts
2867
+ });
2868
+ } catch (err) {
2869
+ const error = coalesce_to_error(err);
2870
+
2871
+ options.handle_error(error, event);
2872
+
2873
+ return new Response(error.stack, {
2874
+ status: 500
2875
+ });
2876
+ }
2877
+ }
2878
+
2879
+ /**
2880
+ * @typedef {import('./types.js').Loaded} Loaded
2881
+ * @typedef {import('types').SSRNode} SSRNode
2882
+ * @typedef {import('types').SSROptions} SSROptions
2883
+ * @typedef {import('types').SSRState} SSRState
2884
+ */
2885
+
2886
+ /**
2887
+ * Gets the nodes, calls `load` for each of them, and then calls render to build the HTML response.
2888
+ * @param {{
2889
+ * event: import('types').RequestEvent;
2890
+ * options: SSROptions;
2891
+ * state: SSRState;
2892
+ * $session: any;
2893
+ * resolve_opts: import('types').RequiredResolveOptions;
2894
+ * route: import('types').SSRPage;
2895
+ * }} opts
2896
+ * @returns {Promise<Response>}
2897
+ */
2898
+ async function respond$1(opts) {
2899
+ const { event, options, state, $session, route, resolve_opts } = opts;
2900
+
2901
+ /** @type {Array<SSRNode | undefined>} */
2902
+ let nodes;
2903
+
2904
+ if (!resolve_opts.ssr) {
2905
+ return await render_response({
2906
+ ...opts,
2907
+ branch: [],
2908
+ page_config: {
2909
+ hydrate: true,
2910
+ router: true
2911
+ },
2912
+ status: 200,
2913
+ error: null,
2914
+ event,
2915
+ stuff: {}
2916
+ });
2917
+ }
2918
+
2919
+ try {
2920
+ nodes = await Promise.all(
2921
+ // we use == here rather than === because [undefined] serializes as "[null]"
2922
+ route.a.map((n) => (n == undefined ? n : options.manifest._.nodes[n]()))
2923
+ );
2924
+ } catch (err) {
2925
+ const error = coalesce_to_error(err);
2926
+
2927
+ options.handle_error(error, event);
2928
+
2929
+ return await respond_with_error({
2930
+ event,
2931
+ options,
2932
+ state,
2933
+ $session,
2934
+ status: 500,
2935
+ error,
2936
+ resolve_opts
2937
+ });
2938
+ }
2939
+
2940
+ // the leaf node will be present. only layouts may be undefined
2941
+ const leaf = /** @type {SSRNode} */ (nodes[nodes.length - 1]).module;
2942
+
2943
+ let page_config = get_page_config(leaf, options);
2944
+
2945
+ if (state.prerendering) {
2946
+ // if the page isn't marked as prerenderable (or is explicitly
2947
+ // marked NOT prerenderable, if `prerender.default` is `true`),
2948
+ // then bail out at this point
2949
+ const should_prerender = leaf.prerender ?? options.prerender.default;
2950
+ if (!should_prerender) {
2951
+ return new Response(undefined, {
2952
+ status: 204
2953
+ });
2954
+ }
2955
+ }
2956
+
2957
+ /** @type {Array<Loaded>} */
2958
+ let branch = [];
2959
+
2960
+ /** @type {number} */
2961
+ let status = 200;
2962
+
2963
+ /** @type {Error | null} */
2964
+ let error = null;
2965
+
2966
+ /** @type {string[]} */
2967
+ let set_cookie_headers = [];
2968
+
2969
+ let stuff = {};
2970
+
2971
+ ssr: {
2972
+ for (let i = 0; i < nodes.length; i += 1) {
2973
+ const node = nodes[i];
2974
+
2975
+ /** @type {Loaded | undefined} */
2976
+ let loaded;
2977
+
2978
+ if (node) {
2979
+ try {
2980
+ loaded = await load_node({
2981
+ ...opts,
2982
+ node,
2983
+ stuff,
2984
+ is_error: false,
2985
+ is_leaf: i === nodes.length - 1
2986
+ });
2987
+
2988
+ set_cookie_headers = set_cookie_headers.concat(loaded.set_cookie_headers);
2989
+
2990
+ if (loaded.loaded.redirect) {
2991
+ return with_cookies(
2992
+ new Response(undefined, {
2993
+ status: loaded.loaded.status,
2994
+ headers: {
2995
+ location: loaded.loaded.redirect
2996
+ }
2997
+ }),
2998
+ set_cookie_headers
2999
+ );
3000
+ }
3001
+
3002
+ if (loaded.loaded.error) {
3003
+ error = loaded.loaded.error;
3004
+ status = loaded.loaded.status ?? 500;
3005
+ }
3006
+ } catch (err) {
3007
+ const e = coalesce_to_error(err);
3008
+
3009
+ options.handle_error(e, event);
3010
+
3011
+ status = 500;
3012
+ error = e;
3013
+ }
3014
+
3015
+ if (loaded && !error) {
3016
+ branch.push(loaded);
3017
+ }
3018
+
3019
+ if (error) {
3020
+ while (i--) {
3021
+ if (route.b[i]) {
3022
+ const index = /** @type {number} */ (route.b[i]);
3023
+ const error_node = await options.manifest._.nodes[index]();
3024
+
3025
+ /** @type {Loaded} */
3026
+ let node_loaded;
3027
+ let j = i;
3028
+ while (!(node_loaded = branch[j])) {
3029
+ j -= 1;
3030
+ }
3031
+
3032
+ try {
3033
+ const error_loaded = /** @type {import('./types').Loaded} */ (
3034
+ await load_node({
3035
+ ...opts,
3036
+ node: error_node,
3037
+ stuff: node_loaded.stuff,
3038
+ is_error: true,
3039
+ is_leaf: false,
3040
+ status,
3041
+ error
3042
+ })
3043
+ );
3044
+
3045
+ if (error_loaded.loaded.error) {
3046
+ continue;
3047
+ }
3048
+
3049
+ page_config = get_page_config(error_node.module, options);
3050
+ branch = branch.slice(0, j + 1).concat(error_loaded);
3051
+ stuff = { ...node_loaded.stuff, ...error_loaded.stuff };
3052
+ break ssr;
3053
+ } catch (err) {
3054
+ const e = coalesce_to_error(err);
3055
+
3056
+ options.handle_error(e, event);
3057
+
3058
+ continue;
3059
+ }
3060
+ }
3061
+ }
3062
+
3063
+ // TODO backtrack until we find an __error.svelte component
3064
+ // that we can use as the leaf node
3065
+ // for now just return regular error page
3066
+ return with_cookies(
3067
+ await respond_with_error({
3068
+ event,
3069
+ options,
3070
+ state,
3071
+ $session,
3072
+ status,
3073
+ error,
3074
+ resolve_opts
3075
+ }),
3076
+ set_cookie_headers
3077
+ );
3078
+ }
3079
+ }
3080
+
3081
+ if (loaded && loaded.loaded.stuff) {
3082
+ stuff = {
3083
+ ...stuff,
3084
+ ...loaded.loaded.stuff
3085
+ };
3086
+ }
3087
+ }
3088
+ }
3089
+
3090
+ try {
3091
+ return with_cookies(
3092
+ await render_response({
3093
+ ...opts,
3094
+ stuff,
3095
+ event,
3096
+ page_config,
3097
+ status,
3098
+ error,
3099
+ branch: branch.filter(Boolean)
3100
+ }),
3101
+ set_cookie_headers
3102
+ );
3103
+ } catch (err) {
3104
+ const error = coalesce_to_error(err);
3105
+
3106
+ options.handle_error(error, event);
3107
+
3108
+ return with_cookies(
3109
+ await respond_with_error({
3110
+ ...opts,
3111
+ status: 500,
3112
+ error
3113
+ }),
3114
+ set_cookie_headers
3115
+ );
3116
+ }
3117
+ }
3118
+
3119
+ /**
3120
+ * @param {import('types').SSRComponent} leaf
3121
+ * @param {SSROptions} options
3122
+ */
3123
+ function get_page_config(leaf, options) {
3124
+ // TODO remove for 1.0
3125
+ if ('ssr' in leaf) {
3126
+ throw new Error(
3127
+ '`export const ssr` has been removed — use the handle hook instead: https://kit.svelte.dev/docs/hooks#handle'
3128
+ );
3129
+ }
3130
+
3131
+ return {
3132
+ router: 'router' in leaf ? !!leaf.router : options.router,
3133
+ hydrate: 'hydrate' in leaf ? !!leaf.hydrate : options.hydrate
3134
+ };
3135
+ }
3136
+
3137
+ /**
3138
+ * @param {Response} response
3139
+ * @param {string[]} set_cookie_headers
3140
+ */
3141
+ function with_cookies(response, set_cookie_headers) {
3142
+ if (set_cookie_headers.length) {
3143
+ set_cookie_headers.forEach((value) => {
3144
+ response.headers.append('set-cookie', value);
3145
+ });
3146
+ }
3147
+ return response;
3148
+ }
3149
+
3150
+ /**
3151
+ * @param {import('types').RequestEvent} event
3152
+ * @param {import('types').SSRPage} route
3153
+ * @param {import('types').SSROptions} options
3154
+ * @param {import('types').SSRState} state
3155
+ * @param {import('types').RequiredResolveOptions} resolve_opts
3156
+ * @returns {Promise<Response>}
3157
+ */
3158
+ async function render_page(event, route, options, state, resolve_opts) {
3159
+ if (state.initiator === route) {
3160
+ // infinite request cycle detected
3161
+ return new Response(`Not found: ${event.url.pathname}`, {
3162
+ status: 404
3163
+ });
3164
+ }
3165
+
3166
+ if (route.shadow) {
3167
+ const type = negotiate(event.request.headers.get('accept') || 'text/html', [
3168
+ 'text/html',
3169
+ 'application/json'
3170
+ ]);
3171
+
3172
+ if (type === 'application/json') {
3173
+ return render_endpoint(event, await route.shadow(), options);
3174
+ }
3175
+ }
3176
+
3177
+ const $session = await options.hooks.getSession(event);
3178
+
3179
+ return respond$1({
3180
+ event,
3181
+ options,
3182
+ state,
3183
+ $session,
3184
+ resolve_opts,
3185
+ route
3186
+ });
3187
+ }
3188
+
3189
+ /**
3190
+ * @param {RegExpMatchArray} match
3191
+ * @param {string[]} names
3192
+ * @param {string[]} types
3193
+ * @param {Record<string, import('types').ParamMatcher>} matchers
3194
+ */
3195
+ function exec(match, names, types, matchers) {
3196
+ /** @type {Record<string, string>} */
3197
+ const params = {};
3198
+
3199
+ for (let i = 0; i < names.length; i += 1) {
3200
+ const name = names[i];
3201
+ const type = types[i];
3202
+ const value = match[i + 1] || '';
3203
+
3204
+ if (type) {
3205
+ const matcher = matchers[type];
3206
+ if (!matcher) throw new Error(`Missing "${type}" param matcher`); // TODO do this ahead of time?
3207
+
3208
+ if (!matcher(value)) return;
3209
+ }
3210
+
3211
+ params[name] = value;
3212
+ }
3213
+
3214
+ return params;
3215
+ }
3216
+
3217
+ /* global __SVELTEKIT_ADAPTER_NAME__ */
3218
+
3219
+ const DATA_SUFFIX = '/__data.json';
3220
+
3221
+ /** @param {{ html: string }} opts */
3222
+ const default_transform = ({ html }) => html;
3223
+
3224
+ /** @type {import('types').Respond} */
3225
+ async function respond(request, options, state) {
3226
+ let url = new URL(request.url);
3227
+
3228
+ const { parameter, allowed } = options.method_override;
3229
+ const method_override = url.searchParams.get(parameter)?.toUpperCase();
3230
+
3231
+ if (method_override) {
3232
+ if (request.method === 'POST') {
3233
+ if (allowed.includes(method_override)) {
3234
+ request = new Proxy(request, {
3235
+ get: (target, property, _receiver) => {
3236
+ if (property === 'method') return method_override;
3237
+ return Reflect.get(target, property, target);
3238
+ }
3239
+ });
3240
+ } else {
3241
+ const verb = allowed.length === 0 ? 'enabled' : 'allowed';
3242
+ const body = `${parameter}=${method_override} is not ${verb}. See https://kit.svelte.dev/docs/configuration#methodoverride`;
3243
+
3244
+ return new Response(body, {
3245
+ status: 400
3246
+ });
3247
+ }
3248
+ } else {
3249
+ throw new Error(`${parameter}=${method_override} is only allowed with POST requests`);
3250
+ }
3251
+ }
3252
+
3253
+ let decoded;
3254
+ try {
3255
+ decoded = decodeURI(url.pathname);
3256
+ } catch {
3257
+ return new Response('Malformed URI', { status: 400 });
3258
+ }
3259
+
3260
+ /** @type {import('types').SSRRoute | null} */
3261
+ let route = null;
3262
+
3263
+ /** @type {Record<string, string>} */
3264
+ let params = {};
3265
+
3266
+ if (options.paths.base && !state.prerendering?.fallback) {
3267
+ if (!decoded.startsWith(options.paths.base)) {
3268
+ return new Response('Not found', { status: 404 });
3269
+ }
3270
+ decoded = decoded.slice(options.paths.base.length) || '/';
3271
+ }
3272
+
3273
+ const is_data_request = decoded.endsWith(DATA_SUFFIX);
3274
+
3275
+ if (is_data_request) {
3276
+ const data_suffix_length = DATA_SUFFIX.length - (options.trailing_slash === 'always' ? 1 : 0);
3277
+ decoded = decoded.slice(0, -data_suffix_length) || '/';
3278
+ url = new URL(url.origin + url.pathname.slice(0, -data_suffix_length) + url.search);
3279
+ }
3280
+
3281
+ if (!state.prerendering?.fallback) {
3282
+ const matchers = await options.manifest._.matchers();
3283
+
3284
+ for (const candidate of options.manifest._.routes) {
3285
+ const match = candidate.pattern.exec(decoded);
3286
+ if (!match) continue;
3287
+
3288
+ const matched = exec(match, candidate.names, candidate.types, matchers);
3289
+ if (matched) {
3290
+ route = candidate;
3291
+ params = decode_params(matched);
3292
+ break;
3293
+ }
3294
+ }
3295
+ }
3296
+
3297
+ if (route) {
3298
+ if (route.type === 'page') {
3299
+ const normalized = normalize_path(url.pathname, options.trailing_slash);
3300
+
3301
+ if (normalized !== url.pathname && !state.prerendering?.fallback) {
3302
+ return new Response(undefined, {
3303
+ status: 301,
3304
+ headers: {
3305
+ 'x-sveltekit-normalize': '1',
3306
+ location:
3307
+ // ensure paths starting with '//' are not treated as protocol-relative
3308
+ (normalized.startsWith('//') ? url.origin + normalized : normalized) +
3309
+ (url.search === '?' ? '' : url.search)
3310
+ }
3311
+ });
3312
+ }
3313
+ } else if (is_data_request) {
3314
+ // requesting /__data.json should fail for a standalone endpoint
3315
+ return new Response(undefined, {
3316
+ status: 404
3317
+ });
3318
+ }
3319
+ }
3320
+
3321
+ /** @type {import('types').RequestEvent} */
3322
+ const event = {
3323
+ get clientAddress() {
3324
+ if (!state.getClientAddress) {
3325
+ throw new Error(
3326
+ `${__SVELTEKIT_ADAPTER_NAME__} does not specify getClientAddress. Please raise an issue`
3327
+ );
3328
+ }
3329
+
3330
+ Object.defineProperty(event, 'clientAddress', {
3331
+ value: state.getClientAddress()
3332
+ });
3333
+
3334
+ return event.clientAddress;
3335
+ },
3336
+ locals: {},
3337
+ params,
3338
+ platform: state.platform,
3339
+ request,
3340
+ routeId: route && route.id,
3341
+ url
3342
+ };
3343
+
3344
+ // TODO remove this for 1.0
3345
+ /**
3346
+ * @param {string} property
3347
+ * @param {string} replacement
3348
+ * @param {string} suffix
3349
+ */
3350
+ const removed = (property, replacement, suffix = '') => ({
3351
+ get: () => {
3352
+ throw new Error(`event.${property} has been replaced by event.${replacement}` + suffix);
3353
+ }
3354
+ });
3355
+
3356
+ const details = '. See https://github.com/sveltejs/kit/pull/3384 for details';
3357
+
3358
+ const body_getter = {
3359
+ get: () => {
3360
+ throw new Error(
3361
+ 'To access the request body use the text/json/arrayBuffer/formData methods, e.g. `body = await request.json()`' +
3362
+ details
3363
+ );
3364
+ }
3365
+ };
3366
+
3367
+ Object.defineProperties(event, {
3368
+ method: removed('method', 'request.method', details),
3369
+ headers: removed('headers', 'request.headers', details),
3370
+ origin: removed('origin', 'url.origin'),
3371
+ path: removed('path', 'url.pathname'),
3372
+ query: removed('query', 'url.searchParams'),
3373
+ body: body_getter,
3374
+ rawBody: body_getter
3375
+ });
3376
+
3377
+ /** @type {import('types').RequiredResolveOptions} */
3378
+ let resolve_opts = {
3379
+ ssr: true,
3380
+ transformPage: default_transform
3381
+ };
3382
+
3383
+ // TODO match route before calling handle?
3384
+
3385
+ try {
3386
+ const response = await options.hooks.handle({
3387
+ event,
3388
+ resolve: async (event, opts) => {
3389
+ if (opts) {
3390
+ resolve_opts = {
3391
+ ssr: opts.ssr !== false,
3392
+ transformPage: opts.transformPage || default_transform
3393
+ };
3394
+ }
3395
+
3396
+ if (state.prerendering?.fallback) {
3397
+ return await render_response({
3398
+ event,
3399
+ options,
3400
+ state,
3401
+ $session: await options.hooks.getSession(event),
3402
+ page_config: { router: true, hydrate: true },
3403
+ stuff: {},
3404
+ status: 200,
3405
+ error: null,
3406
+ branch: [],
3407
+ resolve_opts: {
3408
+ ...resolve_opts,
3409
+ ssr: false
3410
+ }
3411
+ });
3412
+ }
3413
+
3414
+ if (route) {
3415
+ /** @type {Response} */
3416
+ let response;
3417
+
3418
+ if (is_data_request && route.type === 'page' && route.shadow) {
3419
+ response = await render_endpoint(event, await route.shadow(), options);
3420
+
3421
+ // loading data for a client-side transition is a special case
3422
+ if (request.headers.has('x-sveltekit-load')) {
3423
+ // since redirects are opaque to the browser, we need to repackage
3424
+ // 3xx responses as 200s with a custom header
3425
+ if (response.status >= 300 && response.status < 400) {
3426
+ const location = response.headers.get('location');
3427
+
3428
+ if (location) {
3429
+ const headers = new Headers(response.headers);
3430
+ headers.set('x-sveltekit-location', location);
3431
+ response = new Response(undefined, {
3432
+ status: 204,
3433
+ headers
3434
+ });
3435
+ }
3436
+ }
3437
+ }
3438
+ } else {
3439
+ response =
3440
+ route.type === 'endpoint'
3441
+ ? await render_endpoint(event, await route.load(), options)
3442
+ : await render_page(event, route, options, state, resolve_opts);
3443
+ }
3444
+
3445
+ if (response) {
3446
+ // respond with 304 if etag matches
3447
+ if (response.status === 200 && response.headers.has('etag')) {
3448
+ let if_none_match_value = request.headers.get('if-none-match');
3449
+
3450
+ // ignore W/ prefix https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/If-None-Match#directives
3451
+ if (if_none_match_value?.startsWith('W/"')) {
3452
+ if_none_match_value = if_none_match_value.substring(2);
3453
+ }
3454
+
3455
+ const etag = /** @type {string} */ (response.headers.get('etag'));
3456
+
3457
+ if (if_none_match_value === etag) {
3458
+ const headers = new Headers({ etag });
3459
+
3460
+ // https://datatracker.ietf.org/doc/html/rfc7232#section-4.1
3461
+ for (const key of [
3462
+ 'cache-control',
3463
+ 'content-location',
3464
+ 'date',
3465
+ 'expires',
3466
+ 'vary'
3467
+ ]) {
3468
+ const value = response.headers.get(key);
3469
+ if (value) headers.set(key, value);
3470
+ }
3471
+
3472
+ return new Response(undefined, {
3473
+ status: 304,
3474
+ headers
3475
+ });
3476
+ }
3477
+ }
3478
+
3479
+ return response;
3480
+ }
3481
+ }
3482
+
3483
+ if (state.initiator === GENERIC_ERROR) {
3484
+ return new Response('Internal Server Error', {
3485
+ status: 500
3486
+ });
3487
+ }
3488
+
3489
+ // if this request came direct from the user, rather than
3490
+ // via a `fetch` in a `load`, render a 404 page
3491
+ if (!state.initiator) {
3492
+ const $session = await options.hooks.getSession(event);
3493
+ return await respond_with_error({
3494
+ event,
3495
+ options,
3496
+ state,
3497
+ $session,
3498
+ status: 404,
3499
+ error: new Error(`Not found: ${event.url.pathname}`),
3500
+ resolve_opts
3501
+ });
3502
+ }
3503
+
3504
+ if (state.prerendering) {
3505
+ return new Response('not found', { status: 404 });
3506
+ }
3507
+
3508
+ // we can't load the endpoint from our own manifest,
3509
+ // so we need to make an actual HTTP request
3510
+ return await fetch(request);
3511
+ },
3512
+
3513
+ // TODO remove for 1.0
3514
+ // @ts-expect-error
3515
+ get request() {
3516
+ throw new Error('request in handle has been replaced with event' + details);
3517
+ }
3518
+ });
3519
+
3520
+ // TODO for 1.0, change the error message to point to docs rather than PR
3521
+ if (response && !(response instanceof Response)) {
3522
+ throw new Error('handle must return a Response object' + details);
3523
+ }
3524
+
3525
+ return response;
3526
+ } catch (/** @type {unknown} */ e) {
3527
+ const error = coalesce_to_error(e);
3528
+
3529
+ options.handle_error(error, event);
3530
+
3531
+ const type = negotiate(event.request.headers.get('accept') || 'text/html', [
3532
+ 'text/html',
3533
+ 'application/json'
3534
+ ]);
3535
+
3536
+ if (is_data_request || type === 'application/json') {
3537
+ return new Response(serialize_error(error, options.get_stack), {
3538
+ status: 500,
3539
+ headers: { 'content-type': 'application/json; charset=utf-8' }
3540
+ });
3541
+ }
3542
+
3543
+ // TODO is this necessary? should we just return a plain 500 at this point?
3544
+ try {
3545
+ const $session = await options.hooks.getSession(event);
3546
+ return await respond_with_error({
3547
+ event,
3548
+ options,
3549
+ state,
3550
+ $session,
3551
+ status: 500,
3552
+ error,
3553
+ resolve_opts
3554
+ });
3555
+ } catch (/** @type {unknown} */ e) {
3556
+ const error = coalesce_to_error(e);
3557
+
3558
+ return new Response(options.dev ? error.stack : error.message, {
3559
+ status: 500
3560
+ });
3561
+ }
3562
+ }
3563
+ }
3564
+
3565
+ export { respond };