@real-router/core 0.2.4 → 0.3.0

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.
package/README.md CHANGED
@@ -239,6 +239,7 @@ Set up route forwarding (redirect).\
239
239
  `toRoute: string` — target route name\
240
240
  Returns: `void`\
241
241
  [Wiki](https://github.com/greydragon888/real-router/wiki/forward)
242
+
242
243
  ---
243
244
 
244
245
  ### State Utilities
@@ -266,11 +267,29 @@ Build state from route name.\
266
267
  `params?: Params` — route parameters\
267
268
  Returns: `State | undefined`\
268
269
  [Wiki](https://github.com/greydragon888/real-router/wiki/buildState)
270
+ #### `router.buildStateWithSegments(name: string, params?: Params): { state: State; segments: RouteSegment[] } | undefined`
271
+ Build state with route segments for advanced use cases.\
272
+ `name: string` — route name\
273
+ `params?: Params` — route parameters\
274
+ Returns: `{ state, segments } | undefined`\
275
+ [Wiki](https://github.com/greydragon888/real-router/wiki/buildStateWithSegments)
276
+ #### `router.forwardState(name: string, params: Params): { name: string; params: Params }`
277
+ Resolve route forwarding and merge default params.\
278
+ `name: string` — route name\
279
+ `params: Params` — route parameters\
280
+ Returns: `{ name, params }` — resolved route name and merged params\
281
+ [Wiki](https://github.com/greydragon888/real-router/wiki/forwardState)
282
+ #### `router.shouldUpdateNode(nodeName: string): (toState, fromState?) => boolean`
283
+ Create a predicate to check if a route node should update during transition.\
284
+ `nodeName: string` — route node name\
285
+ Returns: predicate function\
286
+ [Wiki](https://github.com/greydragon888/real-router/wiki/shouldUpdateNode)
269
287
  #### `router.areStatesEqual(state1: State, state2: State, ignoreQueryParams?: boolean): boolean`
270
288
  Compare two states for equality.\
271
289
  `state1: State` — first state\
272
290
  `state2: State` — second state\
273
- `ignoreQueryParams?: boolean` — ignore query params (default: true)Returns: `boolean`\
291
+ `ignoreQueryParams?: boolean` — ignore query params (default: true)\
292
+ Returns: `boolean`\
274
293
  [Wiki](https://github.com/greydragon888/real-router/wiki/areStatesEqual)
275
294
  #### `router.areStatesDescendants(parentState: State, childState: State): boolean`
276
295
  Check if child state is descendant of parent.\
@@ -278,6 +297,7 @@ Check if child state is descendant of parent.\
278
297
  `childState: State` — child state\
279
298
  Returns: `boolean`\
280
299
  [Wiki](https://github.com/greydragon888/real-router/wiki/areStatesDescendants)
300
+
281
301
  ---
282
302
 
283
303
  ### Path Operations
@@ -297,7 +317,9 @@ Returns: `State | undefined`\
297
317
  Check if route is currently active.\
298
318
  `name: string` — route name\
299
319
  `params?: Params` — route parameters\
300
- `strictEquality?: boolean` — exact match (default: false)`ignoreQueryParams?: boolean` — ignore query params (default: true)Returns: `boolean`\
320
+ `strictEquality?: boolean` — exact match (default: false)\
321
+ `ignoreQueryParams?: boolean` — ignore query params (default: true)\
322
+ Returns: `boolean`\
301
323
  [Wiki](https://github.com/greydragon888/real-router/wiki/isActiveRoute)
302
324
  #### `router.setRootPath(rootPath: string): void`
303
325
  Set root path prefix for all routes.\
@@ -308,6 +330,7 @@ Returns: `void`\
308
330
  Get root path prefix.\
309
331
  Returns: `string`\
310
332
  [Wiki](https://github.com/greydragon888/real-router/wiki/getRootPath)
333
+
311
334
  ---
312
335
 
313
336
  ### Dependencies
@@ -346,20 +369,27 @@ Returns: `void`\
346
369
  Remove all dependencies.\
347
370
  Returns: `void`\
348
371
  [Wiki](https://github.com/greydragon888/real-router/wiki/resetDependencies)
372
+
349
373
  ---
350
374
 
351
375
  ### Options
352
376
 
353
377
  #### `router.getOptions(): Options`
354
- Get router options.\
378
+ Get all router options.\
355
379
  Returns: `Options`\
356
380
  [Wiki](https://github.com/greydragon888/real-router/wiki/getOptions)
381
+ #### `router.getOption(name: keyof Options): unknown`
382
+ Get a single router option by name.\
383
+ `name: keyof Options` — option name\
384
+ Returns: option value\
385
+ [Wiki](https://github.com/greydragon888/real-router/wiki/getOption)
357
386
  #### `router.setOption(name: string, value: unknown): void`
358
387
  Set a router option. Must be called before `start()`.\
359
388
  `name: string` — option name\
360
389
  `value: unknown` — option value\
361
390
  Returns: `void`\
362
391
  [Wiki](https://github.com/greydragon888/real-router/wiki/setOption)
392
+
363
393
  ---
364
394
 
365
395
  ### Other
@@ -373,12 +403,8 @@ Returns: `Router`\
373
403
  Check if navigation is in progress.\
374
404
  Returns: `boolean`\
375
405
  [Wiki](https://github.com/greydragon888/real-router/wiki/isNavigating)
376
- #### `router.isActive(name: string, params?: Params, strictEquality?: boolean, ignoreQueryParams?: boolean): boolean`
377
- Alias for `isActiveRoute`.\
378
- `name: string` — route name\
379
- `params?: Params` — route parameters\
380
- `strictEquality?: boolean` — exact match\
381
- `ignoreQueryParams?: boolean` — ignore query params\
406
+ #### `router.isActive(): boolean`
407
+ Check if router is active (started and has current state).\
382
408
  Returns: `boolean`\
383
409
  [Wiki](https://github.com/greydragon888/real-router/wiki/isActive)
384
410
  #### `router.clearCanActivate(name: string): void`
@@ -401,6 +427,7 @@ Remove event listener.\
401
427
  `listener: Function` — listener to remove\
402
428
  Returns: `void`\
403
429
  [Wiki](https://github.com/greydragon888/real-router/wiki/removeEventListener)
430
+
404
431
  ---
405
432
 
406
433
  ## Configuration
@@ -1,5 +1,5 @@
1
- import { ErrorCodeKeys, ErrorCodeValues, ErrorCodeToValueMap, EventToNameMap, State, DefaultDependencies, Route, Options, Router } from '@real-router/types';
2
- export { ActivationFn, ActivationFnFactory, CancelFn, Config, DefaultDependencies, DoneFn, Listener, Middleware, MiddlewareFactory, NavigationOptions, Options, Params, Plugin, PluginFactory, Route, Router, SimpleState, State, StateMeta, SubscribeFn, SubscribeState, Subscription, Unsubscribe } from '@real-router/types';
1
+ import { EventToPluginMap, EventToNameMap, ErrorCodeKeys, ErrorCodeValues, ErrorCodeToValueMap, EventsKeys, State, DefaultDependencies, Options, Params, StateMetaInput, NavigationOptions, SimpleState, RouteTreeState, DoneFn, ActivationFn, Unsubscribe, Middleware, RouterError as RouterError$1, EventName, Plugin, CancelFn, SubscribeFn } from '@real-router/types';
2
+ export { ActivationFn, CancelFn, Config, DefaultDependencies, DoneFn, Listener, Middleware, NavigationOptions, Options, Params, Plugin, SimpleState, State, StateMeta, SubscribeFn, SubscribeState, Subscription, Unsubscribe } from '@real-router/types';
3
3
 
4
4
  type ConstantsKeys = "UNKNOWN_ROUTE";
5
5
  type Constants = Record<ConstantsKeys, string>;
@@ -15,12 +15,286 @@ declare const errorCodes: ErrorCodeToValueMap;
15
15
  * Special route names and identifiers.
16
16
  */
17
17
  declare const constants: Constants;
18
+ /**
19
+ * Plugin method names.
20
+ * Maps to methods that plugins can implement to hook into router lifecycle.
21
+ */
22
+ declare const plugins: EventToPluginMap;
18
23
  /**
19
24
  * Event names for router event system.
20
25
  * Used with addEventListener/removeEventListener for reactive subscriptions.
21
26
  */
22
27
  declare const events: EventToNameMap;
23
28
 
29
+ type EventMethodMap = {
30
+ [K in EventsKeys as (typeof events)[K]]: (typeof plugins)[K];
31
+ };
32
+ /**
33
+ * Observable state passed to subscribers
34
+ */
35
+ interface SubscribeState {
36
+ route: State;
37
+ previousRoute: State | undefined;
38
+ }
39
+ /**
40
+ * Observer interface per Observable spec
41
+ */
42
+ interface Observer {
43
+ next?: (value: SubscribeState) => void;
44
+ error?: (err: unknown) => void;
45
+ complete?: () => void;
46
+ }
47
+ /**
48
+ * Subscription interface per Observable spec
49
+ */
50
+ interface Subscription {
51
+ unsubscribe: () => void;
52
+ readonly closed: boolean;
53
+ }
54
+ /**
55
+ * Observable options for enhanced control
56
+ */
57
+ interface ObservableOptions {
58
+ /** AbortSignal for automatic unsubscription */
59
+ signal?: AbortSignal;
60
+ /** Replay current state to new subscribers (default: true) */
61
+ replay?: boolean;
62
+ }
63
+ /**
64
+ * Observable interface for TC39 compliance
65
+ */
66
+ interface RouterObservable {
67
+ [key: symbol]: () => RouterObservable;
68
+ subscribe: (observer: Observer | ((value: SubscribeState) => void), options?: ObservableOptions) => Subscription;
69
+ }
70
+
71
+ /**
72
+ * Symbol.observable polyfill declaration for TC39 proposal
73
+ *
74
+ * @see https://github.com/tc39/proposal-observable
75
+ */
76
+ declare global {
77
+ interface SymbolConstructor {
78
+ readonly observable: unique symbol;
79
+ }
80
+ }
81
+
82
+ /**
83
+ * Router class with integrated namespace architecture.
84
+ *
85
+ * All functionality is provided by namespace classes:
86
+ * - OptionsNamespace: getOptions, setOption
87
+ * - DependenciesNamespace: get/set/remove dependencies
88
+ * - ObservableNamespace: event listeners, subscribe
89
+ * - StateNamespace: state storage (getState, setState, getPreviousState)
90
+ * - RoutesNamespace: route tree operations
91
+ * - RouteLifecycleNamespace: canActivate/canDeactivate guards
92
+ * - MiddlewareNamespace: middleware chain
93
+ * - PluginsNamespace: plugin lifecycle
94
+ * - NavigationNamespace: navigate, navigateToState
95
+ * - RouterLifecycleNamespace: start, stop, isStarted
96
+ *
97
+ * @internal This class implementation is internal. Use createRouter() instead.
98
+ */
99
+ declare class Router<Dependencies extends DefaultDependencies = DefaultDependencies> {
100
+ #private;
101
+ [key: string]: unknown;
102
+ /**
103
+ * @param routes - Route definitions
104
+ * @param options - Router options
105
+ * @param dependencies - DI dependencies
106
+ */
107
+ constructor(routes?: Route<Dependencies>[], options?: Partial<Options>, dependencies?: Dependencies);
108
+ addRoute(routes: Route<Dependencies>[] | Route<Dependencies>): this;
109
+ removeRoute(name: string): this;
110
+ clearRoutes(): this;
111
+ getRoute(name: string): Route<Dependencies> | undefined;
112
+ hasRoute(name: string): boolean;
113
+ updateRoute(name: string, updates: RouteConfigUpdate<Dependencies>): this;
114
+ isActiveRoute(name: string, params?: Params, strictEquality?: boolean, ignoreQueryParams?: boolean): boolean;
115
+ buildPath(route: string, params?: Params): string;
116
+ matchPath<P extends Params = Params, MP extends Params = Params>(path: string, source?: string): State<P, MP> | undefined;
117
+ setRootPath(rootPath: string): void;
118
+ getRootPath(): string;
119
+ makeState<P extends Params = Params, MP extends Params = Params>(name: string, params?: P, path?: string, meta?: StateMetaInput<MP>, forceId?: number): State<P, MP>;
120
+ makeNotFoundState(path: string, options?: NavigationOptions): State;
121
+ getState<P extends Params = Params, MP extends Params = Params>(): State<P, MP> | undefined;
122
+ setState<P extends Params = Params, MP extends Params = Params>(state?: State<P, MP>): void;
123
+ getPreviousState(): State | undefined;
124
+ areStatesEqual(state1: State | undefined, state2: State | undefined, ignoreQueryParams?: boolean): boolean;
125
+ areStatesDescendants(parentState: State, childState: State): boolean;
126
+ forwardState<P extends Params = Params>(routeName: string, routeParams: P): SimpleState<P>;
127
+ buildState(routeName: string, routeParams: Params): RouteTreeState | undefined;
128
+ buildStateWithSegments<P extends Params = Params>(routeName: string, routeParams: P): BuildStateResultWithSegments<P> | undefined;
129
+ shouldUpdateNode(nodeName: string): (toState: State, fromState?: State) => boolean;
130
+ getOptions(): Options;
131
+ getOption<K extends keyof Options>(option: K): Options[K];
132
+ setOption(option: keyof Options, value: Options[keyof Options]): this;
133
+ isStarted(): boolean;
134
+ isActive(): boolean;
135
+ isNavigating(): boolean;
136
+ start(...args: [] | [done: DoneFn] | [startPathOrState: string | State] | [startPathOrState: string | State, done: DoneFn]): this;
137
+ stop(): this;
138
+ canDeactivate(name: string, canDeactivateHandler: ActivationFnFactory<Dependencies> | boolean): this;
139
+ clearCanDeactivate(name: string, silent?: boolean): this;
140
+ canActivate(name: string, canActivateHandler: ActivationFnFactory<Dependencies> | boolean): this;
141
+ clearCanActivate(name: string, silent?: boolean): this;
142
+ getLifecycleFactories(): [
143
+ Record<string, ActivationFnFactory<Dependencies>>,
144
+ Record<string, ActivationFnFactory<Dependencies>>
145
+ ];
146
+ getLifecycleFunctions(): [
147
+ Map<string, ActivationFn>,
148
+ Map<string, ActivationFn>
149
+ ];
150
+ usePlugin(...plugins: PluginFactory<Dependencies>[]): Unsubscribe;
151
+ getPlugins(): PluginFactory<Dependencies>[];
152
+ useMiddleware(...middlewares: MiddlewareFactory<Dependencies>[]): Unsubscribe;
153
+ clearMiddleware(): this;
154
+ getMiddlewareFactories(): MiddlewareFactory<Dependencies>[];
155
+ getMiddlewareFunctions(): Middleware[];
156
+ setDependency<K extends keyof Dependencies & string>(dependencyName: K, dependency: Dependencies[K]): this;
157
+ setDependencies(deps: Dependencies): this;
158
+ getDependency<K extends keyof Dependencies>(key: K): Dependencies[K];
159
+ getDependencies(): Partial<Dependencies>;
160
+ removeDependency(dependencyName: keyof Dependencies): this;
161
+ hasDependency(dependencyName: keyof Dependencies): boolean;
162
+ resetDependencies(): this;
163
+ invokeEventListeners(eventName: EventToNameMap[EventsKeys], toState?: State, fromState?: State, arg?: RouterError$1 | NavigationOptions): void;
164
+ hasListeners(eventName: EventToNameMap[EventsKeys]): boolean;
165
+ removeEventListener<E extends EventName>(eventName: E, cb: Plugin[EventMethodMap[E]]): void;
166
+ addEventListener<E extends EventName>(eventName: E, cb: Plugin[EventMethodMap[E]]): Unsubscribe;
167
+ forward(fromRoute: string, toRoute: string): this;
168
+ navigate(routeName: string, routeParamsOrDone?: Params | DoneFn, optionsOrDone?: NavigationOptions | DoneFn, done?: DoneFn): CancelFn;
169
+ navigateToDefault(optsOrDone?: NavigationOptions | DoneFn, done?: DoneFn): CancelFn;
170
+ navigateToState(toState: State, fromState: State | undefined, opts: NavigationOptions, callback: DoneFn, emitSuccess: boolean): CancelFn;
171
+ subscribe(listener: SubscribeFn): Unsubscribe;
172
+ /**
173
+ * TC39 Observable spec: router[Symbol.observable]() returns observable
174
+ */
175
+ [Symbol.observable](): RouterObservable;
176
+ /**
177
+ * RxJS compatibility: router["@@observable"]() returns observable
178
+ */
179
+ ["@@observable"](): RouterObservable;
180
+ clone(dependencies?: Dependencies): Router<Dependencies>;
181
+ }
182
+
183
+ /**
184
+ * Router-dependent types.
185
+ *
186
+ * These types reference the Router class and are therefore defined in core
187
+ * rather than core-types to avoid circular dependencies.
188
+ */
189
+
190
+ /**
191
+ * Extended build result that includes segments for path building.
192
+ * Used internally to avoid duplicate getSegmentsByName calls.
193
+ *
194
+ * @param segments - Route segments from getSegmentsByName (typed as unknown[] for cross-package compatibility)
195
+ * @internal
196
+ */
197
+ interface BuildStateResultWithSegments<P extends Params = Params> {
198
+ readonly state: RouteTreeState<P>;
199
+ readonly segments: readonly unknown[];
200
+ }
201
+ /**
202
+ * Route configuration.
203
+ */
204
+ interface Route<Dependencies extends DefaultDependencies = DefaultDependencies> {
205
+ [key: string]: unknown;
206
+ /** Route name (dot-separated for nested routes). */
207
+ name: string;
208
+ /** URL path pattern for this route. */
209
+ path: string;
210
+ /** Factory function that returns a guard for route activation. */
211
+ canActivate?: ActivationFnFactory<Dependencies>;
212
+ /**
213
+ * Redirects navigation to another route.
214
+ *
215
+ * IMPORTANT: forwardTo creates a URL alias, not a transition chain.
216
+ * Guards (canActivate) on the source route are NOT executed.
217
+ * Only guards on the final destination are executed.
218
+ *
219
+ * This matches Vue Router and Angular Router behavior.
220
+ *
221
+ * @example
222
+ * // Correct: guard on target
223
+ * { name: "old", path: "/old", forwardTo: "new" }
224
+ * { name: "new", path: "/new", canActivate: myGuard }
225
+ *
226
+ * // Wrong: guard on source (will be ignored with warning)
227
+ * { name: "old", path: "/old", forwardTo: "new", canActivate: myGuard }
228
+ */
229
+ forwardTo?: string;
230
+ /** Nested child routes. */
231
+ children?: Route<Dependencies>[];
232
+ /** Encodes state params to URL params. */
233
+ encodeParams?: (stateParams: Params) => Params;
234
+ /** Decodes URL params to state params. */
235
+ decodeParams?: (pathParams: Params) => Params;
236
+ /**
237
+ * Default parameters for this route.
238
+ *
239
+ * @remarks
240
+ * **Type Contract:**
241
+ * The type of defaultParams MUST match the expected params type P
242
+ * when using `router.makeState<P>()` or `router.navigate<P>()`.
243
+ *
244
+ * These values are merged into state.params when creating route states.
245
+ * Missing URL params are filled from defaultParams.
246
+ *
247
+ * @example
248
+ * ```typescript
249
+ * // Define route with pagination defaults
250
+ * {
251
+ * name: "users",
252
+ * path: "/users",
253
+ * defaultParams: { page: 1, limit: 10 }
254
+ * }
255
+ *
256
+ * // Navigate without specifying page/limit
257
+ * router.navigate("users", { filter: "active" });
258
+ * // Result: state.params = { page: 1, limit: 10, filter: "active" }
259
+ *
260
+ * // Correct typing — include defaultParams properties
261
+ * type UsersParams = { page: number; limit: number; filter?: string };
262
+ * ```
263
+ */
264
+ defaultParams?: Params;
265
+ }
266
+ /**
267
+ * Configuration update options for updateRoute().
268
+ * All properties are optional. Set to null to remove the configuration.
269
+ */
270
+ interface RouteConfigUpdate<Dependencies extends DefaultDependencies = DefaultDependencies> {
271
+ /** Set to null to remove forwardTo */
272
+ forwardTo?: string | null;
273
+ /** Set to null to remove defaultParams */
274
+ defaultParams?: Params | null;
275
+ /** Set to null to remove decoder */
276
+ decodeParams?: ((params: Params) => Params) | null;
277
+ /** Set to null to remove encoder */
278
+ encodeParams?: ((params: Params) => Params) | null;
279
+ /** Set to null to remove canActivate */
280
+ canActivate?: ActivationFnFactory<Dependencies> | null;
281
+ }
282
+ /**
283
+ * Factory function for creating activation guards.
284
+ * Receives the router instance and a dependency getter.
285
+ */
286
+ type ActivationFnFactory<Dependencies extends DefaultDependencies = DefaultDependencies> = (router: Router<Dependencies>, getDependency: <K extends keyof Dependencies>(key: K) => Dependencies[K]) => ActivationFn;
287
+ /**
288
+ * Factory function for creating middleware.
289
+ * Receives the router instance and a dependency getter.
290
+ */
291
+ type MiddlewareFactory<Dependencies extends DefaultDependencies = DefaultDependencies> = (router: Router<Dependencies>, getDependency: <K extends keyof Dependencies>(key: K) => Dependencies[K]) => Middleware;
292
+ /**
293
+ * Factory function for creating plugins.
294
+ * Receives the router instance and a dependency getter.
295
+ */
296
+ type PluginFactory<Dependencies extends DefaultDependencies = DefaultDependencies> = (router: Router<Dependencies>, getDependency: <K extends keyof Dependencies>(key: K) => Dependencies[K]) => Plugin;
297
+
24
298
  declare class RouterError extends Error {
25
299
  [key: string]: unknown;
26
300
  readonly segment: string | undefined;
@@ -210,7 +484,20 @@ declare class RouterError extends Error {
210
484
 
211
485
  /**
212
486
  * Creates a new router instance.
487
+ *
488
+ * @param routes - Array of route definitions
489
+ * @param options - Router configuration options
490
+ * @param dependencies - Dependencies to inject into the router
491
+ * @returns A new Router instance
492
+ *
493
+ * @example
494
+ * const router = createRouter([
495
+ * { name: 'home', path: '/' },
496
+ * { name: 'users', path: '/users' },
497
+ * ]);
498
+ *
499
+ * router.start('/');
213
500
  */
214
501
  declare const createRouter: <Dependencies extends DefaultDependencies = DefaultDependencies>(routes?: Route<Dependencies>[], options?: Partial<Options>, dependencies?: Dependencies) => Router<Dependencies>;
215
502
 
216
- export { type Constants, type ErrorCodes, RouterError, constants, createRouter, errorCodes, events };
503
+ export { type ActivationFnFactory, type BuildStateResultWithSegments, type Constants, type ErrorCodes, type MiddlewareFactory, type PluginFactory, type Route, type RouteConfigUpdate, Router, RouterError, constants, createRouter, errorCodes, events };