@tanstack/router-core 0.0.1-beta.9 → 1.97.24

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 (140) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +5 -0
  3. package/dist/cjs/Matches.cjs +13 -0
  4. package/dist/cjs/Matches.cjs.map +1 -0
  5. package/dist/cjs/Matches.d.cts +28 -0
  6. package/dist/cjs/RouterProvider.d.cts +18 -0
  7. package/dist/cjs/defer.cjs +25 -0
  8. package/dist/cjs/defer.cjs.map +1 -0
  9. package/dist/cjs/defer.d.cts +20 -0
  10. package/dist/cjs/index.cjs +50 -0
  11. package/dist/cjs/index.cjs.map +1 -0
  12. package/dist/cjs/index.d.cts +25 -0
  13. package/dist/cjs/link.cjs +5 -0
  14. package/dist/cjs/link.cjs.map +1 -0
  15. package/dist/cjs/link.d.cts +51 -0
  16. package/dist/cjs/location.d.cts +12 -0
  17. package/dist/cjs/manifest.d.cts +24 -0
  18. package/dist/cjs/path.cjs +289 -0
  19. package/dist/cjs/path.cjs.map +1 -0
  20. package/dist/cjs/path.d.cts +34 -0
  21. package/dist/cjs/qss.cjs +51 -0
  22. package/dist/cjs/qss.cjs.map +1 -0
  23. package/dist/cjs/qss.d.cts +27 -0
  24. package/dist/cjs/root.cjs +5 -0
  25. package/dist/cjs/root.cjs.map +1 -0
  26. package/dist/cjs/root.d.cts +2 -0
  27. package/dist/cjs/route.d.cts +148 -0
  28. package/dist/cjs/router.cjs +19 -0
  29. package/dist/cjs/router.cjs.map +1 -0
  30. package/dist/cjs/router.d.cts +31 -0
  31. package/dist/cjs/searchMiddleware.cjs +42 -0
  32. package/dist/cjs/searchMiddleware.cjs.map +1 -0
  33. package/dist/cjs/searchMiddleware.d.cts +5 -0
  34. package/dist/cjs/searchParams.cjs +61 -0
  35. package/dist/cjs/searchParams.cjs.map +1 -0
  36. package/dist/cjs/searchParams.d.cts +7 -0
  37. package/dist/cjs/serializer.d.cts +15 -0
  38. package/dist/cjs/structuralSharing.d.cts +4 -0
  39. package/dist/cjs/utils.cjs +155 -0
  40. package/dist/cjs/utils.cjs.map +1 -0
  41. package/dist/cjs/utils.d.cts +81 -0
  42. package/dist/cjs/validators.d.cts +51 -0
  43. package/dist/esm/Matches.d.ts +28 -0
  44. package/dist/esm/Matches.js +13 -0
  45. package/dist/esm/Matches.js.map +1 -0
  46. package/dist/esm/RouterProvider.d.ts +18 -0
  47. package/dist/esm/defer.d.ts +20 -0
  48. package/dist/esm/defer.js +25 -0
  49. package/dist/esm/defer.js.map +1 -0
  50. package/dist/esm/index.d.ts +25 -0
  51. package/dist/esm/index.js +50 -0
  52. package/dist/esm/index.js.map +1 -0
  53. package/dist/esm/link.d.ts +51 -0
  54. package/dist/esm/link.js +5 -0
  55. package/dist/esm/link.js.map +1 -0
  56. package/dist/esm/location.d.ts +12 -0
  57. package/dist/esm/manifest.d.ts +24 -0
  58. package/dist/esm/path.d.ts +34 -0
  59. package/dist/esm/path.js +289 -0
  60. package/dist/esm/path.js.map +1 -0
  61. package/dist/esm/qss.d.ts +27 -0
  62. package/dist/esm/qss.js +51 -0
  63. package/dist/esm/qss.js.map +1 -0
  64. package/dist/esm/root.d.ts +2 -0
  65. package/dist/esm/root.js +5 -0
  66. package/dist/esm/root.js.map +1 -0
  67. package/dist/esm/route.d.ts +148 -0
  68. package/dist/esm/router.d.ts +31 -0
  69. package/dist/esm/router.js +19 -0
  70. package/dist/esm/router.js.map +1 -0
  71. package/dist/esm/searchMiddleware.d.ts +5 -0
  72. package/dist/esm/searchMiddleware.js +42 -0
  73. package/dist/esm/searchMiddleware.js.map +1 -0
  74. package/dist/esm/searchParams.d.ts +7 -0
  75. package/dist/esm/searchParams.js +61 -0
  76. package/dist/esm/searchParams.js.map +1 -0
  77. package/dist/esm/serializer.d.ts +15 -0
  78. package/dist/esm/structuralSharing.d.ts +4 -0
  79. package/dist/esm/utils.d.ts +81 -0
  80. package/dist/esm/utils.js +155 -0
  81. package/dist/esm/utils.js.map +1 -0
  82. package/dist/esm/validators.d.ts +51 -0
  83. package/package.json +35 -32
  84. package/src/Matches.ts +94 -0
  85. package/src/RouterProvider.ts +20 -0
  86. package/src/defer.ts +52 -0
  87. package/src/index.ts +206 -19
  88. package/src/link.ts +122 -300
  89. package/src/location.ts +13 -0
  90. package/src/manifest.ts +32 -0
  91. package/src/path.ts +238 -47
  92. package/src/qss.ts +56 -19
  93. package/src/root.ts +2 -0
  94. package/src/route.ts +296 -223
  95. package/src/router.ts +34 -1281
  96. package/src/searchMiddleware.ts +54 -0
  97. package/src/searchParams.ts +43 -20
  98. package/src/serializer.ts +24 -0
  99. package/src/structuralSharing.ts +7 -0
  100. package/src/utils.ts +314 -75
  101. package/src/validators.ts +121 -0
  102. package/build/cjs/_virtual/_rollupPluginBabelHelpers.js +0 -33
  103. package/build/cjs/_virtual/_rollupPluginBabelHelpers.js.map +0 -1
  104. package/build/cjs/node_modules/@babel/runtime/helpers/esm/extends.js +0 -33
  105. package/build/cjs/node_modules/@babel/runtime/helpers/esm/extends.js.map +0 -1
  106. package/build/cjs/node_modules/history/index.js +0 -815
  107. package/build/cjs/node_modules/history/index.js.map +0 -1
  108. package/build/cjs/node_modules/tiny-invariant/dist/esm/tiny-invariant.js +0 -30
  109. package/build/cjs/node_modules/tiny-invariant/dist/esm/tiny-invariant.js.map +0 -1
  110. package/build/cjs/packages/router-core/src/index.js +0 -58
  111. package/build/cjs/packages/router-core/src/index.js.map +0 -1
  112. package/build/cjs/packages/router-core/src/path.js +0 -222
  113. package/build/cjs/packages/router-core/src/path.js.map +0 -1
  114. package/build/cjs/packages/router-core/src/qss.js +0 -71
  115. package/build/cjs/packages/router-core/src/qss.js.map +0 -1
  116. package/build/cjs/packages/router-core/src/route.js +0 -150
  117. package/build/cjs/packages/router-core/src/route.js.map +0 -1
  118. package/build/cjs/packages/router-core/src/routeConfig.js +0 -69
  119. package/build/cjs/packages/router-core/src/routeConfig.js.map +0 -1
  120. package/build/cjs/packages/router-core/src/routeMatch.js +0 -266
  121. package/build/cjs/packages/router-core/src/routeMatch.js.map +0 -1
  122. package/build/cjs/packages/router-core/src/router.js +0 -822
  123. package/build/cjs/packages/router-core/src/router.js.map +0 -1
  124. package/build/cjs/packages/router-core/src/searchParams.js +0 -70
  125. package/build/cjs/packages/router-core/src/searchParams.js.map +0 -1
  126. package/build/cjs/packages/router-core/src/utils.js +0 -125
  127. package/build/cjs/packages/router-core/src/utils.js.map +0 -1
  128. package/build/esm/index.js +0 -2481
  129. package/build/esm/index.js.map +0 -1
  130. package/build/stats-html.html +0 -4034
  131. package/build/stats-react.json +0 -493
  132. package/build/types/index.d.ts +0 -618
  133. package/build/umd/index.development.js +0 -2514
  134. package/build/umd/index.development.js.map +0 -1
  135. package/build/umd/index.production.js +0 -12
  136. package/build/umd/index.production.js.map +0 -1
  137. package/src/frameworks.ts +0 -12
  138. package/src/routeConfig.ts +0 -495
  139. package/src/routeInfo.ts +0 -228
  140. package/src/routeMatch.ts +0 -374
@@ -1,2481 +0,0 @@
1
- /**
2
- * router-core
3
- *
4
- * Copyright (c) TanStack
5
- *
6
- * This source code is licensed under the MIT license found in the
7
- * LICENSE.md file in the root directory of this source tree.
8
- *
9
- * @license MIT
10
- */
11
- function _extends$1() {
12
- _extends$1 = Object.assign ? Object.assign.bind() : function (target) {
13
- for (var i = 1; i < arguments.length; i++) {
14
- var source = arguments[i];
15
-
16
- for (var key in source) {
17
- if (Object.prototype.hasOwnProperty.call(source, key)) {
18
- target[key] = source[key];
19
- }
20
- }
21
- }
22
-
23
- return target;
24
- };
25
- return _extends$1.apply(this, arguments);
26
- }
27
-
28
- /**
29
- * Actions represent the type of change to a location value.
30
- *
31
- * @see https://github.com/remix-run/history/tree/main/docs/api-reference.md#action
32
- */
33
- var Action;
34
-
35
- (function (Action) {
36
- /**
37
- * A POP indicates a change to an arbitrary index in the history stack, such
38
- * as a back or forward navigation. It does not describe the direction of the
39
- * navigation, only that the current index changed.
40
- *
41
- * Note: This is the default action for newly created history objects.
42
- */
43
- Action["Pop"] = "POP";
44
- /**
45
- * A PUSH indicates a new entry being added to the history stack, such as when
46
- * a link is clicked and a new page loads. When this happens, all subsequent
47
- * entries in the stack are lost.
48
- */
49
-
50
- Action["Push"] = "PUSH";
51
- /**
52
- * A REPLACE indicates the entry at the current index in the history stack
53
- * being replaced by a new one.
54
- */
55
-
56
- Action["Replace"] = "REPLACE";
57
- })(Action || (Action = {}));
58
-
59
- var readOnly = process.env.NODE_ENV !== "production" ? function (obj) {
60
- return Object.freeze(obj);
61
- } : function (obj) {
62
- return obj;
63
- };
64
-
65
- function warning$1(cond, message) {
66
- if (!cond) {
67
- // eslint-disable-next-line no-console
68
- if (typeof console !== 'undefined') console.warn(message);
69
-
70
- try {
71
- // Welcome to debugging history!
72
- //
73
- // This error is thrown as a convenience so you can more easily
74
- // find the source for a warning that appears in the console by
75
- // enabling "pause on exceptions" in your JavaScript debugger.
76
- throw new Error(message); // eslint-disable-next-line no-empty
77
- } catch (e) {}
78
- }
79
- }
80
-
81
- var BeforeUnloadEventType = 'beforeunload';
82
- var HashChangeEventType = 'hashchange';
83
- var PopStateEventType = 'popstate';
84
- /**
85
- * Browser history stores the location in regular URLs. This is the standard for
86
- * most web apps, but it requires some configuration on the server to ensure you
87
- * serve the same app at multiple URLs.
88
- *
89
- * @see https://github.com/remix-run/history/tree/main/docs/api-reference.md#createbrowserhistory
90
- */
91
-
92
- function createBrowserHistory(options) {
93
- if (options === void 0) {
94
- options = {};
95
- }
96
-
97
- var _options = options,
98
- _options$window = _options.window,
99
- window = _options$window === void 0 ? document.defaultView : _options$window;
100
- var globalHistory = window.history;
101
-
102
- function getIndexAndLocation() {
103
- var _window$location = window.location,
104
- pathname = _window$location.pathname,
105
- search = _window$location.search,
106
- hash = _window$location.hash;
107
- var state = globalHistory.state || {};
108
- return [state.idx, readOnly({
109
- pathname: pathname,
110
- search: search,
111
- hash: hash,
112
- state: state.usr || null,
113
- key: state.key || 'default'
114
- })];
115
- }
116
-
117
- var blockedPopTx = null;
118
-
119
- function handlePop() {
120
- if (blockedPopTx) {
121
- blockers.call(blockedPopTx);
122
- blockedPopTx = null;
123
- } else {
124
- var nextAction = Action.Pop;
125
-
126
- var _getIndexAndLocation = getIndexAndLocation(),
127
- nextIndex = _getIndexAndLocation[0],
128
- nextLocation = _getIndexAndLocation[1];
129
-
130
- if (blockers.length) {
131
- if (nextIndex != null) {
132
- var delta = index - nextIndex;
133
-
134
- if (delta) {
135
- // Revert the POP
136
- blockedPopTx = {
137
- action: nextAction,
138
- location: nextLocation,
139
- retry: function retry() {
140
- go(delta * -1);
141
- }
142
- };
143
- go(delta);
144
- }
145
- } else {
146
- // Trying to POP to a location with no index. We did not create
147
- // this location, so we can't effectively block the navigation.
148
- process.env.NODE_ENV !== "production" ? warning$1(false, // TODO: Write up a doc that explains our blocking strategy in
149
- // detail and link to it here so people can understand better what
150
- // is going on and how to avoid it.
151
- "You are trying to block a POP navigation to a location that was not " + "created by the history library. The block will fail silently in " + "production, but in general you should do all navigation with the " + "history library (instead of using window.history.pushState directly) " + "to avoid this situation.") : void 0;
152
- }
153
- } else {
154
- applyTx(nextAction);
155
- }
156
- }
157
- }
158
-
159
- window.addEventListener(PopStateEventType, handlePop);
160
- var action = Action.Pop;
161
-
162
- var _getIndexAndLocation2 = getIndexAndLocation(),
163
- index = _getIndexAndLocation2[0],
164
- location = _getIndexAndLocation2[1];
165
-
166
- var listeners = createEvents();
167
- var blockers = createEvents();
168
-
169
- if (index == null) {
170
- index = 0;
171
- globalHistory.replaceState(_extends$1({}, globalHistory.state, {
172
- idx: index
173
- }), '');
174
- }
175
-
176
- function createHref(to) {
177
- return typeof to === 'string' ? to : createPath(to);
178
- } // state defaults to `null` because `window.history.state` does
179
-
180
-
181
- function getNextLocation(to, state) {
182
- if (state === void 0) {
183
- state = null;
184
- }
185
-
186
- return readOnly(_extends$1({
187
- pathname: location.pathname,
188
- hash: '',
189
- search: ''
190
- }, typeof to === 'string' ? parsePath(to) : to, {
191
- state: state,
192
- key: createKey()
193
- }));
194
- }
195
-
196
- function getHistoryStateAndUrl(nextLocation, index) {
197
- return [{
198
- usr: nextLocation.state,
199
- key: nextLocation.key,
200
- idx: index
201
- }, createHref(nextLocation)];
202
- }
203
-
204
- function allowTx(action, location, retry) {
205
- return !blockers.length || (blockers.call({
206
- action: action,
207
- location: location,
208
- retry: retry
209
- }), false);
210
- }
211
-
212
- function applyTx(nextAction) {
213
- action = nextAction;
214
-
215
- var _getIndexAndLocation3 = getIndexAndLocation();
216
-
217
- index = _getIndexAndLocation3[0];
218
- location = _getIndexAndLocation3[1];
219
- listeners.call({
220
- action: action,
221
- location: location
222
- });
223
- }
224
-
225
- function push(to, state) {
226
- var nextAction = Action.Push;
227
- var nextLocation = getNextLocation(to, state);
228
-
229
- function retry() {
230
- push(to, state);
231
- }
232
-
233
- if (allowTx(nextAction, nextLocation, retry)) {
234
- var _getHistoryStateAndUr = getHistoryStateAndUrl(nextLocation, index + 1),
235
- historyState = _getHistoryStateAndUr[0],
236
- url = _getHistoryStateAndUr[1]; // TODO: Support forced reloading
237
- // try...catch because iOS limits us to 100 pushState calls :/
238
-
239
-
240
- try {
241
- globalHistory.pushState(historyState, '', url);
242
- } catch (error) {
243
- // They are going to lose state here, but there is no real
244
- // way to warn them about it since the page will refresh...
245
- window.location.assign(url);
246
- }
247
-
248
- applyTx(nextAction);
249
- }
250
- }
251
-
252
- function replace(to, state) {
253
- var nextAction = Action.Replace;
254
- var nextLocation = getNextLocation(to, state);
255
-
256
- function retry() {
257
- replace(to, state);
258
- }
259
-
260
- if (allowTx(nextAction, nextLocation, retry)) {
261
- var _getHistoryStateAndUr2 = getHistoryStateAndUrl(nextLocation, index),
262
- historyState = _getHistoryStateAndUr2[0],
263
- url = _getHistoryStateAndUr2[1]; // TODO: Support forced reloading
264
-
265
-
266
- globalHistory.replaceState(historyState, '', url);
267
- applyTx(nextAction);
268
- }
269
- }
270
-
271
- function go(delta) {
272
- globalHistory.go(delta);
273
- }
274
-
275
- var history = {
276
- get action() {
277
- return action;
278
- },
279
-
280
- get location() {
281
- return location;
282
- },
283
-
284
- createHref: createHref,
285
- push: push,
286
- replace: replace,
287
- go: go,
288
- back: function back() {
289
- go(-1);
290
- },
291
- forward: function forward() {
292
- go(1);
293
- },
294
- listen: function listen(listener) {
295
- return listeners.push(listener);
296
- },
297
- block: function block(blocker) {
298
- var unblock = blockers.push(blocker);
299
-
300
- if (blockers.length === 1) {
301
- window.addEventListener(BeforeUnloadEventType, promptBeforeUnload);
302
- }
303
-
304
- return function () {
305
- unblock(); // Remove the beforeunload listener so the document may
306
- // still be salvageable in the pagehide event.
307
- // See https://html.spec.whatwg.org/#unloading-documents
308
-
309
- if (!blockers.length) {
310
- window.removeEventListener(BeforeUnloadEventType, promptBeforeUnload);
311
- }
312
- };
313
- }
314
- };
315
- return history;
316
- }
317
- /**
318
- * Hash history stores the location in window.location.hash. This makes it ideal
319
- * for situations where you don't want to send the location to the server for
320
- * some reason, either because you do cannot configure it or the URL space is
321
- * reserved for something else.
322
- *
323
- * @see https://github.com/remix-run/history/tree/main/docs/api-reference.md#createhashhistory
324
- */
325
-
326
- function createHashHistory(options) {
327
- if (options === void 0) {
328
- options = {};
329
- }
330
-
331
- var _options2 = options,
332
- _options2$window = _options2.window,
333
- window = _options2$window === void 0 ? document.defaultView : _options2$window;
334
- var globalHistory = window.history;
335
-
336
- function getIndexAndLocation() {
337
- var _parsePath = parsePath(window.location.hash.substr(1)),
338
- _parsePath$pathname = _parsePath.pathname,
339
- pathname = _parsePath$pathname === void 0 ? '/' : _parsePath$pathname,
340
- _parsePath$search = _parsePath.search,
341
- search = _parsePath$search === void 0 ? '' : _parsePath$search,
342
- _parsePath$hash = _parsePath.hash,
343
- hash = _parsePath$hash === void 0 ? '' : _parsePath$hash;
344
-
345
- var state = globalHistory.state || {};
346
- return [state.idx, readOnly({
347
- pathname: pathname,
348
- search: search,
349
- hash: hash,
350
- state: state.usr || null,
351
- key: state.key || 'default'
352
- })];
353
- }
354
-
355
- var blockedPopTx = null;
356
-
357
- function handlePop() {
358
- if (blockedPopTx) {
359
- blockers.call(blockedPopTx);
360
- blockedPopTx = null;
361
- } else {
362
- var nextAction = Action.Pop;
363
-
364
- var _getIndexAndLocation4 = getIndexAndLocation(),
365
- nextIndex = _getIndexAndLocation4[0],
366
- nextLocation = _getIndexAndLocation4[1];
367
-
368
- if (blockers.length) {
369
- if (nextIndex != null) {
370
- var delta = index - nextIndex;
371
-
372
- if (delta) {
373
- // Revert the POP
374
- blockedPopTx = {
375
- action: nextAction,
376
- location: nextLocation,
377
- retry: function retry() {
378
- go(delta * -1);
379
- }
380
- };
381
- go(delta);
382
- }
383
- } else {
384
- // Trying to POP to a location with no index. We did not create
385
- // this location, so we can't effectively block the navigation.
386
- process.env.NODE_ENV !== "production" ? warning$1(false, // TODO: Write up a doc that explains our blocking strategy in
387
- // detail and link to it here so people can understand better
388
- // what is going on and how to avoid it.
389
- "You are trying to block a POP navigation to a location that was not " + "created by the history library. The block will fail silently in " + "production, but in general you should do all navigation with the " + "history library (instead of using window.history.pushState directly) " + "to avoid this situation.") : void 0;
390
- }
391
- } else {
392
- applyTx(nextAction);
393
- }
394
- }
395
- }
396
-
397
- window.addEventListener(PopStateEventType, handlePop); // popstate does not fire on hashchange in IE 11 and old (trident) Edge
398
- // https://developer.mozilla.org/de/docs/Web/API/Window/popstate_event
399
-
400
- window.addEventListener(HashChangeEventType, function () {
401
- var _getIndexAndLocation5 = getIndexAndLocation(),
402
- nextLocation = _getIndexAndLocation5[1]; // Ignore extraneous hashchange events.
403
-
404
-
405
- if (createPath(nextLocation) !== createPath(location)) {
406
- handlePop();
407
- }
408
- });
409
- var action = Action.Pop;
410
-
411
- var _getIndexAndLocation6 = getIndexAndLocation(),
412
- index = _getIndexAndLocation6[0],
413
- location = _getIndexAndLocation6[1];
414
-
415
- var listeners = createEvents();
416
- var blockers = createEvents();
417
-
418
- if (index == null) {
419
- index = 0;
420
- globalHistory.replaceState(_extends$1({}, globalHistory.state, {
421
- idx: index
422
- }), '');
423
- }
424
-
425
- function getBaseHref() {
426
- var base = document.querySelector('base');
427
- var href = '';
428
-
429
- if (base && base.getAttribute('href')) {
430
- var url = window.location.href;
431
- var hashIndex = url.indexOf('#');
432
- href = hashIndex === -1 ? url : url.slice(0, hashIndex);
433
- }
434
-
435
- return href;
436
- }
437
-
438
- function createHref(to) {
439
- return getBaseHref() + '#' + (typeof to === 'string' ? to : createPath(to));
440
- }
441
-
442
- function getNextLocation(to, state) {
443
- if (state === void 0) {
444
- state = null;
445
- }
446
-
447
- return readOnly(_extends$1({
448
- pathname: location.pathname,
449
- hash: '',
450
- search: ''
451
- }, typeof to === 'string' ? parsePath(to) : to, {
452
- state: state,
453
- key: createKey()
454
- }));
455
- }
456
-
457
- function getHistoryStateAndUrl(nextLocation, index) {
458
- return [{
459
- usr: nextLocation.state,
460
- key: nextLocation.key,
461
- idx: index
462
- }, createHref(nextLocation)];
463
- }
464
-
465
- function allowTx(action, location, retry) {
466
- return !blockers.length || (blockers.call({
467
- action: action,
468
- location: location,
469
- retry: retry
470
- }), false);
471
- }
472
-
473
- function applyTx(nextAction) {
474
- action = nextAction;
475
-
476
- var _getIndexAndLocation7 = getIndexAndLocation();
477
-
478
- index = _getIndexAndLocation7[0];
479
- location = _getIndexAndLocation7[1];
480
- listeners.call({
481
- action: action,
482
- location: location
483
- });
484
- }
485
-
486
- function push(to, state) {
487
- var nextAction = Action.Push;
488
- var nextLocation = getNextLocation(to, state);
489
-
490
- function retry() {
491
- push(to, state);
492
- }
493
-
494
- process.env.NODE_ENV !== "production" ? warning$1(nextLocation.pathname.charAt(0) === '/', "Relative pathnames are not supported in hash history.push(" + JSON.stringify(to) + ")") : void 0;
495
-
496
- if (allowTx(nextAction, nextLocation, retry)) {
497
- var _getHistoryStateAndUr3 = getHistoryStateAndUrl(nextLocation, index + 1),
498
- historyState = _getHistoryStateAndUr3[0],
499
- url = _getHistoryStateAndUr3[1]; // TODO: Support forced reloading
500
- // try...catch because iOS limits us to 100 pushState calls :/
501
-
502
-
503
- try {
504
- globalHistory.pushState(historyState, '', url);
505
- } catch (error) {
506
- // They are going to lose state here, but there is no real
507
- // way to warn them about it since the page will refresh...
508
- window.location.assign(url);
509
- }
510
-
511
- applyTx(nextAction);
512
- }
513
- }
514
-
515
- function replace(to, state) {
516
- var nextAction = Action.Replace;
517
- var nextLocation = getNextLocation(to, state);
518
-
519
- function retry() {
520
- replace(to, state);
521
- }
522
-
523
- process.env.NODE_ENV !== "production" ? warning$1(nextLocation.pathname.charAt(0) === '/', "Relative pathnames are not supported in hash history.replace(" + JSON.stringify(to) + ")") : void 0;
524
-
525
- if (allowTx(nextAction, nextLocation, retry)) {
526
- var _getHistoryStateAndUr4 = getHistoryStateAndUrl(nextLocation, index),
527
- historyState = _getHistoryStateAndUr4[0],
528
- url = _getHistoryStateAndUr4[1]; // TODO: Support forced reloading
529
-
530
-
531
- globalHistory.replaceState(historyState, '', url);
532
- applyTx(nextAction);
533
- }
534
- }
535
-
536
- function go(delta) {
537
- globalHistory.go(delta);
538
- }
539
-
540
- var history = {
541
- get action() {
542
- return action;
543
- },
544
-
545
- get location() {
546
- return location;
547
- },
548
-
549
- createHref: createHref,
550
- push: push,
551
- replace: replace,
552
- go: go,
553
- back: function back() {
554
- go(-1);
555
- },
556
- forward: function forward() {
557
- go(1);
558
- },
559
- listen: function listen(listener) {
560
- return listeners.push(listener);
561
- },
562
- block: function block(blocker) {
563
- var unblock = blockers.push(blocker);
564
-
565
- if (blockers.length === 1) {
566
- window.addEventListener(BeforeUnloadEventType, promptBeforeUnload);
567
- }
568
-
569
- return function () {
570
- unblock(); // Remove the beforeunload listener so the document may
571
- // still be salvageable in the pagehide event.
572
- // See https://html.spec.whatwg.org/#unloading-documents
573
-
574
- if (!blockers.length) {
575
- window.removeEventListener(BeforeUnloadEventType, promptBeforeUnload);
576
- }
577
- };
578
- }
579
- };
580
- return history;
581
- }
582
- /**
583
- * Memory history stores the current location in memory. It is designed for use
584
- * in stateful non-browser environments like tests and React Native.
585
- *
586
- * @see https://github.com/remix-run/history/tree/main/docs/api-reference.md#creatememoryhistory
587
- */
588
-
589
- function createMemoryHistory(options) {
590
- if (options === void 0) {
591
- options = {};
592
- }
593
-
594
- var _options3 = options,
595
- _options3$initialEntr = _options3.initialEntries,
596
- initialEntries = _options3$initialEntr === void 0 ? ['/'] : _options3$initialEntr,
597
- initialIndex = _options3.initialIndex;
598
- var entries = initialEntries.map(function (entry) {
599
- var location = readOnly(_extends$1({
600
- pathname: '/',
601
- search: '',
602
- hash: '',
603
- state: null,
604
- key: createKey()
605
- }, typeof entry === 'string' ? parsePath(entry) : entry));
606
- process.env.NODE_ENV !== "production" ? warning$1(location.pathname.charAt(0) === '/', "Relative pathnames are not supported in createMemoryHistory({ initialEntries }) (invalid entry: " + JSON.stringify(entry) + ")") : void 0;
607
- return location;
608
- });
609
- var index = clamp(initialIndex == null ? entries.length - 1 : initialIndex, 0, entries.length - 1);
610
- var action = Action.Pop;
611
- var location = entries[index];
612
- var listeners = createEvents();
613
- var blockers = createEvents();
614
-
615
- function createHref(to) {
616
- return typeof to === 'string' ? to : createPath(to);
617
- }
618
-
619
- function getNextLocation(to, state) {
620
- if (state === void 0) {
621
- state = null;
622
- }
623
-
624
- return readOnly(_extends$1({
625
- pathname: location.pathname,
626
- search: '',
627
- hash: ''
628
- }, typeof to === 'string' ? parsePath(to) : to, {
629
- state: state,
630
- key: createKey()
631
- }));
632
- }
633
-
634
- function allowTx(action, location, retry) {
635
- return !blockers.length || (blockers.call({
636
- action: action,
637
- location: location,
638
- retry: retry
639
- }), false);
640
- }
641
-
642
- function applyTx(nextAction, nextLocation) {
643
- action = nextAction;
644
- location = nextLocation;
645
- listeners.call({
646
- action: action,
647
- location: location
648
- });
649
- }
650
-
651
- function push(to, state) {
652
- var nextAction = Action.Push;
653
- var nextLocation = getNextLocation(to, state);
654
-
655
- function retry() {
656
- push(to, state);
657
- }
658
-
659
- process.env.NODE_ENV !== "production" ? warning$1(location.pathname.charAt(0) === '/', "Relative pathnames are not supported in memory history.push(" + JSON.stringify(to) + ")") : void 0;
660
-
661
- if (allowTx(nextAction, nextLocation, retry)) {
662
- index += 1;
663
- entries.splice(index, entries.length, nextLocation);
664
- applyTx(nextAction, nextLocation);
665
- }
666
- }
667
-
668
- function replace(to, state) {
669
- var nextAction = Action.Replace;
670
- var nextLocation = getNextLocation(to, state);
671
-
672
- function retry() {
673
- replace(to, state);
674
- }
675
-
676
- process.env.NODE_ENV !== "production" ? warning$1(location.pathname.charAt(0) === '/', "Relative pathnames are not supported in memory history.replace(" + JSON.stringify(to) + ")") : void 0;
677
-
678
- if (allowTx(nextAction, nextLocation, retry)) {
679
- entries[index] = nextLocation;
680
- applyTx(nextAction, nextLocation);
681
- }
682
- }
683
-
684
- function go(delta) {
685
- var nextIndex = clamp(index + delta, 0, entries.length - 1);
686
- var nextAction = Action.Pop;
687
- var nextLocation = entries[nextIndex];
688
-
689
- function retry() {
690
- go(delta);
691
- }
692
-
693
- if (allowTx(nextAction, nextLocation, retry)) {
694
- index = nextIndex;
695
- applyTx(nextAction, nextLocation);
696
- }
697
- }
698
-
699
- var history = {
700
- get index() {
701
- return index;
702
- },
703
-
704
- get action() {
705
- return action;
706
- },
707
-
708
- get location() {
709
- return location;
710
- },
711
-
712
- createHref: createHref,
713
- push: push,
714
- replace: replace,
715
- go: go,
716
- back: function back() {
717
- go(-1);
718
- },
719
- forward: function forward() {
720
- go(1);
721
- },
722
- listen: function listen(listener) {
723
- return listeners.push(listener);
724
- },
725
- block: function block(blocker) {
726
- return blockers.push(blocker);
727
- }
728
- };
729
- return history;
730
- } ////////////////////////////////////////////////////////////////////////////////
731
- // UTILS
732
- ////////////////////////////////////////////////////////////////////////////////
733
-
734
- function clamp(n, lowerBound, upperBound) {
735
- return Math.min(Math.max(n, lowerBound), upperBound);
736
- }
737
-
738
- function promptBeforeUnload(event) {
739
- // Cancel the event.
740
- event.preventDefault(); // Chrome (and legacy IE) requires returnValue to be set.
741
-
742
- event.returnValue = '';
743
- }
744
-
745
- function createEvents() {
746
- var handlers = [];
747
- return {
748
- get length() {
749
- return handlers.length;
750
- },
751
-
752
- push: function push(fn) {
753
- handlers.push(fn);
754
- return function () {
755
- handlers = handlers.filter(function (handler) {
756
- return handler !== fn;
757
- });
758
- };
759
- },
760
- call: function call(arg) {
761
- handlers.forEach(function (fn) {
762
- return fn && fn(arg);
763
- });
764
- }
765
- };
766
- }
767
-
768
- function createKey() {
769
- return Math.random().toString(36).substr(2, 8);
770
- }
771
- /**
772
- * Creates a string URL path from the given pathname, search, and hash components.
773
- *
774
- * @see https://github.com/remix-run/history/tree/main/docs/api-reference.md#createpath
775
- */
776
-
777
-
778
- function createPath(_ref) {
779
- var _ref$pathname = _ref.pathname,
780
- pathname = _ref$pathname === void 0 ? '/' : _ref$pathname,
781
- _ref$search = _ref.search,
782
- search = _ref$search === void 0 ? '' : _ref$search,
783
- _ref$hash = _ref.hash,
784
- hash = _ref$hash === void 0 ? '' : _ref$hash;
785
- if (search && search !== '?') pathname += search.charAt(0) === '?' ? search : '?' + search;
786
- if (hash && hash !== '#') pathname += hash.charAt(0) === '#' ? hash : '#' + hash;
787
- return pathname;
788
- }
789
- /**
790
- * Parses a string URL path into its separate pathname, search, and hash components.
791
- *
792
- * @see https://github.com/remix-run/history/tree/main/docs/api-reference.md#parsepath
793
- */
794
-
795
- function parsePath(path) {
796
- var parsedPath = {};
797
-
798
- if (path) {
799
- var hashIndex = path.indexOf('#');
800
-
801
- if (hashIndex >= 0) {
802
- parsedPath.hash = path.substr(hashIndex);
803
- path = path.substr(0, hashIndex);
804
- }
805
-
806
- var searchIndex = path.indexOf('?');
807
-
808
- if (searchIndex >= 0) {
809
- parsedPath.search = path.substr(searchIndex);
810
- path = path.substr(0, searchIndex);
811
- }
812
-
813
- if (path) {
814
- parsedPath.pathname = path;
815
- }
816
- }
817
-
818
- return parsedPath;
819
- }
820
-
821
- var isProduction = process.env.NODE_ENV === 'production';
822
- var prefix = 'Invariant failed';
823
- function invariant(condition, message) {
824
- if (condition) {
825
- return;
826
- }
827
- if (isProduction) {
828
- throw new Error(prefix);
829
- }
830
- var provided = typeof message === 'function' ? message() : message;
831
- var value = provided ? "".concat(prefix, ": ").concat(provided) : prefix;
832
- throw new Error(value);
833
- }
834
-
835
- // type UnionToIntersection<U> = (U extends any ? (k: U) => void : never) extends (
836
- // k: infer I,
837
- // ) => any
838
- // ? I
839
- // : never
840
-
841
- /**
842
- * This function returns `a` if `b` is deeply equal.
843
- * If not, it will replace any deeply equal children of `b` with those of `a`.
844
- * This can be used for structural sharing between JSON values for example.
845
- */
846
- function replaceEqualDeep(prev, next) {
847
- if (prev === next) {
848
- return prev;
849
- }
850
-
851
- const array = Array.isArray(prev) && Array.isArray(next);
852
-
853
- if (array || isPlainObject(prev) && isPlainObject(next)) {
854
- const aSize = array ? prev.length : Object.keys(prev).length;
855
- const bItems = array ? next : Object.keys(next);
856
- const bSize = bItems.length;
857
- const copy = array ? [] : {};
858
- let equalItems = 0;
859
-
860
- for (let i = 0; i < bSize; i++) {
861
- const key = array ? i : bItems[i];
862
- copy[key] = replaceEqualDeep(prev[key], next[key]);
863
-
864
- if (copy[key] === prev[key]) {
865
- equalItems++;
866
- }
867
- }
868
-
869
- return aSize === bSize && equalItems === aSize ? prev : copy;
870
- }
871
-
872
- return next;
873
- } // Copied from: https://github.com/jonschlinkert/is-plain-object
874
-
875
- function isPlainObject(o) {
876
- if (!hasObjectPrototype(o)) {
877
- return false;
878
- } // If has modified constructor
879
-
880
-
881
- const ctor = o.constructor;
882
-
883
- if (typeof ctor === 'undefined') {
884
- return true;
885
- } // If has modified prototype
886
-
887
-
888
- const prot = ctor.prototype;
889
-
890
- if (!hasObjectPrototype(prot)) {
891
- return false;
892
- } // If constructor does not have an Object-specific method
893
-
894
-
895
- if (!prot.hasOwnProperty('isPrototypeOf')) {
896
- return false;
897
- } // Most likely a plain Object
898
-
899
-
900
- return true;
901
- }
902
-
903
- function hasObjectPrototype(o) {
904
- return Object.prototype.toString.call(o) === '[object Object]';
905
- }
906
-
907
- function last(arr) {
908
- return arr[arr.length - 1];
909
- }
910
- function warning(cond, message) {
911
- if (cond) {
912
- if (typeof console !== 'undefined') console.warn(message);
913
-
914
- try {
915
- throw new Error(message);
916
- } catch (_unused) {}
917
- }
918
-
919
- return true;
920
- }
921
-
922
- function isFunction(d) {
923
- return typeof d === 'function';
924
- }
925
-
926
- function functionalUpdate(updater, previous) {
927
- if (isFunction(updater)) {
928
- return updater(previous);
929
- }
930
-
931
- return updater;
932
- }
933
- function pick(parent, keys) {
934
- return keys.reduce((obj, key) => {
935
- obj[key] = parent[key];
936
- return obj;
937
- }, {});
938
- }
939
-
940
- function joinPaths(paths) {
941
- return cleanPath(paths.filter(Boolean).join('/'));
942
- }
943
- function cleanPath(path) {
944
- // remove double slashes
945
- return path.replace(/\/{2,}/g, '/');
946
- }
947
- function trimPathLeft(path) {
948
- return path === '/' ? path : path.replace(/^\/{1,}/, '');
949
- }
950
- function trimPathRight(path) {
951
- return path === '/' ? path : path.replace(/\/{1,}$/, '');
952
- }
953
- function trimPath(path) {
954
- return trimPathRight(trimPathLeft(path));
955
- }
956
- function resolvePath(basepath, base, to) {
957
- base = base.replace(new RegExp("^" + basepath), '/');
958
- to = to.replace(new RegExp("^" + basepath), '/');
959
- let baseSegments = parsePathname(base);
960
- const toSegments = parsePathname(to);
961
- toSegments.forEach((toSegment, index) => {
962
- if (toSegment.value === '/') {
963
- if (!index) {
964
- // Leading slash
965
- baseSegments = [toSegment];
966
- } else if (index === toSegments.length - 1) {
967
- // Trailing Slash
968
- baseSegments.push(toSegment);
969
- } else ;
970
- } else if (toSegment.value === '..') {
971
- var _last;
972
-
973
- // Extra trailing slash? pop it off
974
- if (baseSegments.length > 1 && ((_last = last(baseSegments)) == null ? void 0 : _last.value) === '/') {
975
- baseSegments.pop();
976
- }
977
-
978
- baseSegments.pop();
979
- } else if (toSegment.value === '.') {
980
- return;
981
- } else {
982
- baseSegments.push(toSegment);
983
- }
984
- });
985
- const joined = joinPaths([basepath, ...baseSegments.map(d => d.value)]);
986
- return cleanPath(joined);
987
- }
988
- function parsePathname(pathname) {
989
- if (!pathname) {
990
- return [];
991
- }
992
-
993
- pathname = cleanPath(pathname);
994
- const segments = [];
995
-
996
- if (pathname.slice(0, 1) === '/') {
997
- pathname = pathname.substring(1);
998
- segments.push({
999
- type: 'pathname',
1000
- value: '/'
1001
- });
1002
- }
1003
-
1004
- if (!pathname) {
1005
- return segments;
1006
- } // Remove empty segments and '.' segments
1007
-
1008
-
1009
- const split = pathname.split('/').filter(Boolean);
1010
- segments.push(...split.map(part => {
1011
- if (part.startsWith('*')) {
1012
- return {
1013
- type: 'wildcard',
1014
- value: part
1015
- };
1016
- }
1017
-
1018
- if (part.charAt(0) === ':') {
1019
- return {
1020
- type: 'param',
1021
- value: part
1022
- };
1023
- }
1024
-
1025
- return {
1026
- type: 'pathname',
1027
- value: part
1028
- };
1029
- }));
1030
-
1031
- if (pathname.slice(-1) === '/') {
1032
- pathname = pathname.substring(1);
1033
- segments.push({
1034
- type: 'pathname',
1035
- value: '/'
1036
- });
1037
- }
1038
-
1039
- return segments;
1040
- }
1041
- function interpolatePath(path, params, leaveWildcard) {
1042
- const interpolatedPathSegments = parsePathname(path);
1043
- return joinPaths(interpolatedPathSegments.map(segment => {
1044
- if (segment.value === '*' && !leaveWildcard) {
1045
- return '';
1046
- }
1047
-
1048
- if (segment.type === 'param') {
1049
- var _segment$value$substr;
1050
-
1051
- return (_segment$value$substr = params[segment.value.substring(1)]) != null ? _segment$value$substr : '';
1052
- }
1053
-
1054
- return segment.value;
1055
- }));
1056
- }
1057
- function matchPathname(currentPathname, matchLocation) {
1058
- const pathParams = matchByPath(currentPathname, matchLocation); // const searchMatched = matchBySearch(currentLocation.search, matchLocation)
1059
-
1060
- if (matchLocation.to && !pathParams) {
1061
- return;
1062
- } // if (matchLocation.search && !searchMatched) {
1063
- // return
1064
- // }
1065
-
1066
-
1067
- return pathParams != null ? pathParams : {};
1068
- }
1069
- function matchByPath(from, matchLocation) {
1070
- var _matchLocation$to;
1071
-
1072
- const baseSegments = parsePathname(from);
1073
- const routeSegments = parsePathname("" + ((_matchLocation$to = matchLocation.to) != null ? _matchLocation$to : '*'));
1074
- const params = {};
1075
-
1076
- let isMatch = (() => {
1077
- for (let i = 0; i < Math.max(baseSegments.length, routeSegments.length); i++) {
1078
- const baseSegment = baseSegments[i];
1079
- const routeSegment = routeSegments[i];
1080
- const isLastRouteSegment = i === routeSegments.length - 1;
1081
- const isLastBaseSegment = i === baseSegments.length - 1;
1082
-
1083
- if (routeSegment) {
1084
- if (routeSegment.type === 'wildcard') {
1085
- if (baseSegment != null && baseSegment.value) {
1086
- params['*'] = joinPaths(baseSegments.slice(i).map(d => d.value));
1087
- return true;
1088
- }
1089
-
1090
- return false;
1091
- }
1092
-
1093
- if (routeSegment.type === 'pathname') {
1094
- if (routeSegment.value === '/' && !(baseSegment != null && baseSegment.value)) {
1095
- return true;
1096
- }
1097
-
1098
- if (baseSegment) {
1099
- if (matchLocation.caseSensitive) {
1100
- if (routeSegment.value !== baseSegment.value) {
1101
- return false;
1102
- }
1103
- } else if (routeSegment.value.toLowerCase() !== baseSegment.value.toLowerCase()) {
1104
- return false;
1105
- }
1106
- }
1107
- }
1108
-
1109
- if (!baseSegment) {
1110
- return false;
1111
- }
1112
-
1113
- if (routeSegment.type === 'param') {
1114
- if ((baseSegment == null ? void 0 : baseSegment.value) === '/') {
1115
- return false;
1116
- }
1117
-
1118
- if (!baseSegment.value.startsWith(':')) {
1119
- params[routeSegment.value.substring(1)] = baseSegment.value;
1120
- }
1121
- }
1122
- }
1123
-
1124
- if (isLastRouteSegment && !isLastBaseSegment) {
1125
- return !!matchLocation.fuzzy;
1126
- }
1127
- }
1128
-
1129
- return true;
1130
- })();
1131
-
1132
- return isMatch ? params : undefined;
1133
- }
1134
-
1135
- // @ts-nocheck
1136
- // qss has been slightly modified and inlined here for our use cases (and compression's sake). We've included it as a hard dependency for MIT license attribution.
1137
- function encode(obj, pfx) {
1138
- var k,
1139
- i,
1140
- tmp,
1141
- str = '';
1142
-
1143
- for (k in obj) {
1144
- if ((tmp = obj[k]) !== void 0) {
1145
- if (Array.isArray(tmp)) {
1146
- for (i = 0; i < tmp.length; i++) {
1147
- str && (str += '&');
1148
- str += encodeURIComponent(k) + '=' + encodeURIComponent(tmp[i]);
1149
- }
1150
- } else {
1151
- str && (str += '&');
1152
- str += encodeURIComponent(k) + '=' + encodeURIComponent(tmp);
1153
- }
1154
- }
1155
- }
1156
-
1157
- return (pfx || '') + str;
1158
- }
1159
-
1160
- function toValue(mix) {
1161
- if (!mix) return '';
1162
- var str = decodeURIComponent(mix);
1163
- if (str === 'false') return false;
1164
- if (str === 'true') return true;
1165
- if (str.charAt(0) === '0') return str;
1166
- return +str * 0 === 0 ? +str : str;
1167
- }
1168
-
1169
- function decode(str) {
1170
- var tmp,
1171
- k,
1172
- out = {},
1173
- arr = str.split('&');
1174
-
1175
- while (tmp = arr.shift()) {
1176
- tmp = tmp.split('=');
1177
- k = tmp.shift();
1178
-
1179
- if (out[k] !== void 0) {
1180
- out[k] = [].concat(out[k], toValue(tmp.shift()));
1181
- } else {
1182
- out[k] = toValue(tmp.shift());
1183
- }
1184
- }
1185
-
1186
- return out;
1187
- }
1188
-
1189
- function _extends() {
1190
- _extends = Object.assign ? Object.assign.bind() : function (target) {
1191
- for (var i = 1; i < arguments.length; i++) {
1192
- var source = arguments[i];
1193
-
1194
- for (var key in source) {
1195
- if (Object.prototype.hasOwnProperty.call(source, key)) {
1196
- target[key] = source[key];
1197
- }
1198
- }
1199
- }
1200
-
1201
- return target;
1202
- };
1203
- return _extends.apply(this, arguments);
1204
- }
1205
-
1206
- function createRoute(routeConfig, options, parent, router) {
1207
- const {
1208
- id,
1209
- routeId,
1210
- path: routePath,
1211
- fullPath
1212
- } = routeConfig;
1213
-
1214
- const action = router.state.actions[id] || (() => {
1215
- router.state.actions[id] = {
1216
- pending: [],
1217
- submit: async (submission, actionOpts) => {
1218
- var _actionOpts$invalidat;
1219
-
1220
- if (!route) {
1221
- return;
1222
- }
1223
-
1224
- const invalidate = (_actionOpts$invalidat = actionOpts == null ? void 0 : actionOpts.invalidate) != null ? _actionOpts$invalidat : true;
1225
- const actionState = {
1226
- submittedAt: Date.now(),
1227
- status: 'pending',
1228
- submission
1229
- };
1230
- action.current = actionState;
1231
- action.latest = actionState;
1232
- action.pending.push(actionState);
1233
- router.state = _extends({}, router.state, {
1234
- currentAction: actionState,
1235
- latestAction: actionState
1236
- });
1237
- router.notify();
1238
-
1239
- try {
1240
- const res = await (route.options.action == null ? void 0 : route.options.action(submission));
1241
- actionState.data = res;
1242
-
1243
- if (invalidate) {
1244
- router.invalidateRoute({
1245
- to: '.',
1246
- fromCurrent: true
1247
- });
1248
- await router.reload();
1249
- }
1250
-
1251
- actionState.status = 'success';
1252
- return res;
1253
- } catch (err) {
1254
- console.error(err);
1255
- actionState.error = err;
1256
- actionState.status = 'error';
1257
- } finally {
1258
- action.pending = action.pending.filter(d => d !== actionState);
1259
- router.removeActionQueue.push({
1260
- action,
1261
- actionState
1262
- });
1263
- router.notify();
1264
- }
1265
- }
1266
- };
1267
- return router.state.actions[id];
1268
- })();
1269
-
1270
- const loader = router.state.loaders[id] || (() => {
1271
- router.state.loaders[id] = {
1272
- pending: [],
1273
- fetch: async loaderContext => {
1274
- if (!route) {
1275
- return;
1276
- }
1277
-
1278
- const loaderState = {
1279
- loadedAt: Date.now(),
1280
- loaderContext
1281
- };
1282
- loader.current = loaderState;
1283
- loader.latest = loaderState;
1284
- loader.pending.push(loaderState); // router.state = {
1285
- // ...router.state,
1286
- // currentAction: loaderState,
1287
- // latestAction: loaderState,
1288
- // }
1289
-
1290
- router.notify();
1291
-
1292
- try {
1293
- return await (route.options.loader == null ? void 0 : route.options.loader(loaderContext));
1294
- } finally {
1295
- loader.pending = loader.pending.filter(d => d !== loaderState); // router.removeActionQueue.push({ loader, loaderState })
1296
-
1297
- router.notify();
1298
- }
1299
- }
1300
- };
1301
- return router.state.loaders[id];
1302
- })();
1303
-
1304
- let route = {
1305
- routeId: id,
1306
- routeRouteId: routeId,
1307
- routePath,
1308
- fullPath,
1309
- options,
1310
- router,
1311
- childRoutes: undefined,
1312
- parentRoute: parent,
1313
- action,
1314
- loader: loader,
1315
- buildLink: options => {
1316
- return router.buildLink(_extends({}, options, {
1317
- from: fullPath
1318
- }));
1319
- },
1320
- navigate: options => {
1321
- return router.navigate(_extends({}, options, {
1322
- from: fullPath
1323
- }));
1324
- },
1325
- matchRoute: (matchLocation, opts) => {
1326
- return router.matchRoute(_extends({}, matchLocation, {
1327
- from: fullPath
1328
- }), opts);
1329
- }
1330
- };
1331
- router.options.createRoute == null ? void 0 : router.options.createRoute({
1332
- router,
1333
- route
1334
- });
1335
- return route;
1336
- }
1337
-
1338
- const rootRouteId = '__root__';
1339
- const createRouteConfig = function createRouteConfig(options, children, isRoot, parentId, parentPath) {
1340
- if (options === void 0) {
1341
- options = {};
1342
- }
1343
-
1344
- if (isRoot === void 0) {
1345
- isRoot = true;
1346
- }
1347
-
1348
- if (isRoot) {
1349
- options.path = rootRouteId;
1350
- } // Strip the root from parentIds
1351
-
1352
-
1353
- if (parentId === rootRouteId) {
1354
- parentId = '';
1355
- }
1356
-
1357
- let path = isRoot ? rootRouteId : options.path; // If the path is anything other than an index path, trim it up
1358
-
1359
- if (path && path !== '/') {
1360
- path = trimPath(path);
1361
- }
1362
-
1363
- const routeId = path || options.id;
1364
- let id = joinPaths([parentId, routeId]);
1365
-
1366
- if (path === rootRouteId) {
1367
- path = '/';
1368
- }
1369
-
1370
- if (id !== rootRouteId) {
1371
- id = joinPaths(['/', id]);
1372
- }
1373
-
1374
- const fullPath = id === rootRouteId ? '/' : trimPathRight(joinPaths([parentPath, path]));
1375
- return {
1376
- id: id,
1377
- routeId: routeId,
1378
- path: path,
1379
- fullPath: fullPath,
1380
- options: options,
1381
- children,
1382
- createChildren: cb => createRouteConfig(options, cb(childOptions => createRouteConfig(childOptions, undefined, false, id, fullPath)), false, parentId, parentPath),
1383
- addChildren: children => createRouteConfig(options, children, false, parentId, parentPath),
1384
- createRoute: childOptions => createRouteConfig(childOptions, undefined, false, id, fullPath)
1385
- };
1386
- };
1387
-
1388
- const elementTypes = ['element', 'errorElement', 'catchElement', 'pendingElement'];
1389
- function createRouteMatch(router, route, opts) {
1390
- const routeMatch = _extends({}, route, opts, {
1391
- router,
1392
- routeSearch: {},
1393
- search: {},
1394
- childMatches: [],
1395
- status: 'idle',
1396
- routeLoaderData: {},
1397
- loaderData: {},
1398
- isPending: false,
1399
- isFetching: false,
1400
- isInvalid: false,
1401
- invalidAt: Infinity,
1402
- getIsInvalid: () => {
1403
- const now = Date.now();
1404
- return routeMatch.isInvalid || routeMatch.invalidAt < now;
1405
- },
1406
- __: {
1407
- abortController: new AbortController(),
1408
- latestId: '',
1409
- resolve: () => {},
1410
- notify: () => {
1411
- routeMatch.__.resolve();
1412
-
1413
- routeMatch.router.notify();
1414
- },
1415
- startPending: () => {
1416
- var _routeMatch$options$p, _routeMatch$options$p2;
1417
-
1418
- const pendingMs = (_routeMatch$options$p = routeMatch.options.pendingMs) != null ? _routeMatch$options$p : router.options.defaultPendingMs;
1419
- const pendingMinMs = (_routeMatch$options$p2 = routeMatch.options.pendingMinMs) != null ? _routeMatch$options$p2 : router.options.defaultPendingMinMs;
1420
-
1421
- if (routeMatch.__.pendingTimeout || routeMatch.status !== 'loading' || typeof pendingMs === 'undefined') {
1422
- return;
1423
- }
1424
-
1425
- routeMatch.__.pendingTimeout = setTimeout(() => {
1426
- routeMatch.isPending = true;
1427
-
1428
- routeMatch.__.resolve();
1429
-
1430
- if (typeof pendingMinMs !== 'undefined') {
1431
- routeMatch.__.pendingMinPromise = new Promise(r => routeMatch.__.pendingMinTimeout = setTimeout(r, pendingMinMs));
1432
- }
1433
- }, pendingMs);
1434
- },
1435
- cancelPending: () => {
1436
- routeMatch.isPending = false;
1437
- clearTimeout(routeMatch.__.pendingTimeout);
1438
- clearTimeout(routeMatch.__.pendingMinTimeout);
1439
- delete routeMatch.__.pendingMinPromise;
1440
- },
1441
- // setParentMatch: (parentMatch?: RouteMatch) => {
1442
- // routeMatch.parentMatch = parentMatch
1443
- // },
1444
- // addChildMatch: (childMatch: RouteMatch) => {
1445
- // if (
1446
- // routeMatch.childMatches.find((d) => d.matchId === childMatch.matchId)
1447
- // ) {
1448
- // return
1449
- // }
1450
- // routeMatch.childMatches.push(childMatch)
1451
- // },
1452
- validate: () => {
1453
- var _routeMatch$parentMat, _routeMatch$parentMat2;
1454
-
1455
- // Validate the search params and stabilize them
1456
- const parentSearch = (_routeMatch$parentMat = (_routeMatch$parentMat2 = routeMatch.parentMatch) == null ? void 0 : _routeMatch$parentMat2.search) != null ? _routeMatch$parentMat : router.location.search;
1457
-
1458
- try {
1459
- const prevSearch = routeMatch.routeSearch;
1460
- const validator = typeof routeMatch.options.validateSearch === 'object' ? routeMatch.options.validateSearch.parse : routeMatch.options.validateSearch;
1461
- let nextSearch = replaceEqualDeep(prevSearch, validator == null ? void 0 : validator(parentSearch)); // Invalidate route matches when search param stability changes
1462
-
1463
- if (prevSearch !== nextSearch) {
1464
- routeMatch.isInvalid = true;
1465
- }
1466
-
1467
- routeMatch.routeSearch = nextSearch;
1468
- routeMatch.search = replaceEqualDeep(parentSearch, _extends({}, parentSearch, nextSearch));
1469
- } catch (err) {
1470
- console.error(err);
1471
- const error = new Error('Invalid search params found', {
1472
- cause: err
1473
- });
1474
- error.code = 'INVALID_SEARCH_PARAMS';
1475
- routeMatch.status = 'error';
1476
- routeMatch.error = error; // Do not proceed with loading the route
1477
-
1478
- return;
1479
- }
1480
- }
1481
- },
1482
- cancel: () => {
1483
- var _routeMatch$__$abortC;
1484
-
1485
- (_routeMatch$__$abortC = routeMatch.__.abortController) == null ? void 0 : _routeMatch$__$abortC.abort();
1486
-
1487
- routeMatch.__.cancelPending();
1488
- },
1489
- invalidate: () => {
1490
- routeMatch.isInvalid = true;
1491
- },
1492
- hasLoaders: () => {
1493
- return !!(route.options.loader || elementTypes.some(d => typeof route.options[d] === 'function'));
1494
- },
1495
- load: async loaderOpts => {
1496
- const now = Date.now();
1497
- const minMaxAge = loaderOpts != null && loaderOpts.preload ? Math.max(loaderOpts == null ? void 0 : loaderOpts.maxAge, loaderOpts == null ? void 0 : loaderOpts.gcMaxAge) : 0; // If this is a preload, add it to the preload cache
1498
-
1499
- if (loaderOpts != null && loaderOpts.preload && minMaxAge > 0) {
1500
- // If the match is currently active, don't preload it
1501
- if (router.state.matches.find(d => d.matchId === routeMatch.matchId)) {
1502
- return;
1503
- }
1504
-
1505
- router.matchCache[routeMatch.matchId] = {
1506
- gc: now + loaderOpts.gcMaxAge,
1507
- match: routeMatch
1508
- };
1509
- } // If the match is invalid, errored or idle, trigger it to load
1510
-
1511
-
1512
- if (routeMatch.status === 'success' && routeMatch.getIsInvalid() || routeMatch.status === 'error' || routeMatch.status === 'idle') {
1513
- const maxAge = loaderOpts != null && loaderOpts.preload ? loaderOpts == null ? void 0 : loaderOpts.maxAge : undefined;
1514
- routeMatch.fetch({
1515
- maxAge
1516
- });
1517
- }
1518
- },
1519
- fetch: async opts => {
1520
- const id = '' + Date.now() + Math.random();
1521
- routeMatch.__.latestId = id; // If the match was in an error state, set it
1522
- // to a loading state again. Otherwise, keep it
1523
- // as loading or resolved
1524
-
1525
- if (routeMatch.status === 'idle') {
1526
- routeMatch.status = 'loading';
1527
- } // We started loading the route, so it's no longer invalid
1528
-
1529
-
1530
- routeMatch.isInvalid = false;
1531
- routeMatch.__.loadPromise = new Promise(async resolve => {
1532
- // We are now fetching, even if it's in the background of a
1533
- // resolved state
1534
- routeMatch.isFetching = true;
1535
- routeMatch.__.resolve = resolve;
1536
-
1537
- const loaderPromise = (async () => {
1538
- // Load the elements and data in parallel
1539
- routeMatch.__.elementsPromise = (async () => {
1540
- // then run all element and data loaders in parallel
1541
- // For each element type, potentially load it asynchronously
1542
- await Promise.all(elementTypes.map(async type => {
1543
- const routeElement = routeMatch.options[type];
1544
-
1545
- if (routeMatch.__[type]) {
1546
- return;
1547
- }
1548
-
1549
- routeMatch.__[type] = await router.options.createElement(routeElement);
1550
- }));
1551
- })();
1552
-
1553
- routeMatch.__.dataPromise = Promise.resolve().then(async () => {
1554
- try {
1555
- var _ref, _ref2, _opts$maxAge;
1556
-
1557
- if (routeMatch.options.loader) {
1558
- const data = await routeMatch.options.loader({
1559
- params: routeMatch.params,
1560
- search: routeMatch.routeSearch,
1561
- signal: routeMatch.__.abortController.signal
1562
- });
1563
-
1564
- if (id !== routeMatch.__.latestId) {
1565
- return routeMatch.__.loaderPromise;
1566
- }
1567
-
1568
- routeMatch.routeLoaderData = replaceEqualDeep(routeMatch.routeLoaderData, data);
1569
- }
1570
-
1571
- routeMatch.error = undefined;
1572
- routeMatch.status = 'success';
1573
- routeMatch.updatedAt = Date.now();
1574
- routeMatch.invalidAt = routeMatch.updatedAt + ((_ref = (_ref2 = (_opts$maxAge = opts == null ? void 0 : opts.maxAge) != null ? _opts$maxAge : routeMatch.options.loaderMaxAge) != null ? _ref2 : router.options.defaultLoaderMaxAge) != null ? _ref : 0);
1575
- } catch (err) {
1576
- if (id !== routeMatch.__.latestId) {
1577
- return routeMatch.__.loaderPromise;
1578
- }
1579
-
1580
- if (process.env.NODE_ENV !== 'production') {
1581
- console.error(err);
1582
- }
1583
-
1584
- routeMatch.error = err;
1585
- routeMatch.status = 'error';
1586
- routeMatch.updatedAt = Date.now();
1587
- }
1588
- });
1589
-
1590
- try {
1591
- await Promise.all([routeMatch.__.elementsPromise, routeMatch.__.dataPromise]);
1592
-
1593
- if (id !== routeMatch.__.latestId) {
1594
- return routeMatch.__.loaderPromise;
1595
- }
1596
-
1597
- if (routeMatch.__.pendingMinPromise) {
1598
- await routeMatch.__.pendingMinPromise;
1599
- delete routeMatch.__.pendingMinPromise;
1600
- }
1601
- } finally {
1602
- if (id !== routeMatch.__.latestId) {
1603
- return routeMatch.__.loaderPromise;
1604
- }
1605
-
1606
- routeMatch.__.cancelPending();
1607
-
1608
- routeMatch.isPending = false;
1609
- routeMatch.isFetching = false;
1610
-
1611
- routeMatch.__.notify();
1612
- }
1613
- })();
1614
-
1615
- routeMatch.__.loaderPromise = loaderPromise;
1616
- await loaderPromise;
1617
-
1618
- if (id !== routeMatch.__.latestId) {
1619
- return routeMatch.__.loaderPromise;
1620
- }
1621
-
1622
- delete routeMatch.__.loaderPromise;
1623
- });
1624
- return await routeMatch.__.loadPromise;
1625
- }
1626
- });
1627
-
1628
- if (!routeMatch.hasLoaders()) {
1629
- routeMatch.status = 'success';
1630
- }
1631
-
1632
- return routeMatch;
1633
- }
1634
-
1635
- const defaultParseSearch = parseSearchWith(JSON.parse);
1636
- const defaultStringifySearch = stringifySearchWith(JSON.stringify);
1637
- function parseSearchWith(parser) {
1638
- return searchStr => {
1639
- if (searchStr.substring(0, 1) === '?') {
1640
- searchStr = searchStr.substring(1);
1641
- }
1642
-
1643
- let query = decode(searchStr); // Try to parse any query params that might be json
1644
-
1645
- for (let key in query) {
1646
- const value = query[key];
1647
-
1648
- if (typeof value === 'string') {
1649
- try {
1650
- query[key] = parser(value);
1651
- } catch (err) {//
1652
- }
1653
- }
1654
- }
1655
-
1656
- return query;
1657
- };
1658
- }
1659
- function stringifySearchWith(stringify) {
1660
- return search => {
1661
- search = _extends({}, search);
1662
-
1663
- if (search) {
1664
- Object.keys(search).forEach(key => {
1665
- const val = search[key];
1666
-
1667
- if (typeof val === 'undefined' || val === undefined) {
1668
- delete search[key];
1669
- } else if (val && typeof val === 'object' && val !== null) {
1670
- try {
1671
- search[key] = stringify(val);
1672
- } catch (err) {// silent
1673
- }
1674
- }
1675
- });
1676
- }
1677
-
1678
- const searchStr = encode(search).toString();
1679
- return searchStr ? "?" + searchStr : '';
1680
- };
1681
- }
1682
-
1683
- var _window$document;
1684
- // Detect if we're in the DOM
1685
- const isServer = typeof window === 'undefined' || !((_window$document = window.document) != null && _window$document.createElement); // This is the default history object if none is defined
1686
-
1687
- const createDefaultHistory = () => isServer ? createMemoryHistory() : createBrowserHistory();
1688
-
1689
- function createRouter(userOptions) {
1690
- var _userOptions$stringif, _userOptions$parseSea;
1691
-
1692
- const history = (userOptions == null ? void 0 : userOptions.history) || createDefaultHistory();
1693
-
1694
- const originalOptions = _extends({
1695
- defaultLoaderGcMaxAge: 5 * 60 * 1000,
1696
- defaultLoaderMaxAge: 0,
1697
- defaultPreloadMaxAge: 2000,
1698
- defaultPreloadDelay: 50
1699
- }, userOptions, {
1700
- stringifySearch: (_userOptions$stringif = userOptions == null ? void 0 : userOptions.stringifySearch) != null ? _userOptions$stringif : defaultStringifySearch,
1701
- parseSearch: (_userOptions$parseSea = userOptions == null ? void 0 : userOptions.parseSearch) != null ? _userOptions$parseSea : defaultParseSearch
1702
- });
1703
-
1704
- let router = {
1705
- history,
1706
- options: originalOptions,
1707
- listeners: [],
1708
- removeActionQueue: [],
1709
- // Resolved after construction
1710
- basepath: '',
1711
- routeTree: undefined,
1712
- routesById: {},
1713
- location: undefined,
1714
- allRouteInfo: undefined,
1715
- //
1716
- navigationPromise: Promise.resolve(),
1717
- resolveNavigation: () => {},
1718
- matchCache: {},
1719
- state: {
1720
- status: 'idle',
1721
- location: null,
1722
- matches: [],
1723
- actions: {},
1724
- loaders: {},
1725
- lastUpdated: Date.now(),
1726
- isFetching: false,
1727
- isPreloading: false
1728
- },
1729
- startedLoadingAt: Date.now(),
1730
- subscribe: listener => {
1731
- router.listeners.push(listener);
1732
- return () => {
1733
- router.listeners = router.listeners.filter(x => x !== listener);
1734
- };
1735
- },
1736
- getRoute: id => {
1737
- return router.routesById[id];
1738
- },
1739
- notify: () => {
1740
- router.state = _extends({}, router.state, {
1741
- isFetching: router.state.status === 'loading' || router.state.matches.some(d => d.isFetching),
1742
- isPreloading: Object.values(router.matchCache).some(d => d.match.isFetching && !router.state.matches.find(dd => dd.matchId === d.match.matchId))
1743
- });
1744
- cascadeLoaderData(router.state.matches);
1745
- router.listeners.forEach(listener => listener(router));
1746
- },
1747
- dehydrateState: () => {
1748
- return _extends({}, pick(router.state, ['status', 'location', 'lastUpdated']), {
1749
- matches: router.state.matches.map(match => pick(match, ['matchId', 'status', 'routeLoaderData', 'loaderData', 'isInvalid', 'invalidAt']))
1750
- });
1751
- },
1752
- hydrateState: dehydratedState => {
1753
- // Match the routes
1754
- const matches = router.matchRoutes(router.location.pathname, {
1755
- strictParseParams: true
1756
- });
1757
- router.state = _extends({}, router.state, dehydratedState, {
1758
- matches: matches.map(match => {
1759
- const dehydratedMatch = dehydratedState.matches.find(d => d.matchId === match.matchId);
1760
- invariant(dehydratedMatch, 'Oh no! Dehydrated route matches did not match the active state of the router 😬');
1761
- Object.assign(match, dehydratedMatch);
1762
- return match;
1763
- })
1764
- });
1765
- },
1766
- mount: () => {
1767
- const next = router.__.buildLocation({
1768
- to: '.',
1769
- search: true,
1770
- hash: true
1771
- }); // If the current location isn't updated, trigger a navigation
1772
- // to the current location. Otherwise, load the current location.
1773
-
1774
-
1775
- if (next.href !== router.location.href) {
1776
- router.__.commitLocation(next, true);
1777
- }
1778
-
1779
- router.loadLocation();
1780
- const unsub = router.history.listen(event => {
1781
- console.log(event.location);
1782
- router.loadLocation(router.__.parseLocation(event.location, router.location));
1783
- }); // addEventListener does not exist in React Native, but window does
1784
- // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
1785
-
1786
- if (!isServer && window.addEventListener) {
1787
- // Listen to visibillitychange and focus
1788
- window.addEventListener('visibilitychange', router.onFocus, false);
1789
- window.addEventListener('focus', router.onFocus, false);
1790
- }
1791
-
1792
- return () => {
1793
- unsub(); // Be sure to unsubscribe if a new handler is set
1794
-
1795
- window.removeEventListener('visibilitychange', router.onFocus);
1796
- window.removeEventListener('focus', router.onFocus);
1797
- };
1798
- },
1799
- onFocus: () => {
1800
- router.loadLocation();
1801
- },
1802
- update: opts => {
1803
- const newHistory = (opts == null ? void 0 : opts.history) !== router.history;
1804
-
1805
- if (!router.location || newHistory) {
1806
- if (opts != null && opts.history) {
1807
- router.history = opts.history;
1808
- }
1809
-
1810
- router.location = router.__.parseLocation(router.history.location);
1811
- router.state.location = router.location;
1812
- }
1813
-
1814
- Object.assign(router.options, opts);
1815
- const {
1816
- basepath,
1817
- routeConfig
1818
- } = router.options;
1819
- router.basepath = cleanPath("/" + (basepath != null ? basepath : ''));
1820
-
1821
- if (routeConfig) {
1822
- router.routesById = {};
1823
- router.routeTree = router.__.buildRouteTree(routeConfig);
1824
- }
1825
-
1826
- return router;
1827
- },
1828
- cancelMatches: () => {
1829
- var _router$state$pending, _router$state$pending2;
1830
- [...router.state.matches, ...((_router$state$pending = (_router$state$pending2 = router.state.pending) == null ? void 0 : _router$state$pending2.matches) != null ? _router$state$pending : [])].forEach(match => {
1831
- match.cancel();
1832
- });
1833
- },
1834
- loadLocation: async next => {
1835
- const id = Math.random();
1836
- router.startedLoadingAt = id;
1837
-
1838
- if (next) {
1839
- // Ingest the new location
1840
- router.location = next;
1841
- } // Clear out old actions
1842
-
1843
-
1844
- router.removeActionQueue.forEach(_ref => {
1845
- let {
1846
- action,
1847
- actionState
1848
- } = _ref;
1849
-
1850
- if (router.state.currentAction === actionState) {
1851
- router.state.currentAction = undefined;
1852
- }
1853
-
1854
- if (action.current === actionState) {
1855
- action.current = undefined;
1856
- }
1857
- });
1858
- router.removeActionQueue = []; // Cancel any pending matches
1859
-
1860
- router.cancelMatches(); // Match the routes
1861
-
1862
- const matches = router.matchRoutes(router.location.pathname, {
1863
- strictParseParams: true
1864
- });
1865
- router.state = _extends({}, router.state, {
1866
- pending: {
1867
- matches: matches,
1868
- location: router.location
1869
- },
1870
- status: 'loading'
1871
- });
1872
- router.notify(); // Load the matches
1873
-
1874
- await router.loadMatches(matches, {
1875
- withPending: true
1876
- });
1877
-
1878
- if (router.startedLoadingAt !== id) {
1879
- // Ignore side-effects of match loading
1880
- return router.navigationPromise;
1881
- }
1882
-
1883
- const previousMatches = router.state.matches;
1884
- const exiting = [],
1885
- staying = [];
1886
- previousMatches.forEach(d => {
1887
- if (matches.find(dd => dd.matchId === d.matchId)) {
1888
- staying.push(d);
1889
- } else {
1890
- exiting.push(d);
1891
- }
1892
- });
1893
- const now = Date.now();
1894
- exiting.forEach(d => {
1895
- var _ref2, _d$options$loaderGcMa, _ref3, _d$options$loaderMaxA;
1896
-
1897
- d.__.onExit == null ? void 0 : d.__.onExit({
1898
- params: d.params,
1899
- search: d.routeSearch
1900
- }); // Clear idle error states when match leaves
1901
-
1902
- if (d.status === 'error' && !d.isFetching) {
1903
- d.status = 'idle';
1904
- d.error = undefined;
1905
- }
1906
-
1907
- const gc = Math.max((_ref2 = (_d$options$loaderGcMa = d.options.loaderGcMaxAge) != null ? _d$options$loaderGcMa : router.options.defaultLoaderGcMaxAge) != null ? _ref2 : 0, (_ref3 = (_d$options$loaderMaxA = d.options.loaderMaxAge) != null ? _d$options$loaderMaxA : router.options.defaultLoaderMaxAge) != null ? _ref3 : 0);
1908
-
1909
- if (gc > 0) {
1910
- router.matchCache[d.matchId] = {
1911
- gc: gc == Infinity ? Number.MAX_SAFE_INTEGER : now + gc,
1912
- match: d
1913
- };
1914
- }
1915
- });
1916
- staying.forEach(d => {
1917
- d.options.onTransition == null ? void 0 : d.options.onTransition({
1918
- params: d.params,
1919
- search: d.routeSearch
1920
- });
1921
- });
1922
- const entering = matches.filter(d => {
1923
- return !previousMatches.find(dd => dd.matchId === d.matchId);
1924
- });
1925
- entering.forEach(d => {
1926
- d.__.onExit = d.options.onMatch == null ? void 0 : d.options.onMatch({
1927
- params: d.params,
1928
- search: d.search
1929
- });
1930
- delete router.matchCache[d.matchId];
1931
- });
1932
-
1933
- if (matches.some(d => d.status === 'loading')) {
1934
- router.notify();
1935
- await Promise.all(matches.map(d => d.__.loaderPromise || Promise.resolve()));
1936
- }
1937
-
1938
- if (router.startedLoadingAt !== id) {
1939
- // Ignore side-effects of match loading
1940
- return;
1941
- }
1942
-
1943
- router.state = _extends({}, router.state, {
1944
- location: router.location,
1945
- matches,
1946
- pending: undefined,
1947
- status: 'idle'
1948
- });
1949
- router.notify();
1950
- router.resolveNavigation();
1951
- },
1952
- cleanMatchCache: () => {
1953
- const now = Date.now();
1954
- Object.keys(router.matchCache).forEach(matchId => {
1955
- const entry = router.matchCache[matchId]; // Don't remove loading matches
1956
-
1957
- if (entry.match.status === 'loading') {
1958
- return;
1959
- } // Do not remove successful matches that are still valid
1960
-
1961
-
1962
- if (entry.gc > 0 && entry.gc > now) {
1963
- return;
1964
- } // Everything else gets removed
1965
-
1966
-
1967
- delete router.matchCache[matchId];
1968
- });
1969
- },
1970
- loadRoute: async function loadRoute(navigateOpts) {
1971
- if (navigateOpts === void 0) {
1972
- navigateOpts = router.location;
1973
- }
1974
-
1975
- const next = router.buildNext(navigateOpts);
1976
- const matches = router.matchRoutes(next.pathname, {
1977
- strictParseParams: true
1978
- });
1979
- await router.loadMatches(matches);
1980
- return matches;
1981
- },
1982
- preloadRoute: async function preloadRoute(navigateOpts, loaderOpts) {
1983
- var _ref4, _ref5, _loaderOpts$maxAge, _ref6, _ref7, _loaderOpts$gcMaxAge;
1984
-
1985
- if (navigateOpts === void 0) {
1986
- navigateOpts = router.location;
1987
- }
1988
-
1989
- const next = router.buildNext(navigateOpts);
1990
- const matches = router.matchRoutes(next.pathname, {
1991
- strictParseParams: true
1992
- });
1993
- await router.loadMatches(matches, {
1994
- preload: true,
1995
- maxAge: (_ref4 = (_ref5 = (_loaderOpts$maxAge = loaderOpts.maxAge) != null ? _loaderOpts$maxAge : router.options.defaultPreloadMaxAge) != null ? _ref5 : router.options.defaultLoaderMaxAge) != null ? _ref4 : 0,
1996
- gcMaxAge: (_ref6 = (_ref7 = (_loaderOpts$gcMaxAge = loaderOpts.gcMaxAge) != null ? _loaderOpts$gcMaxAge : router.options.defaultPreloadGcMaxAge) != null ? _ref7 : router.options.defaultLoaderGcMaxAge) != null ? _ref6 : 0
1997
- });
1998
- return matches;
1999
- },
2000
- matchRoutes: (pathname, opts) => {
2001
- var _router$state$pending3, _router$state$pending4;
2002
-
2003
- router.cleanMatchCache();
2004
- const matches = [];
2005
-
2006
- if (!router.routeTree) {
2007
- return matches;
2008
- }
2009
-
2010
- const existingMatches = [...router.state.matches, ...((_router$state$pending3 = (_router$state$pending4 = router.state.pending) == null ? void 0 : _router$state$pending4.matches) != null ? _router$state$pending3 : [])];
2011
-
2012
- const recurse = async routes => {
2013
- var _parentMatch$params, _router$options$filte, _foundRoute$childRout;
2014
-
2015
- const parentMatch = last(matches);
2016
- let params = (_parentMatch$params = parentMatch == null ? void 0 : parentMatch.params) != null ? _parentMatch$params : {};
2017
- const filteredRoutes = (_router$options$filte = router.options.filterRoutes == null ? void 0 : router.options.filterRoutes(routes)) != null ? _router$options$filte : routes;
2018
- let foundRoutes = [];
2019
-
2020
- const findMatchInRoutes = (parentRoutes, routes) => {
2021
- routes.some(route => {
2022
- var _route$childRoutes, _route$childRoutes2, _route$options$caseSe;
2023
-
2024
- if (!route.routePath && (_route$childRoutes = route.childRoutes) != null && _route$childRoutes.length) {
2025
- return findMatchInRoutes([...foundRoutes, route], route.childRoutes);
2026
- }
2027
-
2028
- const fuzzy = !!(route.routePath !== '/' || (_route$childRoutes2 = route.childRoutes) != null && _route$childRoutes2.length);
2029
- const matchParams = matchPathname(pathname, {
2030
- to: route.fullPath,
2031
- fuzzy,
2032
- caseSensitive: (_route$options$caseSe = route.options.caseSensitive) != null ? _route$options$caseSe : router.options.caseSensitive
2033
- });
2034
-
2035
- if (matchParams) {
2036
- let parsedParams;
2037
-
2038
- try {
2039
- var _route$options$parseP;
2040
-
2041
- parsedParams = (_route$options$parseP = route.options.parseParams == null ? void 0 : route.options.parseParams(matchParams)) != null ? _route$options$parseP : matchParams;
2042
- } catch (err) {
2043
- if (opts != null && opts.strictParseParams) {
2044
- throw err;
2045
- }
2046
- }
2047
-
2048
- params = _extends({}, params, parsedParams);
2049
- }
2050
-
2051
- if (!!matchParams) {
2052
- foundRoutes = [...parentRoutes, route];
2053
- }
2054
-
2055
- return !!foundRoutes.length;
2056
- });
2057
- return !!foundRoutes.length;
2058
- };
2059
-
2060
- findMatchInRoutes([], filteredRoutes);
2061
-
2062
- if (!foundRoutes.length) {
2063
- return;
2064
- }
2065
-
2066
- foundRoutes.forEach(foundRoute => {
2067
- var _router$matchCache$ma;
2068
-
2069
- const interpolatedPath = interpolatePath(foundRoute.routePath, params);
2070
- const matchId = interpolatePath(foundRoute.routeId, params, true);
2071
- const match = existingMatches.find(d => d.matchId === matchId) || ((_router$matchCache$ma = router.matchCache[matchId]) == null ? void 0 : _router$matchCache$ma.match) || createRouteMatch(router, foundRoute, {
2072
- matchId,
2073
- params,
2074
- pathname: joinPaths([pathname, interpolatedPath])
2075
- });
2076
- matches.push(match);
2077
- });
2078
- const foundRoute = last(foundRoutes);
2079
-
2080
- if ((_foundRoute$childRout = foundRoute.childRoutes) != null && _foundRoute$childRout.length) {
2081
- recurse(foundRoute.childRoutes);
2082
- }
2083
- };
2084
-
2085
- recurse([router.routeTree]);
2086
- cascadeLoaderData(matches);
2087
- return matches;
2088
- },
2089
- loadMatches: async (resolvedMatches, loaderOpts) => {
2090
- const matchPromises = resolvedMatches.map(async match => {
2091
- // Validate the match (loads search params etc)
2092
- match.__.validate();
2093
-
2094
- match.load(loaderOpts);
2095
-
2096
- if (match.status === 'loading') {
2097
- // If requested, start the pending timers
2098
- if (loaderOpts != null && loaderOpts.withPending) match.__.startPending(); // Wait for the first sign of activity from the match
2099
- // This might be completion, error, or a pending state
2100
-
2101
- await match.__.loadPromise;
2102
- }
2103
- });
2104
- router.notify();
2105
- await Promise.all(matchPromises);
2106
- },
2107
- invalidateRoute: opts => {
2108
- var _router$state$pending5, _router$state$pending6;
2109
-
2110
- const next = router.buildNext(opts);
2111
- const unloadedMatchIds = router.matchRoutes(next.pathname).map(d => d.matchId);
2112
- [...router.state.matches, ...((_router$state$pending5 = (_router$state$pending6 = router.state.pending) == null ? void 0 : _router$state$pending6.matches) != null ? _router$state$pending5 : [])].forEach(match => {
2113
- if (unloadedMatchIds.includes(match.matchId)) {
2114
- match.invalidate();
2115
- }
2116
- });
2117
- },
2118
- reload: () => router.__.navigate({
2119
- fromCurrent: true,
2120
- replace: true,
2121
- search: true
2122
- }),
2123
- resolvePath: (from, path) => {
2124
- return resolvePath(router.basepath, from, cleanPath(path));
2125
- },
2126
- matchRoute: (location, opts) => {
2127
- var _location$from;
2128
-
2129
- // const location = router.buildNext(opts)
2130
- location = _extends({}, location, {
2131
- to: location.to ? router.resolvePath((_location$from = location.from) != null ? _location$from : '', location.to) : undefined
2132
- });
2133
- const next = router.buildNext(location);
2134
-
2135
- if (opts != null && opts.pending) {
2136
- var _router$state$pending7;
2137
-
2138
- if (!((_router$state$pending7 = router.state.pending) != null && _router$state$pending7.location)) {
2139
- return false;
2140
- }
2141
-
2142
- return !!matchPathname(router.state.pending.location.pathname, _extends({}, opts, {
2143
- to: next.pathname
2144
- }));
2145
- }
2146
-
2147
- return !!matchPathname(router.state.location.pathname, _extends({}, opts, {
2148
- to: next.pathname
2149
- }));
2150
- },
2151
- navigate: async _ref8 => {
2152
- let {
2153
- from,
2154
- to = '.',
2155
- search,
2156
- hash,
2157
- replace,
2158
- params
2159
- } = _ref8;
2160
- // If this link simply reloads the current route,
2161
- // make sure it has a new key so it will trigger a data refresh
2162
- // If this `to` is a valid external URL, return
2163
- // null for LinkUtils
2164
- const toString = String(to);
2165
- const fromString = String(from);
2166
- let isExternal;
2167
-
2168
- try {
2169
- new URL("" + toString);
2170
- isExternal = true;
2171
- } catch (e) {}
2172
-
2173
- invariant(!isExternal, 'Attempting to navigate to external url with router.navigate!');
2174
- return router.__.navigate({
2175
- from: fromString,
2176
- to: toString,
2177
- search,
2178
- hash,
2179
- replace,
2180
- params
2181
- });
2182
- },
2183
- buildLink: _ref9 => {
2184
- var _preload, _ref10;
2185
-
2186
- let {
2187
- from,
2188
- to = '.',
2189
- search,
2190
- params,
2191
- hash,
2192
- target,
2193
- replace,
2194
- activeOptions,
2195
- preload,
2196
- preloadMaxAge: userPreloadMaxAge,
2197
- preloadGcMaxAge: userPreloadGcMaxAge,
2198
- preloadDelay: userPreloadDelay,
2199
- disabled
2200
- } = _ref9;
2201
-
2202
- // If this link simply reloads the current route,
2203
- // make sure it has a new key so it will trigger a data refresh
2204
- // If this `to` is a valid external URL, return
2205
- // null for LinkUtils
2206
- try {
2207
- new URL("" + to);
2208
- return {
2209
- type: 'external',
2210
- href: to
2211
- };
2212
- } catch (e) {}
2213
-
2214
- const nextOpts = {
2215
- from,
2216
- to,
2217
- search,
2218
- params,
2219
- hash,
2220
- replace
2221
- };
2222
- const next = router.buildNext(nextOpts);
2223
- preload = (_preload = preload) != null ? _preload : router.options.defaultPreload;
2224
- const preloadDelay = (_ref10 = userPreloadDelay != null ? userPreloadDelay : router.options.defaultPreloadDelay) != null ? _ref10 : 0; // Compare path/hash for matches
2225
-
2226
- const pathIsEqual = router.state.location.pathname === next.pathname;
2227
- const currentPathSplit = router.state.location.pathname.split('/');
2228
- const nextPathSplit = next.pathname.split('/');
2229
- const pathIsFuzzyEqual = nextPathSplit.every((d, i) => d === currentPathSplit[i]);
2230
- const hashIsEqual = router.state.location.hash === next.hash; // Combine the matches based on user options
2231
-
2232
- const pathTest = activeOptions != null && activeOptions.exact ? pathIsEqual : pathIsFuzzyEqual;
2233
- const hashTest = activeOptions != null && activeOptions.includeHash ? hashIsEqual : true; // The final "active" test
2234
-
2235
- const isActive = pathTest && hashTest; // The click handler
2236
-
2237
- const handleClick = e => {
2238
- if (!disabled && !isCtrlEvent(e) && !e.defaultPrevented && (!target || target === '_self') && e.button === 0) {
2239
- e.preventDefault();
2240
-
2241
- if (pathIsEqual && !search && !hash) {
2242
- router.invalidateRoute(nextOpts);
2243
- } // All is well? Navigate!)
2244
-
2245
-
2246
- router.__.navigate(nextOpts);
2247
- }
2248
- }; // The click handler
2249
-
2250
-
2251
- const handleFocus = e => {
2252
- if (preload) {
2253
- router.preloadRoute(nextOpts, {
2254
- maxAge: userPreloadMaxAge,
2255
- gcMaxAge: userPreloadGcMaxAge
2256
- });
2257
- }
2258
- };
2259
-
2260
- const handleEnter = e => {
2261
- const target = e.target || {};
2262
-
2263
- if (preload) {
2264
- if (target.preloadTimeout) {
2265
- return;
2266
- }
2267
-
2268
- target.preloadTimeout = setTimeout(() => {
2269
- target.preloadTimeout = null;
2270
- router.preloadRoute(nextOpts, {
2271
- maxAge: userPreloadMaxAge,
2272
- gcMaxAge: userPreloadGcMaxAge
2273
- });
2274
- }, preloadDelay);
2275
- }
2276
- };
2277
-
2278
- const handleLeave = e => {
2279
- const target = e.target || {};
2280
-
2281
- if (target.preloadTimeout) {
2282
- clearTimeout(target.preloadTimeout);
2283
- target.preloadTimeout = null;
2284
- }
2285
- };
2286
-
2287
- return {
2288
- type: 'internal',
2289
- next,
2290
- handleFocus,
2291
- handleClick,
2292
- handleEnter,
2293
- handleLeave,
2294
- isActive,
2295
- disabled
2296
- };
2297
- },
2298
- buildNext: opts => {
2299
- const next = router.__.buildLocation(opts);
2300
-
2301
- const matches = router.matchRoutes(next.pathname);
2302
-
2303
- const __preSearchFilters = matches.map(match => {
2304
- var _match$options$preSea;
2305
-
2306
- return (_match$options$preSea = match.options.preSearchFilters) != null ? _match$options$preSea : [];
2307
- }).flat().filter(Boolean);
2308
-
2309
- const __postSearchFilters = matches.map(match => {
2310
- var _match$options$postSe;
2311
-
2312
- return (_match$options$postSe = match.options.postSearchFilters) != null ? _match$options$postSe : [];
2313
- }).flat().filter(Boolean);
2314
-
2315
- return router.__.buildLocation(_extends({}, opts, {
2316
- __preSearchFilters,
2317
- __postSearchFilters
2318
- }));
2319
- },
2320
- __: {
2321
- buildRouteTree: rootRouteConfig => {
2322
- const recurseRoutes = (routeConfigs, parent) => {
2323
- return routeConfigs.map(routeConfig => {
2324
- const routeOptions = routeConfig.options;
2325
- const route = createRoute(routeConfig, routeOptions, parent, router);
2326
- const existingRoute = router.routesById[route.routeId];
2327
-
2328
- if (existingRoute) {
2329
- if (process.env.NODE_ENV !== 'production') {
2330
- console.warn("Duplicate routes found with id: " + String(route.routeId), router.routesById, route);
2331
- }
2332
-
2333
- throw new Error();
2334
- }
2335
- router.routesById[route.routeId] = route;
2336
- const children = routeConfig.children;
2337
- route.childRoutes = children != null && children.length ? recurseRoutes(children, route) : undefined;
2338
- return route;
2339
- });
2340
- };
2341
-
2342
- const routes = recurseRoutes([rootRouteConfig]);
2343
- return routes[0];
2344
- },
2345
- parseLocation: (location, previousLocation) => {
2346
- var _location$hash$split$;
2347
-
2348
- const parsedSearch = router.options.parseSearch(location.search);
2349
- return {
2350
- pathname: location.pathname,
2351
- searchStr: location.search,
2352
- search: replaceEqualDeep(previousLocation == null ? void 0 : previousLocation.search, parsedSearch),
2353
- hash: (_location$hash$split$ = location.hash.split('#').reverse()[0]) != null ? _location$hash$split$ : '',
2354
- href: "" + location.pathname + location.search + location.hash,
2355
- state: location.state,
2356
- key: location.key
2357
- };
2358
- },
2359
- navigate: location => {
2360
- const next = router.buildNext(location);
2361
- return router.__.commitLocation(next, location.replace);
2362
- },
2363
- buildLocation: function buildLocation(dest) {
2364
- var _dest$from, _router$basepath, _dest$to, _last, _dest$params, _dest$__preSearchFilt, _functionalUpdate, _dest$__preSearchFilt2, _dest$__postSearchFil;
2365
-
2366
- if (dest === void 0) {
2367
- dest = {};
2368
- }
2369
-
2370
- // const resolvedFrom: Location = {
2371
- // ...router.location,
2372
- const fromPathname = dest.fromCurrent ? router.location.pathname : (_dest$from = dest.from) != null ? _dest$from : router.location.pathname;
2373
-
2374
- let pathname = resolvePath((_router$basepath = router.basepath) != null ? _router$basepath : '/', fromPathname, "" + ((_dest$to = dest.to) != null ? _dest$to : '.'));
2375
-
2376
- const fromMatches = router.matchRoutes(router.location.pathname, {
2377
- strictParseParams: true
2378
- });
2379
- const toMatches = router.matchRoutes(pathname);
2380
-
2381
- const prevParams = _extends({}, (_last = last(fromMatches)) == null ? void 0 : _last.params);
2382
-
2383
- let nextParams = ((_dest$params = dest.params) != null ? _dest$params : true) === true ? prevParams : functionalUpdate(dest.params, prevParams);
2384
-
2385
- if (nextParams) {
2386
- toMatches.map(d => d.options.stringifyParams).filter(Boolean).forEach(fn => {
2387
- Object.assign({}, nextParams, fn(nextParams));
2388
- });
2389
- }
2390
-
2391
- pathname = interpolatePath(pathname, nextParams != null ? nextParams : {}); // Pre filters first
2392
-
2393
- const preFilteredSearch = (_dest$__preSearchFilt = dest.__preSearchFilters) != null && _dest$__preSearchFilt.length ? dest.__preSearchFilters.reduce((prev, next) => next(prev), router.location.search) : router.location.search; // Then the link/navigate function
2394
-
2395
- const destSearch = dest.search === true ? preFilteredSearch // Preserve resolvedFrom true
2396
- : dest.search ? (_functionalUpdate = functionalUpdate(dest.search, preFilteredSearch)) != null ? _functionalUpdate : {} // Updater
2397
- : (_dest$__preSearchFilt2 = dest.__preSearchFilters) != null && _dest$__preSearchFilt2.length ? preFilteredSearch // Preserve resolvedFrom filters
2398
- : {}; // Then post filters
2399
-
2400
- const postFilteredSearch = (_dest$__postSearchFil = dest.__postSearchFilters) != null && _dest$__postSearchFil.length ? dest.__postSearchFilters.reduce((prev, next) => next(prev), destSearch) : destSearch;
2401
- const search = replaceEqualDeep(router.location.search, postFilteredSearch);
2402
- const searchStr = router.options.stringifySearch(search);
2403
- let hash = dest.hash === true ? router.location.hash : functionalUpdate(dest.hash, router.location.hash);
2404
- hash = hash ? "#" + hash : '';
2405
- return {
2406
- pathname,
2407
- search,
2408
- searchStr,
2409
- state: router.location.state,
2410
- hash,
2411
- href: "" + pathname + searchStr + hash,
2412
- key: dest.key
2413
- };
2414
- },
2415
- commitLocation: (next, replace) => {
2416
- const id = '' + Date.now() + Math.random();
2417
- if (router.navigateTimeout) clearTimeout(router.navigateTimeout);
2418
- let nextAction = 'replace';
2419
-
2420
- if (!replace) {
2421
- nextAction = 'push';
2422
- }
2423
-
2424
- const isSameUrl = router.__.parseLocation(history.location).href === next.href;
2425
-
2426
- if (isSameUrl && !next.key) {
2427
- nextAction = 'replace';
2428
- }
2429
-
2430
- if (nextAction === 'replace') {
2431
- history.replace({
2432
- pathname: next.pathname,
2433
- hash: next.hash,
2434
- search: next.searchStr
2435
- }, {
2436
- id
2437
- });
2438
- } else {
2439
- history.push({
2440
- pathname: next.pathname,
2441
- hash: next.hash,
2442
- search: next.searchStr
2443
- }, {
2444
- id
2445
- });
2446
- }
2447
-
2448
- router.navigationPromise = new Promise(resolve => {
2449
- const previousNavigationResolve = router.resolveNavigation;
2450
-
2451
- router.resolveNavigation = () => {
2452
- previousNavigationResolve();
2453
- resolve();
2454
- };
2455
- });
2456
- return router.navigationPromise;
2457
- }
2458
- }
2459
- };
2460
- router.update(userOptions); // Allow frameworks to hook into the router creation
2461
-
2462
- router.options.createRouter == null ? void 0 : router.options.createRouter(router);
2463
- return router;
2464
- }
2465
-
2466
- function isCtrlEvent(e) {
2467
- return !!(e.metaKey || e.altKey || e.ctrlKey || e.shiftKey);
2468
- }
2469
-
2470
- function cascadeLoaderData(matches) {
2471
- matches.forEach((match, index) => {
2472
- const parent = matches[index - 1];
2473
-
2474
- if (parent) {
2475
- match.loaderData = replaceEqualDeep(match.loaderData, _extends({}, parent.loaderData, match.routeLoaderData));
2476
- }
2477
- });
2478
- }
2479
-
2480
- export { cleanPath, createBrowserHistory, createHashHistory, createMemoryHistory, createRoute, createRouteConfig, createRouteMatch, createRouter, decode, defaultParseSearch, defaultStringifySearch, encode, functionalUpdate, interpolatePath, invariant, joinPaths, last, matchByPath, matchPathname, parsePathname, parseSearchWith, pick, replaceEqualDeep, resolvePath, rootRouteId, stringifySearchWith, trimPath, trimPathLeft, trimPathRight, warning };
2481
- //# sourceMappingURL=index.js.map