@aegisjsproject/router
Version:
A simple but powerful router module
3 lines (2 loc) • 33.6 kB
JavaScript
import{getStateObj as e,diffState as t,notifyStateChange as n}from"@aegisjsproject/state";function r(e){switch(typeof e){case"string":return e;case"function":throw new TypeError("Functions are not supported.");case"undefined":return"";case"object":return null===e?"":e instanceof Date?e.toISOString():Array.isArray(e)?e.map(r).join(","):e instanceof ArrayBuffer&&Uint8Array.prototype.toBase64 instanceof Function?new Uint8Array(e).toBase64():ArrayBuffer.isView(e)&&e.toBase64 instanceof Function?e.toBase64():e instanceof Blob?URL.createObjectURL(e):e.toString();default:return e.toString()}}function o(e){return encodeURIComponent(r(e).trim()).replaceAll("..%2F","%2E%2E%2F").replaceAll(".%2F","%2E%2E%2F")}const a=function(e=globalThis?.document?.baseURI){return function(t,n,...r){return n instanceof Blob&&2===t.length&&""===t[0]&&""===t[1]?new URL(URL.createObjectURL(n)):URL.canParse(n)?URL.parse(String.raw(t,"",...r.map(o)),n):t[0].startsWith("/")||t[0].startsWith("./")||t[0].startsWith("../")?URL.parse(String.raw(t,o(n),...r.map(o)),e):URL.parse(String.raw(t,o(n),...r.map(o)))}}(),i=(e,t=document)=>t.querySelectorAll(e),s=(e,t=document)=>t.querySelector(e),l={debug:{log:"aegis:debug:log",info:"aegis:debug:info",warn:"aegis:debug:warn",error:"aegis:debug:error"},navigate:{back:"aegis:navigate:back",forward:"aegis:navigate:forward",reload:"aegis:navigate:reload",close:"aegis:navigate:close",link:"aegis:navigate:go",popup:"aegis:navigate:popup"},ui:{print:"aegis:ui:print",remove:"aegis:ui:remove",hide:"aegis:ui:hide",unhide:"aegis:ui:unhide",showModal:"aegis:ui:showModal",closeModal:"aegis:ui:closeModal",showPopover:"aegis:ui:showPopover",hidePopover:"aegis:ui:hidePopover",togglePopover:"aegis:ui:togglePopover",enable:"aegis:ui:enable",disable:"aegis:ui:disable",scrollTo:"aegis:ui:scrollTo",prevent:"aegis:ui:prevent",revokeObjectURL:"aegis:ui:revokeObjectURL",cancelAnimationFrame:"aegis:ui:cancelAnimationFrame",abortController:"aegis:ui:controller:abort"}},c=new Map([[l.debug.log,console.log],[l.debug.warn,console.warn],[l.debug.error,console.error],[l.debug.info,console.info],[l.navigate.back,()=>history.back()],[l.navigate.forward,()=>history.forward()],[l.navigate.reload,()=>history.go(0)],[l.navigate.close,()=>globalThis.close()],[l.navigate.link,e=>{e.isTrusted&&(e.preventDefault(),location.href=e.currentTarget.dataset.url)}],[l.navigate.popup,e=>{e.isTrusted&&(e.preventDefault(),globalThis.open(e.currentTarget.dataset.url))}],[l.ui.hide,({currentTarget:e})=>{i(e.dataset.hideSelector).forEach((e=>e.hidden=!0))}],[l.ui.unhide,({currentTarget:e})=>{i(e.dataset.unhideSelector).forEach((e=>e.hidden=!1))}],[l.ui.disable,({currentTarget:e})=>{i(e.dataset.disableSelector).forEach((e=>e.disabled=!0))}],[l.ui.enable,({currentTarget:e})=>{i(e.dataset.enableSelector).forEach((e=>e.disabled=!1))}],[l.ui.remove,({currentTarget:e})=>{i(e.dataset.removeSelector).forEach((e=>e.remove()))}],[l.ui.scrollTo,({currentTarget:e})=>{const t=s(e.dataset.scrollToSelector);t instanceof Element&&t.scrollIntoView({behavior:matchMedia("(prefers-reduced-motion: reduce)").matches?"instant":"smooth"})}],[l.ui.revokeObjectURL,({currentTarget:e})=>URL.revokeObjectURL(e.src)],[l.ui.cancelAnimationFrame,({currentTarget:e})=>cancelAnimationFrame(parseInt(e.dataset.animationFrame))],[l.ui.clearInterval,({currentTarget:e})=>clearInterval(parseInt(e.dataset.clearInterval))],[l.ui.clearTimeout,({currentTarget:e})=>clearTimeout(parseInt(e.dataset.timeout))],[l.ui.abortController,({currentTarget:e})=>function(e,t){const n=dt(e);return n instanceof AbortController&&("string"==typeof t?(n.abort(new Error(t)),!0):(n.abort(t),!0))}(e.dataset.aegisEventController,e.dataset.aegisControllerReason)],[l.ui.showModal,({currentTarget:e})=>{const t=s(e.dataset.showModalSelector);t instanceof HTMLDialogElement&&t.showModal()}],[l.ui.closeModal,({currentTarget:e})=>{const t=s(e.dataset.closeModalSelector);t instanceof HTMLDialogElement&&t.close()}],[l.ui.showPopover,({currentTarget:e})=>{const t=s(e.dataset.showPopoverSelector);t instanceof HTMLElement&&t.showPopover()}],[l.ui.hidePopover,({currentTarget:e})=>{const t=s(e.dataset.hidePopoverSelector);t instanceof HTMLElement&&t.hidePopover()}],[l.ui.togglePopover,({currentTarget:e})=>{const t=s(e.dataset.togglePopoverSelector);t instanceof HTMLElement&&t.togglePopover()}],[l.ui.print,()=>globalThis.print()],[l.ui.prevent,e=>e.preventDefault()]]),u=e=>c.has(e),d=e=>c.get(e),g="data-aegis-event-",f=g+"on-",p="aegisEventOn",m=new Map,h=new Map,y=g+"once",b=g+"passive",w=g+"capture",v=g+"signal",E=f+"abort",L=f+"blur",P=f+"focus",T=f+"cancel",R=f+"auxclick",S=f+"beforeinput",U=f+"beforetoggle",A=f+"canplay",M=f+"canplaythrough",k=f+"change",O=f+"click",C=f+"close",D=f+"contextmenu",H=f+"copy",F=f+"cuechange",j=f+"cut",I=f+"dblclick",q=f+"drag",x=f+"dragend",N=f+"dragenter",W=f+"dragexit",$=f+"dragleave",B=f+"dragover",z=f+"dragstart",G=f+"drop",V=f+"durationchange",K=f+"emptied",J=f+"ended",Q=f+"formdata",_=f+"input",X=f+"invalid",Y=f+"keydown",Z=f+"keypress",ee=f+"keyup",te=f+"load",ne=f+"loadeddata",re=f+"loadedmetadata",oe=f+"loadstart",ae=f+"mousedown",ie=f+"mouseenter",se=f+"mouseleave",le=f+"mousemove",ce=f+"mouseout",ue=f+"mouseover",de=f+"mouseup",ge=f+"wheel",fe=f+"paste",pe=f+"pause",me=f+"play",he=f+"playing",ye=f+"progress",be=f+"ratechange",we=f+"reset",ve=f+"resize",Ee=f+"scroll",Le=f+"scrollend",Pe=f+"securitypolicyviolation",Te=f+"seeked",Re=f+"seeking",Se=f+"select",Ue=f+"slotchange",Ae=f+"stalled",Me=f+"submit",ke=f+"suspend",Oe=f+"timeupdate",Ce=f+"volumechange",De=f+"waiting",He=f+"selectstart",Fe=f+"selectionchange",je=f+"toggle",Ie=f+"pointercancel",qe=f+"pointerdown",xe=f+"pointerup",Ne=f+"pointermove",We=f+"pointerout",$e=f+"pointerover",Be=f+"pointerenter",ze=f+"pointerleave",Ge=f+"gotpointercapture",Ve=f+"lostpointercapture",Ke=f+"mozfullscreenchange",Je=f+"mozfullscreenerror",Qe=f+"animationcancel",_e=f+"animationend",Xe=f+"animationiteration",Ye=f+"animationstart",Ze=f+"transitioncancel",et=f+"transitionend",tt=f+"transitionrun",nt=f+"transitionstart",rt=f+"webkitanimationend",ot=f+"webkitanimationiteration",at=f+"webkitanimationstart",it=f+"webkittransitionend",st=f+"error";let lt=[E,L,P,T,R,S,U,A,M,k,O,C,D,H,F,j,I,q,x,N,W,$,B,z,G,V,K,J,Q,_,X,Y,Z,ee,te,ne,re,oe,ae,ie,se,le,ce,ue,de,ge,fe,pe,me,he,ye,be,we,ve,Ee,Le,Pe,Te,Re,Se,Ue,Ae,Me,ke,Oe,Ce,De,He,Fe,je,Ie,qe,xe,Ne,We,$e,Be,ze,Ge,Ve,Ke,Je,Qe,_e,Xe,Ye,Ze,et,tt,nt,rt,ot,at,it,st].map((e=>`[${CSS.escape(e)}]`)).join(", ");const ct=([e])=>e.startsWith(p);new MutationObserver((e=>{e.forEach((e=>{switch(e.type){case"childList":[...e.addedNodes].filter((e=>e.nodeType===Node.ELEMENT_NODE)).forEach((e=>function(e,{signal:t}={}){return(e instanceof Element&&e.matches(lt)?[e,...e.querySelectorAll(lt)]:e.querySelectorAll(lt)).forEach((e=>function(e,{signal:t,attrFilter:n=ut}={}){const r=e.dataset;for(const[o,a]of Object.entries(r).filter(ct))try{const i="on"+o.substring(12);n.hasOwnProperty(i)&&u(a)&&e.addEventListener(i.substring(2).toLowerCase(),d(a),{passive:r.hasOwnProperty("aegisEventPassive"),capture:r.hasOwnProperty("aegisEventCapture"),once:r.hasOwnProperty("aegisEventOnce"),signal:r.hasOwnProperty("aegisEventSignal")?gt(r.aegisEventSignal):t})}catch(e){reportError(e)}}(e,{signal:t}))),e}(e)));break;case"attributes":"string"==typeof e.oldValue&&u(e.oldValue)&&e.target.removeEventListener(e.attributeName.substring(20),d(e.oldValue),{once:e.target.hasAttribute(y),capture:e.target.hasAttribute(w),passive:e.target.hasAttribute(b)}),e.target.hasAttribute(e.attributeName)&&u(e.target.getAttribute(e.attributeName))&&e.target.addEventListener(e.attributeName.substring(20),d(e.target.getAttribute(e.attributeName)),{once:e.target.hasAttribute(y),capture:e.target.hasAttribute(w),passive:e.target.hasAttribute(b),signal:e.target.hasAttribute(v)?gt(e.target.getAttribute(v)):void 0})}}))}));const ut={onAbort:E,onBlur:L,onFocus:P,onCancel:T,onAuxclick:R,onBeforeinput:S,onBeforetoggle:U,onCanplay:A,onCanplaythrough:M,onChange:k,onClick:O,onClose:C,onContextmenu:D,onCopy:H,onCuechange:F,onCut:j,onDblclick:I,onDrag:q,onDragend:x,onDragenter:N,onDragexit:W,onDragleave:$,onDragover:B,onDragstart:z,onDrop:G,onDurationchange:V,onEmptied:K,onEnded:J,onFormdata:Q,onInput:_,onInvalid:X,onKeydown:Y,onKeypress:Z,onKeyup:ee,onLoad:te,onLoadeddata:ne,onLoadedmetadata:re,onLoadstart:oe,onMousedown:ae,onMouseenter:ie,onMouseleave:se,onMousemove:le,onMouseout:ce,onMouseover:ue,onMouseup:de,onWheel:ge,onPaste:fe,onPause:pe,onPlay:me,onPlaying:he,onProgress:ye,onRatechange:be,onReset:we,onResize:ve,onScroll:Ee,onScrollend:Le,onSecuritypolicyviolation:Pe,onSeeked:Te,onSeeking:Re,onSelect:Se,onSlotchange:Ue,onStalled:Ae,onSubmit:Me,onSuspend:ke,onTimeupdate:Oe,onVolumechange:Ce,onWaiting:De,onSelectstart:He,onSelectionchange:Fe,onToggle:je,onPointercancel:Ie,onPointerdown:qe,onPointerup:xe,onPointermove:Ne,onPointerout:We,onPointerover:$e,onPointerenter:Be,onPointerleave:ze,onGotpointercapture:Ge,onLostpointercapture:Ve,onMozfullscreenchange:Ke,onMozfullscreenerror:Je,onAnimationcancel:Qe,onAnimationend:_e,onAnimationiteration:Xe,onAnimationstart:Ye,onTransitioncancel:Ze,onTransitionend:et,onTransitionrun:tt,onTransitionstart:nt,onWebkitanimationend:rt,onWebkitanimationiteration:ot,onWebkitanimationstart:at,onWebkittransitionend:it,onError:st,once:y,passive:b,capture:w},dt=e=>h.get(e);const gt=e=>m.get(e);const ft=!(document.currentScript instanceof HTMLScriptElement),pt=HTMLScriptElement.supports("importmap"),mt=new Map,ht=["GET","HEAD","DELETE","OPTIONS"],yt='meta[name="description"], meta[itemprop="description"], meta[property="og:description"], meta[name="twitter:description"]',bt=new MutationObserver((e=>e.forEach((e=>Kt(e.target))))),wt=new MutationObserver((e=>e.forEach(At))),vt="root",Et=document,Lt=Symbol.for("aegis:navigate:event:close"),Pt=matchMedia("(prefers-reduced-motion: reduce)");let Tt=document.getElementById(vt)??document.body,Rt="#"+vt;const St="trustedTypes"in globalThis,Ut=e=>St&&trustedTypes.isHTML(e);function At(e){e instanceof MutationRecord?At(e.target):"A"!==e.tagName||e.classList.contains("no-router")||e.hasAttribute(O)?e.querySelectorAll(`a:not(.no-router, [${O}])`).forEach((e=>Ln(e,e.dataset))):Ln(e,e.dataset)}const Mt="aegis:navigate",kt={navigate:"aegis:router:navigate",back:"aegis:router:back",forward:"aegis:router:forward",reload:"aegis:router:reload",pop:"aegis:router:pop",go:"aegis:router:go",load:"aegis:router:load",submit:"aegis:router:submit"},Ot=[kt.back,kt.forward,kt.navigate,kt.submit,kt.reload,kt.go];class Ct extends CustomEvent{#e;#t;#n=new AbortController;#r=[];#o=[];constructor(t=Mt,n="unknown",{bubbles:r=!1,cancelable:o=!0,detail:a={oldState:e(),oldURL:new URL(location.href)}}={}){super(t,{bubbles:r,cancelable:o,detail:a}),this.#e=n,this.#t=location.href}get aborted(){return this.#n.signal.aborted}get error(){switch(this.#o.length){case 0:return null;case 1:return this.#o[0];default:return new AggregateError(this.#o)}}get reason(){return this.#e}get signal(){return this.#n.signal}get url(){return this.#t}async[Lt](){const e=await Promise.allSettled(this.#r).then((e=>(this.#o.push(...e.filter((e=>"rejected"===e.status)).map((e=>e.reason))),this.cancelable&&this.defaultPrevented)));return this.#n.abort(),e}abort(e){this.#n.abort(e)}waitUntil(e,{signal:t}={}){const{promise:n,resolve:r,reject:o}=Promise.withResolvers();this.#r.push(n),t instanceof AbortSignal&&!t.aborted&&t.addEventListener("abort",(({target:e})=>{o(e.reason),this.cancelable&&!this.defaultPrevented&&super.preventDefault()}),{once:!0,signal:this.#n.signal}),this.#n.signal.aborted?o(this.#n.signal.reason):t instanceof AbortSignal&&t.aborted?(o(t.reason),this.cancelable&&!this.defaultPrevented&&super.preventDefault()):!this.defaultPrevented&&e instanceof Function?Promise.try((()=>e(this,{signal:t instanceof AbortSignal?AbortSignal.any([t,this.#n.signal]):this.#n.signal,timestamp:performance.now()}))).then(r,o):!this.defaultPrevented&&e instanceof Promise&&e.then(r,o)}[Symbol.toStringTag](){return"NavigationEvent"}static get defaultType(){return Mt}static get reasons(){return kt}}const Dt=St?trustedTypes.createPolicy("aegis-router#html",{createHTML:e=>e}):Object.freeze({createPolicy:e=>e});async function Ht(e){const r=t(e.state??{}),o=new Ct(Mt,kt.pop,{detail:{newState:e.state,oldState:null,oldURL:new URL(location.href),method:"GET",formData:null}});if(Et.dispatchEvent(o),!await o[Lt]()){const e=history.scrollRestoration,[t]=await Promise.all([en(new URL(location.href)),n(r)]);history.scrollRestoration="auto",Wt(t),history.scrollRestoration=e}}function Ft(e={}){const t=document.createElement("meta");return Object.entries(e).forEach((([e,n])=>t.setAttribute(e,n))),t}function jt(e,{relList:t=[],crossOrigin:n="anonymous",referrerPolicy:r="no-referrer",fetchPriority:o="auto",signal:a,as:i,integrity:s,media:l,type:c}={}){const{promise:u,resolve:d,reject:g}=Promise.withResolvers(),f=document.createElement("link");if(!(a instanceof AbortSignal&&a.aborted)){if(f.relList.add(...t),"string"==typeof o&&(f.fetchPriority=o),"string"==typeof n&&(f.crossOrigin=n),"string"==typeof c&&(f.type=c),"string"==typeof l?f.media=l:l instanceof MediaQueryList&&(f.media=l.media),"string"==typeof i&&(f.as=i),"string"==typeof s&&(f.integrity=s),f.relList.contains("preload")||f.relList.contains("modulepreload")){const t=new AbortController,n=a instanceof AbortSignal?AbortSignal.any([t.signal,a]):t.signal;return a.addEventListener("abort",(({target:e})=>{g(e.reason)}),{signal:t.signal}),f.referrerPolicy=r,f.addEventListener("load",(()=>{d(),t.abort()}),{signal:n}),f.addEventListener("error",(()=>{g(new DOMException(`Error loading ${e}`,"NotFoundError")),t.abort()}),{signal:n}),f.href=function(e){if(It(e))return URL.parse(e,document.baseURI);if(pt){if(ft)return import.meta.resolve(e);throw new TypeError("Cannot resolve a module specifier outside of a module script.")}throw new TypeError("Importmaps and module specifiers are not supported")}(e),document.head.append(f),u.then((()=>f.remove())).catch((e=>{f.isConnected&&f.remove(),reportError(e)}))}return f.href=e,document.head.append(f),d(),u}g(a.reason)}function It(e){switch(e[0]){case"/":case".":return!0;case"h":return"http"===e.substring(0,"4")&&URL.canParse(e);default:return!1}}function qt(e){if(e.target.classList.contains("no-router")||e.target.hasAttribute(O))e.target.removeEventListener(qt);else if(e.isTrusted&&e.currentTarget.href.startsWith(location.origin)){e.preventDefault();const t=function(e){const t=Object.entries(e.dataset).filter((([e])=>e.startsWith("aegisState"))).map((([e,t])=>[e[10].toLowerCase()+e.substring(11),t]));return Object.fromEntries(t)}(e.currentTarget);tn(e.currentTarget.href,t,{integrity:e.currentTarget.dataset.integrity,cache:e.currentTarget.dataset.cache,referrerPolicy:e.currentTarget.dataset.referrerPolicy})}}async function xt(t){if(t.target.classList.contains("no-router")||t.target.hasAttribute(Me))t.target.removeEventListener("submit",xt);else if(t.isTrusted&&t.target.action.startsWith(location.origin)){t.preventDefault();const{method:n,action:r}=t.target,o=new FormData(t.target),a=new Ct(Mt,kt.submit,{detail:{oldState:e(),oldURL:new URL(location.href),formData:o}});if(Et.dispatchEvent(a),await a[Lt]())return;if(ht.includes(n.toUpperCase())){const t=new URL(r),a=new URLSearchParams(o);for(const[e,n]of a.entries())t.searchParams.append(e,n);await tn(t,e(),{method:n})}else await tn(r,e(),{method:n,formData:o})}}async function Nt(t,{signal:n,method:r="GET",body:o,integrity:a,cache:i="default",referrerPolicy:s="no-referrer"}={}){const l=await fetch(t,{method:r,body:ht.includes(r.toUpperCase())?null:o,headers:{Accept:"text/html"},cache:i,referrerPolicy:s,integrity:a,signal:n}).catch((e=>e));if(l.ok){const e=await l.text();return Document.parseHTMLUnsafe(Dt.createHTML(e))}return l instanceof Error?l:async function(t=location,n="GET",{signal:r,formData:o,integrity:a}={}){const i=performance.now();if("string"==typeof zt)return await Bt(zt,{url:t,matches:null,signal:r,method:n,formData:o,timestamp:i,integrity:a});zt instanceof Function&&Wt(zt({timestamp:i,state:e(),url:t,matches:null,signal:r,method:n,formData:o,integrity:a}))}(t,r,{signal:n})}function Wt(t){const n=performance.now();if(t instanceof Document){0!==t.head.childElementCount&&(dn(t.title),gn(t.querySelector(yt)?.content));const e="string"==typeof Rt?t.body.querySelector(Rt)??t.body:t.body;Tt.replaceChildren(...e.childNodes)}else t instanceof HTMLTemplateElement?Tt.replaceChildren(t.content):t instanceof Function&&t.prototype instanceof HTMLElement?Tt.replaceChildren(new t({state:e(),url:new URL(location.href),timestamp:n})):t instanceof Node?Tt.replaceChildren(t):t instanceof Function?Wt(t()):"string"==typeof t?Tt.setHTMLUnsafe(Dt.createHTML(t)):Ut(t)?Tt.setHTMLUnsafe(t):t instanceof Error?(reportError(t),Tt.textContent=t.message):null!=t&&(Tt.textContent=t);if(Et.dispatchEvent(new Ct(Mt,kt.load,{cancelable:!1})),"manual"===history.scrollRestoration)if(location.hash.length>1){(document.getElementById(location.hash.substring(1))??document.body).scrollIntoView({behavior:Pt.matches?"instant":"smooth"})}else{const e=Tt.querySelector("[autofocus]");e instanceof Element?e.focus():document.body.scrollIntoView({behavior:Pt.matches?"instant":"smooth"})}}async function $t({title:e,description:t}={},{state:n,matches:r,params:o,url:a,signal:i}={}){"string"==typeof e?dn(e):"function"==typeof e&&dn(await e({state:n,matches:r,params:o,url:a,signal:i})),"string"==typeof t?gn(t):"function"==typeof t&&gn(await t({state:n,matches:r,params:o,url:a,signal:i}))}async function Bt(t,{state:n=e(),matches:r={},params:o={},signal:a,...i}={}){const s=await Promise.try((()=>t instanceof Function?t(i):"string"==typeof t||s instanceof URL?It(t)?import(URL.parse(t,document.baseURI)):import(t):new TypeError("Invalid module src."))).catch((e=>e)),l=new URL(location.href),c=performance.now();if(s instanceof URL)await tn(s,n,i);else{if(s instanceof Error)return s.message;if(!("default"in s))return new Error(`${t} has no default export.`);if(s.default instanceof Function&&s.default.prototype instanceof HTMLElement)return"string"!=typeof customElements.getName(s.default)&&customElements.define(s.default[Symbol.for("tagName")]??`aegis-el-${crypto.randomUUID()}`,s.default),$t(s,{state:n,matches:r,params:o,url:l,signal:a}),new s.default({url:l,matches:r,params:o,state:n,timestamp:c,signal:vn({signal:a}),...i});if(s.default instanceof Function)return $t(s,{state:n,matches:r,params:o,url:l,signal:a}),await s.default({url:l,matches:r,params:o,state:n,timestamp:c,signal:vn({signal:a}),...i});if(!(s.default instanceof Node||s.default instanceof Error))throw new TypeError(`${t} has a missing or invalid default export.`);$t(s,{state:n,matches:r,params:o,url:l,signal:a}),Wt(s.default)}}let zt=({url:e=location,method:t="GET"})=>{const n=document.createElement("div"),r=document.createElement("p"),o=document.createElement("a");return r.textContent=`${t.toUpperCase()} ${e.href} [404 Not Found]`,o.href=document.baseURI,o.textContent="Go Home",o.addEventListener("click",qt),n.append(r,o),n};const Gt=e=>mt.keys().find((t=>t.test(e))),Vt=e=>zt=e;function Kt(e=document.body,{signal:t}={}){if("string"==typeof e)Kt(document.querySelector(e),{signal:t});else{if(!(e instanceof HTMLElement||e instanceof ShadowRoot))throw new TypeError("Cannot intercept navigation on a non-Element. Element or selector is required.");e instanceof HTMLAnchorElement&&!e.classList.contains("no-router")&&!e.hasAttribute(O)&&e.href.startsWith(location.origin)?e.addEventListener("click",qt,{signal:t,passive:!1}):e instanceof HTMLFormElement&&!e.classList.contains("no-router")&&!e.hasAttribute(Me)&&e.action.startsWith(location.origin)?(e.addEventListener("submit",xt,{signal:t,passive:!1}),e.querySelectorAll(`a[href]:not([rel~="external"], [download], .no-router, [${O}])`).forEach((e=>{e.href.startsWith(location.origin)&&e.addEventListener("click",qt,{passive:!1,signal:t})}))):(e.querySelectorAll(`a[href]:not([rel~="external"], [download], .no-router, [${O}])`).forEach((e=>{e.href.startsWith(location.origin)&&e.addEventListener("click",qt,{passive:!1,signal:t})})),e.querySelectorAll(`form:not(.no-router, [${Me}])`).forEach((e=>{e.addEventListener("submit",xt,{passive:!1,signal:t})})))}}function Jt(e,t){if(e instanceof HTMLElement)Tt=e,Rt="string"==typeof t?t:e.hasAttribute("id")?`#${e.id}`:null,"string"!=typeof Tt.ariaLive&&(Tt.ariaLive="assertive");else{if("string"!=typeof e)throw new TypeError("Cannot set root to a non-html element.");Jt(document.querySelector(e),e)}}function Qt(e=document.body,{signal:t}={}){if(t instanceof AbortSignal&&t.aborted)throw t.reason;if("string"==typeof e)Qt(document.querySelector(e),{signal:t});else{if(!(e instanceof HTMLElement||e instanceof ShadowRoot))throw new TypeError("Cannot observe link on a non-Element. Requires an Element or selector.");Kt(e,{signal:t}),bt.observe(e,{childList:!0,subtree:!0}),t instanceof AbortSignal&&t.addEventListener("abort",(()=>bt.disconnect()),{once:!0})}}function _t(e,t=location.origin){return e instanceof URLPattern?e:"string"==typeof e?new URLPattern(e,t):e instanceof URL?new URLPattern(e.href):null}function Xt(e,t,{fallbackValue:n="",baseURL:r=location.origin}={}){const o=_t(e,r);return Object.freeze({toString:()=>o.exec(location.href)?.pathname.groups?.[t]??n,[Symbol.toPrimitive](e="default"){return"number"===e?parseFloat(this.toString()):this.toString()}})}async function Yt(e,t,{preload:n=!1,signal:r,baseURL:o=location.origin,crossOrigin:a="anonymous",referrerPolicy:i="no-referrer"}={}){if(r instanceof AbortSignal&&r.aborted)throw r.reason;if("string"==typeof e)await Yt(new URLPattern(e,o),t,{preload:n,signal:r,crossOrigin:a,referrerPolicy:i});else if(e instanceof URL)await Yt(new URLPattern(e.href),t,{preload:n,baseURL:o,signal:r,crossOrigin:a,referrerPolicy:i});else{if(!("string"==typeof t||t instanceof Function||t instanceof URL))throw new TypeError("Module source/handler must be a module specifier/url or handler function.");if(!(e instanceof URLPattern))throw new TypeError(`Could not convert ${e} to a URLPattern.`);mt.set(e,t),n&&("string"==typeof t||t instanceof URL)&&await pn(t,{signal:r,crossOrigin:a,referrerPolicy:i}),r instanceof AbortSignal&&r.addEventListener("abort",Zt,{once:!0})}}function Zt(){mt.clear()}async function en(t=location,{method:n="GET",state:r=e(),formData:o=new FormData,cache:a="default",referrerPolicy:i="no-referrer",integrity:s,signal:l}={}){const c=performance.now();if(null===t)throw new Error("Invalid path.");if(t instanceof URL){const e=Gt(t);if(e instanceof URLPattern){const a=mt.get(e),i=e.exec(t),l="object"==typeof i?{...i.protocol.groups,...i.username.groups,...i.password.groups,...i.hostname.groups,...i.port.groups,...i.pathname.groups,...i.search.groups,...i.hash.groups}:{};return delete l[0],await Bt(a,{url:t,matches:i,params:l,state:r,method:n,formData:o,integrity:s,timestamp:c})}return await Nt(t,{method:n,signal:vn({signal:l}),body:o,integrity:s,cache:a,referrerPolicy:i})}return await en(URL.parse(t,document.baseURI),{signal:l,method:n,formData:o,state:r,integrity:s,cache:a,referrerPolicy:i})}async function tn(r,o=e(),{signal:a,method:i="GET",cache:s="default",referrerPolicy:l="no-referrer",formData:c,integrity:u,scrollRestoration:d=null}={}){if(null===r)throw new TypeError("URL cannot be null.");if(a instanceof AbortSignal&&a.aborted)throw a.reason;if(!(r instanceof URL))return await tn(URL.parse(r,document.baseURI),o,{signal:a,method:i,cache:s,referrerPolicy:l,formData:c,integrity:u});if(c instanceof FormData&&ht.includes(i.toUpperCase())){const e=new URLSearchParams(c);for(const[t,n]of e)r.searchParams.append(t,n);return await tn(r,o,{signal:a,method:i,cache:s,referrerPolicy:l,integrity:u})}if(r.href!==location.href)try{const g=e(),f=t(o,g),p=new Ct(Mt,kt.navigate,{detail:{newState:o,oldState:g,oldURL:new URL(location.href),newURL:r,method:i,formData:c}});if(Et.dispatchEvent(p),await p[Lt]())return null;{"string"==typeof d&&(history.scrollRestoration=d),history.pushState(o,"",r);const e=await en(r,{signal:a,method:i,cache:s,referrerPolicy:l,formData:c,state:o,integrity:u});return await n(f),Wt(e),e}}catch(e){nn(),reportError(e)}}async function nn({signal:e}={}){const t=new Ct(Mt,kt.back);Et.dispatchEvent(t),await t[Lt]().then((async t=>{t||(history.back(),await En({signal:e,reasons:[kt.load]}))}))}async function rn({signal:e}={}){const t=new Ct(Mt,kt.forward);Et.dispatchEvent(t),await t[Lt]().then((async t=>{t||(history.forward(),await En({signal:e,reasons:[kt.load]}))}))}async function on(e=0,{signal:t}={}){const n=new Ct(Mt,kt.go);Et.dispatchEvent(n),await n[Lt]().then((async n=>{n||(history.go(e),await En({signal:t,reasons:[kt.load]}))}))}function an(){const e=new Ct(Mt,kt.reload);Et.dispatchEvent(e),e[Lt]().then((e=>{e||history.go(0)}))}function sn({signal:e}={}){globalThis.addEventListener("popstate",Ht,{signal:e})}function ln(){globalThis.removeEventListener("popstate",Ht)}function cn(e="auto"){history.scrollRestoration=e}function un(){return history.scrollRestoration}function dn(e){"string"==typeof e&&(document.title=e)}function gn(e){if("string"==typeof e&&0!==e.length){document.head.querySelectorAll(yt).forEach((e=>e.remove())),document.head.append(Ft({name:"description",content:e}),Ft({itemprop:"description",content:e}),Ft({property:"og:description",content:e}),Ft({name:"twitter:description",content:e}))}}async function fn(e,{preload:t=!1,observePreloads:n=!1,inteceptRoot:r=document.body,baseURL:o=location.origin,crossOrigin:a="anonymous",referrerPolicy:i="no-referrer",fetchPriority:s="low",as:l="script",scrollRestoration:c="manual",notFound:u,rootEl:d,transition:{keyframes:g,options:{duration:f=150,easing:p="ease-out",delay:m=0,composite:h="replace",fill:y="both"}={}}={},signal:b}={}){if("string"==typeof e)await fn(document.querySelector(e),{preload:t,observePreloads:n,inteceptRoot:r,baseURL:o,notFound:u,rootEl:d,transition:{keyframes:g,options:{duration:f,easing:p,delay:m,composite:h,fill:y}},signal:b});else if(e instanceof HTMLScriptElement&&"application/json"===e.type)await fn(JSON.parse(e.textContent),{preload:t,observePreloads:n,inteceptRoot:r,baseURL:o,notFound:u,rootEl:d,transition:{keyframes:g,options:{duration:f,easing:p,delay:m,composite:h,fill:y}},signal:b});else{if("object"!=typeof e||null===e||Object.getPrototypeOf(e)!==Object.prototype)throw new TypeError("Routes must be a plain object, a script with JSON, or the selector to such a script.");if("string"==typeof r)fn(e,{preload:t,observePreloads:n,inteceptRoot:document.querySelector(r),baseURL:o,notFound:u,rootEl:Tt,signal:b});else if("string"==typeof d)fn(e,{preload:t,observePreloads:n,inteceptRoot:r,baseURL:o,notFound:u,rootEl:document.querySelector(d),transition:{keyframes:g,options:{duration:f,easing:p,delay:m,composite:h,fill:y}},signal:b});else{if(!(r instanceof HTMLElement||r instanceof ShadowRoot))throw new TypeError("`interceptRoot` must be a selector, HTMLElement, or ShadowRoot.");if(!(d instanceof HTMLElement||d instanceof ShadowRoot))throw new TypeError("`rootEl` must be a selector, HTMLElement, or ShadowRoot.");{const s={preload:t,signal:b,crossOrigin:a,referrerPolicy:i,baseURL:o},l=Object.entries(e).map((([e,t])=>Yt(e,t,s)));n&&Pn(r),"string"==typeof u&&(Vt(u),t&&pn(u)),d instanceof HTMLElement||d instanceof ShadowRoot||"string"==typeof d?Jt(d):Tt instanceof HTMLElement&&"string"!=typeof Tt.ariaLive&&(Tt.ariaLive="assertive"),(r instanceof HTMLElement||r instanceof ShadowRoot||"string"==typeof r)&&Qt(r,{signal:b});const w=await en(new URL(location.href));if(cn(c),Wt(w),sn({signal:b}),"object"==typeof g&&null!==g){const e=[kt.navigate,kt.go,kt.back,kt.forward];Et.addEventListener(Mt,(t=>{!t.defaultPrevented&&e.includes(t.reason)?t.waitUntil((()=>Tt.animate(g,{duration:f,easing:p,fill:y,delay:m,composite:h,direction:"normal"}).finished),{signal:b}):t.reason===kt.load&&t.waitUntil((()=>Tt.animate(g,{duration:f,easing:p,fill:y,delay:m,composite:h,direction:"reverse"}).finished),{signal:b})}),{signal:b})}await Promise.allSettled(l).then((e=>{const t=e.filter((e=>"rejected"===e.status));if(1===t.length)throw t[0].reason;if(0!==t.length)throw new AggregateError(t.map((e=>e.reason)),"Error initializing module routes.")}))}}}return vn({signal:b})}async function pn(e,{crossOrigin:t="anonymous",referrerPolicy:n="no-referrer",fetchPriority:r="low",as:o="script",signal:a=AbortSignal.timeout(5e3),integrity:i}={}){await jt(e,{relList:["modulepreload"],crossOrigin:t,referrerPolicy:n,fetchPriority:r,as:o,signal:a,integrity:i})}async function mn(e,{crossOrigin:t="anonymous",referrerPolicy:n="no-referrer",fetchPriority:r="auto",signal:o=AbortSignal.timeout(5e3),as:a,integrity:i,media:s,type:l}={}){await jt(e,{relList:["preload"],crossOrigin:t,referrerPolicy:n,fetchPriority:r,as:a,signal:o,type:l,media:s,integrity:i})}function hn(e,{referrerPolicy:t="no-referrer"}={}){const n=document.createElement("link");n.referrerPolicy=t,n.relList.add("prefetch"),n.href=e,document.head.append(n)}async function yn(e,{crossOrigin:t="anonymous",referrerPolicy:n="no-referrer"}={}){const r=e instanceof URL?e:URL.parse(e);if(!(r instanceof URL))throw new TypeError(`Invalid origin: ${e}.`);if(r.href!==`${r.origin}/`)throw new TypeError("Preconnect requires only the origin of a URL.");await jt(r.origin,{relList:["preconnect"],crossOrigin:t,referrerPolicy:n,fetchPriority:null,signal:null})}async function bn(e){const t=URL.parse(e);t instanceof URL&&t.origin===`${t.origin}/`&&await jt(e,{relList:["dns-prefetch"],crossOrigin:null,referrerPolicy:null,fetchPriority:null,signal:null})}function wn({signal:e,reasons:t=Ot}={}){if("string"==typeof t)return wn({signal:e,reasons:[t]});if(Array.isArray(t)&&0!==t.length){if(e instanceof AbortSignal&&e.aborted)throw e.reason;{const n=new AbortController;return e instanceof AbortSignal&&e.addEventListener("abort",(({target:e})=>{n.abort(e.reason)}),{once:!0,signal:n.signal}),Et.addEventListener(Mt,(e=>{t.includes(e.reason)&&setTimeout(n.abort.bind(n),50,`Navigated away from ${location.href}.`)}),{passive:!0,signal:n.signal}),n}}throw new TypeError("`reasosn` must be an array of reasons for the naviation event.")}function vn({signal:e,reasons:t=Ot}={}){return wn({signal:e,reasons:t}).signal}async function En({signal:e,reasons:t=Ot}={}){const{resolve:n,reject:r,promise:o}=Promise.withResolvers();if("string"==typeof t)return En({signal:e,reasons:[t]});if(e instanceof AbortSignal&&e.aborted)r(e.reason);else if(Array.isArray(t)&&0!==t.length){const o=new AbortController;document.addEventListener(Mt,(e=>{t.includes(e.reason)&&(n(new URL(location.href)),o.abort())}),{signal:o.signal}),e instanceof AbortSignal&&e.addEventListener("abort",(({target:e})=>{r(e.reason),o.abort(e.reason)}),{once:!0,signal:o.signal})}else r(new TypeError("`reasosn` must be an array of reasons for the naviation event."));return o}async function Ln(e,{crossOrigin:t="anonymous",referrerPolicy:n="no-referrer",fetchPriority:r="high",signal:o}={}){const{resolve:a,reject:i,promise:s}=Promise.withResolvers();"string"==typeof e?await Promise.all(Array.from(document.querySelectorAll(e),(e=>Ln(e)))).then(a,i):e instanceof HTMLElement&&!e.classList.contains("no-router")&&"string"==typeof e.href&&e.origin===location.origin&&0===e.download.length&&URL.canParse(e.href)?e.addEventListener("mouseover",(async({currentTarget:e})=>{const i=Gt(e.href);i instanceof URLPattern?(await pn(mt.get(i),{fetchPriority:r,referrerPolicy:n,crossOrigin:t,integrity:e.dataset.integrity,signal:o}),a()):(await mn(e.href,{fetchPriority:r,crossOrigin:t,referrerPolicy:n,as:e.dataset.preloadAs??"fetch",type:e.dataset.preloadType??"text/html",integrity:e.dataset.integrity,signal:o}),a())}),{once:!0,passive:!0,signal:o}):a(),await s}function Pn(e,t=document.documentElement){if("string"==typeof e)Pn(t.querySelector(e));else{if(!(e instanceof HTMLElement||e instanceof ShadowRoot))throw new TypeError("`observePreloadsOn` requires a selector or HTMLElement or ShadowRoot.");wt.observe(e,{childList:!0,subtree:!0}),At(e)}}function Tn(e,t=document.documentElement){if("string"==typeof e)Tn(t.querySelector(e));else{if(!(e instanceof HTMLElement||e instanceof ShadowRoot))throw new TypeError("`observe` requires a selector or HTMLElement or ShadowRoot.");Qt(e),Pn(e)}}async function Rn({signal:e}={}){const{resolve:t,promise:n,reject:r}=Promise.withResolvers(),o=new AbortController,a=new AbortController;return e instanceof AbortSignal&&(e.aborted?r(e.reason):e.addEventListener("abort",(({target:e})=>{r(e.reason),o.abort(e.reason),a.abort(e.reason)}),{signal:a.signal})),Et.addEventListener(Mt,(e=>{if([kt.navigate,kt.back,kt.forward,kt.go].includes(e.reason)){o.abort();const e=performance.now();Et.addEventListener(Mt,(n=>{n.reason===kt.load&&(t(performance.now()-e),a.abort())}),{signal:a.signal})}}),{signal:o.signal}),n}export{Ct as AegisNavigationEvent,kt as EVENT_TYPES,Mt as NAV_EVENT,sn as addPopstateListener,nn as back,Zt as clearPaths,bn as dnsPrefetch,Gt as findPath,rn as forward,en as getModule,wn as getNavController,vn as getNavSignal,un as getScrollRestoration,Xt as getURLPath,_t as getURLPattern,on as go,fn as init,Kt as interceptNav,tn as navigate,Tn as observe,Qt as observeLinksOn,Pn as observePreloadsOn,yn as preconnect,hn as prefetch,mn as preload,pn as preloadModule,Ln as preloadOnHover,Yt as registerPath,an as reload,ln as removeListener,Vt as set404,gn as setDescription,Jt as setRoot,cn as setScrollRestoration,dn as setTitle,Rn as timeNavigation,a as url,En as whenNavigated};
//# sourceMappingURL=router.mjs.map