@sveltejs/kit 1.0.0-next.46 → 1.0.0-next.460

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 (115) hide show
  1. package/README.md +12 -9
  2. package/package.json +93 -65
  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 +498 -0
  15. package/src/core/config/types.d.ts +1 -0
  16. package/src/core/env.js +112 -0
  17. package/src/core/generate_manifest/index.js +78 -0
  18. package/src/core/prerender/crawl.js +194 -0
  19. package/src/core/prerender/prerender.js +425 -0
  20. package/src/core/prerender/queue.js +80 -0
  21. package/src/core/sync/create_manifest_data/index.js +452 -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 +595 -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 +45 -0
  35. package/src/exports/node/index.js +145 -0
  36. package/src/exports/node/polyfills.js +40 -0
  37. package/src/exports/vite/build/build_server.js +349 -0
  38. package/src/exports/vite/build/build_service_worker.js +90 -0
  39. package/src/exports/vite/build/utils.js +160 -0
  40. package/src/exports/vite/dev/index.js +543 -0
  41. package/src/exports/vite/index.js +595 -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 +345 -0
  45. package/src/runtime/app/env.js +1 -0
  46. package/src/runtime/app/environment.js +11 -0
  47. package/src/runtime/app/navigation.js +22 -0
  48. package/src/runtime/app/paths.js +1 -0
  49. package/src/runtime/app/stores.js +102 -0
  50. package/src/runtime/client/ambient.d.ts +24 -0
  51. package/src/runtime/client/client.js +1387 -0
  52. package/src/runtime/client/fetcher.js +60 -0
  53. package/src/runtime/client/parse.js +60 -0
  54. package/src/runtime/client/singletons.js +21 -0
  55. package/src/runtime/client/start.js +45 -0
  56. package/src/runtime/client/types.d.ts +88 -0
  57. package/src/runtime/client/utils.js +140 -0
  58. package/src/runtime/components/error.svelte +16 -0
  59. package/{assets → src/runtime}/components/layout.svelte +0 -0
  60. package/src/runtime/control.js +33 -0
  61. package/src/runtime/env/dynamic/private.js +1 -0
  62. package/src/runtime/env/dynamic/public.js +1 -0
  63. package/src/runtime/env-private.js +6 -0
  64. package/src/runtime/env-public.js +6 -0
  65. package/src/runtime/env.js +6 -0
  66. package/src/runtime/hash.js +16 -0
  67. package/src/runtime/paths.js +11 -0
  68. package/src/runtime/server/data/index.js +146 -0
  69. package/src/runtime/server/endpoint.js +63 -0
  70. package/src/runtime/server/index.js +339 -0
  71. package/src/runtime/server/page/cookie.js +25 -0
  72. package/src/runtime/server/page/crypto.js +239 -0
  73. package/src/runtime/server/page/csp.js +249 -0
  74. package/src/runtime/server/page/fetch.js +269 -0
  75. package/src/runtime/server/page/index.js +404 -0
  76. package/src/runtime/server/page/load_data.js +124 -0
  77. package/src/runtime/server/page/render.js +358 -0
  78. package/src/runtime/server/page/respond_with_error.js +92 -0
  79. package/src/runtime/server/page/serialize_data.js +58 -0
  80. package/src/runtime/server/page/types.d.ts +44 -0
  81. package/src/runtime/server/utils.js +209 -0
  82. package/src/utils/array.js +9 -0
  83. package/src/utils/error.js +22 -0
  84. package/src/utils/escape.js +46 -0
  85. package/src/utils/filesystem.js +108 -0
  86. package/src/utils/functions.js +16 -0
  87. package/src/utils/http.js +55 -0
  88. package/src/utils/misc.js +1 -0
  89. package/src/utils/routing.js +137 -0
  90. package/src/utils/url.js +142 -0
  91. package/svelte-kit.js +1 -1
  92. package/types/ambient.d.ts +332 -0
  93. package/types/index.d.ts +343 -0
  94. package/types/internal.d.ts +383 -0
  95. package/types/private.d.ts +213 -0
  96. package/CHANGELOG.md +0 -456
  97. package/assets/components/error.svelte +0 -13
  98. package/assets/runtime/app/env.js +0 -5
  99. package/assets/runtime/app/navigation.js +0 -44
  100. package/assets/runtime/app/paths.js +0 -1
  101. package/assets/runtime/app/stores.js +0 -93
  102. package/assets/runtime/chunks/utils.js +0 -22
  103. package/assets/runtime/internal/singletons.js +0 -23
  104. package/assets/runtime/internal/start.js +0 -771
  105. package/assets/runtime/paths.js +0 -12
  106. package/dist/chunks/index.js +0 -3522
  107. package/dist/chunks/index2.js +0 -587
  108. package/dist/chunks/index3.js +0 -246
  109. package/dist/chunks/index4.js +0 -539
  110. package/dist/chunks/index5.js +0 -763
  111. package/dist/chunks/index6.js +0 -322
  112. package/dist/chunks/standard.js +0 -99
  113. package/dist/chunks/utils.js +0 -83
  114. package/dist/cli.js +0 -546
  115. package/dist/ssr.js +0 -2581
@@ -0,0 +1,1387 @@
1
+ import { onMount, tick } from 'svelte';
2
+ import { normalize_error } from '../../utils/error.js';
3
+ import { make_trackable, decode_params, normalize_path } from '../../utils/url.js';
4
+ import { find_anchor, get_base_uri, scroll_state } from './utils.js';
5
+ import { lock_fetch, unlock_fetch, initial_fetch, native_fetch } from './fetcher.js';
6
+ import { parse } from './parse.js';
7
+ import { error } from '../../exports/index.js';
8
+
9
+ import Root from '__GENERATED__/root.svelte';
10
+ import { nodes, server_loads, dictionary, matchers } from '__GENERATED__/client-manifest.js';
11
+ import { HttpError, Redirect } from '../control.js';
12
+ import { stores } from './singletons.js';
13
+ import { DATA_SUFFIX } from '../../constants.js';
14
+
15
+ const SCROLL_KEY = 'sveltekit:scroll';
16
+ const INDEX_KEY = 'sveltekit:index';
17
+
18
+ const routes = parse(nodes, server_loads, dictionary, matchers);
19
+
20
+ const default_layout_loader = nodes[0];
21
+ const default_error_loader = nodes[1];
22
+
23
+ // we import the root layout/error nodes eagerly, so that
24
+ // connectivity errors after initialisation don't nuke the app
25
+ default_layout_loader();
26
+ default_error_loader();
27
+
28
+ // We track the scroll position associated with each history entry in sessionStorage,
29
+ // rather than on history.state itself, because when navigation is driven by
30
+ // popstate it's too late to update the scroll position associated with the
31
+ // state we're navigating from
32
+
33
+ /** @typedef {{ x: number, y: number }} ScrollPosition */
34
+ /** @type {Record<number, ScrollPosition>} */
35
+ let scroll_positions = {};
36
+ try {
37
+ scroll_positions = JSON.parse(sessionStorage[SCROLL_KEY]);
38
+ } catch {
39
+ // do nothing
40
+ }
41
+
42
+ /** @param {number} index */
43
+ function update_scroll_positions(index) {
44
+ scroll_positions[index] = scroll_state();
45
+ }
46
+
47
+ /** @type {Record<string, true>} */
48
+ let warned_about_attributes = {};
49
+
50
+ function check_for_removed_attributes() {
51
+ const attrs = ['prefetch', 'noscroll', 'reload'];
52
+ for (const attr of attrs) {
53
+ if (document.querySelector(`[sveltekit\\:${attr}]`)) {
54
+ if (!warned_about_attributes[attr]) {
55
+ warned_about_attributes[attr] = true;
56
+ console.error(
57
+ `The sveltekit:${attr} attribute has been replaced with data-sveltekit-${attr}`
58
+ );
59
+ }
60
+ }
61
+ }
62
+ }
63
+
64
+ /**
65
+ * @param {{
66
+ * target: Element;
67
+ * base: string;
68
+ * trailing_slash: import('types').TrailingSlash;
69
+ * }} opts
70
+ * @returns {import('./types').Client}
71
+ */
72
+ export function create_client({ target, base, trailing_slash }) {
73
+ /** @type {Array<((href: string) => boolean)>} */
74
+ const invalidated = [];
75
+
76
+ /** @type {{id: string | null, promise: Promise<import('./types').NavigationResult | undefined> | null}} */
77
+ const load_cache = {
78
+ id: null,
79
+ promise: null
80
+ };
81
+
82
+ const callbacks = {
83
+ /** @type {Array<(opts: { from: URL, to: URL | null, cancel: () => void }) => void>} */
84
+ before_navigate: [],
85
+
86
+ /** @type {Array<(opts: { from: URL | null, to: URL }) => void>} */
87
+ after_navigate: []
88
+ };
89
+
90
+ /** @type {import('./types').NavigationState} */
91
+ let current = {
92
+ branch: [],
93
+ error: null,
94
+ session_id: 0,
95
+ // @ts-ignore - we need the initial value to be null
96
+ url: null
97
+ };
98
+
99
+ let started = false;
100
+ let autoscroll = true;
101
+ let updating = false;
102
+ let session_id = 1;
103
+
104
+ /** @type {Promise<void> | null} */
105
+ let invalidating = null;
106
+
107
+ /** @type {import('svelte').SvelteComponent} */
108
+ let root;
109
+
110
+ // keeping track of the history index in order to prevent popstate navigation events if needed
111
+ let current_history_index = history.state?.[INDEX_KEY];
112
+
113
+ if (!current_history_index) {
114
+ // we use Date.now() as an offset so that cross-document navigations
115
+ // within the app don't result in data loss
116
+ current_history_index = Date.now();
117
+
118
+ // create initial history entry, so we can return here
119
+ history.replaceState(
120
+ { ...history.state, [INDEX_KEY]: current_history_index },
121
+ '',
122
+ location.href
123
+ );
124
+ }
125
+
126
+ // if we reload the page, or Cmd-Shift-T back to it,
127
+ // recover scroll position
128
+ const scroll = scroll_positions[current_history_index];
129
+ if (scroll) {
130
+ history.scrollRestoration = 'manual';
131
+ scrollTo(scroll.x, scroll.y);
132
+ }
133
+
134
+ let hash_navigating = false;
135
+
136
+ /** @type {import('types').Page} */
137
+ let page;
138
+
139
+ /** @type {{}} */
140
+ let token;
141
+
142
+ /**
143
+ * @param {string | URL} url
144
+ * @param {{ noscroll?: boolean; replaceState?: boolean; keepfocus?: boolean; state?: any }} opts
145
+ * @param {string[]} redirect_chain
146
+ */
147
+ async function goto(
148
+ url,
149
+ { noscroll = false, replaceState = false, keepfocus = false, state = {} },
150
+ redirect_chain
151
+ ) {
152
+ if (typeof url === 'string') {
153
+ url = new URL(url, get_base_uri(document));
154
+ }
155
+
156
+ return navigate({
157
+ url,
158
+ scroll: noscroll ? scroll_state() : null,
159
+ keepfocus,
160
+ redirect_chain,
161
+ details: {
162
+ state,
163
+ replaceState
164
+ },
165
+ accepted: () => {},
166
+ blocked: () => {}
167
+ });
168
+ }
169
+
170
+ /** @param {URL} url */
171
+ async function prefetch(url) {
172
+ const intent = get_navigation_intent(url);
173
+
174
+ if (!intent) {
175
+ throw new Error('Attempted to prefetch a URL that does not belong to this app');
176
+ }
177
+
178
+ load_cache.promise = load_route(intent);
179
+ load_cache.id = intent.id;
180
+
181
+ return load_cache.promise;
182
+ }
183
+
184
+ /**
185
+ * Returns `true` if update completes, `false` if it is aborted
186
+ * @param {URL} url
187
+ * @param {string[]} redirect_chain
188
+ * @param {{hash?: string, scroll: { x: number, y: number } | null, keepfocus: boolean, details: { replaceState: boolean, state: any } | null}} [opts]
189
+ * @param {() => void} [callback]
190
+ */
191
+ async function update(url, redirect_chain, opts, callback) {
192
+ const intent = get_navigation_intent(url);
193
+
194
+ const current_token = (token = {});
195
+ let navigation_result = intent && (await load_route(intent));
196
+
197
+ if (
198
+ !navigation_result &&
199
+ url.origin === location.origin &&
200
+ url.pathname === location.pathname
201
+ ) {
202
+ // this could happen in SPA fallback mode if the user navigated to
203
+ // `/non-existent-page`. if we fall back to reloading the page, it
204
+ // will create an infinite loop. so whereas we normally handle
205
+ // unknown routes by going to the server, in this special case
206
+ // we render a client-side error page instead
207
+ navigation_result = await load_root_error_page({
208
+ status: 404,
209
+ error: new Error(`Not found: ${url.pathname}`),
210
+ url,
211
+ routeId: null
212
+ });
213
+ }
214
+
215
+ if (!navigation_result) {
216
+ await native_navigation(url);
217
+ return false; // unnecessary, but TypeScript prefers it this way
218
+ }
219
+
220
+ // if this is an internal navigation intent, use the normalized
221
+ // URL for the rest of the function
222
+ url = intent?.url || url;
223
+
224
+ // abort if user navigated during update
225
+ if (token !== current_token) return false;
226
+
227
+ invalidated.length = 0;
228
+
229
+ if (navigation_result.type === 'redirect') {
230
+ if (redirect_chain.length > 10 || redirect_chain.includes(url.pathname)) {
231
+ navigation_result = await load_root_error_page({
232
+ status: 500,
233
+ error: new Error('Redirect loop'),
234
+ url,
235
+ routeId: null
236
+ });
237
+ } else {
238
+ goto(new URL(navigation_result.location, url).href, {}, [...redirect_chain, url.pathname]);
239
+ return false;
240
+ }
241
+ } else if (navigation_result.props?.page?.status >= 400) {
242
+ const updated = await stores.updated.check();
243
+ if (updated) {
244
+ await native_navigation(url);
245
+ }
246
+ }
247
+
248
+ updating = true;
249
+
250
+ if (opts && opts.details) {
251
+ const { details } = opts;
252
+ const change = details.replaceState ? 0 : 1;
253
+ details.state[INDEX_KEY] = current_history_index += change;
254
+ history[details.replaceState ? 'replaceState' : 'pushState'](details.state, '', url);
255
+ }
256
+
257
+ if (started) {
258
+ current = navigation_result.state;
259
+
260
+ if (navigation_result.props.page) {
261
+ navigation_result.props.page.url = url;
262
+ }
263
+
264
+ if (import.meta.env.DEV) {
265
+ // Nasty hack to silence harmless warnings the user can do nothing about
266
+ const warn = console.warn;
267
+ console.warn = (...args) => {
268
+ if (
269
+ args.length !== 1 ||
270
+ !/<(Layout|Page)(_[\w$]+)?> was created with unknown prop '(data|errors)'/.test(args[0])
271
+ ) {
272
+ warn(...args);
273
+ }
274
+ };
275
+ root.$set(navigation_result.props);
276
+ tick().then(() => (console.warn = warn));
277
+
278
+ check_for_removed_attributes();
279
+ } else {
280
+ root.$set(navigation_result.props);
281
+ }
282
+ } else {
283
+ initialize(navigation_result);
284
+ }
285
+
286
+ // opts must be passed if we're navigating
287
+ if (opts) {
288
+ const { scroll, keepfocus } = opts;
289
+
290
+ if (!keepfocus) {
291
+ // Reset page selection and focus
292
+ // We try to mimic browsers' behaviour as closely as possible by targeting the
293
+ // first scrollable region, but unfortunately it's not a perfect match — e.g.
294
+ // shift-tabbing won't immediately cycle up from the end of the page on Chromium
295
+ // See https://html.spec.whatwg.org/multipage/interaction.html#get-the-focusable-area
296
+ const root = document.body;
297
+ const tabindex = root.getAttribute('tabindex');
298
+
299
+ root.tabIndex = -1;
300
+ root.focus({ preventScroll: true });
301
+
302
+ setTimeout(() => {
303
+ getSelection()?.removeAllRanges();
304
+ });
305
+
306
+ // restore `tabindex` as to prevent `root` from stealing input from elements
307
+ if (tabindex !== null) {
308
+ root.setAttribute('tabindex', tabindex);
309
+ } else {
310
+ root.removeAttribute('tabindex');
311
+ }
312
+ }
313
+
314
+ // need to render the DOM before we can scroll to the rendered elements
315
+ await tick();
316
+
317
+ if (autoscroll) {
318
+ const deep_linked = url.hash && document.getElementById(url.hash.slice(1));
319
+ if (scroll) {
320
+ scrollTo(scroll.x, scroll.y);
321
+ } else if (deep_linked) {
322
+ // Here we use `scrollIntoView` on the element instead of `scrollTo`
323
+ // because it natively supports the `scroll-margin` and `scroll-behavior`
324
+ // CSS properties.
325
+ deep_linked.scrollIntoView();
326
+ } else {
327
+ scrollTo(0, 0);
328
+ }
329
+ }
330
+ } else {
331
+ // in this case we're simply invalidating
332
+ await tick();
333
+ }
334
+
335
+ load_cache.promise = null;
336
+ load_cache.id = null;
337
+ autoscroll = true;
338
+
339
+ if (navigation_result.props.page) {
340
+ page = navigation_result.props.page;
341
+ }
342
+
343
+ if (callback) callback();
344
+
345
+ updating = false;
346
+ }
347
+
348
+ /** @param {import('./types').NavigationFinished} result */
349
+ function initialize(result) {
350
+ current = result.state;
351
+
352
+ const style = document.querySelector('style[data-sveltekit]');
353
+ if (style) style.remove();
354
+
355
+ page = result.props.page;
356
+
357
+ if (import.meta.env.DEV) {
358
+ // Nasty hack to silence harmless warnings the user can do nothing about
359
+ const warn = console.warn;
360
+ console.warn = (...args) => {
361
+ if (
362
+ args.length !== 1 ||
363
+ !/<(Layout|Page)(_[\w$]+)?> was created with unknown prop '(data|errors)'/.test(args[0])
364
+ ) {
365
+ warn(...args);
366
+ }
367
+ };
368
+ root = new Root({
369
+ target,
370
+ props: { ...result.props, stores },
371
+ hydrate: true
372
+ });
373
+ console.warn = warn;
374
+
375
+ check_for_removed_attributes();
376
+ } else {
377
+ root = new Root({
378
+ target,
379
+ props: { ...result.props, stores },
380
+ hydrate: true
381
+ });
382
+ }
383
+
384
+ const navigation = { from: null, to: new URL(location.href) };
385
+ callbacks.after_navigate.forEach((fn) => fn(navigation));
386
+
387
+ started = true;
388
+ }
389
+
390
+ /**
391
+ *
392
+ * @param {{
393
+ * url: URL;
394
+ * params: Record<string, string>;
395
+ * branch: Array<import('./types').BranchNode | undefined>;
396
+ * status: number;
397
+ * error: HttpError | Error | null;
398
+ * routeId: string | null;
399
+ * validation_errors?: Record<string, any> | null;
400
+ * }} opts
401
+ */
402
+ async function get_navigation_result_from_branch({
403
+ url,
404
+ params,
405
+ branch,
406
+ status,
407
+ error,
408
+ routeId,
409
+ validation_errors
410
+ }) {
411
+ const filtered = /** @type {import('./types').BranchNode[] } */ (branch.filter(Boolean));
412
+
413
+ /** @type {import('./types').NavigationFinished} */
414
+ const result = {
415
+ type: 'loaded',
416
+ state: {
417
+ url,
418
+ params,
419
+ branch,
420
+ error,
421
+ session_id
422
+ },
423
+ props: {
424
+ components: filtered.map((branch_node) => branch_node.node.component),
425
+ errors: validation_errors
426
+ }
427
+ };
428
+
429
+ let data = {};
430
+ let data_changed = !page;
431
+ for (let i = 0; i < filtered.length; i += 1) {
432
+ const node = filtered[i];
433
+ data = { ...data, ...node.data };
434
+
435
+ // Only set props if the node actually updated. This prevents needless rerenders.
436
+ if (data_changed || !current.branch.some((previous) => previous === node)) {
437
+ result.props[`data_${i}`] = data;
438
+ data_changed = data_changed || Object.keys(node.data ?? {}).length > 0;
439
+ }
440
+ }
441
+ if (!data_changed) {
442
+ // If nothing was added, and the object entries are the same length, this means
443
+ // that nothing was removed either and therefore the data is the same as the previous one.
444
+ // This would be more readable with a separate boolean but that would cost us some bytes.
445
+ data_changed = Object.keys(page.data).length !== Object.keys(data).length;
446
+ }
447
+
448
+ const page_changed =
449
+ !current.url || url.href !== current.url.href || current.error !== error || data_changed;
450
+
451
+ if (page_changed) {
452
+ result.props.page = {
453
+ error,
454
+ params,
455
+ routeId,
456
+ status,
457
+ url,
458
+ // The whole page store is updated, but this way the object reference stays the same
459
+ data: data_changed ? data : page.data
460
+ };
461
+
462
+ // TODO remove this for 1.0
463
+ /**
464
+ * @param {string} property
465
+ * @param {string} replacement
466
+ */
467
+ const print_error = (property, replacement) => {
468
+ Object.defineProperty(result.props.page, property, {
469
+ get: () => {
470
+ throw new Error(`$page.${property} has been replaced by $page.url.${replacement}`);
471
+ }
472
+ });
473
+ };
474
+
475
+ print_error('origin', 'origin');
476
+ print_error('path', 'pathname');
477
+ print_error('query', 'searchParams');
478
+ }
479
+
480
+ return result;
481
+ }
482
+
483
+ /**
484
+ * Call the load function of the given node, if it exists.
485
+ * If `server_data` is passed, this is treated as the initial run and the page endpoint is not requested.
486
+ *
487
+ * @param {{
488
+ * loader: import('types').CSRPageNodeLoader;
489
+ * parent: () => Promise<Record<string, any>>;
490
+ * url: URL;
491
+ * params: Record<string, string>;
492
+ * routeId: string | null;
493
+ * server_data_node: import('./types').DataNode | null;
494
+ * }} options
495
+ * @returns {Promise<import('./types').BranchNode>}
496
+ */
497
+ async function load_node({ loader, parent, url, params, routeId, server_data_node }) {
498
+ /** @type {Record<string, any> | null} */
499
+ let data = null;
500
+
501
+ /** @type {import('types').Uses} */
502
+ const uses = {
503
+ dependencies: new Set(),
504
+ params: new Set(),
505
+ parent: false,
506
+ url: false
507
+ };
508
+
509
+ const node = await loader();
510
+
511
+ if (node.shared?.load) {
512
+ /** @param {string[]} deps */
513
+ function depends(...deps) {
514
+ for (const dep of deps) {
515
+ const { href } = new URL(dep, url);
516
+ uses.dependencies.add(href);
517
+ }
518
+ }
519
+
520
+ /** @type {Record<string, string>} */
521
+ const uses_params = {};
522
+ for (const key in params) {
523
+ Object.defineProperty(uses_params, key, {
524
+ get() {
525
+ uses.params.add(key);
526
+ return params[key];
527
+ },
528
+ enumerable: true
529
+ });
530
+ }
531
+
532
+ /** @type {import('types').LoadEvent} */
533
+ const load_input = {
534
+ routeId,
535
+ params: uses_params,
536
+ data: server_data_node?.data ?? null,
537
+ url: make_trackable(url, () => {
538
+ uses.url = true;
539
+ }),
540
+ async fetch(resource, init) {
541
+ let requested;
542
+
543
+ if (typeof resource === 'string') {
544
+ requested = resource;
545
+ } else {
546
+ requested = resource.url;
547
+
548
+ // we're not allowed to modify the received `Request` object, so in order
549
+ // to fixup relative urls we create a new equivalent `init` object instead
550
+ init = {
551
+ // the request body must be consumed in memory until browsers
552
+ // implement streaming request bodies and/or the body getter
553
+ body:
554
+ resource.method === 'GET' || resource.method === 'HEAD'
555
+ ? undefined
556
+ : await resource.blob(),
557
+ cache: resource.cache,
558
+ credentials: resource.credentials,
559
+ headers: resource.headers,
560
+ integrity: resource.integrity,
561
+ keepalive: resource.keepalive,
562
+ method: resource.method,
563
+ mode: resource.mode,
564
+ redirect: resource.redirect,
565
+ referrer: resource.referrer,
566
+ referrerPolicy: resource.referrerPolicy,
567
+ signal: resource.signal,
568
+ ...init
569
+ };
570
+ }
571
+
572
+ // we must fixup relative urls so they are resolved from the target page
573
+ const normalized = new URL(requested, url).href;
574
+ depends(normalized);
575
+
576
+ // prerendered pages may be served from any origin, so `initial_fetch` urls shouldn't be normalized
577
+ return started ? native_fetch(normalized, init) : initial_fetch(requested, init);
578
+ },
579
+ setHeaders: () => {}, // noop
580
+ depends,
581
+ parent() {
582
+ uses.parent = true;
583
+ return parent();
584
+ }
585
+ };
586
+
587
+ // TODO remove this for 1.0
588
+ Object.defineProperties(load_input, {
589
+ props: {
590
+ get() {
591
+ throw new Error(
592
+ '@migration task: Replace `props` with `data` stuff https://github.com/sveltejs/kit/discussions/5774#discussioncomment-3292693'
593
+ );
594
+ },
595
+ enumerable: false
596
+ },
597
+ session: {
598
+ get() {
599
+ throw new Error(
600
+ 'session is no longer available. See https://github.com/sveltejs/kit/discussions/5883'
601
+ );
602
+ },
603
+ enumerable: false
604
+ },
605
+ stuff: {
606
+ get() {
607
+ throw new Error(
608
+ '@migration task: Remove stuff https://github.com/sveltejs/kit/discussions/5774#discussioncomment-3292693'
609
+ );
610
+ },
611
+ enumerable: false
612
+ }
613
+ });
614
+
615
+ if (import.meta.env.DEV) {
616
+ try {
617
+ lock_fetch();
618
+ data = (await node.shared.load.call(null, load_input)) ?? null;
619
+ } finally {
620
+ unlock_fetch();
621
+ }
622
+ } else {
623
+ data = (await node.shared.load.call(null, load_input)) ?? null;
624
+ }
625
+ }
626
+
627
+ return {
628
+ node,
629
+ loader,
630
+ server: server_data_node,
631
+ shared: node.shared?.load ? { type: 'data', data, uses } : null,
632
+ data: data ?? server_data_node?.data ?? null
633
+ };
634
+ }
635
+
636
+ /**
637
+ * @param {import('types').Uses | undefined} uses
638
+ * @param {boolean} parent_changed
639
+ * @param {{ url: boolean, params: string[] }} changed
640
+ */
641
+ function has_changed(changed, parent_changed, uses) {
642
+ if (!uses) return false;
643
+
644
+ if (uses.parent && parent_changed) return true;
645
+ if (changed.url && uses.url) return true;
646
+
647
+ for (const param of changed.params) {
648
+ if (uses.params.has(param)) return true;
649
+ }
650
+
651
+ for (const dep of uses.dependencies) {
652
+ if (invalidated.some((fn) => fn(dep))) return true;
653
+ }
654
+
655
+ return false;
656
+ }
657
+
658
+ /**
659
+ * @param {import('types').ServerDataNode | import('types').ServerDataSkippedNode | null} node
660
+ * @param {import('./types').DataNode | null} [previous]
661
+ * @returns {import('./types').DataNode | null}
662
+ */
663
+ function create_data_node(node, previous) {
664
+ if (node?.type === 'data') {
665
+ return {
666
+ type: 'data',
667
+ data: node.data,
668
+ uses: {
669
+ dependencies: new Set(node.uses.dependencies ?? []),
670
+ params: new Set(node.uses.params ?? []),
671
+ parent: !!node.uses.parent,
672
+ url: !!node.uses.url
673
+ }
674
+ };
675
+ } else if (node?.type === 'skip') {
676
+ return previous ?? null;
677
+ }
678
+ return null;
679
+ }
680
+
681
+ /**
682
+ * @param {import('./types').NavigationIntent} intent
683
+ * @returns {Promise<import('./types').NavigationResult | undefined>}
684
+ */
685
+ async function load_route({ id, url, params, route }) {
686
+ if (load_cache.id === id && load_cache.promise) {
687
+ return load_cache.promise;
688
+ }
689
+
690
+ const { errors, layouts, leaf } = route;
691
+
692
+ const changed = current.url && {
693
+ url: id !== current.url.pathname + current.url.search,
694
+ params: Object.keys(params).filter((key) => current.params[key] !== params[key])
695
+ };
696
+
697
+ const loaders = [...layouts, leaf];
698
+
699
+ // preload modules to avoid waterfall, but handle rejections
700
+ // so they don't get reported to Sentry et al (we don't need
701
+ // to act on the failures at this point)
702
+ errors.forEach((loader) => loader?.().catch(() => {}));
703
+ loaders.forEach((loader) => loader?.[1]().catch(() => {}));
704
+
705
+ /** @type {import('types').ServerData | null} */
706
+ let server_data = null;
707
+
708
+ const invalid_server_nodes = loaders.reduce((acc, loader, i) => {
709
+ const previous = current.branch[i];
710
+ const invalid =
711
+ !!loader?.[0] &&
712
+ (previous?.loader !== loader[1] ||
713
+ has_changed(changed, acc.some(Boolean), previous.server?.uses));
714
+
715
+ acc.push(invalid);
716
+ return acc;
717
+ }, /** @type {boolean[]} */ ([]));
718
+
719
+ if (invalid_server_nodes.some(Boolean)) {
720
+ try {
721
+ server_data = await load_data(url, invalid_server_nodes);
722
+ } catch (error) {
723
+ return load_root_error_page({
724
+ status: 500,
725
+ error: /** @type {Error} */ (error),
726
+ url,
727
+ routeId: route.id
728
+ });
729
+ }
730
+
731
+ if (server_data.type === 'redirect') {
732
+ return server_data;
733
+ }
734
+ }
735
+
736
+ const server_data_nodes = server_data?.nodes;
737
+
738
+ let parent_changed = false;
739
+
740
+ const branch_promises = loaders.map(async (loader, i) => {
741
+ if (!loader) return;
742
+
743
+ /** @type {import('./types').BranchNode | undefined} */
744
+ const previous = current.branch[i];
745
+
746
+ const server_data_node = server_data_nodes?.[i] ?? null;
747
+
748
+ const can_reuse_server_data = !server_data_node || server_data_node.type === 'skip';
749
+ // re-use data from previous load if it's still valid
750
+ const valid =
751
+ can_reuse_server_data &&
752
+ loader[1] === previous?.loader &&
753
+ !has_changed(changed, parent_changed, previous.shared?.uses);
754
+ if (valid) return previous;
755
+
756
+ parent_changed = true;
757
+
758
+ if (server_data_node?.type === 'error') {
759
+ if (server_data_node.httperror) {
760
+ // reconstruct as an HttpError
761
+ throw error(server_data_node.httperror.status, server_data_node.httperror.message);
762
+ } else {
763
+ throw server_data_node.error;
764
+ }
765
+ }
766
+
767
+ return load_node({
768
+ loader: loader[1],
769
+ url,
770
+ params,
771
+ routeId: route.id,
772
+ parent: async () => {
773
+ const data = {};
774
+ for (let j = 0; j < i; j += 1) {
775
+ Object.assign(data, (await branch_promises[j])?.data);
776
+ }
777
+ return data;
778
+ },
779
+ server_data_node: create_data_node(server_data_node, previous?.server)
780
+ });
781
+ });
782
+
783
+ // if we don't do this, rejections will be unhandled
784
+ for (const p of branch_promises) p.catch(() => {});
785
+
786
+ /** @type {Array<import('./types').BranchNode | undefined>} */
787
+ const branch = [];
788
+
789
+ for (let i = 0; i < loaders.length; i += 1) {
790
+ if (loaders[i]) {
791
+ try {
792
+ branch.push(await branch_promises[i]);
793
+ } catch (e) {
794
+ const error = normalize_error(e);
795
+
796
+ if (error instanceof Redirect) {
797
+ return {
798
+ type: 'redirect',
799
+ location: error.location
800
+ };
801
+ }
802
+
803
+ const status = e instanceof HttpError ? e.status : 500;
804
+
805
+ while (i--) {
806
+ if (errors[i]) {
807
+ /** @type {import('./types').BranchNode | undefined} */
808
+ let error_loaded;
809
+
810
+ let j = i;
811
+ while (!branch[j]) j -= 1;
812
+ try {
813
+ error_loaded = {
814
+ node: await /** @type {import('types').CSRPageNodeLoader } */ (errors[i])(),
815
+ loader: /** @type {import('types').CSRPageNodeLoader } */ (errors[i]),
816
+ data: {},
817
+ server: null,
818
+ shared: null
819
+ };
820
+
821
+ return await get_navigation_result_from_branch({
822
+ url,
823
+ params,
824
+ branch: branch.slice(0, j + 1).concat(error_loaded),
825
+ status,
826
+ error,
827
+ routeId: route.id
828
+ });
829
+ } catch (e) {
830
+ continue;
831
+ }
832
+ }
833
+ }
834
+
835
+ // if we get here, it's because the root `load` function failed,
836
+ // and we need to fall back to the server
837
+ await native_navigation(url);
838
+ return;
839
+ }
840
+ } else {
841
+ // push an empty slot so we can rewind past gaps to the
842
+ // layout that corresponds with an +error.svelte page
843
+ branch.push(undefined);
844
+ }
845
+ }
846
+
847
+ return await get_navigation_result_from_branch({
848
+ url,
849
+ params,
850
+ branch,
851
+ status: 200,
852
+ error: null,
853
+ routeId: route.id
854
+ });
855
+ }
856
+
857
+ /**
858
+ * @param {{
859
+ * status: number;
860
+ * error: HttpError | Error;
861
+ * url: URL;
862
+ * routeId: string | null
863
+ * }} opts
864
+ * @returns {Promise<import('./types').NavigationFinished>}
865
+ */
866
+ async function load_root_error_page({ status, error, url, routeId }) {
867
+ /** @type {Record<string, string>} */
868
+ const params = {}; // error page does not have params
869
+
870
+ const node = await default_layout_loader();
871
+
872
+ /** @type {import('types').ServerDataNode | null} */
873
+ let server_data_node = null;
874
+
875
+ if (node.server) {
876
+ // TODO post-https://github.com/sveltejs/kit/discussions/6124 we can use
877
+ // existing root layout data
878
+ try {
879
+ const server_data = await load_data(url, [true]);
880
+
881
+ if (
882
+ server_data.type !== 'data' ||
883
+ (server_data.nodes[0] && server_data.nodes[0].type !== 'data')
884
+ ) {
885
+ throw 0;
886
+ }
887
+
888
+ server_data_node = server_data.nodes[0] ?? null;
889
+ } catch {
890
+ // at this point we have no choice but to fall back to the server
891
+ await native_navigation(url);
892
+
893
+ // @ts-expect-error
894
+ return;
895
+ }
896
+ }
897
+
898
+ const root_layout = await load_node({
899
+ loader: default_layout_loader,
900
+ url,
901
+ params,
902
+ routeId,
903
+ parent: () => Promise.resolve({}),
904
+ server_data_node: create_data_node(server_data_node)
905
+ });
906
+
907
+ /** @type {import('./types').BranchNode} */
908
+ const root_error = {
909
+ node: await default_error_loader(),
910
+ loader: default_error_loader,
911
+ shared: null,
912
+ server: null,
913
+ data: null
914
+ };
915
+
916
+ return await get_navigation_result_from_branch({
917
+ url,
918
+ params,
919
+ branch: [root_layout, root_error],
920
+ status,
921
+ error,
922
+ routeId
923
+ });
924
+ }
925
+
926
+ /** @param {URL} url */
927
+ function get_navigation_intent(url) {
928
+ if (url.origin !== location.origin || !url.pathname.startsWith(base)) return;
929
+
930
+ const path = decodeURI(url.pathname.slice(base.length) || '/');
931
+
932
+ for (const route of routes) {
933
+ const params = route.exec(path);
934
+
935
+ if (params) {
936
+ const normalized = new URL(
937
+ url.origin + normalize_path(url.pathname, trailing_slash) + url.search + url.hash
938
+ );
939
+ const id = normalized.pathname + normalized.search;
940
+ /** @type {import('./types').NavigationIntent} */
941
+ const intent = { id, route, params: decode_params(params), url: normalized };
942
+ return intent;
943
+ }
944
+ }
945
+ }
946
+
947
+ /**
948
+ * @param {{
949
+ * url: URL;
950
+ * scroll: { x: number, y: number } | null;
951
+ * keepfocus: boolean;
952
+ * redirect_chain: string[];
953
+ * details: {
954
+ * replaceState: boolean;
955
+ * state: any;
956
+ * } | null;
957
+ * accepted: () => void;
958
+ * blocked: () => void;
959
+ * }} opts
960
+ */
961
+ async function navigate({ url, scroll, keepfocus, redirect_chain, details, accepted, blocked }) {
962
+ const from = current.url;
963
+ let should_block = false;
964
+
965
+ const navigation = {
966
+ from,
967
+ to: url,
968
+ cancel: () => (should_block = true)
969
+ };
970
+
971
+ callbacks.before_navigate.forEach((fn) => fn(navigation));
972
+
973
+ if (should_block) {
974
+ blocked();
975
+ return;
976
+ }
977
+
978
+ update_scroll_positions(current_history_index);
979
+
980
+ accepted();
981
+
982
+ if (started) {
983
+ stores.navigating.set({
984
+ from: current.url,
985
+ to: url
986
+ });
987
+ }
988
+
989
+ await update(
990
+ url,
991
+ redirect_chain,
992
+ {
993
+ scroll,
994
+ keepfocus,
995
+ details
996
+ },
997
+ () => {
998
+ const navigation = { from, to: url };
999
+ callbacks.after_navigate.forEach((fn) => fn(navigation));
1000
+
1001
+ stores.navigating.set(null);
1002
+ }
1003
+ );
1004
+ }
1005
+
1006
+ /**
1007
+ * Loads `href` the old-fashioned way, with a full page reload.
1008
+ * Returns a `Promise` that never resolves (to prevent any
1009
+ * subsequent work, e.g. history manipulation, from happening)
1010
+ * @param {URL} url
1011
+ */
1012
+ function native_navigation(url) {
1013
+ location.href = url.href;
1014
+ return new Promise(() => {});
1015
+ }
1016
+
1017
+ if (import.meta.hot) {
1018
+ import.meta.hot.on('vite:beforeUpdate', () => {
1019
+ if (current.error) location.reload();
1020
+ });
1021
+ }
1022
+
1023
+ return {
1024
+ after_navigate: (fn) => {
1025
+ onMount(() => {
1026
+ callbacks.after_navigate.push(fn);
1027
+
1028
+ return () => {
1029
+ const i = callbacks.after_navigate.indexOf(fn);
1030
+ callbacks.after_navigate.splice(i, 1);
1031
+ };
1032
+ });
1033
+ },
1034
+
1035
+ before_navigate: (fn) => {
1036
+ onMount(() => {
1037
+ callbacks.before_navigate.push(fn);
1038
+
1039
+ return () => {
1040
+ const i = callbacks.before_navigate.indexOf(fn);
1041
+ callbacks.before_navigate.splice(i, 1);
1042
+ };
1043
+ });
1044
+ },
1045
+
1046
+ disable_scroll_handling: () => {
1047
+ if (import.meta.env.DEV && started && !updating) {
1048
+ throw new Error('Can only disable scroll handling during navigation');
1049
+ }
1050
+
1051
+ if (updating || !started) {
1052
+ autoscroll = false;
1053
+ }
1054
+ },
1055
+
1056
+ goto: (href, opts = {}) => goto(href, opts, []),
1057
+
1058
+ invalidate: (resource) => {
1059
+ if (resource === undefined) {
1060
+ // Force rerun of all load functions, regardless of their dependencies
1061
+ for (const node of current.branch) {
1062
+ node?.server?.uses.dependencies.add('');
1063
+ node?.shared?.uses.dependencies.add('');
1064
+ }
1065
+ invalidated.push(() => true);
1066
+ } else if (typeof resource === 'function') {
1067
+ invalidated.push(resource);
1068
+ } else {
1069
+ const { href } = new URL(resource, location.href);
1070
+ invalidated.push((dep) => dep === href);
1071
+ }
1072
+
1073
+ if (!invalidating) {
1074
+ invalidating = Promise.resolve().then(async () => {
1075
+ await update(new URL(location.href), []);
1076
+
1077
+ invalidating = null;
1078
+ });
1079
+ }
1080
+
1081
+ return invalidating;
1082
+ },
1083
+
1084
+ prefetch: async (href) => {
1085
+ const url = new URL(href, get_base_uri(document));
1086
+ await prefetch(url);
1087
+ },
1088
+
1089
+ // TODO rethink this API
1090
+ prefetch_routes: async (pathnames) => {
1091
+ const matching = pathnames
1092
+ ? routes.filter((route) => pathnames.some((pathname) => route.exec(pathname)))
1093
+ : routes;
1094
+
1095
+ const promises = matching.map((r) => {
1096
+ return Promise.all([...r.layouts, r.leaf].map((load) => load?.[1]()));
1097
+ });
1098
+
1099
+ await Promise.all(promises);
1100
+ },
1101
+
1102
+ _start_router: () => {
1103
+ history.scrollRestoration = 'manual';
1104
+
1105
+ // Adopted from Nuxt.js
1106
+ // Reset scrollRestoration to auto when leaving page, allowing page reload
1107
+ // and back-navigation from other pages to use the browser to restore the
1108
+ // scrolling position.
1109
+ addEventListener('beforeunload', (e) => {
1110
+ let should_block = false;
1111
+
1112
+ const navigation = {
1113
+ from: current.url,
1114
+ to: null,
1115
+ cancel: () => (should_block = true)
1116
+ };
1117
+
1118
+ callbacks.before_navigate.forEach((fn) => fn(navigation));
1119
+
1120
+ if (should_block) {
1121
+ e.preventDefault();
1122
+ e.returnValue = '';
1123
+ } else {
1124
+ history.scrollRestoration = 'auto';
1125
+ }
1126
+ });
1127
+
1128
+ addEventListener('visibilitychange', () => {
1129
+ if (document.visibilityState === 'hidden') {
1130
+ update_scroll_positions(current_history_index);
1131
+
1132
+ try {
1133
+ sessionStorage[SCROLL_KEY] = JSON.stringify(scroll_positions);
1134
+ } catch {
1135
+ // do nothing
1136
+ }
1137
+ }
1138
+ });
1139
+
1140
+ /** @param {Event} event */
1141
+ const trigger_prefetch = (event) => {
1142
+ const { url, options } = find_anchor(event);
1143
+ if (url && options.prefetch === '') {
1144
+ prefetch(url);
1145
+ }
1146
+ };
1147
+
1148
+ /** @type {NodeJS.Timeout} */
1149
+ let mousemove_timeout;
1150
+
1151
+ /** @param {MouseEvent|TouchEvent} event */
1152
+ const handle_mousemove = (event) => {
1153
+ clearTimeout(mousemove_timeout);
1154
+ mousemove_timeout = setTimeout(() => {
1155
+ // event.composedPath(), which is used in find_anchor, will be empty if the event is read in a timeout
1156
+ // add a layer of indirection to address that
1157
+ event.target?.dispatchEvent(
1158
+ new CustomEvent('sveltekit:trigger_prefetch', { bubbles: true })
1159
+ );
1160
+ }, 20);
1161
+ };
1162
+
1163
+ addEventListener('touchstart', trigger_prefetch);
1164
+ addEventListener('mousemove', handle_mousemove);
1165
+ addEventListener('sveltekit:trigger_prefetch', trigger_prefetch);
1166
+
1167
+ /** @param {MouseEvent} event */
1168
+ addEventListener('click', (event) => {
1169
+ // Adapted from https://github.com/visionmedia/page.js
1170
+ // MIT license https://github.com/visionmedia/page.js#license
1171
+ if (event.button || event.which !== 1) return;
1172
+ if (event.metaKey || event.ctrlKey || event.shiftKey || event.altKey) return;
1173
+ if (event.defaultPrevented) return;
1174
+
1175
+ const { a, url, options } = find_anchor(event);
1176
+ if (!a || !url) return;
1177
+
1178
+ const is_svg_a_element = a instanceof SVGAElement;
1179
+
1180
+ // Ignore non-HTTP URL protocols (e.g. `mailto:`, `tel:`, `myapp:`, etc.)
1181
+ // MEMO: Without this condition, firefox will open mailer twice.
1182
+ // See:
1183
+ // - https://github.com/sveltejs/kit/issues/4045
1184
+ // - https://github.com/sveltejs/kit/issues/5725
1185
+ if (!is_svg_a_element && !(url.protocol === 'https:' || url.protocol === 'http:')) return;
1186
+
1187
+ // Ignore if tag has
1188
+ // 1. 'download' attribute
1189
+ // 2. 'rel' attribute includes external
1190
+ const rel = (a.getAttribute('rel') || '').split(/\s+/);
1191
+
1192
+ if (a.hasAttribute('download') || rel.includes('external') || options.reload === '') {
1193
+ return;
1194
+ }
1195
+
1196
+ // Ignore if <a> has a target
1197
+ if (is_svg_a_element ? a.target.baseVal : a.target) return;
1198
+
1199
+ // Check if new url only differs by hash and use the browser default behavior in that case
1200
+ // This will ensure the `hashchange` event is fired
1201
+ // Removing the hash does a full page navigation in the browser, so make sure a hash is present
1202
+ const [base, hash] = url.href.split('#');
1203
+ if (hash !== undefined && base === location.href.split('#')[0]) {
1204
+ // set this flag to distinguish between navigations triggered by
1205
+ // clicking a hash link and those triggered by popstate
1206
+ hash_navigating = true;
1207
+
1208
+ update_scroll_positions(current_history_index);
1209
+
1210
+ stores.page.set({ ...page, url });
1211
+ stores.page.notify();
1212
+
1213
+ return;
1214
+ }
1215
+
1216
+ navigate({
1217
+ url,
1218
+ scroll: options.noscroll === '' ? scroll_state() : null,
1219
+ keepfocus: false,
1220
+ redirect_chain: [],
1221
+ details: {
1222
+ state: {},
1223
+ replaceState: url.href === location.href
1224
+ },
1225
+ accepted: () => event.preventDefault(),
1226
+ blocked: () => event.preventDefault()
1227
+ });
1228
+ });
1229
+
1230
+ addEventListener('popstate', (event) => {
1231
+ if (event.state) {
1232
+ // if a popstate-driven navigation is cancelled, we need to counteract it
1233
+ // with history.go, which means we end up back here, hence this check
1234
+ if (event.state[INDEX_KEY] === current_history_index) return;
1235
+
1236
+ navigate({
1237
+ url: new URL(location.href),
1238
+ scroll: scroll_positions[event.state[INDEX_KEY]],
1239
+ keepfocus: false,
1240
+ redirect_chain: [],
1241
+ details: null,
1242
+ accepted: () => {
1243
+ current_history_index = event.state[INDEX_KEY];
1244
+ },
1245
+ blocked: () => {
1246
+ const delta = current_history_index - event.state[INDEX_KEY];
1247
+ history.go(delta);
1248
+ }
1249
+ });
1250
+ }
1251
+ });
1252
+
1253
+ addEventListener('hashchange', () => {
1254
+ // if the hashchange happened as a result of clicking on a link,
1255
+ // we need to update history, otherwise we have to leave it alone
1256
+ if (hash_navigating) {
1257
+ hash_navigating = false;
1258
+ history.replaceState(
1259
+ { ...history.state, [INDEX_KEY]: ++current_history_index },
1260
+ '',
1261
+ location.href
1262
+ );
1263
+ }
1264
+ });
1265
+
1266
+ // fix link[rel=icon], because browsers will occasionally try to load relative
1267
+ // URLs after a pushState/replaceState, resulting in a 404 — see
1268
+ // https://github.com/sveltejs/kit/issues/3748#issuecomment-1125980897
1269
+ for (const link of document.querySelectorAll('link')) {
1270
+ if (link.rel === 'icon') link.href = link.href;
1271
+ }
1272
+
1273
+ addEventListener('pageshow', (event) => {
1274
+ // If the user navigates to another site and then uses the back button and
1275
+ // bfcache hits, we need to set navigating to null, the site doesn't know
1276
+ // the navigation away from it was successful.
1277
+ // Info about bfcache here: https://web.dev/bfcache
1278
+ if (event.persisted) {
1279
+ stores.navigating.set(null);
1280
+ }
1281
+ });
1282
+ },
1283
+
1284
+ _hydrate: async ({
1285
+ status,
1286
+ error: original_error, // TODO get rid of this
1287
+ node_ids,
1288
+ params,
1289
+ routeId,
1290
+ data: server_data_nodes,
1291
+ errors: validation_errors
1292
+ }) => {
1293
+ const url = new URL(location.href);
1294
+
1295
+ /** @type {import('./types').NavigationFinished | undefined} */
1296
+ let result;
1297
+
1298
+ try {
1299
+ const branch_promises = node_ids.map(async (n, i) => {
1300
+ const server_data_node = server_data_nodes[i];
1301
+
1302
+ return load_node({
1303
+ loader: nodes[n],
1304
+ url,
1305
+ params,
1306
+ routeId,
1307
+ parent: async () => {
1308
+ const data = {};
1309
+ for (let j = 0; j < i; j += 1) {
1310
+ Object.assign(data, (await branch_promises[j]).data);
1311
+ }
1312
+ return data;
1313
+ },
1314
+ server_data_node: create_data_node(server_data_node)
1315
+ });
1316
+ });
1317
+
1318
+ result = await get_navigation_result_from_branch({
1319
+ url,
1320
+ params,
1321
+ branch: await Promise.all(branch_promises),
1322
+ status,
1323
+ error: /** @type {import('../server/page/types').SerializedHttpError} */ (original_error)
1324
+ ?.__is_http_error
1325
+ ? new HttpError(
1326
+ /** @type {import('../server/page/types').SerializedHttpError} */ (
1327
+ original_error
1328
+ ).status,
1329
+ original_error.message
1330
+ )
1331
+ : original_error,
1332
+ validation_errors,
1333
+ routeId
1334
+ });
1335
+ } catch (e) {
1336
+ const error = normalize_error(e);
1337
+
1338
+ if (error instanceof Redirect) {
1339
+ // this is a real edge case — `load` would need to return
1340
+ // a redirect but only in the browser
1341
+ await native_navigation(new URL(/** @type {Redirect} */ (e).location, location.href));
1342
+ return;
1343
+ }
1344
+
1345
+ result = await load_root_error_page({
1346
+ status: error instanceof HttpError ? error.status : 500,
1347
+ error,
1348
+ url,
1349
+ routeId
1350
+ });
1351
+ }
1352
+
1353
+ initialize(result);
1354
+ }
1355
+ };
1356
+ }
1357
+
1358
+ let data_id = 1;
1359
+
1360
+ /**
1361
+ * @param {URL} url
1362
+ * @param {boolean[]} invalid
1363
+ * @returns {Promise<import('types').ServerData>}
1364
+ */
1365
+ async function load_data(url, invalid) {
1366
+ const data_url = new URL(url);
1367
+ data_url.pathname = url.pathname.replace(/\/$/, '') + DATA_SUFFIX;
1368
+ data_url.searchParams.set('__invalid', invalid.map((x) => (x ? 'y' : 'n')).join(''));
1369
+ data_url.searchParams.set('__id', String(data_id++));
1370
+
1371
+ // The __data.js file is generated by the server and looks like
1372
+ // `window.__sveltekit_data = ${devalue(data)}`. We do this instead
1373
+ // of `export const data` because modules are cached indefinitely,
1374
+ // and that would cause memory leaks.
1375
+ //
1376
+ // The data is read and deleted in the same tick as the promise
1377
+ // resolves, so it's not vulnerable to race conditions
1378
+ await import(/* @vite-ignore */ data_url.href);
1379
+
1380
+ // @ts-expect-error
1381
+ const server_data = window.__sveltekit_data;
1382
+
1383
+ // @ts-expect-error
1384
+ delete window.__sveltekit_data;
1385
+
1386
+ return server_data;
1387
+ }