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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (117) hide show
  1. package/README.md +12 -9
  2. package/package.json +93 -64
  3. package/scripts/special-types/$env+dynamic+private.md +8 -0
  4. package/scripts/special-types/$env+dynamic+public.md +8 -0
  5. package/scripts/special-types/$env+static+private.md +19 -0
  6. package/scripts/special-types/$env+static+public.md +7 -0
  7. package/scripts/special-types/$lib.md +1 -0
  8. package/src/cli.js +112 -0
  9. package/src/constants.js +7 -0
  10. package/src/core/adapt/builder.js +207 -0
  11. package/src/core/adapt/index.js +31 -0
  12. package/src/core/config/default-error.html +56 -0
  13. package/src/core/config/index.js +105 -0
  14. package/src/core/config/options.js +492 -0
  15. package/src/core/config/types.d.ts +1 -0
  16. package/src/core/env.js +121 -0
  17. package/src/core/generate_manifest/index.js +92 -0
  18. package/src/core/prerender/crawl.js +194 -0
  19. package/src/core/prerender/prerender.js +431 -0
  20. package/src/core/prerender/queue.js +80 -0
  21. package/src/core/sync/create_manifest_data/index.js +472 -0
  22. package/src/core/sync/create_manifest_data/types.d.ts +37 -0
  23. package/src/core/sync/sync.js +59 -0
  24. package/src/core/sync/utils.js +33 -0
  25. package/src/core/sync/write_ambient.js +53 -0
  26. package/src/core/sync/write_client_manifest.js +94 -0
  27. package/src/core/sync/write_matchers.js +25 -0
  28. package/src/core/sync/write_root.js +91 -0
  29. package/src/core/sync/write_tsconfig.js +195 -0
  30. package/src/core/sync/write_types/index.js +673 -0
  31. package/src/core/utils.js +70 -0
  32. package/src/exports/hooks/index.js +1 -0
  33. package/src/exports/hooks/sequence.js +44 -0
  34. package/src/exports/index.js +54 -0
  35. package/src/exports/node/index.js +145 -0
  36. package/src/exports/node/polyfills.js +41 -0
  37. package/src/exports/vite/build/build_server.js +357 -0
  38. package/src/exports/vite/build/build_service_worker.js +90 -0
  39. package/src/exports/vite/build/utils.js +162 -0
  40. package/src/exports/vite/dev/index.js +554 -0
  41. package/src/exports/vite/index.js +591 -0
  42. package/src/exports/vite/preview/index.js +186 -0
  43. package/src/exports/vite/types.d.ts +3 -0
  44. package/src/exports/vite/utils.js +361 -0
  45. package/src/runtime/app/env.js +1 -0
  46. package/src/runtime/app/environment.js +11 -0
  47. package/src/runtime/app/forms.js +65 -0
  48. package/src/runtime/app/navigation.js +23 -0
  49. package/src/runtime/app/paths.js +1 -0
  50. package/src/runtime/app/stores.js +102 -0
  51. package/src/runtime/client/ambient.d.ts +24 -0
  52. package/src/runtime/client/client.js +1558 -0
  53. package/src/runtime/client/fetcher.js +107 -0
  54. package/src/runtime/client/parse.js +60 -0
  55. package/src/runtime/client/singletons.js +21 -0
  56. package/src/runtime/client/start.js +37 -0
  57. package/src/runtime/client/types.d.ts +87 -0
  58. package/src/runtime/client/utils.js +159 -0
  59. package/src/runtime/components/error.svelte +16 -0
  60. package/{assets → src/runtime}/components/layout.svelte +0 -0
  61. package/src/runtime/control.js +100 -0
  62. package/src/runtime/env/dynamic/private.js +1 -0
  63. package/src/runtime/env/dynamic/public.js +1 -0
  64. package/src/runtime/env-private.js +6 -0
  65. package/src/runtime/env-public.js +6 -0
  66. package/src/runtime/env.js +6 -0
  67. package/src/runtime/hash.js +16 -0
  68. package/src/runtime/paths.js +11 -0
  69. package/src/runtime/server/cookie.js +76 -0
  70. package/src/runtime/server/data/index.js +146 -0
  71. package/src/runtime/server/endpoint.js +66 -0
  72. package/src/runtime/server/index.js +339 -0
  73. package/src/runtime/server/page/actions.js +225 -0
  74. package/src/runtime/server/page/crypto.js +239 -0
  75. package/src/runtime/server/page/csp.js +249 -0
  76. package/src/runtime/server/page/fetch.js +286 -0
  77. package/src/runtime/server/page/index.js +308 -0
  78. package/src/runtime/server/page/load_data.js +124 -0
  79. package/src/runtime/server/page/render.js +359 -0
  80. package/src/runtime/server/page/respond_with_error.js +92 -0
  81. package/src/runtime/server/page/serialize_data.js +87 -0
  82. package/src/runtime/server/page/types.d.ts +41 -0
  83. package/src/runtime/server/utils.js +220 -0
  84. package/src/utils/array.js +9 -0
  85. package/src/utils/error.js +22 -0
  86. package/src/utils/escape.js +46 -0
  87. package/src/utils/filesystem.js +108 -0
  88. package/src/utils/functions.js +16 -0
  89. package/src/utils/http.js +55 -0
  90. package/src/utils/misc.js +1 -0
  91. package/src/utils/routing.js +117 -0
  92. package/src/utils/url.js +142 -0
  93. package/svelte-kit.js +1 -1
  94. package/types/ambient.d.ts +404 -0
  95. package/types/index.d.ts +396 -0
  96. package/types/internal.d.ts +377 -0
  97. package/types/private.d.ts +210 -0
  98. package/CHANGELOG.md +0 -463
  99. package/assets/components/error.svelte +0 -13
  100. package/assets/runtime/app/env.js +0 -5
  101. package/assets/runtime/app/navigation.js +0 -44
  102. package/assets/runtime/app/paths.js +0 -1
  103. package/assets/runtime/app/stores.js +0 -93
  104. package/assets/runtime/chunks/utils.js +0 -22
  105. package/assets/runtime/internal/singletons.js +0 -23
  106. package/assets/runtime/internal/start.js +0 -773
  107. package/assets/runtime/paths.js +0 -12
  108. package/dist/chunks/index.js +0 -3517
  109. package/dist/chunks/index2.js +0 -587
  110. package/dist/chunks/index3.js +0 -246
  111. package/dist/chunks/index4.js +0 -530
  112. package/dist/chunks/index5.js +0 -763
  113. package/dist/chunks/index6.js +0 -322
  114. package/dist/chunks/standard.js +0 -99
  115. package/dist/chunks/utils.js +0 -83
  116. package/dist/cli.js +0 -553
  117. package/dist/ssr.js +0 -2581
@@ -0,0 +1,1558 @@
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, true);
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, false);
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
+ const post_update = pre_update();
282
+ root.$set(navigation_result.props);
283
+ post_update();
284
+ } else {
285
+ initialize(navigation_result);
286
+ }
287
+
288
+ // opts must be passed if we're navigating
289
+ if (opts) {
290
+ const { scroll, keepfocus } = opts;
291
+
292
+ if (!keepfocus) {
293
+ // Reset page selection and focus
294
+ // We try to mimic browsers' behaviour as closely as possible by targeting the
295
+ // first scrollable region, but unfortunately it's not a perfect match — e.g.
296
+ // shift-tabbing won't immediately cycle up from the end of the page on Chromium
297
+ // See https://html.spec.whatwg.org/multipage/interaction.html#get-the-focusable-area
298
+ const root = document.body;
299
+ const tabindex = root.getAttribute('tabindex');
300
+
301
+ root.tabIndex = -1;
302
+ root.focus({ preventScroll: true });
303
+
304
+ setTimeout(() => {
305
+ getSelection()?.removeAllRanges();
306
+ });
307
+
308
+ // restore `tabindex` as to prevent `root` from stealing input from elements
309
+ if (tabindex !== null) {
310
+ root.setAttribute('tabindex', tabindex);
311
+ } else {
312
+ root.removeAttribute('tabindex');
313
+ }
314
+ }
315
+
316
+ // need to render the DOM before we can scroll to the rendered elements
317
+ await tick();
318
+
319
+ if (autoscroll) {
320
+ const deep_linked = url.hash && document.getElementById(url.hash.slice(1));
321
+ if (scroll) {
322
+ scrollTo(scroll.x, scroll.y);
323
+ } else if (deep_linked) {
324
+ // Here we use `scrollIntoView` on the element instead of `scrollTo`
325
+ // because it natively supports the `scroll-margin` and `scroll-behavior`
326
+ // CSS properties.
327
+ deep_linked.scrollIntoView();
328
+ } else {
329
+ scrollTo(0, 0);
330
+ }
331
+ }
332
+ } else {
333
+ // in this case we're simply invalidating
334
+ await tick();
335
+ }
336
+
337
+ load_cache.promise = null;
338
+ load_cache.id = null;
339
+ autoscroll = true;
340
+
341
+ if (navigation_result.props.page) {
342
+ page = navigation_result.props.page;
343
+ }
344
+
345
+ if (callback) callback();
346
+
347
+ updating = false;
348
+ }
349
+
350
+ /** @param {import('./types').NavigationFinished} result */
351
+ function initialize(result) {
352
+ current = result.state;
353
+
354
+ const style = document.querySelector('style[data-sveltekit]');
355
+ if (style) style.remove();
356
+
357
+ page = result.props.page;
358
+
359
+ const post_update = pre_update();
360
+ root = new Root({
361
+ target,
362
+ props: { ...result.props, stores },
363
+ hydrate: true
364
+ });
365
+ post_update();
366
+
367
+ /** @type {import('types').Navigation} */
368
+ const navigation = {
369
+ from: null,
370
+ to: add_url_properties('to', {
371
+ params: current.params,
372
+ routeId: current.route?.id ?? null,
373
+ url: new URL(location.href)
374
+ }),
375
+ type: 'load'
376
+ };
377
+ callbacks.after_navigate.forEach((fn) => fn(navigation));
378
+
379
+ started = true;
380
+ }
381
+
382
+ /**
383
+ *
384
+ * @param {{
385
+ * url: URL;
386
+ * params: Record<string, string>;
387
+ * branch: Array<import('./types').BranchNode | undefined>;
388
+ * status: number;
389
+ * error: HttpError | Error | null;
390
+ * route: import('types').CSRRoute | null;
391
+ * form?: Record<string, any> | null;
392
+ * }} opts
393
+ */
394
+ async function get_navigation_result_from_branch({
395
+ url,
396
+ params,
397
+ branch,
398
+ status,
399
+ error,
400
+ route,
401
+ form
402
+ }) {
403
+ const filtered = /** @type {import('./types').BranchNode[] } */ (branch.filter(Boolean));
404
+
405
+ /** @type {import('./types').NavigationFinished} */
406
+ const result = {
407
+ type: 'loaded',
408
+ state: {
409
+ url,
410
+ params,
411
+ branch,
412
+ error,
413
+ route,
414
+ session_id
415
+ },
416
+ props: {
417
+ components: filtered.map((branch_node) => branch_node.node.component)
418
+ }
419
+ };
420
+
421
+ if (form !== undefined) {
422
+ result.props.form = form;
423
+ }
424
+
425
+ let data = {};
426
+ let data_changed = !page;
427
+ for (let i = 0; i < filtered.length; i += 1) {
428
+ const node = filtered[i];
429
+ data = { ...data, ...node.data };
430
+
431
+ // Only set props if the node actually updated. This prevents needless rerenders.
432
+ if (data_changed || !current.branch.some((previous) => previous === node)) {
433
+ result.props[`data_${i}`] = data;
434
+ data_changed = data_changed || Object.keys(node.data ?? {}).length > 0;
435
+ }
436
+ }
437
+ if (!data_changed) {
438
+ // If nothing was added, and the object entries are the same length, this means
439
+ // that nothing was removed either and therefore the data is the same as the previous one.
440
+ // This would be more readable with a separate boolean but that would cost us some bytes.
441
+ data_changed = Object.keys(page.data).length !== Object.keys(data).length;
442
+ }
443
+
444
+ const page_changed =
445
+ !current.url || url.href !== current.url.href || current.error !== error || data_changed;
446
+
447
+ if (page_changed) {
448
+ result.props.page = {
449
+ error,
450
+ params,
451
+ routeId: route && route.id,
452
+ status,
453
+ url,
454
+ // The whole page store is updated, but this way the object reference stays the same
455
+ data: data_changed ? data : page.data
456
+ };
457
+
458
+ // TODO remove this for 1.0
459
+ /**
460
+ * @param {string} property
461
+ * @param {string} replacement
462
+ */
463
+ const print_error = (property, replacement) => {
464
+ Object.defineProperty(result.props.page, property, {
465
+ get: () => {
466
+ throw new Error(`$page.${property} has been replaced by $page.url.${replacement}`);
467
+ }
468
+ });
469
+ };
470
+
471
+ print_error('origin', 'origin');
472
+ print_error('path', 'pathname');
473
+ print_error('query', 'searchParams');
474
+ }
475
+
476
+ return result;
477
+ }
478
+
479
+ /**
480
+ * Call the load function of the given node, if it exists.
481
+ * If `server_data` is passed, this is treated as the initial run and the page endpoint is not requested.
482
+ *
483
+ * @param {{
484
+ * loader: import('types').CSRPageNodeLoader;
485
+ * parent: () => Promise<Record<string, any>>;
486
+ * url: URL;
487
+ * params: Record<string, string>;
488
+ * routeId: string | null;
489
+ * server_data_node: import('./types').DataNode | null;
490
+ * }} options
491
+ * @returns {Promise<import('./types').BranchNode>}
492
+ */
493
+ async function load_node({ loader, parent, url, params, routeId, server_data_node }) {
494
+ /** @type {Record<string, any> | null} */
495
+ let data = null;
496
+
497
+ /** @type {import('types').Uses} */
498
+ const uses = {
499
+ dependencies: new Set(),
500
+ params: new Set(),
501
+ parent: false,
502
+ url: false
503
+ };
504
+
505
+ const node = await loader();
506
+
507
+ if (node.shared?.load) {
508
+ /** @param {string[]} deps */
509
+ function depends(...deps) {
510
+ for (const dep of deps) {
511
+ const { href } = new URL(dep, url);
512
+ uses.dependencies.add(href);
513
+ }
514
+ }
515
+
516
+ /** @type {Record<string, string>} */
517
+ const uses_params = {};
518
+ for (const key in params) {
519
+ Object.defineProperty(uses_params, key, {
520
+ get() {
521
+ uses.params.add(key);
522
+ return params[key];
523
+ },
524
+ enumerable: true
525
+ });
526
+ }
527
+
528
+ /** @type {import('types').LoadEvent} */
529
+ const load_input = {
530
+ routeId,
531
+ params: uses_params,
532
+ data: server_data_node?.data ?? null,
533
+ url: make_trackable(url, () => {
534
+ uses.url = true;
535
+ }),
536
+ async fetch(resource, init) {
537
+ let requested;
538
+
539
+ if (typeof resource === 'string') {
540
+ requested = resource;
541
+ } else {
542
+ requested = resource.url;
543
+
544
+ // we're not allowed to modify the received `Request` object, so in order
545
+ // to fixup relative urls we create a new equivalent `init` object instead
546
+ init = {
547
+ // the request body must be consumed in memory until browsers
548
+ // implement streaming request bodies and/or the body getter
549
+ body:
550
+ resource.method === 'GET' || resource.method === 'HEAD'
551
+ ? undefined
552
+ : await resource.blob(),
553
+ cache: resource.cache,
554
+ credentials: resource.credentials,
555
+ headers: resource.headers,
556
+ integrity: resource.integrity,
557
+ keepalive: resource.keepalive,
558
+ method: resource.method,
559
+ mode: resource.mode,
560
+ redirect: resource.redirect,
561
+ referrer: resource.referrer,
562
+ referrerPolicy: resource.referrerPolicy,
563
+ signal: resource.signal,
564
+ ...init
565
+ };
566
+ }
567
+
568
+ // we must fixup relative urls so they are resolved from the target page
569
+ const resolved = new URL(requested, url).href;
570
+ depends(resolved);
571
+
572
+ // prerendered pages may be served from any origin, so `initial_fetch` urls shouldn't be resolved
573
+ return started
574
+ ? subsequent_fetch(resolved, init)
575
+ : initial_fetch(requested, resolved, init);
576
+ },
577
+ setHeaders: () => {}, // noop
578
+ depends,
579
+ parent() {
580
+ uses.parent = true;
581
+ return parent();
582
+ }
583
+ };
584
+
585
+ // TODO remove this for 1.0
586
+ Object.defineProperties(load_input, {
587
+ props: {
588
+ get() {
589
+ throw new Error(
590
+ '@migration task: Replace `props` with `data` stuff https://github.com/sveltejs/kit/discussions/5774#discussioncomment-3292693'
591
+ );
592
+ },
593
+ enumerable: false
594
+ },
595
+ session: {
596
+ get() {
597
+ throw new Error(
598
+ 'session is no longer available. See https://github.com/sveltejs/kit/discussions/5883'
599
+ );
600
+ },
601
+ enumerable: false
602
+ },
603
+ stuff: {
604
+ get() {
605
+ throw new Error(
606
+ '@migration task: Remove stuff https://github.com/sveltejs/kit/discussions/5774#discussioncomment-3292693'
607
+ );
608
+ },
609
+ enumerable: false
610
+ }
611
+ });
612
+
613
+ if (import.meta.env.DEV) {
614
+ try {
615
+ lock_fetch();
616
+ data = (await node.shared.load.call(null, load_input)) ?? null;
617
+ } finally {
618
+ unlock_fetch();
619
+ }
620
+ } else {
621
+ data = (await node.shared.load.call(null, load_input)) ?? null;
622
+ }
623
+ }
624
+
625
+ return {
626
+ node,
627
+ loader,
628
+ server: server_data_node,
629
+ shared: node.shared?.load ? { type: 'data', data, uses } : null,
630
+ data: data ?? server_data_node?.data ?? null
631
+ };
632
+ }
633
+
634
+ /**
635
+ * @param {import('types').Uses | undefined} uses
636
+ * @param {boolean} parent_changed
637
+ * @param {{ url: boolean, params: string[] }} changed
638
+ */
639
+ function has_changed(changed, parent_changed, uses) {
640
+ if (force_invalidation) return true;
641
+
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 href of uses.dependencies) {
652
+ if (invalidated.some((fn) => fn(new URL(href)))) 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, invalidating, 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
+ route
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
+ route,
854
+ // Reset `form` on navigation, but not invalidation
855
+ form: invalidating ? undefined : null
856
+ });
857
+ }
858
+
859
+ /**
860
+ * @param {{
861
+ * status: number;
862
+ * error: HttpError | Error;
863
+ * url: URL;
864
+ * routeId: string | null
865
+ * }} opts
866
+ * @returns {Promise<import('./types').NavigationFinished>}
867
+ */
868
+ async function load_root_error_page({ status, error, url, routeId }) {
869
+ /** @type {Record<string, string>} */
870
+ const params = {}; // error page does not have params
871
+
872
+ const node = await default_layout_loader();
873
+
874
+ /** @type {import('types').ServerDataNode | null} */
875
+ let server_data_node = null;
876
+
877
+ if (node.server) {
878
+ // TODO post-https://github.com/sveltejs/kit/discussions/6124 we can use
879
+ // existing root layout data
880
+ try {
881
+ const server_data = await load_data(url, [true]);
882
+
883
+ if (
884
+ server_data.type !== 'data' ||
885
+ (server_data.nodes[0] && server_data.nodes[0].type !== 'data')
886
+ ) {
887
+ throw 0;
888
+ }
889
+
890
+ server_data_node = server_data.nodes[0] ?? null;
891
+ } catch {
892
+ // at this point we have no choice but to fall back to the server
893
+ await native_navigation(url);
894
+
895
+ // @ts-expect-error
896
+ return;
897
+ }
898
+ }
899
+
900
+ const root_layout = await load_node({
901
+ loader: default_layout_loader,
902
+ url,
903
+ params,
904
+ routeId,
905
+ parent: () => Promise.resolve({}),
906
+ server_data_node: create_data_node(server_data_node)
907
+ });
908
+
909
+ /** @type {import('./types').BranchNode} */
910
+ const root_error = {
911
+ node: await default_error_loader(),
912
+ loader: default_error_loader,
913
+ shared: null,
914
+ server: null,
915
+ data: null
916
+ };
917
+
918
+ return await get_navigation_result_from_branch({
919
+ url,
920
+ params,
921
+ branch: [root_layout, root_error],
922
+ status,
923
+ error,
924
+ route: null
925
+ });
926
+ }
927
+
928
+ /**
929
+ * @param {URL} url
930
+ * @param {boolean} invalidating
931
+ */
932
+ function get_navigation_intent(url, invalidating) {
933
+ if (is_external_url(url)) return;
934
+
935
+ const path = decodeURI(url.pathname.slice(base.length) || '/');
936
+
937
+ for (const route of routes) {
938
+ const params = route.exec(path);
939
+
940
+ if (params) {
941
+ const normalized = new URL(
942
+ url.origin + normalize_path(url.pathname, trailing_slash) + url.search + url.hash
943
+ );
944
+ const id = normalized.pathname + normalized.search;
945
+ /** @type {import('./types').NavigationIntent} */
946
+ const intent = { id, invalidating, route, params: decode_params(params), url: normalized };
947
+ return intent;
948
+ }
949
+ }
950
+ }
951
+
952
+ /** @param {URL} url */
953
+ function is_external_url(url) {
954
+ return url.origin !== location.origin || !url.pathname.startsWith(base);
955
+ }
956
+
957
+ /**
958
+ * @param {{
959
+ * url: URL;
960
+ * scroll: { x: number, y: number } | null;
961
+ * keepfocus: boolean;
962
+ * redirect_chain: string[];
963
+ * details: {
964
+ * replaceState: boolean;
965
+ * state: any;
966
+ * } | null;
967
+ * type: import('types').NavigationType;
968
+ * delta?: number;
969
+ * accepted: () => void;
970
+ * blocked: () => void;
971
+ * }} opts
972
+ */
973
+ async function navigate({
974
+ url,
975
+ scroll,
976
+ keepfocus,
977
+ redirect_chain,
978
+ details,
979
+ type,
980
+ delta,
981
+ accepted,
982
+ blocked
983
+ }) {
984
+ let should_block = false;
985
+
986
+ const intent = get_navigation_intent(url, false);
987
+
988
+ /** @type {import('types').Navigation} */
989
+ const navigation = {
990
+ from: add_url_properties('from', {
991
+ params: current.params,
992
+ routeId: current.route?.id ?? null,
993
+ url: current.url
994
+ }),
995
+ to: add_url_properties('to', {
996
+ params: intent?.params ?? null,
997
+ routeId: intent?.route.id ?? null,
998
+ url
999
+ }),
1000
+ type
1001
+ };
1002
+
1003
+ if (delta !== undefined) {
1004
+ navigation.delta = delta;
1005
+ }
1006
+
1007
+ const cancellable = {
1008
+ ...navigation,
1009
+ cancel: () => {
1010
+ should_block = true;
1011
+ }
1012
+ };
1013
+
1014
+ callbacks.before_navigate.forEach((fn) => fn(cancellable));
1015
+
1016
+ if (should_block) {
1017
+ blocked();
1018
+ return;
1019
+ }
1020
+
1021
+ update_scroll_positions(current_history_index);
1022
+
1023
+ accepted();
1024
+
1025
+ if (started) {
1026
+ stores.navigating.set(navigation);
1027
+ }
1028
+
1029
+ await update(
1030
+ intent,
1031
+ url,
1032
+ redirect_chain,
1033
+ {
1034
+ scroll,
1035
+ keepfocus,
1036
+ details
1037
+ },
1038
+ () => {
1039
+ callbacks.after_navigate.forEach((fn) => fn(navigation));
1040
+ stores.navigating.set(null);
1041
+ }
1042
+ );
1043
+ }
1044
+
1045
+ /**
1046
+ * Loads `href` the old-fashioned way, with a full page reload.
1047
+ * Returns a `Promise` that never resolves (to prevent any
1048
+ * subsequent work, e.g. history manipulation, from happening)
1049
+ * @param {URL} url
1050
+ */
1051
+ function native_navigation(url) {
1052
+ location.href = url.href;
1053
+ return new Promise(() => {});
1054
+ }
1055
+
1056
+ if (import.meta.hot) {
1057
+ import.meta.hot.on('vite:beforeUpdate', () => {
1058
+ if (current.error) location.reload();
1059
+ });
1060
+ }
1061
+
1062
+ return {
1063
+ after_navigate: (fn) => {
1064
+ onMount(() => {
1065
+ callbacks.after_navigate.push(fn);
1066
+
1067
+ return () => {
1068
+ const i = callbacks.after_navigate.indexOf(fn);
1069
+ callbacks.after_navigate.splice(i, 1);
1070
+ };
1071
+ });
1072
+ },
1073
+
1074
+ before_navigate: (fn) => {
1075
+ onMount(() => {
1076
+ callbacks.before_navigate.push(fn);
1077
+
1078
+ return () => {
1079
+ const i = callbacks.before_navigate.indexOf(fn);
1080
+ callbacks.before_navigate.splice(i, 1);
1081
+ };
1082
+ });
1083
+ },
1084
+
1085
+ disable_scroll_handling: () => {
1086
+ if (import.meta.env.DEV && started && !updating) {
1087
+ throw new Error('Can only disable scroll handling during navigation');
1088
+ }
1089
+
1090
+ if (updating || !started) {
1091
+ autoscroll = false;
1092
+ }
1093
+ },
1094
+
1095
+ goto: (href, opts = {}) => goto(href, opts, []),
1096
+
1097
+ invalidate: (resource) => {
1098
+ if (resource === undefined) {
1099
+ // TODO remove for 1.0
1100
+ throw new Error(
1101
+ '`invalidate()` (with no arguments) has been replaced by `invalidateAll()`'
1102
+ );
1103
+ }
1104
+
1105
+ if (typeof resource === 'function') {
1106
+ invalidated.push(resource);
1107
+ } else {
1108
+ const { href } = new URL(resource, location.href);
1109
+ invalidated.push((url) => url.href === href);
1110
+ }
1111
+
1112
+ return invalidate();
1113
+ },
1114
+
1115
+ invalidateAll: () => {
1116
+ force_invalidation = true;
1117
+ return invalidate();
1118
+ },
1119
+
1120
+ prefetch: async (href) => {
1121
+ const url = new URL(href, get_base_uri(document));
1122
+ await prefetch(url);
1123
+ },
1124
+
1125
+ // TODO rethink this API
1126
+ prefetch_routes: async (pathnames) => {
1127
+ const matching = pathnames
1128
+ ? routes.filter((route) => pathnames.some((pathname) => route.exec(pathname)))
1129
+ : routes;
1130
+
1131
+ const promises = matching.map((r) => {
1132
+ return Promise.all([...r.layouts, r.leaf].map((load) => load?.[1]()));
1133
+ });
1134
+
1135
+ await Promise.all(promises);
1136
+ },
1137
+
1138
+ apply_action: async (result) => {
1139
+ if (result.type === 'error') {
1140
+ const url = new URL(location.href);
1141
+
1142
+ const { branch, route } = current;
1143
+ if (!route) return;
1144
+
1145
+ let i = current.branch.length;
1146
+
1147
+ while (i--) {
1148
+ if (route.errors[i]) {
1149
+ /** @type {import('./types').BranchNode | undefined} */
1150
+ let error_loaded;
1151
+
1152
+ let j = i;
1153
+ while (!branch[j]) j -= 1;
1154
+ try {
1155
+ error_loaded = {
1156
+ node: await /** @type {import('types').CSRPageNodeLoader } */ (route.errors[i])(),
1157
+ loader: /** @type {import('types').CSRPageNodeLoader } */ (route.errors[i]),
1158
+ data: {},
1159
+ server: null,
1160
+ shared: null
1161
+ };
1162
+
1163
+ const navigation_result = await get_navigation_result_from_branch({
1164
+ url,
1165
+ params: current.params,
1166
+ branch: branch.slice(0, j + 1).concat(error_loaded),
1167
+ status: 500, // TODO might not be 500?
1168
+ error: result.error,
1169
+ route
1170
+ });
1171
+
1172
+ current = navigation_result.state;
1173
+
1174
+ const post_update = pre_update();
1175
+ root.$set(navigation_result.props);
1176
+ post_update();
1177
+
1178
+ return;
1179
+ } catch (e) {
1180
+ continue;
1181
+ }
1182
+ }
1183
+ }
1184
+ } else if (result.type === 'redirect') {
1185
+ goto(result.location, {}, []);
1186
+ } else {
1187
+ /** @type {Record<string, any>} */
1188
+ const props = { form: result.data };
1189
+
1190
+ if (result.status !== page.status) {
1191
+ props.page = {
1192
+ ...page,
1193
+ status: result.status
1194
+ };
1195
+ }
1196
+
1197
+ const post_update = pre_update();
1198
+ root.$set(props);
1199
+ post_update();
1200
+ }
1201
+ },
1202
+
1203
+ _start_router: () => {
1204
+ history.scrollRestoration = 'manual';
1205
+
1206
+ // Adopted from Nuxt.js
1207
+ // Reset scrollRestoration to auto when leaving page, allowing page reload
1208
+ // and back-navigation from other pages to use the browser to restore the
1209
+ // scrolling position.
1210
+ addEventListener('beforeunload', (e) => {
1211
+ let should_block = false;
1212
+
1213
+ /** @type {import('types').Navigation & { cancel: () => void }} */
1214
+ const navigation = {
1215
+ from: add_url_properties('from', {
1216
+ params: current.params,
1217
+ routeId: current.route?.id ?? null,
1218
+ url: current.url
1219
+ }),
1220
+ to: null,
1221
+ type: 'unload',
1222
+ cancel: () => (should_block = true)
1223
+ };
1224
+
1225
+ callbacks.before_navigate.forEach((fn) => fn(navigation));
1226
+
1227
+ if (should_block) {
1228
+ e.preventDefault();
1229
+ e.returnValue = '';
1230
+ } else {
1231
+ history.scrollRestoration = 'auto';
1232
+ }
1233
+ });
1234
+
1235
+ addEventListener('visibilitychange', () => {
1236
+ if (document.visibilityState === 'hidden') {
1237
+ update_scroll_positions(current_history_index);
1238
+
1239
+ try {
1240
+ sessionStorage[SCROLL_KEY] = JSON.stringify(scroll_positions);
1241
+ } catch {
1242
+ // do nothing
1243
+ }
1244
+ }
1245
+ });
1246
+
1247
+ /** @param {Event} event */
1248
+ const trigger_prefetch = (event) => {
1249
+ const { url, options } = find_anchor(event);
1250
+ if (url && options.prefetch) {
1251
+ if (is_external_url(url)) return;
1252
+ prefetch(url);
1253
+ }
1254
+ };
1255
+
1256
+ /** @type {NodeJS.Timeout} */
1257
+ let mousemove_timeout;
1258
+
1259
+ /** @param {MouseEvent|TouchEvent} event */
1260
+ const handle_mousemove = (event) => {
1261
+ clearTimeout(mousemove_timeout);
1262
+ mousemove_timeout = setTimeout(() => {
1263
+ // event.composedPath(), which is used in find_anchor, will be empty if the event is read in a timeout
1264
+ // add a layer of indirection to address that
1265
+ event.target?.dispatchEvent(
1266
+ new CustomEvent('sveltekit:trigger_prefetch', { bubbles: true })
1267
+ );
1268
+ }, 20);
1269
+ };
1270
+
1271
+ addEventListener('touchstart', trigger_prefetch);
1272
+ addEventListener('mousemove', handle_mousemove);
1273
+ addEventListener('sveltekit:trigger_prefetch', trigger_prefetch);
1274
+
1275
+ /** @param {MouseEvent} event */
1276
+ addEventListener('click', (event) => {
1277
+ // Adapted from https://github.com/visionmedia/page.js
1278
+ // MIT license https://github.com/visionmedia/page.js#license
1279
+ if (event.button || event.which !== 1) return;
1280
+ if (event.metaKey || event.ctrlKey || event.shiftKey || event.altKey) return;
1281
+ if (event.defaultPrevented) return;
1282
+
1283
+ const { a, url, options } = find_anchor(event);
1284
+ if (!a || !url) return;
1285
+
1286
+ const is_svg_a_element = a instanceof SVGAElement;
1287
+
1288
+ // Ignore non-HTTP URL protocols (e.g. `mailto:`, `tel:`, `myapp:`, etc.)
1289
+ // MEMO: Without this condition, firefox will open mailer twice.
1290
+ // See:
1291
+ // - https://github.com/sveltejs/kit/issues/4045
1292
+ // - https://github.com/sveltejs/kit/issues/5725
1293
+ if (!is_svg_a_element && !(url.protocol === 'https:' || url.protocol === 'http:')) return;
1294
+
1295
+ // Ignore if tag has
1296
+ // 1. 'download' attribute
1297
+ // 2. 'rel' attribute includes external
1298
+ const rel = (a.getAttribute('rel') || '').split(/\s+/);
1299
+
1300
+ if (a.hasAttribute('download') || rel.includes('external') || options.reload) {
1301
+ return;
1302
+ }
1303
+
1304
+ // Ignore if <a> has a target
1305
+ if (is_svg_a_element ? a.target.baseVal : a.target) return;
1306
+
1307
+ // Check if new url only differs by hash and use the browser default behavior in that case
1308
+ // This will ensure the `hashchange` event is fired
1309
+ // Removing the hash does a full page navigation in the browser, so make sure a hash is present
1310
+ const [base, hash] = url.href.split('#');
1311
+ if (hash !== undefined && base === location.href.split('#')[0]) {
1312
+ // set this flag to distinguish between navigations triggered by
1313
+ // clicking a hash link and those triggered by popstate
1314
+ hash_navigating = true;
1315
+
1316
+ update_scroll_positions(current_history_index);
1317
+
1318
+ stores.page.set({ ...page, url });
1319
+ stores.page.notify();
1320
+
1321
+ return;
1322
+ }
1323
+
1324
+ navigate({
1325
+ url,
1326
+ scroll: options.noscroll ? scroll_state() : null,
1327
+ keepfocus: false,
1328
+ redirect_chain: [],
1329
+ details: {
1330
+ state: {},
1331
+ replaceState: url.href === location.href
1332
+ },
1333
+ accepted: () => event.preventDefault(),
1334
+ blocked: () => event.preventDefault(),
1335
+ type: 'link'
1336
+ });
1337
+ });
1338
+
1339
+ addEventListener('popstate', (event) => {
1340
+ if (event.state) {
1341
+ // if a popstate-driven navigation is cancelled, we need to counteract it
1342
+ // with history.go, which means we end up back here, hence this check
1343
+ if (event.state[INDEX_KEY] === current_history_index) return;
1344
+
1345
+ const delta = event.state[INDEX_KEY] - current_history_index;
1346
+
1347
+ navigate({
1348
+ url: new URL(location.href),
1349
+ scroll: scroll_positions[event.state[INDEX_KEY]],
1350
+ keepfocus: false,
1351
+ redirect_chain: [],
1352
+ details: null,
1353
+ accepted: () => {
1354
+ current_history_index = event.state[INDEX_KEY];
1355
+ },
1356
+ blocked: () => {
1357
+ history.go(-delta);
1358
+ },
1359
+ type: 'popstate',
1360
+ delta
1361
+ });
1362
+ }
1363
+ });
1364
+
1365
+ addEventListener('hashchange', () => {
1366
+ // if the hashchange happened as a result of clicking on a link,
1367
+ // we need to update history, otherwise we have to leave it alone
1368
+ if (hash_navigating) {
1369
+ hash_navigating = false;
1370
+ history.replaceState(
1371
+ { ...history.state, [INDEX_KEY]: ++current_history_index },
1372
+ '',
1373
+ location.href
1374
+ );
1375
+ }
1376
+ });
1377
+
1378
+ // fix link[rel=icon], because browsers will occasionally try to load relative
1379
+ // URLs after a pushState/replaceState, resulting in a 404 — see
1380
+ // https://github.com/sveltejs/kit/issues/3748#issuecomment-1125980897
1381
+ for (const link of document.querySelectorAll('link')) {
1382
+ if (link.rel === 'icon') link.href = link.href;
1383
+ }
1384
+
1385
+ addEventListener('pageshow', (event) => {
1386
+ // If the user navigates to another site and then uses the back button and
1387
+ // bfcache hits, we need to set navigating to null, the site doesn't know
1388
+ // the navigation away from it was successful.
1389
+ // Info about bfcache here: https://web.dev/bfcache
1390
+ if (event.persisted) {
1391
+ stores.navigating.set(null);
1392
+ }
1393
+ });
1394
+ },
1395
+
1396
+ _hydrate: async ({
1397
+ status,
1398
+ error: original_error, // TODO get rid of this
1399
+ node_ids,
1400
+ params,
1401
+ routeId,
1402
+ data: server_data_nodes,
1403
+ form
1404
+ }) => {
1405
+ const url = new URL(location.href);
1406
+
1407
+ /** @type {import('./types').NavigationFinished | undefined} */
1408
+ let result;
1409
+
1410
+ try {
1411
+ const branch_promises = node_ids.map(async (n, i) => {
1412
+ const server_data_node = server_data_nodes[i];
1413
+
1414
+ return load_node({
1415
+ loader: nodes[n],
1416
+ url,
1417
+ params,
1418
+ routeId,
1419
+ parent: async () => {
1420
+ const data = {};
1421
+ for (let j = 0; j < i; j += 1) {
1422
+ Object.assign(data, (await branch_promises[j]).data);
1423
+ }
1424
+ return data;
1425
+ },
1426
+ server_data_node: create_data_node(server_data_node)
1427
+ });
1428
+ });
1429
+
1430
+ result = await get_navigation_result_from_branch({
1431
+ url,
1432
+ params,
1433
+ branch: await Promise.all(branch_promises),
1434
+ status,
1435
+ error: /** @type {import('../server/page/types').SerializedHttpError} */ (original_error)
1436
+ ?.__is_http_error
1437
+ ? new HttpError(
1438
+ /** @type {import('../server/page/types').SerializedHttpError} */ (
1439
+ original_error
1440
+ ).status,
1441
+ original_error.message
1442
+ )
1443
+ : original_error,
1444
+ form,
1445
+ route: routes.find((route) => route.id === routeId) ?? null
1446
+ });
1447
+ } catch (e) {
1448
+ const error = normalize_error(e);
1449
+
1450
+ if (error instanceof Redirect) {
1451
+ // this is a real edge case — `load` would need to return
1452
+ // a redirect but only in the browser
1453
+ await native_navigation(new URL(/** @type {Redirect} */ (e).location, location.href));
1454
+ return;
1455
+ }
1456
+
1457
+ result = await load_root_error_page({
1458
+ status: error instanceof HttpError ? error.status : 500,
1459
+ error,
1460
+ url,
1461
+ routeId
1462
+ });
1463
+ }
1464
+
1465
+ initialize(result);
1466
+ }
1467
+ };
1468
+ }
1469
+
1470
+ let data_id = 1;
1471
+
1472
+ /**
1473
+ * @param {URL} url
1474
+ * @param {boolean[]} invalid
1475
+ * @returns {Promise<import('types').ServerData>}
1476
+ */
1477
+ async function load_data(url, invalid) {
1478
+ const data_url = new URL(url);
1479
+ data_url.pathname = url.pathname.replace(/\/$/, '') + DATA_SUFFIX;
1480
+ data_url.searchParams.set('__invalid', invalid.map((x) => (x ? 'y' : 'n')).join(''));
1481
+ data_url.searchParams.set('__id', String(data_id++));
1482
+
1483
+ // The __data.js file is generated by the server and looks like
1484
+ // `window.__sveltekit_data = ${devalue(data)}`. We do this instead
1485
+ // of `export const data` because modules are cached indefinitely,
1486
+ // and that would cause memory leaks.
1487
+ //
1488
+ // The data is read and deleted in the same tick as the promise
1489
+ // resolves, so it's not vulnerable to race conditions
1490
+ await import(/* @vite-ignore */ data_url.href);
1491
+
1492
+ // @ts-expect-error
1493
+ const server_data = window.__sveltekit_data;
1494
+
1495
+ // @ts-expect-error
1496
+ delete window.__sveltekit_data;
1497
+
1498
+ return server_data;
1499
+ }
1500
+
1501
+ // TODO remove for 1.0
1502
+ const properties = [
1503
+ 'hash',
1504
+ 'href',
1505
+ 'host',
1506
+ 'hostname',
1507
+ 'origin',
1508
+ 'pathname',
1509
+ 'port',
1510
+ 'protocol',
1511
+ 'search',
1512
+ 'searchParams',
1513
+ 'toString',
1514
+ 'toJSON'
1515
+ ];
1516
+
1517
+ /**
1518
+ * @param {'from' | 'to'} type
1519
+ * @param {import('types').NavigationTarget} target
1520
+ */
1521
+ function add_url_properties(type, target) {
1522
+ for (const prop of properties) {
1523
+ Object.defineProperty(target, prop, {
1524
+ get() {
1525
+ throw new Error(
1526
+ `The navigation shape changed - ${type}.${prop} should now be ${type}.url.${prop}`
1527
+ );
1528
+ }
1529
+ });
1530
+ }
1531
+
1532
+ return target;
1533
+ }
1534
+
1535
+ function pre_update() {
1536
+ if (__SVELTEKIT_DEV__) {
1537
+ // Nasty hack to silence harmless warnings the user can do nothing about
1538
+ const warn = console.warn;
1539
+ console.warn = (...args) => {
1540
+ if (
1541
+ args.length === 1 &&
1542
+ /<(Layout|Page)(_[\w$]+)?> was created (with unknown|without expected) prop '(data|form)'/.test(
1543
+ args[0]
1544
+ )
1545
+ ) {
1546
+ return;
1547
+ }
1548
+ warn(...args);
1549
+ };
1550
+
1551
+ return () => {
1552
+ tick().then(() => (console.warn = warn));
1553
+ check_for_removed_attributes();
1554
+ };
1555
+ }
1556
+
1557
+ return () => {};
1558
+ }