@sveltejs/kit 1.0.0-next.39 → 1.0.0-next.392

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