eleva 1.0.0-rc.5 → 1.0.0-rc.7
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.
- package/README.md +135 -6
- package/dist/eleva-plugins.cjs.js +861 -29
- package/dist/eleva-plugins.cjs.js.map +1 -1
- package/dist/eleva-plugins.esm.js +861 -30
- package/dist/eleva-plugins.esm.js.map +1 -1
- package/dist/eleva-plugins.umd.js +861 -29
- package/dist/eleva-plugins.umd.js.map +1 -1
- package/dist/eleva-plugins.umd.min.js +2 -2
- package/dist/eleva-plugins.umd.min.js.map +1 -1
- package/dist/eleva.cjs.js +31 -25
- package/dist/eleva.cjs.js.map +1 -1
- package/dist/eleva.esm.js +31 -25
- package/dist/eleva.esm.js.map +1 -1
- package/dist/eleva.umd.js +31 -25
- package/dist/eleva.umd.js.map +1 -1
- package/dist/eleva.umd.min.js +2 -2
- package/dist/eleva.umd.min.js.map +1 -1
- package/dist/plugins/attr.umd.js +2 -2
- package/dist/plugins/attr.umd.js.map +1 -1
- package/dist/plugins/attr.umd.min.js +1 -1
- package/dist/plugins/attr.umd.min.js.map +1 -1
- package/dist/plugins/props.umd.js +235 -2
- package/dist/plugins/props.umd.js.map +1 -1
- package/dist/plugins/props.umd.min.js +2 -2
- package/dist/plugins/props.umd.min.js.map +1 -1
- package/dist/plugins/router.umd.js +22 -25
- package/dist/plugins/router.umd.js.map +1 -1
- package/dist/plugins/router.umd.min.js +1 -1
- package/dist/plugins/router.umd.min.js.map +1 -1
- package/dist/plugins/store.umd.js +632 -0
- package/dist/plugins/store.umd.js.map +1 -0
- package/dist/plugins/store.umd.min.js +3 -0
- package/dist/plugins/store.umd.min.js.map +1 -0
- package/package.json +4 -4
- package/src/plugins/Props.js +206 -1
- package/src/plugins/Store.js +741 -0
- package/src/plugins/index.js +6 -1
- package/types/plugins/Props.d.ts.map +1 -1
- package/types/plugins/Store.d.ts +86 -0
- package/types/plugins/Store.d.ts.map +1 -0
- package/types/plugins/index.d.ts +1 -0
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
/*! Eleva Router Plugin v1.0.0-rc.1 | MIT License | https://elevajs.com */
|
|
2
|
-
var t,e;t=this,e=function(t){"use strict";const e={handle(t,e,r={}){const n=new Error(`[ElevaRouter] ${e}: ${t.message}`);throw n.originalError=t,n.context=e,n.details=r,n},warn(t,e={}){},log(t,e,r={}){}};class r{constructor(t,r={}){this.eleva=t,this.options={mode:"hash",queryParam:"view",viewSelector:"root",...r},this.routes=this._processRoutes(r.routes||[]),this.emitter=this.eleva.emitter,this.isStarted=!1,this._isNavigating=!1,this.eventListeners=[],this.currentRoute=new this.eleva.signal(null),this.previousRoute=new this.eleva.signal(null),this.currentParams=new this.eleva.signal({}),this.currentQuery=new this.eleva.signal({}),this.currentLayout=new this.eleva.signal(null),this.currentView=new this.eleva.signal(null),this.plugins=new Map,this.errorHandler=e,this._validateOptions()}_validateOptions(){["hash","query","history"].includes(this.options.mode)||this.errorHandler.handle(new Error(`Invalid routing mode: ${this.options.mode}. Must be "hash", "query", or "history".`),"Configuration validation failed")}_processRoutes(t){const e=[];for(const r of t)try{e.push({...r,segments:this._parsePathIntoSegments(r.path)})}catch(t){this.errorHandler.warn(`Invalid path in route definition "${r.path||"undefined"}": ${t.message}`,{route:r,error:t})}return e}_parsePathIntoSegments(t){t&&"string"==typeof t||this.errorHandler.handle(new Error("Route path must be a non-empty string"),"Path parsing failed",{path:t});const e=t.replace(/\/+/g,"/").replace(/\/$/,"")||"/";return"/"===e?[]:e.split("/").filter(Boolean).map(e=>{if(e.startsWith(":")){const r=e.substring(1);return r||this.errorHandler.handle(new Error(`Invalid parameter segment: ${e}`),"Path parsing failed",{segment:e,path:t}),{type:"param",name:r}}return{type:"static",value:e}})}_findViewElement(t){const e=this.options.viewSelector;return t.querySelector(`#${e}`)||t.querySelector(`.${e}`)||t.querySelector(`[data-${e}]`)||t.querySelector(e)||t}async start(){if(this.isStarted)return void this.errorHandler.warn("Router is already started");if("undefined"==typeof window)return void this.errorHandler.warn("Router start skipped: `window` object not available (SSR environment)");if("undefined"!=typeof document&&!document.querySelector(this.options.mount))return void this.errorHandler.warn(`Mount element "${this.options.mount}" was not found in the DOM. The router will not start.`,{mountSelector:this.options.mount});const t=()=>this._handleRouteChange();"hash"===this.options.mode?(window.addEventListener("hashchange",t),this.eventListeners.push(()=>window.removeEventListener("hashchange",t))):(window.addEventListener("popstate",t),this.eventListeners.push(()=>window.removeEventListener("popstate",t))),this.isStarted=!0,await this._handleRouteChange()}async destroy(){if(this.isStarted){for(const t of this.plugins.values())if("function"==typeof t.destroy)try{await t.destroy(this)}catch(e){this.errorHandler.log(`Plugin ${t.name} destroy failed`,e)}this.eventListeners.forEach(t=>t()),this.eventListeners=[],this.currentLayout.value&&await this.currentLayout.value.unmount(),this.isStarted=!1}}async navigate(t,e={}){try{const r="string"==typeof t?{path:t,params:e}:t;let n=this._buildPath(r.path,r.params||{});const o=r.query||{};if(Object.keys(o).length>0){const t=new URLSearchParams(o).toString();t&&(n+=`?${t}`)}if(this._isSameRoute(n,r.params,o))return;if(await this._proceedWithNavigation(n)){this._isNavigating=!0;const t=r.state||{},e=r.replace||!1,o=e?"replaceState":"pushState";if("hash"===this.options.mode)if(e){const e=`${window.location.pathname}${window.location.search}#${n}`;window.history.replaceState(t,"",e)}else window.location.hash=n;else{const e="query"===this.options.mode?this._buildQueryUrl(n):n;history[o](t,"",e)}queueMicrotask(()=>{this._isNavigating=!1})}}catch(t){this.errorHandler.log("Navigation failed",t),await this.emitter.emit("router:onError",t)}}_buildQueryUrl(t){const e=new URLSearchParams(window.location.search);return e.set(this.options.queryParam,t.split("?")[0]),`${window.location.pathname}?${e.toString()}`}_isSameRoute(t,e,r){const n=this.currentRoute.value;if(!n)return!1;const[o,i]=t.split("?"),a=r||this._parseQuery(i||"");return n.path===o&&JSON.stringify(n.params)===JSON.stringify(e||{})&&JSON.stringify(n.query)===JSON.stringify(a)}_buildPath(t,e){let r=t;for(const[t,n]of Object.entries(e)){const e=encodeURIComponent(String(n));r=r.replace(new RegExp(`:${t}\\b`,"g"),e)}return r}async _handleRouteChange(){if(this._isNavigating)return;const t=this.currentRoute.value,e=this._getCurrentLocation();!await this._proceedWithNavigation(e.fullUrl)&&t&&this.navigate({path:t.path,query:t.query,replace:!0})}async _proceedWithNavigation(t){const e=this.currentRoute.value,[r,n]=(t||"/").split("?"),o={path:r.startsWith("/")?r:`/${r}`,query:this._parseQuery(n),fullUrl:t};let i=this._matchRoute(o.path);if(!i){const t=this.routes.find(t=>"*"===t.path);if(!t)return await this.emitter.emit("router:onError",new Error(`Route not found: ${o.path}`),o,e),!1;i={route:t,params:{pathMatch:o.path.substring(1)}}}const a={...o,params:i.params,meta:i.route.meta||{},name:i.route.name,matched:i.route};try{if(!await this._runGuards(a,e,i.route))return!1;const{layoutComponent:t,pageComponent:r}=await this._resolveComponents(i.route);if(e){const t=async t=>{if(t)try{await t.unmount()}catch(e){this.errorHandler.warn("Error during component unmount",{error:e,instance:t})}};(i.route.layout||this.options.globalLayout)!==(e.matched.layout||this.options.globalLayout)?(await t(this.currentLayout.value),this.currentLayout.value=null):(await t(this.currentView.value),this.currentView.value=null),e.matched.afterLeave&&(await e.matched.afterLeave(a,e),await this.emitter.emit("router:afterLeave",a,e))}return this.previousRoute.value=e,this.currentRoute.value=a,this.currentParams.value=a.params||{},this.currentQuery.value=a.query||{},await this._render(t,r,a),i.route.afterEnter&&(await i.route.afterEnter(a,e),await this.emitter.emit("router:afterEnter",a,e)),await this.emitter.emit("router:afterEach",a,e),!0}catch(t){return this.errorHandler.log("Error during navigation",t,{to:a,from:e}),await this.emitter.emit("router:onError",t,a,e),!1}}async _runGuards(t,e,r){const n=[...this.options.onBeforeEach?[this.options.onBeforeEach]:[],...e&&e.matched.beforeLeave?[e.matched.beforeLeave]:[],...r.beforeEnter?[r.beforeEnter]:[]];for(const r of n){const n=await r(t,e);if(!1===n)return!1;if("string"==typeof n||"object"==typeof n)return this.navigate(n),!1}return!0}_resolveStringComponent(t){const e=this.eleva._components.get(t);return e||this.errorHandler.handle(new Error(`Component "${t}" not registered.`),"Component resolution failed",{componentName:t,availableComponents:Array.from(this.eleva._components.keys())}),e}async _resolveFunctionComponent(t){try{const e=t.toString(),r=e.includes("import(")||e.startsWith("() =>"),n=await t();return r&&n.default||n}catch(e){this.errorHandler.handle(new Error(`Failed to load async component: ${e.message}`),"Component resolution failed",{function:t.toString(),error:e})}}_validateComponentDefinition(t){return t&&"object"==typeof t||this.errorHandler.handle(new Error("Invalid component definition: "+typeof t),"Component validation failed",{definition:t}),"function"!=typeof t.template&&"string"!=typeof t.template&&this.errorHandler.handle(new Error("Component missing template property"),"Component validation failed",{definition:t}),t}async _resolveComponent(t){return null==t?null:"string"==typeof t?this._resolveStringComponent(t):"function"==typeof t?await this._resolveFunctionComponent(t):t&&"object"==typeof t?this._validateComponentDefinition(t):void this.errorHandler.handle(new Error("Invalid component definition: "+typeof t),"Component resolution failed",{definition:t})}async _resolveComponents(t){const e=t.layout||this.options.globalLayout;try{const[r,n]=await Promise.all([this._resolveComponent(e),this._resolveComponent(t.component)]);return n||this.errorHandler.handle(new Error(`Page component is null or undefined for route: ${t.path}`),"Component resolution failed",{route:t.path}),{layoutComponent:r,pageComponent:n}}catch(e){throw this.errorHandler.log(`Error resolving components for route ${t.path}`,e,{route:t.path}),e}}async _render(t,e){const r=document.querySelector(this.options.mount);if(r||this.errorHandler.handle(new Error(`Mount element "${this.options.mount}" not found.`),{mountSelector:this.options.mount}),t){const n=await this.eleva.mount(r,this._wrapComponentWithChildren(t));this.currentLayout.value=n;const o=this._findViewElement(n.container),i=await this.eleva.mount(o,this._wrapComponentWithChildren(e));this.currentView.value=i}else{const t=await this.eleva.mount(r,this._wrapComponentWithChildren(e));this.currentView.value=t,this.currentLayout.value=null}}_createRouteGetter(t,e){return()=>this.currentRoute.value?.[t]??e}_wrapComponent(t){const e=t.setup,r=this;return{...t,setup:async t=>(t.router={navigate:r.navigate.bind(r),current:r.currentRoute,previous:r.previousRoute,get params(){return r._createRouteGetter("params",{})()},get query(){return r._createRouteGetter("query",{})()},get path(){return r._createRouteGetter("path","/")()},get fullUrl(){return r._createRouteGetter("fullUrl",window.location.href)()},get meta(){return r._createRouteGetter("meta",{})()}},e?await e(t):{})}}_wrapComponentWithChildren(t){const e=this._wrapComponent(t);if(e.children&&"object"==typeof e.children){const t={};for(const[r,n]of Object.entries(e.children))t[r]=this._wrapComponentWithChildren(n);e.children=t}return e}_getCurrentLocation(){if("undefined"==typeof window)return{path:"/",query:{},fullUrl:""};let t,e,r;switch(this.options.mode){case"hash":r=window.location.hash.slice(1)||"/",[t,e]=r.split("?");break;case"query":t=new URLSearchParams(window.location.search).get(this.options.queryParam)||"/",e=window.location.search.slice(1),r=t;break;default:t=window.location.pathname||"/",e=window.location.search.slice(1),r=`${t}${e?"?"+e:""}`}return{path:t.startsWith("/")?t:`/${t}`,query:this._parseQuery(e),fullUrl:r}}_parseQuery(t){const e={};return t&&new URLSearchParams(t).forEach((t,r)=>{e[r]=t}),e}_matchRoute(t){const e=t.split("/").filter(Boolean);for(const t of this.routes){if("/"===t.path){if(0===e.length)return{route:t,params:{}};continue}if(t.segments.length!==e.length)continue;const r={};let n=!0;for(let o=0;o<t.segments.length;o++){const i=t.segments[o],a=e[o];if("param"===i.type)r[i.name]=decodeURIComponent(a);else if(i.value!==a){n=!1;break}}if(n)return{route:t,params:r}}return null}onBeforeEach(t){this.options.onBeforeEach=t}onAfterEnter(t){this.emitter.on("router:afterEnter",t)}onAfterLeave(t){this.emitter.on("router:afterLeave",t)}onAfterEach(t){this.emitter.on("router:afterEach",t)}onError(t){this.emitter.on("router:onError",t)}use(t,e={}){"function"!=typeof t.install&&this.errorHandler.handle(new Error("Plugin must have an install method"),"Plugin registration failed",{plugin:t}),this.plugins.has(t.name)?this.errorHandler.warn(`Plugin "${t.name}" is already registered`,{existingPlugin:this.plugins.get(t.name)}):(this.plugins.set(t.name,t),t.install(this,e))}getPlugins(){return Array.from(this.plugins.values())}getPlugin(t){return this.plugins.get(t)}removePlugin(t){const e=this.plugins.get(t);if(!e)return!1;if("function"==typeof e.destroy)try{e.destroy(this)}catch(e){this.errorHandler.log(`Plugin ${t} destroy failed`,e)}return this.plugins.delete(t)}setErrorHandler(t){t&&"function"==typeof t.handle&&"function"==typeof t.warn&&"function"==typeof t.log&&(this.errorHandler=t)}}t.RouterPlugin={name:"router",version:"1.0.0-rc.1",description:"Client-side routing for Eleva applications",install(t,e={}){if(!e.mount)throw new Error("[RouterPlugin] 'mount' option is required");if(!e.routes||!Array.isArray(e.routes))throw new Error("[RouterPlugin] 'routes' option must be an array");const n=(e,r)=>{if(!e)return null;if("object"==typeof e&&null!==e&&!e.name){const n=`Eleva${r}Component_${Math.random().toString(36).slice(2,11)}`;try{return t.component(n,e),n}catch(t){throw new Error(`[RouterPlugin] Failed to register ${r} component: ${t.message}`)}}return e};e.globalLayout&&(e.globalLayout=n(e.globalLayout,"GlobalLayout")),(e.routes||[]).forEach(t=>{t.component=n(t.component,"Route"),t.layout&&(t.layout=n(t.layout,"RouteLayout"))});const o=new r(t,e);return t.router=o,!1!==e.autoStart&&queueMicrotask(()=>o.start()),t.plugins||(t.plugins=new Map),t.plugins.set(this.name,{name:this.name,version:this.version,description:this.description,options:e}),t.navigate=o.navigate.bind(o),t.getCurrentRoute=()=>o.currentRoute.value,t.getRouteParams=()=>o.currentParams.value,t.getRouteQuery=()=>o.currentQuery.value,o},async uninstall(t){t.router&&(await t.router.destroy(),delete t.router),t.plugins&&t.plugins.delete(this.name),delete t.navigate,delete t.getCurrentRoute,delete t.getRouteParams,delete t.getRouteQuery}}},"object"==typeof exports&&"undefined"!=typeof module?e(exports):"function"==typeof define&&define.amd?define(["exports"],e):e((t="undefined"!=typeof globalThis?globalThis:t||self).ElevaRouterPlugin={});
|
|
2
|
+
var t,e;t=this,e=function(t){"use strict";function e(){return e=Object.assign?Object.assign.bind():function(t){for(var e=1;e<arguments.length;e++){var r=arguments[e];for(var n in r)({}).hasOwnProperty.call(r,n)&&(t[n]=r[n])}return t},e.apply(null,arguments)}const r={handle(t,e,r={}){const n=new Error(`[ElevaRouter] ${e}: ${t.message}`);throw n.originalError=t,n.context=e,n.details=r,n},warn(t,e={}){},log(t,e,r={}){}};class n{constructor(t,n={}){this.eleva=t,this.options=e({mode:"hash",queryParam:"view",viewSelector:"root"},n),this.routes=this._processRoutes(n.routes||[]),this.emitter=this.eleva.emitter,this.isStarted=!1,this._isNavigating=!1,this.eventListeners=[],this.currentRoute=new this.eleva.signal(null),this.previousRoute=new this.eleva.signal(null),this.currentParams=new this.eleva.signal({}),this.currentQuery=new this.eleva.signal({}),this.currentLayout=new this.eleva.signal(null),this.currentView=new this.eleva.signal(null),this.plugins=new Map,this.errorHandler=r,this._validateOptions()}_validateOptions(){["hash","query","history"].includes(this.options.mode)||this.errorHandler.handle(new Error(`Invalid routing mode: ${this.options.mode}. Must be "hash", "query", or "history".`),"Configuration validation failed")}_processRoutes(t){const r=[];for(const n of t)try{r.push(e({},n,{segments:this._parsePathIntoSegments(n.path)}))}catch(t){this.errorHandler.warn(`Invalid path in route definition "${n.path||"undefined"}": ${t.message}`,{route:n,error:t})}return r}_parsePathIntoSegments(t){t&&"string"==typeof t||this.errorHandler.handle(new Error("Route path must be a non-empty string"),"Path parsing failed",{path:t});const e=t.replace(/\/+/g,"/").replace(/\/$/,"")||"/";return"/"===e?[]:e.split("/").filter(Boolean).map(e=>{if(e.startsWith(":")){const r=e.substring(1);return r||this.errorHandler.handle(new Error(`Invalid parameter segment: ${e}`),"Path parsing failed",{segment:e,path:t}),{type:"param",name:r}}return{type:"static",value:e}})}_findViewElement(t){const e=this.options.viewSelector;return t.querySelector(`#${e}`)||t.querySelector(`.${e}`)||t.querySelector(`[data-${e}]`)||t.querySelector(e)||t}async start(){if(this.isStarted)return void this.errorHandler.warn("Router is already started");if("undefined"==typeof window)return void this.errorHandler.warn("Router start skipped: `window` object not available (SSR environment)");if("undefined"!=typeof document&&!document.querySelector(this.options.mount))return void this.errorHandler.warn(`Mount element "${this.options.mount}" was not found in the DOM. The router will not start.`,{mountSelector:this.options.mount});const t=()=>this._handleRouteChange();"hash"===this.options.mode?(window.addEventListener("hashchange",t),this.eventListeners.push(()=>window.removeEventListener("hashchange",t))):(window.addEventListener("popstate",t),this.eventListeners.push(()=>window.removeEventListener("popstate",t))),this.isStarted=!0,await this._handleRouteChange()}async destroy(){if(this.isStarted){for(const t of this.plugins.values())if("function"==typeof t.destroy)try{await t.destroy(this)}catch(e){this.errorHandler.log(`Plugin ${t.name} destroy failed`,e)}this.eventListeners.forEach(t=>t()),this.eventListeners=[],this.currentLayout.value&&await this.currentLayout.value.unmount(),this.isStarted=!1}}async navigate(t,e={}){try{const r="string"==typeof t?{path:t,params:e}:t;let n=this._buildPath(r.path,r.params||{});const o=r.query||{};if(Object.keys(o).length>0){const t=new URLSearchParams(o).toString();t&&(n+=`?${t}`)}if(this._isSameRoute(n,r.params,o))return;if(await this._proceedWithNavigation(n)){this._isNavigating=!0;const t=r.state||{},e=r.replace||!1,o=e?"replaceState":"pushState";if("hash"===this.options.mode)if(e){const e=`${window.location.pathname}${window.location.search}#${n}`;window.history.replaceState(t,"",e)}else window.location.hash=n;else{const e="query"===this.options.mode?this._buildQueryUrl(n):n;history[o](t,"",e)}queueMicrotask(()=>{this._isNavigating=!1})}}catch(t){this.errorHandler.log("Navigation failed",t),await this.emitter.emit("router:onError",t)}}_buildQueryUrl(t){const e=new URLSearchParams(window.location.search);return e.set(this.options.queryParam,t.split("?")[0]),`${window.location.pathname}?${e.toString()}`}_isSameRoute(t,e,r){const n=this.currentRoute.value;if(!n)return!1;const[o,i]=t.split("?"),a=r||this._parseQuery(i||"");return n.path===o&&JSON.stringify(n.params)===JSON.stringify(e||{})&&JSON.stringify(n.query)===JSON.stringify(a)}_buildPath(t,e){let r=t;for(const[t,n]of Object.entries(e)){const e=encodeURIComponent(String(n));r=r.replace(new RegExp(`:${t}\\b`,"g"),e)}return r}async _handleRouteChange(){if(this._isNavigating)return;const t=this.currentRoute.value,e=this._getCurrentLocation();!await this._proceedWithNavigation(e.fullUrl)&&t&&this.navigate({path:t.path,query:t.query,replace:!0})}async _proceedWithNavigation(t){const r=this.currentRoute.value,[n,o]=(t||"/").split("?"),i={path:n.startsWith("/")?n:`/${n}`,query:this._parseQuery(o),fullUrl:t};let a=this._matchRoute(i.path);if(!a){const t=this.routes.find(t=>"*"===t.path);if(!t)return await this.emitter.emit("router:onError",new Error(`Route not found: ${i.path}`),i,r),!1;a={route:t,params:{pathMatch:i.path.substring(1)}}}const s=e({},i,{params:a.params,meta:a.route.meta||{},name:a.route.name,matched:a.route});try{if(!await this._runGuards(s,r,a.route))return!1;const{layoutComponent:t,pageComponent:e}=await this._resolveComponents(a.route);if(r){const t=async t=>{if(t)try{await t.unmount()}catch(e){this.errorHandler.warn("Error during component unmount",{error:e,instance:t})}};(a.route.layout||this.options.globalLayout)!==(r.matched.layout||this.options.globalLayout)?(await t(this.currentLayout.value),this.currentLayout.value=null):(await t(this.currentView.value),this.currentView.value=null),r.matched.afterLeave&&(await r.matched.afterLeave(s,r),await this.emitter.emit("router:afterLeave",s,r))}return this.previousRoute.value=r,this.currentRoute.value=s,this.currentParams.value=s.params||{},this.currentQuery.value=s.query||{},await this._render(t,e,s),a.route.afterEnter&&(await a.route.afterEnter(s,r),await this.emitter.emit("router:afterEnter",s,r)),await this.emitter.emit("router:afterEach",s,r),!0}catch(t){return this.errorHandler.log("Error during navigation",t,{to:s,from:r}),await this.emitter.emit("router:onError",t,s,r),!1}}async _runGuards(t,e,r){const n=[...this.options.onBeforeEach?[this.options.onBeforeEach]:[],...e&&e.matched.beforeLeave?[e.matched.beforeLeave]:[],...r.beforeEnter?[r.beforeEnter]:[]];for(const r of n){const n=await r(t,e);if(!1===n)return!1;if("string"==typeof n||"object"==typeof n)return this.navigate(n),!1}return!0}_resolveStringComponent(t){const e=this.eleva._components.get(t);return e||this.errorHandler.handle(new Error(`Component "${t}" not registered.`),"Component resolution failed",{componentName:t,availableComponents:Array.from(this.eleva._components.keys())}),e}async _resolveFunctionComponent(t){try{const e=t.toString(),r=e.includes("import(")||e.startsWith("() =>"),n=await t();return r&&n.default||n}catch(e){this.errorHandler.handle(new Error(`Failed to load async component: ${e.message}`),"Component resolution failed",{function:t.toString(),error:e})}}_validateComponentDefinition(t){return t&&"object"==typeof t||this.errorHandler.handle(new Error("Invalid component definition: "+typeof t),"Component validation failed",{definition:t}),"function"!=typeof t.template&&"string"!=typeof t.template&&this.errorHandler.handle(new Error("Component missing template property"),"Component validation failed",{definition:t}),t}async _resolveComponent(t){return null==t?null:"string"==typeof t?this._resolveStringComponent(t):"function"==typeof t?await this._resolveFunctionComponent(t):t&&"object"==typeof t?this._validateComponentDefinition(t):void this.errorHandler.handle(new Error("Invalid component definition: "+typeof t),"Component resolution failed",{definition:t})}async _resolveComponents(t){const e=t.layout||this.options.globalLayout;try{const[r,n]=await Promise.all([this._resolveComponent(e),this._resolveComponent(t.component)]);return n||this.errorHandler.handle(new Error(`Page component is null or undefined for route: ${t.path}`),"Component resolution failed",{route:t.path}),{layoutComponent:r,pageComponent:n}}catch(e){throw this.errorHandler.log(`Error resolving components for route ${t.path}`,e,{route:t.path}),e}}async _render(t,e){const r=document.querySelector(this.options.mount);if(r||this.errorHandler.handle(new Error(`Mount element "${this.options.mount}" not found.`),{mountSelector:this.options.mount}),t){const n=await this.eleva.mount(r,this._wrapComponentWithChildren(t));this.currentLayout.value=n;const o=this._findViewElement(n.container),i=await this.eleva.mount(o,this._wrapComponentWithChildren(e));this.currentView.value=i}else{const t=await this.eleva.mount(r,this._wrapComponentWithChildren(e));this.currentView.value=t,this.currentLayout.value=null}}_createRouteGetter(t,e){return()=>{var r,n;return null!=(r=null==(n=this.currentRoute.value)?void 0:n[t])?r:e}}_wrapComponent(t){const r=t.setup,n=this;return e({},t,{setup:async t=>(t.router={navigate:n.navigate.bind(n),current:n.currentRoute,previous:n.previousRoute,get params(){return n._createRouteGetter("params",{})()},get query(){return n._createRouteGetter("query",{})()},get path(){return n._createRouteGetter("path","/")()},get fullUrl(){return n._createRouteGetter("fullUrl",window.location.href)()},get meta(){return n._createRouteGetter("meta",{})()}},r?await r(t):{})})}_wrapComponentWithChildren(t){const e=this._wrapComponent(t);if(e.children&&"object"==typeof e.children){const t={};for(const[r,n]of Object.entries(e.children))t[r]=this._wrapComponentWithChildren(n);e.children=t}return e}_getCurrentLocation(){if("undefined"==typeof window)return{path:"/",query:{},fullUrl:""};let t,e,r;switch(this.options.mode){case"hash":r=window.location.hash.slice(1)||"/",[t,e]=r.split("?");break;case"query":t=new URLSearchParams(window.location.search).get(this.options.queryParam)||"/",e=window.location.search.slice(1),r=t;break;default:t=window.location.pathname||"/",e=window.location.search.slice(1),r=`${t}${e?"?"+e:""}`}return{path:t.startsWith("/")?t:`/${t}`,query:this._parseQuery(e),fullUrl:r}}_parseQuery(t){const e={};return t&&new URLSearchParams(t).forEach((t,r)=>{e[r]=t}),e}_matchRoute(t){const e=t.split("/").filter(Boolean);for(const t of this.routes){if("/"===t.path){if(0===e.length)return{route:t,params:{}};continue}if(t.segments.length!==e.length)continue;const r={};let n=!0;for(let o=0;o<t.segments.length;o++){const i=t.segments[o],a=e[o];if("param"===i.type)r[i.name]=decodeURIComponent(a);else if(i.value!==a){n=!1;break}}if(n)return{route:t,params:r}}return null}onBeforeEach(t){this.options.onBeforeEach=t}onAfterEnter(t){this.emitter.on("router:afterEnter",t)}onAfterLeave(t){this.emitter.on("router:afterLeave",t)}onAfterEach(t){this.emitter.on("router:afterEach",t)}onError(t){this.emitter.on("router:onError",t)}use(t,e={}){"function"!=typeof t.install&&this.errorHandler.handle(new Error("Plugin must have an install method"),"Plugin registration failed",{plugin:t}),this.plugins.has(t.name)?this.errorHandler.warn(`Plugin "${t.name}" is already registered`,{existingPlugin:this.plugins.get(t.name)}):(this.plugins.set(t.name,t),t.install(this,e))}getPlugins(){return Array.from(this.plugins.values())}getPlugin(t){return this.plugins.get(t)}removePlugin(t){const e=this.plugins.get(t);if(!e)return!1;if("function"==typeof e.destroy)try{e.destroy(this)}catch(e){this.errorHandler.log(`Plugin ${t} destroy failed`,e)}return this.plugins.delete(t)}setErrorHandler(t){t&&"function"==typeof t.handle&&"function"==typeof t.warn&&"function"==typeof t.log&&(this.errorHandler=t)}}t.RouterPlugin={name:"router",version:"1.0.0-rc.1",description:"Client-side routing for Eleva applications",install(t,e={}){if(!e.mount)throw new Error("[RouterPlugin] 'mount' option is required");if(!e.routes||!Array.isArray(e.routes))throw new Error("[RouterPlugin] 'routes' option must be an array");const r=(e,r)=>{if(!e)return null;if("object"==typeof e&&null!==e&&!e.name){const n=`Eleva${r}Component_${Math.random().toString(36).slice(2,11)}`;try{return t.component(n,e),n}catch(t){throw new Error(`[RouterPlugin] Failed to register ${r} component: ${t.message}`)}}return e};e.globalLayout&&(e.globalLayout=r(e.globalLayout,"GlobalLayout")),(e.routes||[]).forEach(t=>{t.component=r(t.component,"Route"),t.layout&&(t.layout=r(t.layout,"RouteLayout"))});const o=new n(t,e);return t.router=o,!1!==e.autoStart&&queueMicrotask(()=>o.start()),t.plugins||(t.plugins=new Map),t.plugins.set(this.name,{name:this.name,version:this.version,description:this.description,options:e}),t.navigate=o.navigate.bind(o),t.getCurrentRoute=()=>o.currentRoute.value,t.getRouteParams=()=>o.currentParams.value,t.getRouteQuery=()=>o.currentQuery.value,o},async uninstall(t){t.router&&(await t.router.destroy(),delete t.router),t.plugins&&t.plugins.delete(this.name),delete t.navigate,delete t.getCurrentRoute,delete t.getRouteParams,delete t.getRouteQuery}}},"object"==typeof exports&&"undefined"!=typeof module?e(exports):"function"==typeof define&&define.amd?define(["exports"],e):e((t="undefined"!=typeof globalThis?globalThis:t||self).ElevaRouterPlugin={});
|
|
3
3
|
//# sourceMappingURL=router.umd.min.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"router.umd.min.js","sources":["../../src/plugins/Router.js"],"sourcesContent":["\"use strict\";\n\n/**\n * @typedef {import('eleva').Eleva} Eleva\n * @typedef {import('eleva').Signal} Signal\n * @typedef {import('eleva').ComponentDefinition} ComponentDefinition\n */\n\n/**\n * Simple error handler for the core router.\n * Can be overridden by error handling plugins.\n * Provides consistent error formatting and logging for router operations.\n * @private\n */\nconst CoreErrorHandler = {\n /**\n * Handles router errors with basic formatting.\n * @param {Error} error - The error to handle.\n * @param {string} context - The context where the error occurred.\n * @param {Object} details - Additional error details.\n * @throws {Error} The formatted error.\n */\n handle(error, context, details = {}) {\n const message = `[ElevaRouter] ${context}: ${error.message}`;\n const formattedError = new Error(message);\n\n // Preserve original error details\n formattedError.originalError = error;\n formattedError.context = context;\n formattedError.details = details;\n\n console.error(message, { error, context, details });\n throw formattedError;\n },\n\n /**\n * Logs a warning without throwing an error.\n * @param {string} message - The warning message.\n * @param {Object} details - Additional warning details.\n */\n warn(message, details = {}) {\n console.warn(`[ElevaRouter] ${message}`, details);\n },\n\n /**\n * Logs an error without throwing.\n * @param {string} message - The error message.\n * @param {Error} error - The original error.\n * @param {Object} details - Additional error details.\n */\n log(message, error, details = {}) {\n console.error(`[ElevaRouter] ${message}`, { error, details });\n },\n};\n\n/**\n * @typedef {Object} RouteLocation\n * @property {string} path - The path of the route (e.g., '/users/123').\n * @property {Object<string, string>} query - An object representing the query parameters.\n * @property {string} fullUrl - The complete URL including hash, path, and query string.\n * @property {Object<string, string>} params - An object containing dynamic route parameters.\n * @property {Object<string, any>} meta - The meta object associated with the matched route.\n * @property {string} [name] - The optional name of the matched route.\n * @property {RouteDefinition} matched - The raw route definition object that was matched.\n */\n\n/**\n * @typedef {(to: RouteLocation, from: RouteLocation | null) => boolean | string | {path: string} | void | Promise<boolean | string | {path: string} | void>} NavigationGuard\n * A function that acts as a guard for navigation. It runs *before* the navigation is confirmed.\n * It can return:\n * - `true` or `undefined`: to allow navigation.\n * - `false`: to abort the navigation.\n * - a `string` (path) or a `location object`: to redirect to a new route.\n */\n\n/**\n * @typedef {(...args: any[]) => void | Promise<void>} NavigationHook\n * A function that acts as a lifecycle hook, typically for side effects. It does not affect navigation flow.\n */\n\n/**\n * @typedef {Object} RouterPlugin\n * @property {string} name - The plugin name.\n * @property {string} [version] - The plugin version.\n * @property {Function} install - The install function that receives the router instance.\n * @property {Function} [destroy] - Optional cleanup function called when the router is destroyed.\n */\n\n/**\n * @typedef {Object} RouteDefinition\n * @property {string} path - The URL path pattern (e.g., '/', '/about', '/users/:id', '*').\n * @property {string | ComponentDefinition | (() => Promise<{default: ComponentDefinition}>)} component - The component to render. Can be a registered name, a definition object, or an async import function.\n * @property {string | ComponentDefinition | (() => Promise<{default: ComponentDefinition}>)} [layout] - An optional layout component to wrap the route's component.\n * @property {string} [name] - An optional name for the route.\n * @property {Object<string, any>} [meta] - Optional metadata for the route (e.g., for titles, auth flags).\n * @property {NavigationGuard} [beforeEnter] - A route-specific guard executed before entering the route.\n * @property {NavigationHook} [afterEnter] - A hook executed *after* the route has been entered and the new component is mounted.\n * @property {NavigationGuard} [beforeLeave] - A guard executed *before* leaving the current route.\n * @property {NavigationHook} [afterLeave] - A hook executed *after* leaving the current route and its component has been unmounted.\n */\n\n/**\n * @class Router\n * @classdesc A powerful, reactive, and flexible Router Plugin for Eleva.js.\n * This class manages all routing logic, including state, navigation, and rendering.\n * @private\n */\nclass Router {\n /**\n * Creates an instance of the Router.\n * @param {Eleva} eleva - The Eleva framework instance.\n * @param {RouterOptions} options - The configuration options for the router.\n */\n constructor(eleva, options = {}) {\n /** @type {Eleva} The Eleva framework instance. */\n this.eleva = eleva;\n\n /** @type {RouterOptions} The merged router options. */\n this.options = {\n mode: \"hash\",\n queryParam: \"view\",\n viewSelector: \"root\",\n ...options,\n };\n\n /** @private @type {RouteDefinition[]} The processed list of route definitions. */\n this.routes = this._processRoutes(options.routes || []);\n\n /** @private @type {import('eleva').Emitter} The shared Eleva event emitter for global hooks. */\n this.emitter = this.eleva.emitter;\n\n /** @private @type {boolean} A flag indicating if the router has been started. */\n this.isStarted = false;\n\n /** @private @type {boolean} A flag to prevent navigation loops from history events. */\n this._isNavigating = false;\n\n /** @private @type {Array<() => void>} A collection of cleanup functions for event listeners. */\n this.eventListeners = [];\n\n /** @type {Signal<RouteLocation | null>} A reactive signal holding the current route's information. */\n this.currentRoute = new this.eleva.signal(null);\n\n /** @type {Signal<RouteLocation | null>} A reactive signal holding the previous route's information. */\n this.previousRoute = new this.eleva.signal(null);\n\n /** @type {Signal<Object<string, string>>} A reactive signal holding the current route's parameters. */\n this.currentParams = new this.eleva.signal({});\n\n /** @type {Signal<Object<string, string>>} A reactive signal holding the current route's query parameters. */\n this.currentQuery = new this.eleva.signal({});\n\n /** @type {Signal<import('eleva').MountResult | null>} A reactive signal for the currently mounted layout instance. */\n this.currentLayout = new this.eleva.signal(null);\n\n /** @type {Signal<import('eleva').MountResult | null>} A reactive signal for the currently mounted view (page) instance. */\n this.currentView = new this.eleva.signal(null);\n\n /** @private @type {Map<string, RouterPlugin>} Map of registered plugins by name. */\n this.plugins = new Map();\n\n /** @type {Object} The error handler instance. Can be overridden by plugins. */\n this.errorHandler = CoreErrorHandler;\n\n this._validateOptions();\n }\n\n /**\n * Validates the provided router options.\n * @private\n * @throws {Error} If the routing mode is invalid.\n */\n _validateOptions() {\n if (![\"hash\", \"query\", \"history\"].includes(this.options.mode)) {\n this.errorHandler.handle(\n new Error(\n `Invalid routing mode: ${this.options.mode}. Must be \"hash\", \"query\", or \"history\".`\n ),\n \"Configuration validation failed\"\n );\n }\n }\n\n /**\n * Pre-processes route definitions to parse their path segments for efficient matching.\n * @private\n * @param {RouteDefinition[]} routes - The raw route definitions.\n * @returns {RouteDefinition[]} The processed routes.\n */\n _processRoutes(routes) {\n const processedRoutes = [];\n for (const route of routes) {\n try {\n processedRoutes.push({\n ...route,\n segments: this._parsePathIntoSegments(route.path),\n });\n } catch (error) {\n this.errorHandler.warn(\n `Invalid path in route definition \"${route.path || \"undefined\"}\": ${error.message}`,\n { route, error }\n );\n }\n }\n return processedRoutes;\n }\n\n /**\n * Parses a route path string into an array of static and parameter segments.\n * @private\n * @param {string} path - The path pattern to parse.\n * @returns {Array<{type: 'static' | 'param', value?: string, name?: string}>} An array of segment objects.\n * @throws {Error} If the route path is not a valid string.\n */\n _parsePathIntoSegments(path) {\n if (!path || typeof path !== \"string\") {\n this.errorHandler.handle(\n new Error(\"Route path must be a non-empty string\"),\n \"Path parsing failed\",\n { path }\n );\n }\n\n const normalizedPath = path.replace(/\\/+/g, \"/\").replace(/\\/$/, \"\") || \"/\";\n\n if (normalizedPath === \"/\") {\n return [];\n }\n\n return normalizedPath\n .split(\"/\")\n .filter(Boolean)\n .map((segment) => {\n if (segment.startsWith(\":\")) {\n const paramName = segment.substring(1);\n if (!paramName) {\n this.errorHandler.handle(\n new Error(`Invalid parameter segment: ${segment}`),\n \"Path parsing failed\",\n { segment, path }\n );\n }\n return { type: \"param\", name: paramName };\n }\n return { type: \"static\", value: segment };\n });\n }\n\n /**\n * Finds the view element within a container using multiple selector strategies.\n * @private\n * @param {HTMLElement} container - The parent element to search within.\n * @returns {HTMLElement} The found view element or the container itself as a fallback.\n */\n _findViewElement(container) {\n const selector = this.options.viewSelector;\n return (\n container.querySelector(`#${selector}`) ||\n container.querySelector(`.${selector}`) ||\n container.querySelector(`[data-${selector}]`) ||\n container.querySelector(selector) ||\n container\n );\n }\n\n /**\n * Starts the router, initializes event listeners, and performs the initial navigation.\n * @returns {Promise<void>}\n */\n async start() {\n if (this.isStarted) {\n this.errorHandler.warn(\"Router is already started\");\n return;\n }\n if (typeof window === \"undefined\") {\n this.errorHandler.warn(\n \"Router start skipped: `window` object not available (SSR environment)\"\n );\n return;\n }\n if (\n typeof document !== \"undefined\" &&\n !document.querySelector(this.options.mount)\n ) {\n this.errorHandler.warn(\n `Mount element \"${this.options.mount}\" was not found in the DOM. The router will not start.`,\n { mountSelector: this.options.mount }\n );\n return;\n }\n const handler = () => this._handleRouteChange();\n if (this.options.mode === \"hash\") {\n window.addEventListener(\"hashchange\", handler);\n this.eventListeners.push(() =>\n window.removeEventListener(\"hashchange\", handler)\n );\n } else {\n window.addEventListener(\"popstate\", handler);\n this.eventListeners.push(() =>\n window.removeEventListener(\"popstate\", handler)\n );\n }\n this.isStarted = true;\n await this._handleRouteChange();\n }\n\n /**\n * Stops the router and cleans up all event listeners and mounted components.\n * @returns {Promise<void>}\n */\n async destroy() {\n if (!this.isStarted) return;\n\n // Clean up plugins\n for (const plugin of this.plugins.values()) {\n if (typeof plugin.destroy === \"function\") {\n try {\n await plugin.destroy(this);\n } catch (error) {\n this.errorHandler.log(`Plugin ${plugin.name} destroy failed`, error);\n }\n }\n }\n\n this.eventListeners.forEach((cleanup) => cleanup());\n this.eventListeners = [];\n if (this.currentLayout.value) {\n await this.currentLayout.value.unmount();\n }\n this.isStarted = false;\n }\n\n /**\n * Programmatically navigates to a new route.\n * @param {string | {path: string, query?: object, params?: object, replace?: boolean, state?: object}} location - The target location as a string or object.\n * @param {object} [params] - Optional route parameters (for string-based location).\n * @returns {Promise<void>}\n */\n async navigate(location, params = {}) {\n try {\n const target =\n typeof location === \"string\" ? { path: location, params } : location;\n let path = this._buildPath(target.path, target.params || {});\n const query = target.query || {};\n\n if (Object.keys(query).length > 0) {\n const queryString = new URLSearchParams(query).toString();\n if (queryString) path += `?${queryString}`;\n }\n\n if (this._isSameRoute(path, target.params, query)) {\n return;\n }\n\n const navigationSuccessful = await this._proceedWithNavigation(path);\n\n if (navigationSuccessful) {\n this._isNavigating = true;\n const state = target.state || {};\n const replace = target.replace || false;\n const historyMethod = replace ? \"replaceState\" : \"pushState\";\n\n if (this.options.mode === \"hash\") {\n if (replace) {\n const newUrl = `${window.location.pathname}${window.location.search}#${path}`;\n window.history.replaceState(state, \"\", newUrl);\n } else {\n window.location.hash = path;\n }\n } else {\n const url =\n this.options.mode === \"query\" ? this._buildQueryUrl(path) : path;\n history[historyMethod](state, \"\", url);\n }\n queueMicrotask(() => {\n this._isNavigating = false;\n });\n }\n } catch (error) {\n this.errorHandler.log(\"Navigation failed\", error);\n await this.emitter.emit(\"router:onError\", error);\n }\n }\n\n /**\n * Builds a URL for query mode.\n * @private\n * @param {string} path - The path to set as the query parameter.\n * @returns {string} The full URL with the updated query string.\n */\n _buildQueryUrl(path) {\n const urlParams = new URLSearchParams(window.location.search);\n urlParams.set(this.options.queryParam, path.split(\"?\")[0]);\n return `${window.location.pathname}?${urlParams.toString()}`;\n }\n\n /**\n * Checks if the target route is identical to the current route.\n * @private\n * @param {string} path - The target path with query string.\n * @param {object} params - The target params.\n * @param {object} query - The target query.\n * @returns {boolean} - True if the routes are the same.\n */\n _isSameRoute(path, params, query) {\n const current = this.currentRoute.value;\n if (!current) return false;\n const [targetPath, queryString] = path.split(\"?\");\n const targetQuery = query || this._parseQuery(queryString || \"\");\n return (\n current.path === targetPath &&\n JSON.stringify(current.params) === JSON.stringify(params || {}) &&\n JSON.stringify(current.query) === JSON.stringify(targetQuery)\n );\n }\n\n /**\n * Injects dynamic parameters into a path string.\n * @private\n */\n _buildPath(path, params) {\n let result = path;\n for (const [key, value] of Object.entries(params)) {\n // Fix: Handle special characters and ensure proper encoding\n const encodedValue = encodeURIComponent(String(value));\n result = result.replace(new RegExp(`:${key}\\\\b`, \"g\"), encodedValue);\n }\n return result;\n }\n\n /**\n * The handler for browser-initiated route changes (e.g., back/forward buttons).\n * @private\n */\n async _handleRouteChange() {\n if (this._isNavigating) return;\n const from = this.currentRoute.value;\n const toLocation = this._getCurrentLocation();\n\n const navigationSuccessful = await this._proceedWithNavigation(\n toLocation.fullUrl\n );\n\n // If navigation was blocked by a guard, revert the URL change\n if (!navigationSuccessful && from) {\n this.navigate({ path: from.path, query: from.query, replace: true });\n }\n }\n\n /**\n * Manages the core navigation lifecycle. Runs guards before committing changes.\n * @private\n * @param {string} fullPath - The full path (e.g., '/users/123?foo=bar') to navigate to.\n * @returns {Promise<boolean>} - `true` if navigation succeeded, `false` if aborted.\n */\n async _proceedWithNavigation(fullPath) {\n const from = this.currentRoute.value;\n const [path, queryString] = (fullPath || \"/\").split(\"?\");\n const toLocation = {\n path: path.startsWith(\"/\") ? path : `/${path}`,\n query: this._parseQuery(queryString),\n fullUrl: fullPath,\n };\n\n let toMatch = this._matchRoute(toLocation.path);\n\n if (!toMatch) {\n const notFoundRoute = this.routes.find((route) => route.path === \"*\");\n if (notFoundRoute) {\n toMatch = {\n route: notFoundRoute,\n params: { pathMatch: toLocation.path.substring(1) },\n };\n } else {\n await this.emitter.emit(\n \"router:onError\",\n new Error(`Route not found: ${toLocation.path}`),\n toLocation,\n from\n );\n return false;\n }\n }\n\n const to = {\n ...toLocation,\n params: toMatch.params,\n meta: toMatch.route.meta || {},\n name: toMatch.route.name,\n matched: toMatch.route,\n };\n\n try {\n // 1. Run all *pre-navigation* guards.\n const canNavigate = await this._runGuards(to, from, toMatch.route);\n if (!canNavigate) return false;\n\n // 2. Resolve async components *before* touching the DOM.\n const { layoutComponent, pageComponent } = await this._resolveComponents(\n toMatch.route\n );\n\n // 3. Unmount the previous view/layout.\n if (from) {\n const toLayout = toMatch.route.layout || this.options.globalLayout;\n const fromLayout = from.matched.layout || this.options.globalLayout;\n\n const tryUnmount = async (instance) => {\n if (!instance) return;\n\n try {\n await instance.unmount();\n } catch (error) {\n this.errorHandler.warn(\"Error during component unmount\", {\n error,\n instance,\n });\n }\n };\n\n if (toLayout !== fromLayout) {\n await tryUnmount(this.currentLayout.value);\n this.currentLayout.value = null;\n } else {\n await tryUnmount(this.currentView.value);\n this.currentView.value = null;\n }\n\n // 4. Call `afterLeave` hook *after* the old component has been unmounted.\n if (from.matched.afterLeave) {\n await from.matched.afterLeave(to, from);\n await this.emitter.emit(\"router:afterLeave\", to, from);\n }\n }\n\n // 5. Update reactive state.\n this.previousRoute.value = from;\n this.currentRoute.value = to;\n this.currentParams.value = to.params || {};\n this.currentQuery.value = to.query || {};\n\n // 6. Render the new components.\n await this._render(layoutComponent, pageComponent, to);\n\n // 7. Run post-navigation hooks.\n if (toMatch.route.afterEnter) {\n await toMatch.route.afterEnter(to, from);\n await this.emitter.emit(\"router:afterEnter\", to, from);\n }\n await this.emitter.emit(\"router:afterEach\", to, from);\n\n return true;\n } catch (error) {\n this.errorHandler.log(\"Error during navigation\", error, { to, from });\n await this.emitter.emit(\"router:onError\", error, to, from);\n return false;\n }\n }\n\n /**\n * Executes all applicable navigation guards for a transition in order.\n * @private\n * @returns {Promise<boolean>} - `false` if navigation should be aborted.\n */\n async _runGuards(to, from, route) {\n const guards = [\n ...(this.options.onBeforeEach ? [this.options.onBeforeEach] : []),\n ...(from && from.matched.beforeLeave ? [from.matched.beforeLeave] : []),\n ...(route.beforeEnter ? [route.beforeEnter] : []),\n ];\n for (const guard of guards) {\n const result = await guard(to, from);\n if (result === false) return false;\n if (typeof result === \"string\" || typeof result === \"object\") {\n this.navigate(result);\n return false;\n }\n }\n return true;\n }\n\n /**\n * Resolves a string component definition to a component object.\n * @private\n * @param {string} def - The component name to resolve.\n * @returns {ComponentDefinition} The resolved component.\n * @throws {Error} If the component is not registered.\n */\n _resolveStringComponent(def) {\n const componentDef = this.eleva._components.get(def);\n if (!componentDef) {\n this.errorHandler.handle(\n new Error(`Component \"${def}\" not registered.`),\n \"Component resolution failed\",\n {\n componentName: def,\n availableComponents: Array.from(this.eleva._components.keys()),\n }\n );\n }\n return componentDef;\n }\n\n /**\n * Resolves a function component definition to a component object.\n * @private\n * @param {Function} def - The function to resolve.\n * @returns {Promise<ComponentDefinition>} The resolved component.\n * @throws {Error} If the function fails to load the component.\n */\n async _resolveFunctionComponent(def) {\n try {\n const funcStr = def.toString();\n const isAsyncImport =\n funcStr.includes(\"import(\") || funcStr.startsWith(\"() =>\");\n\n const result = await def();\n return isAsyncImport ? result.default || result : result;\n } catch (error) {\n this.errorHandler.handle(\n new Error(`Failed to load async component: ${error.message}`),\n \"Component resolution failed\",\n { function: def.toString(), error }\n );\n }\n }\n\n /**\n * Validates a component definition object.\n * @private\n * @param {any} def - The component definition to validate.\n * @returns {ComponentDefinition} The validated component.\n * @throws {Error} If the component definition is invalid.\n */\n _validateComponentDefinition(def) {\n if (!def || typeof def !== \"object\") {\n this.errorHandler.handle(\n new Error(`Invalid component definition: ${typeof def}`),\n \"Component validation failed\",\n { definition: def }\n );\n }\n\n if (\n typeof def.template !== \"function\" &&\n typeof def.template !== \"string\"\n ) {\n this.errorHandler.handle(\n new Error(\"Component missing template property\"),\n \"Component validation failed\",\n { definition: def }\n );\n }\n\n return def;\n }\n\n /**\n * Resolves a component definition to a component object.\n * @private\n * @param {any} def - The component definition to resolve.\n * @returns {Promise<ComponentDefinition | null>} The resolved component or null.\n */\n async _resolveComponent(def) {\n if (def === null || def === undefined) {\n return null;\n }\n\n if (typeof def === \"string\") {\n return this._resolveStringComponent(def);\n }\n\n if (typeof def === \"function\") {\n return await this._resolveFunctionComponent(def);\n }\n\n if (def && typeof def === \"object\") {\n return this._validateComponentDefinition(def);\n }\n\n this.errorHandler.handle(\n new Error(`Invalid component definition: ${typeof def}`),\n \"Component resolution failed\",\n { definition: def }\n );\n }\n\n /**\n * Asynchronously resolves the layout and page components for a route.\n * @private\n * @param {RouteDefinition} route - The route to resolve components for.\n * @returns {Promise<{layoutComponent: ComponentDefinition | null, pageComponent: ComponentDefinition}>}\n */\n async _resolveComponents(route) {\n const effectiveLayout = route.layout || this.options.globalLayout;\n\n try {\n const [layoutComponent, pageComponent] = await Promise.all([\n this._resolveComponent(effectiveLayout),\n this._resolveComponent(route.component),\n ]);\n\n if (!pageComponent) {\n this.errorHandler.handle(\n new Error(\n `Page component is null or undefined for route: ${route.path}`\n ),\n \"Component resolution failed\",\n { route: route.path }\n );\n }\n\n return { layoutComponent, pageComponent };\n } catch (error) {\n this.errorHandler.log(\n `Error resolving components for route ${route.path}`,\n error,\n { route: route.path }\n );\n throw error;\n }\n }\n\n /**\n * Renders the components for the current route into the DOM.\n * @private\n * @param {ComponentDefinition | null} layoutComponent - The pre-loaded layout component.\n * @param {ComponentDefinition} pageComponent - The pre-loaded page component.\n */\n async _render(layoutComponent, pageComponent) {\n const mountEl = document.querySelector(this.options.mount);\n if (!mountEl) {\n this.errorHandler.handle(\n new Error(`Mount element \"${this.options.mount}\" not found.`),\n { mountSelector: this.options.mount }\n );\n }\n\n if (layoutComponent) {\n const layoutInstance = await this.eleva.mount(\n mountEl,\n this._wrapComponentWithChildren(layoutComponent)\n );\n this.currentLayout.value = layoutInstance;\n const viewEl = this._findViewElement(layoutInstance.container);\n const viewInstance = await this.eleva.mount(\n viewEl,\n this._wrapComponentWithChildren(pageComponent)\n );\n this.currentView.value = viewInstance;\n } else {\n const viewInstance = await this.eleva.mount(\n mountEl,\n this._wrapComponentWithChildren(pageComponent)\n );\n this.currentView.value = viewInstance;\n this.currentLayout.value = null;\n }\n }\n\n /**\n * Creates a getter function for router context properties.\n * @private\n * @param {string} property - The property name to access.\n * @param {any} defaultValue - The default value if property is undefined.\n * @returns {Function} A getter function.\n */\n _createRouteGetter(property, defaultValue) {\n return () => this.currentRoute.value?.[property] ?? defaultValue;\n }\n\n /**\n * Wraps a component definition to inject router-specific context into its setup function.\n * @private\n * @param {ComponentDefinition} component - The component to wrap.\n * @returns {ComponentDefinition} The wrapped component definition.\n */\n _wrapComponent(component) {\n const originalSetup = component.setup;\n const self = this;\n\n return {\n ...component,\n async setup(ctx) {\n ctx.router = {\n navigate: self.navigate.bind(self),\n current: self.currentRoute,\n previous: self.previousRoute,\n\n // Route property getters\n get params() {\n return self._createRouteGetter(\"params\", {})();\n },\n get query() {\n return self._createRouteGetter(\"query\", {})();\n },\n get path() {\n return self._createRouteGetter(\"path\", \"/\")();\n },\n get fullUrl() {\n return self._createRouteGetter(\"fullUrl\", window.location.href)();\n },\n get meta() {\n return self._createRouteGetter(\"meta\", {})();\n },\n };\n\n return originalSetup ? await originalSetup(ctx) : {};\n },\n };\n }\n\n /**\n * Recursively wraps all child components to ensure they have access to router context.\n * @private\n * @param {ComponentDefinition} component - The component to wrap.\n * @returns {ComponentDefinition} The wrapped component definition.\n */\n _wrapComponentWithChildren(component) {\n const wrappedComponent = this._wrapComponent(component);\n\n // If the component has children, wrap them too\n if (\n wrappedComponent.children &&\n typeof wrappedComponent.children === \"object\"\n ) {\n const wrappedChildren = {};\n for (const [selector, childComponent] of Object.entries(\n wrappedComponent.children\n )) {\n wrappedChildren[selector] =\n this._wrapComponentWithChildren(childComponent);\n }\n wrappedComponent.children = wrappedChildren;\n }\n\n return wrappedComponent;\n }\n\n /**\n * Gets the current location information from the browser's window object.\n * @private\n * @returns {Omit<RouteLocation, 'params' | 'meta' | 'name' | 'matched'>}\n */\n _getCurrentLocation() {\n if (typeof window === \"undefined\")\n return { path: \"/\", query: {}, fullUrl: \"\" };\n let path, queryString, fullUrl;\n switch (this.options.mode) {\n case \"hash\":\n fullUrl = window.location.hash.slice(1) || \"/\";\n [path, queryString] = fullUrl.split(\"?\");\n break;\n case \"query\":\n const urlParams = new URLSearchParams(window.location.search);\n path = urlParams.get(this.options.queryParam) || \"/\";\n queryString = window.location.search.slice(1);\n fullUrl = path;\n break;\n default: // 'history' mode\n path = window.location.pathname || \"/\";\n queryString = window.location.search.slice(1);\n fullUrl = `${path}${queryString ? \"?\" + queryString : \"\"}`;\n }\n return {\n path: path.startsWith(\"/\") ? path : `/${path}`,\n query: this._parseQuery(queryString),\n fullUrl,\n };\n }\n\n /**\n * Parses a query string into a key-value object.\n * @private\n */\n _parseQuery(queryString) {\n const query = {};\n if (queryString) {\n new URLSearchParams(queryString).forEach((value, key) => {\n query[key] = value;\n });\n }\n return query;\n }\n\n /**\n * Matches a given path against the registered routes.\n * @private\n * @param {string} path - The path to match.\n * @returns {{route: RouteDefinition, params: Object<string, string>} | null} The matched route and its params, or null.\n */\n _matchRoute(path) {\n const pathSegments = path.split(\"/\").filter(Boolean);\n\n for (const route of this.routes) {\n // Handle the root path as a special case.\n if (route.path === \"/\") {\n if (pathSegments.length === 0) return { route, params: {} };\n continue;\n }\n\n if (route.segments.length !== pathSegments.length) continue;\n\n const params = {};\n let isMatch = true;\n for (let i = 0; i < route.segments.length; i++) {\n const routeSegment = route.segments[i];\n const pathSegment = pathSegments[i];\n if (routeSegment.type === \"param\") {\n params[routeSegment.name] = decodeURIComponent(pathSegment);\n } else if (routeSegment.value !== pathSegment) {\n isMatch = false;\n break;\n }\n }\n if (isMatch) return { route, params };\n }\n return null;\n }\n\n /** Registers a global pre-navigation guard. */\n onBeforeEach(guard) {\n this.options.onBeforeEach = guard;\n }\n /** Registers a global hook that runs after a new route component has been mounted *if* the route has an `afterEnter` hook. */\n onAfterEnter(hook) {\n this.emitter.on(\"router:afterEnter\", hook);\n }\n /** Registers a global hook that runs after a route component has been unmounted *if* the route has an `afterLeave` hook. */\n onAfterLeave(hook) {\n this.emitter.on(\"router:afterLeave\", hook);\n }\n /** Registers a global hook that runs after a navigation has been confirmed and all hooks have completed. */\n onAfterEach(hook) {\n this.emitter.on(\"router:afterEach\", hook);\n }\n /** Registers a global error handler for navigation. */\n onError(handler) {\n this.emitter.on(\"router:onError\", handler);\n }\n\n /**\n * Registers a plugin with the router.\n * @param {RouterPlugin} plugin - The plugin to register.\n */\n use(plugin, options = {}) {\n if (typeof plugin.install !== \"function\") {\n this.errorHandler.handle(\n new Error(\"Plugin must have an install method\"),\n \"Plugin registration failed\",\n { plugin }\n );\n }\n\n // Check if plugin is already registered\n if (this.plugins.has(plugin.name)) {\n this.errorHandler.warn(`Plugin \"${plugin.name}\" is already registered`, {\n existingPlugin: this.plugins.get(plugin.name),\n });\n return;\n }\n\n this.plugins.set(plugin.name, plugin);\n plugin.install(this, options);\n }\n\n /**\n * Gets all registered plugins.\n * @returns {RouterPlugin[]} Array of registered plugins.\n */\n getPlugins() {\n return Array.from(this.plugins.values());\n }\n\n /**\n * Gets a plugin by name.\n * @param {string} name - The plugin name.\n * @returns {RouterPlugin | undefined} The plugin or undefined.\n */\n getPlugin(name) {\n return this.plugins.get(name);\n }\n\n /**\n * Removes a plugin from the router.\n * @param {string} name - The plugin name.\n * @returns {boolean} True if the plugin was removed.\n */\n removePlugin(name) {\n const plugin = this.plugins.get(name);\n if (!plugin) return false;\n\n // Call destroy if available\n if (typeof plugin.destroy === \"function\") {\n try {\n plugin.destroy(this);\n } catch (error) {\n this.errorHandler.log(`Plugin ${name} destroy failed`, error);\n }\n }\n\n return this.plugins.delete(name);\n }\n\n /**\n * Sets a custom error handler. Used by error handling plugins.\n * @param {Object} errorHandler - The error handler object with handle, warn, and log methods.\n */\n setErrorHandler(errorHandler) {\n if (\n errorHandler &&\n typeof errorHandler.handle === \"function\" &&\n typeof errorHandler.warn === \"function\" &&\n typeof errorHandler.log === \"function\"\n ) {\n this.errorHandler = errorHandler;\n } else {\n console.warn(\n \"[ElevaRouter] Invalid error handler provided. Must have handle, warn, and log methods.\"\n );\n }\n }\n}\n\n/**\n * @typedef {Object} RouterOptions\n * @property {string} mount - A CSS selector for the main element where the app is mounted.\n * @property {RouteDefinition[]} routes - An array of route definitions.\n * @property {'hash' | 'query' | 'history'} [mode='hash'] - The routing mode.\n * @property {string} [queryParam='page'] - The query parameter to use in 'query' mode.\n * @property {string} [viewSelector='view'] - The selector for the view element within a layout.\n * @property {boolean} [autoStart=true] - Whether to start the router automatically.\n * @property {NavigationGuard} [onBeforeEach] - A global guard executed before every navigation.\n * @property {string | ComponentDefinition | (() => Promise<{default: ComponentDefinition}>)} [globalLayout] - A global layout for all routes. Can be overridden by a route's specific layout.\n */\n\n/**\n * @class 🚀 RouterPlugin\n * @classdesc A powerful, reactive, and flexible Router Plugin for Eleva.js applications.\n * This plugin provides comprehensive client-side routing functionality including:\n * - Multiple routing modes (hash, history, query)\n * - Navigation guards and lifecycle hooks\n * - Reactive state management\n * - Component resolution and lazy loading\n * - Layout and page component separation\n * - Plugin system for extensibility\n * - Advanced error handling\n *\n * @example\n * // Install the plugin\n * const app = new Eleva(\"myApp\");\n *\n * const HomePage = { template: () => `<h1>Home</h1>` };\n * const AboutPage = { template: () => `<h1>About Us</h1>` };\n * const UserPage = {\n * template: (ctx) => `<h1>User: ${ctx.router.params.id}</h1>`\n * };\n *\n * app.use(RouterPlugin, {\n * mount: '#app',\n * mode: 'hash',\n * routes: [\n * { path: '/', component: HomePage },\n * { path: '/about', component: AboutPage },\n * { path: '/users/:id', component: UserPage }\n * ]\n * });\n */\nexport const RouterPlugin = {\n /**\n * Unique identifier for the plugin\n * @type {string}\n */\n name: \"router\",\n\n /**\n * Plugin version\n * @type {string}\n */\n version: \"1.0.0-rc.1\",\n\n /**\n * Plugin description\n * @type {string}\n */\n description: \"Client-side routing for Eleva applications\",\n\n /**\n * Installs the RouterPlugin into an Eleva instance.\n *\n * @param {Eleva} eleva - The Eleva instance\n * @param {RouterOptions} options - Router configuration options\n * @param {string} options.mount - A CSS selector for the main element where the app is mounted\n * @param {RouteDefinition[]} options.routes - An array of route definitions\n * @param {'hash' | 'query' | 'history'} [options.mode='hash'] - The routing mode\n * @param {string} [options.queryParam='page'] - The query parameter to use in 'query' mode\n * @param {string} [options.viewSelector='view'] - The selector for the view element within a layout\n * @param {boolean} [options.autoStart=true] - Whether to start the router automatically\n * @param {NavigationGuard} [options.onBeforeEach] - A global guard executed before every navigation\n * @param {string | ComponentDefinition | (() => Promise<{default: ComponentDefinition}>)} [options.globalLayout] - A global layout for all routes\n *\n * @example\n * // main.js\n * import Eleva from './eleva.js';\n * import { RouterPlugin } from './plugins/RouterPlugin.js';\n *\n * const app = new Eleva('myApp');\n *\n * const HomePage = { template: () => `<h1>Home</h1>` };\n * const AboutPage = { template: () => `<h1>About Us</h1>` };\n *\n * app.use(RouterPlugin, {\n * mount: '#app',\n * routes: [\n * { path: '/', component: HomePage },\n * { path: '/about', component: AboutPage }\n * ]\n * });\n */\n install(eleva, options = {}) {\n if (!options.mount) {\n throw new Error(\"[RouterPlugin] 'mount' option is required\");\n }\n\n if (!options.routes || !Array.isArray(options.routes)) {\n throw new Error(\"[RouterPlugin] 'routes' option must be an array\");\n }\n\n /**\n * Registers a component definition with the Eleva instance.\n * This method handles both inline component objects and pre-registered component names.\n *\n * @param {any} def - The component definition to register\n * @param {string} type - The type of component for naming (e.g., \"Route\", \"Layout\")\n * @returns {string | null} The registered component name or null if no definition provided\n */\n const register = (def, type) => {\n if (!def) return null;\n\n if (typeof def === \"object\" && def !== null && !def.name) {\n const name = `Eleva${type}Component_${Math.random()\n .toString(36)\n .slice(2, 11)}`;\n\n try {\n eleva.component(name, def);\n return name;\n } catch (error) {\n throw new Error(\n `[RouterPlugin] Failed to register ${type} component: ${error.message}`\n );\n }\n }\n return def;\n };\n\n if (options.globalLayout) {\n options.globalLayout = register(options.globalLayout, \"GlobalLayout\");\n }\n\n (options.routes || []).forEach((route) => {\n route.component = register(route.component, \"Route\");\n if (route.layout) {\n route.layout = register(route.layout, \"RouteLayout\");\n }\n });\n\n const router = new Router(eleva, options);\n eleva.router = router;\n\n if (options.autoStart !== false) {\n queueMicrotask(() => router.start());\n }\n\n // Add plugin metadata to the Eleva instance\n if (!eleva.plugins) {\n eleva.plugins = new Map();\n }\n eleva.plugins.set(this.name, {\n name: this.name,\n version: this.version,\n description: this.description,\n options,\n });\n\n // Add utility methods for manual router access\n eleva.navigate = router.navigate.bind(router);\n eleva.getCurrentRoute = () => router.currentRoute.value;\n eleva.getRouteParams = () => router.currentParams.value;\n eleva.getRouteQuery = () => router.currentQuery.value;\n\n return router;\n },\n\n /**\n * Uninstalls the plugin from the Eleva instance\n *\n * @param {Eleva} eleva - The Eleva instance\n */\n async uninstall(eleva) {\n if (eleva.router) {\n await eleva.router.destroy();\n delete eleva.router;\n }\n\n // Remove plugin metadata\n if (eleva.plugins) {\n eleva.plugins.delete(this.name);\n }\n\n // Remove utility methods\n delete eleva.navigate;\n delete eleva.getCurrentRoute;\n delete eleva.getRouteParams;\n delete eleva.getRouteQuery;\n },\n};\n"],"names":["CoreErrorHandler","handle","error","context","details","formattedError","Error","message","originalError","warn","log","Router","constructor","eleva","options","this","mode","queryParam","viewSelector","routes","_processRoutes","emitter","isStarted","_isNavigating","eventListeners","currentRoute","signal","previousRoute","currentParams","currentQuery","currentLayout","currentView","plugins","Map","errorHandler","_validateOptions","includes","processedRoutes","route","push","segments","_parsePathIntoSegments","path","normalizedPath","replace","split","filter","Boolean","map","segment","startsWith","paramName","substring","type","name","value","_findViewElement","container","selector","querySelector","start","window","document","mount","mountSelector","handler","_handleRouteChange","addEventListener","removeEventListener","destroy","plugin","values","forEach","cleanup","unmount","navigate","location","params","target","_buildPath","query","Object","keys","length","queryString","URLSearchParams","toString","_isSameRoute","_proceedWithNavigation","state","historyMethod","newUrl","pathname","search","history","replaceState","hash","url","_buildQueryUrl","queueMicrotask","emit","urlParams","set","current","targetPath","targetQuery","_parseQuery","JSON","stringify","result","key","entries","encodedValue","encodeURIComponent","String","RegExp","from","toLocation","_getCurrentLocation","fullUrl","fullPath","toMatch","_matchRoute","notFoundRoute","find","pathMatch","to","meta","matched","_runGuards","layoutComponent","pageComponent","_resolveComponents","tryUnmount","async","instance","layout","globalLayout","afterLeave","_render","afterEnter","guards","onBeforeEach","beforeLeave","beforeEnter","guard","_resolveStringComponent","def","componentDef","_components","get","componentName","availableComponents","Array","_resolveFunctionComponent","funcStr","isAsyncImport","default","function","_validateComponentDefinition","definition","template","_resolveComponent","effectiveLayout","Promise","all","component","mountEl","layoutInstance","_wrapComponentWithChildren","viewEl","viewInstance","_createRouteGetter","property","defaultValue","_wrapComponent","originalSetup","setup","self","ctx","router","bind","previous","href","wrappedComponent","children","wrappedChildren","childComponent","slice","pathSegments","isMatch","i","routeSegment","pathSegment","decodeURIComponent","onAfterEnter","hook","on","onAfterLeave","onAfterEach","onError","use","install","has","existingPlugin","getPlugins","getPlugin","removePlugin","delete","setErrorHandler","version","description","isArray","register","Math","random","autoStart","getCurrentRoute","getRouteParams","getRouteQuery","uninstall"],"mappings":";0CAcA,MAAMA,EAAmB,CAQvBC,MAAAA,CAAOC,EAAOC,EAASC,EAAU,CAAA,GAC/B,MACMC,EAAiB,IAAIC,MADX,iBAAiBH,MAAYD,EAAMK,WASnD,MALAF,EAAeG,cAAgBN,EAC/BG,EAAe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,EAAM8M,aACf"}
|
|
1
|
+
{"version":3,"file":"router.umd.min.js","sources":["../../src/plugins/Router.js"],"sourcesContent":["\"use strict\";\n\n/**\n * @typedef {import('eleva').Eleva} Eleva\n * @typedef {import('eleva').Signal} Signal\n * @typedef {import('eleva').ComponentDefinition} ComponentDefinition\n */\n\n/**\n * Simple error handler for the core router.\n * Can be overridden by error handling plugins.\n * Provides consistent error formatting and logging for router operations.\n * @private\n */\nconst CoreErrorHandler = {\n /**\n * Handles router errors with basic formatting.\n * @param {Error} error - The error to handle.\n * @param {string} context - The context where the error occurred.\n * @param {Object} details - Additional error details.\n * @throws {Error} The formatted error.\n */\n handle(error, context, details = {}) {\n const message = `[ElevaRouter] ${context}: ${error.message}`;\n const formattedError = new Error(message);\n\n // Preserve original error details\n formattedError.originalError = error;\n formattedError.context = context;\n formattedError.details = details;\n\n console.error(message, { error, context, details });\n throw formattedError;\n },\n\n /**\n * Logs a warning without throwing an error.\n * @param {string} message - The warning message.\n * @param {Object} details - Additional warning details.\n */\n warn(message, details = {}) {\n console.warn(`[ElevaRouter] ${message}`, details);\n },\n\n /**\n * Logs an error without throwing.\n * @param {string} message - The error message.\n * @param {Error} error - The original error.\n * @param {Object} details - Additional error details.\n */\n log(message, error, details = {}) {\n console.error(`[ElevaRouter] ${message}`, { error, details });\n },\n};\n\n/**\n * @typedef {Object} RouteLocation\n * @property {string} path - The path of the route (e.g., '/users/123').\n * @property {Object<string, string>} query - An object representing the query parameters.\n * @property {string} fullUrl - The complete URL including hash, path, and query string.\n * @property {Object<string, string>} params - An object containing dynamic route parameters.\n * @property {Object<string, any>} meta - The meta object associated with the matched route.\n * @property {string} [name] - The optional name of the matched route.\n * @property {RouteDefinition} matched - The raw route definition object that was matched.\n */\n\n/**\n * @typedef {(to: RouteLocation, from: RouteLocation | null) => boolean | string | {path: string} | void | Promise<boolean | string | {path: string} | void>} NavigationGuard\n * A function that acts as a guard for navigation. It runs *before* the navigation is confirmed.\n * It can return:\n * - `true` or `undefined`: to allow navigation.\n * - `false`: to abort the navigation.\n * - a `string` (path) or a `location object`: to redirect to a new route.\n */\n\n/**\n * @typedef {(...args: any[]) => void | Promise<void>} NavigationHook\n * A function that acts as a lifecycle hook, typically for side effects. It does not affect navigation flow.\n */\n\n/**\n * @typedef {Object} RouterPlugin\n * @property {string} name - The plugin name.\n * @property {string} [version] - The plugin version.\n * @property {Function} install - The install function that receives the router instance.\n * @property {Function} [destroy] - Optional cleanup function called when the router is destroyed.\n */\n\n/**\n * @typedef {Object} RouteDefinition\n * @property {string} path - The URL path pattern (e.g., '/', '/about', '/users/:id', '*').\n * @property {string | ComponentDefinition | (() => Promise<{default: ComponentDefinition}>)} component - The component to render. Can be a registered name, a definition object, or an async import function.\n * @property {string | ComponentDefinition | (() => Promise<{default: ComponentDefinition}>)} [layout] - An optional layout component to wrap the route's component.\n * @property {string} [name] - An optional name for the route.\n * @property {Object<string, any>} [meta] - Optional metadata for the route (e.g., for titles, auth flags).\n * @property {NavigationGuard} [beforeEnter] - A route-specific guard executed before entering the route.\n * @property {NavigationHook} [afterEnter] - A hook executed *after* the route has been entered and the new component is mounted.\n * @property {NavigationGuard} [beforeLeave] - A guard executed *before* leaving the current route.\n * @property {NavigationHook} [afterLeave] - A hook executed *after* leaving the current route and its component has been unmounted.\n */\n\n/**\n * @class Router\n * @classdesc A powerful, reactive, and flexible Router Plugin for Eleva.js.\n * This class manages all routing logic, including state, navigation, and rendering.\n * @private\n */\nclass Router {\n /**\n * Creates an instance of the Router.\n * @param {Eleva} eleva - The Eleva framework instance.\n * @param {RouterOptions} options - The configuration options for the router.\n */\n constructor(eleva, options = {}) {\n /** @type {Eleva} The Eleva framework instance. */\n this.eleva = eleva;\n\n /** @type {RouterOptions} The merged router options. */\n this.options = {\n mode: \"hash\",\n queryParam: \"view\",\n viewSelector: \"root\",\n ...options,\n };\n\n /** @private @type {RouteDefinition[]} The processed list of route definitions. */\n this.routes = this._processRoutes(options.routes || []);\n\n /** @private @type {import('eleva').Emitter} The shared Eleva event emitter for global hooks. */\n this.emitter = this.eleva.emitter;\n\n /** @private @type {boolean} A flag indicating if the router has been started. */\n this.isStarted = false;\n\n /** @private @type {boolean} A flag to prevent navigation loops from history events. */\n this._isNavigating = false;\n\n /** @private @type {Array<() => void>} A collection of cleanup functions for event listeners. */\n this.eventListeners = [];\n\n /** @type {Signal<RouteLocation | null>} A reactive signal holding the current route's information. */\n this.currentRoute = new this.eleva.signal(null);\n\n /** @type {Signal<RouteLocation | null>} A reactive signal holding the previous route's information. */\n this.previousRoute = new this.eleva.signal(null);\n\n /** @type {Signal<Object<string, string>>} A reactive signal holding the current route's parameters. */\n this.currentParams = new this.eleva.signal({});\n\n /** @type {Signal<Object<string, string>>} A reactive signal holding the current route's query parameters. */\n this.currentQuery = new this.eleva.signal({});\n\n /** @type {Signal<import('eleva').MountResult | null>} A reactive signal for the currently mounted layout instance. */\n this.currentLayout = new this.eleva.signal(null);\n\n /** @type {Signal<import('eleva').MountResult | null>} A reactive signal for the currently mounted view (page) instance. */\n this.currentView = new this.eleva.signal(null);\n\n /** @private @type {Map<string, RouterPlugin>} Map of registered plugins by name. */\n this.plugins = new Map();\n\n /** @type {Object} The error handler instance. Can be overridden by plugins. */\n this.errorHandler = CoreErrorHandler;\n\n this._validateOptions();\n }\n\n /**\n * Validates the provided router options.\n * @private\n * @throws {Error} If the routing mode is invalid.\n */\n _validateOptions() {\n if (![\"hash\", \"query\", \"history\"].includes(this.options.mode)) {\n this.errorHandler.handle(\n new Error(\n `Invalid routing mode: ${this.options.mode}. Must be \"hash\", \"query\", or \"history\".`\n ),\n \"Configuration validation failed\"\n );\n }\n }\n\n /**\n * Pre-processes route definitions to parse their path segments for efficient matching.\n * @private\n * @param {RouteDefinition[]} routes - The raw route definitions.\n * @returns {RouteDefinition[]} The processed routes.\n */\n _processRoutes(routes) {\n const processedRoutes = [];\n for (const route of routes) {\n try {\n processedRoutes.push({\n ...route,\n segments: this._parsePathIntoSegments(route.path),\n });\n } catch (error) {\n this.errorHandler.warn(\n `Invalid path in route definition \"${route.path || \"undefined\"}\": ${error.message}`,\n { route, error }\n );\n }\n }\n return processedRoutes;\n }\n\n /**\n * Parses a route path string into an array of static and parameter segments.\n * @private\n * @param {string} path - The path pattern to parse.\n * @returns {Array<{type: 'static' | 'param', value?: string, name?: string}>} An array of segment objects.\n * @throws {Error} If the route path is not a valid string.\n */\n _parsePathIntoSegments(path) {\n if (!path || typeof path !== \"string\") {\n this.errorHandler.handle(\n new Error(\"Route path must be a non-empty string\"),\n \"Path parsing failed\",\n { path }\n );\n }\n\n const normalizedPath = path.replace(/\\/+/g, \"/\").replace(/\\/$/, \"\") || \"/\";\n\n if (normalizedPath === \"/\") {\n return [];\n }\n\n return normalizedPath\n .split(\"/\")\n .filter(Boolean)\n .map((segment) => {\n if (segment.startsWith(\":\")) {\n const paramName = segment.substring(1);\n if (!paramName) {\n this.errorHandler.handle(\n new Error(`Invalid parameter segment: ${segment}`),\n \"Path parsing failed\",\n { segment, path }\n );\n }\n return { type: \"param\", name: paramName };\n }\n return { type: \"static\", value: segment };\n });\n }\n\n /**\n * Finds the view element within a container using multiple selector strategies.\n * @private\n * @param {HTMLElement} container - The parent element to search within.\n * @returns {HTMLElement} The found view element or the container itself as a fallback.\n */\n _findViewElement(container) {\n const selector = this.options.viewSelector;\n return (\n container.querySelector(`#${selector}`) ||\n container.querySelector(`.${selector}`) ||\n container.querySelector(`[data-${selector}]`) ||\n container.querySelector(selector) ||\n container\n );\n }\n\n /**\n * Starts the router, initializes event listeners, and performs the initial navigation.\n * @returns {Promise<void>}\n */\n async start() {\n if (this.isStarted) {\n this.errorHandler.warn(\"Router is already started\");\n return;\n }\n if (typeof window === \"undefined\") {\n this.errorHandler.warn(\n \"Router start skipped: `window` object not available (SSR environment)\"\n );\n return;\n }\n if (\n typeof document !== \"undefined\" &&\n !document.querySelector(this.options.mount)\n ) {\n this.errorHandler.warn(\n `Mount element \"${this.options.mount}\" was not found in the DOM. The router will not start.`,\n { mountSelector: this.options.mount }\n );\n return;\n }\n const handler = () => this._handleRouteChange();\n if (this.options.mode === \"hash\") {\n window.addEventListener(\"hashchange\", handler);\n this.eventListeners.push(() =>\n window.removeEventListener(\"hashchange\", handler)\n );\n } else {\n window.addEventListener(\"popstate\", handler);\n this.eventListeners.push(() =>\n window.removeEventListener(\"popstate\", handler)\n );\n }\n this.isStarted = true;\n await this._handleRouteChange();\n }\n\n /**\n * Stops the router and cleans up all event listeners and mounted components.\n * @returns {Promise<void>}\n */\n async destroy() {\n if (!this.isStarted) return;\n\n // Clean up plugins\n for (const plugin of this.plugins.values()) {\n if (typeof plugin.destroy === \"function\") {\n try {\n await plugin.destroy(this);\n } catch (error) {\n this.errorHandler.log(`Plugin ${plugin.name} destroy failed`, error);\n }\n }\n }\n\n this.eventListeners.forEach((cleanup) => cleanup());\n this.eventListeners = [];\n if (this.currentLayout.value) {\n await this.currentLayout.value.unmount();\n }\n this.isStarted = false;\n }\n\n /**\n * Programmatically navigates to a new route.\n * @param {string | {path: string, query?: object, params?: object, replace?: boolean, state?: object}} location - The target location as a string or object.\n * @param {object} [params] - Optional route parameters (for string-based location).\n * @returns {Promise<void>}\n */\n async navigate(location, params = {}) {\n try {\n const target =\n typeof location === \"string\" ? { path: location, params } : location;\n let path = this._buildPath(target.path, target.params || {});\n const query = target.query || {};\n\n if (Object.keys(query).length > 0) {\n const queryString = new URLSearchParams(query).toString();\n if (queryString) path += `?${queryString}`;\n }\n\n if (this._isSameRoute(path, target.params, query)) {\n return;\n }\n\n const navigationSuccessful = await this._proceedWithNavigation(path);\n\n if (navigationSuccessful) {\n this._isNavigating = true;\n const state = target.state || {};\n const replace = target.replace || false;\n const historyMethod = replace ? \"replaceState\" : \"pushState\";\n\n if (this.options.mode === \"hash\") {\n if (replace) {\n const newUrl = `${window.location.pathname}${window.location.search}#${path}`;\n window.history.replaceState(state, \"\", newUrl);\n } else {\n window.location.hash = path;\n }\n } else {\n const url =\n this.options.mode === \"query\" ? this._buildQueryUrl(path) : path;\n history[historyMethod](state, \"\", url);\n }\n queueMicrotask(() => {\n this._isNavigating = false;\n });\n }\n } catch (error) {\n this.errorHandler.log(\"Navigation failed\", error);\n await this.emitter.emit(\"router:onError\", error);\n }\n }\n\n /**\n * Builds a URL for query mode.\n * @private\n * @param {string} path - The path to set as the query parameter.\n * @returns {string} The full URL with the updated query string.\n */\n _buildQueryUrl(path) {\n const urlParams = new URLSearchParams(window.location.search);\n urlParams.set(this.options.queryParam, path.split(\"?\")[0]);\n return `${window.location.pathname}?${urlParams.toString()}`;\n }\n\n /**\n * Checks if the target route is identical to the current route.\n * @private\n * @param {string} path - The target path with query string.\n * @param {object} params - The target params.\n * @param {object} query - The target query.\n * @returns {boolean} - True if the routes are the same.\n */\n _isSameRoute(path, params, query) {\n const current = this.currentRoute.value;\n if (!current) return false;\n const [targetPath, queryString] = path.split(\"?\");\n const targetQuery = query || this._parseQuery(queryString || \"\");\n return (\n current.path === targetPath &&\n JSON.stringify(current.params) === JSON.stringify(params || {}) &&\n JSON.stringify(current.query) === JSON.stringify(targetQuery)\n );\n }\n\n /**\n * Injects dynamic parameters into a path string.\n * @private\n */\n _buildPath(path, params) {\n let result = path;\n for (const [key, value] of Object.entries(params)) {\n // Fix: Handle special characters and ensure proper encoding\n const encodedValue = encodeURIComponent(String(value));\n result = result.replace(new RegExp(`:${key}\\\\b`, \"g\"), encodedValue);\n }\n return result;\n }\n\n /**\n * The handler for browser-initiated route changes (e.g., back/forward buttons).\n * @private\n */\n async _handleRouteChange() {\n if (this._isNavigating) return;\n const from = this.currentRoute.value;\n const toLocation = this._getCurrentLocation();\n\n const navigationSuccessful = await this._proceedWithNavigation(\n toLocation.fullUrl\n );\n\n // If navigation was blocked by a guard, revert the URL change\n if (!navigationSuccessful && from) {\n this.navigate({ path: from.path, query: from.query, replace: true });\n }\n }\n\n /**\n * Manages the core navigation lifecycle. Runs guards before committing changes.\n * @private\n * @param {string} fullPath - The full path (e.g., '/users/123?foo=bar') to navigate to.\n * @returns {Promise<boolean>} - `true` if navigation succeeded, `false` if aborted.\n */\n async _proceedWithNavigation(fullPath) {\n const from = this.currentRoute.value;\n const [path, queryString] = (fullPath || \"/\").split(\"?\");\n const toLocation = {\n path: path.startsWith(\"/\") ? path : `/${path}`,\n query: this._parseQuery(queryString),\n fullUrl: fullPath,\n };\n\n let toMatch = this._matchRoute(toLocation.path);\n\n if (!toMatch) {\n const notFoundRoute = this.routes.find((route) => route.path === \"*\");\n if (notFoundRoute) {\n toMatch = {\n route: notFoundRoute,\n params: { pathMatch: toLocation.path.substring(1) },\n };\n } else {\n await this.emitter.emit(\n \"router:onError\",\n new Error(`Route not found: ${toLocation.path}`),\n toLocation,\n from\n );\n return false;\n }\n }\n\n const to = {\n ...toLocation,\n params: toMatch.params,\n meta: toMatch.route.meta || {},\n name: toMatch.route.name,\n matched: toMatch.route,\n };\n\n try {\n // 1. Run all *pre-navigation* guards.\n const canNavigate = await this._runGuards(to, from, toMatch.route);\n if (!canNavigate) return false;\n\n // 2. Resolve async components *before* touching the DOM.\n const { layoutComponent, pageComponent } = await this._resolveComponents(\n toMatch.route\n );\n\n // 3. Unmount the previous view/layout.\n if (from) {\n const toLayout = toMatch.route.layout || this.options.globalLayout;\n const fromLayout = from.matched.layout || this.options.globalLayout;\n\n const tryUnmount = async (instance) => {\n if (!instance) return;\n\n try {\n await instance.unmount();\n } catch (error) {\n this.errorHandler.warn(\"Error during component unmount\", {\n error,\n instance,\n });\n }\n };\n\n if (toLayout !== fromLayout) {\n await tryUnmount(this.currentLayout.value);\n this.currentLayout.value = null;\n } else {\n await tryUnmount(this.currentView.value);\n this.currentView.value = null;\n }\n\n // 4. Call `afterLeave` hook *after* the old component has been unmounted.\n if (from.matched.afterLeave) {\n await from.matched.afterLeave(to, from);\n await this.emitter.emit(\"router:afterLeave\", to, from);\n }\n }\n\n // 5. Update reactive state.\n this.previousRoute.value = from;\n this.currentRoute.value = to;\n this.currentParams.value = to.params || {};\n this.currentQuery.value = to.query || {};\n\n // 6. Render the new components.\n await this._render(layoutComponent, pageComponent, to);\n\n // 7. Run post-navigation hooks.\n if (toMatch.route.afterEnter) {\n await toMatch.route.afterEnter(to, from);\n await this.emitter.emit(\"router:afterEnter\", to, from);\n }\n await this.emitter.emit(\"router:afterEach\", to, from);\n\n return true;\n } catch (error) {\n this.errorHandler.log(\"Error during navigation\", error, { to, from });\n await this.emitter.emit(\"router:onError\", error, to, from);\n return false;\n }\n }\n\n /**\n * Executes all applicable navigation guards for a transition in order.\n * @private\n * @returns {Promise<boolean>} - `false` if navigation should be aborted.\n */\n async _runGuards(to, from, route) {\n const guards = [\n ...(this.options.onBeforeEach ? [this.options.onBeforeEach] : []),\n ...(from && from.matched.beforeLeave ? [from.matched.beforeLeave] : []),\n ...(route.beforeEnter ? [route.beforeEnter] : []),\n ];\n for (const guard of guards) {\n const result = await guard(to, from);\n if (result === false) return false;\n if (typeof result === \"string\" || typeof result === \"object\") {\n this.navigate(result);\n return false;\n }\n }\n return true;\n }\n\n /**\n * Resolves a string component definition to a component object.\n * @private\n * @param {string} def - The component name to resolve.\n * @returns {ComponentDefinition} The resolved component.\n * @throws {Error} If the component is not registered.\n */\n _resolveStringComponent(def) {\n const componentDef = this.eleva._components.get(def);\n if (!componentDef) {\n this.errorHandler.handle(\n new Error(`Component \"${def}\" not registered.`),\n \"Component resolution failed\",\n {\n componentName: def,\n availableComponents: Array.from(this.eleva._components.keys()),\n }\n );\n }\n return componentDef;\n }\n\n /**\n * Resolves a function component definition to a component object.\n * @private\n * @param {Function} def - The function to resolve.\n * @returns {Promise<ComponentDefinition>} The resolved component.\n * @throws {Error} If the function fails to load the component.\n */\n async _resolveFunctionComponent(def) {\n try {\n const funcStr = def.toString();\n const isAsyncImport =\n funcStr.includes(\"import(\") || funcStr.startsWith(\"() =>\");\n\n const result = await def();\n return isAsyncImport ? result.default || result : result;\n } catch (error) {\n this.errorHandler.handle(\n new Error(`Failed to load async component: ${error.message}`),\n \"Component resolution failed\",\n { function: def.toString(), error }\n );\n }\n }\n\n /**\n * Validates a component definition object.\n * @private\n * @param {any} def - The component definition to validate.\n * @returns {ComponentDefinition} The validated component.\n * @throws {Error} If the component definition is invalid.\n */\n _validateComponentDefinition(def) {\n if (!def || typeof def !== \"object\") {\n this.errorHandler.handle(\n new Error(`Invalid component definition: ${typeof def}`),\n \"Component validation failed\",\n { definition: def }\n );\n }\n\n if (\n typeof def.template !== \"function\" &&\n typeof def.template !== \"string\"\n ) {\n this.errorHandler.handle(\n new Error(\"Component missing template property\"),\n \"Component validation failed\",\n { definition: def }\n );\n }\n\n return def;\n }\n\n /**\n * Resolves a component definition to a component object.\n * @private\n * @param {any} def - The component definition to resolve.\n * @returns {Promise<ComponentDefinition | null>} The resolved component or null.\n */\n async _resolveComponent(def) {\n if (def === null || def === undefined) {\n return null;\n }\n\n if (typeof def === \"string\") {\n return this._resolveStringComponent(def);\n }\n\n if (typeof def === \"function\") {\n return await this._resolveFunctionComponent(def);\n }\n\n if (def && typeof def === \"object\") {\n return this._validateComponentDefinition(def);\n }\n\n this.errorHandler.handle(\n new Error(`Invalid component definition: ${typeof def}`),\n \"Component resolution failed\",\n { definition: def }\n );\n }\n\n /**\n * Asynchronously resolves the layout and page components for a route.\n * @private\n * @param {RouteDefinition} route - The route to resolve components for.\n * @returns {Promise<{layoutComponent: ComponentDefinition | null, pageComponent: ComponentDefinition}>}\n */\n async _resolveComponents(route) {\n const effectiveLayout = route.layout || this.options.globalLayout;\n\n try {\n const [layoutComponent, pageComponent] = await Promise.all([\n this._resolveComponent(effectiveLayout),\n this._resolveComponent(route.component),\n ]);\n\n if (!pageComponent) {\n this.errorHandler.handle(\n new Error(\n `Page component is null or undefined for route: ${route.path}`\n ),\n \"Component resolution failed\",\n { route: route.path }\n );\n }\n\n return { layoutComponent, pageComponent };\n } catch (error) {\n this.errorHandler.log(\n `Error resolving components for route ${route.path}`,\n error,\n { route: route.path }\n );\n throw error;\n }\n }\n\n /**\n * Renders the components for the current route into the DOM.\n * @private\n * @param {ComponentDefinition | null} layoutComponent - The pre-loaded layout component.\n * @param {ComponentDefinition} pageComponent - The pre-loaded page component.\n */\n async _render(layoutComponent, pageComponent) {\n const mountEl = document.querySelector(this.options.mount);\n if (!mountEl) {\n this.errorHandler.handle(\n new Error(`Mount element \"${this.options.mount}\" not found.`),\n { mountSelector: this.options.mount }\n );\n }\n\n if (layoutComponent) {\n const layoutInstance = await this.eleva.mount(\n mountEl,\n this._wrapComponentWithChildren(layoutComponent)\n );\n this.currentLayout.value = layoutInstance;\n const viewEl = this._findViewElement(layoutInstance.container);\n const viewInstance = await this.eleva.mount(\n viewEl,\n this._wrapComponentWithChildren(pageComponent)\n );\n this.currentView.value = viewInstance;\n } else {\n const viewInstance = await this.eleva.mount(\n mountEl,\n this._wrapComponentWithChildren(pageComponent)\n );\n this.currentView.value = viewInstance;\n this.currentLayout.value = null;\n }\n }\n\n /**\n * Creates a getter function for router context properties.\n * @private\n * @param {string} property - The property name to access.\n * @param {any} defaultValue - The default value if property is undefined.\n * @returns {Function} A getter function.\n */\n _createRouteGetter(property, defaultValue) {\n return () => this.currentRoute.value?.[property] ?? defaultValue;\n }\n\n /**\n * Wraps a component definition to inject router-specific context into its setup function.\n * @private\n * @param {ComponentDefinition} component - The component to wrap.\n * @returns {ComponentDefinition} The wrapped component definition.\n */\n _wrapComponent(component) {\n const originalSetup = component.setup;\n const self = this;\n\n return {\n ...component,\n async setup(ctx) {\n ctx.router = {\n navigate: self.navigate.bind(self),\n current: self.currentRoute,\n previous: self.previousRoute,\n\n // Route property getters\n get params() {\n return self._createRouteGetter(\"params\", {})();\n },\n get query() {\n return self._createRouteGetter(\"query\", {})();\n },\n get path() {\n return self._createRouteGetter(\"path\", \"/\")();\n },\n get fullUrl() {\n return self._createRouteGetter(\"fullUrl\", window.location.href)();\n },\n get meta() {\n return self._createRouteGetter(\"meta\", {})();\n },\n };\n\n return originalSetup ? await originalSetup(ctx) : {};\n },\n };\n }\n\n /**\n * Recursively wraps all child components to ensure they have access to router context.\n * @private\n * @param {ComponentDefinition} component - The component to wrap.\n * @returns {ComponentDefinition} The wrapped component definition.\n */\n _wrapComponentWithChildren(component) {\n const wrappedComponent = this._wrapComponent(component);\n\n // If the component has children, wrap them too\n if (\n wrappedComponent.children &&\n typeof wrappedComponent.children === \"object\"\n ) {\n const wrappedChildren = {};\n for (const [selector, childComponent] of Object.entries(\n wrappedComponent.children\n )) {\n wrappedChildren[selector] =\n this._wrapComponentWithChildren(childComponent);\n }\n wrappedComponent.children = wrappedChildren;\n }\n\n return wrappedComponent;\n }\n\n /**\n * Gets the current location information from the browser's window object.\n * @private\n * @returns {Omit<RouteLocation, 'params' | 'meta' | 'name' | 'matched'>}\n */\n _getCurrentLocation() {\n if (typeof window === \"undefined\")\n return { path: \"/\", query: {}, fullUrl: \"\" };\n let path, queryString, fullUrl;\n switch (this.options.mode) {\n case \"hash\":\n fullUrl = window.location.hash.slice(1) || \"/\";\n [path, queryString] = fullUrl.split(\"?\");\n break;\n case \"query\":\n const urlParams = new URLSearchParams(window.location.search);\n path = urlParams.get(this.options.queryParam) || \"/\";\n queryString = window.location.search.slice(1);\n fullUrl = path;\n break;\n default: // 'history' mode\n path = window.location.pathname || \"/\";\n queryString = window.location.search.slice(1);\n fullUrl = `${path}${queryString ? \"?\" + queryString : \"\"}`;\n }\n return {\n path: path.startsWith(\"/\") ? path : `/${path}`,\n query: this._parseQuery(queryString),\n fullUrl,\n };\n }\n\n /**\n * Parses a query string into a key-value object.\n * @private\n */\n _parseQuery(queryString) {\n const query = {};\n if (queryString) {\n new URLSearchParams(queryString).forEach((value, key) => {\n query[key] = value;\n });\n }\n return query;\n }\n\n /**\n * Matches a given path against the registered routes.\n * @private\n * @param {string} path - The path to match.\n * @returns {{route: RouteDefinition, params: Object<string, string>} | null} The matched route and its params, or null.\n */\n _matchRoute(path) {\n const pathSegments = path.split(\"/\").filter(Boolean);\n\n for (const route of this.routes) {\n // Handle the root path as a special case.\n if (route.path === \"/\") {\n if (pathSegments.length === 0) return { route, params: {} };\n continue;\n }\n\n if (route.segments.length !== pathSegments.length) continue;\n\n const params = {};\n let isMatch = true;\n for (let i = 0; i < route.segments.length; i++) {\n const routeSegment = route.segments[i];\n const pathSegment = pathSegments[i];\n if (routeSegment.type === \"param\") {\n params[routeSegment.name] = decodeURIComponent(pathSegment);\n } else if (routeSegment.value !== pathSegment) {\n isMatch = false;\n break;\n }\n }\n if (isMatch) return { route, params };\n }\n return null;\n }\n\n /** Registers a global pre-navigation guard. */\n onBeforeEach(guard) {\n this.options.onBeforeEach = guard;\n }\n /** Registers a global hook that runs after a new route component has been mounted *if* the route has an `afterEnter` hook. */\n onAfterEnter(hook) {\n this.emitter.on(\"router:afterEnter\", hook);\n }\n /** Registers a global hook that runs after a route component has been unmounted *if* the route has an `afterLeave` hook. */\n onAfterLeave(hook) {\n this.emitter.on(\"router:afterLeave\", hook);\n }\n /** Registers a global hook that runs after a navigation has been confirmed and all hooks have completed. */\n onAfterEach(hook) {\n this.emitter.on(\"router:afterEach\", hook);\n }\n /** Registers a global error handler for navigation. */\n onError(handler) {\n this.emitter.on(\"router:onError\", handler);\n }\n\n /**\n * Registers a plugin with the router.\n * @param {RouterPlugin} plugin - The plugin to register.\n */\n use(plugin, options = {}) {\n if (typeof plugin.install !== \"function\") {\n this.errorHandler.handle(\n new Error(\"Plugin must have an install method\"),\n \"Plugin registration failed\",\n { plugin }\n );\n }\n\n // Check if plugin is already registered\n if (this.plugins.has(plugin.name)) {\n this.errorHandler.warn(`Plugin \"${plugin.name}\" is already registered`, {\n existingPlugin: this.plugins.get(plugin.name),\n });\n return;\n }\n\n this.plugins.set(plugin.name, plugin);\n plugin.install(this, options);\n }\n\n /**\n * Gets all registered plugins.\n * @returns {RouterPlugin[]} Array of registered plugins.\n */\n getPlugins() {\n return Array.from(this.plugins.values());\n }\n\n /**\n * Gets a plugin by name.\n * @param {string} name - The plugin name.\n * @returns {RouterPlugin | undefined} The plugin or undefined.\n */\n getPlugin(name) {\n return this.plugins.get(name);\n }\n\n /**\n * Removes a plugin from the router.\n * @param {string} name - The plugin name.\n * @returns {boolean} True if the plugin was removed.\n */\n removePlugin(name) {\n const plugin = this.plugins.get(name);\n if (!plugin) return false;\n\n // Call destroy if available\n if (typeof plugin.destroy === \"function\") {\n try {\n plugin.destroy(this);\n } catch (error) {\n this.errorHandler.log(`Plugin ${name} destroy failed`, error);\n }\n }\n\n return this.plugins.delete(name);\n }\n\n /**\n * Sets a custom error handler. Used by error handling plugins.\n * @param {Object} errorHandler - The error handler object with handle, warn, and log methods.\n */\n setErrorHandler(errorHandler) {\n if (\n errorHandler &&\n typeof errorHandler.handle === \"function\" &&\n typeof errorHandler.warn === \"function\" &&\n typeof errorHandler.log === \"function\"\n ) {\n this.errorHandler = errorHandler;\n } else {\n console.warn(\n \"[ElevaRouter] Invalid error handler provided. Must have handle, warn, and log methods.\"\n );\n }\n }\n}\n\n/**\n * @typedef {Object} RouterOptions\n * @property {string} mount - A CSS selector for the main element where the app is mounted.\n * @property {RouteDefinition[]} routes - An array of route definitions.\n * @property {'hash' | 'query' | 'history'} [mode='hash'] - The routing mode.\n * @property {string} [queryParam='page'] - The query parameter to use in 'query' mode.\n * @property {string} [viewSelector='view'] - The selector for the view element within a layout.\n * @property {boolean} [autoStart=true] - Whether to start the router automatically.\n * @property {NavigationGuard} [onBeforeEach] - A global guard executed before every navigation.\n * @property {string | ComponentDefinition | (() => Promise<{default: ComponentDefinition}>)} [globalLayout] - A global layout for all routes. Can be overridden by a route's specific layout.\n */\n\n/**\n * @class 🚀 RouterPlugin\n * @classdesc A powerful, reactive, and flexible Router Plugin for Eleva.js applications.\n * This plugin provides comprehensive client-side routing functionality including:\n * - Multiple routing modes (hash, history, query)\n * - Navigation guards and lifecycle hooks\n * - Reactive state management\n * - Component resolution and lazy loading\n * - Layout and page component separation\n * - Plugin system for extensibility\n * - Advanced error handling\n *\n * @example\n * // Install the plugin\n * const app = new Eleva(\"myApp\");\n *\n * const HomePage = { template: () => `<h1>Home</h1>` };\n * const AboutPage = { template: () => `<h1>About Us</h1>` };\n * const UserPage = {\n * template: (ctx) => `<h1>User: ${ctx.router.params.id}</h1>`\n * };\n *\n * app.use(RouterPlugin, {\n * mount: '#app',\n * mode: 'hash',\n * routes: [\n * { path: '/', component: HomePage },\n * { path: '/about', component: AboutPage },\n * { path: '/users/:id', component: UserPage }\n * ]\n * });\n */\nexport const RouterPlugin = {\n /**\n * Unique identifier for the plugin\n * @type {string}\n */\n name: \"router\",\n\n /**\n * Plugin version\n * @type {string}\n */\n version: \"1.0.0-rc.1\",\n\n /**\n * Plugin description\n * @type {string}\n */\n description: \"Client-side routing for Eleva applications\",\n\n /**\n * Installs the RouterPlugin into an Eleva instance.\n *\n * @param {Eleva} eleva - The Eleva instance\n * @param {RouterOptions} options - Router configuration options\n * @param {string} options.mount - A CSS selector for the main element where the app is mounted\n * @param {RouteDefinition[]} options.routes - An array of route definitions\n * @param {'hash' | 'query' | 'history'} [options.mode='hash'] - The routing mode\n * @param {string} [options.queryParam='page'] - The query parameter to use in 'query' mode\n * @param {string} [options.viewSelector='view'] - The selector for the view element within a layout\n * @param {boolean} [options.autoStart=true] - Whether to start the router automatically\n * @param {NavigationGuard} [options.onBeforeEach] - A global guard executed before every navigation\n * @param {string | ComponentDefinition | (() => Promise<{default: ComponentDefinition}>)} [options.globalLayout] - A global layout for all routes\n *\n * @example\n * // main.js\n * import Eleva from './eleva.js';\n * import { RouterPlugin } from './plugins/RouterPlugin.js';\n *\n * const app = new Eleva('myApp');\n *\n * const HomePage = { template: () => `<h1>Home</h1>` };\n * const AboutPage = { template: () => `<h1>About Us</h1>` };\n *\n * app.use(RouterPlugin, {\n * mount: '#app',\n * routes: [\n * { path: '/', component: HomePage },\n * { path: '/about', component: AboutPage }\n * ]\n * });\n */\n install(eleva, options = {}) {\n if (!options.mount) {\n throw new Error(\"[RouterPlugin] 'mount' option is required\");\n }\n\n if (!options.routes || !Array.isArray(options.routes)) {\n throw new Error(\"[RouterPlugin] 'routes' option must be an array\");\n }\n\n /**\n * Registers a component definition with the Eleva instance.\n * This method handles both inline component objects and pre-registered component names.\n *\n * @param {any} def - The component definition to register\n * @param {string} type - The type of component for naming (e.g., \"Route\", \"Layout\")\n * @returns {string | null} The registered component name or null if no definition provided\n */\n const register = (def, type) => {\n if (!def) return null;\n\n if (typeof def === \"object\" && def !== null && !def.name) {\n const name = `Eleva${type}Component_${Math.random()\n .toString(36)\n .slice(2, 11)}`;\n\n try {\n eleva.component(name, def);\n return name;\n } catch (error) {\n throw new Error(\n `[RouterPlugin] Failed to register ${type} component: ${error.message}`\n );\n }\n }\n return def;\n };\n\n if (options.globalLayout) {\n options.globalLayout = register(options.globalLayout, \"GlobalLayout\");\n }\n\n (options.routes || []).forEach((route) => {\n route.component = register(route.component, \"Route\");\n if (route.layout) {\n route.layout = register(route.layout, \"RouteLayout\");\n }\n });\n\n const router = new Router(eleva, options);\n eleva.router = router;\n\n if (options.autoStart !== false) {\n queueMicrotask(() => router.start());\n }\n\n // Add plugin metadata to the Eleva instance\n if (!eleva.plugins) {\n eleva.plugins = new Map();\n }\n eleva.plugins.set(this.name, {\n name: this.name,\n version: this.version,\n description: this.description,\n options,\n });\n\n // Add utility methods for manual router access\n eleva.navigate = router.navigate.bind(router);\n eleva.getCurrentRoute = () => router.currentRoute.value;\n eleva.getRouteParams = () => router.currentParams.value;\n eleva.getRouteQuery = () => router.currentQuery.value;\n\n return router;\n },\n\n /**\n * Uninstalls the plugin from the Eleva instance\n *\n * @param {Eleva} eleva - The Eleva instance\n */\n async uninstall(eleva) {\n if (eleva.router) {\n await eleva.router.destroy();\n delete eleva.router;\n }\n\n // Remove plugin metadata\n if (eleva.plugins) {\n eleva.plugins.delete(this.name);\n }\n\n // Remove utility methods\n delete eleva.navigate;\n delete eleva.getCurrentRoute;\n delete eleva.getRouteParams;\n delete eleva.getRouteQuery;\n },\n};\n"],"names":["CoreErrorHandler","handle","error","context","details","formattedError","Error","message","originalError","warn","log","Router","constructor","eleva","options","this","_extends","mode","queryParam","viewSelector","routes","_processRoutes","emitter","isStarted","_isNavigating","eventListeners","currentRoute","signal","previousRoute","currentParams","currentQuery","currentLayout","currentView","plugins","Map","errorHandler","_validateOptions","includes","processedRoutes","route","push","segments","_parsePathIntoSegments","path","normalizedPath","replace","split","filter","Boolean","map","segment","startsWith","paramName","substring","type","name","value","_findViewElement","container","selector","querySelector","start","window","document","mount","mountSelector","handler","_handleRouteChange","addEventListener","removeEventListener","destroy","plugin","values","forEach","cleanup","unmount","navigate","location","params","target","_buildPath","query","Object","keys","length","queryString","URLSearchParams","toString","_isSameRoute","_proceedWithNavigation","state","historyMethod","newUrl","pathname","search","history","replaceState","hash","url","_buildQueryUrl","queueMicrotask","emit","urlParams","set","current","targetPath","targetQuery","_parseQuery","JSON","stringify","result","key","entries","encodedValue","encodeURIComponent","String","RegExp","from","toLocation","_getCurrentLocation","fullUrl","fullPath","toMatch","_matchRoute","notFoundRoute","find","pathMatch","to","meta","matched","_runGuards","layoutComponent","pageComponent","_resolveComponents","tryUnmount","async","instance","layout","globalLayout","afterLeave","_render","afterEnter","guards","onBeforeEach","beforeLeave","beforeEnter","guard","_resolveStringComponent","def","componentDef","_components","get","componentName","availableComponents","Array","_resolveFunctionComponent","funcStr","isAsyncImport","default","function","_validateComponentDefinition","definition","template","_resolveComponent","effectiveLayout","Promise","all","component","mountEl","layoutInstance","_wrapComponentWithChildren","viewEl","viewInstance","_createRouteGetter","property","defaultValue","_this$currentRoute$va","_this$currentRoute$va2","_wrapComponent","originalSetup","setup","self","ctx","router","bind","previous","href","wrappedComponent","children","wrappedChildren","childComponent","slice","pathSegments","isMatch","i","routeSegment","pathSegment","decodeURIComponent","onAfterEnter","hook","on","onAfterLeave","onAfterEach","onError","use","install","has","existingPlugin","getPlugins","getPlugin","removePlugin","delete","setErrorHandler","version","description","isArray","register","Math","random","autoStart","getCurrentRoute","getRouteParams","getRouteQuery","uninstall"],"mappings":";kQAcA,MAAMA,EAAmB,CAQvBC,M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