eleva 1.0.1 → 1.1.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.
Files changed (97) hide show
  1. package/README.md +21 -10
  2. package/dist/{eleva-plugins.cjs.js → eleva-plugins.cjs} +1002 -292
  3. package/dist/eleva-plugins.cjs.map +1 -0
  4. package/dist/eleva-plugins.d.cts +1352 -0
  5. package/dist/eleva-plugins.d.cts.map +1 -0
  6. package/dist/eleva-plugins.d.ts +1352 -0
  7. package/dist/eleva-plugins.d.ts.map +1 -0
  8. package/dist/{eleva-plugins.esm.js → eleva-plugins.js} +1002 -292
  9. package/dist/eleva-plugins.js.map +1 -0
  10. package/dist/eleva-plugins.umd.js +1001 -291
  11. package/dist/eleva-plugins.umd.js.map +1 -1
  12. package/dist/eleva-plugins.umd.min.js +1 -1
  13. package/dist/eleva-plugins.umd.min.js.map +1 -1
  14. package/dist/{eleva.cjs.js → eleva.cjs} +421 -191
  15. package/dist/eleva.cjs.map +1 -0
  16. package/dist/eleva.d.cts +1329 -0
  17. package/dist/eleva.d.cts.map +1 -0
  18. package/dist/eleva.d.ts +473 -226
  19. package/dist/eleva.d.ts.map +1 -0
  20. package/dist/{eleva.esm.js → eleva.js} +422 -192
  21. package/dist/eleva.js.map +1 -0
  22. package/dist/eleva.umd.js +420 -190
  23. package/dist/eleva.umd.js.map +1 -1
  24. package/dist/eleva.umd.min.js +1 -1
  25. package/dist/eleva.umd.min.js.map +1 -1
  26. package/dist/plugins/attr.cjs +279 -0
  27. package/dist/plugins/attr.cjs.map +1 -0
  28. package/dist/plugins/attr.d.cts +101 -0
  29. package/dist/plugins/attr.d.cts.map +1 -0
  30. package/dist/plugins/attr.d.ts +101 -0
  31. package/dist/plugins/attr.d.ts.map +1 -0
  32. package/dist/plugins/attr.js +276 -0
  33. package/dist/plugins/attr.js.map +1 -0
  34. package/dist/plugins/attr.umd.js +111 -22
  35. package/dist/plugins/attr.umd.js.map +1 -1
  36. package/dist/plugins/attr.umd.min.js +1 -1
  37. package/dist/plugins/attr.umd.min.js.map +1 -1
  38. package/dist/plugins/router.cjs +1873 -0
  39. package/dist/plugins/router.cjs.map +1 -0
  40. package/dist/plugins/router.d.cts +1296 -0
  41. package/dist/plugins/router.d.cts.map +1 -0
  42. package/dist/plugins/router.d.ts +1296 -0
  43. package/dist/plugins/router.d.ts.map +1 -0
  44. package/dist/plugins/router.js +1870 -0
  45. package/dist/plugins/router.js.map +1 -0
  46. package/dist/plugins/router.umd.js +482 -186
  47. package/dist/plugins/router.umd.js.map +1 -1
  48. package/dist/plugins/router.umd.min.js +1 -1
  49. package/dist/plugins/router.umd.min.js.map +1 -1
  50. package/dist/plugins/store.cjs +920 -0
  51. package/dist/plugins/store.cjs.map +1 -0
  52. package/dist/plugins/store.d.cts +266 -0
  53. package/dist/plugins/store.d.cts.map +1 -0
  54. package/dist/plugins/store.d.ts +266 -0
  55. package/dist/plugins/store.d.ts.map +1 -0
  56. package/dist/plugins/store.js +917 -0
  57. package/dist/plugins/store.js.map +1 -0
  58. package/dist/plugins/store.umd.js +410 -85
  59. package/dist/plugins/store.umd.js.map +1 -1
  60. package/dist/plugins/store.umd.min.js +1 -1
  61. package/dist/plugins/store.umd.min.js.map +1 -1
  62. package/package.json +112 -68
  63. package/src/core/Eleva.js +195 -115
  64. package/src/index.cjs +10 -0
  65. package/src/index.js +11 -0
  66. package/src/modules/Emitter.js +68 -20
  67. package/src/modules/Renderer.js +82 -20
  68. package/src/modules/Signal.js +43 -15
  69. package/src/modules/TemplateEngine.js +50 -9
  70. package/src/plugins/Attr.js +121 -19
  71. package/src/plugins/Router.js +526 -181
  72. package/src/plugins/Store.js +448 -69
  73. package/src/plugins/index.js +1 -0
  74. package/types/core/Eleva.d.ts +263 -169
  75. package/types/core/Eleva.d.ts.map +1 -1
  76. package/types/index.d.cts +3 -0
  77. package/types/index.d.cts.map +1 -0
  78. package/types/index.d.ts +5 -0
  79. package/types/index.d.ts.map +1 -1
  80. package/types/modules/Emitter.d.ts +73 -30
  81. package/types/modules/Emitter.d.ts.map +1 -1
  82. package/types/modules/Renderer.d.ts +48 -18
  83. package/types/modules/Renderer.d.ts.map +1 -1
  84. package/types/modules/Signal.d.ts +44 -16
  85. package/types/modules/Signal.d.ts.map +1 -1
  86. package/types/modules/TemplateEngine.d.ts +46 -11
  87. package/types/modules/TemplateEngine.d.ts.map +1 -1
  88. package/types/plugins/Attr.d.ts +83 -16
  89. package/types/plugins/Attr.d.ts.map +1 -1
  90. package/types/plugins/Router.d.ts +498 -207
  91. package/types/plugins/Router.d.ts.map +1 -1
  92. package/types/plugins/Store.d.ts +211 -37
  93. package/types/plugins/Store.d.ts.map +1 -1
  94. package/dist/eleva-plugins.cjs.js.map +0 -1
  95. package/dist/eleva-plugins.esm.js.map +0 -1
  96. package/dist/eleva.cjs.js.map +0 -1
  97. package/dist/eleva.esm.js.map +0 -1
@@ -0,0 +1,1870 @@
1
+ /*! Eleva Router Plugin v1.1.0 | MIT License | https://elevajs.com */
2
+ /**
3
+ * @module eleva/plugins/router
4
+ * @fileoverview Client-side router plugin with hash, history, and query modes,
5
+ * navigation guards, and lifecycle hooks.
6
+ */ // ============================================================================
7
+ // TYPE DEFINITIONS
8
+ // ============================================================================
9
+ // -----------------------------------------------------------------------------
10
+ // External Type Imports
11
+ // -----------------------------------------------------------------------------
12
+ /**
13
+ * Type imports from the Eleva core library.
14
+ * @typedef {import('eleva').Eleva} Eleva
15
+ * @typedef {import('eleva').ComponentDefinition} ComponentDefinition
16
+ * @typedef {import('eleva').Emitter} Emitter
17
+ * @typedef {import('eleva').MountResult} MountResult
18
+ * @typedef {import('eleva').UnsubscribeFunction} UnsubscribeFunction
19
+ */ /**
20
+ * Generic type import.
21
+ * @template T
22
+ * @typedef {import('eleva').Signal<T>} Signal
23
+ */ // -----------------------------------------------------------------------------
24
+ // Router Events
25
+ // -----------------------------------------------------------------------------
26
+ /**
27
+ * Fired when the router initialization completes successfully.
28
+ * @event router:ready
29
+ * @type {Router}
30
+ */ /**
31
+ * Fired when an error occurs during navigation or route handling.
32
+ * @event router:error
33
+ * @type {Error}
34
+ */ /**
35
+ * Fired when no matching route is found for the requested path.
36
+ * @event router:notFound
37
+ * @type {{to: RouteLocation, from: RouteLocation | null, path: string}}
38
+ */ /**
39
+ * Fired before guards run, allowing plugins to block or redirect navigation.
40
+ * @event router:beforeEach
41
+ * @type {NavigationContext}
42
+ */ /**
43
+ * Fired before component resolution, allowing plugins to modify the resolve context.
44
+ * @event router:beforeResolve
45
+ * @type {ResolveContext}
46
+ */ /**
47
+ * Fired after components are resolved successfully.
48
+ * @event router:afterResolve
49
+ * @type {ResolveContext}
50
+ */ /**
51
+ * Fired after leaving the previous route.
52
+ * @event router:afterLeave
53
+ * @type {{to: RouteLocation, from: RouteLocation}}
54
+ */ /**
55
+ * Fired before DOM rendering begins.
56
+ * @event router:beforeRender
57
+ * @type {RenderContext}
58
+ */ /**
59
+ * Fired after DOM rendering completes.
60
+ * @event router:afterRender
61
+ * @type {RenderContext}
62
+ */ /**
63
+ * Fired after render for scroll behavior handling.
64
+ * @event router:scroll
65
+ * @type {ScrollContext}
66
+ */ /**
67
+ * Fired after entering the new route.
68
+ * @event router:afterEnter
69
+ * @type {{to: RouteLocation, from: RouteLocation | null}}
70
+ */ /**
71
+ * Fired after navigation completes successfully.
72
+ * @event router:afterEach
73
+ * @type {{to: RouteLocation, from: RouteLocation | null}}
74
+ */ /**
75
+ * Fired when a route is dynamically added.
76
+ * @event router:routeAdded
77
+ * @type {RouteDefinition}
78
+ */ /**
79
+ * Fired when a route is dynamically removed.
80
+ * @event router:routeRemoved
81
+ * @type {RouteDefinition}
82
+ */ // -----------------------------------------------------------------------------
83
+ // Router Data Types
84
+ // -----------------------------------------------------------------------------
85
+ /**
86
+ * The routing mode determines how the router manages URL state.
87
+ * - `hash`: Uses URL hash (e.g., `/#/path`) - works without server config
88
+ * - `history`: Uses HTML5 History API (e.g., `/path`) - requires server config
89
+ * - `query`: Uses query parameters (e.g., `?view=/path`) - useful for embedded apps
90
+ * @typedef {'hash' | 'history' | 'query'} RouterMode
91
+ */ /**
92
+ * Route parameters extracted from the URL path.
93
+ * @typedef {Record<string, string>} RouteParams
94
+ * @description Key-value pairs extracted from dynamic route segments (e.g., `/users/:id` → `{ id: '123' }`).
95
+ */ /**
96
+ * Query parameters from the URL query string.
97
+ * @typedef {Record<string, string>} QueryParams
98
+ * @description Key-value pairs from the URL query string (e.g., `?page=1&sort=name`).
99
+ */ /**
100
+ * Navigation input parameters supporting multiple value types.
101
+ * @typedef {Record<string, string | number | boolean>} NavigationParams
102
+ * @description Parameters passed to navigation functions, automatically converted to strings in URLs.
103
+ */ /**
104
+ * Function signature for programmatic navigation.
105
+ * @typedef {(location: string | NavigationTarget, params?: NavigationParams) => Promise<boolean>} NavigateFunction
106
+ * @description Returns true if navigation succeeded, false if blocked by a guard.
107
+ */ /**
108
+ * Router configuration options.
109
+ * @typedef {Object} RouterOptions
110
+ * @property {RouterMode} [mode='hash']
111
+ * The routing mode to use.
112
+ * @property {string} [queryParam='view']
113
+ * Query parameter name for 'query' mode.
114
+ * @property {string} [viewSelector='view']
115
+ * Base selector for the view element.
116
+ * @property {string} mount
117
+ * CSS selector for the mount point element.
118
+ * @property {RouteDefinition[]} routes
119
+ * Array of route definitions.
120
+ * @property {RouteComponent} [globalLayout]
121
+ * Default layout for all routes.
122
+ * @property {NavigationGuard} [onBeforeEach]
123
+ * Global navigation guard.
124
+ * @property {boolean} [autoStart=true]
125
+ * Whether to start the router automatically.
126
+ * @description Configuration options for the Router plugin.
127
+ */ /**
128
+ * Object describing a navigation target for `router.navigate()`.
129
+ * @typedef {Object} NavigationTarget
130
+ * @property {string} path
131
+ * The target path (can include params like '/users/:id').
132
+ * @property {NavigationParams} [params]
133
+ * Route parameters to inject.
134
+ * @property {NavigationParams} [query]
135
+ * Query parameters to append.
136
+ * @property {boolean} [replace=false]
137
+ * Whether to replace current history entry.
138
+ * @property {unknown} [state]
139
+ * History state to pass.
140
+ * @description Object describing a navigation target for `router.navigate()`.
141
+ */ /**
142
+ * Saved scroll position.
143
+ * @typedef {Object} ScrollPosition
144
+ * @property {number} x
145
+ * Horizontal scroll position.
146
+ * @property {number} y
147
+ * Vertical scroll position.
148
+ * @description Represents a saved scroll position.
149
+ */ /**
150
+ * Internal representation of a parsed route path segment.
151
+ * @typedef {Object} RouteSegment
152
+ * @property {'static' | 'param'} type
153
+ * The segment type.
154
+ * @property {string} [value]
155
+ * The segment value (static segments).
156
+ * @property {string} [name]
157
+ * The parameter name (param segments).
158
+ * @description Internal representation of a parsed route path segment.
159
+ * @private
160
+ */ /**
161
+ * Result of matching a path against route definitions.
162
+ * @typedef {Object} RouteMatch
163
+ * @property {RouteDefinition} route
164
+ * The matched route definition.
165
+ * @property {RouteParams} params
166
+ * The extracted route parameters.
167
+ * @description Result of matching a path against route definitions.
168
+ * @private
169
+ */ /**
170
+ * Arbitrary metadata attached to routes for use in guards and components.
171
+ * @typedef {Record<string, unknown>} RouteMeta
172
+ * @description Common properties include:
173
+ * - `requiresAuth: boolean` - Whether the route requires authentication
174
+ * - `title: string` - Page title for the route
175
+ * - `roles: string[]` - Required user roles
176
+ * @example
177
+ * {
178
+ * path: '/admin',
179
+ * component: AdminPage,
180
+ * meta: { requiresAuth: true, roles: ['admin'], title: 'Admin Dashboard' }
181
+ * }
182
+ */ /**
183
+ * Interface for the router's error handling system.
184
+ * @typedef {Object} RouterErrorHandler
185
+ * @property {(error: Error, context: string, details?: Record<string, unknown>) => void} handle
186
+ * Throws a formatted error.
187
+ * @property {(message: string, details?: Record<string, unknown>) => void} warn
188
+ * Logs a warning.
189
+ * @property {(message: string, error: Error, details?: Record<string, unknown>) => void} log
190
+ * Logs an error without throwing.
191
+ * @description Interface for the router's error handling system.
192
+ */ // -----------------------------------------------------------------------------
193
+ // Event Callback Types
194
+ // -----------------------------------------------------------------------------
195
+ /**
196
+ * Callback for `router:beforeEach` event.
197
+ * @callback NavigationContextCallback
198
+ * @param {NavigationContext} context
199
+ * The navigation context (can be modified to block/redirect).
200
+ * @returns {void | Promise<void>}
201
+ * @description Modify context to control navigation flow.
202
+ */ /**
203
+ * Callback for `router:beforeResolve` and `router:afterResolve` events.
204
+ * @callback ResolveContextCallback
205
+ * @param {ResolveContext} context
206
+ * The resolve context (can be modified to block/redirect).
207
+ * @returns {void | Promise<void>}
208
+ * @description Callback for `router:beforeResolve` and `router:afterResolve` events.
209
+ */ /**
210
+ * Callback for `router:beforeRender` and `router:afterRender` events.
211
+ * @callback RenderContextCallback
212
+ * @param {RenderContext} context
213
+ * The render context.
214
+ * @returns {void | Promise<void>}
215
+ * @description Callback for `router:beforeRender` and `router:afterRender` events.
216
+ */ /**
217
+ * Callback for `router:scroll` event.
218
+ * @callback ScrollContextCallback
219
+ * @param {ScrollContext} context
220
+ * The scroll context with saved position info.
221
+ * @returns {void | Promise<void>}
222
+ * @description Use to implement custom scroll behavior.
223
+ */ /**
224
+ * Callback for `router:afterEnter`, `router:afterLeave`, `router:afterEach` events.
225
+ * @callback RouteChangeCallback
226
+ * @param {RouteLocation} to
227
+ * The target route location.
228
+ * @param {RouteLocation | null} from
229
+ * The source route location.
230
+ * @returns {void | Promise<void>}
231
+ * @description Callback for `router:afterEnter`, `router:afterLeave`, `router:afterEach` events.
232
+ */ /**
233
+ * Router context injected into component setup as `ctx.router`.
234
+ * @typedef {Object} RouterContext
235
+ * @property {NavigateFunction} navigate
236
+ * Programmatic navigation function.
237
+ * @property {Signal<RouteLocation | null>} current
238
+ * Reactive signal for current route.
239
+ * @property {Signal<RouteLocation | null>} previous
240
+ * Reactive signal for previous route.
241
+ * @property {RouteParams} params
242
+ * Current route params (getter).
243
+ * @property {QueryParams} query
244
+ * Current route query (getter).
245
+ * @property {string} path
246
+ * Current route path (getter).
247
+ * @property {string} fullUrl
248
+ * Current routed URL string (getter).
249
+ * @property {RouteMeta} meta
250
+ * Current route meta (getter).
251
+ * @description Injected into component setup as `ctx.router`.
252
+ */ /**
253
+ * Callback for `router:error` event.
254
+ * @callback RouterErrorCallback
255
+ * @param {Error} error
256
+ * The error that occurred.
257
+ * @param {RouteLocation} [to]
258
+ * The target route (if available).
259
+ * @param {RouteLocation | null} [from]
260
+ * The source route (if available).
261
+ * @returns {void | Promise<void>}
262
+ * @description Callback for `router:error` event.
263
+ */ /**
264
+ * Callback for `router:ready` event.
265
+ * @callback RouterReadyCallback
266
+ * @param {Router} router
267
+ * The router instance.
268
+ * @returns {void | Promise<void>}
269
+ * @description Callback for `router:ready` event.
270
+ */ /**
271
+ * Callback for `router:routeAdded` event.
272
+ * @callback RouteAddedCallback
273
+ * @param {RouteDefinition} route
274
+ * The added route definition.
275
+ * @returns {void | Promise<void>}
276
+ * @description Callback for `router:routeAdded` event.
277
+ */ /**
278
+ * Callback for `router:routeRemoved` event.
279
+ * @callback RouteRemovedCallback
280
+ * @param {RouteDefinition} route
281
+ * The removed route definition.
282
+ * @returns {void | Promise<void>}
283
+ * @description Callback for `router:routeRemoved` event.
284
+ */ // ============================================================================
285
+ // CORE IMPLEMENTATION
286
+ // ============================================================================
287
+ /**
288
+ * Simple error handler for the core router.
289
+ * @private
290
+ */ const CoreErrorHandler = {
291
+ /**
292
+ * Handles router errors with basic formatting.
293
+ * @param {Error} error - The error to handle.
294
+ * @param {string} context - The context where the error occurred.
295
+ * @param {Record<string, unknown>} details - Additional error details.
296
+ * @throws {Error} The formatted error.
297
+ */ handle (error, context, details = {}) {
298
+ const message = `[ElevaRouter] ${context}: ${error.message}`;
299
+ const formattedError = new Error(message);
300
+ // Preserve original error details
301
+ formattedError.originalError = error;
302
+ formattedError.context = context;
303
+ formattedError.details = details;
304
+ console.error(message, {
305
+ error,
306
+ context,
307
+ details
308
+ });
309
+ throw formattedError;
310
+ },
311
+ /**
312
+ * Logs a warning without throwing an error.
313
+ * @param {string} message - The warning message.
314
+ * @param {Record<string, unknown>} details - Additional warning details.
315
+ */ warn (message, details = {}) {
316
+ console.warn(`[ElevaRouter] ${message}`, details);
317
+ },
318
+ /**
319
+ * Logs an error without throwing.
320
+ * @param {string} message - The error message.
321
+ * @param {Error} error - The original error.
322
+ * @param {Record<string, unknown>} details - Additional error details.
323
+ */ log (message, error, details = {}) {
324
+ console.error(`[ElevaRouter] ${message}`, {
325
+ error,
326
+ details
327
+ });
328
+ }
329
+ };
330
+ /**
331
+ * Represents the current or target location in the router.
332
+ * @typedef {Object} RouteLocation
333
+ * @property {string} path
334
+ * The path of the route (e.g., '/users/123').
335
+ * @property {QueryParams} query
336
+ * Query parameters as key-value pairs.
337
+ * @property {string} fullUrl
338
+ * The routed URL string (path plus query).
339
+ * @property {RouteParams} params
340
+ * Dynamic route parameters.
341
+ * @property {RouteMeta} meta
342
+ * Metadata associated with the matched route.
343
+ * @property {string} [name]
344
+ * The optional name of the matched route.
345
+ * @property {RouteDefinition} matched
346
+ * The raw route definition that was matched.
347
+ * @description Represents the current or target location in the router.
348
+ */ /**
349
+ * Return value of a navigation guard.
350
+ * - `true` or `undefined/void`: Allow navigation
351
+ * - `false`: Abort navigation
352
+ * - `string`: Redirect to path
353
+ * - `NavigationTarget`: Redirect with options
354
+ * @typedef {boolean | string | NavigationTarget | void} NavigationGuardResult
355
+ */ /**
356
+ * Navigation guard function that controls navigation flow.
357
+ * @callback NavigationGuard
358
+ * @param {RouteLocation} to
359
+ * The target route location.
360
+ * @param {RouteLocation | null} from
361
+ * The source route location (null on initial).
362
+ * @returns {NavigationGuardResult | Promise<NavigationGuardResult>}
363
+ * @description A function that controls navigation flow. Runs before navigation is confirmed.
364
+ * @example
365
+ * // Simple auth guard
366
+ * const authGuard = (to, from) => {
367
+ * if (to.meta.requiresAuth && !isLoggedIn()) {
368
+ * return '/login'; // Redirect
369
+ * }
370
+ * // Allow navigation (implicit return undefined)
371
+ * };
372
+ */ /**
373
+ * Navigation hook for side effects. Does not affect navigation flow.
374
+ * @callback NavigationHook
375
+ * @param {RouteLocation} to
376
+ * The target route location.
377
+ * @param {RouteLocation | null} from
378
+ * The source route location.
379
+ * @returns {void | Promise<void>}
380
+ * @description A lifecycle hook for side effects. Does not affect navigation flow.
381
+ * @example
382
+ * // Analytics hook
383
+ * const analyticsHook = (to, from) => {
384
+ * analytics.trackPageView(to.path);
385
+ * };
386
+ */ /**
387
+ * Interface for router plugins.
388
+ * @typedef {Object} RouterPlugin
389
+ * @property {string} name
390
+ * Unique plugin identifier.
391
+ * @property {string} [version]
392
+ * Plugin version (recommended to match router version).
393
+ * @property {(router: Router, options?: Record<string, unknown>) => void} install
394
+ * Installation function.
395
+ * @property {(router: Router) => void | Promise<void>} [destroy]
396
+ * Cleanup function called on router.destroy().
397
+ * @description Interface for router plugins. Plugins can extend router functionality.
398
+ * @example
399
+ * const AnalyticsPlugin = {
400
+ * name: 'analytics',
401
+ * version: '1.0.0',
402
+ * install(router, options) {
403
+ * router.emitter.on('router:afterEach', (to, from) => {
404
+ * analytics.track(to.path);
405
+ * });
406
+ * }
407
+ * };
408
+ */ /**
409
+ * Context object for navigation events that plugins can modify.
410
+ * @typedef {Object} NavigationContext
411
+ * @property {RouteLocation} to
412
+ * The target route location.
413
+ * @property {RouteLocation | null} from
414
+ * The source route location.
415
+ * @property {boolean} cancelled
416
+ * Whether navigation has been cancelled.
417
+ * @property {string | NavigationTarget | null} redirectTo
418
+ * Redirect target if set.
419
+ * @description Passed to navigation events. Plugins can modify to control navigation flow.
420
+ */ /**
421
+ * Context object for component resolution events.
422
+ * @typedef {Object} ResolveContext
423
+ * @property {RouteLocation} to
424
+ * The target route location.
425
+ * @property {RouteLocation | null} from
426
+ * The source route location.
427
+ * @property {RouteDefinition} route
428
+ * The matched route definition.
429
+ * @property {ComponentDefinition | null} layoutComponent
430
+ * The resolved layout component (available in afterResolve).
431
+ * @property {ComponentDefinition | null} pageComponent
432
+ * The resolved page component (available in afterResolve).
433
+ * @property {boolean} cancelled
434
+ * Whether navigation has been cancelled.
435
+ * @property {string | NavigationTarget | null} redirectTo
436
+ * Redirect target if set.
437
+ * @description Passed to component resolution events.
438
+ */ /**
439
+ * Context object for render events.
440
+ * @typedef {Object} RenderContext
441
+ * @property {RouteLocation} to
442
+ * The target route location.
443
+ * @property {RouteLocation | null} from
444
+ * The source route location.
445
+ * @property {ComponentDefinition | null} layoutComponent
446
+ * The layout component being rendered.
447
+ * @property {ComponentDefinition} pageComponent
448
+ * The page component being rendered.
449
+ * @description Passed to render events.
450
+ */ /**
451
+ * Context object for scroll events.
452
+ * @typedef {Object} ScrollContext
453
+ * @property {RouteLocation} to
454
+ * The target route location.
455
+ * @property {RouteLocation | null} from
456
+ * The source route location.
457
+ * @property {{x: number, y: number} | null} savedPosition
458
+ * Saved position (back/forward nav).
459
+ * @description Passed to scroll events for plugins to handle scroll behavior.
460
+ */ /**
461
+ * A component that can be rendered for a route.
462
+ * - `string`: Name of a registered component
463
+ * - `ComponentDefinition`: Inline component definition
464
+ * - `() => ComponentDefinition`: Factory function returning a component
465
+ * - `() => Promise<ComponentDefinition>`: Async factory function
466
+ * - `() => Promise<{default: ComponentDefinition}>`: Lazy-loaded module (e.g., `() => import('./Page.js')`)
467
+ * @typedef {string | ComponentDefinition | (() => ComponentDefinition | Promise<ComponentDefinition | {default: ComponentDefinition}>)} RouteComponent
468
+ */ /**
469
+ * Defines a route in the application.
470
+ * @typedef {Object} RouteDefinition
471
+ * @property {string} path
472
+ * URL path pattern. Supports:
473
+ * - Static: '/about'
474
+ * - Dynamic params: '/users/:id'
475
+ * - Wildcard: '*' (catch-all, conventionally last)
476
+ * @property {RouteComponent} component
477
+ * The component to render for this route.
478
+ * @property {RouteComponent} [layout]
479
+ * Optional layout component to wrap the route component.
480
+ * @property {string} [name]
481
+ * Optional route name for programmatic navigation.
482
+ * @property {RouteMeta} [meta]
483
+ * Optional metadata (auth flags, titles, etc.).
484
+ * @property {NavigationGuard} [beforeEnter]
485
+ * Route-specific guard before entering.
486
+ * @property {NavigationHook} [afterEnter]
487
+ * Hook after entering and component is mounted.
488
+ * @property {NavigationGuard} [beforeLeave]
489
+ * Guard before leaving this route.
490
+ * @property {NavigationHook} [afterLeave]
491
+ * Hook after leaving and component is unmounted.
492
+ * @property {RouteSegment[]} [segments]
493
+ * Internal: parsed path segments (added by router).
494
+ * @description Defines a route in the application.
495
+ * @note Nested routes are not supported. Use shared layouts with flat routes instead.
496
+ * @example
497
+ * // Static route
498
+ * { path: '/about', component: AboutPage }
499
+ *
500
+ * // Dynamic route with params
501
+ * { path: '/users/:id', component: UserPage, meta: { requiresAuth: true } }
502
+ *
503
+ * // Lazy-loaded route with layout
504
+ * {
505
+ * path: '/dashboard',
506
+ * component: () => import('./Dashboard.js'),
507
+ * layout: DashboardLayout,
508
+ * beforeEnter: (to, from) => isLoggedIn() || '/login'
509
+ * }
510
+ *
511
+ * // Catch-all 404 route (conventionally last)
512
+ * { path: '*', component: NotFoundPage }
513
+ */ /**
514
+ * @class 🛤️ Router
515
+ * @classdesc A powerful, reactive, and flexible Router Plugin for Eleva.
516
+ * This class manages all routing logic, including state, navigation, and rendering.
517
+ *
518
+ * ## Features
519
+ * - Multiple routing modes (hash, history, query)
520
+ * - Reactive route state via Signals
521
+ * - Navigation guards and lifecycle hooks
522
+ * - Lazy-loaded components
523
+ * - Layout system
524
+ * - Plugin architecture
525
+ * - Scroll position management
526
+ *
527
+ * ## Events Reference
528
+ * | Event | Callback Type | Can Block | Description |
529
+ * |-------|--------------|-----------|-------------|
530
+ * | `router:ready` | {@link RouterReadyCallback} | No | Router initialized |
531
+ * | `router:beforeEach` | {@link NavigationContextCallback} | Yes | Before guards run |
532
+ * | `router:beforeResolve` | {@link ResolveContextCallback} | Yes | Before component loading |
533
+ * | `router:afterResolve` | {@link ResolveContextCallback} | No | After components loaded |
534
+ * | `router:afterLeave` | {@link RouteChangeCallback} | No | After leaving route |
535
+ * | `router:beforeRender` | {@link RenderContextCallback} | No | Before DOM update |
536
+ * | `router:afterRender` | {@link RenderContextCallback} | No | After DOM update |
537
+ * | `router:scroll` | {@link ScrollContextCallback} | No | For scroll behavior |
538
+ * | `router:afterEnter` | {@link RouteChangeCallback} | No | After entering route |
539
+ * | `router:afterEach` | {@link RouteChangeCallback} | No | Navigation complete |
540
+ * | `router:error` | {@link RouterErrorCallback} | No | Navigation error |
541
+ * | `router:routeAdded` | {@link RouteAddedCallback} | No | Dynamic route added |
542
+ * | `router:routeRemoved` | {@link RouteRemovedCallback} | No | Dynamic route removed |
543
+ *
544
+ * ## Reactive Signals
545
+ * - `currentRoute: Signal<RouteLocation | null>` - Current route info
546
+ * - `previousRoute: Signal<RouteLocation | null>` - Previous route info
547
+ * - `currentParams: Signal<RouteParams>` - Current route params
548
+ * - `currentQuery: Signal<QueryParams>` - Current query params
549
+ * - `currentLayout: Signal<MountResult | null>` - Mounted layout instance
550
+ * - `currentView: Signal<MountResult | null>` - Mounted view instance
551
+ * - `isReady: Signal<boolean>` - Router readiness state
552
+ *
553
+ * @note Internal API Access Policy:
554
+ * As a core Eleva plugin, the Router may access internal Eleva APIs (prefixed with _)
555
+ * such as `eleva._components`. This is intentional and these internal APIs are
556
+ * considered stable for official plugins. Third-party plugins should avoid
557
+ * accessing internal APIs as they may change without notice.
558
+ *
559
+ * @example
560
+ * // Basic setup
561
+ * const router = new Router(eleva, {
562
+ * mode: 'hash',
563
+ * mount: '#app',
564
+ * routes: [
565
+ * { path: '/', component: HomePage },
566
+ * { path: '/users/:id', component: UserPage },
567
+ * { path: '*', component: NotFoundPage }
568
+ * ]
569
+ * });
570
+ *
571
+ * // Start router
572
+ * await router.start();
573
+ *
574
+ * // Navigate programmatically
575
+ * const success = await router.navigate('/users/123');
576
+ *
577
+ * // Watch for route changes
578
+ * router.currentRoute.watch((route) => {
579
+ * document.title = route?.meta?.title || 'My App';
580
+ * });
581
+ *
582
+ * @private
583
+ */ class Router {
584
+ /**
585
+ * Validates the provided router options.
586
+ * @private
587
+ * @throws {Error} If the routing mode is invalid.
588
+ */ _validateOptions() {
589
+ if (![
590
+ "hash",
591
+ "query",
592
+ "history"
593
+ ].includes(this.options.mode)) {
594
+ this.errorHandler.handle(new Error(`Invalid routing mode: ${this.options.mode}. Must be "hash", "query", or "history".`), "Configuration validation failed");
595
+ }
596
+ }
597
+ /**
598
+ * Pre-processes route definitions to parse their path segments for efficient matching.
599
+ * @private
600
+ * @param {RouteDefinition[]} routes - The raw route definitions.
601
+ * @returns {RouteDefinition[]} The processed routes.
602
+ */ _processRoutes(routes) {
603
+ const processedRoutes = [];
604
+ for (const route of routes){
605
+ try {
606
+ processedRoutes.push({
607
+ ...route,
608
+ segments: this._parsePathIntoSegments(route.path)
609
+ });
610
+ } catch (error) {
611
+ this.errorHandler.warn(`Invalid path in route definition "${route.path || "undefined"}": ${error.message}`, {
612
+ route,
613
+ error
614
+ });
615
+ }
616
+ }
617
+ return processedRoutes;
618
+ }
619
+ /**
620
+ * Parses a route path string into an array of static and parameter segments.
621
+ * @private
622
+ * @param {string} path - The path pattern to parse.
623
+ * @returns {{type: 'static' | 'param', value?: string, name?: string}[]} An array of segment objects.
624
+ * @throws {Error} If the route path is not a valid string.
625
+ */ _parsePathIntoSegments(path) {
626
+ if (!path || typeof path !== "string") {
627
+ this.errorHandler.handle(new Error("Route path must be a non-empty string"), "Path parsing failed", {
628
+ path
629
+ });
630
+ }
631
+ const normalizedPath = path.replace(/\/+/g, "/").replace(/\/$/, "") || "/";
632
+ if (normalizedPath === "/") {
633
+ return [];
634
+ }
635
+ return normalizedPath.split("/").filter(Boolean).map((segment)=>{
636
+ if (segment.startsWith(":")) {
637
+ const paramName = segment.substring(1);
638
+ if (!paramName) {
639
+ this.errorHandler.handle(new Error(`Invalid parameter segment: ${segment}`), "Path parsing failed", {
640
+ segment,
641
+ path
642
+ });
643
+ }
644
+ return {
645
+ type: "param",
646
+ name: paramName
647
+ };
648
+ }
649
+ return {
650
+ type: "static",
651
+ value: segment
652
+ };
653
+ });
654
+ }
655
+ /**
656
+ * Finds the view element within a container using multiple selector strategies.
657
+ * @private
658
+ * @param {HTMLElement} container - The parent element to search within.
659
+ * @returns {HTMLElement} The found view element or the container itself as a fallback.
660
+ */ _findViewElement(container) {
661
+ const selector = this.options.viewSelector;
662
+ return container.querySelector(`#${selector}`) || container.querySelector(`.${selector}`) || container.querySelector(`[data-${selector}]`) || container.querySelector(selector) || container;
663
+ }
664
+ /**
665
+ * Starts the router, initializes event listeners, and performs the initial navigation.
666
+ * @returns {Promise<Router>} The router instance for method chaining.
667
+ * @listens window:hashchange In hash mode, triggers route changes.
668
+ * @listens window:popstate In history/query mode, triggers route changes.
669
+ * @emits router:ready When initialization completes successfully.
670
+ * @see destroy - Stop the router and clean up listeners.
671
+ * @see navigate - Programmatically navigate to a route.
672
+ *
673
+ * @example
674
+ * // Basic usage
675
+ * await router.start();
676
+ *
677
+ * // Method chaining
678
+ * await router.start().then(r => r.navigate('/home'));
679
+ *
680
+ * // Reactive readiness
681
+ * router.isReady.watch((ready) => {
682
+ * if (ready) console.log('Router is ready!');
683
+ * });
684
+ */ async start() {
685
+ if (this.isStarted) {
686
+ this.errorHandler.warn("Router is already started");
687
+ return this;
688
+ }
689
+ if (typeof window === "undefined") {
690
+ this.errorHandler.warn("Router start skipped: `window` object not available (SSR environment)");
691
+ return this;
692
+ }
693
+ if (typeof document !== "undefined" && !document.querySelector(this.options.mount)) {
694
+ this.errorHandler.warn(`Mount element "${this.options.mount}" was not found in the DOM. The router will not start.`, {
695
+ mountSelector: this.options.mount
696
+ });
697
+ return this;
698
+ }
699
+ const handler = ()=>this._handleRouteChange();
700
+ if (this.options.mode === "hash") {
701
+ window.addEventListener("hashchange", handler);
702
+ this.eventListeners.push(()=>window.removeEventListener("hashchange", handler));
703
+ } else {
704
+ window.addEventListener("popstate", handler);
705
+ this.eventListeners.push(()=>window.removeEventListener("popstate", handler));
706
+ }
707
+ this.isStarted = true;
708
+ // Initial navigation is not a popstate event
709
+ await this._handleRouteChange(false);
710
+ // Set isReady to true after initial navigation completes
711
+ this.isReady.value = true;
712
+ await this.emitter.emit("router:ready", this);
713
+ return this;
714
+ }
715
+ /**
716
+ * Stops the router and cleans up event listeners.
717
+ * Unmounts the current layout instance if present.
718
+ * @async
719
+ * @returns {Promise<void>}
720
+ * @see start - Restart the router after destroying.
721
+ */ async destroy() {
722
+ if (!this.isStarted) return;
723
+ // Clean up plugins
724
+ for (const plugin of this.plugins.values()){
725
+ if (typeof plugin.destroy === "function") {
726
+ try {
727
+ await plugin.destroy(this);
728
+ } catch (error) {
729
+ this.errorHandler.log(`Plugin ${plugin.name} destroy failed`, error);
730
+ }
731
+ }
732
+ }
733
+ this.eventListeners.forEach((cleanup)=>cleanup());
734
+ this.eventListeners = [];
735
+ if (this.currentLayout.value) {
736
+ await this.currentLayout.value.unmount();
737
+ }
738
+ this.isStarted = false;
739
+ this.isReady.value = false;
740
+ }
741
+ /**
742
+ * Alias for destroy(). Stops the router and cleans up all resources.
743
+ * Provided for semantic consistency (start/stop pattern).
744
+ * @async
745
+ * @returns {Promise<void>}
746
+ *
747
+ * @example
748
+ * await router.start();
749
+ * // ... later
750
+ * await router.stop();
751
+ */ async stop() {
752
+ return this.destroy();
753
+ }
754
+ /**
755
+ * Programmatically navigates to a new route.
756
+ * @async
757
+ * @param {string | NavigationTarget} location - The target location as a path string or navigation target object.
758
+ * @param {NavigationParams} [params] - Route parameters (only used when location is a string).
759
+ * @returns {Promise<boolean>} True if navigation succeeded, false if blocked by guards or failed.
760
+ * @emits router:error When navigation fails due to an exception.
761
+ * @see start - Initialize the router before navigating.
762
+ * @see currentRoute - Access the current route after navigation.
763
+ *
764
+ * @example
765
+ * // Basic navigation
766
+ * await router.navigate('/users/123');
767
+ *
768
+ * // Check if navigation succeeded
769
+ * const success = await router.navigate('/protected');
770
+ * if (!success) {
771
+ * console.log('Navigation was blocked by a guard');
772
+ * }
773
+ *
774
+ * // Navigate with options
775
+ * await router.navigate({
776
+ * path: '/users/:id',
777
+ * params: { id: '123' },
778
+ * query: { tab: 'profile' },
779
+ * replace: true
780
+ * });
781
+ */ async navigate(location, params = {}) {
782
+ try {
783
+ const target = typeof location === "string" ? {
784
+ path: location,
785
+ params
786
+ } : location;
787
+ let path = this._buildPath(target.path, target.params || {});
788
+ const query = target.query || {};
789
+ if (Object.keys(query).length > 0) {
790
+ const queryString = new URLSearchParams(query).toString();
791
+ if (queryString) path += `?${queryString}`;
792
+ }
793
+ if (this._isSameRoute(path, target.params, query)) {
794
+ return true; // Already at this route, consider it successful
795
+ }
796
+ const navigationSuccessful = await this._proceedWithNavigation(path);
797
+ if (navigationSuccessful) {
798
+ // Increment navigation ID and capture it for this navigation
799
+ const currentNavId = ++this._navigationId;
800
+ this._isNavigating = true;
801
+ const state = target.state || {};
802
+ const replace = target.replace || false;
803
+ const historyMethod = replace ? "replaceState" : "pushState";
804
+ if (this.options.mode === "hash") {
805
+ if (replace) {
806
+ const newUrl = `${window.location.pathname}${window.location.search}#${path}`;
807
+ window.history.replaceState(state, "", newUrl);
808
+ } else {
809
+ window.location.hash = path;
810
+ }
811
+ } else {
812
+ const url = this.options.mode === "query" ? this._buildQueryUrl(path) : path;
813
+ history[historyMethod](state, "", url);
814
+ }
815
+ // Only reset the flag if no newer navigation has started
816
+ queueMicrotask(()=>{
817
+ if (this._navigationId === currentNavId) {
818
+ this._isNavigating = false;
819
+ }
820
+ });
821
+ }
822
+ return navigationSuccessful;
823
+ } catch (error) {
824
+ this.errorHandler.log("Navigation failed", error);
825
+ await this.emitter.emit("router:error", error);
826
+ return false;
827
+ }
828
+ }
829
+ /**
830
+ * Builds a URL for query mode.
831
+ * @private
832
+ * @param {string} path - The path to set as the query parameter.
833
+ * @returns {string} The full URL with the updated query string.
834
+ */ _buildQueryUrl(path) {
835
+ const urlParams = new URLSearchParams(window.location.search);
836
+ urlParams.set(this.options.queryParam, path.split("?")[0]);
837
+ return `${window.location.pathname}?${urlParams.toString()}`;
838
+ }
839
+ /**
840
+ * Checks if the target route is identical to the current route.
841
+ * @private
842
+ * @param {string} path - The target path with query string.
843
+ * @param {object} params - The target params.
844
+ * @param {object} query - The target query.
845
+ * @returns {boolean} True if the routes are the same.
846
+ */ _isSameRoute(path, params, query) {
847
+ const current = this.currentRoute.value;
848
+ if (!current) return false;
849
+ const [targetPath, queryString] = path.split("?");
850
+ const targetQuery = query || this._parseQuery(queryString || "");
851
+ return current.path === targetPath && JSON.stringify(current.params) === JSON.stringify(params || {}) && JSON.stringify(current.query) === JSON.stringify(targetQuery);
852
+ }
853
+ /**
854
+ * Injects dynamic parameters into a path string.
855
+ * Replaces `:param` placeholders with URL-encoded values from the params object.
856
+ *
857
+ * @private
858
+ * @param {string} path - The path pattern containing `:param` placeholders.
859
+ * @param {RouteParams} params - Key-value pairs to inject into the path.
860
+ * @returns {string} The path with all parameters replaced.
861
+ *
862
+ * @example
863
+ * this._buildPath('/users/:id/posts/:postId', { id: '123', postId: '456' });
864
+ * // Returns: '/users/123/posts/456'
865
+ */ _buildPath(path, params) {
866
+ let result = path;
867
+ for (const [key, value] of Object.entries(params)){
868
+ // Fix: Handle special characters and ensure proper encoding
869
+ const encodedValue = encodeURIComponent(String(value));
870
+ result = result.replace(new RegExp(`:${key}\\b`, "g"), encodedValue);
871
+ }
872
+ return result;
873
+ }
874
+ /**
875
+ * The handler for browser-initiated route changes (e.g., back/forward buttons).
876
+ *
877
+ * @private
878
+ * @async
879
+ * @param {boolean} [isPopState=true] - Whether this is a popstate event (back/forward navigation).
880
+ * @returns {Promise<void>}
881
+ * @emits router:error When route change handling fails.
882
+ */ async _handleRouteChange(isPopState = true) {
883
+ if (this._isNavigating) return;
884
+ try {
885
+ const from = this.currentRoute.value;
886
+ const toLocation = this._getCurrentLocation();
887
+ const navigationSuccessful = await this._proceedWithNavigation(toLocation.fullUrl, isPopState);
888
+ // If navigation was blocked by a guard, revert the URL change
889
+ if (!navigationSuccessful && from) {
890
+ this.navigate({
891
+ path: from.path,
892
+ query: from.query,
893
+ replace: true
894
+ });
895
+ }
896
+ } catch (error) {
897
+ this.errorHandler.log("Route change handling failed", error, {
898
+ currentUrl: typeof window !== "undefined" ? window.location.href : ""
899
+ });
900
+ await this.emitter.emit("router:error", error);
901
+ }
902
+ }
903
+ /**
904
+ * Manages the core navigation lifecycle. Runs guards before committing changes.
905
+ *
906
+ * @private
907
+ * @async
908
+ * @param {string} fullPath - The full path (e.g., '/users/123?foo=bar') to navigate to.
909
+ * @param {boolean} [isPopState=false] - Whether this navigation was triggered by popstate (back/forward).
910
+ * @returns {Promise<boolean>} `true` if navigation succeeded, `false` if aborted.
911
+ * @emits router:notFound When no matching route is found.
912
+ * @emits router:beforeResolve Before component resolution (can block/redirect).
913
+ * @emits router:afterResolve After components are resolved.
914
+ * @emits router:afterLeave After leaving the previous route.
915
+ * @emits router:beforeRender Before DOM rendering.
916
+ * @emits router:afterRender After DOM rendering completes.
917
+ * @emits router:scroll After render, for scroll behavior handling.
918
+ * @emits router:afterEnter After entering the new route.
919
+ * @emits router:afterEach After navigation completes successfully.
920
+ * @emits router:error When an error occurs during navigation.
921
+ * @see _runGuards - Guard execution.
922
+ * @see _resolveComponents - Component resolution.
923
+ * @see _render - DOM rendering.
924
+ */ async _proceedWithNavigation(fullPath, isPopState = false) {
925
+ const from = this.currentRoute.value;
926
+ const [path, queryString] = (fullPath || "/").split("?");
927
+ const toLocation = {
928
+ path: path.startsWith("/") ? path : `/${path}`,
929
+ query: this._parseQuery(queryString),
930
+ fullUrl: fullPath
931
+ };
932
+ let toMatch = this._matchRoute(toLocation.path);
933
+ if (!toMatch) {
934
+ const notFoundRoute = this.routes.find((route)=>route.path === "*");
935
+ if (notFoundRoute) {
936
+ toMatch = {
937
+ route: notFoundRoute,
938
+ params: {
939
+ pathMatch: decodeURIComponent(toLocation.path.substring(1))
940
+ }
941
+ };
942
+ } else {
943
+ await this.emitter.emit("router:error", new Error(`Route not found: ${toLocation.path}`), toLocation, from);
944
+ return false;
945
+ }
946
+ }
947
+ const to = {
948
+ ...toLocation,
949
+ params: toMatch.params,
950
+ meta: toMatch.route.meta || {},
951
+ name: toMatch.route.name,
952
+ matched: toMatch.route
953
+ };
954
+ try {
955
+ // 1. Run all *pre-navigation* guards.
956
+ const canNavigate = await this._runGuards(to, from, toMatch.route);
957
+ if (!canNavigate) return false;
958
+ // 2. Save current scroll position before navigating away
959
+ if (from && typeof window !== "undefined") {
960
+ this._scrollPositions.set(from.path, {
961
+ x: window.scrollX || window.pageXOffset || 0,
962
+ y: window.scrollY || window.pageYOffset || 0
963
+ });
964
+ }
965
+ // 3. Emit beforeResolve event - plugins can show loading indicators
966
+ /** @type {ResolveContext} */ const resolveContext = {
967
+ to,
968
+ from,
969
+ route: toMatch.route,
970
+ layoutComponent: null,
971
+ pageComponent: null,
972
+ cancelled: false,
973
+ redirectTo: null
974
+ };
975
+ await this.emitter.emit("router:beforeResolve", resolveContext);
976
+ // Check if resolution was cancelled or redirected
977
+ if (resolveContext.cancelled) return false;
978
+ if (resolveContext.redirectTo) {
979
+ this.navigate(resolveContext.redirectTo);
980
+ return false;
981
+ }
982
+ // 4. Resolve async components *before* touching the DOM.
983
+ const { layoutComponent, pageComponent } = await this._resolveComponents(toMatch.route);
984
+ // 5. Emit afterResolve event - plugins can hide loading indicators
985
+ resolveContext.layoutComponent = layoutComponent;
986
+ resolveContext.pageComponent = pageComponent;
987
+ await this.emitter.emit("router:afterResolve", resolveContext);
988
+ // 6. Unmount the previous view/layout.
989
+ if (from) {
990
+ const toLayout = toMatch.route.layout || this.options.globalLayout;
991
+ const fromLayout = from.matched.layout || this.options.globalLayout;
992
+ const tryUnmount = async (instance)=>{
993
+ if (!instance) return;
994
+ try {
995
+ await instance.unmount();
996
+ } catch (error) {
997
+ this.errorHandler.warn("Error during component unmount", {
998
+ error,
999
+ instance
1000
+ });
1001
+ }
1002
+ };
1003
+ if (toLayout !== fromLayout) {
1004
+ await tryUnmount(this.currentLayout.value);
1005
+ this.currentLayout.value = null;
1006
+ } else {
1007
+ await tryUnmount(this.currentView.value);
1008
+ this.currentView.value = null;
1009
+ }
1010
+ // Call `afterLeave` hook *after* the old component has been unmounted.
1011
+ if (from.matched.afterLeave) {
1012
+ await from.matched.afterLeave(to, from);
1013
+ }
1014
+ await this.emitter.emit("router:afterLeave", to, from);
1015
+ }
1016
+ // 7. Update reactive state.
1017
+ this.previousRoute.value = from;
1018
+ this.currentRoute.value = to;
1019
+ this.currentParams.value = to.params || {};
1020
+ this.currentQuery.value = to.query || {};
1021
+ // 8. Emit beforeRender event - plugins can add transitions
1022
+ /** @type {RenderContext} */ const renderContext = {
1023
+ to,
1024
+ from,
1025
+ layoutComponent,
1026
+ pageComponent
1027
+ };
1028
+ await this.emitter.emit("router:beforeRender", renderContext);
1029
+ // 9. Render the new components.
1030
+ await this._render(layoutComponent, pageComponent);
1031
+ // 10. Emit afterRender event - plugins can trigger animations
1032
+ await this.emitter.emit("router:afterRender", renderContext);
1033
+ // 11. Emit scroll event - plugins can handle scroll restoration
1034
+ /** @type {ScrollContext} */ const scrollContext = {
1035
+ to,
1036
+ from,
1037
+ savedPosition: isPopState ? this._scrollPositions.get(to.path) || null : null
1038
+ };
1039
+ await this.emitter.emit("router:scroll", scrollContext);
1040
+ // 12. Run post-navigation hooks.
1041
+ if (toMatch.route.afterEnter) {
1042
+ await toMatch.route.afterEnter(to, from);
1043
+ }
1044
+ await this.emitter.emit("router:afterEnter", to, from);
1045
+ await this.emitter.emit("router:afterEach", to, from);
1046
+ return true;
1047
+ } catch (error) {
1048
+ this.errorHandler.log("Error during navigation", error, {
1049
+ to,
1050
+ from
1051
+ });
1052
+ await this.emitter.emit("router:error", error, to, from);
1053
+ return false;
1054
+ }
1055
+ }
1056
+ /**
1057
+ * Executes all applicable navigation guards for a transition in order.
1058
+ * Guards are executed in the following order:
1059
+ * 1. Global beforeEach event (emitter-based, can block via context)
1060
+ * 2. Global beforeEach guards (registered via onBeforeEach)
1061
+ * 3. Route-specific beforeLeave guard (from the route being left)
1062
+ * 4. Route-specific beforeEnter guard (from the route being entered)
1063
+ *
1064
+ * @private
1065
+ * @param {RouteLocation} to - The target route location.
1066
+ * @param {RouteLocation | null} from - The current route location (null on initial navigation).
1067
+ * @param {RouteDefinition} route - The matched route definition.
1068
+ * @returns {Promise<boolean>} `false` if navigation should be aborted.
1069
+ * @emits router:beforeEach Before guards run (can block/redirect via context).
1070
+ */ async _runGuards(to, from, route) {
1071
+ // Create navigation context that plugins can modify to block navigation
1072
+ /** @type {NavigationContext} */ const navContext = {
1073
+ to,
1074
+ from,
1075
+ cancelled: false,
1076
+ redirectTo: null
1077
+ };
1078
+ // Emit beforeEach event with context - plugins can block by modifying context
1079
+ await this.emitter.emit("router:beforeEach", navContext);
1080
+ // Check if navigation was cancelled or redirected by event listeners
1081
+ if (navContext.cancelled) return false;
1082
+ if (navContext.redirectTo) {
1083
+ this.navigate(navContext.redirectTo);
1084
+ return false;
1085
+ }
1086
+ // Collect all guards in execution order
1087
+ const guards = [
1088
+ ...this._beforeEachGuards,
1089
+ ...from && from.matched.beforeLeave ? [
1090
+ from.matched.beforeLeave
1091
+ ] : [],
1092
+ ...route.beforeEnter ? [
1093
+ route.beforeEnter
1094
+ ] : []
1095
+ ];
1096
+ for (const guard of guards){
1097
+ const result = await guard(to, from);
1098
+ if (result === false) return false;
1099
+ if (typeof result === "string" || typeof result === "object") {
1100
+ this.navigate(result);
1101
+ return false;
1102
+ }
1103
+ }
1104
+ return true;
1105
+ }
1106
+ /**
1107
+ * Resolves a string component definition to a component object.
1108
+ * @private
1109
+ * @param {string} def - The component name to resolve.
1110
+ * @returns {ComponentDefinition} The resolved component.
1111
+ * @throws {Error} If the component is not registered.
1112
+ *
1113
+ * @note Core plugins (Router, Attr, Store) may access eleva._components
1114
+ * directly. This is intentional and stable for official Eleva plugins shipped
1115
+ * with the framework. Third-party plugins should use eleva.component() for
1116
+ * registration and avoid direct access to internal APIs.
1117
+ */ _resolveStringComponent(def) {
1118
+ const componentDef = this.eleva._components.get(def);
1119
+ if (!componentDef) {
1120
+ this.errorHandler.handle(new Error(`Component "${def}" not registered.`), "Component resolution failed", {
1121
+ componentName: def,
1122
+ availableComponents: Array.from(this.eleva._components.keys())
1123
+ });
1124
+ }
1125
+ return componentDef;
1126
+ }
1127
+ /**
1128
+ * Resolves a function component definition to a component object.
1129
+ * @private
1130
+ * @async
1131
+ * @param {() => ComponentDefinition | Promise<ComponentDefinition | { default: ComponentDefinition }>} def - The function to resolve.
1132
+ * @returns {Promise<ComponentDefinition>} The resolved component.
1133
+ * @throws {Error} If the function fails to load the component.
1134
+ */ async _resolveFunctionComponent(def) {
1135
+ try {
1136
+ const funcStr = def.toString();
1137
+ const isAsyncImport = funcStr.includes("import(") || funcStr.startsWith("() =>");
1138
+ const result = await def();
1139
+ return isAsyncImport ? result.default || result : result;
1140
+ } catch (error) {
1141
+ this.errorHandler.handle(new Error(`Failed to load async component: ${error.message}`), "Component resolution failed", {
1142
+ function: def.toString(),
1143
+ error
1144
+ });
1145
+ }
1146
+ }
1147
+ /**
1148
+ * Validates a component definition object.
1149
+ * @private
1150
+ * @param {unknown} def - The component definition to validate.
1151
+ * @returns {ComponentDefinition} The validated component.
1152
+ * @throws {Error} If the component definition is invalid.
1153
+ */ _validateComponentDefinition(def) {
1154
+ if (!def || typeof def !== "object") {
1155
+ this.errorHandler.handle(new Error(`Invalid component definition: ${typeof def}`), "Component validation failed", {
1156
+ definition: def
1157
+ });
1158
+ }
1159
+ if (typeof def.template !== "function" && typeof def.template !== "string") {
1160
+ this.errorHandler.handle(new Error("Component missing template property"), "Component validation failed", {
1161
+ definition: def
1162
+ });
1163
+ }
1164
+ return def;
1165
+ }
1166
+ /**
1167
+ * Resolves a component definition to a component object.
1168
+ * @private
1169
+ * @param {unknown} def - The component definition to resolve.
1170
+ * @returns {Promise<ComponentDefinition | null>} The resolved component or null.
1171
+ */ async _resolveComponent(def) {
1172
+ if (def === null || def === undefined) {
1173
+ return null;
1174
+ }
1175
+ if (typeof def === "string") {
1176
+ return this._resolveStringComponent(def);
1177
+ }
1178
+ if (typeof def === "function") {
1179
+ return await this._resolveFunctionComponent(def);
1180
+ }
1181
+ if (def && typeof def === "object") {
1182
+ return this._validateComponentDefinition(def);
1183
+ }
1184
+ this.errorHandler.handle(new Error(`Invalid component definition: ${typeof def}`), "Component resolution failed", {
1185
+ definition: def
1186
+ });
1187
+ }
1188
+ /**
1189
+ * Asynchronously resolves the layout and page components for a route.
1190
+ * @private
1191
+ * @async
1192
+ * @param {RouteDefinition} route - The route to resolve components for.
1193
+ * @returns {Promise<{layoutComponent: ComponentDefinition | null, pageComponent: ComponentDefinition}>}
1194
+ * @throws {Error} If page component cannot be resolved.
1195
+ */ async _resolveComponents(route) {
1196
+ const effectiveLayout = route.layout || this.options.globalLayout;
1197
+ try {
1198
+ const [layoutComponent, pageComponent] = await Promise.all([
1199
+ this._resolveComponent(effectiveLayout),
1200
+ this._resolveComponent(route.component)
1201
+ ]);
1202
+ if (!pageComponent) {
1203
+ this.errorHandler.handle(new Error(`Page component is null or undefined for route: ${route.path}`), "Component resolution failed", {
1204
+ route: route.path
1205
+ });
1206
+ }
1207
+ return {
1208
+ layoutComponent,
1209
+ pageComponent
1210
+ };
1211
+ } catch (error) {
1212
+ this.errorHandler.log(`Error resolving components for route ${route.path}`, error, {
1213
+ route: route.path
1214
+ });
1215
+ throw error;
1216
+ }
1217
+ }
1218
+ /**
1219
+ * Renders the components for the current route into the DOM.
1220
+ *
1221
+ * Rendering algorithm:
1222
+ * 1. Find the mount element using options.mount selector
1223
+ * 2. If layoutComponent exists:
1224
+ * a. Mount layout to mount element
1225
+ * b. Find view element within layout (using viewSelector)
1226
+ * c. Mount page component to view element
1227
+ * 3. If no layoutComponent:
1228
+ * a. Mount page component directly to mount element
1229
+ * b. Set currentLayout to null
1230
+ *
1231
+ * @private
1232
+ * @async
1233
+ * @param {ComponentDefinition | null} layoutComponent - The pre-loaded layout component.
1234
+ * @param {ComponentDefinition} pageComponent - The pre-loaded page component.
1235
+ * @returns {Promise<void>}
1236
+ * @throws {Error} If mount element is not found in the DOM.
1237
+ * @throws {Error} If component mounting fails (propagated from eleva.mount).
1238
+ */ async _render(layoutComponent, pageComponent) {
1239
+ const mountEl = document.querySelector(this.options.mount);
1240
+ if (!mountEl) {
1241
+ this.errorHandler.handle(new Error(`Mount element "${this.options.mount}" not found.`), {
1242
+ mountSelector: this.options.mount
1243
+ });
1244
+ }
1245
+ if (layoutComponent) {
1246
+ const layoutInstance = await this.eleva.mount(mountEl, this._wrapComponentWithChildren(layoutComponent));
1247
+ this.currentLayout.value = layoutInstance;
1248
+ const viewEl = this._findViewElement(layoutInstance.container);
1249
+ const viewInstance = await this.eleva.mount(viewEl, this._wrapComponentWithChildren(pageComponent));
1250
+ this.currentView.value = viewInstance;
1251
+ } else {
1252
+ const viewInstance = await this.eleva.mount(mountEl, this._wrapComponentWithChildren(pageComponent));
1253
+ this.currentView.value = viewInstance;
1254
+ this.currentLayout.value = null;
1255
+ }
1256
+ }
1257
+ /**
1258
+ * Creates a getter function for router context properties.
1259
+ * @private
1260
+ * @param {string} property - The property name to access.
1261
+ * @param {unknown} defaultValue - The default value if property is undefined.
1262
+ * @returns {() => unknown} A getter function.
1263
+ */ _createRouteGetter(property, defaultValue) {
1264
+ return ()=>this.currentRoute.value?.[property] ?? defaultValue;
1265
+ }
1266
+ /**
1267
+ * Wraps a component definition to inject router-specific context into its setup function.
1268
+ * @private
1269
+ * @param {ComponentDefinition} component - The component to wrap.
1270
+ * @returns {ComponentDefinition} The wrapped component definition.
1271
+ */ _wrapComponent(component) {
1272
+ const originalSetup = component.setup;
1273
+ const self = this;
1274
+ return {
1275
+ ...component,
1276
+ async setup (ctx) {
1277
+ /** @type {RouterContext} */ ctx.router = {
1278
+ navigate: self.navigate.bind(self),
1279
+ current: self.currentRoute,
1280
+ previous: self.previousRoute,
1281
+ // Route property getters
1282
+ get params () {
1283
+ return self._createRouteGetter("params", {})();
1284
+ },
1285
+ get query () {
1286
+ return self._createRouteGetter("query", {})();
1287
+ },
1288
+ get path () {
1289
+ return self._createRouteGetter("path", "/")();
1290
+ },
1291
+ get fullUrl () {
1292
+ return self._createRouteGetter("fullUrl", window.location.href)();
1293
+ },
1294
+ get meta () {
1295
+ return self._createRouteGetter("meta", {})();
1296
+ }
1297
+ };
1298
+ return originalSetup ? await originalSetup(ctx) : {};
1299
+ }
1300
+ };
1301
+ }
1302
+ /**
1303
+ * Recursively wraps all child components to ensure they have access to router context.
1304
+ * String component references are returned as-is (context injected during mount).
1305
+ * Objects are wrapped with router context and their children are recursively wrapped.
1306
+ *
1307
+ * @private
1308
+ * @param {ComponentDefinition | string} component - The component to wrap (can be a definition object or a registered component name).
1309
+ * @returns {ComponentDefinition | string} The wrapped component definition or the original string reference.
1310
+ * @see _wrapComponent - Single component wrapping.
1311
+ */ _wrapComponentWithChildren(component) {
1312
+ // If the component is a string (registered component name), return as-is
1313
+ // The router context will be injected when the component is resolved during mounting
1314
+ if (typeof component === "string") {
1315
+ return component;
1316
+ }
1317
+ // If not a valid component object, return as-is
1318
+ if (!component || typeof component !== "object") {
1319
+ return component;
1320
+ }
1321
+ const wrappedComponent = this._wrapComponent(component);
1322
+ // If the component has children, wrap them too
1323
+ if (wrappedComponent.children && typeof wrappedComponent.children === "object") {
1324
+ const wrappedChildren = {};
1325
+ for (const [selector, childComponent] of Object.entries(wrappedComponent.children)){
1326
+ wrappedChildren[selector] = this._wrapComponentWithChildren(childComponent);
1327
+ }
1328
+ wrappedComponent.children = wrappedChildren;
1329
+ }
1330
+ return wrappedComponent;
1331
+ }
1332
+ /**
1333
+ * Gets the current location information from the browser's window object.
1334
+ * @private
1335
+ * @returns {Omit<RouteLocation, 'params' | 'meta' | 'name' | 'matched'>}
1336
+ */ _getCurrentLocation() {
1337
+ if (typeof window === "undefined") return {
1338
+ path: "/",
1339
+ query: {},
1340
+ fullUrl: ""
1341
+ };
1342
+ let path, queryString, fullUrl;
1343
+ switch(this.options.mode){
1344
+ case "hash":
1345
+ fullUrl = window.location.hash.slice(1) || "/";
1346
+ [path, queryString] = fullUrl.split("?");
1347
+ break;
1348
+ case "query":
1349
+ const urlParams = new URLSearchParams(window.location.search);
1350
+ path = urlParams.get(this.options.queryParam) || "/";
1351
+ queryString = window.location.search.slice(1);
1352
+ fullUrl = path;
1353
+ break;
1354
+ default:
1355
+ path = window.location.pathname || "/";
1356
+ queryString = window.location.search.slice(1);
1357
+ fullUrl = `${path}${queryString ? "?" + queryString : ""}`;
1358
+ }
1359
+ return {
1360
+ path: path.startsWith("/") ? path : `/${path}`,
1361
+ query: this._parseQuery(queryString),
1362
+ fullUrl
1363
+ };
1364
+ }
1365
+ /**
1366
+ * Parses a query string into a key-value object.
1367
+ * Uses URLSearchParams for robust parsing of encoded values.
1368
+ *
1369
+ * @private
1370
+ * @param {string} queryString - The query string to parse (without leading '?').
1371
+ * @returns {QueryParams} Key-value pairs from the query string.
1372
+ *
1373
+ * @example
1374
+ * this._parseQuery('foo=bar&baz=qux');
1375
+ * // Returns: { foo: 'bar', baz: 'qux' }
1376
+ */ _parseQuery(queryString) {
1377
+ const query = {};
1378
+ if (queryString) {
1379
+ new URLSearchParams(queryString).forEach((value, key)=>{
1380
+ query[key] = value;
1381
+ });
1382
+ }
1383
+ return query;
1384
+ }
1385
+ /**
1386
+ * Matches a given path against the registered routes.
1387
+ * @private
1388
+ * @param {string} path - The path to match.
1389
+ * @returns {{route: RouteDefinition, params: Object<string, string>} | null} The matched route and its params, or null.
1390
+ */ _matchRoute(path) {
1391
+ const pathSegments = path.split("/").filter(Boolean);
1392
+ for (const route of this.routes){
1393
+ // Handle the root path as a special case.
1394
+ if (route.path === "/") {
1395
+ if (pathSegments.length === 0) return {
1396
+ route,
1397
+ params: {}
1398
+ };
1399
+ continue;
1400
+ }
1401
+ if (route.segments.length !== pathSegments.length) continue;
1402
+ const params = {};
1403
+ let isMatch = true;
1404
+ for(let i = 0; i < route.segments.length; i++){
1405
+ const routeSegment = route.segments[i];
1406
+ const pathSegment = pathSegments[i];
1407
+ if (routeSegment.type === "param") {
1408
+ params[routeSegment.name] = decodeURIComponent(pathSegment);
1409
+ } else if (routeSegment.value !== pathSegment) {
1410
+ isMatch = false;
1411
+ break;
1412
+ }
1413
+ }
1414
+ if (isMatch) return {
1415
+ route,
1416
+ params
1417
+ };
1418
+ }
1419
+ return null;
1420
+ }
1421
+ // ============================================
1422
+ // Dynamic Route Management API
1423
+ // ============================================
1424
+ /**
1425
+ * Adds a new route dynamically at runtime.
1426
+ * The route will be processed and available for navigation immediately.
1427
+ * Routes are inserted before the wildcard (*) route if one exists.
1428
+ *
1429
+ * @param {RouteDefinition} route - The route definition to add.
1430
+ * @param {RouteDefinition} [parentRoute] - Optional parent route to add as a child (not yet implemented).
1431
+ * @returns {() => void} A function to remove the added route (returns no-op if route was invalid).
1432
+ * @emits router:routeAdded When a route is successfully added.
1433
+ *
1434
+ * @example
1435
+ * // Add a route dynamically
1436
+ * const removeRoute = router.addRoute({
1437
+ * path: '/dynamic',
1438
+ * component: DynamicPage,
1439
+ * meta: { title: 'Dynamic Page' }
1440
+ * });
1441
+ *
1442
+ * // Later, remove the route
1443
+ * removeRoute();
1444
+ */ addRoute(route, parentRoute = null) {
1445
+ if (!route || !route.path) {
1446
+ this.errorHandler.warn("Invalid route definition: missing path", {
1447
+ route
1448
+ });
1449
+ return ()=>{};
1450
+ }
1451
+ // Check if route already exists
1452
+ if (this.hasRoute(route.path)) {
1453
+ this.errorHandler.warn(`Route "${route.path}" already exists`, {
1454
+ route
1455
+ });
1456
+ return ()=>{};
1457
+ }
1458
+ // Process the route (parse segments)
1459
+ const processedRoute = {
1460
+ ...route,
1461
+ segments: this._parsePathIntoSegments(route.path)
1462
+ };
1463
+ // Add to routes array (before wildcard if exists)
1464
+ const wildcardIndex = this.routes.findIndex((r)=>r.path === "*");
1465
+ if (wildcardIndex !== -1) {
1466
+ this.routes.splice(wildcardIndex, 0, processedRoute);
1467
+ } else {
1468
+ this.routes.push(processedRoute);
1469
+ }
1470
+ // Emit event for plugins
1471
+ this.emitter.emit("router:routeAdded", processedRoute);
1472
+ // Return removal function
1473
+ return ()=>this.removeRoute(route.path);
1474
+ }
1475
+ /**
1476
+ * Removes a route by its path.
1477
+ *
1478
+ * @param {string} path - The path of the route to remove.
1479
+ * @returns {boolean} True if the route was removed, false if not found.
1480
+ * @emits router:routeRemoved When a route is successfully removed.
1481
+ *
1482
+ * @example
1483
+ * router.removeRoute('/dynamic');
1484
+ */ removeRoute(path) {
1485
+ const index = this.routes.findIndex((r)=>r.path === path);
1486
+ if (index === -1) {
1487
+ return false;
1488
+ }
1489
+ const [removedRoute] = this.routes.splice(index, 1);
1490
+ // Emit event for plugins
1491
+ this.emitter.emit("router:routeRemoved", removedRoute);
1492
+ return true;
1493
+ }
1494
+ /**
1495
+ * Checks if a route with the given path exists.
1496
+ *
1497
+ * @param {string} path - The path to check.
1498
+ * @returns {boolean} True if the route exists.
1499
+ *
1500
+ * @example
1501
+ * if (router.hasRoute('/users/:id')) {
1502
+ * console.log('User route exists');
1503
+ * }
1504
+ */ hasRoute(path) {
1505
+ return this.routes.some((r)=>r.path === path);
1506
+ }
1507
+ /**
1508
+ * Gets all registered routes.
1509
+ *
1510
+ * @returns {RouteDefinition[]} A copy of the routes array.
1511
+ *
1512
+ * @example
1513
+ * const routes = router.getRoutes();
1514
+ * console.log('Available routes:', routes.map(r => r.path));
1515
+ */ getRoutes() {
1516
+ return [
1517
+ ...this.routes
1518
+ ];
1519
+ }
1520
+ /**
1521
+ * Gets a route by its path.
1522
+ *
1523
+ * @param {string} path - The path of the route to get.
1524
+ * @returns {RouteDefinition | undefined} The route definition or undefined.
1525
+ *
1526
+ * @example
1527
+ * const route = router.getRoute('/users/:id');
1528
+ * if (route) {
1529
+ * console.log('Route meta:', route.meta);
1530
+ * }
1531
+ */ getRoute(path) {
1532
+ return this.routes.find((r)=>r.path === path);
1533
+ }
1534
+ // ============================================
1535
+ // Hook Registration Methods
1536
+ // ============================================
1537
+ /**
1538
+ * Registers a global pre-navigation guard.
1539
+ * Multiple guards can be registered and will be executed in order.
1540
+ * Guards can also be registered via the emitter using `router:beforeEach` event.
1541
+ *
1542
+ * @param {NavigationGuard} guard - The guard function to register.
1543
+ * @returns {() => void} A function to unregister the guard.
1544
+ *
1545
+ * @example
1546
+ * // Register a guard
1547
+ * const unregister = router.onBeforeEach((to, from) => {
1548
+ * if (to.meta.requiresAuth && !isAuthenticated()) {
1549
+ * return '/login';
1550
+ * }
1551
+ * });
1552
+ *
1553
+ * // Later, unregister the guard
1554
+ * unregister();
1555
+ */ onBeforeEach(guard) {
1556
+ this._beforeEachGuards.push(guard);
1557
+ return ()=>{
1558
+ const index = this._beforeEachGuards.indexOf(guard);
1559
+ if (index > -1) {
1560
+ this._beforeEachGuards.splice(index, 1);
1561
+ }
1562
+ };
1563
+ }
1564
+ /**
1565
+ * Registers a global hook that runs after a new route component has been mounted.
1566
+ * @param {NavigationHook} hook - The hook function to register.
1567
+ * @returns {() => void} A function to unregister the hook.
1568
+ * @listens router:afterEnter
1569
+ */ onAfterEnter(hook) {
1570
+ return this.emitter.on("router:afterEnter", hook);
1571
+ }
1572
+ /**
1573
+ * Registers a global hook that runs after a route component has been unmounted.
1574
+ * @param {NavigationHook} hook - The hook function to register.
1575
+ * @returns {() => void} A function to unregister the hook.
1576
+ * @listens router:afterLeave
1577
+ */ onAfterLeave(hook) {
1578
+ return this.emitter.on("router:afterLeave", hook);
1579
+ }
1580
+ /**
1581
+ * Registers a global hook that runs after a navigation has been confirmed and all hooks have completed.
1582
+ * @param {NavigationHook} hook - The hook function to register.
1583
+ * @returns {() => void} A function to unregister the hook.
1584
+ * @listens router:afterEach
1585
+ */ onAfterEach(hook) {
1586
+ return this.emitter.on("router:afterEach", hook);
1587
+ }
1588
+ /**
1589
+ * Registers a global error handler for navigation errors.
1590
+ * @param {(error: Error, to?: RouteLocation, from?: RouteLocation) => void} handler - The error handler function.
1591
+ * @returns {() => void} A function to unregister the handler.
1592
+ * @listens router:error
1593
+ */ onError(handler) {
1594
+ return this.emitter.on("router:error", handler);
1595
+ }
1596
+ /**
1597
+ * Registers a plugin with the router.
1598
+ * Logs a warning if the plugin is already registered.
1599
+ *
1600
+ * @param {RouterPlugin} plugin - The plugin to register (must have install method).
1601
+ * @param {Record<string, unknown>} [options={}] - Options to pass to plugin.install().
1602
+ * @returns {void}
1603
+ * @throws {Error} If plugin does not have an install method.
1604
+ */ use(plugin, options = {}) {
1605
+ if (typeof plugin.install !== "function") {
1606
+ this.errorHandler.handle(new Error("Plugin must have an install method"), "Plugin registration failed", {
1607
+ plugin
1608
+ });
1609
+ }
1610
+ // Check if plugin is already registered
1611
+ if (this.plugins.has(plugin.name)) {
1612
+ this.errorHandler.warn(`Plugin "${plugin.name}" is already registered`, {
1613
+ existingPlugin: this.plugins.get(plugin.name)
1614
+ });
1615
+ return;
1616
+ }
1617
+ this.plugins.set(plugin.name, plugin);
1618
+ plugin.install(this, options);
1619
+ }
1620
+ /**
1621
+ * Gets all registered plugins.
1622
+ * @returns {RouterPlugin[]} Array of registered plugins.
1623
+ */ getPlugins() {
1624
+ return Array.from(this.plugins.values());
1625
+ }
1626
+ /**
1627
+ * Gets a plugin by name.
1628
+ * @param {string} name - The plugin name.
1629
+ * @returns {RouterPlugin | undefined} The plugin or undefined.
1630
+ */ getPlugin(name) {
1631
+ return this.plugins.get(name);
1632
+ }
1633
+ /**
1634
+ * Removes a plugin from the router.
1635
+ * @param {string} name - The plugin name.
1636
+ * @returns {boolean} True if the plugin was removed.
1637
+ */ removePlugin(name) {
1638
+ const plugin = this.plugins.get(name);
1639
+ if (!plugin) return false;
1640
+ // Call destroy if available
1641
+ if (typeof plugin.destroy === "function") {
1642
+ try {
1643
+ plugin.destroy(this);
1644
+ } catch (error) {
1645
+ this.errorHandler.log(`Plugin ${name} destroy failed`, error);
1646
+ }
1647
+ }
1648
+ return this.plugins.delete(name);
1649
+ }
1650
+ /**
1651
+ * Sets a custom error handler. Used by error handling plugins.
1652
+ * Logs a warning if the provided handler is invalid (missing required methods).
1653
+ * @param {RouterErrorHandler} errorHandler - The error handler object with handle, warn, and log methods.
1654
+ * @returns {void}
1655
+ */ setErrorHandler(errorHandler) {
1656
+ if (errorHandler && typeof errorHandler.handle === "function" && typeof errorHandler.warn === "function" && typeof errorHandler.log === "function") {
1657
+ this.errorHandler = errorHandler;
1658
+ } else {
1659
+ console.warn("[ElevaRouter] Invalid error handler provided. Must have handle, warn, and log methods.");
1660
+ }
1661
+ }
1662
+ /**
1663
+ * Creates an instance of the Router.
1664
+ * @param {Eleva} eleva - The Eleva framework instance.
1665
+ * @param {RouterOptions} options - The configuration options for the router.
1666
+ * @throws {Error} If the routing mode is invalid.
1667
+ */ constructor(eleva, options = {}){
1668
+ /** @type {Eleva} The Eleva framework instance. */ this.eleva = eleva;
1669
+ /** @type {RouterOptions} The merged router options. */ this.options = {
1670
+ mode: "hash",
1671
+ queryParam: "view",
1672
+ viewSelector: "view",
1673
+ ...options
1674
+ };
1675
+ /** @private @type {RouteDefinition[]} The processed list of route definitions. */ this.routes = this._processRoutes(options.routes || []);
1676
+ /** @private @type {Emitter} The shared Eleva event emitter for global hooks. */ this.emitter = this.eleva.emitter;
1677
+ /** @private @type {boolean} A flag indicating if the router has been started. */ this.isStarted = false;
1678
+ /** @private @type {boolean} A flag to prevent navigation loops from history events. */ this._isNavigating = false;
1679
+ /** @private @type {number} Counter for tracking navigation operations to prevent race conditions. */ this._navigationId = 0;
1680
+ /** @private @type {UnsubscribeFunction[]} A collection of cleanup functions for event listeners. */ this.eventListeners = [];
1681
+ /** @type {Signal<RouteLocation | null>} A reactive signal holding the current route's information. */ this.currentRoute = new this.eleva.signal(null);
1682
+ /** @type {Signal<RouteLocation | null>} A reactive signal holding the previous route's information. */ this.previousRoute = new this.eleva.signal(null);
1683
+ /** @type {Signal<RouteParams>} A reactive signal holding the current route's parameters. */ this.currentParams = new this.eleva.signal({});
1684
+ /** @type {Signal<QueryParams>} A reactive signal holding the current route's query parameters. */ this.currentQuery = new this.eleva.signal({});
1685
+ /** @type {Signal<MountResult | null>} A reactive signal for the currently mounted layout instance. */ this.currentLayout = new this.eleva.signal(null);
1686
+ /** @type {Signal<MountResult | null>} A reactive signal for the currently mounted view (page) instance. */ this.currentView = new this.eleva.signal(null);
1687
+ /** @type {Signal<boolean>} A reactive signal indicating if the router is ready (started and initial navigation complete). */ this.isReady = new this.eleva.signal(false);
1688
+ /** @private @type {Map<string, RouterPlugin>} Map of registered plugins by name. */ this.plugins = new Map();
1689
+ /** @private @type {NavigationGuard[]} Array of global before-each navigation guards. */ this._beforeEachGuards = [];
1690
+ // If onBeforeEach was provided in options, add it to the guards array
1691
+ if (options.onBeforeEach) {
1692
+ this._beforeEachGuards.push(options.onBeforeEach);
1693
+ }
1694
+ /** @type {RouterErrorHandler} The error handler instance. Can be overridden by plugins. */ this.errorHandler = CoreErrorHandler;
1695
+ /** @private @type {Map<string, {x: number, y: number}>} Saved scroll positions by route path. */ this._scrollPositions = new Map();
1696
+ this._validateOptions();
1697
+ }
1698
+ }
1699
+ /**
1700
+ * @class 🚀 RouterPlugin
1701
+ * @classdesc A powerful, reactive, and flexible Router Plugin for Eleva applications.
1702
+ * This plugin provides comprehensive client-side routing functionality including:
1703
+ * - Multiple routing modes (hash, history, query)
1704
+ * - Navigation guards and lifecycle hooks
1705
+ * - Reactive state management
1706
+ * - Component resolution and lazy loading
1707
+ * - Layout and page component separation
1708
+ * - Plugin system for extensibility
1709
+ * - Advanced error handling
1710
+ *
1711
+ * @example
1712
+ * // Install the plugin
1713
+ * const app = new Eleva("myApp");
1714
+ *
1715
+ * const HomePage = { template: () => `<h1>Home</h1>` };
1716
+ * const AboutPage = { template: () => `<h1>About Us</h1>` };
1717
+ * const UserPage = {
1718
+ * template: (ctx) => `<h1>User: ${ctx.router.params.id}</h1>`
1719
+ * };
1720
+ *
1721
+ * app.use(RouterPlugin, {
1722
+ * mount: '#app',
1723
+ * mode: 'hash',
1724
+ * routes: [
1725
+ * { path: '/', component: HomePage },
1726
+ * { path: '/about', component: AboutPage },
1727
+ * { path: '/users/:id', component: UserPage }
1728
+ * ]
1729
+ * });
1730
+ */ const RouterPlugin = {
1731
+ /**
1732
+ * Unique identifier for the plugin
1733
+ * @type {string}
1734
+ */ name: "router",
1735
+ /**
1736
+ * Plugin version
1737
+ * @type {string}
1738
+ */ version: "1.1.0",
1739
+ /**
1740
+ * Plugin description
1741
+ * @type {string}
1742
+ */ description: "Client-side routing for Eleva applications",
1743
+ /**
1744
+ * Installs the RouterPlugin into an Eleva instance.
1745
+ *
1746
+ * @public
1747
+ * @param {Eleva} eleva - The Eleva instance.
1748
+ * @param {RouterOptions} options - Router configuration options.
1749
+ * @param {string} options.mount - A CSS selector for the main element where the app is mounted.
1750
+ * @param {RouteDefinition[]} options.routes - An array of route definitions.
1751
+ * @param {'hash' | 'query' | 'history'} [options.mode='hash'] - The routing mode.
1752
+ * @param {string} [options.queryParam='view'] - The query parameter to use in 'query' mode.
1753
+ * @param {string} [options.viewSelector='view'] - Base selector for the view element (matched as #id, .class, [data-*], or raw selector).
1754
+ * @param {boolean} [options.autoStart=true] - Whether to start the router automatically.
1755
+ * @param {NavigationGuard} [options.onBeforeEach] - A global guard executed before every navigation.
1756
+ * @param {RouteComponent} [options.globalLayout] - A global layout for all routes.
1757
+ * @returns {Router} The created router instance.
1758
+ * @throws {Error} If 'mount' option is not provided.
1759
+ * @throws {Error} If 'routes' option is not an array.
1760
+ * @throws {Error} If component registration fails during route processing.
1761
+ * @description
1762
+ * Registers route/layout components, sets `eleva.router`, and adds helpers
1763
+ * (`eleva.navigate`, `eleva.getCurrentRoute`, `eleva.getRouteParams`, `eleva.getRouteQuery`).
1764
+ * When `autoStart` is enabled, startup is scheduled via microtask.
1765
+ *
1766
+ * @example
1767
+ * // main.js
1768
+ * import Eleva from 'eleva';
1769
+ * import { RouterPlugin } from './plugins/RouterPlugin.js';
1770
+ *
1771
+ * const app = new Eleva('myApp');
1772
+ *
1773
+ * const HomePage = { template: () => `<h1>Home</h1>` };
1774
+ * const AboutPage = { template: () => `<h1>About Us</h1>` };
1775
+ *
1776
+ * app.use(RouterPlugin, {
1777
+ * mount: '#app',
1778
+ * routes: [
1779
+ * { path: '/', component: HomePage },
1780
+ * { path: '/about', component: AboutPage }
1781
+ * ]
1782
+ * });
1783
+ */ install (eleva, options = {}) {
1784
+ if (!options.mount) {
1785
+ throw new Error("[RouterPlugin] 'mount' option is required");
1786
+ }
1787
+ if (!options.routes || !Array.isArray(options.routes)) {
1788
+ throw new Error("[RouterPlugin] 'routes' option must be an array");
1789
+ }
1790
+ /**
1791
+ * Registers a component definition with the Eleva instance.
1792
+ * This method handles both inline component objects and pre-registered component names.
1793
+ *
1794
+ * @inner
1795
+ * @param {unknown} def - The component definition to register.
1796
+ * @param {string} type - The type of component for naming (e.g., "Route", "Layout").
1797
+ * @returns {string | null} The registered component name or null if no definition provided.
1798
+ */ const register = (def, type)=>{
1799
+ if (!def) return null;
1800
+ if (typeof def === "object" && def !== null && !def.name) {
1801
+ const name = `Eleva${type}Component_${Math.random().toString(36).slice(2, 11)}`;
1802
+ try {
1803
+ eleva.component(name, def);
1804
+ return name;
1805
+ } catch (error) {
1806
+ throw new Error(`[RouterPlugin] Failed to register ${type} component: ${error.message}`);
1807
+ }
1808
+ }
1809
+ return def;
1810
+ };
1811
+ if (options.globalLayout) {
1812
+ options.globalLayout = register(options.globalLayout, "GlobalLayout");
1813
+ }
1814
+ (options.routes || []).forEach((route)=>{
1815
+ route.component = register(route.component, "Route");
1816
+ if (route.layout) {
1817
+ route.layout = register(route.layout, "RouteLayout");
1818
+ }
1819
+ });
1820
+ const router = new Router(eleva, options);
1821
+ /** @type {Router} */ eleva.router = router;
1822
+ if (options.autoStart !== false) {
1823
+ queueMicrotask(()=>router.start());
1824
+ }
1825
+ // Add plugin metadata to the Eleva instance
1826
+ if (!eleva.plugins) {
1827
+ eleva.plugins = new Map();
1828
+ }
1829
+ eleva.plugins.set(this.name, {
1830
+ name: this.name,
1831
+ version: this.version,
1832
+ description: this.description,
1833
+ options
1834
+ });
1835
+ // Add utility methods for manual router access
1836
+ /** @type {NavigateFunction} */ eleva.navigate = router.navigate.bind(router);
1837
+ /** @type {() => RouteLocation | null} */ eleva.getCurrentRoute = ()=>router.currentRoute.value;
1838
+ /** @type {() => RouteParams} */ eleva.getRouteParams = ()=>router.currentParams.value;
1839
+ /** @type {() => QueryParams} */ eleva.getRouteQuery = ()=>router.currentQuery.value;
1840
+ return router;
1841
+ },
1842
+ /**
1843
+ * Uninstalls the plugin from the Eleva instance.
1844
+ *
1845
+ * @public
1846
+ * @async
1847
+ * @param {Eleva} eleva - The Eleva instance.
1848
+ * @returns {Promise<void>}
1849
+ * @description
1850
+ * Destroys the router instance, removes `eleva.router`, and deletes helper methods
1851
+ * (`eleva.navigate`, `eleva.getCurrentRoute`, `eleva.getRouteParams`, `eleva.getRouteQuery`).
1852
+ */ async uninstall (eleva) {
1853
+ if (eleva.router) {
1854
+ await eleva.router.destroy();
1855
+ delete eleva.router;
1856
+ }
1857
+ // Remove plugin metadata
1858
+ if (eleva.plugins) {
1859
+ eleva.plugins.delete(this.name);
1860
+ }
1861
+ // Remove utility methods
1862
+ delete eleva.navigate;
1863
+ delete eleva.getCurrentRoute;
1864
+ delete eleva.getRouteParams;
1865
+ delete eleva.getRouteQuery;
1866
+ }
1867
+ };
1868
+
1869
+ export { RouterPlugin as Router, RouterPlugin };
1870
+ //# sourceMappingURL=router.js.map