@aegisjsproject/core
Version:
A fast, secure, modern, light-weight, and simple JS library for creating web components and more!
11 lines • 115 kB
JavaScript
let e=!0;const t=(e,t=document)=>t.querySelectorAll(e),r=(e,t=document)=>t.querySelector(e),n={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"}},o=new Map([[n.debug.log,console.log],[n.debug.warn,console.warn],[n.debug.error,console.error],[n.debug.info,console.info],[n.navigate.back,()=>history.back()],[n.navigate.forward,()=>history.forward()],[n.navigate.reload,()=>history.go(0)],[n.navigate.close,()=>globalThis.close()],[n.navigate.link,e=>{e.isTrusted&&(e.preventDefault(),location.href=e.currentTarget.dataset.url)}],[n.navigate.popup,e=>{e.isTrusted&&(e.preventDefault(),globalThis.open(e.currentTarget.dataset.url))}],[n.ui.hide,({currentTarget:e})=>{t(e.dataset.hideSelector).forEach((e=>e.hidden=!0))}],[n.ui.unhide,({currentTarget:e})=>{t(e.dataset.unhideSelector).forEach((e=>e.hidden=!1))}],[n.ui.disable,({currentTarget:e})=>{t(e.dataset.disableSelector).forEach((e=>e.disabled=!0))}],[n.ui.enable,({currentTarget:e})=>{t(e.dataset.enableSelector).forEach((e=>e.disabled=!1))}],[n.ui.remove,({currentTarget:e})=>{t(e.dataset.removeSelector).forEach((e=>e.remove()))}],[n.ui.scrollTo,({currentTarget:e})=>{const t=r(e.dataset.scrollToSelector);t instanceof Element&&t.scrollIntoView({behavior:matchMedia("(prefers-reduced-motion: reduce)").matches?"instant":"smooth"})}],[n.ui.revokeObjectURL,({currentTarget:e})=>URL.revokeObjectURL(e.src)],[n.ui.cancelAnimationFrame,({currentTarget:e})=>cancelAnimationFrame(parseInt(e.dataset.animationFrame))],[n.ui.clearInterval,({currentTarget:e})=>clearInterval(parseInt(e.dataset.clearInterval))],[n.ui.clearTimeout,({currentTarget:e})=>clearTimeout(parseInt(e.dataset.timeout))],[n.ui.abortController,({currentTarget:e})=>function(e,t){const r=wt(e);return r instanceof AbortController&&("string"==typeof t?(r.abort(new Error(t)),!0):(r.abort(t),!0))}(e.dataset.aegisEventController,e.dataset.aegisControllerReason)],[n.ui.showModal,({currentTarget:e})=>{const t=r(e.dataset.showModalSelector);t instanceof HTMLDialogElement&&t.showModal()}],[n.ui.closeModal,({currentTarget:e})=>{const t=r(e.dataset.closeModalSelector);t instanceof HTMLDialogElement&&t.close()}],[n.ui.showPopover,({currentTarget:e})=>{const t=r(e.dataset.showPopoverSelector);t instanceof HTMLElement&&t.showPopover()}],[n.ui.hidePopover,({currentTarget:e})=>{const t=r(e.dataset.hidePopoverSelector);t instanceof HTMLElement&&t.hidePopover()}],[n.ui.togglePopover,({currentTarget:e})=>{const t=r(e.dataset.togglePopoverSelector);t instanceof HTMLElement&&t.togglePopover()}],[n.ui.print,()=>globalThis.print()],[n.ui.prevent,e=>e.preventDefault()]]),a=()=>e=!1,i=()=>Object.freeze(Array.from(o.keys())),s=e=>o.has(e),c=e=>o.get(e),l=e=>u("aegis:callback:"+crypto.randomUUID(),e);function d(e,...t){if(o.has(e))return o.get(e).apply(this||globalThis,t);throw new Error(`No ${e} function registered.`)}function u(t,r){if("string"!=typeof t||0===t.length)throw new TypeError("Callback name must be a string.");if(r instanceof Function){if(e){if(o.has(t))throw new Error(`Handler "${t}" is already registered.`);return o.set(t,r),t}throw new TypeError("Cannot register new callbacks because registry is closed.")}throw new TypeError("Callback must be a function.")}function g(e){return e instanceof Event?g(e.currentTarget):e instanceof Document?e:e instanceof Element?g(e.getRootNode()):e instanceof ShadowRoot?e.host:null}const f="data-aegis-event-",p=f+"on-",m="aegisEventOn",h=12,b=Symbol("aegis:signal"),y=Symbol("aegis:controller"),v=new Map,w=new Map,S=f+"once",T=f+"passive",E=f+"capture",L=f+"signal",k=p+"abort",A=p+"blur",R=p+"focus",$=p+"cancel",M=p+"auxclick",P=p+"beforeinput",U=p+"beforetoggle",C=p+"canplay",x=p+"canplaythrough",N=p+"change",O=p+"click",F=p+"close",D=p+"contextmenu",H=p+"copy",j=p+"cuechange",I=p+"cut",z=p+"dblclick",q=p+"drag",B=p+"dragend",V=p+"dragenter",_=p+"dragexit",W=p+"dragleave",G=p+"dragover",X=p+"dragstart",K=p+"drop",Q=p+"durationchange",J=p+"emptied",Y=p+"ended",Z=p+"formdata",ee=p+"input",te=p+"invalid",re=p+"keydown",ne=p+"keypress",oe=p+"keyup",ae=p+"load",ie=p+"loadeddata",se=p+"loadedmetadata",ce=p+"loadstart",le=p+"mousedown",de=p+"mouseenter",ue=p+"mouseleave",ge=p+"mousemove",fe=p+"mouseout",pe=p+"mouseover",me=p+"mouseup",he=p+"wheel",be=p+"paste",ye=p+"pause",ve=p+"play",we=p+"playing",Se=p+"progress",Te=p+"ratechange",Ee=p+"reset",Le=p+"resize",ke=p+"scroll",Ae=p+"scrollend",Re=p+"securitypolicyviolation",$e=p+"seeked",Me=p+"seeking",Pe=p+"select",Ue=p+"slotchange",Ce=p+"stalled",xe=p+"submit",Ne=p+"suspend",Oe=p+"timeupdate",Fe=p+"volumechange",De=p+"waiting",He=p+"selectstart",je=p+"selectionchange",Ie=p+"toggle",ze=p+"pointercancel",qe=p+"pointerdown",Be=p+"pointerup",Ve=p+"pointermove",_e=p+"pointerout",We=p+"pointerover",Ge=p+"pointerenter",Xe=p+"pointerleave",Ke=p+"gotpointercapture",Qe=p+"lostpointercapture",Je=p+"mozfullscreenchange",Ye=p+"mozfullscreenerror",Ze=p+"animationcancel",et=p+"animationend",tt=p+"animationiteration",rt=p+"animationstart",nt=p+"transitioncancel",ot=p+"transitionend",at=p+"transitionrun",it=p+"transitionstart",st=p+"webkitanimationend",ct=p+"webkitanimationiteration",lt=p+"webkitanimationstart",dt=p+"webkittransitionend",ut=p+"error",gt=[k,A,R,$,M,P,U,C,x,N,O,F,D,H,j,I,z,q,B,V,_,W,G,X,K,Q,J,Y,Z,ee,te,re,ne,oe,ae,ie,se,ce,le,de,ue,ge,fe,pe,me,he,be,ye,ve,we,Se,Te,Ee,Le,ke,Ae,Re,$e,Me,Pe,Ue,Ce,xe,Ne,Oe,Fe,De,He,je,Ie,ze,qe,Be,Ve,_e,We,Ge,Xe,Ke,Qe,Je,Ye,Ze,et,tt,rt,nt,ot,at,it,st,ct,lt,dt,ut];let ft=gt.map((e=>`[${CSS.escape(e)}]`)).join(", ");const pt=([e])=>e.startsWith(m);function mt(e,{signal:t,attrFilter:r=bt}={}){const n=e.dataset;for(const[o,a]of Object.entries(n).filter(pt))try{const i="on"+o.substring(h);r.hasOwnProperty(i)&&s(a)&&e.addEventListener(i.substring(2).toLowerCase(),c(a),{passive:n.hasOwnProperty("aegisEventPassive"),capture:n.hasOwnProperty("aegisEventCapture"),once:n.hasOwnProperty("aegisEventOnce"),signal:n.hasOwnProperty("aegisEventSignal")?Tt(n.aegisEventSignal):t})}catch(e){reportError(e)}}const ht=new MutationObserver((e=>{e.forEach((e=>{switch(e.type){case"childList":[...e.addedNodes].filter((e=>e.nodeType===Node.ELEMENT_NODE)).forEach((e=>Et(e)));break;case"attributes":"string"==typeof e.oldValue&&s(e.oldValue)&&e.target.removeEventListener(e.attributeName.substring(20),c(e.oldValue),{once:e.target.hasAttribute(S),capture:e.target.hasAttribute(E),passive:e.target.hasAttribute(T)}),e.target.hasAttribute(e.attributeName)&&s(e.target.getAttribute(e.attributeName))&&e.target.addEventListener(e.attributeName.substring(20),c(e.target.getAttribute(e.attributeName)),{once:e.target.hasAttribute(S),capture:e.target.hasAttribute(E),passive:e.target.hasAttribute(T),signal:e.target.hasAttribute(L)?Tt(e.target.getAttribute(L)):void 0})}}))})),bt={onAbort:k,onBlur:A,onFocus:R,onCancel:$,onAuxclick:M,onBeforeinput:P,onBeforetoggle:U,onCanplay:C,onCanplaythrough:x,onChange:N,onClick:O,onClose:F,onContextmenu:D,onCopy:H,onCuechange:j,onCut:I,onDblclick:z,onDrag:q,onDragend:B,onDragenter:V,onDragexit:_,onDragleave:W,onDragover:G,onDragstart:X,onDrop:K,onDurationchange:Q,onEmptied:J,onEnded:Y,onFormdata:Z,onInput:ee,onInvalid:te,onKeydown:re,onKeypress:ne,onKeyup:oe,onLoad:ae,onLoadeddata:ie,onLoadedmetadata:se,onLoadstart:ce,onMousedown:le,onMouseenter:de,onMouseleave:ue,onMousemove:ge,onMouseout:fe,onMouseover:pe,onMouseup:me,onWheel:he,onPaste:be,onPause:ye,onPlay:ve,onPlaying:we,onProgress:Se,onRatechange:Te,onReset:Ee,onResize:Le,onScroll:ke,onScrollend:Ae,onSecuritypolicyviolation:Re,onSeeked:$e,onSeeking:Me,onSelect:Pe,onSlotchange:Ue,onStalled:Ce,onSubmit:xe,onSuspend:Ne,onTimeupdate:Oe,onVolumechange:Fe,onWaiting:De,onSelectstart:He,onSelectionchange:je,onToggle:Ie,onPointercancel:ze,onPointerdown:qe,onPointerup:Be,onPointermove:Ve,onPointerout:_e,onPointerover:We,onPointerenter:Ge,onPointerleave:Xe,onGotpointercapture:Ke,onLostpointercapture:Qe,onMozfullscreenchange:Je,onMozfullscreenerror:Ye,onAnimationcancel:Ze,onAnimationend:et,onAnimationiteration:tt,onAnimationstart:rt,onTransitioncancel:nt,onTransitionend:ot,onTransitionrun:at,onTransitionstart:it,onWebkitanimationend:st,onWebkitanimationiteration:ct,onWebkitanimationstart:lt,onWebkittransitionend:dt,onError:ut,once:S,passive:T,capture:E};function yt(e,{addListeners:t=!1,base:r=document.body,signal:n}={}){const o=p+e.toLowerCase();if(!gt.includes(o)){const e=`[${CSS.escape(o)}]`,a=(e=>`on${e[20].toUpperCase()}${e.substring(21)}`)(o);gt.push(o),bt[a]=o,ft+=`, ${e}`,t&&requestAnimationFrame((()=>{const t={attrFilter:{[a]:e},signal:n};[r,...r.querySelectorAll(e)].forEach((e=>mt(e,t)))}))}return o}function vt(e){return e instanceof AbortController?w.delete(e.signal[y]):e instanceof AbortSignal?w.delete(e[y]):w.delete(e)}const wt=e=>w.get(e);function St(e){if(e instanceof AbortSignal){if("string"==typeof e[b])return e[b];{const t="aegis:event:signal:"+crypto.randomUUID();return Object.defineProperty(e,b,{value:t,writable:!1,enumerable:!1}),v.set(t,e),e.addEventListener("abort",(({target:e})=>function(e){if(e instanceof AbortSignal)return v.delete(e[b]);if("string"==typeof e)return v.delete(e);throw new TypeError("Signal must be an `AbortSignal` or registered key/attribute.")}(e[b])),{once:!0}),t}}throw new TypeError("Signal must be an `AbortSignal`.")}const Tt=e=>v.get(e);function Et(e,{signal:t}={}){return(e instanceof Element&&e.matches(ft)?[e,...e.querySelectorAll(ft)]:e.querySelectorAll(ft)).forEach((e=>mt(e,{signal:t}))),e}function Lt(e=document){Et(e),ht.observe(e,{subtree:!0,childList:!0,attributes:!0,attributeOldValue:!0,attributeFilter:gt})}const kt=()=>ht.disconnect();function At(e,{capture:t,once:r,passive:n,signal:o}={}){if(!(e instanceof Function))throw new TypeError("Callback is not a function.");globalThis.addEventListener("error",e,{capture:t,once:r,passive:n,signal:o})}const Rt=e=>{switch(typeof e){case"undefined":return"";case"boolean":return e?"true":"false";case"object":return null===e?"":e instanceof CSSStyleSheet?[...e.cssRules].map((e=>e.cssText)).join("\n\n"):e instanceof CSSRule?e.cssText:e instanceof HTMLLinkElement?Rt(e.sheet):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 $t(e,{media:t,disabled:r,baseURL:n}={}){const o=new CSSStyleSheet({media:t instanceof MediaQueryList?t.media:t,disabled:r,baseURL:n});return o.replace(e).catch(reportError),o}const Mt=({media:e,disabled:t,baseURL:r,sync:n=!1}={})=>n?(n,...o)=>function(e,{media:t,disabled:r,baseURL:n}={}){const o=new CSSStyleSheet({media:t instanceof MediaQueryList?t.media:t,disabled:r,baseURL:n});return o.replaceSync(e),o}(String.raw(n,...o.map(Rt)).trim(),{media:e,disabled:t,baseURL:r}):(n,...o)=>$t(String.raw(n,...o.map(Rt)).trim(),{media:e,disabled:t,baseURL:r}),Pt=Mt(),Ut=Mt({media:"(prefers-color-scheme: light)",baseURL:document.baseURI}),Ct=Mt({media:"(prefers-color-scheme: dark)",baseURL:document.baseURI});function xt(e,t="styles.css"){if(e instanceof CSSStyleSheet){const r=Array.from(e.cssRules,(e=>e.cssText));return new File(r,t,{type:e.type})}throw new TypeError("Not a CSSStyleSheet.")}function Nt(e){const t=xt(e),r=document.createElement("link");return r.relList.add("stylesheet"),r.disabled=e.disabled,0!==e.media.length&&(r.media=e.media.mediaText),r.href=URL.createObjectURL(t),r}const Ot=/&(?![a-zA-Z\d]{2,5};|#\d{1,3};)/g,Ft=e=>e.toString().replaceAll(Ot,"&").replaceAll('"',""");function Dt(e,t="",r){const n="string"==typeof r?document.createAttributeNS(r,e):document.createAttribute(e);return n.value=t,n}const Ht=e=>`${e.name}="${Ft(e.value)}"`,jt=e=>e.toString().replaceAll(Ot,"&").replaceAll("<","<").replaceAll(">",">").replaceAll('"',"""),It=(e="_aegis-scope")=>`${e}-${crypto.randomUUID()}`;function zt(e,...t){if(!(e instanceof Node))throw new TypeError("Expected target to be a Document, DocumentFragment, ShadowRoot, or Element.");if(!(e instanceof Document||e instanceof ShadowRoot)){if(e instanceof Element||DocumentFragment){if(e.shadowRoot instanceof ShadowRoot)return zt(e.shadowRoot,...t);if(e.isConnected)return zt(e.getRootNode({composed:!1}),...t);throw new TypeError("Target is not connected to the document yet.")}throw new TypeError("Expected target to be a Document, DocumentFragment, ShadowRoot, or Element.")}e.adoptedStyleSheets=t}function qt(e,...t){if(!(e instanceof Node))throw new TypeError("Expected target to be a Document, DocumentFragment, ShadowRoot, or Element.");if(!(e instanceof Document||e instanceof ShadowRoot))return e.shadowRoot instanceof ShadowRoot?qt(e.shadowRoot,...t):qt(e.getRootNode({composed:!1}),...t);zt(e,...e.adoptedStyleSheets,...t)}function Bt(e,...t){if(!(e instanceof Node))throw new TypeError("Target must be a Node.");{const r=t.filter((e=>e instanceof CSSStyleSheet)),n=t.filter((e=>"string"==typeof e||e instanceof Node));0!==r.length&&qt(e,...r),0!==n.length&&e.append(...n),Et(e instanceof ShadowRoot?e.host:e)}}function Vt(e,...t){if(!(e instanceof Node))throw new TypeError("Target must be a Node.");{const r=t.filter((e=>e instanceof CSSStyleSheet)),n=t.filter((e=>"string"==typeof e||e instanceof Node));0!==r.length&&qt(e,...r),0!==n.length&&e.prepend(...n),Et(e instanceof ShadowRoot?e.host:e)}}function _t(e,...t){if(!(e instanceof Node))throw new TypeError("Target must be a Node.");{const r=t.filter((e=>e instanceof CSSStyleSheet)),n=t.filter((e=>"string"==typeof e||e instanceof Node));0!==r.length&&zt(e,...r),0!==n.length&&e.replaceChildren(...n),Et(e instanceof ShadowRoot?e.host:e)}}const Wt=([e,t])=>["data-"+e.replaceAll(/[A-Z]/g,(e=>`-${e.toLowerCase()}`)),t],Gt=e=>Object.entries(e).map((([e,t])=>{switch(typeof t){case"string":return Dt(e,t);case"number":case"bigint":return Number.isNaN(t)?void 0:Dt(e,t.toString());case"boolean":return t?Dt(e):void 0;case"undefined":return;case"function":return l(t);case"object":return null===t?void 0:t instanceof URL?Dt(e,t.href):t instanceof Date?Dt(e,t.toISOString()):Dt(e,t.toString());case"symbol":return Dt(e,t.description);default:return Dt(e,t.toString())}})).filter((e=>e instanceof Attr)).map(Ht).join(" ");function Xt(e){return Gt(Object.fromEntries(Object.entries(e).map(Wt)))}const Kt={weekday:"short",month:"short",day:"numeric",year:"numeric",hour:"numeric",minute:"2-digit"},Qt=(e,{weekday:t=Kt.weekday,month:r=Kt.month,day:n=Kt.day,year:o=Kt.year,hour:a=Kt.hour,minute:i=Kt.minute}=Kt)=>e.toLocaleString(navigator.language,{weekday:t,month:r,day:n,year:o,hour:a,minute:i}),Jt="Intl"in globalThis&&Intl.ListFormat instanceof Function?e=>(new Intl.ListFormat).format(e.map(Zt)):e=>e.join(", "),Yt="Intl"in globalThis&&Intl.NumberFormat instanceof Function?e=>(new Intl.NumberFormat).format(e):e=>e.toString(),Zt=e=>{switch(typeof e){case"string":return e;case"boolean":return e?"true":"false";case"symbol":return e.description;case"number":case"bigint":return Yt(e);case"undefined":return"";case"function":return l(e);case"object":if(null===e)return"";if(Array.isArray(e))return Jt(e);if(e instanceof HTMLTemplateElement){const t=document.createElement("div");return t.append(e.content.cloneNode(!0)),t.innerHTML}if(e instanceof Element)return e.outerHTML;if(e instanceof DocumentFragment){const t=document.createElement("div");return t.append(e.cloneNode(!0)),t.innerHTML}return e instanceof Blob?URL.createObjectURL(e):e instanceof Date?Qt(e):e instanceof CSSStyleSheet?Nt(e).outerHTML:e instanceof DOMTokenList?[...e].join(" "):e instanceof NodeList||e instanceof HTMLCollection||e instanceof HTMLFormControlsCollection?[...e].map((e=>e.outerHTML)).join("\n"):e instanceof MediaList?e.mediaText:e instanceof Attr?Ht(e):e instanceof NamedNodeMap?Array.from(e,Ht).join(" "):"TrustedType"in globalThis&&e instanceof globalThis.TrustedType?e:"Iterator"in globalThis&&e instanceof globalThis.Iterator?Zt([...e]):e instanceof AbortSignal?St(e):e instanceof AbortController?function(e){if(e instanceof AbortController){if(e.signal.aborted)throw e.signal.reason;if("string"==typeof e.signal[y])return e.signal[y];{const t="aegis:event:controller:"+crypto.randomUUID();return Object.defineProperty(e.signal,y,{value:t,writable:!1,enumerable:!1}),w.set(t,e),e.signal.addEventListener("abort",vt,{once:!0}),t}}throw new TypeError("Controller is not an `AbortSignal.")}(e):e.toString();default:return e.toString()}},er=(e,...t)=>Array.isArray(e)&&Array.isArray(e.raw)?String.raw(e,...t.map(Zt)):String.raw({raw:Array.isArray(e)?e:[e]},...t.map(Zt))
/**
* @copyright 2023-2024 Chris Zuber <admin@kernvalley.us>
*/,tr="http://www.w3.org/1999/xhtml",rr="http://www.w3.org/1999/xlink";function nr(e,t=tr){if("string"==typeof e)return Object.freeze({name:e,namespace:t});if("object"==typeof e&&"string"==typeof e.name){const{name:r,namespace:n=t,attributes:o}=e;return Object.freeze({name:r,namespace:"string"==typeof n&&0!==n.length?n:t,attributes:o})}throw new TypeError("Invalid config entry for `elements`.")}function or(e,t){if("string"==typeof e)return Object.freeze({name:e,namespace:t});if("object"==typeof e&&"string"==typeof e.name){const{name:r,namespace:n=t,elements:o,...a}=e;return Object.freeze({name:r,namespace:"string"==typeof n?n:t,elements:o,...a})}throw new TypeError("Invalid entry in `attributes` config.")}new Set(("HTMLElement"in globalThis?Object.keys(HTMLElement.prototype):[]).filter((e=>e.startsWith("on"))));const ar=Object.freeze(["accesskey","autocapitalize","autofocus","class","contenteditable","dir","draggable","enterkeyhint","exportparts","hidden","id","inert","inputmode","itemid","itemprop","itemref","itemscope","itemtype","lang","part","popover","slot","spellcheck","tabindex","title","translate","virtualkeyboardpolicy","aria-keyshortcuts","aria-activedescendant","aria-atomic","aria-autocomplete","aria-braillelabel","aria-brailleroledescription","aria-busy","aria-checked","aria-colcount","aria-colindex","aria-colindextext","aria-colspan","aria-controls","aria-current","aria-describedby","aria-description","aria-details","aria-disabled","aria-dropeffect","aria-errormessage","aria-expanded","aria-flowto","aria-grabbed","aria-haspopup","aria-hidden","aria-invalid","aria-keyshortcuts","aria-label","aria-labelledby","aria-level","aria-live","aria-modal","aria-multiline","aria-multiselectable","aria-orientation","aria-owns","aria-placeholder","aria-posinset","aria-pressed","aria-readonly","aria-relevant","aria-required","aria-roledescription","aria-rowcount","aria-rowindex","aria-rowindextext","aria-rowspan","aria-selected","aria-setsize","aria-sort","aria-valuemax","aria-valuemin","aria-valuenow","aria-valuetext"].map((e=>or(e)))),ir=Object.freeze(["html","head","link","meta","body","address","article","aside","footer","header","h1","h2","h3","h4","h5","h6","hgroup","main","nav","section","search","blockquote","cite","div","dd","dt","dl","figcaption","figure","hr","li","ol","ul","menu","p","pre","a","abbr","b","bdi","bdo","br","code","data","dfn","em","i","kbd","mark","q","rp","ruby","rt","s","del","ins","samp","small","span","strong","sub","sup","time","u","var","wbr","area","audio","img","map","track","video","picture","source","canvas","caption","col","colgroup","table","tbody","tr","td","tfoot","th","thead","button","datalist","option","fieldset","label","form","input","legend","meter","optgroup","select","output","progress","textarea","details","summary","dialog","slot","template","dir","strike","selectmenu","center"].map((e=>nr(e,tr)))),sr=Object.freeze(["abbr","accept","accept-charset","align","alink","allow","allowfullscreen","alt","anchor","archive","as","async","autocomplete","autocorrect","autopictureinpicture","autoplay","axis","background","behavior","border","bordercolor","capture","cellpadding","cellspacing","challenge","char","charoff","charset","checked","cite","classid","clear","code","codetype","color","cols","colspan","compact","content","controls","controlslist","conversiondestination","coords","crossorigin","csp","data","datetime","declare","decoding","default","defer","direction","dirname","disabled","disablepictureinpicture","disableremoteplayback","disallowdocumentaccess","download","elementtiming","enctype","end","for","form","formenctype","formmethod","formnovalidate","formtarget","frameborder","headers","height","high","href","hreflang","hreftranslate","hspace","imagesizes","imagesrcset","importance","impressiondata","impressionexpiry","incremental","integrity","invisible","invoketarget","invokeaction","is","ismap","keytype","kind","label","language","latencyhint","leftmargin","link","list","loading","longdesc","loop","low","lowsrc","manifest","marginheight","marginwidth","max","maxlength","mayscript","media","method","min","minlength","multiple","muted","name","nohref","nomodule","noresize","noshade","novalidate","nowrap","object","open","optimum","pattern","ping","placeholder","playsinline","policy","popovertarget","popovertargetaction","poster","preload","pseudo","readonly","referrerpolicy","rel","reportingorigin","required","resources","rev","reversed","role","rows","rowspan","rules","sandbox","scheme","scope","scopes","scrollamount","scrolldelay","scrolling","select","selected","shadowrootclonable","shadowrootdelegatesfocus","shadowrootmode","shadowrootserializable","shape","size","sizes","span","src","srcdoc","srclang","srcset","standby","start","step","summary","target","text","topmargin","truespeed","trusttoken","type","usemap","valign","value","valuetype","version","vlink","vspace","webkitdirectory","width","wrap"].map((e=>or(e))).concat(ar)),cr=Object.freeze(["a","animate","animateMotion","animateTransform","circle","clipPath","defs","desc","ellipse","feBlend","feColorMatrix","feComponentTransfer","feComposite","feConvolveMatrix","feDiffuseLighting","feDisplacementMap","feDistantLight","feDropShadow","feFlood","feFuncA","feFuncB","feFuncG","feFuncR","feGaussianBlur","feImage","feMerge","feMergeNode","feMorphology","feOffset","fePointLight","feSpecularLighting","feSpotLight","feTile","feTurbulence","filter","foreignObject","g","line","linearGradient","marker","mask","metadata","mpath","path","pattern","polygon","polyline","radialGradient","rect","script","set","stop","style","svg","switch","symbol","text","textPath","title","tspan","view","missing-glyph","font","font-face","font-face-format","font-face-name","font-face-src","font-face-uri","hkern","vkern","glyph","glyphRef","tref","cursor","use"].map((e=>nr(e,"http://www.w3.org/2000/svg")))),lr=Object.freeze(["accent-height","accumulate","additive","alignment-baseline","alphabetic","amplitude","arabic-form","ascent","attributeName","attributeType","azimuth","baseFrequency","baseline-shift","baseProfile","bbox","begin","bias","by","calcMode","cap-height","class","clip","clipPathUnits","clip-path","clip-rule","color","color-interpolation","color-interpolation-filters","color-profile","color-rendering","crossorigin","cursor","cx","cy","d","decelerate","descent","diffuseConstant","direction","display","divisor","dominant-baseline","dur","dx","dy","edgeMode","elevation","enable-background","end","exponent","fill","fill-opacity","fill-rule","filter","filterUnits","flood-color","flood-opacity","font-family","font-size","font-size-adjust","font-stretch","font-style","font-variant","font-weight","format","from","fr","fx","fy","g1","g2","glyph-name","glyph-orientation-horizontal","glyph-orientation-vertical","glyphRef","gradientTransform","gradientUnits","hanging","height","href","hreflang","horiz-adv-x","horiz-origin-x","id","ideographic","image-rendering","in","in2","intercept","k","k1","k2","k3","k4","kernelMatrix","kernelUnitLength","kerning","keyPoints","keySplines","keyTimes","lang","lengthAdjust","letter-spacing","lighting-color","limitingConeAngle","local","marker-end","marker-mid","marker-start","markerHeight","markerUnits","markerWidth","mask","maskContentUnits","maskUnits","mathematical","max","media","method","min","mode","name","numOctaves","offset","opacity","operator","order","orient","orientation","origin","overflow","overline-position","overline-thickness","panose-1","paint-order","path","pathLength","patternContentUnits","patternTransform","patternUnits","ping","pointer-events","points","pointsAtX","pointsAtY","pointsAtZ","preserveAlpha","preserveAspectRatio","primitiveUnits","r","radius","referrerPolicy","refX","refY","rel","rendering-intent","repeatCount","repeatDur","requiredExtensions","requiredFeatures","restart","result","rotate","rx","ry","scale","seed","shape-rendering","slope","spacing","specularConstant","specularExponent","speed","spreadMethod","startOffset","stdDeviation","stemh","stemv","stitchTiles","stop-color","stop-opacity","strikethrough-position","strikethrough-thickness","string","stroke","stroke-dasharray","stroke-dashoffset","stroke-linecap","stroke-linejoin","stroke-miterlimit","stroke-opacity","stroke-width","style","surfaceScale","systemLanguage","tabindex","tableValues","target","targetX","targetY","text-anchor","text-decoration","text-rendering","textLength","to","transform","transform-origin","type","u1","u2","underline-position","underline-thickness","unicode","unicode-bidi","unicode-range","units-per-em","v-alphabetic","v-hanging","v-ideographic","v-mathematical","values","vector-effect","version","vert-adv-y","vert-origin-x","vert-origin-y","viewBox","visibility","width","widths","word-spacing","writing-mode","x","x-height","x1","x2","xChannelSelector","y","y1","y2","yChannelSelector","z","zoomAndPan","autoReverse","accelerate","xmlns",{name:"actuate",namespace:rr},{name:"arcrole",namespaec:rr},{name:"href",namespace:rr},{name:"role",namespace:rr},{name:"show",namespace:rr},{name:"title",namespace:rr},{name:"type",namespace:rr},{name:"space",namespace:"http://www.w3.org/XML/1998/namespace"}].map((e=>or(e))).concat(ar)),dr=Object.freeze([...ir,...cr]),ur=Object.freeze(Array.from(new Set([...sr,...lr]))),gr=Object.freeze({elements:dr,attributes:ur,comments:!1,dataAttributes:!0}),fr=new Set;
/**
* @copyright 2023-2024 Chris Zuber <admin@kernvalley.us>
* @see https://wicg.github.io/sanitizer-api/#default-configuration-dictionary
*/function pr(e,t,r){if(fr.has(e))throw new Error(`<${e}> is already registered.`);return customElements.define(e,t,r),fr.add(e),t}function mr(){return Object.freeze(Array.from(fr))}function hr(){return Object.freeze(Array.from(fr,(e=>customElements.get(e))))}const br=e=>Array.from(e[Symbol.iterator](),(e=>e.nodeType===Node.ELEMENT_NODE?e.outerHTML:e.textContent)).join("");function yr(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 DocumentFragment||e instanceof Document?br(e.childNodes):e instanceof NodeList||e instanceof HTMLCollection?br(e):e instanceof Element?e.outerHTML:e instanceof Date?e.toISOString():Array.isArray(e)?e.map(yr).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 vr(e=gr,{mapper:t=yr}={}){return(r,...n)=>{const o=document.createDocumentFragment(),a=document.createElement("div");return a.setHTML(String.raw(r,...n.map(t)).trim(),e),o.append(...a.childNodes),o}}function wr(e,...t){return Document.parseHTML(String.raw(e,...t.map(yr)),gr)}const Sr=vr(Object.freeze({...gr,get elements(){return[...gr.elements,...mr()]},get attributes(){return["theme",...gr.attributes]}}),{mapper:Zt});function Tr(e,...t){const r=String.raw(e,...t.map(Zt)),n=document.createDocumentFragment(),o=document.createElement("div");return o.setHTMLUnsafe(r),n.append(...o.childNodes),n}function Er(e,...t){const r=String.raw(e,...t.map(Zt));return Document.parseHTMLUnsafe(r)}function Lr(e,t="document.html",{elements:r=gr.elements,attributes:n=gr.attributes,comments:o=gr.comments,...a}=gr){const i=Document.parseHTML(e,{elements:r,attributes:n,comments:o,...a});return new File([`<!DOCTYPE ${i.doctype instanceof Node?i.doctype.name:"html"}>`,i.documentElement.outerHTML],t,{type:i.contentType})}const kr=(...e)=>(new DOMParser).parseFromString(String.raw.apply(null,e).trim(),"application/xml");function Ar(...e){return Document.parseHTML(String.raw.apply(null,e).trim(),{sanitizer:{elements:["html","head","body",...cr],attributes:lr}}).body.firstElementChild}const Rr=(...e)=>JSON.parse(String.raw.apply(null,e).trim()),$r=Object.freeze(["math","maction","annotation","annotation-xml","menclose","merror","mfenced","mfrac","mi","mmultiscripts","mn","mo","mover","mpadded","mphantom","mprescripts","mroot","mrow","ms","semantics","mspace","msqrt","mstyle","msub","msup","msubsup","mtable","mtd","mtext","mtr","munder","munderover"].map((e=>nr(e,"http://www.w3.org/1998/Math/MathML")))),Mr=Object.freeze(["accent","accentunder","actiontype","align","background","close","color","columnalign","columnlines","columnspacing","columnspan","denomalign","depth","dir","display","displaystyle","fence","fontfamily","fontsize","fontstyle","fontweight","frame","framespacing","height","href","id","linethickness","lspace","lquote","mathbackground","mathcolor","mathsize","mathvariant","maxsize","minsize","movablelimits","notation","numalign","open","rowalign","rowlines","rowspacing","rowspan","rspace","rquote","scriptlevel","scriptminsize","scriptsizemultiplier","selection","separator","separators","stretchy","subscriptshift","superscriptshift","symmetric","voffset","width","xmlns"].map((e=>or(e))).concat(ar));function Pr(...e){return Document.parseHTML(String.raw.apply(null,e).trim(),{sanitizer:{elements:["html","head","body",...$r],attributes:Mr}}).body.firstElementChild}function Ur(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(Ur).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 Cr(e){return encodeURIComponent(Ur(e).trim()).replaceAll("..%2F","%2E%2E%2F").replaceAll(".%2F","%2E%2E%2F")}const xr=function(e=globalThis?.document?.baseURI){return function(t,r,...n){return r instanceof Blob&&2===t.length&&""===t[0]&&""===t[1]?new URL(URL.createObjectURL(r)):URL.canParse(r)?URL.parse(String.raw(t,"",...n.map(Cr)),r):t[0].startsWith("/")||t[0].startsWith("./")||t[0].startsWith("../")?URL.parse(String.raw(t,Cr(r),...n.map(Cr)),e):URL.parse(String.raw(t,Cr(r),...n.map(Cr)))}}();
/**
* @copyright 2023-2024 Chris Zuber <admin@kernvalley.us>
*/function Nr(e,t,r,{policy:n}={}){switch(Ir(e.tagName,t)){case"TrustedScript":e[t]=Wr(r,{policy:n});break;case"TrustedScriptURL":e[t]=Gr(r,{policy:n});break;case"TrustedHTML":e[t]=_r(r,{policy:n});break;default:e[t]=r}}function Or(e,t,r,{elementNs:n,policy:o}={}){switch(jr(e.tagName,t,n)){case"TrustedScriptURL":"string"==typeof n?e.setAttributeNs(n,t,Gr(r,{policy:o})):e.setAttribute(t,Gr(r,{policy:o}));break;case"TrustedScript":"string"==typeof n?e.setAttributeNS(n,t,Wr(r,{policy:o})):e.setAttribute(t,Wr(r,{policy:o}));break;case"TrustedHTML":"string"==typeof n?e.setAttributeNS(n,t,_r(r,{policy:o})):e.setAttribute(t,_r(r,{policy:o}));break;default:"string"==typeof n?e.setAttributeNS(n,t,r):e.setAttribute(t,r)}}function Fr(){return"trustedTypes"in globalThis&&trustedTypes.createPolicy instanceof Function}function Dr(e){return"TrustedTypePolicy"in globalThis&&e instanceof TrustedTypePolicy||null!=e&&e.createHTML instanceof Function}function Hr(){return Fr()&&Dr(trustedTypes.defaultPolicy)}function jr(e,t,r){return Fr()?trustedTypes.getAttributeType(e.toLowerCase(),t,r):null}function Ir(e,t){return Fr()?trustedTypes.getPropertyType(e.toLowerCase(),t):null}function zr(e){return Fr()?trustedTypes.isHTML(e):"string"==typeof e}function qr(e){return Fr()?trustedTypes.isScript(e):"string"==typeof e}function Br(e){return Fr()?trustedTypes.isScriptURL(e):"string"==typeof e||e instanceof URL}function Vr(e){return!Fr()||(trustedTypes.isHTML(e)||trustedTypes.isScript(e)||trustedTypes.isScriptURL(e))}function _r(e,{policy:t=Qr()}={}){return Dr(t)&&!zr(e)?t.createHTML(e):e}function Wr(e,{policy:t=Qr()}={}){return Dr(t)&&!qr(e)?t.createScript(e):e}function Gr(e,{policy:t=Qr()}={}){return Dr(t)&&!Br(e)?t.createScriptURL(e):e}function Xr(e,{createHTML:t=(()=>{throw new TypeError("This policy does not provide `createHTML()`")}),createScript:r=(()=>{throw new TypeError("This policy does not provide `createScript()`")}),createScriptURL:n=(()=>{throw new TypeError("This policy does not provide `createScriptURL()`")})}){return Fr()?trustedTypes.createPolicy(e,{createHTML:t,createScript:r,createScriptURL:n}):Object.freeze({name:e,createHTML:(e,...r)=>t(e.toString(),...r),createScript:(e,...t)=>r(e.toString(),...t),createScriptURL:(e,...t)=>n(e.toString(),...t)})}function Kr(e="aegis#html"){return Xr(e,{createHTML(e,t){const r=document.createElement("div");return r.setHTML(e,{sanitizer:t}),r.innerHTML}})}function Qr(){return"trustedTypes"in globalThis?trustedTypes.defaultPolicy:null}function Jr(e,t=!0){if(e.shadowRoot instanceof ShadowRoot&&e.shadowRoot.clonable){const r=e.cloneNode(t);return r.shadowRoot.adoptedStyleSheets=e.shadowRoot.adoptedStyleSheets,r}return e.cloneNode(t)}function Yr({tag:e="div",template:t="<slot></slot>",styles:r,mode:n="open",delegatesFocus:o=!1,clonable:a=!0,slotAssignment:i="named",exportParts:s,sanitizer:{elements:c,attributes:l,comments:d=!1,dataAttributes:u=!0,...g}={},...f}){const p=document.createElement(e),m=p.attachShadow({mode:n,clonable:a,delegatesFocus:o,slotAssignment:i});if("string"==typeof t&&0!==t.length){const e=document.createDocumentFragment();e.setHTML(t,{elements:c,attributes:l,comments:d,dataAttributes:u,...g}),m.append(e)}else{if(!(t instanceof Node))throw new TypeError("Missing or invalid template.");t instanceof HTMLTemplateElement?m.append(t.content.cloneNode(!0)):t instanceof DocumentFragment?m.append(t.cloneNode(!0)):m.append(t)}return Array.isArray(r)?Promise.all(r.map((e=>"string"==typeof e?(new CSSStyleSheet).replace(e):e))).then((e=>m.adoptedStyleSheets=e)):"string"==typeof r&&0!==r.length&&(new CSSStyleSheet).replace(r).then((e=>m.adoptedStyleSheets=[e])),"string"==typeof s?p.setAttribute("exportparts",s):Array.isArray(s)?p.setAttribute("exportparts",s.join(", ")):"object"==typeof s&&null!==s&&p.setAttribute("exportparts",Object.entries(s).map((([e,t])=>`${e}:${t}`)).join(", ")),Object.entries(f).forEach((([e,t])=>p.setAttribute(e,t))),p}const Zr=new Map,en=new BroadcastChannel("aegis:state_sync"),tn=crypto.randomUUID(),rn=Symbol("proxy"),nn=Symbol("aegis:state:update");let on=!0;const an=new EventTarget,sn="aegisStateKey",cn="aegisStateAttr",ln="aegisStateStyle",dn="aegisStateProperty",un="data-aegis-state-key",gn="data-aegis-state-attr",fn="data-aegis-state-property",pn="data-aegis-state-style",mn="change",hn="beforechange",bn=(e,t=null)=>history.state?.[e]??t;function yn(e,t=document.documentElement){const r=t.querySelectorAll(e);return t.matches(e)?[t,...r]:Array.from(r)}async function vn({state:e=history.state??{}}={}){const t=this.dataset.aegisStateKey,r=e?.[t];if(await(scheduler?.yield()),"string"==typeof this.dataset[cn]){const e=this.dataset[cn],t=this.getAttribute(e);"string"==typeof t&&t.startsWith("blob:")&&URL.revokeObjectURL(t),"boolean"==typeof r?this.toggleAttribute(e,r):null==r?this.removeAttribute(e):r instanceof Blob?this.setAttribute(e,URL.createObjectURL(r)):this.setAttribute(e,r)}else"string"==typeof this.dataset[dn]&&"innerHTML"!==this.dataset[dn]?this[this.dataset[dn]]=r:"string"==typeof this.dataset[ln]?null==r||!1===r?this.style.removeProperty(this.dataset[ln]):this.style.setProperty(this.dataset[ln],r):this instanceof HTMLInputElement||this instanceof HTMLSelectElement||this instanceof HTMLTextAreaElement?this.value=r:this.textContent=r}const wn=new MutationObserver((e=>{e.forEach((e=>{switch(e.type){case"childList":e.addedNodes.forEach((e=>{e.nodeType===Node.ELEMENT_NODE&&yn(`[${un}]`,e.target).forEach((e=>{e[nn]=vn.bind(e),An(e[nn],e.dataset[sn])}))})),e.removedNodes.forEach((e=>{e.nodeType===Node.ELEMENT_NODE&&yn(`[${un}]`,e.target).forEach((e=>{$n(e[nn]),delete e[nn]}))}));break;case"attributes":"string"==typeof e.oldValue?($n(e.target[nn]),delete e.target[nn]):"string"==typeof e.target.dataset[sn]&&(e.target[nn]=vn.bind(e.target),An(e.target[nn],e.target.dataset[sn]))}}))}));function Sn(e,t,r={}){return{sender:tn,type:e,state:Mn(),msgId:crypto.randomUUID(),recipient:t,location:location.href,timestamp:Date.now(),...r}}function Tn(e=Mn(),t=location.href){const r=Ln(e);return 0!==r.length&&(history.replaceState(e,"",t),kn(r),!0)}function En(){on&&(en.close(),on=!1)}function Ln(e,t=Mn()){if(t!==e){const r=Object.keys(t),n=Object.keys(e),o=n.filter((e=>!r.includes(e))),a=r.filter((e=>!n.includes(e))),i=r.filter((r=>r in e&&r in t&&e[r]!==t[r]));return Object.freeze([...o,...i,...a])}return[]}async function kn(e){if(Array.isArray(e)&&0!==e.length){const t=Mn(),r=Object.fromEntries(e.map((e=>[e,t[e]])));await Promise.allSettled(Array.from(Zr.entries(),(([t,n])=>{(0===n.length||n.some((t=>e.includes(t))))&&t({diff:e,state:r})})))}}function An(e,...t){return e instanceof Function&&!Zr.has(e)&&(Zr.set(e,t),!0)}function Rn(e,t=null){return new Proxy({toString:()=>bn(e,t)?.toString()??"",valueOf(){const r=bn(e,t);return r?.valueOf instanceof Function?r.valueOf():r},toJSON:()=>bn(e,t),[Symbol.toPrimitive](r){const n=bn(e,t);return typeof n===r||"default"===r&&"object"!=typeof n?n:n?.[Symbol.toPrimitive]instanceof Function?n?.[Symbol.toPrimitive]instanceof Function?n[Symbol.toPrimitive](r):n:"number"!==r&&n?.toString instanceof Function?n.toString():"number"===r?parseFloat(n):n},[rn]:!0,[Symbol.toStringTag]:"StateValue",[Symbol.iterator]:()=>bn(e,t)?.[Symbol.iterator]()},{defineProperty(r,n,o){const a=bn(e,t);return!!Reflect.defineProperty(a,n,o)&&(Un(e,a),a)},deleteProperty:(r,n)=>Reflect.deleteProperty(bn(e,t),n),get(r,n){const o=bn(e,t);if(n in r)return r[n];if("object"==typeof o){const e=Reflect.get(o,n,o);return e instanceof Function?e.bind(o):e}return o[n]},getOwnPropertyDescriptor:(r,n)=>Reflect.getOwnPropertyDescriptor(bn(e,t),n),getPrototypeOf(){const r=bn(e,t);return"object"==typeof r?Reflect.getPrototypeOf(r):Object.getPrototypeOf(r)},has:(r,n)=>Reflect.has(bn(e,t),n),isExtensible:()=>Reflect.isExtensible(bn(e,t)),ownKeys:()=>Reflect.ownKeys(bn(e,t)),preventExtensions:()=>Reflect.preventExtensions(bn(e,t)),set(r,n,o){const a=bn(e,t);return!!Reflect.set(a,n,o,a)&&(Un(e,a),!0)}})}const $n=e=>Zr.delete(e),Mn=()=>Object.freeze(null===history.state?{}:structuredClone(history.state)),Pn=e=>e in Mn();function Un(e,t){const r=Mn();if("function"==typeof t)Cn(e,t);else if(r[e]!==t){const n={key:e,oldValue:r[e],newValue:t},o=new CustomEvent(hn,{cancelable:!0,detail:n});an.dispatchEvent(o),o.defaultPrevented||(Hn({...Mn(),[e]:t?.[rn]?t.valueOf():t},location.href),an.dispatchEvent(new CustomEvent(mn,{detail:n})))}}const Cn=async(e,t)=>await Promise.try((()=>t(bn(e),e))).then((t=>(Un(e,t),t)));function xn(e,t=null){return[Rn(e,t),t=>Un(e,t)]}function Nn(e){const t={...Mn()};delete t[e],Hn(t,location.href)}const On=(e="aegis:state")=>localStorage.setItem(e,JSON.stringify(Mn())),Fn=(e="aegis:state")=>Tn(JSON.parse(localStorage.getItem(e)),location.href),Dn=()=>Hn({},location.href);function Hn(e=Mn(),t=location.href){Tn(e,t)&&on&&en.postMessage(Sn("update"))}function jn({signal:e}={}){en.addEventListener("message",(e=>{if(e.isTrusted&&"string"==typeof e.data.msgId&&"string"==typeof e.data.sender&&e.data.sender!==tn&&"object"==typeof e.data.state&&("string"!=typeof e.data.recipient||e.data.recipient===tn)){const t=Mn();if(0!==Ln(e.data.state,t).length)switch(e.data.type){case"update":Tn({...t,...e.data.state},location.href);break;case"sync":on&&en.postMessage(Sn("update",e.data.sender));break;case"clear":Tn({},location.href);break;default:reportError(new Error(`Unhandled broadcast channel message type: ${e.data.type}`))}}}),{signal:e}),en.postMessage(Sn("sync")),e instanceof AbortSignal&&e.aborted?En():e instanceof AbortSignal&&e.addEventListener("abort",En,{once:!0})}function In(e=document.documentElement,{signal:t,base:r=document.documentElement}={}){if(t instanceof AbortSignal&&t.aborted)throw t.reason;if("string"==typeof e)In(r.querySelector(e),{signal:t});else{if(!(e instanceof Element||e instanceof ShadowRoot))throw new TypeError("Target must be an element, selector, or shadow root.");wn.observe(e,{childList:!0,subtree:!0,attributeFilter:[un],attributeOldValue:!0}),yn(`[${un}]`,e).forEach((e=>{e[nn]=vn.bind(e),An(e[nn],e.dataset[sn]),e[nn]({state:history.state})})),t instanceof AbortSignal&&t.addEventListener("abort",(()=>wn.disconnect()),{once:!0})}}function zn(e,t,{attr:r,style:n,base:o=document.body}={}){if("string"==typeof e)zn(o.querySelector(e),t,{attr:r,style:n});else{if(!(e instanceof Element))throw new TypeError("Target must be an element or selector.");e instanceof HTMLElement?(e.dataset[sn]=t,"string"==typeof r?e.dataset[cn]=r:"string"==typeof n&&(e.dataset[ln]=n),requestAnimationFrame((()=>vn.call(e,{state:history.state??{}})))):e instanceof Element&&(e.setAttribute(un,t),"string"==typeof r?e.setAttribute(gn,r):"string"==typeof n&&e.setAttribute(pn,n),requestAnimationFrame((()=>vn.call(e,{state:history.state??{}}))))}}function qn(e,t,r,{base:n=document.documentElement,signal:o}={}){if(o instanceof AbortSignal&&o.aborted)throw o.reason;if("string"==typeof e)return qn(n.querySelector(e),t,r,{});if(e instanceof Element){if("string"!=typeof t||0===t.length)throw new TypeError("State key must be a non-empty string.");if(r instanceof Function){const n=function({state:e={}}={}){return r.call(this,e[t],this)}.bind(e);return An(n,t),o instanceof AbortSignal&&o.addEventListener("abort",(()=>$n(n)),{once:!0}),n}throw new TypeError("Callback must be a function.")}throw new TypeError("Target must be an element or selector.")}function Bn({target:e,type:t}){if(!(e instanceof HTMLElement))throw new TypeError(`Event ${t} target must be an HTMLElement.`);if(e instanceof HTMLSelectElement)Un(e.name,e.multiple?Array.from(e.selectedOptions,(e=>e.value)):e.value);else if(e instanceof HTMLInputElement)switch(e.type){case"checkbox":{const t=Array.from(e.form?.elements??[e]).filter((t=>t.name===e.name&&"checkbox"===t.type));1===t.length?Un(e.name,"on"===e.value?e.checked:e.value):Un(e.name,Array.from(t).filter((e=>e.checked)).map((e=>e.value)))}break;case"number":case"range":Un(e.name,e.valueAsNumber);break;case"date":Un(e.name,e.valueAsDate?.toISOString()?.split("T")?.at(0));break;case"file":Un(e.name,e.multiple?Array.from(e.files):e.files.item(0));break;case"datetime-local":Un(e.name,e.valueAsDate);break;default:Un(e.name,e.value)}else if(e instanceof HTMLTextAreaElement)Un(e.name,e.value);else{if(!e.constructor.formAssociated)throw new TypeError(`Event ${t} target is not a valid form element.`);Un(e.name,e.value)}}function Vn(e,{signal:t,once:r=!1,passive:n=!1}={}){an.addEventListener(mn,e,{signal:t,once:r,passive:n})}function _n(e,{signal:t,once:r=!1,passive:n=!1}={}){an.addEventListener(hn,e,{signal:t,once:r,passive:n})}console.log({onClick:O,onSubmit:xe});const Wn=!(document.currentScript instanceof HTMLScriptElement),Gn=HTMLScriptElement.supports("importmap"),Xn=new Map,Kn=["GET","HEAD","DELETE","OPTIONS"],Qn='meta[name="description"], meta[itemprop="description"], meta[property="og:description"], meta[name="twitter:description"]',Jn=new MutationObserver((e=>e.forEach((e=>ko(e.target))))),Yn=new MutationObserver((e=>e.forEach(ao))),Zn="root",eo=document,to=Symbol.for("aegis:navigate:event:close"),ro=matchMedia("(prefers-reduced-motion: reduce)");let no=document.getElementById(Zn)??document.body,oo="#"+Zn;function ao(e){e instanceof MutationRecord?ao(e.target):"A"!==e.tagName||e.classList.contains("no-router")||e.hasAttribute(O)?e.querySelectorAll(`a:not(.no-router, [${O}])`).forEach((e=>Zo(e,e.dataset))):Zo(e,e.dataset)}const io="aegis:navigate",so={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"},co=[so.back,so.forward,so.navigate,so.submit,so.reload,so.go];class lo extends CustomEvent{#e;#t;#r=new AbortController;#n=[];#o=[];constructor(e=io,t="unknown",{bubbles:r=!1,cancelable:n=!0,detail:o={oldState:Mn(),oldURL:new URL(location.href)}}={}){super(e,{bubbles:r,cancelable:n,detail:o}),this.#e=t,this.#t=location.href}get aborted(){return this.#r.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.#r.signal}get url(){return this.#t}async[to](){const e=await Promise.allSettled(this.#n).then((e=>(this.#o.push(...e.filter((e=>"rejected"===e.status)).map((e=>e.reason))),this.cancelable&&this.defaultPrevented)));return this.#r.abort(),e}abort(e){this.#r.abort(e)}waitUntil(e,{signal:t}={}){const{promise:r,resolve:n,reject:o}=Promise.withResolvers();this.#n.push(r),t instanceof AbortSignal&&!t.aborted&&t.addEventListener("abort",(({target:e})=>{o(e.reason),this.cancelable&&!this.defaultPrevented&&super.preventDefault()}),{once:!0,signal:this.#r.signal}),this.#r.signal.aborted?o(this.#r.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.#r.signal]):this.#r.signal,timestamp:performance.now()}))).then(n,o):!this.defaultPrevented&&e instanceof Promise&&e.then(n,o)}[Symbol.toStringTag](){return"NavigationEvent"}static get defaultType(){return io}static get reasons(){return so}}const uo="trustedTypes"in globalThis?trustedTypes.createPolicy("aegis-router#html",{createHTML:e=>e}):Object.freeze({createPolicy:e=>e});async function go(e){const t=Ln(e.state??{}),r=new lo(io,so.pop,{detail:{newState:e.state,oldState:null,oldURL:new URL(location.href),method:"GET",formData:null}});if(eo.dispatchEvent(r),!await r[to]()){const e=history.scrollRestoration,[r]=await Promise.all([Co(new URL(location.href)),kn(t)]);history.scrollRestoration="auto",vo(r),history.scrollRestoration=e}}function fo(e={}){const t=document.createElement("meta");return Object.entries(e).forEach((([e,r])=>t.setAttribute(e,r))),t}function po(e,{relList:t=[],crossOrigin:r="anonymous",referrerPolicy:n="no-referrer",fetchPriority:o="auto",signal:a=AbortSignal.timeout(5e3),as:i,integrity:s,media:c,type:l}={}){const{promise:d,resolve:u,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 r&&(f.crossOrigin=r),"string"==typeof l&&(f.type=l),"string"==typeof c?f.media=c:c instanceof MediaQueryList&&(f.media=c.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,r=AbortSignal.any([t.signal,a]);return a.addEventListener("abort",(({target:e})=>{g(e.reason)}),{signal:t.signal}),f.referrerPolicy=n,f.addEventListener("load",(()=>{u(),t.abort()}),{signal:r}),f.addEventListener("error",(()=>{g(new DOMException(`Error loading ${e}`,"NotFoundError")),t.abort()}),{signal:r}),f.href=function(e){if(mo(e))return URL.parse(e,document.baseURI);if(Gn){if(Wn)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),d.then((()=>f.remove())).catch((e=>{f.isConnected&&f.remove(),reportError(e)}))}return f.href=e,document.head.append(f),u(),d}g(a.reason)}function mo(e){switch(e[0]){case"/":case".":return!0;case"h":return"http"===e.substring(0,"4")&&URL.canParse(e);default:return!1}}function ho(e){if(e.target.classList.contains("no-router")||e.target.hasAttribute(O))e.target.removeEventListener(ho);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);xo(e.currentTarget.href,t,{integrity:e.currentTarget.dataset.integrity,cache:e.currentTarget.dataset.cache,referrerPolicy:e.currentTarget.dataset.referrerPolicy})}}async function bo(e){if(e.target.classList.contains("no-router")||e.target.hasAttribute(xe))e.target.removeEventListener("submit",bo);else if(e.isTrusted&&e.target.action.startsWith(location.origin)){e.preventDefault();const{method:t,action:r}=e.target,n=new FormData(e.target),o=new lo(io,so.submit,{detail:{oldState