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