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

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