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

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