@sveltejs/kit 1.0.0-next.38 → 1.0.0-next.380

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 (42) hide show
  1. package/README.md +12 -9
  2. package/assets/app/env.js +28 -0
  3. package/assets/app/navigation.js +24 -0
  4. package/assets/app/paths.js +1 -0
  5. package/assets/{runtime/app → app}/stores.js +33 -29
  6. package/assets/client/singletons.js +13 -0
  7. package/assets/client/start.js +1803 -0
  8. package/assets/components/error.svelte +18 -2
  9. package/assets/env.js +8 -0
  10. package/assets/{runtime/chunks/paths.js → paths.js} +4 -3
  11. package/assets/server/index.js +3563 -0
  12. package/dist/chunks/_commonjsHelpers.js +3 -0
  13. package/dist/chunks/error.js +664 -0
  14. package/dist/chunks/index.js +15292 -3067
  15. package/dist/chunks/index2.js +186 -555
  16. package/dist/chunks/multipart-parser.js +445 -0
  17. package/dist/chunks/sync.js +1007 -0
  18. package/dist/chunks/write_tsconfig.js +274 -0
  19. package/dist/cli.js +66 -514
  20. package/dist/hooks.js +28 -0
  21. package/dist/node/polyfills.js +12240 -0
  22. package/dist/node.js +5883 -0
  23. package/dist/vite.js +3243 -0
  24. package/package.json +97 -64
  25. package/types/ambient.d.ts +345 -0
  26. package/types/index.d.ts +289 -0
  27. package/types/internal.d.ts +326 -0
  28. package/types/private.d.ts +235 -0
  29. package/CHANGELOG.md +0 -399
  30. package/assets/runtime/app/env.js +0 -5
  31. package/assets/runtime/app/navigation.js +0 -41
  32. package/assets/runtime/app/paths.js +0 -1
  33. package/assets/runtime/chunks/utils.js +0 -19
  34. package/assets/runtime/internal/singletons.js +0 -23
  35. package/assets/runtime/internal/start.js +0 -770
  36. package/dist/chunks/index3.js +0 -246
  37. package/dist/chunks/index4.js +0 -511
  38. package/dist/chunks/index5.js +0 -761
  39. package/dist/chunks/index6.js +0 -322
  40. package/dist/chunks/standard.js +0 -99
  41. package/dist/chunks/utils.js +0 -83
  42. package/dist/ssr.js +0 -2523
@@ -0,0 +1,1803 @@
1
+ import { onMount, tick } from 'svelte';
2
+ import { writable } from 'svelte/store';
3
+ import { assets, set_paths } from '../paths.js';
4
+ import Root from '__GENERATED__/root.svelte';
5
+ import { components, dictionary, matchers } from '__GENERATED__/client-manifest.js';
6
+ import { init } from './singletons.js';
7
+
8
+ /**
9
+ * @param {unknown} err
10
+ * @return {Error}
11
+ */
12
+ function coalesce_to_error(err) {
13
+ return err instanceof Error ||
14
+ (err && /** @type {any} */ (err).name && /** @type {any} */ (err).message)
15
+ ? /** @type {Error} */ (err)
16
+ : new Error(JSON.stringify(err));
17
+ }
18
+
19
+ /**
20
+ * @param {import('types').LoadOutput | void} loaded
21
+ * @returns {import('types').NormalizedLoadOutput}
22
+ */
23
+ function normalize(loaded) {
24
+ if (!loaded) {
25
+ return {};
26
+ }
27
+
28
+ // TODO remove for 1.0
29
+ // @ts-expect-error
30
+ if (loaded.fallthrough) {
31
+ throw new Error(
32
+ 'fallthrough is no longer supported. Use matchers instead: https://kit.svelte.dev/docs/routing#advanced-routing-matching'
33
+ );
34
+ }
35
+
36
+ // TODO remove for 1.0
37
+ if ('maxage' in loaded) {
38
+ throw new Error('maxage should be replaced with cache: { maxage }');
39
+ }
40
+
41
+ const has_error_status =
42
+ loaded.status && loaded.status >= 400 && loaded.status <= 599 && !loaded.redirect;
43
+ if (loaded.error || has_error_status) {
44
+ const status = loaded.status;
45
+
46
+ if (!loaded.error && has_error_status) {
47
+ return {
48
+ status: status || 500,
49
+ error: new Error(`${status}`)
50
+ };
51
+ }
52
+
53
+ const error = typeof loaded.error === 'string' ? new Error(loaded.error) : loaded.error;
54
+
55
+ if (!(error instanceof Error)) {
56
+ return {
57
+ status: 500,
58
+ error: new Error(
59
+ `"error" property returned from load() must be a string or instance of Error, received type "${typeof error}"`
60
+ )
61
+ };
62
+ }
63
+
64
+ if (!status || status < 400 || status > 599) {
65
+ console.warn('"error" returned from load() without a valid status code — defaulting to 500');
66
+ return { status: 500, error };
67
+ }
68
+
69
+ return { status, error };
70
+ }
71
+
72
+ if (loaded.redirect) {
73
+ if (!loaded.status || Math.floor(loaded.status / 100) !== 3) {
74
+ throw new Error(
75
+ '"redirect" property returned from load() must be accompanied by a 3xx status code'
76
+ );
77
+ }
78
+
79
+ if (typeof loaded.redirect !== 'string') {
80
+ throw new Error('"redirect" property returned from load() must be a string');
81
+ }
82
+ }
83
+
84
+ if (loaded.dependencies) {
85
+ if (
86
+ !Array.isArray(loaded.dependencies) ||
87
+ loaded.dependencies.some((dep) => typeof dep !== 'string')
88
+ ) {
89
+ throw new Error('"dependencies" property returned from load() must be of type string[]');
90
+ }
91
+ }
92
+
93
+ // TODO remove before 1.0
94
+ if (/** @type {any} */ (loaded).context) {
95
+ throw new Error(
96
+ 'You are returning "context" from a load function. ' +
97
+ '"context" was renamed to "stuff", please adjust your code accordingly.'
98
+ );
99
+ }
100
+
101
+ return /** @type {import('types').NormalizedLoadOutput} */ (loaded);
102
+ }
103
+
104
+ /**
105
+ * @param {string} path
106
+ * @param {import('types').TrailingSlash} trailing_slash
107
+ */
108
+ function normalize_path(path, trailing_slash) {
109
+ if (path === '/' || trailing_slash === 'ignore') return path;
110
+
111
+ if (trailing_slash === 'never') {
112
+ return path.endsWith('/') ? path.slice(0, -1) : path;
113
+ } else if (trailing_slash === 'always' && !path.endsWith('/')) {
114
+ return path + '/';
115
+ }
116
+
117
+ return path;
118
+ }
119
+
120
+ class LoadURL extends URL {
121
+ /** @returns {string} */
122
+ get hash() {
123
+ throw new Error(
124
+ 'url.hash is inaccessible from load. Consider accessing hash from the page store within the script tag of your component.'
125
+ );
126
+ }
127
+ }
128
+
129
+ /* global __SVELTEKIT_APP_VERSION__, __SVELTEKIT_APP_VERSION_FILE__, __SVELTEKIT_APP_VERSION_POLL_INTERVAL__ */
130
+
131
+ /** @param {HTMLDocument} doc */
132
+ function get_base_uri(doc) {
133
+ let baseURI = doc.baseURI;
134
+
135
+ if (!baseURI) {
136
+ const baseTags = doc.getElementsByTagName('base');
137
+ baseURI = baseTags.length ? baseTags[0].href : doc.URL;
138
+ }
139
+
140
+ return baseURI;
141
+ }
142
+
143
+ function scroll_state() {
144
+ return {
145
+ x: pageXOffset,
146
+ y: pageYOffset
147
+ };
148
+ }
149
+
150
+ /** @param {Event} event */
151
+ function find_anchor(event) {
152
+ const node = event
153
+ .composedPath()
154
+ .find((e) => e instanceof Node && e.nodeName.toUpperCase() === 'A'); // SVG <a> elements have a lowercase name
155
+ return /** @type {HTMLAnchorElement | SVGAElement | undefined} */ (node);
156
+ }
157
+
158
+ /** @param {HTMLAnchorElement | SVGAElement} node */
159
+ function get_href(node) {
160
+ return node instanceof SVGAElement
161
+ ? new URL(node.href.baseVal, document.baseURI)
162
+ : new URL(node.href);
163
+ }
164
+
165
+ /** @param {any} value */
166
+ function notifiable_store(value) {
167
+ const store = writable(value);
168
+ let ready = true;
169
+
170
+ function notify() {
171
+ ready = true;
172
+ store.update((val) => val);
173
+ }
174
+
175
+ /** @param {any} new_value */
176
+ function set(new_value) {
177
+ ready = false;
178
+ store.set(new_value);
179
+ }
180
+
181
+ /** @param {(value: any) => void} run */
182
+ function subscribe(run) {
183
+ /** @type {any} */
184
+ let old_value;
185
+ return store.subscribe((new_value) => {
186
+ if (old_value === undefined || (ready && new_value !== old_value)) {
187
+ run((old_value = new_value));
188
+ }
189
+ });
190
+ }
191
+
192
+ return { notify, set, subscribe };
193
+ }
194
+
195
+ function create_updated_store() {
196
+ const { set, subscribe } = writable(false);
197
+
198
+ const interval = __SVELTEKIT_APP_VERSION_POLL_INTERVAL__;
199
+
200
+ /** @type {NodeJS.Timeout} */
201
+ let timeout;
202
+
203
+ async function check() {
204
+ if (import.meta.env.DEV || import.meta.env.SSR) return false;
205
+
206
+ clearTimeout(timeout);
207
+
208
+ if (interval) timeout = setTimeout(check, interval);
209
+
210
+ const res = await fetch(`${assets}/${__SVELTEKIT_APP_VERSION_FILE__}`, {
211
+ headers: {
212
+ pragma: 'no-cache',
213
+ 'cache-control': 'no-cache'
214
+ }
215
+ });
216
+
217
+ if (res.ok) {
218
+ const { version } = await res.json();
219
+ const updated = version !== __SVELTEKIT_APP_VERSION__;
220
+
221
+ if (updated) {
222
+ set(true);
223
+ clearTimeout(timeout);
224
+ }
225
+
226
+ return updated;
227
+ } else {
228
+ throw new Error(`Version check failed: ${res.status}`);
229
+ }
230
+ }
231
+
232
+ if (interval) timeout = setTimeout(check, interval);
233
+
234
+ return {
235
+ subscribe,
236
+ check
237
+ };
238
+ }
239
+
240
+ /**
241
+ * Hash using djb2
242
+ * @param {import('types').StrictBody} value
243
+ */
244
+ function hash(value) {
245
+ let hash = 5381;
246
+ let i = value.length;
247
+
248
+ if (typeof value === 'string') {
249
+ while (i) hash = (hash * 33) ^ value.charCodeAt(--i);
250
+ } else {
251
+ while (i) hash = (hash * 33) ^ value[--i];
252
+ }
253
+
254
+ return (hash >>> 0).toString(36);
255
+ }
256
+
257
+ let loading = 0;
258
+
259
+ const native_fetch = window.fetch;
260
+
261
+ function lock_fetch() {
262
+ loading += 1;
263
+ }
264
+
265
+ function unlock_fetch() {
266
+ loading -= 1;
267
+ }
268
+
269
+ if (import.meta.env.DEV) {
270
+ let can_inspect_stack_trace = false;
271
+
272
+ const check_stack_trace = async () => {
273
+ const stack = /** @type {string} */ (new Error().stack);
274
+ can_inspect_stack_trace = stack.includes('check_stack_trace');
275
+ };
276
+
277
+ check_stack_trace();
278
+
279
+ window.fetch = (input, init) => {
280
+ const url = input instanceof Request ? input.url : input.toString();
281
+ const stack = /** @type {string} */ (new Error().stack);
282
+
283
+ const heuristic = can_inspect_stack_trace ? stack.includes('load_node') : loading;
284
+ if (heuristic) {
285
+ console.warn(
286
+ `Loading ${url} using \`window.fetch\`. For best results, use the \`fetch\` that is passed to your \`load\` function: https://kit.svelte.dev/docs/loading#input-fetch`
287
+ );
288
+ }
289
+
290
+ return native_fetch(input, init);
291
+ };
292
+ }
293
+
294
+ /**
295
+ * @param {RequestInfo} resource
296
+ * @param {RequestInit} [opts]
297
+ */
298
+ function initial_fetch(resource, opts) {
299
+ const url = JSON.stringify(typeof resource === 'string' ? resource : resource.url);
300
+
301
+ let selector = `script[sveltekit\\:data-type="data"][sveltekit\\:data-url=${url}]`;
302
+
303
+ if (opts && typeof opts.body === 'string') {
304
+ selector += `[sveltekit\\:data-body="${hash(opts.body)}"]`;
305
+ }
306
+
307
+ const script = document.querySelector(selector);
308
+ if (script && script.textContent) {
309
+ const { body, ...init } = JSON.parse(script.textContent);
310
+ return Promise.resolve(new Response(body, init));
311
+ }
312
+
313
+ return native_fetch(resource, opts);
314
+ }
315
+
316
+ const param_pattern = /^(\.\.\.)?(\w+)(?:=(\w+))?$/;
317
+
318
+ /** @param {string} id */
319
+ function parse_route_id(id) {
320
+ /** @type {string[]} */
321
+ const names = [];
322
+
323
+ /** @type {string[]} */
324
+ const types = [];
325
+
326
+ // `/foo` should get an optional trailing slash, `/foo.json` should not
327
+ // const add_trailing_slash = !/\.[a-z]+$/.test(key);
328
+ let add_trailing_slash = true;
329
+
330
+ const pattern =
331
+ id === ''
332
+ ? /^\/$/
333
+ : new RegExp(
334
+ `^${decodeURIComponent(id)
335
+ .split(/(?:@[a-zA-Z0-9_-]+)?(?:\/|$)/)
336
+ .map((segment, i, segments) => {
337
+ // special case — /[...rest]/ could contain zero segments
338
+ const match = /^\[\.\.\.(\w+)(?:=(\w+))?\]$/.exec(segment);
339
+ if (match) {
340
+ names.push(match[1]);
341
+ types.push(match[2]);
342
+ return '(?:/(.*))?';
343
+ }
344
+
345
+ const is_last = i === segments.length - 1;
346
+
347
+ return (
348
+ segment &&
349
+ '/' +
350
+ segment
351
+ .split(/\[(.+?)\]/)
352
+ .map((content, i) => {
353
+ if (i % 2) {
354
+ const match = param_pattern.exec(content);
355
+ if (!match) {
356
+ throw new Error(
357
+ `Invalid param: ${content}. Params and matcher names can only have underscores and alphanumeric characters.`
358
+ );
359
+ }
360
+
361
+ const [, rest, name, type] = match;
362
+ names.push(name);
363
+ types.push(type);
364
+ return rest ? '(.*?)' : '([^/]+?)';
365
+ }
366
+
367
+ if (is_last && content.includes('.')) add_trailing_slash = false;
368
+
369
+ return (
370
+ content // allow users to specify characters on the file system in an encoded manner
371
+ .normalize()
372
+ // We use [ and ] to denote parameters, so users must encode these on the file
373
+ // system to match against them. We don't decode all characters since others
374
+ // can already be epressed and so that '%' can be easily used directly in filenames
375
+ .replace(/%5[Bb]/g, '[')
376
+ .replace(/%5[Dd]/g, ']')
377
+ // '#', '/', and '?' can only appear in URL path segments in an encoded manner.
378
+ // They will not be touched by decodeURI so need to be encoded here, so
379
+ // that we can match against them.
380
+ // We skip '/' since you can't create a file with it on any OS
381
+ .replace(/#/g, '%23')
382
+ .replace(/\?/g, '%3F')
383
+ // escape characters that have special meaning in regex
384
+ .replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
385
+ ); // TODO handle encoding
386
+ })
387
+ .join('')
388
+ );
389
+ })
390
+ .join('')}${add_trailing_slash ? '/?' : ''}$`
391
+ );
392
+
393
+ return { pattern, names, types };
394
+ }
395
+
396
+ /**
397
+ * @param {RegExpMatchArray} match
398
+ * @param {string[]} names
399
+ * @param {string[]} types
400
+ * @param {Record<string, import('types').ParamMatcher>} matchers
401
+ */
402
+ function exec(match, names, types, matchers) {
403
+ /** @type {Record<string, string>} */
404
+ const params = {};
405
+
406
+ for (let i = 0; i < names.length; i += 1) {
407
+ const name = names[i];
408
+ const type = types[i];
409
+ const value = match[i + 1] || '';
410
+
411
+ if (type) {
412
+ const matcher = matchers[type];
413
+ if (!matcher) throw new Error(`Missing "${type}" param matcher`); // TODO do this ahead of time?
414
+
415
+ if (!matcher(value)) return;
416
+ }
417
+
418
+ params[name] = value;
419
+ }
420
+
421
+ return params;
422
+ }
423
+
424
+ /**
425
+ * @param {import('types').CSRComponentLoader[]} components
426
+ * @param {Record<string, [number[], number[], 1?]>} dictionary
427
+ * @param {Record<string, (param: string) => boolean>} matchers
428
+ * @returns {import('types').CSRRoute[]}
429
+ */
430
+ function parse(components, dictionary, matchers) {
431
+ const routes = Object.entries(dictionary).map(([id, [a, b, has_shadow]]) => {
432
+ const { pattern, names, types } = parse_route_id(id);
433
+
434
+ return {
435
+ id,
436
+ /** @param {string} path */
437
+ exec: (path) => {
438
+ const match = pattern.exec(path);
439
+ if (match) return exec(match, names, types, matchers);
440
+ },
441
+ a: a.map((n) => components[n]),
442
+ b: b.map((n) => components[n]),
443
+ has_shadow: !!has_shadow
444
+ };
445
+ });
446
+
447
+ return routes;
448
+ }
449
+
450
+ const SCROLL_KEY = 'sveltekit:scroll';
451
+ const INDEX_KEY = 'sveltekit:index';
452
+
453
+ const routes = parse(components, dictionary, matchers);
454
+
455
+ // we import the root layout/error components eagerly, so that
456
+ // connectivity errors after initialisation don't nuke the app
457
+ const default_layout = components[0]();
458
+ const default_error = components[1]();
459
+
460
+ const root_stuff = {};
461
+
462
+ // We track the scroll position associated with each history entry in sessionStorage,
463
+ // rather than on history.state itself, because when navigation is driven by
464
+ // popstate it's too late to update the scroll position associated with the
465
+ // state we're navigating from
466
+
467
+ /** @typedef {{ x: number, y: number }} ScrollPosition */
468
+ /** @type {Record<number, ScrollPosition>} */
469
+ let scroll_positions = {};
470
+ try {
471
+ scroll_positions = JSON.parse(sessionStorage[SCROLL_KEY]);
472
+ } catch {
473
+ // do nothing
474
+ }
475
+
476
+ /** @param {number} index */
477
+ function update_scroll_positions(index) {
478
+ scroll_positions[index] = scroll_state();
479
+ }
480
+
481
+ /**
482
+ * @param {{
483
+ * target: Element;
484
+ * session: App.Session;
485
+ * base: string;
486
+ * trailing_slash: import('types').TrailingSlash;
487
+ * }} opts
488
+ * @returns {import('./types').Client}
489
+ */
490
+ function create_client({ target, session, base, trailing_slash }) {
491
+ /** @type {Map<string, import('./types').NavigationResult>} */
492
+ const cache = new Map();
493
+
494
+ /** @type {Array<((href: string) => boolean)>} */
495
+ const invalidated = [];
496
+
497
+ const stores = {
498
+ url: notifiable_store({}),
499
+ page: notifiable_store({}),
500
+ navigating: writable(/** @type {import('types').Navigation | null} */ (null)),
501
+ session: writable(session),
502
+ updated: create_updated_store()
503
+ };
504
+
505
+ /** @type {{id: string | null, promise: Promise<import('./types').NavigationResult | undefined> | null}} */
506
+ const load_cache = {
507
+ id: null,
508
+ promise: null
509
+ };
510
+
511
+ const callbacks = {
512
+ /** @type {Array<(opts: { from: URL, to: URL | null, cancel: () => void }) => void>} */
513
+ before_navigate: [],
514
+
515
+ /** @type {Array<(opts: { from: URL | null, to: URL }) => void>} */
516
+ after_navigate: []
517
+ };
518
+
519
+ /** @type {import('./types').NavigationState} */
520
+ let current = {
521
+ branch: [],
522
+ error: null,
523
+ session_id: 0,
524
+ stuff: root_stuff,
525
+ // @ts-ignore - we need the initial value to be null
526
+ url: null
527
+ };
528
+
529
+ let started = false;
530
+ let autoscroll = true;
531
+ let updating = false;
532
+ let session_id = 1;
533
+
534
+ /** @type {Promise<void> | null} */
535
+ let invalidating = null;
536
+
537
+ /** @type {import('svelte').SvelteComponent} */
538
+ let root;
539
+
540
+ /** @type {App.Session} */
541
+ let $session;
542
+
543
+ let ready = false;
544
+ stores.session.subscribe(async (value) => {
545
+ $session = value;
546
+
547
+ if (!ready) return;
548
+ session_id += 1;
549
+
550
+ update(new URL(location.href), [], true);
551
+ });
552
+ ready = true;
553
+
554
+ let router_enabled = true;
555
+
556
+ // keeping track of the history index in order to prevent popstate navigation events if needed
557
+ let current_history_index = history.state?.[INDEX_KEY];
558
+
559
+ if (!current_history_index) {
560
+ // we use Date.now() as an offset so that cross-document navigations
561
+ // within the app don't result in data loss
562
+ current_history_index = Date.now();
563
+
564
+ // create initial history entry, so we can return here
565
+ history.replaceState(
566
+ { ...history.state, [INDEX_KEY]: current_history_index },
567
+ '',
568
+ location.href
569
+ );
570
+ }
571
+
572
+ // if we reload the page, or Cmd-Shift-T back to it,
573
+ // recover scroll position
574
+ const scroll = scroll_positions[current_history_index];
575
+ if (scroll) {
576
+ history.scrollRestoration = 'manual';
577
+ scrollTo(scroll.x, scroll.y);
578
+ }
579
+
580
+ let hash_navigating = false;
581
+
582
+ /** @type {import('types').Page} */
583
+ let page;
584
+
585
+ /** @type {{}} */
586
+ let token;
587
+
588
+ /**
589
+ * @param {string | URL} url
590
+ * @param {{ noscroll?: boolean; replaceState?: boolean; keepfocus?: boolean; state?: any }} opts
591
+ * @param {string[]} redirect_chain
592
+ */
593
+ async function goto(
594
+ url,
595
+ { noscroll = false, replaceState = false, keepfocus = false, state = {} },
596
+ redirect_chain
597
+ ) {
598
+ if (typeof url === 'string') {
599
+ url = new URL(url, get_base_uri(document));
600
+ }
601
+
602
+ if (router_enabled) {
603
+ return navigate({
604
+ url,
605
+ scroll: noscroll ? scroll_state() : null,
606
+ keepfocus,
607
+ redirect_chain,
608
+ details: {
609
+ state,
610
+ replaceState
611
+ },
612
+ accepted: () => {},
613
+ blocked: () => {}
614
+ });
615
+ }
616
+
617
+ await native_navigation(url);
618
+ }
619
+
620
+ /** @param {URL} url */
621
+ async function prefetch(url) {
622
+ const intent = get_navigation_intent(url);
623
+
624
+ if (!intent) {
625
+ throw new Error('Attempted to prefetch a URL that does not belong to this app');
626
+ }
627
+
628
+ load_cache.promise = load_route(intent, false);
629
+ load_cache.id = intent.id;
630
+
631
+ return load_cache.promise;
632
+ }
633
+
634
+ /**
635
+ * Returns `true` if update completes, `false` if it is aborted
636
+ * @param {URL} url
637
+ * @param {string[]} redirect_chain
638
+ * @param {boolean} no_cache
639
+ * @param {{hash?: string, scroll: { x: number, y: number } | null, keepfocus: boolean, details: { replaceState: boolean, state: any } | null}} [opts]
640
+ * @param {() => void} [callback]
641
+ */
642
+ async function update(url, redirect_chain, no_cache, opts, callback) {
643
+ const intent = get_navigation_intent(url);
644
+
645
+ const current_token = (token = {});
646
+ let navigation_result = intent && (await load_route(intent, no_cache));
647
+
648
+ if (
649
+ !navigation_result &&
650
+ url.origin === location.origin &&
651
+ url.pathname === location.pathname
652
+ ) {
653
+ // this could happen in SPA fallback mode if the user navigated to
654
+ // `/non-existent-page`. if we fall back to reloading the page, it
655
+ // will create an infinite loop. so whereas we normally handle
656
+ // unknown routes by going to the server, in this special case
657
+ // we render a client-side error page instead
658
+ navigation_result = await load_root_error_page({
659
+ status: 404,
660
+ error: new Error(`Not found: ${url.pathname}`),
661
+ url,
662
+ routeId: null
663
+ });
664
+ }
665
+
666
+ if (!navigation_result) {
667
+ await native_navigation(url);
668
+ return false; // unnecessary, but TypeScript prefers it this way
669
+ }
670
+
671
+ // abort if user navigated during update
672
+ if (token !== current_token) return false;
673
+
674
+ invalidated.length = 0;
675
+
676
+ if (navigation_result.redirect) {
677
+ if (redirect_chain.length > 10 || redirect_chain.includes(url.pathname)) {
678
+ navigation_result = await load_root_error_page({
679
+ status: 500,
680
+ error: new Error('Redirect loop'),
681
+ url,
682
+ routeId: null
683
+ });
684
+ } else {
685
+ if (router_enabled) {
686
+ goto(new URL(navigation_result.redirect, url).href, {}, [
687
+ ...redirect_chain,
688
+ url.pathname
689
+ ]);
690
+ } else {
691
+ await native_navigation(new URL(navigation_result.redirect, location.href));
692
+ }
693
+
694
+ return false;
695
+ }
696
+ } else if (navigation_result.props?.page?.status >= 400) {
697
+ const updated = await stores.updated.check();
698
+ if (updated) {
699
+ await native_navigation(url);
700
+ }
701
+ }
702
+
703
+ updating = true;
704
+
705
+ if (opts && opts.details) {
706
+ const { details } = opts;
707
+ const change = details.replaceState ? 0 : 1;
708
+ details.state[INDEX_KEY] = current_history_index += change;
709
+ history[details.replaceState ? 'replaceState' : 'pushState'](details.state, '', url);
710
+ }
711
+
712
+ if (started) {
713
+ current = navigation_result.state;
714
+
715
+ if (navigation_result.props.page) {
716
+ navigation_result.props.page.url = url;
717
+ }
718
+
719
+ root.$set(navigation_result.props);
720
+ } else {
721
+ initialize(navigation_result);
722
+ }
723
+
724
+ // opts must be passed if we're navigating
725
+ if (opts) {
726
+ const { scroll, keepfocus } = opts;
727
+
728
+ if (!keepfocus) {
729
+ // Reset page selection and focus
730
+ // We try to mimic browsers' behaviour as closely as possible by targeting the
731
+ // first scrollable region, but unfortunately it's not a perfect match — e.g.
732
+ // shift-tabbing won't immediately cycle up from the end of the page on Chromium
733
+ // See https://html.spec.whatwg.org/multipage/interaction.html#get-the-focusable-area
734
+ const root = document.body;
735
+ const tabindex = root.getAttribute('tabindex');
736
+
737
+ root.tabIndex = -1;
738
+ root.focus({ preventScroll: true });
739
+
740
+ setTimeout(() => {
741
+ getSelection()?.removeAllRanges();
742
+ });
743
+
744
+ // restore `tabindex` as to prevent `root` from stealing input from elements
745
+ if (tabindex !== null) {
746
+ root.setAttribute('tabindex', tabindex);
747
+ } else {
748
+ root.removeAttribute('tabindex');
749
+ }
750
+ }
751
+
752
+ // need to render the DOM before we can scroll to the rendered elements
753
+ await tick();
754
+
755
+ if (autoscroll) {
756
+ const deep_linked = url.hash && document.getElementById(url.hash.slice(1));
757
+ if (scroll) {
758
+ scrollTo(scroll.x, scroll.y);
759
+ } else if (deep_linked) {
760
+ // Here we use `scrollIntoView` on the element instead of `scrollTo`
761
+ // because it natively supports the `scroll-margin` and `scroll-behavior`
762
+ // CSS properties.
763
+ deep_linked.scrollIntoView();
764
+ } else {
765
+ scrollTo(0, 0);
766
+ }
767
+ }
768
+ } else {
769
+ // in this case we're simply invalidating
770
+ await tick();
771
+ }
772
+
773
+ load_cache.promise = null;
774
+ load_cache.id = null;
775
+ autoscroll = true;
776
+
777
+ if (navigation_result.props.page) {
778
+ page = navigation_result.props.page;
779
+ }
780
+
781
+ const leaf_node = navigation_result.state.branch[navigation_result.state.branch.length - 1];
782
+ router_enabled = leaf_node?.module.router !== false;
783
+
784
+ if (callback) callback();
785
+
786
+ updating = false;
787
+ }
788
+
789
+ /** @param {import('./types').NavigationResult} result */
790
+ function initialize(result) {
791
+ current = result.state;
792
+
793
+ const style = document.querySelector('style[data-sveltekit]');
794
+ if (style) style.remove();
795
+
796
+ page = result.props.page;
797
+
798
+ root = new Root({
799
+ target,
800
+ props: { ...result.props, stores },
801
+ hydrate: true
802
+ });
803
+
804
+ if (router_enabled) {
805
+ const navigation = { from: null, to: new URL(location.href) };
806
+ callbacks.after_navigate.forEach((fn) => fn(navigation));
807
+ }
808
+
809
+ started = true;
810
+ }
811
+
812
+ /**
813
+ *
814
+ * @param {{
815
+ * url: URL;
816
+ * params: Record<string, string>;
817
+ * stuff: Record<string, any>;
818
+ * branch: Array<import('./types').BranchNode | undefined>;
819
+ * status: number;
820
+ * error: Error | null;
821
+ * routeId: string | null;
822
+ * }} opts
823
+ */
824
+ async function get_navigation_result_from_branch({
825
+ url,
826
+ params,
827
+ stuff,
828
+ branch,
829
+ status,
830
+ error,
831
+ routeId
832
+ }) {
833
+ const filtered = /** @type {import('./types').BranchNode[] } */ (branch.filter(Boolean));
834
+ const redirect = filtered.find((f) => f.loaded?.redirect);
835
+
836
+ /** @type {import('./types').NavigationResult} */
837
+ const result = {
838
+ redirect: redirect?.loaded?.redirect,
839
+ state: {
840
+ url,
841
+ params,
842
+ branch,
843
+ error,
844
+ stuff,
845
+ session_id
846
+ },
847
+ props: {
848
+ components: filtered.map((node) => node.module.default)
849
+ }
850
+ };
851
+
852
+ for (let i = 0; i < filtered.length; i += 1) {
853
+ const loaded = filtered[i].loaded;
854
+ result.props[`props_${i}`] = loaded ? await loaded.props : null;
855
+ }
856
+
857
+ const page_changed =
858
+ !current.url ||
859
+ url.href !== current.url.href ||
860
+ current.error !== error ||
861
+ current.stuff !== stuff;
862
+
863
+ if (page_changed) {
864
+ result.props.page = { error, params, routeId, status, stuff, url };
865
+
866
+ // TODO remove this for 1.0
867
+ /**
868
+ * @param {string} property
869
+ * @param {string} replacement
870
+ */
871
+ const print_error = (property, replacement) => {
872
+ Object.defineProperty(result.props.page, property, {
873
+ get: () => {
874
+ throw new Error(`$page.${property} has been replaced by $page.url.${replacement}`);
875
+ }
876
+ });
877
+ };
878
+
879
+ print_error('origin', 'origin');
880
+ print_error('path', 'pathname');
881
+ print_error('query', 'searchParams');
882
+ }
883
+
884
+ const leaf = filtered[filtered.length - 1];
885
+ const load_cache = leaf?.loaded?.cache;
886
+
887
+ if (load_cache) {
888
+ const key = url.pathname + url.search; // omit hash
889
+ let ready = false;
890
+
891
+ const clear = () => {
892
+ if (cache.get(key) === result) {
893
+ cache.delete(key);
894
+ }
895
+
896
+ unsubscribe();
897
+ clearTimeout(timeout);
898
+ };
899
+
900
+ const timeout = setTimeout(clear, load_cache.maxage * 1000);
901
+
902
+ const unsubscribe = stores.session.subscribe(() => {
903
+ if (ready) clear();
904
+ });
905
+
906
+ ready = true;
907
+
908
+ cache.set(key, result);
909
+ }
910
+
911
+ return result;
912
+ }
913
+
914
+ /**
915
+ * @param {{
916
+ * status?: number;
917
+ * error?: Error;
918
+ * module: import('types').CSRComponent;
919
+ * url: URL;
920
+ * params: Record<string, string>;
921
+ * stuff: Record<string, any>;
922
+ * props?: Record<string, any>;
923
+ * routeId: string | null;
924
+ * }} options
925
+ */
926
+ async function load_node({ status, error, module, url, params, stuff, props, routeId }) {
927
+ /** @type {import('./types').BranchNode} */
928
+ const node = {
929
+ module,
930
+ uses: {
931
+ params: new Set(),
932
+ url: false,
933
+ session: false,
934
+ stuff: false,
935
+ dependencies: new Set()
936
+ },
937
+ loaded: null,
938
+ stuff
939
+ };
940
+
941
+ /** @param dep {string} */
942
+ function add_dependency(dep) {
943
+ const { href } = new URL(dep, url);
944
+ node.uses.dependencies.add(href);
945
+ }
946
+
947
+ if (props) {
948
+ // shadow endpoint props means we need to mark this URL as a dependency of itself
949
+ node.uses.dependencies.add(url.href);
950
+ }
951
+
952
+ /** @type {Record<string, string>} */
953
+ const uses_params = {};
954
+ for (const key in params) {
955
+ Object.defineProperty(uses_params, key, {
956
+ get() {
957
+ node.uses.params.add(key);
958
+ return params[key];
959
+ },
960
+ enumerable: true
961
+ });
962
+ }
963
+
964
+ const session = $session;
965
+ const load_url = new LoadURL(url);
966
+
967
+ if (module.load) {
968
+ /** @type {import('types').LoadEvent} */
969
+ const load_input = {
970
+ routeId,
971
+ params: uses_params,
972
+ props: props || {},
973
+ get url() {
974
+ node.uses.url = true;
975
+ return load_url;
976
+ },
977
+ get session() {
978
+ node.uses.session = true;
979
+ return session;
980
+ },
981
+ get stuff() {
982
+ node.uses.stuff = true;
983
+ return { ...stuff };
984
+ },
985
+ async fetch(resource, init) {
986
+ let requested;
987
+
988
+ if (typeof resource === 'string') {
989
+ requested = resource;
990
+ } else {
991
+ requested = resource.url;
992
+
993
+ // we're not allowed to modify the received `Request` object, so in order
994
+ // to fixup relative urls we create a new equivalent `init` object instead
995
+ init = {
996
+ // the request body must be consumed in memory until browsers
997
+ // implement streaming request bodies and/or the body getter
998
+ body:
999
+ resource.method === 'GET' || resource.method === 'HEAD'
1000
+ ? undefined
1001
+ : await resource.blob(),
1002
+ cache: resource.cache,
1003
+ credentials: resource.credentials,
1004
+ headers: resource.headers,
1005
+ integrity: resource.integrity,
1006
+ keepalive: resource.keepalive,
1007
+ method: resource.method,
1008
+ mode: resource.mode,
1009
+ redirect: resource.redirect,
1010
+ referrer: resource.referrer,
1011
+ referrerPolicy: resource.referrerPolicy,
1012
+ signal: resource.signal,
1013
+ ...init
1014
+ };
1015
+ }
1016
+
1017
+ // we must fixup relative urls so they are resolved from the target page
1018
+ const normalized = new URL(requested, url).href;
1019
+ add_dependency(normalized);
1020
+
1021
+ // prerendered pages may be served from any origin, so `initial_fetch` urls shouldn't be normalized
1022
+ return started ? native_fetch(normalized, init) : initial_fetch(requested, init);
1023
+ },
1024
+ status: status ?? null,
1025
+ error: error ?? null
1026
+ };
1027
+
1028
+ if (import.meta.env.DEV) {
1029
+ // TODO remove this for 1.0
1030
+ Object.defineProperty(load_input, 'page', {
1031
+ get: () => {
1032
+ throw new Error('`page` in `load` functions has been replaced by `url` and `params`');
1033
+ }
1034
+ });
1035
+ }
1036
+
1037
+ if (import.meta.env.DEV) {
1038
+ try {
1039
+ lock_fetch();
1040
+ node.loaded = normalize(await module.load.call(null, load_input));
1041
+ } finally {
1042
+ unlock_fetch();
1043
+ }
1044
+ } else {
1045
+ node.loaded = normalize(await module.load.call(null, load_input));
1046
+ }
1047
+
1048
+ if (node.loaded.stuff) node.stuff = node.loaded.stuff;
1049
+ if (node.loaded.dependencies) {
1050
+ node.loaded.dependencies.forEach(add_dependency);
1051
+ }
1052
+ } else if (props) {
1053
+ node.loaded = normalize({ props });
1054
+ }
1055
+
1056
+ return node;
1057
+ }
1058
+
1059
+ /**
1060
+ * @param {import('./types').NavigationIntent} intent
1061
+ * @param {boolean} no_cache
1062
+ */
1063
+ async function load_route({ id, url, params, route }, no_cache) {
1064
+ if (load_cache.id === id && load_cache.promise) {
1065
+ return load_cache.promise;
1066
+ }
1067
+
1068
+ if (!no_cache) {
1069
+ const cached = cache.get(id);
1070
+ if (cached) return cached;
1071
+ }
1072
+
1073
+ const { a, b, has_shadow } = route;
1074
+
1075
+ const changed = current.url && {
1076
+ url: id !== current.url.pathname + current.url.search,
1077
+ params: Object.keys(params).filter((key) => current.params[key] !== params[key]),
1078
+ session: session_id !== current.session_id
1079
+ };
1080
+
1081
+ /** @type {Array<import('./types').BranchNode | undefined>} */
1082
+ let branch = [];
1083
+
1084
+ /** @type {Record<string, any>} */
1085
+ let stuff = root_stuff;
1086
+ let stuff_changed = false;
1087
+
1088
+ /** @type {number} */
1089
+ let status = 200;
1090
+
1091
+ /** @type {Error | null} */
1092
+ let error = null;
1093
+
1094
+ // preload modules to avoid waterfall, but handle rejections
1095
+ // so they don't get reported to Sentry et al (we don't need
1096
+ // to act on the failures at this point)
1097
+ a.forEach((loader) => loader().catch(() => {}));
1098
+
1099
+ load: for (let i = 0; i < a.length; i += 1) {
1100
+ /** @type {import('./types').BranchNode | undefined} */
1101
+ let node;
1102
+
1103
+ try {
1104
+ if (!a[i]) continue;
1105
+
1106
+ const module = await a[i]();
1107
+ const previous = current.branch[i];
1108
+
1109
+ const changed_since_last_render =
1110
+ !previous ||
1111
+ module !== previous.module ||
1112
+ (changed.url && previous.uses.url) ||
1113
+ changed.params.some((param) => previous.uses.params.has(param)) ||
1114
+ (changed.session && previous.uses.session) ||
1115
+ Array.from(previous.uses.dependencies).some((dep) => invalidated.some((fn) => fn(dep))) ||
1116
+ (stuff_changed && previous.uses.stuff);
1117
+
1118
+ if (changed_since_last_render) {
1119
+ /** @type {Record<string, any>} */
1120
+ let props = {};
1121
+
1122
+ const is_shadow_page = has_shadow && i === a.length - 1;
1123
+
1124
+ if (is_shadow_page) {
1125
+ const res = await native_fetch(
1126
+ `${url.pathname}${url.pathname.endsWith('/') ? '' : '/'}__data.json${url.search}`,
1127
+ {
1128
+ headers: {
1129
+ 'x-sveltekit-load': 'true'
1130
+ }
1131
+ }
1132
+ );
1133
+
1134
+ if (res.ok) {
1135
+ const redirect = res.headers.get('x-sveltekit-location');
1136
+
1137
+ if (redirect) {
1138
+ return {
1139
+ redirect,
1140
+ props: {},
1141
+ state: current
1142
+ };
1143
+ }
1144
+
1145
+ props = res.status === 204 ? {} : await res.json();
1146
+ } else {
1147
+ status = res.status;
1148
+ try {
1149
+ error = await res.json();
1150
+ } catch (e) {
1151
+ error = new Error('Failed to load data');
1152
+ }
1153
+ }
1154
+ }
1155
+
1156
+ if (!error) {
1157
+ node = await load_node({
1158
+ module,
1159
+ url,
1160
+ params,
1161
+ props,
1162
+ stuff,
1163
+ routeId: route.id
1164
+ });
1165
+ }
1166
+
1167
+ if (node) {
1168
+ if (is_shadow_page) {
1169
+ node.uses.url = true;
1170
+ }
1171
+
1172
+ if (node.loaded) {
1173
+ if (node.loaded.error) {
1174
+ status = node.loaded.status ?? 500;
1175
+ error = node.loaded.error;
1176
+ }
1177
+
1178
+ if (node.loaded.redirect) {
1179
+ return {
1180
+ redirect: node.loaded.redirect,
1181
+ props: {},
1182
+ state: current
1183
+ };
1184
+ }
1185
+
1186
+ if (node.loaded.stuff) {
1187
+ stuff_changed = true;
1188
+ }
1189
+ }
1190
+ }
1191
+ } else {
1192
+ node = previous;
1193
+ }
1194
+ } catch (e) {
1195
+ status = 500;
1196
+ error = coalesce_to_error(e);
1197
+ }
1198
+
1199
+ if (error) {
1200
+ while (i--) {
1201
+ if (b[i]) {
1202
+ let error_loaded;
1203
+
1204
+ /** @type {import('./types').BranchNode | undefined} */
1205
+ let node_loaded;
1206
+ let j = i;
1207
+ while (!(node_loaded = branch[j])) {
1208
+ j -= 1;
1209
+ }
1210
+
1211
+ try {
1212
+ error_loaded = await load_node({
1213
+ status,
1214
+ error,
1215
+ module: await b[i](),
1216
+ url,
1217
+ params,
1218
+ stuff: node_loaded.stuff,
1219
+ routeId: route.id
1220
+ });
1221
+
1222
+ if (error_loaded?.loaded?.error) {
1223
+ continue;
1224
+ }
1225
+
1226
+ if (error_loaded?.loaded?.stuff) {
1227
+ stuff = {
1228
+ ...stuff,
1229
+ ...error_loaded.loaded.stuff
1230
+ };
1231
+ }
1232
+
1233
+ branch = branch.slice(0, j + 1).concat(error_loaded);
1234
+ break load;
1235
+ } catch (e) {
1236
+ continue;
1237
+ }
1238
+ }
1239
+ }
1240
+
1241
+ return await load_root_error_page({
1242
+ status,
1243
+ error,
1244
+ url,
1245
+ routeId: route.id
1246
+ });
1247
+ } else {
1248
+ if (node?.loaded?.stuff) {
1249
+ stuff = {
1250
+ ...stuff,
1251
+ ...node.loaded.stuff
1252
+ };
1253
+ }
1254
+
1255
+ branch.push(node);
1256
+ }
1257
+ }
1258
+
1259
+ return await get_navigation_result_from_branch({
1260
+ url,
1261
+ params,
1262
+ stuff,
1263
+ branch,
1264
+ status,
1265
+ error,
1266
+ routeId: route.id
1267
+ });
1268
+ }
1269
+
1270
+ /**
1271
+ * @param {{
1272
+ * status: number;
1273
+ * error: Error;
1274
+ * url: URL;
1275
+ * routeId: string | null
1276
+ * }} opts
1277
+ */
1278
+ async function load_root_error_page({ status, error, url, routeId }) {
1279
+ /** @type {Record<string, string>} */
1280
+ const params = {}; // error page does not have params
1281
+
1282
+ const root_layout = await load_node({
1283
+ module: await default_layout,
1284
+ url,
1285
+ params,
1286
+ stuff: {},
1287
+ routeId
1288
+ });
1289
+
1290
+ const root_error = await load_node({
1291
+ status,
1292
+ error,
1293
+ module: await default_error,
1294
+ url,
1295
+ params,
1296
+ stuff: (root_layout && root_layout.loaded && root_layout.loaded.stuff) || {},
1297
+ routeId
1298
+ });
1299
+
1300
+ return await get_navigation_result_from_branch({
1301
+ url,
1302
+ params,
1303
+ stuff: {
1304
+ ...root_layout?.loaded?.stuff,
1305
+ ...root_error?.loaded?.stuff
1306
+ },
1307
+ branch: [root_layout, root_error],
1308
+ status,
1309
+ error,
1310
+ routeId
1311
+ });
1312
+ }
1313
+
1314
+ /** @param {URL} url */
1315
+ function get_navigation_intent(url) {
1316
+ if (url.origin !== location.origin || !url.pathname.startsWith(base)) return;
1317
+
1318
+ const path = decodeURI(url.pathname.slice(base.length) || '/');
1319
+
1320
+ for (const route of routes) {
1321
+ const params = route.exec(path);
1322
+
1323
+ if (params) {
1324
+ const id = normalize_path(url.pathname, trailing_slash) + url.search;
1325
+ /** @type {import('./types').NavigationIntent} */
1326
+ const intent = { id, route, params, url };
1327
+ return intent;
1328
+ }
1329
+ }
1330
+ }
1331
+
1332
+ /**
1333
+ * @param {{
1334
+ * url: URL;
1335
+ * scroll: { x: number, y: number } | null;
1336
+ * keepfocus: boolean;
1337
+ * redirect_chain: string[];
1338
+ * details: {
1339
+ * replaceState: boolean;
1340
+ * state: any;
1341
+ * } | null;
1342
+ * accepted: () => void;
1343
+ * blocked: () => void;
1344
+ * }} opts
1345
+ */
1346
+ async function navigate({ url, scroll, keepfocus, redirect_chain, details, accepted, blocked }) {
1347
+ const from = current.url;
1348
+ let should_block = false;
1349
+
1350
+ const navigation = {
1351
+ from,
1352
+ to: url,
1353
+ cancel: () => (should_block = true)
1354
+ };
1355
+
1356
+ callbacks.before_navigate.forEach((fn) => fn(navigation));
1357
+
1358
+ if (should_block) {
1359
+ blocked();
1360
+ return;
1361
+ }
1362
+
1363
+ const pathname = normalize_path(url.pathname, trailing_slash);
1364
+ const normalized = new URL(url.origin + pathname + url.search + url.hash);
1365
+
1366
+ update_scroll_positions(current_history_index);
1367
+
1368
+ accepted();
1369
+
1370
+ if (started) {
1371
+ stores.navigating.set({
1372
+ from: current.url,
1373
+ to: normalized
1374
+ });
1375
+ }
1376
+
1377
+ await update(
1378
+ normalized,
1379
+ redirect_chain,
1380
+ false,
1381
+ {
1382
+ scroll,
1383
+ keepfocus,
1384
+ details
1385
+ },
1386
+ () => {
1387
+ const navigation = { from, to: normalized };
1388
+ callbacks.after_navigate.forEach((fn) => fn(navigation));
1389
+
1390
+ stores.navigating.set(null);
1391
+ }
1392
+ );
1393
+ }
1394
+
1395
+ /**
1396
+ * Loads `href` the old-fashioned way, with a full page reload.
1397
+ * Returns a `Promise` that never resolves (to prevent any
1398
+ * subsequent work, e.g. history manipulation, from happening)
1399
+ * @param {URL} url
1400
+ */
1401
+ function native_navigation(url) {
1402
+ location.href = url.href;
1403
+ return new Promise(() => {});
1404
+ }
1405
+
1406
+ if (import.meta.hot) {
1407
+ import.meta.hot.on('vite:beforeUpdate', () => {
1408
+ if (current.error) location.reload();
1409
+ });
1410
+ }
1411
+
1412
+ return {
1413
+ after_navigate: (fn) => {
1414
+ onMount(() => {
1415
+ callbacks.after_navigate.push(fn);
1416
+
1417
+ return () => {
1418
+ const i = callbacks.after_navigate.indexOf(fn);
1419
+ callbacks.after_navigate.splice(i, 1);
1420
+ };
1421
+ });
1422
+ },
1423
+
1424
+ before_navigate: (fn) => {
1425
+ onMount(() => {
1426
+ callbacks.before_navigate.push(fn);
1427
+
1428
+ return () => {
1429
+ const i = callbacks.before_navigate.indexOf(fn);
1430
+ callbacks.before_navigate.splice(i, 1);
1431
+ };
1432
+ });
1433
+ },
1434
+
1435
+ disable_scroll_handling: () => {
1436
+ if (import.meta.env.DEV && started && !updating) {
1437
+ throw new Error('Can only disable scroll handling during navigation');
1438
+ }
1439
+
1440
+ if (updating || !started) {
1441
+ autoscroll = false;
1442
+ }
1443
+ },
1444
+
1445
+ goto: (href, opts = {}) => goto(href, opts, []),
1446
+
1447
+ invalidate: (resource) => {
1448
+ if (typeof resource === 'function') {
1449
+ invalidated.push(resource);
1450
+ } else {
1451
+ const { href } = new URL(resource, location.href);
1452
+ invalidated.push((dep) => dep === href);
1453
+ }
1454
+
1455
+ if (!invalidating) {
1456
+ invalidating = Promise.resolve().then(async () => {
1457
+ await update(new URL(location.href), [], true);
1458
+
1459
+ invalidating = null;
1460
+ });
1461
+ }
1462
+
1463
+ return invalidating;
1464
+ },
1465
+
1466
+ prefetch: async (href) => {
1467
+ const url = new URL(href, get_base_uri(document));
1468
+ await prefetch(url);
1469
+ },
1470
+
1471
+ // TODO rethink this API
1472
+ prefetch_routes: async (pathnames) => {
1473
+ const matching = pathnames
1474
+ ? routes.filter((route) => pathnames.some((pathname) => route.exec(pathname)))
1475
+ : routes;
1476
+
1477
+ const promises = matching.map((r) => Promise.all(r.a.map((load) => load())));
1478
+
1479
+ await Promise.all(promises);
1480
+ },
1481
+
1482
+ _start_router: () => {
1483
+ history.scrollRestoration = 'manual';
1484
+
1485
+ // Adopted from Nuxt.js
1486
+ // Reset scrollRestoration to auto when leaving page, allowing page reload
1487
+ // and back-navigation from other pages to use the browser to restore the
1488
+ // scrolling position.
1489
+ addEventListener('beforeunload', (e) => {
1490
+ let should_block = false;
1491
+
1492
+ const navigation = {
1493
+ from: current.url,
1494
+ to: null,
1495
+ cancel: () => (should_block = true)
1496
+ };
1497
+
1498
+ callbacks.before_navigate.forEach((fn) => fn(navigation));
1499
+
1500
+ if (should_block) {
1501
+ e.preventDefault();
1502
+ e.returnValue = '';
1503
+ } else {
1504
+ history.scrollRestoration = 'auto';
1505
+ }
1506
+ });
1507
+
1508
+ addEventListener('visibilitychange', () => {
1509
+ if (document.visibilityState === 'hidden') {
1510
+ update_scroll_positions(current_history_index);
1511
+
1512
+ try {
1513
+ sessionStorage[SCROLL_KEY] = JSON.stringify(scroll_positions);
1514
+ } catch {
1515
+ // do nothing
1516
+ }
1517
+ }
1518
+ });
1519
+
1520
+ /** @param {Event} event */
1521
+ const trigger_prefetch = (event) => {
1522
+ const a = find_anchor(event);
1523
+ if (a && a.href && a.hasAttribute('sveltekit:prefetch')) {
1524
+ prefetch(get_href(a));
1525
+ }
1526
+ };
1527
+
1528
+ /** @type {NodeJS.Timeout} */
1529
+ let mousemove_timeout;
1530
+
1531
+ /** @param {MouseEvent|TouchEvent} event */
1532
+ const handle_mousemove = (event) => {
1533
+ clearTimeout(mousemove_timeout);
1534
+ mousemove_timeout = setTimeout(() => {
1535
+ // event.composedPath(), which is used in find_anchor, will be empty if the event is read in a timeout
1536
+ // add a layer of indirection to address that
1537
+ event.target?.dispatchEvent(
1538
+ new CustomEvent('sveltekit:trigger_prefetch', { bubbles: true })
1539
+ );
1540
+ }, 20);
1541
+ };
1542
+
1543
+ addEventListener('touchstart', trigger_prefetch);
1544
+ addEventListener('mousemove', handle_mousemove);
1545
+ addEventListener('sveltekit:trigger_prefetch', trigger_prefetch);
1546
+
1547
+ /** @param {MouseEvent} event */
1548
+ addEventListener('click', (event) => {
1549
+ if (!router_enabled) return;
1550
+
1551
+ // Adapted from https://github.com/visionmedia/page.js
1552
+ // MIT license https://github.com/visionmedia/page.js#license
1553
+ if (event.button || event.which !== 1) return;
1554
+ if (event.metaKey || event.ctrlKey || event.shiftKey || event.altKey) return;
1555
+ if (event.defaultPrevented) return;
1556
+
1557
+ const a = find_anchor(event);
1558
+ if (!a) return;
1559
+
1560
+ if (!a.href) return;
1561
+
1562
+ const is_svg_a_element = a instanceof SVGAElement;
1563
+ const url = get_href(a);
1564
+
1565
+ // Ignore if url does not have origin (e.g. `mailto:`, `tel:`.)
1566
+ // MEMO: Without this condition, firefox will open mailer twice.
1567
+ // See: https://github.com/sveltejs/kit/issues/4045
1568
+ if (!is_svg_a_element && url.origin === 'null') return;
1569
+
1570
+ // Ignore if tag has
1571
+ // 1. 'download' attribute
1572
+ // 2. 'rel' attribute includes external
1573
+ const rel = (a.getAttribute('rel') || '').split(/\s+/);
1574
+
1575
+ if (
1576
+ a.hasAttribute('download') ||
1577
+ rel.includes('external') ||
1578
+ a.hasAttribute('sveltekit:reload')
1579
+ ) {
1580
+ return;
1581
+ }
1582
+
1583
+ // Ignore if <a> has a target
1584
+ if (is_svg_a_element ? a.target.baseVal : a.target) return;
1585
+
1586
+ // Check if new url only differs by hash and use the browser default behavior in that case
1587
+ // This will ensure the `hashchange` event is fired
1588
+ // Removing the hash does a full page navigation in the browser, so make sure a hash is present
1589
+ const [base, hash] = url.href.split('#');
1590
+ if (hash !== undefined && base === location.href.split('#')[0]) {
1591
+ // set this flag to distinguish between navigations triggered by
1592
+ // clicking a hash link and those triggered by popstate
1593
+ hash_navigating = true;
1594
+
1595
+ update_scroll_positions(current_history_index);
1596
+
1597
+ stores.page.set({ ...page, url });
1598
+ stores.page.notify();
1599
+
1600
+ return;
1601
+ }
1602
+
1603
+ navigate({
1604
+ url,
1605
+ scroll: a.hasAttribute('sveltekit:noscroll') ? scroll_state() : null,
1606
+ keepfocus: false,
1607
+ redirect_chain: [],
1608
+ details: {
1609
+ state: {},
1610
+ replaceState: url.href === location.href
1611
+ },
1612
+ accepted: () => event.preventDefault(),
1613
+ blocked: () => event.preventDefault()
1614
+ });
1615
+ });
1616
+
1617
+ addEventListener('popstate', (event) => {
1618
+ if (event.state && router_enabled) {
1619
+ // if a popstate-driven navigation is cancelled, we need to counteract it
1620
+ // with history.go, which means we end up back here, hence this check
1621
+ if (event.state[INDEX_KEY] === current_history_index) return;
1622
+
1623
+ navigate({
1624
+ url: new URL(location.href),
1625
+ scroll: scroll_positions[event.state[INDEX_KEY]],
1626
+ keepfocus: false,
1627
+ redirect_chain: [],
1628
+ details: null,
1629
+ accepted: () => {
1630
+ current_history_index = event.state[INDEX_KEY];
1631
+ },
1632
+ blocked: () => {
1633
+ const delta = current_history_index - event.state[INDEX_KEY];
1634
+ history.go(delta);
1635
+ }
1636
+ });
1637
+ }
1638
+ });
1639
+
1640
+ addEventListener('hashchange', () => {
1641
+ // if the hashchange happened as a result of clicking on a link,
1642
+ // we need to update history, otherwise we have to leave it alone
1643
+ if (hash_navigating) {
1644
+ hash_navigating = false;
1645
+ history.replaceState(
1646
+ { ...history.state, [INDEX_KEY]: ++current_history_index },
1647
+ '',
1648
+ location.href
1649
+ );
1650
+ }
1651
+ });
1652
+
1653
+ addEventListener('pageshow', (event) => {
1654
+ // If the user navigates to another site and then uses the back button and
1655
+ // bfcache hits, we need to set navigating to null, the site doesn't know
1656
+ // the navigation away from it was successful.
1657
+ // Info about bfcache here: https://web.dev/bfcache
1658
+ if (event.persisted) {
1659
+ stores.navigating.set(null);
1660
+ }
1661
+ });
1662
+ },
1663
+
1664
+ _hydrate: async ({ status, error, nodes, params, routeId }) => {
1665
+ const url = new URL(location.href);
1666
+
1667
+ /** @type {Array<import('./types').BranchNode | undefined>} */
1668
+ const branch = [];
1669
+
1670
+ /** @type {Record<string, any>} */
1671
+ let stuff = {};
1672
+
1673
+ /** @type {import('./types').NavigationResult | undefined} */
1674
+ let result;
1675
+
1676
+ let error_args;
1677
+
1678
+ try {
1679
+ for (let i = 0; i < nodes.length; i += 1) {
1680
+ const is_leaf = i === nodes.length - 1;
1681
+
1682
+ let props;
1683
+
1684
+ if (is_leaf) {
1685
+ const serialized = document.querySelector('script[sveltekit\\:data-type="props"]');
1686
+ if (serialized) {
1687
+ props = JSON.parse(/** @type {string} */ (serialized.textContent));
1688
+ }
1689
+ }
1690
+
1691
+ const node = await load_node({
1692
+ module: await components[nodes[i]](),
1693
+ url,
1694
+ params,
1695
+ stuff,
1696
+ status: is_leaf ? status : undefined,
1697
+ error: is_leaf ? error : undefined,
1698
+ props,
1699
+ routeId
1700
+ });
1701
+
1702
+ if (props) {
1703
+ node.uses.dependencies.add(url.href);
1704
+ node.uses.url = true;
1705
+ }
1706
+
1707
+ branch.push(node);
1708
+
1709
+ if (node && node.loaded) {
1710
+ if (node.loaded.error) {
1711
+ if (error) throw node.loaded.error;
1712
+ error_args = {
1713
+ status: node.loaded.status ?? 500,
1714
+ error: node.loaded.error,
1715
+ url,
1716
+ routeId
1717
+ };
1718
+ } else if (node.loaded.stuff) {
1719
+ stuff = {
1720
+ ...stuff,
1721
+ ...node.loaded.stuff
1722
+ };
1723
+ }
1724
+ }
1725
+ }
1726
+
1727
+ result = error_args
1728
+ ? await load_root_error_page(error_args)
1729
+ : await get_navigation_result_from_branch({
1730
+ url,
1731
+ params,
1732
+ stuff,
1733
+ branch,
1734
+ status,
1735
+ error,
1736
+ routeId
1737
+ });
1738
+ } catch (e) {
1739
+ if (error) throw e;
1740
+
1741
+ result = await load_root_error_page({
1742
+ status: 500,
1743
+ error: coalesce_to_error(e),
1744
+ url,
1745
+ routeId
1746
+ });
1747
+ }
1748
+
1749
+ if (result.redirect) {
1750
+ // this is a real edge case — `load` would need to return
1751
+ // a redirect but only in the browser
1752
+ await native_navigation(new URL(result.redirect, location.href));
1753
+ }
1754
+
1755
+ initialize(result);
1756
+ }
1757
+ };
1758
+ }
1759
+
1760
+ /**
1761
+ * @param {{
1762
+ * paths: {
1763
+ * assets: string;
1764
+ * base: string;
1765
+ * },
1766
+ * target: Element;
1767
+ * session: any;
1768
+ * route: boolean;
1769
+ * spa: boolean;
1770
+ * trailing_slash: import('types').TrailingSlash;
1771
+ * hydrate: {
1772
+ * status: number;
1773
+ * error: Error;
1774
+ * nodes: number[];
1775
+ * params: Record<string, string>;
1776
+ * routeId: string | null;
1777
+ * };
1778
+ * }} opts
1779
+ */
1780
+ async function start({ paths, target, session, route, spa, trailing_slash, hydrate }) {
1781
+ const client = create_client({
1782
+ target,
1783
+ session,
1784
+ base: paths.base,
1785
+ trailing_slash
1786
+ });
1787
+
1788
+ init({ client });
1789
+ set_paths(paths);
1790
+
1791
+ if (hydrate) {
1792
+ await client._hydrate(hydrate);
1793
+ }
1794
+
1795
+ if (route) {
1796
+ if (spa) client.goto(location.href, { replaceState: true });
1797
+ client._start_router();
1798
+ }
1799
+
1800
+ dispatchEvent(new CustomEvent('sveltekit:start'));
1801
+ }
1802
+
1803
+ export { start };