@sveltejs/kit 1.0.0-next.36 → 1.0.0-next.362

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 +1793 -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 +3460 -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 +980 -0
  18. package/dist/chunks/write_tsconfig.js +274 -0
  19. package/dist/cli.js +64 -117
  20. package/dist/hooks.js +28 -0
  21. package/dist/node/polyfills.js +12237 -0
  22. package/dist/node.js +5855 -0
  23. package/dist/vite.js +3141 -0
  24. package/package.json +100 -55
  25. package/types/ambient.d.ts +345 -0
  26. package/types/index.d.ts +293 -0
  27. package/types/internal.d.ts +318 -0
  28. package/types/private.d.ts +235 -0
  29. package/CHANGELOG.md +0 -377
  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 -296
  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 -730
  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,3460 @@
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
+ const init_service_worker = `
1422
+ if ('serviceWorker' in navigator) {
1423
+ addEventListener('load', () => {
1424
+ navigator.serviceWorker.register('${options.service_worker}');
1425
+ });
1426
+ }
1427
+ `;
1428
+
1429
+ if (inline_styles.size > 0) {
1430
+ const content = Array.from(inline_styles.values()).join('\n');
1431
+
1432
+ const attributes = [];
1433
+ if (options.dev) attributes.push(' data-sveltekit');
1434
+ if (csp.style_needs_nonce) attributes.push(` nonce="${csp.nonce}"`);
1435
+
1436
+ csp.add_style(content);
1437
+
1438
+ head += `\n\t<style${attributes.join('')}>${content}</style>`;
1439
+ }
1440
+
1441
+ // prettier-ignore
1442
+ head += Array.from(stylesheets)
1443
+ .map((dep) => {
1444
+ const attributes = [
1445
+ 'rel="stylesheet"',
1446
+ `href="${options.prefix + dep}"`
1447
+ ];
1448
+
1449
+ if (csp.style_needs_nonce) {
1450
+ attributes.push(`nonce="${csp.nonce}"`);
1451
+ }
1452
+
1453
+ if (inline_styles.has(dep)) {
1454
+ // don't load stylesheets that are already inlined
1455
+ // include them in disabled state so that Vite can detect them and doesn't try to add them
1456
+ attributes.push('disabled', 'media="(max-width: 0)"');
1457
+ }
1458
+
1459
+ return `\n\t<link ${attributes.join(' ')}>`;
1460
+ })
1461
+ .join('');
1462
+
1463
+ if (page_config.router || page_config.hydrate) {
1464
+ head += Array.from(modulepreloads)
1465
+ .map((dep) => `\n\t<link rel="modulepreload" href="${options.prefix + dep}">`)
1466
+ .join('');
1467
+
1468
+ const attributes = ['type="module"', `data-sveltekit-hydrate="${target}"`];
1469
+
1470
+ csp.add_script(init_app);
1471
+
1472
+ if (csp.script_needs_nonce) {
1473
+ attributes.push(`nonce="${csp.nonce}"`);
1474
+ }
1475
+
1476
+ body += `\n\t\t<script ${attributes.join(' ')}>${init_app}</script>`;
1477
+
1478
+ body += serialized_data
1479
+ .map(({ url, body, response }) =>
1480
+ render_json_payload_script(
1481
+ { type: 'data', url, body: typeof body === 'string' ? hash(body) : undefined },
1482
+ response
1483
+ )
1484
+ )
1485
+ .join('\n\t');
1486
+
1487
+ if (shadow_props) {
1488
+ body += render_json_payload_script({ type: 'props' }, shadow_props);
1489
+ }
1490
+ }
1491
+
1492
+ if (options.service_worker) {
1493
+ // always include service worker unless it's turned off explicitly
1494
+ csp.add_script(init_service_worker);
1495
+
1496
+ head += `
1497
+ <script${csp.script_needs_nonce ? ` nonce="${csp.nonce}"` : ''}>${init_service_worker}</script>`;
1498
+ }
1499
+
1500
+ if (state.prerendering) {
1501
+ const http_equiv = [];
1502
+
1503
+ const csp_headers = csp.get_meta();
1504
+ if (csp_headers) {
1505
+ http_equiv.push(csp_headers);
1506
+ }
1507
+
1508
+ if (cache) {
1509
+ http_equiv.push(`<meta http-equiv="cache-control" content="max-age=${cache.maxage}">`);
1510
+ }
1511
+
1512
+ if (http_equiv.length > 0) {
1513
+ head = http_equiv.join('\n') + head;
1514
+ }
1515
+ }
1516
+
1517
+ const segments = event.url.pathname.slice(options.paths.base.length).split('/').slice(2);
1518
+ const assets =
1519
+ options.paths.assets || (segments.length > 0 ? segments.map(() => '..').join('/') : '.');
1520
+
1521
+ const html = await resolve_opts.transformPage({
1522
+ html: options.template({ head, body, assets, nonce: /** @type {string} */ (csp.nonce) })
1523
+ });
1524
+
1525
+ const headers = new Headers({
1526
+ 'content-type': 'text/html',
1527
+ etag: `"${hash(html)}"`
1528
+ });
1529
+
1530
+ if (cache) {
1531
+ headers.set('cache-control', `${is_private ? 'private' : 'public'}, max-age=${cache.maxage}`);
1532
+ }
1533
+
1534
+ if (!state.prerendering) {
1535
+ const csp_header = csp.get_header();
1536
+ if (csp_header) {
1537
+ headers.set('content-security-policy', csp_header);
1538
+ }
1539
+ }
1540
+
1541
+ return new Response(html, {
1542
+ status,
1543
+ headers
1544
+ });
1545
+ }
1546
+
1547
+ /**
1548
+ * @param {any} data
1549
+ * @param {(error: Error) => void} [fail]
1550
+ */
1551
+ function try_serialize(data, fail) {
1552
+ try {
1553
+ return devalue(data);
1554
+ } catch (err) {
1555
+ if (fail) fail(coalesce_to_error(err));
1556
+ return null;
1557
+ }
1558
+ }
1559
+
1560
+ /*!
1561
+ * cookie
1562
+ * Copyright(c) 2012-2014 Roman Shtylman
1563
+ * Copyright(c) 2015 Douglas Christopher Wilson
1564
+ * MIT Licensed
1565
+ */
1566
+
1567
+ /**
1568
+ * Module exports.
1569
+ * @public
1570
+ */
1571
+
1572
+ var parse_1 = parse$1;
1573
+ var serialize_1 = serialize;
1574
+
1575
+ /**
1576
+ * Module variables.
1577
+ * @private
1578
+ */
1579
+
1580
+ var __toString = Object.prototype.toString;
1581
+
1582
+ /**
1583
+ * RegExp to match field-content in RFC 7230 sec 3.2
1584
+ *
1585
+ * field-content = field-vchar [ 1*( SP / HTAB ) field-vchar ]
1586
+ * field-vchar = VCHAR / obs-text
1587
+ * obs-text = %x80-FF
1588
+ */
1589
+
1590
+ var fieldContentRegExp = /^[\u0009\u0020-\u007e\u0080-\u00ff]+$/;
1591
+
1592
+ /**
1593
+ * Parse a cookie header.
1594
+ *
1595
+ * Parse the given cookie header string into an object
1596
+ * The object has the various cookies as keys(names) => values
1597
+ *
1598
+ * @param {string} str
1599
+ * @param {object} [options]
1600
+ * @return {object}
1601
+ * @public
1602
+ */
1603
+
1604
+ function parse$1(str, options) {
1605
+ if (typeof str !== 'string') {
1606
+ throw new TypeError('argument str must be a string');
1607
+ }
1608
+
1609
+ var obj = {};
1610
+ var opt = options || {};
1611
+ var dec = opt.decode || decode;
1612
+
1613
+ var index = 0;
1614
+ while (index < str.length) {
1615
+ var eqIdx = str.indexOf('=', index);
1616
+
1617
+ // no more cookie pairs
1618
+ if (eqIdx === -1) {
1619
+ break
1620
+ }
1621
+
1622
+ var endIdx = str.indexOf(';', index);
1623
+
1624
+ if (endIdx === -1) {
1625
+ endIdx = str.length;
1626
+ } else if (endIdx < eqIdx) {
1627
+ // backtrack on prior semicolon
1628
+ index = str.lastIndexOf(';', eqIdx - 1) + 1;
1629
+ continue
1630
+ }
1631
+
1632
+ var key = str.slice(index, eqIdx).trim();
1633
+
1634
+ // only assign once
1635
+ if (undefined === obj[key]) {
1636
+ var val = str.slice(eqIdx + 1, endIdx).trim();
1637
+
1638
+ // quoted values
1639
+ if (val.charCodeAt(0) === 0x22) {
1640
+ val = val.slice(1, -1);
1641
+ }
1642
+
1643
+ obj[key] = tryDecode(val, dec);
1644
+ }
1645
+
1646
+ index = endIdx + 1;
1647
+ }
1648
+
1649
+ return obj;
1650
+ }
1651
+
1652
+ /**
1653
+ * Serialize data into a cookie header.
1654
+ *
1655
+ * Serialize the a name value pair into a cookie string suitable for
1656
+ * http headers. An optional options object specified cookie parameters.
1657
+ *
1658
+ * serialize('foo', 'bar', { httpOnly: true })
1659
+ * => "foo=bar; httpOnly"
1660
+ *
1661
+ * @param {string} name
1662
+ * @param {string} val
1663
+ * @param {object} [options]
1664
+ * @return {string}
1665
+ * @public
1666
+ */
1667
+
1668
+ function serialize(name, val, options) {
1669
+ var opt = options || {};
1670
+ var enc = opt.encode || encode;
1671
+
1672
+ if (typeof enc !== 'function') {
1673
+ throw new TypeError('option encode is invalid');
1674
+ }
1675
+
1676
+ if (!fieldContentRegExp.test(name)) {
1677
+ throw new TypeError('argument name is invalid');
1678
+ }
1679
+
1680
+ var value = enc(val);
1681
+
1682
+ if (value && !fieldContentRegExp.test(value)) {
1683
+ throw new TypeError('argument val is invalid');
1684
+ }
1685
+
1686
+ var str = name + '=' + value;
1687
+
1688
+ if (null != opt.maxAge) {
1689
+ var maxAge = opt.maxAge - 0;
1690
+
1691
+ if (isNaN(maxAge) || !isFinite(maxAge)) {
1692
+ throw new TypeError('option maxAge is invalid')
1693
+ }
1694
+
1695
+ str += '; Max-Age=' + Math.floor(maxAge);
1696
+ }
1697
+
1698
+ if (opt.domain) {
1699
+ if (!fieldContentRegExp.test(opt.domain)) {
1700
+ throw new TypeError('option domain is invalid');
1701
+ }
1702
+
1703
+ str += '; Domain=' + opt.domain;
1704
+ }
1705
+
1706
+ if (opt.path) {
1707
+ if (!fieldContentRegExp.test(opt.path)) {
1708
+ throw new TypeError('option path is invalid');
1709
+ }
1710
+
1711
+ str += '; Path=' + opt.path;
1712
+ }
1713
+
1714
+ if (opt.expires) {
1715
+ var expires = opt.expires;
1716
+
1717
+ if (!isDate(expires) || isNaN(expires.valueOf())) {
1718
+ throw new TypeError('option expires is invalid');
1719
+ }
1720
+
1721
+ str += '; Expires=' + expires.toUTCString();
1722
+ }
1723
+
1724
+ if (opt.httpOnly) {
1725
+ str += '; HttpOnly';
1726
+ }
1727
+
1728
+ if (opt.secure) {
1729
+ str += '; Secure';
1730
+ }
1731
+
1732
+ if (opt.priority) {
1733
+ var priority = typeof opt.priority === 'string'
1734
+ ? opt.priority.toLowerCase()
1735
+ : opt.priority;
1736
+
1737
+ switch (priority) {
1738
+ case 'low':
1739
+ str += '; Priority=Low';
1740
+ break
1741
+ case 'medium':
1742
+ str += '; Priority=Medium';
1743
+ break
1744
+ case 'high':
1745
+ str += '; Priority=High';
1746
+ break
1747
+ default:
1748
+ throw new TypeError('option priority is invalid')
1749
+ }
1750
+ }
1751
+
1752
+ if (opt.sameSite) {
1753
+ var sameSite = typeof opt.sameSite === 'string'
1754
+ ? opt.sameSite.toLowerCase() : opt.sameSite;
1755
+
1756
+ switch (sameSite) {
1757
+ case true:
1758
+ str += '; SameSite=Strict';
1759
+ break;
1760
+ case 'lax':
1761
+ str += '; SameSite=Lax';
1762
+ break;
1763
+ case 'strict':
1764
+ str += '; SameSite=Strict';
1765
+ break;
1766
+ case 'none':
1767
+ str += '; SameSite=None';
1768
+ break;
1769
+ default:
1770
+ throw new TypeError('option sameSite is invalid');
1771
+ }
1772
+ }
1773
+
1774
+ return str;
1775
+ }
1776
+
1777
+ /**
1778
+ * URL-decode string value. Optimized to skip native call when no %.
1779
+ *
1780
+ * @param {string} str
1781
+ * @returns {string}
1782
+ */
1783
+
1784
+ function decode (str) {
1785
+ return str.indexOf('%') !== -1
1786
+ ? decodeURIComponent(str)
1787
+ : str
1788
+ }
1789
+
1790
+ /**
1791
+ * URL-encode value.
1792
+ *
1793
+ * @param {string} str
1794
+ * @returns {string}
1795
+ */
1796
+
1797
+ function encode (val) {
1798
+ return encodeURIComponent(val)
1799
+ }
1800
+
1801
+ /**
1802
+ * Determine if value is a Date.
1803
+ *
1804
+ * @param {*} val
1805
+ * @private
1806
+ */
1807
+
1808
+ function isDate (val) {
1809
+ return __toString.call(val) === '[object Date]' ||
1810
+ val instanceof Date
1811
+ }
1812
+
1813
+ /**
1814
+ * Try decoding a string using a decoding function.
1815
+ *
1816
+ * @param {string} str
1817
+ * @param {function} decode
1818
+ * @private
1819
+ */
1820
+
1821
+ function tryDecode(str, decode) {
1822
+ try {
1823
+ return decode(str);
1824
+ } catch (e) {
1825
+ return str;
1826
+ }
1827
+ }
1828
+
1829
+ var setCookie = {exports: {}};
1830
+
1831
+ var defaultParseOptions = {
1832
+ decodeValues: true,
1833
+ map: false,
1834
+ silent: false,
1835
+ };
1836
+
1837
+ function isNonEmptyString(str) {
1838
+ return typeof str === "string" && !!str.trim();
1839
+ }
1840
+
1841
+ function parseString(setCookieValue, options) {
1842
+ var parts = setCookieValue.split(";").filter(isNonEmptyString);
1843
+ var nameValue = parts.shift().split("=");
1844
+ var name = nameValue.shift();
1845
+ var value = nameValue.join("="); // everything after the first =, joined by a "=" if there was more than one part
1846
+
1847
+ options = options
1848
+ ? Object.assign({}, defaultParseOptions, options)
1849
+ : defaultParseOptions;
1850
+
1851
+ try {
1852
+ value = options.decodeValues ? decodeURIComponent(value) : value; // decode cookie value
1853
+ } catch (e) {
1854
+ console.error(
1855
+ "set-cookie-parser encountered an error while decoding a cookie with value '" +
1856
+ value +
1857
+ "'. Set options.decodeValues to false to disable this feature.",
1858
+ e
1859
+ );
1860
+ }
1861
+
1862
+ var cookie = {
1863
+ name: name, // grab everything before the first =
1864
+ value: value,
1865
+ };
1866
+
1867
+ parts.forEach(function (part) {
1868
+ var sides = part.split("=");
1869
+ var key = sides.shift().trimLeft().toLowerCase();
1870
+ var value = sides.join("=");
1871
+ if (key === "expires") {
1872
+ cookie.expires = new Date(value);
1873
+ } else if (key === "max-age") {
1874
+ cookie.maxAge = parseInt(value, 10);
1875
+ } else if (key === "secure") {
1876
+ cookie.secure = true;
1877
+ } else if (key === "httponly") {
1878
+ cookie.httpOnly = true;
1879
+ } else if (key === "samesite") {
1880
+ cookie.sameSite = value;
1881
+ } else {
1882
+ cookie[key] = value;
1883
+ }
1884
+ });
1885
+
1886
+ return cookie;
1887
+ }
1888
+
1889
+ function parse(input, options) {
1890
+ options = options
1891
+ ? Object.assign({}, defaultParseOptions, options)
1892
+ : defaultParseOptions;
1893
+
1894
+ if (!input) {
1895
+ if (!options.map) {
1896
+ return [];
1897
+ } else {
1898
+ return {};
1899
+ }
1900
+ }
1901
+
1902
+ if (input.headers && input.headers["set-cookie"]) {
1903
+ // fast-path for node.js (which automatically normalizes header names to lower-case
1904
+ input = input.headers["set-cookie"];
1905
+ } else if (input.headers) {
1906
+ // slow-path for other environments - see #25
1907
+ var sch =
1908
+ input.headers[
1909
+ Object.keys(input.headers).find(function (key) {
1910
+ return key.toLowerCase() === "set-cookie";
1911
+ })
1912
+ ];
1913
+ // warn if called on a request-like object with a cookie header rather than a set-cookie header - see #34, 36
1914
+ if (!sch && input.headers.cookie && !options.silent) {
1915
+ console.warn(
1916
+ "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."
1917
+ );
1918
+ }
1919
+ input = sch;
1920
+ }
1921
+ if (!Array.isArray(input)) {
1922
+ input = [input];
1923
+ }
1924
+
1925
+ options = options
1926
+ ? Object.assign({}, defaultParseOptions, options)
1927
+ : defaultParseOptions;
1928
+
1929
+ if (!options.map) {
1930
+ return input.filter(isNonEmptyString).map(function (str) {
1931
+ return parseString(str, options);
1932
+ });
1933
+ } else {
1934
+ var cookies = {};
1935
+ return input.filter(isNonEmptyString).reduce(function (cookies, str) {
1936
+ var cookie = parseString(str, options);
1937
+ cookies[cookie.name] = cookie;
1938
+ return cookies;
1939
+ }, cookies);
1940
+ }
1941
+ }
1942
+
1943
+ /*
1944
+ Set-Cookie header field-values are sometimes comma joined in one string. This splits them without choking on commas
1945
+ that are within a single set-cookie field-value, such as in the Expires portion.
1946
+
1947
+ This is uncommon, but explicitly allowed - see https://tools.ietf.org/html/rfc2616#section-4.2
1948
+ Node.js does this for every header *except* set-cookie - see https://github.com/nodejs/node/blob/d5e363b77ebaf1caf67cd7528224b651c86815c1/lib/_http_incoming.js#L128
1949
+ React Native's fetch does this for *every* header, including set-cookie.
1950
+
1951
+ Based on: https://github.com/google/j2objc/commit/16820fdbc8f76ca0c33472810ce0cb03d20efe25
1952
+ Credits to: https://github.com/tomball for original and https://github.com/chrusart for JavaScript implementation
1953
+ */
1954
+ function splitCookiesString(cookiesString) {
1955
+ if (Array.isArray(cookiesString)) {
1956
+ return cookiesString;
1957
+ }
1958
+ if (typeof cookiesString !== "string") {
1959
+ return [];
1960
+ }
1961
+
1962
+ var cookiesStrings = [];
1963
+ var pos = 0;
1964
+ var start;
1965
+ var ch;
1966
+ var lastComma;
1967
+ var nextStart;
1968
+ var cookiesSeparatorFound;
1969
+
1970
+ function skipWhitespace() {
1971
+ while (pos < cookiesString.length && /\s/.test(cookiesString.charAt(pos))) {
1972
+ pos += 1;
1973
+ }
1974
+ return pos < cookiesString.length;
1975
+ }
1976
+
1977
+ function notSpecialChar() {
1978
+ ch = cookiesString.charAt(pos);
1979
+
1980
+ return ch !== "=" && ch !== ";" && ch !== ",";
1981
+ }
1982
+
1983
+ while (pos < cookiesString.length) {
1984
+ start = pos;
1985
+ cookiesSeparatorFound = false;
1986
+
1987
+ while (skipWhitespace()) {
1988
+ ch = cookiesString.charAt(pos);
1989
+ if (ch === ",") {
1990
+ // ',' is a cookie separator if we have later first '=', not ';' or ','
1991
+ lastComma = pos;
1992
+ pos += 1;
1993
+
1994
+ skipWhitespace();
1995
+ nextStart = pos;
1996
+
1997
+ while (pos < cookiesString.length && notSpecialChar()) {
1998
+ pos += 1;
1999
+ }
2000
+
2001
+ // currently special character
2002
+ if (pos < cookiesString.length && cookiesString.charAt(pos) === "=") {
2003
+ // we found cookies separator
2004
+ cookiesSeparatorFound = true;
2005
+ // pos is inside the next cookie, so back up and return it.
2006
+ pos = nextStart;
2007
+ cookiesStrings.push(cookiesString.substring(start, lastComma));
2008
+ start = pos;
2009
+ } else {
2010
+ // in param ',' or param separator ';',
2011
+ // we continue from that comma
2012
+ pos = lastComma + 1;
2013
+ }
2014
+ } else {
2015
+ pos += 1;
2016
+ }
2017
+ }
2018
+
2019
+ if (!cookiesSeparatorFound || pos >= cookiesString.length) {
2020
+ cookiesStrings.push(cookiesString.substring(start, cookiesString.length));
2021
+ }
2022
+ }
2023
+
2024
+ return cookiesStrings;
2025
+ }
2026
+
2027
+ setCookie.exports = parse;
2028
+ setCookie.exports.parse = parse;
2029
+ var parseString_1 = setCookie.exports.parseString = parseString;
2030
+ var splitCookiesString_1 = setCookie.exports.splitCookiesString = splitCookiesString;
2031
+
2032
+ /**
2033
+ * @param {import('types').LoadOutput} loaded
2034
+ * @returns {import('types').NormalizedLoadOutput}
2035
+ */
2036
+ function normalize(loaded) {
2037
+ // TODO remove for 1.0
2038
+ // @ts-expect-error
2039
+ if (loaded.fallthrough) {
2040
+ throw new Error(
2041
+ 'fallthrough is no longer supported. Use matchers instead: https://kit.svelte.dev/docs/routing#advanced-routing-matching'
2042
+ );
2043
+ }
2044
+
2045
+ // TODO remove for 1.0
2046
+ if ('maxage' in loaded) {
2047
+ throw new Error('maxage should be replaced with cache: { maxage }');
2048
+ }
2049
+
2050
+ const has_error_status =
2051
+ loaded.status && loaded.status >= 400 && loaded.status <= 599 && !loaded.redirect;
2052
+ if (loaded.error || has_error_status) {
2053
+ const status = loaded.status;
2054
+
2055
+ if (!loaded.error && has_error_status) {
2056
+ return { status: status || 500, error: new Error() };
2057
+ }
2058
+
2059
+ const error = typeof loaded.error === 'string' ? new Error(loaded.error) : loaded.error;
2060
+
2061
+ if (!(error instanceof Error)) {
2062
+ return {
2063
+ status: 500,
2064
+ error: new Error(
2065
+ `"error" property returned from load() must be a string or instance of Error, received type "${typeof error}"`
2066
+ )
2067
+ };
2068
+ }
2069
+
2070
+ if (!status || status < 400 || status > 599) {
2071
+ console.warn('"error" returned from load() without a valid status code — defaulting to 500');
2072
+ return { status: 500, error };
2073
+ }
2074
+
2075
+ return { status, error };
2076
+ }
2077
+
2078
+ if (loaded.redirect) {
2079
+ if (!loaded.status || Math.floor(loaded.status / 100) !== 3) {
2080
+ throw new Error(
2081
+ '"redirect" property returned from load() must be accompanied by a 3xx status code'
2082
+ );
2083
+ }
2084
+
2085
+ if (typeof loaded.redirect !== 'string') {
2086
+ throw new Error('"redirect" property returned from load() must be a string');
2087
+ }
2088
+ }
2089
+
2090
+ if (loaded.dependencies) {
2091
+ if (
2092
+ !Array.isArray(loaded.dependencies) ||
2093
+ loaded.dependencies.some((dep) => typeof dep !== 'string')
2094
+ ) {
2095
+ throw new Error('"dependencies" property returned from load() must be of type string[]');
2096
+ }
2097
+ }
2098
+
2099
+ // TODO remove before 1.0
2100
+ if (/** @type {any} */ (loaded).context) {
2101
+ throw new Error(
2102
+ 'You are returning "context" from a load function. ' +
2103
+ '"context" was renamed to "stuff", please adjust your code accordingly.'
2104
+ );
2105
+ }
2106
+
2107
+ return /** @type {import('types').NormalizedLoadOutput} */ (loaded);
2108
+ }
2109
+
2110
+ /**
2111
+ * @param {string} hostname
2112
+ * @param {string} [constraint]
2113
+ */
2114
+ function domain_matches(hostname, constraint) {
2115
+ if (!constraint) return true;
2116
+
2117
+ const normalized = constraint[0] === '.' ? constraint.slice(1) : constraint;
2118
+
2119
+ if (hostname === normalized) return true;
2120
+ return hostname.endsWith('.' + normalized);
2121
+ }
2122
+
2123
+ /**
2124
+ * @param {string} path
2125
+ * @param {string} [constraint]
2126
+ */
2127
+ function path_matches(path, constraint) {
2128
+ if (!constraint) return true;
2129
+
2130
+ const normalized = constraint.endsWith('/') ? constraint.slice(0, -1) : constraint;
2131
+
2132
+ if (path === normalized) return true;
2133
+ return path.startsWith(normalized + '/');
2134
+ }
2135
+
2136
+ /**
2137
+ * Calls the user's `load` function.
2138
+ * @param {{
2139
+ * event: import('types').RequestEvent;
2140
+ * options: import('types').SSROptions;
2141
+ * state: import('types').SSRState;
2142
+ * route: import('types').SSRPage | null;
2143
+ * node: import('types').SSRNode;
2144
+ * $session: any;
2145
+ * stuff: Record<string, any>;
2146
+ * is_error: boolean;
2147
+ * is_leaf: boolean;
2148
+ * status?: number;
2149
+ * error?: Error;
2150
+ * }} opts
2151
+ * @returns {Promise<import('./types').Loaded>}
2152
+ */
2153
+ async function load_node({
2154
+ event,
2155
+ options,
2156
+ state,
2157
+ route,
2158
+ node,
2159
+ $session,
2160
+ stuff,
2161
+ is_error,
2162
+ is_leaf,
2163
+ status,
2164
+ error
2165
+ }) {
2166
+ const { module } = node;
2167
+
2168
+ let uses_credentials = false;
2169
+
2170
+ /** @type {Array<import('./types').Fetched>} */
2171
+ const fetched = [];
2172
+
2173
+ const cookies = parse_1(event.request.headers.get('cookie') || '');
2174
+
2175
+ /** @type {import('set-cookie-parser').Cookie[]} */
2176
+ const new_cookies = [];
2177
+
2178
+ /** @type {import('types').LoadOutput} */
2179
+ let loaded;
2180
+
2181
+ const should_prerender = node.module.prerender ?? options.prerender.default;
2182
+
2183
+ /** @type {import('types').ShadowData} */
2184
+ const shadow = is_leaf
2185
+ ? await load_shadow_data(
2186
+ /** @type {import('types').SSRPage} */ (route),
2187
+ event,
2188
+ options,
2189
+ should_prerender
2190
+ )
2191
+ : {};
2192
+
2193
+ if (shadow.cookies) {
2194
+ shadow.cookies.forEach((header) => {
2195
+ new_cookies.push(parseString_1(header));
2196
+ });
2197
+ }
2198
+
2199
+ if (shadow.error) {
2200
+ loaded = {
2201
+ status: shadow.status,
2202
+ error: shadow.error
2203
+ };
2204
+ } else if (shadow.redirect) {
2205
+ loaded = {
2206
+ status: shadow.status,
2207
+ redirect: shadow.redirect
2208
+ };
2209
+ } else if (module.load) {
2210
+ /** @type {import('types').LoadEvent} */
2211
+ const load_input = {
2212
+ url: state.prerendering ? new PrerenderingURL(event.url) : new LoadURL(event.url),
2213
+ params: event.params,
2214
+ props: shadow.body || {},
2215
+ routeId: event.routeId,
2216
+ get session() {
2217
+ if (node.module.prerender ?? options.prerender.default) {
2218
+ throw Error(
2219
+ 'Attempted to access session from a prerendered page. Session would never be populated.'
2220
+ );
2221
+ }
2222
+ uses_credentials = true;
2223
+ return $session;
2224
+ },
2225
+ /**
2226
+ * @param {RequestInfo} resource
2227
+ * @param {RequestInit} opts
2228
+ */
2229
+ fetch: async (resource, opts = {}) => {
2230
+ /** @type {string} */
2231
+ let requested;
2232
+
2233
+ if (typeof resource === 'string') {
2234
+ requested = resource;
2235
+ } else {
2236
+ requested = resource.url;
2237
+
2238
+ opts = {
2239
+ method: resource.method,
2240
+ headers: resource.headers,
2241
+ body: resource.body,
2242
+ mode: resource.mode,
2243
+ credentials: resource.credentials,
2244
+ cache: resource.cache,
2245
+ redirect: resource.redirect,
2246
+ referrer: resource.referrer,
2247
+ integrity: resource.integrity,
2248
+ ...opts
2249
+ };
2250
+ }
2251
+
2252
+ opts.headers = new Headers(opts.headers);
2253
+
2254
+ // merge headers from request
2255
+ for (const [key, value] of event.request.headers) {
2256
+ if (
2257
+ key !== 'authorization' &&
2258
+ key !== 'connection' &&
2259
+ key !== 'cookie' &&
2260
+ key !== 'host' &&
2261
+ key !== 'if-none-match' &&
2262
+ !opts.headers.has(key)
2263
+ ) {
2264
+ opts.headers.set(key, value);
2265
+ }
2266
+ }
2267
+
2268
+ const resolved = resolve(event.url.pathname, requested.split('?')[0]);
2269
+
2270
+ /** @type {Response} */
2271
+ let response;
2272
+
2273
+ /** @type {import('types').PrerenderDependency} */
2274
+ let dependency;
2275
+
2276
+ // handle fetch requests for static assets. e.g. prebaked data, etc.
2277
+ // we need to support everything the browser's fetch supports
2278
+ const prefix = options.paths.assets || options.paths.base;
2279
+ const filename = decodeURIComponent(
2280
+ resolved.startsWith(prefix) ? resolved.slice(prefix.length) : resolved
2281
+ ).slice(1);
2282
+ const filename_html = `${filename}/index.html`; // path may also match path/index.html
2283
+
2284
+ const is_asset = options.manifest.assets.has(filename);
2285
+ const is_asset_html = options.manifest.assets.has(filename_html);
2286
+
2287
+ if (is_asset || is_asset_html) {
2288
+ const file = is_asset ? filename : filename_html;
2289
+
2290
+ if (options.read) {
2291
+ const type = is_asset
2292
+ ? options.manifest.mimeTypes[filename.slice(filename.lastIndexOf('.'))]
2293
+ : 'text/html';
2294
+
2295
+ response = new Response(options.read(file), {
2296
+ headers: type ? { 'content-type': type } : {}
2297
+ });
2298
+ } else {
2299
+ response = await fetch(
2300
+ `${event.url.origin}/${file}`,
2301
+ /** @type {RequestInit} */ (opts)
2302
+ );
2303
+ }
2304
+ } else if (is_root_relative(resolved)) {
2305
+ if (opts.credentials !== 'omit') {
2306
+ uses_credentials = true;
2307
+
2308
+ const authorization = event.request.headers.get('authorization');
2309
+
2310
+ // combine cookies from the initiating request with any that were
2311
+ // added via set-cookie
2312
+ const combined_cookies = { ...cookies };
2313
+
2314
+ for (const cookie of new_cookies) {
2315
+ if (!domain_matches(event.url.hostname, cookie.domain)) continue;
2316
+ if (!path_matches(resolved, cookie.path)) continue;
2317
+
2318
+ combined_cookies[cookie.name] = cookie.value;
2319
+ }
2320
+
2321
+ const cookie = Object.entries(combined_cookies)
2322
+ .map(([name, value]) => `${name}=${value}`)
2323
+ .join('; ');
2324
+
2325
+ if (cookie) {
2326
+ opts.headers.set('cookie', cookie);
2327
+ }
2328
+
2329
+ if (authorization && !opts.headers.has('authorization')) {
2330
+ opts.headers.set('authorization', authorization);
2331
+ }
2332
+ }
2333
+
2334
+ if (opts.body && typeof opts.body !== 'string') {
2335
+ // per https://developer.mozilla.org/en-US/docs/Web/API/Request/Request, this can be a
2336
+ // Blob, BufferSource, FormData, URLSearchParams, USVString, or ReadableStream object.
2337
+ // non-string bodies are irksome to deal with, but luckily aren't particularly useful
2338
+ // in this context anyway, so we take the easy route and ban them
2339
+ throw new Error('Request body must be a string');
2340
+ }
2341
+
2342
+ response = await respond(
2343
+ new Request(new URL(requested, event.url).href, { ...opts }),
2344
+ options,
2345
+ {
2346
+ ...state,
2347
+ initiator: route
2348
+ }
2349
+ );
2350
+
2351
+ if (state.prerendering) {
2352
+ dependency = { response, body: null };
2353
+ state.prerendering.dependencies.set(resolved, dependency);
2354
+ }
2355
+ } else {
2356
+ // external
2357
+ if (resolved.startsWith('//')) {
2358
+ requested = event.url.protocol + requested;
2359
+ }
2360
+
2361
+ // external fetch
2362
+ // allow cookie passthrough for "same-origin"
2363
+ // if SvelteKit is serving my.domain.com:
2364
+ // - domain.com WILL NOT receive cookies
2365
+ // - my.domain.com WILL receive cookies
2366
+ // - api.domain.dom WILL NOT receive cookies
2367
+ // - sub.my.domain.com WILL receive cookies
2368
+ // ports do not affect the resolution
2369
+ // leading dot prevents mydomain.com matching domain.com
2370
+ if (
2371
+ `.${new URL(requested).hostname}`.endsWith(`.${event.url.hostname}`) &&
2372
+ opts.credentials !== 'omit'
2373
+ ) {
2374
+ uses_credentials = true;
2375
+
2376
+ const cookie = event.request.headers.get('cookie');
2377
+ if (cookie) opts.headers.set('cookie', cookie);
2378
+ }
2379
+
2380
+ // we need to delete the connection header, as explained here:
2381
+ // https://github.com/nodejs/undici/issues/1470#issuecomment-1140798467
2382
+ // TODO this may be a case for being selective about which headers we let through
2383
+ opts.headers.delete('connection');
2384
+
2385
+ const external_request = new Request(requested, /** @type {RequestInit} */ (opts));
2386
+ response = await options.hooks.externalFetch.call(null, external_request);
2387
+ }
2388
+
2389
+ const set_cookie = response.headers.get('set-cookie');
2390
+ if (set_cookie) {
2391
+ new_cookies.push(
2392
+ ...splitCookiesString_1(set_cookie)
2393
+ .map((str) => parseString_1(str))
2394
+ );
2395
+ }
2396
+
2397
+ const proxy = new Proxy(response, {
2398
+ get(response, key, _receiver) {
2399
+ async function text() {
2400
+ const body = await response.text();
2401
+
2402
+ /** @type {import('types').ResponseHeaders} */
2403
+ const headers = {};
2404
+ for (const [key, value] of response.headers) {
2405
+ // TODO skip others besides set-cookie and etag?
2406
+ if (key !== 'set-cookie' && key !== 'etag') {
2407
+ headers[key] = value;
2408
+ }
2409
+ }
2410
+
2411
+ if (!opts.body || typeof opts.body === 'string') {
2412
+ const status_number = Number(response.status);
2413
+ if (isNaN(status_number)) {
2414
+ throw new Error(
2415
+ `response.status is not a number. value: "${
2416
+ response.status
2417
+ }" type: ${typeof response.status}`
2418
+ );
2419
+ }
2420
+
2421
+ fetched.push({
2422
+ url: requested,
2423
+ body: opts.body,
2424
+ response: {
2425
+ status: status_number,
2426
+ statusText: response.statusText,
2427
+ headers,
2428
+ body
2429
+ }
2430
+ });
2431
+ }
2432
+
2433
+ if (dependency) {
2434
+ dependency.body = body;
2435
+ }
2436
+
2437
+ return body;
2438
+ }
2439
+
2440
+ if (key === 'arrayBuffer') {
2441
+ return async () => {
2442
+ const buffer = await response.arrayBuffer();
2443
+
2444
+ if (dependency) {
2445
+ dependency.body = new Uint8Array(buffer);
2446
+ }
2447
+
2448
+ // TODO should buffer be inlined into the page (albeit base64'd)?
2449
+ // any conditions in which it shouldn't be?
2450
+
2451
+ return buffer;
2452
+ };
2453
+ }
2454
+
2455
+ if (key === 'text') {
2456
+ return text;
2457
+ }
2458
+
2459
+ if (key === 'json') {
2460
+ return async () => {
2461
+ return JSON.parse(await text());
2462
+ };
2463
+ }
2464
+
2465
+ // TODO arrayBuffer?
2466
+
2467
+ return Reflect.get(response, key, response);
2468
+ }
2469
+ });
2470
+
2471
+ return proxy;
2472
+ },
2473
+ stuff: { ...stuff },
2474
+ status: is_error ? status ?? null : null,
2475
+ error: is_error ? error ?? null : null
2476
+ };
2477
+
2478
+ if (options.dev) {
2479
+ // TODO remove this for 1.0
2480
+ Object.defineProperty(load_input, 'page', {
2481
+ get: () => {
2482
+ throw new Error('`page` in `load` functions has been replaced by `url` and `params`');
2483
+ }
2484
+ });
2485
+ }
2486
+
2487
+ loaded = await module.load.call(null, load_input);
2488
+
2489
+ if (!loaded) {
2490
+ // TODO do we still want to enforce this now that there's no fallthrough?
2491
+ throw new Error(`load function must return a value${options.dev ? ` (${node.file})` : ''}`);
2492
+ }
2493
+ } else if (shadow.body) {
2494
+ loaded = {
2495
+ props: shadow.body
2496
+ };
2497
+ } else {
2498
+ loaded = {};
2499
+ }
2500
+
2501
+ // generate __data.json files when prerendering
2502
+ if (shadow.body && state.prerendering) {
2503
+ const pathname = `${event.url.pathname.replace(/\/$/, '')}/__data.json`;
2504
+
2505
+ const dependency = {
2506
+ response: new Response(undefined),
2507
+ body: JSON.stringify(shadow.body)
2508
+ };
2509
+
2510
+ state.prerendering.dependencies.set(pathname, dependency);
2511
+ }
2512
+
2513
+ return {
2514
+ node,
2515
+ props: shadow.body,
2516
+ loaded: normalize(loaded),
2517
+ stuff: loaded.stuff || stuff,
2518
+ fetched,
2519
+ set_cookie_headers: new_cookies.map((new_cookie) => {
2520
+ const { name, value, ...options } = new_cookie;
2521
+ // @ts-expect-error
2522
+ return serialize_1(name, value, options);
2523
+ }),
2524
+ uses_credentials
2525
+ };
2526
+ }
2527
+
2528
+ /**
2529
+ *
2530
+ * @param {import('types').SSRPage} route
2531
+ * @param {import('types').RequestEvent} event
2532
+ * @param {import('types').SSROptions} options
2533
+ * @param {boolean} prerender
2534
+ * @returns {Promise<import('types').ShadowData>}
2535
+ */
2536
+ async function load_shadow_data(route, event, options, prerender) {
2537
+ if (!route.shadow) return {};
2538
+
2539
+ try {
2540
+ const mod = await route.shadow();
2541
+
2542
+ if (prerender && (mod.post || mod.put || mod.del || mod.patch)) {
2543
+ throw new Error('Cannot prerender pages that have endpoints with mutative methods');
2544
+ }
2545
+
2546
+ const method = normalize_request_method(event);
2547
+ const is_get = method === 'head' || method === 'get';
2548
+ const handler = method === 'head' ? mod.head || mod.get : mod[method];
2549
+
2550
+ if (!handler && !is_get) {
2551
+ return {
2552
+ status: 405,
2553
+ error: new Error(`${method} method not allowed`)
2554
+ };
2555
+ }
2556
+
2557
+ /** @type {import('types').ShadowData} */
2558
+ const data = {
2559
+ status: 200,
2560
+ cookies: [],
2561
+ body: {}
2562
+ };
2563
+
2564
+ if (!is_get) {
2565
+ const { status, headers, body } = validate_shadow_output(await handler(event));
2566
+ add_cookies(/** @type {string[]} */ (data.cookies), headers);
2567
+ data.status = status;
2568
+
2569
+ // explicit errors cause an error page...
2570
+ if (body instanceof Error) {
2571
+ if (status < 400) {
2572
+ data.status = 500;
2573
+ data.error = new Error('A non-error status code was returned with an error body');
2574
+ } else {
2575
+ data.error = body;
2576
+ }
2577
+
2578
+ return data;
2579
+ }
2580
+
2581
+ // ...redirects are respected...
2582
+ if (status >= 300 && status < 400) {
2583
+ data.redirect = /** @type {string} */ (
2584
+ headers instanceof Headers ? headers.get('location') : headers.location
2585
+ );
2586
+ return data;
2587
+ }
2588
+
2589
+ // ...but 4xx and 5xx status codes _don't_ result in the error page
2590
+ // rendering for non-GET requests — instead, we allow the page
2591
+ // to render with any validation errors etc that were returned
2592
+ data.body = body;
2593
+ }
2594
+
2595
+ const get = (method === 'head' && mod.head) || mod.get;
2596
+ if (get) {
2597
+ const { status, headers, body } = validate_shadow_output(await get(event));
2598
+ add_cookies(/** @type {string[]} */ (data.cookies), headers);
2599
+ data.status = status;
2600
+
2601
+ if (body instanceof Error) {
2602
+ if (status < 400) {
2603
+ data.status = 500;
2604
+ data.error = new Error('A non-error status code was returned with an error body');
2605
+ } else {
2606
+ data.error = body;
2607
+ }
2608
+
2609
+ return data;
2610
+ }
2611
+
2612
+ if (status >= 400) {
2613
+ data.error = new Error('Failed to load data');
2614
+ return data;
2615
+ }
2616
+
2617
+ if (status >= 300) {
2618
+ data.redirect = /** @type {string} */ (
2619
+ headers instanceof Headers ? headers.get('location') : headers.location
2620
+ );
2621
+ return data;
2622
+ }
2623
+
2624
+ data.body = { ...body, ...data.body };
2625
+ }
2626
+
2627
+ return data;
2628
+ } catch (e) {
2629
+ const error = coalesce_to_error(e);
2630
+ options.handle_error(error, event);
2631
+
2632
+ return {
2633
+ status: 500,
2634
+ error
2635
+ };
2636
+ }
2637
+ }
2638
+
2639
+ /**
2640
+ * @param {string[]} target
2641
+ * @param {Partial<import('types').ResponseHeaders>} headers
2642
+ */
2643
+ function add_cookies(target, headers) {
2644
+ const cookies = headers['set-cookie'];
2645
+ if (cookies) {
2646
+ if (Array.isArray(cookies)) {
2647
+ target.push(...cookies);
2648
+ } else {
2649
+ target.push(/** @type {string} */ (cookies));
2650
+ }
2651
+ }
2652
+ }
2653
+
2654
+ /**
2655
+ * @param {import('types').ShadowEndpointOutput} result
2656
+ */
2657
+ function validate_shadow_output(result) {
2658
+ // TODO remove for 1.0
2659
+ // @ts-expect-error
2660
+ if (result.fallthrough) {
2661
+ throw new Error(
2662
+ 'fallthrough is no longer supported. Use matchers instead: https://kit.svelte.dev/docs/routing#advanced-routing-matching'
2663
+ );
2664
+ }
2665
+
2666
+ const { status = 200, body = {} } = result;
2667
+ let headers = result.headers || {};
2668
+
2669
+ if (headers instanceof Headers) {
2670
+ if (headers.has('set-cookie')) {
2671
+ throw new Error(
2672
+ 'Endpoint request handler cannot use Headers interface with Set-Cookie headers'
2673
+ );
2674
+ }
2675
+ } else {
2676
+ headers = lowercase_keys(/** @type {Record<string, string>} */ (headers));
2677
+ }
2678
+
2679
+ if (!is_pojo(body)) {
2680
+ throw new Error(
2681
+ 'Body returned from endpoint request handler must be a plain object or an Error'
2682
+ );
2683
+ }
2684
+
2685
+ return { status, headers, body };
2686
+ }
2687
+
2688
+ /**
2689
+ * @typedef {import('./types.js').Loaded} Loaded
2690
+ * @typedef {import('types').SSROptions} SSROptions
2691
+ * @typedef {import('types').SSRState} SSRState
2692
+ */
2693
+
2694
+ /**
2695
+ * @param {{
2696
+ * event: import('types').RequestEvent;
2697
+ * options: SSROptions;
2698
+ * state: SSRState;
2699
+ * $session: any;
2700
+ * status: number;
2701
+ * error: Error;
2702
+ * resolve_opts: import('types').RequiredResolveOptions;
2703
+ * }} opts
2704
+ */
2705
+ async function respond_with_error({
2706
+ event,
2707
+ options,
2708
+ state,
2709
+ $session,
2710
+ status,
2711
+ error,
2712
+ resolve_opts
2713
+ }) {
2714
+ try {
2715
+ const branch = [];
2716
+ let stuff = {};
2717
+
2718
+ if (resolve_opts.ssr) {
2719
+ const default_layout = await options.manifest._.nodes[0](); // 0 is always the root layout
2720
+ const default_error = await options.manifest._.nodes[1](); // 1 is always the root error
2721
+
2722
+ const layout_loaded = /** @type {Loaded} */ (
2723
+ await load_node({
2724
+ event,
2725
+ options,
2726
+ state,
2727
+ route: null,
2728
+ node: default_layout,
2729
+ $session,
2730
+ stuff: {},
2731
+ is_error: false,
2732
+ is_leaf: false
2733
+ })
2734
+ );
2735
+
2736
+ const error_loaded = /** @type {Loaded} */ (
2737
+ await load_node({
2738
+ event,
2739
+ options,
2740
+ state,
2741
+ route: null,
2742
+ node: default_error,
2743
+ $session,
2744
+ stuff: layout_loaded ? layout_loaded.stuff : {},
2745
+ is_error: true,
2746
+ is_leaf: false,
2747
+ status,
2748
+ error
2749
+ })
2750
+ );
2751
+
2752
+ branch.push(layout_loaded, error_loaded);
2753
+ stuff = error_loaded.stuff;
2754
+ }
2755
+
2756
+ return await render_response({
2757
+ options,
2758
+ state,
2759
+ $session,
2760
+ page_config: {
2761
+ hydrate: options.hydrate,
2762
+ router: options.router
2763
+ },
2764
+ stuff,
2765
+ status,
2766
+ error,
2767
+ branch,
2768
+ event,
2769
+ resolve_opts
2770
+ });
2771
+ } catch (err) {
2772
+ const error = coalesce_to_error(err);
2773
+
2774
+ options.handle_error(error, event);
2775
+
2776
+ return new Response(error.stack, {
2777
+ status: 500
2778
+ });
2779
+ }
2780
+ }
2781
+
2782
+ /**
2783
+ * @typedef {import('./types.js').Loaded} Loaded
2784
+ * @typedef {import('types').SSRNode} SSRNode
2785
+ * @typedef {import('types').SSROptions} SSROptions
2786
+ * @typedef {import('types').SSRState} SSRState
2787
+ */
2788
+
2789
+ /**
2790
+ * Gets the nodes, calls `load` for each of them, and then calls render to build the HTML response.
2791
+ * @param {{
2792
+ * event: import('types').RequestEvent;
2793
+ * options: SSROptions;
2794
+ * state: SSRState;
2795
+ * $session: any;
2796
+ * resolve_opts: import('types').RequiredResolveOptions;
2797
+ * route: import('types').SSRPage;
2798
+ * }} opts
2799
+ * @returns {Promise<Response>}
2800
+ */
2801
+ async function respond$1(opts) {
2802
+ const { event, options, state, $session, route, resolve_opts } = opts;
2803
+
2804
+ /** @type {Array<SSRNode | undefined>} */
2805
+ let nodes;
2806
+
2807
+ if (!resolve_opts.ssr) {
2808
+ return await render_response({
2809
+ ...opts,
2810
+ branch: [],
2811
+ page_config: {
2812
+ hydrate: true,
2813
+ router: true
2814
+ },
2815
+ status: 200,
2816
+ error: null,
2817
+ event,
2818
+ stuff: {}
2819
+ });
2820
+ }
2821
+
2822
+ try {
2823
+ nodes = await Promise.all(
2824
+ // we use == here rather than === because [undefined] serializes as "[null]"
2825
+ route.a.map((n) => (n == undefined ? n : options.manifest._.nodes[n]()))
2826
+ );
2827
+ } catch (err) {
2828
+ const error = coalesce_to_error(err);
2829
+
2830
+ options.handle_error(error, event);
2831
+
2832
+ return await respond_with_error({
2833
+ event,
2834
+ options,
2835
+ state,
2836
+ $session,
2837
+ status: 500,
2838
+ error,
2839
+ resolve_opts
2840
+ });
2841
+ }
2842
+
2843
+ // the leaf node will be present. only layouts may be undefined
2844
+ const leaf = /** @type {SSRNode} */ (nodes[nodes.length - 1]).module;
2845
+
2846
+ let page_config = get_page_config(leaf, options);
2847
+
2848
+ if (state.prerendering) {
2849
+ // if the page isn't marked as prerenderable (or is explicitly
2850
+ // marked NOT prerenderable, if `prerender.default` is `true`),
2851
+ // then bail out at this point
2852
+ const should_prerender = leaf.prerender ?? options.prerender.default;
2853
+ if (!should_prerender) {
2854
+ return new Response(undefined, {
2855
+ status: 204
2856
+ });
2857
+ }
2858
+ }
2859
+
2860
+ /** @type {Array<Loaded>} */
2861
+ let branch = [];
2862
+
2863
+ /** @type {number} */
2864
+ let status = 200;
2865
+
2866
+ /** @type {Error | null} */
2867
+ let error = null;
2868
+
2869
+ /** @type {string[]} */
2870
+ let set_cookie_headers = [];
2871
+
2872
+ let stuff = {};
2873
+
2874
+ ssr: {
2875
+ for (let i = 0; i < nodes.length; i += 1) {
2876
+ const node = nodes[i];
2877
+
2878
+ /** @type {Loaded | undefined} */
2879
+ let loaded;
2880
+
2881
+ if (node) {
2882
+ try {
2883
+ loaded = await load_node({
2884
+ ...opts,
2885
+ node,
2886
+ stuff,
2887
+ is_error: false,
2888
+ is_leaf: i === nodes.length - 1
2889
+ });
2890
+
2891
+ set_cookie_headers = set_cookie_headers.concat(loaded.set_cookie_headers);
2892
+
2893
+ if (loaded.loaded.redirect) {
2894
+ return with_cookies(
2895
+ new Response(undefined, {
2896
+ status: loaded.loaded.status,
2897
+ headers: {
2898
+ location: loaded.loaded.redirect
2899
+ }
2900
+ }),
2901
+ set_cookie_headers
2902
+ );
2903
+ }
2904
+
2905
+ if (loaded.loaded.error) {
2906
+ ({ status, error } = loaded.loaded);
2907
+ }
2908
+ } catch (err) {
2909
+ const e = coalesce_to_error(err);
2910
+
2911
+ options.handle_error(e, event);
2912
+
2913
+ status = 500;
2914
+ error = e;
2915
+ }
2916
+
2917
+ if (loaded && !error) {
2918
+ branch.push(loaded);
2919
+ }
2920
+
2921
+ if (error) {
2922
+ while (i--) {
2923
+ if (route.b[i]) {
2924
+ const index = /** @type {number} */ (route.b[i]);
2925
+ const error_node = await options.manifest._.nodes[index]();
2926
+
2927
+ /** @type {Loaded} */
2928
+ let node_loaded;
2929
+ let j = i;
2930
+ while (!(node_loaded = branch[j])) {
2931
+ j -= 1;
2932
+ }
2933
+
2934
+ try {
2935
+ const error_loaded = /** @type {import('./types').Loaded} */ (
2936
+ await load_node({
2937
+ ...opts,
2938
+ node: error_node,
2939
+ stuff: node_loaded.stuff,
2940
+ is_error: true,
2941
+ is_leaf: false,
2942
+ status,
2943
+ error
2944
+ })
2945
+ );
2946
+
2947
+ if (error_loaded.loaded.error) {
2948
+ continue;
2949
+ }
2950
+
2951
+ page_config = get_page_config(error_node.module, options);
2952
+ branch = branch.slice(0, j + 1).concat(error_loaded);
2953
+ stuff = { ...node_loaded.stuff, ...error_loaded.stuff };
2954
+ break ssr;
2955
+ } catch (err) {
2956
+ const e = coalesce_to_error(err);
2957
+
2958
+ options.handle_error(e, event);
2959
+
2960
+ continue;
2961
+ }
2962
+ }
2963
+ }
2964
+
2965
+ // TODO backtrack until we find an __error.svelte component
2966
+ // that we can use as the leaf node
2967
+ // for now just return regular error page
2968
+ return with_cookies(
2969
+ await respond_with_error({
2970
+ event,
2971
+ options,
2972
+ state,
2973
+ $session,
2974
+ status,
2975
+ error,
2976
+ resolve_opts
2977
+ }),
2978
+ set_cookie_headers
2979
+ );
2980
+ }
2981
+ }
2982
+
2983
+ if (loaded && loaded.loaded.stuff) {
2984
+ stuff = {
2985
+ ...stuff,
2986
+ ...loaded.loaded.stuff
2987
+ };
2988
+ }
2989
+ }
2990
+ }
2991
+
2992
+ try {
2993
+ return with_cookies(
2994
+ await render_response({
2995
+ ...opts,
2996
+ stuff,
2997
+ event,
2998
+ page_config,
2999
+ status,
3000
+ error,
3001
+ branch: branch.filter(Boolean)
3002
+ }),
3003
+ set_cookie_headers
3004
+ );
3005
+ } catch (err) {
3006
+ const error = coalesce_to_error(err);
3007
+
3008
+ options.handle_error(error, event);
3009
+
3010
+ return with_cookies(
3011
+ await respond_with_error({
3012
+ ...opts,
3013
+ status: 500,
3014
+ error
3015
+ }),
3016
+ set_cookie_headers
3017
+ );
3018
+ }
3019
+ }
3020
+
3021
+ /**
3022
+ * @param {import('types').SSRComponent} leaf
3023
+ * @param {SSROptions} options
3024
+ */
3025
+ function get_page_config(leaf, options) {
3026
+ // TODO remove for 1.0
3027
+ if ('ssr' in leaf) {
3028
+ throw new Error(
3029
+ '`export const ssr` has been removed — use the handle hook instead: https://kit.svelte.dev/docs/hooks#handle'
3030
+ );
3031
+ }
3032
+
3033
+ return {
3034
+ router: 'router' in leaf ? !!leaf.router : options.router,
3035
+ hydrate: 'hydrate' in leaf ? !!leaf.hydrate : options.hydrate
3036
+ };
3037
+ }
3038
+
3039
+ /**
3040
+ * @param {Response} response
3041
+ * @param {string[]} set_cookie_headers
3042
+ */
3043
+ function with_cookies(response, set_cookie_headers) {
3044
+ if (set_cookie_headers.length) {
3045
+ set_cookie_headers.forEach((value) => {
3046
+ response.headers.append('set-cookie', value);
3047
+ });
3048
+ }
3049
+ return response;
3050
+ }
3051
+
3052
+ /**
3053
+ * @param {import('types').RequestEvent} event
3054
+ * @param {import('types').SSRPage} route
3055
+ * @param {import('types').SSROptions} options
3056
+ * @param {import('types').SSRState} state
3057
+ * @param {import('types').RequiredResolveOptions} resolve_opts
3058
+ * @returns {Promise<Response>}
3059
+ */
3060
+ async function render_page(event, route, options, state, resolve_opts) {
3061
+ if (state.initiator === route) {
3062
+ // infinite request cycle detected
3063
+ return new Response(`Not found: ${event.url.pathname}`, {
3064
+ status: 404
3065
+ });
3066
+ }
3067
+
3068
+ if (route.shadow) {
3069
+ const type = negotiate(event.request.headers.get('accept') || 'text/html', [
3070
+ 'text/html',
3071
+ 'application/json'
3072
+ ]);
3073
+
3074
+ if (type === 'application/json') {
3075
+ return render_endpoint(event, await route.shadow(), options);
3076
+ }
3077
+ }
3078
+
3079
+ const $session = await options.hooks.getSession(event);
3080
+
3081
+ return respond$1({
3082
+ event,
3083
+ options,
3084
+ state,
3085
+ $session,
3086
+ resolve_opts,
3087
+ route
3088
+ });
3089
+ }
3090
+
3091
+ /**
3092
+ * @param {RegExpMatchArray} match
3093
+ * @param {string[]} names
3094
+ * @param {string[]} types
3095
+ * @param {Record<string, import('types').ParamMatcher>} matchers
3096
+ */
3097
+ function exec(match, names, types, matchers) {
3098
+ /** @type {Record<string, string>} */
3099
+ const params = {};
3100
+
3101
+ for (let i = 0; i < names.length; i += 1) {
3102
+ const name = names[i];
3103
+ const type = types[i];
3104
+ const value = match[i + 1] || '';
3105
+
3106
+ if (type) {
3107
+ const matcher = matchers[type];
3108
+ if (!matcher) throw new Error(`Missing "${type}" param matcher`); // TODO do this ahead of time?
3109
+
3110
+ if (!matcher(value)) return;
3111
+ }
3112
+
3113
+ params[name] = value;
3114
+ }
3115
+
3116
+ return params;
3117
+ }
3118
+
3119
+ const DATA_SUFFIX = '/__data.json';
3120
+
3121
+ /** @param {{ html: string }} opts */
3122
+ const default_transform = ({ html }) => html;
3123
+
3124
+ /** @type {import('types').Respond} */
3125
+ async function respond(request, options, state) {
3126
+ let url = new URL(request.url);
3127
+
3128
+ const { parameter, allowed } = options.method_override;
3129
+ const method_override = url.searchParams.get(parameter)?.toUpperCase();
3130
+
3131
+ if (method_override) {
3132
+ if (request.method === 'POST') {
3133
+ if (allowed.includes(method_override)) {
3134
+ request = new Proxy(request, {
3135
+ get: (target, property, _receiver) => {
3136
+ if (property === 'method') return method_override;
3137
+ return Reflect.get(target, property, target);
3138
+ }
3139
+ });
3140
+ } else {
3141
+ const verb = allowed.length === 0 ? 'enabled' : 'allowed';
3142
+ const body = `${parameter}=${method_override} is not ${verb}. See https://kit.svelte.dev/docs/configuration#methodoverride`;
3143
+
3144
+ return new Response(body, {
3145
+ status: 400
3146
+ });
3147
+ }
3148
+ } else {
3149
+ throw new Error(`${parameter}=${method_override} is only allowed with POST requests`);
3150
+ }
3151
+ }
3152
+
3153
+ let decoded;
3154
+ try {
3155
+ decoded = decodeURI(url.pathname);
3156
+ } catch {
3157
+ return new Response('Malformed URI', { status: 400 });
3158
+ }
3159
+
3160
+ /** @type {import('types').SSRRoute | null} */
3161
+ let route = null;
3162
+
3163
+ /** @type {Record<string, string>} */
3164
+ let params = {};
3165
+
3166
+ if (options.paths.base && !state.prerendering?.fallback) {
3167
+ if (!decoded.startsWith(options.paths.base)) {
3168
+ return new Response('Not found', { status: 404 });
3169
+ }
3170
+ decoded = decoded.slice(options.paths.base.length) || '/';
3171
+ }
3172
+
3173
+ const is_data_request = decoded.endsWith(DATA_SUFFIX);
3174
+
3175
+ if (is_data_request) {
3176
+ const data_suffix_length = DATA_SUFFIX.length - (options.trailing_slash === 'always' ? 1 : 0);
3177
+ decoded = decoded.slice(0, -data_suffix_length) || '/';
3178
+ url = new URL(url.origin + url.pathname.slice(0, -data_suffix_length) + url.search);
3179
+ }
3180
+
3181
+ if (!state.prerendering?.fallback) {
3182
+ const matchers = await options.manifest._.matchers();
3183
+
3184
+ for (const candidate of options.manifest._.routes) {
3185
+ const match = candidate.pattern.exec(decoded);
3186
+ if (!match) continue;
3187
+
3188
+ const matched = exec(match, candidate.names, candidate.types, matchers);
3189
+ if (matched) {
3190
+ route = candidate;
3191
+ params = decode_params(matched);
3192
+ break;
3193
+ }
3194
+ }
3195
+ }
3196
+
3197
+ if (route) {
3198
+ if (route.type === 'page') {
3199
+ const normalized = normalize_path(url.pathname, options.trailing_slash);
3200
+
3201
+ if (normalized !== url.pathname && !state.prerendering?.fallback) {
3202
+ return new Response(undefined, {
3203
+ status: 301,
3204
+ headers: {
3205
+ 'x-sveltekit-normalize': '1',
3206
+ location:
3207
+ // ensure paths starting with '//' are not treated as protocol-relative
3208
+ (normalized.startsWith('//') ? url.origin + normalized : normalized) +
3209
+ (url.search === '?' ? '' : url.search)
3210
+ }
3211
+ });
3212
+ }
3213
+ } else if (is_data_request) {
3214
+ // requesting /__data.json should fail for a standalone endpoint
3215
+ return new Response(undefined, {
3216
+ status: 404
3217
+ });
3218
+ }
3219
+ }
3220
+
3221
+ /** @type {import('types').RequestEvent} */
3222
+ const event = {
3223
+ get clientAddress() {
3224
+ if (!state.getClientAddress) {
3225
+ throw new Error(
3226
+ `${
3227
+ import.meta.env.VITE_SVELTEKIT_ADAPTER_NAME
3228
+ } does not specify getClientAddress. Please raise an issue`
3229
+ );
3230
+ }
3231
+
3232
+ Object.defineProperty(event, 'clientAddress', {
3233
+ value: state.getClientAddress()
3234
+ });
3235
+
3236
+ return event.clientAddress;
3237
+ },
3238
+ locals: {},
3239
+ params,
3240
+ platform: state.platform,
3241
+ request,
3242
+ routeId: route && route.id,
3243
+ url
3244
+ };
3245
+
3246
+ // TODO remove this for 1.0
3247
+ /**
3248
+ * @param {string} property
3249
+ * @param {string} replacement
3250
+ * @param {string} suffix
3251
+ */
3252
+ const removed = (property, replacement, suffix = '') => ({
3253
+ get: () => {
3254
+ throw new Error(`event.${property} has been replaced by event.${replacement}` + suffix);
3255
+ }
3256
+ });
3257
+
3258
+ const details = '. See https://github.com/sveltejs/kit/pull/3384 for details';
3259
+
3260
+ const body_getter = {
3261
+ get: () => {
3262
+ throw new Error(
3263
+ 'To access the request body use the text/json/arrayBuffer/formData methods, e.g. `body = await request.json()`' +
3264
+ details
3265
+ );
3266
+ }
3267
+ };
3268
+
3269
+ Object.defineProperties(event, {
3270
+ method: removed('method', 'request.method', details),
3271
+ headers: removed('headers', 'request.headers', details),
3272
+ origin: removed('origin', 'url.origin'),
3273
+ path: removed('path', 'url.pathname'),
3274
+ query: removed('query', 'url.searchParams'),
3275
+ body: body_getter,
3276
+ rawBody: body_getter
3277
+ });
3278
+
3279
+ /** @type {import('types').RequiredResolveOptions} */
3280
+ let resolve_opts = {
3281
+ ssr: true,
3282
+ transformPage: default_transform
3283
+ };
3284
+
3285
+ // TODO match route before calling handle?
3286
+
3287
+ try {
3288
+ const response = await options.hooks.handle({
3289
+ event,
3290
+ resolve: async (event, opts) => {
3291
+ if (opts) {
3292
+ resolve_opts = {
3293
+ ssr: opts.ssr !== false,
3294
+ transformPage: opts.transformPage || default_transform
3295
+ };
3296
+ }
3297
+
3298
+ if (state.prerendering?.fallback) {
3299
+ return await render_response({
3300
+ event,
3301
+ options,
3302
+ state,
3303
+ $session: await options.hooks.getSession(event),
3304
+ page_config: { router: true, hydrate: true },
3305
+ stuff: {},
3306
+ status: 200,
3307
+ error: null,
3308
+ branch: [],
3309
+ resolve_opts: {
3310
+ ...resolve_opts,
3311
+ ssr: false
3312
+ }
3313
+ });
3314
+ }
3315
+
3316
+ if (route) {
3317
+ /** @type {Response} */
3318
+ let response;
3319
+
3320
+ if (is_data_request && route.type === 'page' && route.shadow) {
3321
+ response = await render_endpoint(event, await route.shadow(), options);
3322
+
3323
+ // loading data for a client-side transition is a special case
3324
+ if (request.headers.has('x-sveltekit-load')) {
3325
+ // since redirects are opaque to the browser, we need to repackage
3326
+ // 3xx responses as 200s with a custom header
3327
+ if (response.status >= 300 && response.status < 400) {
3328
+ const location = response.headers.get('location');
3329
+
3330
+ if (location) {
3331
+ const headers = new Headers(response.headers);
3332
+ headers.set('x-sveltekit-location', location);
3333
+ response = new Response(undefined, {
3334
+ status: 204,
3335
+ headers
3336
+ });
3337
+ }
3338
+ }
3339
+ }
3340
+ } else {
3341
+ response =
3342
+ route.type === 'endpoint'
3343
+ ? await render_endpoint(event, await route.load(), options)
3344
+ : await render_page(event, route, options, state, resolve_opts);
3345
+ }
3346
+
3347
+ if (response) {
3348
+ // respond with 304 if etag matches
3349
+ if (response.status === 200 && response.headers.has('etag')) {
3350
+ let if_none_match_value = request.headers.get('if-none-match');
3351
+
3352
+ // ignore W/ prefix https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/If-None-Match#directives
3353
+ if (if_none_match_value?.startsWith('W/"')) {
3354
+ if_none_match_value = if_none_match_value.substring(2);
3355
+ }
3356
+
3357
+ const etag = /** @type {string} */ (response.headers.get('etag'));
3358
+
3359
+ if (if_none_match_value === etag) {
3360
+ const headers = new Headers({ etag });
3361
+
3362
+ // https://datatracker.ietf.org/doc/html/rfc7232#section-4.1
3363
+ for (const key of [
3364
+ 'cache-control',
3365
+ 'content-location',
3366
+ 'date',
3367
+ 'expires',
3368
+ 'vary'
3369
+ ]) {
3370
+ const value = response.headers.get(key);
3371
+ if (value) headers.set(key, value);
3372
+ }
3373
+
3374
+ return new Response(undefined, {
3375
+ status: 304,
3376
+ headers
3377
+ });
3378
+ }
3379
+ }
3380
+
3381
+ return response;
3382
+ }
3383
+ }
3384
+
3385
+ // if this request came direct from the user, rather than
3386
+ // via a `fetch` in a `load`, render a 404 page
3387
+ if (!state.initiator) {
3388
+ const $session = await options.hooks.getSession(event);
3389
+ return await respond_with_error({
3390
+ event,
3391
+ options,
3392
+ state,
3393
+ $session,
3394
+ status: 404,
3395
+ error: new Error(`Not found: ${event.url.pathname}`),
3396
+ resolve_opts
3397
+ });
3398
+ }
3399
+
3400
+ if (state.prerendering) {
3401
+ return new Response('not found', { status: 404 });
3402
+ }
3403
+
3404
+ // we can't load the endpoint from our own manifest,
3405
+ // so we need to make an actual HTTP request
3406
+ return await fetch(request);
3407
+ },
3408
+
3409
+ // TODO remove for 1.0
3410
+ // @ts-expect-error
3411
+ get request() {
3412
+ throw new Error('request in handle has been replaced with event' + details);
3413
+ }
3414
+ });
3415
+
3416
+ // TODO for 1.0, change the error message to point to docs rather than PR
3417
+ if (response && !(response instanceof Response)) {
3418
+ throw new Error('handle must return a Response object' + details);
3419
+ }
3420
+
3421
+ return response;
3422
+ } catch (/** @type {unknown} */ e) {
3423
+ const error = coalesce_to_error(e);
3424
+
3425
+ options.handle_error(error, event);
3426
+
3427
+ const type = negotiate(event.request.headers.get('accept') || 'text/html', [
3428
+ 'text/html',
3429
+ 'application/json'
3430
+ ]);
3431
+
3432
+ if (is_data_request || type === 'application/json') {
3433
+ return new Response(serialize_error(error, options.get_stack), {
3434
+ status: 500,
3435
+ headers: { 'content-type': 'application/json; charset=utf-8' }
3436
+ });
3437
+ }
3438
+
3439
+ try {
3440
+ const $session = await options.hooks.getSession(event);
3441
+ return await respond_with_error({
3442
+ event,
3443
+ options,
3444
+ state,
3445
+ $session,
3446
+ status: 500,
3447
+ error,
3448
+ resolve_opts
3449
+ });
3450
+ } catch (/** @type {unknown} */ e) {
3451
+ const error = coalesce_to_error(e);
3452
+
3453
+ return new Response(options.dev ? error.stack : error.message, {
3454
+ status: 500
3455
+ });
3456
+ }
3457
+ }
3458
+ }
3459
+
3460
+ export { respond };