UNPKG

node-red-contrib-uibuilder

Version:

Easily create data-driven web UI's for Node-RED. Single- & Multi-page. Multiple UI's. Work with existing web development workflows or mix and match with no-code/low-code features.

1 lines 176 kB
var _i=Object.create;var Ze=Object.defineProperty;var ki=Object.getOwnPropertyDescriptor;var Ci=Object.getOwnPropertyNames;var Si=Object.getPrototypeOf,xi=Object.prototype.hasOwnProperty;var Lt=n=>{throw TypeError(n)};var Ti=(n,e,t)=>e in n?Ze(n,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):n[e]=t;var Nt=(n=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(n,{get:(e,t)=>(typeof require<"u"?require:e)[t]}):n)(function(n){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+n+'" is not supported')});var Oi=(n,e)=>{for(var t in e)Ze(n,t,{get:e[t],enumerable:!0})},Ai=(n,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of Ci(e))!xi.call(n,s)&&s!==t&&Ze(n,s,{get:()=>e[s],enumerable:!(i=ki(e,s))||i.enumerable});return n};var $t=(n,e,t)=>(t=n!=null?_i(Si(n)):{},Ai(e||!n||!n.__esModule?Ze(t,"default",{value:n,enumerable:!0}):t,n));var p=(n,e,t)=>Ti(n,typeof e!="symbol"?e+"":e,t),Rt=(n,e,t)=>e.has(n)||Lt("Cannot "+t);var u=(n,e,t)=>(Rt(n,e,"read from private field"),t?t.call(n):e.get(n)),k=(n,e,t)=>e.has(n)?Lt("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(n):e.set(n,t),C=(n,e,t,i)=>(Rt(n,e,"write to private field"),i?i.call(n,t):e.set(n,t),t);var de=(n,e,t,i)=>({set _(s){C(n,e,s,t)},get _(){return u(n,e,i)}});function Mt(n={}){let{content:e="",title:t="",icon:i="",type:s="info",showDismiss:r,autoClose:o=5,time:a=!0}=n,c="uib-info-overlay",h=document.getElementById(c);h||(h=document.createElement("div"),h.id=c,document.body.appendChild(h),console.log(">> SHOW OVERLAY >>",n,document.getElementById(c)));let f="overlay-entry-".concat(Date.now(),"-").concat(Math.random().toString(36).substr(2,9)),m=document.createElement("div");m.id=f,m.style.marginBottom="0.5rem";let b={info:{iconDefault:"\u2139\uFE0F",titleDefault:"Information",color:"hsl(188.2deg 77.78% 40.59%)"},success:{iconDefault:"\u2705",titleDefault:"Success",color:"hsl(133.7deg 61.35% 40.59%)"},warning:{iconDefault:"\u26A0\uFE0F",titleDefault:"Warning",color:"hsl(35.19deg 84.38% 62.35%)"},error:{iconDefault:"\u274C",titleDefault:"Error",color:"hsl(2.74deg 92.59% 62.94%)"}},g=b[s]||b.info,y=r!==void 0?r:o===null,v=i||g.iconDefault,x=t||g.titleDefault,N="";if(a){let A=new Date,Ae=A.getFullYear(),Le=String(A.getMonth()+1).padStart(2,"0"),Ne=String(A.getDate()).padStart(2,"0"),$e=String(A.getHours()).padStart(2,"0"),Re=String(A.getMinutes()).padStart(2,"0"),ut=String(A.getSeconds()).padStart(2,"0"),Ei="".concat(Ae,"-").concat(Le,"-").concat(Ne," ").concat($e,":").concat(Re,":").concat(ut);N='<div class="uib-overlay-time" style="font-size: 0.8em; color: var(--text3, #999); margin-left: auto; margin-right: '.concat(y?"0.5rem":"0",';">').concat(Ei,"</div>")}m.innerHTML='\n <div class="uib-overlay-entry" style="--callout-color:'.concat(g.color,';">\n <div class="uib-overlay-header">\n <div class="uib-overlay-icon">').concat(v,'</div>\n <div class="uib-overlay-title">').concat(x,"</div>\n ").concat(N,"\n ").concat(y?'<button class="uib-overlay-dismiss" data-entry-id="'.concat(f,'" title="Close">\xD7</button>'):"",'\n </div>\n <div class="uib-overlay-content">\n ').concat(e,"\n </div>\n </div>\n "),h.children.length>0?h.insertBefore(m,h.firstChild):h.appendChild(m);let E=()=>{let A=document.getElementById(f);A&&(A.style.animation="slideOut 0.3s ease-in",setTimeout(()=>{A.parentNode&&A.remove()},300))},O=m.querySelector(".uib-overlay-dismiss");O&&O.addEventListener("click",E);let D=null;return o!==null&&o>0&&(D=setTimeout(E,o*1e3)),{close:()=>{D&&clearTimeout(D),E()},id:f}}var l,Li=(l=class{constructor(e,t,i){p(this,"version","7.7.0-src");p(this,"sanitiseExtraTags",["uib-var"]);p(this,"sanitiseExtraAttribs",["variable","report","undefined"]);p(this,"sanitiseCustomElementHandling",{tagNameCheck:/^[a-z][a-z0-9]*-[a-z0-9-]*$/,attributeNameCheck:/^[a-z_][\w.-]*$/i,allowCustomizedBuiltInElements:!1});p(this,"ui_md_plugins");if(e)l.win=e;else throw new Error("Ui:constructor. Current environment does not include `window`, UI functions cannot be used.");l.doc=l.win.document,t?l.log=t:l.log=function(){return function(){}},i?this.syntaxHighlight=i:this.syntaxHighlight=function(){},l.win.markdownit&&(l.mdOpts={html:!0,xhtmlOut:!1,linkify:!0,_highlight:!0,_strict:!1,_view:"html",langPrefix:"language-",highlight:function(s,r){return r&&window.hljs&&window.hljs.getLanguage(r)?'<pre class="">\n <code class="hljs border">'.concat(window.hljs.highlight(s,{language:r,ignoreIllegals:!0}).value,"</code></pre>"):'<pre class="hljs border"><code>'.concat(l.md.utils.escapeHtml(s).trim(),"</code></pre>")}},l.md=l.win.markdownit(l.mdOpts))}_markDownIt(){if(l.win.markdownit&&(!this.ui_md_plugins&&l.win.uibuilder&&l.win.uibuilder.ui_md_plugins&&(this.ui_md_plugins=l.win.uibuilder.ui_md_plugins),l.mdOpts={html:!0,xhtmlOut:!1,linkify:!0,_highlight:!0,_strict:!1,_view:"html",langPrefix:"language-",highlight:function(e,t){if(window.hljs){if(t&&window.hljs.getLanguage(t))return'<pre><code class="hljs border language-'.concat(t,'" data-language="').concat(t,'" title="Source language: \'').concat(t,"'\">").concat(window.hljs.highlight(e,{language:t,ignoreIllegals:!0}).value,"</code></pre>");{let i=window.hljs.highlightAuto(e);return'<pre><code class="hljs border language-'.concat(i.language,'" data-language="').concat(i.language,'" title="Source language estimated by HighlightJS: \'').concat(i.language,"'\">").concat(i.value,"</code></pre>")}}return'<pre><code class="border">'.concat(l.md.utils.escapeHtml(e).trim(),"</code></pre>")}},l.md=l.win.markdownit(l.mdOpts),this.ui_md_plugins)){if(!Array.isArray(this.ui_md_plugins)){l.log("error","Ui:_markDownIt:plugins","Could not load plugins, ui_md_plugins is not an array")();return}this.ui_md_plugins.forEach(e=>{if(typeof e=="string")l.md.use(l.win[e]);else{let t=Object.keys(e)[0];l.md.use(l.win[t],e[t])}})}}_showNotification(e){e.topic&&!e.title&&(e.title=e.topic),e.title||(e.title="uibuilder notification"),e.payload&&!e.body&&(e.body=e.payload),e.body||(e.body=" No message given.");try{let t=new Notification(e.title,e);return new Promise((i,s)=>{t.addEventListener("close",r=>{r.currentTarget.userAction="close",i(r)}),t.addEventListener("click",r=>{r.currentTarget.userAction="click",i(r)}),t.addEventListener("error",r=>{r.currentTarget.userAction="error",s(r)})})}catch{return Promise.reject(new Error("Browser refused to create a Notification"))}}_uiAdd(e,t){l.log("trace","Ui:_uiManager:add","Starting _uiAdd")(),e.components.forEach((i,s)=>{l.log("trace","Ui:_uiAdd:components-forEach:".concat(s),"Component to add: ",i)();let r;switch(i.type){case"html":{i.ns="html",r=l.doc.createElement("div");break}case"svg":{i.ns="svg",r=l.doc.createElementNS("http://www.w3.org/2000/svg","svg");break}default:{i.ns="dom",r=l.doc.createElement(i.type);break}}!i.slot&&e.payload&&(i.slot=e.payload),this._uiComposeComponent(r,i);let o;i.parentEl?o=i.parentEl:e.parentEl?o=e.parentEl:i.parent?o=l.doc.querySelector(i.parent):e.parent&&(o=l.doc.querySelector(e.parent)),o||(l.log("info","Ui:_uiAdd","No parent found, adding to body")(),o=l.doc.querySelector("body")),i.position&&i.position==="first"?o.insertBefore(r,o.firstChild):i.position&&Number.isInteger(Number(i.position))?o.insertBefore(r,o.children[i.position]):o.appendChild(r),i.components&&this._uiExtendEl(r,i.components,i.ns)})}_uiComposeComponent(e,t){t.attributes&&Object.keys(t.attributes).forEach(i=>{i==="class"&&Array.isArray(t.attributes[i])&&t.attributes[i].join(" "),l.log("trace","_uiComposeComponent:attributes-forEach","Attribute: '".concat(i,"', value: '").concat(t.attributes[i],"'"))(),i==="value"&&(e.value=t.attributes[i]),i.startsWith("xlink:")?e.setAttributeNS("http://www.w3.org/1999/xlink",i,t.attributes[i]):e.setAttribute(i,t.attributes[i])}),t.id&&e.setAttribute("id",t.id),t.type==="svg"&&(e.setAttributeNS("http://www.w3.org/2000/xmlns/","xmlns","http://www.w3.org/2000/svg"),e.setAttributeNS("http://www.w3.org/2000/xmlns/","xmlns:xlink","http://www.w3.org/1999/xlink")),t.events&&Object.keys(t.events).forEach(i=>{i.toLowerCase==="onclick"&&(i="click");try{e.addEventListener(i,s=>{new Function("evt","".concat(t.events[i],"(evt)"))(s)})}catch(s){l.log("error","Ui:_uiComposeComponent","Add event '".concat(i,"' for element '").concat(t.type,"': Cannot add event handler. ").concat(s.message))()}}),t.properties&&Object.keys(t.properties).forEach(i=>{e[i]=t.properties[i],["value","checked"].includes(i)&&(e.dispatchEvent(new Event("input")),e.dispatchEvent(new Event("change")))}),t.slot&&this.replaceSlot(e,t.slot),t.slotMarkdown&&this.replaceSlotMarkdown(e,t)}_uiExtendEl(e,t,i=""){t.forEach((s,r)=>{l.log("trace","Ui:_uiExtendEl:components-forEach:".concat(r),s)();let o;s.ns=i,s.ns==="html"?(o=e,this.replaceSlot(e,s.slot)):s.ns==="svg"?(o=l.doc.createElementNS("http://www.w3.org/2000/svg",s.type),this._uiComposeComponent(o,s),e.appendChild(o)):(o=l.doc.createElement(s.type==="html"?"div":s.type),this._uiComposeComponent(o,s),e.appendChild(o)),s.components&&this._uiExtendEl(o,s.components,s.ns)})}_uiLoad(e){e.components&&(Array.isArray(e.components)||(e.components=[e.components]),e.components.forEach(async t=>{Promise.resolve().then(()=>$t(Nt(t)))})),e.srcScripts&&(Array.isArray(e.srcScripts)||(e.srcScripts=[e.srcScripts]),e.srcScripts.forEach(t=>{this.loadScriptSrc(t)})),e.txtScripts&&(Array.isArray(e.txtScripts)||(e.txtScripts=[e.txtScripts]),this.loadScriptTxt(e.txtScripts.join("\n"))),e.srcStyles&&(Array.isArray(e.srcStyles)||(e.srcStyles=[e.srcStyles]),e.srcStyles.forEach(t=>{this.loadStyleSrc(t)})),e.txtStyles&&(Array.isArray(e.txtStyles)||(e.txtStyles=[e.txtStyles]),this.loadStyleTxt(e.txtStyles.join("\n")))}_uiManager(e){e._ui&&(Array.isArray(e._ui)||(e._ui=[e._ui]),e._ui.forEach((t,i)=>{if(t.mode&&!t.method&&(t.method=t.mode),!t.method){l.log("error","Ui:_uiManager","No method defined for msg._ui[".concat(i,"]. Ignoring. "),t)();return}switch(t.payload=e.payload,t.topic=e.topic,t.method){case"add":{this._uiAdd(t,!1);break}case"remove":{this._uiRemove(t,!1);break}case"removeAll":{this._uiRemove(t,!0);break}case"replace":{this._uiReplace(t);break}case"update":{this._uiUpdate(t);break}case"load":{this._uiLoad(t);break}case"reload":{this._uiReload();break}case"notify":{this.showDialog("notify",t,e);break}case"alert":{this.showDialog("alert",t,e);break}default:{l.log("error","Ui:_uiManager","Invalid msg._ui[".concat(i,"].method (").concat(t.method,"). Ignoring"))();break}}}))}_uiReload(){l.log("trace","Ui:uiManager:reload","reloading")(),location.reload()}_uiRemove(e,t=!1){e.components.forEach(i=>{let s;t!==!0?s=[l.doc.querySelector(i)]:s=l.doc.querySelectorAll(i),s.forEach(r=>{try{r.remove()}catch(o){l.log("trace","Ui:_uiRemove","Could not remove. ".concat(o.message))()}})})}_uiReplace(e){l.log("trace","Ui:_uiReplace","Starting")(),e.components.forEach((t,i)=>{l.log("trace","Ui:_uiReplace:components-forEach:".concat(i),"Component to replace: ",t)();let s;if(t.id?s=l.doc.getElementById(t.id):t.selector||t.select?s=l.doc.querySelector(t.selector):t.name?s=l.doc.querySelector('[name="'.concat(t.name,'"]')):t.type&&(s=l.doc.querySelector(t.type)),l.log("trace","Ui:_uiReplace:components-forEach:".concat(i),"Element to replace: ",s)(),s==null){l.log("trace","Ui:_uiReplace:components-forEach:".concat(i,":noReplace"),"Cannot find the DOM element. Adding instead.",t)(),this._uiAdd({components:[t]},!1);return}let r;switch(t.type){case"html":{t.ns="html",r=l.doc.createElement("div");break}case"svg":{t.ns="svg",r=l.doc.createElementNS("http://www.w3.org/2000/svg","svg");break}default:{t.ns="dom",r=l.doc.createElement(t.type);break}}this._uiComposeComponent(r,t),s.replaceWith(r),t.components&&this._uiExtendEl(r,t.components,t.ns)})}_uiUpdate(e){l.log("trace","UI:_uiUpdate:update","Starting _uiUpdate",e)(),e.components||(e.components=[Object.assign({},e)]),e.components.forEach((t,i)=>{l.log("trace","_uiUpdate:components-forEach","Start loop #".concat(i),t)();let s;if(t.parentEl?s=t.parentEl:t.id?s=l.doc.querySelectorAll("#".concat(t.id)):t.selector||t.select?s=l.doc.querySelectorAll(t.selector):t.name?s=l.doc.querySelectorAll('[name="'.concat(t.name,'"]')):t.type&&(s=l.doc.querySelectorAll(t.type)),s===void 0||s.length<1){l.log("warn","Ui:_uiManager:update","Cannot find the DOM element. Ignoring.",t)();return}l.log("trace","_uiUpdate:components-forEach","Element(s) to update. Count: ".concat(s.length),s)(),!t.slot&&t.payload&&(t.slot=t.payload),s.forEach((r,o)=>{if(l.log("trace","_uiUpdate:components-forEach","Updating element #".concat(o),r)(),this._uiComposeComponent(r,t),t.components){l.log("trace","_uiUpdate:nested-component","Element #".concat(o," - nested-component"),t,r)();let a={_ui:[]};t.components.forEach((c,h)=>{let f=c.method||t.method||e.method;c.method&&delete c.method,Array.isArray(c)||(c=[c]),l.log("trace","_uiUpdate:nested-component","Element #".concat(o," - nested-component #").concat(h),c)(),a._ui.push({method:f,parentEl:r,components:c})}),l.log("trace","_uiUpdate:nested-component","Element #".concat(o," - nested-component new manager"),a)(),this._uiManager(a)}})})}$(e,t,i){if(i||(i=l.doc),t||(t="el"),!i||!i.nodeType)return l.log(1,"Uib:$","Invalid context element. Must be a valid HTML element.",i)(),null;let s=i.querySelector(e);if(!s||!s.nodeType)return l.log(1,"Uib:$","No element found or element is not an HTML element for CSS selector ".concat(e))(),null;if(s.nodeName==="TEMPLATE"&&(s=s.content.firstElementChild,!s))return l.log(0,"Uib:$","Template selected for CSS selector ".concat(e," but it is empty"))(),null;let r;try{switch(t.toLowerCase()){case"text":{r=s.innerText;break}case"html":{r=s.innerHTML;break}case"attr":case"attributes":{r={};for(let o of s.attributes)r[o.name]=o.value;break}default:{r=s;break}}}catch(o){r=s,l.log(1,"Uib:$",'Could not process output type "'.concat(t,'" for CSS selector ').concat(e,", returned the DOM element. ").concat(o.message),o)()}return r}$$(e,t){return t||(t=l.doc),!t||!t.nodeType?(l.log(1,"Uib:$$","Invalid context element. Must be a valid HTML element.",t)(),null):Array.from(t.querySelectorAll(e))}addClass(e,t){Array.isArray(e)||(e=[e]),t&&t.classList.add(...e)}applyTemplate(e,t,i){var c;i||(i={}),i.onceOnly||(i.onceOnly=!1),i.mode||(i.mode="insert");let s=l.doc.getElementById(e);if(!s||s.tagName!=="TEMPLATE"){l.log("error","Ui:applyTemplate","Source must be a <template>. id='".concat(e,"'"))();return}let r=l.doc.getElementById(t);if(!r){l.log("error","Ui:applyTemplate","Target not found: id='".concat(t,"'"))();return}let o=(c=r.innerHTML)!=null?c:"";o&&i.mode==="replace"&&l.log("warn","Ui:applyTemplate","Target element is not empty, content is replaced. id='".concat(t,"'"))();let a;if(i.onceOnly===!0?a=l.doc.adoptNode(s.content):a=l.doc.importNode(s.content,!0),a){if(i.attributes){let h=a.firstElementChild;Object.keys(i.attributes).forEach(f=>{h.setAttribute(f,i.attributes[f])})}if(i.mode==="insert")r.appendChild(a);else if(i.mode==="replace")r.innerHTML="",r.appendChild(a);else if(i.mode==="wrap"&&(r.innerHTML="",r.appendChild(a),o)){let h=r.getElementsByTagName("slot");h.length>0&&(h[0].innerHTML=o)}}else l.log("warn","Ui:applyTemplate","No valid content found in template")()}convertMarkdown(e){if(!e)return"";if(!l.win.markdownit)return e;l.md||this._markDownIt();try{return l.md.render(e.trim())}catch(t){return l.log(0,"uibuilder:convertMarkdown","Could not render Markdown. ".concat(t.message),t)(),'<p class="border error">Could not render Markdown<p>'}}async include(e,t){if(!fetch)return l.log(0,"Ui:include","Current environment does not include `fetch`, skipping.")(),"Current environment does not include `fetch`, skipping.";if(!e)return l.log(0,"Ui:include","url parameter must be provided, skipping.")(),"url parameter must be provided, skipping.";if(!t||!t.id)return l.log(0,"Ui:include","uiOptions parameter MUST be provided and must contain at least an `id` property, skipping.")(),"uiOptions parameter MUST be provided and must contain at least an `id` property, skipping.";let i;try{i=await fetch(e)}catch(h){return l.log(0,"Ui:include","Fetch of file '".concat(e,"' failed. "),h.message)(),h.message}if(!i.ok)return l.log(0,"Ui:include","Fetch of file '".concat(e,"' failed. Status='").concat(i.statusText,"'"))(),i.statusText;let s=await i.headers.get("content-type"),r=null;s&&(s.includes("text/html")?r="html":s.includes("application/json")?r="json":s.includes("multipart/form-data")?r="form":s.includes("image/")?r="image":s.includes("video/")?r="video":s.includes("application/pdf")?r="pdf":s.includes("text/plain")&&(r="text"));let o="",a="Include successful",c;switch(r){case"html":{c=await i.text(),o=c;break}case"json":{c=await i.json(),o='<pre class="syntax-highlight">',o+=this.syntaxHighlight(c),o+="</pre>";break}case"form":{c=await i.formData(),o='<pre class="syntax-highlight">',o+=this.syntaxHighlight(c),o+="</pre>";break}case"image":{c=await i.blob(),o='<img src="'.concat(URL.createObjectURL(c),'">'),l.win.DOMPurify&&(a="Include successful. BUT DOMPurify loaded which may block its use.",l.log("warn","Ui:include:image",a)());break}case"video":{c=await i.blob(),o='<video controls autoplay><source src="'.concat(URL.createObjectURL(c),'"></video>'),l.win.DOMPurify&&(a="Include successful. BUT DOMPurify loaded which may block its use.",l.log("warn","Ui:include:video",a)());break}default:{c=await i.blob(),o='<iframe style="resize:both;width:inherit;height:inherit;" src="'.concat(URL.createObjectURL(c),'">'),l.win.DOMPurify&&(a="Include successful. BUT DOMPurify loaded which may block its use.",l.log("warn","Ui:include:".concat(r),a)());break}}return t.type="div",t.slot=o,t.parent||(t.parent="body"),t.attributes||(t.attributes={class:"included"}),this._uiReplace({components:[t]}),l.log("trace","Ui:include:".concat(r),a)(),a}loadScriptSrc(e){let t=l.doc.createElement("script");t.src=e,t.async=!1,l.doc.head.appendChild(t)}loadScriptTxt(e){let t=l.doc.createElement("script");t.async=!1,t.textContent=e,l.doc.head.appendChild(t)}loadStyleSrc(e){let t=l.doc.createElement("link");t.href=e,t.rel="stylesheet",t.type="text/css",l.doc.head.appendChild(t)}loadStyleTxt(e){let t=l.doc.createElement("style");t.textContent=e,l.doc.head.appendChild(t)}loadui(e){if(!fetch){l.log(0,"Ui:loadui","Current environment does not include `fetch`, skipping.")();return}if(!e){l.log(0,"Ui:loadui","url parameter must be provided, skipping.")();return}fetch(e).then(t=>{if(t.ok===!1)throw new Error("Could not load '".concat(e,"'. Status ").concat(t.status,", Error: ").concat(t.statusText));l.log("trace","Ui:loadui:then1","Loaded '".concat(e,"'. Status ").concat(t.status,", ").concat(t.statusText))();let i=t.headers.get("content-type");if(!i||!i.includes("application/json"))throw new TypeError("Fetch '".concat(e,"' did not return JSON, ignoring"));return t.json()}).then(t=>t!==void 0?(l.log("trace","Ui:loadui:then2","Parsed JSON successfully obtained")(),this._uiManager({_ui:t}),!0):!1).catch(t=>{l.log("warn","Ui:loadui:catch","Error. ",t)()})}moveElement(e){let{sourceSelector:t,targetSelector:i,moveType:s,position:r}=e;if(!document.querySelector(t)){l.log(0,"Ui:moveElement","Source element not found")();return}if(!document.querySelector(i)){l.log(0,"Ui:moveElement","Target element not found")();return}}nodeGet(e,t){let i={id:e.id===""?void 0:e.id,name:e.name,children:e.childNodes.length,type:e.nodeName,attributes:void 0,isUserInput:!!e.validity,userInput:e.validity?{value:e.value,validity:void 0,willValidate:e.willValidate,valueAsDate:e.valueAsDate,valueAsNumber:e.valueAsNumber,type:e.type}:void 0};if(["UL","OL"].includes(e.nodeName)){let s=l.doc.querySelectorAll("".concat(t," li"));s&&(i.list={entries:s.length})}if(e.nodeName==="DL"){let s=l.doc.querySelectorAll("".concat(t," dt"));s&&(i.list={entries:s.length})}if(e.nodeName==="TABLE"){let s=l.doc.querySelectorAll("".concat(t," > tbody > tr")),r=l.doc.querySelectorAll("".concat(t," > thead > tr")),o=l.doc.querySelectorAll("".concat(t," > tbody > tr:last-child > *"));(s||r||o)&&(i.table={headRows:r?r.length:0,bodyRows:s?s.length:0,columns:o?o.length:0})}if(e.nodeName!=="#text"&&e.attributes&&e.attributes.length>0){i.attributes={};for(let s of e.attributes)s.name!=="id"&&(i.attributes[s.name]=e.attributes[s.name].value),s.name==="class"&&(i.classes=Array.from(e.classList))}e.nodeName==="#text"&&(i.text=e.textContent),e.validity&&(i.userInput.validity={});for(let s in e.validity)i.userInput.validity[s]=e.validity[s];return i}async notification(e){if(typeof e=="string"&&(e={body:e}),typeof Notification>"u")return Promise.reject(new Error("Notifications not available in this browser"));let t=Notification.permission;return t==="denied"?Promise.reject(new Error("Notifications not permitted by user")):t==="granted"?this._showNotification(e):(t=await Notification.requestPermission(),t==="granted"?this._showNotification(e):Promise.reject(new Error("Notifications not permitted by user")))}removeClass(e,t){if(!e){t.removeAttribute("class");return}Array.isArray(e)||(e=[e]),t&&t.classList.remove(...e)}replaceSlot(e,t){if(!e)return;if(t||(t=""),t=this.sanitiseHTML(t),e.nodeName==="TEMPLATE"){e.innerHTML=t;return}let i=l.doc.createRange().createContextualFragment(t),s=l.doc.createRange();s.selectNodeContents(e),s.deleteContents(),e.append(i)}replaceSlotMarkdown(e,t){e&&t.slotMarkdown&&(t.slotMarkdown=this.convertMarkdown(t.slotMarkdown),t.slotMarkdown=this.sanitiseHTML(t.slotMarkdown),e.innerHTML=t.slotMarkdown)}sanitiseHTML(e){return l.win.DOMPurify?l.win.DOMPurify.sanitize(e,{ADD_TAGS:this.sanitiseExtraTags,ADD_ATTR:this.sanitiseExtraAttribs,CUSTOM_ELEMENT_HANDLING:this.sanitiseCustomElementHandling}):e}showDialog(e,t,i){(!e||!["notify","alert"].includes(e))&&(e="notify"),t||(t={noAutohide:!0,modal:!0,appendToast:!1});let s="";if(i.payload&&typeof i.payload=="string"&&(s+="<div>".concat(i.payload,"</div>")),t.content&&(s+="<div>".concat(t.content,"</div>")),s==="")return l.log(1,"Ui:showDialog","Toast content is blank. Not shown.")(),null;let r="";t.title?r=t.title:i.topic&&(r=i.topic),t.noAutohide&&(t.noAutoHide=t.noAutohide),t.noAutoHide&&(t.autohide=!t.noAutoHide),t.autoHideDelay?(t.autohide||(t.autohide=!0),t.delay=t.autoHideDelay):t.autoHideDelay=1e4,Object.prototype.hasOwnProperty.call(t,"autohide")||(t.autohide=!0);let o="",a="";e==="alert"&&(a='<svg viewBox="0 0 192.146 192.146"><path d="M108.186 144.372c0 7.054-4.729 12.32-12.037 12.32h-.254c-7.054 0-11.92-5.266-11.92-12.32 0-7.298 5.012-12.31 12.174-12.31s11.91 4.992 12.037 12.31zM88.44 125.301h15.447l2.951-61.298H85.46l2.98 61.298zm101.932 51.733c-2.237 3.664-6.214 5.921-10.493 5.921H12.282c-4.426 0-8.51-2.384-10.698-6.233a12.34 12.34 0 0 1 .147-12.349l84.111-149.22c2.208-3.722 6.204-5.96 10.522-5.96h.332c4.445.107 8.441 2.618 10.513 6.546l83.515 149.229c1.993 3.8 1.905 8.363-.352 12.066zm-10.493-6.4L96.354 21.454l-84.062 149.18h167.587z" /></svg>',t.modal=!0,t.autohide=!1),o='<div class="toast-head">'.concat(a).concat(r,'</div><div class="toast-body">').concat(s,"</div>");let c=()=>{g&&(l.doc.body.removeEventListener("keyup",f),g.removeEventListener("keyup",f),g.removeEventListener("touchend",f),g.removeEventListener("click",f),g.remove())},h=y=>{y.removeEventListener("keyup",f),y.removeEventListener("touchend",f),y.removeEventListener("click",f),y.remove(),g&&g.childElementCount===0&&c()},f=y=>{y.stopPropagation(),g&&(console.log("toasterEventHandler",y,g.contains(y.target),b.contains(y.target),b===y.target),c())},m=y=>{y.stopPropagation();let v;if(y.target.classList.contains("toast")?v=y.target:v=y.target.closest(".toast"),!v){l.log(1,"Ui:showDialog","Event target is not a (or in a) toast element, ignoring event")();return}let x=!!v.querySelector("input, textarea, button");if(console.log("toastEventHandler",x,y,v.contains(y.target),v===y.target),x){if(y.key!=="Escape")return;h(v)}h(v)},b=l.doc.createElement("div");if(b.title="Click or Esc to clear this notifcation",b.setAttribute("class","toast ".concat(e)),b.setAttribute("role",e==="alert"?"alertdialog":"dialog"),b.dataset.modal=t.modal,b.dataset.autohide=t.autohide,b.dataset.autoHideDelay=t.autoHideDelay,b.innerHTML=o,t.appendToast===!0){let y=Array.from(l.doc.body.querySelectorAll(".toast")).pop();y?y.insertAdjacentElement("afterend",b):l.doc.body.insertBefore(b,l.doc.body.firstChild)}else l.doc.body.insertBefore(b,l.doc.body.firstChild);b.addEventListener("keyup",m),b.addEventListener("click",m),b.addEventListener("touchend",m),t.autohide===!0&&setInterval(()=>{h(b)},t.autoHideDelay);let g;return t.modal===!0&&(g=l.doc.getElementById("toaster"),g===null&&(g=l.doc.createElement("div"),g.id="toaster",g.title="Click, touch, or ESC to clear notifcations",g.setAttribute("class","toaster"),g.setAttribute("arial-label","Toast message"),g.addEventListener("click",f),g.addEventListener("touchend",f),l.doc.body.addEventListener("keyup",f),l.doc.body.insertAdjacentElement("afterbegin",g))),b}showOverlay(e){return Mt(e)}ui(e){let t={};e._ui?t=e:t._ui=e,this._uiManager(t)}uiGet(e,t=null){let i=l.doc.querySelectorAll(e),s=[];return i.forEach(r=>{if(t){t==="classes"&&(t="class");let o=r.getAttribute(t);if(o==null)try{o=r[t]}catch{}if(o==null)t.toLowerCase()==="value"?s.push(r.innerText):s.push("Property '".concat(t,"' not found"));else{let a={},c=o.constructor.name.toLowerCase();if(c==="namednodemap")for(let h of o)a[h.name]=o[h.name].value;else if(!c.includes("map"))a[t]=o;else{let h={};for(let f in o)h[f]=o[f]}a.class&&(a.classes=Array.from(r.classList)),s.push(a)}}else s.push(this.nodeGet(r,e))}),s}uiEnhanceElement(e,t){this._uiComposeComponent(e,t)}createTable(e=[],t={parent:"body"}){if(!t.parent)throw new Error("[ui.js:createTable] opts.parent must be provided");this.buildHtmlTable(e,t)}buildHtmlTable(e,t={}){let i,s=Object.prototype.toString.apply(e);if(s==="[object Array]"||s==="[object Object]")i=Object.keys(e),e=Object.values(e);else{let f=l.doc.createElement("p");return f.textContent="Input data is not an array or an object, cannot create a table.",f}i.length>1e3&&l.log(1,"Uib:buildHtmlTable","Warning, data is ".concat(i.length," rows. Anything over 1,000 can get very slow to complete."))();let r=l.doc.createElement("table"),o=l.doc.createElement("thead"),a=l.doc.createElement("tr");if(!t.cols){if(e.length<1)throw new Error("[ui.js:buildHtmlTable] When no opts.cols is provided, data must contain at least 1 row");let f=Object.prototype.toString.apply(e[0])!=="[object Array]";a.dataset.colReference="",t.cols=[],Object.keys(e[0]).forEach((m,b)=>{t.cols.push({index:b,hasName:f,name:f?m:void 0,key:m!=null?m:b,title:m})})}r.cols=t.cols,t.cols.forEach(f=>{let m=l.doc.createElement("th");m.textContent=f.title,f.hasName===!0&&(m.dataset.colName=name),a.appendChild(m)}),o.appendChild(a),r.appendChild(o);let c=l.doc.createElement("tbody");r.appendChild(c);let h={allowHTML:!0,cols:t.cols};if(e.forEach((f,m)=>{isNaN(Number(i[m]))?h.rowId=i[m]:h.rowId=void 0,this.tblAddRow(r,f,h)}),t.parent){let f;typeof t.parent=="string"?f=l.doc.querySelector(t.parent):f=t.parent;try{f.appendChild(r)}catch(m){throw new Error("[ui.js:buildHtmlTable] Could not add table to parent. ".concat(m.message))}return}return r}tblAddRow(e,t={},i={}){let s=Object.prototype.toString.apply(e);if(Object.prototype.toString.apply(i)!=="[object Object]")throw new Error("[tblAddDataRow] options must be an object");let r=Object.prototype.toString.apply(t);if(r!=="[object Object]"&&r!=="[object Array]")throw new Error("[tblAddDataRow] rowData MUST be an object or an array containing column/cell data for each column");let o;if(s==="[object HTMLTableElement]")o=e;else if(o=l.doc.querySelector(e),!o)throw new Error('[tblAddDataRow] Table with CSS Selector "'.concat(e,'" not found'));i.body||(i.body=0),"allowHTML"in i||(i.allowHTML=!1);let a=o.getElementsByTagName("tbody")[i.body];if(!a)throw new Error("[tblAddDataRow] Table must have a tbody tag, tbody section ".concat(i.body," does not exist"));i.cols||(i.cols=this.tblGetColMeta(o));let c=i.cols,h=l.doc.createElement("tr");i.rowId&&(h.id=i.rowId);let f=[];for(let m of c){let b=l.doc.createElement("td");b.colMeta=m,m.hasName&&(b.dataset.colName=m.name),f.push(b)}if(Object.keys(t).forEach((m,b,g)=>{let y=f.find(x=>{var N;return((N=x==null?void 0:x.colMeta)==null?void 0:N.name)===m}),v;if(y)v=t[m];else{let x=Number(m);isNaN(x)&&(x=b),x<=f.length-1&&(y=f[x],v=Object.values(t)[x])}y&&(i.allowHTML?y.innerHTML=this.sanitiseHTML(v):y.textContent=v)}),h.append(...f),"afterRow"in i){let m=a.rows[i.afterRow];if(m)return m.after(h)}else if("beforeRow"in i){let m=a.rows[i.beforeRow];if(m)return m.before(h)}else if("replaceRow"in i){let m=a.rows[i.replaceRow];if(m)return m.replaceWith(h)}return a.appendChild(h)}tblAddListener(e,t={},i={}){let s=l.doc.querySelector(e);if(!s)throw new Error('Table with CSS Selector "'.concat(e,'" not found'));if(typeof i!="object")throw new Error('The "out" argument MUST be an object');t.eventScope||(t.eventScope="row"),t.returnType||(t.returnType="text"),t.eventType||(t.eventType="click"),t.pad||(t.pad=3),t.logLevel||(t.logLevel=2),"send"in t||(t.send=!0),s.querySelector("tbody").addEventListener(t.eventType,r=>{Object.keys(i).forEach(c=>delete i[c]);let o=r.target.closest("tr"),a=r.target.closest("td");if(o){i.clickType=t.eventScope,i.eventType=t.eventType;let c=i.rowIndex=o.rowIndex,h=i.cellIndex=a.cellIndex+1;if(o.id&&(i.rowId=o.id),t.eventScope==="row")o.querySelectorAll("td").forEach(f=>{let m=this.tblGetCellName(f,t.pad);i[m]=t.returnType==="text"?f.textContent.trim():f.innerHTML});else{let f=this.tblGetCellName(a,t.pad);i[f]=t.returnType==="text"?a.textContent.trim():a.innerHTML}l.log(t.logLevel,"Ui:tblAddClickListener","".concat(t.eventScope," ").concat(t.eventType," on row=").concat(c,", col=").concat(h,", data: "),i)(),t.send===!0&&l.win.uibuilder&&l.win.uibuilder.send({topic:"".concat(e," ").concat(t.eventScope," ").concat(t.eventType),payload:i})}})}tblFindColMeta(e,t,i){if(!t&&!i)throw new Error("[tblFindColMeta] Either the column metadata array or the HTML table element must be provided");!t&&i&&(t=this.tblGetColMeta(i));let s;if(t[e])s=t[e];else{let r=t.find(o=>o.name===e||o.index===Number(e));r&&(s=r)}return s}tblGetCellName(e,t=3){var i;return(i=e.getAttribute("data-col-name"))!=null?i:"C".concat(String(e.cellIndex+1).padStart(t,"0"))}tblGetColMeta(e,t={}){var o,a,c;if(t.pad||(t.pad=3),e.cols)return e.cols;let i=(o=e.querySelector("tr[data-col-reference]"))==null?void 0:o.children;if(i||(i=(a=e.querySelector("thead>tr:first-of-type"))==null?void 0:a.children),i||(i=(c=e.querySelector("tr:first-of-type"))==null?void 0:c.children),!i)return l.log(1,"Ui:tblGetColMeta","No columns found in table")(),[];let s=[],r;for(r of i){let h=!!r.dataset.colName,f=r.dataset.colName,m=r.cellIndex+1,b=h?f:"C".concat(String(r.cellIndex+1).padStart(t.pad,"0"));s.push({index:m,hasName:h,name:f,key:b,title:r.textContent})}return e.cols=s,s}tblRemoveRow(e,t,i={}){let s=Object.prototype.toString.apply(e);if(Object.prototype.toString.apply(i)!=="[object Object]")throw new Error("[tblRemoveRow] options must be an object");let r;if(s==="[object HTMLTableElement]")r=e;else if(r=l.doc.querySelector(e),!r)throw new Error('[tblRemoveRow] Table with CSS Selector "'.concat(e,'" not found'));i.body||(i.body=0);let o=r.getElementsByTagName("tbody")[i.body];if(!o)throw new Error("[tblAddDataRow] Table must have a tbody tag, tbody section ".concat(i.body," does not exist"));o.deleteRow(t)}},p(l,"win"),p(l,"doc"),p(l,"log"),p(l,"mdOpts"),p(l,"md"),l),It=Li;var U=Object.create(null);U.open="0";U.close="1";U.ping="2";U.pong="3";U.message="4";U.upgrade="5";U.noop="6";var Me=Object.create(null);Object.keys(U).forEach(n=>{Me[U[n]]=n});var Ie={type:"error",data:"parser error"};var Ht=typeof Blob=="function"||typeof Blob<"u"&&Object.prototype.toString.call(Blob)==="[object BlobConstructor]",Pt=typeof ArrayBuffer=="function",Bt=n=>typeof ArrayBuffer.isView=="function"?ArrayBuffer.isView(n):n&&n.buffer instanceof ArrayBuffer,De=({type:n,data:e},t,i)=>Ht&&e instanceof Blob?t?i(e):Dt(e,i):Pt&&(e instanceof ArrayBuffer||Bt(e))?t?i(e):Dt(new Blob([e]),i):i(U[n]+(e||"")),Dt=(n,e)=>{let t=new FileReader;return t.onload=function(){let i=t.result.split(",")[1];e("b"+(i||""))},t.readAsDataURL(n)};function Ut(n){return n instanceof Uint8Array?n:n instanceof ArrayBuffer?new Uint8Array(n):new Uint8Array(n.buffer,n.byteOffset,n.byteLength)}var ht;function qt(n,e){if(Ht&&n.data instanceof Blob)return n.data.arrayBuffer().then(Ut).then(e);if(Pt&&(n.data instanceof ArrayBuffer||Bt(n.data)))return e(Ut(n.data));De(n,!1,t=>{ht||(ht=new TextEncoder),e(ht.encode(t))})}var jt="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",Ue=typeof Uint8Array>"u"?[]:new Uint8Array(256);for(let n=0;n<jt.length;n++)Ue[jt.charCodeAt(n)]=n;var Ft=n=>{let e=n.length*.75,t=n.length,i,s=0,r,o,a,c;n[n.length-1]==="="&&(e--,n[n.length-2]==="="&&e--);let h=new ArrayBuffer(e),f=new Uint8Array(h);for(i=0;i<t;i+=4)r=Ue[n.charCodeAt(i)],o=Ue[n.charCodeAt(i+1)],a=Ue[n.charCodeAt(i+2)],c=Ue[n.charCodeAt(i+3)],f[s++]=r<<2|o>>4,f[s++]=(o&15)<<4|a>>2,f[s++]=(a&3)<<6|c&63;return h};var Ni=typeof ArrayBuffer=="function",He=(n,e)=>{if(typeof n!="string")return{type:"message",data:Vt(n,e)};let t=n.charAt(0);return t==="b"?{type:"message",data:$i(n.substring(1),e)}:Me[t]?n.length>1?{type:Me[t],data:n.substring(1)}:{type:Me[t]}:Ie},$i=(n,e)=>{if(Ni){let t=Ft(n);return Vt(t,e)}else return{base64:!0,data:n}},Vt=(n,e)=>e==="blob"?n instanceof Blob?n:new Blob([n]):n instanceof ArrayBuffer?n:n.buffer;var Wt="",zt=(n,e)=>{let t=n.length,i=new Array(t),s=0;n.forEach((r,o)=>{De(r,!1,a=>{i[o]=a,++s===t&&e(i.join(Wt))})})},Yt=(n,e)=>{let t=n.split(Wt),i=[];for(let s=0;s<t.length;s++){let r=He(t[s],e);if(i.push(r),r.type==="error")break}return i};function Kt(){return new TransformStream({transform(n,e){qt(n,t=>{let i=t.length,s;if(i<126)s=new Uint8Array(1),new DataView(s.buffer).setUint8(0,i);else if(i<65536){s=new Uint8Array(3);let r=new DataView(s.buffer);r.setUint8(0,126),r.setUint16(1,i)}else{s=new Uint8Array(9);let r=new DataView(s.buffer);r.setUint8(0,127),r.setBigUint64(1,BigInt(i))}n.data&&typeof n.data!="string"&&(s[0]|=128),e.enqueue(s),e.enqueue(t)})}})}var dt;function et(n){return n.reduce((e,t)=>e+t.length,0)}function tt(n,e){if(n[0].length===e)return n.shift();let t=new Uint8Array(e),i=0;for(let s=0;s<e;s++)t[s]=n[0][i++],i===n[0].length&&(n.shift(),i=0);return n.length&&i<n[0].length&&(n[0]=n[0].slice(i)),t}function Gt(n,e){dt||(dt=new TextDecoder);let t=[],i=0,s=-1,r=!1;return new TransformStream({transform(o,a){for(t.push(o);;){if(i===0){if(et(t)<1)break;let c=tt(t,1);r=(c[0]&128)===128,s=c[0]&127,s<126?i=3:s===126?i=1:i=2}else if(i===1){if(et(t)<2)break;let c=tt(t,2);s=new DataView(c.buffer,c.byteOffset,c.length).getUint16(0),i=3}else if(i===2){if(et(t)<8)break;let c=tt(t,8),h=new DataView(c.buffer,c.byteOffset,c.length),f=h.getUint32(0);if(f>Math.pow(2,21)-1){a.enqueue(Ie);break}s=f*Math.pow(2,32)+h.getUint32(4),i=3}else{if(et(t)<s)break;let c=tt(t,s);a.enqueue(He(r?c:dt.decode(c),e)),i=0}if(s===0||s>n){a.enqueue(Ie);break}}}})}var ft=4;function T(n){if(n)return Ri(n)}function Ri(n){for(var e in T.prototype)n[e]=T.prototype[e];return n}T.prototype.on=T.prototype.addEventListener=function(n,e){return this._callbacks=this._callbacks||{},(this._callbacks["$"+n]=this._callbacks["$"+n]||[]).push(e),this};T.prototype.once=function(n,e){function t(){this.off(n,t),e.apply(this,arguments)}return t.fn=e,this.on(n,t),this};T.prototype.off=T.prototype.removeListener=T.prototype.removeAllListeners=T.prototype.removeEventListener=function(n,e){if(this._callbacks=this._callbacks||{},arguments.length==0)return this._callbacks={},this;var t=this._callbacks["$"+n];if(!t)return this;if(arguments.length==1)return delete this._callbacks["$"+n],this;for(var i,s=0;s<t.length;s++)if(i=t[s],i===e||i.fn===e){t.splice(s,1);break}return t.length===0&&delete this._callbacks["$"+n],this};T.prototype.emit=function(n){this._callbacks=this._callbacks||{};for(var e=new Array(arguments.length-1),t=this._callbacks["$"+n],i=1;i<arguments.length;i++)e[i-1]=arguments[i];if(t){t=t.slice(0);for(var i=0,s=t.length;i<s;++i)t[i].apply(this,e)}return this};T.prototype.emitReserved=T.prototype.emit;T.prototype.listeners=function(n){return this._callbacks=this._callbacks||{},this._callbacks["$"+n]||[]};T.prototype.hasListeners=function(n){return!!this.listeners(n).length};var j=typeof Promise=="function"&&typeof Promise.resolve=="function"?e=>Promise.resolve().then(e):(e,t)=>t(e,0),$=typeof self<"u"?self:typeof window<"u"?window:Function("return this")(),Jt="arraybuffer";function it(n,...e){return e.reduce((t,i)=>(n.hasOwnProperty(i)&&(t[i]=n[i]),t),{})}var Mi=$.setTimeout,Ii=$.clearTimeout;function F(n,e){e.useNativeTimers?(n.setTimeoutFn=Mi.bind($),n.clearTimeoutFn=Ii.bind($)):(n.setTimeoutFn=$.setTimeout.bind($),n.clearTimeoutFn=$.clearTimeout.bind($))}var Di=1.33;function Xt(n){return typeof n=="string"?Ui(n):Math.ceil((n.byteLength||n.size)*Di)}function Ui(n){let e=0,t=0;for(let i=0,s=n.length;i<s;i++)e=n.charCodeAt(i),e<128?t+=1:e<2048?t+=2:e<55296||e>=57344?t+=3:(i++,t+=4);return t}function st(){return Date.now().toString(36).substring(3)+Math.random().toString(36).substring(2,5)}function Qt(n){let e="";for(let t in n)n.hasOwnProperty(t)&&(e.length&&(e+="&"),e+=encodeURIComponent(t)+"="+encodeURIComponent(n[t]));return e}function Zt(n){let e={},t=n.split("&");for(let i=0,s=t.length;i<s;i++){let r=t[i].split("=");e[decodeURIComponent(r[0])]=decodeURIComponent(r[1])}return e}var rt=class extends Error{constructor(e,t,i){super(e),this.description=t,this.context=i,this.type="TransportError"}},V=class extends T{constructor(e){super(),this.writable=!1,F(this,e),this.opts=e,this.query=e.query,this.socket=e.socket,this.supportsBinary=!e.forceBase64}onError(e,t,i){return super.emitReserved("error",new rt(e,t,i)),this}open(){return this.readyState="opening",this.doOpen(),this}close(){return(this.readyState==="opening"||this.readyState==="open")&&(this.doClose(),this.onClose()),this}send(e){this.readyState==="open"&&this.write(e)}onOpen(){this.readyState="open",this.writable=!0,super.emitReserved("open")}onData(e){let t=He(e,this.socket.binaryType);this.onPacket(t)}onPacket(e){super.emitReserved("packet",e)}onClose(e){this.readyState="closed",super.emitReserved("close",e)}pause(e){}createUri(e,t={}){return e+"://"+this._hostname()+this._port()+this.opts.path+this._query(t)}_hostname(){let e=this.opts.hostname;return e.indexOf(":")===-1?e:"["+e+"]"}_port(){return this.opts.port&&(this.opts.secure&&Number(this.opts.port)!==443||!this.opts.secure&&Number(this.opts.port)!==80)?":"+this.opts.port:""}_query(e){let t=Qt(e);return t.length?"?"+t:""}};var Pe=class extends V{constructor(){super(...arguments),this._polling=!1}get name(){return"polling"}doOpen(){this._poll()}pause(e){this.readyState="pausing";let t=()=>{this.readyState="paused",e()};if(this._polling||!this.writable){let i=0;this._polling&&(i++,this.once("pollComplete",function(){--i||t()})),this.writable||(i++,this.once("drain",function(){--i||t()}))}else t()}_poll(){this._polling=!0,this.doPoll(),this.emitReserved("poll")}onData(e){let t=i=>{if(this.readyState==="opening"&&i.type==="open"&&this.onOpen(),i.type==="close")return this.onClose({description:"transport closed by the server"}),!1;this.onPacket(i)};Yt(e,this.socket.binaryType).forEach(t),this.readyState!=="closed"&&(this._polling=!1,this.emitReserved("pollComplete"),this.readyState==="open"&&this._poll())}doClose(){let e=()=>{this.write([{type:"close"}])};this.readyState==="open"?e():this.once("open",e)}write(e){this.writable=!1,zt(e,t=>{this.doWrite(t,()=>{this.writable=!0,this.emitReserved("drain")})})}uri(){let e=this.opts.secure?"https":"http",t=this.query||{};return this.opts.timestampRequests!==!1&&(t[this.opts.timestampParam]=st()),!this.supportsBinary&&!t.sid&&(t.b64=1),this.createUri(e,t)}};var ei=!1;try{ei=typeof XMLHttpRequest<"u"&&"withCredentials"in new XMLHttpRequest}catch{}var ti=ei;function Hi(){}var pt=class extends Pe{constructor(e){if(super(e),typeof location<"u"){let t=location.protocol==="https:",i=location.port;i||(i=t?"443":"80"),this.xd=typeof location<"u"&&e.hostname!==location.hostname||i!==e.port}}doWrite(e,t){let i=this.request({method:"POST",data:e});i.on("success",t),i.on("error",(s,r)=>{this.onError("xhr post error",s,r)})}doPoll(){let e=this.request();e.on("data",this.onData.bind(this)),e.on("error",(t,i)=>{this.onError("xhr poll error",t,i)}),this.pollXhr=e}},K=class n extends T{constructor(e,t,i){super(),this.createRequest=e,F(this,i),this._opts=i,this._method=i.method||"GET",this._uri=t,this._data=i.data!==void 0?i.data:null,this._create()}_create(){var e;let t=it(this._opts,"agent","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","autoUnref");t.xdomain=!!this._opts.xd;let i=this._xhr=this.createRequest(t);try{i.open(this._method,this._uri,!0);try{if(this._opts.extraHeaders){i.setDisableHeaderCheck&&i.setDisableHeaderCheck(!0);for(let s in this._opts.extraHeaders)this._opts.extraHeaders.hasOwnProperty(s)&&i.setRequestHeader(s,this._opts.extraHeaders[s])}}catch{}if(this._method==="POST")try{i.setRequestHeader("Content-type","text/plain;charset=UTF-8")}catch{}try{i.setRequestHeader("Accept","*/*")}catch{}(e=this._opts.cookieJar)===null||e===void 0||e.addCookies(i),"withCredentials"in i&&(i.withCredentials=this._opts.withCredentials),this._opts.requestTimeout&&(i.timeout=this._opts.requestTimeout),i.onreadystatechange=()=>{var s;i.readyState===3&&((s=this._opts.cookieJar)===null||s===void 0||s.parseCookies(i.getResponseHeader("set-cookie"))),i.readyState===4&&(i.status===200||i.status===1223?this._onLoad():this.setTimeoutFn(()=>{this._onError(typeof i.status=="number"?i.status:0)},0))},i.send(this._data)}catch(s){this.setTimeoutFn(()=>{this._onError(s)},0);return}typeof document<"u"&&(this._index=n.requestsCount++,n.requests[this._index]=this)}_onError(e){this.emitReserved("error",e,this._xhr),this._cleanup(!0)}_cleanup(e){if(!(typeof this._xhr>"u"||this._xhr===null)){if(this._xhr.onreadystatechange=Hi,e)try{this._xhr.abort()}catch{}typeof document<"u"&&delete n.requests[this._index],this._xhr=null}}_onLoad(){let e=this._xhr.responseText;e!==null&&(this.emitReserved("data",e),this.emitReserved("success"),this._cleanup())}abort(){this._cleanup()}};K.requestsCount=0;K.requests={};if(typeof document<"u"){if(typeof attachEvent=="function")attachEvent("onunload",ii);else if(typeof addEventListener=="function"){let n="onpagehide"in $?"pagehide":"unload";addEventListener(n,ii,!1)}}function ii(){for(let n in K.requests)K.requests.hasOwnProperty(n)&&K.requests[n].abort()}var Pi=(function(){let n=si({xdomain:!1});return n&&n.responseType!==null})(),G=class extends pt{constructor(e){super(e);let t=e&&e.forceBase64;this.supportsBinary=Pi&&!t}request(e={}){return Object.assign(e,{xd:this.xd},this.opts),new K(si,this.uri(),e)}};function si(n){let e=n.xdomain;try{if(typeof XMLHttpRequest<"u"&&(!e||ti))return new XMLHttpRequest}catch{}if(!e)try{return new $[["Active"].concat("Object").join("X")]("Microsoft.XMLHTTP")}catch{}}var ri=typeof navigator<"u"&&typeof navigator.product=="string"&&navigator.product.toLowerCase()==="reactnative",bt=class extends V{get name(){return"websocket"}doOpen(){let e=this.uri(),t=this.opts.protocols,i=ri?{}:it(this.opts,"agent","perMessageDeflate","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","localAddress","protocolVersion","origin","maxPayload","family","checkServerIdentity");this.opts.extraHeaders&&(i.headers=this.opts.extraHeaders);try{this.ws=this.createSocket(e,t,i)}catch(s){return this.emitReserved("error",s)}this.ws.binaryType=this.socket.binaryType,this.addEventListeners()}addEventListeners(){this.ws.onopen=()=>{this.opts.autoUnref&&this.ws._socket.unref(),this.onOpen()},this.ws.onclose=e=>this.onClose({description:"websocket connection closed",context:e}),this.ws.onmessage=e=>this.onData(e.data),this.ws.onerror=e=>this.onError("websocket error",e)}write(e){this.writable=!1;for(let t=0;t<e.length;t++){let i=e[t],s=t===e.length-1;De(i,this.supportsBinary,r=>{try{this.doWrite(i,r)}catch{}s&&j(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){typeof this.ws<"u"&&(this.ws.onerror=()=>{},this.ws.close(),this.ws=null)}uri(){let e=this.opts.secure?"wss":"ws",t=this.query||{};return this.opts.timestampRequests&&(t[this.opts.timestampParam]=st()),this.supportsBinary||(t.b64=1),this.createUri(e,t)}},mt=$.WebSocket||$.MozWebSocket,J=class extends bt{createSocket(e,t,i){return ri?new mt(e,t,i):t?new mt(e,t):new mt(e)}doWrite(e,t){this.ws.send(t)}};var fe=class extends V{get name(){return"webtransport"}doOpen(){try{this._transport=new WebTransport(this.createUri("https"),this.opts.transportOptions[this.name])}catch(e){return this.emitReserved("error",e)}this._transport.closed.then(()=>{this.onClose()}).catch(e=>{this.onError("webtransport error",e)}),this._transport.ready.then(()=>{this._transport.createBidirectionalStream().then(e=>{let t=Gt(Number.MAX_SAFE_INTEGER,this.socket.binaryType),i=e.readable.pipeThrough(t).getReader(),s=Kt();s.readable.pipeTo(e.writable),this._writer=s.writable.getWriter();let r=()=>{i.read().then(({done:a,value:c})=>{a||(this.onPacket(c),r())}).catch(a=>{})};r();let o={type:"open"};this.query.sid&&(o.data='{"sid":"'.concat(this.query.sid,'"}')),this._writer.write(o).then(()=>this.onOpen())})})}write(e){this.writable=!1;for(let t=0;t<e.length;t++){let i=e[t],s=t===e.length-1;this._writer.write(i).then(()=>{s&&j(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){var e;(e=this._transport)===null||e===void 0||e.close()}};var gt={websocket:J,webtransport:fe,polling:G};var Bi=/^(?:(?![^:@\/?#]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@\/?#]*)(?::([^:@\/?#]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,qi=["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"];function pe(n){if(n.length>8e3)throw"URI too long";let e=n,t=n.indexOf("["),i=n.indexOf("]");t!=-1&&i!=-1&&(n=n.substring(0,t)+n.substring(t,i).replace(/:/g,";")+n.substring(i,n.length));let s=Bi.exec(n||""),r={},o=14;for(;o--;)r[qi[o]]=s[o]||"";return t!=-1&&i!=-1&&(r.source=e,r.host=r.host.substring(1,r.host.length-1).replace(/;/g,":"),r.authority=r.authority.replace("[","").replace("]","").replace(/;/g,":"),r.ipv6uri=!0),r.pathNames=ji(r,r.path),r.queryKey=Fi(r,r.query),r}function ji(n,e){let t=/\/{2,9}/g,i=e.replace(t,"/").split("/");return(e.slice(0,1)=="/"||e.length===0)&&i.splice(0,1),e.slice(-1)=="/"&&i.splice(i.length-1,1),i}function Fi(n,e){let t={};return e.replace(/(?:^|&)([^&=]*)=?([^&]*)/g,function(i,s,r){s&&(t[s]=r)}),t}var yt=typeof addEventListener=="function"&&typeof removeEventListener=="function",nt=[];yt&&addEventListener("offline",()=>{nt.forEach(n=>n())},!1);var re=class n extends T{constructor(e,t){if(super(),this.binaryType=Jt,this.writeBuffer=[],this._prevBufferLen=0,this._pingInterval=-1,this._pingTimeout=-1,this._maxPayload=-1,this._pingTimeoutTime=1/0,e&&typeof e=="object"&&(t=e,e=null),e){let i=pe(e);t.hostname=i.host,t.secure=i.protocol==="https"||i.protocol==="wss",t.port=i.port,i.query&&(t.query=i.query)}else t.host&&(t.hostname=pe(t.host).host);F(this,t),this.secure=t.secure!=null?t.secure:typeof location<"u"&&location.protocol==="https:",t.hostname&&!t.port&&(t.port=this.secure?"443":"80"),this.hostname=t.hostname||(typeof location<"u"?location.hostname:"localhost"),this.port=t.port||(typeof location<"u"&&location.port?location.port:this.secure?"443":"80"),this.transports=[],this._transportsByName={},t.transports.forEach(i=>{let s=i.prototype.name;this.transports.push(s),this._transportsByName[s]=i}),this.opts=Object.assign({path:"/engine.io",agent:!1,withCredentials:!1,upgrade:!0,timestampParam:"t",rememberUpgrade:!1,addTrailingSlash:!0,rejectUnauthorized:!0,perMessageDeflate:{threshold:1024},transportOptions:{},closeOnBeforeunload:!1},t),this.opts.path=this.opts.path.replace(/\/$/,"")+(this.opts.addTrailingSlash?"/":""),typeof this.opts.query=="string"&&(this.opts.query=Zt(this.opts.query)),yt&&(this.opts.closeOnBeforeunload&&(this._beforeunloadEventListener=()=>{this.transport&&(this.transport.removeAllListeners(),this.transport.close())},addEventListener("beforeunload",this._beforeunloadEventListener,!1)),this.hostname!=="localhost"&&(this._offlineEventListener=()=>{this._onClose("transport close",{description:"network connection lost"})},nt.push(this._offlineEventListener))),this.opts.withCredentials&&(this._cookieJar=void 0),this._open()}createTransport(e){let t=Object.assign({},this.opts.query);t.EIO=ft,t.transport=e,this.id&&(t.sid=this.id);let i=Object.assign({},this.opts,{query:t,socket:this,hostname:this.hostname,secure:this.secure,port:this.port},this.opts.transportOptions[e]);return new this._transportsByName[e](i)}_open(){if(this.transports.length===0){this.setTimeoutFn(()=>{this.emitReserved("error","No transports available")},0);return}let e=this.opts.rememberUpgrade&&n.priorWebsocketSuccess&&this.transports.indexOf("websocket")!==-1?"websocket":this.transports[0];this.readyState="opening";let t=this.createTransport(e);t.open(),this.setTransport(t)}setTransport(e){this.transport&&this.transport.removeAllListeners(),this.transport=e,e.on("drain",this._onDrain.bind(this)).on("packet",this._onPacket.bind(this)).on("error",this._onError.bind(this)).on("close",t=>this._onClose("transport close",t))}onOpen(){this.readyState="open",n.priorWebsocketSuccess=this.transport.name==="websocket",this.emitReserved("open"),this.flush()