@sveltejs/kit 1.0.0-next.48 → 1.0.0-next.480

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