@tinkoff/router 0.2.7 → 0.2.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (60) hide show
  1. package/lib/components/react/context.browser.js +7 -0
  2. package/lib/components/react/context.es.js +7 -0
  3. package/lib/components/react/context.js +13 -0
  4. package/lib/components/react/provider.browser.js +12 -0
  5. package/lib/components/react/provider.es.js +12 -0
  6. package/lib/components/react/provider.js +16 -0
  7. package/lib/components/react/useNavigate.browser.js +17 -0
  8. package/lib/components/react/useNavigate.es.js +17 -0
  9. package/lib/components/react/useNavigate.js +21 -0
  10. package/lib/components/react/useRoute.browser.js +8 -0
  11. package/lib/components/react/useRoute.es.js +8 -0
  12. package/lib/components/react/useRoute.js +12 -0
  13. package/lib/components/react/useRouter.browser.js +8 -0
  14. package/lib/components/react/useRouter.es.js +8 -0
  15. package/lib/components/react/useRouter.js +12 -0
  16. package/lib/components/react/useUrl.browser.js +8 -0
  17. package/lib/components/react/useUrl.es.js +8 -0
  18. package/lib/components/react/useUrl.js +12 -0
  19. package/lib/history/base.browser.js +11 -0
  20. package/lib/history/base.es.js +11 -0
  21. package/lib/history/base.js +15 -0
  22. package/lib/history/client.browser.js +121 -0
  23. package/lib/history/client.es.js +121 -0
  24. package/lib/history/client.js +125 -0
  25. package/lib/history/server.es.js +15 -0
  26. package/lib/history/server.js +19 -0
  27. package/lib/history/wrapper.browser.js +72 -0
  28. package/lib/history/wrapper.es.js +72 -0
  29. package/lib/history/wrapper.js +80 -0
  30. package/lib/index.browser.js +12 -1169
  31. package/lib/index.es.js +12 -1097
  32. package/lib/index.js +36 -1124
  33. package/lib/logger.browser.js +15 -0
  34. package/lib/logger.es.js +15 -0
  35. package/lib/logger.js +23 -0
  36. package/lib/router/abstract.browser.js +395 -0
  37. package/lib/router/abstract.es.js +395 -0
  38. package/lib/router/abstract.js +404 -0
  39. package/lib/router/browser.browser.js +166 -0
  40. package/lib/router/client.browser.js +116 -0
  41. package/lib/router/client.es.js +116 -0
  42. package/lib/router/client.js +120 -0
  43. package/lib/router/clientNoSpa.browser.js +17 -0
  44. package/lib/router/clientNoSpa.es.js +17 -0
  45. package/lib/router/clientNoSpa.js +21 -0
  46. package/lib/router/server.es.js +85 -0
  47. package/lib/router/server.js +89 -0
  48. package/lib/tree/constants.browser.js +6 -0
  49. package/lib/tree/constants.es.js +6 -0
  50. package/lib/tree/constants.js +13 -0
  51. package/lib/tree/tree.browser.js +148 -0
  52. package/lib/tree/tree.es.js +148 -0
  53. package/lib/tree/tree.js +158 -0
  54. package/lib/tree/utils.browser.js +77 -0
  55. package/lib/tree/utils.es.js +77 -0
  56. package/lib/tree/utils.js +90 -0
  57. package/lib/utils.browser.js +35 -0
  58. package/lib/utils.es.js +35 -0
  59. package/lib/utils.js +48 -0
  60. package/package.json +5 -6
package/lib/index.js CHANGED
@@ -2,1127 +2,39 @@
2
2
 
3
3
  Object.defineProperty(exports, '__esModule', { value: true });
4
4
 
5
- var url = require('@tinkoff/url');
6
- var isString = require('@tinkoff/utils/is/string');
7
- var isObject = require('@tinkoff/utils/is/object');
8
- var map = require('@tinkoff/utils/array/map');
9
- var T = require('@tinkoff/utils/function/T');
10
- var noop = require('@tinkoff/utils/function/noop');
11
- var each = require('@tinkoff/utils/array/each');
12
- var find = require('@tinkoff/utils/array/find');
13
- var findIndex = require('@tinkoff/utils/array/findIndex');
14
- var jsxRuntime = require('react/jsx-runtime');
15
- var shim = require('use-sync-external-store/shim');
16
- var react = require('react');
17
- var reactHooks = require('@tinkoff/react-hooks');
18
-
19
- function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
20
-
21
- var isString__default = /*#__PURE__*/_interopDefaultLegacy(isString);
22
- var isObject__default = /*#__PURE__*/_interopDefaultLegacy(isObject);
23
- var map__default = /*#__PURE__*/_interopDefaultLegacy(map);
24
- var T__default = /*#__PURE__*/_interopDefaultLegacy(T);
25
- var noop__default = /*#__PURE__*/_interopDefaultLegacy(noop);
26
- var each__default = /*#__PURE__*/_interopDefaultLegacy(each);
27
- var find__default = /*#__PURE__*/_interopDefaultLegacy(find);
28
- var findIndex__default = /*#__PURE__*/_interopDefaultLegacy(findIndex);
29
-
30
- const PARAMETER_DELIMITER = ':';
31
- const WILDCARD_REGEXP = /\*/;
32
- const HISTORY_FALLBACK_REGEXP = /<history-fallback>/;
33
- const PARAM_PARSER_REGEXP = /([^(?]+)(?:\((.+)\))?(\?)?/;
34
-
35
- const isFilePath = (pathname) => {
36
- return /\/.+\.[^/]+$/.test(pathname);
37
- };
38
- const normalizeTrailingSlash = (pathname, trailingSlash = false) => {
39
- const hasTrailingSlash = pathname.endsWith('/');
40
- if (trailingSlash) {
41
- return hasTrailingSlash || isFilePath(pathname) ? pathname : `${pathname}/`;
42
- }
43
- return pathname.length > 1 && hasTrailingSlash ? pathname.slice(0, -1) : pathname;
44
- };
45
- const normalizeManySlashes = (hrefOrPath) => {
46
- const [href, ...search] = hrefOrPath.split('?');
47
- return [href.replace(/\/+/g, '/').replace(/^(\w+):\//, '$1://'), ...search].join('?');
48
- };
49
- const isSameHost = typeof window === 'undefined'
50
- ? T__default["default"]
51
- : (url) => {
52
- return !url.host || url.host === window.location.host;
53
- };
54
- const makeNavigateOptions = (options) => {
55
- if (typeof options === 'string') {
56
- return { url: options };
57
- }
58
- return options;
59
- };
60
- const registerHook = (hooksSet, hook) => {
61
- hooksSet.add(hook);
62
- return () => {
63
- hooksSet.delete(hook);
64
- };
65
- };
66
-
67
- const getParts = (pathname) => pathname
68
- .split('/')
69
- .slice(pathname.startsWith('/') ? 1 : 0, pathname.endsWith('/') ? -1 : Infinity);
70
- const isHistoryFallback = (part) => {
71
- return HISTORY_FALLBACK_REGEXP.test(part);
72
- };
73
- const isWildcard = (part) => {
74
- return WILDCARD_REGEXP.test(part);
75
- };
76
- const isParameterized = (part) => {
77
- return part.includes(PARAMETER_DELIMITER);
78
- };
79
- const parseParameter = (part) => {
80
- const [prefix = '', param, postfix = ''] = part.split(PARAMETER_DELIMITER);
81
- const match = PARAM_PARSER_REGEXP.exec(param);
82
- if (!match) {
83
- throw new Error('parameters should satisfy pattern "prefix:paramName(regexp)\\?:postfix"');
84
- }
85
- const [, paramName, regexp, optional] = match;
86
- const useRegexp = prefix || postfix || regexp;
87
- return {
88
- type: 3 /* PartType.parameter */,
89
- paramName,
90
- regexp: useRegexp
91
- ? new RegExp(`^${prefix}(${regexp || '.+'})${optional ? '?' : ''}${postfix}$`)
92
- : undefined,
93
- optional: !!optional && !prefix && !postfix,
94
- };
95
- };
96
- const parse = (part) => {
97
- if (isHistoryFallback(part)) {
98
- return { type: 1 /* PartType.historyFallback */ };
99
- }
100
- if (isWildcard(part)) {
101
- return { type: 2 /* PartType.wildcard */ };
102
- }
103
- if (isParameterized(part)) {
104
- return parseParameter(part);
105
- }
106
- return { type: 0 /* PartType.literal */, value: part };
107
- };
108
- const makePath = (pathname, params) => {
109
- const parts = getParts(pathname);
110
- const result = map__default["default"]((part) => {
111
- var _a;
112
- if (isHistoryFallback(part) || isWildcard(part)) {
113
- throw new Error(`Pathname should be only a string with dynamic parameters, not a special string, got ${pathname}`);
114
- }
115
- if (isParameterized(part)) {
116
- const [prefix = '', param = '', postfix = ''] = part.split(PARAMETER_DELIMITER);
117
- const match = PARAM_PARSER_REGEXP.exec(param);
118
- if (!match) {
119
- throw new Error('parameters should satisfy pattern "prefix:paramName(regexp)\\?:postfix"');
120
- }
121
- const [, paramName, regexp, optional] = match;
122
- const value = (_a = params[paramName]) === null || _a === void 0 ? void 0 : _a.toString();
123
- if (optional && !value) {
124
- return '';
125
- }
126
- if (!value) {
127
- throw new Error(`value for parameter for ${paramName} should be defined in params`);
128
- }
129
- if (regexp && !new RegExp(regexp).test(value)) {
130
- throw new Error(`passed parameter for ${paramName} should satisfy regxep: ${regexp}, got: ${value}`);
131
- }
132
- return prefix + value + postfix || part;
133
- }
134
- return part;
135
- }, parts).join('/');
136
- return normalizeTrailingSlash(`/${result}`, pathname.endsWith('/'));
137
- };
138
-
139
- // eslint-disable-next-line import/no-mutable-exports
140
- exports.logger = {
141
- trace: noop__default["default"],
142
- debug: noop__default["default"],
143
- info: noop__default["default"],
144
- warn: noop__default["default"],
145
- error: noop__default["default"],
146
- };
147
- const setLogger = (newLogger) => {
148
- exports.logger = newLogger;
149
- };
150
-
151
- class AbstractRouter {
152
- constructor({ trailingSlash, mergeSlashes, beforeResolve = [], beforeNavigate = [], afterNavigate = [], beforeUpdateCurrent = [], afterUpdateCurrent = [], guards = [], onChange = [], onRedirect, onNotFound, onBlock, }) {
153
- this.started = false;
154
- this.trailingSlash = false;
155
- this.strictTrailingSlash = true;
156
- this.mergeSlashes = false;
157
- this.trailingSlash = trailingSlash !== null && trailingSlash !== void 0 ? trailingSlash : false;
158
- this.strictTrailingSlash = typeof trailingSlash === 'undefined';
159
- this.mergeSlashes = mergeSlashes !== null && mergeSlashes !== void 0 ? mergeSlashes : false;
160
- this.hooks = new Map([
161
- ['beforeResolve', new Set(beforeResolve)],
162
- ['beforeNavigate', new Set(beforeNavigate)],
163
- ['afterNavigate', new Set(afterNavigate)],
164
- ['beforeUpdateCurrent', new Set(beforeUpdateCurrent)],
165
- ['afterUpdateCurrent', new Set(afterUpdateCurrent)],
166
- ]);
167
- this.guards = new Set(guards);
168
- this.syncHooks = new Map([['change', new Set(onChange)]]);
169
- this.onRedirect = onRedirect;
170
- this.onNotFound = onNotFound;
171
- this.onBlock = onBlock;
172
- }
173
- // start is using as marker that any preparation for proper work has done in the app
174
- // and now router can manage any navigations
175
- async start() {
176
- exports.logger.debug({
177
- event: 'start',
178
- });
179
- this.started = true;
180
- }
181
- getCurrentRoute() {
182
- var _a, _b, _c;
183
- // when something will try to get currentRoute while navigating, it will get route which router currently navigating
184
- // in case some handler supposed to load data of route or similar
185
- return (_b = (_a = this.currentNavigation) === null || _a === void 0 ? void 0 : _a.to) !== null && _b !== void 0 ? _b : (_c = this.lastNavigation) === null || _c === void 0 ? void 0 : _c.to;
186
- }
187
- getCurrentUrl() {
188
- var _a, _b, _c;
189
- // same as getCurrentRoute
190
- return (_b = (_a = this.currentNavigation) === null || _a === void 0 ? void 0 : _a.url) !== null && _b !== void 0 ? _b : (_c = this.lastNavigation) === null || _c === void 0 ? void 0 : _c.url;
191
- }
192
- getLastRoute() {
193
- var _a;
194
- return (_a = this.lastNavigation) === null || _a === void 0 ? void 0 : _a.to;
195
- }
196
- getLastUrl() {
197
- var _a;
198
- return (_a = this.lastNavigation) === null || _a === void 0 ? void 0 : _a.url;
199
- }
200
- commitNavigation(navigation) {
201
- exports.logger.debug({
202
- event: 'commit-navigation',
203
- navigation,
204
- });
205
- if (!navigation.history) {
206
- // in case we came from history do not history back to prevent infinity recursive calls
207
- this.history.save(navigation);
208
- }
209
- this.lastNavigation = navigation;
210
- this.currentNavigation = null;
211
- this.runSyncHooks('change', navigation);
212
- }
213
- async updateCurrentRoute(updateRouteOptions) {
214
- return this.internalUpdateCurrentRoute(updateRouteOptions, {});
215
- }
216
- async internalUpdateCurrentRoute(updateRouteOptions, { history }) {
217
- var _a;
218
- const prevNavigation = (_a = this.currentNavigation) !== null && _a !== void 0 ? _a : this.lastNavigation;
219
- if (!prevNavigation) {
220
- throw new Error('updateCurrentRoute should only be called after navigate to some route');
221
- }
222
- const { replace, params, navigateState } = updateRouteOptions;
223
- const { to: from, url: fromUrl } = prevNavigation;
224
- const navigation = {
225
- type: 'updateCurrentRoute',
226
- from,
227
- to: this.resolveRoute({ params, navigateState }, { wildcard: true }),
228
- url: this.resolveUrl(updateRouteOptions),
229
- fromUrl,
230
- replace,
231
- history,
232
- navigateState,
233
- code: updateRouteOptions.code,
234
- };
235
- exports.logger.debug({
236
- event: 'update-current-route',
237
- updateRouteOptions,
238
- navigation,
239
- });
240
- await this.run(navigation);
241
- }
242
- async runUpdateCurrentRoute(navigation) {
243
- await this.runHooks('beforeUpdateCurrent', navigation);
244
- this.commitNavigation(navigation);
245
- await this.runHooks('afterUpdateCurrent', navigation);
246
- }
247
- async navigate(navigateOptions) {
248
- return this.internalNavigate(makeNavigateOptions(navigateOptions), {});
249
- }
250
- async internalNavigate(navigateOptions, { history, redirect }) {
251
- var _a;
252
- const { url, replace, params, navigateState, code } = navigateOptions;
253
- const prevNavigation = redirect
254
- ? this.lastNavigation
255
- : (_a = this.currentNavigation) !== null && _a !== void 0 ? _a : this.lastNavigation;
256
- if (!url && !prevNavigation) {
257
- throw new Error('Navigate url should be specified and cannot be omitted for first navigation');
258
- }
259
- const resolvedUrl = this.resolveUrl(navigateOptions);
260
- const { to: from, url: fromUrl } = prevNavigation !== null && prevNavigation !== void 0 ? prevNavigation : {};
261
- const redirectFrom = redirect ? this.currentNavigation.to : undefined;
262
- let navigation = {
263
- type: 'navigate',
264
- from,
265
- url: resolvedUrl,
266
- fromUrl,
267
- replace,
268
- history,
269
- navigateState,
270
- code,
271
- redirect,
272
- redirectFrom,
273
- };
274
- await this.runHooks('beforeResolve', navigation);
275
- const to = this.resolveRoute({ url: resolvedUrl, params, navigateState }, { wildcard: true });
276
- if (to) {
277
- navigation = {
278
- ...navigation,
279
- to,
280
- };
281
- }
282
- exports.logger.debug({
283
- event: 'navigation',
284
- navigation,
285
- });
286
- if (!navigation.to) {
287
- return this.notfound(navigation);
288
- }
289
- await this.run(navigation);
290
- }
291
- async runNavigate(navigation) {
292
- // check for redirect in new route description
293
- if (navigation.to.redirect) {
294
- return this.redirect(navigation, makeNavigateOptions(navigation.to.redirect));
295
- }
296
- await this.runGuards(navigation);
297
- await this.runHooks('beforeNavigate', navigation);
298
- this.commitNavigation(navigation);
299
- await this.runHooks('afterNavigate', navigation);
300
- }
301
- async run(navigation) {
302
- this.currentNavigation = navigation;
303
- if (navigation.type === 'navigate') {
304
- await this.runNavigate(navigation);
305
- }
306
- if (navigation.type === 'updateCurrentRoute') {
307
- await this.runUpdateCurrentRoute(navigation);
308
- }
309
- }
310
- resolve(resolveOptions, options) {
311
- const opts = typeof resolveOptions === 'string' ? { url: resolveOptions } : resolveOptions;
312
- return this.resolveRoute({ ...opts, url: url.parse(opts.url) }, options);
313
- }
314
- back(options) {
315
- return this.go(-1, options);
316
- }
317
- forward() {
318
- return this.go(1);
319
- }
320
- async go(to, options) {
321
- exports.logger.debug({
322
- event: 'history.go',
323
- to,
324
- });
325
- return this.history.go(to, options);
326
- }
327
- isNavigating() {
328
- return !!this.currentNavigation;
329
- }
330
- async dehydrate() {
331
- throw new Error('Not implemented');
332
- }
333
- async rehydrate(navigation) {
334
- throw new Error('Not implemented');
335
- }
336
- addRoute(route) {
337
- var _a;
338
- (_a = this.tree) === null || _a === void 0 ? void 0 : _a.addRoute(route);
339
- }
340
- async redirect(navigation, target) {
341
- var _a;
342
- exports.logger.debug({
343
- event: 'redirect',
344
- navigation,
345
- target,
346
- });
347
- return (_a = this.onRedirect) === null || _a === void 0 ? void 0 : _a.call(this, {
348
- ...navigation,
349
- from: navigation.to,
350
- fromUrl: navigation.url,
351
- to: null,
352
- url: this.resolveUrl(target),
353
- });
354
- }
355
- async notfound(navigation) {
356
- var _a;
357
- exports.logger.debug({
358
- event: 'not-found',
359
- navigation,
360
- });
361
- return (_a = this.onNotFound) === null || _a === void 0 ? void 0 : _a.call(this, navigation);
362
- }
363
- async block(navigation) {
364
- exports.logger.debug({
365
- event: 'blocked',
366
- navigation,
367
- });
368
- this.currentNavigation = null;
369
- if (this.onBlock) {
370
- return this.onBlock(navigation);
371
- }
372
- throw new Error('Navigation blocked');
373
- }
374
- normalizePathname(pathname) {
375
- let normalized = pathname;
376
- if (this.mergeSlashes) {
377
- normalized = normalizeManySlashes(normalized);
378
- }
379
- if (!this.strictTrailingSlash) {
380
- normalized = normalizeTrailingSlash(normalized, this.trailingSlash);
381
- }
382
- return normalized;
383
- }
384
- resolveUrl({ url: url$1, query = {}, params, preserveQuery, hash }) {
385
- var _a;
386
- const currentRoute = this.getCurrentRoute();
387
- const currentUrl = this.getCurrentUrl();
388
- const resultUrl = url$1 ? url.rawResolveUrl((_a = currentUrl === null || currentUrl === void 0 ? void 0 : currentUrl.href) !== null && _a !== void 0 ? _a : '', url$1) : url.rawParse(currentUrl.href);
389
- let { pathname } = resultUrl;
390
- if (params) {
391
- if (url$1) {
392
- pathname = makePath(resultUrl.pathname, params);
393
- }
394
- else if (currentRoute) {
395
- pathname = makePath(currentRoute.path, { ...currentRoute.params, ...params });
396
- }
397
- }
398
- if (isSameHost(resultUrl)) {
399
- pathname = this.normalizePathname(pathname);
400
- }
401
- return url.convertRawUrl(url.rawAssignUrl(resultUrl, {
402
- pathname,
403
- search: url$1 ? resultUrl.search : '',
404
- query: {
405
- ...(preserveQuery ? this.getCurrentUrl().query : {}),
406
- ...query,
407
- },
408
- hash: hash !== null && hash !== void 0 ? hash : resultUrl.hash,
409
- }));
410
- }
411
- resolveRoute({ url, params, navigateState }, { wildcard } = {}) {
412
- var _a, _b;
413
- let route = url ? (_a = this.tree) === null || _a === void 0 ? void 0 : _a.getRoute(url.pathname) : this.getCurrentRoute();
414
- if (wildcard && !route && url) {
415
- // if ordinary route not found look for a wildcard route
416
- route = (_b = this.tree) === null || _b === void 0 ? void 0 : _b.getWildcard(url.pathname);
417
- }
418
- if (!route) {
419
- return;
420
- }
421
- // if condition is true route data not changed, so no need to create new reference for route object
422
- if (!params && navigateState === route.navigateState) {
423
- return route;
424
- }
425
- return {
426
- ...route,
427
- params: { ...route.params, ...params },
428
- navigateState,
429
- };
430
- }
431
- async runGuards(navigation) {
432
- exports.logger.debug({
433
- event: 'guards.run',
434
- navigation,
435
- });
436
- if (!this.guards) {
437
- exports.logger.debug({
438
- event: 'guards.empty',
439
- navigation,
440
- });
441
- return;
442
- }
443
- const results = await Promise.all(Array.from(this.guards).map((guard) => Promise.resolve(guard(navigation)).catch((error) => {
444
- exports.logger.warn({
445
- event: 'guard.error',
446
- error,
447
- });
448
- })));
449
- exports.logger.debug({
450
- event: 'guards.done',
451
- navigation,
452
- results,
453
- });
454
- for (const result of results) {
455
- if (result === false) {
456
- return this.block(navigation);
457
- }
458
- if (isString__default["default"](result) || isObject__default["default"](result)) {
459
- return this.redirect(navigation, makeNavigateOptions(result));
460
- }
461
- }
462
- }
463
- registerGuard(guard) {
464
- return registerHook(this.guards, guard);
465
- }
466
- runSyncHooks(hookName, navigation) {
467
- exports.logger.debug({
468
- event: 'sync-hooks.run',
469
- hookName,
470
- navigation,
471
- });
472
- const hooks = this.syncHooks.get(hookName);
473
- if (!hooks) {
474
- exports.logger.debug({
475
- event: 'sync-hooks.empty',
476
- hookName,
477
- navigation,
478
- });
479
- return;
480
- }
481
- for (const hook of hooks) {
482
- try {
483
- hook(navigation);
484
- }
485
- catch (error) {
486
- exports.logger.warn({
487
- event: 'sync-hooks.error',
488
- error,
489
- });
490
- }
491
- }
492
- exports.logger.debug({
493
- event: 'sync-hooks.done',
494
- hookName,
495
- navigation,
496
- });
497
- }
498
- registerSyncHook(hookName, hook) {
499
- return registerHook(this.syncHooks.get(hookName), hook);
500
- }
501
- async runHooks(hookName, navigation) {
502
- exports.logger.debug({
503
- event: 'hooks.run',
504
- hookName,
505
- navigation,
506
- });
507
- const hooks = this.hooks.get(hookName);
508
- if (!hooks) {
509
- exports.logger.debug({
510
- event: 'hooks.empty',
511
- hookName,
512
- navigation,
513
- });
514
- return;
515
- }
516
- await Promise.all(Array.from(hooks).map((hook) => Promise.resolve(hook(navigation)).catch((error) => {
517
- exports.logger.warn({
518
- event: 'hook.error',
519
- error,
520
- });
521
- // rethrow error for beforeResolve to prevent showing not found page
522
- // if app has problems while loading info about routes
523
- if (hookName === 'beforeResolve') {
524
- throw error;
525
- }
526
- })));
527
- exports.logger.debug({
528
- event: 'hooks.done',
529
- hookName,
530
- navigation,
531
- });
532
- }
533
- registerHook(hookName, hook) {
534
- return registerHook(this.hooks.get(hookName), hook);
535
- }
536
- }
537
-
538
- class History {
539
- init(navigation) { }
540
- listen(listener) {
541
- this.listener = listener;
542
- }
543
- setTree(tree) {
544
- this.tree = tree;
545
- }
546
- }
547
-
548
- class ServerHistory extends History {
549
- save() { }
550
- go() {
551
- exports.logger.warn({
552
- event: 'history.server',
553
- message: 'Trying to change history on server',
554
- });
555
- return Promise.resolve();
556
- }
557
- }
558
-
559
- const createTree = (route) => {
560
- return {
561
- route,
562
- children: Object.create(null),
563
- parameters: [],
564
- };
565
- };
566
- const createNavigationRoute = (route, pathname, params) => {
567
- return {
568
- ...route,
569
- actualPath: pathname,
570
- params: params !== null && params !== void 0 ? params : {},
571
- };
572
- };
573
- class RouteTree {
574
- constructor(routes) {
575
- this.tree = createTree();
576
- each__default["default"]((route) => this.addRoute(route), routes);
577
- }
578
- // eslint-disable-next-line max-statements
579
- addRoute(route) {
580
- const parts = getParts(route.path);
581
- let currentTree = this.tree;
582
- for (let i = 0; i < parts.length; i++) {
583
- const part = parts[i];
584
- const parsed = parse(part);
585
- if (parsed.type === 1 /* PartType.historyFallback */) {
586
- currentTree.historyFallbackRoute = route;
587
- return;
588
- }
589
- if (parsed.type === 2 /* PartType.wildcard */) {
590
- currentTree.wildcardRoute = route;
591
- return;
592
- }
593
- if (parsed.type === 3 /* PartType.parameter */) {
594
- const { paramName, regexp, optional } = parsed;
595
- // prevent from creating new entries for same route
596
- const found = find__default["default"]((par) => par.key === part, currentTree.parameters);
597
- if (found) {
598
- currentTree = found.tree;
599
- }
600
- else {
601
- const parameter = {
602
- key: part,
603
- paramName,
604
- regexp,
605
- optional,
606
- tree: createTree(),
607
- };
608
- if (regexp && !optional) {
609
- // insert parameters with regexp before
610
- const index = findIndex__default["default"]((par) => !par.regexp, currentTree.parameters);
611
- currentTree.parameters.splice(index, 0, parameter);
612
- }
613
- else {
614
- currentTree.parameters.push(parameter);
615
- }
616
- currentTree = parameter.tree;
617
- }
618
- }
619
- else {
620
- if (!currentTree.children[part]) {
621
- currentTree.children[part] = createTree();
622
- }
623
- currentTree = currentTree.children[part];
624
- }
625
- }
626
- currentTree.route = route;
627
- }
628
- getRoute(pathname) {
629
- return this.findRoute(pathname, 'route');
630
- }
631
- getWildcard(pathname) {
632
- return this.findRoute(pathname, 'wildcardRoute');
633
- }
634
- getHistoryFallback(pathname) {
635
- const route = this.findRoute(pathname, 'historyFallbackRoute');
636
- return (route && {
637
- ...route,
638
- // remove <history-fallback> from path
639
- actualPath: route.path.replace(HISTORY_FALLBACK_REGEXP, '') || '/',
640
- });
641
- }
642
- // eslint-disable-next-line max-statements
643
- findRoute(pathname, propertyName) {
644
- // we should use exact match only for classic route
645
- // as special routes (for not-found and history-fallback) are defined for whole subtree
646
- const exactMatch = propertyName === 'route';
647
- const parts = getParts(pathname);
648
- const queue = [
649
- [this.tree, 0],
650
- ];
651
- while (queue.length) {
652
- const [currentTree, index, params] = queue.pop();
653
- const { children, parameters } = currentTree;
654
- // this flag mean we can only check for optional parameters
655
- // as we didn't find static route for this path, but still may find
656
- // some inner route inside optional branch
657
- // the value of parameter will be empty in this case ofc
658
- let optionalOnly = false;
659
- if (index >= parts.length) {
660
- if (currentTree[propertyName]) {
661
- return createNavigationRoute(currentTree[propertyName], pathname, params);
662
- }
663
- // here we cant check any options except for optional parameters
664
- optionalOnly = true;
665
- }
666
- // first add to queue special routes (not-found or history-fallback) to check it after other cases, as it will be processed last
667
- if (!exactMatch && currentTree[propertyName]) {
668
- queue.push([currentTree, parts.length, params]);
669
- }
670
- const part = parts[index];
671
- const child = children[part];
672
- // then add checks for only optional
673
- for (const param of parameters) {
674
- const { optional, tree } = param;
675
- if (optional) {
676
- queue.push([tree, index, params]);
677
- }
678
- }
679
- if (optionalOnly) {
680
- continue;
681
- }
682
- // for non-optional cases
683
- for (let i = parameters.length - 1; i >= 0; i--) {
684
- const param = parameters[i];
685
- const { paramName, tree, regexp } = param;
686
- const match = regexp === null || regexp === void 0 ? void 0 : regexp.exec(part);
687
- const paramValue = regexp ? match === null || match === void 0 ? void 0 : match[1] : part;
688
- if (paramValue) {
689
- queue.push([tree, index + 1, { ...params, [paramName]: paramValue }]);
690
- }
691
- }
692
- if (child) {
693
- // add checks for static child subtree last as it will be processed first after queue.pop
694
- queue.push([child, index + 1, params]);
695
- }
696
- }
697
- }
698
- }
699
-
700
- class Router extends AbstractRouter {
701
- constructor(options) {
702
- var _a;
703
- super(options);
704
- this.blocked = false;
705
- this.tree = new RouteTree(options.routes);
706
- this.defaultRedirectCode = (_a = options.defaultRedirectCode) !== null && _a !== void 0 ? _a : 308;
707
- this.history = new ServerHistory();
708
- }
709
- async dehydrate() {
710
- exports.logger.debug({
711
- event: 'dehydrate',
712
- navigation: this.lastNavigation,
713
- });
714
- return this.lastNavigation;
715
- }
716
- async internalNavigate(navigateOptions, internalOptions) {
717
- // any navigation after initial should be considered as redirects
718
- if (this.getCurrentRoute()) {
719
- return this.redirect(this.lastNavigation, navigateOptions);
720
- }
721
- return super.internalNavigate(navigateOptions, internalOptions);
722
- }
723
- async run(navigation) {
724
- if (this.redirectCode) {
725
- return this.redirect(navigation, { url: navigation.url.href, code: this.redirectCode });
726
- }
727
- await super.run(navigation);
728
- }
729
- async redirect(navigation, target) {
730
- exports.logger.debug({
731
- event: 'redirect',
732
- navigation,
733
- target,
734
- });
735
- this.blocked = true;
736
- return this.onRedirect({
737
- ...navigation,
738
- from: navigation.to,
739
- fromUrl: navigation.url,
740
- to: null,
741
- url: this.resolveUrl(target),
742
- code: target.code,
743
- });
744
- }
745
- async notfound(navigation) {
746
- this.blocked = true;
747
- return super.notfound(navigation);
748
- }
749
- normalizePathname(pathname) {
750
- const normalized = super.normalizePathname(pathname);
751
- if (normalized !== pathname) {
752
- this.redirectCode = this.defaultRedirectCode;
753
- }
754
- return normalized;
755
- }
756
- resolveUrl(options) {
757
- if (options.url && url.isInvalidUrl(options.url)) {
758
- this.redirectCode = this.defaultRedirectCode;
759
- }
760
- return super.resolveUrl(options);
761
- }
762
- async runHooks(hookName, navigation) {
763
- // do not run hooks if another parallel navigation has been called
764
- if (this.blocked) {
765
- return;
766
- }
767
- return super.runHooks(hookName, navigation);
768
- }
769
- async runGuards(navigation) {
770
- // do not run guards if another parallel navigation has been called
771
- if (this.blocked) {
772
- return;
773
- }
774
- return super.runGuards(navigation);
775
- }
776
- }
777
-
778
- const supportsHtml5History = typeof window !== 'undefined' && window.history && window.history.pushState;
779
- const wrapHistory = ({ onNavigate }) => {
780
- if (!supportsHtml5History) {
781
- const navigate = (data, title, url) => {
782
- window.location.href = url.toString();
783
- };
784
- window.history.pushState = navigate;
785
- window.history.replaceState = navigate;
786
- return {
787
- navigate: ({ path }) => navigate({}, '', path),
788
- history: () => {
789
- throw new Error('Method not implemented');
790
- },
791
- init: noop__default["default"],
792
- subscribe: noop__default["default"],
793
- };
794
- }
795
- let browserHistory = window.history;
796
- if ('__originalHistory' in window.history) {
797
- browserHistory = window.history.__originalHistory;
798
- }
799
- else {
800
- window.history.__originalHistory = {
801
- pushState: browserHistory.pushState.bind(window.history),
802
- replaceState: browserHistory.replaceState.bind(window.history),
803
- go: browserHistory.go.bind(window.history),
804
- };
805
- }
806
- const pushState = browserHistory.pushState.bind(window.history);
807
- const replaceState = browserHistory.replaceState.bind(window.history);
808
- const go = browserHistory.go.bind(window.history);
809
- const navigate = ({ path, replace, state }) => {
810
- if (replace) {
811
- replaceState(state, '', path);
812
- }
813
- else {
814
- pushState(state, '', path);
815
- }
816
- };
817
- const history = (delta) => {
818
- go(delta);
819
- };
820
- const browserNavigate = (replace = false) => {
821
- return (navigateState, title, url) => {
822
- onNavigate({ url: url.toString(), replace, navigateState });
823
- };
824
- };
825
- window.history.pushState = browserNavigate(false);
826
- window.history.replaceState = browserNavigate(true);
827
- window.history.go = history;
828
- window.history.back = () => history(-1);
829
- window.history.forward = () => history(1);
830
- return {
831
- navigate,
832
- history,
833
- init: (state) => {
834
- replaceState(state, '');
835
- },
836
- subscribe: (handler) => {
837
- window.addEventListener('popstate', ({ state }) => {
838
- handler({
839
- path: window.location.pathname + window.location.search + window.location.hash,
840
- state,
841
- });
842
- });
843
- },
844
- };
845
- };
846
-
847
- const isHistoryState = (state) => {
848
- return state && typeof state.key === 'string';
849
- };
850
- const generateKey = (navigation) => {
851
- const { to } = navigation;
852
- if (to) {
853
- return `${to.name}_${to.path}`;
854
- }
855
- };
856
- const generateState = (navigation, currentState) => {
857
- const key = generateKey(navigation);
858
- let { type } = navigation;
859
- if (navigation.replace && currentState) {
860
- type = currentState.type === type ? type : 'navigate';
861
- }
862
- return {
863
- key,
864
- type,
865
- navigateState: navigation.navigateState,
866
- };
867
- };
868
- class ClientHistory extends History {
869
- constructor() {
870
- super();
871
- this.currentIndex = 0;
872
- this.historyWrapper = wrapHistory({
873
- onNavigate: ({ url, replace, navigateState }) => {
874
- this.listener({
875
- url,
876
- replace,
877
- navigateState,
878
- });
879
- },
880
- });
881
- }
882
- init(navigation) {
883
- var _a;
884
- this.currentState = isHistoryState((_a = window.history) === null || _a === void 0 ? void 0 : _a.state)
885
- ? window.history.state
886
- : generateState(navigation);
887
- this.historyWrapper.init(this.currentState);
888
- this.historyWrapper.subscribe(async ({ path, state }) => {
889
- var _a, _b;
890
- try {
891
- let navigationType;
892
- let navigateState;
893
- if (isHistoryState(state)) {
894
- const { key: prevKey, type: prevType } = this.currentState;
895
- const { key, type } = state;
896
- this.currentState = state;
897
- navigateState = state.navigateState;
898
- if (key === prevKey &&
899
- (type === 'updateCurrentRoute' || prevType === 'updateCurrentRoute')) {
900
- navigationType = 'updateCurrentRoute';
901
- }
902
- else {
903
- navigationType = 'navigate';
904
- }
905
- }
906
- else {
907
- // if it is not HistoryState than it is probably not a state from @tinkoff/router so reset it
908
- this.currentIndex = 0;
909
- }
910
- await this.listener({
911
- type: navigationType,
912
- history: true,
913
- url: path,
914
- navigateState,
915
- });
916
- (_a = this.goPromiseResolve) === null || _a === void 0 ? void 0 : _a.call(this);
917
- }
918
- catch (err) {
919
- (_b = this.goPromiseReject) === null || _b === void 0 ? void 0 : _b.call(this, err);
920
- }
921
- });
922
- }
923
- save(navigation) {
924
- const { replace, url } = navigation;
925
- if (!replace) {
926
- this.currentIndex++;
927
- }
928
- this.currentState = generateState(navigation, this.currentState);
929
- this.historyWrapper.navigate({
930
- path: url.path,
931
- replace,
932
- state: this.currentState,
933
- });
934
- }
935
- go(to, options) {
936
- var _a;
937
- const index = this.currentIndex + to;
938
- if (index < 0) {
939
- if (options === null || options === void 0 ? void 0 : options.historyFallback) {
940
- return this.listener({
941
- url: options.historyFallback,
942
- type: 'navigate',
943
- history: false,
944
- });
945
- }
946
- const historyFallbackRoute = (_a = this.tree) === null || _a === void 0 ? void 0 : _a.getHistoryFallback(window.location.pathname);
947
- if (historyFallbackRoute) {
948
- return this.listener({
949
- url: historyFallbackRoute.actualPath,
950
- type: 'navigate',
951
- history: false,
952
- });
953
- }
954
- }
955
- const promise = new Promise((resolve, reject) => {
956
- this.goPromiseResolve = resolve;
957
- this.goPromiseReject = reject;
958
- });
959
- this.historyWrapper.history(to);
960
- return promise;
961
- }
962
- }
963
-
964
- class ClientRouter extends AbstractRouter {
965
- constructor(options) {
966
- super(options);
967
- this.history = new ClientHistory();
968
- this.history.listen(async ({ type, url, navigateState, replace, history }) => {
969
- var _a;
970
- const currentUrl = this.getCurrentUrl();
971
- const { pathname, query } = this.resolveUrl({ url });
972
- const isSameUrlNavigation = currentUrl.pathname === pathname;
973
- if (type === 'updateCurrentRoute' || (!type && isSameUrlNavigation)) {
974
- const route = (_a = this.tree) === null || _a === void 0 ? void 0 : _a.getRoute(pathname);
975
- await this.internalUpdateCurrentRoute({
976
- params: route === null || route === void 0 ? void 0 : route.params,
977
- query,
978
- replace,
979
- navigateState,
980
- }, { history });
981
- }
982
- else {
983
- await this.internalNavigate({
984
- url,
985
- replace,
986
- navigateState,
987
- }, { history });
988
- }
989
- });
990
- }
991
- async rehydrate(navigation) {
992
- exports.logger.debug({
993
- event: 'rehydrate',
994
- navigation,
995
- });
996
- const url$1 = url.parse(window.location.href);
997
- this.currentNavigation = {
998
- ...navigation,
999
- type: 'navigate',
1000
- url: url$1,
1001
- };
1002
- this.lastNavigation = this.currentNavigation;
1003
- // rerun guard check in case it differs from server side
1004
- await this.runGuards(this.currentNavigation);
1005
- // and init any history listeners
1006
- this.history.init(this.currentNavigation);
1007
- this.currentNavigation = null;
1008
- // add dehydrated route to tree to prevent its loading
1009
- if (navigation.to) {
1010
- this.addRoute({
1011
- name: navigation.to.name,
1012
- path: navigation.to.path,
1013
- config: navigation.to.config,
1014
- // in case we have loaded page from some path-changing proxy
1015
- // save this actual path as alias
1016
- alias: url$1.pathname,
1017
- });
1018
- }
1019
- }
1020
- resolveRoute(...options) {
1021
- const { url } = options[0];
1022
- // navigation for other hosts should be considered as external navigation
1023
- if (url && !isSameHost(url)) {
1024
- return;
1025
- }
1026
- return super.resolveRoute(...options);
1027
- }
1028
- async notfound(navigation) {
1029
- var _a, _b;
1030
- await super.notfound(navigation);
1031
- // in case we didn't find any matched route just force hard page navigation
1032
- const prevUrl = (_b = (_a = navigation.fromUrl) === null || _a === void 0 ? void 0 : _a.href) !== null && _b !== void 0 ? _b : window.location.href;
1033
- const nextUrl = navigation.url.href;
1034
- const isNoSpaNavigation = navigation.from && !navigation.to;
1035
- // prevent redirect cycle on the same page,
1036
- // except cases when we run no-spa navigations,
1037
- // because we need hard reload in this cases
1038
- if (isNoSpaNavigation ? true : prevUrl !== nextUrl) {
1039
- if (navigation.replace) {
1040
- window.location.replace(nextUrl);
1041
- }
1042
- else {
1043
- window.location.assign(nextUrl);
1044
- }
1045
- }
1046
- // prevent routing from any continues navigation returning promise which will be not resolved
1047
- return new Promise(() => { });
1048
- }
1049
- async block(navigation) {
1050
- return this.notfound(navigation);
1051
- }
1052
- async redirect(navigation, target) {
1053
- await super.redirect(navigation, target);
1054
- return this.internalNavigate({
1055
- ...target,
1056
- replace: target.replace || navigation.replace,
1057
- }, {
1058
- redirect: true,
1059
- });
1060
- }
1061
- }
1062
-
1063
- const omitHash = (url) => url.href.replace(/#.*$/, '');
1064
- class NoSpaRouter extends ClientRouter {
1065
- run(navigation) {
1066
- const { type, fromUrl, url } = navigation;
1067
- // support only updateCurrentRoute or hash navigations
1068
- if (type === 'updateCurrentRoute' || omitHash(url) === omitHash(fromUrl)) {
1069
- return super.run(navigation);
1070
- }
1071
- return this.notfound(navigation);
1072
- }
1073
- // do not call any hooks as it is only supports url updates with hash
1074
- async runHooks() { }
1075
- }
1076
-
1077
- const RouterContext = react.createContext(null);
1078
- const RouteContext = react.createContext(null);
1079
- const UrlContext = react.createContext(null);
1080
-
1081
- const Provider = ({ router, serverState, children }) => {
1082
- const route = shim.useSyncExternalStore((cb) => router.registerSyncHook('change', cb), () => router.getLastRoute(), serverState ? () => serverState.currentRoute : () => router.getLastRoute());
1083
- const url = shim.useSyncExternalStore((cb) => router.registerSyncHook('change', cb), () => router.getLastUrl(), serverState ? () => serverState.currentUrl : () => router.getLastUrl());
1084
- return (jsxRuntime.jsx(RouterContext.Provider, { value: router, children: jsxRuntime.jsx(RouteContext.Provider, { value: route, children: jsxRuntime.jsx(UrlContext.Provider, { value: url, children: children }) }) }));
1085
- };
1086
- Provider.displayName = 'Provider';
1087
-
1088
- const useRouter = () => {
1089
- return react.useContext(RouterContext);
1090
- };
1091
-
1092
- const useRoute = () => {
1093
- return react.useContext(RouteContext);
1094
- };
1095
-
1096
- const useUrl = () => {
1097
- return react.useContext(UrlContext);
1098
- };
1099
-
1100
- const convertToNavigateOptions = (options) => {
1101
- return typeof options === 'string' ? { url: options } : options;
1102
- };
1103
- const useNavigate = (rootOptions) => {
1104
- const router = useRouter();
1105
- const rootOpts = reactHooks.useShallowEqual(convertToNavigateOptions(rootOptions));
1106
- return react.useCallback((specificOptions) => {
1107
- const opts = rootOpts !== null && rootOpts !== void 0 ? rootOpts : convertToNavigateOptions(specificOptions);
1108
- return router.navigate(opts);
1109
- }, [rootOpts, router]);
1110
- };
1111
-
1112
- exports.AbstractRouter = AbstractRouter;
1113
- exports.History = History;
1114
- exports.NoSpaRouter = NoSpaRouter;
1115
- exports.Provider = Provider;
1116
- exports.RouteTree = RouteTree;
1117
- exports.Router = Router;
1118
- exports.getParts = getParts;
1119
- exports.isHistoryFallback = isHistoryFallback;
1120
- exports.isParameterized = isParameterized;
1121
- exports.isWildcard = isWildcard;
1122
- exports.makePath = makePath;
1123
- exports.parse = parse;
1124
- exports.setLogger = setLogger;
1125
- exports.useNavigate = useNavigate;
1126
- exports.useRoute = useRoute;
1127
- exports.useRouter = useRouter;
1128
- exports.useUrl = useUrl;
5
+ var server = require('./router/server.js');
6
+ var clientNoSpa = require('./router/clientNoSpa.js');
7
+ var abstract = require('./router/abstract.js');
8
+ var base = require('./history/base.js');
9
+ var logger = require('./logger.js');
10
+ var provider = require('./components/react/provider.js');
11
+ var useRouter = require('./components/react/useRouter.js');
12
+ var useRoute = require('./components/react/useRoute.js');
13
+ var useUrl = require('./components/react/useUrl.js');
14
+ var useNavigate = require('./components/react/useNavigate.js');
15
+ var tree = require('./tree/tree.js');
16
+ var utils = require('./tree/utils.js');
17
+
18
+
19
+
20
+ exports.Router = server.Router;
21
+ exports.NoSpaRouter = clientNoSpa.NoSpaRouter;
22
+ exports.AbstractRouter = abstract.AbstractRouter;
23
+ exports.History = base.History;
24
+ Object.defineProperty(exports, 'logger', {
25
+ enumerable: true,
26
+ get: function () { return logger.logger; }
27
+ });
28
+ exports.setLogger = logger.setLogger;
29
+ exports.Provider = provider.Provider;
30
+ exports.useRouter = useRouter.useRouter;
31
+ exports.useRoute = useRoute.useRoute;
32
+ exports.useUrl = useUrl.useUrl;
33
+ exports.useNavigate = useNavigate.useNavigate;
34
+ exports.RouteTree = tree.RouteTree;
35
+ exports.getParts = utils.getParts;
36
+ exports.isHistoryFallback = utils.isHistoryFallback;
37
+ exports.isParameterized = utils.isParameterized;
38
+ exports.isWildcard = utils.isWildcard;
39
+ exports.makePath = utils.makePath;
40
+ exports.parse = utils.parse;