@sveltejs/kit 1.0.0-next.47 → 1.0.0-next.472

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 (117) hide show
  1. package/README.md +12 -9
  2. package/package.json +93 -64
  3. package/scripts/special-types/$env+dynamic+private.md +8 -0
  4. package/scripts/special-types/$env+dynamic+public.md +8 -0
  5. package/scripts/special-types/$env+static+private.md +19 -0
  6. package/scripts/special-types/$env+static+public.md +7 -0
  7. package/scripts/special-types/$lib.md +1 -0
  8. package/src/cli.js +112 -0
  9. package/src/constants.js +7 -0
  10. package/src/core/adapt/builder.js +207 -0
  11. package/src/core/adapt/index.js +31 -0
  12. package/src/core/config/default-error.html +56 -0
  13. package/src/core/config/index.js +105 -0
  14. package/src/core/config/options.js +492 -0
  15. package/src/core/config/types.d.ts +1 -0
  16. package/src/core/env.js +121 -0
  17. package/src/core/generate_manifest/index.js +92 -0
  18. package/src/core/prerender/crawl.js +194 -0
  19. package/src/core/prerender/prerender.js +431 -0
  20. package/src/core/prerender/queue.js +80 -0
  21. package/src/core/sync/create_manifest_data/index.js +472 -0
  22. package/src/core/sync/create_manifest_data/types.d.ts +37 -0
  23. package/src/core/sync/sync.js +59 -0
  24. package/src/core/sync/utils.js +33 -0
  25. package/src/core/sync/write_ambient.js +53 -0
  26. package/src/core/sync/write_client_manifest.js +94 -0
  27. package/src/core/sync/write_matchers.js +25 -0
  28. package/src/core/sync/write_root.js +91 -0
  29. package/src/core/sync/write_tsconfig.js +195 -0
  30. package/src/core/sync/write_types/index.js +673 -0
  31. package/src/core/utils.js +70 -0
  32. package/src/exports/hooks/index.js +1 -0
  33. package/src/exports/hooks/sequence.js +44 -0
  34. package/src/exports/index.js +54 -0
  35. package/src/exports/node/index.js +145 -0
  36. package/src/exports/node/polyfills.js +41 -0
  37. package/src/exports/vite/build/build_server.js +357 -0
  38. package/src/exports/vite/build/build_service_worker.js +90 -0
  39. package/src/exports/vite/build/utils.js +162 -0
  40. package/src/exports/vite/dev/index.js +554 -0
  41. package/src/exports/vite/index.js +591 -0
  42. package/src/exports/vite/preview/index.js +186 -0
  43. package/src/exports/vite/types.d.ts +3 -0
  44. package/src/exports/vite/utils.js +361 -0
  45. package/src/runtime/app/env.js +1 -0
  46. package/src/runtime/app/environment.js +11 -0
  47. package/src/runtime/app/forms.js +65 -0
  48. package/src/runtime/app/navigation.js +23 -0
  49. package/src/runtime/app/paths.js +1 -0
  50. package/src/runtime/app/stores.js +102 -0
  51. package/src/runtime/client/ambient.d.ts +24 -0
  52. package/src/runtime/client/client.js +1558 -0
  53. package/src/runtime/client/fetcher.js +107 -0
  54. package/src/runtime/client/parse.js +60 -0
  55. package/src/runtime/client/singletons.js +21 -0
  56. package/src/runtime/client/start.js +37 -0
  57. package/src/runtime/client/types.d.ts +87 -0
  58. package/src/runtime/client/utils.js +159 -0
  59. package/src/runtime/components/error.svelte +16 -0
  60. package/{assets → src/runtime}/components/layout.svelte +0 -0
  61. package/src/runtime/control.js +100 -0
  62. package/src/runtime/env/dynamic/private.js +1 -0
  63. package/src/runtime/env/dynamic/public.js +1 -0
  64. package/src/runtime/env-private.js +6 -0
  65. package/src/runtime/env-public.js +6 -0
  66. package/src/runtime/env.js +6 -0
  67. package/src/runtime/hash.js +16 -0
  68. package/src/runtime/paths.js +11 -0
  69. package/src/runtime/server/cookie.js +76 -0
  70. package/src/runtime/server/data/index.js +146 -0
  71. package/src/runtime/server/endpoint.js +66 -0
  72. package/src/runtime/server/index.js +339 -0
  73. package/src/runtime/server/page/actions.js +225 -0
  74. package/src/runtime/server/page/crypto.js +239 -0
  75. package/src/runtime/server/page/csp.js +249 -0
  76. package/src/runtime/server/page/fetch.js +286 -0
  77. package/src/runtime/server/page/index.js +308 -0
  78. package/src/runtime/server/page/load_data.js +124 -0
  79. package/src/runtime/server/page/render.js +359 -0
  80. package/src/runtime/server/page/respond_with_error.js +92 -0
  81. package/src/runtime/server/page/serialize_data.js +87 -0
  82. package/src/runtime/server/page/types.d.ts +41 -0
  83. package/src/runtime/server/utils.js +220 -0
  84. package/src/utils/array.js +9 -0
  85. package/src/utils/error.js +22 -0
  86. package/src/utils/escape.js +46 -0
  87. package/src/utils/filesystem.js +108 -0
  88. package/src/utils/functions.js +16 -0
  89. package/src/utils/http.js +55 -0
  90. package/src/utils/misc.js +1 -0
  91. package/src/utils/routing.js +117 -0
  92. package/src/utils/url.js +142 -0
  93. package/svelte-kit.js +1 -1
  94. package/types/ambient.d.ts +404 -0
  95. package/types/index.d.ts +396 -0
  96. package/types/internal.d.ts +377 -0
  97. package/types/private.d.ts +210 -0
  98. package/CHANGELOG.md +0 -463
  99. package/assets/components/error.svelte +0 -13
  100. package/assets/runtime/app/env.js +0 -5
  101. package/assets/runtime/app/navigation.js +0 -44
  102. package/assets/runtime/app/paths.js +0 -1
  103. package/assets/runtime/app/stores.js +0 -93
  104. package/assets/runtime/chunks/utils.js +0 -22
  105. package/assets/runtime/internal/singletons.js +0 -23
  106. package/assets/runtime/internal/start.js +0 -773
  107. package/assets/runtime/paths.js +0 -12
  108. package/dist/chunks/index.js +0 -3517
  109. package/dist/chunks/index2.js +0 -587
  110. package/dist/chunks/index3.js +0 -246
  111. package/dist/chunks/index4.js +0 -530
  112. package/dist/chunks/index5.js +0 -763
  113. package/dist/chunks/index6.js +0 -322
  114. package/dist/chunks/standard.js +0 -99
  115. package/dist/chunks/utils.js +0 -83
  116. package/dist/cli.js +0 -553
  117. package/dist/ssr.js +0 -2581
@@ -0,0 +1,76 @@
1
+ import * as cookie from 'cookie';
2
+
3
+ /**
4
+ * @param {Request} request
5
+ * @param {URL} url
6
+ */
7
+ export function get_cookies(request, url) {
8
+ const initial_cookies = cookie.parse(request.headers.get('cookie') ?? '');
9
+
10
+ /** @type {Array<{ name: string, value: string, options: import('cookie').CookieSerializeOptions }>} */
11
+ const new_cookies = [];
12
+
13
+ /** @type {import('types').Cookies} */
14
+ const cookies = {
15
+ get(name, opts) {
16
+ const decode = opts?.decode || decodeURIComponent;
17
+
18
+ let i = new_cookies.length;
19
+ while (i--) {
20
+ const cookie = new_cookies[i];
21
+
22
+ if (
23
+ cookie.name === name &&
24
+ domain_matches(url.hostname, cookie.options.domain) &&
25
+ path_matches(url.pathname, cookie.options.path)
26
+ ) {
27
+ return cookie.value;
28
+ }
29
+ }
30
+
31
+ return name in initial_cookies ? decode(initial_cookies[name]) : undefined;
32
+ },
33
+ set(name, value, options = {}) {
34
+ new_cookies.push({
35
+ name,
36
+ value,
37
+ options: {
38
+ httpOnly: true,
39
+ secure: true,
40
+ ...options
41
+ }
42
+ });
43
+ },
44
+ delete(name) {
45
+ new_cookies.push({ name, value: '', options: { expires: new Date(0) } });
46
+ }
47
+ };
48
+
49
+ return { cookies, new_cookies };
50
+ }
51
+
52
+ /**
53
+ * @param {string} hostname
54
+ * @param {string} [constraint]
55
+ */
56
+ export function domain_matches(hostname, constraint) {
57
+ if (!constraint) return true;
58
+
59
+ const normalized = constraint[0] === '.' ? constraint.slice(1) : constraint;
60
+
61
+ if (hostname === normalized) return true;
62
+ return hostname.endsWith('.' + normalized);
63
+ }
64
+
65
+ /**
66
+ * @param {string} path
67
+ * @param {string} [constraint]
68
+ */
69
+ export function path_matches(path, constraint) {
70
+ if (!constraint) return true;
71
+
72
+ const normalized = constraint.endsWith('/') ? constraint.slice(0, -1) : constraint;
73
+
74
+ if (path === normalized) return true;
75
+ return path.startsWith(normalized + '/');
76
+ }
@@ -0,0 +1,146 @@
1
+ import { HttpError, Redirect } from '../../control.js';
2
+ import { normalize_error } from '../../../utils/error.js';
3
+ import { once } from '../../../utils/functions.js';
4
+ import { load_server_data } from '../page/load_data.js';
5
+ import { data_response, error_to_pojo } from '../utils.js';
6
+ import { normalize_path } from '../../../utils/url.js';
7
+ import { DATA_SUFFIX } from '../../../constants.js';
8
+
9
+ /**
10
+ * @param {import('types').RequestEvent} event
11
+ * @param {import('types').SSRRoute} route
12
+ * @param {import('types').SSROptions} options
13
+ * @param {import('types').SSRState} state
14
+ * @returns {Promise<Response>}
15
+ */
16
+ export async function render_data(event, route, options, state) {
17
+ if (!route.page) {
18
+ // requesting /__data.js should fail for a +server.js
19
+ return new Response(undefined, {
20
+ status: 404
21
+ });
22
+ }
23
+
24
+ try {
25
+ const node_ids = [...route.page.layouts, route.page.leaf];
26
+
27
+ const invalidated =
28
+ event.url.searchParams
29
+ .get('__invalid')
30
+ ?.split('')
31
+ .map((x) => x === 'y') ?? node_ids.map(() => true);
32
+
33
+ let aborted = false;
34
+
35
+ const url = new URL(event.url);
36
+ url.pathname = normalize_path(
37
+ url.pathname.slice(0, -DATA_SUFFIX.length),
38
+ options.trailing_slash
39
+ );
40
+
41
+ url.searchParams.delete('__invalid');
42
+ url.searchParams.delete('__id');
43
+
44
+ const new_event = { ...event, url };
45
+
46
+ const functions = node_ids.map((n, i) => {
47
+ return once(async () => {
48
+ try {
49
+ if (aborted) {
50
+ return /** @type {import('types').ServerDataSkippedNode} */ ({
51
+ type: 'skip'
52
+ });
53
+ }
54
+
55
+ // == because it could be undefined (in dev) or null (in build, because of JSON.stringify)
56
+ const node = n == undefined ? n : await options.manifest._.nodes[n]();
57
+ return load_server_data({
58
+ event: new_event,
59
+ state,
60
+ node,
61
+ parent: async () => {
62
+ /** @type {Record<string, any>} */
63
+ const data = {};
64
+ for (let j = 0; j < i; j += 1) {
65
+ const parent = /** @type {import('types').ServerDataNode | null} */ (
66
+ await functions[j]()
67
+ );
68
+
69
+ if (parent) {
70
+ Object.assign(data, parent.data);
71
+ }
72
+ }
73
+ return data;
74
+ }
75
+ });
76
+ } catch (e) {
77
+ aborted = true;
78
+ throw e;
79
+ }
80
+ });
81
+ });
82
+
83
+ const promises = functions.map(async (fn, i) => {
84
+ if (!invalidated[i]) {
85
+ return /** @type {import('types').ServerDataSkippedNode} */ ({
86
+ type: 'skip'
87
+ });
88
+ }
89
+
90
+ return fn();
91
+ });
92
+
93
+ let length = promises.length;
94
+ const nodes = await Promise.all(
95
+ promises.map((p, i) =>
96
+ p.catch((e) => {
97
+ const error = normalize_error(e);
98
+
99
+ if (error instanceof Redirect) {
100
+ throw error;
101
+ }
102
+
103
+ // Math.min because array isn't guaranteed to resolve in order
104
+ length = Math.min(length, i + 1);
105
+
106
+ if (error instanceof HttpError) {
107
+ return /** @type {import('types').ServerErrorNode} */ ({
108
+ type: 'error',
109
+ httperror: { ...error }
110
+ });
111
+ }
112
+
113
+ options.handle_error(error, event);
114
+
115
+ return /** @type {import('types').ServerErrorNode} */ ({
116
+ type: 'error',
117
+ error: error_to_pojo(error, options.get_stack)
118
+ });
119
+ })
120
+ )
121
+ );
122
+
123
+ /** @type {import('types').ServerData} */
124
+ const server_data = {
125
+ type: 'data',
126
+ nodes: nodes.slice(0, length)
127
+ };
128
+
129
+ return data_response(server_data);
130
+ } catch (e) {
131
+ const error = normalize_error(e);
132
+
133
+ if (error instanceof Redirect) {
134
+ /** @type {import('types').ServerData} */
135
+ const server_data = {
136
+ type: 'redirect',
137
+ location: error.location
138
+ };
139
+
140
+ return data_response(server_data);
141
+ } else {
142
+ // TODO make it clearer that this was an unexpected error
143
+ return data_response(error_to_pojo(error, options.get_stack));
144
+ }
145
+ }
146
+ }
@@ -0,0 +1,66 @@
1
+ import { json } from '../../exports/index.js';
2
+ import { Redirect, ValidationError } from '../control.js';
3
+ import { check_method_names, method_not_allowed } from './utils.js';
4
+
5
+ /**
6
+ * @param {import('types').RequestEvent} event
7
+ * @param {import('types').SSREndpoint} mod
8
+ * @param {import('types').SSRState} state
9
+ * @returns {Promise<Response>}
10
+ */
11
+ export async function render_endpoint(event, mod, state) {
12
+ const method = /** @type {import('types').HttpMethod} */ (event.request.method);
13
+
14
+ // TODO: Remove for 1.0
15
+ check_method_names(mod);
16
+
17
+ let handler = mod[method];
18
+
19
+ if (!handler && method === 'HEAD') {
20
+ handler = mod.GET;
21
+ }
22
+
23
+ if (!handler) {
24
+ return method_not_allowed(mod, method);
25
+ }
26
+
27
+ const prerender = mod.prerender ?? state.prerender_default;
28
+
29
+ if (prerender && (mod.POST || mod.PATCH || mod.PUT || mod.DELETE)) {
30
+ throw new Error('Cannot prerender endpoints that have mutative methods');
31
+ }
32
+
33
+ if (state.prerendering && !prerender) {
34
+ throw new Error(`${event.routeId} is not prerenderable`);
35
+ }
36
+
37
+ try {
38
+ const response = await handler(
39
+ /** @type {import('types').RequestEvent<Record<string, any>>} */ (event)
40
+ );
41
+
42
+ if (!(response instanceof Response)) {
43
+ throw new Error(
44
+ `Invalid response from route ${event.url.pathname}: handler should return a Response object`
45
+ );
46
+ }
47
+
48
+ if (state.prerendering) {
49
+ response.headers.set('x-sveltekit-routeid', /** @type {string} */ (event.routeId));
50
+ response.headers.set('x-sveltekit-prerender', String(prerender));
51
+ }
52
+
53
+ return response;
54
+ } catch (error) {
55
+ if (error instanceof Redirect) {
56
+ return new Response(undefined, {
57
+ status: error.status,
58
+ headers: { location: error.location }
59
+ });
60
+ } else if (error instanceof ValidationError) {
61
+ return json(error.data, { status: error.status });
62
+ }
63
+
64
+ throw error;
65
+ }
66
+ }
@@ -0,0 +1,339 @@
1
+ import * as cookie from 'cookie';
2
+ import { render_endpoint } from './endpoint.js';
3
+ import { render_page } from './page/index.js';
4
+ import { render_response } from './page/render.js';
5
+ import { respond_with_error } from './page/respond_with_error.js';
6
+ import { coalesce_to_error } from '../../utils/error.js';
7
+ import { GENERIC_ERROR, handle_fatal_error } from './utils.js';
8
+ import { decode_params, disable_search, normalize_path } from '../../utils/url.js';
9
+ import { exec } from '../../utils/routing.js';
10
+ import { render_data } from './data/index.js';
11
+ import { DATA_SUFFIX } from '../../constants.js';
12
+ import { get_cookies } from './cookie.js';
13
+
14
+ /* global __SVELTEKIT_ADAPTER_NAME__ */
15
+
16
+ /** @param {{ html: string }} opts */
17
+ const default_transform = ({ html }) => html;
18
+
19
+ const default_filter = () => false;
20
+
21
+ /** @type {import('types').Respond} */
22
+ export async function respond(request, options, state) {
23
+ let url = new URL(request.url);
24
+
25
+ if (options.csrf.check_origin) {
26
+ const type = request.headers.get('content-type')?.split(';')[0];
27
+
28
+ const forbidden =
29
+ request.method === 'POST' &&
30
+ request.headers.get('origin') !== url.origin &&
31
+ (type === 'application/x-www-form-urlencoded' || type === 'multipart/form-data');
32
+
33
+ if (forbidden) {
34
+ return new Response(`Cross-site ${request.method} form submissions are forbidden`, {
35
+ status: 403
36
+ });
37
+ }
38
+ }
39
+
40
+ let decoded;
41
+ try {
42
+ decoded = decodeURI(url.pathname);
43
+ } catch {
44
+ return new Response('Malformed URI', { status: 400 });
45
+ }
46
+
47
+ /** @type {import('types').SSRRoute | null} */
48
+ let route = null;
49
+
50
+ /** @type {Record<string, string>} */
51
+ let params = {};
52
+
53
+ if (options.paths.base && !state.prerendering?.fallback) {
54
+ if (!decoded.startsWith(options.paths.base)) {
55
+ return new Response('Not found', { status: 404 });
56
+ }
57
+ decoded = decoded.slice(options.paths.base.length) || '/';
58
+ }
59
+
60
+ const is_data_request = decoded.endsWith(DATA_SUFFIX);
61
+ if (is_data_request) decoded = decoded.slice(0, -DATA_SUFFIX.length) || '/';
62
+
63
+ if (!state.prerendering?.fallback) {
64
+ const matchers = await options.manifest._.matchers();
65
+
66
+ for (const candidate of options.manifest._.routes) {
67
+ const match = candidate.pattern.exec(decoded);
68
+ if (!match) continue;
69
+
70
+ const matched = exec(match, candidate.names, candidate.types, matchers);
71
+ if (matched) {
72
+ route = candidate;
73
+ params = decode_params(matched);
74
+ break;
75
+ }
76
+ }
77
+ }
78
+
79
+ if (route?.page && !is_data_request) {
80
+ const normalized = normalize_path(url.pathname, options.trailing_slash);
81
+
82
+ if (normalized !== url.pathname && !state.prerendering?.fallback) {
83
+ return new Response(undefined, {
84
+ status: 301,
85
+ headers: {
86
+ 'x-sveltekit-normalize': '1',
87
+ location:
88
+ // ensure paths starting with '//' are not treated as protocol-relative
89
+ (normalized.startsWith('//') ? url.origin + normalized : normalized) +
90
+ (url.search === '?' ? '' : url.search)
91
+ }
92
+ });
93
+ }
94
+ }
95
+
96
+ /** @type {Record<string, string>} */
97
+ const headers = {};
98
+
99
+ const { cookies, new_cookies } = get_cookies(request, url);
100
+
101
+ if (state.prerendering) disable_search(url);
102
+
103
+ /** @type {import('types').RequestEvent} */
104
+ const event = {
105
+ cookies,
106
+ getClientAddress:
107
+ state.getClientAddress ||
108
+ (() => {
109
+ throw new Error(
110
+ `${__SVELTEKIT_ADAPTER_NAME__} does not specify getClientAddress. Please raise an issue`
111
+ );
112
+ }),
113
+ locals: {},
114
+ params,
115
+ platform: state.platform,
116
+ request,
117
+ routeId: route && route.id,
118
+ setHeaders: (new_headers) => {
119
+ for (const key in new_headers) {
120
+ const lower = key.toLowerCase();
121
+ const value = new_headers[key];
122
+
123
+ if (lower === 'set-cookie') {
124
+ throw new Error(
125
+ `Use \`event.cookie.set(name, value, options)\` instead of \`event.setHeaders\` to set cookies`
126
+ );
127
+ } else if (lower in headers) {
128
+ throw new Error(`"${key}" header is already set`);
129
+ } else {
130
+ headers[lower] = value;
131
+
132
+ if (state.prerendering && lower === 'cache-control') {
133
+ state.prerendering.cache = /** @type {string} */ (value);
134
+ }
135
+ }
136
+ }
137
+ },
138
+ url
139
+ };
140
+
141
+ // TODO remove this for 1.0
142
+ /**
143
+ * @param {string} property
144
+ * @param {string} replacement
145
+ * @param {string} suffix
146
+ */
147
+ const removed = (property, replacement, suffix = '') => ({
148
+ get: () => {
149
+ throw new Error(`event.${property} has been replaced by event.${replacement}` + suffix);
150
+ }
151
+ });
152
+
153
+ const details = '. See https://github.com/sveltejs/kit/pull/3384 for details';
154
+
155
+ const body_getter = {
156
+ get: () => {
157
+ throw new Error(
158
+ 'To access the request body use the text/json/arrayBuffer/formData methods, e.g. `body = await request.json()`' +
159
+ details
160
+ );
161
+ }
162
+ };
163
+
164
+ Object.defineProperties(event, {
165
+ clientAddress: removed('clientAddress', 'getClientAddress'),
166
+ method: removed('method', 'request.method', details),
167
+ headers: removed('headers', 'request.headers', details),
168
+ origin: removed('origin', 'url.origin'),
169
+ path: removed('path', 'url.pathname'),
170
+ query: removed('query', 'url.searchParams'),
171
+ body: body_getter,
172
+ rawBody: body_getter
173
+ });
174
+
175
+ /** @type {import('types').RequiredResolveOptions} */
176
+ let resolve_opts = {
177
+ transformPageChunk: default_transform,
178
+ filterSerializedResponseHeaders: default_filter
179
+ };
180
+
181
+ /**
182
+ *
183
+ * @param {import('types').RequestEvent} event
184
+ * @param {import('types').ResolveOptions} [opts]
185
+ */
186
+ async function resolve(event, opts) {
187
+ try {
188
+ if (opts) {
189
+ // TODO remove for 1.0
190
+ if ('transformPage' in opts) {
191
+ throw new Error(
192
+ 'transformPage has been replaced by transformPageChunk — see https://github.com/sveltejs/kit/pull/5657 for more information'
193
+ );
194
+ }
195
+
196
+ if ('ssr' in opts) {
197
+ throw new Error(
198
+ 'ssr has been removed, set it in the appropriate +layout.js instead. See the PR for more information: https://github.com/sveltejs/kit/pull/6197'
199
+ );
200
+ }
201
+
202
+ resolve_opts = {
203
+ transformPageChunk: opts.transformPageChunk || default_transform,
204
+ filterSerializedResponseHeaders: opts.filterSerializedResponseHeaders || default_filter
205
+ };
206
+ }
207
+
208
+ if (state.prerendering?.fallback) {
209
+ return await render_response({
210
+ event,
211
+ options,
212
+ state,
213
+ page_config: { ssr: false, csr: true },
214
+ status: 200,
215
+ error: null,
216
+ branch: [],
217
+ fetched: [],
218
+ cookies: [],
219
+ resolve_opts
220
+ });
221
+ }
222
+
223
+ if (route) {
224
+ /** @type {Response} */
225
+ let response;
226
+
227
+ if (is_data_request) {
228
+ response = await render_data(event, route, options, state);
229
+ } else if (route.page) {
230
+ response = await render_page(event, route, route.page, options, state, resolve_opts);
231
+ } else if (route.endpoint) {
232
+ response = await render_endpoint(event, await route.endpoint(), state);
233
+ } else {
234
+ // a route will always have a page or an endpoint, but TypeScript
235
+ // doesn't know that
236
+ throw new Error('This should never happen');
237
+ }
238
+
239
+ if (!is_data_request) {
240
+ // we only want to set cookies on __data.js requests, we don't
241
+ // want to cache stuff erroneously etc
242
+ for (const key in headers) {
243
+ const value = headers[key];
244
+ response.headers.set(key, /** @type {string} */ (value));
245
+ }
246
+ }
247
+
248
+ for (const new_cookie of new_cookies) {
249
+ response.headers.append(
250
+ 'set-cookie',
251
+ cookie.serialize(new_cookie.name, new_cookie.value, new_cookie.options)
252
+ );
253
+ }
254
+
255
+ // respond with 304 if etag matches
256
+ if (response.status === 200 && response.headers.has('etag')) {
257
+ let if_none_match_value = request.headers.get('if-none-match');
258
+
259
+ // ignore W/ prefix https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/If-None-Match#directives
260
+ if (if_none_match_value?.startsWith('W/"')) {
261
+ if_none_match_value = if_none_match_value.substring(2);
262
+ }
263
+
264
+ const etag = /** @type {string} */ (response.headers.get('etag'));
265
+
266
+ if (if_none_match_value === etag) {
267
+ const headers = new Headers({ etag });
268
+
269
+ // https://datatracker.ietf.org/doc/html/rfc7232#section-4.1
270
+ for (const key of ['cache-control', 'content-location', 'date', 'expires', 'vary']) {
271
+ const value = response.headers.get(key);
272
+ if (value) headers.set(key, value);
273
+ }
274
+
275
+ return new Response(undefined, {
276
+ status: 304,
277
+ headers
278
+ });
279
+ }
280
+ }
281
+
282
+ return response;
283
+ }
284
+
285
+ if (state.initiator === GENERIC_ERROR) {
286
+ return new Response('Internal Server Error', {
287
+ status: 500
288
+ });
289
+ }
290
+
291
+ // if this request came direct from the user, rather than
292
+ // via a `fetch` in a `load`, render a 404 page
293
+ if (!state.initiator) {
294
+ return await respond_with_error({
295
+ event,
296
+ options,
297
+ state,
298
+ status: 404,
299
+ error: new Error(`Not found: ${event.url.pathname}`),
300
+ resolve_opts
301
+ });
302
+ }
303
+
304
+ if (state.prerendering) {
305
+ return new Response('not found', { status: 404 });
306
+ }
307
+
308
+ // we can't load the endpoint from our own manifest,
309
+ // so we need to make an actual HTTP request
310
+ return await fetch(request);
311
+ } catch (e) {
312
+ const error = coalesce_to_error(e);
313
+ return handle_fatal_error(event, options, error);
314
+ } finally {
315
+ event.cookies.set = () => {
316
+ throw new Error('Cannot use `cookies.set(...)` after the response has been generated');
317
+ };
318
+
319
+ event.setHeaders = () => {
320
+ throw new Error('Cannot use `setHeaders(...)` after the response has been generated');
321
+ };
322
+ }
323
+ }
324
+
325
+ try {
326
+ return await options.hooks.handle({
327
+ event,
328
+ resolve,
329
+ // TODO remove for 1.0
330
+ // @ts-expect-error
331
+ get request() {
332
+ throw new Error('request in handle has been replaced with event' + details);
333
+ }
334
+ });
335
+ } catch (/** @type {unknown} */ e) {
336
+ const error = coalesce_to_error(e);
337
+ return handle_fatal_error(event, options, error);
338
+ }
339
+ }