UNPKG

@connectifi/agent-web

Version:

A simple web implementation of a connectifi agent

2 lines 1.91 kB
import{d as n,e as f,f as u}from"./chunk-XKZHR3EO.js";async function d(){if(!document.requestStorageAccess||await document.hasStorageAccess())return!0;try{let e=await navigator.permissions.query({name:"storage-access"});if(!e)return!1;if(e.state==="granted")try{return await document.requestStorageAccess(),!0}catch{return!1}}catch(e){console.error("failed to check storage access:",e)}return!1}var m=typeof window!="undefined"?new URL(window.location.href):void 0,c=m==null?void 0:m.pathname.split("/"),l=c==null?void 0:c[c.length-2];async function g({instanceId:e,instanceTitle:o,instanceUrl:t}){let r=`/api/tunnel/${l}?title=${encodeURIComponent(o||"")}&src=${encodeURIComponent(t||"")}&instanceId=${encodeURIComponent(e||"")}`;try{return(await fetch(r)).json()}catch(s){console.error("failed to call tunnel:",s)}}function h(e,{directory:o,namespace:t,instanceId:r}){let s=`/interop/?instanceId=${r}&${f}=${o}&${u}=${t}`,I=window.location.protocol==="https:"?"wss://":"ws://",R=window.location.host,w=`${I}${R}${s}`,a=new WebSocket(w);return a.onopen=()=>n(e,{topic:"open"}),a.onmessage=({data:i})=>n(e,{topic:"message",data:i}),a.onerror=()=>n(e,{topic:"error"}),a.onclose=({code:i})=>n(e,{topic:"close",code:i,directory:o,namespace:t,instanceId:r}),a}function S(){let e;return async function(t,{data:r}){let s=JSON.parse(r);switch(s.topic){case"connect":e==null||e.close(),e=h(t,s);break;case"send":e==null||e.send(JSON.stringify({action:"send",message:s.message}));break;case"close":e==null||e.close();break;case"has-storage-access":n(t,{topic:"has-storage-access",hasStorageAccess:await d()});break;case"tunnel":n(t,await g(s));break}}}var k=S();function p({ports:e}){if(!e.length)return;window.removeEventListener("message",p);let o=e[0];o.addEventListener("message",k.bind(void 0,o)),o.start(),n(o,{topic:"handshake"})}window.addEventListener("message",p); //# sourceMappingURL=agent-iframe.bundle.js.map