@tanstack/react-router 0.0.1-beta.8 → 0.0.1-beta.81

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.
@@ -9,10 +9,10 @@
9
9
  * @license MIT
10
10
  */
11
11
  (function (global, factory) {
12
- typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('react'), require('use-sync-external-store/shim')) :
13
- typeof define === 'function' && define.amd ? define(['exports', 'react', 'use-sync-external-store/shim'], factory) :
14
- (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.ReactRouter = {}, global.React, global.shim));
15
- })(this, (function (exports, React, shim) { 'use strict';
12
+ typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('react'), require('use-sync-external-store/shim/with-selector')) :
13
+ typeof define === 'function' && define.amd ? define(['exports', 'react', 'use-sync-external-store/shim/with-selector'], factory) :
14
+ (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.ReactRouter = {}, global.React, global.withSelector));
15
+ })(this, (function (exports, React, withSelector) { 'use strict';
16
16
 
17
17
  function _interopNamespace(e) {
18
18
  if (e && e.__esModule) return e;
@@ -34,40 +34,51 @@
34
34
 
35
35
  var React__namespace = /*#__PURE__*/_interopNamespace(React);
36
36
 
37
- function _extends$2() {
38
- _extends$2 = Object.assign ? Object.assign.bind() : function (target) {
37
+ function _extends() {
38
+ _extends = Object.assign ? Object.assign.bind() : function (target) {
39
39
  for (var i = 1; i < arguments.length; i++) {
40
40
  var source = arguments[i];
41
-
42
41
  for (var key in source) {
43
42
  if (Object.prototype.hasOwnProperty.call(source, key)) {
44
43
  target[key] = source[key];
45
44
  }
46
45
  }
47
46
  }
48
-
49
47
  return target;
50
48
  };
51
- return _extends$2.apply(this, arguments);
49
+ return _extends.apply(this, arguments);
52
50
  }
53
51
 
54
- function _objectWithoutPropertiesLoose(source, excluded) {
55
- if (source == null) return {};
56
- var target = {};
57
- var sourceKeys = Object.keys(source);
58
- var key, i;
52
+ var prefix = 'Invariant failed';
53
+ function invariant(condition, message) {
54
+ if (condition) {
55
+ return;
56
+ }
57
+ var provided = typeof message === 'function' ? message() : message;
58
+ var value = provided ? "".concat(prefix, ": ").concat(provided) : prefix;
59
+ throw new Error(value);
60
+ }
59
61
 
60
- for (i = 0; i < sourceKeys.length; i++) {
61
- key = sourceKeys[i];
62
- if (excluded.indexOf(key) >= 0) continue;
63
- target[key] = source[key];
64
- }
62
+ function warning(condition, message) {
63
+ {
64
+ if (condition) {
65
+ return;
66
+ }
67
+
68
+ var text = "Warning: " + message;
69
+
70
+ if (typeof console !== 'undefined') {
71
+ console.warn(text);
72
+ }
65
73
 
66
- return target;
74
+ try {
75
+ throw Error(text);
76
+ } catch (x) {}
77
+ }
67
78
  }
68
79
 
69
80
  /**
70
- * router-core
81
+ * store
71
82
  *
72
83
  * Copyright (c) TanStack
73
84
  *
@@ -76,927 +87,381 @@
76
87
  *
77
88
  * @license MIT
78
89
  */
79
- function _extends$1() {
80
- _extends$1 = Object.assign ? Object.assign.bind() : function (target) {
81
- for (var i = 1; i < arguments.length; i++) {
82
- var source = arguments[i];
83
-
84
- for (var key in source) {
85
- if (Object.prototype.hasOwnProperty.call(source, key)) {
86
- target[key] = source[key];
87
- }
88
- }
89
- }
90
-
91
- return target;
92
- };
93
- return _extends$1.apply(this, arguments);
94
- }
95
-
96
- /**
97
- * Actions represent the type of change to a location value.
98
- *
99
- * @see https://github.com/remix-run/history/tree/main/docs/api-reference.md#action
100
- */
101
- var Action;
102
-
103
- (function (Action) {
104
- /**
105
- * A POP indicates a change to an arbitrary index in the history stack, such
106
- * as a back or forward navigation. It does not describe the direction of the
107
- * navigation, only that the current index changed.
108
- *
109
- * Note: This is the default action for newly created history objects.
110
- */
111
- Action["Pop"] = "POP";
112
- /**
113
- * A PUSH indicates a new entry being added to the history stack, such as when
114
- * a link is clicked and a new page loads. When this happens, all subsequent
115
- * entries in the stack are lost.
116
- */
117
-
118
- Action["Push"] = "PUSH";
119
- /**
120
- * A REPLACE indicates the entry at the current index in the history stack
121
- * being replaced by a new one.
122
- */
123
-
124
- Action["Replace"] = "REPLACE";
125
- })(Action || (Action = {}));
126
-
127
- var readOnly = function (obj) {
128
- return Object.freeze(obj);
129
- } ;
130
-
131
- function warning$1(cond, message) {
132
- if (!cond) {
133
- // eslint-disable-next-line no-console
134
- if (typeof console !== 'undefined') console.warn(message);
135
-
136
- try {
137
- // Welcome to debugging history!
138
- //
139
- // This error is thrown as a convenience so you can more easily
140
- // find the source for a warning that appears in the console by
141
- // enabling "pause on exceptions" in your JavaScript debugger.
142
- throw new Error(message); // eslint-disable-next-line no-empty
143
- } catch (e) {}
90
+ class Store {
91
+ listeners = new Set();
92
+ batching = false;
93
+ queue = [];
94
+ constructor(initialState, options) {
95
+ this.state = initialState;
96
+ this.options = options;
144
97
  }
98
+ subscribe = listener => {
99
+ this.listeners.add(listener);
100
+ const unsub = this.options?.onSubscribe?.(listener, this);
101
+ return () => {
102
+ this.listeners.delete(listener);
103
+ unsub?.();
104
+ };
105
+ };
106
+ setState = updater => {
107
+ const previous = this.state;
108
+ this.state = this.options?.updateFn ? this.options.updateFn(previous)(updater) : updater(previous);
109
+ if (this.state === previous) return;
110
+ this.options?.onUpdate?.(this.state, previous);
111
+ this.queue.push(() => {
112
+ this.listeners.forEach(listener => listener(this.state, previous));
113
+ });
114
+ this.#flush();
115
+ };
116
+ #flush = () => {
117
+ if (this.batching) return;
118
+ this.queue.forEach(cb => cb());
119
+ this.queue = [];
120
+ };
121
+ batch = cb => {
122
+ this.batching = true;
123
+ cb();
124
+ this.batching = false;
125
+ this.#flush();
126
+ };
145
127
  }
146
-
147
- var BeforeUnloadEventType = 'beforeunload';
148
- var HashChangeEventType = 'hashchange';
149
- var PopStateEventType = 'popstate';
150
- /**
151
- * Browser history stores the location in regular URLs. This is the standard for
152
- * most web apps, but it requires some configuration on the server to ensure you
153
- * serve the same app at multiple URLs.
154
- *
155
- * @see https://github.com/remix-run/history/tree/main/docs/api-reference.md#createbrowserhistory
156
- */
157
-
158
- function createBrowserHistory(options) {
159
- if (options === void 0) {
160
- options = {};
128
+ function shallow(objA, objB) {
129
+ if (Object.is(objA, objB)) {
130
+ return true;
161
131
  }
162
-
163
- var _options = options,
164
- _options$window = _options.window,
165
- window = _options$window === void 0 ? document.defaultView : _options$window;
166
- var globalHistory = window.history;
167
-
168
- function getIndexAndLocation() {
169
- var _window$location = window.location,
170
- pathname = _window$location.pathname,
171
- search = _window$location.search,
172
- hash = _window$location.hash;
173
- var state = globalHistory.state || {};
174
- return [state.idx, readOnly({
175
- pathname: pathname,
176
- search: search,
177
- hash: hash,
178
- state: state.usr || null,
179
- key: state.key || 'default'
180
- })];
132
+ if (typeof objA !== 'object' || objA === null || typeof objB !== 'object' || objB === null) {
133
+ return false;
181
134
  }
182
135
 
183
- var blockedPopTx = null;
184
-
185
- function handlePop() {
186
- if (blockedPopTx) {
187
- blockers.call(blockedPopTx);
188
- blockedPopTx = null;
189
- } else {
190
- var nextAction = Action.Pop;
191
-
192
- var _getIndexAndLocation = getIndexAndLocation(),
193
- nextIndex = _getIndexAndLocation[0],
194
- nextLocation = _getIndexAndLocation[1];
195
-
196
- if (blockers.length) {
197
- if (nextIndex != null) {
198
- var delta = index - nextIndex;
199
-
200
- if (delta) {
201
- // Revert the POP
202
- blockedPopTx = {
203
- action: nextAction,
204
- location: nextLocation,
205
- retry: function retry() {
206
- go(delta * -1);
207
- }
208
- };
209
- go(delta);
210
- }
211
- } else {
212
- // Trying to POP to a location with no index. We did not create
213
- // this location, so we can't effectively block the navigation.
214
- warning$1(false, // TODO: Write up a doc that explains our blocking strategy in
215
- // detail and link to it here so people can understand better what
216
- // is going on and how to avoid it.
217
- "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.") ;
218
- }
219
- } else {
220
- applyTx(nextAction);
221
- }
222
- }
223
- }
136
+ // if (objA instanceof Map && objB instanceof Map) {
137
+ // if (objA.size !== objB.size) return false
224
138
 
225
- window.addEventListener(PopStateEventType, handlePop);
226
- var action = Action.Pop;
139
+ // for (const [key, value] of objA) {
140
+ // if (!Object.is(value, objB.get(key))) {
141
+ // return false
142
+ // }
143
+ // }
144
+ // return true
145
+ // }
227
146
 
228
- var _getIndexAndLocation2 = getIndexAndLocation(),
229
- index = _getIndexAndLocation2[0],
230
- location = _getIndexAndLocation2[1];
147
+ // if (objA instanceof Set && objB instanceof Set) {
148
+ // if (objA.size !== objB.size) return false
231
149
 
232
- var listeners = createEvents();
233
- var blockers = createEvents();
150
+ // for (const value of objA) {
151
+ // if (!objB.has(value)) {
152
+ // return false
153
+ // }
154
+ // }
155
+ // return true
156
+ // }
234
157
 
235
- if (index == null) {
236
- index = 0;
237
- globalHistory.replaceState(_extends$1({}, globalHistory.state, {
238
- idx: index
239
- }), '');
158
+ const keysA = Object.keys(objA);
159
+ if (keysA.length !== Object.keys(objB).length) {
160
+ return false;
240
161
  }
241
-
242
- function createHref(to) {
243
- return typeof to === 'string' ? to : createPath(to);
244
- } // state defaults to `null` because `window.history.state` does
245
-
246
-
247
- function getNextLocation(to, state) {
248
- if (state === void 0) {
249
- state = null;
162
+ for (let i = 0; i < keysA.length; i++) {
163
+ if (!Object.prototype.hasOwnProperty.call(objB, keysA[i]) || !Object.is(objA[keysA[i]], objB[keysA[i]])) {
164
+ return false;
250
165
  }
251
-
252
- return readOnly(_extends$1({
253
- pathname: location.pathname,
254
- hash: '',
255
- search: ''
256
- }, typeof to === 'string' ? parsePath(to) : to, {
257
- state: state,
258
- key: createKey()
259
- }));
260
- }
261
-
262
- function getHistoryStateAndUrl(nextLocation, index) {
263
- return [{
264
- usr: nextLocation.state,
265
- key: nextLocation.key,
266
- idx: index
267
- }, createHref(nextLocation)];
268
- }
269
-
270
- function allowTx(action, location, retry) {
271
- return !blockers.length || (blockers.call({
272
- action: action,
273
- location: location,
274
- retry: retry
275
- }), false);
276
- }
277
-
278
- function applyTx(nextAction) {
279
- action = nextAction;
280
-
281
- var _getIndexAndLocation3 = getIndexAndLocation();
282
-
283
- index = _getIndexAndLocation3[0];
284
- location = _getIndexAndLocation3[1];
285
- listeners.call({
286
- action: action,
287
- location: location
288
- });
289
166
  }
167
+ return true;
168
+ }
290
169
 
291
- function push(to, state) {
292
- var nextAction = Action.Push;
293
- var nextLocation = getNextLocation(to, state);
294
-
295
- function retry() {
296
- push(to, state);
297
- }
298
-
299
- if (allowTx(nextAction, nextLocation, retry)) {
300
- var _getHistoryStateAndUr = getHistoryStateAndUrl(nextLocation, index + 1),
301
- historyState = _getHistoryStateAndUr[0],
302
- url = _getHistoryStateAndUr[1]; // TODO: Support forced reloading
303
- // try...catch because iOS limits us to 100 pushState calls :/
304
-
305
-
306
- try {
307
- globalHistory.pushState(historyState, '', url);
308
- } catch (error) {
309
- // They are going to lose state here, but there is no real
310
- // way to warn them about it since the page will refresh...
311
- window.location.assign(url);
312
- }
313
-
314
- applyTx(nextAction);
315
- }
316
- }
170
+ /**
171
+ * router
172
+ *
173
+ * Copyright (c) TanStack
174
+ *
175
+ * This source code is licensed under the MIT license found in the
176
+ * LICENSE.md file in the root directory of this source tree.
177
+ *
178
+ * @license MIT
179
+ */
317
180
 
318
- function replace(to, state) {
319
- var nextAction = Action.Replace;
320
- var nextLocation = getNextLocation(to, state);
181
+ // While the public API was clearly inspired by the "history" npm package,
182
+ // This implementation attempts to be more lightweight by
183
+ // making assumptions about the way TanStack Router works
321
184
 
322
- function retry() {
323
- replace(to, state);
185
+ const popStateEvent = 'popstate';
186
+ const beforeUnloadEvent = 'beforeunload';
187
+ const beforeUnloadListener = event => {
188
+ event.preventDefault();
189
+ // @ts-ignore
190
+ return event.returnValue = '';
191
+ };
192
+ const stopBlocking = () => {
193
+ removeEventListener(beforeUnloadEvent, beforeUnloadListener, {
194
+ capture: true
195
+ });
196
+ };
197
+ function createHistory(opts) {
198
+ let currentLocation = opts.getLocation();
199
+ let unsub = () => {};
200
+ let listeners = new Set();
201
+ let blockers = [];
202
+ let queue = [];
203
+ const tryFlush = () => {
204
+ if (blockers.length) {
205
+ blockers[0]?.(tryFlush, () => {
206
+ blockers = [];
207
+ stopBlocking();
208
+ });
209
+ return;
324
210
  }
325
-
326
- if (allowTx(nextAction, nextLocation, retry)) {
327
- var _getHistoryStateAndUr2 = getHistoryStateAndUrl(nextLocation, index),
328
- historyState = _getHistoryStateAndUr2[0],
329
- url = _getHistoryStateAndUr2[1]; // TODO: Support forced reloading
330
-
331
-
332
- globalHistory.replaceState(historyState, '', url);
333
- applyTx(nextAction);
211
+ while (queue.length) {
212
+ queue.shift()?.();
334
213
  }
335
- }
336
-
337
- function go(delta) {
338
- globalHistory.go(delta);
339
- }
340
-
341
- var history = {
342
- get action() {
343
- return action;
344
- },
345
-
214
+ onUpdate();
215
+ };
216
+ const queueTask = task => {
217
+ queue.push(task);
218
+ tryFlush();
219
+ };
220
+ const onUpdate = () => {
221
+ currentLocation = opts.getLocation();
222
+ listeners.forEach(listener => listener());
223
+ };
224
+ return {
346
225
  get location() {
347
- return location;
226
+ return currentLocation;
348
227
  },
349
-
350
- createHref: createHref,
351
- push: push,
352
- replace: replace,
353
- go: go,
354
- back: function back() {
355
- go(-1);
228
+ listen: cb => {
229
+ if (listeners.size === 0) {
230
+ unsub = opts.listener(onUpdate);
231
+ }
232
+ listeners.add(cb);
233
+ return () => {
234
+ listeners.delete(cb);
235
+ if (listeners.size === 0) {
236
+ unsub();
237
+ }
238
+ };
239
+ },
240
+ push: (path, state) => {
241
+ queueTask(() => {
242
+ opts.pushState(path, state);
243
+ });
356
244
  },
357
- forward: function forward() {
358
- go(1);
245
+ replace: (path, state) => {
246
+ queueTask(() => {
247
+ opts.replaceState(path, state);
248
+ });
359
249
  },
360
- listen: function listen(listener) {
361
- return listeners.push(listener);
250
+ go: index => {
251
+ queueTask(() => {
252
+ opts.go(index);
253
+ });
362
254
  },
363
- block: function block(blocker) {
364
- var unblock = blockers.push(blocker);
365
-
255
+ back: () => {
256
+ queueTask(() => {
257
+ opts.back();
258
+ });
259
+ },
260
+ forward: () => {
261
+ queueTask(() => {
262
+ opts.forward();
263
+ });
264
+ },
265
+ createHref: str => opts.createHref(str),
266
+ block: cb => {
267
+ blockers.push(cb);
366
268
  if (blockers.length === 1) {
367
- window.addEventListener(BeforeUnloadEventType, promptBeforeUnload);
269
+ addEventListener(beforeUnloadEvent, beforeUnloadListener, {
270
+ capture: true
271
+ });
368
272
  }
369
-
370
- return function () {
371
- unblock(); // Remove the beforeunload listener so the document may
372
- // still be salvageable in the pagehide event.
373
- // See https://html.spec.whatwg.org/#unloading-documents
374
-
273
+ return () => {
274
+ blockers = blockers.filter(b => b !== cb);
375
275
  if (!blockers.length) {
376
- window.removeEventListener(BeforeUnloadEventType, promptBeforeUnload);
276
+ stopBlocking();
377
277
  }
378
278
  };
379
279
  }
380
280
  };
381
- return history;
382
- }
383
- /**
384
- * Hash history stores the location in window.location.hash. This makes it ideal
385
- * for situations where you don't want to send the location to the server for
386
- * some reason, either because you do cannot configure it or the URL space is
387
- * reserved for something else.
388
- *
389
- * @see https://github.com/remix-run/history/tree/main/docs/api-reference.md#createhashhistory
390
- */
281
+ }
282
+ function createBrowserHistory(opts) {
283
+ const getHref = opts?.getHref ?? (() => `${window.location.pathname}${window.location.hash}${window.location.search}`);
284
+ const createHref = opts?.createHref ?? (path => path);
285
+ const getLocation = () => parseLocation(getHref(), history.state);
286
+ return createHistory({
287
+ getLocation,
288
+ listener: onUpdate => {
289
+ window.addEventListener(popStateEvent, onUpdate);
290
+ return () => {
291
+ window.removeEventListener(popStateEvent, onUpdate);
292
+ };
293
+ },
294
+ pushState: (path, state) => {
295
+ window.history.pushState({
296
+ ...state,
297
+ key: createRandomKey()
298
+ }, '', createHref(path));
299
+ },
300
+ replaceState: (path, state) => {
301
+ window.history.replaceState({
302
+ ...state,
303
+ key: createRandomKey()
304
+ }, '', createHref(path));
305
+ },
306
+ back: () => window.history.back(),
307
+ forward: () => window.history.forward(),
308
+ go: n => window.history.go(n),
309
+ createHref: path => createHref(path)
310
+ });
311
+ }
312
+ function createHashHistory() {
313
+ return createBrowserHistory({
314
+ getHref: () => window.location.hash.substring(1),
315
+ createHref: path => `#${path}`
316
+ });
317
+ }
318
+ function createMemoryHistory(opts = {
319
+ initialEntries: ['/']
320
+ }) {
321
+ const entries = opts.initialEntries;
322
+ let index = opts.initialIndex ?? entries.length - 1;
323
+ let currentState = {};
324
+ const getLocation = () => parseLocation(entries[index], currentState);
325
+ return createHistory({
326
+ getLocation,
327
+ listener: () => {
328
+ return () => {};
329
+ },
330
+ pushState: (path, state) => {
331
+ currentState = {
332
+ ...state,
333
+ key: createRandomKey()
334
+ };
335
+ entries.push(path);
336
+ index++;
337
+ },
338
+ replaceState: (path, state) => {
339
+ currentState = {
340
+ ...state,
341
+ key: createRandomKey()
342
+ };
343
+ entries[index] = path;
344
+ },
345
+ back: () => {
346
+ index--;
347
+ },
348
+ forward: () => {
349
+ index = Math.min(index + 1, entries.length - 1);
350
+ },
351
+ go: n => window.history.go(n),
352
+ createHref: path => path
353
+ });
354
+ }
355
+ function parseLocation(href, state) {
356
+ let hashIndex = href.indexOf('#');
357
+ let searchIndex = href.indexOf('?');
358
+ return {
359
+ href,
360
+ pathname: href.substring(0, hashIndex > 0 ? searchIndex > 0 ? Math.min(hashIndex, searchIndex) : hashIndex : searchIndex > 0 ? searchIndex : href.length),
361
+ hash: hashIndex > -1 ? href.substring(hashIndex, searchIndex) : '',
362
+ search: searchIndex > -1 ? href.substring(searchIndex) : '',
363
+ state
364
+ };
365
+ }
391
366
 
392
- function createHashHistory(options) {
393
- if (options === void 0) {
394
- options = {};
395
- }
367
+ // Thanks co-pilot!
368
+ function createRandomKey() {
369
+ return (Math.random() + 1).toString(36).substring(7);
370
+ }
396
371
 
397
- var _options2 = options,
398
- _options2$window = _options2.window,
399
- window = _options2$window === void 0 ? document.defaultView : _options2$window;
400
- var globalHistory = window.history;
401
-
402
- function getIndexAndLocation() {
403
- var _parsePath = parsePath(window.location.hash.substr(1)),
404
- _parsePath$pathname = _parsePath.pathname,
405
- pathname = _parsePath$pathname === void 0 ? '/' : _parsePath$pathname,
406
- _parsePath$search = _parsePath.search,
407
- search = _parsePath$search === void 0 ? '' : _parsePath$search,
408
- _parsePath$hash = _parsePath.hash,
409
- hash = _parsePath$hash === void 0 ? '' : _parsePath$hash;
410
-
411
- var state = globalHistory.state || {};
412
- return [state.idx, readOnly({
413
- pathname: pathname,
414
- search: search,
415
- hash: hash,
416
- state: state.usr || null,
417
- key: state.key || 'default'
418
- })];
372
+ function last(arr) {
373
+ return arr[arr.length - 1];
374
+ }
375
+ function isFunction(d) {
376
+ return typeof d === 'function';
377
+ }
378
+ function functionalUpdate(updater, previous) {
379
+ if (isFunction(updater)) {
380
+ return updater(previous);
419
381
  }
382
+ return updater;
383
+ }
384
+ function pick(parent, keys) {
385
+ return keys.reduce((obj, key) => {
386
+ obj[key] = parent[key];
387
+ return obj;
388
+ }, {});
389
+ }
420
390
 
421
- var blockedPopTx = null;
422
-
423
- function handlePop() {
424
- if (blockedPopTx) {
425
- blockers.call(blockedPopTx);
426
- blockedPopTx = null;
427
- } else {
428
- var nextAction = Action.Pop;
429
-
430
- var _getIndexAndLocation4 = getIndexAndLocation(),
431
- nextIndex = _getIndexAndLocation4[0],
432
- nextLocation = _getIndexAndLocation4[1];
433
-
434
- if (blockers.length) {
435
- if (nextIndex != null) {
436
- var delta = index - nextIndex;
437
-
438
- if (delta) {
439
- // Revert the POP
440
- blockedPopTx = {
441
- action: nextAction,
442
- location: nextLocation,
443
- retry: function retry() {
444
- go(delta * -1);
445
- }
446
- };
447
- go(delta);
448
- }
449
- } else {
450
- // Trying to POP to a location with no index. We did not create
451
- // this location, so we can't effectively block the navigation.
452
- warning$1(false, // TODO: Write up a doc that explains our blocking strategy in
453
- // detail and link to it here so people can understand better
454
- // what is going on and how to avoid it.
455
- "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.") ;
456
- }
457
- } else {
458
- applyTx(nextAction);
391
+ /**
392
+ * This function returns `a` if `b` is deeply equal.
393
+ * If not, it will replace any deeply equal children of `b` with those of `a`.
394
+ * This can be used for structural sharing between immutable JSON values for example.
395
+ * Do not use this with signals
396
+ */
397
+ function replaceEqualDeep(prev, _next) {
398
+ if (prev === _next) {
399
+ return prev;
400
+ }
401
+ const next = _next;
402
+ const array = Array.isArray(prev) && Array.isArray(next);
403
+ if (array || isPlainObject(prev) && isPlainObject(next)) {
404
+ const prevSize = array ? prev.length : Object.keys(prev).length;
405
+ const nextItems = array ? next : Object.keys(next);
406
+ const nextSize = nextItems.length;
407
+ const copy = array ? [] : {};
408
+ let equalItems = 0;
409
+ for (let i = 0; i < nextSize; i++) {
410
+ const key = array ? i : nextItems[i];
411
+ copy[key] = replaceEqualDeep(prev[key], next[key]);
412
+ if (copy[key] === prev[key]) {
413
+ equalItems++;
459
414
  }
460
415
  }
416
+ return prevSize === nextSize && equalItems === prevSize ? prev : copy;
461
417
  }
418
+ return next;
419
+ }
462
420
 
463
- window.addEventListener(PopStateEventType, handlePop); // popstate does not fire on hashchange in IE 11 and old (trident) Edge
464
- // https://developer.mozilla.org/de/docs/Web/API/Window/popstate_event
465
-
466
- window.addEventListener(HashChangeEventType, function () {
467
- var _getIndexAndLocation5 = getIndexAndLocation(),
468
- nextLocation = _getIndexAndLocation5[1]; // Ignore extraneous hashchange events.
469
-
470
-
471
- if (createPath(nextLocation) !== createPath(location)) {
472
- handlePop();
473
- }
474
- });
475
- var action = Action.Pop;
476
-
477
- var _getIndexAndLocation6 = getIndexAndLocation(),
478
- index = _getIndexAndLocation6[0],
479
- location = _getIndexAndLocation6[1];
480
-
481
- var listeners = createEvents();
482
- var blockers = createEvents();
483
-
484
- if (index == null) {
485
- index = 0;
486
- globalHistory.replaceState(_extends$1({}, globalHistory.state, {
487
- idx: index
488
- }), '');
421
+ // Copied from: https://github.com/jonschlinkert/is-plain-object
422
+ function isPlainObject(o) {
423
+ if (!hasObjectPrototype(o)) {
424
+ return false;
489
425
  }
490
426
 
491
- function getBaseHref() {
492
- var base = document.querySelector('base');
493
- var href = '';
494
-
495
- if (base && base.getAttribute('href')) {
496
- var url = window.location.href;
497
- var hashIndex = url.indexOf('#');
498
- href = hashIndex === -1 ? url : url.slice(0, hashIndex);
499
- }
500
-
501
- return href;
427
+ // If has modified constructor
428
+ const ctor = o.constructor;
429
+ if (typeof ctor === 'undefined') {
430
+ return true;
502
431
  }
503
432
 
504
- function createHref(to) {
505
- return getBaseHref() + '#' + (typeof to === 'string' ? to : createPath(to));
433
+ // If has modified prototype
434
+ const prot = ctor.prototype;
435
+ if (!hasObjectPrototype(prot)) {
436
+ return false;
506
437
  }
507
438
 
508
- function getNextLocation(to, state) {
509
- if (state === void 0) {
510
- state = null;
511
- }
512
-
513
- return readOnly(_extends$1({
514
- pathname: location.pathname,
515
- hash: '',
516
- search: ''
517
- }, typeof to === 'string' ? parsePath(to) : to, {
518
- state: state,
519
- key: createKey()
520
- }));
439
+ // If constructor does not have an Object-specific method
440
+ if (!prot.hasOwnProperty('isPrototypeOf')) {
441
+ return false;
521
442
  }
522
443
 
523
- function getHistoryStateAndUrl(nextLocation, index) {
524
- return [{
525
- usr: nextLocation.state,
526
- key: nextLocation.key,
527
- idx: index
528
- }, createHref(nextLocation)];
444
+ // Most likely a plain Object
445
+ return true;
446
+ }
447
+ function hasObjectPrototype(o) {
448
+ return Object.prototype.toString.call(o) === '[object Object]';
449
+ }
450
+ function partialDeepEqual(a, b) {
451
+ if (a === b) {
452
+ return true;
529
453
  }
530
-
531
- function allowTx(action, location, retry) {
532
- return !blockers.length || (blockers.call({
533
- action: action,
534
- location: location,
535
- retry: retry
536
- }), false);
454
+ if (typeof a !== typeof b) {
455
+ return false;
537
456
  }
538
-
539
- function applyTx(nextAction) {
540
- action = nextAction;
541
-
542
- var _getIndexAndLocation7 = getIndexAndLocation();
543
-
544
- index = _getIndexAndLocation7[0];
545
- location = _getIndexAndLocation7[1];
546
- listeners.call({
547
- action: action,
548
- location: location
549
- });
457
+ if (isPlainObject(a) && isPlainObject(b)) {
458
+ return !Object.keys(b).some(key => !partialDeepEqual(a[key], b[key]));
550
459
  }
551
-
552
- function push(to, state) {
553
- var nextAction = Action.Push;
554
- var nextLocation = getNextLocation(to, state);
555
-
556
- function retry() {
557
- push(to, state);
558
- }
559
-
560
- warning$1(nextLocation.pathname.charAt(0) === '/', "Relative pathnames are not supported in hash history.push(" + JSON.stringify(to) + ")") ;
561
-
562
- if (allowTx(nextAction, nextLocation, retry)) {
563
- var _getHistoryStateAndUr3 = getHistoryStateAndUrl(nextLocation, index + 1),
564
- historyState = _getHistoryStateAndUr3[0],
565
- url = _getHistoryStateAndUr3[1]; // TODO: Support forced reloading
566
- // try...catch because iOS limits us to 100 pushState calls :/
567
-
568
-
569
- try {
570
- globalHistory.pushState(historyState, '', url);
571
- } catch (error) {
572
- // They are going to lose state here, but there is no real
573
- // way to warn them about it since the page will refresh...
574
- window.location.assign(url);
575
- }
576
-
577
- applyTx(nextAction);
578
- }
460
+ if (Array.isArray(a) && Array.isArray(b)) {
461
+ return a.length === b.length && a.every((item, index) => partialDeepEqual(item, b[index]));
579
462
  }
580
-
581
- function replace(to, state) {
582
- var nextAction = Action.Replace;
583
- var nextLocation = getNextLocation(to, state);
584
-
585
- function retry() {
586
- replace(to, state);
587
- }
588
-
589
- warning$1(nextLocation.pathname.charAt(0) === '/', "Relative pathnames are not supported in hash history.replace(" + JSON.stringify(to) + ")") ;
590
-
591
- if (allowTx(nextAction, nextLocation, retry)) {
592
- var _getHistoryStateAndUr4 = getHistoryStateAndUrl(nextLocation, index),
593
- historyState = _getHistoryStateAndUr4[0],
594
- url = _getHistoryStateAndUr4[1]; // TODO: Support forced reloading
595
-
596
-
597
- globalHistory.replaceState(historyState, '', url);
598
- applyTx(nextAction);
599
- }
600
- }
601
-
602
- function go(delta) {
603
- globalHistory.go(delta);
604
- }
605
-
606
- var history = {
607
- get action() {
608
- return action;
609
- },
610
-
611
- get location() {
612
- return location;
613
- },
614
-
615
- createHref: createHref,
616
- push: push,
617
- replace: replace,
618
- go: go,
619
- back: function back() {
620
- go(-1);
621
- },
622
- forward: function forward() {
623
- go(1);
624
- },
625
- listen: function listen(listener) {
626
- return listeners.push(listener);
627
- },
628
- block: function block(blocker) {
629
- var unblock = blockers.push(blocker);
630
-
631
- if (blockers.length === 1) {
632
- window.addEventListener(BeforeUnloadEventType, promptBeforeUnload);
633
- }
634
-
635
- return function () {
636
- unblock(); // Remove the beforeunload listener so the document may
637
- // still be salvageable in the pagehide event.
638
- // See https://html.spec.whatwg.org/#unloading-documents
639
-
640
- if (!blockers.length) {
641
- window.removeEventListener(BeforeUnloadEventType, promptBeforeUnload);
642
- }
643
- };
644
- }
645
- };
646
- return history;
647
- }
648
- /**
649
- * Memory history stores the current location in memory. It is designed for use
650
- * in stateful non-browser environments like tests and React Native.
651
- *
652
- * @see https://github.com/remix-run/history/tree/main/docs/api-reference.md#creatememoryhistory
653
- */
654
-
655
- function createMemoryHistory(options) {
656
- if (options === void 0) {
657
- options = {};
658
- }
659
-
660
- var _options3 = options,
661
- _options3$initialEntr = _options3.initialEntries,
662
- initialEntries = _options3$initialEntr === void 0 ? ['/'] : _options3$initialEntr,
663
- initialIndex = _options3.initialIndex;
664
- var entries = initialEntries.map(function (entry) {
665
- var location = readOnly(_extends$1({
666
- pathname: '/',
667
- search: '',
668
- hash: '',
669
- state: null,
670
- key: createKey()
671
- }, typeof entry === 'string' ? parsePath(entry) : entry));
672
- warning$1(location.pathname.charAt(0) === '/', "Relative pathnames are not supported in createMemoryHistory({ initialEntries }) (invalid entry: " + JSON.stringify(entry) + ")") ;
673
- return location;
674
- });
675
- var index = clamp(initialIndex == null ? entries.length - 1 : initialIndex, 0, entries.length - 1);
676
- var action = Action.Pop;
677
- var location = entries[index];
678
- var listeners = createEvents();
679
- var blockers = createEvents();
680
-
681
- function createHref(to) {
682
- return typeof to === 'string' ? to : createPath(to);
683
- }
684
-
685
- function getNextLocation(to, state) {
686
- if (state === void 0) {
687
- state = null;
688
- }
689
-
690
- return readOnly(_extends$1({
691
- pathname: location.pathname,
692
- search: '',
693
- hash: ''
694
- }, typeof to === 'string' ? parsePath(to) : to, {
695
- state: state,
696
- key: createKey()
697
- }));
698
- }
699
-
700
- function allowTx(action, location, retry) {
701
- return !blockers.length || (blockers.call({
702
- action: action,
703
- location: location,
704
- retry: retry
705
- }), false);
706
- }
707
-
708
- function applyTx(nextAction, nextLocation) {
709
- action = nextAction;
710
- location = nextLocation;
711
- listeners.call({
712
- action: action,
713
- location: location
714
- });
715
- }
716
-
717
- function push(to, state) {
718
- var nextAction = Action.Push;
719
- var nextLocation = getNextLocation(to, state);
720
-
721
- function retry() {
722
- push(to, state);
723
- }
724
-
725
- warning$1(location.pathname.charAt(0) === '/', "Relative pathnames are not supported in memory history.push(" + JSON.stringify(to) + ")") ;
726
-
727
- if (allowTx(nextAction, nextLocation, retry)) {
728
- index += 1;
729
- entries.splice(index, entries.length, nextLocation);
730
- applyTx(nextAction, nextLocation);
731
- }
732
- }
733
-
734
- function replace(to, state) {
735
- var nextAction = Action.Replace;
736
- var nextLocation = getNextLocation(to, state);
737
-
738
- function retry() {
739
- replace(to, state);
740
- }
741
-
742
- warning$1(location.pathname.charAt(0) === '/', "Relative pathnames are not supported in memory history.replace(" + JSON.stringify(to) + ")") ;
743
-
744
- if (allowTx(nextAction, nextLocation, retry)) {
745
- entries[index] = nextLocation;
746
- applyTx(nextAction, nextLocation);
747
- }
748
- }
749
-
750
- function go(delta) {
751
- var nextIndex = clamp(index + delta, 0, entries.length - 1);
752
- var nextAction = Action.Pop;
753
- var nextLocation = entries[nextIndex];
754
-
755
- function retry() {
756
- go(delta);
757
- }
758
-
759
- if (allowTx(nextAction, nextLocation, retry)) {
760
- index = nextIndex;
761
- applyTx(nextAction, nextLocation);
762
- }
763
- }
764
-
765
- var history = {
766
- get index() {
767
- return index;
768
- },
769
-
770
- get action() {
771
- return action;
772
- },
773
-
774
- get location() {
775
- return location;
776
- },
777
-
778
- createHref: createHref,
779
- push: push,
780
- replace: replace,
781
- go: go,
782
- back: function back() {
783
- go(-1);
784
- },
785
- forward: function forward() {
786
- go(1);
787
- },
788
- listen: function listen(listener) {
789
- return listeners.push(listener);
790
- },
791
- block: function block(blocker) {
792
- return blockers.push(blocker);
793
- }
794
- };
795
- return history;
796
- } ////////////////////////////////////////////////////////////////////////////////
797
- // UTILS
798
- ////////////////////////////////////////////////////////////////////////////////
799
-
800
- function clamp(n, lowerBound, upperBound) {
801
- return Math.min(Math.max(n, lowerBound), upperBound);
802
- }
803
-
804
- function promptBeforeUnload(event) {
805
- // Cancel the event.
806
- event.preventDefault(); // Chrome (and legacy IE) requires returnValue to be set.
807
-
808
- event.returnValue = '';
809
- }
810
-
811
- function createEvents() {
812
- var handlers = [];
813
- return {
814
- get length() {
815
- return handlers.length;
816
- },
817
-
818
- push: function push(fn) {
819
- handlers.push(fn);
820
- return function () {
821
- handlers = handlers.filter(function (handler) {
822
- return handler !== fn;
823
- });
824
- };
825
- },
826
- call: function call(arg) {
827
- handlers.forEach(function (fn) {
828
- return fn && fn(arg);
829
- });
830
- }
831
- };
832
- }
833
-
834
- function createKey() {
835
- return Math.random().toString(36).substr(2, 8);
836
- }
837
- /**
838
- * Creates a string URL path from the given pathname, search, and hash components.
839
- *
840
- * @see https://github.com/remix-run/history/tree/main/docs/api-reference.md#createpath
841
- */
842
-
843
-
844
- function createPath(_ref) {
845
- var _ref$pathname = _ref.pathname,
846
- pathname = _ref$pathname === void 0 ? '/' : _ref$pathname,
847
- _ref$search = _ref.search,
848
- search = _ref$search === void 0 ? '' : _ref$search,
849
- _ref$hash = _ref.hash,
850
- hash = _ref$hash === void 0 ? '' : _ref$hash;
851
- if (search && search !== '?') pathname += search.charAt(0) === '?' ? search : '?' + search;
852
- if (hash && hash !== '#') pathname += hash.charAt(0) === '#' ? hash : '#' + hash;
853
- return pathname;
854
- }
855
- /**
856
- * Parses a string URL path into its separate pathname, search, and hash components.
857
- *
858
- * @see https://github.com/remix-run/history/tree/main/docs/api-reference.md#parsepath
859
- */
860
-
861
- function parsePath(path) {
862
- var parsedPath = {};
863
-
864
- if (path) {
865
- var hashIndex = path.indexOf('#');
866
-
867
- if (hashIndex >= 0) {
868
- parsedPath.hash = path.substr(hashIndex);
869
- path = path.substr(0, hashIndex);
870
- }
871
-
872
- var searchIndex = path.indexOf('?');
873
-
874
- if (searchIndex >= 0) {
875
- parsedPath.search = path.substr(searchIndex);
876
- path = path.substr(0, searchIndex);
877
- }
878
-
879
- if (path) {
880
- parsedPath.pathname = path;
881
- }
882
- }
883
-
884
- return parsedPath;
885
- }
886
- var prefix = 'Invariant failed';
887
- function invariant(condition, message) {
888
- if (condition) {
889
- return;
890
- }
891
- var provided = typeof message === 'function' ? message() : message;
892
- var value = provided ? "".concat(prefix, ": ").concat(provided) : prefix;
893
- throw new Error(value);
894
- }
895
-
896
- // type UnionToIntersection<U> = (U extends any ? (k: U) => void : never) extends (
897
- // k: infer I,
898
- // ) => any
899
- // ? I
900
- // : never
901
-
902
- /**
903
- * This function returns `a` if `b` is deeply equal.
904
- * If not, it will replace any deeply equal children of `b` with those of `a`.
905
- * This can be used for structural sharing between JSON values for example.
906
- */
907
- function replaceEqualDeep(prev, next) {
908
- if (prev === next) {
909
- return prev;
910
- }
911
-
912
- const array = Array.isArray(prev) && Array.isArray(next);
913
-
914
- if (array || isPlainObject(prev) && isPlainObject(next)) {
915
- const aSize = array ? prev.length : Object.keys(prev).length;
916
- const bItems = array ? next : Object.keys(next);
917
- const bSize = bItems.length;
918
- const copy = array ? [] : {};
919
- let equalItems = 0;
920
-
921
- for (let i = 0; i < bSize; i++) {
922
- const key = array ? i : bItems[i];
923
- copy[key] = replaceEqualDeep(prev[key], next[key]);
924
-
925
- if (copy[key] === prev[key]) {
926
- equalItems++;
927
- }
928
- }
929
-
930
- return aSize === bSize && equalItems === aSize ? prev : copy;
931
- }
932
-
933
- return next;
934
- } // Copied from: https://github.com/jonschlinkert/is-plain-object
935
-
936
- function isPlainObject(o) {
937
- if (!hasObjectPrototype(o)) {
938
- return false;
939
- } // If has modified constructor
940
-
941
-
942
- const ctor = o.constructor;
943
-
944
- if (typeof ctor === 'undefined') {
945
- return true;
946
- } // If has modified prototype
947
-
948
-
949
- const prot = ctor.prototype;
950
-
951
- if (!hasObjectPrototype(prot)) {
952
- return false;
953
- } // If constructor does not have an Object-specific method
954
-
955
-
956
- if (!prot.hasOwnProperty('isPrototypeOf')) {
957
- return false;
958
- } // Most likely a plain Object
959
-
960
-
961
- return true;
962
- }
963
-
964
- function hasObjectPrototype(o) {
965
- return Object.prototype.toString.call(o) === '[object Object]';
966
- }
967
-
968
- function last(arr) {
969
- return arr[arr.length - 1];
970
- }
971
- function warning(cond, message) {
972
- if (cond) {
973
- if (typeof console !== 'undefined') console.warn(message);
974
-
975
- try {
976
- throw new Error(message);
977
- } catch (_unused) {}
978
- }
979
-
980
- return true;
981
- }
982
-
983
- function isFunction(d) {
984
- return typeof d === 'function';
985
- }
986
-
987
- function functionalUpdate(updater, previous) {
988
- if (isFunction(updater)) {
989
- return updater(previous);
990
- }
991
-
992
- return updater;
993
- }
994
- function pick(parent, keys) {
995
- return keys.reduce((obj, key) => {
996
- obj[key] = parent[key];
997
- return obj;
998
- }, {});
999
- }
463
+ return false;
464
+ }
1000
465
 
1001
466
  function joinPaths(paths) {
1002
467
  return cleanPath(paths.filter(Boolean).join('/'));
@@ -1015,8 +480,8 @@
1015
480
  return trimPathRight(trimPathLeft(path));
1016
481
  }
1017
482
  function resolvePath(basepath, base, to) {
1018
- base = base.replace(new RegExp("^" + basepath), '/');
1019
- to = to.replace(new RegExp("^" + basepath), '/');
483
+ base = base.replace(new RegExp(`^${basepath}`), '/');
484
+ to = to.replace(new RegExp(`^${basepath}`), '/');
1020
485
  let baseSegments = parsePathname(base);
1021
486
  const toSegments = parsePathname(to);
1022
487
  toSegments.forEach((toSegment, index) => {
@@ -1029,13 +494,10 @@
1029
494
  baseSegments.push(toSegment);
1030
495
  } else ;
1031
496
  } else if (toSegment.value === '..') {
1032
- var _last;
1033
-
1034
497
  // Extra trailing slash? pop it off
1035
- if (baseSegments.length > 1 && ((_last = last(baseSegments)) == null ? void 0 : _last.value) === '/') {
498
+ if (baseSegments.length > 1 && last(baseSegments)?.value === '/') {
1036
499
  baseSegments.pop();
1037
500
  }
1038
-
1039
501
  baseSegments.pop();
1040
502
  } else if (toSegment.value === '.') {
1041
503
  return;
@@ -1050,10 +512,8 @@
1050
512
  if (!pathname) {
1051
513
  return [];
1052
514
  }
1053
-
1054
515
  pathname = cleanPath(pathname);
1055
516
  const segments = [];
1056
-
1057
517
  if (pathname.slice(0, 1) === '/') {
1058
518
  pathname = pathname.substring(1);
1059
519
  segments.push({
@@ -1061,34 +521,30 @@
1061
521
  value: '/'
1062
522
  });
1063
523
  }
1064
-
1065
524
  if (!pathname) {
1066
525
  return segments;
1067
- } // Remove empty segments and '.' segments
1068
-
526
+ }
1069
527
 
528
+ // Remove empty segments and '.' segments
1070
529
  const split = pathname.split('/').filter(Boolean);
1071
530
  segments.push(...split.map(part => {
1072
- if (part.startsWith('*')) {
531
+ if (part === '$' || part === '*') {
1073
532
  return {
1074
533
  type: 'wildcard',
1075
534
  value: part
1076
535
  };
1077
536
  }
1078
-
1079
- if (part.charAt(0) === ':') {
537
+ if (part.charAt(0) === '$') {
1080
538
  return {
1081
539
  type: 'param',
1082
540
  value: part
1083
541
  };
1084
542
  }
1085
-
1086
543
  return {
1087
544
  type: 'pathname',
1088
545
  value: part
1089
546
  };
1090
547
  }));
1091
-
1092
548
  if (pathname.slice(-1) === '/') {
1093
549
  pathname = pathname.substring(1);
1094
550
  segments.push({
@@ -1096,66 +552,59 @@
1096
552
  value: '/'
1097
553
  });
1098
554
  }
1099
-
1100
555
  return segments;
1101
556
  }
1102
557
  function interpolatePath(path, params, leaveWildcard) {
1103
558
  const interpolatedPathSegments = parsePathname(path);
1104
559
  return joinPaths(interpolatedPathSegments.map(segment => {
1105
- if (segment.value === '*' && !leaveWildcard) {
560
+ if (['$', '*'].includes(segment.value) && !leaveWildcard) {
1106
561
  return '';
1107
562
  }
1108
-
1109
563
  if (segment.type === 'param') {
1110
- var _segment$value$substr;
1111
-
1112
- return (_segment$value$substr = params[segment.value.substring(1)]) != null ? _segment$value$substr : '';
564
+ return params[segment.value.substring(1)] ?? '';
1113
565
  }
1114
-
1115
566
  return segment.value;
1116
567
  }));
1117
568
  }
1118
- function matchPathname(currentPathname, matchLocation) {
1119
- const pathParams = matchByPath(currentPathname, matchLocation); // const searchMatched = matchBySearch(currentLocation.search, matchLocation)
569
+ function matchPathname(basepath, currentPathname, matchLocation) {
570
+ const pathParams = matchByPath(basepath, currentPathname, matchLocation);
571
+ // const searchMatched = matchBySearch(currentLocation.search, matchLocation)
1120
572
 
1121
573
  if (matchLocation.to && !pathParams) {
1122
574
  return;
1123
- } // if (matchLocation.search && !searchMatched) {
1124
- // return
1125
- // }
1126
-
1127
-
1128
- return pathParams != null ? pathParams : {};
575
+ }
576
+ return pathParams ?? {};
1129
577
  }
1130
- function matchByPath(from, matchLocation) {
1131
- var _matchLocation$to;
1132
-
578
+ function matchByPath(basepath, from, matchLocation) {
579
+ if (!from.startsWith(basepath)) {
580
+ return undefined;
581
+ }
582
+ from = basepath != '/' ? from.substring(basepath.length) : from;
1133
583
  const baseSegments = parsePathname(from);
1134
- const routeSegments = parsePathname("" + ((_matchLocation$to = matchLocation.to) != null ? _matchLocation$to : '*'));
584
+ const to = `${matchLocation.to ?? '$'}`;
585
+ const routeSegments = parsePathname(to);
586
+ if (last(baseSegments)?.value === '/') {
587
+ baseSegments.pop();
588
+ }
1135
589
  const params = {};
1136
-
1137
590
  let isMatch = (() => {
1138
591
  for (let i = 0; i < Math.max(baseSegments.length, routeSegments.length); i++) {
1139
592
  const baseSegment = baseSegments[i];
1140
593
  const routeSegment = routeSegments[i];
1141
594
  const isLastRouteSegment = i === routeSegments.length - 1;
1142
595
  const isLastBaseSegment = i === baseSegments.length - 1;
1143
-
1144
596
  if (routeSegment) {
1145
597
  if (routeSegment.type === 'wildcard') {
1146
- if (baseSegment != null && baseSegment.value) {
598
+ if (baseSegment?.value) {
1147
599
  params['*'] = joinPaths(baseSegments.slice(i).map(d => d.value));
1148
600
  return true;
1149
601
  }
1150
-
1151
602
  return false;
1152
603
  }
1153
-
1154
604
  if (routeSegment.type === 'pathname') {
1155
- if (routeSegment.value === '/' && !(baseSegment != null && baseSegment.value)) {
605
+ if (routeSegment.value === '/' && !baseSegment?.value) {
1156
606
  return true;
1157
607
  }
1158
-
1159
608
  if (baseSegment) {
1160
609
  if (matchLocation.caseSensitive) {
1161
610
  if (routeSegment.value !== baseSegment.value) {
@@ -1166,41 +615,36 @@
1166
615
  }
1167
616
  }
1168
617
  }
1169
-
1170
618
  if (!baseSegment) {
1171
619
  return false;
1172
620
  }
1173
-
1174
621
  if (routeSegment.type === 'param') {
1175
- if ((baseSegment == null ? void 0 : baseSegment.value) === '/') {
622
+ if (baseSegment?.value === '/') {
1176
623
  return false;
1177
624
  }
1178
-
1179
- if (!baseSegment.value.startsWith(':')) {
625
+ if (baseSegment.value.charAt(0) !== '$') {
1180
626
  params[routeSegment.value.substring(1)] = baseSegment.value;
1181
627
  }
1182
628
  }
1183
629
  }
1184
-
1185
630
  if (isLastRouteSegment && !isLastBaseSegment) {
1186
631
  return !!matchLocation.fuzzy;
1187
632
  }
1188
633
  }
1189
-
1190
634
  return true;
1191
635
  })();
1192
-
1193
636
  return isMatch ? params : undefined;
1194
637
  }
1195
638
 
1196
639
  // @ts-nocheck
640
+
1197
641
  // 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.
642
+
1198
643
  function encode(obj, pfx) {
1199
644
  var k,
1200
- i,
1201
- tmp,
1202
- str = '';
1203
-
645
+ i,
646
+ tmp,
647
+ str = '';
1204
648
  for (k in obj) {
1205
649
  if ((tmp = obj[k]) !== void 0) {
1206
650
  if (Array.isArray(tmp)) {
@@ -1214,10 +658,8 @@
1214
658
  }
1215
659
  }
1216
660
  }
1217
-
1218
661
  return (pfx || '') + str;
1219
662
  }
1220
-
1221
663
  function toValue(mix) {
1222
664
  if (!mix) return '';
1223
665
  var str = decodeURIComponent(mix);
@@ -1226,482 +668,153 @@
1226
668
  if (str.charAt(0) === '0') return str;
1227
669
  return +str * 0 === 0 ? +str : str;
1228
670
  }
1229
-
1230
671
  function decode(str) {
1231
672
  var tmp,
1232
- k,
1233
- out = {},
1234
- arr = str.split('&');
1235
-
673
+ k,
674
+ out = {},
675
+ arr = str.split('&');
1236
676
  while (tmp = arr.shift()) {
1237
677
  tmp = tmp.split('=');
1238
678
  k = tmp.shift();
1239
-
1240
679
  if (out[k] !== void 0) {
1241
680
  out[k] = [].concat(out[k], toValue(tmp.shift()));
1242
681
  } else {
1243
682
  out[k] = toValue(tmp.shift());
1244
683
  }
1245
684
  }
1246
-
1247
685
  return out;
1248
686
  }
1249
687
 
1250
- function _extends() {
1251
- _extends = Object.assign ? Object.assign.bind() : function (target) {
1252
- for (var i = 1; i < arguments.length; i++) {
1253
- var source = arguments[i];
688
+ const rootRouteId = '__root__';
689
+ class Route {
690
+ // Set up in this.init()
1254
691
 
1255
- for (var key in source) {
1256
- if (Object.prototype.hasOwnProperty.call(source, key)) {
1257
- target[key] = source[key];
1258
- }
1259
- }
1260
- }
1261
-
1262
- return target;
1263
- };
1264
- return _extends.apply(this, arguments);
1265
- }
1266
-
1267
- function createRoute(routeConfig, options, parent, router) {
1268
- const {
1269
- id,
1270
- routeId,
1271
- path: routePath,
1272
- fullPath
1273
- } = routeConfig;
1274
-
1275
- const action = router.state.actions[id] || (() => {
1276
- router.state.actions[id] = {
1277
- pending: [],
1278
- submit: async (submission, actionOpts) => {
1279
- var _actionOpts$invalidat;
1280
-
1281
- if (!route) {
1282
- return;
1283
- }
1284
-
1285
- const invalidate = (_actionOpts$invalidat = actionOpts == null ? void 0 : actionOpts.invalidate) != null ? _actionOpts$invalidat : true;
1286
- const actionState = {
1287
- submittedAt: Date.now(),
1288
- status: 'pending',
1289
- submission
1290
- };
1291
- action.current = actionState;
1292
- action.latest = actionState;
1293
- action.pending.push(actionState);
1294
- router.state = _extends({}, router.state, {
1295
- currentAction: actionState,
1296
- latestAction: actionState
1297
- });
1298
- router.notify();
1299
-
1300
- try {
1301
- const res = await (route.options.action == null ? void 0 : route.options.action(submission));
1302
- actionState.data = res;
692
+ // customId!: TCustomId
1303
693
 
1304
- if (invalidate) {
1305
- router.invalidateRoute({
1306
- to: '.',
1307
- fromCurrent: true
1308
- });
1309
- await router.reload();
1310
- }
1311
-
1312
- actionState.status = 'success';
1313
- return res;
1314
- } catch (err) {
1315
- console.error(err);
1316
- actionState.error = err;
1317
- actionState.status = 'error';
1318
- } finally {
1319
- action.pending = action.pending.filter(d => d !== actionState);
1320
- router.removeActionQueue.push({
1321
- action,
1322
- actionState
1323
- });
1324
- router.notify();
1325
- }
1326
- }
1327
- };
1328
- return router.state.actions[id];
1329
- })();
1330
-
1331
- const loader = router.state.loaders[id] || (() => {
1332
- router.state.loaders[id] = {
1333
- pending: [],
1334
- fetch: async loaderContext => {
1335
- if (!route) {
1336
- return;
1337
- }
1338
-
1339
- const loaderState = {
1340
- loadedAt: Date.now(),
1341
- loaderContext
1342
- };
1343
- loader.current = loaderState;
1344
- loader.latest = loaderState;
1345
- loader.pending.push(loaderState); // router.state = {
1346
- // ...router.state,
1347
- // currentAction: loaderState,
1348
- // latestAction: loaderState,
1349
- // }
694
+ // Optional
1350
695
 
1351
- router.notify();
1352
-
1353
- try {
1354
- return await (route.options.loader == null ? void 0 : route.options.loader(loaderContext));
1355
- } finally {
1356
- loader.pending = loader.pending.filter(d => d !== loaderState); // router.removeActionQueue.push({ loader, loaderState })
696
+ constructor(options) {
697
+ this.options = options || {};
698
+ this.isRoot = !options?.getParentRoute;
699
+ }
700
+ init = opts => {
701
+ this.originalIndex = opts.originalIndex;
702
+ this.router = opts.router;
703
+ const allOptions = this.options;
704
+ const isRoot = !allOptions?.path && !allOptions?.id;
705
+ this.parentRoute = this.options?.getParentRoute?.();
706
+ if (isRoot) {
707
+ this.path = rootRouteId;
708
+ } else {
709
+ invariant(this.parentRoute, `Child Route instances must pass a 'getParentRoute: () => ParentRoute' option that returns a Route instance.`);
710
+ }
711
+ let path = isRoot ? rootRouteId : allOptions.path;
1357
712
 
1358
- router.notify();
1359
- }
1360
- }
1361
- };
1362
- return router.state.loaders[id];
1363
- })();
713
+ // If the path is anything other than an index path, trim it up
714
+ if (path && path !== '/') {
715
+ path = trimPath(path);
716
+ }
717
+ const customId = allOptions?.id || path;
1364
718
 
1365
- let route = {
1366
- routeId: id,
1367
- routeRouteId: routeId,
1368
- routePath,
1369
- fullPath,
1370
- options,
1371
- router,
1372
- childRoutes: undefined,
1373
- parentRoute: parent,
1374
- action,
1375
- loader: loader,
1376
- buildLink: options => {
1377
- return router.buildLink(_extends({}, options, {
1378
- from: fullPath
1379
- }));
1380
- },
1381
- navigate: options => {
1382
- return router.navigate(_extends({}, options, {
1383
- from: fullPath
1384
- }));
1385
- },
1386
- matchRoute: (matchLocation, opts) => {
1387
- return router.matchRoute(_extends({}, matchLocation, {
1388
- from: fullPath
1389
- }), opts);
719
+ // Strip the parentId prefix from the first level of children
720
+ let id = isRoot ? rootRouteId : joinPaths([this.parentRoute.id === rootRouteId ? '' : this.parentRoute.id, customId]);
721
+ if (path === rootRouteId) {
722
+ path = '/';
1390
723
  }
724
+ if (id !== rootRouteId) {
725
+ id = joinPaths(['/', id]);
726
+ }
727
+ const fullPath = id === rootRouteId ? '/' : trimPathRight(joinPaths([this.parentRoute.fullPath, path]));
728
+ this.path = path;
729
+ this.id = id;
730
+ // this.customId = customId as TCustomId
731
+ this.fullPath = fullPath;
732
+ };
733
+ addChildren = children => {
734
+ this.children = children;
735
+ return this;
1391
736
  };
1392
- router.options.createRoute == null ? void 0 : router.options.createRoute({
1393
- router,
1394
- route
1395
- });
1396
- return route;
1397
- }
1398
- function cascadeLoaderData(matches) {
1399
- matches.forEach((match, index) => {
1400
- const parent = matches[index - 1];
1401
737
 
1402
- if (parent) {
1403
- match.loaderData = replaceEqualDeep(match.loaderData, _extends({}, parent.loaderData, match.routeLoaderData));
1404
- }
1405
- });
738
+ // generate = (
739
+ // options: Omit<
740
+ // RouteOptions<
741
+ // TParentRoute,
742
+ // TCustomId,
743
+ // TPath,
744
+ // InferFullSearchSchema<TParentRoute>,
745
+ // TSearchSchema,
746
+ // TFullSearchSchema,
747
+ // TParentRoute['__types']['allParams'],
748
+ // TParams,
749
+ // TAllParams,
750
+ // TParentContext,
751
+ // TAllParentContext,
752
+ // TRouteContext,
753
+ // TContext
754
+ // >,
755
+ // 'path'
756
+ // >,
757
+ // ) => {
758
+ // invariant(
759
+ // false,
760
+ // `route.generate() is used by TanStack Router's file-based routing code generation and should not actually be called during runtime. `,
761
+ // )
762
+ // }
1406
763
  }
1407
764
 
1408
- const rootRouteId = '__root__';
1409
- const createRouteConfig = function createRouteConfig(options, children, isRoot, parentId, parentPath) {
1410
- if (options === void 0) {
1411
- options = {};
1412
- }
1413
-
1414
- if (isRoot === void 0) {
1415
- isRoot = true;
1416
- }
1417
-
1418
- if (isRoot) {
1419
- options.path = rootRouteId;
1420
- } // Strip the root from parentIds
1421
-
1422
-
1423
- if (parentId === rootRouteId) {
1424
- parentId = '';
765
+ class RootRoute extends Route {
766
+ constructor(options) {
767
+ super(options);
1425
768
  }
1426
-
1427
- let path = isRoot ? rootRouteId : options.path; // If the path is anything other than an index path, trim it up
1428
-
1429
- if (path && path !== '/') {
1430
- path = trimPath(path);
1431
- }
1432
-
1433
- const routeId = path || options.id;
1434
- let id = joinPaths([parentId, routeId]);
1435
-
1436
- if (path === rootRouteId) {
1437
- path = '/';
1438
- }
1439
-
1440
- if (id !== rootRouteId) {
1441
- id = joinPaths(['/', id]);
1442
- }
1443
-
1444
- const fullPath = id === rootRouteId ? '/' : trimPathRight(joinPaths([parentPath, path]));
1445
- return {
1446
- id: id,
1447
- routeId: routeId,
1448
- path: path,
1449
- fullPath: fullPath,
1450
- options: options,
1451
- children,
1452
- createChildren: cb => createRouteConfig(options, cb(childOptions => createRouteConfig(childOptions, undefined, false, id, fullPath)), false, parentId, parentPath),
1453
- addChildren: children => createRouteConfig(options, children, false, parentId, parentPath),
1454
- createRoute: childOptions => createRouteConfig(childOptions, undefined, false, id, fullPath)
769
+ static withRouterContext = () => {
770
+ return options => new RootRoute(options);
1455
771
  };
1456
- };
1457
-
1458
- const elementTypes = ['element', 'errorElement', 'catchElement', 'pendingElement'];
1459
- function createRouteMatch(router, route, opts) {
1460
- const routeMatch = _extends({}, route, opts, {
1461
- router,
1462
- routeSearch: {},
1463
- search: {},
1464
- childMatches: [],
1465
- status: 'idle',
1466
- routeLoaderData: {},
1467
- loaderData: {},
1468
- isPending: false,
1469
- isFetching: false,
1470
- isInvalid: false,
1471
- invalidAt: Infinity,
1472
- getIsInvalid: () => {
1473
- const now = Date.now();
1474
- return routeMatch.isInvalid || routeMatch.invalidAt < now;
1475
- },
1476
- __: {
1477
- abortController: new AbortController(),
1478
- latestId: '',
1479
- resolve: () => {},
1480
- notify: () => {
1481
- routeMatch.__.resolve();
1482
-
1483
- routeMatch.router.notify();
1484
- },
1485
- startPending: () => {
1486
- var _routeMatch$options$p, _routeMatch$options$p2;
1487
-
1488
- const pendingMs = (_routeMatch$options$p = routeMatch.options.pendingMs) != null ? _routeMatch$options$p : router.options.defaultPendingMs;
1489
- const pendingMinMs = (_routeMatch$options$p2 = routeMatch.options.pendingMinMs) != null ? _routeMatch$options$p2 : router.options.defaultPendingMinMs;
1490
-
1491
- if (routeMatch.__.pendingTimeout || routeMatch.status !== 'loading' || typeof pendingMs === 'undefined') {
1492
- return;
1493
- }
1494
-
1495
- routeMatch.__.pendingTimeout = setTimeout(() => {
1496
- routeMatch.isPending = true;
1497
-
1498
- routeMatch.__.resolve();
1499
-
1500
- if (typeof pendingMinMs !== 'undefined') {
1501
- routeMatch.__.pendingMinPromise = new Promise(r => routeMatch.__.pendingMinTimeout = setTimeout(r, pendingMinMs));
1502
- }
1503
- }, pendingMs);
1504
- },
1505
- cancelPending: () => {
1506
- routeMatch.isPending = false;
1507
- clearTimeout(routeMatch.__.pendingTimeout);
1508
- clearTimeout(routeMatch.__.pendingMinTimeout);
1509
- delete routeMatch.__.pendingMinPromise;
1510
- },
1511
- // setParentMatch: (parentMatch?: RouteMatch) => {
1512
- // routeMatch.parentMatch = parentMatch
1513
- // },
1514
- // addChildMatch: (childMatch: RouteMatch) => {
1515
- // if (
1516
- // routeMatch.childMatches.find((d) => d.matchId === childMatch.matchId)
1517
- // ) {
1518
- // return
1519
- // }
1520
- // routeMatch.childMatches.push(childMatch)
1521
- // },
1522
- validate: () => {
1523
- var _routeMatch$parentMat, _routeMatch$parentMat2;
1524
-
1525
- // Validate the search params and stabilize them
1526
- const parentSearch = (_routeMatch$parentMat = (_routeMatch$parentMat2 = routeMatch.parentMatch) == null ? void 0 : _routeMatch$parentMat2.search) != null ? _routeMatch$parentMat : router.location.search;
1527
-
1528
- try {
1529
- const prevSearch = routeMatch.routeSearch;
1530
- const validator = typeof routeMatch.options.validateSearch === 'object' ? routeMatch.options.validateSearch.parse : routeMatch.options.validateSearch;
1531
- let nextSearch = replaceEqualDeep(prevSearch, validator == null ? void 0 : validator(parentSearch)); // Invalidate route matches when search param stability changes
1532
-
1533
- if (prevSearch !== nextSearch) {
1534
- routeMatch.isInvalid = true;
1535
- }
1536
-
1537
- routeMatch.routeSearch = nextSearch;
1538
- routeMatch.search = replaceEqualDeep(parentSearch, _extends({}, parentSearch, nextSearch));
1539
- } catch (err) {
1540
- console.error(err);
1541
- const error = new Error('Invalid search params found', {
1542
- cause: err
1543
- });
1544
- error.code = 'INVALID_SEARCH_PARAMS';
1545
- routeMatch.status = 'error';
1546
- routeMatch.error = error; // Do not proceed with loading the route
1547
-
1548
- return;
1549
- }
1550
- }
1551
- },
1552
- cancel: () => {
1553
- var _routeMatch$__$abortC;
1554
-
1555
- (_routeMatch$__$abortC = routeMatch.__.abortController) == null ? void 0 : _routeMatch$__$abortC.abort();
1556
-
1557
- routeMatch.__.cancelPending();
1558
- },
1559
- invalidate: () => {
1560
- routeMatch.isInvalid = true;
1561
- },
1562
- hasLoaders: () => {
1563
- return !!(route.options.loader || elementTypes.some(d => typeof route.options[d] === 'function'));
1564
- },
1565
- load: async loaderOpts => {
1566
- const now = Date.now();
1567
- 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
1568
-
1569
- if (loaderOpts != null && loaderOpts.preload && minMaxAge > 0) {
1570
- // If the match is currently active, don't preload it
1571
- if (router.state.matches.find(d => d.matchId === routeMatch.matchId)) {
1572
- return;
1573
- }
1574
-
1575
- router.matchCache[routeMatch.matchId] = {
1576
- gc: now + loaderOpts.gcMaxAge,
1577
- match: routeMatch
1578
- };
1579
- } // If the match is invalid, errored or idle, trigger it to load
1580
-
1581
-
1582
- if (routeMatch.status === 'success' && routeMatch.getIsInvalid() || routeMatch.status === 'error' || routeMatch.status === 'idle') {
1583
- const maxAge = loaderOpts != null && loaderOpts.preload ? loaderOpts == null ? void 0 : loaderOpts.maxAge : undefined;
1584
- routeMatch.fetch({
1585
- maxAge
1586
- });
1587
- }
1588
- },
1589
- fetch: async opts => {
1590
- const id = '' + Date.now() + Math.random();
1591
- routeMatch.__.latestId = id; // If the match was in an error state, set it
1592
- // to a loading state again. Otherwise, keep it
1593
- // as loading or resolved
1594
-
1595
- if (routeMatch.status === 'idle') {
1596
- routeMatch.status = 'loading';
1597
- } // We started loading the route, so it's no longer invalid
1598
-
1599
-
1600
- routeMatch.isInvalid = false;
1601
- routeMatch.__.loadPromise = new Promise(async resolve => {
1602
- // We are now fetching, even if it's in the background of a
1603
- // resolved state
1604
- routeMatch.isFetching = true;
1605
- routeMatch.__.resolve = resolve;
1606
-
1607
- const loaderPromise = (async () => {
1608
- // Load the elements and data in parallel
1609
- routeMatch.__.elementsPromise = (async () => {
1610
- // then run all element and data loaders in parallel
1611
- // For each element type, potentially load it asynchronously
1612
- await Promise.all(elementTypes.map(async type => {
1613
- const routeElement = routeMatch.options[type];
1614
-
1615
- if (routeMatch.__[type]) {
1616
- return;
1617
- }
1618
-
1619
- routeMatch.__[type] = await router.options.createElement(routeElement);
1620
- }));
1621
- })();
1622
-
1623
- routeMatch.__.dataPromise = Promise.resolve().then(async () => {
1624
- try {
1625
- var _ref, _ref2, _opts$maxAge;
1626
-
1627
- if (routeMatch.options.loader) {
1628
- const data = await routeMatch.options.loader({
1629
- params: routeMatch.params,
1630
- search: routeMatch.routeSearch,
1631
- signal: routeMatch.__.abortController.signal
1632
- });
1633
-
1634
- if (id !== routeMatch.__.latestId) {
1635
- return routeMatch.__.loaderPromise;
1636
- }
1637
-
1638
- routeMatch.routeLoaderData = replaceEqualDeep(routeMatch.routeLoaderData, data);
1639
- }
1640
-
1641
- routeMatch.error = undefined;
1642
- routeMatch.status = 'success';
1643
- routeMatch.updatedAt = Date.now();
1644
- 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);
1645
- } catch (err) {
1646
- if (id !== routeMatch.__.latestId) {
1647
- return routeMatch.__.loaderPromise;
1648
- }
1649
-
1650
- {
1651
- console.error(err);
1652
- }
1653
-
1654
- routeMatch.error = err;
1655
- routeMatch.status = 'error';
1656
- routeMatch.updatedAt = Date.now();
1657
- }
1658
- });
1659
-
1660
- try {
1661
- await Promise.all([routeMatch.__.elementsPromise, routeMatch.__.dataPromise]);
1662
-
1663
- if (id !== routeMatch.__.latestId) {
1664
- return routeMatch.__.loaderPromise;
1665
- }
1666
-
1667
- if (routeMatch.__.pendingMinPromise) {
1668
- await routeMatch.__.pendingMinPromise;
1669
- delete routeMatch.__.pendingMinPromise;
1670
- }
1671
- } finally {
1672
- if (id !== routeMatch.__.latestId) {
1673
- return routeMatch.__.loaderPromise;
1674
- }
1675
-
1676
- routeMatch.__.cancelPending();
1677
-
1678
- routeMatch.isPending = false;
1679
- routeMatch.isFetching = false;
1680
-
1681
- routeMatch.__.notify();
1682
- }
1683
- })();
1684
-
1685
- routeMatch.__.loaderPromise = loaderPromise;
1686
- await loaderPromise;
1687
-
1688
- if (id !== routeMatch.__.latestId) {
1689
- return routeMatch.__.loaderPromise;
1690
- }
1691
-
1692
- delete routeMatch.__.loaderPromise;
1693
- });
1694
- return await routeMatch.__.loadPromise;
1695
- }
1696
- });
1697
-
1698
- if (!routeMatch.hasLoaders()) {
1699
- routeMatch.status = 'success';
1700
- }
1701
-
1702
- return routeMatch;
1703
772
  }
1704
773
 
774
+ // const rootRoute = new RootRoute({
775
+ // validateSearch: () => null as unknown as { root?: boolean },
776
+ // })
777
+
778
+ // const aRoute = new Route({
779
+ // getParentRoute: () => rootRoute,
780
+ // path: 'a',
781
+ // validateSearch: () => null as unknown as { a?: string },
782
+ // })
783
+
784
+ // const bRoute = new Route({
785
+ // getParentRoute: () => aRoute,
786
+ // path: 'b',
787
+ // })
788
+
789
+ // const rootIsRoot = rootRoute.isRoot
790
+ // // ^?
791
+ // const aIsRoot = aRoute.isRoot
792
+ // // ^?
793
+
794
+ // const rId = rootRoute.id
795
+ // // ^?
796
+ // const aId = aRoute.id
797
+ // // ^?
798
+ // const bId = bRoute.id
799
+ // // ^?
800
+
801
+ // const rPath = rootRoute.fullPath
802
+ // // ^?
803
+ // const aPath = aRoute.fullPath
804
+ // // ^?
805
+ // const bPath = bRoute.fullPath
806
+ // // ^?
807
+
808
+ // const rSearch = rootRoute.__types.fullSearchSchema
809
+ // // ^?
810
+ // const aSearch = aRoute.__types.fullSearchSchema
811
+ // // ^?
812
+ // const bSearch = bRoute.__types.fullSearchSchema
813
+ // // ^?
814
+
815
+ // const config = rootRoute.addChildren([aRoute.addChildren([bRoute])])
816
+ // // ^?
817
+
1705
818
  const defaultParseSearch = parseSearchWith(JSON.parse);
1706
819
  const defaultStringifySearch = stringifySearchWith(JSON.stringify);
1707
820
  function parseSearchWith(parser) {
@@ -1709,1156 +822,1382 @@
1709
822
  if (searchStr.substring(0, 1) === '?') {
1710
823
  searchStr = searchStr.substring(1);
1711
824
  }
825
+ let query = decode(searchStr);
1712
826
 
1713
- let query = decode(searchStr); // Try to parse any query params that might be json
1714
-
827
+ // Try to parse any query params that might be json
1715
828
  for (let key in query) {
1716
829
  const value = query[key];
1717
-
1718
830
  if (typeof value === 'string') {
1719
831
  try {
1720
832
  query[key] = parser(value);
1721
- } catch (err) {//
833
+ } catch (err) {
834
+ //
1722
835
  }
1723
836
  }
1724
837
  }
1725
-
1726
838
  return query;
1727
839
  };
1728
840
  }
1729
841
  function stringifySearchWith(stringify) {
1730
842
  return search => {
1731
- search = _extends({}, search);
1732
-
843
+ search = {
844
+ ...search
845
+ };
1733
846
  if (search) {
1734
847
  Object.keys(search).forEach(key => {
1735
848
  const val = search[key];
1736
-
1737
849
  if (typeof val === 'undefined' || val === undefined) {
1738
850
  delete search[key];
1739
851
  } else if (val && typeof val === 'object' && val !== null) {
1740
852
  try {
1741
853
  search[key] = stringify(val);
1742
- } catch (err) {// silent
854
+ } catch (err) {
855
+ // silent
1743
856
  }
1744
857
  }
1745
858
  });
1746
859
  }
1747
-
1748
860
  const searchStr = encode(search).toString();
1749
- return searchStr ? "?" + searchStr : '';
861
+ return searchStr ? `?${searchStr}` : '';
1750
862
  };
1751
863
  }
1752
864
 
1753
- var _window$document;
1754
- // Detect if we're in the DOM
1755
- const isServer = typeof window === 'undefined' || !((_window$document = window.document) != null && _window$document.createElement); // This is the default history object if none is defined
1756
-
1757
- const createDefaultHistory = () => isServer ? createMemoryHistory() : createBrowserHistory();
1758
-
1759
- function createRouter(userOptions) {
1760
- var _userOptions$stringif, _userOptions$parseSea;
1761
-
1762
- const history = (userOptions == null ? void 0 : userOptions.history) || createDefaultHistory();
1763
-
1764
- const originalOptions = _extends({
1765
- defaultLoaderGcMaxAge: 5 * 60 * 1000,
1766
- defaultLoaderMaxAge: 0,
1767
- defaultPreloadMaxAge: 2000,
1768
- defaultPreloadDelay: 50
1769
- }, userOptions, {
1770
- stringifySearch: (_userOptions$stringif = userOptions == null ? void 0 : userOptions.stringifySearch) != null ? _userOptions$stringif : defaultStringifySearch,
1771
- parseSearch: (_userOptions$parseSea = userOptions == null ? void 0 : userOptions.parseSearch) != null ? _userOptions$parseSea : defaultParseSearch
1772
- });
1773
-
1774
- let router = {
1775
- history,
1776
- options: originalOptions,
1777
- listeners: [],
1778
- removeActionQueue: [],
1779
- // Resolved after construction
1780
- basepath: '',
1781
- routeTree: undefined,
1782
- routesById: {},
1783
- location: undefined,
1784
- allRouteInfo: undefined,
1785
- //
1786
- navigationPromise: Promise.resolve(),
1787
- resolveNavigation: () => {},
1788
- matchCache: {},
1789
- state: {
1790
- status: 'idle',
1791
- location: null,
1792
- matches: [],
1793
- actions: {},
1794
- loaders: {},
1795
- lastUpdated: Date.now(),
1796
- isFetching: false,
1797
- isPreloading: false
1798
- },
1799
- startedLoadingAt: Date.now(),
1800
- subscribe: listener => {
1801
- router.listeners.push(listener);
1802
- return () => {
1803
- router.listeners = router.listeners.filter(x => x !== listener);
1804
- };
1805
- },
1806
- getRoute: id => {
1807
- return router.routesById[id];
1808
- },
1809
- notify: () => {
1810
- router.state = _extends({}, router.state, {
1811
- isFetching: router.state.status === 'loading' || router.state.matches.some(d => d.isFetching),
1812
- isPreloading: Object.values(router.matchCache).some(d => d.match.isFetching && !router.state.matches.find(dd => dd.matchId === d.match.matchId))
1813
- });
1814
- cascadeLoaderData(router.state.matches);
1815
- router.listeners.forEach(listener => listener(router));
1816
- },
1817
- dehydrateState: () => {
1818
- return _extends({}, pick(router.state, ['status', 'location', 'lastUpdated']), {
1819
- matches: router.state.matches.map(match => pick(match, ['matchId', 'status', 'routeLoaderData', 'loaderData', 'isInvalid', 'invalidAt']))
1820
- });
1821
- },
1822
- hydrateState: dehydratedState => {
1823
- // Match the routes
1824
- const matches = router.matchRoutes(router.location.pathname, {
1825
- strictParseParams: true
1826
- });
1827
- router.state = _extends({}, router.state, dehydratedState, {
1828
- matches: matches.map(match => {
1829
- const dehydratedMatch = dehydratedState.matches.find(d => d.matchId === match.matchId);
1830
- invariant(dehydratedMatch, 'Oh no! Dehydrated route matches did not match the active state of the router 😬');
1831
- Object.assign(match, dehydratedMatch);
1832
- return match;
1833
- })
1834
- });
1835
- },
1836
- mount: () => {
1837
- const next = router.__.buildLocation({
1838
- to: '.',
1839
- search: true,
1840
- hash: true
1841
- }); // If the current location isn't updated, trigger a navigation
1842
- // to the current location. Otherwise, load the current location.
1843
-
1844
-
1845
- if (next.href !== router.location.href) {
1846
- router.__.commitLocation(next, true);
865
+ const defaultFetchServerDataFn = async ({
866
+ router,
867
+ routeMatch
868
+ }) => {
869
+ const next = router.buildNext({
870
+ to: '.',
871
+ search: d => ({
872
+ ...(d ?? {}),
873
+ __data: {
874
+ matchId: routeMatch.id
1847
875
  }
1848
-
1849
- router.loadLocation();
1850
- const unsub = router.history.listen(event => {
1851
- console.log(event.location);
1852
- router.loadLocation(router.__.parseLocation(event.location, router.location));
1853
- }); // addEventListener does not exist in React Native, but window does
1854
- // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
1855
-
1856
- if (!isServer && window.addEventListener) {
1857
- // Listen to visibillitychange and focus
1858
- window.addEventListener('visibilitychange', router.onFocus, false);
1859
- window.addEventListener('focus', router.onFocus, false);
876
+ })
877
+ });
878
+ const res = await fetch(next.href, {
879
+ method: 'GET',
880
+ signal: routeMatch.abortController.signal
881
+ });
882
+ if (res.ok) {
883
+ return res.json();
884
+ }
885
+ throw new Error('Failed to fetch match data');
886
+ };
887
+ class Router {
888
+ #unsubHistory;
889
+ startedLoadingAt = Date.now();
890
+ resolveNavigation = () => {};
891
+ constructor(options) {
892
+ this.options = {
893
+ defaultPreloadDelay: 50,
894
+ context: undefined,
895
+ ...options,
896
+ stringifySearch: options?.stringifySearch ?? defaultStringifySearch,
897
+ parseSearch: options?.parseSearch ?? defaultParseSearch,
898
+ fetchServerDataFn: options?.fetchServerDataFn ?? defaultFetchServerDataFn
899
+ };
900
+ this.__store = new Store(getInitialRouterState(), {
901
+ onUpdate: state => {
902
+ this.state = state;
1860
903
  }
1861
-
1862
- return () => {
1863
- unsub(); // Be sure to unsubscribe if a new handler is set
1864
-
1865
- window.removeEventListener('visibilitychange', router.onFocus);
1866
- window.removeEventListener('focus', router.onFocus);
1867
- };
1868
- },
1869
- onFocus: () => {
1870
- router.loadLocation();
1871
- },
1872
- update: opts => {
1873
- const newHistory = (opts == null ? void 0 : opts.history) !== router.history;
1874
-
1875
- if (!router.location || newHistory) {
1876
- if (opts != null && opts.history) {
1877
- router.history = opts.history;
1878
- }
1879
-
1880
- router.location = router.__.parseLocation(router.history.location);
1881
- router.state.location = router.location;
904
+ });
905
+ this.state = this.__store.state;
906
+ this.basepath = '';
907
+ this.update(options);
908
+
909
+ // Allow frameworks to hook into the router creation
910
+ this.options.Router?.(this);
911
+ const next = this.buildNext({
912
+ hash: true,
913
+ fromCurrent: true,
914
+ search: true,
915
+ state: true
916
+ });
917
+ if (this.state.latestLocation.href !== next.href) {
918
+ this.#commitLocation({
919
+ ...next,
920
+ replace: true
921
+ });
922
+ }
923
+ }
924
+ reset = () => {
925
+ this.__store.setState(s => Object.assign(s, getInitialRouterState()));
926
+ };
927
+ mount = () => {
928
+ // Mount only does anything on the client
929
+ if (!isServer) {
930
+ // If the router matches are empty, start loading the matches
931
+ if (!this.state.currentMatches.length) {
932
+ this.safeLoad();
1882
933
  }
1883
-
1884
- Object.assign(router.options, opts);
1885
- const {
1886
- basepath,
1887
- routeConfig
1888
- } = router.options;
1889
- router.basepath = cleanPath("/" + (basepath != null ? basepath : ''));
1890
-
1891
- if (routeConfig) {
1892
- router.routesById = {};
1893
- router.routeTree = router.__.buildRouteTree(routeConfig);
934
+ }
935
+ return () => {};
936
+ };
937
+ update = opts => {
938
+ Object.assign(this.options, opts);
939
+ if (!this.history || this.options.history && this.options.history !== this.history) {
940
+ if (this.#unsubHistory) {
941
+ this.#unsubHistory();
1894
942
  }
1895
-
1896
- return router;
1897
- },
1898
- cancelMatches: () => {
1899
- var _router$state$pending, _router$state$pending2;
1900
- [...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 => {
1901
- match.cancel();
943
+ this.history = this.options.history ?? (isServer ? createMemoryHistory() : createBrowserHistory());
944
+ const parsedLocation = this.#parseLocation();
945
+ this.__store.setState(s => ({
946
+ ...s,
947
+ latestLocation: parsedLocation,
948
+ currentLocation: parsedLocation
949
+ }));
950
+ this.#unsubHistory = this.history.listen(() => {
951
+ this.safeLoad({
952
+ next: this.#parseLocation(this.state.latestLocation)
953
+ });
1902
954
  });
1903
- },
1904
- loadLocation: async next => {
1905
- const id = Math.random();
1906
- router.startedLoadingAt = id;
1907
-
1908
- if (next) {
955
+ }
956
+ const {
957
+ basepath,
958
+ routeTree
959
+ } = this.options;
960
+ this.basepath = `/${trimPath(basepath ?? '') ?? ''}`;
961
+ if (routeTree) {
962
+ this.routesById = {};
963
+ this.routeTree = this.#buildRouteTree(routeTree);
964
+ }
965
+ return this;
966
+ };
967
+ buildNext = opts => {
968
+ const next = this.#buildLocation(opts);
969
+ const __matches = this.matchRoutes(next.pathname);
970
+ return this.#buildLocation({
971
+ ...opts,
972
+ __matches
973
+ });
974
+ };
975
+ cancelMatches = () => {
976
+ [...this.state.currentMatches, ...(this.state.pendingMatches || [])].forEach(match => {
977
+ match.cancel();
978
+ });
979
+ };
980
+ safeLoad = opts => {
981
+ this.load(opts).catch(err => {
982
+ console.warn(err);
983
+ invariant(false, 'Encountered an error during router.load()! ☝️.');
984
+ });
985
+ };
986
+ load = async opts => {
987
+ let now = Date.now();
988
+ const startedAt = now;
989
+ this.startedLoadingAt = startedAt;
990
+
991
+ // Cancel any pending matches
992
+ this.cancelMatches();
993
+ let matches;
994
+ this.__store.batch(() => {
995
+ if (opts?.next) {
1909
996
  // Ingest the new location
1910
- router.location = next;
1911
- } // Clear out old actions
1912
-
1913
-
1914
- router.removeActionQueue.forEach(_ref => {
1915
- let {
1916
- action,
1917
- actionState
1918
- } = _ref;
1919
-
1920
- if (router.state.currentAction === actionState) {
1921
- router.state.currentAction = undefined;
1922
- }
1923
-
1924
- if (action.current === actionState) {
1925
- action.current = undefined;
1926
- }
1927
- });
1928
- router.removeActionQueue = []; // Cancel any pending matches
1929
-
1930
- router.cancelMatches(); // Match the routes
997
+ this.__store.setState(s => ({
998
+ ...s,
999
+ latestLocation: opts.next
1000
+ }));
1001
+ }
1931
1002
 
1932
- const matches = router.matchRoutes(router.location.pathname, {
1003
+ // Match the routes
1004
+ matches = this.matchRoutes(this.state.latestLocation.pathname, {
1933
1005
  strictParseParams: true
1934
1006
  });
1935
- router.state = _extends({}, router.state, {
1936
- pending: {
1937
- matches: matches,
1938
- location: router.location
1939
- },
1940
- status: 'loading'
1941
- });
1942
- router.notify(); // Load the matches
1007
+ this.__store.setState(s => ({
1008
+ ...s,
1009
+ status: 'pending',
1010
+ pendingMatches: matches,
1011
+ pendingLocation: this.state.latestLocation
1012
+ }));
1013
+ });
1943
1014
 
1944
- await router.loadMatches(matches, {
1945
- withPending: true
1946
- });
1015
+ // Load the matches
1016
+ await this.loadMatches(matches, this.state.pendingLocation
1017
+ // opts
1018
+ );
1947
1019
 
1948
- if (router.startedLoadingAt !== id) {
1949
- // Ignore side-effects of match loading
1950
- return router.navigationPromise;
1020
+ if (this.startedLoadingAt !== startedAt) {
1021
+ // Ignore side-effects of outdated side-effects
1022
+ return this.navigationPromise;
1023
+ }
1024
+ const previousMatches = this.state.currentMatches;
1025
+ const exiting = [],
1026
+ staying = [];
1027
+ previousMatches.forEach(d => {
1028
+ if (matches.find(dd => dd.id === d.id)) {
1029
+ staying.push(d);
1030
+ } else {
1031
+ exiting.push(d);
1951
1032
  }
1952
-
1953
- const previousMatches = router.state.matches;
1954
- const exiting = [],
1955
- staying = [];
1956
- previousMatches.forEach(d => {
1957
- if (matches.find(dd => dd.matchId === d.matchId)) {
1958
- staying.push(d);
1959
- } else {
1960
- exiting.push(d);
1961
- }
1033
+ });
1034
+ const entering = matches.filter(d => {
1035
+ return !previousMatches.find(dd => dd.id === d.id);
1036
+ });
1037
+ now = Date.now();
1038
+ exiting.forEach(d => {
1039
+ d.__onExit?.({
1040
+ params: d.params,
1041
+ search: d.state.routeSearch
1962
1042
  });
1963
- const now = Date.now();
1964
- exiting.forEach(d => {
1965
- var _ref2, _d$options$loaderGcMa, _ref3, _d$options$loaderMaxA;
1966
-
1967
- d.__.onExit == null ? void 0 : d.__.onExit({
1968
- params: d.params,
1969
- search: d.routeSearch
1970
- }); // Clear idle error states when match leaves
1971
-
1972
- if (d.status === 'error' && !d.isFetching) {
1973
- d.status = 'idle';
1974
- d.error = undefined;
1975
- }
1976
-
1977
- 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);
1978
1043
 
1979
- if (gc > 0) {
1980
- router.matchCache[d.matchId] = {
1981
- gc: gc == Infinity ? Number.MAX_SAFE_INTEGER : now + gc,
1982
- match: d
1983
- };
1984
- }
1985
- });
1986
- staying.forEach(d => {
1987
- d.options.onTransition == null ? void 0 : d.options.onTransition({
1988
- params: d.params,
1989
- search: d.routeSearch
1990
- });
1044
+ // Clear non-loading error states when match leaves
1045
+ if (d.state.status === 'error') {
1046
+ this.__store.setState(s => ({
1047
+ ...s,
1048
+ status: 'idle',
1049
+ error: undefined
1050
+ }));
1051
+ }
1052
+ });
1053
+ staying.forEach(d => {
1054
+ d.route.options.onTransition?.({
1055
+ params: d.params,
1056
+ search: d.state.routeSearch
1991
1057
  });
1992
- const entering = matches.filter(d => {
1993
- return !previousMatches.find(dd => dd.matchId === d.matchId);
1058
+ });
1059
+ entering.forEach(d => {
1060
+ d.__onExit = d.route.options.onLoaded?.({
1061
+ params: d.params,
1062
+ search: d.state.search
1994
1063
  });
1995
- entering.forEach(d => {
1996
- d.__.onExit = d.options.onMatch == null ? void 0 : d.options.onMatch({
1997
- params: d.params,
1998
- search: d.search
1064
+ });
1065
+ const prevLocation = this.state.currentLocation;
1066
+ this.__store.setState(s => ({
1067
+ ...s,
1068
+ status: 'idle',
1069
+ currentLocation: this.state.latestLocation,
1070
+ currentMatches: matches,
1071
+ pendingLocation: undefined,
1072
+ pendingMatches: undefined
1073
+ }));
1074
+ matches.forEach(match => {
1075
+ match.__commit();
1076
+ });
1077
+ if (prevLocation.href !== this.state.currentLocation.href) {
1078
+ this.options.onRouteChange?.();
1079
+ }
1080
+ this.resolveNavigation();
1081
+ };
1082
+ getRoute = id => {
1083
+ const route = this.routesById[id];
1084
+ invariant(route, `Route with id "${id}" not found`);
1085
+ return route;
1086
+ };
1087
+ loadRoute = async (navigateOpts = this.state.latestLocation) => {
1088
+ const next = this.buildNext(navigateOpts);
1089
+ const matches = this.matchRoutes(next.pathname, {
1090
+ strictParseParams: true
1091
+ });
1092
+ await this.loadMatches(matches, next);
1093
+ return matches;
1094
+ };
1095
+ preloadRoute = async (navigateOpts = this.state.latestLocation) => {
1096
+ const next = this.buildNext(navigateOpts);
1097
+ const matches = this.matchRoutes(next.pathname, {
1098
+ strictParseParams: true
1099
+ });
1100
+ await this.loadMatches(matches, next, {
1101
+ preload: true
1102
+ });
1103
+ return matches;
1104
+ };
1105
+ matchRoutes = (pathname, opts) => {
1106
+ const matches = [];
1107
+ if (!this.routeTree) {
1108
+ return matches;
1109
+ }
1110
+ const existingMatches = [...this.state.currentMatches, ...(this.state.pendingMatches ?? [])];
1111
+ const findInRouteTree = async routes => {
1112
+ const parentMatch = last(matches);
1113
+ let params = parentMatch?.params ?? {};
1114
+ const filteredRoutes = this.options.filterRoutes?.(routes) ?? routes;
1115
+ let matchingRoutes = [];
1116
+ const findMatchInRoutes = (parentRoutes, routes) => {
1117
+ routes.some(route => {
1118
+ const children = route.children;
1119
+ if (!route.path && children?.length) {
1120
+ return findMatchInRoutes([...matchingRoutes, route], children);
1121
+ }
1122
+ const fuzzy = !!(route.path !== '/' || children?.length);
1123
+ const matchParams = matchPathname(this.basepath, pathname, {
1124
+ to: route.fullPath,
1125
+ fuzzy,
1126
+ caseSensitive: route.options.caseSensitive ?? this.options.caseSensitive
1127
+ });
1128
+ if (matchParams) {
1129
+ let parsedParams;
1130
+ try {
1131
+ parsedParams = route.options.parseParams?.(matchParams) ?? matchParams;
1132
+ } catch (err) {
1133
+ if (opts?.strictParseParams) {
1134
+ throw err;
1135
+ }
1136
+ }
1137
+ params = {
1138
+ ...params,
1139
+ ...parsedParams
1140
+ };
1141
+ }
1142
+ if (!!matchParams) {
1143
+ matchingRoutes = [...parentRoutes, route];
1144
+ }
1145
+ return !!matchingRoutes.length;
1146
+ });
1147
+ return !!matchingRoutes.length;
1148
+ };
1149
+ findMatchInRoutes([], filteredRoutes);
1150
+ if (!matchingRoutes.length) {
1151
+ return;
1152
+ }
1153
+ matchingRoutes.forEach(foundRoute => {
1154
+ const interpolatedPath = interpolatePath(foundRoute.path, params);
1155
+ const matchId = interpolatePath(foundRoute.id, params, true);
1156
+ const match = existingMatches.find(d => d.id === matchId) || new RouteMatch(this, foundRoute, {
1157
+ id: matchId,
1158
+ params,
1159
+ pathname: joinPaths([this.basepath, interpolatedPath])
1999
1160
  });
2000
- delete router.matchCache[d.matchId];
1161
+ matches.push(match);
2001
1162
  });
2002
-
2003
- if (matches.some(d => d.status === 'loading')) {
2004
- router.notify();
2005
- await Promise.all(matches.map(d => d.__.loaderPromise || Promise.resolve()));
1163
+ const foundRoute = last(matchingRoutes);
1164
+ const foundChildren = foundRoute.children;
1165
+ if (foundChildren?.length) {
1166
+ findInRouteTree(foundChildren);
2006
1167
  }
2007
-
2008
- if (router.startedLoadingAt !== id) {
2009
- // Ignore side-effects of match loading
1168
+ };
1169
+ findInRouteTree([this.routeTree]);
1170
+ return matches;
1171
+ };
1172
+ loadMatches = async (resolvedMatches, location, opts) => {
1173
+ // Check each match middleware to see if the route can be accessed
1174
+ try {
1175
+ await Promise.all(resolvedMatches.map(async match => {
1176
+ try {
1177
+ await match.route.options.beforeLoad?.({
1178
+ router: this,
1179
+ match
1180
+ });
1181
+ } catch (err) {
1182
+ if (isRedirect(err)) {
1183
+ throw err;
1184
+ }
1185
+ const errorHandler = match.route.options.onBeforeLoadError ?? match.route.options.onError;
1186
+ errorHandler?.(err);
1187
+ throw err;
1188
+ }
1189
+ }));
1190
+ } catch (err) {
1191
+ if (isRedirect(err)) {
1192
+ if (!opts?.preload) {
1193
+ this.navigate(err);
1194
+ }
2010
1195
  return;
2011
1196
  }
2012
-
2013
- router.state = _extends({}, router.state, {
2014
- location: router.location,
2015
- matches,
2016
- pending: undefined,
2017
- status: 'idle'
1197
+ throw err;
1198
+ }
1199
+ const matchPromises = resolvedMatches.map(async (match, index) => {
1200
+ const parentMatch = resolvedMatches[index - 1];
1201
+ match.__load({
1202
+ preload: opts?.preload,
1203
+ location,
1204
+ parentMatch
2018
1205
  });
2019
- router.notify();
2020
- router.resolveNavigation();
2021
- },
2022
- cleanMatchCache: () => {
2023
- const now = Date.now();
2024
- Object.keys(router.matchCache).forEach(matchId => {
2025
- const entry = router.matchCache[matchId]; // Don't remove loading matches
2026
-
2027
- if (entry.match.status === 'loading') {
2028
- return;
2029
- } // Do not remove successful matches that are still valid
2030
-
2031
-
2032
- if (entry.gc > 0 && entry.gc > now) {
2033
- return;
2034
- } // Everything else gets removed
2035
-
1206
+ await match.__loadPromise;
1207
+ if (parentMatch) {
1208
+ await parentMatch.__loadPromise;
1209
+ }
1210
+ });
1211
+ await Promise.all(matchPromises);
1212
+ };
1213
+ reload = () => {
1214
+ this.navigate({
1215
+ fromCurrent: true,
1216
+ replace: true,
1217
+ search: true
1218
+ });
1219
+ };
1220
+ resolvePath = (from, path) => {
1221
+ return resolvePath(this.basepath, from, cleanPath(path));
1222
+ };
1223
+ navigate = async ({
1224
+ from,
1225
+ to = '',
1226
+ search,
1227
+ hash,
1228
+ replace,
1229
+ params
1230
+ }) => {
1231
+ // If this link simply reloads the current route,
1232
+ // make sure it has a new key so it will trigger a data refresh
1233
+
1234
+ // If this `to` is a valid external URL, return
1235
+ // null for LinkUtils
1236
+ const toString = String(to);
1237
+ const fromString = typeof from === 'undefined' ? from : String(from);
1238
+ let isExternal;
1239
+ try {
1240
+ new URL(`${toString}`);
1241
+ isExternal = true;
1242
+ } catch (e) {}
1243
+ invariant(!isExternal, 'Attempting to navigate to external url with this.navigate!');
1244
+ return this.#commitLocation({
1245
+ from: fromString,
1246
+ to: toString,
1247
+ search,
1248
+ hash,
1249
+ replace,
1250
+ params
1251
+ });
1252
+ };
1253
+ matchRoute = (location, opts) => {
1254
+ location = {
1255
+ ...location,
1256
+ to: location.to ? this.resolvePath(location.from ?? '', location.to) : undefined
1257
+ };
1258
+ const next = this.buildNext(location);
1259
+ const baseLocation = opts?.pending ? this.state.pendingLocation : this.state.currentLocation;
1260
+ if (!baseLocation) {
1261
+ return false;
1262
+ }
1263
+ const match = matchPathname(this.basepath, baseLocation.pathname, {
1264
+ ...opts,
1265
+ to: next.pathname
1266
+ });
1267
+ if (!match) {
1268
+ return false;
1269
+ }
1270
+ if (opts?.includeSearch ?? true) {
1271
+ return partialDeepEqual(baseLocation.search, next.search) ? match : false;
1272
+ }
1273
+ return match;
1274
+ };
1275
+ buildLink = ({
1276
+ from,
1277
+ to = '.',
1278
+ search,
1279
+ params,
1280
+ hash,
1281
+ target,
1282
+ replace,
1283
+ activeOptions,
1284
+ preload,
1285
+ preloadDelay: userPreloadDelay,
1286
+ disabled
1287
+ }) => {
1288
+ // If this link simply reloads the current route,
1289
+ // make sure it has a new key so it will trigger a data refresh
1290
+
1291
+ // If this `to` is a valid external URL, return
1292
+ // null for LinkUtils
2036
1293
 
2037
- delete router.matchCache[matchId];
2038
- });
2039
- },
2040
- loadRoute: async function loadRoute(navigateOpts) {
2041
- if (navigateOpts === void 0) {
2042
- navigateOpts = router.location;
1294
+ try {
1295
+ new URL(`${to}`);
1296
+ return {
1297
+ type: 'external',
1298
+ href: to
1299
+ };
1300
+ } catch (e) {}
1301
+ const nextOpts = {
1302
+ from,
1303
+ to,
1304
+ search,
1305
+ params,
1306
+ hash,
1307
+ replace
1308
+ };
1309
+ const next = this.buildNext(nextOpts);
1310
+ preload = preload ?? this.options.defaultPreload;
1311
+ const preloadDelay = userPreloadDelay ?? this.options.defaultPreloadDelay ?? 0;
1312
+
1313
+ // Compare path/hash for matches
1314
+ const currentPathSplit = this.state.currentLocation.pathname.split('/');
1315
+ const nextPathSplit = next.pathname.split('/');
1316
+ const pathIsFuzzyEqual = nextPathSplit.every((d, i) => d === currentPathSplit[i]);
1317
+ // Combine the matches based on user options
1318
+ const pathTest = activeOptions?.exact ? this.state.currentLocation.pathname === next.pathname : pathIsFuzzyEqual;
1319
+ const hashTest = activeOptions?.includeHash ? this.state.currentLocation.hash === next.hash : true;
1320
+ const searchTest = activeOptions?.includeSearch ?? true ? partialDeepEqual(this.state.currentLocation.search, next.search) : true;
1321
+
1322
+ // The final "active" test
1323
+ const isActive = pathTest && hashTest && searchTest;
1324
+
1325
+ // The click handler
1326
+ const handleClick = e => {
1327
+ if (!disabled && !isCtrlEvent(e) && !e.defaultPrevented && (!target || target === '_self') && e.button === 0) {
1328
+ e.preventDefault();
1329
+
1330
+ // All is well? Navigate!
1331
+ this.#commitLocation(nextOpts);
2043
1332
  }
1333
+ };
2044
1334
 
2045
- const next = router.buildNext(navigateOpts);
2046
- const matches = router.matchRoutes(next.pathname, {
2047
- strictParseParams: true
1335
+ // The click handler
1336
+ const handleFocus = e => {
1337
+ if (preload) {
1338
+ this.preloadRoute(nextOpts).catch(err => {
1339
+ console.warn(err);
1340
+ console.warn('Error preloading route! ☝️');
1341
+ });
1342
+ }
1343
+ };
1344
+ const handleTouchStart = e => {
1345
+ this.preloadRoute(nextOpts).catch(err => {
1346
+ console.warn(err);
1347
+ console.warn('Error preloading route! ☝️');
2048
1348
  });
2049
- await router.loadMatches(matches);
2050
- return matches;
2051
- },
2052
- preloadRoute: async function preloadRoute(navigateOpts, loaderOpts) {
2053
- var _ref4, _ref5, _loaderOpts$maxAge, _ref6, _ref7, _loaderOpts$gcMaxAge;
2054
-
2055
- if (navigateOpts === void 0) {
2056
- navigateOpts = router.location;
1349
+ };
1350
+ const handleEnter = e => {
1351
+ const target = e.target || {};
1352
+ if (preload) {
1353
+ if (target.preloadTimeout) {
1354
+ return;
1355
+ }
1356
+ target.preloadTimeout = setTimeout(() => {
1357
+ target.preloadTimeout = null;
1358
+ this.preloadRoute(nextOpts).catch(err => {
1359
+ console.warn(err);
1360
+ console.warn('Error preloading route! ☝️');
1361
+ });
1362
+ }, preloadDelay);
2057
1363
  }
2058
-
2059
- const next = router.buildNext(navigateOpts);
2060
- const matches = router.matchRoutes(next.pathname, {
1364
+ };
1365
+ const handleLeave = e => {
1366
+ const target = e.target || {};
1367
+ if (target.preloadTimeout) {
1368
+ clearTimeout(target.preloadTimeout);
1369
+ target.preloadTimeout = null;
1370
+ }
1371
+ };
1372
+ return {
1373
+ type: 'internal',
1374
+ next,
1375
+ handleFocus,
1376
+ handleClick,
1377
+ handleEnter,
1378
+ handleLeave,
1379
+ handleTouchStart,
1380
+ isActive,
1381
+ disabled
1382
+ };
1383
+ };
1384
+ dehydrate = () => {
1385
+ return {
1386
+ state: {
1387
+ ...pick(this.state, ['latestLocation', 'currentLocation', 'status', 'lastUpdated']),
1388
+ currentMatches: this.state.currentMatches.map(match => ({
1389
+ id: match.id,
1390
+ state: {
1391
+ status: match.state.status
1392
+ }
1393
+ }))
1394
+ }
1395
+ };
1396
+ };
1397
+ hydrate = dehydratedRouter => {
1398
+ this.__store.setState(s => {
1399
+ // Match the routes
1400
+ const currentMatches = this.matchRoutes(dehydratedRouter.state.latestLocation.pathname, {
2061
1401
  strictParseParams: true
2062
1402
  });
2063
- await router.loadMatches(matches, {
2064
- preload: true,
2065
- maxAge: (_ref4 = (_ref5 = (_loaderOpts$maxAge = loaderOpts.maxAge) != null ? _loaderOpts$maxAge : router.options.defaultPreloadMaxAge) != null ? _ref5 : router.options.defaultLoaderMaxAge) != null ? _ref4 : 0,
2066
- gcMaxAge: (_ref6 = (_ref7 = (_loaderOpts$gcMaxAge = loaderOpts.gcMaxAge) != null ? _loaderOpts$gcMaxAge : router.options.defaultPreloadGcMaxAge) != null ? _ref7 : router.options.defaultLoaderGcMaxAge) != null ? _ref6 : 0
1403
+ currentMatches.forEach((match, index) => {
1404
+ const dehydratedMatch = dehydratedRouter.state.currentMatches[index];
1405
+ invariant(dehydratedMatch && dehydratedMatch.id === match.id, 'Oh no! There was a hydration mismatch when attempting to hydrate the state of the router! 😬');
1406
+ match.__store.setState(s => ({
1407
+ ...s,
1408
+ ...dehydratedMatch.state
1409
+ }));
2067
1410
  });
2068
- return matches;
2069
- },
2070
- matchRoutes: (pathname, opts) => {
2071
- var _router$state$pending3, _router$state$pending4;
2072
-
2073
- router.cleanMatchCache();
2074
- const matches = [];
2075
-
2076
- if (!router.routeTree) {
2077
- return matches;
2078
- }
2079
-
2080
- 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 : [])];
2081
-
2082
- const recurse = async routes => {
2083
- var _parentMatch$params, _router$options$filte, _foundRoute$childRout;
2084
-
2085
- const parentMatch = last(matches);
2086
- let params = (_parentMatch$params = parentMatch == null ? void 0 : parentMatch.params) != null ? _parentMatch$params : {};
2087
- const filteredRoutes = (_router$options$filte = router.options.filterRoutes == null ? void 0 : router.options.filterRoutes(routes)) != null ? _router$options$filte : routes;
2088
- let foundRoutes = [];
2089
-
2090
- const findMatchInRoutes = (parentRoutes, routes) => {
2091
- routes.some(route => {
2092
- var _route$childRoutes, _route$childRoutes2, _route$options$caseSe;
2093
-
2094
- if (!route.routePath && (_route$childRoutes = route.childRoutes) != null && _route$childRoutes.length) {
2095
- return findMatchInRoutes([...foundRoutes, route], route.childRoutes);
1411
+ return {
1412
+ ...s,
1413
+ ...dehydratedRouter.state,
1414
+ currentMatches
1415
+ };
1416
+ });
1417
+ };
1418
+ #buildRouteTree = routeTree => {
1419
+ const recurseRoutes = (routes, parentRoute) => {
1420
+ routes.forEach((route, i) => {
1421
+ route.init({
1422
+ originalIndex: i,
1423
+ router: this
1424
+ });
1425
+ const existingRoute = this.routesById[route.id];
1426
+ invariant(!existingRoute, `Duplicate routes found with id: ${String(route.id)}`);
1427
+ this.routesById[route.id] = route;
1428
+ const children = route.children;
1429
+ if (children?.length) {
1430
+ recurseRoutes(children);
1431
+ route.children = children.map((d, i) => {
1432
+ const parsed = parsePathname(trimPathLeft(cleanPath(d.path ?? '/')));
1433
+ while (parsed.length > 1 && parsed[0]?.value === '/') {
1434
+ parsed.shift();
2096
1435
  }
2097
-
2098
- const fuzzy = !!(route.routePath !== '/' || (_route$childRoutes2 = route.childRoutes) != null && _route$childRoutes2.length);
2099
- const matchParams = matchPathname(pathname, {
2100
- to: route.fullPath,
2101
- fuzzy,
2102
- caseSensitive: (_route$options$caseSe = route.options.caseSensitive) != null ? _route$options$caseSe : router.options.caseSensitive
2103
- });
2104
-
2105
- if (matchParams) {
2106
- let parsedParams;
2107
-
2108
- try {
2109
- var _route$options$parseP;
2110
-
2111
- parsedParams = (_route$options$parseP = route.options.parseParams == null ? void 0 : route.options.parseParams(matchParams)) != null ? _route$options$parseP : matchParams;
2112
- } catch (err) {
2113
- if (opts != null && opts.strictParseParams) {
2114
- throw err;
2115
- }
1436
+ let score = 0;
1437
+ parsed.forEach((d, i) => {
1438
+ let modifier = 1;
1439
+ while (i--) {
1440
+ modifier *= 0.001;
2116
1441
  }
2117
-
2118
- params = _extends({}, params, parsedParams);
2119
- }
2120
-
2121
- if (!!matchParams) {
2122
- foundRoutes = [...parentRoutes, route];
1442
+ if (d.type === 'pathname' && d.value !== '/') {
1443
+ score += 1 * modifier;
1444
+ } else if (d.type === 'param') {
1445
+ score += 2 * modifier;
1446
+ } else if (d.type === 'wildcard') {
1447
+ score += 3 * modifier;
1448
+ }
1449
+ });
1450
+ return {
1451
+ child: d,
1452
+ parsed,
1453
+ index: i,
1454
+ score
1455
+ };
1456
+ }).sort((a, b) => {
1457
+ if (a.score !== b.score) {
1458
+ return a.score - b.score;
2123
1459
  }
2124
-
2125
- return !!foundRoutes.length;
2126
- });
2127
- return !!foundRoutes.length;
2128
- };
2129
-
2130
- findMatchInRoutes([], filteredRoutes);
2131
-
2132
- if (!foundRoutes.length) {
2133
- return;
2134
- }
2135
-
2136
- foundRoutes.forEach(foundRoute => {
2137
- var _router$matchCache$ma;
2138
-
2139
- const interpolatedPath = interpolatePath(foundRoute.routePath, params);
2140
- const matchId = interpolatePath(foundRoute.routeId, params, true);
2141
- const match = existingMatches.find(d => d.matchId === matchId) || ((_router$matchCache$ma = router.matchCache[matchId]) == null ? void 0 : _router$matchCache$ma.match) || createRouteMatch(router, foundRoute, {
2142
- matchId,
2143
- params,
2144
- pathname: joinPaths([pathname, interpolatedPath])
2145
- });
2146
- matches.push(match);
2147
- });
2148
- const foundRoute = last(foundRoutes);
2149
-
2150
- if ((_foundRoute$childRout = foundRoute.childRoutes) != null && _foundRoute$childRout.length) {
2151
- recurse(foundRoute.childRoutes);
2152
- }
2153
- };
2154
-
2155
- recurse([router.routeTree]);
2156
- cascadeLoaderData(matches);
2157
- return matches;
2158
- },
2159
- loadMatches: async (resolvedMatches, loaderOpts) => {
2160
- const matchPromises = resolvedMatches.map(async match => {
2161
- // Validate the match (loads search params etc)
2162
- match.__.validate();
2163
-
2164
- match.load(loaderOpts);
2165
-
2166
- if (match.status === 'loading') {
2167
- // If requested, start the pending timers
2168
- if (loaderOpts != null && loaderOpts.withPending) match.__.startPending(); // Wait for the first sign of activity from the match
2169
- // This might be completion, error, or a pending state
2170
-
2171
- await match.__.loadPromise;
1460
+ return a.index - b.index;
1461
+ }).map(d => d.child);
2172
1462
  }
2173
1463
  });
2174
- router.notify();
2175
- await Promise.all(matchPromises);
2176
- },
2177
- invalidateRoute: opts => {
2178
- var _router$state$pending5, _router$state$pending6;
2179
-
2180
- const next = router.buildNext(opts);
2181
- const unloadedMatchIds = router.matchRoutes(next.pathname).map(d => d.matchId);
2182
- [...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 => {
2183
- if (unloadedMatchIds.includes(match.matchId)) {
2184
- match.invalidate();
1464
+ };
1465
+ recurseRoutes([routeTree]);
1466
+ const recurceCheckRoutes = (routes, parentRoute) => {
1467
+ routes.forEach(route => {
1468
+ if (route.isRoot) {
1469
+ invariant(!parentRoute, 'Root routes can only be used as the root of a route tree.');
1470
+ } else {
1471
+ invariant(parentRoute ? route.parentRoute === parentRoute : true, `Expected a route with path "${route.path}" to be passed to its parent route "${route.parentRoute?.id}" in an addChildren() call, but was instead passed as a child of the "${parentRoute?.id}" route.`);
2185
1472
  }
2186
- });
2187
- },
2188
- reload: () => router.__.navigate({
2189
- fromCurrent: true,
2190
- replace: true,
2191
- search: true
2192
- }),
2193
- resolvePath: (from, path) => {
2194
- return resolvePath(router.basepath, from, cleanPath(path));
2195
- },
2196
- matchRoute: (location, opts) => {
2197
- var _location$from;
2198
-
2199
- // const location = router.buildNext(opts)
2200
- location = _extends({}, location, {
2201
- to: location.to ? router.resolvePath((_location$from = location.from) != null ? _location$from : '', location.to) : undefined
2202
- });
2203
- const next = router.buildNext(location);
2204
-
2205
- if (opts != null && opts.pending) {
2206
- var _router$state$pending7;
2207
-
2208
- if (!((_router$state$pending7 = router.state.pending) != null && _router$state$pending7.location)) {
2209
- return false;
1473
+ if (route.children) {
1474
+ recurceCheckRoutes(route.children, route);
2210
1475
  }
2211
-
2212
- return !!matchPathname(router.state.pending.location.pathname, _extends({}, opts, {
2213
- to: next.pathname
2214
- }));
2215
- }
2216
-
2217
- return !!matchPathname(router.state.location.pathname, _extends({}, opts, {
2218
- to: next.pathname
2219
- }));
2220
- },
2221
- navigate: async _ref8 => {
2222
- let {
2223
- from,
2224
- to = '.',
2225
- search,
2226
- hash,
2227
- replace,
2228
- params
2229
- } = _ref8;
2230
- // If this link simply reloads the current route,
2231
- // make sure it has a new key so it will trigger a data refresh
2232
- // If this `to` is a valid external URL, return
2233
- // null for LinkUtils
2234
- const toString = String(to);
2235
- const fromString = String(from);
2236
- let isExternal;
2237
-
2238
- try {
2239
- new URL("" + toString);
2240
- isExternal = true;
2241
- } catch (e) {}
2242
-
2243
- invariant(!isExternal, 'Attempting to navigate to external url with router.navigate!');
2244
- return router.__.navigate({
2245
- from: fromString,
2246
- to: toString,
2247
- search,
2248
- hash,
2249
- replace,
2250
- params
2251
1476
  });
2252
- },
2253
- buildLink: _ref9 => {
2254
- var _preload, _ref10;
2255
-
2256
- let {
2257
- from,
2258
- to = '.',
2259
- search,
2260
- params,
2261
- hash,
2262
- target,
2263
- replace,
2264
- activeOptions,
2265
- preload,
2266
- preloadMaxAge: userPreloadMaxAge,
2267
- preloadGcMaxAge: userPreloadGcMaxAge,
2268
- preloadDelay: userPreloadDelay,
2269
- disabled
2270
- } = _ref9;
2271
-
2272
- // If this link simply reloads the current route,
2273
- // make sure it has a new key so it will trigger a data refresh
2274
- // If this `to` is a valid external URL, return
2275
- // null for LinkUtils
2276
- try {
2277
- new URL("" + to);
2278
- return {
2279
- type: 'external',
2280
- href: to
1477
+ };
1478
+ recurceCheckRoutes([routeTree], undefined);
1479
+ return routeTree;
1480
+ };
1481
+ #parseLocation = previousLocation => {
1482
+ let {
1483
+ pathname,
1484
+ search,
1485
+ hash,
1486
+ state
1487
+ } = this.history.location;
1488
+ const parsedSearch = this.options.parseSearch(search);
1489
+ return {
1490
+ pathname: pathname,
1491
+ searchStr: search,
1492
+ search: replaceEqualDeep(previousLocation?.search, parsedSearch),
1493
+ hash: hash.split('#').reverse()[0] ?? '',
1494
+ href: `${pathname}${search}${hash}`,
1495
+ state: state,
1496
+ key: state?.key || '__init__'
1497
+ };
1498
+ };
1499
+ #buildLocation = (dest = {}) => {
1500
+ dest.fromCurrent = dest.fromCurrent ?? dest.to === '';
1501
+ const fromPathname = dest.fromCurrent ? this.state.latestLocation.pathname : dest.from ?? this.state.latestLocation.pathname;
1502
+ let pathname = resolvePath(this.basepath ?? '/', fromPathname, `${dest.to ?? ''}`);
1503
+ const fromMatches = this.matchRoutes(this.state.latestLocation.pathname, {
1504
+ strictParseParams: true
1505
+ });
1506
+ const prevParams = {
1507
+ ...last(fromMatches)?.params
1508
+ };
1509
+ let nextParams = (dest.params ?? true) === true ? prevParams : functionalUpdate(dest.params, prevParams);
1510
+ if (nextParams) {
1511
+ dest.__matches?.map(d => d.route.options.stringifyParams).filter(Boolean).forEach(fn => {
1512
+ nextParams = {
1513
+ ...nextParams,
1514
+ ...fn(nextParams)
2281
1515
  };
2282
- } catch (e) {}
2283
-
2284
- const nextOpts = {
2285
- from,
2286
- to,
2287
- search,
2288
- params,
2289
- hash,
2290
- replace
2291
- };
2292
- const next = router.buildNext(nextOpts);
2293
- preload = (_preload = preload) != null ? _preload : router.options.defaultPreload;
2294
- const preloadDelay = (_ref10 = userPreloadDelay != null ? userPreloadDelay : router.options.defaultPreloadDelay) != null ? _ref10 : 0; // Compare path/hash for matches
2295
-
2296
- const pathIsEqual = router.state.location.pathname === next.pathname;
2297
- const currentPathSplit = router.state.location.pathname.split('/');
2298
- const nextPathSplit = next.pathname.split('/');
2299
- const pathIsFuzzyEqual = nextPathSplit.every((d, i) => d === currentPathSplit[i]);
2300
- const hashIsEqual = router.state.location.hash === next.hash; // Combine the matches based on user options
2301
-
2302
- const pathTest = activeOptions != null && activeOptions.exact ? pathIsEqual : pathIsFuzzyEqual;
2303
- const hashTest = activeOptions != null && activeOptions.includeHash ? hashIsEqual : true; // The final "active" test
2304
-
2305
- const isActive = pathTest && hashTest; // The click handler
2306
-
2307
- const handleClick = e => {
2308
- if (!disabled && !isCtrlEvent(e) && !e.defaultPrevented && (!target || target === '_self') && e.button === 0) {
2309
- e.preventDefault();
2310
-
2311
- if (pathIsEqual && !search && !hash) {
2312
- router.invalidateRoute(nextOpts);
2313
- } // All is well? Navigate!)
2314
-
2315
-
2316
- router.__.navigate(nextOpts);
2317
- }
2318
- }; // The click handler
2319
-
2320
-
2321
- const handleFocus = e => {
2322
- if (preload) {
2323
- router.preloadRoute(nextOpts, {
2324
- maxAge: userPreloadMaxAge,
2325
- gcMaxAge: userPreloadGcMaxAge
2326
- });
2327
- }
1516
+ });
1517
+ }
1518
+ pathname = interpolatePath(pathname, nextParams ?? {});
1519
+ const preSearchFilters = dest.__matches?.map(match => match.route.options.preSearchFilters ?? []).flat().filter(Boolean) ?? [];
1520
+ const postSearchFilters = dest.__matches?.map(match => match.route.options.postSearchFilters ?? []).flat().filter(Boolean) ?? [];
1521
+
1522
+ // Pre filters first
1523
+ const preFilteredSearch = preSearchFilters?.length ? preSearchFilters?.reduce((prev, next) => next(prev), this.state.latestLocation.search) : this.state.latestLocation.search;
1524
+
1525
+ // Then the link/navigate function
1526
+ const destSearch = dest.search === true ? preFilteredSearch // Preserve resolvedFrom true
1527
+ : dest.search ? functionalUpdate(dest.search, preFilteredSearch) ?? {} // Updater
1528
+ : preSearchFilters?.length ? preFilteredSearch // Preserve resolvedFrom filters
1529
+ : {};
1530
+
1531
+ // Then post filters
1532
+ const postFilteredSearch = postSearchFilters?.length ? postSearchFilters.reduce((prev, next) => next(prev), destSearch) : destSearch;
1533
+ const search = replaceEqualDeep(this.state.latestLocation.search, postFilteredSearch);
1534
+ const searchStr = this.options.stringifySearch(search);
1535
+ let hash = dest.hash === true ? this.state.latestLocation.hash : functionalUpdate(dest.hash, this.state.latestLocation.hash);
1536
+ hash = hash ? `#${hash}` : '';
1537
+ const nextState = dest.state === true ? this.state.latestLocation.state : functionalUpdate(dest.state, this.state.latestLocation.state);
1538
+ return {
1539
+ pathname,
1540
+ search,
1541
+ searchStr,
1542
+ state: nextState,
1543
+ hash,
1544
+ href: this.history.createHref(`${pathname}${searchStr}${hash}`),
1545
+ key: dest.key
1546
+ };
1547
+ };
1548
+ #commitLocation = async location => {
1549
+ const next = this.buildNext(location);
1550
+ const id = '' + Date.now() + Math.random();
1551
+ if (this.navigateTimeout) clearTimeout(this.navigateTimeout);
1552
+ let nextAction = 'replace';
1553
+ if (!location.replace) {
1554
+ nextAction = 'push';
1555
+ }
1556
+ const isSameUrl = this.state.latestLocation.href === next.href;
1557
+ if (isSameUrl && !next.key) {
1558
+ nextAction = 'replace';
1559
+ }
1560
+ const href = `${next.pathname}${next.searchStr}${next.hash ? `#${next.hash}` : ''}`;
1561
+ this.history[nextAction === 'push' ? 'push' : 'replace'](href, {
1562
+ id,
1563
+ ...next.state
1564
+ });
1565
+ return this.navigationPromise = new Promise(resolve => {
1566
+ const previousNavigationResolve = this.resolveNavigation;
1567
+ this.resolveNavigation = () => {
1568
+ previousNavigationResolve();
1569
+ resolve();
2328
1570
  };
1571
+ });
1572
+ };
1573
+ }
2329
1574
 
2330
- const handleEnter = e => {
2331
- const target = e.target || {};
2332
-
2333
- if (preload) {
2334
- if (target.preloadTimeout) {
2335
- return;
2336
- }
1575
+ // Detect if we're in the DOM
1576
+ const isServer = typeof window === 'undefined' || !window.document.createElement;
1577
+ function getInitialRouterState() {
1578
+ return {
1579
+ status: 'idle',
1580
+ latestLocation: null,
1581
+ currentLocation: null,
1582
+ currentMatches: [],
1583
+ lastUpdated: Date.now()
1584
+ };
1585
+ }
1586
+ function isCtrlEvent(e) {
1587
+ return !!(e.metaKey || e.altKey || e.ctrlKey || e.shiftKey);
1588
+ }
1589
+ function redirect(opts) {
1590
+ opts.isRedirect = true;
1591
+ return opts;
1592
+ }
1593
+ function isRedirect(obj) {
1594
+ return !!obj?.isRedirect;
1595
+ }
2337
1596
 
2338
- target.preloadTimeout = setTimeout(() => {
2339
- target.preloadTimeout = null;
2340
- router.preloadRoute(nextOpts, {
2341
- maxAge: userPreloadMaxAge,
2342
- gcMaxAge: userPreloadGcMaxAge
2343
- });
2344
- }, preloadDelay);
1597
+ const componentTypes = ['component', 'errorComponent', 'pendingComponent'];
1598
+ class RouteMatch {
1599
+ abortController = new AbortController();
1600
+ constructor(router, route, opts) {
1601
+ Object.assign(this, {
1602
+ route,
1603
+ router,
1604
+ id: opts.id,
1605
+ pathname: opts.pathname,
1606
+ params: opts.params,
1607
+ __store: new Store({
1608
+ updatedAt: 0,
1609
+ routeSearch: {},
1610
+ search: {},
1611
+ status: 'idle'
1612
+ }, {
1613
+ onUpdate: next => {
1614
+ this.state = next;
2345
1615
  }
1616
+ })
1617
+ });
1618
+ this.state = this.__store.state;
1619
+ componentTypes.map(async type => {
1620
+ const component = this.route.options[type];
1621
+ if (typeof this[type] !== 'function') {
1622
+ this[type] = component;
1623
+ }
1624
+ });
1625
+ if (this.state.status === 'idle' && !this.#hasLoaders()) {
1626
+ this.__store.setState(s => ({
1627
+ ...s,
1628
+ status: 'success'
1629
+ }));
1630
+ }
1631
+ }
1632
+ #hasLoaders = () => {
1633
+ return !!(this.route.options.onLoad || componentTypes.some(d => this.route.options[d]?.preload));
1634
+ };
1635
+ __commit = () => {
1636
+ const {
1637
+ routeSearch,
1638
+ search,
1639
+ context,
1640
+ routeContext
1641
+ } = this.#resolveInfo({
1642
+ location: this.router.state.currentLocation
1643
+ });
1644
+ this.context = context;
1645
+ this.routeContext = routeContext;
1646
+ this.__store.setState(s => ({
1647
+ ...s,
1648
+ routeSearch: replaceEqualDeep(s.routeSearch, routeSearch),
1649
+ search: replaceEqualDeep(s.search, search)
1650
+ }));
1651
+ };
1652
+ cancel = () => {
1653
+ this.abortController?.abort();
1654
+ };
1655
+ #resolveSearchInfo = opts => {
1656
+ // Validate the search params and stabilize them
1657
+ const parentSearchInfo = this.parentMatch ? this.parentMatch.#resolveSearchInfo(opts) : {
1658
+ search: opts.location.search,
1659
+ routeSearch: opts.location.search
1660
+ };
1661
+ try {
1662
+ const validator = typeof this.route.options.validateSearch === 'object' ? this.route.options.validateSearch.parse : this.route.options.validateSearch;
1663
+ const routeSearch = validator?.(parentSearchInfo.search) ?? {};
1664
+ const search = {
1665
+ ...parentSearchInfo.search,
1666
+ ...routeSearch
2346
1667
  };
2347
-
2348
- const handleLeave = e => {
2349
- const target = e.target || {};
2350
-
2351
- if (target.preloadTimeout) {
2352
- clearTimeout(target.preloadTimeout);
2353
- target.preloadTimeout = null;
2354
- }
1668
+ return {
1669
+ routeSearch,
1670
+ search
1671
+ };
1672
+ } catch (err) {
1673
+ if (isRedirect(err)) {
1674
+ throw err;
1675
+ }
1676
+ const errorHandler = this.route.options.onValidateSearchError ?? this.route.options.onError;
1677
+ errorHandler?.(err);
1678
+ const error = new Error('Invalid search params found', {
1679
+ cause: err
1680
+ });
1681
+ error.code = 'INVALID_SEARCH_PARAMS';
1682
+ throw error;
1683
+ }
1684
+ };
1685
+ #resolveInfo = opts => {
1686
+ const {
1687
+ search,
1688
+ routeSearch
1689
+ } = this.#resolveSearchInfo(opts);
1690
+ try {
1691
+ const routeContext = this.route.options.getContext?.({
1692
+ parentContext: this.parentMatch?.routeContext ?? {},
1693
+ context: this.parentMatch?.context ?? this.router?.options.context ?? {},
1694
+ params: this.params,
1695
+ search
1696
+ }) || {};
1697
+ const context = {
1698
+ ...(this.parentMatch?.context ?? this.router?.options.context),
1699
+ ...routeContext
2355
1700
  };
2356
-
2357
1701
  return {
2358
- type: 'internal',
2359
- next,
2360
- handleFocus,
2361
- handleClick,
2362
- handleEnter,
2363
- handleLeave,
2364
- isActive,
2365
- disabled
1702
+ routeSearch,
1703
+ search,
1704
+ context,
1705
+ routeContext
2366
1706
  };
2367
- },
2368
- buildNext: opts => {
2369
- const next = router.__.buildLocation(opts);
2370
-
2371
- const matches = router.matchRoutes(next.pathname);
2372
-
2373
- const __preSearchFilters = matches.map(match => {
2374
- var _match$options$preSea;
2375
-
2376
- return (_match$options$preSea = match.options.preSearchFilters) != null ? _match$options$preSea : [];
2377
- }).flat().filter(Boolean);
2378
-
2379
- const __postSearchFilters = matches.map(match => {
2380
- var _match$options$postSe;
2381
-
2382
- return (_match$options$postSe = match.options.postSearchFilters) != null ? _match$options$postSe : [];
2383
- }).flat().filter(Boolean);
2384
-
2385
- return router.__.buildLocation(_extends({}, opts, {
2386
- __preSearchFilters,
2387
- __postSearchFilters
2388
- }));
2389
- },
2390
- __: {
2391
- buildRouteTree: rootRouteConfig => {
2392
- const recurseRoutes = (routeConfigs, parent) => {
2393
- return routeConfigs.map(routeConfig => {
2394
- const routeOptions = routeConfig.options;
2395
- const route = createRoute(routeConfig, routeOptions, parent, router);
2396
- const existingRoute = router.routesById[route.routeId];
2397
-
2398
- if (existingRoute) {
2399
- {
2400
- console.warn("Duplicate routes found with id: " + String(route.routeId), router.routesById, route);
2401
- }
2402
-
2403
- throw new Error();
2404
- }
2405
- router.routesById[route.routeId] = route;
2406
- const children = routeConfig.children;
2407
- route.childRoutes = children != null && children.length ? recurseRoutes(children, route) : undefined;
2408
- return route;
2409
- });
2410
- };
2411
-
2412
- const routes = recurseRoutes([rootRouteConfig]);
2413
- return routes[0];
2414
- },
2415
- parseLocation: (location, previousLocation) => {
2416
- var _location$hash$split$;
2417
-
2418
- const parsedSearch = router.options.parseSearch(location.search);
2419
- return {
2420
- pathname: location.pathname,
2421
- searchStr: location.search,
2422
- search: replaceEqualDeep(previousLocation == null ? void 0 : previousLocation.search, parsedSearch),
2423
- hash: (_location$hash$split$ = location.hash.split('#').reverse()[0]) != null ? _location$hash$split$ : '',
2424
- href: "" + location.pathname + location.search + location.hash,
2425
- state: location.state,
2426
- key: location.key
2427
- };
2428
- },
2429
- navigate: location => {
2430
- const next = router.buildNext(location);
2431
- return router.__.commitLocation(next, location.replace);
2432
- },
2433
- buildLocation: function buildLocation(dest) {
2434
- var _dest$from, _router$basepath, _dest$to, _last, _dest$params, _dest$__preSearchFilt, _functionalUpdate, _dest$__preSearchFilt2, _dest$__postSearchFil;
2435
-
2436
- if (dest === void 0) {
2437
- dest = {};
1707
+ } catch (err) {
1708
+ this.route.options.onError?.(err);
1709
+ throw err;
1710
+ }
1711
+ };
1712
+ __load = async opts => {
1713
+ this.parentMatch = opts.parentMatch;
1714
+ let info;
1715
+ try {
1716
+ info = this.#resolveInfo(opts);
1717
+ } catch (err) {
1718
+ if (isRedirect(err)) {
1719
+ if (!opts?.preload) {
1720
+ this.router.navigate(err);
2438
1721
  }
1722
+ return;
1723
+ }
1724
+ this.__store.setState(s => ({
1725
+ ...s,
1726
+ status: 'error',
1727
+ error: err
1728
+ }));
2439
1729
 
2440
- // const resolvedFrom: Location = {
2441
- // ...router.location,
2442
- const fromPathname = dest.fromCurrent ? router.location.pathname : (_dest$from = dest.from) != null ? _dest$from : router.location.pathname;
2443
-
2444
- let pathname = resolvePath((_router$basepath = router.basepath) != null ? _router$basepath : '/', fromPathname, "" + ((_dest$to = dest.to) != null ? _dest$to : '.'));
2445
-
2446
- const fromMatches = router.matchRoutes(router.location.pathname, {
2447
- strictParseParams: true
2448
- });
2449
- const toMatches = router.matchRoutes(pathname);
2450
-
2451
- const prevParams = _extends({}, (_last = last(fromMatches)) == null ? void 0 : _last.params);
1730
+ // Do not proceed with loading the route
1731
+ return;
1732
+ }
1733
+ const {
1734
+ routeSearch,
1735
+ search,
1736
+ context,
1737
+ routeContext
1738
+ } = info;
1739
+
1740
+ // If the match is invalid, errored or idle, trigger it to load
1741
+ if (this.state.status === 'pending') {
1742
+ return;
1743
+ }
2452
1744
 
2453
- let nextParams = ((_dest$params = dest.params) != null ? _dest$params : true) === true ? prevParams : functionalUpdate(dest.params, prevParams);
1745
+ // TODO: Should load promises be tracked based on location?
1746
+ this.__loadPromise = Promise.resolve().then(async () => {
1747
+ const loadId = '' + Date.now() + Math.random();
1748
+ this.#latestId = loadId;
1749
+ const checkLatest = () => {
1750
+ return loadId !== this.#latestId ? this.__loadPromise : undefined;
1751
+ };
1752
+ let latestPromise;
2454
1753
 
2455
- if (nextParams) {
2456
- toMatches.map(d => d.options.stringifyParams).filter(Boolean).forEach(fn => {
2457
- Object.assign({}, nextParams, fn(nextParams));
1754
+ // If the match was in an error state, set it
1755
+ // to a loading state again. Otherwise, keep it
1756
+ // as loading or resolved
1757
+ if (this.state.status === 'idle') {
1758
+ this.__store.setState(s => ({
1759
+ ...s,
1760
+ status: 'pending'
1761
+ }));
1762
+ }
1763
+ const componentsPromise = (async () => {
1764
+ // then run all component and data loaders in parallel
1765
+ // For each component type, potentially load it asynchronously
1766
+
1767
+ await Promise.all(componentTypes.map(async type => {
1768
+ const component = this.route.options[type];
1769
+ if (this[type]?.preload) {
1770
+ this[type] = await this.router.options.loadComponent(component);
1771
+ }
1772
+ }));
1773
+ })();
1774
+ const dataPromise = Promise.resolve().then(() => {
1775
+ if (this.route.options.onLoad) {
1776
+ return this.route.options.onLoad({
1777
+ params: this.params,
1778
+ routeSearch,
1779
+ search,
1780
+ signal: this.abortController.signal,
1781
+ preload: !!opts?.preload,
1782
+ routeContext: routeContext,
1783
+ context: context
2458
1784
  });
2459
1785
  }
2460
-
2461
- pathname = interpolatePath(pathname, nextParams != null ? nextParams : {}); // Pre filters first
2462
-
2463
- 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
2464
-
2465
- const destSearch = dest.search === true ? preFilteredSearch // Preserve resolvedFrom true
2466
- : dest.search ? (_functionalUpdate = functionalUpdate(dest.search, preFilteredSearch)) != null ? _functionalUpdate : {} // Updater
2467
- : (_dest$__preSearchFilt2 = dest.__preSearchFilters) != null && _dest$__preSearchFilt2.length ? preFilteredSearch // Preserve resolvedFrom filters
2468
- : {}; // Then post filters
2469
-
2470
- const postFilteredSearch = (_dest$__postSearchFil = dest.__postSearchFilters) != null && _dest$__postSearchFil.length ? dest.__postSearchFilters.reduce((prev, next) => next(prev), destSearch) : destSearch;
2471
- const search = replaceEqualDeep(router.location.search, postFilteredSearch);
2472
- const searchStr = router.options.stringifySearch(search);
2473
- let hash = dest.hash === true ? router.location.hash : functionalUpdate(dest.hash, router.location.hash);
2474
- hash = hash ? "#" + hash : '';
2475
- return {
2476
- pathname,
2477
- search,
2478
- searchStr,
2479
- state: router.location.state,
2480
- hash,
2481
- href: "" + pathname + searchStr + hash,
2482
- key: dest.key
2483
- };
2484
- },
2485
- commitLocation: (next, replace) => {
2486
- const id = '' + Date.now() + Math.random();
2487
- if (router.navigateTimeout) clearTimeout(router.navigateTimeout);
2488
- let nextAction = 'replace';
2489
-
2490
- if (!replace) {
2491
- nextAction = 'push';
2492
- }
2493
-
2494
- const isSameUrl = router.__.parseLocation(history.location).href === next.href;
2495
-
2496
- if (isSameUrl && !next.key) {
2497
- nextAction = 'replace';
1786
+ return;
1787
+ });
1788
+ try {
1789
+ await Promise.all([componentsPromise, dataPromise]);
1790
+ if (latestPromise = checkLatest()) return await latestPromise;
1791
+ this.__store.setState(s => ({
1792
+ ...s,
1793
+ error: undefined,
1794
+ status: 'success',
1795
+ updatedAt: Date.now()
1796
+ }));
1797
+ } catch (err) {
1798
+ if (isRedirect(err)) {
1799
+ if (!opts?.preload) {
1800
+ this.router.navigate(err);
1801
+ }
1802
+ return;
2498
1803
  }
2499
-
2500
- if (nextAction === 'replace') {
2501
- history.replace({
2502
- pathname: next.pathname,
2503
- hash: next.hash,
2504
- search: next.searchStr
2505
- }, {
2506
- id
2507
- });
2508
- } else {
2509
- history.push({
2510
- pathname: next.pathname,
2511
- hash: next.hash,
2512
- search: next.searchStr
2513
- }, {
2514
- id
2515
- });
1804
+ const errorHandler = this.route.options.onLoadError ?? this.route.options.onError;
1805
+ try {
1806
+ errorHandler?.(err);
1807
+ } catch (errorHandlerErr) {
1808
+ if (isRedirect(errorHandlerErr)) {
1809
+ if (!opts?.preload) {
1810
+ this.router.navigate(errorHandlerErr);
1811
+ }
1812
+ return;
1813
+ }
1814
+ this.__store.setState(s => ({
1815
+ ...s,
1816
+ error: errorHandlerErr,
1817
+ status: 'error',
1818
+ updatedAt: Date.now()
1819
+ }));
1820
+ return;
2516
1821
  }
2517
-
2518
- router.navigationPromise = new Promise(resolve => {
2519
- const previousNavigationResolve = router.resolveNavigation;
2520
-
2521
- router.resolveNavigation = () => {
2522
- previousNavigationResolve();
2523
- resolve();
2524
- };
2525
- });
2526
- return router.navigationPromise;
1822
+ this.__store.setState(s => ({
1823
+ ...s,
1824
+ error: err,
1825
+ status: 'error',
1826
+ updatedAt: Date.now()
1827
+ }));
1828
+ } finally {
1829
+ delete this.__loadPromise;
2527
1830
  }
2528
- }
1831
+ });
1832
+ return this.__loadPromise;
2529
1833
  };
2530
- router.update(userOptions); // Allow frameworks to hook into the router creation
2531
-
2532
- router.options.createRouter == null ? void 0 : router.options.createRouter(router);
2533
- return router;
1834
+ #latestId = '';
2534
1835
  }
2535
1836
 
2536
- function isCtrlEvent(e) {
2537
- return !!(e.metaKey || e.altKey || e.ctrlKey || e.shiftKey);
1837
+ /**
1838
+ * react-store
1839
+ *
1840
+ * Copyright (c) TanStack
1841
+ *
1842
+ * This source code is licensed under the MIT license found in the
1843
+ * LICENSE.md file in the root directory of this source tree.
1844
+ *
1845
+ * @license MIT
1846
+ */
1847
+
1848
+ function useStore(store, selector = d => d, compareShallow) {
1849
+ const slice = withSelector.useSyncExternalStoreWithSelector(store.subscribe, () => store.state, () => store.state, selector, compareShallow ? shallow : undefined);
1850
+ return slice;
2538
1851
  }
2539
1852
 
2540
- const _excluded = ["type", "children", "target", "activeProps", "inactiveProps", "activeOptions", "disabled", "hash", "search", "params", "to", "preload", "preloadDelay", "preloadMaxAge", "replace", "style", "className", "onClick", "onFocus", "onMouseEnter", "onMouseLeave", "onTouchStart", "onTouchEnd"],
2541
- _excluded2 = ["pending", "caseSensitive", "children"],
2542
- _excluded3 = ["children", "router"];
2543
1853
  //
2544
- const matchesContext = /*#__PURE__*/React__namespace.createContext(null);
2545
- const routerContext = /*#__PURE__*/React__namespace.createContext(null); // Detect if we're in the DOM
2546
1854
 
2547
- const isDOM = Boolean(typeof window !== 'undefined' && window.document && window.document.createElement);
2548
- const useLayoutEffect = isDOM ? React__namespace.useLayoutEffect : React__namespace.useEffect;
2549
- function MatchesProvider(props) {
2550
- return /*#__PURE__*/React__namespace.createElement(matchesContext.Provider, props);
1855
+ function lazy(importer) {
1856
+ const lazyComp = /*#__PURE__*/React__namespace.lazy(importer);
1857
+ const finalComp = lazyComp;
1858
+ finalComp.preload = async () => {
1859
+ {
1860
+ await importer();
1861
+ }
1862
+ };
1863
+ return finalComp;
2551
1864
  }
1865
+ //
2552
1866
 
2553
- const useRouterSubscription = router => {
2554
- shim.useSyncExternalStore(cb => router.subscribe(() => cb()), () => router.state, () => router.state);
2555
- };
2556
-
2557
- function createReactRouter(opts) {
2558
- const makeRouteExt = (route, router) => {
1867
+ function useLinkProps(options) {
1868
+ const router = useRouterContext();
1869
+ const {
1870
+ // custom props
1871
+ type,
1872
+ children,
1873
+ target,
1874
+ activeProps = () => ({
1875
+ className: 'active'
1876
+ }),
1877
+ inactiveProps = () => ({}),
1878
+ activeOptions,
1879
+ disabled,
1880
+ // fromCurrent,
1881
+ hash,
1882
+ search,
1883
+ params,
1884
+ to = '.',
1885
+ preload,
1886
+ preloadDelay,
1887
+ replace,
1888
+ // element props
1889
+ style,
1890
+ className,
1891
+ onClick,
1892
+ onFocus,
1893
+ onMouseEnter,
1894
+ onMouseLeave,
1895
+ onTouchStart,
1896
+ ...rest
1897
+ } = options;
1898
+ const linkInfo = router.buildLink(options);
1899
+ if (linkInfo.type === 'external') {
1900
+ const {
1901
+ href
1902
+ } = linkInfo;
2559
1903
  return {
2560
- useRoute: function useRoute(subRouteId) {
2561
- if (subRouteId === void 0) {
2562
- subRouteId = '.';
2563
- }
2564
-
2565
- const resolvedRouteId = router.resolvePath(route.routeId, subRouteId);
2566
- const resolvedRoute = router.getRoute(resolvedRouteId);
2567
- useRouterSubscription(router);
2568
- invariant(resolvedRoute, "Could not find a route for route \"" + resolvedRouteId + "\"! Did you forget to add it to your route config?");
2569
- return resolvedRoute;
2570
- },
2571
- linkProps: options => {
2572
- var _functionalUpdate, _functionalUpdate2;
2573
-
2574
- const {
2575
- // custom props
2576
- target,
2577
- activeProps = () => ({
2578
- className: 'active'
2579
- }),
2580
- inactiveProps = () => ({}),
2581
- disabled,
2582
- // element props
2583
- style,
2584
- className,
2585
- onClick,
2586
- onFocus,
2587
- onMouseEnter,
2588
- onMouseLeave
2589
- } = options,
2590
- rest = _objectWithoutPropertiesLoose(options, _excluded);
2591
-
2592
- const linkInfo = route.buildLink(options);
2593
-
2594
- if (linkInfo.type === 'external') {
2595
- const {
2596
- href
2597
- } = linkInfo;
2598
- return {
2599
- href
2600
- };
2601
- }
2602
-
2603
- const {
2604
- handleClick,
2605
- handleFocus,
2606
- handleEnter,
2607
- handleLeave,
2608
- isActive,
2609
- next
2610
- } = linkInfo;
2611
-
2612
- const composeHandlers = handlers => e => {
2613
- e.persist();
2614
- handlers.forEach(handler => {
2615
- if (handler) handler(e);
2616
- });
2617
- }; // Get the active props
2618
-
2619
-
2620
- const resolvedActiveProps = isActive ? (_functionalUpdate = functionalUpdate(activeProps, {})) != null ? _functionalUpdate : {} : {}; // Get the inactive props
2621
-
2622
- const resolvedInactiveProps = isActive ? {} : (_functionalUpdate2 = functionalUpdate(inactiveProps, {})) != null ? _functionalUpdate2 : {};
2623
- return _extends$2({}, resolvedActiveProps, resolvedInactiveProps, rest, {
2624
- href: disabled ? undefined : next.href,
2625
- onClick: composeHandlers([handleClick, onClick]),
2626
- onFocus: composeHandlers([handleFocus, onFocus]),
2627
- onMouseEnter: composeHandlers([handleEnter, onMouseEnter]),
2628
- onMouseLeave: composeHandlers([handleLeave, onMouseLeave]),
2629
- target,
2630
- style: _extends$2({}, style, resolvedActiveProps.style, resolvedInactiveProps.style),
2631
- className: [className, resolvedActiveProps.className, resolvedInactiveProps.className].filter(Boolean).join(' ') || undefined
2632
- }, disabled ? {
2633
- role: 'link',
2634
- 'aria-disabled': true
2635
- } : undefined, {
2636
- ['data-status']: isActive ? 'active' : undefined
2637
- });
2638
- },
2639
- Link: /*#__PURE__*/React__namespace.forwardRef((props, ref) => {
2640
- const linkProps = route.linkProps(props);
2641
- useRouterSubscription(router);
2642
- return /*#__PURE__*/React__namespace.createElement("a", _extends$2({
2643
- ref: ref
2644
- }, linkProps, {
2645
- children: typeof props.children === 'function' ? props.children({
2646
- isActive: linkProps['data-status'] === 'active'
2647
- }) : props.children
2648
- }));
2649
- }),
2650
- MatchRoute: opts => {
2651
- const {
2652
- pending,
2653
- caseSensitive
2654
- } = opts,
2655
- rest = _objectWithoutPropertiesLoose(opts, _excluded2);
2656
-
2657
- const params = route.matchRoute(rest, {
2658
- pending,
2659
- caseSensitive
2660
- });
2661
-
2662
- if (!params) {
2663
- return null;
2664
- }
2665
-
2666
- return typeof opts.children === 'function' ? opts.children(params) : opts.children;
2667
- }
1904
+ href
2668
1905
  };
1906
+ }
1907
+ const {
1908
+ handleClick,
1909
+ handleFocus,
1910
+ handleEnter,
1911
+ handleLeave,
1912
+ handleTouchStart,
1913
+ isActive,
1914
+ next
1915
+ } = linkInfo;
1916
+ const reactHandleClick = e => {
1917
+ if (React__namespace.startTransition) {
1918
+ // This is a hack for react < 18
1919
+ React__namespace.startTransition(() => {
1920
+ handleClick(e);
1921
+ });
1922
+ } else {
1923
+ handleClick(e);
1924
+ }
1925
+ };
1926
+ const composeHandlers = handlers => e => {
1927
+ if (e.persist) e.persist();
1928
+ handlers.filter(Boolean).forEach(handler => {
1929
+ if (e.defaultPrevented) return;
1930
+ handler(e);
1931
+ });
2669
1932
  };
2670
1933
 
2671
- const coreRouter = createRouter(_extends$2({}, opts, {
2672
- createRouter: router => {
2673
- const routerExt = {
2674
- useState: () => {
2675
- useRouterSubscription(router);
2676
- return router.state;
2677
- },
2678
- useMatch: routeId => {
2679
- useRouterSubscription(router);
2680
- invariant(routeId !== rootRouteId, "\"" + rootRouteId + "\" cannot be used with useMatch! Did you mean to useRoute(\"" + rootRouteId + "\")?");
2681
-
2682
- const runtimeMatch = _useMatch();
2683
-
2684
- const match = router.state.matches.find(d => d.routeId === routeId);
2685
- invariant(match, "Could not find a match for route \"" + routeId + "\" being rendered in this component!");
2686
- invariant(runtimeMatch.routeId == (match == null ? void 0 : match.routeId), "useMatch('" + (match == null ? void 0 : match.routeId) + "') is being called in a component that is meant to render the '" + runtimeMatch.routeId + "' route. Did you mean to 'useRoute(" + (match == null ? void 0 : match.routeId) + ")' instead?");
2687
-
2688
- if (!match) {
2689
- invariant('Match not found!');
2690
- }
1934
+ // Get the active props
1935
+ const resolvedActiveProps = isActive ? functionalUpdate(activeProps, {}) ?? {} : {};
2691
1936
 
2692
- return match;
2693
- }
2694
- };
2695
- const routeExt = makeRouteExt(router.getRoute('/'), router);
2696
- Object.assign(router, routerExt, routeExt);
2697
- },
2698
- createRoute: _ref => {
2699
- let {
2700
- router,
2701
- route
2702
- } = _ref;
2703
- const routeExt = makeRouteExt(route, router);
2704
- Object.assign(route, routeExt);
1937
+ // Get the inactive props
1938
+ const resolvedInactiveProps = isActive ? {} : functionalUpdate(inactiveProps, {}) ?? {};
1939
+ return {
1940
+ ...resolvedActiveProps,
1941
+ ...resolvedInactiveProps,
1942
+ ...rest,
1943
+ href: disabled ? undefined : next.href,
1944
+ onClick: composeHandlers([onClick, reactHandleClick]),
1945
+ onFocus: composeHandlers([onFocus, handleFocus]),
1946
+ onMouseEnter: composeHandlers([onMouseEnter, handleEnter]),
1947
+ onMouseLeave: composeHandlers([onMouseLeave, handleLeave]),
1948
+ onTouchStart: composeHandlers([onTouchStart, handleTouchStart]),
1949
+ target,
1950
+ style: {
1951
+ ...style,
1952
+ ...resolvedActiveProps.style,
1953
+ ...resolvedInactiveProps.style
2705
1954
  },
2706
- createElement: async element => {
2707
- if (typeof element === 'function') {
2708
- const res = await element(); // Support direct import() calls
2709
-
2710
- if (typeof res === 'object' && res.default) {
2711
- return /*#__PURE__*/React__namespace.createElement(res.default);
2712
- } else {
2713
- return res;
1955
+ className: [className, resolvedActiveProps.className, resolvedInactiveProps.className].filter(Boolean).join(' ') || undefined,
1956
+ ...(disabled ? {
1957
+ role: 'link',
1958
+ 'aria-disabled': true
1959
+ } : undefined),
1960
+ ['data-status']: isActive ? 'active' : undefined
1961
+ };
1962
+ }
1963
+ const Link = /*#__PURE__*/React__namespace.forwardRef((props, ref) => {
1964
+ const linkProps = useLinkProps(props);
1965
+ return /*#__PURE__*/React__namespace.createElement("a", _extends({
1966
+ ref: ref
1967
+ }, linkProps, {
1968
+ children: typeof props.children === 'function' ? props.children({
1969
+ isActive: linkProps['data-status'] === 'active'
1970
+ }) : props.children
1971
+ }));
1972
+ });
1973
+ function Navigate(props) {
1974
+ const router = useRouterContext();
1975
+ React__namespace.useLayoutEffect(() => {
1976
+ router.navigate(props);
1977
+ }, []);
1978
+ return null;
1979
+ }
1980
+ const matchesContext = /*#__PURE__*/React__namespace.createContext(null);
1981
+ const routerContext = /*#__PURE__*/React__namespace.createContext(null);
1982
+ class ReactRouter extends Router {
1983
+ constructor(opts) {
1984
+ super({
1985
+ ...opts,
1986
+ loadComponent: async component => {
1987
+ if (component.preload) {
1988
+ await component.preload();
2714
1989
  }
1990
+ return component;
2715
1991
  }
2716
-
2717
- return element;
2718
- }
2719
- }));
2720
- return coreRouter;
1992
+ });
1993
+ }
2721
1994
  }
2722
- function RouterProvider(_ref2) {
2723
- let {
2724
- children,
2725
- router
2726
- } = _ref2,
2727
- rest = _objectWithoutPropertiesLoose(_ref2, _excluded3);
2728
-
1995
+ function RouterProvider({
1996
+ router,
1997
+ ...rest
1998
+ }) {
2729
1999
  router.update(rest);
2730
- useRouterSubscription(router);
2731
- useLayoutEffect(() => {
2732
- return router.mount();
2733
- }, [router]);
2000
+ const currentMatches = useStore(router.__store, s => s.currentMatches);
2001
+ React__namespace.useEffect(router.mount, [router]);
2734
2002
  return /*#__PURE__*/React__namespace.createElement(routerContext.Provider, {
2735
2003
  value: {
2736
- router
2004
+ router: router
2005
+ }
2006
+ }, /*#__PURE__*/React__namespace.createElement(matchesContext.Provider, {
2007
+ value: [undefined, ...currentMatches]
2008
+ }, /*#__PURE__*/React__namespace.createElement(CatchBoundary, {
2009
+ errorComponent: ErrorComponent,
2010
+ onCatch: () => {
2011
+ warning(false, `Error in router! Consider setting an 'errorComponent' in your RootRoute! 👍`);
2737
2012
  }
2738
- }, /*#__PURE__*/React__namespace.createElement(MatchesProvider, {
2739
- value: router.state.matches
2740
- }, children != null ? children : /*#__PURE__*/React__namespace.createElement(Outlet, null)));
2013
+ }, /*#__PURE__*/React__namespace.createElement(Outlet, null))));
2741
2014
  }
2742
-
2743
- function useRouter() {
2015
+ function useRouterContext() {
2744
2016
  const value = React__namespace.useContext(routerContext);
2745
- warning(!value, 'useRouter must be used inside a <Router> component!');
2746
- useRouterSubscription(value.router);
2017
+ warning(value, 'useRouter must be used inside a <Router> component!');
2018
+ useStore(value.router.__store);
2747
2019
  return value.router;
2748
2020
  }
2749
-
2021
+ function useRouter(track, shallow) {
2022
+ const router = useRouterContext();
2023
+ useStore(router.__store, track, shallow);
2024
+ return router;
2025
+ }
2750
2026
  function useMatches() {
2751
2027
  return React__namespace.useContext(matchesContext);
2752
- } // function useParentMatches(): RouteMatch[] {
2753
- // const router = useRouter()
2754
- // const match = useMatch()
2755
- // const matches = router.state.matches
2756
- // return matches.slice(
2757
- // 0,
2758
- // matches.findIndex((d) => d.matchId === match.matchId) - 1,
2759
- // )
2760
- // }
2761
-
2762
-
2763
- function _useMatch() {
2764
- var _useMatches;
2765
-
2766
- return (_useMatches = useMatches()) == null ? void 0 : _useMatches[0];
2767
2028
  }
2768
-
2029
+ function useMatch(opts) {
2030
+ const router = useRouterContext();
2031
+ const nearestMatch = useMatches()[0];
2032
+ const match = opts?.from ? router.state.currentMatches.find(d => d.route.id === opts?.from) : nearestMatch;
2033
+ invariant(match, `Could not find ${opts?.from ? `an active match from "${opts.from}"` : 'a nearest match!'}`);
2034
+ if (opts?.strict ?? true) {
2035
+ invariant(nearestMatch.route.id == match?.route.id, `useMatch("${match?.route.id}") is being called in a component that is meant to render the '${nearestMatch.route.id}' route. Did you mean to 'useMatch("${match?.route.id}", { strict: false })' or 'useRoute("${match?.route.id}")' instead?`);
2036
+ }
2037
+ useStore(match.__store, d => opts?.track?.(match) ?? match, opts?.shallow);
2038
+ return match;
2039
+ }
2040
+ function useRoute(routeId) {
2041
+ const router = useRouterContext();
2042
+ const resolvedRoute = router.getRoute(routeId);
2043
+ invariant(resolvedRoute, `Could not find a route for route "${routeId}"! Did you forget to add it to your route?`);
2044
+ return resolvedRoute;
2045
+ }
2046
+ function useSearch(opts) {
2047
+ const {
2048
+ track,
2049
+ ...matchOpts
2050
+ } = opts;
2051
+ const match = useMatch(matchOpts);
2052
+ useStore(match.__store, d => opts?.track?.(d.search) ?? d.search, true);
2053
+ return match.state.search;
2054
+ }
2055
+ function useParams(opts) {
2056
+ const router = useRouterContext();
2057
+ useStore(router.__store, d => {
2058
+ const params = last(d.currentMatches)?.params;
2059
+ return opts?.track?.(params) ?? params;
2060
+ }, true);
2061
+ return last(router.state.currentMatches)?.params;
2062
+ }
2063
+ function useNavigate(defaultOpts) {
2064
+ const router = useRouterContext();
2065
+ return React__namespace.useCallback(opts => {
2066
+ return router.navigate({
2067
+ ...defaultOpts,
2068
+ ...opts
2069
+ });
2070
+ }, []);
2071
+ }
2072
+ function useMatchRoute() {
2073
+ const router = useRouterContext();
2074
+ return React__namespace.useCallback(opts => {
2075
+ const {
2076
+ pending,
2077
+ caseSensitive,
2078
+ ...rest
2079
+ } = opts;
2080
+ return router.matchRoute(rest, {
2081
+ pending,
2082
+ caseSensitive
2083
+ });
2084
+ }, []);
2085
+ }
2086
+ function MatchRoute(props) {
2087
+ const matchRoute = useMatchRoute();
2088
+ const params = matchRoute(props);
2089
+ if (!params) {
2090
+ return null;
2091
+ }
2092
+ if (typeof props.children === 'function') {
2093
+ return props.children(params);
2094
+ }
2095
+ return params ? props.children : null;
2096
+ }
2769
2097
  function Outlet() {
2770
- var _childMatch$options$c;
2771
-
2772
- const router = useRouter();
2773
- const [, ...matches] = useMatches();
2774
- const childMatch = matches[0];
2775
- if (!childMatch) return null;
2776
-
2777
- const element = (() => {
2778
- var _childMatch$__$errorE, _ref4;
2779
-
2780
- if (!childMatch) {
2781
- return null;
2782
- }
2783
-
2784
- const errorElement = (_childMatch$__$errorE = childMatch.__.errorElement) != null ? _childMatch$__$errorE : router.options.defaultErrorElement;
2785
-
2786
- if (childMatch.status === 'error') {
2787
- if (errorElement) {
2788
- return errorElement;
2789
- }
2790
-
2791
- if (childMatch.options.useErrorBoundary || router.options.useErrorBoundary) {
2792
- throw childMatch.error;
2793
- }
2794
-
2795
- return /*#__PURE__*/React__namespace.createElement(DefaultErrorBoundary, {
2796
- error: childMatch.error
2797
- });
2798
- }
2799
-
2800
- if (childMatch.status === 'loading' || childMatch.status === 'idle') {
2801
- if (childMatch.isPending) {
2802
- var _childMatch$__$pendin;
2803
-
2804
- const pendingElement = (_childMatch$__$pendin = childMatch.__.pendingElement) != null ? _childMatch$__$pendin : router.options.defaultPendingElement;
2805
-
2806
- if (childMatch.options.pendingMs || pendingElement) {
2807
- var _ref3;
2808
-
2809
- return (_ref3 = pendingElement) != null ? _ref3 : null;
2810
- }
2811
- }
2812
-
2813
- return null;
2098
+ const matches = useMatches().slice(1);
2099
+ const match = matches[0];
2100
+ if (!match) {
2101
+ return null;
2102
+ }
2103
+ return /*#__PURE__*/React__namespace.createElement(SubOutlet, {
2104
+ matches: matches,
2105
+ match: match
2106
+ });
2107
+ }
2108
+ function SubOutlet({
2109
+ matches,
2110
+ match
2111
+ }) {
2112
+ const router = useRouterContext();
2113
+ useStore(match.__store, store => [store.status, store.error], true);
2114
+ const defaultPending = React__namespace.useCallback(() => null, []);
2115
+ const PendingComponent = match.pendingComponent ?? router.options.defaultPendingComponent ?? defaultPending;
2116
+ const errorComponent = match.errorComponent ?? router.options.defaultErrorComponent;
2117
+ const ResolvedSuspenseBoundary = match.route.options.wrapInSuspense ?? true ? React__namespace.Suspense : SafeFragment;
2118
+ const ResolvedCatchBoundary = errorComponent ? CatchBoundary : SafeFragment;
2119
+ return /*#__PURE__*/React__namespace.createElement(matchesContext.Provider, {
2120
+ value: matches
2121
+ }, /*#__PURE__*/React__namespace.createElement(ResolvedSuspenseBoundary, {
2122
+ fallback: /*#__PURE__*/React__namespace.createElement(PendingComponent, null)
2123
+ }, /*#__PURE__*/React__namespace.createElement(ResolvedCatchBoundary, {
2124
+ key: match.route.id,
2125
+ errorComponent: errorComponent,
2126
+ onCatch: () => {
2127
+ warning(false, `Error in route match: ${match.id}`);
2814
2128
  }
2815
-
2816
- return (_ref4 = childMatch.__.element) != null ? _ref4 : router.options.defaultElement;
2817
- })();
2818
-
2819
- const catchElement = (_childMatch$options$c = childMatch == null ? void 0 : childMatch.options.catchElement) != null ? _childMatch$options$c : router.options.defaultCatchElement;
2820
- return /*#__PURE__*/React__namespace.createElement(MatchesProvider, {
2821
- value: matches,
2822
- key: childMatch.matchId
2823
- }, /*#__PURE__*/React__namespace.createElement(CatchBoundary, {
2824
- catchElement: catchElement
2825
- }, element));
2129
+ }, /*#__PURE__*/React__namespace.createElement(Inner, {
2130
+ match: match
2131
+ }))));
2826
2132
  }
2827
-
2828
- class CatchBoundary extends React__namespace.Component {
2829
- constructor() {
2830
- super(...arguments);
2831
- this.state = {
2832
- error: false
2833
- };
2133
+ function Inner(props) {
2134
+ const router = useRouterContext();
2135
+ if (props.match.state.status === 'error') {
2136
+ throw props.match.state.error;
2137
+ }
2138
+ if (props.match.state.status === 'success') {
2139
+ return /*#__PURE__*/React__namespace.createElement(props.match.component ?? router.options.defaultComponent ?? Outlet);
2834
2140
  }
2141
+ if (props.match.state.status === 'pending') {
2142
+ throw props.match.__loadPromise;
2143
+ }
2144
+ invariant(false, 'Idle routeMatch status encountered during rendering! You should never see this. File an issue!');
2145
+ }
2146
+ function SafeFragment(props) {
2147
+ return /*#__PURE__*/React__namespace.createElement(React__namespace.Fragment, null, props.children);
2148
+ }
2149
+
2150
+ // This is the messiest thing ever... I'm either seriously tired (likely) or
2151
+ // there has to be a better way to reset error boundaries when the
2152
+ // router's location key changes.
2835
2153
 
2154
+ class CatchBoundary extends React__namespace.Component {
2155
+ state = {
2156
+ error: false,
2157
+ info: undefined
2158
+ };
2836
2159
  componentDidCatch(error, info) {
2160
+ this.props.onCatch(error, info);
2837
2161
  console.error(error);
2838
2162
  this.setState({
2839
2163
  error,
2840
2164
  info
2841
2165
  });
2842
2166
  }
2843
-
2844
2167
  render() {
2845
- var _this$props$catchElem;
2846
-
2847
- const catchElement = (_this$props$catchElem = this.props.catchElement) != null ? _this$props$catchElem : DefaultErrorBoundary;
2848
-
2849
- if (this.state.error) {
2850
- return typeof catchElement === 'function' ? catchElement(this.state) : catchElement;
2168
+ return /*#__PURE__*/React__namespace.createElement(CatchBoundaryInner, _extends({}, this.props, {
2169
+ errorState: this.state,
2170
+ reset: () => this.setState({})
2171
+ }));
2172
+ }
2173
+ }
2174
+ function CatchBoundaryInner(props) {
2175
+ const [activeErrorState, setActiveErrorState] = React__namespace.useState(props.errorState);
2176
+ const router = useRouterContext();
2177
+ const errorComponent = props.errorComponent ?? ErrorComponent;
2178
+ const prevKeyRef = React__namespace.useRef('');
2179
+ React__namespace.useEffect(() => {
2180
+ if (activeErrorState) {
2181
+ if (router.state.currentLocation.key !== prevKeyRef.current) {
2182
+ setActiveErrorState({});
2183
+ }
2851
2184
  }
2852
-
2853
- return this.props.children;
2185
+ prevKeyRef.current = router.state.currentLocation.key;
2186
+ }, [activeErrorState, router.state.currentLocation.key]);
2187
+ React__namespace.useEffect(() => {
2188
+ if (props.errorState.error) {
2189
+ setActiveErrorState(props.errorState);
2190
+ }
2191
+ // props.reset()
2192
+ }, [props.errorState.error]);
2193
+ if (props.errorState.error && activeErrorState.error) {
2194
+ return /*#__PURE__*/React__namespace.createElement(errorComponent, activeErrorState);
2854
2195
  }
2855
-
2196
+ return props.children;
2856
2197
  }
2857
-
2858
- function DefaultErrorBoundary(_ref5) {
2859
- let {
2860
- error
2861
- } = _ref5;
2198
+ function ErrorComponent({
2199
+ error
2200
+ }) {
2862
2201
  return /*#__PURE__*/React__namespace.createElement("div", {
2863
2202
  style: {
2864
2203
  padding: '.5rem',
@@ -2872,89 +2211,98 @@
2872
2211
  style: {
2873
2212
  height: '.5rem'
2874
2213
  }
2875
- }), /*#__PURE__*/React__namespace.createElement("div", null, /*#__PURE__*/React__namespace.createElement("pre", null, error.message ? /*#__PURE__*/React__namespace.createElement("code", {
2214
+ }), /*#__PURE__*/React__namespace.createElement("div", null, /*#__PURE__*/React__namespace.createElement("pre", {
2876
2215
  style: {
2877
2216
  fontSize: '.7em',
2878
2217
  border: '1px solid red',
2879
2218
  borderRadius: '.25rem',
2880
2219
  padding: '.5rem',
2881
- color: 'red'
2882
- }
2883
- }, error.message) : null)), /*#__PURE__*/React__namespace.createElement("div", {
2884
- style: {
2885
- height: '1rem'
2886
- }
2887
- }), /*#__PURE__*/React__namespace.createElement("div", {
2888
- style: {
2889
- fontSize: '.8em',
2890
- borderLeft: '3px solid rgba(127, 127, 127, 1)',
2891
- paddingLeft: '.5rem',
2892
- opacity: 0.5
2220
+ color: 'red',
2221
+ overflow: 'auto'
2893
2222
  }
2894
- }, "If you are the owner of this website, it's highly recommended that you configure your own custom Catch/Error boundaries for the router. You can optionally configure a boundary for each route."));
2223
+ }, error.message ? /*#__PURE__*/React__namespace.createElement("code", null, error.message) : null)));
2895
2224
  }
2896
- function usePrompt(message, when) {
2225
+ function useBlocker(message, condition = true) {
2897
2226
  const router = useRouter();
2898
2227
  React__namespace.useEffect(() => {
2899
- if (!when) return;
2900
- let unblock = router.history.block(transition => {
2228
+ if (!condition) return;
2229
+ let unblock = router.history.block((retry, cancel) => {
2901
2230
  if (window.confirm(message)) {
2902
2231
  unblock();
2903
- transition.retry();
2232
+ retry();
2904
2233
  } else {
2905
- router.location.pathname = window.location.pathname;
2234
+ cancel();
2906
2235
  }
2907
2236
  });
2908
2237
  return unblock;
2909
- }, [when, location, message]);
2238
+ });
2910
2239
  }
2911
- function Prompt(_ref6) {
2912
- let {
2913
- message,
2914
- when,
2915
- children
2916
- } = _ref6;
2917
- usePrompt(message, when != null ? when : true);
2918
- return children != null ? children : null;
2240
+ function Block({
2241
+ message,
2242
+ condition,
2243
+ children
2244
+ }) {
2245
+ useBlocker(message, condition);
2246
+ return children ?? null;
2919
2247
  }
2920
2248
 
2921
- exports.DefaultErrorBoundary = DefaultErrorBoundary;
2922
- exports.MatchesProvider = MatchesProvider;
2249
+ exports.Block = Block;
2250
+ exports.ErrorComponent = ErrorComponent;
2251
+ exports.Link = Link;
2252
+ exports.MatchRoute = MatchRoute;
2253
+ exports.Navigate = Navigate;
2923
2254
  exports.Outlet = Outlet;
2924
- exports.Prompt = Prompt;
2255
+ exports.ReactRouter = ReactRouter;
2256
+ exports.RootRoute = RootRoute;
2257
+ exports.Route = Route;
2258
+ exports.RouteMatch = RouteMatch;
2259
+ exports.Router = Router;
2925
2260
  exports.RouterProvider = RouterProvider;
2926
- exports.cascadeLoaderData = cascadeLoaderData;
2927
2261
  exports.cleanPath = cleanPath;
2928
2262
  exports.createBrowserHistory = createBrowserHistory;
2929
2263
  exports.createHashHistory = createHashHistory;
2930
2264
  exports.createMemoryHistory = createMemoryHistory;
2931
- exports.createReactRouter = createReactRouter;
2932
- exports.createRoute = createRoute;
2933
- exports.createRouteConfig = createRouteConfig;
2934
- exports.createRouteMatch = createRouteMatch;
2935
- exports.createRouter = createRouter;
2936
2265
  exports.decode = decode;
2266
+ exports.defaultFetchServerDataFn = defaultFetchServerDataFn;
2937
2267
  exports.defaultParseSearch = defaultParseSearch;
2938
2268
  exports.defaultStringifySearch = defaultStringifySearch;
2939
2269
  exports.encode = encode;
2940
2270
  exports.functionalUpdate = functionalUpdate;
2941
2271
  exports.interpolatePath = interpolatePath;
2942
2272
  exports.invariant = invariant;
2273
+ exports.isPlainObject = isPlainObject;
2274
+ exports.isRedirect = isRedirect;
2943
2275
  exports.joinPaths = joinPaths;
2944
2276
  exports.last = last;
2277
+ exports.lazy = lazy;
2945
2278
  exports.matchByPath = matchByPath;
2946
2279
  exports.matchPathname = matchPathname;
2280
+ exports.matchesContext = matchesContext;
2947
2281
  exports.parsePathname = parsePathname;
2948
2282
  exports.parseSearchWith = parseSearchWith;
2283
+ exports.partialDeepEqual = partialDeepEqual;
2949
2284
  exports.pick = pick;
2285
+ exports.redirect = redirect;
2950
2286
  exports.replaceEqualDeep = replaceEqualDeep;
2951
2287
  exports.resolvePath = resolvePath;
2952
2288
  exports.rootRouteId = rootRouteId;
2289
+ exports.routerContext = routerContext;
2953
2290
  exports.stringifySearchWith = stringifySearchWith;
2954
2291
  exports.trimPath = trimPath;
2955
2292
  exports.trimPathLeft = trimPathLeft;
2956
2293
  exports.trimPathRight = trimPathRight;
2957
- exports.usePrompt = usePrompt;
2294
+ exports.useBlocker = useBlocker;
2295
+ exports.useLinkProps = useLinkProps;
2296
+ exports.useMatch = useMatch;
2297
+ exports.useMatchRoute = useMatchRoute;
2298
+ exports.useMatches = useMatches;
2299
+ exports.useNavigate = useNavigate;
2300
+ exports.useParams = useParams;
2301
+ exports.useRoute = useRoute;
2302
+ exports.useRouter = useRouter;
2303
+ exports.useRouterContext = useRouterContext;
2304
+ exports.useSearch = useSearch;
2305
+ exports.useStore = useStore;
2958
2306
  exports.warning = warning;
2959
2307
 
2960
2308
  Object.defineProperty(exports, '__esModule', { value: true });