@tanstack/react-router 1.20.0 → 1.20.3-alpha.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (320) hide show
  1. package/README.md +31 -0
  2. package/dist/cjs/Asset.cjs +41 -0
  3. package/dist/cjs/Asset.cjs.map +1 -0
  4. package/dist/cjs/Asset.d.cts +2 -0
  5. package/dist/cjs/CatchBoundary.cjs +16 -12
  6. package/dist/cjs/CatchBoundary.cjs.map +1 -1
  7. package/dist/cjs/CatchBoundary.d.cts +8 -32
  8. package/dist/cjs/ClientOnly.cjs +20 -0
  9. package/dist/cjs/ClientOnly.cjs.map +1 -0
  10. package/dist/cjs/ClientOnly.d.cts +29 -0
  11. package/dist/cjs/HeadContent.cjs +155 -0
  12. package/dist/cjs/HeadContent.cjs.map +1 -0
  13. package/dist/cjs/HeadContent.d.cts +7 -0
  14. package/dist/cjs/Match.cjs +252 -0
  15. package/dist/cjs/Match.cjs.map +1 -0
  16. package/dist/cjs/Match.d.cts +8 -0
  17. package/dist/cjs/Matches.cjs +39 -287
  18. package/dist/cjs/Matches.cjs.map +1 -1
  19. package/dist/cjs/Matches.d.cts +23 -83
  20. package/dist/cjs/RouterProvider.cjs +17 -140
  21. package/dist/cjs/RouterProvider.cjs.map +1 -1
  22. package/dist/cjs/RouterProvider.d.cts +8 -27
  23. package/dist/cjs/SafeFragment.cjs +8 -0
  24. package/dist/cjs/SafeFragment.cjs.map +1 -0
  25. package/dist/cjs/SafeFragment.d.cts +1 -0
  26. package/dist/cjs/ScriptOnce.cjs +28 -0
  27. package/dist/cjs/ScriptOnce.cjs.map +1 -0
  28. package/dist/cjs/ScriptOnce.d.cts +5 -0
  29. package/dist/cjs/Scripts.cjs +51 -0
  30. package/dist/cjs/Scripts.cjs.map +1 -0
  31. package/dist/cjs/Scripts.d.cts +1 -0
  32. package/dist/cjs/ScrollRestoration.cjs +39 -0
  33. package/dist/cjs/ScrollRestoration.cjs.map +1 -0
  34. package/dist/cjs/ScrollRestoration.d.cts +14 -0
  35. package/dist/cjs/Transitioner.cjs +115 -0
  36. package/dist/cjs/Transitioner.cjs.map +1 -0
  37. package/dist/cjs/Transitioner.d.cts +1 -0
  38. package/dist/cjs/awaited.cjs +12 -65
  39. package/dist/cjs/awaited.cjs.map +1 -1
  40. package/dist/cjs/awaited.d.cts +4 -4
  41. package/dist/cjs/fileRoute.cjs +41 -15
  42. package/dist/cjs/fileRoute.cjs.map +1 -1
  43. package/dist/cjs/fileRoute.d.cts +33 -108
  44. package/dist/cjs/history.d.cts +1 -0
  45. package/dist/cjs/index.cjs +216 -73
  46. package/dist/cjs/index.cjs.map +1 -1
  47. package/dist/cjs/index.d.cts +52 -29
  48. package/dist/cjs/lazyRouteComponent.cjs +40 -29
  49. package/dist/cjs/lazyRouteComponent.cjs.map +1 -1
  50. package/dist/cjs/lazyRouteComponent.d.cts +1 -1
  51. package/dist/cjs/link.cjs +212 -106
  52. package/dist/cjs/link.cjs.map +1 -1
  53. package/dist/cjs/link.d.cts +41 -86
  54. package/dist/cjs/matchContext.cjs +27 -0
  55. package/dist/cjs/matchContext.cjs.map +1 -0
  56. package/dist/cjs/matchContext.d.cts +3 -0
  57. package/dist/cjs/not-found.cjs +9 -15
  58. package/dist/cjs/not-found.cjs.map +1 -1
  59. package/dist/cjs/not-found.d.cts +5 -22
  60. package/dist/cjs/renderRouteNotFound.cjs +22 -0
  61. package/dist/cjs/renderRouteNotFound.cjs.map +1 -0
  62. package/dist/cjs/renderRouteNotFound.d.cts +2 -0
  63. package/dist/cjs/route.cjs +110 -79
  64. package/dist/cjs/route.cjs.map +1 -1
  65. package/dist/cjs/route.d.cts +64 -361
  66. package/dist/cjs/router.cjs +12 -1237
  67. package/dist/cjs/router.cjs.map +1 -1
  68. package/dist/cjs/router.d.cts +69 -237
  69. package/dist/cjs/routerContext.cjs +1 -1
  70. package/dist/cjs/routerContext.cjs.map +1 -1
  71. package/dist/cjs/routerContext.d.cts +7 -2
  72. package/dist/cjs/scroll-restoration.cjs +16 -177
  73. package/dist/cjs/scroll-restoration.cjs.map +1 -1
  74. package/dist/cjs/scroll-restoration.d.cts +1 -18
  75. package/dist/cjs/serializer.d.cts +6 -0
  76. package/dist/cjs/structuralSharing.d.cts +8 -0
  77. package/dist/cjs/typePrimitives.d.cts +16 -0
  78. package/dist/cjs/useBlocker.cjs +138 -9
  79. package/dist/cjs/useBlocker.cjs.map +1 -1
  80. package/dist/cjs/useBlocker.d.cts +64 -7
  81. package/dist/cjs/useCanGoBack.cjs +8 -0
  82. package/dist/cjs/useCanGoBack.cjs.map +1 -0
  83. package/dist/cjs/useCanGoBack.d.cts +1 -0
  84. package/dist/cjs/useLoaderData.cjs +15 -0
  85. package/dist/cjs/useLoaderData.cjs.map +1 -0
  86. package/dist/cjs/useLoaderData.d.cts +8 -0
  87. package/dist/cjs/useLoaderDeps.cjs +14 -0
  88. package/dist/cjs/useLoaderDeps.cjs.map +1 -0
  89. package/dist/cjs/useLoaderDeps.d.cts +8 -0
  90. package/dist/cjs/useLocation.cjs +10 -0
  91. package/dist/cjs/useLocation.cjs.map +1 -0
  92. package/dist/cjs/useLocation.d.cts +7 -0
  93. package/dist/cjs/useMatch.cjs +47 -0
  94. package/dist/cjs/useMatch.cjs.map +1 -0
  95. package/dist/cjs/useMatch.d.cts +10 -0
  96. package/dist/cjs/useNavigate.cjs +18 -19
  97. package/dist/cjs/useNavigate.cjs.map +1 -1
  98. package/dist/cjs/useNavigate.d.cts +4 -8
  99. package/dist/cjs/useParams.cjs +8 -8
  100. package/dist/cjs/useParams.cjs.map +1 -1
  101. package/dist/cjs/useParams.d.cts +9 -8
  102. package/dist/cjs/useRouteContext.cjs +3 -3
  103. package/dist/cjs/useRouteContext.cjs.map +1 -1
  104. package/dist/cjs/useRouteContext.d.cts +3 -7
  105. package/dist/cjs/useRouter.cjs.map +1 -1
  106. package/dist/cjs/useRouter.d.cts +3 -4
  107. package/dist/cjs/useRouterState.cjs +18 -1
  108. package/dist/cjs/useRouterState.cjs.map +1 -1
  109. package/dist/cjs/useRouterState.d.cts +8 -6
  110. package/dist/cjs/useSearch.cjs +7 -4
  111. package/dist/cjs/useSearch.cjs.map +1 -1
  112. package/dist/cjs/useSearch.d.cts +9 -7
  113. package/dist/cjs/utils.cjs +40 -122
  114. package/dist/cjs/utils.cjs.map +1 -1
  115. package/dist/cjs/utils.d.cts +46 -50
  116. package/dist/esm/Asset.d.ts +2 -0
  117. package/dist/esm/Asset.js +41 -0
  118. package/dist/esm/Asset.js.map +1 -0
  119. package/dist/esm/CatchBoundary.d.ts +8 -32
  120. package/dist/esm/CatchBoundary.js +16 -12
  121. package/dist/esm/CatchBoundary.js.map +1 -1
  122. package/dist/esm/ClientOnly.d.ts +29 -0
  123. package/dist/esm/ClientOnly.js +20 -0
  124. package/dist/esm/ClientOnly.js.map +1 -0
  125. package/dist/esm/HeadContent.d.ts +7 -0
  126. package/dist/esm/HeadContent.js +139 -0
  127. package/dist/esm/HeadContent.js.map +1 -0
  128. package/dist/esm/Match.d.ts +8 -0
  129. package/dist/esm/Match.js +235 -0
  130. package/dist/esm/Match.js.map +1 -0
  131. package/dist/esm/Matches.d.ts +23 -83
  132. package/dist/esm/Matches.js +36 -284
  133. package/dist/esm/Matches.js.map +1 -1
  134. package/dist/esm/RouterProvider.d.ts +8 -27
  135. package/dist/esm/RouterProvider.js +20 -126
  136. package/dist/esm/RouterProvider.js.map +1 -1
  137. package/dist/esm/SafeFragment.d.ts +1 -0
  138. package/dist/esm/SafeFragment.js +8 -0
  139. package/dist/esm/SafeFragment.js.map +1 -0
  140. package/dist/esm/ScriptOnce.d.ts +5 -0
  141. package/dist/esm/ScriptOnce.js +28 -0
  142. package/dist/esm/ScriptOnce.js.map +1 -0
  143. package/dist/esm/Scripts.d.ts +1 -0
  144. package/dist/esm/Scripts.js +51 -0
  145. package/dist/esm/Scripts.js.map +1 -0
  146. package/dist/esm/ScrollRestoration.d.ts +14 -0
  147. package/dist/esm/ScrollRestoration.js +39 -0
  148. package/dist/esm/ScrollRestoration.js.map +1 -0
  149. package/dist/esm/Transitioner.d.ts +1 -0
  150. package/dist/esm/Transitioner.js +98 -0
  151. package/dist/esm/Transitioner.js.map +1 -0
  152. package/dist/esm/awaited.d.ts +4 -4
  153. package/dist/esm/awaited.js +12 -65
  154. package/dist/esm/awaited.js.map +1 -1
  155. package/dist/esm/fileRoute.d.ts +33 -108
  156. package/dist/esm/fileRoute.js +38 -12
  157. package/dist/esm/fileRoute.js.map +1 -1
  158. package/dist/esm/history.d.ts +1 -0
  159. package/dist/esm/index.d.ts +52 -29
  160. package/dist/esm/index.js +41 -29
  161. package/dist/esm/index.js.map +1 -1
  162. package/dist/esm/lazyRouteComponent.d.ts +1 -1
  163. package/dist/esm/lazyRouteComponent.js +40 -29
  164. package/dist/esm/lazyRouteComponent.js.map +1 -1
  165. package/dist/esm/link.d.ts +41 -86
  166. package/dist/esm/link.js +212 -106
  167. package/dist/esm/link.js.map +1 -1
  168. package/dist/esm/matchContext.d.ts +3 -0
  169. package/dist/esm/matchContext.js +10 -0
  170. package/dist/esm/matchContext.js.map +1 -0
  171. package/dist/esm/not-found.d.ts +5 -22
  172. package/dist/esm/not-found.js +9 -15
  173. package/dist/esm/not-found.js.map +1 -1
  174. package/dist/esm/renderRouteNotFound.d.ts +2 -0
  175. package/dist/esm/renderRouteNotFound.js +22 -0
  176. package/dist/esm/renderRouteNotFound.js.map +1 -0
  177. package/dist/esm/route.d.ts +64 -361
  178. package/dist/esm/route.js +103 -72
  179. package/dist/esm/route.js.map +1 -1
  180. package/dist/esm/router.d.ts +69 -237
  181. package/dist/esm/router.js +13 -1238
  182. package/dist/esm/router.js.map +1 -1
  183. package/dist/esm/routerContext.d.ts +7 -2
  184. package/dist/esm/routerContext.js +1 -1
  185. package/dist/esm/routerContext.js.map +1 -1
  186. package/dist/esm/scroll-restoration.d.ts +1 -18
  187. package/dist/esm/scroll-restoration.js +17 -161
  188. package/dist/esm/scroll-restoration.js.map +1 -1
  189. package/dist/esm/serializer.d.ts +6 -0
  190. package/dist/esm/structuralSharing.d.ts +8 -0
  191. package/dist/esm/typePrimitives.d.ts +16 -0
  192. package/dist/esm/useBlocker.d.ts +64 -7
  193. package/dist/esm/useBlocker.js +138 -9
  194. package/dist/esm/useBlocker.js.map +1 -1
  195. package/dist/esm/useCanGoBack.d.ts +1 -0
  196. package/dist/esm/useCanGoBack.js +8 -0
  197. package/dist/esm/useCanGoBack.js.map +1 -0
  198. package/dist/esm/useLoaderData.d.ts +8 -0
  199. package/dist/esm/useLoaderData.js +15 -0
  200. package/dist/esm/useLoaderData.js.map +1 -0
  201. package/dist/esm/useLoaderDeps.d.ts +8 -0
  202. package/dist/esm/useLoaderDeps.js +14 -0
  203. package/dist/esm/useLoaderDeps.js.map +1 -0
  204. package/dist/esm/useLocation.d.ts +7 -0
  205. package/dist/esm/useLocation.js +10 -0
  206. package/dist/esm/useLocation.js.map +1 -0
  207. package/dist/esm/useMatch.d.ts +10 -0
  208. package/dist/esm/useMatch.js +30 -0
  209. package/dist/esm/useMatch.js.map +1 -0
  210. package/dist/esm/useNavigate.d.ts +4 -8
  211. package/dist/esm/useNavigate.js +18 -19
  212. package/dist/esm/useNavigate.js.map +1 -1
  213. package/dist/esm/useParams.d.ts +9 -8
  214. package/dist/esm/useParams.js +8 -8
  215. package/dist/esm/useParams.js.map +1 -1
  216. package/dist/esm/useRouteContext.d.ts +3 -7
  217. package/dist/esm/useRouteContext.js +2 -2
  218. package/dist/esm/useRouteContext.js.map +1 -1
  219. package/dist/esm/useRouter.d.ts +3 -4
  220. package/dist/esm/useRouter.js.map +1 -1
  221. package/dist/esm/useRouterState.d.ts +8 -6
  222. package/dist/esm/useRouterState.js +18 -1
  223. package/dist/esm/useRouterState.js.map +1 -1
  224. package/dist/esm/useSearch.d.ts +9 -7
  225. package/dist/esm/useSearch.js +6 -3
  226. package/dist/esm/useSearch.js.map +1 -1
  227. package/dist/esm/utils.d.ts +46 -50
  228. package/dist/esm/utils.js +41 -123
  229. package/dist/esm/utils.js.map +1 -1
  230. package/package.json +30 -31
  231. package/src/Asset.tsx +40 -0
  232. package/src/CatchBoundary.tsx +35 -19
  233. package/src/ClientOnly.tsx +68 -0
  234. package/src/HeadContent.tsx +174 -0
  235. package/src/Match.tsx +330 -0
  236. package/src/Matches.tsx +149 -558
  237. package/src/RouterProvider.tsx +58 -212
  238. package/src/SafeFragment.tsx +5 -0
  239. package/src/ScriptOnce.tsx +32 -0
  240. package/src/Scripts.tsx +65 -0
  241. package/src/ScrollRestoration.tsx +69 -0
  242. package/src/Transitioner.tsx +130 -0
  243. package/src/awaited.tsx +16 -87
  244. package/src/fileRoute.ts +145 -248
  245. package/src/history.ts +2 -1
  246. package/src/index.tsx +368 -30
  247. package/src/lazyRouteComponent.tsx +68 -54
  248. package/src/link.tsx +397 -522
  249. package/src/matchContext.tsx +8 -0
  250. package/src/not-found.tsx +13 -34
  251. package/src/renderRouteNotFound.tsx +27 -0
  252. package/src/route.tsx +572 -0
  253. package/src/router.ts +99 -2067
  254. package/src/routerContext.tsx +8 -2
  255. package/src/scroll-restoration.tsx +23 -224
  256. package/src/serializer.ts +7 -0
  257. package/src/structuralSharing.ts +47 -0
  258. package/src/typePrimitives.ts +84 -0
  259. package/src/useBlocker.tsx +297 -15
  260. package/src/useCanGoBack.ts +5 -0
  261. package/src/useLoaderData.tsx +80 -0
  262. package/src/useLoaderDeps.tsx +58 -0
  263. package/src/useLocation.tsx +41 -0
  264. package/src/useMatch.tsx +119 -0
  265. package/src/useNavigate.tsx +41 -61
  266. package/src/useParams.tsx +88 -23
  267. package/src/useRouteContext.ts +24 -18
  268. package/src/useRouter.tsx +4 -5
  269. package/src/useRouterState.tsx +52 -10
  270. package/src/useSearch.tsx +87 -24
  271. package/src/utils.ts +97 -312
  272. package/dist/cjs/createServerFn.cjs +0 -40
  273. package/dist/cjs/createServerFn.cjs.map +0 -1
  274. package/dist/cjs/createServerFn.d.cts +0 -44
  275. package/dist/cjs/defer.cjs +0 -30
  276. package/dist/cjs/defer.cjs.map +0 -1
  277. package/dist/cjs/defer.d.cts +0 -25
  278. package/dist/cjs/location.d.cts +0 -12
  279. package/dist/cjs/path.cjs +0 -213
  280. package/dist/cjs/path.cjs.map +0 -1
  281. package/dist/cjs/path.d.cts +0 -24
  282. package/dist/cjs/qss.cjs +0 -45
  283. package/dist/cjs/qss.cjs.map +0 -1
  284. package/dist/cjs/qss.d.cts +0 -2
  285. package/dist/cjs/redirects.cjs +0 -16
  286. package/dist/cjs/redirects.cjs.map +0 -1
  287. package/dist/cjs/redirects.d.cts +0 -18
  288. package/dist/cjs/routeInfo.d.cts +0 -33
  289. package/dist/cjs/searchParams.cjs +0 -63
  290. package/dist/cjs/searchParams.cjs.map +0 -1
  291. package/dist/cjs/searchParams.d.cts +0 -7
  292. package/dist/esm/createServerFn.d.ts +0 -44
  293. package/dist/esm/createServerFn.js +0 -40
  294. package/dist/esm/createServerFn.js.map +0 -1
  295. package/dist/esm/defer.d.ts +0 -25
  296. package/dist/esm/defer.js +0 -30
  297. package/dist/esm/defer.js.map +0 -1
  298. package/dist/esm/location.d.ts +0 -12
  299. package/dist/esm/path.d.ts +0 -24
  300. package/dist/esm/path.js +0 -213
  301. package/dist/esm/path.js.map +0 -1
  302. package/dist/esm/qss.d.ts +0 -2
  303. package/dist/esm/qss.js +0 -45
  304. package/dist/esm/qss.js.map +0 -1
  305. package/dist/esm/redirects.d.ts +0 -18
  306. package/dist/esm/redirects.js +0 -16
  307. package/dist/esm/redirects.js.map +0 -1
  308. package/dist/esm/routeInfo.d.ts +0 -33
  309. package/dist/esm/searchParams.d.ts +0 -7
  310. package/dist/esm/searchParams.js +0 -63
  311. package/dist/esm/searchParams.js.map +0 -1
  312. package/src/createServerFn.ts +0 -107
  313. package/src/defer.ts +0 -70
  314. package/src/location.ts +0 -13
  315. package/src/path.ts +0 -280
  316. package/src/qss.ts +0 -53
  317. package/src/redirects.ts +0 -56
  318. package/src/route.ts +0 -1356
  319. package/src/routeInfo.ts +0 -62
  320. package/src/searchParams.ts +0 -79
@@ -1,1247 +1,22 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
3
- const history = require("@tanstack/history");
4
- const reactStore = require("@tanstack/react-store");
5
- const route = require("./route.cjs");
6
- const searchParams = require("./searchParams.cjs");
7
- const utils = require("./utils.cjs");
8
- const RouterProvider = require("./RouterProvider.cjs");
9
- const path = require("./path.cjs");
10
- const invariant = require("tiny-invariant");
11
- const redirects = require("./redirects.cjs");
12
- const notFound = require("./not-found.cjs");
13
- const warning = require("tiny-warning");
14
- const componentTypes = [
15
- "component",
16
- "errorComponent",
17
- "pendingComponent",
18
- "notFoundComponent"
19
- ];
20
- function createRouter(options) {
3
+ const routerCore = require("@tanstack/router-core");
4
+ const fileRoute = require("./fileRoute.cjs");
5
+ const createRouter = (options) => {
21
6
  return new Router(options);
22
- }
23
- class Router {
24
- /**
25
- * @deprecated Use the `createRouter` function instead
26
- */
7
+ };
8
+ class Router extends routerCore.RouterCore {
27
9
  constructor(options) {
28
- this.tempLocationKey = `${Math.round(
29
- Math.random() * 1e7
30
- )}`;
31
- this.resetNextScroll = true;
32
- this.navigateTimeout = null;
33
- this.latestLoadPromise = Promise.resolve();
34
- this.subscribers = /* @__PURE__ */ new Set();
35
- this.injectedHtml = [];
36
- this.startReactTransition = (fn) => fn();
37
- this.update = (newOptions) => {
38
- if (newOptions.notFoundRoute) {
39
- console.warn(
40
- "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."
41
- );
42
- }
43
- const previousOptions = this.options;
44
- this.options = {
45
- ...this.options,
46
- ...newOptions
47
- };
48
- if (!this.basepath || newOptions.basepath && newOptions.basepath !== previousOptions.basepath) {
49
- if (newOptions.basepath === void 0 || newOptions.basepath === "" || newOptions.basepath === "/") {
50
- this.basepath = "/";
51
- } else {
52
- this.basepath = `/${path.trimPath(newOptions.basepath)}`;
53
- }
54
- }
55
- if (!this.history || this.options.history && this.options.history !== this.history) {
56
- this.history = this.options.history ?? (typeof document !== "undefined" ? history.createBrowserHistory() : history.createMemoryHistory({
57
- initialEntries: [this.options.basepath || "/"]
58
- }));
59
- this.latestLocation = this.parseLocation();
60
- }
61
- if (this.options.routeTree !== this.routeTree) {
62
- this.routeTree = this.options.routeTree;
63
- this.buildRouteTree();
64
- }
65
- if (!this.__store) {
66
- this.__store = new reactStore.Store(getInitialRouterState(this.latestLocation), {
67
- onUpdate: () => {
68
- this.__store.state = {
69
- ...this.state,
70
- status: this.state.isTransitioning || this.state.isLoading ? "pending" : "idle",
71
- cachedMatches: this.state.cachedMatches.filter(
72
- (d) => !["redirected"].includes(d.status)
73
- )
74
- };
75
- }
76
- });
77
- }
78
- };
79
- this.buildRouteTree = () => {
80
- this.routesById = {};
81
- this.routesByPath = {};
82
- const notFoundRoute = this.options.notFoundRoute;
83
- if (notFoundRoute) {
84
- notFoundRoute.init({ originalIndex: 99999999999 });
85
- this.routesById[notFoundRoute.id] = notFoundRoute;
86
- }
87
- const recurseRoutes = (childRoutes) => {
88
- childRoutes.forEach((childRoute, i) => {
89
- childRoute.init({ originalIndex: i });
90
- const existingRoute = this.routesById[childRoute.id];
91
- invariant(
92
- !existingRoute,
93
- `Duplicate routes found with id: ${String(childRoute.id)}`
94
- );
95
- this.routesById[childRoute.id] = childRoute;
96
- if (!childRoute.isRoot && childRoute.path) {
97
- const trimmedFullPath = path.trimPathRight(childRoute.fullPath);
98
- if (!this.routesByPath[trimmedFullPath] || childRoute.fullPath.endsWith("/")) {
99
- this.routesByPath[trimmedFullPath] = childRoute;
100
- }
101
- }
102
- const children = childRoute.children;
103
- if (children == null ? void 0 : children.length) {
104
- recurseRoutes(children);
105
- }
106
- });
107
- };
108
- recurseRoutes([this.routeTree]);
109
- const scoredRoutes = [];
110
- Object.values(this.routesById).forEach((d, i) => {
111
- var _a;
112
- if (d.isRoot || !d.path) {
113
- return;
114
- }
115
- const trimmed = path.trimPathLeft(d.fullPath);
116
- const parsed = path.parsePathname(trimmed);
117
- while (parsed.length > 1 && ((_a = parsed[0]) == null ? void 0 : _a.value) === "/") {
118
- parsed.shift();
119
- }
120
- const scores = parsed.map((d2) => {
121
- if (d2.value === "/") {
122
- return 0.75;
123
- }
124
- if (d2.type === "param") {
125
- return 0.5;
126
- }
127
- if (d2.type === "wildcard") {
128
- return 0.25;
129
- }
130
- return 1;
131
- });
132
- scoredRoutes.push({ child: d, trimmed, parsed, index: i, scores });
133
- });
134
- this.flatRoutes = scoredRoutes.sort((a, b) => {
135
- const minLength = Math.min(a.scores.length, b.scores.length);
136
- for (let i = 0; i < minLength; i++) {
137
- if (a.scores[i] !== b.scores[i]) {
138
- return b.scores[i] - a.scores[i];
139
- }
140
- }
141
- if (a.scores.length !== b.scores.length) {
142
- return b.scores.length - a.scores.length;
143
- }
144
- for (let i = 0; i < minLength; i++) {
145
- if (a.parsed[i].value !== b.parsed[i].value) {
146
- return a.parsed[i].value > b.parsed[i].value ? 1 : -1;
147
- }
148
- }
149
- return a.index - b.index;
150
- }).map((d, i) => {
151
- d.child.rank = i;
152
- return d.child;
153
- });
154
- };
155
- this.subscribe = (eventType, fn) => {
156
- const listener = {
157
- eventType,
158
- fn
159
- };
160
- this.subscribers.add(listener);
161
- return () => {
162
- this.subscribers.delete(listener);
163
- };
164
- };
165
- this.emit = (routerEvent) => {
166
- this.subscribers.forEach((listener) => {
167
- if (listener.eventType === routerEvent.type) {
168
- listener.fn(routerEvent);
169
- }
170
- });
171
- };
172
- this.checkLatest = (promise) => {
173
- return this.latestLoadPromise !== promise ? this.latestLoadPromise : void 0;
174
- };
175
- this.parseLocation = (previousLocation) => {
176
- const parse = ({
177
- pathname,
178
- search,
179
- hash,
180
- state
181
- }) => {
182
- const parsedSearch = this.options.parseSearch(search);
183
- const searchStr = this.options.stringifySearch(parsedSearch);
184
- return {
185
- pathname,
186
- searchStr,
187
- search: utils.replaceEqualDeep(previousLocation == null ? void 0 : previousLocation.search, parsedSearch),
188
- hash: hash.split("#").reverse()[0] ?? "",
189
- href: `${pathname}${searchStr}${hash}`,
190
- state: utils.replaceEqualDeep(previousLocation == null ? void 0 : previousLocation.state, state)
191
- };
192
- };
193
- const location = parse(this.history.location);
194
- let { __tempLocation, __tempKey } = location.state;
195
- if (__tempLocation && (!__tempKey || __tempKey === this.tempLocationKey)) {
196
- const parsedTempLocation = parse(__tempLocation);
197
- parsedTempLocation.state.key = location.state.key;
198
- delete parsedTempLocation.state.__tempLocation;
199
- return {
200
- ...parsedTempLocation,
201
- maskedLocation: location
202
- };
203
- }
204
- return location;
205
- };
206
- this.resolvePathWithBase = (from, path$1) => {
207
- return path.resolvePath(this.basepath, from, path.cleanPath(path$1));
208
- };
209
- this.matchRoutes = (pathname, locationSearch, opts) => {
210
- let routeParams = {};
211
- let foundRoute = this.flatRoutes.find((route2) => {
212
- const matchedParams = path.matchPathname(
213
- this.basepath,
214
- path.trimPathRight(pathname),
215
- {
216
- to: route2.fullPath,
217
- caseSensitive: route2.options.caseSensitive ?? this.options.caseSensitive,
218
- fuzzy: true
219
- }
220
- );
221
- if (matchedParams) {
222
- routeParams = matchedParams;
223
- return true;
224
- }
225
- return false;
226
- });
227
- let routeCursor = foundRoute || this.routesById[route.rootRouteId];
228
- let matchedRoutes = [routeCursor];
229
- let isGlobalNotFound = false;
230
- if (
231
- // If we found a route, and it's not an index route and we have left over path
232
- foundRoute ? foundRoute.path !== "/" && routeParams["**"] : (
233
- // Or if we didn't find a route and we have left over path
234
- path.trimPathRight(pathname)
235
- )
236
- ) {
237
- if (this.options.notFoundRoute) {
238
- matchedRoutes.push(this.options.notFoundRoute);
239
- } else {
240
- isGlobalNotFound = true;
241
- }
242
- }
243
- while (routeCursor == null ? void 0 : routeCursor.parentRoute) {
244
- routeCursor = routeCursor.parentRoute;
245
- if (routeCursor)
246
- matchedRoutes.unshift(routeCursor);
247
- }
248
- const globalNotFoundRouteId = (() => {
249
- if (!isGlobalNotFound) {
250
- return void 0;
251
- }
252
- if (this.options.notFoundMode !== "root") {
253
- for (let i = matchedRoutes.length - 1; i >= 0; i--) {
254
- const route2 = matchedRoutes[i];
255
- if (route2.children) {
256
- return route2.id;
257
- }
258
- }
259
- }
260
- return route.rootRouteId;
261
- })();
262
- const parseErrors = matchedRoutes.map((route2) => {
263
- let parsedParamsError;
264
- if (route2.options.parseParams) {
265
- try {
266
- const parsedParams = route2.options.parseParams(routeParams);
267
- Object.assign(routeParams, parsedParams);
268
- } catch (err) {
269
- parsedParamsError = new PathParamError(err.message, {
270
- cause: err
271
- });
272
- if (opts == null ? void 0 : opts.throwOnError) {
273
- throw parsedParamsError;
274
- }
275
- return parsedParamsError;
276
- }
277
- }
278
- return;
279
- });
280
- const matches = [];
281
- matchedRoutes.forEach((route2, index) => {
282
- var _a, _b, _c, _d, _e, _f;
283
- const parentMatch = matches[index - 1];
284
- const [preMatchSearch, searchError] = (() => {
285
- const parentSearch = (parentMatch == null ? void 0 : parentMatch.search) ?? locationSearch;
286
- try {
287
- const validator = typeof route2.options.validateSearch === "object" ? route2.options.validateSearch.parse : route2.options.validateSearch;
288
- let search = (validator == null ? void 0 : validator(parentSearch)) ?? {};
289
- return [
290
- {
291
- ...parentSearch,
292
- ...search
293
- },
294
- void 0
295
- ];
296
- } catch (err) {
297
- const searchError2 = new SearchParamError(err.message, {
298
- cause: err
299
- });
300
- if (opts == null ? void 0 : opts.throwOnError) {
301
- throw searchError2;
302
- }
303
- return [parentSearch, searchError2];
304
- }
305
- })();
306
- const loaderDeps = ((_b = (_a = route2.options).loaderDeps) == null ? void 0 : _b.call(_a, {
307
- search: preMatchSearch
308
- })) ?? "";
309
- const loaderDepsHash = loaderDeps ? JSON.stringify(loaderDeps) : "";
310
- const interpolatedPath = path.interpolatePath({
311
- path: route2.fullPath,
312
- params: routeParams
313
- });
314
- const matchId = path.interpolatePath({
315
- path: route2.id,
316
- params: routeParams,
317
- leaveWildcards: true
318
- }) + loaderDepsHash;
319
- let existingMatch = RouterProvider.getRouteMatch(this.state, matchId);
320
- const cause = this.state.matches.find((d) => d.id === matchId) ? "stay" : "enter";
321
- const match = existingMatch ? {
322
- ...existingMatch,
323
- cause,
324
- params: routeParams
325
- } : {
326
- id: matchId,
327
- routeId: route2.id,
328
- params: routeParams,
329
- pathname: path.joinPaths([this.basepath, interpolatedPath]),
330
- updatedAt: Date.now(),
331
- search: {},
332
- searchError: void 0,
333
- status: "pending",
334
- showPending: false,
335
- isFetching: false,
336
- error: void 0,
337
- paramsError: parseErrors[index],
338
- loadPromise: Promise.resolve(),
339
- routeContext: void 0,
340
- context: void 0,
341
- abortController: new AbortController(),
342
- fetchCount: 0,
343
- cause,
344
- loaderDeps,
345
- invalid: false,
346
- preload: false,
347
- links: (_d = (_c = route2.options).links) == null ? void 0 : _d.call(_c),
348
- scripts: (_f = (_e = route2.options).scripts) == null ? void 0 : _f.call(_e),
349
- staticData: route2.options.staticData || {}
350
- };
351
- if (!(opts == null ? void 0 : opts.preload)) {
352
- match.globalNotFound = globalNotFoundRouteId === route2.id;
353
- }
354
- match.search = utils.replaceEqualDeep(match.search, preMatchSearch);
355
- match.searchError = searchError;
356
- matches.push(match);
357
- });
358
- return matches;
359
- };
360
- this.cancelMatch = (id) => {
361
- };
362
- this.cancelMatches = () => {
363
- var _a;
364
- (_a = this.state.pendingMatches) == null ? void 0 : _a.forEach((match) => {
365
- this.cancelMatch(match.id);
366
- });
367
- };
368
- this.buildLocation = (opts) => {
369
- const build = (dest = {}, matches) => {
370
- var _a, _b, _c;
371
- const relevantMatches = this.state.pendingMatches || this.state.matches;
372
- const fromSearch = ((_a = relevantMatches[relevantMatches.length - 1]) == null ? void 0 : _a.search) || this.latestLocation.search;
373
- const fromMatches = this.matchRoutes(
374
- this.latestLocation.pathname,
375
- fromSearch
376
- );
377
- const stayingMatches = matches == null ? void 0 : matches.filter(
378
- (d) => fromMatches == null ? void 0 : fromMatches.find((e) => e.routeId === d.routeId)
379
- );
380
- const fromRoute = this.looseRoutesById[(_b = utils.last(fromMatches)) == null ? void 0 : _b.routeId];
381
- let pathname = dest.to ? this.resolvePathWithBase(
382
- dest.from ?? this.latestLocation.pathname,
383
- `${dest.to}`
384
- ) : this.resolvePathWithBase(fromRoute == null ? void 0 : fromRoute.fullPath, fromRoute == null ? void 0 : fromRoute.fullPath);
385
- const prevParams = { ...(_c = utils.last(fromMatches)) == null ? void 0 : _c.params };
386
- let nextParams = (dest.params ?? true) === true ? prevParams : { ...prevParams, ...utils.functionalUpdate(dest.params, prevParams) };
387
- if (Object.keys(nextParams).length > 0) {
388
- matches == null ? void 0 : matches.map((d) => this.looseRoutesById[d.routeId].options.stringifyParams).filter(Boolean).forEach((fn) => {
389
- nextParams = { ...nextParams, ...fn(nextParams) };
390
- });
391
- }
392
- pathname = path.interpolatePath({
393
- path: pathname,
394
- params: nextParams ?? {},
395
- leaveWildcards: false,
396
- leaveParams: opts.leaveParams
397
- });
398
- const preSearchFilters = (stayingMatches == null ? void 0 : stayingMatches.map(
399
- (match) => this.looseRoutesById[match.routeId].options.preSearchFilters ?? []
400
- ).flat().filter(Boolean)) ?? [];
401
- const postSearchFilters = (stayingMatches == null ? void 0 : stayingMatches.map(
402
- (match) => this.looseRoutesById[match.routeId].options.postSearchFilters ?? []
403
- ).flat().filter(Boolean)) ?? [];
404
- const preFilteredSearch = (preSearchFilters == null ? void 0 : preSearchFilters.length) ? preSearchFilters == null ? void 0 : preSearchFilters.reduce(
405
- (prev, next) => next(prev),
406
- fromSearch
407
- ) : fromSearch;
408
- const destSearch = dest.search === true ? preFilteredSearch : dest.search ? utils.functionalUpdate(dest.search, preFilteredSearch) ?? {} : (preSearchFilters == null ? void 0 : preSearchFilters.length) ? preFilteredSearch : {};
409
- const postFilteredSearch = (postSearchFilters == null ? void 0 : postSearchFilters.length) ? postSearchFilters.reduce((prev, next) => next(prev), destSearch) : destSearch;
410
- const search = utils.replaceEqualDeep(fromSearch, postFilteredSearch);
411
- const searchStr = this.options.stringifySearch(search);
412
- const hash = dest.hash === true ? this.latestLocation.hash : dest.hash ? utils.functionalUpdate(dest.hash, this.latestLocation.hash) : void 0;
413
- const hashStr = hash ? `#${hash}` : "";
414
- let nextState = dest.state === true ? this.latestLocation.state : dest.state ? utils.functionalUpdate(dest.state, this.latestLocation.state) : {};
415
- nextState = utils.replaceEqualDeep(this.latestLocation.state, nextState);
416
- return {
417
- pathname,
418
- search,
419
- searchStr,
420
- state: nextState,
421
- hash: hash ?? "",
422
- href: `${pathname}${searchStr}${hashStr}`,
423
- unmaskOnReload: dest.unmaskOnReload
424
- };
425
- };
426
- const buildWithMatches = (dest = {}, maskedDest) => {
427
- var _a;
428
- let next = build(dest);
429
- let maskedNext = maskedDest ? build(maskedDest) : void 0;
430
- if (!maskedNext) {
431
- let params = {};
432
- let foundMask = (_a = this.options.routeMasks) == null ? void 0 : _a.find((d) => {
433
- const match = path.matchPathname(this.basepath, next.pathname, {
434
- to: d.from,
435
- caseSensitive: false,
436
- fuzzy: false
437
- });
438
- if (match) {
439
- params = match;
440
- return true;
441
- }
442
- return false;
443
- });
444
- if (foundMask) {
445
- maskedDest = {
446
- ...utils.pick(opts, ["from"]),
447
- ...foundMask,
448
- params
449
- };
450
- maskedNext = build(maskedDest);
451
- }
452
- }
453
- const nextMatches = this.matchRoutes(next.pathname, next.search);
454
- const maskedMatches = maskedNext ? this.matchRoutes(maskedNext.pathname, maskedNext.search) : void 0;
455
- const maskedFinal = maskedNext ? build(maskedDest, maskedMatches) : void 0;
456
- const final = build(dest, nextMatches);
457
- if (maskedFinal) {
458
- final.maskedLocation = maskedFinal;
459
- }
460
- return final;
461
- };
462
- if (opts.mask) {
463
- return buildWithMatches(opts, {
464
- ...utils.pick(opts, ["from"]),
465
- ...opts.mask
466
- });
467
- }
468
- return buildWithMatches(opts);
469
- };
470
- this.commitLocation = async ({
471
- startTransition,
472
- ...next
473
- }) => {
474
- if (this.navigateTimeout)
475
- clearTimeout(this.navigateTimeout);
476
- const isSameUrl = this.latestLocation.href === next.href;
477
- if (!isSameUrl) {
478
- let { maskedLocation, ...nextHistory } = next;
479
- if (maskedLocation) {
480
- nextHistory = {
481
- ...maskedLocation,
482
- state: {
483
- ...maskedLocation.state,
484
- __tempKey: void 0,
485
- __tempLocation: {
486
- ...nextHistory,
487
- search: nextHistory.searchStr,
488
- state: {
489
- ...nextHistory.state,
490
- __tempKey: void 0,
491
- __tempLocation: void 0,
492
- key: void 0
493
- }
494
- }
495
- }
496
- };
497
- if (nextHistory.unmaskOnReload ?? this.options.unmaskOnReload ?? false) {
498
- nextHistory.state.__tempKey = this.tempLocationKey;
499
- }
500
- }
501
- const apply = () => {
502
- this.history[next.replace ? "replace" : "push"](
503
- nextHistory.href,
504
- nextHistory.state
505
- );
506
- };
507
- if (startTransition ?? true) {
508
- this.startReactTransition(apply);
509
- } else {
510
- apply();
511
- }
512
- }
513
- this.resetNextScroll = next.resetScroll ?? true;
514
- return this.latestLoadPromise;
515
- };
516
- this.buildAndCommitLocation = ({
517
- replace,
518
- resetScroll,
519
- startTransition,
520
- ...rest
521
- } = {}) => {
522
- const location = this.buildLocation(rest);
523
- return this.commitLocation({
524
- ...location,
525
- startTransition,
526
- replace,
527
- resetScroll
528
- });
529
- };
530
- this.navigate = ({ from, to, ...rest }) => {
531
- const toString = String(to);
532
- let isExternal;
533
- try {
534
- new URL(`${toString}`);
535
- isExternal = true;
536
- } catch (e) {
537
- }
538
- invariant(
539
- !isExternal,
540
- "Attempting to navigate to external url with this.navigate!"
541
- );
542
- return this.buildAndCommitLocation({
543
- ...rest,
544
- from,
545
- to
546
- // to: toString,
547
- });
548
- };
549
- this.loadMatches = async ({
550
- checkLatest,
551
- location,
552
- matches,
553
- preload
554
- }) => {
555
- var _a, _b;
556
- let latestPromise;
557
- let firstBadMatchIndex;
558
- const updateMatch = (match, opts) => {
559
- var _a2;
560
- const isPending = (_a2 = this.state.pendingMatches) == null ? void 0 : _a2.find(
561
- (d) => d.id === match.id
562
- );
563
- const isMatched = this.state.matches.find((d) => d.id === match.id);
564
- const matchesKey = isPending ? "pendingMatches" : isMatched ? "matches" : "cachedMatches";
565
- this.__store.setState((s) => {
566
- var _a3, _b2;
567
- return {
568
- ...s,
569
- [matchesKey]: (opts == null ? void 0 : opts.remove) ? (_a3 = s[matchesKey]) == null ? void 0 : _a3.filter((d) => d.id !== match.id) : (_b2 = s[matchesKey]) == null ? void 0 : _b2.map((d) => d.id === match.id ? match : d)
570
- };
571
- });
572
- };
573
- const handleMatchSpecialError = (match, err) => {
574
- match = {
575
- ...match,
576
- status: redirects.isRedirect(err) ? "redirected" : notFound.isNotFound(err) ? "notFound" : "error",
577
- isFetching: false,
578
- error: err
579
- };
580
- updateMatch(match);
581
- if (!err.routeId) {
582
- err.routeId = match.routeId;
583
- }
584
- throw err;
585
- };
586
- for (let [index, match] of matches.entries()) {
587
- const parentMatch = matches[index - 1];
588
- const route2 = this.looseRoutesById[match.routeId];
589
- const abortController = new AbortController();
590
- const handleSerialError = (err, code) => {
591
- var _a2, _b2;
592
- err.routerCode = code;
593
- firstBadMatchIndex = firstBadMatchIndex ?? index;
594
- if (redirects.isRedirect(err) || notFound.isNotFound(err)) {
595
- handleMatchSpecialError(match, err);
596
- }
597
- try {
598
- (_b2 = (_a2 = route2.options).onError) == null ? void 0 : _b2.call(_a2, err);
599
- } catch (errorHandlerErr) {
600
- err = errorHandlerErr;
601
- if (redirects.isRedirect(err) || notFound.isNotFound(err)) {
602
- handleMatchSpecialError(match, errorHandlerErr);
603
- }
604
- }
605
- matches[index] = match = {
606
- ...match,
607
- error: err,
608
- status: "error",
609
- updatedAt: Date.now(),
610
- abortController: new AbortController()
611
- };
612
- };
613
- if (match.paramsError) {
614
- handleSerialError(match.paramsError, "PARSE_PARAMS");
615
- }
616
- if (match.searchError) {
617
- handleSerialError(match.searchError, "VALIDATE_SEARCH");
618
- }
619
- try {
620
- const parentContext = (parentMatch == null ? void 0 : parentMatch.context) ?? this.options.context ?? {};
621
- const pendingMs = route2.options.pendingMs ?? this.options.defaultPendingMs;
622
- const pendingPromise = typeof pendingMs === "number" && pendingMs <= 0 ? Promise.resolve() : new Promise((r) => setTimeout(r, pendingMs));
623
- const beforeLoadContext = await ((_b = (_a = route2.options).beforeLoad) == null ? void 0 : _b.call(_a, {
624
- search: match.search,
625
- abortController,
626
- params: match.params,
627
- preload: !!preload,
628
- context: parentContext,
629
- location,
630
- navigate: (opts) => this.navigate({ ...opts, from: match.pathname }),
631
- buildLocation: this.buildLocation,
632
- cause: preload ? "preload" : match.cause
633
- })) ?? {};
634
- if (redirects.isRedirect(beforeLoadContext) || notFound.isNotFound(beforeLoadContext)) {
635
- handleSerialError(beforeLoadContext, "BEFORE_LOAD");
636
- }
637
- const context = {
638
- ...parentContext,
639
- ...beforeLoadContext
640
- };
641
- matches[index] = match = {
642
- ...match,
643
- routeContext: utils.replaceEqualDeep(match.routeContext, beforeLoadContext),
644
- context: utils.replaceEqualDeep(match.context, context),
645
- abortController,
646
- pendingPromise
647
- };
648
- } catch (err) {
649
- handleSerialError(err, "BEFORE_LOAD");
650
- break;
651
- }
652
- }
653
- const validResolvedMatches = matches.slice(0, firstBadMatchIndex);
654
- const matchPromises = [];
655
- validResolvedMatches.forEach((match, index) => {
656
- matchPromises.push(
657
- new Promise(async (resolve, reject) => {
658
- var _a2;
659
- const parentMatchPromise = matchPromises[index - 1];
660
- const route2 = this.looseRoutesById[match.routeId];
661
- const handleError = (err) => {
662
- if (redirects.isRedirect(err) || notFound.isNotFound(err)) {
663
- handleMatchSpecialError(match, err);
664
- }
665
- };
666
- let loadPromise;
667
- matches[index] = match = {
668
- ...match,
669
- showPending: false
670
- };
671
- let didShowPending = false;
672
- const pendingMs = route2.options.pendingMs ?? this.options.defaultPendingMs;
673
- const pendingMinMs = route2.options.pendingMinMs ?? this.options.defaultPendingMinMs;
674
- const loaderContext = {
675
- params: match.params,
676
- deps: match.loaderDeps,
677
- preload: !!preload,
678
- parentMatchPromise,
679
- abortController: match.abortController,
680
- context: match.context,
681
- location,
682
- navigate: (opts) => this.navigate({ ...opts, from: match.pathname }),
683
- cause: preload ? "preload" : match.cause,
684
- route: route2
685
- };
686
- const fetch = async () => {
687
- var _a3, _b2, _c, _d, _e, _f, _g, _h, _i, _j;
688
- try {
689
- if (match.isFetching) {
690
- loadPromise = (_a3 = RouterProvider.getRouteMatch(this.state, match.id)) == null ? void 0 : _a3.loadPromise;
691
- } else {
692
- matches[index] = match = {
693
- ...match,
694
- isFetching: true,
695
- fetchCount: match.fetchCount + 1
696
- };
697
- const lazyPromise = ((_b2 = route2.lazyFn) == null ? void 0 : _b2.call(route2).then((lazyRoute) => {
698
- Object.assign(route2.options, lazyRoute.options);
699
- })) || Promise.resolve();
700
- const componentsPromise = lazyPromise.then(
701
- () => Promise.all(
702
- componentTypes.map(async (type) => {
703
- const component = route2.options[type];
704
- if (component == null ? void 0 : component.preload) {
705
- await component.preload();
706
- }
707
- })
708
- )
709
- );
710
- const loaderPromise = (_d = (_c = route2.options).loader) == null ? void 0 : _d.call(_c, loaderContext);
711
- loadPromise = Promise.all([
712
- componentsPromise,
713
- loaderPromise,
714
- lazyPromise
715
- ]).then((d) => d[1]);
716
- }
717
- matches[index] = match = {
718
- ...match,
719
- loadPromise
720
- };
721
- updateMatch(match);
722
- const loaderData = await loadPromise;
723
- if (latestPromise = checkLatest())
724
- return await latestPromise;
725
- handleError(loaderData);
726
- if (didShowPending && pendingMinMs) {
727
- await new Promise((r) => setTimeout(r, pendingMinMs));
728
- }
729
- if (latestPromise = checkLatest())
730
- return await latestPromise;
731
- const [meta, headers] = await Promise.all([
732
- (_f = (_e = route2.options).meta) == null ? void 0 : _f.call(_e, {
733
- params: match.params,
734
- loaderData
735
- }),
736
- (_h = (_g = route2.options).headers) == null ? void 0 : _h.call(_g, {
737
- loaderData
738
- })
739
- ]);
740
- matches[index] = match = {
741
- ...match,
742
- error: void 0,
743
- status: "success",
744
- isFetching: false,
745
- updatedAt: Date.now(),
746
- loaderData,
747
- loadPromise: void 0,
748
- meta,
749
- headers
750
- };
751
- } catch (error) {
752
- if (latestPromise = checkLatest())
753
- return await latestPromise;
754
- handleError(error);
755
- try {
756
- (_j = (_i = route2.options).onError) == null ? void 0 : _j.call(_i, error);
757
- } catch (onErrorError) {
758
- error = onErrorError;
759
- handleError(onErrorError);
760
- }
761
- matches[index] = match = {
762
- ...match,
763
- error,
764
- status: "error",
765
- isFetching: false
766
- };
767
- }
768
- updateMatch(match);
769
- };
770
- const age = Date.now() - match.updatedAt;
771
- let staleAge = preload ? route2.options.preloadStaleTime ?? this.options.defaultPreloadStaleTime ?? 3e4 : route2.options.staleTime ?? this.options.defaultStaleTime ?? 0;
772
- let shouldReload;
773
- const shouldReloadOption = route2.options.shouldReload;
774
- shouldReload = typeof shouldReloadOption === "function" ? shouldReloadOption(loaderContext) : shouldReloadOption;
775
- matches[index] = match = {
776
- ...match,
777
- preload: !!preload && !this.state.matches.find((d) => d.id === match.id)
778
- };
779
- if (match.status === "success" && (match.invalid || (shouldReload ?? age > staleAge))) {
780
- (async () => {
781
- try {
782
- await fetch();
783
- } catch (err) {
784
- console.info("Background Fetching Error", err);
785
- if (redirects.isRedirect(err)) {
786
- (this.state.pendingMatches || this.state.matches).find((d) => d.id === match.id);
787
- handleError(err);
788
- invariant(
789
- false,
790
- "You need to redirect from a background fetch? This is not supported yet. File an issue."
791
- );
792
- }
793
- }
794
- })();
795
- return resolve();
796
- }
797
- const shouldPending = !preload && typeof pendingMs === "number" && (route2.options.pendingComponent ?? this.options.defaultPendingComponent);
798
- if (match.status !== "success") {
799
- try {
800
- if (shouldPending) {
801
- (_a2 = match.pendingPromise) == null ? void 0 : _a2.then(async () => {
802
- if (latestPromise = checkLatest())
803
- return latestPromise;
804
- didShowPending = true;
805
- matches[index] = match = {
806
- ...match,
807
- showPending: true
808
- };
809
- updateMatch(match);
810
- resolve();
811
- });
812
- }
813
- await fetch();
814
- } catch (err) {
815
- reject(err);
816
- }
817
- }
818
- resolve();
819
- })
820
- );
821
- });
822
- await Promise.all(matchPromises);
823
- return matches;
824
- };
825
- this.invalidate = () => {
826
- const invalidate = (d) => ({
827
- ...d,
828
- invalid: true
829
- });
830
- this.__store.setState((s) => {
831
- var _a;
832
- return {
833
- ...s,
834
- matches: s.matches.map(invalidate),
835
- cachedMatches: s.cachedMatches.map(invalidate),
836
- pendingMatches: (_a = s.pendingMatches) == null ? void 0 : _a.map(invalidate)
837
- };
838
- });
839
- this.load();
840
- };
841
- this.load = async () => {
842
- const promise = new Promise(async (resolve, reject) => {
843
- const next = this.latestLocation;
844
- const prevLocation = this.state.resolvedLocation;
845
- const pathDidChange = prevLocation.href !== next.href;
846
- let latestPromise;
847
- this.cancelMatches();
848
- this.emit({
849
- type: "onBeforeLoad",
850
- fromLocation: prevLocation,
851
- toLocation: next,
852
- pathChanged: pathDidChange
853
- });
854
- let pendingMatches;
855
- const previousMatches = this.state.matches;
856
- this.__store.batch(() => {
857
- this.cleanCache();
858
- pendingMatches = this.matchRoutes(next.pathname, next.search, {
859
- debug: true
860
- });
861
- this.__store.setState((s) => ({
862
- ...s,
863
- isLoading: true,
864
- location: next,
865
- pendingMatches,
866
- cachedMatches: s.cachedMatches.filter((d) => {
867
- return !pendingMatches.find((e) => e.id === d.id);
868
- })
869
- }));
870
- });
871
- try {
872
- let redirect;
873
- let notFound$1;
874
- try {
875
- await this.loadMatches({
876
- matches: pendingMatches,
877
- location: next,
878
- checkLatest: () => this.checkLatest(promise)
879
- });
880
- } catch (err) {
881
- if (redirects.isRedirect(err)) {
882
- redirect = this.resolveRedirect(err);
883
- if (!utils.isServer) {
884
- this.navigate({ ...redirect, replace: true });
885
- }
886
- } else if (notFound.isNotFound(err)) {
887
- notFound$1 = err;
888
- this.handleNotFound(pendingMatches, err);
889
- }
890
- }
891
- if (latestPromise = this.checkLatest(promise)) {
892
- return latestPromise;
893
- }
894
- const exitingMatches = previousMatches.filter(
895
- (match) => !pendingMatches.find((d) => d.id === match.id)
896
- );
897
- const enteringMatches = pendingMatches.filter(
898
- (match) => !previousMatches.find((d) => d.id === match.id)
899
- );
900
- const stayingMatches = previousMatches.filter(
901
- (match) => pendingMatches.find((d) => d.id === match.id)
902
- );
903
- this.__store.batch(() => {
904
- this.__store.setState((s) => ({
905
- ...s,
906
- isLoading: false,
907
- matches: s.pendingMatches,
908
- pendingMatches: void 0,
909
- cachedMatches: [
910
- ...s.cachedMatches,
911
- ...exitingMatches.filter((d) => d.status !== "error")
912
- ],
913
- statusCode: (redirect == null ? void 0 : redirect.statusCode) || notFound$1 ? 404 : s.matches.some((d) => d.status === "error") ? 500 : 200,
914
- redirect
915
- }));
916
- this.cleanCache();
917
- });
918
- [
919
- [exitingMatches, "onLeave"],
920
- [enteringMatches, "onEnter"],
921
- [stayingMatches, "onStay"]
922
- ].forEach(([matches, hook]) => {
923
- matches.forEach((match) => {
924
- var _a, _b;
925
- (_b = (_a = this.looseRoutesById[match.routeId].options)[hook]) == null ? void 0 : _b.call(_a, match);
926
- });
927
- });
928
- this.emit({
929
- type: "onLoad",
930
- fromLocation: prevLocation,
931
- toLocation: next,
932
- pathChanged: pathDidChange
933
- });
934
- resolve();
935
- } catch (err) {
936
- if (latestPromise = this.checkLatest(promise)) {
937
- return latestPromise;
938
- }
939
- console.log("Load Error", err);
940
- reject(err);
941
- }
942
- });
943
- this.latestLoadPromise = promise;
944
- return this.latestLoadPromise;
945
- };
946
- this.resolveRedirect = (err) => {
947
- let redirect = err;
948
- if (!redirect.href) {
949
- redirect.href = this.buildLocation(redirect).href;
950
- }
951
- return redirect;
952
- };
953
- this.cleanCache = () => {
954
- this.__store.setState((s) => {
955
- return {
956
- ...s,
957
- cachedMatches: s.cachedMatches.filter((d) => {
958
- const route2 = this.looseRoutesById[d.routeId];
959
- if (!route2.options.loader) {
960
- return false;
961
- }
962
- const gcTime = (d.preload ? route2.options.preloadGcTime ?? this.options.defaultPreloadGcTime : route2.options.gcTime ?? this.options.defaultGcTime) ?? 5 * 60 * 1e3;
963
- return d.status !== "error" && Date.now() - d.updatedAt < gcTime;
964
- })
965
- };
966
- });
967
- };
968
- this.preloadRoute = async (opts) => {
969
- var _a;
970
- let next = this.buildLocation(opts);
971
- let matches = this.matchRoutes(next.pathname, next.search, {
972
- throwOnError: true,
973
- preload: true
974
- });
975
- const loadedMatchIds = Object.fromEntries(
976
- (_a = [
977
- ...this.state.matches,
978
- ...this.state.pendingMatches ?? [],
979
- ...this.state.cachedMatches
980
- ]) == null ? void 0 : _a.map((d) => [d.id, true])
981
- );
982
- this.__store.batch(() => {
983
- matches.forEach((match) => {
984
- if (!loadedMatchIds[match.id]) {
985
- this.__store.setState((s) => ({
986
- ...s,
987
- cachedMatches: [...s.cachedMatches, match]
988
- }));
989
- }
990
- });
991
- });
992
- try {
993
- matches = await this.loadMatches({
994
- matches,
995
- location: next,
996
- preload: true,
997
- checkLatest: () => void 0
998
- });
999
- return matches;
1000
- } catch (err) {
1001
- if (redirects.isRedirect(err)) {
1002
- return await this.preloadRoute(err);
1003
- }
1004
- console.error(err);
1005
- return void 0;
1006
- }
1007
- };
1008
- this.matchRoute = (location, opts) => {
1009
- const matchLocation = {
1010
- ...location,
1011
- to: location.to ? this.resolvePathWithBase(location.from || "", location.to) : void 0,
1012
- params: location.params || {},
1013
- leaveParams: true
1014
- };
1015
- const next = this.buildLocation(matchLocation);
1016
- if ((opts == null ? void 0 : opts.pending) && this.state.status !== "pending") {
1017
- return false;
1018
- }
1019
- const baseLocation = (opts == null ? void 0 : opts.pending) ? this.latestLocation : this.state.resolvedLocation;
1020
- if (!baseLocation) {
1021
- return false;
1022
- }
1023
- const match = path.matchPathname(this.basepath, baseLocation.pathname, {
1024
- ...opts,
1025
- to: next.pathname
1026
- });
1027
- if (!match) {
1028
- return false;
1029
- }
1030
- if (location.params) {
1031
- if (!utils.deepEqual(match, location.params, true)) {
1032
- return false;
1033
- }
1034
- }
1035
- if (match && ((opts == null ? void 0 : opts.includeSearch) ?? true)) {
1036
- return utils.deepEqual(baseLocation.search, next.search, true) ? match : false;
1037
- }
1038
- return match;
1039
- };
1040
- this.injectHtml = async (html) => {
1041
- this.injectedHtml.push(html);
1042
- };
1043
- this.registeredDeferredsIds = /* @__PURE__ */ new Map();
1044
- this.registeredDeferreds = /* @__PURE__ */ new WeakMap();
1045
- this.getDeferred = (uid) => {
1046
- const token = this.registeredDeferredsIds.get(uid);
1047
- if (!token) {
1048
- return void 0;
1049
- }
1050
- return this.registeredDeferreds.get(token);
1051
- };
1052
- this.dehydrateData = (key, getData) => {
1053
- warning(
1054
- false,
1055
- `The dehydrateData method is deprecated. Please use the injectHtml method to inject your own data.`
1056
- );
1057
- if (typeof document === "undefined") {
1058
- const strKey = typeof key === "string" ? key : JSON.stringify(key);
1059
- this.injectHtml(async () => {
1060
- const id = `__TSR_DEHYDRATED__${strKey}`;
1061
- const data = typeof getData === "function" ? await getData() : getData;
1062
- return `<script id='${id}' suppressHydrationWarning>
1063
- window["__TSR_DEHYDRATED__${utils.escapeJSON(
1064
- strKey
1065
- )}"] = ${JSON.stringify(this.options.transformer.stringify(data))}
1066
- <\/script>`;
1067
- });
1068
- return () => this.hydrateData(key);
1069
- }
1070
- return () => void 0;
1071
- };
1072
- this.hydrateData = (key) => {
1073
- warning(
1074
- false,
1075
- `The hydrateData method is deprecated. Please use the extractHtml method to extract your own data.`
1076
- );
1077
- if (typeof document !== "undefined") {
1078
- const strKey = typeof key === "string" ? key : JSON.stringify(key);
1079
- return this.options.transformer.parse(
1080
- window[`__TSR_DEHYDRATED__${strKey}`]
1081
- );
1082
- }
1083
- return void 0;
1084
- };
1085
- this.dehydrate = () => {
1086
- var _a;
1087
- const pickError = ((_a = this.options.errorSerializer) == null ? void 0 : _a.serialize) ?? defaultSerializeError;
1088
- return {
1089
- state: {
1090
- dehydratedMatches: this.state.matches.map((d) => ({
1091
- ...utils.pick(d, ["id", "status", "updatedAt", "loaderData"]),
1092
- // If an error occurs server-side during SSRing,
1093
- // send a small subset of the error to the client
1094
- error: d.error ? {
1095
- data: pickError(d.error),
1096
- __isServerError: true
1097
- } : void 0
1098
- }))
1099
- }
1100
- };
1101
- };
1102
- this.hydrate = async (__do_not_use_server_ctx) => {
1103
- var _a, _b, _c;
1104
- let _ctx = __do_not_use_server_ctx;
1105
- if (typeof document !== "undefined") {
1106
- _ctx = (_a = window.__TSR_DEHYDRATED__) == null ? void 0 : _a.data;
1107
- }
1108
- invariant(
1109
- _ctx,
1110
- "Expected to find a __TSR_DEHYDRATED__ property on window... but we did not. Did you forget to render <DehydrateRouter /> in your app?"
1111
- );
1112
- const ctx = this.options.transformer.parse(_ctx);
1113
- this.dehydratedData = ctx.payload;
1114
- (_c = (_b = this.options).hydrate) == null ? void 0 : _c.call(_b, ctx.payload);
1115
- const dehydratedState = ctx.router.state;
1116
- let matches = this.matchRoutes(
1117
- this.state.location.pathname,
1118
- this.state.location.search
1119
- ).map((match) => {
1120
- var _a2, _b2, _c2, _d, _e, _f;
1121
- const dehydratedMatch = dehydratedState.dehydratedMatches.find(
1122
- (d) => d.id === match.id
1123
- );
1124
- invariant(
1125
- dehydratedMatch,
1126
- `Could not find a client-side match for dehydrated match with id: ${match.id}!`
1127
- );
1128
- if (dehydratedMatch) {
1129
- const route2 = this.looseRoutesById[match.routeId];
1130
- const assets = dehydratedMatch.status === "notFound" || dehydratedMatch.status === "redirected" ? {} : {
1131
- meta: (_b2 = (_a2 = route2.options).meta) == null ? void 0 : _b2.call(_a2, {
1132
- params: match.params,
1133
- loaderData: dehydratedMatch.loaderData
1134
- }),
1135
- links: (_d = (_c2 = route2.options).links) == null ? void 0 : _d.call(_c2),
1136
- scripts: (_f = (_e = route2.options).scripts) == null ? void 0 : _f.call(_e)
1137
- };
1138
- return {
1139
- ...match,
1140
- ...dehydratedMatch,
1141
- ...assets
1142
- };
1143
- }
1144
- return match;
1145
- });
1146
- this.__store.setState((s) => {
1147
- return {
1148
- ...s,
1149
- matches,
1150
- lastUpdated: Date.now()
1151
- };
1152
- });
1153
- };
1154
- this.handleNotFound = (matches, err) => {
1155
- const matchesByRouteId = Object.fromEntries(
1156
- matches.map((match2) => [match2.routeId, match2])
1157
- );
1158
- let routeCursor = (err.global ? this.looseRoutesById[route.rootRouteId] : this.looseRoutesById[err.routeId]) || this.looseRoutesById[route.rootRouteId];
1159
- while (!routeCursor.options.notFoundComponent && !this.options.defaultNotFoundComponent && routeCursor.id !== route.rootRouteId) {
1160
- routeCursor = routeCursor == null ? void 0 : routeCursor.parentRoute;
1161
- invariant(
1162
- routeCursor,
1163
- "Found invalid route tree while trying to find not-found handler."
1164
- );
1165
- }
1166
- let match = matchesByRouteId[routeCursor.id];
1167
- invariant(match, "Could not find match for route: " + routeCursor.id);
1168
- Object.assign(match, {
1169
- status: "notFound",
1170
- error: err,
1171
- isFetching: false
1172
- });
1173
- };
1174
- this.hasNotFoundMatch = () => {
1175
- return this.__store.state.matches.some(
1176
- (d) => d.status === "notFound" || d.globalNotFound
1177
- );
1178
- };
1179
- this.update({
1180
- defaultPreloadDelay: 50,
1181
- defaultPendingMs: 1e3,
1182
- defaultPendingMinMs: 500,
1183
- context: void 0,
1184
- ...options,
1185
- stringifySearch: (options == null ? void 0 : options.stringifySearch) ?? searchParams.defaultStringifySearch,
1186
- parseSearch: (options == null ? void 0 : options.parseSearch) ?? searchParams.defaultParseSearch,
1187
- transformer: (options == null ? void 0 : options.transformer) ?? JSON
1188
- });
1189
- if (typeof document !== "undefined") {
1190
- window.__TSR__ROUTER__ = this;
1191
- }
1192
- }
1193
- get state() {
1194
- return this.__store.state;
10
+ super(options);
1195
11
  }
1196
- get looseRoutesById() {
1197
- return this.routesById;
1198
- }
1199
- // resolveMatchPromise = (matchId: string, key: string, value: any) => {
1200
- // state.matches
1201
- // .find((d) => d.id === matchId)
1202
- // ?.__promisesByKey[key]?.resolve(value)
1203
- // }
1204
- }
1205
- function lazyFn(fn, key) {
1206
- return async (...args) => {
1207
- const imported = await fn();
1208
- return imported[key || "default"](...args);
1209
- };
1210
- }
1211
- class SearchParamError extends Error {
1212
- }
1213
- class PathParamError extends Error {
1214
- }
1215
- function getInitialRouterState(location) {
1216
- return {
1217
- isLoading: false,
1218
- isTransitioning: false,
1219
- status: "idle",
1220
- resolvedLocation: { ...location },
1221
- location,
1222
- matches: [],
1223
- pendingMatches: [],
1224
- cachedMatches: [],
1225
- lastUpdated: 0,
1226
- statusCode: 200
1227
- };
1228
12
  }
1229
- function defaultSerializeError(err) {
1230
- if (err instanceof Error)
1231
- return {
1232
- name: err.name,
1233
- message: err.message
1234
- };
1235
- return {
1236
- data: err
1237
- };
13
+ if (typeof globalThis !== "undefined") {
14
+ globalThis.createFileRoute = fileRoute.createFileRoute;
15
+ globalThis.createLazyFileRoute = fileRoute.createLazyFileRoute;
16
+ } else if (typeof window !== "undefined") {
17
+ window.createFileRoute = fileRoute.createFileRoute;
18
+ window.createFileRoute = fileRoute.createLazyFileRoute;
1238
19
  }
1239
- exports.PathParamError = PathParamError;
1240
20
  exports.Router = Router;
1241
- exports.SearchParamError = SearchParamError;
1242
- exports.componentTypes = componentTypes;
1243
21
  exports.createRouter = createRouter;
1244
- exports.defaultSerializeError = defaultSerializeError;
1245
- exports.getInitialRouterState = getInitialRouterState;
1246
- exports.lazyFn = lazyFn;
1247
22
  //# sourceMappingURL=router.cjs.map