eleva 1.0.0-rc.3 → 1.0.0-rc.4

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 (41) hide show
  1. package/README.md +135 -2
  2. package/dist/eleva-plugins.cjs.js +1330 -0
  3. package/dist/eleva-plugins.cjs.js.map +1 -0
  4. package/dist/eleva-plugins.esm.js +1327 -0
  5. package/dist/eleva-plugins.esm.js.map +1 -0
  6. package/dist/eleva-plugins.umd.js +1336 -0
  7. package/dist/eleva-plugins.umd.js.map +1 -0
  8. package/dist/eleva-plugins.umd.min.js +3 -0
  9. package/dist/eleva-plugins.umd.min.js.map +1 -0
  10. package/dist/eleva.cjs.js +15 -34
  11. package/dist/eleva.cjs.js.map +1 -1
  12. package/dist/eleva.d.ts +0 -1
  13. package/dist/eleva.esm.js +15 -34
  14. package/dist/eleva.esm.js.map +1 -1
  15. package/dist/eleva.umd.js +15 -34
  16. package/dist/eleva.umd.js.map +1 -1
  17. package/dist/eleva.umd.min.js +2 -2
  18. package/dist/eleva.umd.min.js.map +1 -1
  19. package/dist/plugins/attr.umd.js +231 -0
  20. package/dist/plugins/attr.umd.js.map +1 -0
  21. package/dist/plugins/attr.umd.min.js +3 -0
  22. package/dist/plugins/attr.umd.min.js.map +1 -0
  23. package/dist/plugins/router.umd.js +1115 -0
  24. package/dist/plugins/router.umd.js.map +1 -0
  25. package/dist/plugins/router.umd.min.js +3 -0
  26. package/dist/plugins/router.umd.min.js.map +1 -0
  27. package/package.json +40 -1
  28. package/src/core/Eleva.js +6 -7
  29. package/src/modules/Renderer.js +8 -36
  30. package/src/plugins/Attr.js +252 -0
  31. package/src/plugins/Router.js +1217 -0
  32. package/src/plugins/index.js +34 -0
  33. package/types/core/Eleva.d.ts +0 -1
  34. package/types/core/Eleva.d.ts.map +1 -1
  35. package/types/modules/Renderer.d.ts.map +1 -1
  36. package/types/plugins/Attr.d.ts +28 -0
  37. package/types/plugins/Attr.d.ts.map +1 -0
  38. package/types/plugins/Router.d.ts +500 -0
  39. package/types/plugins/Router.d.ts.map +1 -0
  40. package/types/plugins/index.d.ts +3 -0
  41. package/types/plugins/index.d.ts.map +1 -0
@@ -0,0 +1,1330 @@
1
+ /*! Eleva Plugins v1.0.0-rc.4 | MIT License | https://elevajs.com */
2
+ 'use strict';
3
+
4
+ /**
5
+ * A regular expression to match hyphenated lowercase letters.
6
+ * @private
7
+ * @type {RegExp}
8
+ */
9
+ const CAMEL_RE = /-([a-z])/g;
10
+
11
+ /**
12
+ * @class 🎯 AttrPlugin
13
+ * @classdesc A plugin that provides advanced attribute handling for Eleva components.
14
+ * This plugin extends the renderer with sophisticated attribute processing including:
15
+ * - ARIA attribute handling with proper property mapping
16
+ * - Data attribute management
17
+ * - Boolean attribute processing
18
+ * - Dynamic property detection and mapping
19
+ * - Attribute cleanup and removal
20
+ *
21
+ * @example
22
+ * // Install the plugin
23
+ * const app = new Eleva("myApp");
24
+ * app.use(AttrPlugin);
25
+ *
26
+ * // Use advanced attributes in components
27
+ * app.component("myComponent", {
28
+ * template: (ctx) => `
29
+ * <button
30
+ * aria-expanded="${ctx.isExpanded.value}"
31
+ * data-user-id="${ctx.userId.value}"
32
+ * disabled="${ctx.isLoading.value}"
33
+ * class="btn ${ctx.variant.value}"
34
+ * >
35
+ * ${ctx.text.value}
36
+ * </button>
37
+ * `
38
+ * });
39
+ */
40
+ const AttrPlugin = {
41
+ /**
42
+ * Unique identifier for the plugin
43
+ * @type {string}
44
+ */
45
+ name: "attr",
46
+ /**
47
+ * Plugin version
48
+ * @type {string}
49
+ */
50
+ version: "1.0.0-rc.1",
51
+ /**
52
+ * Plugin description
53
+ * @type {string}
54
+ */
55
+ description: "Advanced attribute handling for Eleva components",
56
+ /**
57
+ * Installs the plugin into the Eleva instance
58
+ *
59
+ * @param {Object} eleva - The Eleva instance
60
+ * @param {Object} options - Plugin configuration options
61
+ * @param {boolean} [options.enableAria=true] - Enable ARIA attribute handling
62
+ * @param {boolean} [options.enableData=true] - Enable data attribute handling
63
+ * @param {boolean} [options.enableBoolean=true] - Enable boolean attribute handling
64
+ * @param {boolean} [options.enableDynamic=true] - Enable dynamic property detection
65
+ */
66
+ install(eleva, options = {}) {
67
+ const {
68
+ enableAria = true,
69
+ enableData = true,
70
+ enableBoolean = true,
71
+ enableDynamic = true
72
+ } = options;
73
+
74
+ /**
75
+ * Updates the attributes of an element to match a new element's attributes.
76
+ * This method provides sophisticated attribute processing including:
77
+ * - ARIA attribute handling with proper property mapping
78
+ * - Data attribute management
79
+ * - Boolean attribute processing
80
+ * - Dynamic property detection and mapping
81
+ * - Attribute cleanup and removal
82
+ *
83
+ * @param {HTMLElement} oldEl - The original element to update
84
+ * @param {HTMLElement} newEl - The new element to update
85
+ * @returns {void}
86
+ */
87
+ const updateAttributes = (oldEl, newEl) => {
88
+ const oldAttrs = oldEl.attributes;
89
+ const newAttrs = newEl.attributes;
90
+
91
+ // Process new attributes
92
+ for (let i = 0; i < newAttrs.length; i++) {
93
+ const {
94
+ name,
95
+ value
96
+ } = newAttrs[i];
97
+
98
+ // Skip event attributes (handled by event system)
99
+ if (name.startsWith("@")) continue;
100
+
101
+ // Skip if attribute hasn't changed
102
+ if (oldEl.getAttribute(name) === value) continue;
103
+
104
+ // Handle ARIA attributes
105
+ if (enableAria && name.startsWith("aria-")) {
106
+ const prop = "aria" + name.slice(5).replace(CAMEL_RE, (_, l) => l.toUpperCase());
107
+ oldEl[prop] = value;
108
+ oldEl.setAttribute(name, value);
109
+ }
110
+ // Handle data attributes
111
+ else if (enableData && name.startsWith("data-")) {
112
+ oldEl.dataset[name.slice(5)] = value;
113
+ oldEl.setAttribute(name, value);
114
+ }
115
+ // Handle other attributes
116
+ else {
117
+ let prop = name.replace(CAMEL_RE, (_, l) => l.toUpperCase());
118
+
119
+ // Dynamic property detection
120
+ if (enableDynamic && !(prop in oldEl) && !Object.getOwnPropertyDescriptor(Object.getPrototypeOf(oldEl), prop)) {
121
+ const elementProps = Object.getOwnPropertyNames(Object.getPrototypeOf(oldEl));
122
+ const matchingProp = elementProps.find(p => p.toLowerCase() === name.toLowerCase() || p.toLowerCase().includes(name.toLowerCase()) || name.toLowerCase().includes(p.toLowerCase()));
123
+ if (matchingProp) {
124
+ prop = matchingProp;
125
+ }
126
+ }
127
+ const descriptor = Object.getOwnPropertyDescriptor(Object.getPrototypeOf(oldEl), prop);
128
+ const hasProperty = prop in oldEl || descriptor;
129
+ if (hasProperty) {
130
+ // Boolean attribute handling
131
+ if (enableBoolean) {
132
+ const isBoolean = typeof oldEl[prop] === "boolean" || descriptor?.get && typeof descriptor.get.call(oldEl) === "boolean";
133
+ if (isBoolean) {
134
+ const boolValue = value !== "false" && (value === "" || value === prop || value === "true");
135
+ oldEl[prop] = boolValue;
136
+ if (boolValue) {
137
+ oldEl.setAttribute(name, "");
138
+ } else {
139
+ oldEl.removeAttribute(name);
140
+ }
141
+ } else {
142
+ oldEl[prop] = value;
143
+ oldEl.setAttribute(name, value);
144
+ }
145
+ } else {
146
+ oldEl[prop] = value;
147
+ oldEl.setAttribute(name, value);
148
+ }
149
+ } else {
150
+ oldEl.setAttribute(name, value);
151
+ }
152
+ }
153
+ }
154
+
155
+ // Remove old attributes that are no longer present
156
+ for (let i = oldAttrs.length - 1; i >= 0; i--) {
157
+ const name = oldAttrs[i].name;
158
+ if (!newEl.hasAttribute(name)) {
159
+ oldEl.removeAttribute(name);
160
+ }
161
+ }
162
+ };
163
+
164
+ // Extend the renderer with the advanced attribute handler
165
+ if (eleva.renderer) {
166
+ eleva.renderer.updateAttributes = updateAttributes;
167
+
168
+ // Store the original _patchNode method
169
+ const originalPatchNode = eleva.renderer._patchNode;
170
+ eleva.renderer._originalPatchNode = originalPatchNode;
171
+
172
+ // Override the _patchNode method to use our attribute handler
173
+ eleva.renderer._patchNode = function (oldNode, newNode) {
174
+ if (oldNode?._eleva_instance) return;
175
+ if (!this._isSameNode(oldNode, newNode)) {
176
+ oldNode.replaceWith(newNode.cloneNode(true));
177
+ return;
178
+ }
179
+ if (oldNode.nodeType === Node.ELEMENT_NODE) {
180
+ updateAttributes(oldNode, newNode);
181
+ this._diff(oldNode, newNode);
182
+ } else if (oldNode.nodeType === Node.TEXT_NODE && oldNode.nodeValue !== newNode.nodeValue) {
183
+ oldNode.nodeValue = newNode.nodeValue;
184
+ }
185
+ };
186
+ }
187
+
188
+ // Add plugin metadata to the Eleva instance
189
+ if (!eleva.plugins) {
190
+ eleva.plugins = new Map();
191
+ }
192
+ eleva.plugins.set(this.name, {
193
+ name: this.name,
194
+ version: this.version,
195
+ description: this.description,
196
+ options
197
+ });
198
+
199
+ // Add utility methods for manual attribute updates
200
+ eleva.updateElementAttributes = updateAttributes;
201
+ },
202
+ /**
203
+ * Uninstalls the plugin from the Eleva instance
204
+ *
205
+ * @param {Object} eleva - The Eleva instance
206
+ */
207
+ uninstall(eleva) {
208
+ // Restore original _patchNode method if it exists
209
+ if (eleva.renderer && eleva.renderer._originalPatchNode) {
210
+ eleva.renderer._patchNode = eleva.renderer._originalPatchNode;
211
+ delete eleva.renderer._originalPatchNode;
212
+ }
213
+
214
+ // Remove plugin metadata
215
+ if (eleva.plugins) {
216
+ eleva.plugins.delete(this.name);
217
+ }
218
+
219
+ // Remove utility methods
220
+ delete eleva.updateElementAttributes;
221
+ }
222
+ };
223
+
224
+ /**
225
+ * @typedef {import('eleva').Eleva} Eleva
226
+ * @typedef {import('eleva').Signal} Signal
227
+ * @typedef {import('eleva').ComponentDefinition} ComponentDefinition
228
+ */
229
+
230
+ /**
231
+ * Simple error handler for the core router.
232
+ * Can be overridden by error handling plugins.
233
+ * Provides consistent error formatting and logging for router operations.
234
+ * @private
235
+ */
236
+ const CoreErrorHandler = {
237
+ /**
238
+ * Handles router errors with basic formatting.
239
+ * @param {Error} error - The error to handle.
240
+ * @param {string} context - The context where the error occurred.
241
+ * @param {Object} details - Additional error details.
242
+ * @throws {Error} The formatted error.
243
+ */
244
+ handle(error, context, details = {}) {
245
+ const message = `[ElevaRouter] ${context}: ${error.message}`;
246
+ const formattedError = new Error(message);
247
+
248
+ // Preserve original error details
249
+ formattedError.originalError = error;
250
+ formattedError.context = context;
251
+ formattedError.details = details;
252
+ console.error(message, {
253
+ error,
254
+ context,
255
+ details
256
+ });
257
+ throw formattedError;
258
+ },
259
+ /**
260
+ * Logs a warning without throwing an error.
261
+ * @param {string} message - The warning message.
262
+ * @param {Object} details - Additional warning details.
263
+ */
264
+ warn(message, details = {}) {
265
+ console.warn(`[ElevaRouter] ${message}`, details);
266
+ },
267
+ /**
268
+ * Logs an error without throwing.
269
+ * @param {string} message - The error message.
270
+ * @param {Error} error - The original error.
271
+ * @param {Object} details - Additional error details.
272
+ */
273
+ log(message, error, details = {}) {
274
+ console.error(`[ElevaRouter] ${message}`, {
275
+ error,
276
+ details
277
+ });
278
+ }
279
+ };
280
+
281
+ /**
282
+ * @typedef {Object} RouteLocation
283
+ * @property {string} path - The path of the route (e.g., '/users/123').
284
+ * @property {Object<string, string>} query - An object representing the query parameters.
285
+ * @property {string} fullUrl - The complete URL including hash, path, and query string.
286
+ * @property {Object<string, string>} params - An object containing dynamic route parameters.
287
+ * @property {Object<string, any>} meta - The meta object associated with the matched route.
288
+ * @property {string} [name] - The optional name of the matched route.
289
+ * @property {RouteDefinition} matched - The raw route definition object that was matched.
290
+ */
291
+
292
+ /**
293
+ * @typedef {(to: RouteLocation, from: RouteLocation | null) => boolean | string | {path: string} | void | Promise<boolean | string | {path: string} | void>} NavigationGuard
294
+ * A function that acts as a guard for navigation. It runs *before* the navigation is confirmed.
295
+ * It can return:
296
+ * - `true` or `undefined`: to allow navigation.
297
+ * - `false`: to abort the navigation.
298
+ * - a `string` (path) or a `location object`: to redirect to a new route.
299
+ */
300
+
301
+ /**
302
+ * @typedef {(...args: any[]) => void | Promise<void>} NavigationHook
303
+ * A function that acts as a lifecycle hook, typically for side effects. It does not affect navigation flow.
304
+ */
305
+
306
+ /**
307
+ * @typedef {Object} RouterPlugin
308
+ * @property {string} name - The plugin name.
309
+ * @property {string} [version] - The plugin version.
310
+ * @property {Function} install - The install function that receives the router instance.
311
+ * @property {Function} [destroy] - Optional cleanup function called when the router is destroyed.
312
+ */
313
+
314
+ /**
315
+ * @typedef {Object} RouteDefinition
316
+ * @property {string} path - The URL path pattern (e.g., '/', '/about', '/users/:id', '*').
317
+ * @property {string | ComponentDefinition | (() => Promise<{default: ComponentDefinition}>)} component - The component to render. Can be a registered name, a definition object, or an async import function.
318
+ * @property {string | ComponentDefinition | (() => Promise<{default: ComponentDefinition}>)} [layout] - An optional layout component to wrap the route's component.
319
+ * @property {string} [name] - An optional name for the route.
320
+ * @property {Object<string, any>} [meta] - Optional metadata for the route (e.g., for titles, auth flags).
321
+ * @property {NavigationGuard} [beforeEnter] - A route-specific guard executed before entering the route.
322
+ * @property {NavigationHook} [afterEnter] - A hook executed *after* the route has been entered and the new component is mounted.
323
+ * @property {NavigationGuard} [beforeLeave] - A guard executed *before* leaving the current route.
324
+ * @property {NavigationHook} [afterLeave] - A hook executed *after* leaving the current route and its component has been unmounted.
325
+ */
326
+
327
+ /**
328
+ * @class Router
329
+ * @classdesc A powerful, reactive, and flexible Router Plugin for Eleva.js.
330
+ * This class manages all routing logic, including state, navigation, and rendering.
331
+ * @private
332
+ */
333
+ class Router {
334
+ /**
335
+ * Creates an instance of the Router.
336
+ * @param {Eleva} eleva - The Eleva framework instance.
337
+ * @param {RouterOptions} options - The configuration options for the router.
338
+ */
339
+ constructor(eleva, options = {}) {
340
+ /** @type {Eleva} The Eleva framework instance. */
341
+ this.eleva = eleva;
342
+
343
+ /** @type {RouterOptions} The merged router options. */
344
+ this.options = {
345
+ mode: "hash",
346
+ queryParam: "view",
347
+ viewSelector: "root",
348
+ ...options
349
+ };
350
+
351
+ /** @private @type {RouteDefinition[]} The processed list of route definitions. */
352
+ this.routes = this._processRoutes(options.routes || []);
353
+
354
+ /** @private @type {import('eleva').Emitter} The shared Eleva event emitter for global hooks. */
355
+ this.emitter = this.eleva.emitter;
356
+
357
+ /** @private @type {boolean} A flag indicating if the router has been started. */
358
+ this.isStarted = false;
359
+
360
+ /** @private @type {boolean} A flag to prevent navigation loops from history events. */
361
+ this._isNavigating = false;
362
+
363
+ /** @private @type {Array<() => void>} A collection of cleanup functions for event listeners. */
364
+ this.eventListeners = [];
365
+
366
+ /** @type {Signal<RouteLocation | null>} A reactive signal holding the current route's information. */
367
+ this.currentRoute = new this.eleva.signal(null);
368
+
369
+ /** @type {Signal<RouteLocation | null>} A reactive signal holding the previous route's information. */
370
+ this.previousRoute = new this.eleva.signal(null);
371
+
372
+ /** @type {Signal<Object<string, string>>} A reactive signal holding the current route's parameters. */
373
+ this.currentParams = new this.eleva.signal({});
374
+
375
+ /** @type {Signal<Object<string, string>>} A reactive signal holding the current route's query parameters. */
376
+ this.currentQuery = new this.eleva.signal({});
377
+
378
+ /** @type {Signal<import('eleva').MountResult | null>} A reactive signal for the currently mounted layout instance. */
379
+ this.currentLayout = new this.eleva.signal(null);
380
+
381
+ /** @type {Signal<import('eleva').MountResult | null>} A reactive signal for the currently mounted view (page) instance. */
382
+ this.currentView = new this.eleva.signal(null);
383
+
384
+ /** @private @type {Map<string, RouterPlugin>} Map of registered plugins by name. */
385
+ this.plugins = new Map();
386
+
387
+ /** @type {Object} The error handler instance. Can be overridden by plugins. */
388
+ this.errorHandler = CoreErrorHandler;
389
+ this._validateOptions();
390
+ }
391
+
392
+ /**
393
+ * Validates the provided router options.
394
+ * @private
395
+ * @throws {Error} If the routing mode is invalid.
396
+ */
397
+ _validateOptions() {
398
+ if (!["hash", "query", "history"].includes(this.options.mode)) {
399
+ this.errorHandler.handle(new Error(`Invalid routing mode: ${this.options.mode}. Must be "hash", "query", or "history".`), "Configuration validation failed");
400
+ }
401
+ }
402
+
403
+ /**
404
+ * Pre-processes route definitions to parse their path segments for efficient matching.
405
+ * @private
406
+ * @param {RouteDefinition[]} routes - The raw route definitions.
407
+ * @returns {RouteDefinition[]} The processed routes.
408
+ */
409
+ _processRoutes(routes) {
410
+ const processedRoutes = [];
411
+ for (const route of routes) {
412
+ try {
413
+ processedRoutes.push({
414
+ ...route,
415
+ segments: this._parsePathIntoSegments(route.path)
416
+ });
417
+ } catch (error) {
418
+ this.errorHandler.warn(`Invalid path in route definition "${route.path || "undefined"}": ${error.message}`, {
419
+ route,
420
+ error
421
+ });
422
+ }
423
+ }
424
+ return processedRoutes;
425
+ }
426
+
427
+ /**
428
+ * Parses a route path string into an array of static and parameter segments.
429
+ * @private
430
+ * @param {string} path - The path pattern to parse.
431
+ * @returns {Array<{type: 'static' | 'param', value?: string, name?: string}>} An array of segment objects.
432
+ * @throws {Error} If the route path is not a valid string.
433
+ */
434
+ _parsePathIntoSegments(path) {
435
+ if (!path || typeof path !== "string") {
436
+ this.errorHandler.handle(new Error("Route path must be a non-empty string"), "Path parsing failed", {
437
+ path
438
+ });
439
+ }
440
+ const normalizedPath = path.replace(/\/+/g, "/").replace(/\/$/, "") || "/";
441
+ if (normalizedPath === "/") {
442
+ return [];
443
+ }
444
+ return normalizedPath.split("/").filter(Boolean).map(segment => {
445
+ if (segment.startsWith(":")) {
446
+ const paramName = segment.substring(1);
447
+ if (!paramName) {
448
+ this.errorHandler.handle(new Error(`Invalid parameter segment: ${segment}`), "Path parsing failed", {
449
+ segment,
450
+ path
451
+ });
452
+ }
453
+ return {
454
+ type: "param",
455
+ name: paramName
456
+ };
457
+ }
458
+ return {
459
+ type: "static",
460
+ value: segment
461
+ };
462
+ });
463
+ }
464
+
465
+ /**
466
+ * Finds the view element within a container using multiple selector strategies.
467
+ * @private
468
+ * @param {HTMLElement} container - The parent element to search within.
469
+ * @returns {HTMLElement} The found view element or the container itself as a fallback.
470
+ */
471
+ _findViewElement(container) {
472
+ const selector = this.options.viewSelector;
473
+ return container.querySelector(`#${selector}`) || container.querySelector(`.${selector}`) || container.querySelector(`[data-${selector}]`) || container.querySelector(selector) || container;
474
+ }
475
+
476
+ /**
477
+ * Starts the router, initializes event listeners, and performs the initial navigation.
478
+ * @returns {Promise<void>}
479
+ */
480
+ async start() {
481
+ if (this.isStarted) {
482
+ this.errorHandler.warn("Router is already started");
483
+ return;
484
+ }
485
+ if (typeof window === "undefined") {
486
+ this.errorHandler.warn("Router start skipped: `window` object not available (SSR environment)");
487
+ return;
488
+ }
489
+ if (typeof document !== "undefined" && !document.querySelector(this.options.mount)) {
490
+ this.errorHandler.warn(`Mount element "${this.options.mount}" was not found in the DOM. The router will not start.`, {
491
+ mountSelector: this.options.mount
492
+ });
493
+ return;
494
+ }
495
+ const handler = () => this._handleRouteChange();
496
+ if (this.options.mode === "hash") {
497
+ window.addEventListener("hashchange", handler);
498
+ this.eventListeners.push(() => window.removeEventListener("hashchange", handler));
499
+ } else {
500
+ window.addEventListener("popstate", handler);
501
+ this.eventListeners.push(() => window.removeEventListener("popstate", handler));
502
+ }
503
+ this.isStarted = true;
504
+ await this._handleRouteChange();
505
+ }
506
+
507
+ /**
508
+ * Stops the router and cleans up all event listeners and mounted components.
509
+ * @returns {Promise<void>}
510
+ */
511
+ async destroy() {
512
+ if (!this.isStarted) return;
513
+
514
+ // Clean up plugins
515
+ for (const plugin of this.plugins.values()) {
516
+ if (typeof plugin.destroy === "function") {
517
+ try {
518
+ await plugin.destroy(this);
519
+ } catch (error) {
520
+ this.errorHandler.log(`Plugin ${plugin.name} destroy failed`, error);
521
+ }
522
+ }
523
+ }
524
+ this.eventListeners.forEach(cleanup => cleanup());
525
+ this.eventListeners = [];
526
+ if (this.currentLayout.value) {
527
+ await this.currentLayout.value.unmount();
528
+ }
529
+ this.isStarted = false;
530
+ }
531
+
532
+ /**
533
+ * Programmatically navigates to a new route.
534
+ * @param {string | {path: string, query?: object, params?: object, replace?: boolean, state?: object}} location - The target location as a string or object.
535
+ * @param {object} [params] - Optional route parameters (for string-based location).
536
+ * @returns {Promise<void>}
537
+ */
538
+ async navigate(location, params = {}) {
539
+ try {
540
+ const target = typeof location === "string" ? {
541
+ path: location,
542
+ params
543
+ } : location;
544
+ let path = this._buildPath(target.path, target.params || {});
545
+ const query = target.query || {};
546
+ if (Object.keys(query).length > 0) {
547
+ const queryString = new URLSearchParams(query).toString();
548
+ if (queryString) path += `?${queryString}`;
549
+ }
550
+ if (this._isSameRoute(path, target.params, query)) {
551
+ return;
552
+ }
553
+ const navigationSuccessful = await this._proceedWithNavigation(path);
554
+ if (navigationSuccessful) {
555
+ this._isNavigating = true;
556
+ const state = target.state || {};
557
+ const replace = target.replace || false;
558
+ const historyMethod = replace ? "replaceState" : "pushState";
559
+ if (this.options.mode === "hash") {
560
+ if (replace) {
561
+ const newUrl = `${window.location.pathname}${window.location.search}#${path}`;
562
+ window.history.replaceState(state, "", newUrl);
563
+ } else {
564
+ window.location.hash = path;
565
+ }
566
+ } else {
567
+ const url = this.options.mode === "query" ? this._buildQueryUrl(path) : path;
568
+ history[historyMethod](state, "", url);
569
+ }
570
+ queueMicrotask(() => {
571
+ this._isNavigating = false;
572
+ });
573
+ }
574
+ } catch (error) {
575
+ this.errorHandler.log("Navigation failed", error);
576
+ await this.emitter.emit("router:onError", error);
577
+ }
578
+ }
579
+
580
+ /**
581
+ * Builds a URL for query mode.
582
+ * @private
583
+ * @param {string} path - The path to set as the query parameter.
584
+ * @returns {string} The full URL with the updated query string.
585
+ */
586
+ _buildQueryUrl(path) {
587
+ const urlParams = new URLSearchParams(window.location.search);
588
+ urlParams.set(this.options.queryParam, path.split("?")[0]);
589
+ return `${window.location.pathname}?${urlParams.toString()}`;
590
+ }
591
+
592
+ /**
593
+ * Checks if the target route is identical to the current route.
594
+ * @private
595
+ * @param {string} path - The target path with query string.
596
+ * @param {object} params - The target params.
597
+ * @param {object} query - The target query.
598
+ * @returns {boolean} - True if the routes are the same.
599
+ */
600
+ _isSameRoute(path, params, query) {
601
+ const current = this.currentRoute.value;
602
+ if (!current) return false;
603
+ const [targetPath, queryString] = path.split("?");
604
+ const targetQuery = query || this._parseQuery(queryString || "");
605
+ return current.path === targetPath && JSON.stringify(current.params) === JSON.stringify(params || {}) && JSON.stringify(current.query) === JSON.stringify(targetQuery);
606
+ }
607
+
608
+ /**
609
+ * Injects dynamic parameters into a path string.
610
+ * @private
611
+ */
612
+ _buildPath(path, params) {
613
+ let result = path;
614
+ for (const [key, value] of Object.entries(params)) {
615
+ // Fix: Handle special characters and ensure proper encoding
616
+ const encodedValue = encodeURIComponent(String(value));
617
+ result = result.replace(new RegExp(`:${key}\\b`, "g"), encodedValue);
618
+ }
619
+ return result;
620
+ }
621
+
622
+ /**
623
+ * The handler for browser-initiated route changes (e.g., back/forward buttons).
624
+ * @private
625
+ */
626
+ async _handleRouteChange() {
627
+ if (this._isNavigating) return;
628
+ const from = this.currentRoute.value;
629
+ const toLocation = this._getCurrentLocation();
630
+ const navigationSuccessful = await this._proceedWithNavigation(toLocation.fullUrl);
631
+
632
+ // If navigation was blocked by a guard, revert the URL change
633
+ if (!navigationSuccessful && from) {
634
+ this.navigate({
635
+ path: from.path,
636
+ query: from.query,
637
+ replace: true
638
+ });
639
+ }
640
+ }
641
+
642
+ /**
643
+ * Manages the core navigation lifecycle. Runs guards before committing changes.
644
+ * @private
645
+ * @param {string} fullPath - The full path (e.g., '/users/123?foo=bar') to navigate to.
646
+ * @returns {Promise<boolean>} - `true` if navigation succeeded, `false` if aborted.
647
+ */
648
+ async _proceedWithNavigation(fullPath) {
649
+ const from = this.currentRoute.value;
650
+ const [path, queryString] = (fullPath || "/").split("?");
651
+ const toLocation = {
652
+ path: path.startsWith("/") ? path : `/${path}`,
653
+ query: this._parseQuery(queryString),
654
+ fullUrl: fullPath
655
+ };
656
+ let toMatch = this._matchRoute(toLocation.path);
657
+ if (!toMatch) {
658
+ const notFoundRoute = this.routes.find(route => route.path === "*");
659
+ if (notFoundRoute) {
660
+ toMatch = {
661
+ route: notFoundRoute,
662
+ params: {
663
+ pathMatch: toLocation.path.substring(1)
664
+ }
665
+ };
666
+ } else {
667
+ await this.emitter.emit("router:onError", new Error(`Route not found: ${toLocation.path}`), toLocation, from);
668
+ return false;
669
+ }
670
+ }
671
+ const to = {
672
+ ...toLocation,
673
+ params: toMatch.params,
674
+ meta: toMatch.route.meta || {},
675
+ name: toMatch.route.name,
676
+ matched: toMatch.route
677
+ };
678
+ try {
679
+ // 1. Run all *pre-navigation* guards.
680
+ const canNavigate = await this._runGuards(to, from, toMatch.route);
681
+ if (!canNavigate) return false;
682
+
683
+ // 2. Resolve async components *before* touching the DOM.
684
+ const {
685
+ layoutComponent,
686
+ pageComponent
687
+ } = await this._resolveComponents(toMatch.route);
688
+
689
+ // 3. Unmount the previous view/layout.
690
+ if (from) {
691
+ const toLayout = toMatch.route.layout || this.options.globalLayout;
692
+ const fromLayout = from.matched.layout || this.options.globalLayout;
693
+ const tryUnmount = async instance => {
694
+ if (!instance) return;
695
+ try {
696
+ await instance.unmount();
697
+ } catch (error) {
698
+ this.errorHandler.warn("Error during component unmount", {
699
+ error,
700
+ instance
701
+ });
702
+ }
703
+ };
704
+ if (toLayout !== fromLayout) {
705
+ await tryUnmount(this.currentLayout.value);
706
+ this.currentLayout.value = null;
707
+ } else {
708
+ await tryUnmount(this.currentView.value);
709
+ this.currentView.value = null;
710
+ }
711
+
712
+ // 4. Call `afterLeave` hook *after* the old component has been unmounted.
713
+ if (from.matched.afterLeave) {
714
+ await from.matched.afterLeave(to, from);
715
+ await this.emitter.emit("router:afterLeave", to, from);
716
+ }
717
+ }
718
+
719
+ // 5. Update reactive state.
720
+ this.previousRoute.value = from;
721
+ this.currentRoute.value = to;
722
+ this.currentParams.value = to.params || {};
723
+ this.currentQuery.value = to.query || {};
724
+
725
+ // 6. Render the new components.
726
+ await this._render(layoutComponent, pageComponent, to);
727
+
728
+ // 7. Run post-navigation hooks.
729
+ if (toMatch.route.afterEnter) {
730
+ await toMatch.route.afterEnter(to, from);
731
+ await this.emitter.emit("router:afterEnter", to, from);
732
+ }
733
+ await this.emitter.emit("router:afterEach", to, from);
734
+ return true;
735
+ } catch (error) {
736
+ this.errorHandler.log("Error during navigation", error, {
737
+ to,
738
+ from
739
+ });
740
+ await this.emitter.emit("router:onError", error, to, from);
741
+ return false;
742
+ }
743
+ }
744
+
745
+ /**
746
+ * Executes all applicable navigation guards for a transition in order.
747
+ * @private
748
+ * @returns {Promise<boolean>} - `false` if navigation should be aborted.
749
+ */
750
+ async _runGuards(to, from, route) {
751
+ const guards = [...(this.options.onBeforeEach ? [this.options.onBeforeEach] : []), ...(from && from.matched.beforeLeave ? [from.matched.beforeLeave] : []), ...(route.beforeEnter ? [route.beforeEnter] : [])];
752
+ for (const guard of guards) {
753
+ const result = await guard(to, from);
754
+ if (result === false) return false;
755
+ if (typeof result === "string" || typeof result === "object") {
756
+ this.navigate(result);
757
+ return false;
758
+ }
759
+ }
760
+ return true;
761
+ }
762
+
763
+ /**
764
+ * Resolves a string component definition to a component object.
765
+ * @private
766
+ * @param {string} def - The component name to resolve.
767
+ * @returns {ComponentDefinition} The resolved component.
768
+ * @throws {Error} If the component is not registered.
769
+ */
770
+ _resolveStringComponent(def) {
771
+ const componentDef = this.eleva._components.get(def);
772
+ if (!componentDef) {
773
+ this.errorHandler.handle(new Error(`Component "${def}" not registered.`), "Component resolution failed", {
774
+ componentName: def,
775
+ availableComponents: Array.from(this.eleva._components.keys())
776
+ });
777
+ }
778
+ return componentDef;
779
+ }
780
+
781
+ /**
782
+ * Resolves a function component definition to a component object.
783
+ * @private
784
+ * @param {Function} def - The function to resolve.
785
+ * @returns {Promise<ComponentDefinition>} The resolved component.
786
+ * @throws {Error} If the function fails to load the component.
787
+ */
788
+ async _resolveFunctionComponent(def) {
789
+ try {
790
+ const funcStr = def.toString();
791
+ const isAsyncImport = funcStr.includes("import(") || funcStr.startsWith("() =>");
792
+ const result = await def();
793
+ return isAsyncImport ? result.default || result : result;
794
+ } catch (error) {
795
+ this.errorHandler.handle(new Error(`Failed to load async component: ${error.message}`), "Component resolution failed", {
796
+ function: def.toString(),
797
+ error
798
+ });
799
+ }
800
+ }
801
+
802
+ /**
803
+ * Validates a component definition object.
804
+ * @private
805
+ * @param {any} def - The component definition to validate.
806
+ * @returns {ComponentDefinition} The validated component.
807
+ * @throws {Error} If the component definition is invalid.
808
+ */
809
+ _validateComponentDefinition(def) {
810
+ if (!def || typeof def !== "object") {
811
+ this.errorHandler.handle(new Error(`Invalid component definition: ${typeof def}`), "Component validation failed", {
812
+ definition: def
813
+ });
814
+ }
815
+ if (typeof def.template !== "function" && typeof def.template !== "string") {
816
+ this.errorHandler.handle(new Error("Component missing template property"), "Component validation failed", {
817
+ definition: def
818
+ });
819
+ }
820
+ return def;
821
+ }
822
+
823
+ /**
824
+ * Resolves a component definition to a component object.
825
+ * @private
826
+ * @param {any} def - The component definition to resolve.
827
+ * @returns {Promise<ComponentDefinition | null>} The resolved component or null.
828
+ */
829
+ async _resolveComponent(def) {
830
+ if (def === null || def === undefined) {
831
+ return null;
832
+ }
833
+ if (typeof def === "string") {
834
+ return this._resolveStringComponent(def);
835
+ }
836
+ if (typeof def === "function") {
837
+ return await this._resolveFunctionComponent(def);
838
+ }
839
+ if (def && typeof def === "object") {
840
+ return this._validateComponentDefinition(def);
841
+ }
842
+ this.errorHandler.handle(new Error(`Invalid component definition: ${typeof def}`), "Component resolution failed", {
843
+ definition: def
844
+ });
845
+ }
846
+
847
+ /**
848
+ * Asynchronously resolves the layout and page components for a route.
849
+ * @private
850
+ * @param {RouteDefinition} route - The route to resolve components for.
851
+ * @returns {Promise<{layoutComponent: ComponentDefinition | null, pageComponent: ComponentDefinition}>}
852
+ */
853
+ async _resolveComponents(route) {
854
+ const effectiveLayout = route.layout || this.options.globalLayout;
855
+ try {
856
+ const [layoutComponent, pageComponent] = await Promise.all([this._resolveComponent(effectiveLayout), this._resolveComponent(route.component)]);
857
+ if (!pageComponent) {
858
+ this.errorHandler.handle(new Error(`Page component is null or undefined for route: ${route.path}`), "Component resolution failed", {
859
+ route: route.path
860
+ });
861
+ }
862
+ return {
863
+ layoutComponent,
864
+ pageComponent
865
+ };
866
+ } catch (error) {
867
+ this.errorHandler.log(`Error resolving components for route ${route.path}`, error, {
868
+ route: route.path
869
+ });
870
+ throw error;
871
+ }
872
+ }
873
+
874
+ /**
875
+ * Renders the components for the current route into the DOM.
876
+ * @private
877
+ * @param {ComponentDefinition | null} layoutComponent - The pre-loaded layout component.
878
+ * @param {ComponentDefinition} pageComponent - The pre-loaded page component.
879
+ */
880
+ async _render(layoutComponent, pageComponent) {
881
+ const mountEl = document.querySelector(this.options.mount);
882
+ if (!mountEl) {
883
+ this.errorHandler.handle(new Error(`Mount element "${this.options.mount}" not found.`), {
884
+ mountSelector: this.options.mount
885
+ });
886
+ }
887
+ if (layoutComponent) {
888
+ const layoutInstance = await this.eleva.mount(mountEl, this._wrapComponentWithChildren(layoutComponent));
889
+ this.currentLayout.value = layoutInstance;
890
+ const viewEl = this._findViewElement(layoutInstance.container);
891
+ const viewInstance = await this.eleva.mount(viewEl, this._wrapComponentWithChildren(pageComponent));
892
+ this.currentView.value = viewInstance;
893
+ } else {
894
+ const viewInstance = await this.eleva.mount(mountEl, this._wrapComponentWithChildren(pageComponent));
895
+ this.currentView.value = viewInstance;
896
+ this.currentLayout.value = null;
897
+ }
898
+ }
899
+
900
+ /**
901
+ * Creates a getter function for router context properties.
902
+ * @private
903
+ * @param {string} property - The property name to access.
904
+ * @param {any} defaultValue - The default value if property is undefined.
905
+ * @returns {Function} A getter function.
906
+ */
907
+ _createRouteGetter(property, defaultValue) {
908
+ return () => this.currentRoute.value?.[property] ?? defaultValue;
909
+ }
910
+
911
+ /**
912
+ * Wraps a component definition to inject router-specific context into its setup function.
913
+ * @private
914
+ * @param {ComponentDefinition} component - The component to wrap.
915
+ * @returns {ComponentDefinition} The wrapped component definition.
916
+ */
917
+ _wrapComponent(component) {
918
+ const originalSetup = component.setup;
919
+ const self = this;
920
+ return {
921
+ ...component,
922
+ async setup(ctx) {
923
+ ctx.router = {
924
+ navigate: self.navigate.bind(self),
925
+ current: self.currentRoute,
926
+ previous: self.previousRoute,
927
+ // Route property getters
928
+ get params() {
929
+ return self._createRouteGetter("params", {})();
930
+ },
931
+ get query() {
932
+ return self._createRouteGetter("query", {})();
933
+ },
934
+ get path() {
935
+ return self._createRouteGetter("path", "/")();
936
+ },
937
+ get fullUrl() {
938
+ return self._createRouteGetter("fullUrl", window.location.href)();
939
+ },
940
+ get meta() {
941
+ return self._createRouteGetter("meta", {})();
942
+ }
943
+ };
944
+ return originalSetup ? await originalSetup(ctx) : {};
945
+ }
946
+ };
947
+ }
948
+
949
+ /**
950
+ * Recursively wraps all child components to ensure they have access to router context.
951
+ * @private
952
+ * @param {ComponentDefinition} component - The component to wrap.
953
+ * @returns {ComponentDefinition} The wrapped component definition.
954
+ */
955
+ _wrapComponentWithChildren(component) {
956
+ const wrappedComponent = this._wrapComponent(component);
957
+
958
+ // If the component has children, wrap them too
959
+ if (wrappedComponent.children && typeof wrappedComponent.children === "object") {
960
+ const wrappedChildren = {};
961
+ for (const [selector, childComponent] of Object.entries(wrappedComponent.children)) {
962
+ wrappedChildren[selector] = this._wrapComponentWithChildren(childComponent);
963
+ }
964
+ wrappedComponent.children = wrappedChildren;
965
+ }
966
+ return wrappedComponent;
967
+ }
968
+
969
+ /**
970
+ * Gets the current location information from the browser's window object.
971
+ * @private
972
+ * @returns {Omit<RouteLocation, 'params' | 'meta' | 'name' | 'matched'>}
973
+ */
974
+ _getCurrentLocation() {
975
+ if (typeof window === "undefined") return {
976
+ path: "/",
977
+ query: {},
978
+ fullUrl: ""
979
+ };
980
+ let path, queryString, fullUrl;
981
+ switch (this.options.mode) {
982
+ case "hash":
983
+ fullUrl = window.location.hash.slice(1) || "/";
984
+ [path, queryString] = fullUrl.split("?");
985
+ break;
986
+ case "query":
987
+ const urlParams = new URLSearchParams(window.location.search);
988
+ path = urlParams.get(this.options.queryParam) || "/";
989
+ queryString = window.location.search.slice(1);
990
+ fullUrl = path;
991
+ break;
992
+ default:
993
+ // 'history' mode
994
+ path = window.location.pathname || "/";
995
+ queryString = window.location.search.slice(1);
996
+ fullUrl = `${path}${queryString ? "?" + queryString : ""}`;
997
+ }
998
+ return {
999
+ path: path.startsWith("/") ? path : `/${path}`,
1000
+ query: this._parseQuery(queryString),
1001
+ fullUrl
1002
+ };
1003
+ }
1004
+
1005
+ /**
1006
+ * Parses a query string into a key-value object.
1007
+ * @private
1008
+ */
1009
+ _parseQuery(queryString) {
1010
+ const query = {};
1011
+ if (queryString) {
1012
+ new URLSearchParams(queryString).forEach((value, key) => {
1013
+ query[key] = value;
1014
+ });
1015
+ }
1016
+ return query;
1017
+ }
1018
+
1019
+ /**
1020
+ * Matches a given path against the registered routes.
1021
+ * @private
1022
+ * @param {string} path - The path to match.
1023
+ * @returns {{route: RouteDefinition, params: Object<string, string>} | null} The matched route and its params, or null.
1024
+ */
1025
+ _matchRoute(path) {
1026
+ const pathSegments = path.split("/").filter(Boolean);
1027
+ for (const route of this.routes) {
1028
+ // Handle the root path as a special case.
1029
+ if (route.path === "/") {
1030
+ if (pathSegments.length === 0) return {
1031
+ route,
1032
+ params: {}
1033
+ };
1034
+ continue;
1035
+ }
1036
+ if (route.segments.length !== pathSegments.length) continue;
1037
+ const params = {};
1038
+ let isMatch = true;
1039
+ for (let i = 0; i < route.segments.length; i++) {
1040
+ const routeSegment = route.segments[i];
1041
+ const pathSegment = pathSegments[i];
1042
+ if (routeSegment.type === "param") {
1043
+ params[routeSegment.name] = decodeURIComponent(pathSegment);
1044
+ } else if (routeSegment.value !== pathSegment) {
1045
+ isMatch = false;
1046
+ break;
1047
+ }
1048
+ }
1049
+ if (isMatch) return {
1050
+ route,
1051
+ params
1052
+ };
1053
+ }
1054
+ return null;
1055
+ }
1056
+
1057
+ /** Registers a global pre-navigation guard. */
1058
+ onBeforeEach(guard) {
1059
+ this.options.onBeforeEach = guard;
1060
+ }
1061
+ /** Registers a global hook that runs after a new route component has been mounted *if* the route has an `afterEnter` hook. */
1062
+ onAfterEnter(hook) {
1063
+ this.emitter.on("router:afterEnter", hook);
1064
+ }
1065
+ /** Registers a global hook that runs after a route component has been unmounted *if* the route has an `afterLeave` hook. */
1066
+ onAfterLeave(hook) {
1067
+ this.emitter.on("router:afterLeave", hook);
1068
+ }
1069
+ /** Registers a global hook that runs after a navigation has been confirmed and all hooks have completed. */
1070
+ onAfterEach(hook) {
1071
+ this.emitter.on("router:afterEach", hook);
1072
+ }
1073
+ /** Registers a global error handler for navigation. */
1074
+ onError(handler) {
1075
+ this.emitter.on("router:onError", handler);
1076
+ }
1077
+
1078
+ /**
1079
+ * Registers a plugin with the router.
1080
+ * @param {RouterPlugin} plugin - The plugin to register.
1081
+ */
1082
+ use(plugin, options = {}) {
1083
+ if (typeof plugin.install !== "function") {
1084
+ this.errorHandler.handle(new Error("Plugin must have an install method"), "Plugin registration failed", {
1085
+ plugin
1086
+ });
1087
+ }
1088
+
1089
+ // Check if plugin is already registered
1090
+ if (this.plugins.has(plugin.name)) {
1091
+ this.errorHandler.warn(`Plugin "${plugin.name}" is already registered`, {
1092
+ existingPlugin: this.plugins.get(plugin.name)
1093
+ });
1094
+ return;
1095
+ }
1096
+ this.plugins.set(plugin.name, plugin);
1097
+ plugin.install(this, options);
1098
+ }
1099
+
1100
+ /**
1101
+ * Gets all registered plugins.
1102
+ * @returns {RouterPlugin[]} Array of registered plugins.
1103
+ */
1104
+ getPlugins() {
1105
+ return Array.from(this.plugins.values());
1106
+ }
1107
+
1108
+ /**
1109
+ * Gets a plugin by name.
1110
+ * @param {string} name - The plugin name.
1111
+ * @returns {RouterPlugin | undefined} The plugin or undefined.
1112
+ */
1113
+ getPlugin(name) {
1114
+ return this.plugins.get(name);
1115
+ }
1116
+
1117
+ /**
1118
+ * Removes a plugin from the router.
1119
+ * @param {string} name - The plugin name.
1120
+ * @returns {boolean} True if the plugin was removed.
1121
+ */
1122
+ removePlugin(name) {
1123
+ const plugin = this.plugins.get(name);
1124
+ if (!plugin) return false;
1125
+
1126
+ // Call destroy if available
1127
+ if (typeof plugin.destroy === "function") {
1128
+ try {
1129
+ plugin.destroy(this);
1130
+ } catch (error) {
1131
+ this.errorHandler.log(`Plugin ${name} destroy failed`, error);
1132
+ }
1133
+ }
1134
+ return this.plugins.delete(name);
1135
+ }
1136
+
1137
+ /**
1138
+ * Sets a custom error handler. Used by error handling plugins.
1139
+ * @param {Object} errorHandler - The error handler object with handle, warn, and log methods.
1140
+ */
1141
+ setErrorHandler(errorHandler) {
1142
+ if (errorHandler && typeof errorHandler.handle === "function" && typeof errorHandler.warn === "function" && typeof errorHandler.log === "function") {
1143
+ this.errorHandler = errorHandler;
1144
+ } else {
1145
+ console.warn("[ElevaRouter] Invalid error handler provided. Must have handle, warn, and log methods.");
1146
+ }
1147
+ }
1148
+ }
1149
+
1150
+ /**
1151
+ * @typedef {Object} RouterOptions
1152
+ * @property {string} mount - A CSS selector for the main element where the app is mounted.
1153
+ * @property {RouteDefinition[]} routes - An array of route definitions.
1154
+ * @property {'hash' | 'query' | 'history'} [mode='hash'] - The routing mode.
1155
+ * @property {string} [queryParam='page'] - The query parameter to use in 'query' mode.
1156
+ * @property {string} [viewSelector='view'] - The selector for the view element within a layout.
1157
+ * @property {boolean} [autoStart=true] - Whether to start the router automatically.
1158
+ * @property {NavigationGuard} [onBeforeEach] - A global guard executed before every navigation.
1159
+ * @property {string | ComponentDefinition | (() => Promise<{default: ComponentDefinition}>)} [globalLayout] - A global layout for all routes. Can be overridden by a route's specific layout.
1160
+ */
1161
+
1162
+ /**
1163
+ * @class 🚀 RouterPlugin
1164
+ * @classdesc A powerful, reactive, and flexible Router Plugin for Eleva.js applications.
1165
+ * This plugin provides comprehensive client-side routing functionality including:
1166
+ * - Multiple routing modes (hash, history, query)
1167
+ * - Navigation guards and lifecycle hooks
1168
+ * - Reactive state management
1169
+ * - Component resolution and lazy loading
1170
+ * - Layout and page component separation
1171
+ * - Plugin system for extensibility
1172
+ * - Advanced error handling
1173
+ *
1174
+ * @example
1175
+ * // Install the plugin
1176
+ * const app = new Eleva("myApp");
1177
+ *
1178
+ * const HomePage = { template: () => `<h1>Home</h1>` };
1179
+ * const AboutPage = { template: () => `<h1>About Us</h1>` };
1180
+ * const UserPage = {
1181
+ * template: (ctx) => `<h1>User: ${ctx.router.params.id}</h1>`
1182
+ * };
1183
+ *
1184
+ * app.use(RouterPlugin, {
1185
+ * mount: '#app',
1186
+ * mode: 'hash',
1187
+ * routes: [
1188
+ * { path: '/', component: HomePage },
1189
+ * { path: '/about', component: AboutPage },
1190
+ * { path: '/users/:id', component: UserPage }
1191
+ * ]
1192
+ * });
1193
+ */
1194
+ const RouterPlugin = {
1195
+ /**
1196
+ * Unique identifier for the plugin
1197
+ * @type {string}
1198
+ */
1199
+ name: "router",
1200
+ /**
1201
+ * Plugin version
1202
+ * @type {string}
1203
+ */
1204
+ version: "1.0.0-rc.1",
1205
+ /**
1206
+ * Plugin description
1207
+ * @type {string}
1208
+ */
1209
+ description: "Client-side routing for Eleva applications",
1210
+ /**
1211
+ * Installs the RouterPlugin into an Eleva instance.
1212
+ *
1213
+ * @param {Eleva} eleva - The Eleva instance
1214
+ * @param {RouterOptions} options - Router configuration options
1215
+ * @param {string} options.mount - A CSS selector for the main element where the app is mounted
1216
+ * @param {RouteDefinition[]} options.routes - An array of route definitions
1217
+ * @param {'hash' | 'query' | 'history'} [options.mode='hash'] - The routing mode
1218
+ * @param {string} [options.queryParam='page'] - The query parameter to use in 'query' mode
1219
+ * @param {string} [options.viewSelector='view'] - The selector for the view element within a layout
1220
+ * @param {boolean} [options.autoStart=true] - Whether to start the router automatically
1221
+ * @param {NavigationGuard} [options.onBeforeEach] - A global guard executed before every navigation
1222
+ * @param {string | ComponentDefinition | (() => Promise<{default: ComponentDefinition}>)} [options.globalLayout] - A global layout for all routes
1223
+ *
1224
+ * @example
1225
+ * // main.js
1226
+ * import Eleva from './eleva.js';
1227
+ * import { RouterPlugin } from './plugins/RouterPlugin.js';
1228
+ *
1229
+ * const app = new Eleva('myApp');
1230
+ *
1231
+ * const HomePage = { template: () => `<h1>Home</h1>` };
1232
+ * const AboutPage = { template: () => `<h1>About Us</h1>` };
1233
+ *
1234
+ * app.use(RouterPlugin, {
1235
+ * mount: '#app',
1236
+ * routes: [
1237
+ * { path: '/', component: HomePage },
1238
+ * { path: '/about', component: AboutPage }
1239
+ * ]
1240
+ * });
1241
+ */
1242
+ install(eleva, options = {}) {
1243
+ if (!options.mount) {
1244
+ throw new Error("[RouterPlugin] 'mount' option is required");
1245
+ }
1246
+ if (!options.routes || !Array.isArray(options.routes)) {
1247
+ throw new Error("[RouterPlugin] 'routes' option must be an array");
1248
+ }
1249
+
1250
+ /**
1251
+ * Registers a component definition with the Eleva instance.
1252
+ * This method handles both inline component objects and pre-registered component names.
1253
+ *
1254
+ * @param {any} def - The component definition to register
1255
+ * @param {string} type - The type of component for naming (e.g., "Route", "Layout")
1256
+ * @returns {string | null} The registered component name or null if no definition provided
1257
+ */
1258
+ const register = (def, type) => {
1259
+ if (!def) return null;
1260
+ if (typeof def === "object" && def !== null && !def.name) {
1261
+ const name = `Eleva${type}Component_${Math.random().toString(36).slice(2, 11)}`;
1262
+ try {
1263
+ eleva.component(name, def);
1264
+ return name;
1265
+ } catch (error) {
1266
+ throw new Error(`[RouterPlugin] Failed to register ${type} component: ${error.message}`);
1267
+ }
1268
+ }
1269
+ return def;
1270
+ };
1271
+ if (options.globalLayout) {
1272
+ options.globalLayout = register(options.globalLayout, "GlobalLayout");
1273
+ }
1274
+ (options.routes || []).forEach(route => {
1275
+ route.component = register(route.component, "Route");
1276
+ if (route.layout) {
1277
+ route.layout = register(route.layout, "RouteLayout");
1278
+ }
1279
+ });
1280
+ const router = new Router(eleva, options);
1281
+ eleva.router = router;
1282
+ if (options.autoStart !== false) {
1283
+ queueMicrotask(() => router.start());
1284
+ }
1285
+
1286
+ // Add plugin metadata to the Eleva instance
1287
+ if (!eleva.plugins) {
1288
+ eleva.plugins = new Map();
1289
+ }
1290
+ eleva.plugins.set(this.name, {
1291
+ name: this.name,
1292
+ version: this.version,
1293
+ description: this.description,
1294
+ options
1295
+ });
1296
+
1297
+ // Add utility methods for manual router access
1298
+ eleva.navigate = router.navigate.bind(router);
1299
+ eleva.getCurrentRoute = () => router.currentRoute.value;
1300
+ eleva.getRouteParams = () => router.currentParams.value;
1301
+ eleva.getRouteQuery = () => router.currentQuery.value;
1302
+ return router;
1303
+ },
1304
+ /**
1305
+ * Uninstalls the plugin from the Eleva instance
1306
+ *
1307
+ * @param {Eleva} eleva - The Eleva instance
1308
+ */
1309
+ async uninstall(eleva) {
1310
+ if (eleva.router) {
1311
+ await eleva.router.destroy();
1312
+ delete eleva.router;
1313
+ }
1314
+
1315
+ // Remove plugin metadata
1316
+ if (eleva.plugins) {
1317
+ eleva.plugins.delete(this.name);
1318
+ }
1319
+
1320
+ // Remove utility methods
1321
+ delete eleva.navigate;
1322
+ delete eleva.getCurrentRoute;
1323
+ delete eleva.getRouteParams;
1324
+ delete eleva.getRouteQuery;
1325
+ }
1326
+ };
1327
+
1328
+ exports.Attr = AttrPlugin;
1329
+ exports.Router = RouterPlugin;
1330
+ //# sourceMappingURL=eleva-plugins.cjs.js.map