@sveltejs/kit 1.0.0-next.38 → 1.0.0-next.380

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