@tanstack/solid-router 1.114.24 → 1.114.26

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.
@@ -1,1687 +1,14 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
3
- const history = require("@tanstack/history");
4
- const solidStore = require("@tanstack/solid-store");
5
- const invariant = require("tiny-invariant");
6
3
  const routerCore = require("@tanstack/router-core");
7
- const componentTypes = [
8
- "component",
9
- "errorComponent",
10
- "pendingComponent",
11
- "notFoundComponent"
12
- ];
13
- function routeNeedsPreload(route) {
14
- var _a;
15
- for (const componentType of componentTypes) {
16
- if ((_a = route.options[componentType]) == null ? void 0 : _a.preload) {
17
- return true;
18
- }
19
- }
20
- return false;
21
- }
22
- function validateSearch(validateSearch2, input) {
23
- if (validateSearch2 == null) return {};
24
- if ("~standard" in validateSearch2) {
25
- const result = validateSearch2["~standard"].validate(input);
26
- if (result instanceof Promise)
27
- throw new SearchParamError("Async validation not supported");
28
- if (result.issues)
29
- throw new SearchParamError(JSON.stringify(result.issues, void 0, 2), {
30
- cause: result
31
- });
32
- return result.value;
33
- }
34
- if ("parse" in validateSearch2) {
35
- return validateSearch2.parse(input);
36
- }
37
- if (typeof validateSearch2 === "function") {
38
- return validateSearch2(input);
39
- }
40
- return {};
41
- }
42
- function createRouter(options) {
4
+ const createRouter = (options) => {
43
5
  return new Router(options);
44
- }
45
- class Router {
46
- /**
47
- * @deprecated Use the `createRouter` function instead
48
- */
6
+ };
7
+ class Router extends routerCore.RouterCore {
49
8
  constructor(options) {
50
- this.tempLocationKey = `${Math.round(
51
- Math.random() * 1e7
52
- )}`;
53
- this.resetNextScroll = true;
54
- this.shouldViewTransition = void 0;
55
- this.isViewTransitionTypesSupported = void 0;
56
- this.subscribers = /* @__PURE__ */ new Set();
57
- this.isScrollRestoring = false;
58
- this.isScrollRestorationSetup = false;
59
- this.startTransition = (fn) => fn();
60
- this.update = (newOptions) => {
61
- var _a;
62
- if (newOptions.notFoundRoute) {
63
- console.warn(
64
- "The notFoundRoute API is deprecated and will be removed in the next major version. See https://tanstack.com/router/v1/docs/guide/not-found-errors#migrating-from-notfoundroute for more info."
65
- );
66
- }
67
- const previousOptions = this.options;
68
- this.options = {
69
- ...this.options,
70
- ...newOptions
71
- };
72
- this.isServer = this.options.isServer ?? typeof document === "undefined";
73
- this.pathParamsDecodeCharMap = this.options.pathParamsAllowedCharacters ? new Map(
74
- this.options.pathParamsAllowedCharacters.map((char) => [
75
- encodeURIComponent(char),
76
- char
77
- ])
78
- ) : void 0;
79
- if (!this.basepath || newOptions.basepath && newOptions.basepath !== previousOptions.basepath) {
80
- if (newOptions.basepath === void 0 || newOptions.basepath === "" || newOptions.basepath === "/") {
81
- this.basepath = "/";
82
- } else {
83
- this.basepath = `/${routerCore.trimPath(newOptions.basepath)}`;
84
- }
85
- }
86
- if (!this.history || this.options.history && this.options.history !== this.history) {
87
- this.history = this.options.history ?? (this.isServer ? history.createMemoryHistory({
88
- initialEntries: [this.basepath || "/"]
89
- }) : history.createBrowserHistory());
90
- this.latestLocation = this.parseLocation();
91
- }
92
- if (this.options.routeTree !== this.routeTree) {
93
- this.routeTree = this.options.routeTree;
94
- this.buildRouteTree();
95
- }
96
- if (!this.__store) {
97
- this.__store = new solidStore.Store(getInitialRouterState(this.latestLocation), {
98
- onUpdate: () => {
99
- this.__store.state = {
100
- ...this.state,
101
- cachedMatches: this.state.cachedMatches.filter(
102
- (d) => !["redirected"].includes(d.status)
103
- )
104
- };
105
- }
106
- });
107
- routerCore.setupScrollRestoration(this);
108
- }
109
- if (typeof window !== "undefined" && "CSS" in window && typeof ((_a = window.CSS) == null ? void 0 : _a.supports) === "function") {
110
- this.isViewTransitionTypesSupported = window.CSS.supports(
111
- "selector(:active-view-transition-type(a)"
112
- );
113
- }
114
- };
115
- this.buildRouteTree = () => {
116
- this.routesById = {};
117
- this.routesByPath = {};
118
- const notFoundRoute = this.options.notFoundRoute;
119
- if (notFoundRoute) {
120
- notFoundRoute.init({
121
- originalIndex: 99999999999,
122
- defaultSsr: this.options.defaultSsr
123
- });
124
- this.routesById[notFoundRoute.id] = notFoundRoute;
125
- }
126
- const recurseRoutes = (childRoutes) => {
127
- childRoutes.forEach((childRoute, i) => {
128
- childRoute.init({
129
- originalIndex: i,
130
- defaultSsr: this.options.defaultSsr
131
- });
132
- const existingRoute = this.routesById[childRoute.id];
133
- invariant(
134
- !existingRoute,
135
- `Duplicate routes found with id: ${String(childRoute.id)}`
136
- );
137
- this.routesById[childRoute.id] = childRoute;
138
- if (!childRoute.isRoot && childRoute.path) {
139
- const trimmedFullPath = routerCore.trimPathRight(childRoute.fullPath);
140
- if (!this.routesByPath[trimmedFullPath] || childRoute.fullPath.endsWith("/")) {
141
- this.routesByPath[trimmedFullPath] = childRoute;
142
- }
143
- }
144
- const children = childRoute.children;
145
- if (children == null ? void 0 : children.length) {
146
- recurseRoutes(children);
147
- }
148
- });
149
- };
150
- recurseRoutes([this.routeTree]);
151
- const scoredRoutes = [];
152
- const routes = Object.values(this.routesById);
153
- routes.forEach((d, i) => {
154
- var _a;
155
- if (d.isRoot || !d.path) {
156
- return;
157
- }
158
- const trimmed = routerCore.trimPathLeft(d.fullPath);
159
- const parsed = routerCore.parsePathname(trimmed);
160
- while (parsed.length > 1 && ((_a = parsed[0]) == null ? void 0 : _a.value) === "/") {
161
- parsed.shift();
162
- }
163
- const scores = parsed.map((segment) => {
164
- if (segment.value === "/") {
165
- return 0.75;
166
- }
167
- if (segment.type === "param") {
168
- return 0.5;
169
- }
170
- if (segment.type === "wildcard") {
171
- return 0.25;
172
- }
173
- return 1;
174
- });
175
- scoredRoutes.push({ child: d, trimmed, parsed, index: i, scores });
176
- });
177
- this.flatRoutes = scoredRoutes.sort((a, b) => {
178
- const minLength = Math.min(a.scores.length, b.scores.length);
179
- for (let i = 0; i < minLength; i++) {
180
- if (a.scores[i] !== b.scores[i]) {
181
- return b.scores[i] - a.scores[i];
182
- }
183
- }
184
- if (a.scores.length !== b.scores.length) {
185
- return b.scores.length - a.scores.length;
186
- }
187
- for (let i = 0; i < minLength; i++) {
188
- if (a.parsed[i].value !== b.parsed[i].value) {
189
- return a.parsed[i].value > b.parsed[i].value ? 1 : -1;
190
- }
191
- }
192
- return a.index - b.index;
193
- }).map((d, i) => {
194
- d.child.rank = i;
195
- return d.child;
196
- });
197
- };
198
- this.subscribe = (eventType, fn) => {
199
- const listener = {
200
- eventType,
201
- fn
202
- };
203
- this.subscribers.add(listener);
204
- return () => {
205
- this.subscribers.delete(listener);
206
- };
207
- };
208
- this.emit = (routerEvent) => {
209
- this.subscribers.forEach((listener) => {
210
- if (listener.eventType === routerEvent.type) {
211
- listener.fn(routerEvent);
212
- }
213
- });
214
- };
215
- this.parseLocation = (previousLocation, locationToParse) => {
216
- const parse = ({
217
- pathname,
218
- search,
219
- hash,
220
- state
221
- }) => {
222
- const parsedSearch = this.options.parseSearch(search);
223
- const searchStr = this.options.stringifySearch(parsedSearch);
224
- return {
225
- pathname,
226
- searchStr,
227
- search: routerCore.replaceEqualDeep(previousLocation == null ? void 0 : previousLocation.search, parsedSearch),
228
- hash: hash.split("#").reverse()[0] ?? "",
229
- href: `${pathname}${searchStr}${hash}`,
230
- state: routerCore.replaceEqualDeep(previousLocation == null ? void 0 : previousLocation.state, state)
231
- };
232
- };
233
- const location = parse(locationToParse ?? this.history.location);
234
- const { __tempLocation, __tempKey } = location.state;
235
- if (__tempLocation && (!__tempKey || __tempKey === this.tempLocationKey)) {
236
- const parsedTempLocation = parse(__tempLocation);
237
- parsedTempLocation.state.key = location.state.key;
238
- delete parsedTempLocation.state.__tempLocation;
239
- return {
240
- ...parsedTempLocation,
241
- maskedLocation: location
242
- };
243
- }
244
- return location;
245
- };
246
- this.resolvePathWithBase = (from, path) => {
247
- const resolvedPath = routerCore.resolvePath({
248
- basepath: this.basepath,
249
- base: from,
250
- to: routerCore.cleanPath(path),
251
- trailingSlash: this.options.trailingSlash,
252
- caseSensitive: this.options.caseSensitive
253
- });
254
- return resolvedPath;
255
- };
256
- this.matchRoutes = (pathnameOrNext, locationSearchOrOpts, opts) => {
257
- if (typeof pathnameOrNext === "string") {
258
- return this.matchRoutesInternal(
259
- {
260
- pathname: pathnameOrNext,
261
- search: locationSearchOrOpts
262
- },
263
- opts
264
- );
265
- } else {
266
- return this.matchRoutesInternal(pathnameOrNext, locationSearchOrOpts);
267
- }
268
- };
269
- this.getMatchedRoutes = (next, dest) => {
270
- let routeParams = {};
271
- const trimmedPath = routerCore.trimPathRight(next.pathname);
272
- const getMatchedParams = (route) => {
273
- const result = routerCore.matchPathname(this.basepath, trimmedPath, {
274
- to: route.fullPath,
275
- caseSensitive: route.options.caseSensitive ?? this.options.caseSensitive,
276
- fuzzy: true
277
- });
278
- return result;
279
- };
280
- let foundRoute = (dest == null ? void 0 : dest.to) !== void 0 ? this.routesByPath[dest.to] : void 0;
281
- if (foundRoute) {
282
- routeParams = getMatchedParams(foundRoute);
283
- } else {
284
- foundRoute = this.flatRoutes.find((route) => {
285
- const matchedParams = getMatchedParams(route);
286
- if (matchedParams) {
287
- routeParams = matchedParams;
288
- return true;
289
- }
290
- return false;
291
- });
292
- }
293
- let routeCursor = foundRoute || this.routesById[routerCore.rootRouteId];
294
- const matchedRoutes = [routeCursor];
295
- while (routeCursor.parentRoute) {
296
- routeCursor = routeCursor.parentRoute;
297
- matchedRoutes.unshift(routeCursor);
298
- }
299
- return { matchedRoutes, routeParams, foundRoute };
300
- };
301
- this.cancelMatch = (id) => {
302
- const match = this.getMatch(id);
303
- if (!match) return;
304
- match.abortController.abort();
305
- clearTimeout(match.pendingTimeout);
306
- };
307
- this.cancelMatches = () => {
308
- var _a;
309
- (_a = this.state.pendingMatches) == null ? void 0 : _a.forEach((match) => {
310
- this.cancelMatch(match.id);
311
- });
312
- };
313
- this.buildLocation = (opts) => {
314
- const build = (dest = {}, matchedRoutesResult) => {
315
- var _a, _b, _c, _d, _e, _f, _g;
316
- const fromMatches = dest._fromLocation ? this.matchRoutes(dest._fromLocation, { _buildLocation: true }) : this.state.matches;
317
- const fromMatch = dest.from != null ? fromMatches.find(
318
- (d) => routerCore.matchPathname(this.basepath, routerCore.trimPathRight(d.pathname), {
319
- to: dest.from,
320
- caseSensitive: false,
321
- fuzzy: false
322
- })
323
- ) : void 0;
324
- const fromPath = (fromMatch == null ? void 0 : fromMatch.pathname) || this.latestLocation.pathname;
325
- invariant(
326
- dest.from == null || fromMatch != null,
327
- "Could not find match for from: " + dest.from
328
- );
329
- const fromSearch = ((_a = this.state.pendingMatches) == null ? void 0 : _a.length) ? (_b = routerCore.last(this.state.pendingMatches)) == null ? void 0 : _b.search : ((_c = routerCore.last(fromMatches)) == null ? void 0 : _c.search) || this.latestLocation.search;
330
- const stayingMatches = matchedRoutesResult == null ? void 0 : matchedRoutesResult.matchedRoutes.filter(
331
- (d) => fromMatches.find((e) => e.routeId === d.id)
332
- );
333
- let pathname;
334
- if (dest.to) {
335
- const resolvePathTo = (fromMatch == null ? void 0 : fromMatch.fullPath) || ((_d = routerCore.last(fromMatches)) == null ? void 0 : _d.fullPath) || this.latestLocation.pathname;
336
- pathname = this.resolvePathWithBase(resolvePathTo, `${dest.to}`);
337
- } else {
338
- const fromRouteByFromPathRouteId = this.routesById[(_e = stayingMatches == null ? void 0 : stayingMatches.find((route) => {
339
- const interpolatedPath = routerCore.interpolatePath({
340
- path: route.fullPath,
341
- params: (matchedRoutesResult == null ? void 0 : matchedRoutesResult.routeParams) ?? {},
342
- decodeCharMap: this.pathParamsDecodeCharMap
343
- }).interpolatedPath;
344
- const pathname2 = routerCore.joinPaths([this.basepath, interpolatedPath]);
345
- return pathname2 === fromPath;
346
- })) == null ? void 0 : _e.id];
347
- pathname = this.resolvePathWithBase(
348
- fromPath,
349
- (fromRouteByFromPathRouteId == null ? void 0 : fromRouteByFromPathRouteId.to) ?? fromPath
350
- );
351
- }
352
- const prevParams = { ...(_f = routerCore.last(fromMatches)) == null ? void 0 : _f.params };
353
- let nextParams = (dest.params ?? true) === true ? prevParams : {
354
- ...prevParams,
355
- ...routerCore.functionalUpdate(dest.params, prevParams)
356
- };
357
- if (Object.keys(nextParams).length > 0) {
358
- matchedRoutesResult == null ? void 0 : matchedRoutesResult.matchedRoutes.map((route) => {
359
- var _a2;
360
- return ((_a2 = route.options.params) == null ? void 0 : _a2.stringify) ?? route.options.stringifyParams;
361
- }).filter(Boolean).forEach((fn) => {
362
- nextParams = { ...nextParams, ...fn(nextParams) };
363
- });
364
- }
365
- pathname = routerCore.interpolatePath({
366
- path: pathname,
367
- params: nextParams ?? {},
368
- leaveWildcards: false,
369
- leaveParams: opts.leaveParams,
370
- decodeCharMap: this.pathParamsDecodeCharMap
371
- }).interpolatedPath;
372
- let search = fromSearch;
373
- if (opts._includeValidateSearch && ((_g = this.options.search) == null ? void 0 : _g.strict)) {
374
- let validatedSearch = {};
375
- matchedRoutesResult == null ? void 0 : matchedRoutesResult.matchedRoutes.forEach((route) => {
376
- try {
377
- if (route.options.validateSearch) {
378
- validatedSearch = {
379
- ...validatedSearch,
380
- ...validateSearch(route.options.validateSearch, {
381
- ...validatedSearch,
382
- ...search
383
- }) ?? {}
384
- };
385
- }
386
- } catch {
387
- }
388
- });
389
- search = validatedSearch;
390
- }
391
- const applyMiddlewares = (search2) => {
392
- const allMiddlewares = (matchedRoutesResult == null ? void 0 : matchedRoutesResult.matchedRoutes.reduce(
393
- (acc, route) => {
394
- var _a2;
395
- const middlewares = [];
396
- if ("search" in route.options) {
397
- if ((_a2 = route.options.search) == null ? void 0 : _a2.middlewares) {
398
- middlewares.push(...route.options.search.middlewares);
399
- }
400
- } else if (route.options.preSearchFilters || route.options.postSearchFilters) {
401
- const legacyMiddleware = ({
402
- search: search3,
403
- next
404
- }) => {
405
- let nextSearch = search3;
406
- if ("preSearchFilters" in route.options && route.options.preSearchFilters) {
407
- nextSearch = route.options.preSearchFilters.reduce(
408
- (prev, next2) => next2(prev),
409
- search3
410
- );
411
- }
412
- const result = next(nextSearch);
413
- if ("postSearchFilters" in route.options && route.options.postSearchFilters) {
414
- return route.options.postSearchFilters.reduce(
415
- (prev, next2) => next2(prev),
416
- result
417
- );
418
- }
419
- return result;
420
- };
421
- middlewares.push(legacyMiddleware);
422
- }
423
- if (opts._includeValidateSearch && route.options.validateSearch) {
424
- const validate = ({ search: search3, next }) => {
425
- const result = next(search3);
426
- try {
427
- const validatedSearch = {
428
- ...result,
429
- ...validateSearch(
430
- route.options.validateSearch,
431
- result
432
- ) ?? {}
433
- };
434
- return validatedSearch;
435
- } catch {
436
- return result;
437
- }
438
- };
439
- middlewares.push(validate);
440
- }
441
- return acc.concat(middlewares);
442
- },
443
- []
444
- )) ?? [];
445
- const final = ({ search: search3 }) => {
446
- if (!dest.search) {
447
- return {};
448
- }
449
- if (dest.search === true) {
450
- return search3;
451
- }
452
- return routerCore.functionalUpdate(dest.search, search3);
453
- };
454
- allMiddlewares.push(final);
455
- const applyNext = (index, currentSearch) => {
456
- if (index >= allMiddlewares.length) {
457
- return currentSearch;
458
- }
459
- const middleware = allMiddlewares[index];
460
- const next = (newSearch) => {
461
- return applyNext(index + 1, newSearch);
462
- };
463
- return middleware({ search: currentSearch, next });
464
- };
465
- return applyNext(0, search2);
466
- };
467
- search = applyMiddlewares(search);
468
- search = routerCore.replaceEqualDeep(fromSearch, search);
469
- const searchStr = this.options.stringifySearch(search);
470
- const hash = dest.hash === true ? this.latestLocation.hash : dest.hash ? routerCore.functionalUpdate(dest.hash, this.latestLocation.hash) : void 0;
471
- const hashStr = hash ? `#${hash}` : "";
472
- let nextState = dest.state === true ? this.latestLocation.state : dest.state ? routerCore.functionalUpdate(dest.state, this.latestLocation.state) : {};
473
- nextState = routerCore.replaceEqualDeep(this.latestLocation.state, nextState);
474
- return {
475
- pathname,
476
- search,
477
- searchStr,
478
- state: nextState,
479
- hash: hash ?? "",
480
- href: `${pathname}${searchStr}${hashStr}`,
481
- unmaskOnReload: dest.unmaskOnReload
482
- };
483
- };
484
- const buildWithMatches = (dest = {}, maskedDest) => {
485
- var _a;
486
- const next = build(dest);
487
- let maskedNext = maskedDest ? build(maskedDest) : void 0;
488
- if (!maskedNext) {
489
- let params = {};
490
- const foundMask = (_a = this.options.routeMasks) == null ? void 0 : _a.find((d) => {
491
- const match = routerCore.matchPathname(this.basepath, next.pathname, {
492
- to: d.from,
493
- caseSensitive: false,
494
- fuzzy: false
495
- });
496
- if (match) {
497
- params = match;
498
- return true;
499
- }
500
- return false;
501
- });
502
- if (foundMask) {
503
- const { from: _from, ...maskProps } = foundMask;
504
- maskedDest = {
505
- ...routerCore.pick(opts, ["from"]),
506
- ...maskProps,
507
- params
508
- };
509
- maskedNext = build(maskedDest);
510
- }
511
- }
512
- const nextMatches = this.getMatchedRoutes(next, dest);
513
- const final = build(dest, nextMatches);
514
- if (maskedNext) {
515
- const maskedMatches = this.getMatchedRoutes(maskedNext, maskedDest);
516
- const maskedFinal = build(maskedDest, maskedMatches);
517
- final.maskedLocation = maskedFinal;
518
- }
519
- return final;
520
- };
521
- if (opts.mask) {
522
- return buildWithMatches(opts, {
523
- ...routerCore.pick(opts, ["from"]),
524
- ...opts.mask
525
- });
526
- }
527
- return buildWithMatches(opts);
528
- };
529
- this.commitLocation = ({
530
- viewTransition,
531
- ignoreBlocker,
532
- ...next
533
- }) => {
534
- const isSameState = () => {
535
- const ignoredProps = [
536
- "key",
537
- "__TSR_index",
538
- "__hashScrollIntoViewOptions"
539
- ];
540
- ignoredProps.forEach((prop) => {
541
- next.state[prop] = this.latestLocation.state[prop];
542
- });
543
- const isEqual = routerCore.deepEqual(next.state, this.latestLocation.state);
544
- ignoredProps.forEach((prop) => {
545
- delete next.state[prop];
546
- });
547
- return isEqual;
548
- };
549
- const isSameUrl = this.latestLocation.href === next.href;
550
- const previousCommitPromise = this.commitLocationPromise;
551
- this.commitLocationPromise = routerCore.createControlledPromise(() => {
552
- previousCommitPromise == null ? void 0 : previousCommitPromise.resolve();
553
- });
554
- if (isSameUrl && isSameState()) {
555
- this.load();
556
- } else {
557
- let { maskedLocation, hashScrollIntoView, ...nextHistory } = next;
558
- if (maskedLocation) {
559
- nextHistory = {
560
- ...maskedLocation,
561
- state: {
562
- ...maskedLocation.state,
563
- __tempKey: void 0,
564
- __tempLocation: {
565
- ...nextHistory,
566
- search: nextHistory.searchStr,
567
- state: {
568
- ...nextHistory.state,
569
- __tempKey: void 0,
570
- __tempLocation: void 0,
571
- key: void 0
572
- }
573
- }
574
- }
575
- };
576
- if (nextHistory.unmaskOnReload ?? this.options.unmaskOnReload ?? false) {
577
- nextHistory.state.__tempKey = this.tempLocationKey;
578
- }
579
- }
580
- nextHistory.state.__hashScrollIntoViewOptions = hashScrollIntoView ?? this.options.defaultHashScrollIntoView ?? true;
581
- this.shouldViewTransition = viewTransition;
582
- this.history[next.replace ? "replace" : "push"](
583
- nextHistory.href,
584
- nextHistory.state,
585
- { ignoreBlocker }
586
- );
587
- }
588
- this.resetNextScroll = next.resetScroll ?? true;
589
- if (!this.history.subscribers.size) {
590
- this.load();
591
- }
592
- return this.commitLocationPromise;
593
- };
594
- this.buildAndCommitLocation = ({
595
- replace,
596
- resetScroll,
597
- hashScrollIntoView,
598
- viewTransition,
599
- ignoreBlocker,
600
- href,
601
- ...rest
602
- } = {}) => {
603
- if (href) {
604
- const currentIndex = this.history.location.state.__TSR_index;
605
- const parsed = history.parseHref(href, {
606
- __TSR_index: replace ? currentIndex : currentIndex + 1
607
- });
608
- rest.to = parsed.pathname;
609
- rest.search = this.options.parseSearch(parsed.search);
610
- rest.hash = parsed.hash.slice(1);
611
- }
612
- const location = this.buildLocation({
613
- ...rest,
614
- _includeValidateSearch: true
615
- });
616
- return this.commitLocation({
617
- ...location,
618
- viewTransition,
619
- replace,
620
- resetScroll,
621
- hashScrollIntoView,
622
- ignoreBlocker
623
- });
624
- };
625
- this.navigate = ({ to, reloadDocument, href, ...rest }) => {
626
- if (reloadDocument) {
627
- if (!href) {
628
- const location = this.buildLocation({ to, ...rest });
629
- href = this.history.createHref(location.href);
630
- }
631
- if (rest.replace) {
632
- window.location.replace(href);
633
- } else {
634
- window.location.href = href;
635
- }
636
- return;
637
- }
638
- return this.buildAndCommitLocation({
639
- ...rest,
640
- href,
641
- to
642
- });
643
- };
644
- this.load = async (opts) => {
645
- this.latestLocation = this.parseLocation(this.latestLocation);
646
- let redirect;
647
- let notFound;
648
- let loadPromise;
649
- loadPromise = new Promise((resolve) => {
650
- this.startTransition(async () => {
651
- var _a;
652
- try {
653
- const next = this.latestLocation;
654
- const prevLocation = this.state.resolvedLocation;
655
- this.cancelMatches();
656
- let pendingMatches;
657
- solidStore.batch(() => {
658
- pendingMatches = this.matchRoutes(next);
659
- this.__store.setState((s) => ({
660
- ...s,
661
- status: "pending",
662
- isLoading: true,
663
- location: next,
664
- pendingMatches,
665
- // If a cached moved to pendingMatches, remove it from cachedMatches
666
- cachedMatches: s.cachedMatches.filter((d) => {
667
- return !pendingMatches.find((e) => e.id === d.id);
668
- })
669
- }));
670
- });
671
- if (!this.state.redirect) {
672
- this.emit({
673
- type: "onBeforeNavigate",
674
- ...routerCore.getLocationChangeInfo({
675
- resolvedLocation: prevLocation,
676
- location: next
677
- })
678
- });
679
- }
680
- this.emit({
681
- type: "onBeforeLoad",
682
- ...routerCore.getLocationChangeInfo({
683
- resolvedLocation: prevLocation,
684
- location: next
685
- })
686
- });
687
- await this.loadMatches({
688
- sync: opts == null ? void 0 : opts.sync,
689
- matches: pendingMatches,
690
- location: next,
691
- // eslint-disable-next-line @typescript-eslint/require-await
692
- onReady: async () => {
693
- this.startViewTransition(async () => {
694
- let exitingMatches;
695
- let enteringMatches;
696
- let stayingMatches;
697
- solidStore.batch(() => {
698
- this.__store.setState((s) => {
699
- const previousMatches = s.matches;
700
- const newMatches = s.pendingMatches || s.matches;
701
- exitingMatches = previousMatches.filter(
702
- (match) => !newMatches.find((d) => d.id === match.id)
703
- );
704
- enteringMatches = newMatches.filter(
705
- (match) => !previousMatches.find((d) => d.id === match.id)
706
- );
707
- stayingMatches = previousMatches.filter(
708
- (match) => newMatches.find((d) => d.id === match.id)
709
- );
710
- return {
711
- ...s,
712
- isLoading: false,
713
- loadedAt: Date.now(),
714
- matches: newMatches,
715
- pendingMatches: void 0,
716
- cachedMatches: [
717
- ...s.cachedMatches,
718
- ...exitingMatches.filter((d) => d.status !== "error")
719
- ]
720
- };
721
- });
722
- this.clearExpiredCache();
723
- });
724
- [
725
- [exitingMatches, "onLeave"],
726
- [enteringMatches, "onEnter"],
727
- [stayingMatches, "onStay"]
728
- ].forEach(([matches, hook]) => {
729
- matches.forEach((match) => {
730
- var _a2, _b;
731
- (_b = (_a2 = this.looseRoutesById[match.routeId].options)[hook]) == null ? void 0 : _b.call(_a2, match);
732
- });
733
- });
734
- });
735
- }
736
- });
737
- } catch (err) {
738
- if (routerCore.isResolvedRedirect(err)) {
739
- redirect = err;
740
- if (!this.isServer) {
741
- this.navigate({
742
- ...redirect,
743
- replace: true,
744
- ignoreBlocker: true
745
- });
746
- }
747
- } else if (routerCore.isNotFound(err)) {
748
- notFound = err;
749
- }
750
- this.__store.setState((s) => ({
751
- ...s,
752
- statusCode: redirect ? redirect.statusCode : notFound ? 404 : s.matches.some((d) => d.status === "error") ? 500 : 200,
753
- redirect
754
- }));
755
- }
756
- if (this.latestLoadPromise === loadPromise) {
757
- (_a = this.commitLocationPromise) == null ? void 0 : _a.resolve();
758
- this.latestLoadPromise = void 0;
759
- this.commitLocationPromise = void 0;
760
- }
761
- resolve();
762
- });
763
- });
764
- this.latestLoadPromise = loadPromise;
765
- await loadPromise;
766
- while (this.latestLoadPromise && loadPromise !== this.latestLoadPromise) {
767
- await this.latestLoadPromise;
768
- }
769
- if (this.hasNotFoundMatch()) {
770
- this.__store.setState((s) => ({
771
- ...s,
772
- statusCode: 404
773
- }));
774
- }
775
- };
776
- this.startViewTransition = (fn) => {
777
- const shouldViewTransition = this.shouldViewTransition ?? this.options.defaultViewTransition;
778
- delete this.shouldViewTransition;
779
- if (shouldViewTransition && typeof document !== "undefined" && "startViewTransition" in document && typeof document.startViewTransition === "function") {
780
- let startViewTransitionParams;
781
- if (typeof shouldViewTransition === "object" && this.isViewTransitionTypesSupported) {
782
- startViewTransitionParams = {
783
- update: fn,
784
- types: shouldViewTransition.types
785
- };
786
- } else {
787
- startViewTransitionParams = fn;
788
- }
789
- document.startViewTransition(startViewTransitionParams);
790
- } else {
791
- fn();
792
- }
793
- };
794
- this.updateMatch = (id, updater) => {
795
- var _a;
796
- let updated;
797
- const isPending = (_a = this.state.pendingMatches) == null ? void 0 : _a.find((d) => d.id === id);
798
- const isMatched = this.state.matches.find((d) => d.id === id);
799
- const isCached = this.state.cachedMatches.find((d) => d.id === id);
800
- const matchesKey = isPending ? "pendingMatches" : isMatched ? "matches" : isCached ? "cachedMatches" : "";
801
- if (matchesKey) {
802
- this.__store.setState((s) => {
803
- var _a2;
804
- return {
805
- ...s,
806
- [matchesKey]: (_a2 = s[matchesKey]) == null ? void 0 : _a2.map(
807
- (d) => d.id === id ? updated = updater(d) : d
808
- )
809
- };
810
- });
811
- }
812
- return updated;
813
- };
814
- this.getMatch = (matchId) => {
815
- return [
816
- ...this.state.cachedMatches,
817
- ...this.state.pendingMatches ?? [],
818
- ...this.state.matches
819
- ].find((d) => d.id === matchId);
820
- };
821
- this.loadMatches = async ({
822
- location,
823
- matches,
824
- preload: allPreload,
825
- onReady,
826
- updateMatch = this.updateMatch,
827
- sync
828
- }) => {
829
- let firstBadMatchIndex;
830
- let rendered = false;
831
- const triggerOnReady = async () => {
832
- if (!rendered) {
833
- rendered = true;
834
- await (onReady == null ? void 0 : onReady());
835
- }
836
- };
837
- const resolvePreload = (matchId) => {
838
- return !!(allPreload && !this.state.matches.find((d) => d.id === matchId));
839
- };
840
- if (!this.isServer && !this.state.matches.length) {
841
- triggerOnReady();
842
- }
843
- const handleRedirectAndNotFound = (match, err) => {
844
- var _a, _b, _c, _d;
845
- if (routerCore.isResolvedRedirect(err)) {
846
- if (!err.reloadDocument) {
847
- throw err;
848
- }
849
- }
850
- if (routerCore.isRedirect(err) || routerCore.isNotFound(err)) {
851
- updateMatch(match.id, (prev) => ({
852
- ...prev,
853
- status: routerCore.isRedirect(err) ? "redirected" : routerCore.isNotFound(err) ? "notFound" : "error",
854
- isFetching: false,
855
- error: err,
856
- beforeLoadPromise: void 0,
857
- loaderPromise: void 0
858
- }));
859
- if (!err.routeId) {
860
- err.routeId = match.routeId;
861
- }
862
- (_a = match.beforeLoadPromise) == null ? void 0 : _a.resolve();
863
- (_b = match.loaderPromise) == null ? void 0 : _b.resolve();
864
- (_c = match.loadPromise) == null ? void 0 : _c.resolve();
865
- if (routerCore.isRedirect(err)) {
866
- rendered = true;
867
- err = this.resolveRedirect({ ...err, _fromLocation: location });
868
- throw err;
869
- } else if (routerCore.isNotFound(err)) {
870
- this._handleNotFound(matches, err, {
871
- updateMatch
872
- });
873
- (_d = this.serverSsr) == null ? void 0 : _d.onMatchSettled({
874
- router: this,
875
- match: this.getMatch(match.id)
876
- });
877
- throw err;
878
- }
879
- }
880
- };
881
- try {
882
- await new Promise((resolveAll, rejectAll) => {
883
- ;
884
- (async () => {
885
- var _a, _b, _c;
886
- try {
887
- const handleSerialError = (index, err, routerCode) => {
888
- var _a2, _b2;
889
- const { id: matchId, routeId } = matches[index];
890
- const route = this.looseRoutesById[routeId];
891
- if (err instanceof Promise) {
892
- throw err;
893
- }
894
- err.routerCode = routerCode;
895
- firstBadMatchIndex = firstBadMatchIndex ?? index;
896
- handleRedirectAndNotFound(this.getMatch(matchId), err);
897
- try {
898
- (_b2 = (_a2 = route.options).onError) == null ? void 0 : _b2.call(_a2, err);
899
- } catch (errorHandlerErr) {
900
- err = errorHandlerErr;
901
- handleRedirectAndNotFound(this.getMatch(matchId), err);
902
- }
903
- updateMatch(matchId, (prev) => {
904
- var _a3, _b3;
905
- (_a3 = prev.beforeLoadPromise) == null ? void 0 : _a3.resolve();
906
- (_b3 = prev.loadPromise) == null ? void 0 : _b3.resolve();
907
- return {
908
- ...prev,
909
- error: err,
910
- status: "error",
911
- isFetching: false,
912
- updatedAt: Date.now(),
913
- abortController: new AbortController(),
914
- beforeLoadPromise: void 0
915
- };
916
- });
917
- };
918
- for (const [index, { id: matchId, routeId }] of matches.entries()) {
919
- const existingMatch = this.getMatch(matchId);
920
- const parentMatchId = (_a = matches[index - 1]) == null ? void 0 : _a.id;
921
- const route = this.looseRoutesById[routeId];
922
- const pendingMs = route.options.pendingMs ?? this.options.defaultPendingMs;
923
- const shouldPending = !!(onReady && !this.isServer && !resolvePreload(matchId) && (route.options.loader || route.options.beforeLoad) && typeof pendingMs === "number" && pendingMs !== Infinity && (route.options.pendingComponent ?? this.options.defaultPendingComponent));
924
- let executeBeforeLoad = true;
925
- if (
926
- // If we are in the middle of a load, either of these will be present
927
- // (not to be confused with `loadPromise`, which is always defined)
928
- existingMatch.beforeLoadPromise || existingMatch.loaderPromise
929
- ) {
930
- if (shouldPending) {
931
- setTimeout(() => {
932
- try {
933
- triggerOnReady();
934
- } catch {
935
- }
936
- }, pendingMs);
937
- }
938
- await existingMatch.beforeLoadPromise;
939
- executeBeforeLoad = this.getMatch(matchId).status !== "success";
940
- }
941
- if (executeBeforeLoad) {
942
- try {
943
- updateMatch(matchId, (prev) => {
944
- const prevLoadPromise = prev.loadPromise;
945
- return {
946
- ...prev,
947
- loadPromise: routerCore.createControlledPromise(() => {
948
- prevLoadPromise == null ? void 0 : prevLoadPromise.resolve();
949
- }),
950
- beforeLoadPromise: routerCore.createControlledPromise()
951
- };
952
- });
953
- const abortController = new AbortController();
954
- let pendingTimeout;
955
- if (shouldPending) {
956
- pendingTimeout = setTimeout(() => {
957
- try {
958
- triggerOnReady();
959
- } catch {
960
- }
961
- }, pendingMs);
962
- }
963
- const { paramsError, searchError } = this.getMatch(matchId);
964
- if (paramsError) {
965
- handleSerialError(index, paramsError, "PARSE_PARAMS");
966
- }
967
- if (searchError) {
968
- handleSerialError(index, searchError, "VALIDATE_SEARCH");
969
- }
970
- const getParentMatchContext = () => parentMatchId ? this.getMatch(parentMatchId).context : this.options.context ?? {};
971
- updateMatch(matchId, (prev) => ({
972
- ...prev,
973
- isFetching: "beforeLoad",
974
- fetchCount: prev.fetchCount + 1,
975
- abortController,
976
- pendingTimeout,
977
- context: {
978
- ...getParentMatchContext(),
979
- ...prev.__routeContext
980
- }
981
- }));
982
- const { search, params, context, cause } = this.getMatch(matchId);
983
- const preload = resolvePreload(matchId);
984
- const beforeLoadFnContext = {
985
- search,
986
- abortController,
987
- params,
988
- preload,
989
- context,
990
- location,
991
- navigate: (opts) => this.navigate({ ...opts, _fromLocation: location }),
992
- buildLocation: this.buildLocation,
993
- cause: preload ? "preload" : cause,
994
- matches
995
- };
996
- const beforeLoadContext = await ((_c = (_b = route.options).beforeLoad) == null ? void 0 : _c.call(_b, beforeLoadFnContext)) ?? {};
997
- if (routerCore.isRedirect(beforeLoadContext) || routerCore.isNotFound(beforeLoadContext)) {
998
- handleSerialError(index, beforeLoadContext, "BEFORE_LOAD");
999
- }
1000
- updateMatch(matchId, (prev) => {
1001
- return {
1002
- ...prev,
1003
- __beforeLoadContext: beforeLoadContext,
1004
- context: {
1005
- ...getParentMatchContext(),
1006
- ...prev.__routeContext,
1007
- ...beforeLoadContext
1008
- },
1009
- abortController
1010
- };
1011
- });
1012
- } catch (err) {
1013
- handleSerialError(index, err, "BEFORE_LOAD");
1014
- }
1015
- updateMatch(matchId, (prev) => {
1016
- var _a2;
1017
- (_a2 = prev.beforeLoadPromise) == null ? void 0 : _a2.resolve();
1018
- return {
1019
- ...prev,
1020
- beforeLoadPromise: void 0,
1021
- isFetching: false
1022
- };
1023
- });
1024
- }
1025
- }
1026
- const validResolvedMatches = matches.slice(0, firstBadMatchIndex);
1027
- const matchPromises = [];
1028
- validResolvedMatches.forEach(({ id: matchId, routeId }, index) => {
1029
- matchPromises.push(
1030
- (async () => {
1031
- const { loaderPromise: prevLoaderPromise } = this.getMatch(matchId);
1032
- let loaderShouldRunAsync = false;
1033
- let loaderIsRunningAsync = false;
1034
- if (prevLoaderPromise) {
1035
- await prevLoaderPromise;
1036
- const match = this.getMatch(matchId);
1037
- if (match.error) {
1038
- handleRedirectAndNotFound(match, match.error);
1039
- }
1040
- } else {
1041
- const parentMatchPromise = matchPromises[index - 1];
1042
- const route = this.looseRoutesById[routeId];
1043
- const getLoaderContext = () => {
1044
- const {
1045
- params,
1046
- loaderDeps,
1047
- abortController,
1048
- context,
1049
- cause
1050
- } = this.getMatch(matchId);
1051
- const preload2 = resolvePreload(matchId);
1052
- return {
1053
- params,
1054
- deps: loaderDeps,
1055
- preload: !!preload2,
1056
- parentMatchPromise,
1057
- abortController,
1058
- context,
1059
- location,
1060
- navigate: (opts) => this.navigate({ ...opts, _fromLocation: location }),
1061
- cause: preload2 ? "preload" : cause,
1062
- route
1063
- };
1064
- };
1065
- const age = Date.now() - this.getMatch(matchId).updatedAt;
1066
- const preload = resolvePreload(matchId);
1067
- const staleAge = preload ? route.options.preloadStaleTime ?? this.options.defaultPreloadStaleTime ?? 3e4 : route.options.staleTime ?? this.options.defaultStaleTime ?? 0;
1068
- const shouldReloadOption = route.options.shouldReload;
1069
- const shouldReload = typeof shouldReloadOption === "function" ? shouldReloadOption(getLoaderContext()) : shouldReloadOption;
1070
- updateMatch(matchId, (prev) => ({
1071
- ...prev,
1072
- loaderPromise: routerCore.createControlledPromise(),
1073
- preload: !!preload && !this.state.matches.find((d) => d.id === matchId)
1074
- }));
1075
- const runLoader = async () => {
1076
- var _a2, _b2, _c2, _d, _e, _f, _g, _h, _i, _j, _k;
1077
- try {
1078
- const potentialPendingMinPromise = async () => {
1079
- const latestMatch = this.getMatch(matchId);
1080
- if (latestMatch.minPendingPromise) {
1081
- await latestMatch.minPendingPromise;
1082
- }
1083
- };
1084
- try {
1085
- this.loadRouteChunk(route);
1086
- updateMatch(matchId, (prev) => ({
1087
- ...prev,
1088
- isFetching: "loader"
1089
- }));
1090
- const loaderData = await ((_b2 = (_a2 = route.options).loader) == null ? void 0 : _b2.call(_a2, getLoaderContext()));
1091
- handleRedirectAndNotFound(
1092
- this.getMatch(matchId),
1093
- loaderData
1094
- );
1095
- await route._lazyPromise;
1096
- await potentialPendingMinPromise();
1097
- const assetContext = {
1098
- matches,
1099
- match: this.getMatch(matchId),
1100
- params: this.getMatch(matchId).params,
1101
- loaderData
1102
- };
1103
- const headFnContent = (_d = (_c2 = route.options).head) == null ? void 0 : _d.call(_c2, assetContext);
1104
- const meta = headFnContent == null ? void 0 : headFnContent.meta;
1105
- const links = headFnContent == null ? void 0 : headFnContent.links;
1106
- const headScripts = headFnContent == null ? void 0 : headFnContent.scripts;
1107
- const scripts = (_f = (_e = route.options).scripts) == null ? void 0 : _f.call(_e, assetContext);
1108
- const headers = (_h = (_g = route.options).headers) == null ? void 0 : _h.call(_g, {
1109
- loaderData
1110
- });
1111
- updateMatch(matchId, (prev) => ({
1112
- ...prev,
1113
- error: void 0,
1114
- status: "success",
1115
- isFetching: false,
1116
- updatedAt: Date.now(),
1117
- loaderData,
1118
- meta,
1119
- links,
1120
- headScripts,
1121
- headers,
1122
- scripts
1123
- }));
1124
- } catch (e) {
1125
- let error = e;
1126
- await potentialPendingMinPromise();
1127
- handleRedirectAndNotFound(this.getMatch(matchId), e);
1128
- try {
1129
- (_j = (_i = route.options).onError) == null ? void 0 : _j.call(_i, e);
1130
- } catch (onErrorError) {
1131
- error = onErrorError;
1132
- handleRedirectAndNotFound(
1133
- this.getMatch(matchId),
1134
- onErrorError
1135
- );
1136
- }
1137
- updateMatch(matchId, (prev) => ({
1138
- ...prev,
1139
- error,
1140
- status: "error",
1141
- isFetching: false
1142
- }));
1143
- }
1144
- (_k = this.serverSsr) == null ? void 0 : _k.onMatchSettled({
1145
- router: this,
1146
- match: this.getMatch(matchId)
1147
- });
1148
- await route._componentsPromise;
1149
- } catch (err) {
1150
- updateMatch(matchId, (prev) => ({
1151
- ...prev,
1152
- loaderPromise: void 0
1153
- }));
1154
- handleRedirectAndNotFound(this.getMatch(matchId), err);
1155
- }
1156
- };
1157
- const { status, invalid } = this.getMatch(matchId);
1158
- loaderShouldRunAsync = status === "success" && (invalid || (shouldReload ?? age > staleAge));
1159
- if (preload && route.options.preload === false) {
1160
- } else if (loaderShouldRunAsync && !sync) {
1161
- loaderIsRunningAsync = true;
1162
- (async () => {
1163
- try {
1164
- await runLoader();
1165
- const { loaderPromise, loadPromise } = this.getMatch(matchId);
1166
- loaderPromise == null ? void 0 : loaderPromise.resolve();
1167
- loadPromise == null ? void 0 : loadPromise.resolve();
1168
- updateMatch(matchId, (prev) => ({
1169
- ...prev,
1170
- loaderPromise: void 0
1171
- }));
1172
- } catch (err) {
1173
- if (routerCore.isResolvedRedirect(err)) {
1174
- await this.navigate(err);
1175
- }
1176
- }
1177
- })();
1178
- } else if (status !== "success" || loaderShouldRunAsync && sync) {
1179
- await runLoader();
1180
- }
1181
- }
1182
- if (!loaderIsRunningAsync) {
1183
- const { loaderPromise, loadPromise } = this.getMatch(matchId);
1184
- loaderPromise == null ? void 0 : loaderPromise.resolve();
1185
- loadPromise == null ? void 0 : loadPromise.resolve();
1186
- }
1187
- updateMatch(matchId, (prev) => ({
1188
- ...prev,
1189
- isFetching: loaderIsRunningAsync ? prev.isFetching : false,
1190
- loaderPromise: loaderIsRunningAsync ? prev.loaderPromise : void 0,
1191
- invalid: false
1192
- }));
1193
- return this.getMatch(matchId);
1194
- })()
1195
- );
1196
- });
1197
- await Promise.all(matchPromises);
1198
- resolveAll();
1199
- } catch (err) {
1200
- rejectAll(err);
1201
- }
1202
- })();
1203
- });
1204
- await triggerOnReady();
1205
- } catch (err) {
1206
- if (routerCore.isRedirect(err) || routerCore.isNotFound(err)) {
1207
- if (routerCore.isNotFound(err) && !allPreload) {
1208
- await triggerOnReady();
1209
- }
1210
- throw err;
1211
- }
1212
- }
1213
- return matches;
1214
- };
1215
- this.invalidate = (opts) => {
1216
- const invalidate = (d) => {
1217
- var _a;
1218
- if (((_a = opts == null ? void 0 : opts.filter) == null ? void 0 : _a.call(opts, d)) ?? true) {
1219
- return {
1220
- ...d,
1221
- invalid: true,
1222
- ...d.status === "error" ? { status: "pending", error: void 0 } : {}
1223
- };
1224
- }
1225
- return d;
1226
- };
1227
- this.__store.setState((s) => {
1228
- var _a;
1229
- return {
1230
- ...s,
1231
- matches: s.matches.map(invalidate),
1232
- cachedMatches: s.cachedMatches.map(invalidate),
1233
- pendingMatches: (_a = s.pendingMatches) == null ? void 0 : _a.map(invalidate)
1234
- };
1235
- });
1236
- return this.load({ sync: opts == null ? void 0 : opts.sync });
1237
- };
1238
- this.resolveRedirect = (err) => {
1239
- const redirect = err;
1240
- if (!redirect.href) {
1241
- redirect.href = this.buildLocation(redirect).href;
1242
- }
1243
- return redirect;
1244
- };
1245
- this.clearCache = (opts) => {
1246
- const filter = opts == null ? void 0 : opts.filter;
1247
- if (filter !== void 0) {
1248
- this.__store.setState((s) => {
1249
- return {
1250
- ...s,
1251
- cachedMatches: s.cachedMatches.filter(
1252
- (m) => !filter(m)
1253
- )
1254
- };
1255
- });
1256
- } else {
1257
- this.__store.setState((s) => {
1258
- return {
1259
- ...s,
1260
- cachedMatches: []
1261
- };
1262
- });
1263
- }
1264
- };
1265
- this.clearExpiredCache = () => {
1266
- const filter = (d) => {
1267
- const route = this.looseRoutesById[d.routeId];
1268
- if (!route.options.loader) {
1269
- return true;
1270
- }
1271
- const gcTime = (d.preload ? route.options.preloadGcTime ?? this.options.defaultPreloadGcTime : route.options.gcTime ?? this.options.defaultGcTime) ?? 5 * 60 * 1e3;
1272
- return !(d.status !== "error" && Date.now() - d.updatedAt < gcTime);
1273
- };
1274
- this.clearCache({ filter });
1275
- };
1276
- this.loadRouteChunk = (route) => {
1277
- if (route._lazyPromise === void 0) {
1278
- if (route.lazyFn) {
1279
- route._lazyPromise = route.lazyFn().then((lazyRoute) => {
1280
- const { id: _id, ...options2 } = lazyRoute.options;
1281
- Object.assign(route.options, options2);
1282
- });
1283
- } else {
1284
- route._lazyPromise = Promise.resolve();
1285
- }
1286
- }
1287
- if (route._componentsPromise === void 0) {
1288
- route._componentsPromise = route._lazyPromise.then(
1289
- () => Promise.all(
1290
- componentTypes.map(async (type) => {
1291
- const component = route.options[type];
1292
- if (component == null ? void 0 : component.preload) {
1293
- await component.preload();
1294
- }
1295
- })
1296
- )
1297
- );
1298
- }
1299
- return route._componentsPromise;
1300
- };
1301
- this.preloadRoute = async (opts) => {
1302
- const next = this.buildLocation(opts);
1303
- let matches = this.matchRoutes(next, {
1304
- throwOnError: true,
1305
- preload: true,
1306
- dest: opts
1307
- });
1308
- const activeMatchIds = new Set(
1309
- [...this.state.matches, ...this.state.pendingMatches ?? []].map(
1310
- (d) => d.id
1311
- )
1312
- );
1313
- const loadedMatchIds = /* @__PURE__ */ new Set([
1314
- ...activeMatchIds,
1315
- ...this.state.cachedMatches.map((d) => d.id)
1316
- ]);
1317
- solidStore.batch(() => {
1318
- matches.forEach((match) => {
1319
- if (!loadedMatchIds.has(match.id)) {
1320
- this.__store.setState((s) => ({
1321
- ...s,
1322
- cachedMatches: [...s.cachedMatches, match]
1323
- }));
1324
- }
1325
- });
1326
- });
1327
- try {
1328
- matches = await this.loadMatches({
1329
- matches,
1330
- location: next,
1331
- preload: true,
1332
- updateMatch: (id, updater) => {
1333
- if (activeMatchIds.has(id)) {
1334
- matches = matches.map((d) => d.id === id ? updater(d) : d);
1335
- } else {
1336
- this.updateMatch(id, updater);
1337
- }
1338
- }
1339
- });
1340
- return matches;
1341
- } catch (err) {
1342
- if (routerCore.isRedirect(err)) {
1343
- if (err.reloadDocument) {
1344
- return void 0;
1345
- }
1346
- return await this.preloadRoute({
1347
- ...err,
1348
- _fromLocation: next
1349
- });
1350
- }
1351
- if (!routerCore.isNotFound(err)) {
1352
- console.error(err);
1353
- }
1354
- return void 0;
1355
- }
1356
- };
1357
- this.matchRoute = (location, opts) => {
1358
- const matchLocation = {
1359
- ...location,
1360
- to: location.to ? this.resolvePathWithBase(
1361
- location.from || "",
1362
- location.to
1363
- ) : void 0,
1364
- params: location.params || {},
1365
- leaveParams: true
1366
- };
1367
- const next = this.buildLocation(matchLocation);
1368
- if ((opts == null ? void 0 : opts.pending) && this.state.status !== "pending") {
1369
- return false;
1370
- }
1371
- const pending = (opts == null ? void 0 : opts.pending) === void 0 ? !this.state.isLoading : opts.pending;
1372
- const baseLocation = pending ? this.latestLocation : this.state.resolvedLocation || this.state.location;
1373
- const match = routerCore.matchPathname(this.basepath, baseLocation.pathname, {
1374
- ...opts,
1375
- to: next.pathname
1376
- });
1377
- if (!match) {
1378
- return false;
1379
- }
1380
- if (location.params) {
1381
- if (!routerCore.deepEqual(match, location.params, { partial: true })) {
1382
- return false;
1383
- }
1384
- }
1385
- if (match && ((opts == null ? void 0 : opts.includeSearch) ?? true)) {
1386
- return routerCore.deepEqual(baseLocation.search, next.search, { partial: true }) ? match : false;
1387
- }
1388
- return match;
1389
- };
1390
- this._handleNotFound = (matches, err, {
1391
- updateMatch = this.updateMatch
1392
- } = {}) => {
1393
- const matchesByRouteId = Object.fromEntries(
1394
- matches.map((match2) => [match2.routeId, match2])
1395
- );
1396
- let routeCursor = (err.global ? this.looseRoutesById[routerCore.rootRouteId] : this.looseRoutesById[err.routeId]) || this.looseRoutesById[routerCore.rootRouteId];
1397
- while (!routeCursor.options.notFoundComponent && !this.options.defaultNotFoundComponent && routeCursor.id !== routerCore.rootRouteId) {
1398
- routeCursor = routeCursor.parentRoute;
1399
- invariant(
1400
- routeCursor,
1401
- "Found invalid route tree while trying to find not-found handler."
1402
- );
1403
- }
1404
- const match = matchesByRouteId[routeCursor.id];
1405
- invariant(match, "Could not find match for route: " + routeCursor.id);
1406
- updateMatch(match.id, (prev) => ({
1407
- ...prev,
1408
- status: "notFound",
1409
- error: err,
1410
- isFetching: false
1411
- }));
1412
- if (err.routerCode === "BEFORE_LOAD" && routeCursor.parentRoute) {
1413
- err.routeId = routeCursor.parentRoute.id;
1414
- this._handleNotFound(matches, err, {
1415
- updateMatch
1416
- });
1417
- }
1418
- };
1419
- this.hasNotFoundMatch = () => {
1420
- return this.__store.state.matches.some(
1421
- (d) => d.status === "notFound" || d.globalNotFound
1422
- );
1423
- };
1424
- this.update({
1425
- defaultPreloadDelay: 50,
1426
- defaultPendingMs: 1e3,
1427
- defaultPendingMinMs: 500,
1428
- context: void 0,
1429
- ...options,
1430
- caseSensitive: options.caseSensitive ?? false,
1431
- notFoundMode: options.notFoundMode ?? "fuzzy",
1432
- stringifySearch: options.stringifySearch ?? routerCore.defaultStringifySearch,
1433
- parseSearch: options.parseSearch ?? routerCore.defaultParseSearch
1434
- });
1435
- if (typeof document !== "undefined") {
1436
- window.__TSR_ROUTER__ = this;
1437
- }
9
+ super(options);
1438
10
  }
1439
- get state() {
1440
- return this.__store.state;
1441
- }
1442
- get looseRoutesById() {
1443
- return this.routesById;
1444
- }
1445
- matchRoutesInternal(next, opts) {
1446
- const { foundRoute, matchedRoutes, routeParams } = this.getMatchedRoutes(
1447
- next,
1448
- opts == null ? void 0 : opts.dest
1449
- );
1450
- let isGlobalNotFound = false;
1451
- if (
1452
- // If we found a route, and it's not an index route and we have left over path
1453
- foundRoute ? foundRoute.path !== "/" && routeParams["**"] : (
1454
- // Or if we didn't find a route and we have left over path
1455
- routerCore.trimPathRight(next.pathname)
1456
- )
1457
- ) {
1458
- if (this.options.notFoundRoute) {
1459
- matchedRoutes.push(this.options.notFoundRoute);
1460
- } else {
1461
- isGlobalNotFound = true;
1462
- }
1463
- }
1464
- const globalNotFoundRouteId = (() => {
1465
- if (!isGlobalNotFound) {
1466
- return void 0;
1467
- }
1468
- if (this.options.notFoundMode !== "root") {
1469
- for (let i = matchedRoutes.length - 1; i >= 0; i--) {
1470
- const route = matchedRoutes[i];
1471
- if (route.children) {
1472
- return route.id;
1473
- }
1474
- }
1475
- }
1476
- return routerCore.rootRouteId;
1477
- })();
1478
- const parseErrors = matchedRoutes.map((route) => {
1479
- var _a;
1480
- let parsedParamsError;
1481
- const parseParams = ((_a = route.options.params) == null ? void 0 : _a.parse) ?? route.options.parseParams;
1482
- if (parseParams) {
1483
- try {
1484
- const parsedParams = parseParams(routeParams);
1485
- Object.assign(routeParams, parsedParams);
1486
- } catch (err) {
1487
- parsedParamsError = new PathParamError(err.message, {
1488
- cause: err
1489
- });
1490
- if (opts == null ? void 0 : opts.throwOnError) {
1491
- throw parsedParamsError;
1492
- }
1493
- return parsedParamsError;
1494
- }
1495
- }
1496
- return;
1497
- });
1498
- const matches = [];
1499
- const getParentContext = (parentMatch) => {
1500
- const parentMatchId = parentMatch == null ? void 0 : parentMatch.id;
1501
- const parentContext = !parentMatchId ? this.options.context ?? {} : parentMatch.context ?? this.options.context ?? {};
1502
- return parentContext;
1503
- };
1504
- matchedRoutes.forEach((route, index) => {
1505
- var _a, _b;
1506
- const parentMatch = matches[index - 1];
1507
- const [preMatchSearch, strictMatchSearch, searchError] = (() => {
1508
- const parentSearch = (parentMatch == null ? void 0 : parentMatch.search) ?? next.search;
1509
- const parentStrictSearch = (parentMatch == null ? void 0 : parentMatch._strictSearch) ?? {};
1510
- try {
1511
- const strictSearch = validateSearch(route.options.validateSearch, { ...parentSearch }) ?? {};
1512
- return [
1513
- {
1514
- ...parentSearch,
1515
- ...strictSearch
1516
- },
1517
- { ...parentStrictSearch, ...strictSearch },
1518
- void 0
1519
- ];
1520
- } catch (err) {
1521
- let searchParamError = err;
1522
- if (!(err instanceof SearchParamError)) {
1523
- searchParamError = new SearchParamError(err.message, {
1524
- cause: err
1525
- });
1526
- }
1527
- if (opts == null ? void 0 : opts.throwOnError) {
1528
- throw searchParamError;
1529
- }
1530
- return [parentSearch, {}, searchParamError];
1531
- }
1532
- })();
1533
- const loaderDeps = ((_b = (_a = route.options).loaderDeps) == null ? void 0 : _b.call(_a, {
1534
- search: preMatchSearch
1535
- })) ?? "";
1536
- const loaderDepsHash = loaderDeps ? JSON.stringify(loaderDeps) : "";
1537
- const { usedParams, interpolatedPath } = routerCore.interpolatePath({
1538
- path: route.fullPath,
1539
- params: routeParams,
1540
- decodeCharMap: this.pathParamsDecodeCharMap
1541
- });
1542
- const matchId = routerCore.interpolatePath({
1543
- path: route.id,
1544
- params: routeParams,
1545
- leaveWildcards: true,
1546
- decodeCharMap: this.pathParamsDecodeCharMap
1547
- }).interpolatedPath + loaderDepsHash;
1548
- const existingMatch = this.getMatch(matchId);
1549
- const previousMatch = this.state.matches.find(
1550
- (d) => d.routeId === route.id
1551
- );
1552
- const cause = previousMatch ? "stay" : "enter";
1553
- let match;
1554
- if (existingMatch) {
1555
- match = {
1556
- ...existingMatch,
1557
- cause,
1558
- params: previousMatch ? routerCore.replaceEqualDeep(previousMatch.params, routeParams) : routeParams,
1559
- _strictParams: usedParams,
1560
- search: previousMatch ? routerCore.replaceEqualDeep(previousMatch.search, preMatchSearch) : routerCore.replaceEqualDeep(existingMatch.search, preMatchSearch),
1561
- _strictSearch: strictMatchSearch
1562
- };
1563
- } else {
1564
- const status = route.options.loader || route.options.beforeLoad || route.lazyFn || routeNeedsPreload(route) ? "pending" : "success";
1565
- match = {
1566
- id: matchId,
1567
- index,
1568
- routeId: route.id,
1569
- params: previousMatch ? routerCore.replaceEqualDeep(previousMatch.params, routeParams) : routeParams,
1570
- _strictParams: usedParams,
1571
- pathname: routerCore.joinPaths([this.basepath, interpolatedPath]),
1572
- updatedAt: Date.now(),
1573
- search: previousMatch ? routerCore.replaceEqualDeep(previousMatch.search, preMatchSearch) : preMatchSearch,
1574
- _strictSearch: strictMatchSearch,
1575
- searchError: void 0,
1576
- status,
1577
- isFetching: false,
1578
- error: void 0,
1579
- paramsError: parseErrors[index],
1580
- __routeContext: {},
1581
- __beforeLoadContext: {},
1582
- context: {},
1583
- abortController: new AbortController(),
1584
- fetchCount: 0,
1585
- cause,
1586
- loaderDeps: previousMatch ? routerCore.replaceEqualDeep(previousMatch.loaderDeps, loaderDeps) : loaderDeps,
1587
- invalid: false,
1588
- preload: false,
1589
- links: void 0,
1590
- scripts: void 0,
1591
- headScripts: void 0,
1592
- meta: void 0,
1593
- staticData: route.options.staticData || {},
1594
- loadPromise: routerCore.createControlledPromise(),
1595
- fullPath: route.fullPath
1596
- };
1597
- }
1598
- if (!(opts == null ? void 0 : opts.preload)) {
1599
- match.globalNotFound = globalNotFoundRouteId === route.id;
1600
- }
1601
- match.searchError = searchError;
1602
- const parentContext = getParentContext(parentMatch);
1603
- match.context = {
1604
- ...parentContext,
1605
- ...match.__routeContext,
1606
- ...match.__beforeLoadContext
1607
- };
1608
- matches.push(match);
1609
- });
1610
- matches.forEach((match, index) => {
1611
- var _a, _b, _c, _d, _e, _f, _g, _h;
1612
- const route = this.looseRoutesById[match.routeId];
1613
- const existingMatch = this.getMatch(match.id);
1614
- if (!existingMatch && (opts == null ? void 0 : opts._buildLocation) !== true) {
1615
- const parentMatch = matches[index - 1];
1616
- const parentContext = getParentContext(parentMatch);
1617
- const contextFnContext = {
1618
- deps: match.loaderDeps,
1619
- params: match.params,
1620
- context: parentContext,
1621
- location: next,
1622
- navigate: (opts2) => this.navigate({ ...opts2, _fromLocation: next }),
1623
- buildLocation: this.buildLocation,
1624
- cause: match.cause,
1625
- abortController: match.abortController,
1626
- preload: !!match.preload,
1627
- matches
1628
- };
1629
- match.__routeContext = ((_b = (_a = route.options).context) == null ? void 0 : _b.call(_a, contextFnContext)) ?? {};
1630
- match.context = {
1631
- ...parentContext,
1632
- ...match.__routeContext,
1633
- ...match.__beforeLoadContext
1634
- };
1635
- }
1636
- if (match.status === "success") {
1637
- match.headers = (_d = (_c = route.options).headers) == null ? void 0 : _d.call(_c, {
1638
- loaderData: match.loaderData
1639
- });
1640
- const assetContext = {
1641
- matches,
1642
- match,
1643
- params: match.params,
1644
- loaderData: match.loaderData
1645
- };
1646
- const headFnContent = (_f = (_e = route.options).head) == null ? void 0 : _f.call(_e, assetContext);
1647
- match.links = headFnContent == null ? void 0 : headFnContent.links;
1648
- match.headScripts = headFnContent == null ? void 0 : headFnContent.scripts;
1649
- match.meta = headFnContent == null ? void 0 : headFnContent.meta;
1650
- match.scripts = (_h = (_g = route.options).scripts) == null ? void 0 : _h.call(_g, assetContext);
1651
- }
1652
- });
1653
- return matches;
1654
- }
1655
- }
1656
- function lazyFn(fn, key) {
1657
- return async (...args) => {
1658
- const imported = await fn();
1659
- return imported[key || "default"](...args);
1660
- };
1661
- }
1662
- class SearchParamError extends Error {
1663
- }
1664
- class PathParamError extends Error {
1665
- }
1666
- function getInitialRouterState(location) {
1667
- return {
1668
- loadedAt: 0,
1669
- isLoading: false,
1670
- isTransitioning: false,
1671
- status: "idle",
1672
- resolvedLocation: void 0,
1673
- location,
1674
- matches: [],
1675
- pendingMatches: [],
1676
- cachedMatches: [],
1677
- statusCode: 200
1678
- };
1679
11
  }
1680
- exports.PathParamError = PathParamError;
1681
12
  exports.Router = Router;
1682
- exports.SearchParamError = SearchParamError;
1683
- exports.componentTypes = componentTypes;
1684
13
  exports.createRouter = createRouter;
1685
- exports.getInitialRouterState = getInitialRouterState;
1686
- exports.lazyFn = lazyFn;
1687
14
  //# sourceMappingURL=router.cjs.map