@real-router/core 0.34.1 → 0.35.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (33) hide show
  1. package/README.md +50 -250
  2. package/dist/cjs/index.d.ts +3 -1
  3. package/dist/cjs/index.js +1 -1
  4. package/dist/cjs/index.js.map +1 -1
  5. package/dist/cjs/metafile-cjs.json +1 -1
  6. package/dist/esm/index.d.mts +3 -1
  7. package/dist/esm/index.mjs +1 -1
  8. package/dist/esm/index.mjs.map +1 -1
  9. package/dist/esm/metafile-esm.json +1 -1
  10. package/package.json +5 -5
  11. package/src/Router.ts +21 -27
  12. package/src/api/getDependenciesApi.ts +2 -9
  13. package/src/api/getLifecycleApi.ts +1 -8
  14. package/src/api/getPluginApi.ts +1 -6
  15. package/src/api/getRoutesApi.ts +3 -11
  16. package/src/api/helpers.ts +10 -0
  17. package/src/constants.ts +3 -1
  18. package/src/index.ts +2 -1
  19. package/src/namespaces/EventBusNamespace/EventBusNamespace.ts +14 -20
  20. package/src/namespaces/NavigationNamespace/NavigationNamespace.ts +129 -144
  21. package/src/namespaces/NavigationNamespace/index.ts +1 -1
  22. package/src/namespaces/NavigationNamespace/transition/index.ts +5 -2
  23. package/src/namespaces/NavigationNamespace/types.ts +26 -28
  24. package/src/namespaces/PluginsNamespace/PluginsNamespace.ts +1 -9
  25. package/src/namespaces/PluginsNamespace/types.ts +2 -12
  26. package/src/namespaces/RouteLifecycleNamespace/RouteLifecycleNamespace.ts +32 -58
  27. package/src/namespaces/RouteLifecycleNamespace/types.ts +3 -10
  28. package/src/namespaces/RouterLifecycleNamespace/RouterLifecycleNamespace.ts +8 -51
  29. package/src/namespaces/RouterLifecycleNamespace/types.ts +12 -2
  30. package/src/namespaces/StateNamespace/StateNamespace.ts +0 -15
  31. package/src/transitionPath.ts +1 -1
  32. package/src/wiring/RouterWiringBuilder.ts +54 -39
  33. package/src/wiring/wireRouter.ts +2 -3
@@ -8,7 +8,6 @@ import { DEFAULT_LIMITS } from "../../constants";
8
8
  import { computeThresholds } from "../../helpers";
9
9
 
10
10
  import type { RouteLifecycleDependencies } from "./types";
11
- import type { Router } from "../../Router";
12
11
  import type { GuardFnFactory, Limits } from "../../types";
13
12
  import type { DefaultDependencies, GuardFn, State } from "@real-router/types";
14
13
 
@@ -48,24 +47,9 @@ export class RouteLifecycleNamespace<
48
47
  readonly #definitionActivateGuardNames = new Set<string>();
49
48
  readonly #definitionDeactivateGuardNames = new Set<string>();
50
49
 
51
- #router!: Router<Dependencies>;
52
50
  #deps!: RouteLifecycleDependencies<Dependencies>;
53
51
  #limits: Limits = DEFAULT_LIMITS;
54
52
 
55
- /**
56
- * Injects the router instance during wiring phase.
57
- *
58
- * @param router - Router instance to use for factory compilation
59
- */
60
- setRouter(router: Router<Dependencies>): void {
61
- this.#router = router;
62
- }
63
-
64
- /**
65
- * Injects namespace dependencies (getDependency accessor) during wiring phase.
66
- *
67
- * @param deps - Dependencies object containing getDependency accessor
68
- */
69
53
  setDependencies(deps: RouteLifecycleDependencies<Dependencies>): void {
70
54
  this.#deps = deps;
71
55
  }
@@ -268,50 +252,41 @@ export class RouteLifecycleNamespace<
268
252
  return [this.#canDeactivateFunctions, this.#canActivateFunctions];
269
253
  }
270
254
 
271
- /**
272
- * Synchronously checks the canActivate guard for a route.
273
- * Returns `true` if no guard is registered or the guard allows activation.
274
- * Returns `false` if the guard blocks, returns a Promise, or throws.
275
- *
276
- * @param name - Route name to check the guard for
277
- * @param toState - Target navigation state
278
- * @param fromState - Current state (`undefined` on initial navigation)
279
- */
280
- checkActivateGuardSync(
281
- name: string,
255
+ canNavigateTo(
256
+ toDeactivate: string[],
257
+ toActivate: string[],
282
258
  toState: State,
283
259
  fromState: State | undefined,
284
260
  ): boolean {
285
- return this.#checkGuardSync(
286
- this.#canActivateFunctions,
287
- name,
288
- toState,
289
- fromState,
290
- "checkActivateGuardSync",
291
- );
292
- }
261
+ for (const segment of toDeactivate) {
262
+ if (
263
+ !this.#checkGuardSync(
264
+ this.#canDeactivateFunctions,
265
+ segment,
266
+ toState,
267
+ fromState,
268
+ "canNavigateTo",
269
+ )
270
+ ) {
271
+ return false;
272
+ }
273
+ }
293
274
 
294
- /**
295
- * Synchronously checks the canDeactivate guard for a route.
296
- * Returns `true` if no guard is registered or the guard allows deactivation.
297
- * Returns `false` if the guard blocks, returns a Promise, or throws.
298
- *
299
- * @param name - Route name to check the guard for
300
- * @param toState - Target navigation state
301
- * @param fromState - Current state (`undefined` on initial navigation)
302
- */
303
- checkDeactivateGuardSync(
304
- name: string,
305
- toState: State,
306
- fromState: State | undefined,
307
- ): boolean {
308
- return this.#checkGuardSync(
309
- this.#canDeactivateFunctions,
310
- name,
311
- toState,
312
- fromState,
313
- "checkDeactivateGuardSync",
314
- );
275
+ for (const segment of toActivate) {
276
+ if (
277
+ !this.#checkGuardSync(
278
+ this.#canActivateFunctions,
279
+ segment,
280
+ toState,
281
+ fromState,
282
+ "canNavigateTo",
283
+ )
284
+ ) {
285
+ return false;
286
+ }
287
+ }
288
+
289
+ return true;
315
290
  }
316
291
 
317
292
  // =========================================================================
@@ -361,8 +336,7 @@ export class RouteLifecycleNamespace<
361
336
  this.#registering.add(name);
362
337
 
363
338
  try {
364
- // Lifecycle factories receive full router as part of their public API
365
- const fn = factory(this.#router, this.#deps.getDependency);
339
+ const fn = this.#deps.compileFactory(factory);
366
340
 
367
341
  if (typeof fn !== "function") {
368
342
  throw new TypeError(
@@ -1,17 +1,10 @@
1
1
  // packages/core/src/namespaces/RouteLifecycleNamespace/types.ts
2
2
 
3
- import type { DefaultDependencies } from "@real-router/types";
3
+ import type { GuardFnFactory } from "../../types";
4
+ import type { DefaultDependencies, GuardFn } from "@real-router/types";
4
5
 
5
- /**
6
- * Dependencies injected into RouteLifecycleNamespace.
7
- *
8
- * Note: Lifecycle factories still receive the router object directly
9
- * as they need access to various router methods. This interface
10
- * only covers the internal namespace operations.
11
- */
12
6
  export interface RouteLifecycleDependencies<
13
7
  Dependencies extends DefaultDependencies = DefaultDependencies,
14
8
  > {
15
- /** Get dependency value for lifecycle factory */
16
- getDependency: <K extends keyof Dependencies>(key: K) => Dependencies[K];
9
+ compileFactory: (factory: GuardFnFactory<Dependencies>) => GuardFn;
17
10
  }
@@ -6,13 +6,9 @@ import { RouterError } from "../../RouterError";
6
6
  import type { RouterLifecycleDependencies } from "./types";
7
7
  import type { NavigationOptions, State } from "@real-router/types";
8
8
 
9
- // ═══════════════════════════════════════════════════════════════════════════════
10
- // CYCLIC DEPENDENCIES
11
- // ═══════════════════════════════════════════════════════════════════════════════
12
- // RouterLifecycle → Navigation.navigateToState() (for start transitions)
13
- //
14
- // Solution: functional references configured in Router.#setupDependencies()
15
- // ═══════════════════════════════════════════════════════════════════════════════
9
+ const REPLACE_OPTS: NavigationOptions = { replace: true };
10
+
11
+ Object.freeze(REPLACE_OPTS);
16
12
 
17
13
  /**
18
14
  * Independent namespace for managing router lifecycle.
@@ -21,17 +17,6 @@ import type { NavigationOptions, State } from "@real-router/types";
21
17
  * by RouterFSM in the facade (Router.ts).
22
18
  */
23
19
  export class RouterLifecycleNamespace {
24
- // ═══════════════════════════════════════════════════════════════════════════
25
- // Functional references for cyclic dependencies
26
- // ═══════════════════════════════════════════════════════════════════════════
27
-
28
- // Dependencies injected via setDependencies (replaces full router reference)
29
- #navigateToState!: (
30
- toState: State,
31
- fromState: State | undefined,
32
- opts: NavigationOptions,
33
- ) => Promise<State>;
34
-
35
20
  #deps!: RouterLifecycleDependencies;
36
21
 
37
22
  // =========================================================================
@@ -54,20 +39,6 @@ export class RouterLifecycleNamespace {
54
39
  // Dependency injection
55
40
  // =========================================================================
56
41
 
57
- /**
58
- * Sets the navigateToState reference (cyclic dependency on NavigationNamespace).
59
- * Must be called before using start().
60
- */
61
- setNavigateToState(
62
- fn: (
63
- toState: State,
64
- fromState: State | undefined,
65
- opts: NavigationOptions,
66
- ) => Promise<State>,
67
- ): void {
68
- this.#navigateToState = fn;
69
- }
70
-
71
42
  /**
72
43
  * Sets dependencies for lifecycle operations.
73
44
  * Must be called before using lifecycle methods.
@@ -90,10 +61,6 @@ export class RouterLifecycleNamespace {
90
61
  const deps = this.#deps;
91
62
  const options = deps.getOptions();
92
63
 
93
- const startOptions: NavigationOptions = {
94
- replace: true,
95
- };
96
-
97
64
  const matchedState = deps.matchPath(startPath);
98
65
 
99
66
  if (!matchedState && !options.allowNotFound) {
@@ -108,25 +75,15 @@ export class RouterLifecycleNamespace {
108
75
 
109
76
  deps.completeStart();
110
77
 
111
- let finalState: State;
112
-
113
78
  if (matchedState) {
114
- finalState = await this.#navigateToState(
115
- matchedState,
116
- undefined,
117
- startOptions,
118
- );
119
- } else {
120
- const notFoundState = deps.makeNotFoundState(startPath);
121
-
122
- finalState = await this.#navigateToState(
123
- notFoundState,
124
- undefined,
125
- startOptions,
79
+ return deps.navigate(
80
+ matchedState.name,
81
+ matchedState.params,
82
+ REPLACE_OPTS,
126
83
  );
127
84
  }
128
85
 
129
- return finalState;
86
+ return deps.navigateToNotFound(startPath);
130
87
  }
131
88
 
132
89
  /**
@@ -1,10 +1,20 @@
1
1
  // packages/core/src/namespaces/RouterLifecycleNamespace/types.ts
2
2
 
3
- import type { Options, Params, State } from "@real-router/types";
3
+ import type {
4
+ NavigationOptions,
5
+ Options,
6
+ Params,
7
+ State,
8
+ } from "@real-router/types";
4
9
 
5
10
  export interface RouterLifecycleDependencies {
6
11
  getOptions: () => Options;
7
- makeNotFoundState: (path: string) => State;
12
+ navigate: (
13
+ name: string,
14
+ params: Params,
15
+ opts: NavigationOptions,
16
+ ) => Promise<State>;
17
+ navigateToNotFound: (path: string) => State;
8
18
  clearState: () => void;
9
19
  matchPath: <P extends Params = Params, MP extends Params = Params>(
10
20
  path: string,
@@ -3,7 +3,6 @@
3
3
  import { getTypeDescription, validateState } from "type-guards";
4
4
 
5
5
  import { areParamValuesEqual, getUrlParamsFromMeta } from "./helpers";
6
- import { constants } from "../../constants";
7
6
  import { freezeStateInPlace } from "../../helpers";
8
7
 
9
8
  import type { StateNamespaceDependencies } from "./types";
@@ -181,20 +180,6 @@ export class StateNamespace {
181
180
  return freezeStateInPlace(state);
182
181
  }
183
182
 
184
- /**
185
- * Creates a frozen state object for the "not found" route.
186
- */
187
- makeNotFoundState(path: string): State {
188
- return this.makeState<{ path: string }>(
189
- constants.UNKNOWN_ROUTE,
190
- { path },
191
- path,
192
- {
193
- params: {},
194
- },
195
- );
196
- }
197
-
198
183
  // =========================================================================
199
184
  // State Comparison Methods
200
185
  // =========================================================================
@@ -181,7 +181,7 @@ function pointOfDifference(
181
181
  * Validation significantly slows down nameToIDs execution.
182
182
  * The input should be validated by the function/method that calls nameToIDs.
183
183
  */
184
- function nameToIDs(name: string): string[] {
184
+ export function nameToIDs(name: string): string[] {
185
185
  // ===== FAST PATH 1: Empty string (root route) =====
186
186
  // Most common in initial navigation
187
187
  if (!name) {
@@ -1,14 +1,12 @@
1
1
  // packages/core/src/wiring/RouterWiringBuilder.ts
2
2
 
3
3
  import { getInternals } from "../internals";
4
+ import { resolveOption } from "../namespaces/OptionsNamespace";
4
5
  import { validateStateBuilderArgs } from "../namespaces/RoutesNamespace/validators";
5
6
 
6
7
  import type { EventBusNamespace } from "../namespaces";
7
8
  import type { WiringOptions } from "./types";
8
- import type {
9
- NavigationDependencies,
10
- TransitionDependencies,
11
- } from "../namespaces/NavigationNamespace";
9
+ import type { NavigationDependencies } from "../namespaces/NavigationNamespace";
12
10
  import type { PluginsDependencies } from "../namespaces/PluginsNamespace";
13
11
  import type { RouteLifecycleDependencies } from "../namespaces/RouteLifecycleNamespace";
14
12
  import type { RouterLifecycleDependencies } from "../namespaces/RouterLifecycleNamespace";
@@ -56,11 +54,8 @@ export class RouterWiringBuilder<
56
54
  }
57
55
 
58
56
  wireRouteLifecycleDeps(): void {
59
- this.routeLifecycle.setRouter(this.router);
60
-
61
57
  const routeLifecycleDeps: RouteLifecycleDependencies<Dependencies> = {
62
- getDependency: <K extends keyof Dependencies>(dependencyName: K) =>
63
- this.dependenciesStore.dependencies[dependencyName] as Dependencies[K],
58
+ compileFactory: this.createCompileFactory(),
64
59
  };
65
60
 
66
61
  this.routeLifecycle.setDependencies(routeLifecycleDeps);
@@ -97,14 +92,11 @@ export class RouterWiringBuilder<
97
92
  }
98
93
 
99
94
  wirePluginsDeps(): void {
100
- this.plugins.setRouter(this.router);
101
-
102
95
  const pluginsDeps: PluginsDependencies<Dependencies> = {
103
96
  addEventListener: (eventName, cb) =>
104
97
  this.eventBus.addEventListener(eventName, cb),
105
98
  canNavigate: () => this.eventBus.canBeginTransition(),
106
- getDependency: <K extends keyof Dependencies>(dependencyName: K) =>
107
- this.dependenciesStore.dependencies[dependencyName] as Dependencies[K],
99
+ compileFactory: this.createCompileFactory(),
108
100
  };
109
101
 
110
102
  this.plugins.setDependencies(pluginsDeps);
@@ -141,58 +133,71 @@ export class RouterWiringBuilder<
141
133
  },
142
134
  areStatesEqual: (state1, state2, ignoreQueryParams) =>
143
135
  this.state.areStatesEqual(state1, state2, ignoreQueryParams),
144
- getDependency: (name: string) =>
145
- this.dependenciesStore.dependencies[name as keyof Dependencies],
136
+ resolveDefault: () => {
137
+ const options = this.options.get();
138
+
139
+ return {
140
+ route: resolveOption(
141
+ options.defaultRoute,
142
+ (name: string) =>
143
+ this.dependenciesStore.dependencies[name as keyof Dependencies],
144
+ ),
145
+ params: resolveOption(
146
+ options.defaultParams,
147
+ /* v8 ignore next -- @preserve: unreachable unless defaultParams is a callback that calls getDependency */
148
+ (name: string) =>
149
+ this.dependenciesStore.dependencies[name as keyof Dependencies],
150
+ ),
151
+ };
152
+ },
146
153
  startTransition: (toState, fromState) => {
147
- this.eventBus.beginTransition(toState, fromState);
154
+ this.eventBus.sendNavigate(toState, fromState);
148
155
  },
149
156
  cancelNavigation: () => {
150
- this.eventBus.cancelTransition(
157
+ this.eventBus.sendCancel(
151
158
  this.eventBus.getCurrentToState()!, // eslint-disable-line @typescript-eslint/no-non-null-assertion -- guaranteed set before TRANSITIONING
152
159
  this.state.get(),
153
160
  );
154
161
  },
155
162
  sendTransitionDone: (state, fromState, opts) => {
156
- this.eventBus.completeTransition(state, fromState, opts);
163
+ this.eventBus.sendComplete(state, fromState, opts);
157
164
  },
158
- sendTransitionBlocked: (toState, fromState, error) => {
159
- this.eventBus.failTransition(toState, fromState, error);
160
- },
161
- sendTransitionError: (toState, fromState, error) => {
162
- this.eventBus.failTransition(toState, fromState, error);
165
+ sendTransitionFail: (toState, fromState, error) => {
166
+ this.eventBus.sendFail(toState, fromState, error);
163
167
  },
164
168
  emitTransitionError: (toState, fromState, error) => {
165
- this.eventBus.emitOrFailTransitionError(toState, fromState, error);
169
+ this.eventBus.sendFailSafe(toState, fromState, error);
166
170
  },
167
- };
168
-
169
- this.navigation.setDependencies(navigationDeps);
170
-
171
- const transitionDeps: TransitionDependencies = {
171
+ emitTransitionSuccess: (toState, fromState, opts) => {
172
+ this.eventBus.emitTransitionSuccess(toState, fromState, opts);
173
+ },
174
+ canNavigate: () => this.eventBus.canBeginTransition(),
172
175
  getLifecycleFunctions: () => this.routeLifecycle.getFunctions(),
173
176
  isActive: () => this.router.isActive(),
174
177
  isTransitioning: () => this.eventBus.isTransitioning(),
175
- clearCanDeactivate: (name) => {
178
+ clearCanDeactivate: (name: string) => {
176
179
  this.routeLifecycle.clearCanDeactivate(name);
177
180
  },
178
181
  };
179
182
 
180
- this.navigation.setTransitionDependencies(transitionDeps);
183
+ this.navigation.setDependencies(navigationDeps);
181
184
  }
182
185
 
183
186
  wireLifecycleDeps(): void {
184
187
  const lifecycleDeps: RouterLifecycleDependencies = {
185
188
  getOptions: () => this.options.get(),
186
- makeNotFoundState: (path) => this.state.makeNotFoundState(path),
189
+ navigate: (name, params, opts) =>
190
+ this.navigation.navigate(name, params, opts),
191
+ navigateToNotFound: (path) => this.navigation.navigateToNotFound(path),
187
192
  clearState: () => {
188
193
  this.state.set(undefined);
189
194
  },
190
195
  matchPath: (path) => this.routes.matchPath(path, this.options.get()),
191
196
  completeStart: () => {
192
- this.eventBus.completeStart();
197
+ this.eventBus.sendStarted();
193
198
  },
194
199
  emitTransitionError: (toState, fromState, error) => {
195
- this.eventBus.failTransition(toState, fromState, error);
200
+ this.eventBus.sendFail(toState, fromState, error);
196
201
  },
197
202
  };
198
203
 
@@ -211,11 +216,21 @@ export class RouterWiringBuilder<
211
216
  });
212
217
  }
213
218
 
214
- wireCyclicDeps(): void {
215
- this.navigation.setCanNavigate(() => this.eventBus.canBeginTransition());
216
-
217
- this.lifecycle.setNavigateToState((toState, fromState, opts) =>
218
- this.navigation.navigateToState(toState, fromState, opts),
219
- );
219
+ private createCompileFactory() {
220
+ const { router, dependenciesStore } = this;
221
+
222
+ return <T>(
223
+ factory: (
224
+ router: WiringOptions<Dependencies>["router"],
225
+ getDependency: <K extends keyof Dependencies>(
226
+ name: K,
227
+ ) => Dependencies[K],
228
+ ) => T,
229
+ ): T =>
230
+ factory(
231
+ router,
232
+ <K extends keyof Dependencies>(name: K) =>
233
+ dependenciesStore.dependencies[name] as Dependencies[K],
234
+ );
220
235
  }
221
236
  }
@@ -10,8 +10,8 @@ import type { DefaultDependencies } from "@real-router/types";
10
10
  * - `wireLimits()` first: all namespaces must have limits before any other setup
11
11
  * - `wireRouteLifecycleDeps()` BEFORE `wireRoutesDeps()`: RoutesNamespace.setDependencies()
12
12
  * registers pending canActivate handlers which require RouteLifecycleNamespace to be ready
13
- * - `wireCyclicDeps()` LAST: resolves circular references between NavigationNamespace and
14
- * RouterLifecycleNamespace (they depend on each other via direct property assignment)
13
+ * - `wireNavigationDeps()` BEFORE `wireLifecycleDeps()`: lifecycle deps reference
14
+ * NavigationNamespace.navigate() which requires navigation deps to be set
15
15
  */
16
16
  export function wireRouter<Dependencies extends DefaultDependencies>(
17
17
  builder: RouterWiringBuilder<Dependencies>,
@@ -23,5 +23,4 @@ export function wireRouter<Dependencies extends DefaultDependencies>(
23
23
  builder.wireNavigationDeps();
24
24
  builder.wireLifecycleDeps();
25
25
  builder.wireStateDeps();
26
- builder.wireCyclicDeps();
27
26
  }