-
-
Notifications
You must be signed in to change notification settings - Fork 2k
/
Copy pathclient.js
2012 lines (1715 loc) · 54.7 KB
/
client.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { DEV } from 'esm-env';
import { onMount, tick } from 'svelte';
import {
add_data_suffix,
decode_params,
decode_pathname,
make_trackable,
normalize_path
} from '../../utils/url.js';
import {
initial_fetch,
lock_fetch,
native_fetch,
subsequent_fetch,
unlock_fetch
} from './fetcher.js';
import { parse } from './parse.js';
import * as storage from './session-storage.js';
import {
find_anchor,
get_base_uri,
get_link_info,
get_router_options,
is_external_url,
scroll_state
} from './utils.js';
import { base } from '__sveltekit/paths';
import * as devalue from 'devalue';
import { compact } from '../../utils/array.js';
import { validate_page_exports } from '../../utils/exports.js';
import { unwrap_promises } from '../../utils/promises.js';
import { HttpError, Redirect } from '../control.js';
import { INVALIDATED_PARAM, validate_depends } from '../shared.js';
import { INDEX_KEY, PRELOAD_PRIORITIES, SCROLL_KEY, SNAPSHOT_KEY } from './constants.js';
import { stores } from './singletons.js';
let errored = false;
// We track the scroll position associated with each history entry in sessionStorage,
// rather than on history.state itself, because when navigation is driven by
// popstate it's too late to update the scroll position associated with the
// state we're navigating from
/** @typedef {{ x: number, y: number }} ScrollPosition */
/** @type {Record<number, ScrollPosition>} */
const scroll_positions = storage.get(SCROLL_KEY) ?? {};
/** @type {Record<string, any[]>} */
const snapshots = storage.get(SNAPSHOT_KEY) ?? {};
/** @param {number} index */
function update_scroll_positions(index) {
scroll_positions[index] = scroll_state();
}
/**
* @param {import('./types').SvelteKitApp} app
* @param {HTMLElement} target
* @returns {import('./types').Client}
*/
export function create_client(app, target) {
const routes = parse(app);
const default_layout_loader = app.nodes[0];
const default_error_loader = app.nodes[1];
// we import the root layout/error nodes eagerly, so that
// connectivity errors after initialisation don't nuke the app
default_layout_loader();
default_error_loader();
const container = __SVELTEKIT_EMBEDDED__ ? target : document.documentElement;
/** @type {Array<((url: URL) => boolean)>} */
const invalidated = [];
/**
* An array of the `+layout.svelte` and `+page.svelte` component instances
* that currently live on the page — used for capturing and restoring snapshots.
* It's updated/manipulated through `bind:this` in `Root.svelte`.
* @type {import('svelte').SvelteComponent[]}
*/
const components = [];
/** @type {{id: string, promise: Promise<import('./types').NavigationResult>} | null} */
let load_cache = null;
const callbacks = {
/** @type {Array<(navigation: import('@sveltejs/kit').BeforeNavigate) => void>} */
before_navigate: [],
/** @type {Array<(navigation: import('@sveltejs/kit').AfterNavigate) => void>} */
after_navigate: []
};
/** @type {import('./types').NavigationState} */
let current = {
branch: [],
error: null,
// @ts-ignore - we need the initial value to be null
url: null
};
/** this being true means we SSR'd */
let hydrated = false;
let started = false;
let autoscroll = true;
let updating = false;
let navigating = false;
let hash_navigating = false;
let force_invalidation = false;
/** @type {import('svelte').SvelteComponent} */
let root;
// keeping track of the history index in order to prevent popstate navigation events if needed
let current_history_index = history.state?.[INDEX_KEY];
if (!current_history_index) {
// we use Date.now() as an offset so that cross-document navigations
// within the app don't result in data loss
current_history_index = Date.now();
// create initial history entry, so we can return here
history.replaceState(
{ ...history.state, [INDEX_KEY]: current_history_index },
'',
location.href
);
}
// if we reload the page, or Cmd-Shift-T back to it,
// recover scroll position
const scroll = scroll_positions[current_history_index];
if (scroll) {
history.scrollRestoration = 'manual';
scrollTo(scroll.x, scroll.y);
}
/** @type {import('@sveltejs/kit').Page} */
let page;
/** @type {{}} */
let token;
/** @type {Promise<void> | null} */
let pending_invalidate;
async function invalidate() {
// Accept all invalidations as they come, don't swallow any while another invalidation
// is running because subsequent invalidations may make earlier ones outdated,
// but batch multiple synchronous invalidations.
pending_invalidate = pending_invalidate || Promise.resolve();
await pending_invalidate;
if (!pending_invalidate) return;
pending_invalidate = null;
const url = new URL(location.href);
const intent = get_navigation_intent(url, true);
// Clear preload, it might be affected by the invalidation.
// Also solves an edge case where a preload is triggered, the navigation for it
// was then triggered and is still running while the invalidation kicks in,
// at which point the invalidation should take over and "win".
load_cache = null;
const nav_token = (token = {});
const navigation_result = intent && (await load_route(intent));
if (nav_token !== token) return;
if (navigation_result) {
if (navigation_result.type === 'redirect') {
return goto(new URL(navigation_result.location, url).href, {}, [url.pathname], nav_token);
} else {
if (navigation_result.props.page !== undefined) {
page = navigation_result.props.page;
}
root.$set(navigation_result.props);
}
}
}
/** @param {number} index */
function capture_snapshot(index) {
if (components.some((c) => c?.snapshot)) {
snapshots[index] = components.map((c) => c?.snapshot?.capture());
}
}
/** @param {number} index */
function restore_snapshot(index) {
snapshots[index]?.forEach((value, i) => {
components[i]?.snapshot?.restore(value);
});
}
function persist_state() {
update_scroll_positions(current_history_index);
storage.set(SCROLL_KEY, scroll_positions);
capture_snapshot(current_history_index);
storage.set(SNAPSHOT_KEY, snapshots);
}
/**
* @param {string | URL} url
* @param {{ noScroll?: boolean; replaceState?: boolean; keepFocus?: boolean; state?: any; invalidateAll?: boolean }} opts
* @param {string[]} redirect_chain
* @param {{}} [nav_token]
*/
async function goto(
url,
{
noScroll = false,
replaceState = false,
keepFocus = false,
state = {},
invalidateAll = false
},
redirect_chain,
nav_token
) {
if (typeof url === 'string') {
url = new URL(url, get_base_uri(document));
}
return navigate({
url,
scroll: noScroll ? scroll_state() : null,
keepfocus: keepFocus,
redirect_chain,
details: {
state,
replaceState
},
nav_token,
accepted: () => {
if (invalidateAll) {
force_invalidation = true;
}
},
blocked: () => {},
type: 'goto'
});
}
/** @param {import('./types').NavigationIntent} intent */
async function preload_data(intent) {
load_cache = {
id: intent.id,
promise: load_route(intent).then((result) => {
if (result.type === 'loaded' && result.state.error) {
// Don't cache errors, because they might be transient
load_cache = null;
}
return result;
})
};
return load_cache.promise;
}
/** @param {...string} pathnames */
async function preload_code(...pathnames) {
const matching = routes.filter((route) => pathnames.some((pathname) => route.exec(pathname)));
const promises = matching.map((r) => {
return Promise.all([...r.layouts, r.leaf].map((load) => load?.[1]()));
});
await Promise.all(promises);
}
/** @param {import('./types').NavigationFinished} result */
function initialize(result) {
if (DEV && result.state.error && document.querySelector('vite-error-overlay')) return;
current = result.state;
const style = document.querySelector('style[data-sveltekit]');
if (style) style.remove();
page = /** @type {import('@sveltejs/kit').Page} */ (result.props.page);
root = new app.root({
target,
props: { ...result.props, stores, components },
hydrate: true
});
restore_snapshot(current_history_index);
/** @type {import('@sveltejs/kit').AfterNavigate} */
const navigation = {
from: null,
to: {
params: current.params,
route: { id: current.route?.id ?? null },
url: new URL(location.href)
},
willUnload: false,
type: 'enter'
};
callbacks.after_navigate.forEach((fn) => fn(navigation));
started = true;
}
/**
*
* @param {{
* url: URL;
* params: Record<string, string>;
* branch: Array<import('./types').BranchNode | undefined>;
* status: number;
* error: App.Error | null;
* route: import('types').CSRRoute | null;
* form?: Record<string, any> | null;
* }} opts
*/
async function get_navigation_result_from_branch({
url,
params,
branch,
status,
error,
route,
form
}) {
/** @type {import('types').TrailingSlash} */
let slash = 'never';
for (const node of branch) {
if (node?.slash !== undefined) slash = node.slash;
}
url.pathname = normalize_path(url.pathname, slash);
// eslint-disable-next-line
url.search = url.search; // turn `/?` into `/`
/** @type {import('./types').NavigationFinished} */
const result = {
type: 'loaded',
state: {
url,
params,
branch,
error,
route
},
props: {
// @ts-ignore Somehow it's getting SvelteComponent and SvelteComponentDev mixed up
constructors: compact(branch).map((branch_node) => branch_node.node.component)
}
};
if (form !== undefined) {
result.props.form = form;
}
let data = {};
let data_changed = !page;
let p = 0;
for (let i = 0; i < Math.max(branch.length, current.branch.length); i += 1) {
const node = branch[i];
const prev = current.branch[i];
if (node?.data !== prev?.data) data_changed = true;
if (!node) continue;
data = { ...data, ...node.data };
// Only set props if the node actually updated. This prevents needless rerenders.
if (data_changed) {
result.props[`data_${p}`] = data;
}
p += 1;
}
const page_changed =
!current.url ||
url.href !== current.url.href ||
current.error !== error ||
(form !== undefined && form !== page.form) ||
data_changed;
if (page_changed) {
result.props.page = {
error,
params,
route: {
id: route?.id ?? null
},
status,
url: new URL(url),
form: form ?? null,
// The whole page store is updated, but this way the object reference stays the same
data: data_changed ? data : page.data
};
}
return result;
}
/**
* Call the load function of the given node, if it exists.
* If `server_data` is passed, this is treated as the initial run and the page endpoint is not requested.
*
* @param {{
* loader: import('types').CSRPageNodeLoader;
* parent: () => Promise<Record<string, any>>;
* url: URL;
* params: Record<string, string>;
* route: { id: string | null };
* server_data_node: import('./types').DataNode | null;
* }} options
* @returns {Promise<import('./types').BranchNode>}
*/
async function load_node({ loader, parent, url, params, route, server_data_node }) {
/** @type {Record<string, any> | null} */
let data = null;
/** @type {import('types').Uses} */
const uses = {
dependencies: new Set(),
params: new Set(),
parent: false,
route: false,
url: false
};
const node = await loader();
if (DEV) {
validate_page_exports(node.universal);
}
if (node.universal?.load) {
/** @param {string[]} deps */
function depends(...deps) {
for (const dep of deps) {
if (DEV) validate_depends(/** @type {string} */ (route.id), dep);
const { href } = new URL(dep, url);
uses.dependencies.add(href);
}
}
/** @type {import('@sveltejs/kit').LoadEvent} */
const load_input = {
route: {
get id() {
uses.route = true;
return route.id;
}
},
params: new Proxy(params, {
get: (target, key) => {
uses.params.add(/** @type {string} */ (key));
return target[/** @type {string} */ (key)];
}
}),
data: server_data_node?.data ?? null,
url: make_trackable(url, () => {
uses.url = true;
}),
async fetch(resource, init) {
/** @type {URL | string} */
let requested;
if (resource instanceof Request) {
requested = resource.url;
// we're not allowed to modify the received `Request` object, so in order
// to fixup relative urls we create a new equivalent `init` object instead
init = {
// the request body must be consumed in memory until browsers
// implement streaming request bodies and/or the body getter
body:
resource.method === 'GET' || resource.method === 'HEAD'
? undefined
: await resource.blob(),
cache: resource.cache,
credentials: resource.credentials,
headers: resource.headers,
integrity: resource.integrity,
keepalive: resource.keepalive,
method: resource.method,
mode: resource.mode,
redirect: resource.redirect,
referrer: resource.referrer,
referrerPolicy: resource.referrerPolicy,
signal: resource.signal,
...init
};
} else {
requested = resource;
}
// we must fixup relative urls so they are resolved from the target page
const resolved = new URL(requested, url);
depends(resolved.href);
// match ssr serialized data url, which is important to find cached responses
if (resolved.origin === url.origin) {
requested = resolved.href.slice(url.origin.length);
}
// prerendered pages may be served from any origin, so `initial_fetch` urls shouldn't be resolved
return started
? subsequent_fetch(requested, resolved.href, init)
: initial_fetch(requested, init);
},
setHeaders: () => {}, // noop
depends,
parent() {
uses.parent = true;
return parent();
}
};
if (DEV) {
try {
lock_fetch();
data = (await node.universal.load.call(null, load_input)) ?? null;
if (data != null && Object.getPrototypeOf(data) !== Object.prototype) {
throw new Error(
`a load function related to route '${route.id}' returned ${
typeof data !== 'object'
? `a ${typeof data}`
: data instanceof Response
? 'a Response object'
: Array.isArray(data)
? 'an array'
: 'a non-plain object'
}, but must return a plain object at the top level (i.e. \`return {...}\`)`
);
}
} finally {
unlock_fetch();
}
} else {
data = (await node.universal.load.call(null, load_input)) ?? null;
}
data = data ? await unwrap_promises(data) : null;
}
return {
node,
loader,
server: server_data_node,
universal: node.universal?.load ? { type: 'data', data, uses } : null,
data: data ?? server_data_node?.data ?? null,
slash: node.universal?.trailingSlash ?? server_data_node?.slash
};
}
/**
* @param {boolean} parent_changed
* @param {boolean} route_changed
* @param {boolean} url_changed
* @param {import('types').Uses | undefined} uses
* @param {Record<string, string>} params
*/
function has_changed(parent_changed, route_changed, url_changed, uses, params) {
if (force_invalidation) return true;
if (!uses) return false;
if (uses.parent && parent_changed) return true;
if (uses.route && route_changed) return true;
if (uses.url && url_changed) return true;
for (const param of uses.params) {
if (params[param] !== current.params[param]) return true;
}
for (const href of uses.dependencies) {
if (invalidated.some((fn) => fn(new URL(href)))) return true;
}
return false;
}
/**
* @param {import('types').ServerDataNode | import('types').ServerDataSkippedNode | null} node
* @param {import('./types').DataNode | null} [previous]
* @returns {import('./types').DataNode | null}
*/
function create_data_node(node, previous) {
if (node?.type === 'data') return node;
if (node?.type === 'skip') return previous ?? null;
return null;
}
/**
* @param {import('./types').NavigationIntent} intent
* @returns {Promise<import('./types').NavigationResult>}
*/
async function load_route({ id, invalidating, url, params, route }) {
if (load_cache?.id === id) {
return load_cache.promise;
}
const { errors, layouts, leaf } = route;
const loaders = [...layouts, leaf];
// preload modules to avoid waterfall, but handle rejections
// so they don't get reported to Sentry et al (we don't need
// to act on the failures at this point)
errors.forEach((loader) => loader?.().catch(() => {}));
loaders.forEach((loader) => loader?.[1]().catch(() => {}));
/** @type {import('types').ServerNodesResponse | import('types').ServerRedirectNode | null} */
let server_data = null;
const url_changed = current.url ? id !== current.url.pathname + current.url.search : false;
const route_changed = current.route ? route.id !== current.route.id : false;
let parent_invalid = false;
const invalid_server_nodes = loaders.map((loader, i) => {
const previous = current.branch[i];
const invalid =
!!loader?.[0] &&
(previous?.loader !== loader[1] ||
has_changed(parent_invalid, route_changed, url_changed, previous.server?.uses, params));
if (invalid) {
// For the next one
parent_invalid = true;
}
return invalid;
});
if (invalid_server_nodes.some(Boolean)) {
try {
server_data = await load_data(url, invalid_server_nodes);
} catch (error) {
return load_root_error_page({
status: error instanceof HttpError ? error.status : 500,
error: await handle_error(error, { url, params, route: { id: route.id } }),
url,
route
});
}
if (server_data.type === 'redirect') {
return server_data;
}
}
const server_data_nodes = server_data?.nodes;
let parent_changed = false;
const branch_promises = loaders.map(async (loader, i) => {
if (!loader) return;
/** @type {import('./types').BranchNode | undefined} */
const previous = current.branch[i];
const server_data_node = server_data_nodes?.[i];
// re-use data from previous load if it's still valid
const valid =
(!server_data_node || server_data_node.type === 'skip') &&
loader[1] === previous?.loader &&
!has_changed(parent_changed, route_changed, url_changed, previous.universal?.uses, params);
if (valid) return previous;
parent_changed = true;
if (server_data_node?.type === 'error') {
// rethrow and catch below
throw server_data_node;
}
return load_node({
loader: loader[1],
url,
params,
route,
parent: async () => {
const data = {};
for (let j = 0; j < i; j += 1) {
Object.assign(data, (await branch_promises[j])?.data);
}
return data;
},
server_data_node: create_data_node(
// server_data_node is undefined if it wasn't reloaded from the server;
// and if current loader uses server data, we want to reuse previous data.
server_data_node === undefined && loader[0] ? { type: 'skip' } : server_data_node ?? null,
loader[0] ? previous?.server : undefined
)
});
});
// if we don't do this, rejections will be unhandled
for (const p of branch_promises) p.catch(() => {});
/** @type {Array<import('./types').BranchNode | undefined>} */
const branch = [];
for (let i = 0; i < loaders.length; i += 1) {
if (loaders[i]) {
try {
branch.push(await branch_promises[i]);
} catch (err) {
if (err instanceof Redirect) {
return {
type: 'redirect',
location: err.location
};
}
let status = 500;
/** @type {App.Error} */
let error;
if (server_data_nodes?.includes(/** @type {import('types').ServerErrorNode} */ (err))) {
// this is the server error rethrown above, reconstruct but don't invoke
// the client error handler; it should've already been handled on the server
status = /** @type {import('types').ServerErrorNode} */ (err).status ?? status;
error = /** @type {import('types').ServerErrorNode} */ (err).error;
} else if (err instanceof HttpError) {
status = err.status;
error = err.body;
} else {
// Referenced node could have been removed due to redeploy, check
const updated = await stores.updated.check();
if (updated) {
return await native_navigation(url);
}
error = await handle_error(err, { params, url, route: { id: route.id } });
}
const error_load = await load_nearest_error_page(i, branch, errors);
if (error_load) {
return await get_navigation_result_from_branch({
url,
params,
branch: branch.slice(0, error_load.idx).concat(error_load.node),
status,
error,
route
});
} else {
// if we get here, it's because the root `load` function failed,
// and we need to fall back to the server
return await server_fallback(url, { id: route.id }, error, status);
}
}
} else {
// push an empty slot so we can rewind past gaps to the
// layout that corresponds with an +error.svelte page
branch.push(undefined);
}
}
return await get_navigation_result_from_branch({
url,
params,
branch,
status: 200,
error: null,
route,
// Reset `form` on navigation, but not invalidation
form: invalidating ? undefined : null
});
}
/**
* @param {number} i Start index to backtrack from
* @param {Array<import('./types').BranchNode | undefined>} branch Branch to backtrack
* @param {Array<import('types').CSRPageNodeLoader | undefined>} errors All error pages for this branch
* @returns {Promise<{idx: number; node: import('./types').BranchNode} | undefined>}
*/
async function load_nearest_error_page(i, branch, errors) {
while (i--) {
if (errors[i]) {
let j = i;
while (!branch[j]) j -= 1;
try {
return {
idx: j + 1,
node: {
node: await /** @type {import('types').CSRPageNodeLoader } */ (errors[i])(),
loader: /** @type {import('types').CSRPageNodeLoader } */ (errors[i]),
data: {},
server: null,
universal: null
}
};
} catch (e) {
continue;
}
}
}
}
/**
* @param {{
* status: number;
* error: App.Error;
* url: URL;
* route: { id: string | null }
* }} opts
* @returns {Promise<import('./types').NavigationFinished>}
*/
async function load_root_error_page({ status, error, url, route }) {
/** @type {Record<string, string>} */
const params = {}; // error page does not have params
/** @type {import('types').ServerDataNode | null} */
let server_data_node = null;
const default_layout_has_server_load = app.server_loads[0] === 0;
if (default_layout_has_server_load) {
// TODO post-https://github.com/sveltejs/kit/discussions/6124 we can use
// existing root layout data
try {
const server_data = await load_data(url, [true]);
if (
server_data.type !== 'data' ||
(server_data.nodes[0] && server_data.nodes[0].type !== 'data')
) {
throw 0;
}
server_data_node = server_data.nodes[0] ?? null;
} catch {
// at this point we have no choice but to fall back to the server, if it wouldn't
// bring us right back here, turning this into an endless loop
if (url.origin !== location.origin || url.pathname !== location.pathname || hydrated) {
await native_navigation(url);
}
}
}
const root_layout = await load_node({
loader: default_layout_loader,
url,
params,
route,
parent: () => Promise.resolve({}),
server_data_node: create_data_node(server_data_node)
});
/** @type {import('./types').BranchNode} */
const root_error = {
node: await default_error_loader(),
loader: default_error_loader,
universal: null,
server: null,
data: null
};
return await get_navigation_result_from_branch({
url,
params,
branch: [root_layout, root_error],
status,
error,
route: null
});
}
/**
* @param {URL} url
* @param {boolean} invalidating
*/
function get_navigation_intent(url, invalidating) {
if (is_external_url(url, base)) return;
const path = get_url_path(url);
for (const route of routes) {
const params = route.exec(path);
if (params) {
const id = url.pathname + url.search;
/** @type {import('./types').NavigationIntent} */
const intent = { id, invalidating, route, params: decode_params(params), url };
return intent;
}
}
}
/** @param {URL} url */
function get_url_path(url) {
return decode_pathname(url.pathname.slice(base.length) || '/');
}
/**
* @param {{
* url: URL;
* type: import('@sveltejs/kit').NavigationType;
* intent?: import('./types').NavigationIntent;
* delta?: number;
* }} opts
*/
function before_navigate({ url, type, intent, delta }) {
let should_block = false;
/** @type {import('@sveltejs/kit').Navigation} */
const navigation = {
from: {
params: current.params,
route: { id: current.route?.id ?? null },
url: current.url
},
to: {
params: intent?.params ?? null,
route: { id: intent?.route?.id ?? null },
url
},
willUnload: !intent,
type
};
if (delta !== undefined) {
navigation.delta = delta;
}
const cancellable = {
...navigation,
cancel: () => {
should_block = true;
}
};
if (!navigating) {
// Don't run the event during redirects
callbacks.before_navigate.forEach((fn) => fn(cancellable));
}
return should_block ? null : navigation;
}
/**
* @param {{
* url: URL;
* scroll: { x: number, y: number } | null;
* keepfocus: boolean;
* redirect_chain: string[];
* details: {
* replaceState: boolean;
* state: any;
* } | null;
* type: import('@sveltejs/kit').NavigationType;
* delta?: number;
* nav_token?: {};
* accepted: () => void;
* blocked: () => void;
* }} opts
*/
async function navigate({
url,
scroll,
keepfocus,
redirect_chain,
details,
type,
delta,
nav_token = {},
accepted,
blocked
}) {
const intent = get_navigation_intent(url, false);
const navigation = before_navigate({ url, type, delta, intent });
if (!navigation) {
blocked();
return;
}
// store this before calling `accepted()`, which may change the index
const previous_history_index = current_history_index;
accepted();
navigating = true;
if (started) {
stores.navigating.set(navigation);
}
token = nav_token;
let navigation_result = intent && (await load_route(intent));
if (!navigation_result) {
if (is_external_url(url, base)) {