@sveltejs/kit 1.0.0-next.34 → 1.0.0-next.340

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