@fkn/lib 0.4.0 → 0.4.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/index.cjs +5 -5
- package/index.d.ts +3 -3
- package/index.js +26 -26
- package/package.json +1 -1
package/index.cjs
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
|
-
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require(`./locator-jHaMLjtv.cjs`);let t=require(`osra`),n=require(`stream`),r=require(`events`),i=require(`ip-address`),a=require(`buffer`);var o=`FKN_WEB_EXTENSION_MAIN_WORLD_CONTENT_SCRIPT_ENABLED_EVENT_KEY`,s=`fknExtension`,c=(0,t.createTypedEventTarget)();typeof document<`u`&&document.addEventListener(o,e=>{c.dispatchEvent(new CustomEvent(`statuschange`,{detail:{enabled:e.detail.enabled}}))});var l=()=>typeof document>`u`?!1:document.documentElement.dataset[s]===`true`,u=null,d=e=>{u=e},ee=150,f=(e=1e3)=>new Promise((t,n)=>{if(l())return t();let r,i=e=>{clearTimeout(r),s.disconnect(),document.removeEventListener(`readystatechange`,c),e()},a=()=>i(async()=>{if(u&&(await u().catch(()=>{}),l()))return t();n(Error(`The FKN WebExtension is not installed, enabled or not exposed on this page.`))}),o=()=>{clearTimeout(r),r=setTimeout(()=>l()?i(t):a(),ee)},s=new MutationObserver(()=>{l()&&i(t)}),c=()=>{document.readyState===`complete`&&!l()&&o()};if(r=setTimeout(a,e),s.observe(document.documentElement,{attributes:!0,attributeFilter:[`data-fkn-extension`]}),document.addEventListener(`readystatechange`,c),document.readyState===`complete`)return o();l()&&i(t)}),te,p=new Proxy({},{get:(n,r)=>async(...n)=>{await f(),te??=(0,t.expose)({},{transport:window,revivableModules:e.l});let i=(await te)[r];return i(...n)}}),m={scope:`network.fetch`,category:`network`,severity:0,title:`Fetch data from other sites`,description:`Lets the app download public data from other websites directly, past the usual cross-origin limits.`},h={scope:`network.fetchCredentialed`,category:`network`,severity:3,unsafe:!0,title:`Fetch from other sites, signed in as you`,description:`Lets the app fetch other sites using your logged-in session cookies, so it can read data only you should see.`},ne=[`fkn.app`,`fkn.dev`],g=e=>{let t;try{t=new URL(e)}catch{return!1}if(t.protocol===`chrome-extension:`||t.protocol===`moz-extension:`)return!0;let n=t.hostname;return ne.some(e=>n===e||n.endsWith(`.${e}`))},_=e=>{if(g(e))throw Error(`fetch: refusing to target the extension's own pages or FKN platform domains`)},re=[`origin`,`referer`],ie=e=>{if(!e?.headers)return;let t=new Headers(e.headers),n=re.map(e=>{let n=t.get(e);return n===null?void 0:[e,n]}).filter(e=>e!==void 0);return n.length?n:void 0},v=async(e,t)=>{let n=new Request(e,t);_(n.url);let r=n.body?await n.arrayBuffer():null;return p.proxyFetch({url:n.url,method:n.method,headers:[...n.headers],body:r,credentials:t?.credentials===`include`?`include`:`omit`,redirect:n.redirect,unsafeHeaders:ie(t),reason:t?.reason,signal:t?.signal??void 0})},ae={scope:`network.readCookie`,category:`network`,severity:3,unsafe:!0,title:`Read a site’s cookie`,description:`Lets the app read a named cookie from another site, which can include the login token only that site should see.`},oe={get:e=>p.getCookie(e)},se={scope:`network.modifyRequestHeaders`,category:`network`,severity:2,unsafe:!0,title:`Rewrite request headers to other sites`,description:`Lets the app set or remove headers (like Origin and Referer) on this page’s own requests to the listed sites.`},ce=e=>p.setRequestHeaderRule(e),y=e=>p.removeRequestHeaderRule({ruleId:e});(()=>{let t={},n=[...e.t.selectorModules,...e.i.selectorModules];for(let e of n)e.render&&!(e.type in t)&&(t[e.type]=e.render);return t})();var b=`FKN_WEB_EXTENSION_ATTACH_FRAME_EVENT_KEY`,x=e=>{if(!e||e===`about:blank`)return!1;let t;try{t=new URL(e,location.href)}catch{return!1}if(t.protocol===`chrome-extension:`||t.protocol===`moz-extension:`)return!0;if(t.protocol===`about:`)return!1;let n=t.hostname;return n===`fkn.app`||n.endsWith(`.fkn.app`)},S=e=>{if(x(e))throw Error(`attachFrame: refusing to target the extension's own pages or fkn.app`)},C={scope:`embed.iframe`,category:`embed`,severity:0,title:`Load another website inside this app`,description:`Lets the app embed external pages directly inside its own view.`},le={scope:`embed.open`,category:`embed`,severity:0,title:`Open a website inside this app`,description:`Lets the app navigate to another site without leaving its window.`},ue=async({iframe:t,domains:n=[]})=>{let r=crypto.randomUUID();if(S(t.src),await f(),!t.isConnected)throw Error(`attachFrame: the iframe must be connected to the document before attaching`);t.dispatchEvent(new CustomEvent(b,{detail:r}));let{executeLocator:i,ensureLocatorPermission:a,goto:o}=await p.attachFrame({marker:r,domains:n}),s=e.r(i,a),c=(e,t={})=>(S(e),o({url:e,...t})),l=()=>t.src;return{...s,goto:c,url:l}},de={request:e=>p.requestPermissions(e.map(e=>({key:e.key,scope:e.scope??``,reason:e.reason})))},fe=32,pe=typeof CSS<`u`&&CSS.supports(`clip-path`,`path('M0 0H1V1H0Z')`),me=e=>{let t=e.style;t.setProperty(`display`,`block`,`important`),t.setProperty(`position`,`fixed`,`important`),t.setProperty(`top`,`0`,`important`),t.setProperty(`left`,`0`,`important`),t.setProperty(`width`,`100%`,`important`),t.setProperty(`height`,`100%`,`important`),t.setProperty(`border`,`none`,`important`),t.setProperty(`clip-path`,`inset(100%)`,`important`),t.setProperty(`background`,`transparent`),t.setProperty(`color-scheme`,`normal`),t.setProperty(`z-index`,`2147483647`),e.setAttribute(`title`,`FKN`)},he=({x:e,y:t,width:n,height:r})=>`M${e} ${t}h${n}v${r}h${-n}Z`,ge=(e,{modal:t,rects:n})=>{if(!pe){let r=t||n.length>0;e.style.setProperty(`pointer-events`,r?`auto`:`none`,`important`),e.style.setProperty(`visibility`,r?`visible`:`hidden`,`important`);return}let r=t?`none`:n.length===0?`inset(100%)`:`path('${n.map(he).join(``)}')`,i=r===`none`||CSS.supports(`clip-path`,r)?r:`inset(100%)`;e.style.setProperty(`clip-path`,i,`important`)},_e=e=>{if(typeof e!=`object`||!e)return null;let{x:t,y:n,width:r,height:i}=e;if(![t,n,r,i].every(e=>typeof e==`number`&&Number.isFinite(e)))return null;let a=window.innerWidth,o=window.innerHeight,s=Math.max(0,Math.min(Math.round(t),a)),c=Math.max(0,Math.min(Math.round(n),o)),l=Math.max(s,Math.min(Math.round(t+r),a)),u=Math.max(c,Math.min(Math.round(n+i),o));return{x:s,y:c,width:l-s,height:u-c}},ve=e=>{if(typeof e!=`object`||!e)return null;let t=e,n=(Array.isArray(t.rects)?t.rects.slice(0,fe):[]).map(_e).filter(e=>e!==null&&e.width>0&&e.height>0);return{modal:t.modal===!0,rects:n}},w=null,ye=()=>w!==null,be=e=>{me(e),ge(e,{modal:!1,rects:[]}),w=e},xe=e=>{if(!w)return;let t=ve(e);t&&ge(w,t)},Se=`https://fkn.app`,T=typeof globalThis<`u`&&globalThis.document?globalThis.document:void 0,Ce=T?.querySelector(`iframe[src="${Se}/api"]`)??null,E=T?.createElement(`iframe`)??null;!Ce&&E&&T&&(E.src=`${Se}/api`,T.body.appendChild(E));var D=Ce??E,O=D?.contentWindow??null;D&&T&&be(D);var k=(()=>{if(typeof window<`u`)return O?{receive:window,emit:O}:void 0;if(typeof self<`u`)return{receive:self,emit:self}})(),we=k!==void 0,A=k?(0,t.expose)({},{key:`fkn-api`,transport:k}):new Promise(()=>{});A.then(e=>{ye()&&e.overlay.setHost(xe)},()=>{});var Te=[`fkn.app`,`fkn.dev`],j=e=>{let t=typeof e==`string`?e:e instanceof URL?e.href:e.url,n;try{n=new URL(t)}catch{return}let r=n.hostname;if(Te.some(e=>r===e||r.endsWith(`.${e}`)))throw Error(`fetch refuses FKN platform domains (${r})`)},M=(e,t)=>(j(e),A.then(n=>n.cloud.fetch(e,t))),Ee=async()=>{let e=await A.then(e=>e.cloud.quota());return{premium:e.premium,overQuota:e.overQuota,throttled:e.overQuota&&!e.premium,usedBytes:e.usedBytes,limitBytes:e.limitBytes,remainingBytes:e.remaining,bytesPerSecond:e.bytesPerSecond,bitsPerSecond:e.bytesPerSecond*8}},De=e.g({lookup:()=>Oe}),Oe=(e,t)=>A.then(n=>n.cloud.dns.lookup(e,t)),ke=new TextEncoder;new TextDecoder;var N=e=>i.Address4.isValid(e),P=e=>i.Address6.isValid(e),Ae=e=>N(e)?4:P(e)?6:0,je=(...e)=>{if(typeof e[0]==`string`)throw Error(`FKN WebVPN does not support IPC connections`);let t=typeof e.at(-1)==`function`?e.at(-1):void 0;return e[0]&&typeof e[0]==`object`?{...e[0],callback:t}:{port:e[0]??0,host:typeof e[1]==`string`?e[1]:void 0,callback:t}},Me=(...e)=>{let t=typeof e.at(-1)==`function`?e.at(-1):void 0,n=e[0]??0,r=typeof e[1]==`string`?e[1]:void 0;return typeof e[0]==`object`?{...e[0],address:e[0].address??r,port:e[0].port??n,callback:t}:{address:r,port:n,callback:t}},Ne=(...e)=>{let t=typeof e.at(-1)==`function`?e.at(-1):void 0,n=e[0];if(typeof e[2]==`number`)return{message:n,offset:e[1],length:e[2],port:typeof e[3]==`number`?e[3]:0,address:typeof e[4]==`string`?e[4]:void 0,callback:t};{let r=typeof e[1]==`number`?e[1]:0,i=typeof e[2]==`string`?e[2]:void 0;return{message:n,offset:0,length:n.length,port:r,address:i,callback:t}}};new TextEncoder,new TextDecoder;var Pe=e.g({Server:()=>I,Socket:()=>F,_default:()=>Le,connect:()=>Fe,createConnection:()=>Ie,createServer:()=>L,default:()=>Le,isIP:()=>Ae,isIPv4:()=>N,isIPv6:()=>P}),F=class extends n.Stream.Duplex{_localAddress;_remoteAddress;_webVPNTcpSocketPromise;constructor(e){if(e?.fd!==void 0)throw Error(`FKN WebVPN does not support file descriptors`);super(e),e?.connection&&this.__webvpn_tcp_socket_init__(e.connection)}__webvpn_tcp_socket_init__(e){if(this._webVPNTcpSocketPromise=e.then(e=>{let t=e.dataReadableStream.getReader(),n=e.dataWritableStream.getWriter();return this._localAddress={address:e.localAddress,family:e.localFamily,port:e.localPort},this._remoteAddress={address:e.remoteAddress,family:e.remoteFamily,port:e.remotePort},{...e,reader:t,writer:n}}).catch(e=>{this.emit(`error`,e)}),!this._webVPNTcpSocketPromise)throw Error(`Socket not connected`);return this._webVPNTcpSocketPromise.then(e=>{e&&this.emit(`connect`)}),this._webVPNTcpSocketPromise}_read(e){if(!this._webVPNTcpSocketPromise)throw Error(`Socket not connected`);this._webVPNTcpSocketPromise.then(e=>{if(!e){this.push(null);return}e.reader.read().then(({value:e,done:t})=>{if(t){this.push(null);return}this._restartTimeoutTimer(),this.push(e)}).catch(e=>{this.destroy(e)})})}_write(e,t,n){if(!this._webVPNTcpSocketPromise){n(Error(`Socket not connected`));return}this._webVPNTcpSocketPromise.then(async t=>{if(!t)throw Error(`Socket not connected`);await t.writer.ready,await t.writer.write(e),this._restartTimeoutTimer(),n()}).catch(n)}connect(...e){let t=je(...e),n=this.__webvpn_tcp_socket_init__(A.then(e=>e.cloud.webvpn.tcpSocket({remoteAddress:t.host??`localhost`,remotePort:t.port})));return t.callback&&n.then(e=>{e&&t.callback.call(this)}),this}_end(...e){return this._webVPNTcpSocketPromise?(e.length!==0&&this.write(e[0],e[1],e[2]),this._webVPNTcpSocketPromise.then(async e=>{e&&await e.end()}),this):this}_destroy(e){return this._timeoutTimer&&clearTimeout(this._timeoutTimer),this._webVPNTcpSocketPromise&&this._webVPNTcpSocketPromise.then(async e=>{e&&await e.destroy()}),this}destroySoon(){this._webVPNTcpSocketPromise&&this._webVPNTcpSocketPromise.then(async e=>{e&&await e.destroySoon()})}resetAndDestroy(){return this._webVPNTcpSocketPromise&&this._webVPNTcpSocketPromise.then(async e=>{e&&await e.resetAndDestroy()}),this}_timeoutMs;_timeoutTimer;_restartTimeoutTimer(){this._timeoutTimer&&clearTimeout(this._timeoutTimer),this._timeoutMs&&(this._timeoutTimer=setTimeout(()=>this.emit(`timeout`),this._timeoutMs))}setTimeout(e,t){return t&&this.on(`timeout`,t),this._timeoutMs=e,this._restartTimeoutTimer(),this}setNoDelay(e){let t=e??!0;return this._setTcpOption({type:0,value:t}),this}setKeepAlive(e,t){let n=e??!1,r=t!==void 0&&t>0?Math.max(1,Math.round(t/1e3)):0;return this._setTcpOption({type:2,enabled:n,initialDelaySeconds:r}),this}setSendBufferSize(e){return this._setTcpOption({type:3,value:e}),this}setRecvBufferSize(e){return this._setTcpOption({type:4,value:e}),this}_typeOfService;getTypeOfService(){return this._typeOfService??0}setTypeOfService(e){return this._typeOfService=e,this}_setTcpOption(e){if(!this._webVPNTcpSocketPromise){this.emit(`error`,Error(`Cannot set socket option before connect`));return}this._webVPNTcpSocketPromise.then(async t=>{if(t)try{await t.setOption(e)}catch(e){this.emit(`error`,e)}})}write(e,t,...n){return super.write(e,t,...n)}address(){return this._localAddress??{}}unref(){return this}ref(){return this}autoSelectFamilyAttemptedAddresses;bufferSize;bytesRead;bytesWritten;connecting;pending;get localAddress(){if(!this._localAddress)throw Error(`Socket is not connected`);return this._localAddress.address}get localPort(){if(!this._localAddress)throw Error(`Socket is not connected`);return this._localAddress.port}get localFamily(){if(!this._localAddress)throw Error(`Socket is not connected`);return this._localAddress.family}readyState;get remoteAddress(){if(!this._remoteAddress)throw Error(`Socket is not connected`);return this._remoteAddress.address}get remotePort(){if(!this._remoteAddress)throw Error(`Socket is not connected`);return this._remoteAddress.port}get remoteFamily(){if(!this._remoteAddress)throw Error(`Socket is not connected`);return this._remoteAddress.family}timeout},I=class extends r.EventEmitter{_localAddress;_webVPNTcpSocketListenerPromise;constructor(e,t){super(e),t&&this.on(`connection`,t),e?.connection&&this.__webvpn_tcp_socket_listener_init__(e.connection)}__webvpn_tcp_socket_listener_init__(e){return this._webVPNTcpSocketListenerPromise=e.then(e=>(this._localAddress={address:e.localAddress,family:e.localFamily,port:e.localPort},e)).catch(e=>{this.emit(`error`,e)}),this._webVPNTcpSocketListenerPromise.then(e=>{e&&this.emit(`listening`)}),this._webVPNTcpSocketListenerPromise}listen(...e){let t=je(...e),n=e=>{let t=new F({connection:Promise.resolve(e)});this.emit(`connection`,t)},r=e=>A.then(r=>r.cloud.webvpn.tcpSocketListener({localAddress:e,localPort:t.port,onConnection:n})),i=t.host?r(t.host):r(`::`).catch(()=>r(`0.0.0.0`)),a=this.__webvpn_tcp_socket_listener_init__(i);return t.callback&&a.then(e=>{e&&t.callback.call(this)}),this}close(e){return this._webVPNTcpSocketListenerPromise&&this._webVPNTcpSocketListenerPromise.then(async t=>{if(t)try{await t.close(),this._localAddress=void 0,this.emit(`close`),e&&e()}catch(t){this._localAddress=void 0,this.emit(`close`),e&&e(t)}}),this}address(){return this._localAddress??null}getConnections(e){throw Error(`Method not implemented.`)}ref(){return this}unref(){return this}maxConnections;connections;listening;async[Symbol.asyncDispose](){}},Fe=(e,t)=>new F().connect(e,t),Ie=(e,t)=>new F().connect(e,t),L=(e,t)=>{typeof e==`function`&&(t=e,e=void 0);let n=new I(e);return t&&n.on(`connection`,t),n},Le={Socket:F,Server:I,connect:Fe,createConnection:Ie,createServer:L,isIP:Ae,isIPv4:N,isIPv6:P},Re=e.g({Socket:()=>ze,createSocket:()=>Ve}),ze=class extends r.EventEmitter{_type;_localAddress;_remoteAddress;_webVPNUdpSocketPromise;constructor(e){if(super(e),!e)throw Error(`Missing options`);this._type=e.type}_lastRecvBufferSize=0;_lastSendBufferSize=0;_lastTtl=64;_lastMulticastTtl=1;_lastMulticastLoopback=!0;_setUdpOption(e){if(!this._webVPNUdpSocketPromise){this.emit(`error`,Error(`Cannot set socket option before bind`));return}this._webVPNUdpSocketPromise.then(async t=>{if(t)try{await t.setOption(e)}catch(e){this.emit(`error`,e)}})}addMembership(e,t){if(i.Address4.isValid(e)){let n=R(e),r=t&&i.Address4.isValid(t)?R(t):new Uint8Array([0,0,0,0]);this._setUdpOption({type:5,group:n,interface:r})}else if(i.Address6.isValid(e)){let t=Be(e);this._setUdpOption({type:7,group:t,ifIndex:0})}else this.emit(`error`,Error(`Invalid multicast address: ${e}`))}address(){if(!this._localAddress)throw Error(`EBADF`);return this._localAddress}bind(...e){let t=Me(...e),n=this._type===`udp6`?`::`:`0.0.0.0`;return this._webVPNUdpSocketPromise=A.then(e=>e.cloud.webvpn.udpSocket({type:this._type,address:t.address??n,port:t.port})).then(e=>{let t=e.dataReadableStream.getReader(),n=async()=>{let{value:e,done:r}=await t.read();r||(this.emit(`message`,a.Buffer.from(e.data),{address:e.address,family:e.family,port:e.port,size:e.size}),n())};return n(),this._localAddress={address:e.localAddress,family:e.localFamily,port:e.localPort},e}).catch(e=>{this.emit(`error`,e)}),this._webVPNUdpSocketPromise.then(e=>{e&&this.emit(`listening`)}),t.callback&&this._webVPNUdpSocketPromise.then(e=>{e&&t.callback()}),this}close(e){if(!this._webVPNUdpSocketPromise)throw Error(`Socket not bound`);return this._webVPNUdpSocketPromise.then(async t=>{if(!t)throw Error(`Socket not bound`);await t.close(),e&&e(),this.emit(`close`)}),this}connect(...e){if(!this._webVPNUdpSocketPromise)throw Error(`Socket not bound`);this._webVPNUdpSocketPromise.then(async t=>{if(!t)throw Error(`Socket not bound`);let n=e[0],r=this._type===`udp6`?`::1`:`127.0.0.1`,i=typeof e[1]==`string`?e[1]:r,a=typeof e.at(-1)==`function`?e.at(-1):void 0;await t.connect({remotePort:n,remoteAddress:i}),this._remoteAddress={address:i,family:this._type===`udp6`?`IPv6`:`IPv4`,port:n},a&&a()})}disconnect(){if(!this._webVPNUdpSocketPromise)throw Error(`Socket not bound`);this._webVPNUdpSocketPromise.then(async e=>{if(!e)throw Error(`Socket not bound`);await e.connect({remotePort:0,remoteAddress:this._type===`udp4`?`0.0.0.0`:`::`})})}dropMembership(e,t){if(i.Address4.isValid(e)){let n=R(e),r=t&&i.Address4.isValid(t)?R(t):new Uint8Array([0,0,0,0]);this._setUdpOption({type:6,group:n,interface:r})}else if(i.Address6.isValid(e)){let t=Be(e);this._setUdpOption({type:8,group:t,ifIndex:0})}else this.emit(`error`,Error(`Invalid multicast address: ${e}`))}getRecvBufferSize(){return this._lastRecvBufferSize}getSendBufferSize(){return this._lastSendBufferSize}getSendQueueSize(){return 0}getSendQueueCount(){return 0}ref(){return this}remoteAddress(){if(!this._remoteAddress)throw Error(`ERR_SOCKET_DGRAM_NOT_CONNECTED`);return{address:this._remoteAddress.address,family:this._remoteAddress.family,port:this._remoteAddress.port}}send(...e){this._webVPNUdpSocketPromise||this.bind();let t=Ne(...e),n=this._type===`udp6`?`::1`:`127.0.0.1`;if(!this._webVPNUdpSocketPromise)throw Error(`Socket not bound`);this._webVPNUdpSocketPromise.then(e=>{if(!e)throw Error(`Socket not bound`);let r=typeof t.message==`string`?ke.encode(t.message):t.message;e.send({...t,address:t.address??n,message:r.buffer})})}setBroadcast(e){this._setUdpOption({type:0,value:e})}setMulticastInterface(e){}setMulticastLoopback(e){return this._setUdpOption({type:3,value:e}),this._setUdpOption({type:4,value:e}),this._lastMulticastLoopback=e,e}setMulticastTTL(e){return this._setUdpOption({type:2,value:e}),this._lastMulticastTtl=e,e}setRecvBufferSize(e){this._setUdpOption({type:10,value:e}),this._lastRecvBufferSize=e}setSendBufferSize(e){this._setUdpOption({type:9,value:e}),this._lastSendBufferSize=e}setTTL(e){return this._setUdpOption({type:1,value:e}),this._lastTtl=e,e}unref(){return this}addSourceSpecificMembership(e,t,n){}dropSourceSpecificMembership(e,t,n){}async[Symbol.asyncDispose](){await new Promise(e=>{this.close(e)})}},R=e=>{let t=e.split(`.`).map(e=>parseInt(e,10));if(t.length!==4||t.some(e=>Number.isNaN(e)||e<0||e>255))throw Error(`Invalid IPv4 address: ${e}`);return new Uint8Array(t)},Be=e=>{let t=new i.Address6(e).getBitsBase16(0,128).match(/.{2}/g);if(!t||t.length!==16)throw Error(`Invalid IPv6 address: ${e}`);return new Uint8Array(t.map(e=>parseInt(e,16)))},Ve=(e,t)=>{let n=new ze(typeof e==`string`?{type:e}:e);return t&&n.on(`message`,t),n},He=e.g({Agent:()=>Y,ClientRequest:()=>q,HTTPParser:()=>U,IncomingMessage:()=>W,METHODS:()=>We,STATUS_CODES:()=>z,Server:()=>J,ServerResponse:()=>K,_default:()=>tt,createServer:()=>et,default:()=>tt,get:()=>$e,globalAgent:()=>Qe,request:()=>X}),Ue=new TextDecoder(`latin1`),We=`ACL.BIND.CHECKOUT.CONNECT.COPY.DELETE.GET.HEAD.LINK.LOCK.M-SEARCH.MERGE.MKACTIVITY.MKCALENDAR.MKCOL.MOVE.NOTIFY.OPTIONS.PATCH.POST.PROPFIND.PROPPATCH.PURGE.PUT.REBIND.REPORT.SEARCH.SOURCE.SUBSCRIBE.TRACE.UNBIND.UNLINK.UNLOCK.UNSUBSCRIBE`.split(`.`),z={100:`Continue`,101:`Switching Protocols`,102:`Processing`,103:`Early Hints`,200:`OK`,201:`Created`,202:`Accepted`,203:`Non-Authoritative Information`,204:`No Content`,205:`Reset Content`,206:`Partial Content`,207:`Multi-Status`,208:`Already Reported`,226:`IM Used`,300:`Multiple Choices`,301:`Moved Permanently`,302:`Found`,303:`See Other`,304:`Not Modified`,305:`Use Proxy`,307:`Temporary Redirect`,308:`Permanent Redirect`,400:`Bad Request`,401:`Unauthorized`,402:`Payment Required`,403:`Forbidden`,404:`Not Found`,405:`Method Not Allowed`,406:`Not Acceptable`,407:`Proxy Authentication Required`,408:`Request Timeout`,409:`Conflict`,410:`Gone`,411:`Length Required`,412:`Precondition Failed`,413:`Payload Too Large`,414:`URI Too Long`,415:`Unsupported Media Type`,416:`Range Not Satisfiable`,417:`Expectation Failed`,418:`I'm a Teapot`,421:`Misdirected Request`,422:`Unprocessable Entity`,423:`Locked`,424:`Failed Dependency`,425:`Too Early`,426:`Upgrade Required`,428:`Precondition Required`,429:`Too Many Requests`,431:`Request Header Fields Too Large`,451:`Unavailable For Legal Reasons`,500:`Internal Server Error`,501:`Not Implemented`,502:`Bad Gateway`,503:`Service Unavailable`,504:`Gateway Timeout`,505:`HTTP Version Not Supported`,506:`Variant Also Negotiates`,507:`Insufficient Storage`,508:`Loop Detected`,509:`Bandwidth Limit Exceeded`,510:`Not Extended`,511:`Network Authentication Required`},Ge=new Set([`content-type`,`content-length`,`user-agent`,`referer`,`host`,`authorization`,`proxy-authorization`,`if-modified-since`,`if-unmodified-since`,`from`,`location`,`max-forwards`,`retry-after`,`etag`,`last-modified`,`server`,`age`,`expires`]),B=13,V=10,Ke=/^[\^_`a-zA-Z\-0-9!#$%&'*+.|~]+$/,H=(e,t)=>(e.code=t,e),qe=(e,t)=>{if(e.length===0)return t;if(t.length===0)return e;let n=new Uint8Array(e.length+t.length);return n.set(e,0),n.set(t,e.length),n},Je=(e,t)=>{for(let n=t;n+1<e.length;n++)if(e[n]===B&&e[n+1]===V)return n;return-1},Ye=e=>{for(let t=0;t+3<e.length;t++)if(e[t]===B&&e[t+1]===V&&e[t+2]===B&&e[t+3]===V)return t;return-1},U=class{buf=new Uint8Array;state=`HEAD`;framing=`none`;bodyRemaining=0;chunkState=`size`;skipBody=!1;constructor(e,t){this.mode=e,this.handlers=t}execute(e){this.buf=qe(this.buf,e);let t=!0;for(;t;)if(t=!1,this.state===`HEAD`){let e=Ye(this.buf);if(e===-1)return;let n=this.buf.subarray(0,e);this.buf=this.buf.subarray(e+4);let r=this.parseHead(n);this.handlers.onHeaders(r),this.setupBody(r),this.framing===`none`?(this.handlers.onComplete(),this.reset(),t=this.buf.length>0):(this.state=`BODY`,t=!0)}else this.consumeBody()&&(this.handlers.onComplete(),this.reset(),t=this.buf.length>0)}finish(){this.state===`BODY`&&this.framing===`eof`&&(this.handlers.onComplete(),this.reset())}reset(){this.state=`HEAD`,this.framing=`none`,this.bodyRemaining=0,this.chunkState=`size`,this.skipBody=!1}parseHead(e){let t=Ue.decode(e).split(`\r
|
|
2
|
-
`),n=t.shift()??``,r=[];for(let e of t)(e.startsWith(` `)||e.startsWith(` `))&&r.length>0?r[r.length-1]+=` `+e.trim():r.push(e);let i=[],a={};for(let e of r){if(!e)continue;let t=e.indexOf(`:`);if(t===-1)continue;let n=e.slice(0,t).trim(),r=e.slice(t+1).trim();i.push(n,r),this.addHeader(a,n,r)}let o={httpVersionMajor:1,httpVersionMinor:1,httpVersion:`1.1`,headers:a,rawHeaders:i};if(this.mode===`request`){let[e,t,r]=n.split(` `);o.method=(e??`GET`).toUpperCase(),o.url=t??`/`,this.applyVersion(o,r)}else{let e=n.indexOf(` `),t=n.slice(0,e),r=n.slice(e+1),i=r.indexOf(` `),a=i===-1?r:r.slice(0,i);o.statusCode=parseInt(a,10)||0,o.statusMessage=i===-1?``:r.slice(i+1),this.applyVersion(o,t)}return o}applyVersion(e,t){let n=/HTTP\/(\d)\.(\d)/i.exec(t??``);n&&(e.httpVersionMajor=parseInt(n[1],10),e.httpVersionMinor=parseInt(n[2],10),e.httpVersion=`${e.httpVersionMajor}.${e.httpVersionMinor}`)}addHeader(e,t,n){let r=t.toLowerCase();if(r===`set-cookie`){let t=e[`set-cookie`];Array.isArray(t)?t.push(n):e[`set-cookie`]=[n];return}let i=e[r];i===void 0?e[r]=n:
|
|
1
|
+
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require(`./locator-jHaMLjtv.cjs`);let t=require(`osra`),n=require(`stream`),r=require(`events`),i=require(`ip-address`),a=require(`buffer`);var o=`FKN_WEB_EXTENSION_MAIN_WORLD_CONTENT_SCRIPT_ENABLED_EVENT_KEY`,s=`fknExtension`,c=(0,t.createTypedEventTarget)();typeof document<`u`&&document.addEventListener(o,e=>{c.dispatchEvent(new CustomEvent(`statuschange`,{detail:{enabled:e.detail.enabled}}))});var l=()=>typeof document>`u`?!1:document.documentElement.dataset[s]===`true`,u=null,d=e=>{u=e},ee=150,f=(e=1e3)=>new Promise((t,n)=>{if(l())return t();let r,i=e=>{clearTimeout(r),s.disconnect(),document.removeEventListener(`readystatechange`,c),e()},a=()=>i(async()=>{if(u&&(await u().catch(()=>{}),l()))return t();n(Error(`The FKN WebExtension is not installed, enabled or not exposed on this page.`))}),o=()=>{clearTimeout(r),r=setTimeout(()=>l()?i(t):a(),ee)},s=new MutationObserver(()=>{l()&&i(t)}),c=()=>{document.readyState===`complete`&&!l()&&o()};if(r=setTimeout(a,e),s.observe(document.documentElement,{attributes:!0,attributeFilter:[`data-fkn-extension`]}),document.addEventListener(`readystatechange`,c),document.readyState===`complete`)return o();l()&&i(t)}),te,p=new Proxy({},{get:(n,r)=>async(...n)=>{await f(),te??=(0,t.expose)({},{transport:window,revivableModules:e.l});let i=(await te)[r];return i(...n)}}),m={scope:`network.fetch`,category:`network`,severity:0,title:`Fetch data from other sites`,description:`Lets the app download public data from other websites directly, past the usual cross-origin limits.`},h={scope:`network.fetchCredentialed`,category:`network`,severity:3,unsafe:!0,title:`Fetch from other sites, signed in as you`,description:`Lets the app fetch other sites using your logged-in session cookies, so it can read data only you should see.`},ne=[`fkn.app`,`fkn.dev`],g=e=>{let t;try{t=new URL(e)}catch{return!1}if(t.protocol===`chrome-extension:`||t.protocol===`moz-extension:`)return!0;let n=t.hostname;return ne.some(e=>n===e||n.endsWith(`.${e}`))},_=e=>{if(g(e))throw Error(`fetch: refusing to target the extension's own pages or FKN platform domains`)},re=[`origin`,`referer`],ie=e=>{if(!e?.headers)return;let t=new Headers(e.headers),n=re.map(e=>{let n=t.get(e);return n===null?void 0:[e,n]}).filter(e=>e!==void 0);return n.length?n:void 0},v=async(e,t)=>{let n=new Request(e,t);_(n.url);let r=n.body?await n.arrayBuffer():null;return p.proxyFetch({url:n.url,method:n.method,headers:[...n.headers],body:r,credentials:t?.credentials===`include`?`include`:`omit`,redirect:n.redirect,unsafeHeaders:ie(t),reason:t?.reason,signal:t?.signal??void 0})},ae={scope:`network.readCookie`,category:`network`,severity:3,unsafe:!0,title:`Read a site’s cookie`,description:`Lets the app read a named cookie from another site, which can include the login token only that site should see.`},oe={get:e=>p.getCookie(e)},se={scope:`network.modifyRequestHeaders`,category:`network`,severity:2,unsafe:!0,title:`Rewrite request headers to other sites`,description:`Lets the app set or remove headers (like Origin and Referer) on this page’s own requests to the listed sites.`},ce=e=>p.setRequestHeaderRule(e),y=e=>p.removeRequestHeaderRule({ruleId:e});(()=>{let t={},n=[...e.t.selectorModules,...e.i.selectorModules];for(let e of n)e.render&&!(e.type in t)&&(t[e.type]=e.render);return t})();var b=`FKN_WEB_EXTENSION_ATTACH_FRAME_EVENT_KEY`,x=e=>{if(!e||e===`about:blank`)return!1;let t;try{t=new URL(e,location.href)}catch{return!1}if(t.protocol===`chrome-extension:`||t.protocol===`moz-extension:`)return!0;if(t.protocol===`about:`)return!1;let n=t.hostname;return n===`fkn.app`||n.endsWith(`.fkn.app`)},S=e=>{if(x(e))throw Error(`attachFrame: refusing to target the extension's own pages or fkn.app`)},le={scope:`embed.iframe`,category:`embed`,severity:0,title:`Load another website inside this app`,description:`Lets the app embed external pages directly inside its own view.`},ue={scope:`embed.open`,category:`embed`,severity:0,title:`Open a website inside this app`,description:`Lets the app navigate to another site without leaving its window.`},de=async({iframe:t,domains:n=[]})=>{let r=crypto.randomUUID();if(S(t.src),await f(),!t.isConnected)throw Error(`attachFrame: the iframe must be connected to the document before attaching`);t.dispatchEvent(new CustomEvent(b,{detail:r}));let{executeLocator:i,ensureLocatorPermission:a,goto:o}=await p.attachFrame({marker:r,domains:n}),s=e.r(i,a),c=(e,t={})=>(S(e),o({url:e,...t})),l=()=>t.src;return{...s,goto:c,url:l}},fe={request:e=>p.requestPermissions(e.map(e=>({key:e.key,scope:e.scope??``,reason:e.reason})))},pe=32,me=typeof CSS<`u`&&CSS.supports(`clip-path`,`path('M0 0H1V1H0Z')`),he=e=>{let t=e.style;t.setProperty(`display`,`block`,`important`),t.setProperty(`position`,`fixed`,`important`),t.setProperty(`top`,`0`,`important`),t.setProperty(`left`,`0`,`important`),t.setProperty(`width`,`100%`,`important`),t.setProperty(`height`,`100%`,`important`),t.setProperty(`border`,`none`,`important`),t.setProperty(`clip-path`,`inset(100%)`,`important`),t.setProperty(`background`,`transparent`),t.setProperty(`color-scheme`,`normal`),t.setProperty(`z-index`,`2147483647`),e.setAttribute(`title`,`FKN`)},ge=({x:e,y:t,width:n,height:r})=>`M${e} ${t}h${n}v${r}h${-n}Z`,_e=(e,{modal:t,rects:n})=>{if(!me){let r=t||n.length>0;e.style.setProperty(`pointer-events`,r?`auto`:`none`,`important`),e.style.setProperty(`visibility`,r?`visible`:`hidden`,`important`);return}let r=t?`none`:n.length===0?`inset(100%)`:`path('${n.map(ge).join(``)}')`,i=r===`none`||CSS.supports(`clip-path`,r)?r:`inset(100%)`;e.style.setProperty(`clip-path`,i,`important`)},ve=e=>{if(typeof e!=`object`||!e)return null;let{x:t,y:n,width:r,height:i}=e;if(![t,n,r,i].every(e=>typeof e==`number`&&Number.isFinite(e)))return null;let a=window.innerWidth,o=window.innerHeight,s=Math.max(0,Math.min(Math.round(t),a)),c=Math.max(0,Math.min(Math.round(n),o)),l=Math.max(s,Math.min(Math.round(t+r),a)),u=Math.max(c,Math.min(Math.round(n+i),o));return{x:s,y:c,width:l-s,height:u-c}},ye=e=>{if(typeof e!=`object`||!e)return null;let t=e,n=(Array.isArray(t.rects)?t.rects.slice(0,pe):[]).map(ve).filter(e=>e!==null&&e.width>0&&e.height>0);return{modal:t.modal===!0,rects:n}},C=null,be=()=>C!==null,xe=e=>{he(e),_e(e,{modal:!1,rects:[]}),C=e},Se=e=>{if(!C)return;let t=ye(e);t&&_e(C,t)},Ce=`https://fkn.app`,w=typeof globalThis<`u`&&globalThis.document?globalThis.document:void 0,T=w?.querySelector(`iframe[src="${Ce}/api"]`)??null,E=w?.createElement(`iframe`)??null;!T&&E&&w&&(E.src=`${Ce}/api`,w.body.appendChild(E));var D=T??E,O=D?.contentWindow??null;D&&w&&xe(D);var k=(()=>{if(typeof window<`u`)return O?{receive:window,emit:O}:void 0;if(typeof self<`u`)return{receive:self,emit:self}})(),we=k!==void 0,A=k?(0,t.expose)({},{key:`fkn-api`,transport:k}):new Promise(()=>{});A.then(e=>{be()&&e.overlay.setHost(Se)},()=>{});var Te=[`fkn.app`,`fkn.dev`],j=e=>{let t=typeof e==`string`?e:e instanceof URL?e.href:e.url,n;try{n=new URL(t)}catch{return}let r=n.hostname;if(Te.some(e=>r===e||r.endsWith(`.${e}`)))throw Error(`fetch refuses FKN platform domains (${r})`)},Ee=(e,t)=>(j(e),A.then(n=>n.cloud.fetch(e,t))),De=async()=>{let e=await A.then(e=>e.cloud.quota());return{premium:e.premium,overQuota:e.overQuota,throttled:e.overQuota&&!e.premium,usedBytes:e.usedBytes,limitBytes:e.limitBytes,remainingBytes:e.remaining,bytesPerSecond:e.bytesPerSecond,bitsPerSecond:e.bytesPerSecond*8}},Oe=e.g({lookup:()=>ke}),ke=(e,t)=>A.then(n=>n.cloud.dns.lookup(e,t)),Ae=new TextEncoder;new TextDecoder;var M=e=>i.Address4.isValid(e),N=e=>i.Address6.isValid(e),je=e=>M(e)?4:N(e)?6:0,Me=(...e)=>{if(typeof e[0]==`string`)throw Error(`FKN WebVPN does not support IPC connections`);let t=typeof e.at(-1)==`function`?e.at(-1):void 0;return e[0]&&typeof e[0]==`object`?{...e[0],callback:t}:{port:e[0]??0,host:typeof e[1]==`string`?e[1]:void 0,callback:t}},Ne=(...e)=>{let t=typeof e.at(-1)==`function`?e.at(-1):void 0,n=e[0]??0,r=typeof e[1]==`string`?e[1]:void 0;return typeof e[0]==`object`?{...e[0],address:e[0].address??r,port:e[0].port??n,callback:t}:{address:r,port:n,callback:t}},Pe=(...e)=>{let t=typeof e.at(-1)==`function`?e.at(-1):void 0,n=e[0];if(typeof e[2]==`number`)return{message:n,offset:e[1],length:e[2],port:typeof e[3]==`number`?e[3]:0,address:typeof e[4]==`string`?e[4]:void 0,callback:t};{let r=typeof e[1]==`number`?e[1]:0,i=typeof e[2]==`string`?e[2]:void 0;return{message:n,offset:0,length:n.length,port:r,address:i,callback:t}}};new TextEncoder,new TextDecoder;var Fe=e.g({Server:()=>F,Socket:()=>P,_default:()=>Re,connect:()=>Ie,createConnection:()=>Le,createServer:()=>I,default:()=>Re,isIP:()=>je,isIPv4:()=>M,isIPv6:()=>N}),P=class extends n.Stream.Duplex{_localAddress;_remoteAddress;_webVPNTcpSocketPromise;constructor(e){if(e?.fd!==void 0)throw Error(`FKN WebVPN does not support file descriptors`);super(e),e?.connection&&this.__webvpn_tcp_socket_init__(e.connection)}__webvpn_tcp_socket_init__(e){if(this._webVPNTcpSocketPromise=e.then(e=>{let t=e.dataReadableStream.getReader(),n=e.dataWritableStream.getWriter();return this._localAddress={address:e.localAddress,family:e.localFamily,port:e.localPort},this._remoteAddress={address:e.remoteAddress,family:e.remoteFamily,port:e.remotePort},{...e,reader:t,writer:n}}).catch(e=>{this.emit(`error`,e)}),!this._webVPNTcpSocketPromise)throw Error(`Socket not connected`);return this._webVPNTcpSocketPromise.then(e=>{e&&this.emit(`connect`)}),this._webVPNTcpSocketPromise}_read(e){if(!this._webVPNTcpSocketPromise)throw Error(`Socket not connected`);this._webVPNTcpSocketPromise.then(e=>{if(!e){this.push(null);return}e.reader.read().then(({value:e,done:t})=>{if(t){this.push(null);return}this._restartTimeoutTimer(),this.push(e)}).catch(e=>{this.destroy(e)})})}_write(e,t,n){if(!this._webVPNTcpSocketPromise){n(Error(`Socket not connected`));return}this._webVPNTcpSocketPromise.then(async t=>{if(!t)throw Error(`Socket not connected`);await t.writer.ready,await t.writer.write(e),this._restartTimeoutTimer(),n()}).catch(n)}connect(...e){let t=Me(...e),n=this.__webvpn_tcp_socket_init__(A.then(e=>e.cloud.webvpn.tcpSocket({remoteAddress:t.host??`localhost`,remotePort:t.port})));return t.callback&&n.then(e=>{e&&t.callback.call(this)}),this}_end(...e){return this._webVPNTcpSocketPromise?(e.length!==0&&this.write(e[0],e[1],e[2]),this._webVPNTcpSocketPromise.then(async e=>{e&&await e.end()}),this):this}_destroy(e){return this._timeoutTimer&&clearTimeout(this._timeoutTimer),this._webVPNTcpSocketPromise&&this._webVPNTcpSocketPromise.then(async e=>{e&&await e.destroy()}),this}destroySoon(){this._webVPNTcpSocketPromise&&this._webVPNTcpSocketPromise.then(async e=>{e&&await e.destroySoon()})}resetAndDestroy(){return this._webVPNTcpSocketPromise&&this._webVPNTcpSocketPromise.then(async e=>{e&&await e.resetAndDestroy()}),this}_timeoutMs;_timeoutTimer;_restartTimeoutTimer(){this._timeoutTimer&&clearTimeout(this._timeoutTimer),this._timeoutMs&&(this._timeoutTimer=setTimeout(()=>this.emit(`timeout`),this._timeoutMs))}setTimeout(e,t){return t&&this.on(`timeout`,t),this._timeoutMs=e,this._restartTimeoutTimer(),this}setNoDelay(e){let t=e??!0;return this._setTcpOption({type:0,value:t}),this}setKeepAlive(e,t){let n=e??!1,r=t!==void 0&&t>0?Math.max(1,Math.round(t/1e3)):0;return this._setTcpOption({type:2,enabled:n,initialDelaySeconds:r}),this}setSendBufferSize(e){return this._setTcpOption({type:3,value:e}),this}setRecvBufferSize(e){return this._setTcpOption({type:4,value:e}),this}_typeOfService;getTypeOfService(){return this._typeOfService??0}setTypeOfService(e){return this._typeOfService=e,this}_setTcpOption(e){if(!this._webVPNTcpSocketPromise){this.emit(`error`,Error(`Cannot set socket option before connect`));return}this._webVPNTcpSocketPromise.then(async t=>{if(t)try{await t.setOption(e)}catch(e){this.emit(`error`,e)}})}write(e,t,...n){return super.write(e,t,...n)}address(){return this._localAddress??{}}unref(){return this}ref(){return this}autoSelectFamilyAttemptedAddresses;bufferSize;bytesRead;bytesWritten;connecting;pending;get localAddress(){if(!this._localAddress)throw Error(`Socket is not connected`);return this._localAddress.address}get localPort(){if(!this._localAddress)throw Error(`Socket is not connected`);return this._localAddress.port}get localFamily(){if(!this._localAddress)throw Error(`Socket is not connected`);return this._localAddress.family}readyState;get remoteAddress(){if(!this._remoteAddress)throw Error(`Socket is not connected`);return this._remoteAddress.address}get remotePort(){if(!this._remoteAddress)throw Error(`Socket is not connected`);return this._remoteAddress.port}get remoteFamily(){if(!this._remoteAddress)throw Error(`Socket is not connected`);return this._remoteAddress.family}timeout},F=class extends r.EventEmitter{_localAddress;_webVPNTcpSocketListenerPromise;constructor(e,t){super(e),t&&this.on(`connection`,t),e?.connection&&this.__webvpn_tcp_socket_listener_init__(e.connection)}__webvpn_tcp_socket_listener_init__(e){return this._webVPNTcpSocketListenerPromise=e.then(e=>(this._localAddress={address:e.localAddress,family:e.localFamily,port:e.localPort},e)).catch(e=>{this.emit(`error`,e)}),this._webVPNTcpSocketListenerPromise.then(e=>{e&&this.emit(`listening`)}),this._webVPNTcpSocketListenerPromise}listen(...e){let t=Me(...e),n=e=>{let t=new P({connection:Promise.resolve(e)});this.emit(`connection`,t)},r=e=>A.then(r=>r.cloud.webvpn.tcpSocketListener({localAddress:e,localPort:t.port,onConnection:n})),i=t.host?r(t.host):r(`::`).catch(()=>r(`0.0.0.0`)),a=this.__webvpn_tcp_socket_listener_init__(i);return t.callback&&a.then(e=>{e&&t.callback.call(this)}),this}close(e){return this._webVPNTcpSocketListenerPromise&&this._webVPNTcpSocketListenerPromise.then(async t=>{if(t)try{await t.close(),this._localAddress=void 0,this.emit(`close`),e&&e()}catch(t){this._localAddress=void 0,this.emit(`close`),e&&e(t)}}),this}address(){return this._localAddress??null}getConnections(e){throw Error(`Method not implemented.`)}ref(){return this}unref(){return this}maxConnections;connections;listening;async[Symbol.asyncDispose](){}},Ie=(e,t)=>new P().connect(e,t),Le=(e,t)=>new P().connect(e,t),I=(e,t)=>{typeof e==`function`&&(t=e,e=void 0);let n=new F(e);return t&&n.on(`connection`,t),n},Re={Socket:P,Server:F,connect:Ie,createConnection:Le,createServer:I,isIP:je,isIPv4:M,isIPv6:N},ze=e.g({Socket:()=>Be,createSocket:()=>He}),Be=class extends r.EventEmitter{_type;_localAddress;_remoteAddress;_webVPNUdpSocketPromise;constructor(e){if(super(e),!e)throw Error(`Missing options`);this._type=e.type}_lastRecvBufferSize=0;_lastSendBufferSize=0;_lastTtl=64;_lastMulticastTtl=1;_lastMulticastLoopback=!0;_setUdpOption(e){if(!this._webVPNUdpSocketPromise){this.emit(`error`,Error(`Cannot set socket option before bind`));return}this._webVPNUdpSocketPromise.then(async t=>{if(t)try{await t.setOption(e)}catch(e){this.emit(`error`,e)}})}addMembership(e,t){if(i.Address4.isValid(e)){let n=L(e),r=t&&i.Address4.isValid(t)?L(t):new Uint8Array([0,0,0,0]);this._setUdpOption({type:5,group:n,interface:r})}else if(i.Address6.isValid(e)){let t=Ve(e);this._setUdpOption({type:7,group:t,ifIndex:0})}else this.emit(`error`,Error(`Invalid multicast address: ${e}`))}address(){if(!this._localAddress)throw Error(`EBADF`);return this._localAddress}bind(...e){let t=Ne(...e),n=this._type===`udp6`?`::`:`0.0.0.0`;return this._webVPNUdpSocketPromise=A.then(e=>e.cloud.webvpn.udpSocket({type:this._type,address:t.address??n,port:t.port})).then(e=>{let t=e.dataReadableStream.getReader(),n=async()=>{let{value:e,done:r}=await t.read();r||(this.emit(`message`,a.Buffer.from(e.data),{address:e.address,family:e.family,port:e.port,size:e.size}),n())};return n(),this._localAddress={address:e.localAddress,family:e.localFamily,port:e.localPort},e}).catch(e=>{this.emit(`error`,e)}),this._webVPNUdpSocketPromise.then(e=>{e&&this.emit(`listening`)}),t.callback&&this._webVPNUdpSocketPromise.then(e=>{e&&t.callback()}),this}close(e){if(!this._webVPNUdpSocketPromise)throw Error(`Socket not bound`);return this._webVPNUdpSocketPromise.then(async t=>{if(!t)throw Error(`Socket not bound`);await t.close(),e&&e(),this.emit(`close`)}),this}connect(...e){if(!this._webVPNUdpSocketPromise)throw Error(`Socket not bound`);this._webVPNUdpSocketPromise.then(async t=>{if(!t)throw Error(`Socket not bound`);let n=e[0],r=this._type===`udp6`?`::1`:`127.0.0.1`,i=typeof e[1]==`string`?e[1]:r,a=typeof e.at(-1)==`function`?e.at(-1):void 0;await t.connect({remotePort:n,remoteAddress:i}),this._remoteAddress={address:i,family:this._type===`udp6`?`IPv6`:`IPv4`,port:n},a&&a()})}disconnect(){if(!this._webVPNUdpSocketPromise)throw Error(`Socket not bound`);this._webVPNUdpSocketPromise.then(async e=>{if(!e)throw Error(`Socket not bound`);await e.connect({remotePort:0,remoteAddress:this._type===`udp4`?`0.0.0.0`:`::`})})}dropMembership(e,t){if(i.Address4.isValid(e)){let n=L(e),r=t&&i.Address4.isValid(t)?L(t):new Uint8Array([0,0,0,0]);this._setUdpOption({type:6,group:n,interface:r})}else if(i.Address6.isValid(e)){let t=Ve(e);this._setUdpOption({type:8,group:t,ifIndex:0})}else this.emit(`error`,Error(`Invalid multicast address: ${e}`))}getRecvBufferSize(){return this._lastRecvBufferSize}getSendBufferSize(){return this._lastSendBufferSize}getSendQueueSize(){return 0}getSendQueueCount(){return 0}ref(){return this}remoteAddress(){if(!this._remoteAddress)throw Error(`ERR_SOCKET_DGRAM_NOT_CONNECTED`);return{address:this._remoteAddress.address,family:this._remoteAddress.family,port:this._remoteAddress.port}}send(...e){this._webVPNUdpSocketPromise||this.bind();let t=Pe(...e),n=this._type===`udp6`?`::1`:`127.0.0.1`;if(!this._webVPNUdpSocketPromise)throw Error(`Socket not bound`);this._webVPNUdpSocketPromise.then(e=>{if(!e)throw Error(`Socket not bound`);let r=typeof t.message==`string`?Ae.encode(t.message):t.message;e.send({...t,address:t.address??n,message:r.buffer})})}setBroadcast(e){this._setUdpOption({type:0,value:e})}setMulticastInterface(e){}setMulticastLoopback(e){return this._setUdpOption({type:3,value:e}),this._setUdpOption({type:4,value:e}),this._lastMulticastLoopback=e,e}setMulticastTTL(e){return this._setUdpOption({type:2,value:e}),this._lastMulticastTtl=e,e}setRecvBufferSize(e){this._setUdpOption({type:10,value:e}),this._lastRecvBufferSize=e}setSendBufferSize(e){this._setUdpOption({type:9,value:e}),this._lastSendBufferSize=e}setTTL(e){return this._setUdpOption({type:1,value:e}),this._lastTtl=e,e}unref(){return this}addSourceSpecificMembership(e,t,n){}dropSourceSpecificMembership(e,t,n){}async[Symbol.asyncDispose](){await new Promise(e=>{this.close(e)})}},L=e=>{let t=e.split(`.`).map(e=>parseInt(e,10));if(t.length!==4||t.some(e=>Number.isNaN(e)||e<0||e>255))throw Error(`Invalid IPv4 address: ${e}`);return new Uint8Array(t)},Ve=e=>{let t=new i.Address6(e).getBitsBase16(0,128).match(/.{2}/g);if(!t||t.length!==16)throw Error(`Invalid IPv6 address: ${e}`);return new Uint8Array(t.map(e=>parseInt(e,16)))},He=(e,t)=>{let n=new Be(typeof e==`string`?{type:e}:e);return t&&n.on(`message`,t),n},Ue=e.g({Agent:()=>J,ClientRequest:()=>K,HTTPParser:()=>H,IncomingMessage:()=>U,METHODS:()=>Ge,STATUS_CODES:()=>R,Server:()=>q,ServerResponse:()=>G,_default:()=>nt,createServer:()=>tt,default:()=>nt,get:()=>et,globalAgent:()=>$e,request:()=>Y}),We=new TextDecoder(`latin1`),Ge=`ACL.BIND.CHECKOUT.CONNECT.COPY.DELETE.GET.HEAD.LINK.LOCK.M-SEARCH.MERGE.MKACTIVITY.MKCALENDAR.MKCOL.MOVE.NOTIFY.OPTIONS.PATCH.POST.PROPFIND.PROPPATCH.PURGE.PUT.REBIND.REPORT.SEARCH.SOURCE.SUBSCRIBE.TRACE.UNBIND.UNLINK.UNLOCK.UNSUBSCRIBE`.split(`.`),R={100:`Continue`,101:`Switching Protocols`,102:`Processing`,103:`Early Hints`,200:`OK`,201:`Created`,202:`Accepted`,203:`Non-Authoritative Information`,204:`No Content`,205:`Reset Content`,206:`Partial Content`,207:`Multi-Status`,208:`Already Reported`,226:`IM Used`,300:`Multiple Choices`,301:`Moved Permanently`,302:`Found`,303:`See Other`,304:`Not Modified`,305:`Use Proxy`,307:`Temporary Redirect`,308:`Permanent Redirect`,400:`Bad Request`,401:`Unauthorized`,402:`Payment Required`,403:`Forbidden`,404:`Not Found`,405:`Method Not Allowed`,406:`Not Acceptable`,407:`Proxy Authentication Required`,408:`Request Timeout`,409:`Conflict`,410:`Gone`,411:`Length Required`,412:`Precondition Failed`,413:`Payload Too Large`,414:`URI Too Long`,415:`Unsupported Media Type`,416:`Range Not Satisfiable`,417:`Expectation Failed`,418:`I'm a Teapot`,421:`Misdirected Request`,422:`Unprocessable Entity`,423:`Locked`,424:`Failed Dependency`,425:`Too Early`,426:`Upgrade Required`,428:`Precondition Required`,429:`Too Many Requests`,431:`Request Header Fields Too Large`,451:`Unavailable For Legal Reasons`,500:`Internal Server Error`,501:`Not Implemented`,502:`Bad Gateway`,503:`Service Unavailable`,504:`Gateway Timeout`,505:`HTTP Version Not Supported`,506:`Variant Also Negotiates`,507:`Insufficient Storage`,508:`Loop Detected`,509:`Bandwidth Limit Exceeded`,510:`Not Extended`,511:`Network Authentication Required`},Ke=new Set([`content-type`,`content-length`,`user-agent`,`referer`,`host`,`authorization`,`proxy-authorization`,`if-modified-since`,`if-unmodified-since`,`from`,`location`,`max-forwards`,`retry-after`,`etag`,`last-modified`,`server`,`age`,`expires`]),z=13,B=10,qe=/^[\^_`a-zA-Z\-0-9!#$%&'*+.|~]+$/,V=(e,t)=>(e.code=t,e),Je=(e,t)=>{if(e.length===0)return t;if(t.length===0)return e;let n=new Uint8Array(e.length+t.length);return n.set(e,0),n.set(t,e.length),n},Ye=(e,t)=>{for(let n=t;n+1<e.length;n++)if(e[n]===z&&e[n+1]===B)return n;return-1},Xe=e=>{for(let t=0;t+3<e.length;t++)if(e[t]===z&&e[t+1]===B&&e[t+2]===z&&e[t+3]===B)return t;return-1},H=class{buf=new Uint8Array;state=`HEAD`;framing=`none`;bodyRemaining=0;chunkState=`size`;skipBody=!1;constructor(e,t){this.mode=e,this.handlers=t}execute(e){this.buf=Je(this.buf,e);let t=!0;for(;t;)if(t=!1,this.state===`HEAD`){let e=Xe(this.buf);if(e===-1)return;let n=this.buf.subarray(0,e);this.buf=this.buf.subarray(e+4);let r=this.parseHead(n);this.handlers.onHeaders(r),this.setupBody(r),this.framing===`none`?(this.handlers.onComplete(),this.reset(),t=this.buf.length>0):(this.state=`BODY`,t=!0)}else this.consumeBody()&&(this.handlers.onComplete(),this.reset(),t=this.buf.length>0)}finish(){this.state===`BODY`&&this.framing===`eof`&&(this.handlers.onComplete(),this.reset())}reset(){this.state=`HEAD`,this.framing=`none`,this.bodyRemaining=0,this.chunkState=`size`,this.skipBody=!1}parseHead(e){let t=We.decode(e).split(`\r
|
|
2
|
+
`),n=t.shift()??``,r=[];for(let e of t)(e.startsWith(` `)||e.startsWith(` `))&&r.length>0?r[r.length-1]+=` `+e.trim():r.push(e);let i=[],a={};for(let e of r){if(!e)continue;let t=e.indexOf(`:`);if(t===-1)continue;let n=e.slice(0,t).trim(),r=e.slice(t+1).trim();i.push(n,r),this.addHeader(a,n,r)}let o={httpVersionMajor:1,httpVersionMinor:1,httpVersion:`1.1`,headers:a,rawHeaders:i};if(this.mode===`request`){let[e,t,r]=n.split(` `);o.method=(e??`GET`).toUpperCase(),o.url=t??`/`,this.applyVersion(o,r)}else{let e=n.indexOf(` `),t=n.slice(0,e),r=n.slice(e+1),i=r.indexOf(` `),a=i===-1?r:r.slice(0,i);o.statusCode=parseInt(a,10)||0,o.statusMessage=i===-1?``:r.slice(i+1),this.applyVersion(o,t)}return o}applyVersion(e,t){let n=/HTTP\/(\d)\.(\d)/i.exec(t??``);n&&(e.httpVersionMajor=parseInt(n[1],10),e.httpVersionMinor=parseInt(n[2],10),e.httpVersion=`${e.httpVersionMajor}.${e.httpVersionMinor}`)}addHeader(e,t,n){let r=t.toLowerCase();if(r===`set-cookie`){let t=e[`set-cookie`];Array.isArray(t)?t.push(n):e[`set-cookie`]=[n];return}let i=e[r];i===void 0?e[r]=n:Ke.has(r)||(e[r]=`${i}, ${n}`)}setupBody(e){if(this.skipBody){this.framing=`none`;return}let t=e.headers[`transfer-encoding`];if(typeof t==`string`&&t.toLowerCase().includes(`chunked`)){this.framing=`chunked`,this.chunkState=`size`;return}let n=e.headers[`content-length`];if(typeof n==`string`&&n!==``){let e=parseInt(n,10);e>0?(this.framing=`length`,this.bodyRemaining=e):this.framing=`none`;return}if(this.mode===`response`){let t=e.statusCode??0;t>=100&&t<200||t===204||t===304?this.framing=`none`:this.framing=`eof`}else this.framing=`none`}consumeBody(){if(this.framing===`length`){if(this.buf.length===0)return!1;let e=Math.min(this.bodyRemaining,this.buf.length);return this.handlers.onBody(this.buf.subarray(0,e)),this.buf=this.buf.subarray(e),this.bodyRemaining-=e,this.bodyRemaining===0}return this.framing===`eof`?(this.buf.length>0&&(this.handlers.onBody(this.buf),this.buf=new Uint8Array),!1):this.framing===`chunked`?this.consumeChunked():!0}consumeChunked(){for(;;)if(this.chunkState===`size`){let e=Ye(this.buf,0);if(e===-1)return!1;let t=We.decode(this.buf.subarray(0,e)),n=parseInt(t.split(`;`)[0].trim(),16);if(this.buf=this.buf.subarray(e+2),Number.isNaN(n))return!0;n===0?this.chunkState=`trailer`:(this.bodyRemaining=n,this.chunkState=`data`)}else if(this.chunkState===`data`){if(this.buf.length===0)return!1;let e=Math.min(this.bodyRemaining,this.buf.length);this.handlers.onBody(this.buf.subarray(0,e)),this.buf=this.buf.subarray(e),this.bodyRemaining-=e,this.bodyRemaining===0&&(this.chunkState=`dataCRLF`)}else if(this.chunkState===`dataCRLF`){if(this.buf.length<2)return!1;this.buf=this.buf.subarray(2),this.chunkState=`size`}else{let e=Ye(this.buf,0);if(e===-1)return!1;let t=e===0;if(this.buf=this.buf.subarray(e+2),t)return!0}}},Ze=(e,t)=>a.Buffer.isBuffer(e)?e:typeof e==`string`?a.Buffer.from(e,t??`utf8`):e instanceof Uint8Array?a.Buffer.from(e):e instanceof ArrayBuffer?a.Buffer.from(new Uint8Array(e)):a.Buffer.from(String(e)),U=class extends n.Stream.Readable{httpVersion=`1.1`;httpVersionMajor=1;httpVersionMinor=1;headers={};rawHeaders=[];trailers={};rawTrailers=[];method;url;statusCode;statusMessage;complete=!1;socket;constructor(e){super(),this.socket=e}get connection(){return this.socket}_applyHead(e){this.httpVersion=e.httpVersion,this.httpVersionMajor=e.httpVersionMajor,this.httpVersionMinor=e.httpVersionMinor,this.headers=e.headers,this.rawHeaders=e.rawHeaders,this.method=e.method,this.url=e.url,this.statusCode=e.statusCode,this.statusMessage=e.statusMessage}_read(){}setTimeout(e,t){return this.socket.setTimeout(e,t),this}},W=class extends n.Stream.Writable{_headerStore=new Map;headersSent=!1;chunkedEncoding=!1;finished=!1;_bodyWritten=!1;setHeader(e,t){if(this.headersSent)throw V(Error(`Cannot set headers after they are sent to the client`),`ERR_HTTP_HEADERS_SENT`);if(typeof e!=`string`||!qe.test(e))throw V(TypeError(`Header name must be a valid HTTP token [${JSON.stringify(String(e))}]`),`ERR_INVALID_HTTP_TOKEN`);if(t===void 0)throw V(TypeError(`Invalid value "undefined" for header "${e}"`),`ERR_HTTP_INVALID_HEADER_VALUE`);return this._headerStore.set(e.toLowerCase(),[e,Array.isArray(t)?[...t]:t]),this}getHeader(e){return this._headerStore.get(e.toLowerCase())?.[1]}getHeaderNames(){return[...this._headerStore.values()].map(([e])=>e)}getHeaders(){let e={};for(let[t,n]of this._headerStore.values())e[t]=n;return e}hasHeader(e){return this._headerStore.has(e.toLowerCase())}removeHeader(e){if(this.headersSent)throw Error(`Cannot remove headers after they are sent to the client`);this._headerStore.delete(e.toLowerCase())}_storeHeader(e){let t=this.hasHeader(`content-length`),n=this.getHeader(`transfer-encoding`);typeof n==`string`&&n.toLowerCase().includes(`chunked`)?this.chunkedEncoding=!0:!t&&this._shouldSendBody()&&(this.chunkedEncoding=!0,this.setHeader(`Transfer-Encoding`,`chunked`));let r=e+`\r
|
|
3
3
|
`;for(let[e,t]of this._headerStore.values())if(Array.isArray(t))for(let n of t)r+=`${e}: ${n}\r\n`;else r+=`${e}: ${t}\r\n`;return r+=`\r
|
|
4
|
-
`,r}_writeToSocket(e,t){if(!this.socket){t(Error(`Socket is not available`));return}this.socket.write(e,t)}write(e,t,n){return this._bodyWritten=!0,super.write(e,t,n)}_write(e,t,n){let r=
|
|
4
|
+
`,r}_writeToSocket(e,t){if(!this.socket){t(Error(`Socket is not available`));return}this.socket.write(e,t)}write(e,t,n){return this._bodyWritten=!0,super.write(e,t,n)}_write(e,t,n){let r=Ze(e),i=[];if(this.headersSent||=(this._implicitHeader(),i.push(a.Buffer.from(this._headBlock,`latin1`)),!0),this.chunkedEncoding?r.length>0&&(i.push(a.Buffer.from(`${r.length.toString(16)}\r\n`,`latin1`)),i.push(r),i.push(a.Buffer.from(`\r
|
|
5
5
|
`,`latin1`))):i.push(r),i.length===0){n();return}this._writeToSocket(a.Buffer.concat(i),n)}_final(e){let t=[];if(this.headersSent||=(!this.chunkedEncoding&&!this.hasHeader(`content-length`)&&this.setHeader(`Content-Length`,0),this._implicitHeader(),t.push(a.Buffer.from(this._headBlock,`latin1`)),!0),this.chunkedEncoding&&t.push(a.Buffer.from(`0\r
|
|
6
6
|
\r
|
|
7
|
-
`,`latin1`)),this.finished=!0,t.length===0){e();return}this._writeToSocket(a.Buffer.concat(t),e)}end(e,t,n){if(e!=null&&typeof e!=`function`&&!this._bodyWritten&&!this.headersSent&&!this.chunkedEncoding&&!this.hasHeader(`content-length`)){let n=typeof t==`string`?t:void 0;this.setHeader(`Content-Length`,
|
|
7
|
+
`,`latin1`)),this.finished=!0,t.length===0){e();return}this._writeToSocket(a.Buffer.concat(t),e)}end(e,t,n){if(e!=null&&typeof e!=`function`&&!this._bodyWritten&&!this.headersSent&&!this.chunkedEncoding&&!this.hasHeader(`content-length`)){let n=typeof t==`string`?t:void 0;this.setHeader(`Content-Length`,Ze(e,n).length)}return super.end(e,t,n)}_headBlock},G=class extends W{statusCode=200;statusMessage;_writeHeadCalled=!1;sendDate=!0;req;socket;_keepAlive=!0;constructor(e){super(),this.req=e,this.socket=e.socket}_shouldSendBody(){if(this.req.method===`HEAD`)return!1;let e=this.statusCode;return!(e>=100&&e<200||e===204||e===304)}writeHead(e,t,n){if(this._writeHeadCalled||this.headersSent)throw V(Error(`Cannot render headers after they are sent to the client`),`ERR_HTTP_HEADERS_SENT`);this._writeHeadCalled=!0,this.statusCode=e;let r=n;if(typeof t==`string`?this.statusMessage=t:t!=null&&(r=t),Array.isArray(r)){let e=Array.isArray(r[0])?r:Array.from({length:Math.floor(r.length/2)},(e,t)=>[r[t*2],r[t*2+1]]);for(let[t,n]of e)n!==void 0&&this._appendHeader(t,n)}else if(r)for(let[e,t]of Object.entries(r))t!==void 0&&this.setHeader(e,t);return this}_appendHeader(e,t){let n=this.getHeader(e);if(n===void 0)this.setHeader(e,t);else{let r=[...Array.isArray(n)?n:[n],...Array.isArray(t)?t:[t]].map(String);this.setHeader(e,r)}}_implicitHeader(){let e=this.statusMessage??R[this.statusCode]??`unknown`;this.sendDate&&!this.hasHeader(`date`)&&this.setHeader(`Date`,new Date().toUTCString()),this.hasHeader(`connection`)||this.setHeader(`Connection`,this._keepAlive?`keep-alive`:`close`),this._headBlock=this._storeHeader(`HTTP/1.1 ${this.statusCode} ${e}`)}writeContinue(){this._writeToSocket(a.Buffer.from(`HTTP/1.1 100 Continue\r
|
|
8
8
|
\r
|
|
9
|
-
`,`latin1`),()=>{})}setTimeout(e,t){return this.socket?.setTimeout(e,t),this}},
|
|
9
|
+
`,`latin1`),()=>{})}setTimeout(e,t){return this.socket?.setTimeout(e,t),this}},Qe=(...e)=>{let t={},n={},r,i=[...e],a=i.shift();if(typeof a==`string`||a instanceof URL){let e=typeof a==`string`?new URL(a):a;t={protocol:e.protocol,hostname:e.hostname,host:e.hostname,port:e.port,path:`${e.pathname}${e.search}`,auth:e.username?`${e.username}:${e.password}`:void 0};let o=i.shift();typeof o==`function`?r=o:o&&typeof o==`object`&&(n=o,r=i.shift())}else a&&typeof a==`object`&&(n=a,r=i.shift());return{options:{...t,...n},callback:r}},K=class extends W{method;path;host;protocol;socket;get connection(){return this.socket}res=null;aborted=!1;_aborted=!1;constructor(e,t){super(),this.method=(e.method??`GET`).toUpperCase(),this.path=e.path??`/`,this.protocol=e.protocol??`http:`;let n=e.hostname??e.host??`localhost`;this.host=n;let r=Number(e.port??(this.protocol===`https:`?443:80));if(t&&this.once(`response`,t),e.headers)for(let[t,n]of Object.entries(e.headers))n!==void 0&&this.setHeader(t,n);if(!this.hasHeader(`host`)){let e=this.protocol===`https:`&&r===443||this.protocol!==`https:`&&r===80;this.setHeader(`Host`,e?n:`${n}:${r}`)}e.auth&&!this.hasHeader(`authorization`)&&this.setHeader(`Authorization`,`Basic ${a.Buffer.from(e.auth).toString(`base64`)}`),this.socket=new P,this.emit(`socket`,this.socket),this.socket.on(`error`,e=>{this._aborted||this.emit(`error`,e)}),this._attachResponseParser(),this.socket.connect({host:n,port:r},()=>{this.emit(`connect`)})}_shouldSendBody(){return this.method!==`GET`&&this.method!==`HEAD`&&this.method!==`DELETE`}_implicitHeader(){this._headBlock=this._storeHeader(`${this.method} ${this.path} HTTP/1.1`)}_attachResponseParser(){let e=new U(this.socket),t=new H(`response`,{onHeaders:n=>{e._applyHead(n),this.method===`HEAD`&&(t.skipBody=!0),this.res=e,this.emit(`response`,e)},onBody:t=>{e.push(a.Buffer.from(t))},onComplete:()=>{e.complete=!0,e.push(null)}});this.socket.on(`data`,e=>{this._aborted||t.execute(e)}),this.socket.on(`end`,()=>{t.finish()}),this.socket.on(`close`,()=>{this.emit(`close`)})}abort(){this._aborted||(this._aborted=!0,this.aborted=!0,this.emit(`abort`),this.socket.destroy())}destroy(e){return this._aborted?this:(this._aborted=!0,this.socket.destroy(e),super.destroy(e),this)}end(e,t,n){return this._aborted?this:super.end(e,t,n)}_writeToSocket(e,t){if(this._aborted){t();return}super._writeToSocket(e,t)}setTimeout(e,t){return this.socket.setTimeout(e,t),this}setNoDelay(e){this.socket.setNoDelay(e)}setSocketKeepAlive(e,t){this.socket.setKeepAlive(e,t)}},q=new Proxy(class extends F{constructor(e,t){let n={},r=t;typeof e==`function`?r=e:e&&(n=e),super(n),r&&this.on(`request`,r),this.on(`connection`,e=>this._handleConnection(e))}_handleConnection(e){let t=null,n=new H(`request`,{onHeaders:r=>{t=new U(e),t._applyHead(r),r.method===`HEAD`&&(n.skipBody=!0);let i=new G(t),a=String(r.headers.connection??``).toLowerCase();i._keepAlive=r.httpVersionMinor>=1?a!==`close`:a===`keep-alive`,i.on(`finish`,()=>{i._keepAlive||e.end()}),this.emit(`request`,t,i)},onBody:e=>{t?.push(a.Buffer.from(e))},onComplete:()=>{t&&(t.complete=!0,t.push(null)),t=null}});e.on(`data`,e=>n.execute(e)),e.on(`end`,()=>{n.finish(),t&&t.push(null)}),e.on(`error`,t=>this.emit(`clientError`,t,e))}},{apply:(e,t,n)=>new e(...n)}),J=class{maxSockets;maxFreeSockets;keepAlive;options;constructor(e={}){this.options=e,this.keepAlive=!!e.keepAlive,this.maxSockets=e.maxSockets??1/0,this.maxFreeSockets=e.maxFreeSockets??256}getName(e={}){return`${e.host??`localhost`}:${e.port??``}:${e.localAddress??``}`}destroy(){}},$e=new J,Y=(...e)=>{let{options:t,callback:n}=Qe(...e);return new K(t,n)},et=(...e)=>{let t=Y(...e);return t.end(),t},tt=(e,t)=>new q(e,t),nt={METHODS:Ge,STATUS_CODES:R,Agent:J,globalAgent:$e,Server:q,ServerResponse:G,IncomingMessage:U,ClientRequest:K,OutgoingMessage:W,createServer:tt,request:Y,get:et},rt=e.g({available:()=>it,dgram:()=>ze,dns:()=>Oe,fetch:()=>Ee,http:()=>Ue,net:()=>Fe,quota:()=>De}),it=()=>we,X=async e=>{if(typeof window>`u`)return!1;if(l())return!0;let t=await A,n=null,r=new Promise(e=>{n=()=>{l()&&e(!0)},c.addEventListener(`statuschange`,n)}),i=t.installPrompt.show(e).then(()=>!1),a=await Promise.race([r,i]);return n&&c.removeEventListener(`statuschange`,n),await t.installPrompt.hide().catch(()=>{}),a},Z=null;d(()=>(Z||=X().then(()=>void 0).finally(()=>{Z=null}),Z));var at=e.g({available:()=>ot,dgram:()=>ut,dns:()=>ct,fetch:()=>st,fs:()=>dt,net:()=>lt}),ot=()=>!1,Q=e=>(...t)=>{throw Error(`The FKN desktop app is not connected, desktop.${e} is unavailable`)},st=Q(`fetch`),ct={lookup:Q(`dns.lookup`)},lt={connect:Q(`net.connect`),createConnection:Q(`net.createConnection`),createServer:Q(`net.createServer`)},ut={createSocket:Q(`dgram.createSocket`)},dt={isLocalDirectorySupported:()=>!1,pickLocalDirectory:Q(`fs.pickLocalDirectory`),queryDirectoryPermission:Q(`fs.queryDirectoryPermission`),ensureDirectoryPermission:Q(`fs.ensureDirectoryPermission`)},ft=()=>typeof document<`u`&&l(),pt=async(e,t)=>{if(j(e),t?.credentials===`include`){if(typeof document>`u`)throw Error(`fetch with credentials needs the FKN extension, which only exists in window realms`);return v(e,t)}return ft()?v(e,{...t,credentials:`omit`}):ot()?st(e,t):Ee(e,t)},mt=e.g({ATTACH_FRAME_EVENT_KEY:()=>b,assertAttachableFrameUrl:()=>S,assertFetchableUrl:()=>_,attachFrame:()=>de,attachFramePermission:()=>le,available:()=>ft,box:()=>e.u,cookies:()=>oe,createVideoElementHandle:()=>e.d,events:()=>c,extension:()=>c,fetch:()=>v,fetchCredentialedPermission:()=>h,fetchPermission:()=>m,gotoPermission:()=>ue,handleRevivableModules:()=>e.l,isBlockedFetchUrl:()=>g,isBlockedFrameUrl:()=>x,isExtensionExposed:()=>l,isType:()=>e.f,modifyRequestHeadersPermission:()=>se,permissions:()=>fe,promptInstall:()=>X,readCookiePermission:()=>ae,removeRequestHeaderRule:()=>y,revive:()=>e.p,setMissingExtensionHandler:()=>d,setRequestHeaderRule:()=>ce,type:()=>e.m,waitForExtensionExposure:()=>f}),ht=e.g({ensureDirectoryPermission:()=>vt,isLocalDirectorySupported:()=>gt,pickLocalDirectory:()=>_t,queryDirectoryPermission:()=>$}),gt=()=>typeof window<`u`&&`showDirectoryPicker`in window,_t=async(e={})=>{if(!gt())return;let t=window.showDirectoryPicker;return t({mode:`readwrite`,...e}).catch(e=>{if(e?.name!==`AbortError`)throw e})},$=async(e,t=`readwrite`)=>{let{queryPermission:n}=e;return await n?.call(e,{mode:t})??`granted`},vt=async(e,t=`readwrite`)=>{if(await $(e,t)===`granted`)return!0;let{requestPermission:n}=e;return await n?.call(e,{mode:t})===`granted`},yt=`https://fkn.app`,bt=(e,n)=>{if(typeof window>`u`)throw Error(`FKN @fkn/lib: relayWorker must be called from the main thread`);if(!D?.contentWindow)throw Error(`FKN @fkn/lib: relayWorker called before the FKN iframe was injected`);(0,t.relay)({receive:window,emit:D.contentWindow},e,{key:`fkn-api`,originA:n?.originA??yt,originB:n?.originB??`*`,unregisterSignal:n?.unregisterSignal})};exports.ATTACH_FRAME_EVENT_KEY=b,exports.assertAttachableFrameUrl=S,exports.assertFetchableUrl=_,exports.attachFrame=de,exports.attachFramePermission=le,exports.box=e.u,Object.defineProperty(exports,`cloud`,{enumerable:!0,get:function(){return rt}}),exports.cookies=oe,exports.createVideoElementHandle=e.d,Object.defineProperty(exports,`desktop`,{enumerable:!0,get:function(){return at}}),Object.defineProperty(exports,`dgram`,{enumerable:!0,get:function(){return ze}}),Object.defineProperty(exports,`dns`,{enumerable:!0,get:function(){return Oe}}),Object.defineProperty(exports,`extension`,{enumerable:!0,get:function(){return mt}}),exports.fetch=pt,exports.fetchCredentialedPermission=h,exports.fetchPermission=m,Object.defineProperty(exports,`fs`,{enumerable:!0,get:function(){return ht}}),exports.gotoPermission=ue,exports.handleRevivableModules=e.l,Object.defineProperty(exports,`http`,{enumerable:!0,get:function(){return Ue}}),exports.isBlockedFetchUrl=g,exports.isBlockedFrameUrl=x,exports.isExtensionExposed=l,exports.isType=e.f,exports.modifyRequestHeadersPermission=se,Object.defineProperty(exports,`net`,{enumerable:!0,get:function(){return Fe}}),exports.permissions=fe,exports.promptInstall=X,exports.readCookiePermission=ae,exports.relayWorker=bt,exports.removeRequestHeaderRule=y,exports.revive=e.p,exports.setMissingExtensionHandler=d,exports.setRequestHeaderRule=ce,exports.type=e.m,exports.waitForExtensionExposure=f;
|
package/index.d.ts
CHANGED
|
@@ -1255,7 +1255,7 @@ type Resolvers = typeof resolvers;
|
|
|
1255
1255
|
|
|
1256
1256
|
type ProxyFetch = Resolvers['cloud']['fetch'];
|
|
1257
1257
|
type FetchParameters = Parameters<ProxyFetch>;
|
|
1258
|
-
declare const
|
|
1258
|
+
declare const cloudFetch: (input: FetchParameters[0], init?: FetchParameters[1]) => Promise<Response>;
|
|
1259
1259
|
|
|
1260
1260
|
type QuotaStatus = {
|
|
1261
1261
|
/** the user has a paid subscription, throttle never applies */
|
|
@@ -1742,7 +1742,7 @@ type cloud_QuotaStatus = QuotaStatus;
|
|
|
1742
1742
|
declare const cloud_http: typeof http;
|
|
1743
1743
|
declare const cloud_quota: typeof quota;
|
|
1744
1744
|
declare namespace cloud {
|
|
1745
|
-
export { available$1 as available, dgram$1 as dgram, dns$1 as dns,
|
|
1745
|
+
export { available$1 as available, dgram$1 as dgram, dns$1 as dns, cloudFetch as fetch, cloud_http as http, net$1 as net, cloud_quota as quota };
|
|
1746
1746
|
export type { cloud_QuotaStatus as QuotaStatus };
|
|
1747
1747
|
}
|
|
1748
1748
|
|
|
@@ -1863,5 +1863,5 @@ declare const relayWorker: (worker: Worker, options?: {
|
|
|
1863
1863
|
originB?: string;
|
|
1864
1864
|
}) => void;
|
|
1865
1865
|
|
|
1866
|
-
export { ATTACH_FRAME_EVENT_KEY, assertAttachableFrameUrl, assertFetchableUrl, attachFrame, attachFramePermission, box, cloud, cookies, createVideoElementHandle, desktop, dgram$1 as dgram, dns$1 as dns, extension, fetch$1 as fetch, fetchCredentialedPermission, fetchPermission, fs, gotoPermission, handleRevivableModules, http, isBlockedFetchUrl, isBlockedFrameUrl, isExtensionExposed, isType, modifyRequestHeadersPermission, net$1 as net, permissions, promptInstall, readCookiePermission, relayWorker, removeRequestHeaderRule, revive,
|
|
1866
|
+
export { ATTACH_FRAME_EVENT_KEY, assertAttachableFrameUrl, assertFetchableUrl, attachFrame, attachFramePermission, box, cloud, cookies, createVideoElementHandle, desktop, dgram$1 as dgram, dns$1 as dns, extension, fetch$1 as fetch, fetchCredentialedPermission, fetchPermission, fs, gotoPermission, handleRevivableModules, http, isBlockedFetchUrl, isBlockedFrameUrl, isExtensionExposed, isType, modifyRequestHeadersPermission, net$1 as net, permissions, promptInstall, readCookiePermission, relayWorker, removeRequestHeaderRule, revive, setMissingExtensionHandler, setRequestHeaderRule, type, waitForExtensionExposure };
|
|
1867
1867
|
export type { AttachFrameOptions, BoxedVideoElement, CookieDetails, FetchInit, Frame, GotoOptions, HeaderOperation, PermissionGrant, PermissionRequest, ProxyFetchRequest, RemoteVideoElement, RequestHeaderRule, SiteCookie, VideoElementState };
|
package/index.js
CHANGED
|
@@ -195,29 +195,29 @@ var C = "FKN_WEB_EXTENSION_ATTACH_FRAME_EVENT_KEY", w = (e) => {
|
|
|
195
195
|
if (!E) return;
|
|
196
196
|
let t = Oe(e);
|
|
197
197
|
t && Ee(E, t);
|
|
198
|
-
},
|
|
199
|
-
!
|
|
200
|
-
var
|
|
201
|
-
|
|
202
|
-
var
|
|
203
|
-
if (typeof window < "u") return
|
|
198
|
+
}, D = "https://fkn.app", O = typeof globalThis < "u" && globalThis.document ? globalThis.document : void 0, Me = O?.querySelector(`iframe[src="${D}/api"]`) ?? null, k = O?.createElement("iframe") ?? null;
|
|
199
|
+
!Me && k && O && (k.src = `${D}/api`, O.body.appendChild(k));
|
|
200
|
+
var A = Me ?? k, Ne = A?.contentWindow ?? null;
|
|
201
|
+
A && O && Ae(A);
|
|
202
|
+
var j = (() => {
|
|
203
|
+
if (typeof window < "u") return Ne ? {
|
|
204
204
|
receive: window,
|
|
205
|
-
emit:
|
|
205
|
+
emit: Ne
|
|
206
206
|
} : void 0;
|
|
207
207
|
if (typeof self < "u") return {
|
|
208
208
|
receive: self,
|
|
209
209
|
emit: self
|
|
210
210
|
};
|
|
211
|
-
})(),
|
|
211
|
+
})(), Pe = j !== void 0, M = j ? te({}, {
|
|
212
212
|
key: "fkn-api",
|
|
213
|
-
transport:
|
|
213
|
+
transport: j
|
|
214
214
|
}) : new Promise(() => {});
|
|
215
|
-
|
|
215
|
+
M.then((e) => {
|
|
216
216
|
ke() && e.overlay.setHost(je);
|
|
217
217
|
}, () => {});
|
|
218
218
|
//#endregion
|
|
219
219
|
//#region src/lib/fkn-target.ts
|
|
220
|
-
var
|
|
220
|
+
var Fe = ["fkn.app", "fkn.dev"], Ie = (e) => {
|
|
221
221
|
let t = typeof e == "string" ? e : e instanceof URL ? e.href : e.url, n;
|
|
222
222
|
try {
|
|
223
223
|
n = new URL(t);
|
|
@@ -225,9 +225,9 @@ var Ie = ["fkn.app", "fkn.dev"], Le = (e) => {
|
|
|
225
225
|
return;
|
|
226
226
|
}
|
|
227
227
|
let r = n.hostname;
|
|
228
|
-
if (
|
|
229
|
-
},
|
|
230
|
-
let e = await
|
|
228
|
+
if (Fe.some((e) => r === e || r.endsWith(`.${e}`))) throw Error(`fetch refuses FKN platform domains (${r})`);
|
|
229
|
+
}, Le = (e, t) => (Ie(e), M.then((n) => n.cloud.fetch(e, t))), Re = async () => {
|
|
230
|
+
let e = await M.then((e) => e.cloud.quota());
|
|
231
231
|
return {
|
|
232
232
|
premium: e.premium,
|
|
233
233
|
overQuota: e.overQuota,
|
|
@@ -238,7 +238,7 @@ var Ie = ["fkn.app", "fkn.dev"], Le = (e) => {
|
|
|
238
238
|
bytesPerSecond: e.bytesPerSecond,
|
|
239
239
|
bitsPerSecond: e.bytesPerSecond * 8
|
|
240
240
|
};
|
|
241
|
-
}, ze = /* @__PURE__ */ n({ lookup: () => Be }), Be = (e, t) =>
|
|
241
|
+
}, ze = /* @__PURE__ */ n({ lookup: () => Be }), Be = (e, t) => M.then((n) => n.cloud.dns.lookup(e, t)), Ve = new TextEncoder();
|
|
242
242
|
new TextDecoder();
|
|
243
243
|
var N = (e) => d.isValid(e), P = (e) => f.isValid(e), He = (e) => N(e) ? 4 : P(e) ? 6 : 0, Ue = (...e) => {
|
|
244
244
|
if (typeof e[0] == "string") throw Error("FKN WebVPN does not support IPC connections");
|
|
@@ -359,7 +359,7 @@ var Ke = /* @__PURE__ */ n({
|
|
|
359
359
|
}).catch(n);
|
|
360
360
|
}
|
|
361
361
|
connect(...e) {
|
|
362
|
-
let t = Ue(...e), n = this.__webvpn_tcp_socket_init__(
|
|
362
|
+
let t = Ue(...e), n = this.__webvpn_tcp_socket_init__(M.then((e) => e.cloud.webvpn.tcpSocket({
|
|
363
363
|
remoteAddress: t.host ?? "localhost",
|
|
364
364
|
remotePort: t.port
|
|
365
365
|
})));
|
|
@@ -507,7 +507,7 @@ var Ke = /* @__PURE__ */ n({
|
|
|
507
507
|
let t = Ue(...e), n = (e) => {
|
|
508
508
|
let t = new F({ connection: Promise.resolve(e) });
|
|
509
509
|
this.emit("connection", t);
|
|
510
|
-
}, r = (e) =>
|
|
510
|
+
}, r = (e) => M.then((r) => r.cloud.webvpn.tcpSocketListener({
|
|
511
511
|
localAddress: e,
|
|
512
512
|
localPort: t.port,
|
|
513
513
|
onConnection: n
|
|
@@ -612,7 +612,7 @@ var Ke = /* @__PURE__ */ n({
|
|
|
612
612
|
}
|
|
613
613
|
bind(...e) {
|
|
614
614
|
let t = We(...e), n = this._type === "udp6" ? "::" : "0.0.0.0";
|
|
615
|
-
return this._webVPNUdpSocketPromise =
|
|
615
|
+
return this._webVPNUdpSocketPromise = M.then((e) => e.cloud.webvpn.udpSocket({
|
|
616
616
|
type: this._type,
|
|
617
617
|
address: t.address ?? n,
|
|
618
618
|
port: t.port
|
|
@@ -1326,14 +1326,14 @@ var Ke = /* @__PURE__ */ n({
|
|
|
1326
1326
|
available: () => ht,
|
|
1327
1327
|
dgram: () => Xe,
|
|
1328
1328
|
dns: () => ze,
|
|
1329
|
-
fetch: () =>
|
|
1329
|
+
fetch: () => Le,
|
|
1330
1330
|
http: () => et,
|
|
1331
1331
|
net: () => Ke,
|
|
1332
1332
|
quota: () => Re
|
|
1333
|
-
}), ht = () =>
|
|
1333
|
+
}), ht = () => Pe, Z = async (e) => {
|
|
1334
1334
|
if (typeof window > "u") return !1;
|
|
1335
1335
|
if (h()) return !0;
|
|
1336
|
-
let t = await
|
|
1336
|
+
let t = await M, n = null, r = new Promise((e) => {
|
|
1337
1337
|
n = () => {
|
|
1338
1338
|
h() && e(!0);
|
|
1339
1339
|
}, m.addEventListener("statuschange", n);
|
|
@@ -1364,14 +1364,14 @@ var gt = /* @__PURE__ */ n({
|
|
|
1364
1364
|
queryDirectoryPermission: $("fs.queryDirectoryPermission"),
|
|
1365
1365
|
ensureDirectoryPermission: $("fs.ensureDirectoryPermission")
|
|
1366
1366
|
}, Ct = () => typeof document < "u" && h(), wt = async (e, t) => {
|
|
1367
|
-
if (
|
|
1367
|
+
if (Ie(e), t?.credentials === "include") {
|
|
1368
1368
|
if (typeof document > "u") throw Error("fetch with credentials needs the FKN extension, which only exists in window realms");
|
|
1369
1369
|
return S(e, t);
|
|
1370
1370
|
}
|
|
1371
1371
|
return Ct() ? S(e, {
|
|
1372
1372
|
...t,
|
|
1373
1373
|
credentials: "omit"
|
|
1374
|
-
}) : _t() ? vt(e, t) :
|
|
1374
|
+
}) : _t() ? vt(e, t) : Le(e, t);
|
|
1375
1375
|
}, Tt = /* @__PURE__ */ n({
|
|
1376
1376
|
ATTACH_FRAME_EVENT_KEY: () => C,
|
|
1377
1377
|
assertAttachableFrameUrl: () => T,
|
|
@@ -1426,10 +1426,10 @@ var gt = /* @__PURE__ */ n({
|
|
|
1426
1426
|
return await n?.call(e, { mode: t }) === "granted";
|
|
1427
1427
|
}, jt = "https://fkn.app", Mt = (e, t) => {
|
|
1428
1428
|
if (typeof window > "u") throw Error("FKN @fkn/lib: relayWorker must be called from the main thread");
|
|
1429
|
-
if (!
|
|
1429
|
+
if (!A?.contentWindow) throw Error("FKN @fkn/lib: relayWorker called before the FKN iframe was injected");
|
|
1430
1430
|
ne({
|
|
1431
1431
|
receive: window,
|
|
1432
|
-
emit:
|
|
1432
|
+
emit: A.contentWindow
|
|
1433
1433
|
}, e, {
|
|
1434
1434
|
key: "fkn-api",
|
|
1435
1435
|
originA: t?.originA ?? jt,
|
|
@@ -1438,4 +1438,4 @@ var gt = /* @__PURE__ */ n({
|
|
|
1438
1438
|
});
|
|
1439
1439
|
};
|
|
1440
1440
|
//#endregion
|
|
1441
|
-
export { C as ATTACH_FRAME_EVENT_KEY, T as assertAttachableFrameUrl, x as assertFetchableUrl, be as attachFrame, ve as attachFramePermission, l as box, mt as cloud, me as cookies, e as createVideoElementHandle, gt as desktop, Xe as dgram, ze as dns, Tt as extension, wt as fetch, le as fetchCredentialedPermission, ce as fetchPermission, Et as fs, ye as gotoPermission, i as handleRevivableModules, et as http, b as isBlockedFetchUrl, w as isBlockedFrameUrl, h as isExtensionExposed, t as isType, he as modifyRequestHeadersPermission, Ke as net, xe as permissions, Z as promptInstall, pe as readCookiePermission, Mt as relayWorker, _e as removeRequestHeaderRule, o as revive,
|
|
1441
|
+
export { C as ATTACH_FRAME_EVENT_KEY, T as assertAttachableFrameUrl, x as assertFetchableUrl, be as attachFrame, ve as attachFramePermission, l as box, mt as cloud, me as cookies, e as createVideoElementHandle, gt as desktop, Xe as dgram, ze as dns, Tt as extension, wt as fetch, le as fetchCredentialedPermission, ce as fetchPermission, Et as fs, ye as gotoPermission, i as handleRevivableModules, et as http, b as isBlockedFetchUrl, w as isBlockedFrameUrl, h as isExtensionExposed, t as isType, he as modifyRequestHeadersPermission, Ke as net, xe as permissions, Z as promptInstall, pe as readCookiePermission, Mt as relayWorker, _e as removeRequestHeaderRule, o as revive, _ as setMissingExtensionHandler, ge as setRequestHeaderRule, a as type, v as waitForExtensionExposure };
|