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

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