@sveltejs/kit 1.0.0-next.30 → 1.0.0-next.302

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