@sveltejs/kit 1.0.0-next.99 → 1.0.1

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 (141) hide show
  1. package/README.md +5 -1
  2. package/package.json +91 -77
  3. package/postinstall.js +47 -0
  4. package/src/cli.js +44 -0
  5. package/src/constants.js +5 -0
  6. package/src/core/adapt/builder.js +221 -0
  7. package/src/core/adapt/index.js +31 -0
  8. package/src/core/config/default-error.html +56 -0
  9. package/src/core/config/index.js +100 -0
  10. package/src/core/config/options.js +387 -0
  11. package/src/core/config/types.d.ts +1 -0
  12. package/src/core/env.js +138 -0
  13. package/src/core/generate_manifest/index.js +116 -0
  14. package/src/core/prerender/crawl.js +207 -0
  15. package/src/core/prerender/entities.js +2252 -0
  16. package/src/core/prerender/fallback.js +43 -0
  17. package/src/core/prerender/prerender.js +459 -0
  18. package/src/core/prerender/queue.js +80 -0
  19. package/src/core/sync/create_manifest_data/conflict.js +0 -0
  20. package/src/core/sync/create_manifest_data/index.js +523 -0
  21. package/src/core/sync/create_manifest_data/sort.js +161 -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 +58 -0
  26. package/src/core/sync/write_client_manifest.js +107 -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 +809 -0
  31. package/src/core/utils.js +67 -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 +55 -0
  35. package/src/exports/node/index.js +172 -0
  36. package/src/exports/node/polyfills.js +28 -0
  37. package/src/exports/vite/build/build_server.js +359 -0
  38. package/src/exports/vite/build/build_service_worker.js +85 -0
  39. package/src/exports/vite/build/utils.js +230 -0
  40. package/src/exports/vite/dev/index.js +597 -0
  41. package/src/exports/vite/graph_analysis/index.js +99 -0
  42. package/src/exports/vite/graph_analysis/types.d.ts +5 -0
  43. package/src/exports/vite/graph_analysis/utils.js +6 -0
  44. package/src/exports/vite/index.js +708 -0
  45. package/src/exports/vite/preview/index.js +194 -0
  46. package/src/exports/vite/types.d.ts +3 -0
  47. package/src/exports/vite/utils.js +184 -0
  48. package/src/runtime/app/env.js +1 -0
  49. package/src/runtime/app/environment.js +13 -0
  50. package/src/runtime/app/forms.js +135 -0
  51. package/src/runtime/app/navigation.js +22 -0
  52. package/src/runtime/app/paths.js +1 -0
  53. package/src/runtime/app/stores.js +57 -0
  54. package/src/runtime/client/ambient.d.ts +30 -0
  55. package/src/runtime/client/client.js +1725 -0
  56. package/src/runtime/client/constants.js +10 -0
  57. package/src/runtime/client/fetcher.js +127 -0
  58. package/src/runtime/client/parse.js +60 -0
  59. package/src/runtime/client/singletons.js +21 -0
  60. package/src/runtime/client/start.js +45 -0
  61. package/src/runtime/client/types.d.ts +86 -0
  62. package/src/runtime/client/utils.js +257 -0
  63. package/src/runtime/components/error.svelte +6 -0
  64. package/{assets → src/runtime}/components/layout.svelte +0 -0
  65. package/src/runtime/control.js +45 -0
  66. package/src/runtime/env/dynamic/private.js +1 -0
  67. package/src/runtime/env/dynamic/public.js +1 -0
  68. package/src/runtime/env-private.js +6 -0
  69. package/src/runtime/env-public.js +6 -0
  70. package/src/runtime/env.js +12 -0
  71. package/src/runtime/hash.js +20 -0
  72. package/src/runtime/paths.js +11 -0
  73. package/src/runtime/server/cookie.js +228 -0
  74. package/src/runtime/server/data/index.js +158 -0
  75. package/src/runtime/server/endpoint.js +86 -0
  76. package/src/runtime/server/fetch.js +175 -0
  77. package/src/runtime/server/index.js +405 -0
  78. package/src/runtime/server/page/actions.js +267 -0
  79. package/src/runtime/server/page/crypto.js +239 -0
  80. package/src/runtime/server/page/csp.js +250 -0
  81. package/src/runtime/server/page/index.js +326 -0
  82. package/src/runtime/server/page/load_data.js +270 -0
  83. package/src/runtime/server/page/render.js +393 -0
  84. package/src/runtime/server/page/respond_with_error.js +103 -0
  85. package/src/runtime/server/page/serialize_data.js +87 -0
  86. package/src/runtime/server/page/types.d.ts +35 -0
  87. package/src/runtime/server/utils.js +179 -0
  88. package/src/utils/array.js +9 -0
  89. package/src/utils/error.js +22 -0
  90. package/src/utils/escape.js +46 -0
  91. package/src/utils/exports.js +54 -0
  92. package/src/utils/filesystem.js +178 -0
  93. package/src/utils/functions.js +16 -0
  94. package/src/utils/http.js +72 -0
  95. package/src/utils/misc.js +1 -0
  96. package/src/utils/promises.js +17 -0
  97. package/src/utils/routing.js +201 -0
  98. package/src/utils/unit_test.js +11 -0
  99. package/src/utils/url.js +161 -0
  100. package/svelte-kit.js +1 -1
  101. package/types/ambient.d.ts +451 -0
  102. package/types/index.d.ts +1168 -5
  103. package/types/internal.d.ts +348 -159
  104. package/types/private.d.ts +237 -0
  105. package/types/synthetic/$env+dynamic+private.md +10 -0
  106. package/types/synthetic/$env+dynamic+public.md +8 -0
  107. package/types/synthetic/$env+static+private.md +19 -0
  108. package/types/synthetic/$env+static+public.md +7 -0
  109. package/types/synthetic/$lib.md +5 -0
  110. package/CHANGELOG.md +0 -825
  111. package/assets/components/error.svelte +0 -21
  112. package/assets/runtime/app/env.js +0 -16
  113. package/assets/runtime/app/navigation.js +0 -53
  114. package/assets/runtime/app/paths.js +0 -1
  115. package/assets/runtime/app/stores.js +0 -87
  116. package/assets/runtime/chunks/utils.js +0 -13
  117. package/assets/runtime/env.js +0 -8
  118. package/assets/runtime/internal/singletons.js +0 -20
  119. package/assets/runtime/internal/start.js +0 -1061
  120. package/assets/runtime/paths.js +0 -12
  121. package/dist/chunks/_commonjsHelpers.js +0 -8
  122. package/dist/chunks/cert.js +0 -29079
  123. package/dist/chunks/constants.js +0 -3
  124. package/dist/chunks/index.js +0 -3532
  125. package/dist/chunks/index2.js +0 -583
  126. package/dist/chunks/index3.js +0 -31
  127. package/dist/chunks/index4.js +0 -1004
  128. package/dist/chunks/index5.js +0 -327
  129. package/dist/chunks/index6.js +0 -325
  130. package/dist/chunks/standard.js +0 -99
  131. package/dist/chunks/utils.js +0 -149
  132. package/dist/cli.js +0 -711
  133. package/dist/http.js +0 -66
  134. package/dist/install-fetch.js +0 -1699
  135. package/dist/ssr.js +0 -1523
  136. package/types/ambient-modules.d.ts +0 -115
  137. package/types/config.d.ts +0 -101
  138. package/types/endpoint.d.ts +0 -23
  139. package/types/helper.d.ts +0 -19
  140. package/types/hooks.d.ts +0 -21
  141. package/types/page.d.ts +0 -30
@@ -0,0 +1,393 @@
1
+ import * as devalue from 'devalue';
2
+ import { readable, writable } from 'svelte/store';
3
+ import { hash } from '../../hash.js';
4
+ import { serialize_data } from './serialize_data.js';
5
+ import { s } from '../../../utils/misc.js';
6
+ import { Csp } from './csp.js';
7
+ import { uneval_action_response } from './actions.js';
8
+ import { clarify_devalue_error } from '../utils.js';
9
+
10
+ // TODO rename this function/module
11
+
12
+ const updated = {
13
+ ...readable(false),
14
+ check: () => false
15
+ };
16
+
17
+ /**
18
+ * Creates the HTML response.
19
+ * @param {{
20
+ * branch: Array<import('./types').Loaded>;
21
+ * fetched: Array<import('./types').Fetched>;
22
+ * options: import('types').SSROptions;
23
+ * state: import('types').SSRState;
24
+ * page_config: { ssr: boolean; csr: boolean };
25
+ * status: number;
26
+ * error: App.Error | null;
27
+ * event: import('types').RequestEvent;
28
+ * resolve_opts: import('types').RequiredResolveOptions;
29
+ * action_result?: import('types').ActionResult;
30
+ * }} opts
31
+ */
32
+ export async function render_response({
33
+ branch,
34
+ fetched,
35
+ options,
36
+ state,
37
+ page_config,
38
+ status,
39
+ error = null,
40
+ event,
41
+ resolve_opts,
42
+ action_result
43
+ }) {
44
+ if (state.prerendering) {
45
+ if (options.csp.mode === 'nonce') {
46
+ throw new Error('Cannot use prerendering if config.kit.csp.mode === "nonce"');
47
+ }
48
+
49
+ if (options.app_template_contains_nonce) {
50
+ throw new Error('Cannot use prerendering if page template contains %sveltekit.nonce%');
51
+ }
52
+ }
53
+
54
+ const { entry } = options.manifest._;
55
+
56
+ const stylesheets = new Set(entry.stylesheets);
57
+ const modulepreloads = new Set(entry.imports);
58
+ const fonts = new Set(options.manifest._.entry.fonts);
59
+
60
+ /** @type {Set<string>} */
61
+ const link_header_preloads = new Set();
62
+
63
+ /** @type {Map<string, string>} */
64
+ // 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
65
+ const inline_styles = new Map();
66
+
67
+ let rendered;
68
+
69
+ const form_value =
70
+ action_result?.type === 'success' || action_result?.type === 'failure'
71
+ ? action_result.data ?? null
72
+ : null;
73
+
74
+ if (page_config.ssr) {
75
+ /** @type {Record<string, any>} */
76
+ const props = {
77
+ stores: {
78
+ page: writable(null),
79
+ navigating: writable(null),
80
+ updated
81
+ },
82
+ components: await Promise.all(branch.map(({ node }) => node.component())),
83
+ form: form_value
84
+ };
85
+
86
+ let data = {};
87
+
88
+ // props_n (instead of props[n]) makes it easy to avoid
89
+ // unnecessary updates for layout components
90
+ for (let i = 0; i < branch.length; i += 1) {
91
+ data = { ...data, ...branch[i].data };
92
+ props[`data_${i}`] = data;
93
+ }
94
+
95
+ props.page = {
96
+ error,
97
+ params: /** @type {Record<string, any>} */ (event.params),
98
+ route: event.route,
99
+ status,
100
+ url: event.url,
101
+ data,
102
+ form: form_value
103
+ };
104
+
105
+ rendered = options.root.render(props);
106
+
107
+ for (const { node } of branch) {
108
+ if (node.imports) {
109
+ node.imports.forEach((url) => modulepreloads.add(url));
110
+ }
111
+
112
+ if (node.stylesheets) {
113
+ node.stylesheets.forEach((url) => stylesheets.add(url));
114
+ }
115
+
116
+ if (node.fonts) {
117
+ node.fonts.forEach((url) => fonts.add(url));
118
+ }
119
+
120
+ if (node.inline_styles) {
121
+ Object.entries(await node.inline_styles()).forEach(([k, v]) => inline_styles.set(k, v));
122
+ }
123
+ }
124
+ } else {
125
+ rendered = { head: '', html: '', css: { code: '', map: null } };
126
+ }
127
+
128
+ let head = '';
129
+ let body = rendered.html;
130
+
131
+ const csp = new Csp(options.csp, {
132
+ dev: options.dev,
133
+ prerender: !!state.prerendering
134
+ });
135
+
136
+ const target = hash(body);
137
+
138
+ /**
139
+ * The prefix to use for static assets. Replaces `%sveltekit.assets%` in the template
140
+ * @type {string}
141
+ */
142
+ let assets;
143
+
144
+ if (options.paths.assets) {
145
+ // if an asset path is specified, use it
146
+ assets = options.paths.assets;
147
+ } else if (state.prerendering?.fallback) {
148
+ // if we're creating a fallback page, asset paths need to be root-relative
149
+ assets = options.paths.base;
150
+ } else {
151
+ // otherwise we want asset paths to be relative to the page, so that they
152
+ // will work in odd contexts like IPFS, the internet archive, and so on
153
+ const segments = event.url.pathname.slice(options.paths.base.length).split('/').slice(2);
154
+ assets = segments.length > 0 ? segments.map(() => '..').join('/') : '.';
155
+ }
156
+
157
+ /** @param {string} path */
158
+ const prefixed = (path) => (path.startsWith('/') ? path : `${assets}/${path}`);
159
+
160
+ const serialized = { data: '', form: 'null' };
161
+
162
+ try {
163
+ serialized.data = `[${branch
164
+ .map(({ server_data }) => {
165
+ if (server_data?.type === 'data') {
166
+ const data = devalue.uneval(server_data.data);
167
+
168
+ const uses = [];
169
+ if (server_data.uses.dependencies.size > 0) {
170
+ uses.push(`dependencies:${s(Array.from(server_data.uses.dependencies))}`);
171
+ }
172
+
173
+ if (server_data.uses.params.size > 0) {
174
+ uses.push(`params:${s(Array.from(server_data.uses.params))}`);
175
+ }
176
+
177
+ if (server_data.uses.parent) uses.push(`parent:1`);
178
+ if (server_data.uses.route) uses.push(`route:1`);
179
+ if (server_data.uses.url) uses.push(`url:1`);
180
+
181
+ return `{type:"data",data:${data},uses:{${uses.join(',')}}${
182
+ server_data.slash ? `,slash:${s(server_data.slash)}` : ''
183
+ }}`;
184
+ }
185
+
186
+ return s(server_data);
187
+ })
188
+ .join(',')}]`;
189
+ } catch (e) {
190
+ const error = /** @type {any} */ (e);
191
+ throw new Error(clarify_devalue_error(event, error));
192
+ }
193
+
194
+ if (form_value) {
195
+ serialized.form = uneval_action_response(form_value, /** @type {string} */ (event.route.id));
196
+ }
197
+
198
+ if (inline_styles.size > 0) {
199
+ const content = Array.from(inline_styles.values()).join('\n');
200
+
201
+ const attributes = [];
202
+ if (options.dev) attributes.push(' data-sveltekit');
203
+ if (csp.style_needs_nonce) attributes.push(` nonce="${csp.nonce}"`);
204
+
205
+ csp.add_style(content);
206
+
207
+ head += `\n\t<style${attributes.join('')}>${content}</style>`;
208
+ }
209
+
210
+ for (const dep of stylesheets) {
211
+ const path = prefixed(dep);
212
+
213
+ if (resolve_opts.preload({ type: 'css', path })) {
214
+ const attributes = [];
215
+
216
+ if (csp.style_needs_nonce) {
217
+ attributes.push(`nonce="${csp.nonce}"`);
218
+ }
219
+
220
+ if (inline_styles.has(dep)) {
221
+ // don't load stylesheets that are already inlined
222
+ // include them in disabled state so that Vite can detect them and doesn't try to add them
223
+ attributes.push('disabled', 'media="(max-width: 0)"');
224
+ } else {
225
+ const preload_atts = ['rel="preload"', 'as="style"'].concat(attributes);
226
+ link_header_preloads.add(`<${encodeURI(path)}>; ${preload_atts.join(';')}; nopush`);
227
+ }
228
+
229
+ attributes.unshift('rel="stylesheet"');
230
+ head += `\n\t\t<link href="${path}" ${attributes.join(' ')}>`;
231
+ }
232
+ }
233
+
234
+ for (const dep of fonts) {
235
+ const path = prefixed(dep);
236
+
237
+ if (resolve_opts.preload({ type: 'font', path })) {
238
+ const ext = dep.slice(dep.lastIndexOf('.') + 1);
239
+ const attributes = [
240
+ 'rel="preload"',
241
+ 'as="font"',
242
+ `type="font/${ext}"`,
243
+ `href="${path}"`,
244
+ 'crossorigin'
245
+ ];
246
+
247
+ head += `\n\t\t<link ${attributes.join(' ')}>`;
248
+ }
249
+ }
250
+
251
+ if (page_config.csr) {
252
+ const opts = [
253
+ `env: ${s(options.public_env)}`,
254
+ `paths: ${s(options.paths)}`,
255
+ `target: document.querySelector('[data-sveltekit-hydrate="${target}"]').parentNode`,
256
+ `version: ${s(options.version)}`
257
+ ];
258
+
259
+ if (page_config.ssr) {
260
+ const hydrate = [
261
+ `node_ids: [${branch.map(({ node }) => node.index).join(', ')}]`,
262
+ `data: ${serialized.data}`,
263
+ `form: ${serialized.form}`
264
+ ];
265
+
266
+ if (status !== 200) {
267
+ hydrate.push(`status: ${status}`);
268
+ }
269
+
270
+ if (error) {
271
+ hydrate.push(`error: ${devalue.uneval(error)}`);
272
+ }
273
+
274
+ if (options.embedded) {
275
+ hydrate.push(`params: ${devalue.uneval(event.params)}`, `route: ${s(event.route)}`);
276
+ }
277
+
278
+ opts.push(`hydrate: {\n\t\t\t\t\t${hydrate.join(',\n\t\t\t\t\t')}\n\t\t\t\t}`);
279
+ }
280
+
281
+ // prettier-ignore
282
+ const init_app = `
283
+ import { start } from ${s(prefixed(entry.file))};
284
+
285
+ start({
286
+ ${opts.join(',\n\t\t\t\t')}
287
+ });
288
+ `;
289
+
290
+ for (const dep of modulepreloads) {
291
+ const path = prefixed(dep);
292
+
293
+ if (resolve_opts.preload({ type: 'js', path })) {
294
+ link_header_preloads.add(`<${encodeURI(path)}>; rel="modulepreload"; nopush`);
295
+ if (state.prerendering) {
296
+ head += `\n\t\t<link rel="modulepreload" href="${path}">`;
297
+ }
298
+ }
299
+ }
300
+
301
+ const attributes = ['type="module"', `data-sveltekit-hydrate="${target}"`];
302
+
303
+ csp.add_script(init_app);
304
+
305
+ if (csp.script_needs_nonce) {
306
+ attributes.push(`nonce="${csp.nonce}"`);
307
+ }
308
+
309
+ body += `\n\t\t<script ${attributes.join(' ')}>${init_app}</script>`;
310
+ }
311
+
312
+ if (page_config.ssr && page_config.csr) {
313
+ body += `\n\t${fetched
314
+ .map((item) =>
315
+ serialize_data(item, resolve_opts.filterSerializedResponseHeaders, !!state.prerendering)
316
+ )
317
+ .join('\n\t')}`;
318
+ }
319
+
320
+ if (options.service_worker) {
321
+ const opts = options.dev ? `, { type: 'module' }` : '';
322
+
323
+ // we use an anonymous function instead of an arrow function to support
324
+ // older browsers (https://github.com/sveltejs/kit/pull/5417)
325
+ const init_service_worker = `
326
+ if ('serviceWorker' in navigator) {
327
+ addEventListener('load', function () {
328
+ navigator.serviceWorker.register('${prefixed('service-worker.js')}'${opts});
329
+ });
330
+ }
331
+ `;
332
+
333
+ // always include service worker unless it's turned off explicitly
334
+ csp.add_script(init_service_worker);
335
+
336
+ head += `
337
+ <script${csp.script_needs_nonce ? ` nonce="${csp.nonce}"` : ''}>${init_service_worker}</script>`;
338
+ }
339
+
340
+ if (state.prerendering) {
341
+ // TODO read headers set with setHeaders and convert into http-equiv where possible
342
+ const http_equiv = [];
343
+
344
+ const csp_headers = csp.csp_provider.get_meta();
345
+ if (csp_headers) {
346
+ http_equiv.push(csp_headers);
347
+ }
348
+
349
+ if (state.prerendering.cache) {
350
+ http_equiv.push(`<meta http-equiv="cache-control" content="${state.prerendering.cache}">`);
351
+ }
352
+
353
+ if (http_equiv.length > 0) {
354
+ head = http_equiv.join('\n') + head;
355
+ }
356
+ }
357
+
358
+ // add the content after the script/css links so the link elements are parsed first
359
+ head += rendered.head;
360
+
361
+ // TODO flush chunks as early as we can
362
+ const html =
363
+ (await resolve_opts.transformPageChunk({
364
+ html: options.app_template({ head, body, assets, nonce: /** @type {string} */ (csp.nonce) }),
365
+ done: true
366
+ })) || '';
367
+
368
+ const headers = new Headers({
369
+ 'x-sveltekit-page': 'true',
370
+ 'content-type': 'text/html',
371
+ etag: `"${hash(html)}"`
372
+ });
373
+
374
+ if (!state.prerendering) {
375
+ const csp_header = csp.csp_provider.get_header();
376
+ if (csp_header) {
377
+ headers.set('content-security-policy', csp_header);
378
+ }
379
+ const report_only_header = csp.report_only_provider.get_header();
380
+ if (report_only_header) {
381
+ headers.set('content-security-policy-report-only', report_only_header);
382
+ }
383
+
384
+ if (link_header_preloads.size) {
385
+ headers.set('link', Array.from(link_header_preloads).join(', '));
386
+ }
387
+ }
388
+
389
+ return new Response(html, {
390
+ status,
391
+ headers
392
+ });
393
+ }
@@ -0,0 +1,103 @@
1
+ import { render_response } from './render.js';
2
+ import { load_data, load_server_data } from './load_data.js';
3
+ import {
4
+ handle_error_and_jsonify,
5
+ get_option,
6
+ static_error_page,
7
+ redirect_response,
8
+ GENERIC_ERROR
9
+ } from '../utils.js';
10
+ import { HttpError, Redirect } from '../../control.js';
11
+
12
+ /**
13
+ * @typedef {import('./types.js').Loaded} Loaded
14
+ * @typedef {import('types').SSROptions} SSROptions
15
+ * @typedef {import('types').SSRState} SSRState
16
+ */
17
+
18
+ /**
19
+ * @param {{
20
+ * event: import('types').RequestEvent;
21
+ * options: SSROptions;
22
+ * state: SSRState;
23
+ * status: number;
24
+ * error: unknown;
25
+ * resolve_opts: import('types').RequiredResolveOptions;
26
+ * }} opts
27
+ */
28
+ export async function respond_with_error({ event, options, state, status, error, resolve_opts }) {
29
+ /** @type {import('./types').Fetched[]} */
30
+ const fetched = [];
31
+
32
+ try {
33
+ const branch = [];
34
+ const default_layout = await options.manifest._.nodes[0](); // 0 is always the root layout
35
+ const ssr = get_option([default_layout], 'ssr') ?? true;
36
+ const csr = get_option([default_layout], 'csr') ?? true;
37
+
38
+ if (ssr) {
39
+ state.initiator = GENERIC_ERROR;
40
+
41
+ const server_data_promise = load_server_data({
42
+ event,
43
+ options,
44
+ state,
45
+ node: default_layout,
46
+ parent: async () => ({})
47
+ });
48
+
49
+ const server_data = await server_data_promise;
50
+
51
+ const data = await load_data({
52
+ event,
53
+ fetched,
54
+ node: default_layout,
55
+ parent: async () => ({}),
56
+ resolve_opts,
57
+ server_data_promise,
58
+ state,
59
+ csr
60
+ });
61
+
62
+ branch.push(
63
+ {
64
+ node: default_layout,
65
+ server_data,
66
+ data
67
+ },
68
+ {
69
+ node: await options.manifest._.nodes[1](), // 1 is always the root error
70
+ data: null,
71
+ server_data: null
72
+ }
73
+ );
74
+ }
75
+
76
+ return await render_response({
77
+ options,
78
+ state,
79
+ page_config: {
80
+ ssr,
81
+ csr: get_option([default_layout], 'csr') ?? true
82
+ },
83
+ status,
84
+ error: await handle_error_and_jsonify(event, options, error),
85
+ branch,
86
+ fetched,
87
+ event,
88
+ resolve_opts
89
+ });
90
+ } catch (error) {
91
+ // Edge case: If route is a 404 and the user redirects to somewhere from the root layout,
92
+ // we end up here.
93
+ if (error instanceof Redirect) {
94
+ return redirect_response(error.status, error.location);
95
+ }
96
+
97
+ return static_error_page(
98
+ options,
99
+ error instanceof HttpError ? error.status : 500,
100
+ (await handle_error_and_jsonify(event, options, error)).message
101
+ );
102
+ }
103
+ }
@@ -0,0 +1,87 @@
1
+ import { escape_html_attr } from '../../../utils/escape.js';
2
+ import { hash } from '../../hash.js';
3
+
4
+ /**
5
+ * Inside a script element, only `</script` and `<!--` hold special meaning to the HTML parser.
6
+ *
7
+ * The first closes the script element, so everything after is treated as raw HTML.
8
+ * The second disables further parsing until `-->`, so the script element might be unexpectedly
9
+ * kept open until until an unrelated HTML comment in the page.
10
+ *
11
+ * U+2028 LINE SEPARATOR and U+2029 PARAGRAPH SEPARATOR are escaped for the sake of pre-2018
12
+ * browsers.
13
+ *
14
+ * @see tests for unsafe parsing examples.
15
+ * @see https://html.spec.whatwg.org/multipage/scripting.html#restrictions-for-contents-of-script-elements
16
+ * @see https://html.spec.whatwg.org/multipage/syntax.html#cdata-rcdata-restrictions
17
+ * @see https://html.spec.whatwg.org/multipage/parsing.html#script-data-state
18
+ * @see https://html.spec.whatwg.org/multipage/parsing.html#script-data-double-escaped-state
19
+ * @see https://github.com/tc39/proposal-json-superset
20
+ * @type {Record<string, string>}
21
+ */
22
+ const replacements = {
23
+ '<': '\\u003C',
24
+ '\u2028': '\\u2028',
25
+ '\u2029': '\\u2029'
26
+ };
27
+
28
+ const pattern = new RegExp(`[${Object.keys(replacements).join('')}]`, 'g');
29
+
30
+ /**
31
+ * Generates a raw HTML string containing a safe script element carrying data and associated attributes.
32
+ *
33
+ * It escapes all the special characters needed to guarantee the element is unbroken, but care must
34
+ * be taken to ensure it is inserted in the document at an acceptable position for a script element,
35
+ * and that the resulting string isn't further modified.
36
+ *
37
+ * @param {import('./types.js').Fetched} fetched
38
+ * @param {(name: string, value: string) => boolean} filter
39
+ * @param {boolean} [prerendering]
40
+ * @returns {string} The raw HTML of a script element carrying the JSON payload.
41
+ * @example const html = serialize_data('/data.json', null, { foo: 'bar' });
42
+ */
43
+ export function serialize_data(fetched, filter, prerendering = false) {
44
+ /** @type {Record<string, string>} */
45
+ const headers = {};
46
+
47
+ let cache_control = null;
48
+ let age = null;
49
+
50
+ for (const [key, value] of fetched.response.headers) {
51
+ if (filter(key, value)) {
52
+ headers[key] = value;
53
+ }
54
+
55
+ if (key === 'cache-control') cache_control = value;
56
+ if (key === 'age') age = value;
57
+ }
58
+
59
+ const payload = {
60
+ status: fetched.response.status,
61
+ statusText: fetched.response.statusText,
62
+ headers,
63
+ body: fetched.response_body
64
+ };
65
+
66
+ const safe_payload = JSON.stringify(payload).replace(pattern, (match) => replacements[match]);
67
+
68
+ const attrs = [
69
+ 'type="application/json"',
70
+ 'data-sveltekit-fetched',
71
+ `data-url=${escape_html_attr(fetched.url)}`
72
+ ];
73
+
74
+ if (fetched.request_body) {
75
+ attrs.push(`data-hash=${escape_html_attr(hash(fetched.request_body))}`);
76
+ }
77
+
78
+ if (!prerendering && fetched.method === 'GET' && cache_control) {
79
+ const match = /s-maxage=(\d+)/g.exec(cache_control) ?? /max-age=(\d+)/g.exec(cache_control);
80
+ if (match) {
81
+ const ttl = +match[1] - +(age ?? '0');
82
+ attrs.push(`data-ttl="${ttl}"`);
83
+ }
84
+ }
85
+
86
+ return `<script ${attrs.join(' ')}>${safe_payload}</script>`;
87
+ }
@@ -0,0 +1,35 @@
1
+ import { CookieSerializeOptions } from 'cookie';
2
+ import { SSRNode, CspDirectives } from 'types';
3
+
4
+ export interface Fetched {
5
+ url: string;
6
+ method: string;
7
+ request_body?: string | ArrayBufferView | null;
8
+ response_body: string;
9
+ response: Response;
10
+ }
11
+
12
+ export type Loaded = {
13
+ node: SSRNode;
14
+ data: Record<string, any> | null;
15
+ server_data: any;
16
+ };
17
+
18
+ type CspMode = 'hash' | 'nonce' | 'auto';
19
+
20
+ export interface CspConfig {
21
+ mode: CspMode;
22
+ directives: CspDirectives;
23
+ reportOnly: CspDirectives;
24
+ }
25
+
26
+ export interface CspOpts {
27
+ dev: boolean;
28
+ prerender: boolean;
29
+ }
30
+
31
+ export interface Cookie {
32
+ name: string;
33
+ value: string;
34
+ options: CookieSerializeOptions;
35
+ }