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