Socket
Socket
Sign inDemoInstall

@tanstack/router

Package Overview
Dependencies
Maintainers
2
Versions
104
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@tanstack/router - npm Package Compare versions

Comparing version 0.0.1-beta.112 to 0.0.1-beta.113

278

build/cjs/router.js

@@ -81,5 +81,2 @@ /**

}
if (typeof document !== 'undefined') {
this.hydrate();
}
}

@@ -124,5 +121,4 @@ reset = () => {

this.basepath = `/${path.trimPath(basepath ?? '') ?? ''}`;
if (routeTree) {
this.routesById = {};
this.routeTree = this.#buildRouteTree(routeTree);
if (routeTree && routeTree !== this.routeTree) {
this.#buildRouteTree(routeTree);
}

@@ -267,100 +263,26 @@ return this;

// If there's no route tree, we can't match anything
if (!this.routeTree) {
if (!this.flatRoutes.length) {
return [];
}
// Existing matches are matches that are already loaded along with
// pending matches that are still loading
const existingMatches = [...this.state.matches];
// We need to "flatten" layout routes, but only process as many
// routes as we need to in order to find the best match
// This mean no looping over all of the routes for the best perf.
// Time to bust out the recursion... As we iterate over the routes,
// we'll keep track of the best match thus far by pushing or popping
// it onto the `matchingRoutes` array. In the case of a layout route,
// we'll assume that it matches and just recurse into its children.
// If we come up with nothing, we'll pop it off and try the next route.
// This way the user can have as many routes, including layout routes,
// as they want without worrying about performance.
// It does make one assumption though: that route branches are ordered from
// most specific to least specific. This is a good assumption to make IMO.
// For now, we also auto-rank routes like Remix and React Router which is a neat trick
// that unfortunately requires looping over all of the routes when we build the route
// tree, but we only do that once. For the matching that will be happening more often,
// I'd rather err on the side of performance here and be able to walk the tree and
// exit early as soon as possible with as little looping/mapping as possible.
let matchingRoutesAndParams = [];
// For any given array of branching routes, find the best route match
// and push it onto the `matchingRoutes` array
const findRoutes = (routes, layoutRoutes = []) => {
let foundRoute;
let foundParams;
// Given a list of routes, find the first route that matches
routes.some(route => {
const children = route.children;
// If there is no path, but there are children,
// this is a layout route, so recurse again
if (!route.path && children?.length) {
const childMatch = findRoutes(children, [...layoutRoutes, route]);
// If we found a child match, mark it as found
// and return true to stop the loop
if (childMatch) {
foundRoute = childMatch;
foundParams = undefined;
return true;
}
return false;
}
// If the route isn't an index route or it has children,
// fuzzy match the path
const fuzzy = route.path !== '/' || !!children?.length;
const matchedParams = path.matchPathname(this.basepath, pathname, {
to: route.fullPath,
fuzzy,
caseSensitive: route.options.caseSensitive ?? this.options.caseSensitive
});
// This was a match!
if (matchedParams) {
// Let's parse the params using the route's `parseParams` function
let parsedParams;
try {
parsedParams = route.options.parseParams?.(matchedParams) ?? matchedParams;
} catch (err) {
if (opts?.strictParseParams) {
throw err;
}
}
foundRoute = route;
foundParams = parsedParams;
return true;
}
return false;
let routeParams = {};
let foundRoute = this.flatRoutes.find(route => {
const matchedParams = path.matchPathname(this.basepath, pathname, {
to: route.fullPath,
caseSensitive: route.options.caseSensitive ?? this.options.caseSensitive
});
// If we didn't find a match in this route branch
// return early.
if (!foundRoute) {
return undefined;
if (matchedParams) {
routeParams = matchedParams;
return true;
}
matchingRoutesAndParams.push(...layoutRoutes.map(d => ({
route: d
})), {
route: foundRoute,
params: foundParams
});
return false;
});
if (!foundRoute) {
return [];
}
let matchedRoutes = [foundRoute];
while (foundRoute?.parentRoute) {
foundRoute = foundRoute.parentRoute;
if (foundRoute) matchedRoutes.unshift(foundRoute);
}
// If the found route has children, recurse again
const foundChildren = foundRoute.children;
if (foundChildren?.length) {
return findRoutes(foundChildren);
}
return foundRoute;
};
findRoutes([this.routeTree]);
// Alright, by now we should have all of our

@@ -371,8 +293,18 @@ // matching routes and their param pairs, let's

let allParams = {};
const matches = matchingRoutesAndParams.map(({
route,
params
}) => {
// Existing matches are matches that are already loaded along with
// pending matches that are still loading
const existingMatches = [...this.state.matches];
const matches = matchedRoutes.map(route => {
let parsedParams;
try {
parsedParams = route.options.parseParams?.(routeParams) ?? routeParams;
} catch (err) {
if (opts?.strictParseParams) {
throw err;
}
}
// Add the parsed params to the accumulated params bag
Object.assign(allParams, params);
Object.assign(allParams, parsedParams);
const interpolatedPath = path.interpolatePath(route.path, allParams);

@@ -387,3 +319,7 @@ const matchId = path.interpolatePath(route.id, allParams, true) + (route.options.getKey?.({

// around between navigation actions that only change leaf routes.
return existingMatches.find(d => d.id === matchId) || new routeMatch.RouteMatch(this, route, {
const existingMatch = existingMatches.find(d => d.id === matchId);
if (existingMatch) {
return existingMatch;
}
return new routeMatch.RouteMatch(this, route, {
id: matchId,

@@ -400,2 +336,3 @@ params: allParams,

});
console.log(matches);
return matches;

@@ -709,3 +646,7 @@ };

#buildRouteTree = routeTree => {
const recurseRoutes = (routes, parentRoute) => {
this.routeTree = routeTree;
this.routesById = {};
this.routesByPath = {};
this.flatRoutes = [];
const recurseRoutes = routes => {
routes.forEach((route, i) => {

@@ -719,59 +660,11 @@ route.init({

this.routesById[route.id] = route;
if (!route.isRoot && route.path) {
const trimmedFullPath = path.trimPathRight(route.fullPath);
if (!this.routesByPath[trimmedFullPath] || route.fullPath.endsWith('/')) {
this.routesByPath[trimmedFullPath] = route;
}
}
const children = route.children;
if (children?.length) {
recurseRoutes(children);
1 / children.length;
route.children = children.map((d, i) => {
const cleaned = path.trimPathLeft(path.cleanPath(d.path ?? '/'));
const parsed = path.parsePathname(cleaned);
while (parsed.length > 1 && parsed[0]?.value === '/') {
parsed.shift();
}
const score = parsed.map(d => {
if (d.type === 'param') {
return 0.5;
}
if (d.type === 'wildcard') {
return 0.25;
}
return 1;
});
return {
child: d,
cleaned,
parsed,
index: i,
score
};
}).sort((a, b) => {
const length = Math.min(a.score.length, b.score.length);
// Sort by min available score
for (let i = 0; i < length; i++) {
if (a.score[i] !== b.score[i]) {
return b.score[i] - a.score[i];
}
}
// Sort by min available parsed value
for (let i = 0; i < length; i++) {
if (a.parsed[i].value !== b.parsed[i].value) {
return a.parsed[i].value > b.parsed[i].value ? 1 : -1;
}
}
// Sort by length of score
if (a.score.length !== b.score.length) {
return b.score.length - a.score.length;
}
// Sort by length of cleaned full path
if (a.cleaned !== b.cleaned) {
return a.cleaned > b.cleaned ? 1 : -1;
}
// Sort by original index
return a.index - b.index;
}).map(d => {
return d.child;
});
}

@@ -781,16 +674,59 @@ });

recurseRoutes([routeTree]);
const recurceCheckRoutes = (routes, parentRoute) => {
routes.forEach(route => {
if (route.isRoot) {
invariant__default["default"](!parentRoute, 'Root routes can only be used as the root of a route tree.');
} else {
invariant__default["default"](parentRoute ? route.parentRoute === parentRoute : true, `Expected a route with path "${route.path}" to be passed to its parent route "${route.parentRoute?.id}" in an addChildren() call, but was instead passed as a child of the "${parentRoute?.id}" route.`);
this.flatRoutes = Object.values(this.routesByPath).map((d, i) => {
const trimmed = path.trimPath(d.fullPath);
const parsed = path.parsePathname(trimmed);
while (parsed.length > 1 && parsed[0]?.value === '/') {
parsed.shift();
}
const score = parsed.map(d => {
if (d.type === 'param') {
return 0.5;
}
if (route.children) {
recurceCheckRoutes(route.children, route);
if (d.type === 'wildcard') {
return 0.25;
}
return 1;
});
};
recurceCheckRoutes([routeTree], undefined);
return routeTree;
return {
child: d,
trimmed,
parsed,
index: i,
score
};
}).sort((a, b) => {
let isIndex = a.trimmed === '/' ? 1 : b.trimmed === '/' ? -1 : 0;
if (isIndex !== 0) return isIndex;
const length = Math.min(a.score.length, b.score.length);
// Sort by length of score
if (a.score.length !== b.score.length) {
return b.score.length - a.score.length;
}
// Sort by min available score
for (let i = 0; i < length; i++) {
if (a.score[i] !== b.score[i]) {
return b.score[i] - a.score[i];
}
}
// Sort by min available parsed value
for (let i = 0; i < length; i++) {
if (a.parsed[i].value !== b.parsed[i].value) {
return a.parsed[i].value > b.parsed[i].value ? 1 : -1;
}
}
// Sort by length of trimmed full path
if (a.trimmed !== b.trimmed) {
return a.trimmed > b.trimmed ? 1 : -1;
}
// Sort by original index
return a.index - b.index;
}).map((d, i) => {
d.child.rank = i;
return d.child;
});
};

@@ -797,0 +733,0 @@ #parseLocation = previousLocation => {

@@ -14,7 +14,7 @@ {

"name": "tiny-invariant@1.3.1/node_modules/tiny-invariant/dist/esm/tiny-invariant.js",
"uid": "4246-49"
"uid": "5eea-49"
},
{
"name": "tiny-warning@1.0.3/node_modules/tiny-warning/dist/tiny-warning.esm.js",
"uid": "4246-51"
"uid": "5eea-51"
}

@@ -30,39 +30,39 @@ ]

{
"uid": "4246-53",
"uid": "5eea-53",
"name": "history.ts"
},
{
"uid": "4246-55",
"uid": "5eea-55",
"name": "utils.ts"
},
{
"uid": "4246-57",
"uid": "5eea-57",
"name": "path.ts"
},
{
"uid": "4246-59",
"uid": "5eea-59",
"name": "qss.ts"
},
{
"uid": "4246-67",
"uid": "5eea-67",
"name": "react.tsx"
},
{
"uid": "4246-69",
"uid": "5eea-69",
"name": "route.ts"
},
{
"uid": "4246-71",
"uid": "5eea-71",
"name": "searchParams.ts"
},
{
"uid": "4246-73",
"uid": "5eea-73",
"name": "router.ts"
},
{
"uid": "4246-75",
"uid": "5eea-75",
"name": "routeMatch.ts"
},
{
"uid": "4246-77",
"uid": "5eea-77",
"name": "index.ts"

@@ -74,7 +74,7 @@ }

"name": "store/build/esm/index.js",
"uid": "4246-63"
"uid": "5eea-63"
},
{
"name": "react-store/build/esm/index.js",
"uid": "4246-65"
"uid": "5eea-65"
}

@@ -84,3 +84,3 @@ ]

{
"uid": "4246-61",
"uid": "5eea-61",
"name": "\u0000rollupPluginBabelHelpers.js"

@@ -94,98 +94,98 @@ }

"nodeParts": {
"4246-49": {
"5eea-49": {
"renderedLength": 199,
"gzipLength": 134,
"brotliLength": 0,
"mainUid": "4246-48"
"mainUid": "5eea-48"
},
"4246-51": {
"5eea-51": {
"renderedLength": 48,
"gzipLength": 65,
"brotliLength": 0,
"mainUid": "4246-50"
"mainUid": "5eea-50"
},
"4246-53": {
"5eea-53": {
"renderedLength": 5643,
"gzipLength": 1404,
"brotliLength": 0,
"mainUid": "4246-52"
"mainUid": "5eea-52"
},
"4246-55": {
"5eea-55": {
"renderedLength": 2821,
"gzipLength": 990,
"brotliLength": 0,
"mainUid": "4246-54"
"mainUid": "5eea-54"
},
"4246-57": {
"5eea-57": {
"renderedLength": 6028,
"gzipLength": 1423,
"brotliLength": 0,
"mainUid": "4246-56"
"mainUid": "5eea-56"
},
"4246-59": {
"5eea-59": {
"renderedLength": 1395,
"gzipLength": 558,
"brotliLength": 0,
"mainUid": "4246-58"
"mainUid": "5eea-58"
},
"4246-61": {
"5eea-61": {
"renderedLength": 457,
"gzipLength": 241,
"brotliLength": 0,
"mainUid": "4246-60"
"mainUid": "5eea-60"
},
"4246-63": {
"5eea-63": {
"renderedLength": 1459,
"gzipLength": 543,
"brotliLength": 0,
"mainUid": "4246-62"
"mainUid": "5eea-62"
},
"4246-65": {
"5eea-65": {
"renderedLength": 1066,
"gzipLength": 481,
"brotliLength": 0,
"mainUid": "4246-64"
"mainUid": "5eea-64"
},
"4246-67": {
"5eea-67": {
"renderedLength": 14227,
"gzipLength": 3360,
"brotliLength": 0,
"mainUid": "4246-66"
"mainUid": "5eea-66"
},
"4246-69": {
"5eea-69": {
"renderedLength": 3556,
"gzipLength": 903,
"brotliLength": 0,
"mainUid": "4246-68"
"mainUid": "5eea-68"
},
"4246-71": {
"5eea-71": {
"renderedLength": 1387,
"gzipLength": 483,
"brotliLength": 0,
"mainUid": "4246-70"
"mainUid": "5eea-70"
},
"4246-73": {
"renderedLength": 31245,
"gzipLength": 7730,
"5eea-73": {
"renderedLength": 27746,
"gzipLength": 6708,
"brotliLength": 0,
"mainUid": "4246-72"
"mainUid": "5eea-72"
},
"4246-75": {
"5eea-75": {
"renderedLength": 8914,
"gzipLength": 1932,
"brotliLength": 0,
"mainUid": "4246-74"
"mainUid": "5eea-74"
},
"4246-77": {
"5eea-77": {
"renderedLength": 0,
"gzipLength": 0,
"brotliLength": 0,
"mainUid": "4246-76"
"mainUid": "5eea-76"
}
},
"nodeMetas": {
"4246-48": {
"5eea-48": {
"id": "/node_modules/.pnpm/tiny-invariant@1.3.1/node_modules/tiny-invariant/dist/esm/tiny-invariant.js",
"moduleParts": {
"index.production.js": "4246-49"
"index.production.js": "5eea-49"
},

@@ -195,19 +195,19 @@ "imported": [],

{
"uid": "4246-76"
"uid": "5eea-76"
},
{
"uid": "4246-68"
"uid": "5eea-68"
},
{
"uid": "4246-72"
"uid": "5eea-72"
},
{
"uid": "4246-66"
"uid": "5eea-66"
}
]
},
"4246-50": {
"5eea-50": {
"id": "/node_modules/.pnpm/tiny-warning@1.0.3/node_modules/tiny-warning/dist/tiny-warning.esm.js",
"moduleParts": {
"index.production.js": "4246-51"
"index.production.js": "5eea-51"
},

@@ -217,13 +217,13 @@ "imported": [],

{
"uid": "4246-76"
"uid": "5eea-76"
},
{
"uid": "4246-66"
"uid": "5eea-66"
}
]
},
"4246-52": {
"5eea-52": {
"id": "/packages/router/src/history.ts",
"moduleParts": {
"index.production.js": "4246-53"
"index.production.js": "5eea-53"
},

@@ -233,13 +233,13 @@ "imported": [],

{
"uid": "4246-76"
"uid": "5eea-76"
},
{
"uid": "4246-72"
"uid": "5eea-72"
}
]
},
"4246-54": {
"5eea-54": {
"id": "/packages/router/src/utils.ts",
"moduleParts": {
"index.production.js": "4246-55"
"index.production.js": "5eea-55"
},

@@ -249,26 +249,26 @@ "imported": [],

{
"uid": "4246-76"
"uid": "5eea-76"
},
{
"uid": "4246-56"
"uid": "5eea-56"
},
{
"uid": "4246-74"
"uid": "5eea-74"
},
{
"uid": "4246-72"
"uid": "5eea-72"
},
{
"uid": "4246-66"
"uid": "5eea-66"
}
]
},
"4246-56": {
"5eea-56": {
"id": "/packages/router/src/path.ts",
"moduleParts": {
"index.production.js": "4246-57"
"index.production.js": "5eea-57"
},
"imported": [
{
"uid": "4246-54"
"uid": "5eea-54"
}

@@ -278,16 +278,16 @@ ],

{
"uid": "4246-76"
"uid": "5eea-76"
},
{
"uid": "4246-68"
"uid": "5eea-68"
},
{
"uid": "4246-72"
"uid": "5eea-72"
}
]
},
"4246-58": {
"5eea-58": {
"id": "/packages/router/src/qss.ts",
"moduleParts": {
"index.production.js": "4246-59"
"index.production.js": "5eea-59"
},

@@ -297,13 +297,13 @@ "imported": [],

{
"uid": "4246-76"
"uid": "5eea-76"
},
{
"uid": "4246-70"
"uid": "5eea-70"
}
]
},
"4246-60": {
"5eea-60": {
"id": "\u0000rollupPluginBabelHelpers.js",
"moduleParts": {
"index.production.js": "4246-61"
"index.production.js": "5eea-61"
},

@@ -313,10 +313,10 @@ "imported": [],

{
"uid": "4246-66"
"uid": "5eea-66"
}
]
},
"4246-62": {
"5eea-62": {
"id": "/packages/store/build/esm/index.js",
"moduleParts": {
"index.production.js": "4246-63"
"index.production.js": "5eea-63"
},

@@ -326,17 +326,17 @@ "imported": [],

{
"uid": "4246-64"
"uid": "5eea-64"
}
]
},
"4246-64": {
"5eea-64": {
"id": "/packages/react-store/build/esm/index.js",
"moduleParts": {
"index.production.js": "4246-65"
"index.production.js": "5eea-65"
},
"imported": [
{
"uid": "4246-81"
"uid": "5eea-81"
},
{
"uid": "4246-62"
"uid": "5eea-62"
}

@@ -346,35 +346,35 @@ ],

{
"uid": "4246-74"
"uid": "5eea-74"
},
{
"uid": "4246-72"
"uid": "5eea-72"
},
{
"uid": "4246-66"
"uid": "5eea-66"
}
]
},
"4246-66": {
"5eea-66": {
"id": "/packages/router/src/react.tsx",
"moduleParts": {
"index.production.js": "4246-67"
"index.production.js": "5eea-67"
},
"imported": [
{
"uid": "4246-60"
"uid": "5eea-60"
},
{
"uid": "4246-80"
"uid": "5eea-80"
},
{
"uid": "4246-64"
"uid": "5eea-64"
},
{
"uid": "4246-48"
"uid": "5eea-48"
},
{
"uid": "4246-50"
"uid": "5eea-50"
},
{
"uid": "4246-54"
"uid": "5eea-54"
}

@@ -384,23 +384,23 @@ ],

{
"uid": "4246-76"
"uid": "5eea-76"
},
{
"uid": "4246-68"
"uid": "5eea-68"
}
]
},
"4246-68": {
"5eea-68": {
"id": "/packages/router/src/route.ts",
"moduleParts": {
"index.production.js": "4246-69"
"index.production.js": "5eea-69"
},
"imported": [
{
"uid": "4246-48"
"uid": "5eea-48"
},
{
"uid": "4246-56"
"uid": "5eea-56"
},
{
"uid": "4246-66"
"uid": "5eea-66"
}

@@ -410,14 +410,14 @@ ],

{
"uid": "4246-76"
"uid": "5eea-76"
}
]
},
"4246-70": {
"5eea-70": {
"id": "/packages/router/src/searchParams.ts",
"moduleParts": {
"index.production.js": "4246-71"
"index.production.js": "5eea-71"
},
"imported": [
{
"uid": "4246-58"
"uid": "5eea-58"
}

@@ -427,35 +427,35 @@ ],

{
"uid": "4246-76"
"uid": "5eea-76"
},
{
"uid": "4246-72"
"uid": "5eea-72"
}
]
},
"4246-72": {
"5eea-72": {
"id": "/packages/router/src/router.ts",
"moduleParts": {
"index.production.js": "4246-73"
"index.production.js": "5eea-73"
},
"imported": [
{
"uid": "4246-64"
"uid": "5eea-64"
},
{
"uid": "4246-48"
"uid": "5eea-48"
},
{
"uid": "4246-56"
"uid": "5eea-56"
},
{
"uid": "4246-74"
"uid": "5eea-74"
},
{
"uid": "4246-70"
"uid": "5eea-70"
},
{
"uid": "4246-54"
"uid": "5eea-54"
},
{
"uid": "4246-52"
"uid": "5eea-52"
}

@@ -465,23 +465,23 @@ ],

{
"uid": "4246-76"
"uid": "5eea-76"
},
{
"uid": "4246-74"
"uid": "5eea-74"
}
]
},
"4246-74": {
"5eea-74": {
"id": "/packages/router/src/routeMatch.ts",
"moduleParts": {
"index.production.js": "4246-75"
"index.production.js": "5eea-75"
},
"imported": [
{
"uid": "4246-64"
"uid": "5eea-64"
},
{
"uid": "4246-72"
"uid": "5eea-72"
},
{
"uid": "4246-54"
"uid": "5eea-54"
}

@@ -491,53 +491,53 @@ ],

{
"uid": "4246-76"
"uid": "5eea-76"
},
{
"uid": "4246-72"
"uid": "5eea-72"
}
]
},
"4246-76": {
"5eea-76": {
"id": "/packages/router/src/index.ts",
"moduleParts": {
"index.production.js": "4246-77"
"index.production.js": "5eea-77"
},
"imported": [
{
"uid": "4246-48"
"uid": "5eea-48"
},
{
"uid": "4246-50"
"uid": "5eea-50"
},
{
"uid": "4246-52"
"uid": "5eea-52"
},
{
"uid": "4246-78"
"uid": "5eea-78"
},
{
"uid": "4246-56"
"uid": "5eea-56"
},
{
"uid": "4246-58"
"uid": "5eea-58"
},
{
"uid": "4246-68"
"uid": "5eea-68"
},
{
"uid": "4246-79"
"uid": "5eea-79"
},
{
"uid": "4246-74"
"uid": "5eea-74"
},
{
"uid": "4246-72"
"uid": "5eea-72"
},
{
"uid": "4246-70"
"uid": "5eea-70"
},
{
"uid": "4246-54"
"uid": "5eea-54"
},
{
"uid": "4246-66"
"uid": "5eea-66"
}

@@ -548,3 +548,3 @@ ],

},
"4246-78": {
"5eea-78": {
"id": "/packages/router/src/link.ts",

@@ -555,7 +555,7 @@ "moduleParts": {},

{
"uid": "4246-76"
"uid": "5eea-76"
}
]
},
"4246-79": {
"5eea-79": {
"id": "/packages/router/src/routeInfo.ts",

@@ -566,7 +566,7 @@ "moduleParts": {},

{
"uid": "4246-76"
"uid": "5eea-76"
}
]
},
"4246-80": {
"5eea-80": {
"id": "react",

@@ -577,3 +577,3 @@ "moduleParts": {},

{
"uid": "4246-66"
"uid": "5eea-66"
}

@@ -583,3 +583,3 @@ ],

},
"4246-81": {
"5eea-81": {
"id": "use-sync-external-store/shim/with-selector",

@@ -590,3 +590,3 @@ "moduleParts": {},

{
"uid": "4246-64"
"uid": "5eea-64"
}

@@ -593,0 +593,0 @@ ],

@@ -78,3 +78,3 @@ import * as React from 'react';

from?: TDefaultFrom;
}): <TFrom extends string = TDefaultFrom, TTo extends string = "">(opts?: MakeLinkOptions<TFrom, TTo> | undefined) => Promise<void>;
}): <TFrom extends string = TDefaultFrom, TTo extends string = "">(opts?: NavigateOptions<AnyRoutesInfo, TFrom, TTo> | undefined) => Promise<void>;
export declare function useMatchRoute(): <TFrom extends string = "/", TTo extends string = "">(opts: MakeUseMatchRouteOptions<TFrom, TTo>) => any;

@@ -81,0 +81,0 @@ export declare function MatchRoute<TFrom extends string = '/', TTo extends string = ''>(props: MakeMatchRouteOptions<TFrom, TTo>): any;

@@ -185,2 +185,3 @@ import { ParsePathParams } from './link';

router?: Router<TRoutesInfo['routeTree'], TRoutesInfo>;
rank: number;
constructor(options: RouteOptions<TParentRoute, TCustomId, TPath, TLoader, InferFullSearchSchema<TParentRoute>, TSearchSchema, TFullSearchSchema, TParentRoute['__types']['allParams'], TParams, TAllParams, TParentContext, TAllParentContext, TRouteContext, TContext>);

@@ -187,0 +188,0 @@ init: (opts: {

@@ -77,2 +77,5 @@ import { AnyRoute, Route } from './route';

export type RouteById<TRoutesInfo extends AnyRoutesInfo, TId> = TId extends keyof TRoutesInfo['routesById'] ? IsAny<TRoutesInfo['routesById'][TId]['id'], Route, TRoutesInfo['routesById'][TId]> : never;
export type RoutesByPath<TRoutesInfo extends AnyRoutesInfo> = {
[K in keyof TRoutesInfo['routesByFullPath']]: TRoutesInfo['routesByFullPath'][K];
};
export type RouteByPath<TRoutesInfo extends AnyRoutesInfo, TPath> = TPath extends keyof TRoutesInfo['routesByFullPath'] ? IsAny<TRoutesInfo['routesByFullPath'][TPath]['id'], Route, TRoutesInfo['routesByFullPath'][TPath]> : never;

@@ -5,3 +5,3 @@ /// <reference types="react" />

import { AnySearchSchema, AnyRoute, RootRoute, AnyContext } from './route';
import { RoutesInfo, AnyRoutesInfo, RoutesById } from './routeInfo';
import { RoutesInfo, AnyRoutesInfo, RoutesById, RoutesByPath } from './routeInfo';
import { RouteMatch } from './routeMatch';

@@ -145,2 +145,4 @@ import { NoInfer, PickAsRequired, Timeout, Updater } from './utils';

routesById: RoutesById<TRoutesInfo>;
routesByPath: RoutesByPath<TRoutesInfo>;
flatRoutes: TRoutesInfo['routesByFullPath'][keyof TRoutesInfo['routesByFullPath']][];
navigateTimeout: undefined | Timeout;

@@ -147,0 +149,0 @@ nextAction: undefined | 'push' | 'replace';

@@ -11,3 +11,3 @@ /**

*/
!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?e(exports,require("react"),require("use-sync-external-store/shim/with-selector")):"function"==typeof define&&define.amd?define(["exports","react","use-sync-external-store/shim/with-selector"],e):e((t="undefined"!=typeof globalThis?globalThis:t||self).RouterCore={},t.React,t.withSelector)}(this,(function(t,e,r){"use strict";function o(t){if(t&&t.__esModule)return t;var e=Object.create(null);return t&&Object.keys(t).forEach((function(r){if("default"!==r){var o=Object.getOwnPropertyDescriptor(t,r);Object.defineProperty(e,r,o.get?o:{enumerable:!0,get:function(){return t[r]}})}})),e.default=t,Object.freeze(e)}var a=o(e);function s(t,e){if(!t)throw new Error("Invariant failed")}function n(t,e){}const i="popstate",c="beforeunload",h=t=>(t.preventDefault(),t.returnValue=""),u=()=>{removeEventListener(c,h,{capture:!0})};function l(t){let e=t.getLocation(),r=()=>{},o=new Set,a=[],s=[];const n=()=>{if(a.length)a[0]?.(n,(()=>{a=[],u()}));else{for(;s.length;)s.shift()?.();l()}},i=t=>{s.push(t),n()},l=()=>{e=t.getLocation(),o.forEach((t=>t()))};return{get location(){return e},listen:e=>(0===o.size&&(r=t.listener(l)),o.add(e),()=>{o.delete(e),0===o.size&&r()}),push:(e,r)=>{i((()=>{t.pushState(e,r)}))},replace:(e,r)=>{i((()=>{t.replaceState(e,r)}))},go:e=>{i((()=>{t.go(e)}))},back:()=>{i((()=>{t.back()}))},forward:()=>{i((()=>{t.forward()}))},createHref:e=>t.createHref(e),block:t=>(a.push(t),1===a.length&&addEventListener(c,h,{capture:!0}),()=>{a=a.filter((e=>e!==t)),a.length||u()})}}function d(t){const e=t?.getHref??(()=>`${window.location.pathname}${window.location.search}${window.location.hash}`),r=t?.createHref??(t=>t);return l({getLocation:()=>f(e(),history.state),listener:t=>(window.addEventListener(i,t),()=>{window.removeEventListener(i,t)}),pushState:(t,e)=>{window.history.pushState({...e,key:m()},"",r(t))},replaceState:(t,e)=>{window.history.replaceState({...e,key:m()},"",r(t))},back:()=>window.history.back(),forward:()=>window.history.forward(),go:t=>window.history.go(t),createHref:t=>r(t)})}function p(t={initialEntries:["/"]}){const e=t.initialEntries;let r=t.initialIndex??e.length-1,o={};return l({getLocation:()=>f(e[r],o),listener:()=>()=>{},pushState:(t,a)=>{o={...a,key:m()},e.push(t),r++},replaceState:(t,a)=>{o={...a,key:m()},e[r]=t},back:()=>{r--},forward:()=>{r=Math.min(r+1,e.length-1)},go:t=>window.history.go(t),createHref:t=>t})}function f(t,e){let r=t.indexOf("#"),o=t.indexOf("?");return{href:t,pathname:t.substring(0,r>0?o>0?Math.min(r,o):r:o>0?o:t.length),hash:r>-1?t.substring(r):"",search:o>-1?t.slice(o,-1===r?void 0:r):"",state:e}}function m(){return(Math.random()+1).toString(36).substring(7)}function y(t){return t[t.length-1]}function g(t,e){return"function"==typeof t?t(e):t}function v(t,e){return e.reduce(((e,r)=>(e[r]=t[r],e)),{})}function _(t,e){if(t===e)return t;const r=e,o=Array.isArray(t)&&Array.isArray(r);if(o||w(t)&&w(r)){const e=o?t.length:Object.keys(t).length,a=o?r:Object.keys(r),s=a.length,n=o?[]:{};let i=0;for(let e=0;e<s;e++){const s=o?e:a[e];n[s]=_(t[s],r[s]),n[s]===t[s]&&i++}return e===s&&i===e?t:n}return r}function w(t){if(!S(t))return!1;const e=t.constructor;if(void 0===e)return!0;const r=e.prototype;return!!S(r)&&!!r.hasOwnProperty("isPrototypeOf")}function S(t){return"[object Object]"===Object.prototype.toString.call(t)}function b(t,e){return t===e||typeof t==typeof e&&(w(t)&&w(e)?!Object.keys(e).some((r=>!b(t[r],e[r]))):!(!Array.isArray(t)||!Array.isArray(e))&&(t.length===e.length&&t.every(((t,r)=>b(t,e[r])))))}function E(t){return P(t.filter(Boolean).join("/"))}function P(t){return t.replace(/\/{2,}/g,"/")}function x(t){return"/"===t?t:t.replace(/^\/{1,}/,"")}function R(t){return"/"===t?t:t.replace(/\/{1,}$/,"")}function C(t){return R(x(t))}function L(t,e,r){e=e.replace(new RegExp(`^${t}`),"/"),r=r.replace(new RegExp(`^${t}`),"/");let o=k(e);const a=k(r);a.forEach(((t,e)=>{if("/"===t.value)e?e===a.length-1&&o.push(t):o=[t];else if(".."===t.value)o.length>1&&"/"===y(o)?.value&&o.pop(),o.pop();else{if("."===t.value)return;o.push(t)}}));return P(E([t,...o.map((t=>t.value))]))}function k(t){if(!t)return[];const e=[];if("/"===(t=P(t)).slice(0,1)&&(t=t.substring(1),e.push({type:"pathname",value:"/"})),!t)return e;const r=t.split("/").filter(Boolean);return e.push(...r.map((t=>"$"===t||"*"===t?{type:"wildcard",value:t}:"$"===t.charAt(0)?{type:"param",value:t}:{type:"pathname",value:t}))),"/"===t.slice(-1)&&(t=t.substring(1),e.push({type:"pathname",value:"/"})),e}function j(t,e,r=!1){return E(k(t).map((t=>{if("wildcard"===t.type){const o=e[t.value];return r?`${t.value}${o??""}`:o}return"param"===t.type?e[t.value.substring(1)]??"":t.value})))}function O(t,e,r){const o=D(t,e,r);if(!r.to||o)return o??{}}function D(t,e,r){e="/"!=t?e.substring(t.length):e;const o=`${r.to??"$"}`,a=k(e),s=k(o);e.startsWith("/")||a.unshift({type:"pathname",value:"/"}),o.startsWith("/")||s.unshift({type:"pathname",value:"/"});const n={};return(()=>{for(let t=0;t<Math.max(a.length,s.length);t++){const e=a[t],o=s[t],i=t>=a.length-1,c=t>=s.length-1;if(o){if("wildcard"===o.type)return!!e?.value&&(n["*"]=E(a.slice(t).map((t=>t.value))),!0);if("pathname"===o.type){if("/"===o.value&&!e?.value)return!0;if(e)if(r.caseSensitive){if(o.value!==e.value)return!1}else if(o.value.toLowerCase()!==e.value.toLowerCase())return!1}if(!e)return!1;if("param"===o.type){if("/"===e?.value)return!1;"$"!==e.value.charAt(0)&&(n[o.value.substring(1)]=e.value)}}if(!i&&c)return!!r.fuzzy}return!0})()?n:void 0}function M(t,e){var r,o,a,s="";for(r in t)if(void 0!==(a=t[r]))if(Array.isArray(a))for(o=0;o<a.length;o++)s&&(s+="&"),s+=encodeURIComponent(r)+"="+encodeURIComponent(a[o]);else s&&(s+="&"),s+=encodeURIComponent(r)+"="+encodeURIComponent(a);return(e||"")+s}function A(t){if(!t)return"";var e=decodeURIComponent(t);return"false"!==e&&("true"===e||("0"===e.charAt(0)?e:0*+e==0?+e:e))}function T(t){for(var e,r,o={},a=t.split("&");e=a.shift();)void 0!==o[r=(e=e.split("=")).shift()]?o[r]=[].concat(o[r],A(e.shift())):o[r]=A(e.shift());return o}function $(){return $=Object.assign?Object.assign.bind():function(t){for(var e=1;e<arguments.length;e++){var r=arguments[e];for(var o in r)Object.prototype.hasOwnProperty.call(r,o)&&(t[o]=r[o])}return t},$.apply(this,arguments)}
!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?e(exports,require("react"),require("use-sync-external-store/shim/with-selector")):"function"==typeof define&&define.amd?define(["exports","react","use-sync-external-store/shim/with-selector"],e):e((t="undefined"!=typeof globalThis?globalThis:t||self).RouterCore={},t.React,t.withSelector)}(this,(function(t,e,r){"use strict";function o(t){if(t&&t.__esModule)return t;var e=Object.create(null);return t&&Object.keys(t).forEach((function(r){if("default"!==r){var o=Object.getOwnPropertyDescriptor(t,r);Object.defineProperty(e,r,o.get?o:{enumerable:!0,get:function(){return t[r]}})}})),e.default=t,Object.freeze(e)}var a=o(e);function s(t,e){if(!t)throw new Error("Invariant failed")}function n(t,e){}const i="popstate",c="beforeunload",h=t=>(t.preventDefault(),t.returnValue=""),u=()=>{removeEventListener(c,h,{capture:!0})};function l(t){let e=t.getLocation(),r=()=>{},o=new Set,a=[],s=[];const n=()=>{if(a.length)a[0]?.(n,(()=>{a=[],u()}));else{for(;s.length;)s.shift()?.();l()}},i=t=>{s.push(t),n()},l=()=>{e=t.getLocation(),o.forEach((t=>t()))};return{get location(){return e},listen:e=>(0===o.size&&(r=t.listener(l)),o.add(e),()=>{o.delete(e),0===o.size&&r()}),push:(e,r)=>{i((()=>{t.pushState(e,r)}))},replace:(e,r)=>{i((()=>{t.replaceState(e,r)}))},go:e=>{i((()=>{t.go(e)}))},back:()=>{i((()=>{t.back()}))},forward:()=>{i((()=>{t.forward()}))},createHref:e=>t.createHref(e),block:t=>(a.push(t),1===a.length&&addEventListener(c,h,{capture:!0}),()=>{a=a.filter((e=>e!==t)),a.length||u()})}}function d(t){const e=t?.getHref??(()=>`${window.location.pathname}${window.location.search}${window.location.hash}`),r=t?.createHref??(t=>t);return l({getLocation:()=>f(e(),history.state),listener:t=>(window.addEventListener(i,t),()=>{window.removeEventListener(i,t)}),pushState:(t,e)=>{window.history.pushState({...e,key:m()},"",r(t))},replaceState:(t,e)=>{window.history.replaceState({...e,key:m()},"",r(t))},back:()=>window.history.back(),forward:()=>window.history.forward(),go:t=>window.history.go(t),createHref:t=>r(t)})}function p(t={initialEntries:["/"]}){const e=t.initialEntries;let r=t.initialIndex??e.length-1,o={};return l({getLocation:()=>f(e[r],o),listener:()=>()=>{},pushState:(t,a)=>{o={...a,key:m()},e.push(t),r++},replaceState:(t,a)=>{o={...a,key:m()},e[r]=t},back:()=>{r--},forward:()=>{r=Math.min(r+1,e.length-1)},go:t=>window.history.go(t),createHref:t=>t})}function f(t,e){let r=t.indexOf("#"),o=t.indexOf("?");return{href:t,pathname:t.substring(0,r>0?o>0?Math.min(r,o):r:o>0?o:t.length),hash:r>-1?t.substring(r):"",search:o>-1?t.slice(o,-1===r?void 0:r):"",state:e}}function m(){return(Math.random()+1).toString(36).substring(7)}function y(t){return t[t.length-1]}function g(t,e){return"function"==typeof t?t(e):t}function v(t,e){return e.reduce(((e,r)=>(e[r]=t[r],e)),{})}function _(t,e){if(t===e)return t;const r=e,o=Array.isArray(t)&&Array.isArray(r);if(o||w(t)&&w(r)){const e=o?t.length:Object.keys(t).length,a=o?r:Object.keys(r),s=a.length,n=o?[]:{};let i=0;for(let e=0;e<s;e++){const s=o?e:a[e];n[s]=_(t[s],r[s]),n[s]===t[s]&&i++}return e===s&&i===e?t:n}return r}function w(t){if(!b(t))return!1;const e=t.constructor;if(void 0===e)return!0;const r=e.prototype;return!!b(r)&&!!r.hasOwnProperty("isPrototypeOf")}function b(t){return"[object Object]"===Object.prototype.toString.call(t)}function S(t,e){return t===e||typeof t==typeof e&&(w(t)&&w(e)?!Object.keys(e).some((r=>!S(t[r],e[r]))):!(!Array.isArray(t)||!Array.isArray(e))&&(t.length===e.length&&t.every(((t,r)=>S(t,e[r])))))}function P(t){return E(t.filter(Boolean).join("/"))}function E(t){return t.replace(/\/{2,}/g,"/")}function x(t){return"/"===t?t:t.replace(/^\/{1,}/,"")}function R(t){return"/"===t?t:t.replace(/\/{1,}$/,"")}function C(t){return R(x(t))}function L(t,e,r){e=e.replace(new RegExp(`^${t}`),"/"),r=r.replace(new RegExp(`^${t}`),"/");let o=k(e);const a=k(r);a.forEach(((t,e)=>{if("/"===t.value)e?e===a.length-1&&o.push(t):o=[t];else if(".."===t.value)o.length>1&&"/"===y(o)?.value&&o.pop(),o.pop();else{if("."===t.value)return;o.push(t)}}));return E(P([t,...o.map((t=>t.value))]))}function k(t){if(!t)return[];const e=[];if("/"===(t=E(t)).slice(0,1)&&(t=t.substring(1),e.push({type:"pathname",value:"/"})),!t)return e;const r=t.split("/").filter(Boolean);return e.push(...r.map((t=>"$"===t||"*"===t?{type:"wildcard",value:t}:"$"===t.charAt(0)?{type:"param",value:t}:{type:"pathname",value:t}))),"/"===t.slice(-1)&&(t=t.substring(1),e.push({type:"pathname",value:"/"})),e}function j(t,e,r=!1){return P(k(t).map((t=>{if("wildcard"===t.type){const o=e[t.value];return r?`${t.value}${o??""}`:o}return"param"===t.type?e[t.value.substring(1)]??"":t.value})))}function O(t,e,r){const o=D(t,e,r);if(!r.to||o)return o??{}}function D(t,e,r){e="/"!=t?e.substring(t.length):e;const o=`${r.to??"$"}`,a=k(e),s=k(o);e.startsWith("/")||a.unshift({type:"pathname",value:"/"}),o.startsWith("/")||s.unshift({type:"pathname",value:"/"});const n={};return(()=>{for(let t=0;t<Math.max(a.length,s.length);t++){const e=a[t],o=s[t],i=t>=a.length-1,c=t>=s.length-1;if(o){if("wildcard"===o.type)return!!e?.value&&(n["*"]=P(a.slice(t).map((t=>t.value))),!0);if("pathname"===o.type){if("/"===o.value&&!e?.value)return!0;if(e)if(r.caseSensitive){if(o.value!==e.value)return!1}else if(o.value.toLowerCase()!==e.value.toLowerCase())return!1}if(!e)return!1;if("param"===o.type){if("/"===e?.value)return!1;"$"!==e.value.charAt(0)&&(n[o.value.substring(1)]=e.value)}}if(!i&&c)return!!r.fuzzy}return!0})()?n:void 0}function M(t,e){var r,o,a,s="";for(r in t)if(void 0!==(a=t[r]))if(Array.isArray(a))for(o=0;o<a.length;o++)s&&(s+="&"),s+=encodeURIComponent(r)+"="+encodeURIComponent(a[o]);else s&&(s+="&"),s+=encodeURIComponent(r)+"="+encodeURIComponent(a);return(e||"")+s}function A(t){if(!t)return"";var e=decodeURIComponent(t);return"false"!==e&&("true"===e||("0"===e.charAt(0)?e:0*+e==0?+e:e))}function $(t){for(var e,r,o={},a=t.split("&");e=a.shift();)void 0!==o[r=(e=e.split("=")).shift()]?o[r]=[].concat(o[r],A(e.shift())):o[r]=A(e.shift());return o}function T(){return T=Object.assign?Object.assign.bind():function(t){for(var e=1;e<arguments.length;e++){var r=arguments[e];for(var o in r)Object.prototype.hasOwnProperty.call(r,o)&&(t[o]=r[o])}return t},T.apply(this,arguments)}
/**

@@ -32,3 +32,3 @@ * @tanstack/store/src/index.ts

* @license MIT
*/function H(t,e=(t=>t)){return r.useSyncExternalStoreWithSelector(t.subscribe,(()=>t.state),(()=>t.state),e,N)}function N(t,e){if(Object.is(t,e))return!0;if("object"!=typeof t||null===t||"object"!=typeof e||null===e)return!1;const r=Object.keys(t);if(r.length!==Object.keys(e).length)return!1;for(let o=0;o<r.length;o++)if(!Object.prototype.hasOwnProperty.call(e,r[o])||!Object.is(t[r[o]],e[r[o]]))return!1;return!0}function B(t){const e=J(),{type:r,children:o,target:s,activeProps:n=(()=>({className:"active"})),inactiveProps:i=(()=>({})),activeOptions:c,disabled:h,hash:u,search:l,params:d,to:p=".",preload:f,preloadDelay:m,replace:y,style:v,className:_,onClick:w,onFocus:S,onMouseEnter:b,onMouseLeave:E,onTouchStart:P,...x}=t,R=e.buildLink(t);if("external"===R.type){const{href:t}=R;return{href:t}}const{handleClick:C,handleFocus:L,handleEnter:k,handleLeave:j,handleTouchStart:O,isActive:D,next:M}=R,A=t=>e=>{e.persist&&e.persist(),t.filter(Boolean).forEach((t=>{e.defaultPrevented||t(e)}))},T=D?g(n,{})??{}:{},$=D?{}:g(i,{})??{};return{...T,...$,...x,href:h?void 0:M.href,onClick:A([w,t=>{a.startTransition?a.startTransition((()=>{C(t)})):C(t)}]),onFocus:A([S,L]),onMouseEnter:A([b,k]),onMouseLeave:A([E,j]),onTouchStart:A([P,O]),target:s,style:{...v,...T.style,...$.style},className:[_,T.className,$.className].filter(Boolean).join(" ")||void 0,...h?{role:"link","aria-disabled":!0}:void 0,"data-status":D?"active":void 0}}const F=a.forwardRef(((t,e)=>{const r=B(t);return a.createElement("a",$({ref:e},r,{children:"function"==typeof t.children?t.children({isActive:"active"===r["data-status"]}):t.children}))}));const U=a.createContext(null),z=a.createContext(null),W=a.useDeferredValue||(t=>t);function J(){const t=a.useContext(z);return H(t.router.__store),t.router}function K(t){const e=J();return H(e.__store,t),e}function q(){return a.useContext(U)}function V(t){const e=J(),r=q()[0],o=W(e.state.matches),a=t?.from?o.find((e=>e.route.id===t?.from)):r;return s(a,t?.from&&t.from),(t?.strict??1)&&s(r.route.id==a?.route.id,(a?.route.id,r.route.id,a?.route.id,a?.route.id)),H(a.__store,(e=>t?.track?.(a)??a)),a}function Y(t){const{track:e,...r}=t,o=V(r);return H(o.__store,(e=>t?.track?.(e.loader)??e.loader)),o.state.loader}function G(t){const{track:e,...r}=t??{},o=V(r);return H(o.__store,(e=>t?.track?.(e.search)??e.search)),o.state.search}function Q(t){const e=J();return H(e.__store,(e=>{const r=y(e.matches)?.params;return t?.track?.(r)??r})),y(e.state.matches)?.params}function X(){const t=J();return a.useCallback((e=>{const{pending:r,caseSensitive:o,...a}=e;return t.matchRoute(a,{pending:r,caseSensitive:o})}),[])}function Z(){const t=q().slice(1),e=t[0];return e?a.createElement(tt,{matches:t,match:e}):null}function tt({matches:t,match:e}){const r=J();H(e.__store,(t=>[t.status,t.error]));const o=a.useCallback((()=>null),[]),s=e.pendingComponent??r.options.defaultPendingComponent??o,n=e.errorComponent??r.options.defaultErrorComponent,i=e.route.options.wrapInSuspense??!e.route.isRoot?a.Suspense:rt,c=n?ot:rt;return a.createElement(U.Provider,{value:t},a.createElement(i,{fallback:a.createElement(s,null)},a.createElement(c,{key:e.route.id,errorComponent:n,onCatch:()=>{e.id}},a.createElement(et,{match:e}))))}function et(t){const e=J();if("error"===t.match.state.status)throw t.match.state.error;if("pending"===t.match.state.status)throw t.match.__loadPromise;if("success"===t.match.state.status)return a.createElement(t.match.component??e.options.defaultComponent??Z,{useLoader:t.match.route.useLoader,useMatch:t.match.route.useMatch,useContext:t.match.route.useContext,useSearch:t.match.route.useSearch,useParams:t.match.route.useParams});s(!1)}function rt(t){return a.createElement(a.Fragment,null,t.children)}class ot extends a.Component{state={error:!1,info:void 0};componentDidCatch(t,e){this.props.onCatch(t,e),console.error(t),this.setState({error:t,info:e})}render(){return a.createElement(at,$({},this.props,{errorState:this.state,reset:()=>this.setState({})}))}}function at(t){const[e,r]=a.useState(t.errorState),o=J(),s=t.errorComponent??st,n=a.useRef("");return a.useEffect((()=>{e&&(o.state.location.key,n.current),n.current=o.state.location.key}),[e,o.state.location.key]),a.useEffect((()=>{t.errorState.error}),[t.errorState.error]),t.errorState.error&&e.error?a.createElement(s,e):t.children}function st({error:t}){return a.createElement("div",{style:{padding:".5rem",maxWidth:"100%"}},a.createElement("strong",{style:{fontSize:"1.2rem"}},"Something went wrong!"),a.createElement("div",{style:{height:".5rem"}}),a.createElement("div",null,a.createElement("pre",{style:{fontSize:".7em",border:"1px solid red",borderRadius:".25rem",padding:".5rem",color:"red",overflow:"auto"}},t.message?a.createElement("code",null,t.message):null)))}function nt(t,e=!0){const r=K();a.useEffect((()=>{if(!e)return;let o=r.history.block(((e,r)=>{window.confirm(t)&&(o(),e())}));return o}))}const it="__root__";class ct{constructor(t){this.options=t||{},this.isRoot=!t?.getParentRoute}init=t=>{this.originalIndex=t.originalIndex,this.router=t.router;const e=this.options,r=!e?.path&&!e?.id;this.parentRoute=this.options?.getParentRoute?.(),r?this.path=it:s(this.parentRoute);let o=r?it:e.path;o&&"/"!==o&&(o=C(o));const a=e?.id||o;let n=r?it:E([this.parentRoute.id===it?"":this.parentRoute.id,a]);o===it&&(o="/"),n!==it&&(n=E(["/",n]));const i=n===it?"/":E([this.parentRoute.fullPath,o]);this.path=o,this.id=n,this.fullPath=i,this.to=i};addChildren=t=>(this.children=t,this);useMatch=t=>V({...t,from:this.id});useLoader=t=>Y({...t,from:this.id});useContext=t=>V({...t,from:this.id}).context;useSearch=t=>G({...t,from:this.id});useParams=t=>Q({...t,from:this.id})}class ht extends ct{constructor(t){super(t)}static withRouterContext=()=>t=>new ht(t)}const ut=dt(JSON.parse),lt=pt(JSON.stringify);function dt(t){return e=>{"?"===e.substring(0,1)&&(e=e.substring(1));let r=T(e);for(let e in r){const o=r[e];if("string"==typeof o)try{r[e]=t(o)}catch(t){}}return r}}function pt(t){return e=>{(e={...e})&&Object.keys(e).forEach((r=>{const o=e[r];if(void 0===o||void 0===o)delete e[r];else if(o&&"object"==typeof o&&null!==o)try{e[r]=t(o)}catch(t){}}));const r=M(e).toString();return r?`?${r}`:""}}const ft=async({router:t,routeMatch:e})=>{const r=t.buildNext({to:".",search:t=>({...t??{},__data:{matchId:e.id}})}),o=await fetch(r.href,{method:"GET",signal:e.abortController.signal});if(o.ok)return o.json();throw new Error("Failed to fetch match data")};const mt="undefined"==typeof window||!window.document.createElement;function yt(){return{status:"idle",currentLocation:null,location:null,matches:[],lastUpdated:Date.now()}}function gt(t){return!!t?.isRedirect}const vt=["component","errorComponent","pendingComponent"];class _t{abortController=new AbortController;constructor(t,e,r){Object.assign(this,{route:e,router:t,id:r.id,pathname:r.pathname,params:r.params,__store:new I({updatedAt:0,routeSearch:{},search:{},status:"pending",loader:void 0},{onUpdate:()=>{this.state=this.__store.state}})}),this.state=this.__store.state,vt.map((async t=>{const e=this.route.options[t];this[t]=e})),this.__loadPromise=new Promise((t=>{this.__loadPromiseResolve=t})),"pending"!==this.state.status||this.#t()||(this.__store.setState((t=>({...t,status:"success"}))),this.__loadPromiseResolve?.())}#t=()=>!(!this.route.options.loader&&!vt.some((t=>this.route.options[t]?.preload)));__commit=()=>{const{routeSearch:t,search:e,context:r,routeContext:o}=this.#e({location:this.router.state.location});this.context=r,this.routeContext=o,this.__store.setState((r=>({...r,routeSearch:_(r.routeSearch,t),search:_(r.search,e)})))};cancel=()=>{this.abortController?.abort()};#r=t=>{const e=this.parentMatch?this.parentMatch.#r(t):{search:t.location.search,routeSearch:t.location.search};try{const t=("object"==typeof this.route.options.validateSearch?this.route.options.validateSearch.parse:this.route.options.validateSearch)?.(e.search)??{};return{routeSearch:t,search:{...e.search,...t}}}catch(t){if(gt(t))throw t;(this.route.options.onValidateSearchError??this.route.options.onError)?.(t);const e=new Error("Invalid search params found",{cause:t});throw e.code="INVALID_SEARCH_PARAMS",e}};#e=t=>{const{search:e,routeSearch:r}=this.#r(t);try{const t=this.route.options.getContext?.({parentContext:this.parentMatch?.routeContext??{},context:this.parentMatch?.context??this.router?.options.context??{},params:this.params,search:e})||{};return{routeSearch:r,search:e,context:{...this.parentMatch?.context??this.router?.options.context,...t},routeContext:t}}catch(t){throw this.route.options.onError?.(t),t}};__load=async t=>{let e;this.parentMatch=t.parentMatch;try{e=this.#e(t)}catch(e){return gt(e)?void(t?.preload||this.router.navigate(e)):void this.__store.setState((t=>({...t,status:"error",error:e})))}const{routeSearch:r,search:o,context:a,routeContext:s}=e,n={params:this.params,routeSearch:r,search:o,signal:this.abortController.signal,preload:!!t?.preload,routeContext:s,context:a};return this.__loadPromise=Promise.resolve().then((async()=>{const e=""+Date.now()+Math.random();this.#o=e;const r=()=>e!==this.#o?this.__loadPromise:void 0;let o;const a=(async()=>{await Promise.all(vt.map((async t=>{const e=this.route.options[t];e?.preload&&await e.preload()})))})(),s=Promise.resolve().then((()=>{if(this.route.options.loader)return this.route.options.loader(n)}));try{const[e,n]=await Promise.all([a,s]);if(o=r())return await o;t.preload||this.__store.setState((t=>({...t,error:void 0,status:"success",updatedAt:Date.now(),loader:n})))}catch(e){if(gt(e))return void(t?.preload||this.router.navigate(e));const r=this.route.options.onLoadError??this.route.options.onError;try{r?.(e)}catch(e){return gt(e)?void(t?.preload||this.router.navigate(e)):void this.__store.setState((t=>({...t,error:e,status:"error",updatedAt:Date.now()})))}this.__store.setState((t=>({...t,error:e,status:"error",updatedAt:Date.now()})))}finally{this.__loadPromiseResolve?.(),delete this.__loadPromise}})),this.__loadPromise};#o=""}t.Block=function({message:t,condition:e,children:r}){return nt(t,e),r??null},t.ErrorComponent=st,t.Link=F,t.MatchRoute=function(t){const e=X()(t);return e?"function"==typeof t.children?t.children(e):e?t.children:null:null},t.Navigate=function(t){const e=J();return a.useLayoutEffect((()=>{e.navigate(t)}),[]),null},t.Outlet=Z,t.RootRoute=ht,t.Route=ct,t.RouteMatch=_t,t.Router=class{#a;startedLoadingAt=Date.now();resolveNavigation=()=>{};constructor(t){this.options={defaultPreloadDelay:50,context:void 0,...t,stringifySearch:t?.stringifySearch??lt,parseSearch:t?.parseSearch??ut,fetchServerDataFn:t?.fetchServerDataFn??ft},this.__store=new I(yt(),{onUpdate:()=>{this.state=this.__store.state}}),this.state=this.__store.state,this.update(t);const e=this.buildNext({hash:!0,fromCurrent:!0,search:!0,state:!0});this.state.location.href!==e.href&&this.#s({...e,replace:!0}),"undefined"!=typeof document&&this.hydrate()}reset=()=>{this.__store.setState((t=>Object.assign(t,yt())))};mount=()=>(mt||this.state.matches.length||this.safeLoad(),()=>{});update=t=>{if(Object.assign(this.options,t),this.context=this.options.context,!this.history||this.options.history&&this.options.history!==this.history){this.#a&&this.#a(),this.history=this.options.history??(mt?p():d());const t=this.#n();this.__store.setState((e=>({...e,currentLocation:t,location:t}))),this.#a=this.history.listen((()=>{this.safeLoad({next:this.#n(this.state.location)})}))}const{basepath:e,routeTree:r}=this.options;return this.basepath=`/${C(e??"")??""}`,r&&(this.routesById={},this.routeTree=this.#i(r)),this};buildNext=t=>{const e=this.#c(t),r=this.matchRoutes(e.pathname,e.search);return this.#c({...t,__matches:r})};cancelMatches=()=>{[...this.state.matches].forEach((t=>{t.cancel()}))};safeLoad=t=>{this.load(t).catch((t=>{console.warn(t),s(!1)}))};load=async t=>{this.#h();let e=Date.now();const r=e;let o;if(this.startedLoadingAt=r,this.cancelMatches(),this.__store.batch((()=>{t?.next&&this.__store.setState((e=>({...e,location:t.next}))),o=this.matchRoutes(this.state.location.pathname,this.state.location.search,{strictParseParams:!0,debug:!0}),this.__store.setState((t=>({...t,status:"pending",matches:o})))})),o.forEach((t=>{t.__commit()})),await this.loadMatches(o,this.state.location),this.startedLoadingAt!==r)return this.navigationPromise;const a=this.state.matches,s=[],n=[];a.forEach((t=>{o.find((e=>e.id===t.id))?n.push(t):s.push(t)}));const i=o.filter((t=>!a.find((e=>e.id===t.id))));e=Date.now(),s.forEach((t=>{t.__onExit?.({params:t.params,search:t.state.routeSearch}),"error"===t.state.status&&this.__store.setState((t=>({...t,status:"idle",error:void 0})))})),n.forEach((t=>{t.route.options.onTransition?.({params:t.params,search:t.state.routeSearch})})),i.forEach((t=>{t.__onExit=t.route.options.onLoaded?.({params:t.params,search:t.state.search})}));const c=this.state.location;this.__store.setState((t=>({...t,status:"idle",currentLocation:t.location,matches:o}))),c.href!==this.state.location.href&&this.options.onRouteChange?.(),this.resolveNavigation()};getRoute=t=>{const e=this.routesById[t];return s(e),e};loadRoute=async(t=this.state.location)=>{const e=this.buildNext(t),r=this.matchRoutes(e.pathname,e.search,{strictParseParams:!0});return await this.loadMatches(r,e),r};preloadRoute=async(t=this.state.location)=>{const e=this.buildNext(t),r=this.matchRoutes(e.pathname,e.search,{strictParseParams:!0});return await this.loadMatches(r,e,{preload:!0}),r};matchRoutes=(t,e,r)=>{if(!this.routeTree)return[];const o=[...this.state.matches];let a=[];const s=(e,o=[])=>{let n,i;if(e.some((e=>{const a=e.children;if(!e.path&&a?.length){const t=s(a,[...o,e]);return!!t&&(n=t,i=void 0,!0)}const c="/"!==e.path||!!a?.length,h=O(this.basepath,t,{to:e.fullPath,fuzzy:c,caseSensitive:e.options.caseSensitive??this.options.caseSensitive});if(h){let t;try{t=e.options.parseParams?.(h)??h}catch(t){if(r?.strictParseParams)throw t}return n=e,i=t,!0}return!1})),!n)return;a.push(...o.map((t=>({route:t}))),{route:n,params:i});const c=n.children;return c?.length?s(c):n};s([this.routeTree]);let n={};return a.map((({route:t,params:r})=>{Object.assign(n,r);const a=j(t.path,n),s=j(t.id,n,!0)+(t.options.getKey?.({params:n,search:e})??"");return o.find((t=>t.id===s))||new _t(this,t,{id:s,params:n,pathname:E([this.basepath,a])})})).filter(((t,e,r)=>r.findIndex((e=>e.id===t.id))===e))};loadMatches=async(t,e,r)=>{let o;try{await Promise.all(t.map((async(t,e)=>{try{await(t.route.options.beforeLoad?.({router:this,match:t}))}catch(r){if(gt(r))throw r;o=o??e;const a=t.route.options.onBeforeLoadError??t.route.options.onError;try{a?.(r)}catch(e){if(gt(e))throw e;return void t.__store.setState((t=>({...t,error:e,status:"error",updatedAt:Date.now()})))}t.__store.setState((t=>({...t,error:r,status:"error",updatedAt:Date.now()})))}})))}catch(t){if(gt(t))return void(r?.preload||this.navigate(t));throw t}const a=t.slice(0,o),s=a.map((async(t,o)=>{const s=a[o-1];t.__load({preload:r?.preload,location:e,parentMatch:s}),await t.__loadPromise,s&&await s.__loadPromise}));await Promise.all(s)};reload=()=>{this.navigate({fromCurrent:!0,replace:!0,search:!0})};resolvePath=(t,e)=>L(this.basepath,t,P(e));navigate=async({from:t,to:e="",search:r,hash:o,replace:a,params:n})=>{const i=String(e),c=void 0===t?t:String(t);let h;try{new URL(`${i}`),h=!0}catch(t){}return s(!h),this.#s({from:c,to:i,search:r,hash:o,replace:a,params:n})};matchRoute=(t,e)=>{t={...t,to:t.to?this.resolvePath(t.from??"",t.to):void 0};const r=this.buildNext(t);if(e?.pending&&"pending"!==this.state.status)return!1;const o=e?.pending?this.state.location:this.state.currentLocation;if(!o)return!1;const a=O(this.basepath,o.pathname,{...e,to:r.pathname});return!!a&&(e?.includeSearch??1?!!b(o.search,r.search)&&a:a)};buildLink=({from:t,to:e=".",search:r,params:o,hash:a,target:s,replace:n,activeOptions:i,preload:c,preloadDelay:h,disabled:u})=>{try{return new URL(`${e}`),{type:"external",href:e}}catch(t){}const l={from:t,to:e,search:r,params:o,hash:a,replace:n},d=this.buildNext(l);c=c??this.options.defaultPreload;const p=h??this.options.defaultPreloadDelay??0,f=this.state.location.pathname.split("/"),m=d.pathname.split("/").every(((t,e)=>t===f[e])),y=i?.exact?this.state.location.pathname===d.pathname:m,g=!i?.includeHash||this.state.location.hash===d.hash,v=!(i?.includeSearch??1)||b(this.state.location.search,d.search);return{type:"internal",next:d,handleFocus:t=>{c&&this.preloadRoute(l).catch((t=>{console.warn(t),console.warn("Error preloading route! ☝️")}))},handleClick:t=>{u||function(t){return!!(t.metaKey||t.altKey||t.ctrlKey||t.shiftKey)}(t)||t.defaultPrevented||s&&"_self"!==s||0!==t.button||(t.preventDefault(),this.#s(l))},handleEnter:t=>{const e=t.target||{};if(c){if(e.preloadTimeout)return;e.preloadTimeout=setTimeout((()=>{e.preloadTimeout=null,this.preloadRoute(l).catch((t=>{console.warn(t),console.warn("Error preloading route! ☝️")}))}),p)}},handleLeave:t=>{const e=t.target||{};e.preloadTimeout&&(clearTimeout(e.preloadTimeout),e.preloadTimeout=null)},handleTouchStart:t=>{this.preloadRoute(l).catch((t=>{console.warn(t),console.warn("Error preloading route! ☝️")}))},isActive:y&&g&&v,disabled:u}};dehydrate=()=>({state:{...v(this.state,["location","status","lastUpdated"])}});hydrate=async t=>{let e=t;"undefined"!=typeof document&&(e=window.__TSR_DEHYDRATED__),s(e);const r=e;this.options.hydrate?.(r.payload),this.__store.setState((t=>({...t,...r.router.state,matches:t.matches,currentLocation:r.router.state.location}))),await this.load()};injectedHtml=[];injectHtml=async t=>{this.injectedHtml.push(t)};dehydrateData=(t,e)=>{if("undefined"==typeof document){const r="string"==typeof t?t:JSON.stringify(t);return this.injectHtml((async()=>{const t="function"==typeof e?await e():e;return`<script>window["__TSR__DEHYRATED__${o=r,o.replace(/\\/g,"\\\\").replace(/'/g,"\\'").replace(/"/g,'\\"')}"] = ${JSON.stringify(t)}<\/script>`;var o})),()=>this.hydrateData(t)}return()=>{}};hydrateData=t=>{if("undefined"!=typeof document){const e="string"==typeof t?t:JSON.stringify(t);return window[`__TSR__DEHYRATED__${e}`]}};#i=t=>{const e=(t,r)=>{t.forEach(((t,r)=>{t.init({originalIndex:r,router:this});s(!this.routesById[t.id],String(t.id)),this.routesById[t.id]=t;const o=t.children;o?.length&&(e(o),o.length,t.children=o.map(((t,e)=>{const r=x(P(t.path??"/")),o=k(r);for(;o.length>1&&"/"===o[0]?.value;)o.shift();const a=o.map((t=>"param"===t.type?.5:"wildcard"===t.type?.25:1));return{child:t,cleaned:r,parsed:o,index:e,score:a}})).sort(((t,e)=>{const r=Math.min(t.score.length,e.score.length);for(let o=0;o<r;o++)if(t.score[o]!==e.score[o])return e.score[o]-t.score[o];for(let o=0;o<r;o++)if(t.parsed[o].value!==e.parsed[o].value)return t.parsed[o].value>e.parsed[o].value?1:-1;return t.score.length!==e.score.length?e.score.length-t.score.length:t.cleaned!==e.cleaned?t.cleaned>e.cleaned?1:-1:t.index-e.index})).map((t=>t.child)))}))};e([t]);const r=(t,e)=>{t.forEach((t=>{t.isRoot?s(!e):s(!e||t.parentRoute===e,(t.path,t.parentRoute?.id,e?.id)),t.children&&r(t.children,t)}))};return r([t],void 0),t};#n=t=>{let{pathname:e,search:r,hash:o,state:a}=this.history.location;const s=this.options.parseSearch(r);return{pathname:e,searchStr:r,search:_(t?.search,s),hash:o.split("#").reverse()[0]??"",href:`${e}${r}${o}`,state:a,key:a?.key||"__init__"}};#c=(t={})=>{t.fromCurrent=t.fromCurrent??""===t.to;const e=t.fromCurrent?this.state.location.pathname:t.from??this.state.location.pathname;let r=L(this.basepath??"/",e,`${t.to??""}`);const o={...y(this.matchRoutes(this.state.location.pathname,this.state.location.search,{strictParseParams:!0}))?.params};let a=!0===(t.params??!0)?o:g(t.params,o);a&&t.__matches?.map((t=>t.route.options.stringifyParams)).filter(Boolean).forEach((t=>{a={...a,...t(a)}})),r=j(r,a??{});const s=t.__matches?.map((t=>t.route.options.preSearchFilters??[])).flat().filter(Boolean)??[],n=t.__matches?.map((t=>t.route.options.postSearchFilters??[])).flat().filter(Boolean)??[],i=s?.length?s?.reduce(((t,e)=>e(t)),this.state.location.search):this.state.location.search,c=!0===t.search?i:t.search?g(t.search,i)??{}:s?.length?i:{},h=n?.length?n.reduce(((t,e)=>e(t)),c):c,u=_(this.state.location.search,h),l=this.options.stringifySearch(u),d=!0===t.hash?this.state.location.hash:g(t.hash,this.state.location.hash),p=d?`#${d}`:"";return{pathname:r,search:u,searchStr:l,state:!0===t.state?this.state.location.state:g(t.state,this.state.location.state),hash:d,href:this.history.createHref(`${r}${l}${p}`),key:t.key}};#s=async t=>{const e=this.buildNext(t),r=""+Date.now()+Math.random();this.navigateTimeout&&clearTimeout(this.navigateTimeout);let o="replace";t.replace||(o="push");this.state.location.href===e.href&&!e.key&&(o="replace");const a=`${e.pathname}${e.searchStr}${e.hash?`#${e.hash}`:""}`;return this.history["push"===o?"push":"replace"](a,{id:r,...e.state}),this.#h()};#h=()=>{const t=this.resolveNavigation;return this.navigationPromise=new Promise((e=>{this.resolveNavigation=()=>{e(),t()}})),this.navigationPromise}},t.RouterProvider=function({router:t,...e}){t.update(e);const r=W(H(t.__store,(t=>t.matches)));return a.useEffect(t.mount,[t]),a.createElement(z.Provider,{value:{router:t}},a.createElement(U.Provider,{value:[void 0,...r]},a.createElement(ot,{errorComponent:st,onCatch:()=>{}},a.createElement(Z,null))))},t.cleanPath=P,t.createBrowserHistory=d,t.createHashHistory=function(){return d({getHref:()=>window.location.hash.substring(1),createHref:t=>`#${t}`})},t.createMemoryHistory=p,t.decode=T,t.defaultFetchServerDataFn=ft,t.defaultParseSearch=ut,t.defaultStringifySearch=lt,t.encode=M,t.functionalUpdate=g,t.interpolatePath=j,t.invariant=s,t.isPlainObject=w,t.isRedirect=gt,t.joinPaths=E,t.last=y,t.lazy=function(t,e="default"){const r=a.lazy((async()=>({default:(await t())[e]})));return r.preload=async()=>{await t()},r},t.matchByPath=D,t.matchPathname=O,t.matchesContext=U,t.parsePathname=k,t.parseSearchWith=dt,t.partialDeepEqual=b,t.pick=v,t.redirect=function(t){return t.isRedirect=!0,t},t.replaceEqualDeep=_,t.resolvePath=L,t.rootRouteId=it,t.routerContext=z,t.stringifySearchWith=pt,t.trimPath=C,t.trimPathLeft=x,t.trimPathRight=R,t.useBlocker=nt,t.useDehydrate=function(){const t=J();return a.useCallback((function(e,r){return t.dehydrateData(e,r)}),[])},t.useHydrate=function(){const t=J();return function(e){return t.hydrateData(e)}},t.useInjectHtml=function(){const t=J();return a.useCallback((e=>{t.injectHtml(e)}),[])},t.useLinkProps=B,t.useLoader=Y,t.useMatch=V,t.useMatchRoute=X,t.useMatches=q,t.useNavigate=function(t){const e=J();return a.useCallback((r=>e.navigate({...t,...r})),[])},t.useParams=Q,t.useRouter=K,t.useRouterContext=J,t.useSearch=G,t.useStore=H,t.warning=n,Object.defineProperty(t,"__esModule",{value:!0})}));
*/function H(t,e=(t=>t)){return r.useSyncExternalStoreWithSelector(t.subscribe,(()=>t.state),(()=>t.state),e,N)}function N(t,e){if(Object.is(t,e))return!0;if("object"!=typeof t||null===t||"object"!=typeof e||null===e)return!1;const r=Object.keys(t);if(r.length!==Object.keys(e).length)return!1;for(let o=0;o<r.length;o++)if(!Object.prototype.hasOwnProperty.call(e,r[o])||!Object.is(t[r[o]],e[r[o]]))return!1;return!0}function B(t){const e=J(),{type:r,children:o,target:s,activeProps:n=(()=>({className:"active"})),inactiveProps:i=(()=>({})),activeOptions:c,disabled:h,hash:u,search:l,params:d,to:p=".",preload:f,preloadDelay:m,replace:y,style:v,className:_,onClick:w,onFocus:b,onMouseEnter:S,onMouseLeave:P,onTouchStart:E,...x}=t,R=e.buildLink(t);if("external"===R.type){const{href:t}=R;return{href:t}}const{handleClick:C,handleFocus:L,handleEnter:k,handleLeave:j,handleTouchStart:O,isActive:D,next:M}=R,A=t=>e=>{e.persist&&e.persist(),t.filter(Boolean).forEach((t=>{e.defaultPrevented||t(e)}))},$=D?g(n,{})??{}:{},T=D?{}:g(i,{})??{};return{...$,...T,...x,href:h?void 0:M.href,onClick:A([w,t=>{a.startTransition?a.startTransition((()=>{C(t)})):C(t)}]),onFocus:A([b,L]),onMouseEnter:A([S,k]),onMouseLeave:A([P,j]),onTouchStart:A([E,O]),target:s,style:{...v,...$.style,...T.style},className:[_,$.className,T.className].filter(Boolean).join(" ")||void 0,...h?{role:"link","aria-disabled":!0}:void 0,"data-status":D?"active":void 0}}const F=a.forwardRef(((t,e)=>{const r=B(t);return a.createElement("a",T({ref:e},r,{children:"function"==typeof t.children?t.children({isActive:"active"===r["data-status"]}):t.children}))}));const U=a.createContext(null),z=a.createContext(null),W=a.useDeferredValue||(t=>t);function J(){const t=a.useContext(z);return H(t.router.__store),t.router}function K(t){const e=J();return H(e.__store,t),e}function q(){return a.useContext(U)}function V(t){const e=J(),r=q()[0],o=W(e.state.matches),a=t?.from?o.find((e=>e.route.id===t?.from)):r;return s(a,t?.from&&t.from),(t?.strict??1)&&s(r.route.id==a?.route.id,(a?.route.id,r.route.id,a?.route.id,a?.route.id)),H(a.__store,(e=>t?.track?.(a)??a)),a}function Y(t){const{track:e,...r}=t,o=V(r);return H(o.__store,(e=>t?.track?.(e.loader)??e.loader)),o.state.loader}function G(t){const{track:e,...r}=t??{},o=V(r);return H(o.__store,(e=>t?.track?.(e.search)??e.search)),o.state.search}function Q(t){const e=J();return H(e.__store,(e=>{const r=y(e.matches)?.params;return t?.track?.(r)??r})),y(e.state.matches)?.params}function X(){const t=J();return a.useCallback((e=>{const{pending:r,caseSensitive:o,...a}=e;return t.matchRoute(a,{pending:r,caseSensitive:o})}),[])}function Z(){const t=q().slice(1),e=t[0];return e?a.createElement(tt,{matches:t,match:e}):null}function tt({matches:t,match:e}){const r=J();H(e.__store,(t=>[t.status,t.error]));const o=a.useCallback((()=>null),[]),s=e.pendingComponent??r.options.defaultPendingComponent??o,n=e.errorComponent??r.options.defaultErrorComponent,i=e.route.options.wrapInSuspense??!e.route.isRoot?a.Suspense:rt,c=n?ot:rt;return a.createElement(U.Provider,{value:t},a.createElement(i,{fallback:a.createElement(s,null)},a.createElement(c,{key:e.route.id,errorComponent:n,onCatch:()=>{e.id}},a.createElement(et,{match:e}))))}function et(t){const e=J();if("error"===t.match.state.status)throw t.match.state.error;if("pending"===t.match.state.status)throw t.match.__loadPromise;if("success"===t.match.state.status)return a.createElement(t.match.component??e.options.defaultComponent??Z,{useLoader:t.match.route.useLoader,useMatch:t.match.route.useMatch,useContext:t.match.route.useContext,useSearch:t.match.route.useSearch,useParams:t.match.route.useParams});s(!1)}function rt(t){return a.createElement(a.Fragment,null,t.children)}class ot extends a.Component{state={error:!1,info:void 0};componentDidCatch(t,e){this.props.onCatch(t,e),console.error(t),this.setState({error:t,info:e})}render(){return a.createElement(at,T({},this.props,{errorState:this.state,reset:()=>this.setState({})}))}}function at(t){const[e,r]=a.useState(t.errorState),o=J(),s=t.errorComponent??st,n=a.useRef("");return a.useEffect((()=>{e&&(o.state.location.key,n.current),n.current=o.state.location.key}),[e,o.state.location.key]),a.useEffect((()=>{t.errorState.error}),[t.errorState.error]),t.errorState.error&&e.error?a.createElement(s,e):t.children}function st({error:t}){return a.createElement("div",{style:{padding:".5rem",maxWidth:"100%"}},a.createElement("strong",{style:{fontSize:"1.2rem"}},"Something went wrong!"),a.createElement("div",{style:{height:".5rem"}}),a.createElement("div",null,a.createElement("pre",{style:{fontSize:".7em",border:"1px solid red",borderRadius:".25rem",padding:".5rem",color:"red",overflow:"auto"}},t.message?a.createElement("code",null,t.message):null)))}function nt(t,e=!0){const r=K();a.useEffect((()=>{if(!e)return;let o=r.history.block(((e,r)=>{window.confirm(t)&&(o(),e())}));return o}))}const it="__root__";class ct{constructor(t){this.options=t||{},this.isRoot=!t?.getParentRoute}init=t=>{this.originalIndex=t.originalIndex,this.router=t.router;const e=this.options,r=!e?.path&&!e?.id;this.parentRoute=this.options?.getParentRoute?.(),r?this.path=it:s(this.parentRoute);let o=r?it:e.path;o&&"/"!==o&&(o=C(o));const a=e?.id||o;let n=r?it:P([this.parentRoute.id===it?"":this.parentRoute.id,a]);o===it&&(o="/"),n!==it&&(n=P(["/",n]));const i=n===it?"/":P([this.parentRoute.fullPath,o]);this.path=o,this.id=n,this.fullPath=i,this.to=i};addChildren=t=>(this.children=t,this);useMatch=t=>V({...t,from:this.id});useLoader=t=>Y({...t,from:this.id});useContext=t=>V({...t,from:this.id}).context;useSearch=t=>G({...t,from:this.id});useParams=t=>Q({...t,from:this.id})}class ht extends ct{constructor(t){super(t)}static withRouterContext=()=>t=>new ht(t)}const ut=dt(JSON.parse),lt=pt(JSON.stringify);function dt(t){return e=>{"?"===e.substring(0,1)&&(e=e.substring(1));let r=$(e);for(let e in r){const o=r[e];if("string"==typeof o)try{r[e]=t(o)}catch(t){}}return r}}function pt(t){return e=>{(e={...e})&&Object.keys(e).forEach((r=>{const o=e[r];if(void 0===o||void 0===o)delete e[r];else if(o&&"object"==typeof o&&null!==o)try{e[r]=t(o)}catch(t){}}));const r=M(e).toString();return r?`?${r}`:""}}const ft=async({router:t,routeMatch:e})=>{const r=t.buildNext({to:".",search:t=>({...t??{},__data:{matchId:e.id}})}),o=await fetch(r.href,{method:"GET",signal:e.abortController.signal});if(o.ok)return o.json();throw new Error("Failed to fetch match data")};const mt="undefined"==typeof window||!window.document.createElement;function yt(){return{status:"idle",currentLocation:null,location:null,matches:[],lastUpdated:Date.now()}}function gt(t){return!!t?.isRedirect}const vt=["component","errorComponent","pendingComponent"];class _t{abortController=new AbortController;constructor(t,e,r){Object.assign(this,{route:e,router:t,id:r.id,pathname:r.pathname,params:r.params,__store:new I({updatedAt:0,routeSearch:{},search:{},status:"pending",loader:void 0},{onUpdate:()=>{this.state=this.__store.state}})}),this.state=this.__store.state,vt.map((async t=>{const e=this.route.options[t];this[t]=e})),this.__loadPromise=new Promise((t=>{this.__loadPromiseResolve=t})),"pending"!==this.state.status||this.#t()||(this.__store.setState((t=>({...t,status:"success"}))),this.__loadPromiseResolve?.())}#t=()=>!(!this.route.options.loader&&!vt.some((t=>this.route.options[t]?.preload)));__commit=()=>{const{routeSearch:t,search:e,context:r,routeContext:o}=this.#e({location:this.router.state.location});this.context=r,this.routeContext=o,this.__store.setState((r=>({...r,routeSearch:_(r.routeSearch,t),search:_(r.search,e)})))};cancel=()=>{this.abortController?.abort()};#r=t=>{const e=this.parentMatch?this.parentMatch.#r(t):{search:t.location.search,routeSearch:t.location.search};try{const t=("object"==typeof this.route.options.validateSearch?this.route.options.validateSearch.parse:this.route.options.validateSearch)?.(e.search)??{};return{routeSearch:t,search:{...e.search,...t}}}catch(t){if(gt(t))throw t;(this.route.options.onValidateSearchError??this.route.options.onError)?.(t);const e=new Error("Invalid search params found",{cause:t});throw e.code="INVALID_SEARCH_PARAMS",e}};#e=t=>{const{search:e,routeSearch:r}=this.#r(t);try{const t=this.route.options.getContext?.({parentContext:this.parentMatch?.routeContext??{},context:this.parentMatch?.context??this.router?.options.context??{},params:this.params,search:e})||{};return{routeSearch:r,search:e,context:{...this.parentMatch?.context??this.router?.options.context,...t},routeContext:t}}catch(t){throw this.route.options.onError?.(t),t}};__load=async t=>{let e;this.parentMatch=t.parentMatch;try{e=this.#e(t)}catch(e){return gt(e)?void(t?.preload||this.router.navigate(e)):void this.__store.setState((t=>({...t,status:"error",error:e})))}const{routeSearch:r,search:o,context:a,routeContext:s}=e,n={params:this.params,routeSearch:r,search:o,signal:this.abortController.signal,preload:!!t?.preload,routeContext:s,context:a};return this.__loadPromise=Promise.resolve().then((async()=>{const e=""+Date.now()+Math.random();this.#o=e;const r=()=>e!==this.#o?this.__loadPromise:void 0;let o;const a=(async()=>{await Promise.all(vt.map((async t=>{const e=this.route.options[t];e?.preload&&await e.preload()})))})(),s=Promise.resolve().then((()=>{if(this.route.options.loader)return this.route.options.loader(n)}));try{const[e,n]=await Promise.all([a,s]);if(o=r())return await o;t.preload||this.__store.setState((t=>({...t,error:void 0,status:"success",updatedAt:Date.now(),loader:n})))}catch(e){if(gt(e))return void(t?.preload||this.router.navigate(e));const r=this.route.options.onLoadError??this.route.options.onError;try{r?.(e)}catch(e){return gt(e)?void(t?.preload||this.router.navigate(e)):void this.__store.setState((t=>({...t,error:e,status:"error",updatedAt:Date.now()})))}this.__store.setState((t=>({...t,error:e,status:"error",updatedAt:Date.now()})))}finally{this.__loadPromiseResolve?.(),delete this.__loadPromise}})),this.__loadPromise};#o=""}t.Block=function({message:t,condition:e,children:r}){return nt(t,e),r??null},t.ErrorComponent=st,t.Link=F,t.MatchRoute=function(t){const e=X()(t);return e?"function"==typeof t.children?t.children(e):e?t.children:null:null},t.Navigate=function(t){const e=J();return a.useLayoutEffect((()=>{e.navigate(t)}),[]),null},t.Outlet=Z,t.RootRoute=ht,t.Route=ct,t.RouteMatch=_t,t.Router=class{#a;startedLoadingAt=Date.now();resolveNavigation=()=>{};constructor(t){this.options={defaultPreloadDelay:50,context:void 0,...t,stringifySearch:t?.stringifySearch??lt,parseSearch:t?.parseSearch??ut,fetchServerDataFn:t?.fetchServerDataFn??ft},this.__store=new I(yt(),{onUpdate:()=>{this.state=this.__store.state}}),this.state=this.__store.state,this.update(t);const e=this.buildNext({hash:!0,fromCurrent:!0,search:!0,state:!0});this.state.location.href!==e.href&&this.#s({...e,replace:!0})}reset=()=>{this.__store.setState((t=>Object.assign(t,yt())))};mount=()=>(mt||this.state.matches.length||this.safeLoad(),()=>{});update=t=>{if(Object.assign(this.options,t),this.context=this.options.context,!this.history||this.options.history&&this.options.history!==this.history){this.#a&&this.#a(),this.history=this.options.history??(mt?p():d());const t=this.#n();this.__store.setState((e=>({...e,currentLocation:t,location:t}))),this.#a=this.history.listen((()=>{this.safeLoad({next:this.#n(this.state.location)})}))}const{basepath:e,routeTree:r}=this.options;return this.basepath=`/${C(e??"")??""}`,r&&r!==this.routeTree&&this.#i(r),this};buildNext=t=>{const e=this.#c(t),r=this.matchRoutes(e.pathname,e.search);return this.#c({...t,__matches:r})};cancelMatches=()=>{[...this.state.matches].forEach((t=>{t.cancel()}))};safeLoad=t=>{this.load(t).catch((t=>{console.warn(t),s(!1)}))};load=async t=>{this.#h();let e=Date.now();const r=e;let o;if(this.startedLoadingAt=r,this.cancelMatches(),this.__store.batch((()=>{t?.next&&this.__store.setState((e=>({...e,location:t.next}))),o=this.matchRoutes(this.state.location.pathname,this.state.location.search,{strictParseParams:!0,debug:!0}),this.__store.setState((t=>({...t,status:"pending",matches:o})))})),o.forEach((t=>{t.__commit()})),await this.loadMatches(o,this.state.location),this.startedLoadingAt!==r)return this.navigationPromise;const a=this.state.matches,s=[],n=[];a.forEach((t=>{o.find((e=>e.id===t.id))?n.push(t):s.push(t)}));const i=o.filter((t=>!a.find((e=>e.id===t.id))));e=Date.now(),s.forEach((t=>{t.__onExit?.({params:t.params,search:t.state.routeSearch}),"error"===t.state.status&&this.__store.setState((t=>({...t,status:"idle",error:void 0})))})),n.forEach((t=>{t.route.options.onTransition?.({params:t.params,search:t.state.routeSearch})})),i.forEach((t=>{t.__onExit=t.route.options.onLoaded?.({params:t.params,search:t.state.search})}));const c=this.state.location;this.__store.setState((t=>({...t,status:"idle",currentLocation:t.location,matches:o}))),c.href!==this.state.location.href&&this.options.onRouteChange?.(),this.resolveNavigation()};getRoute=t=>{const e=this.routesById[t];return s(e),e};loadRoute=async(t=this.state.location)=>{const e=this.buildNext(t),r=this.matchRoutes(e.pathname,e.search,{strictParseParams:!0});return await this.loadMatches(r,e),r};preloadRoute=async(t=this.state.location)=>{const e=this.buildNext(t),r=this.matchRoutes(e.pathname,e.search,{strictParseParams:!0});return await this.loadMatches(r,e,{preload:!0}),r};matchRoutes=(t,e,r)=>{if(!this.flatRoutes.length)return[];let o={},a=this.flatRoutes.find((e=>{const r=O(this.basepath,t,{to:e.fullPath,caseSensitive:e.options.caseSensitive??this.options.caseSensitive});return!!r&&(o=r,!0)}));if(!a)return[];let s=[a];for(;a?.parentRoute;)a=a.parentRoute,a&&s.unshift(a);let n={};const i=[...this.state.matches],c=s.map((t=>{let a;try{a=t.options.parseParams?.(o)??o}catch(t){if(r?.strictParseParams)throw t}Object.assign(n,a);const s=j(t.path,n),c=j(t.id,n,!0)+(t.options.getKey?.({params:n,search:e})??""),h=i.find((t=>t.id===c));return h||new _t(this,t,{id:c,params:n,pathname:P([this.basepath,s])})})).filter(((t,e,r)=>r.findIndex((e=>e.id===t.id))===e));return console.log(c),c};loadMatches=async(t,e,r)=>{let o;try{await Promise.all(t.map((async(t,e)=>{try{await(t.route.options.beforeLoad?.({router:this,match:t}))}catch(r){if(gt(r))throw r;o=o??e;const a=t.route.options.onBeforeLoadError??t.route.options.onError;try{a?.(r)}catch(e){if(gt(e))throw e;return void t.__store.setState((t=>({...t,error:e,status:"error",updatedAt:Date.now()})))}t.__store.setState((t=>({...t,error:r,status:"error",updatedAt:Date.now()})))}})))}catch(t){if(gt(t))return void(r?.preload||this.navigate(t));throw t}const a=t.slice(0,o),s=a.map((async(t,o)=>{const s=a[o-1];t.__load({preload:r?.preload,location:e,parentMatch:s}),await t.__loadPromise,s&&await s.__loadPromise}));await Promise.all(s)};reload=()=>{this.navigate({fromCurrent:!0,replace:!0,search:!0})};resolvePath=(t,e)=>L(this.basepath,t,E(e));navigate=async({from:t,to:e="",search:r,hash:o,replace:a,params:n})=>{const i=String(e),c=void 0===t?t:String(t);let h;try{new URL(`${i}`),h=!0}catch(t){}return s(!h),this.#s({from:c,to:i,search:r,hash:o,replace:a,params:n})};matchRoute=(t,e)=>{t={...t,to:t.to?this.resolvePath(t.from??"",t.to):void 0};const r=this.buildNext(t);if(e?.pending&&"pending"!==this.state.status)return!1;const o=e?.pending?this.state.location:this.state.currentLocation;if(!o)return!1;const a=O(this.basepath,o.pathname,{...e,to:r.pathname});return!!a&&(e?.includeSearch??1?!!S(o.search,r.search)&&a:a)};buildLink=({from:t,to:e=".",search:r,params:o,hash:a,target:s,replace:n,activeOptions:i,preload:c,preloadDelay:h,disabled:u})=>{try{return new URL(`${e}`),{type:"external",href:e}}catch(t){}const l={from:t,to:e,search:r,params:o,hash:a,replace:n},d=this.buildNext(l);c=c??this.options.defaultPreload;const p=h??this.options.defaultPreloadDelay??0,f=this.state.location.pathname.split("/"),m=d.pathname.split("/").every(((t,e)=>t===f[e])),y=i?.exact?this.state.location.pathname===d.pathname:m,g=!i?.includeHash||this.state.location.hash===d.hash,v=!(i?.includeSearch??1)||S(this.state.location.search,d.search);return{type:"internal",next:d,handleFocus:t=>{c&&this.preloadRoute(l).catch((t=>{console.warn(t),console.warn("Error preloading route! ☝️")}))},handleClick:t=>{u||function(t){return!!(t.metaKey||t.altKey||t.ctrlKey||t.shiftKey)}(t)||t.defaultPrevented||s&&"_self"!==s||0!==t.button||(t.preventDefault(),this.#s(l))},handleEnter:t=>{const e=t.target||{};if(c){if(e.preloadTimeout)return;e.preloadTimeout=setTimeout((()=>{e.preloadTimeout=null,this.preloadRoute(l).catch((t=>{console.warn(t),console.warn("Error preloading route! ☝️")}))}),p)}},handleLeave:t=>{const e=t.target||{};e.preloadTimeout&&(clearTimeout(e.preloadTimeout),e.preloadTimeout=null)},handleTouchStart:t=>{this.preloadRoute(l).catch((t=>{console.warn(t),console.warn("Error preloading route! ☝️")}))},isActive:y&&g&&v,disabled:u}};dehydrate=()=>({state:{...v(this.state,["location","status","lastUpdated"])}});hydrate=async t=>{let e=t;"undefined"!=typeof document&&(e=window.__TSR_DEHYDRATED__),s(e);const r=e;this.options.hydrate?.(r.payload),this.__store.setState((t=>({...t,...r.router.state,matches:t.matches,currentLocation:r.router.state.location}))),await this.load()};injectedHtml=[];injectHtml=async t=>{this.injectedHtml.push(t)};dehydrateData=(t,e)=>{if("undefined"==typeof document){const r="string"==typeof t?t:JSON.stringify(t);return this.injectHtml((async()=>{const t="function"==typeof e?await e():e;return`<script>window["__TSR__DEHYRATED__${o=r,o.replace(/\\/g,"\\\\").replace(/'/g,"\\'").replace(/"/g,'\\"')}"] = ${JSON.stringify(t)}<\/script>`;var o})),()=>this.hydrateData(t)}return()=>{}};hydrateData=t=>{if("undefined"!=typeof document){const e="string"==typeof t?t:JSON.stringify(t);return window[`__TSR__DEHYRATED__${e}`]}};#i=t=>{this.routeTree=t,this.routesById={},this.routesByPath={},this.flatRoutes=[];const e=t=>{t.forEach(((t,r)=>{t.init({originalIndex:r,router:this});if(s(!this.routesById[t.id],String(t.id)),this.routesById[t.id]=t,!t.isRoot&&t.path){const e=R(t.fullPath);this.routesByPath[e]&&!t.fullPath.endsWith("/")||(this.routesByPath[e]=t)}const o=t.children;o?.length&&e(o)}))};e([t]),this.flatRoutes=Object.values(this.routesByPath).map(((t,e)=>{const r=C(t.fullPath),o=k(r);for(;o.length>1&&"/"===o[0]?.value;)o.shift();const a=o.map((t=>"param"===t.type?.5:"wildcard"===t.type?.25:1));return{child:t,trimmed:r,parsed:o,index:e,score:a}})).sort(((t,e)=>{let r="/"===t.trimmed?1:"/"===e.trimmed?-1:0;if(0!==r)return r;const o=Math.min(t.score.length,e.score.length);if(t.score.length!==e.score.length)return e.score.length-t.score.length;for(let r=0;r<o;r++)if(t.score[r]!==e.score[r])return e.score[r]-t.score[r];for(let r=0;r<o;r++)if(t.parsed[r].value!==e.parsed[r].value)return t.parsed[r].value>e.parsed[r].value?1:-1;return t.trimmed!==e.trimmed?t.trimmed>e.trimmed?1:-1:t.index-e.index})).map(((t,e)=>(t.child.rank=e,t.child)))};#n=t=>{let{pathname:e,search:r,hash:o,state:a}=this.history.location;const s=this.options.parseSearch(r);return{pathname:e,searchStr:r,search:_(t?.search,s),hash:o.split("#").reverse()[0]??"",href:`${e}${r}${o}`,state:a,key:a?.key||"__init__"}};#c=(t={})=>{t.fromCurrent=t.fromCurrent??""===t.to;const e=t.fromCurrent?this.state.location.pathname:t.from??this.state.location.pathname;let r=L(this.basepath??"/",e,`${t.to??""}`);const o={...y(this.matchRoutes(this.state.location.pathname,this.state.location.search,{strictParseParams:!0}))?.params};let a=!0===(t.params??!0)?o:g(t.params,o);a&&t.__matches?.map((t=>t.route.options.stringifyParams)).filter(Boolean).forEach((t=>{a={...a,...t(a)}})),r=j(r,a??{});const s=t.__matches?.map((t=>t.route.options.preSearchFilters??[])).flat().filter(Boolean)??[],n=t.__matches?.map((t=>t.route.options.postSearchFilters??[])).flat().filter(Boolean)??[],i=s?.length?s?.reduce(((t,e)=>e(t)),this.state.location.search):this.state.location.search,c=!0===t.search?i:t.search?g(t.search,i)??{}:s?.length?i:{},h=n?.length?n.reduce(((t,e)=>e(t)),c):c,u=_(this.state.location.search,h),l=this.options.stringifySearch(u),d=!0===t.hash?this.state.location.hash:g(t.hash,this.state.location.hash),p=d?`#${d}`:"";return{pathname:r,search:u,searchStr:l,state:!0===t.state?this.state.location.state:g(t.state,this.state.location.state),hash:d,href:this.history.createHref(`${r}${l}${p}`),key:t.key}};#s=async t=>{const e=this.buildNext(t),r=""+Date.now()+Math.random();this.navigateTimeout&&clearTimeout(this.navigateTimeout);let o="replace";t.replace||(o="push");this.state.location.href===e.href&&!e.key&&(o="replace");const a=`${e.pathname}${e.searchStr}${e.hash?`#${e.hash}`:""}`;return this.history["push"===o?"push":"replace"](a,{id:r,...e.state}),this.#h()};#h=()=>{const t=this.resolveNavigation;return this.navigationPromise=new Promise((e=>{this.resolveNavigation=()=>{e(),t()}})),this.navigationPromise}},t.RouterProvider=function({router:t,...e}){t.update(e);const r=W(H(t.__store,(t=>t.matches)));return a.useEffect(t.mount,[t]),a.createElement(z.Provider,{value:{router:t}},a.createElement(U.Provider,{value:[void 0,...r]},a.createElement(ot,{errorComponent:st,onCatch:()=>{}},a.createElement(Z,null))))},t.cleanPath=E,t.createBrowserHistory=d,t.createHashHistory=function(){return d({getHref:()=>window.location.hash.substring(1),createHref:t=>`#${t}`})},t.createMemoryHistory=p,t.decode=$,t.defaultFetchServerDataFn=ft,t.defaultParseSearch=ut,t.defaultStringifySearch=lt,t.encode=M,t.functionalUpdate=g,t.interpolatePath=j,t.invariant=s,t.isPlainObject=w,t.isRedirect=gt,t.joinPaths=P,t.last=y,t.lazy=function(t,e="default"){const r=a.lazy((async()=>({default:(await t())[e]})));return r.preload=async()=>{await t()},r},t.matchByPath=D,t.matchPathname=O,t.matchesContext=U,t.parsePathname=k,t.parseSearchWith=dt,t.partialDeepEqual=S,t.pick=v,t.redirect=function(t){return t.isRedirect=!0,t},t.replaceEqualDeep=_,t.resolvePath=L,t.rootRouteId=it,t.routerContext=z,t.stringifySearchWith=pt,t.trimPath=C,t.trimPathLeft=x,t.trimPathRight=R,t.useBlocker=nt,t.useDehydrate=function(){const t=J();return a.useCallback((function(e,r){return t.dehydrateData(e,r)}),[])},t.useHydrate=function(){const t=J();return function(e){return t.hydrateData(e)}},t.useInjectHtml=function(){const t=J();return a.useCallback((e=>{t.injectHtml(e)}),[])},t.useLinkProps=B,t.useLoader=Y,t.useMatch=V,t.useMatchRoute=X,t.useMatches=q,t.useNavigate=function(t){const e=J();return a.useCallback((r=>e.navigate({...t,...r})),[])},t.useParams=Q,t.useRouter=K,t.useRouterContext=J,t.useSearch=G,t.useStore=H,t.warning=n,Object.defineProperty(t,"__esModule",{value:!0})}));
//# sourceMappingURL=index.production.js.map
{
"name": "@tanstack/router",
"author": "Tanner Linsley",
"version": "0.0.1-beta.112",
"version": "0.0.1-beta.113",
"license": "MIT",

@@ -46,3 +46,3 @@ "repository": "tanstack/router",

"@gisatcz/cross-package-react-context": "^0.2.0",
"@tanstack/react-store": "0.0.1-beta.90"
"@tanstack/react-store": "0.0.1-beta.113"
},

@@ -49,0 +49,0 @@ "scripts": {

@@ -579,2 +579,3 @@ import { ParsePathParams } from './link'

router?: Router<TRoutesInfo['routeTree'], TRoutesInfo>
rank!: number

@@ -581,0 +582,0 @@ constructor(

@@ -139,2 +139,6 @@ import { AnyRoute, Route } from './route'

export type RoutesByPath<TRoutesInfo extends AnyRoutesInfo> = {
[K in keyof TRoutesInfo['routesByFullPath']]: TRoutesInfo['routesByFullPath'][K]
}
export type RouteByPath<

@@ -141,0 +145,0 @@ TRoutesInfo extends AnyRoutesInfo,

@@ -22,2 +22,3 @@ import { Store } from '@tanstack/react-store'

trimPathLeft,
trimPathRight,
} from './path'

@@ -33,3 +34,8 @@ import {

} from './route'
import { RoutesInfo, AnyRoutesInfo, RoutesById } from './routeInfo'
import {
RoutesInfo,
AnyRoutesInfo,
RoutesById,
RoutesByPath,
} from './routeInfo'
import { AnyRouteMatch, RouteMatch, RouteMatchState } from './routeMatch'

@@ -274,2 +280,4 @@ import { defaultParseSearch, defaultStringifySearch } from './searchParams'

routesById!: RoutesById<TRoutesInfo>
routesByPath!: RoutesByPath<TRoutesInfo>
flatRoutes!: TRoutesInfo['routesByFullPath'][keyof TRoutesInfo['routesByFullPath']][]
navigateTimeout: undefined | Timeout

@@ -316,6 +324,2 @@ nextAction: undefined | 'push' | 'replace'

}
if (typeof document !== 'undefined') {
this.hydrate()
}
}

@@ -375,5 +379,4 @@

if (routeTree) {
this.routesById = {} as any
this.routeTree = this.#buildRouteTree(routeTree) as RootRoute
if (routeTree && routeTree !== this.routeTree) {
this.#buildRouteTree(routeTree)
}

@@ -564,110 +567,34 @@

// If there's no route tree, we can't match anything
if (!this.routeTree) {
if (!this.flatRoutes.length) {
return []
}
// Existing matches are matches that are already loaded along with
// pending matches that are still loading
const existingMatches = [...this.state.matches]
let routeParams: AnyPathParams = {}
// We need to "flatten" layout routes, but only process as many
// routes as we need to in order to find the best match
// This mean no looping over all of the routes for the best perf.
// Time to bust out the recursion... As we iterate over the routes,
// we'll keep track of the best match thus far by pushing or popping
// it onto the `matchingRoutes` array. In the case of a layout route,
// we'll assume that it matches and just recurse into its children.
// If we come up with nothing, we'll pop it off and try the next route.
// This way the user can have as many routes, including layout routes,
// as they want without worrying about performance.
// It does make one assumption though: that route branches are ordered from
// most specific to least specific. This is a good assumption to make IMO.
// For now, we also auto-rank routes like Remix and React Router which is a neat trick
// that unfortunately requires looping over all of the routes when we build the route
// tree, but we only do that once. For the matching that will be happening more often,
// I'd rather err on the side of performance here and be able to walk the tree and
// exit early as soon as possible with as little looping/mapping as possible.
let matchingRoutesAndParams: { route: AnyRoute; params?: AnyPathParams }[] =
[]
// For any given array of branching routes, find the best route match
// and push it onto the `matchingRoutes` array
const findRoutes = (
routes: AnyRoute[],
layoutRoutes: AnyRoute[] = [],
): undefined | Route => {
let foundRoute: undefined | Route
let foundParams: undefined | AnyPathParams
// Given a list of routes, find the first route that matches
routes.some((route) => {
const children = route.children as undefined | Route[]
// If there is no path, but there are children,
// this is a layout route, so recurse again
if (!route.path && children?.length) {
const childMatch = findRoutes(children, [...layoutRoutes, route])
// If we found a child match, mark it as found
// and return true to stop the loop
if (childMatch) {
foundRoute = childMatch
foundParams = undefined
return true
}
return false
}
// If the route isn't an index route or it has children,
// fuzzy match the path
const fuzzy = route.path !== '/' || !!children?.length
const matchedParams = matchPathname(this.basepath, pathname, {
to: route.fullPath,
fuzzy,
caseSensitive:
route.options.caseSensitive ?? this.options.caseSensitive,
})
// This was a match!
if (matchedParams) {
// Let's parse the params using the route's `parseParams` function
let parsedParams
try {
parsedParams =
route.options.parseParams?.(matchedParams!) ?? matchedParams
} catch (err) {
if (opts?.strictParseParams) {
throw err
}
}
foundRoute = route
foundParams = parsedParams
return true
}
return false
let foundRoute = this.flatRoutes.find((route) => {
const matchedParams = matchPathname(this.basepath, pathname, {
to: route.fullPath,
caseSensitive:
route.options.caseSensitive ?? this.options.caseSensitive,
})
// If we didn't find a match in this route branch
// return early.
if (!foundRoute) {
return undefined
if (matchedParams) {
routeParams = matchedParams
return true
}
matchingRoutesAndParams.push(...layoutRoutes.map((d) => ({ route: d })), {
route: foundRoute,
params: foundParams,
})
return false
})
// If the found route has children, recurse again
const foundChildren = foundRoute.children as any
if (foundChildren?.length) {
return findRoutes(foundChildren)
}
if (!foundRoute) {
return []
}
return foundRoute
let matchedRoutes: AnyRoute[] = [foundRoute]
while (foundRoute?.parentRoute) {
foundRoute = foundRoute.parentRoute
if (foundRoute) matchedRoutes.unshift(foundRoute)
}
findRoutes([this.routeTree as any])
// Alright, by now we should have all of our

@@ -679,6 +606,20 @@ // matching routes and their param pairs, let's

const matches = matchingRoutesAndParams
.map(({ route, params }) => {
// Existing matches are matches that are already loaded along with
// pending matches that are still loading
const existingMatches = [...this.state.matches] as AnyRouteMatch[]
const matches = matchedRoutes
.map((route) => {
let parsedParams
try {
parsedParams =
route.options.parseParams?.(routeParams!) ?? routeParams
} catch (err) {
if (opts?.strictParseParams) {
throw err
}
}
// Add the parsed params to the accumulated params bag
Object.assign(allParams, params)
Object.assign(allParams, parsedParams)

@@ -696,8 +637,13 @@ const interpolatedPath = interpolatePath(route.path, allParams)

// around between navigation actions that only change leaf routes.
return (existingMatches.find((d) => d.id === matchId) ||
new RouteMatch(this, route, {
id: matchId,
params: allParams,
pathname: joinPaths([this.basepath, interpolatedPath]),
})) as RouteMatch
const existingMatch = existingMatches.find((d) => d.id === matchId)
if (existingMatch) {
return existingMatch
}
return new RouteMatch(this, route, {
id: matchId,
params: allParams,
pathname: joinPaths([this.basepath, interpolatedPath]),
}) as AnyRouteMatch
})

@@ -712,2 +658,4 @@ .filter((d, i, all) => {

console.log(matches)
return matches

@@ -1113,4 +1061,9 @@ }

#buildRouteTree = (routeTree: AnyRoute) => {
const recurseRoutes = (routes: Route[], parentRoute: Route | undefined) => {
#buildRouteTree = (routeTree: AnyRootRoute) => {
this.routeTree = routeTree
this.routesById = {} as any
this.routesByPath = {} as any
this.flatRoutes = [] as any
const recurseRoutes = (routes: AnyRoute[]) => {
routes.forEach((route, i) => {

@@ -1127,94 +1080,83 @@ route.init({ originalIndex: i, router: this })

if (!route.isRoot && route.path) {
const trimmedFullPath = trimPathRight(route.fullPath)
if (
!this.routesByPath[trimmedFullPath] ||
route.fullPath.endsWith('/')
) {
;(this.routesByPath as any)[trimmedFullPath] = route
}
}
const children = route.children as Route[]
if (children?.length) {
recurseRoutes(children, route)
recurseRoutes(children)
}
})
}
const range = 1 / children!.length
recurseRoutes([routeTree])
route.children = children
.map((d, i) => {
const cleaned = trimPathLeft(cleanPath(d.path ?? '/'))
const parsed = parsePathname(cleaned)
this.flatRoutes = (Object.values(this.routesByPath) as AnyRoute[])
.map((d, i) => {
const trimmed = trimPath(d.fullPath)
const parsed = parsePathname(trimmed)
while (parsed.length > 1 && parsed[0]?.value === '/') {
parsed.shift()
}
while (parsed.length > 1 && parsed[0]?.value === '/') {
parsed.shift()
}
const score = parsed.map((d) => {
if (d.type === 'param') {
return 0.5
}
if (d.type === 'wildcard') {
return 0.25
}
return 1
})
const score = parsed.map((d) => {
if (d.type === 'param') {
return 0.5
}
return { child: d, cleaned, parsed, index: i, score }
})
.sort((a, b) => {
const length = Math.min(a.score.length, b.score.length)
// Sort by min available score
for (let i = 0; i < length; i++) {
if (a.score[i] !== b.score[i]) {
return b.score[i]! - a.score[i]!
}
}
if (d.type === 'wildcard') {
return 0.25
}
// Sort by min available parsed value
for (let i = 0; i < length; i++) {
if (a.parsed[i]!.value !== b.parsed[i]!.value) {
return a.parsed[i]!.value! > b.parsed[i]!.value! ? 1 : -1
}
}
return 1
})
// Sort by length of score
if (a.score.length !== b.score.length) {
return b.score.length - a.score.length
}
return { child: d, trimmed, parsed, index: i, score }
})
.sort((a, b) => {
let isIndex = a.trimmed === '/' ? 1 : b.trimmed === '/' ? -1 : 0
// Sort by length of cleaned full path
if (a.cleaned !== b.cleaned) {
return a.cleaned > b.cleaned ? 1 : -1
}
if (isIndex !== 0) return isIndex
// Sort by original index
return a.index - b.index
})
.map((d) => {
return d.child
})
const length = Math.min(a.score.length, b.score.length)
// Sort by length of score
if (a.score.length !== b.score.length) {
return b.score.length - a.score.length
}
})
}
recurseRoutes([routeTree] as Route[], undefined)
// Sort by min available score
for (let i = 0; i < length; i++) {
if (a.score[i] !== b.score[i]) {
return b.score[i]! - a.score[i]!
}
}
const recurceCheckRoutes = (
routes: Route[],
parentRoute: Route | undefined,
) => {
routes.forEach((route) => {
if (route.isRoot) {
invariant(
!parentRoute,
'Root routes can only be used as the root of a route tree.',
)
} else {
invariant(
parentRoute ? route.parentRoute === parentRoute : true,
`Expected a route with path "${route.path}" to be passed to its parent route "${route.parentRoute?.id}" in an addChildren() call, but was instead passed as a child of the "${parentRoute?.id}" route.`,
)
// Sort by min available parsed value
for (let i = 0; i < length; i++) {
if (a.parsed[i]!.value !== b.parsed[i]!.value) {
return a.parsed[i]!.value! > b.parsed[i]!.value! ? 1 : -1
}
}
if (route.children) {
recurceCheckRoutes(route.children as Route[], route)
// Sort by length of trimmed full path
if (a.trimmed !== b.trimmed) {
return a.trimmed > b.trimmed ? 1 : -1
}
// Sort by original index
return a.index - b.index
})
}
recurceCheckRoutes([routeTree] as Route[], undefined)
return routeTree
.map((d, i) => {
d.child.rank = i
return d.child
}) as any
}

@@ -1221,0 +1163,0 @@

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc