@real-router/core 0.2.0 → 0.2.2

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.
@@ -1,216 +1,1807 @@
1
- import { ErrorCodeKeys, ErrorCodeValues, EventToNameMap, ErrorCodeToValueMap, State, DefaultDependencies, Route, Options, Router } from 'core-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 'core-types';
1
+ // Generated by dts-bundle-generator v9.5.1
3
2
 
4
- type ConstantsKeys = "UNKNOWN_ROUTE";
5
- type Constants = Record<ConstantsKeys, string>;
6
- type ErrorCodes = Record<ErrorCodeKeys, ErrorCodeValues>;
3
+ /**
4
+ * Route Node Type Definitions — Minimal Public API.
5
+ *
6
+ * This module exports ONLY the essential types used by real-router:
7
+ * - QueryParamsMode, QueryParamsOptions
8
+ * - RouteTreeState
9
+ *
10
+ * These types are copied from route-node to avoid circular dependencies.
11
+ *
12
+ * @module route-node-types
13
+ */
14
+ export type ArrayFormat = "none" | "brackets" | "index" | "comma";
15
+ export type BooleanFormat = "none" | "string" | "empty-true";
16
+ export type NullFormat = "default" | "hidden";
17
+ /**
18
+ * Options for query parameter parsing and building.
19
+ */
20
+ export interface QueryParamsOptions {
21
+ arrayFormat?: ArrayFormat;
22
+ booleanFormat?: BooleanFormat;
23
+ nullFormat?: NullFormat;
24
+ }
25
+ /**
26
+ * Controls how query parameters are handled during matching.
27
+ */
28
+ export type QueryParamsMode = "default" | "strict" | "loose";
29
+ export type ParamSource = "url" | "query";
30
+ export type ParamTypeMap = Record<string, ParamSource>;
31
+ export type RouteTreeStateMeta = Record<string, ParamTypeMap>;
32
+ export interface RouteParams {
33
+ [key: string]: string | string[] | number | number[] | boolean | boolean[] | RouteParams | RouteParams[] | Record<string, string | number | boolean> | null | undefined;
34
+ }
35
+ /**
36
+ * Complete state representation of a matched route.
37
+ */
38
+ export interface RouteTreeState<P extends Record<string, unknown> = RouteParams> {
39
+ name: string;
40
+ params: P;
41
+ meta: RouteTreeStateMeta;
42
+ }
43
+ export type Unsubscribe = () => void;
44
+ export type CancelFn = () => void;
45
+ export interface SimpleState<P extends Params = Params> {
46
+ name: string;
47
+ params: P;
48
+ }
49
+ export interface State<P extends Params = Params, MP extends Params = Params> {
50
+ name: string;
51
+ params: P;
52
+ path: string;
53
+ meta?: StateMeta<MP> | undefined;
54
+ }
55
+ export interface StateMeta<P extends Params = Params> {
56
+ id: number;
57
+ params: P;
58
+ options: NavigationOptions;
59
+ redirected: boolean;
60
+ source?: string | undefined;
61
+ }
62
+ /**
63
+ * Input type for makeState meta parameter.
64
+ * Omits `id` since it's auto-generated by makeState.
65
+ */
66
+ export type StateMetaInput<P extends Params = Params> = Omit<StateMeta<P>, "id">;
67
+ /**
68
+ * RouterError interface describing the public API of the RouterError class.
69
+ * The actual class implementation is in the real-router package.
70
+ * This interface enables structural typing compatibility between
71
+ * core-types and real-router packages.
72
+ */
73
+ export interface RouterError extends Error {
74
+ [key: string]: unknown;
75
+ readonly code: string;
76
+ readonly segment: string | undefined;
77
+ readonly path: string | undefined;
78
+ readonly redirect: State | undefined;
79
+ setCode: (code: string) => void;
80
+ setErrorInstance: (err: Error) => void;
81
+ setAdditionalFields: (fields: Record<string, unknown>) => void;
82
+ hasField: (key: string) => boolean;
83
+ getField: (key: string) => unknown;
84
+ toJSON: () => Record<string, unknown>;
85
+ }
86
+ export type DoneFn = (error?: RouterError, state?: State) => void;
87
+ /**
88
+ * Configuration options that control navigation transition behavior.
89
+ *
90
+ * @description
91
+ * NavigationOptions provides fine-grained control over how the router performs navigation
92
+ * transitions. These options affect history management, transition lifecycle execution,
93
+ * guard enforcement, and state comparison logic.
94
+ *
95
+ * All options are optional and have sensible defaults. Options can be combined to achieve
96
+ * complex navigation behaviors. The options object is stored in state.meta.options and is
97
+ * available to middleware, guards, and event listeners.
98
+ *
99
+ * @see {@link Router.navigate} for navigation method that accepts these options
100
+ * @see {@link State.meta} for where options are stored after navigation
101
+ */
102
+ export interface NavigationOptions {
103
+ [key: string]: string | number | boolean | Record<string, unknown> | undefined;
104
+ /**
105
+ * Replace the current history entry instead of pushing a new one.
106
+ *
107
+ * @description
108
+ * When `true`, the navigation will replace the current entry in browser history instead
109
+ * of adding a new entry. This is typically used by history plugins (browser plugin) to
110
+ * control how navigation affects the browser's back/forward buttons.
111
+ *
112
+ * @default false
113
+ *
114
+ * @example
115
+ * // Redirect after login - prevent back button to login page
116
+ * router.navigate('dashboard', {}, { replace: true });
117
+ *
118
+ * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/History/replaceState}
119
+ */
120
+ replace?: boolean | undefined;
121
+ /**
122
+ * Force reload of the current route even if states are equal.
123
+ *
124
+ * @description
125
+ * When `true`, bypasses the "same state" check that normally prevents navigation when
126
+ * the target state equals the current state. This forces a full transition lifecycle
127
+ * execution, allowing route components to reload with the same parameters.
128
+ *
129
+ * Without `reload`:
130
+ * - Navigation to current route throws SAME_STATES error
131
+ * - No lifecycle hooks or middleware execute
132
+ * - No events are fired
133
+ *
134
+ * With `reload`:
135
+ * - Full transition executes (deactivate → activate → middleware)
136
+ * - All lifecycle hooks run again
137
+ * - TRANSITION_SUCCESS event fires with same state
138
+ * - State object is recreated (new reference)
139
+ *
140
+ * @default false
141
+ *
142
+ * @example
143
+ * // Refresh current page data
144
+ * router.navigate(currentRoute.name, currentRoute.params, { reload: true });
145
+ *
146
+ * @example
147
+ * // Force re-fetch on same route with different query params
148
+ * // Note: query params are in path, not checked for equality
149
+ * router.navigate('search', { term: 'react' }, { reload: true });
150
+ *
151
+ * @see {@link force} for alternative that forces transition
152
+ * @see {@link Router.areStatesEqual} for state comparison logic
153
+ */
154
+ reload?: boolean | undefined;
155
+ /**
156
+ * Preview navigation without any side effects (dry-run mode).
157
+ *
158
+ * @description
159
+ * When `true`, returns the would-be target state via callback WITHOUT:
160
+ * - Executing canDeactivate/canActivate guards
161
+ * - Executing middleware
162
+ * - Updating router state (`router.getState()` remains unchanged)
163
+ * - Emitting any transition events (TRANSITION_START, TRANSITION_SUCCESS, etc.)
164
+ *
165
+ * The callback receives `(undefined, toState)` where `toState` is the computed
166
+ * target state that WOULD result from this navigation.
167
+ *
168
+ * @default false
169
+ *
170
+ * @remarks
171
+ * This option is useful for:
172
+ * - Validating that a route exists and params are correct
173
+ * - SSR: previewing state for pre-rendering without side effects
174
+ * - Dry-run before actual navigation
175
+ *
176
+ * @deprecated Consider using `router.buildState()` + `router.makeState()` instead
177
+ * for clearer intent. This option may be removed in a future major version.
178
+ *
179
+ * @example
180
+ * // Preview navigation - router.getState() is NOT changed
181
+ * router.navigate('users.view', { id: 123 }, { skipTransition: true }, (err, previewState) => {
182
+ * console.log(previewState); // { name: 'users.view', params: { id: 123 }, path: '/users/view/123', ... }
183
+ * console.log(router.getState()); // Still the previous state!
184
+ * });
185
+ *
186
+ * @example
187
+ * // Recommended alternative (clearer intent)
188
+ * const route = router.buildState('users.view', { id: 123 });
189
+ * if (route) {
190
+ * const path = router.buildPath(route.name, route.params);
191
+ * const previewState = router.makeState(route.name, route.params, path, { params: route.meta });
192
+ * }
193
+ *
194
+ * @see {@link forceDeactivate} for skipping only canDeactivate guards
195
+ * @see {@link force} for forcing navigation while preserving lifecycle
196
+ */
197
+ skipTransition?: boolean | undefined;
198
+ /**
199
+ * Force navigation even if target state equals current state.
200
+ *
201
+ * @description
202
+ * When `true`, bypasses the "same state" equality check but still executes the full
203
+ * transition lifecycle (unlike `skipTransition`). Similar to `reload` but can be used
204
+ * for any forced navigation scenario.
205
+ *
206
+ * Difference from `reload`:
207
+ * - `reload`: semantic meaning is "refresh current route"
208
+ * - `force`: general-purpose bypass of equality check
209
+ * - Both have identical implementation effect
210
+ *
211
+ * The equality check compares:
212
+ * - state.name (route name)
213
+ * - state.params (route parameters, shallow comparison)
214
+ *
215
+ * @default false
216
+ *
217
+ * @example
218
+ * // Force transition for tracking even if params didn't change
219
+ * router.navigate('analytics', { event: 'pageview' }, { force: true });
220
+ *
221
+ * @see {@link reload} for semantic equivalent (preferred for refresh scenarios)
222
+ * @see {@link skipTransition} for bypassing entire lifecycle
223
+ */
224
+ force?: boolean | undefined;
225
+ /**
226
+ * Skip canDeactivate guards during transition.
227
+ *
228
+ * @description
229
+ * When `true`, bypasses only the canDeactivate lifecycle hooks for segments being
230
+ * deactivated. canActivate guards and middleware still execute normally. This allows
231
+ * forcing navigation away from routes with confirmation dialogs or unsaved changes.
232
+ *
233
+ * Skipped vs executed:
234
+ * ```
235
+ * // Normal transition
236
+ * deactivate(fromSegments) → activate(toSegments) → middleware → success
237
+ *
238
+ * // With forceDeactivate: true
239
+ * [skip deactivate] → activate(toSegments) → middleware → success
240
+ * ```
241
+ *
242
+ * ⚠️ Data loss risk: Bypassing canDeactivate means unsaved changes will be lost
243
+ *
244
+ * @default false
245
+ *
246
+ * @example
247
+ * // Force logout even with unsaved changes
248
+ * function forceLogout() {
249
+ * router.navigate('login', {}, {
250
+ * forceDeactivate: true,
251
+ * replace: true
252
+ * });
253
+ * }
254
+ *
255
+ * @see {@link skipTransition} for bypassing all guards and middleware
256
+ * @see {@link Router.clearCanDeactivate} for programmatically clearing guards
257
+ */
258
+ forceDeactivate?: boolean | undefined;
259
+ /**
260
+ * Internal flag indicating navigation is result of a redirect.
261
+ *
262
+ * @internal
263
+ *
264
+ * @description
265
+ * Automatically set by the router when a navigation is triggered by a redirect from
266
+ * middleware or lifecycle hooks. This flag is used internally to track redirect chains
267
+ * and is stored in state.meta.redirected.
268
+ *
269
+ * @default false (auto-set by router during redirects)
270
+ *
271
+ * @example
272
+ * // Middleware triggers automatic redirect
273
+ * router.useMiddleware((toState, fromState, opts) => {
274
+ * if (!isAuthenticated && toState.name !== 'login') {
275
+ * // Router will automatically set redirected: true
276
+ * return { name: 'login', params: { next: toState.path } };
277
+ * }
278
+ * });
279
+ *
280
+ * @example
281
+ * // Accessing redirect flag in lifecycle
282
+ * router.canActivate('dashboard', (toState, fromState) => {
283
+ * if (toState.meta?.redirected) {
284
+ * console.log('This navigation is from a redirect');
285
+ * }
286
+ * return true;
287
+ * });
288
+ *
289
+ * @see {@link Router.navigate} for redirect handling implementation
290
+ * @see {@link State.meta.redirected} for redirect flag in state
291
+ */
292
+ redirected?: boolean | undefined;
293
+ }
294
+ export interface Params {
295
+ [key: string]: string | string[] | number | number[] | boolean | boolean[] | Params | Params[] | Record<string, string | number | boolean> | null | undefined;
296
+ }
297
+ /**
298
+ * Event type keys
299
+ */
300
+ export type EventsKeys = "ROUTER_START" | "ROUTER_STOP" | "TRANSITION_START" | "TRANSITION_CANCEL" | "TRANSITION_SUCCESS" | "TRANSITION_ERROR";
301
+ /**
302
+ * Error code values
303
+ */
304
+ export type ErrorCodeValues = "NOT_STARTED" | "NO_START_PATH_OR_STATE" | "ALREADY_STARTED" | "ROUTE_NOT_FOUND" | "SAME_STATES" | "CANNOT_DEACTIVATE" | "CANNOT_ACTIVATE" | "TRANSITION_ERR" | "CANCELLED";
305
+ /**
306
+ * Error code keys
307
+ */
308
+ export type ErrorCodeKeys = "ROUTER_NOT_STARTED" | "NO_START_PATH_OR_STATE" | "ROUTER_ALREADY_STARTED" | "ROUTE_NOT_FOUND" | "SAME_STATES" | "CANNOT_DEACTIVATE" | "CANNOT_ACTIVATE" | "TRANSITION_ERR" | "TRANSITION_CANCELLED";
309
+ /**
310
+ * Mapping of event keys to event names
311
+ */
312
+ export interface EventToNameMap {
313
+ ROUTER_START: "$start";
314
+ ROUTER_STOP: "$stop";
315
+ TRANSITION_START: "$$start";
316
+ TRANSITION_CANCEL: "$$cancel";
317
+ TRANSITION_SUCCESS: "$$success";
318
+ TRANSITION_ERROR: "$$error";
319
+ }
320
+ /**
321
+ * Mapping of error code keys to their values
322
+ */
323
+ export interface ErrorCodeToValueMap {
324
+ ROUTER_NOT_STARTED: "NOT_STARTED";
325
+ NO_START_PATH_OR_STATE: "NO_START_PATH_OR_STATE";
326
+ ROUTER_ALREADY_STARTED: "ALREADY_STARTED";
327
+ ROUTE_NOT_FOUND: "ROUTE_NOT_FOUND";
328
+ SAME_STATES: "SAME_STATES";
329
+ CANNOT_DEACTIVATE: "CANNOT_DEACTIVATE";
330
+ CANNOT_ACTIVATE: "CANNOT_ACTIVATE";
331
+ TRANSITION_ERR: "TRANSITION_ERR";
332
+ TRANSITION_CANCELLED: "CANCELLED";
333
+ }
334
+ /**
335
+ * Log message severity level.
336
+ *
337
+ * Ordered by severity (lowest to highest):
338
+ * - `log`: Informational messages, debugging, trace
339
+ * - `warn`: Warnings, deprecations, non-critical issues
340
+ * - `error`: Critical errors, exceptions, failures
341
+ *
342
+ * @example
343
+ * ```ts
344
+ * const level: LogLevel = 'warn';
345
+ * logger[level]('Router', 'Message'); // Calls logger.warn()
346
+ * ```
347
+ */
348
+ export type LogLevel = "log" | "warn" | "error";
349
+ /**
350
+ * Logger threshold configuration level.
351
+ *
352
+ * Determines which messages are displayed based on severity:
353
+ * - `all`: Show all messages (log, warn, error)
354
+ * - `warn-error`: Show only warnings and errors (filter out log)
355
+ * - `error-only`: Show only errors (filter out log and warn)
356
+ * - `none`: Show no messages (completely silent, unless callback ignores level)
357
+ *
358
+ * Note: Higher threshold = fewer messages shown.
359
+ *
360
+ * @example
361
+ * ```ts
362
+ * // Production: only show errors
363
+ * logger.configure({ level: 'error-only' });
364
+ *
365
+ * // Development: show everything
366
+ * logger.configure({ level: 'all' });
367
+ * ```
368
+ */
369
+ export type LogLevelConfig = "all" | "warn-error" | "error-only" | "none";
370
+ /**
371
+ * Callback function type for custom log processing.
372
+ *
373
+ * Receives all log messages that pass the configured level threshold
374
+ * (unless `callbackIgnoresLevel` is true, then receives all messages).
375
+ *
376
+ * Common use cases:
377
+ * - Send logs to external analytics service
378
+ * - Store logs in memory for debugging
379
+ * - Filter and forward to remote logging system
380
+ * - Display logs in custom UI component
381
+ *
382
+ * @param level - Severity level of this message
383
+ * @param context - Context/module identifier (e.g., 'Router', 'Plugin')
384
+ * @param message - Main log message text
385
+ * @param args - Additional arguments (objects, errors, etc.)
386
+ *
387
+ * @example
388
+ * ```ts
389
+ * const analyticsCallback: LogCallback = (level, context, message, ...args) => {
390
+ * sendToAnalytics({
391
+ * severity: level,
392
+ * module: context,
393
+ * text: message,
394
+ * metadata: args
395
+ * });
396
+ * };
397
+ *
398
+ * logger.configure({ callback: analyticsCallback });
399
+ * ```
400
+ */
401
+ export type LogCallback = (level: LogLevel, context: string, message: string, ...args: unknown[]) => void;
402
+ /**
403
+ * Logger configuration interface.
404
+ *
405
+ * Controls both console output and callback behavior.
406
+ *
407
+ * @example
408
+ * ```ts
409
+ * // Minimal configuration
410
+ * const config: LoggerConfig = {
411
+ * level: 'warn-error'
412
+ * };
413
+ *
414
+ * // Full configuration with callback
415
+ * const config: LoggerConfig = {
416
+ * level: 'error-only',
417
+ * callback: (level, context, message) => {
418
+ * // Send all errors to monitoring service
419
+ * },
420
+ * callbackIgnoresLevel: false // Callback respects 'error-only' level
421
+ * };
422
+ * ```
423
+ */
424
+ export interface LoggerConfig {
425
+ /**
426
+ * Minimum severity level to display in console.
427
+ *
428
+ * Messages below this threshold are filtered out from console output.
429
+ * Does not affect callback unless `callbackIgnoresLevel` is false.
430
+ *
431
+ * @default 'all'
432
+ */
433
+ level: LogLevelConfig;
434
+ /**
435
+ * Optional callback function for custom log processing.
436
+ *
437
+ * Called for each log message (subject to `callbackIgnoresLevel` setting).
438
+ * Can be undefined to disable callback processing.
439
+ *
440
+ * @default undefined
441
+ */
442
+ callback?: LogCallback | undefined;
443
+ /**
444
+ * Whether callback should receive ALL messages regardless of level threshold.
445
+ *
446
+ * - `false` (default): Callback only receives messages that pass level threshold
447
+ * (same filtering as console output)
448
+ * - `true`: Callback receives ALL messages, even those filtered from console
449
+ * (useful for analytics where you want to track everything)
450
+ *
451
+ * @default false
452
+ *
453
+ * @example
454
+ * ```ts
455
+ * // Scenario: Show only errors in console, but track ALL logs in analytics
456
+ * logger.configure({
457
+ * level: 'error-only', // Console: only errors
458
+ * callback: sendToAnalytics,
459
+ * callbackIgnoresLevel: true // Callback: receives log/warn/error
460
+ * });
461
+ * ```
462
+ */
463
+ callbackIgnoresLevel?: boolean;
464
+ }
465
+ /**
466
+ * Extended build result that includes segments for path building.
467
+ * Used internally to avoid duplicate getSegmentsByName calls.
468
+ *
469
+ * @param segments - Route segments from getSegmentsByName (typed as unknown[] for cross-package compatibility)
470
+ * @internal
471
+ */
472
+ export interface BuildStateResultWithSegments<P extends Params = Params> {
473
+ readonly state: RouteTreeState<P>;
474
+ readonly segments: readonly unknown[];
475
+ }
476
+ /**
477
+ * Route configuration.
478
+ */
479
+ export interface Route<Dependencies extends DefaultDependencies = DefaultDependencies> {
480
+ [key: string]: unknown;
481
+ /** Route name (dot-separated for nested routes). */
482
+ name: string;
483
+ /** URL path pattern for this route. */
484
+ path: string;
485
+ /** Factory function that returns a guard for route activation. */
486
+ canActivate?: ActivationFnFactory<Dependencies>;
487
+ /**
488
+ * Redirects navigation to another route.
489
+ *
490
+ * IMPORTANT: forwardTo creates a URL alias, not a transition chain.
491
+ * Guards (canActivate) on the source route are NOT executed.
492
+ * Only guards on the final destination are executed.
493
+ *
494
+ * This matches Vue Router and Angular Router behavior.
495
+ *
496
+ * @example
497
+ * // Correct: guard on target
498
+ * { name: "old", path: "/old", forwardTo: "new" }
499
+ * { name: "new", path: "/new", canActivate: myGuard }
500
+ *
501
+ * // Wrong: guard on source (will be ignored with warning)
502
+ * { name: "old", path: "/old", forwardTo: "new", canActivate: myGuard }
503
+ */
504
+ forwardTo?: string;
505
+ /** Nested child routes. */
506
+ children?: Route<Dependencies>[];
507
+ /** Encodes state params to URL params. */
508
+ encodeParams?: (stateParams: Params) => Params;
509
+ /** Decodes URL params to state params. */
510
+ decodeParams?: (pathParams: Params) => Params;
511
+ /**
512
+ * Default parameters for this route.
513
+ *
514
+ * @remarks
515
+ * **Type Contract:**
516
+ * The type of defaultParams MUST match the expected params type P
517
+ * when using `router.makeState<P>()` or `router.navigate<P>()`.
518
+ *
519
+ * These values are merged into state.params when creating route states.
520
+ * Missing URL params are filled from defaultParams.
521
+ *
522
+ * @example
523
+ * ```typescript
524
+ * // Define route with pagination defaults
525
+ * {
526
+ * name: "users",
527
+ * path: "/users",
528
+ * defaultParams: { page: 1, limit: 10 }
529
+ * }
530
+ *
531
+ * // Navigate without specifying page/limit
532
+ * router.navigate("users", { filter: "active" });
533
+ * // Result: state.params = { page: 1, limit: 10, filter: "active" }
534
+ *
535
+ * // Correct typing — include defaultParams properties
536
+ * type UsersParams = { page: number; limit: number; filter?: string };
537
+ * ```
538
+ */
539
+ defaultParams?: Params;
540
+ }
541
+ /**
542
+ * Router configuration options.
543
+ *
544
+ * Note: For input, use `Partial<Options>` as all fields have defaults.
545
+ * After initialization, `getOptions()` returns resolved `Options` with all fields populated.
546
+ */
547
+ export interface Options {
548
+ /**
549
+ * Default route to navigate to on start.
550
+ * Empty string means no default route.
551
+ *
552
+ * @default ""
553
+ */
554
+ defaultRoute: string;
555
+ /**
556
+ * Default parameters for the default route.
557
+ *
558
+ * @default {}
559
+ */
560
+ defaultParams: Params;
561
+ /**
562
+ * How to handle trailing slashes in URLs.
563
+ * - "strict": Route must match exactly
564
+ * - "never": Always remove trailing slash
565
+ * - "always": Always add trailing slash
566
+ * - "preserve": Keep as provided
567
+ *
568
+ * @default "preserve"
569
+ */
570
+ trailingSlash: "strict" | "never" | "always" | "preserve";
571
+ /**
572
+ * Whether route names are case-sensitive.
573
+ *
574
+ * @default false
575
+ */
576
+ caseSensitive: boolean;
577
+ /**
578
+ * How to encode URL parameters.
579
+ * - "default": Standard encoding
580
+ * - "uri": URI encoding (encodeURI)
581
+ * - "uriComponent": Component encoding (encodeURIComponent)
582
+ * - "none": No encoding
583
+ *
584
+ * @default "default"
585
+ */
586
+ urlParamsEncoding: "default" | "uri" | "uriComponent" | "none";
587
+ /**
588
+ * How to handle query parameters.
589
+ *
590
+ * @default "loose"
591
+ */
592
+ queryParamsMode: QueryParamsMode;
593
+ /**
594
+ * Query parameter parsing options.
595
+ *
596
+ * @default undefined
597
+ */
598
+ queryParams?: QueryParamsOptions;
599
+ /**
600
+ * Allow matching routes that don't exist.
601
+ * When true, unknown routes navigate without error.
602
+ *
603
+ * @default true
604
+ */
605
+ allowNotFound: boolean;
606
+ /**
607
+ * Rewrite path on successful match.
608
+ *
609
+ * @default false
610
+ */
611
+ rewritePathOnMatch: boolean;
612
+ /**
613
+ * Logger configuration.
614
+ *
615
+ * @default undefined
616
+ */
617
+ logger?: Partial<LoggerConfig>;
618
+ }
619
+ export type ActivationFn = (toState: State, fromState: State | undefined, done: DoneFn) => boolean | Promise<boolean | object | void> | State | void;
620
+ export type ActivationFnFactory<Dependencies extends DefaultDependencies = DefaultDependencies> = (router: Router<Dependencies>, getDependency: <K extends keyof Dependencies>(key: K) => Dependencies[K]) => ActivationFn;
621
+ export type DefaultDependencies = object;
622
+ export interface Config {
623
+ decoders: Record<string, (params: Params) => Params>;
624
+ encoders: Record<string, (params: Params) => Params>;
625
+ defaultParams: Record<string, Params>;
626
+ forwardMap: Record<string, string>;
627
+ }
628
+ /**
629
+ * Configuration update options for updateRoute().
630
+ * All properties are optional. Set to null to remove the configuration.
631
+ */
632
+ export interface RouteConfigUpdate<Dependencies extends DefaultDependencies = DefaultDependencies> {
633
+ /** Set to null to remove forwardTo */
634
+ forwardTo?: string | null;
635
+ /** Set to null to remove defaultParams */
636
+ defaultParams?: Params | null;
637
+ /** Set to null to remove decoder */
638
+ decodeParams?: ((params: Params) => Params) | null;
639
+ /** Set to null to remove encoder */
640
+ encodeParams?: ((params: Params) => Params) | null;
641
+ /** Set to null to remove canActivate */
642
+ canActivate?: ActivationFnFactory<Dependencies> | null;
643
+ }
644
+ export interface Router<Dependencies extends DefaultDependencies = DefaultDependencies> {
645
+ [key: symbol]: unknown;
646
+ [key: string]: unknown;
647
+ addRoute: (routes: Route<Dependencies>[] | Route<Dependencies>) => Router<Dependencies>;
648
+ isActiveRoute: (name: string, params?: Params, strictEquality?: boolean, ignoreQueryParams?: boolean) => boolean;
649
+ buildPath: (route: string, params?: Params) => string;
650
+ /**
651
+ * Internal path builder that accepts pre-computed segments.
652
+ * Avoids duplicate getSegmentsByName call when segments are already available.
653
+ *
654
+ * @param segments - Route segments from getSegmentsByName (typed as unknown[] for cross-package compatibility)
655
+ * @internal
656
+ */
657
+ buildPathWithSegments: (route: string, params: Params, segments: readonly unknown[]) => string;
658
+ matchPath: <P extends Params = Params, MP extends Params = Params>(path: string, source?: string) => State<P, MP> | undefined;
659
+ /**
660
+ * Sets the root path for the router.
661
+ *
662
+ * @param rootPath - New root path
663
+ * @returns void
664
+ */
665
+ setRootPath: (rootPath: string) => void;
666
+ /**
667
+ * Gets the current root path for the router.
668
+ *
669
+ * @returns Current root path
670
+ */
671
+ getRootPath: () => string;
672
+ /**
673
+ * Removes route configurations (metadata only).
674
+ *
675
+ * @description
676
+ * Clears associated configurations for a route (decoders, encoders, defaultParams,
677
+ * forwardMap). Note: RouteNode doesn't provide API for actual route removal from tree.
678
+ * Consider recreating the router with filtered routes for full removal.
679
+ *
680
+ * @param name - Route name to remove configurations for
681
+ * @returns Router instance for chaining
682
+ * @throws {TypeError} If name is not a valid route name
683
+ */
684
+ removeRoute: (name: string) => Router<Dependencies>;
685
+ /**
686
+ * Clears all routes from the router.
687
+ *
688
+ * @description
689
+ * Removes all route definitions, configurations, and lifecycle handlers.
690
+ * Preserves: listeners, plugins, dependencies, options, state.
691
+ * After clearing, you can add new routes with addRoute().
692
+ *
693
+ * @returns Router instance for chaining
694
+ *
695
+ * @example
696
+ * // Clear all routes and add new ones
697
+ * router.clearRoutes().addRoute([
698
+ * { name: 'home', path: '/' },
699
+ * { name: 'about', path: '/about' }
700
+ * ]);
701
+ */
702
+ clearRoutes: () => Router<Dependencies>;
703
+ /**
704
+ * Retrieves the full configuration of a route by name.
705
+ *
706
+ * @description
707
+ * Reconstructs the Route object from internal storage, including:
708
+ * - name, path, children from route definitions
709
+ * - forwardTo from forwardMap
710
+ * - defaultParams, decodeParams, encodeParams from config
711
+ * - canActivate from lifecycle factories
712
+ *
713
+ * Note: Custom properties (meta, etc.) are NOT preserved and won't be returned.
714
+ *
715
+ * @param name - Route name (dot-notation for nested routes, e.g., 'users.profile')
716
+ * @returns Route configuration or undefined if not found
717
+ *
718
+ * @throws {TypeError} If name is not a valid route name
719
+ *
720
+ * @example
721
+ * const route = router.getRoute('users.profile');
722
+ * if (route) {
723
+ * console.log(route.path, route.defaultParams);
724
+ * }
725
+ */
726
+ getRoute: (name: string) => Route<Dependencies> | undefined;
727
+ /**
728
+ * Checks if a route exists in the router.
729
+ *
730
+ * @description
731
+ * Lightweight check for route existence without constructing the full Route object.
732
+ * More efficient than `!!router.getRoute(name)` when you only need to check existence.
733
+ *
734
+ * @param name - Route name to check (supports dot notation for nested routes)
735
+ * @returns true if route exists, false otherwise
736
+ *
737
+ * @throws {TypeError} If name is not a valid route name
738
+ *
739
+ * @example
740
+ * if (router.hasRoute('users.profile')) {
741
+ * router.navigate('users.profile', { id: 123 });
742
+ * }
743
+ */
744
+ hasRoute: (name: string) => boolean;
745
+ /**
746
+ * Updates configuration properties of an existing route.
747
+ *
748
+ * @description
749
+ * Only updates configuration (forwardTo, defaultParams, encoders, decoders, canActivate).
750
+ * Does NOT update path or children (requires tree rebuild - use removeRoute + addRoute).
751
+ *
752
+ * Set a property to null to remove it. For example:
753
+ * - `{ forwardTo: null }` removes the forwardTo redirect
754
+ * - `{ canActivate: null }` removes the canActivate guard
755
+ *
756
+ * @param name - Route name to update
757
+ * @param updates - Partial route configuration to apply
758
+ * @returns Router instance for chaining
759
+ *
760
+ * @throws {TypeError} If name is not a valid route name
761
+ * @throws {ReferenceError} If route does not exist
762
+ * @throws {Error} If updating forwardTo with invalid target or cycle
763
+ *
764
+ * @example
765
+ * // Add/update configuration
766
+ * router.updateRoute('users', {
767
+ * defaultParams: { page: 1 },
768
+ * canActivate: authGuard
769
+ * });
770
+ *
771
+ * @example
772
+ * // Remove configuration
773
+ * router.updateRoute('oldRoute', { forwardTo: null });
774
+ */
775
+ updateRoute: (name: string, updates: RouteConfigUpdate<Dependencies>) => Router<Dependencies>;
776
+ /**
777
+ * Returns a copy of the previous state before the last navigation.
778
+ *
779
+ * @returns Copy of the previous state or undefined if no previous state exists
780
+ */
781
+ getPreviousState: () => State | undefined;
782
+ shouldUpdateNode: (nodeName: string) => (toState: State, fromState?: State) => boolean;
783
+ /**
784
+ * Returns a copy of the router's current configuration options.
785
+ *
786
+ * @description
787
+ * Provides read-only access to the router's configuration by returning a shallow
788
+ * copy of all current options. This method is useful for inspecting settings,
789
+ * debugging, passing configuration to other components, or conditional logic
790
+ * based on router configuration.
791
+ *
792
+ * @returns A shallow copy of the current router options. Each call returns
793
+ * a new object with all configuration properties.
794
+ *
795
+ * @example
796
+ * // Basic usage - inspect configuration
797
+ * const options = router.getOptions();
798
+ * console.log('Case sensitive:', options.caseSensitive);
799
+ * console.log('Trailing slash mode:', options.trailingSlash);
800
+ *
801
+ * @see {@link setOption} for modifying individual options
802
+ */
803
+ getOptions: () => Options;
804
+ /**
805
+ * Sets a single configuration option value.
806
+ *
807
+ * @description
808
+ * Modifies an individual router configuration option with type-safe validation.
809
+ * This method can ONLY be used before calling router.start() - after the router
810
+ * starts, all options become immutable and any attempt to modify them will throw
811
+ * an error.
812
+ *
813
+ * @param option - The name of the option to set. Must be a valid option key.
814
+ * @param value - The new value for the option. Type must match the option's expected type.
815
+ *
816
+ * @returns The router instance for method chaining.
817
+ *
818
+ * @throws {Error} If router is already started (router.isStarted() === true)
819
+ * @throws {ReferenceError} If option name doesn't exist in Options interface
820
+ * @throws {TypeError} If value type doesn't match expected type for the option
821
+ * @throws {TypeError} If object option receives non-plain object (array, date, class, null)
822
+ *
823
+ * @see {@link getOptions} for retrieving current options
824
+ */
825
+ setOption: (option: keyof Options, value: Options[keyof Options]) => Router<Dependencies>;
826
+ makeState: <P extends Params = Params, MP extends Params = Params>(name: string, params?: P, path?: string, meta?: StateMetaInput<MP>, forceId?: number) => State<P, MP>;
827
+ makeNotFoundState: (path: string, options?: NavigationOptions) => State;
828
+ getState: <P extends Params = Params, MP extends Params = Params>() => State<P, MP> | undefined;
829
+ setState: <P extends Params = Params, MP extends Params = Params>(state?: State<P, MP>) => void;
830
+ areStatesEqual: (state1: State | undefined, state2: State | undefined, ignoreQueryParams?: boolean) => boolean;
831
+ areStatesDescendants: (parentState: State, childState: State) => boolean;
832
+ forwardState: <P extends Params = Params>(routeName: string, routeParams: P) => SimpleState<P>;
833
+ buildState: (routeName: string, routeParams: Params) => RouteTreeState | undefined;
834
+ /**
835
+ * Builds state with segments for internal use.
836
+ * Avoids duplicate getSegmentsByName call when path building is needed.
837
+ *
838
+ * @internal
839
+ */
840
+ buildStateWithSegments: <P extends Params = Params>(routeName: string, routeParams: P) => BuildStateResultWithSegments<P> | undefined;
841
+ /**
842
+ * Checks whether the router has been successfully started.
843
+ *
844
+ * @description
845
+ * Returns true if the router has been started via the `start()` method and has not
846
+ * been stopped. When the router is started, it means:
847
+ * - Initial navigation has been attempted
848
+ * - Event listeners can receive navigation events
849
+ * - The router is ready to handle navigation requests
850
+ *
851
+ * Note: A router being "started" doesn't guarantee that the initial navigation
852
+ * succeeded. Use `getState()` to verify if a valid state exists.
853
+ *
854
+ * @returns true if the router is started, false otherwise
855
+ *
856
+ * @example
857
+ * // Check if router is started before navigation
858
+ * if (!router.isStarted()) {
859
+ * router.start('/home');
860
+ * }
861
+ *
862
+ * @example
863
+ * // Conditional logic based on router state
864
+ * const isReady = router.isStarted() && router.getState() !== undefined;
865
+ */
866
+ isStarted: () => boolean;
867
+ /**
868
+ * Checks if the router is active (starting or started).
869
+ *
870
+ * @description
871
+ * Returns true if the router is in the process of starting or has already started.
872
+ * This is different from `isStarted()` which only returns true after successful
873
+ * initial transition.
874
+ *
875
+ * This method is primarily used internally by the transition module to determine
876
+ * if transitions should be cancelled. During the initial start transition,
877
+ * `isStarted()` is false but `isActive()` is true, allowing the transition to proceed.
878
+ *
879
+ * @returns true if router is active (starting or started), false if stopped
880
+ *
881
+ * @example
882
+ * // Check if router is active (even during initial start)
883
+ * if (router.isActive()) {
884
+ * console.log('Router is active');
885
+ * }
886
+ *
887
+ * @see {@link isStarted} to check if initial transition completed
888
+ * @see https://github.com/greydragon888/real-router/issues/50
889
+ */
890
+ isActive: () => boolean;
891
+ /**
892
+ * Checks if a navigation transition is currently in progress.
893
+ *
894
+ * @description
895
+ * Returns true when the router is actively processing a navigation request.
896
+ * This includes the time spent executing guards (canDeactivate, canActivate)
897
+ * and middleware functions.
898
+ *
899
+ * Useful for:
900
+ * - Preventing route modifications during navigation
901
+ * - Showing loading indicators
902
+ * - Debouncing navigation requests
903
+ *
904
+ * @returns true if navigation is in progress, false otherwise
905
+ *
906
+ * @example
907
+ * // Prevent route removal during navigation
908
+ * if (router.isNavigating()) {
909
+ * console.warn('Cannot modify routes during navigation');
910
+ * return;
911
+ * }
912
+ *
913
+ * @example
914
+ * // Show loading state
915
+ * const isLoading = router.isNavigating();
916
+ *
917
+ * @remarks
918
+ * After FSM migration (RFC-2), this will use RouterState.TRANSITIONING
919
+ * for more granular state tracking.
920
+ */
921
+ isNavigating: () => boolean;
922
+ /**
923
+ * Initializes the router and performs the initial navigation.
924
+ *
925
+ * @description
926
+ * Starts the router and navigates to the initial route. This method must be called
927
+ * before any navigation operations. The initial route can be specified as a path
928
+ * string, a state object, or determined by the default route option.
929
+ *
930
+ * @param startPathOrState - Optional. The initial route as a path string or state object.
931
+ * If omitted, uses the default route if configured.
932
+ * @param done - Optional. Callback function called when start completes or fails.
933
+ *
934
+ * @returns The router instance for method chaining
935
+ *
936
+ * @example
937
+ * router.start()
938
+ *
939
+ * @example
940
+ * router.start('/users/123', (err, state) => {
941
+ * if (!err) console.log('Started at:', state.name)
942
+ * })
943
+ */
944
+ start: (() => Router<Dependencies>) & ((done: DoneFn) => Router<Dependencies>) & ((startPathOrState: string | State) => Router<Dependencies>) & ((startPathOrState: string | State, done: DoneFn) => Router<Dependencies>);
945
+ /**
946
+ * Stops the router and cleans up its state.
947
+ *
948
+ * @description
949
+ * Stops the router, clearing the current state and preventing further navigation.
950
+ * This method should be called when the router is no longer needed, typically
951
+ * during application cleanup or before unmounting.
952
+ *
953
+ * If the router is not started, this method does nothing and returns silently.
954
+ *
955
+ * @returns The router instance for method chaining
956
+ *
957
+ * @example
958
+ * // Stop the router
959
+ * router.stop();
960
+ *
961
+ * @fires ROUTER_STOP - When the router is successfully stopped
962
+ *
963
+ * @see {@link start} to restart the router
964
+ * @see {@link isStarted} to check router status
965
+ */
966
+ stop: () => Router<Dependencies>;
967
+ canDeactivate: (name: string, canDeactivateHandler: ActivationFnFactory<Dependencies> | boolean) => Router<Dependencies>;
968
+ clearCanDeactivate: (name: string, silent?: boolean) => Router<Dependencies>;
969
+ canActivate: (name: string, canActivateHandler: ActivationFnFactory<Dependencies> | boolean) => Router<Dependencies>;
970
+ clearCanActivate: (name: string, silent?: boolean) => Router<Dependencies>;
971
+ getLifecycleFactories: () => [
972
+ Record<string, ActivationFnFactory<Dependencies>>,
973
+ Record<string, ActivationFnFactory<Dependencies>>
974
+ ];
975
+ getLifecycleFunctions: () => [
976
+ Map<string, ActivationFn>,
977
+ Map<string, ActivationFn>
978
+ ];
979
+ /**
980
+ * Registers plugin(s) to extend router functionality through lifecycle event subscriptions.
981
+ *
982
+ * @description
983
+ * Provides the primary mechanism for adding cross-cutting functionality to the router
984
+ * through a plugin-based architecture. Plugins can react to router lifecycle events
985
+ * (start/stop, navigation transitions) without modifying the core router code.
986
+ *
987
+ * @param plugins - Variable number of plugin factory functions.
988
+ * Each factory receives (router, getDependency) and must return
989
+ * a Plugin object with optional event handler methods.
990
+ *
991
+ * @returns Unsubscribe function that removes only the plugins registered in this call.
992
+ * Calls teardown() for each plugin and removes all event subscriptions.
993
+ * Safe to call multiple times (subsequent calls are no-op with error logging).
994
+ *
995
+ * @throws {TypeError} If any plugin parameter is not a function
996
+ * @throws {TypeError} If any factory returns a non-object value
997
+ * @throws {TypeError} If returned plugin object contains unknown properties
998
+ * @throws {Error} If any plugin factory is already registered (duplicate by reference)
999
+ * @throws {Error} If total plugin count would exceed 50 after registration
1000
+ * @throws {*} Rethrows any exception thrown by factory functions (after rollback)
1001
+ *
1002
+ * @example
1003
+ * // Basic logging plugin
1004
+ * const loggingPlugin = (router) => ({
1005
+ * onTransitionStart: (toState, fromState) => {
1006
+ * console.log(`Navigating: ${fromState?.name} → ${toState.name}`);
1007
+ * },
1008
+ * onTransitionSuccess: (toState) => {
1009
+ * console.log(`Arrived at: ${toState.name}`);
1010
+ * },
1011
+ * });
1012
+ *
1013
+ * @example
1014
+ * // Remove plugin
1015
+ * const remove = router.usePlugin(loggerPlugin)
1016
+ * remove() // Stop logging
1017
+ *
1018
+ * const unsubscribe = router.usePlugin(loggingPlugin);
1019
+ *
1020
+ * @see {@link getPlugins} for retrieving registered plugin factories (internal use)
1021
+ * @see {@link useMiddleware} for navigation-specific middleware (different from plugins)
1022
+ * @see {@link addEventListener} for low-level event subscription
1023
+ */
1024
+ usePlugin: (...plugins: PluginFactory<Dependencies>[]) => Unsubscribe;
1025
+ getPlugins: () => PluginFactory<Dependencies>[];
1026
+ /**
1027
+ * Registers middleware functions to execute during navigation transitions.
1028
+ *
1029
+ * @description
1030
+ * Provides the primary mechanism for adding custom logic to the navigation pipeline
1031
+ * through middleware functions. Middleware execute after lifecycle hooks (canActivate/
1032
+ * canDeactivate) and can modify or validate state during route transitions.
1033
+ *
1034
+ * @param middlewares - Variable number of middleware factory functions.
1035
+ * Each factory receives (router, getDependency) and must return
1036
+ * a middleware function with signature:
1037
+ * (toState, fromState, done) => void | Promise<State | boolean | void>
1038
+ *
1039
+ * @returns Unsubscribe function that removes only the middleware registered in this call.
1040
+ * Safe to call multiple times (subsequent calls are no-op with warnings).
1041
+ *
1042
+ * @throws {TypeError} If any middleware parameter is not a function
1043
+ * @throws {TypeError} If any factory returns a non-function value
1044
+ * @throws {Error} If any middleware factory is already registered (duplicate)
1045
+ * @throws {Error} If total middleware count would exceed 50 after registration
1046
+ * @throws {*} Rethrows any exception thrown by factory functions during initialization
1047
+ *
1048
+ * @example
1049
+ *
1050
+ * router.useMiddleware((router) => (toState, fromState, done) => {
1051
+ * console.log('Navigating to:', toState.name)
1052
+ * done()
1053
+ * })
1054
+ *
1055
+ * @example
1056
+ * // Auth middleware
1057
+ * router.useMiddleware(() => (toState, fromState, done) => {
1058
+ * if (toState.meta.requiresAuth && !isAuthenticated()) {
1059
+ * done({ redirect: { name: 'login' } })
1060
+ * } else {
1061
+ * done()
1062
+ * }
1063
+ * })
1064
+ */
1065
+ useMiddleware: (...middlewares: MiddlewareFactory<Dependencies>[]) => Unsubscribe;
1066
+ clearMiddleware: () => Router<Dependencies>;
1067
+ getMiddlewareFactories: () => MiddlewareFactory<Dependencies>[];
1068
+ getMiddlewareFunctions: () => Middleware[];
1069
+ setDependency: <K extends keyof Dependencies & string>(dependencyName: K, dependency: Dependencies[K]) => Router<Dependencies>;
1070
+ /**
1071
+ * Sets multiple dependencies at once using a batch operation.
1072
+ *
1073
+ * @description
1074
+ * Provides an optimized way to register multiple dependencies in a single operation.
1075
+ * This method is the primary approach for initializing dependencies during router
1076
+ * setup and for bulk updates of the dependency container.
1077
+ *
1078
+ * @param deps - Object containing dependencies to set. Must be a plain object.
1079
+ * Properties with undefined values are ignored (not set).
1080
+ * All other values (including null, false, 0) are set.
1081
+ *
1082
+ * @returns The router instance for method chaining.
1083
+ *
1084
+ * @throws {TypeError} If deps is not a plain object (e.g., class instance, array, null)
1085
+ * @throws {TypeError} If any property in deps has a getter (accessor property)
1086
+ * @throws {Error} If total dependencies would exceed 100 after the operation
1087
+ *
1088
+ * @example
1089
+ * // Basic batch setup
1090
+ * router.setDependencies({
1091
+ * api: new ApiService(),
1092
+ * logger: console,
1093
+ * cache: cacheService,
1094
+ * });
1095
+ *
1096
+ * @see {@link setDependency} for setting individual dependencies
1097
+ * @see {@link getDependencies} for retrieving all dependencies
1098
+ * @see {@link resetDependencies} for clearing all dependencies
1099
+ * @see {@link removeDependency} for removing specific dependencies
1100
+ */
1101
+ setDependencies: (deps: Dependencies) => Router<Dependencies>;
1102
+ /**
1103
+ * Retrieves a dependency from the router's dependency container by name.
1104
+ *
1105
+ * @description
1106
+ * Provides type-safe access to dependencies registered in the router's dependency
1107
+ * injection container. This method is the primary way to access services and utilities
1108
+ * within middleware, plugins, and lifecycle hooks.
1109
+ *
1110
+ * @template K - The dependency name, must be a key of the Dependencies type
1111
+ *
1112
+ * @param key - The name of the dependency to retrieve. Must be a string and
1113
+ * must exist in the Dependencies type definition.
1114
+ *
1115
+ * @returns The dependency value with proper type inference based on Dependencies type.
1116
+ * Returns the same reference on repeated calls (not a copy).
1117
+ *
1118
+ * @throws {TypeError} If the key parameter is not a string type
1119
+ * (e.g., number, object, null, undefined)
1120
+ * @throws {ReferenceError} If no dependency exists with the given name.
1121
+ * Error message includes the dependency name for debugging.
1122
+ *
1123
+ * @example
1124
+ * // Basic usage - direct access
1125
+ * interface MyDependencies {
1126
+ * api: ApiService;
1127
+ * logger: Logger;
1128
+ * }
1129
+ *
1130
+ * router.setDependency('api', new ApiService());
1131
+ * const api = router.getDependency('api'); // Type: ApiService
1132
+ *
1133
+ * @see {@link getDependencies} for retrieving all dependencies at once
1134
+ * @see {@link setDependency} for registering dependencies
1135
+ * @see {@link hasDependency} for checking dependency existence
1136
+ * @see {@link removeDependency} for removing dependencies
1137
+ */
1138
+ getDependency: <K extends keyof Dependencies>(key: K) => Dependencies[K];
1139
+ /**
1140
+ * Returns a shallow copy of all registered dependencies.
1141
+ *
1142
+ * @description
1143
+ * Retrieves a snapshot of all dependencies currently stored in the router's
1144
+ * dependency container. The method creates a new object on each call, protecting
1145
+ * the internal container structure from external modifications.
1146
+ *
1147
+ * @returns A new object containing all dependencies as key-value pairs.
1148
+ * Returns {} if no dependencies are registered.
1149
+ *
1150
+ * @example
1151
+ * // Basic usage - get all dependencies
1152
+ * const deps = router.getDependencies();
1153
+ * console.log(deps); // { api: ApiService, logger: Logger }
1154
+ *
1155
+ * @see {@link getDependency} for accessing individual dependencies
1156
+ * @see {@link setDependency} for adding dependencies
1157
+ * @see {@link setDependencies} for batch setting
1158
+ * @see {@link removeDependency} for removing dependencies
1159
+ * @see {@link resetDependencies} for clearing all dependencies
1160
+ * @see {@link hasDependency} for checking dependency existence
1161
+ */
1162
+ getDependencies: () => Partial<Dependencies>;
1163
+ /**
1164
+ * Removes a dependency from the router's dependency container.
1165
+ *
1166
+ * @description
1167
+ * Safely removes a registered dependency by name. This method is idempotent,
1168
+ * meaning it can be called multiple times with the same dependency name without
1169
+ * causing errors. If the dependency doesn't exist, a warning is logged but
1170
+ * execution continues normally.
1171
+ *
1172
+ * @param dependencyName - The name of the dependency to remove.
1173
+ * Type-safe in TypeScript (must be a key of Dependencies).
1174
+ * Safe to call with non-existent dependencies (logs warning).
1175
+ *
1176
+ * @returns The router instance for method chaining.
1177
+ *
1178
+ * @example
1179
+ * // Basic removal
1180
+ * router.setDependency('tempLogger', logger);
1181
+ * router.removeDependency('tempLogger');
1182
+ *
1183
+ * console.log(router.hasDependency('tempLogger')); // false
1184
+ *
1185
+ * @see {@link setDependency} for adding dependencies
1186
+ * @see {@link getDependency} for retrieving dependencies (throws after removal)
1187
+ * @see {@link hasDependency} for checking dependency existence (returns false after removal)
1188
+ * @see {@link resetDependencies} for removing all dependencies at once
1189
+ */
1190
+ removeDependency: (dependencyName: keyof Dependencies) => Router<Dependencies>;
1191
+ /**
1192
+ * Checks whether a dependency with the specified name exists in the router.
1193
+ *
1194
+ * @description
1195
+ * Provides a safe way to check for dependency existence without throwing errors.
1196
+ * This method is essential for implementing conditional logic based on optional
1197
+ * dependencies and for validating dependency setup before accessing them.
1198
+ *
1199
+ * @param dependencyName - The name of the dependency to check.
1200
+ * Type-safe in TypeScript (must be a key of Dependencies).
1201
+ * In runtime, non-string primitives are coerced to strings.
1202
+ *
1203
+ * @returns true if the dependency exists (even with falsy values like null/false/0),
1204
+ * false if the dependency has never been set or was removed.
1205
+ *
1206
+ * @example
1207
+ * // Basic existence check
1208
+ * router.setDependency('api', apiService);
1209
+ * console.log(router.hasDependency('api')); // true
1210
+ * console.log(router.hasDependency('nonexistent')); // false
1211
+ *
1212
+ * const ready = hasAllDependencies(router, ['api', 'auth', 'logger']);
1213
+ *
1214
+ * @see {@link getDependency} for retrieving dependencies (throws if not found)
1215
+ * @see {@link getDependencies} for getting all dependencies at once
1216
+ * @see {@link setDependency} for registering dependencies
1217
+ * @see {@link removeDependency} for removing dependencies
1218
+ */
1219
+ hasDependency: (dependencyName: keyof Dependencies) => boolean;
1220
+ /**
1221
+ * Removes all dependencies from the router's dependency container.
1222
+ *
1223
+ * @description
1224
+ * Performs a complete reset of the dependency container by removing all registered
1225
+ * dependencies at once. This is a destructive operation that clears the entire
1226
+ * dependency state, effectively returning the container to its initial empty state.
1227
+ *
1228
+ * @returns The router instance for method chaining.
1229
+ *
1230
+ * @example
1231
+ * // Basic reset
1232
+ * router.setDependency('logger', logger);
1233
+ * router.setDependency('api', apiService);
1234
+ * router.setDependency('cache', cacheService);
1235
+ *
1236
+ * router.resetDependencies();
1237
+ *
1238
+ * console.log(router.getDependencies()); // {}
1239
+ * console.log(router.hasDependency('logger')); // false
1240
+ *
1241
+ * @see {@link setDependency} for adding individual dependencies
1242
+ * @see {@link setDependencies} for setting multiple dependencies at once
1243
+ * @see {@link removeDependency} for removing individual dependencies
1244
+ * @see {@link getDependencies} for getting all current dependencies
1245
+ * @see {@link hasDependency} for checking if specific dependency exists
1246
+ */
1247
+ resetDependencies: () => Router<Dependencies>;
1248
+ /**
1249
+ * Invokes all registered event listeners for a specific router lifecycle event.
1250
+ *
1251
+ * @internal
1252
+ * This is an internal method used by the router core. It should NOT be called
1253
+ * directly by application code. Events are automatically dispatched by router
1254
+ * methods like start(), stop(), navigate(), etc.
1255
+ *
1256
+ * @description
1257
+ * Synchronously invokes all registered event listeners for a given router lifecycle
1258
+ * event in their registration order (FIFO). The method provides critical guarantees:
1259
+ * fail-safe execution, state immutability, recursion protection, and iteration safety.
1260
+ *
1261
+ * @param eventName - The event type to invoke listeners for.
1262
+ * Must be one of: ROUTER_START, ROUTER_STOP, TRANSITION_START,
1263
+ * TRANSITION_SUCCESS, TRANSITION_ERROR, TRANSITION_CANCEL.
1264
+ *
1265
+ * @param toState - Target state for navigation events. Deep frozen before passing.
1266
+ * Optional for ROUTER_START/STOP, required for TRANSITION_*.
1267
+ *
1268
+ * @param fromState - Source state for navigation events. Deep frozen before passing.
1269
+ * Optional for all events (undefined for first navigation).
1270
+ *
1271
+ * @param arg - Additional event data:
1272
+ * - NavigationOptions for TRANSITION_SUCCESS
1273
+ * - RouterError for TRANSITION_ERROR
1274
+ * - undefined for other events
1275
+ *
1276
+ * @returns void - Method performs side effects (invokes listeners)
1277
+ *
1278
+ * @throws {Error} If recursion depth exceeds MAX_DEPTH (5) for the event type
1279
+ * @throws {TypeError} If state validation fails (invalid State object structure)
1280
+ *
1281
+ * @see {@link addEventListener} for subscribing to router events (public API)
1282
+ * @see {@link removeEventListener} for unsubscribing from events (public API)
1283
+ * @see {@link usePlugin} for plugin-based event handling (recommended)
1284
+ */
1285
+ invokeEventListeners: (eventName: EventToNameMap[EventsKeys], toState?: State, fromState?: State, arg?: RouterError | NavigationOptions) => void;
1286
+ /**
1287
+ * Checks if there are any listeners registered for a given event.
1288
+ *
1289
+ * @internal
1290
+ * Used for performance optimization to skip event emission when no listeners exist.
1291
+ * This avoids the overhead of argument validation and event dispatch when
1292
+ * there are no subscribers.
1293
+ *
1294
+ * @param eventName - The event type to check for listeners. Must be one of the
1295
+ * predefined event constants.
1296
+ *
1297
+ * @returns true if at least one listener is registered for the event, false otherwise.
1298
+ * Returns false for invalid event names instead of throwing.
1299
+ *
1300
+ * @example
1301
+ * ```typescript
1302
+ * // Skip expensive event emission if no listeners
1303
+ * if (router.hasListeners(events.TRANSITION_ERROR)) {
1304
+ * router.invokeEventListeners(events.TRANSITION_ERROR, toState, fromState, error);
1305
+ * }
1306
+ * ```
1307
+ *
1308
+ * @see {@link invokeEventListeners} for the internal event dispatch mechanism
1309
+ * @see {@link addEventListener} for registering event listeners
1310
+ */
1311
+ hasListeners: (eventName: EventToNameMap[EventsKeys]) => boolean;
1312
+ /**
1313
+ * Removes a previously registered event listener from the router's event system.
1314
+ *
1315
+ * @internal
1316
+ * This is a low-level internal API used primarily by the router core and plugin system.
1317
+ * For application code, use the unsubscribe function returned by addEventListener instead.
1318
+ *
1319
+ * @description
1320
+ * Removes a specific event listener callback from the router's event system, preventing it
1321
+ * from being invoked on future events. This method is a fundamental part of the subscription
1322
+ * lifecycle, ensuring proper cleanup and preventing memory leaks.
1323
+ *
1324
+ * @param eventName - The event type to remove the listener from. Must be one of the
1325
+ * predefined event constants (events.ROUTER_START, events.TRANSITION_SUCCESS, etc.).
1326
+ * TypeScript enforces valid event names at compile time.
1327
+ *
1328
+ * @param cb - The callback function to remove. Must be the **exact same reference** that was
1329
+ * passed to addEventListener. Using a different function (even with identical code)
1330
+ * will not match and will log a warning.
1331
+ *
1332
+ * @returns void - No return value (follows DOM API convention). Use the unsubscribe function
1333
+ * from addEventListener if you need guaranteed cleanup confirmation.
1334
+ *
1335
+ * @throws {Error} If eventName is not a valid event constant
1336
+ * @throws {TypeError} If cb is not a function (null, undefined, string, etc.)
1337
+ *
1338
+ * @see {@link addEventListener} for registering event listeners (returns unsubscribe function)
1339
+ * @see {@link usePlugin} for plugin-based event handling (handles cleanup automatically)
1340
+ * @see {@link invokeEventListeners} for the internal event dispatch mechanism
1341
+ */
1342
+ removeEventListener: (eventName: EventToNameMap[EventsKeys], cb: Plugin$1[keyof Plugin$1]) => void;
1343
+ /**
1344
+ * Registers an event listener for a specific router lifecycle event.
1345
+ *
1346
+ * @description
1347
+ * Provides type-safe subscription to router events with automatic memory leak protection
1348
+ * and state immutability guarantees. This is the low-level API for event handling - for
1349
+ * most use cases, consider using plugins (usePlugin) or the subscribe method instead.
1350
+ *
1351
+ * @param eventName - The event type to listen for. Must be one of the predefined
1352
+ * event constants (events.ROUTER_START, events.TRANSITION_SUCCESS, etc.).
1353
+ * TypeScript enforces valid event names at compile time.
1354
+ *
1355
+ * @param cb - The callback function to invoke when the event occurs. Signature must
1356
+ * match the event type. TypeScript enforces correct callback signature.
1357
+ * All State parameters will be deeply frozen before passing.
1358
+ *
1359
+ * @returns Unsubscribe function that removes the listener. Safe to call multiple times
1360
+ * (subsequent calls log warning but don't throw). Closure captures event and
1361
+ * callback for automatic cleanup.
1362
+ *
1363
+ * @throws {Error} If the same callback is already registered for this event
1364
+ * @throws {Error} If listener count reaches 10000 (hard limit, indicates memory leak)
1365
+ * @throws {Error} If eventName is not a valid event constant
1366
+ * @throws {TypeError} If callback is not a function
1367
+ *
1368
+ * @example
1369
+ * const unsub = router.addEventListener('TRANSITION_START', (toState, fromState) => {
1370
+ * console.log('Starting navigation:', toState.name)
1371
+ * })
1372
+ *
1373
+ * @example
1374
+ * router.addEventListener('TRANSITION_ERROR', (toState, fromState, err) => {
1375
+ * console.error('Navigation failed:', err)
1376
+ * })
1377
+ *
1378
+ * @see {@link usePlugin} for plugin-based event handling (recommended)
1379
+ * @see {@link subscribe} for simplified navigation event subscription
1380
+ * @see {@link removeEventListener} for manual listener removal (use unsubscribe instead)
1381
+ */
1382
+ addEventListener: (eventName: EventToNameMap[EventsKeys], cb: Plugin$1[keyof Plugin$1]) => Unsubscribe;
1383
+ forward: (fromRoute: string, toRoute: string) => Router<Dependencies>;
1384
+ /**
1385
+ * Navigates to the specified route.
1386
+ *
1387
+ * @description
1388
+ * Performs a navigation transition from the current route to the target route.
1389
+ * The method handles route activation/deactivation lifecycle, middleware execution,
1390
+ * and state management. Navigation can be customized with options and supports
1391
+ * both synchronous and asynchronous operations.
1392
+ *
1393
+ * @param routeName - The name of the route to navigate to. Must be a registered route.
1394
+ * @param routeParams - Optional parameters to pass to the route. These will be used
1395
+ * to build the route path and will be available in the route state.
1396
+ * @param options - Optional navigation options to control the transition behavior
1397
+ * @param done - Optional callback function called when navigation completes or fails.
1398
+ * Receives error as first argument and state as second.
1399
+ *
1400
+ * @returns A cancel function that can be called to abort the navigation.
1401
+ * Calling cancel will trigger the TRANSITION_CANCELLED event.
1402
+ *
1403
+ * @example
1404
+ * // Simple navigation
1405
+ * router.navigate('home');
1406
+ *
1407
+ * @example
1408
+ * // Navigation with parameters
1409
+ * router.navigate('user', { id: '123' });
1410
+ *
1411
+ * @example
1412
+ * // Cancellable navigation
1413
+ * const cancel = router.navigate('slow-route', {}, {}, (err) => {
1414
+ * if (err?.code === 'CANCELLED') console.log('Navigation was cancelled');
1415
+ * });
1416
+ * // Later...
1417
+ * cancel(); // Abort the navigation
1418
+ *
1419
+ * @throws {RouterError} With code 'NOT_STARTED' if router is not started
1420
+ * @throws {RouterError} With code 'ROUTE_NOT_FOUND' if route doesn't exist
1421
+ * @throws {RouterError} With code 'SAME_STATES' if navigating to current route without reload
1422
+ * @throws {RouterError} With code 'CANNOT_DEACTIVATE' if canDeactivate guard prevents navigation
1423
+ * @throws {RouterError} With code 'CANNOT_ACTIVATE' if canActivate guard prevents navigation
1424
+ * @throws {RouterError} With code 'TRANSITION_ERR' if middleware throws an error
1425
+ */
1426
+ navigate: ((routeName: string) => CancelFn) & ((routeName: string, routeParams: Params) => CancelFn) & ((routeName: string, done: DoneFn) => CancelFn) & ((routeName: string, routeParams: Params, options: NavigationOptions) => CancelFn) & ((routeName: string, routeParams: Params, done: DoneFn) => CancelFn) & ((routeName: string, routeParams: Params, options: NavigationOptions, done: DoneFn) => CancelFn);
1427
+ /**
1428
+ * Navigates to the default route if one is configured.
1429
+ *
1430
+ * Uses `defaultRoute` and `defaultParams` from router options.
1431
+ * Returns no-op if no default route configured.
1432
+ *
1433
+ * @description
1434
+ * Convenience method that navigates to the route specified in router options
1435
+ * as `defaultRoute` with `defaultParams`. If no default route is configured,
1436
+ * this method does nothing and returns a no-op cancel function.
1437
+ *
1438
+ * @param opts - Optional navigation options (same as navigate method)
1439
+ * @param done - Optional callback function called when navigation completes
1440
+ *
1441
+ * @returns A cancel function that can be called to abort the navigation.
1442
+ * Returns no-op function if no default route is configured.
1443
+ *
1444
+ * @see {@link navigate} for detailed behavior and error handling
1445
+ */
1446
+ navigateToDefault: (() => CancelFn) & ((done: DoneFn) => CancelFn) & ((opts: NavigationOptions) => CancelFn) & ((opts: NavigationOptions, done: DoneFn) => CancelFn);
1447
+ /**
1448
+ * Internal navigation method that accepts pre-built state.
1449
+ *
1450
+ * @internal
1451
+ * @description
1452
+ * This is an internal method used by the router and plugins to perform navigation
1453
+ * with a pre-built state object. It should not be used directly by application code.
1454
+ * Use `navigate()` instead for normal navigation operations.
1455
+ *
1456
+ * The method provides control over TRANSITION_SUCCESS event emission through the
1457
+ * `emitSuccess` parameter, allowing internal callers to manage event emission
1458
+ * themselves to avoid duplicate events.
1459
+ *
1460
+ * @param toState - The target state to navigate to (pre-built)
1461
+ * @param fromState - The current state to navigate from
1462
+ * @param opts - Navigation options
1463
+ * @param callback - Callback function called when navigation completes
1464
+ * @param emitSuccess - Whether to emit TRANSITION_SUCCESS event (false for internal use)
1465
+ *
1466
+ * @returns A cancel function that can be called to abort the navigation
1467
+ *
1468
+ * @private
1469
+ */
1470
+ navigateToState: (toState: State, fromState: State | undefined, opts: NavigationOptions, callback: DoneFn, emitSuccess: boolean) => CancelFn;
1471
+ /**
1472
+ * Subscribes to successful navigation transitions.
1473
+ *
1474
+ * @description
1475
+ * Registers a listener function that will be called whenever a navigation transition
1476
+ * completes successfully. This is the primary method for integrating UI frameworks
1477
+ * with the router to react to route changes.
1478
+ *
1479
+ * @param listener - Function called on each successful navigation transition.
1480
+ * Receives { route, previousRoute } where:
1481
+ * - route: The new state (frozen/immutable)
1482
+ * - previousRoute: The previous state (frozen/immutable, undefined on first navigation)
1483
+ *
1484
+ * @returns Unsubscribe function to remove the listener. Safe to call multiple times.
1485
+ *
1486
+ * @example
1487
+ * // Basic subscription
1488
+ * const unsubscribe = router.subscribe(({ route, previousRoute }) => {
1489
+ * console.log(`Navigation: ${previousRoute?.name || 'init'} → ${route.name}`);
1490
+ * });
1491
+ *
1492
+ * // Later, cleanup
1493
+ * unsubscribe();
1494
+ *
1495
+ * @example
1496
+ *
1497
+ * // Analytics
1498
+ * router.subscribe(({ route }) => {
1499
+ * analytics.track('page_view', { path: route.path })
1500
+ * })
1501
+ *
1502
+ * @throws {TypeError} If listener is not a function. Error message includes
1503
+ * hint about using Symbol.observable for Observable pattern.
1504
+ *
1505
+ * @see {@link addEventListener} for low-level event subscription
1506
+ * @see {@link usePlugin} for subscribing to all router events
1507
+ * @see {@link navigate} for triggering navigation
1508
+ */
1509
+ subscribe: (listener: SubscribeFn) => Unsubscribe;
1510
+ /**
1511
+ * Creates a clone of this router with the same configuration.
1512
+ *
1513
+ * @description
1514
+ * Creates a new router instance with the same routes, options, middleware,
1515
+ * plugins, and lifecycle handlers as the original. The cloned router is
1516
+ * independent of the original - changes to one do not affect the other.
1517
+ *
1518
+ * Use cases:
1519
+ * - Server-side rendering (SSR): Create a fresh router for each request
1520
+ * - Testing: Clone router to test different scenarios without side effects
1521
+ * - Feature flags: Create alternative router configurations
1522
+ *
1523
+ * What is cloned:
1524
+ * - Route tree structure (via rootNode)
1525
+ * - Router options (defaultRoute, trailingSlash, etc.)
1526
+ * - Middleware factories
1527
+ * - Plugin factories
1528
+ * - Lifecycle factories (canActivate, canDeactivate)
1529
+ * - Config (encoders, decoders, defaultParams, forwardMap)
1530
+ *
1531
+ * What is NOT cloned:
1532
+ * - Current state (cloned router starts fresh)
1533
+ * - Event listeners (subscribers must re-register)
1534
+ * - Started status (cloned router is not started)
1535
+ *
1536
+ * @param dependencies - Optional new dependencies for the cloned router.
1537
+ * If not provided, uses empty dependencies.
1538
+ *
1539
+ * @returns A new router instance with the same configuration.
1540
+ *
1541
+ * @example
1542
+ * // Basic cloning
1543
+ * const router = createRouter(routes, options);
1544
+ * const clonedRouter = router.clone();
1545
+ *
1546
+ * @example
1547
+ * // SSR: Clone with request-specific dependencies
1548
+ * app.get('*', (req, res) => {
1549
+ * const ssrRouter = router.clone({ request: req });
1550
+ * ssrRouter.start(req.url, (err, state) => {
1551
+ * // Render with state...
1552
+ * });
1553
+ * });
1554
+ *
1555
+ * @example
1556
+ * // Testing: Clone for isolated test
1557
+ * it('should navigate to user', () => {
1558
+ * const testRouter = router.clone();
1559
+ * testRouter.start();
1560
+ * testRouter.navigate('user', { id: '123' });
1561
+ * expect(testRouter.getState().name).toBe('user');
1562
+ * });
1563
+ */
1564
+ clone: (dependencies?: Dependencies) => Router<Dependencies>;
1565
+ }
1566
+ interface Plugin$1 {
1567
+ onStart?: () => void;
1568
+ onStop?: () => void;
1569
+ onTransitionStart?: (toState: State, fromState?: State) => void;
1570
+ onTransitionCancel?: (toState: State, fromState?: State) => void;
1571
+ onTransitionError?: (toState: State | undefined, fromState: State | undefined, err: RouterError) => void;
1572
+ onTransitionSuccess?: (toState: State, fromState: State | undefined, opts: NavigationOptions) => void;
1573
+ teardown?: () => void;
1574
+ }
1575
+ export type Middleware = ActivationFn;
1576
+ export type MiddlewareFactory<Dependencies extends DefaultDependencies = DefaultDependencies> = (router: Router<Dependencies>, getDependency: <K extends keyof Dependencies>(key: K) => Dependencies[K]) => Middleware;
1577
+ export type PluginFactory<Dependencies extends DefaultDependencies = DefaultDependencies> = (router: Router<Dependencies>, getDependency: <K extends keyof Dependencies>(key: K) => Dependencies[K]) => Plugin$1;
1578
+ export interface SubscribeState {
1579
+ route: State;
1580
+ previousRoute?: State | undefined;
1581
+ }
1582
+ export type SubscribeFn = (state: SubscribeState) => void;
1583
+ export interface Listener {
1584
+ [key: string]: unknown;
1585
+ next: (val: unknown) => void;
1586
+ error?: (err: unknown) => void;
1587
+ complete?: () => void;
1588
+ }
1589
+ export interface Subscription {
1590
+ unsubscribe: Unsubscribe;
1591
+ }
1592
+ export type ConstantsKeys = "UNKNOWN_ROUTE";
1593
+ export type Constants = Record<ConstantsKeys, string>;
1594
+ export type ErrorCodes = Record<ErrorCodeKeys, ErrorCodeValues>;
7
1595
  /**
8
1596
  * Error codes for router operations.
9
1597
  * Used to identify specific failure scenarios in navigation and lifecycle.
10
1598
  * Frozen to prevent accidental modifications.
11
1599
  */
12
- declare const errorCodes: ErrorCodeToValueMap;
1600
+ export declare const errorCodes: ErrorCodeToValueMap;
13
1601
  /**
14
1602
  * General router constants.
15
1603
  * Special route names and identifiers.
16
1604
  */
17
- declare const constants: Constants;
1605
+ export declare const constants: Constants;
18
1606
  /**
19
1607
  * Event names for router event system.
20
1608
  * Used with addEventListener/removeEventListener for reactive subscriptions.
21
1609
  */
22
- declare const events: EventToNameMap;
23
-
24
- declare class RouterError extends Error {
25
- [key: string]: unknown;
26
- readonly segment: string | undefined;
27
- readonly path: string | undefined;
28
- readonly redirect: State | undefined;
29
- code: string;
30
- /**
31
- * Creates a new RouterError instance.
32
- *
33
- * The options object accepts built-in fields (message, segment, path, redirect)
34
- * and any additional custom fields, which will all be attached to the error instance.
35
- *
36
- * @param code - The error code (e.g., "ROUTE_NOT_FOUND", "CANNOT_ACTIVATE")
37
- * @param options - Optional configuration object
38
- * @param options.message - Custom error message (defaults to code if not provided)
39
- * @param options.segment - The route segment where the error occurred
40
- * @param options.path - The full path where the error occurred
41
- * @param options.redirect - Optional redirect state for navigation errors
42
- *
43
- * @example
44
- * ```typescript
45
- * // Basic error
46
- * const err1 = new RouterError("ROUTE_NOT_FOUND");
47
- *
48
- * // Error with custom message
49
- * const err2 = new RouterError("ERR", { message: "Something went wrong" });
50
- *
51
- * // Error with context and custom fields
52
- * const err3 = new RouterError("CANNOT_ACTIVATE", {
53
- * message: "Insufficient permissions",
54
- * segment: "admin",
55
- * path: "/admin/users",
56
- * userId: "123" // custom field
57
- * });
58
- *
59
- * // Error with redirect
60
- * const err4 = new RouterError("TRANSITION_ERR", {
61
- * redirect: { name: "home", path: "/", params: {} }
62
- * });
63
- * ```
64
- */
65
- constructor(code: string, { message, segment, path, redirect, ...rest }?: {
66
- [key: string]: unknown;
67
- message?: string | undefined;
68
- segment?: string | undefined;
69
- path?: string | undefined;
70
- redirect?: State | undefined;
71
- });
72
- /**
73
- * Updates the error code and conditionally updates the message.
74
- *
75
- * If the current message is one of the standard error code values
76
- * (e.g., "ROUTE_NOT_FOUND", "SAME_STATES"), it will be replaced with the new code.
77
- * This allows keeping error messages in sync with codes when using standard error codes.
78
- *
79
- * If the message is custom (not a standard error code), it will be preserved.
80
- *
81
- * @param newCode - The new error code to set
82
- *
83
- * @example
84
- * // Message follows code (standard error code as message)
85
- * const err = new RouterError("ROUTE_NOT_FOUND", { message: "ROUTE_NOT_FOUND" });
86
- * err.setCode("CUSTOM_ERROR"); // message becomes "CUSTOM_ERROR"
87
- *
88
- * @example
89
- * // Custom message is preserved
90
- * const err = new RouterError("ERR", { message: "Custom error message" });
91
- * err.setCode("NEW_CODE"); // message stays "Custom error message"
92
- */
93
- setCode(newCode: string): void;
94
- /**
95
- * Copies properties from another Error instance to this RouterError.
96
- *
97
- * This method updates the message, cause, and stack trace from the provided error.
98
- * Useful for wrapping native errors while preserving error context.
99
- *
100
- * @param err - The Error instance to copy properties from
101
- * @throws {TypeError} If err is null or undefined
102
- *
103
- * @example
104
- * ```typescript
105
- * const routerErr = new RouterError("TRANSITION_ERR");
106
- * try {
107
- * // some operation that might fail
108
- * } catch (nativeErr) {
109
- * routerErr.setErrorInstance(nativeErr);
110
- * throw routerErr;
111
- * }
112
- * ```
113
- */
114
- setErrorInstance(err: Error): void;
115
- /**
116
- * Adds custom fields to the error object.
117
- *
118
- * This method allows attaching arbitrary data to the error for debugging or logging purposes.
119
- * All fields become accessible as properties on the error instance and are included in JSON serialization.
120
- *
121
- * Reserved method names (setCode, setErrorInstance, setAdditionalFields, hasField, getField, toJSON)
122
- * are automatically filtered out to prevent accidental overwriting of class methods.
123
- *
124
- * @param fields - Object containing custom fields to add to the error
125
- *
126
- * @example
127
- * ```typescript
128
- * const err = new RouterError("CANNOT_ACTIVATE");
129
- * err.setAdditionalFields({
130
- * userId: "123",
131
- * attemptedRoute: "/admin",
132
- * reason: "insufficient permissions"
133
- * });
134
- *
135
- * console.log(err.userId); // "123"
136
- * console.log(JSON.stringify(err)); // includes all custom fields
137
- * ```
138
- */
139
- setAdditionalFields(fields: Record<string, unknown>): void;
140
- /**
141
- * Checks if a custom field exists on the error object.
142
- *
143
- * This method checks for both custom fields added via setAdditionalFields()
144
- * and built-in fields (code, message, segment, etc.).
145
- *
146
- * @param key - The field name to check
147
- * @returns `true` if the field exists, `false` otherwise
148
- *
149
- * @example
150
- * ```typescript
151
- * const err = new RouterError("ERR", { segment: "users" });
152
- * err.setAdditionalFields({ userId: "123" });
153
- *
154
- * err.hasField("userId"); // true
155
- * err.hasField("segment"); // true
156
- * err.hasField("unknown"); // false
157
- * ```
158
- */
159
- hasField(key: string): boolean;
160
- /**
161
- * Retrieves a custom field value from the error object.
162
- *
163
- * This method can access both custom fields and built-in fields.
164
- * Returns `undefined` if the field doesn't exist.
165
- *
166
- * @param key - The field name to retrieve
167
- * @returns The field value, or `undefined` if it doesn't exist
168
- *
169
- * @example
170
- * ```typescript
171
- * const err = new RouterError("ERR");
172
- * err.setAdditionalFields({ userId: "123", role: "admin" });
173
- *
174
- * err.getField("userId"); // "123"
175
- * err.getField("role"); // "admin"
176
- * err.getField("code"); // "ERR" (built-in field)
177
- * err.getField("unknown"); // undefined
178
- * ```
179
- */
180
- getField(key: string): unknown;
181
- /**
182
- * Serializes the error to a JSON-compatible object.
183
- *
184
- * This method is automatically called by JSON.stringify() and includes:
185
- * - Built-in fields: code, message, segment (if set), path (if set), redirect (if set)
186
- * - All custom fields added via setAdditionalFields() or constructor
187
- * - Excludes: stack trace (for security/cleanliness)
188
- *
189
- * @returns A plain object representation of the error, suitable for JSON serialization
190
- *
191
- * @example
192
- * ```typescript
193
- * const err = new RouterError("ROUTE_NOT_FOUND", {
194
- * message: "Route not found",
195
- * path: "/admin/users/123"
196
- * });
197
- * err.setAdditionalFields({ userId: "123" });
198
- *
199
- * JSON.stringify(err);
200
- * // {
201
- * // "code": "ROUTE_NOT_FOUND",
202
- * // "message": "Route not found",
203
- * // "path": "/admin/users/123",
204
- * // "userId": "123"
205
- * // }
206
- * ```
207
- */
208
- toJSON(): Record<string, unknown>;
1610
+ export declare const events: EventToNameMap;
1611
+ declare class RouterError$1 extends Error {
1612
+ [key: string]: unknown;
1613
+ readonly segment: string | undefined;
1614
+ readonly path: string | undefined;
1615
+ readonly redirect: State | undefined;
1616
+ code: string;
1617
+ /**
1618
+ * Creates a new RouterError instance.
1619
+ *
1620
+ * The options object accepts built-in fields (message, segment, path, redirect)
1621
+ * and any additional custom fields, which will all be attached to the error instance.
1622
+ *
1623
+ * @param code - The error code (e.g., "ROUTE_NOT_FOUND", "CANNOT_ACTIVATE")
1624
+ * @param options - Optional configuration object
1625
+ * @param options.message - Custom error message (defaults to code if not provided)
1626
+ * @param options.segment - The route segment where the error occurred
1627
+ * @param options.path - The full path where the error occurred
1628
+ * @param options.redirect - Optional redirect state for navigation errors
1629
+ *
1630
+ * @example
1631
+ * ```typescript
1632
+ * // Basic error
1633
+ * const err1 = new RouterError("ROUTE_NOT_FOUND");
1634
+ *
1635
+ * // Error with custom message
1636
+ * const err2 = new RouterError("ERR", { message: "Something went wrong" });
1637
+ *
1638
+ * // Error with context and custom fields
1639
+ * const err3 = new RouterError("CANNOT_ACTIVATE", {
1640
+ * message: "Insufficient permissions",
1641
+ * segment: "admin",
1642
+ * path: "/admin/users",
1643
+ * userId: "123" // custom field
1644
+ * });
1645
+ *
1646
+ * // Error with redirect
1647
+ * const err4 = new RouterError("TRANSITION_ERR", {
1648
+ * redirect: { name: "home", path: "/", params: {} }
1649
+ * });
1650
+ * ```
1651
+ */
1652
+ constructor(code: string, { message, segment, path, redirect, ...rest }?: {
1653
+ [key: string]: unknown;
1654
+ message?: string | undefined;
1655
+ segment?: string | undefined;
1656
+ path?: string | undefined;
1657
+ redirect?: State | undefined;
1658
+ });
1659
+ /**
1660
+ * Updates the error code and conditionally updates the message.
1661
+ *
1662
+ * If the current message is one of the standard error code values
1663
+ * (e.g., "ROUTE_NOT_FOUND", "SAME_STATES"), it will be replaced with the new code.
1664
+ * This allows keeping error messages in sync with codes when using standard error codes.
1665
+ *
1666
+ * If the message is custom (not a standard error code), it will be preserved.
1667
+ *
1668
+ * @param newCode - The new error code to set
1669
+ *
1670
+ * @example
1671
+ * // Message follows code (standard error code as message)
1672
+ * const err = new RouterError("ROUTE_NOT_FOUND", { message: "ROUTE_NOT_FOUND" });
1673
+ * err.setCode("CUSTOM_ERROR"); // message becomes "CUSTOM_ERROR"
1674
+ *
1675
+ * @example
1676
+ * // Custom message is preserved
1677
+ * const err = new RouterError("ERR", { message: "Custom error message" });
1678
+ * err.setCode("NEW_CODE"); // message stays "Custom error message"
1679
+ */
1680
+ setCode(newCode: string): void;
1681
+ /**
1682
+ * Copies properties from another Error instance to this RouterError.
1683
+ *
1684
+ * This method updates the message, cause, and stack trace from the provided error.
1685
+ * Useful for wrapping native errors while preserving error context.
1686
+ *
1687
+ * @param err - The Error instance to copy properties from
1688
+ * @throws {TypeError} If err is null or undefined
1689
+ *
1690
+ * @example
1691
+ * ```typescript
1692
+ * const routerErr = new RouterError("TRANSITION_ERR");
1693
+ * try {
1694
+ * // some operation that might fail
1695
+ * } catch (nativeErr) {
1696
+ * routerErr.setErrorInstance(nativeErr);
1697
+ * throw routerErr;
1698
+ * }
1699
+ * ```
1700
+ */
1701
+ setErrorInstance(err: Error): void;
1702
+ /**
1703
+ * Adds custom fields to the error object.
1704
+ *
1705
+ * This method allows attaching arbitrary data to the error for debugging or logging purposes.
1706
+ * All fields become accessible as properties on the error instance and are included in JSON serialization.
1707
+ *
1708
+ * Reserved method names (setCode, setErrorInstance, setAdditionalFields, hasField, getField, toJSON)
1709
+ * are automatically filtered out to prevent accidental overwriting of class methods.
1710
+ *
1711
+ * @param fields - Object containing custom fields to add to the error
1712
+ *
1713
+ * @example
1714
+ * ```typescript
1715
+ * const err = new RouterError("CANNOT_ACTIVATE");
1716
+ * err.setAdditionalFields({
1717
+ * userId: "123",
1718
+ * attemptedRoute: "/admin",
1719
+ * reason: "insufficient permissions"
1720
+ * });
1721
+ *
1722
+ * console.log(err.userId); // "123"
1723
+ * console.log(JSON.stringify(err)); // includes all custom fields
1724
+ * ```
1725
+ */
1726
+ setAdditionalFields(fields: Record<string, unknown>): void;
1727
+ /**
1728
+ * Checks if a custom field exists on the error object.
1729
+ *
1730
+ * This method checks for both custom fields added via setAdditionalFields()
1731
+ * and built-in fields (code, message, segment, etc.).
1732
+ *
1733
+ * @param key - The field name to check
1734
+ * @returns `true` if the field exists, `false` otherwise
1735
+ *
1736
+ * @example
1737
+ * ```typescript
1738
+ * const err = new RouterError("ERR", { segment: "users" });
1739
+ * err.setAdditionalFields({ userId: "123" });
1740
+ *
1741
+ * err.hasField("userId"); // true
1742
+ * err.hasField("segment"); // true
1743
+ * err.hasField("unknown"); // false
1744
+ * ```
1745
+ */
1746
+ hasField(key: string): boolean;
1747
+ /**
1748
+ * Retrieves a custom field value from the error object.
1749
+ *
1750
+ * This method can access both custom fields and built-in fields.
1751
+ * Returns `undefined` if the field doesn't exist.
1752
+ *
1753
+ * @param key - The field name to retrieve
1754
+ * @returns The field value, or `undefined` if it doesn't exist
1755
+ *
1756
+ * @example
1757
+ * ```typescript
1758
+ * const err = new RouterError("ERR");
1759
+ * err.setAdditionalFields({ userId: "123", role: "admin" });
1760
+ *
1761
+ * err.getField("userId"); // "123"
1762
+ * err.getField("role"); // "admin"
1763
+ * err.getField("code"); // "ERR" (built-in field)
1764
+ * err.getField("unknown"); // undefined
1765
+ * ```
1766
+ */
1767
+ getField(key: string): unknown;
1768
+ /**
1769
+ * Serializes the error to a JSON-compatible object.
1770
+ *
1771
+ * This method is automatically called by JSON.stringify() and includes:
1772
+ * - Built-in fields: code, message, segment (if set), path (if set), redirect (if set)
1773
+ * - All custom fields added via setAdditionalFields() or constructor
1774
+ * - Excludes: stack trace (for security/cleanliness)
1775
+ *
1776
+ * @returns A plain object representation of the error, suitable for JSON serialization
1777
+ *
1778
+ * @example
1779
+ * ```typescript
1780
+ * const err = new RouterError("ROUTE_NOT_FOUND", {
1781
+ * message: "Route not found",
1782
+ * path: "/admin/users/123"
1783
+ * });
1784
+ * err.setAdditionalFields({ userId: "123" });
1785
+ *
1786
+ * JSON.stringify(err);
1787
+ * // {
1788
+ * // "code": "ROUTE_NOT_FOUND",
1789
+ * // "message": "Route not found",
1790
+ * // "path": "/admin/users/123",
1791
+ * // "userId": "123"
1792
+ * // }
1793
+ * ```
1794
+ */
1795
+ toJSON(): Record<string, unknown>;
209
1796
  }
210
-
211
1797
  /**
212
1798
  * Creates a new router instance.
213
1799
  */
214
- declare const createRouter: <Dependencies extends DefaultDependencies = DefaultDependencies>(routes?: Route<Dependencies>[], options?: Partial<Options>, dependencies?: Dependencies) => Router<Dependencies>;
1800
+ export declare const createRouter: <Dependencies extends DefaultDependencies = DefaultDependencies>(routes?: Route<Dependencies>[], options?: Partial<Options>, dependencies?: Dependencies) => Router<Dependencies>;
1801
+
1802
+ export {
1803
+ Plugin$1 as Plugin,
1804
+ RouterError$1 as RouterError,
1805
+ };
215
1806
 
216
- export { type Constants, type ErrorCodes, RouterError, constants, createRouter, errorCodes, events };
1807
+ export {};