@sveltejs/kit 1.0.0-next.37 → 1.0.0-next.370

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