amplibee 0.1.2 → 0.1.3
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/dist/cli.js +50 -32
- package/package.json +4 -2
package/dist/cli.js
CHANGED
|
@@ -1,24 +1,32 @@
|
|
|
1
1
|
import { createRequire as __cr } from 'node:module'; const require = __cr(import.meta.url);
|
|
2
|
-
var
|
|
3
|
-
]))+`;
|
|
4
|
-
Make sure your charset is UTF-8`);r=(r>>>8&255)*192+(r&255),t.put(r,13)}};
|
|
5
|
-
Suggested mode is: `+b.toString(n));switch(r===b.KANJI&&!
|
|
2
|
+
var nl=Object.create;var Xn=Object.defineProperty;var il=Object.getOwnPropertyDescriptor;var sl=Object.getOwnPropertyNames;var ol=Object.getPrototypeOf,al=Object.prototype.hasOwnProperty;var w=(t=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(t,{get:(e,r)=>(typeof require<"u"?require:e)[r]}):t)(function(t){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+t+'" is not supported')});var g=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports);var ll=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of sl(e))!al.call(t,i)&&i!==r&&Xn(t,i,{get:()=>e[i],enumerable:!(n=il(e,i))||n.enumerable});return t};var X=(t,e,r)=>(r=t!=null?nl(ol(t)):{},ll(e||!t||!t.__esModule?Xn(r,"default",{value:t,enumerable:!0}):r,t));var Mr=g((wp,Li)=>{Li.exports=function(){return typeof Promise=="function"&&Promise.prototype&&Promise.prototype.then}});var ae=g(ye=>{var Ur,dc=[0,26,44,70,100,134,172,196,242,292,346,404,466,532,581,655,733,815,901,991,1085,1156,1258,1364,1474,1588,1706,1828,1921,2051,2185,2323,2465,2611,2761,2876,3034,3196,3362,3532,3706];ye.getSymbolSize=function(e){if(!e)throw new Error('"version" cannot be null or undefined');if(e<1||e>40)throw new Error('"version" should be in range from 1 to 40');return e*4+17};ye.getSymbolTotalCodewords=function(e){return dc[e]};ye.getBCHDigit=function(t){let e=0;for(;t!==0;)e++,t>>>=1;return e};ye.setToSJISFunction=function(e){if(typeof e!="function")throw new Error('"toSJISFunc" is not a valid function.');Ur=e};ye.isKanjiModeEnabled=function(){return typeof Ur<"u"};ye.toSJIS=function(e){return Ur(e)}});var Gt=g(F=>{F.L={bit:1};F.M={bit:0};F.Q={bit:3};F.H={bit:2};function pc(t){if(typeof t!="string")throw new Error("Param is not a string");switch(t.toLowerCase()){case"l":case"low":return F.L;case"m":case"medium":return F.M;case"q":case"quartile":return F.Q;case"h":case"high":return F.H;default:throw new Error("Unknown EC Level: "+t)}}F.isValid=function(e){return e&&typeof e.bit<"u"&&e.bit>=0&&e.bit<4};F.from=function(e,r){if(F.isValid(e))return e;try{return pc(e)}catch{return r}}});var Ni=g((xp,Ri)=>{function Oi(){this.buffer=[],this.length=0}Oi.prototype={get:function(t){let e=Math.floor(t/8);return(this.buffer[e]>>>7-t%8&1)===1},put:function(t,e){for(let r=0;r<e;r++)this.putBit((t>>>e-r-1&1)===1)},getLengthInBits:function(){return this.length},putBit:function(t){let e=Math.floor(this.length/8);this.buffer.length<=e&&this.buffer.push(0),t&&(this.buffer[e]|=128>>>this.length%8),this.length++}};Ri.exports=Oi});var Ui=g((Sp,Mi)=>{function ot(t){if(!t||t<1)throw new Error("BitMatrix size must be defined and greater than 0");this.size=t,this.data=new Uint8Array(t*t),this.reservedBit=new Uint8Array(t*t)}ot.prototype.set=function(t,e,r,n){let i=t*this.size+e;this.data[i]=r,n&&(this.reservedBit[i]=!0)};ot.prototype.get=function(t,e){return this.data[t*this.size+e]};ot.prototype.xor=function(t,e,r){this.data[t*this.size+e]^=r};ot.prototype.isReserved=function(t,e){return this.reservedBit[t*this.size+e]};Mi.exports=ot});var qi=g(Vt=>{var gc=ae().getSymbolSize;Vt.getRowColCoords=function(e){if(e===1)return[];let r=Math.floor(e/7)+2,n=gc(e),i=n===145?26:Math.ceil((n-13)/(2*r-2))*2,s=[n-7];for(let o=1;o<r-1;o++)s[o]=s[o-1]-i;return s.push(6),s.reverse()};Vt.getPositions=function(e){let r=[],n=Vt.getRowColCoords(e),i=n.length;for(let s=0;s<i;s++)for(let o=0;o<i;o++)s===0&&o===0||s===0&&o===i-1||s===i-1&&o===0||r.push([n[s],n[o]]);return r}});var Hi=g(Fi=>{var mc=ae().getSymbolSize,Di=7;Fi.getPositions=function(e){let r=mc(e);return[[0,0],[r-Di,0],[0,r-Di]]}});var zi=g(x=>{x.Patterns={PATTERN000:0,PATTERN001:1,PATTERN010:2,PATTERN011:3,PATTERN100:4,PATTERN101:5,PATTERN110:6,PATTERN111:7};var _e={N1:3,N2:3,N3:40,N4:10};x.isValid=function(e){return e!=null&&e!==""&&!isNaN(e)&&e>=0&&e<=7};x.from=function(e){return x.isValid(e)?parseInt(e,10):void 0};x.getPenaltyN1=function(e){let r=e.size,n=0,i=0,s=0,o=null,a=null;for(let l=0;l<r;l++){i=s=0,o=a=null;for(let c=0;c<r;c++){let u=e.get(l,c);u===o?i++:(i>=5&&(n+=_e.N1+(i-5)),o=u,i=1),u=e.get(c,l),u===a?s++:(s>=5&&(n+=_e.N1+(s-5)),a=u,s=1)}i>=5&&(n+=_e.N1+(i-5)),s>=5&&(n+=_e.N1+(s-5))}return n};x.getPenaltyN2=function(e){let r=e.size,n=0;for(let i=0;i<r-1;i++)for(let s=0;s<r-1;s++){let o=e.get(i,s)+e.get(i,s+1)+e.get(i+1,s)+e.get(i+1,s+1);(o===4||o===0)&&n++}return n*_e.N2};x.getPenaltyN3=function(e){let r=e.size,n=0,i=0,s=0;for(let o=0;o<r;o++){i=s=0;for(let a=0;a<r;a++)i=i<<1&2047|e.get(o,a),a>=10&&(i===1488||i===93)&&n++,s=s<<1&2047|e.get(a,o),a>=10&&(s===1488||s===93)&&n++}return n*_e.N3};x.getPenaltyN4=function(e){let r=0,n=e.data.length;for(let s=0;s<n;s++)r+=e.data[s];return Math.abs(Math.ceil(r*100/n/5)-10)*_e.N4};function yc(t,e,r){switch(t){case x.Patterns.PATTERN000:return(e+r)%2===0;case x.Patterns.PATTERN001:return e%2===0;case x.Patterns.PATTERN010:return r%3===0;case x.Patterns.PATTERN011:return(e+r)%3===0;case x.Patterns.PATTERN100:return(Math.floor(e/2)+Math.floor(r/3))%2===0;case x.Patterns.PATTERN101:return e*r%2+e*r%3===0;case x.Patterns.PATTERN110:return(e*r%2+e*r%3)%2===0;case x.Patterns.PATTERN111:return(e*r%3+(e+r)%2)%2===0;default:throw new Error("bad maskPattern:"+t)}}x.applyMask=function(e,r){let n=r.size;for(let i=0;i<n;i++)for(let s=0;s<n;s++)r.isReserved(s,i)||r.xor(s,i,yc(e,s,i))};x.getBestMask=function(e,r){let n=Object.keys(x.Patterns).length,i=0,s=1/0;for(let o=0;o<n;o++){r(o),x.applyMask(o,e);let a=x.getPenaltyN1(e)+x.getPenaltyN2(e)+x.getPenaltyN3(e)+x.getPenaltyN4(e);x.applyMask(o,e),a<s&&(s=a,i=o)}return i}});var Dr=g(qr=>{var le=Gt(),jt=[1,1,1,1,1,1,1,1,1,1,2,2,1,2,2,4,1,2,4,4,2,4,4,4,2,4,6,5,2,4,6,6,2,5,8,8,4,5,8,8,4,5,8,11,4,8,10,11,4,9,12,16,4,9,16,16,6,10,12,18,6,10,17,16,6,11,16,19,6,13,18,21,7,14,21,25,8,16,20,25,8,17,23,25,9,17,23,34,9,18,25,30,10,20,27,32,12,21,29,35,12,23,34,37,12,25,34,40,13,26,35,42,14,28,38,45,15,29,40,48,16,31,43,51,17,33,45,54,18,35,48,57,19,37,51,60,19,38,53,63,20,40,56,66,21,43,59,70,22,45,62,74,24,47,65,77,25,49,68,81],Yt=[7,10,13,17,10,16,22,28,15,26,36,44,20,36,52,64,26,48,72,88,36,64,96,112,40,72,108,130,48,88,132,156,60,110,160,192,72,130,192,224,80,150,224,264,96,176,260,308,104,198,288,352,120,216,320,384,132,240,360,432,144,280,408,480,168,308,448,532,180,338,504,588,196,364,546,650,224,416,600,700,224,442,644,750,252,476,690,816,270,504,750,900,300,560,810,960,312,588,870,1050,336,644,952,1110,360,700,1020,1200,390,728,1050,1260,420,784,1140,1350,450,812,1200,1440,480,868,1290,1530,510,924,1350,1620,540,980,1440,1710,570,1036,1530,1800,570,1064,1590,1890,600,1120,1680,1980,630,1204,1770,2100,660,1260,1860,2220,720,1316,1950,2310,750,1372,2040,2430];qr.getBlocksCount=function(e,r){switch(r){case le.L:return jt[(e-1)*4+0];case le.M:return jt[(e-1)*4+1];case le.Q:return jt[(e-1)*4+2];case le.H:return jt[(e-1)*4+3];default:return}};qr.getTotalCodewordsCount=function(e,r){switch(r){case le.L:return Yt[(e-1)*4+0];case le.M:return Yt[(e-1)*4+1];case le.Q:return Yt[(e-1)*4+2];case le.H:return Yt[(e-1)*4+3];default:return}}});var $i=g(Jt=>{var at=new Uint8Array(512),Kt=new Uint8Array(256);(function(){let e=1;for(let r=0;r<255;r++)at[r]=e,Kt[e]=r,e<<=1,e&256&&(e^=285);for(let r=255;r<512;r++)at[r]=at[r-255]})();Jt.log=function(e){if(e<1)throw new Error("log("+e+")");return Kt[e]};Jt.exp=function(e){return at[e]};Jt.mul=function(e,r){return e===0||r===0?0:at[Kt[e]+Kt[r]]}});var Wi=g(lt=>{var Fr=$i();lt.mul=function(e,r){let n=new Uint8Array(e.length+r.length-1);for(let i=0;i<e.length;i++)for(let s=0;s<r.length;s++)n[i+s]^=Fr.mul(e[i],r[s]);return n};lt.mod=function(e,r){let n=new Uint8Array(e);for(;n.length-r.length>=0;){let i=n[0];for(let o=0;o<r.length;o++)n[o]^=Fr.mul(r[o],i);let s=0;for(;s<n.length&&n[s]===0;)s++;n=n.slice(s)}return n};lt.generateECPolynomial=function(e){let r=new Uint8Array([1]);for(let n=0;n<e;n++)r=lt.mul(r,new Uint8Array([1,Fr.exp(n)]));return r}});var ji=g((Pp,Vi)=>{var Gi=Wi();function Hr(t){this.genPoly=void 0,this.degree=t,this.degree&&this.initialize(this.degree)}Hr.prototype.initialize=function(e){this.degree=e,this.genPoly=Gi.generateECPolynomial(this.degree)};Hr.prototype.encode=function(e){if(!this.genPoly)throw new Error("Encoder not initialized");let r=new Uint8Array(e.length+this.degree);r.set(e);let n=Gi.mod(r,this.genPoly),i=this.degree-n.length;if(i>0){let s=new Uint8Array(this.degree);return s.set(n,i),s}return n};Vi.exports=Hr});var zr=g(Yi=>{Yi.isValid=function(e){return!isNaN(e)&&e>=1&&e<=40}});var $r=g(te=>{var Ki="[0-9]+",_c="[A-Z $%*+\\-./:]+",ct="(?:[u3000-u303F]|[u3040-u309F]|[u30A0-u30FF]|[uFF00-uFFEF]|[u4E00-u9FAF]|[u2605-u2606]|[u2190-u2195]|u203B|[u2010u2015u2018u2019u2025u2026u201Cu201Du2225u2260]|[u0391-u0451]|[u00A7u00A8u00B1u00B4u00D7u00F7])+";ct=ct.replace(/u/g,"\\u");var wc="(?:(?![A-Z0-9 $%*+\\-./:]|"+ct+`)(?:.|[\r
|
|
3
|
+
]))+`;te.KANJI=new RegExp(ct,"g");te.BYTE_KANJI=new RegExp("[^A-Z0-9 $%*+\\-./:]+","g");te.BYTE=new RegExp(wc,"g");te.NUMERIC=new RegExp(Ki,"g");te.ALPHANUMERIC=new RegExp(_c,"g");var bc=new RegExp("^"+ct+"$"),Ec=new RegExp("^"+Ki+"$"),xc=new RegExp("^[A-Z0-9 $%*+\\-./:]+$");te.testKanji=function(e){return bc.test(e)};te.testNumeric=function(e){return Ec.test(e)};te.testAlphanumeric=function(e){return xc.test(e)}});var ce=g(C=>{var Sc=zr(),Wr=$r();C.NUMERIC={id:"Numeric",bit:1,ccBits:[10,12,14]};C.ALPHANUMERIC={id:"Alphanumeric",bit:2,ccBits:[9,11,13]};C.BYTE={id:"Byte",bit:4,ccBits:[8,16,16]};C.KANJI={id:"Kanji",bit:8,ccBits:[8,10,12]};C.MIXED={bit:-1};C.getCharCountIndicator=function(e,r){if(!e.ccBits)throw new Error("Invalid mode: "+e);if(!Sc.isValid(r))throw new Error("Invalid version: "+r);return r>=1&&r<10?e.ccBits[0]:r<27?e.ccBits[1]:e.ccBits[2]};C.getBestModeForData=function(e){return Wr.testNumeric(e)?C.NUMERIC:Wr.testAlphanumeric(e)?C.ALPHANUMERIC:Wr.testKanji(e)?C.KANJI:C.BYTE};C.toString=function(e){if(e&&e.id)return e.id;throw new Error("Invalid mode")};C.isValid=function(e){return e&&e.bit&&e.ccBits};function vc(t){if(typeof t!="string")throw new Error("Param is not a string");switch(t.toLowerCase()){case"numeric":return C.NUMERIC;case"alphanumeric":return C.ALPHANUMERIC;case"kanji":return C.KANJI;case"byte":return C.BYTE;default:throw new Error("Unknown mode: "+t)}}C.from=function(e,r){if(C.isValid(e))return e;try{return vc(e)}catch{return r}}});var es=g(we=>{var Zt=ae(),Tc=Dr(),Ji=Gt(),ue=ce(),Gr=zr(),Qi=7973,Zi=Zt.getBCHDigit(Qi);function Cc(t,e,r){for(let n=1;n<=40;n++)if(e<=we.getCapacity(n,r,t))return n}function Xi(t,e){return ue.getCharCountIndicator(t,e)+4}function kc(t,e){let r=0;return t.forEach(function(n){let i=Xi(n.mode,e);r+=i+n.getBitsLength()}),r}function Ic(t,e){for(let r=1;r<=40;r++)if(kc(t,r)<=we.getCapacity(r,e,ue.MIXED))return r}we.from=function(e,r){return Gr.isValid(e)?parseInt(e,10):r};we.getCapacity=function(e,r,n){if(!Gr.isValid(e))throw new Error("Invalid QR Code version");typeof n>"u"&&(n=ue.BYTE);let i=Zt.getSymbolTotalCodewords(e),s=Tc.getTotalCodewordsCount(e,r),o=(i-s)*8;if(n===ue.MIXED)return o;let a=o-Xi(n,e);switch(n){case ue.NUMERIC:return Math.floor(a/10*3);case ue.ALPHANUMERIC:return Math.floor(a/11*2);case ue.KANJI:return Math.floor(a/13);case ue.BYTE:default:return Math.floor(a/8)}};we.getBestVersionForData=function(e,r){let n,i=Ji.from(r,Ji.M);if(Array.isArray(e)){if(e.length>1)return Ic(e,i);if(e.length===0)return 1;n=e[0]}else n=e;return Cc(n.mode,n.getLength(),i)};we.getEncodedBits=function(e){if(!Gr.isValid(e)||e<7)throw new Error("Invalid QR Code version");let r=e<<12;for(;Zt.getBCHDigit(r)-Zi>=0;)r^=Qi<<Zt.getBCHDigit(r)-Zi;return e<<12|r}});var is=g(ns=>{var Vr=ae(),rs=1335,Ac=21522,ts=Vr.getBCHDigit(rs);ns.getEncodedBits=function(e,r){let n=e.bit<<3|r,i=n<<10;for(;Vr.getBCHDigit(i)-ts>=0;)i^=rs<<Vr.getBCHDigit(i)-ts;return(n<<10|i)^Ac}});var os=g((Mp,ss)=>{var Pc=ce();function Re(t){this.mode=Pc.NUMERIC,this.data=t.toString()}Re.getBitsLength=function(e){return 10*Math.floor(e/3)+(e%3?e%3*3+1:0)};Re.prototype.getLength=function(){return this.data.length};Re.prototype.getBitsLength=function(){return Re.getBitsLength(this.data.length)};Re.prototype.write=function(e){let r,n,i;for(r=0;r+3<=this.data.length;r+=3)n=this.data.substr(r,3),i=parseInt(n,10),e.put(i,10);let s=this.data.length-r;s>0&&(n=this.data.substr(r),i=parseInt(n,10),e.put(i,s*3+1))};ss.exports=Re});var ls=g((Up,as)=>{var Bc=ce(),jr=["0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"," ","$","%","*","+","-",".","/",":"];function Ne(t){this.mode=Bc.ALPHANUMERIC,this.data=t}Ne.getBitsLength=function(e){return 11*Math.floor(e/2)+6*(e%2)};Ne.prototype.getLength=function(){return this.data.length};Ne.prototype.getBitsLength=function(){return Ne.getBitsLength(this.data.length)};Ne.prototype.write=function(e){let r;for(r=0;r+2<=this.data.length;r+=2){let n=jr.indexOf(this.data[r])*45;n+=jr.indexOf(this.data[r+1]),e.put(n,11)}this.data.length%2&&e.put(jr.indexOf(this.data[r]),6)};as.exports=Ne});var us=g((qp,cs)=>{var Lc=ce();function Me(t){this.mode=Lc.BYTE,typeof t=="string"?this.data=new TextEncoder().encode(t):this.data=new Uint8Array(t)}Me.getBitsLength=function(e){return e*8};Me.prototype.getLength=function(){return this.data.length};Me.prototype.getBitsLength=function(){return Me.getBitsLength(this.data.length)};Me.prototype.write=function(t){for(let e=0,r=this.data.length;e<r;e++)t.put(this.data[e],8)};cs.exports=Me});var hs=g((Dp,fs)=>{var Oc=ce(),Rc=ae();function Ue(t){this.mode=Oc.KANJI,this.data=t}Ue.getBitsLength=function(e){return e*13};Ue.prototype.getLength=function(){return this.data.length};Ue.prototype.getBitsLength=function(){return Ue.getBitsLength(this.data.length)};Ue.prototype.write=function(t){let e;for(e=0;e<this.data.length;e++){let r=Rc.toSJIS(this.data[e]);if(r>=33088&&r<=40956)r-=33088;else if(r>=57408&&r<=60351)r-=49472;else throw new Error("Invalid SJIS character: "+this.data[e]+`
|
|
4
|
+
Make sure your charset is UTF-8`);r=(r>>>8&255)*192+(r&255),t.put(r,13)}};fs.exports=Ue});var ds=g((Fp,Yr)=>{"use strict";var ut={single_source_shortest_paths:function(t,e,r){var n={},i={};i[e]=0;var s=ut.PriorityQueue.make();s.push(e,0);for(var o,a,l,c,u,f,h,d,m;!s.empty();){o=s.pop(),a=o.value,c=o.cost,u=t[a]||{};for(l in u)u.hasOwnProperty(l)&&(f=u[l],h=c+f,d=i[l],m=typeof i[l]>"u",(m||d>h)&&(i[l]=h,s.push(l,h),n[l]=a))}if(typeof r<"u"&&typeof i[r]>"u"){var p=["Could not find a path from ",e," to ",r,"."].join("");throw new Error(p)}return n},extract_shortest_path_from_predecessor_list:function(t,e){for(var r=[],n=e,i;n;)r.push(n),i=t[n],n=t[n];return r.reverse(),r},find_path:function(t,e,r){var n=ut.single_source_shortest_paths(t,e,r);return ut.extract_shortest_path_from_predecessor_list(n,r)},PriorityQueue:{make:function(t){var e=ut.PriorityQueue,r={},n;t=t||{};for(n in e)e.hasOwnProperty(n)&&(r[n]=e[n]);return r.queue=[],r.sorter=t.sorter||e.default_sorter,r},default_sorter:function(t,e){return t.cost-e.cost},push:function(t,e){var r={value:t,cost:e};this.queue.push(r),this.queue.sort(this.sorter)},pop:function(){return this.queue.shift()},empty:function(){return this.queue.length===0}}};typeof Yr<"u"&&(Yr.exports=ut)});var Es=g(qe=>{var b=ce(),ms=os(),ys=ls(),_s=us(),ws=hs(),ft=$r(),Qt=ae(),Nc=ds();function ps(t){return unescape(encodeURIComponent(t)).length}function ht(t,e,r){let n=[],i;for(;(i=t.exec(r))!==null;)n.push({data:i[0],index:i.index,mode:e,length:i[0].length});return n}function bs(t){let e=ht(ft.NUMERIC,b.NUMERIC,t),r=ht(ft.ALPHANUMERIC,b.ALPHANUMERIC,t),n,i;return Qt.isKanjiModeEnabled()?(n=ht(ft.BYTE,b.BYTE,t),i=ht(ft.KANJI,b.KANJI,t)):(n=ht(ft.BYTE_KANJI,b.BYTE,t),i=[]),e.concat(r,n,i).sort(function(o,a){return o.index-a.index}).map(function(o){return{data:o.data,mode:o.mode,length:o.length}})}function Kr(t,e){switch(e){case b.NUMERIC:return ms.getBitsLength(t);case b.ALPHANUMERIC:return ys.getBitsLength(t);case b.KANJI:return ws.getBitsLength(t);case b.BYTE:return _s.getBitsLength(t)}}function Mc(t){return t.reduce(function(e,r){let n=e.length-1>=0?e[e.length-1]:null;return n&&n.mode===r.mode?(e[e.length-1].data+=r.data,e):(e.push(r),e)},[])}function Uc(t){let e=[];for(let r=0;r<t.length;r++){let n=t[r];switch(n.mode){case b.NUMERIC:e.push([n,{data:n.data,mode:b.ALPHANUMERIC,length:n.length},{data:n.data,mode:b.BYTE,length:n.length}]);break;case b.ALPHANUMERIC:e.push([n,{data:n.data,mode:b.BYTE,length:n.length}]);break;case b.KANJI:e.push([n,{data:n.data,mode:b.BYTE,length:ps(n.data)}]);break;case b.BYTE:e.push([{data:n.data,mode:b.BYTE,length:ps(n.data)}])}}return e}function qc(t,e){let r={},n={start:{}},i=["start"];for(let s=0;s<t.length;s++){let o=t[s],a=[];for(let l=0;l<o.length;l++){let c=o[l],u=""+s+l;a.push(u),r[u]={node:c,lastCount:0},n[u]={};for(let f=0;f<i.length;f++){let h=i[f];r[h]&&r[h].node.mode===c.mode?(n[h][u]=Kr(r[h].lastCount+c.length,c.mode)-Kr(r[h].lastCount,c.mode),r[h].lastCount+=c.length):(r[h]&&(r[h].lastCount=c.length),n[h][u]=Kr(c.length,c.mode)+4+b.getCharCountIndicator(c.mode,e))}}i=a}for(let s=0;s<i.length;s++)n[i[s]].end=0;return{map:n,table:r}}function gs(t,e){let r,n=b.getBestModeForData(t);if(r=b.from(e,n),r!==b.BYTE&&r.bit<n.bit)throw new Error('"'+t+'" cannot be encoded with mode '+b.toString(r)+`.
|
|
5
|
+
Suggested mode is: `+b.toString(n));switch(r===b.KANJI&&!Qt.isKanjiModeEnabled()&&(r=b.BYTE),r){case b.NUMERIC:return new ms(t);case b.ALPHANUMERIC:return new ys(t);case b.KANJI:return new ws(t);case b.BYTE:return new _s(t)}}qe.fromArray=function(e){return e.reduce(function(r,n){return typeof n=="string"?r.push(gs(n,null)):n.data&&r.push(gs(n.data,n.mode)),r},[])};qe.fromString=function(e,r){let n=bs(e,Qt.isKanjiModeEnabled()),i=Uc(n),s=qc(i,r),o=Nc.find_path(s.map,"start","end"),a=[];for(let l=1;l<o.length-1;l++)a.push(s.table[o[l]].node);return qe.fromArray(Mc(a))};qe.rawSplit=function(e){return qe.fromArray(bs(e,Qt.isKanjiModeEnabled()))}});var tn=g(xs=>{var er=ae(),Jr=Gt(),Dc=Ni(),Fc=Ui(),Hc=qi(),zc=Hi(),Xr=zi(),en=Dr(),$c=ji(),Xt=es(),Wc=is(),Gc=ce(),Zr=Es();function Vc(t,e){let r=t.size,n=zc.getPositions(e);for(let i=0;i<n.length;i++){let s=n[i][0],o=n[i][1];for(let a=-1;a<=7;a++)if(!(s+a<=-1||r<=s+a))for(let l=-1;l<=7;l++)o+l<=-1||r<=o+l||(a>=0&&a<=6&&(l===0||l===6)||l>=0&&l<=6&&(a===0||a===6)||a>=2&&a<=4&&l>=2&&l<=4?t.set(s+a,o+l,!0,!0):t.set(s+a,o+l,!1,!0))}}function jc(t){let e=t.size;for(let r=8;r<e-8;r++){let n=r%2===0;t.set(r,6,n,!0),t.set(6,r,n,!0)}}function Yc(t,e){let r=Hc.getPositions(e);for(let n=0;n<r.length;n++){let i=r[n][0],s=r[n][1];for(let o=-2;o<=2;o++)for(let a=-2;a<=2;a++)o===-2||o===2||a===-2||a===2||o===0&&a===0?t.set(i+o,s+a,!0,!0):t.set(i+o,s+a,!1,!0)}}function Kc(t,e){let r=t.size,n=Xt.getEncodedBits(e),i,s,o;for(let a=0;a<18;a++)i=Math.floor(a/3),s=a%3+r-8-3,o=(n>>a&1)===1,t.set(i,s,o,!0),t.set(s,i,o,!0)}function Qr(t,e,r){let n=t.size,i=Wc.getEncodedBits(e,r),s,o;for(s=0;s<15;s++)o=(i>>s&1)===1,s<6?t.set(s,8,o,!0):s<8?t.set(s+1,8,o,!0):t.set(n-15+s,8,o,!0),s<8?t.set(8,n-s-1,o,!0):s<9?t.set(8,15-s-1+1,o,!0):t.set(8,15-s-1,o,!0);t.set(n-8,8,1,!0)}function Jc(t,e){let r=t.size,n=-1,i=r-1,s=7,o=0;for(let a=r-1;a>0;a-=2)for(a===6&&a--;;){for(let l=0;l<2;l++)if(!t.isReserved(i,a-l)){let c=!1;o<e.length&&(c=(e[o]>>>s&1)===1),t.set(i,a-l,c),s--,s===-1&&(o++,s=7)}if(i+=n,i<0||r<=i){i-=n,n=-n;break}}}function Zc(t,e,r){let n=new Dc;r.forEach(function(l){n.put(l.mode.bit,4),n.put(l.getLength(),Gc.getCharCountIndicator(l.mode,t)),l.write(n)});let i=er.getSymbolTotalCodewords(t),s=en.getTotalCodewordsCount(t,e),o=(i-s)*8;for(n.getLengthInBits()+4<=o&&n.put(0,4);n.getLengthInBits()%8!==0;)n.putBit(0);let a=(o-n.getLengthInBits())/8;for(let l=0;l<a;l++)n.put(l%2?17:236,8);return Qc(n,t,e)}function Qc(t,e,r){let n=er.getSymbolTotalCodewords(e),i=en.getTotalCodewordsCount(e,r),s=n-i,o=en.getBlocksCount(e,r),a=n%o,l=o-a,c=Math.floor(n/o),u=Math.floor(s/o),f=u+1,h=c-u,d=new $c(h),m=0,p=new Array(o),y=new Array(o),_=0,B=new Uint8Array(t.buffer);for(let U=0;U<o;U++){let Ae=U<l?u:f;p[U]=B.slice(m,m+Ae),y[U]=d.encode(p[U]),m+=Ae,_=Math.max(_,Ae)}let O=new Uint8Array(n),S=0,T,E;for(T=0;T<_;T++)for(E=0;E<o;E++)T<p[E].length&&(O[S++]=p[E][T]);for(T=0;T<h;T++)for(E=0;E<o;E++)O[S++]=y[E][T];return O}function Xc(t,e,r,n){let i;if(Array.isArray(t))i=Zr.fromArray(t);else if(typeof t=="string"){let c=e;if(!c){let u=Zr.rawSplit(t);c=Xt.getBestVersionForData(u,r)}i=Zr.fromString(t,c||40)}else throw new Error("Invalid data");let s=Xt.getBestVersionForData(i,r);if(!s)throw new Error("The amount of data is too big to be stored in a QR Code");if(!e)e=s;else if(e<s)throw new Error(`
|
|
6
6
|
The chosen QR Code version cannot contain this amount of data.
|
|
7
|
-
Minimum version required to store current data is: `+
|
|
8
|
-
`);let o=qc(e,r,s),a=Jt.getSymbolSize(e),l=new Ic(a);return Rc(l,e),Nc(l),Mc(l,e),Yr(l,r,0),e>=7&&Uc(l,e),Dc(l,o),isNaN(n)&&(n=Vr.getBestMask(l,Yr.bind(null,l,r))),Vr.applyMask(n,l),Yr(l,r,n),{modules:l,version:e,errorCorrectionLevel:r,maskPattern:n,segments:s}}yi.create=function(e,r){if(typeof e>"u"||e==="")throw new Error("No input text");let n=Gr.M,s,i;return typeof r<"u"&&(n=Gr.from(r.errorCorrectionLevel,Gr.M),s=Kt.from(r.version),i=Vr.from(r.maskPattern),r.toSJISFunc&&Jt.setToSJISFunction(r.toSJISFunc)),Hc(e,s,n,i)}});var Zr=g((yp,bi)=>{"use strict";var zc=w("util"),wi=w("stream"),W=bi.exports=function(){wi.call(this),this._buffers=[],this._buffered=0,this._reads=[],this._paused=!1,this._encoding="utf8",this.writable=!0};zc.inherits(W,wi);W.prototype.read=function(t,e){this._reads.push({length:Math.abs(t),allowLess:t<0,func:e}),process.nextTick(function(){this._process(),this._paused&&this._reads&&this._reads.length>0&&(this._paused=!1,this.emit("drain"))}.bind(this))};W.prototype.write=function(t,e){if(!this.writable)return this.emit("error",new Error("Stream not writable")),!1;let r;return Buffer.isBuffer(t)?r=t:r=Buffer.from(t,e||this._encoding),this._buffers.push(r),this._buffered+=r.length,this._process(),this._reads&&this._reads.length===0&&(this._paused=!0),this.writable&&!this._paused};W.prototype.end=function(t,e){t&&this.write(t,e),this.writable=!1,this._buffers&&(this._buffers.length===0?this._end():(this._buffers.push(null),this._process()))};W.prototype.destroySoon=W.prototype.end;W.prototype._end=function(){this._reads.length>0&&this.emit("error",new Error("Unexpected end of input")),this.destroy()};W.prototype.destroy=function(){this._buffers&&(this.writable=!1,this._reads=null,this._buffers=null,this.emit("close"))};W.prototype._processReadAllowingLess=function(t){this._reads.shift();let e=this._buffers[0];e.length>t.length?(this._buffered-=t.length,this._buffers[0]=e.slice(t.length),t.func.call(this,e.slice(0,t.length))):(this._buffered-=e.length,this._buffers.shift(),t.func.call(this,e))};W.prototype._processRead=function(t){this._reads.shift();let e=0,r=0,n=Buffer.alloc(t.length);for(;e<t.length;){let s=this._buffers[r++],i=Math.min(s.length,t.length-e);s.copy(n,e,0,i),e+=i,i!==s.length&&(this._buffers[--r]=s.slice(i))}r>0&&this._buffers.splice(0,r),this._buffered-=t.length,t.func.call(this,n)};W.prototype._process=function(){try{for(;this._buffered>0&&this._reads&&this._reads.length>0;){let t=this._reads[0];if(t.allowLess)this._processReadAllowingLess(t);else if(this._buffered>=t.length)this._processRead(t);else break}this._buffers&&!this.writable&&this._end()}catch(t){this.emit("error",t)}}});var Qr=g(Xr=>{"use strict";var ue=[{x:[0],y:[0]},{x:[4],y:[0]},{x:[0,4],y:[4]},{x:[2,6],y:[0,4]},{x:[0,2,4,6],y:[2,6]},{x:[1,3,5,7],y:[0,2,4,6]},{x:[0,1,2,3,4,5,6,7],y:[1,3,5,7]}];Xr.getImagePasses=function(t,e){let r=[],n=t%8,s=e%8,i=(t-n)/8,o=(e-s)/8;for(let a=0;a<ue.length;a++){let l=ue[a],c=i*l.x.length,f=o*l.y.length;for(let u=0;u<l.x.length&&l.x[u]<n;u++)c++;for(let u=0;u<l.y.length&&l.y[u]<s;u++)f++;c>0&&f>0&&r.push({width:c,height:f,index:a})}return r};Xr.getInterlaceIterator=function(t){return function(e,r,n){let s=e%ue[n].x.length,i=(e-s)/ue[n].x.length*8+ue[n].x[s],o=r%ue[n].y.length,a=(r-o)/ue[n].y.length*8+ue[n].y[o];return i*4+a*t*4}}});var en=g((bp,Ei)=>{"use strict";Ei.exports=function(e,r,n){let s=e+r-n,i=Math.abs(s-e),o=Math.abs(s-r),a=Math.abs(s-n);return i<=o&&i<=a?e:o<=a?r:n}});var tn=g((Ep,xi)=>{"use strict";var Wc=Qr(),$c=en();function Si(t,e,r){let n=t*e;return r!==8&&(n=Math.ceil(n/(8/r))),n}var De=xi.exports=function(t,e){let r=t.width,n=t.height,s=t.interlace,i=t.bpp,o=t.depth;if(this.read=e.read,this.write=e.write,this.complete=e.complete,this._imageIndex=0,this._images=[],s){let a=Wc.getImagePasses(r,n);for(let l=0;l<a.length;l++)this._images.push({byteWidth:Si(a[l].width,i,o),height:a[l].height,lineIndex:0})}else this._images.push({byteWidth:Si(r,i,o),height:n,lineIndex:0});o===8?this._xComparison=i:o===16?this._xComparison=i*2:this._xComparison=1};De.prototype.start=function(){this.read(this._images[this._imageIndex].byteWidth+1,this._reverseFilterLine.bind(this))};De.prototype._unFilterType1=function(t,e,r){let n=this._xComparison,s=n-1;for(let i=0;i<r;i++){let o=t[1+i],a=i>s?e[i-n]:0;e[i]=o+a}};De.prototype._unFilterType2=function(t,e,r){let n=this._lastLine;for(let s=0;s<r;s++){let i=t[1+s],o=n?n[s]:0;e[s]=i+o}};De.prototype._unFilterType3=function(t,e,r){let n=this._xComparison,s=n-1,i=this._lastLine;for(let o=0;o<r;o++){let a=t[1+o],l=i?i[o]:0,c=o>s?e[o-n]:0,f=Math.floor((c+l)/2);e[o]=a+f}};De.prototype._unFilterType4=function(t,e,r){let n=this._xComparison,s=n-1,i=this._lastLine;for(let o=0;o<r;o++){let a=t[1+o],l=i?i[o]:0,c=o>s?e[o-n]:0,f=o>s&&i?i[o-n]:0,u=$c(c,l,f);e[o]=a+u}};De.prototype._reverseFilterLine=function(t){let e=t[0],r,n=this._images[this._imageIndex],s=n.byteWidth;if(e===0)r=t.slice(1,s+1);else switch(r=Buffer.alloc(s),e){case 1:this._unFilterType1(t,r,s);break;case 2:this._unFilterType2(t,r,s);break;case 3:this._unFilterType3(t,r,s);break;case 4:this._unFilterType4(t,r,s);break;default:throw new Error("Unrecognised filter type - "+e)}this.write(r),n.lineIndex++,n.lineIndex>=n.height?(this._lastLine=null,this._imageIndex++,n=this._images[this._imageIndex]):this._lastLine=r,n?this.read(n.byteWidth+1,this._reverseFilterLine.bind(this)):(this._lastLine=null,this.complete())}});var vi=g((Sp,Ti)=>{"use strict";var Gc=w("util"),Ci=Zr(),jc=tn(),Yc=Ti.exports=function(t){Ci.call(this);let e=[],r=this;this._filter=new jc(t,{read:this.read.bind(this),write:function(n){e.push(n)},complete:function(){r.emit("complete",Buffer.concat(e))}}),this._filter.start()};Gc.inherits(Yc,Ci)});var qe=g((xp,ki)=>{"use strict";ki.exports={PNG_SIGNATURE:[137,80,78,71,13,10,26,10],TYPE_IHDR:1229472850,TYPE_IEND:1229278788,TYPE_IDAT:1229209940,TYPE_PLTE:1347179589,TYPE_tRNS:1951551059,TYPE_gAMA:1732332865,COLORTYPE_GRAYSCALE:0,COLORTYPE_PALETTE:1,COLORTYPE_COLOR:2,COLORTYPE_ALPHA:4,COLORTYPE_PALETTE_COLOR:3,COLORTYPE_COLOR_ALPHA:6,COLORTYPE_TO_BPP_MAP:{0:1,2:3,3:1,4:2,6:4},GAMMA_DIVISION:1e5}});var sn=g((Cp,Ii)=>{"use strict";var rn=[];(function(){for(let t=0;t<256;t++){let e=t;for(let r=0;r<8;r++)e&1?e=3988292384^e>>>1:e=e>>>1;rn[t]=e}})();var nn=Ii.exports=function(){this._crc=-1};nn.prototype.write=function(t){for(let e=0;e<t.length;e++)this._crc=rn[(this._crc^t[e])&255]^this._crc>>>8;return!0};nn.prototype.crc32=function(){return this._crc^-1};nn.crc32=function(t){let e=-1;for(let r=0;r<t.length;r++)e=rn[(e^t[r])&255]^e>>>8;return e^-1}});var on=g((Tp,Ai)=>{"use strict";var k=qe(),Vc=sn(),I=Ai.exports=function(t,e){this._options=t,t.checkCRC=t.checkCRC!==!1,this._hasIHDR=!1,this._hasIEND=!1,this._emittedHeadersFinished=!1,this._palette=[],this._colorType=0,this._chunks={},this._chunks[k.TYPE_IHDR]=this._handleIHDR.bind(this),this._chunks[k.TYPE_IEND]=this._handleIEND.bind(this),this._chunks[k.TYPE_IDAT]=this._handleIDAT.bind(this),this._chunks[k.TYPE_PLTE]=this._handlePLTE.bind(this),this._chunks[k.TYPE_tRNS]=this._handleTRNS.bind(this),this._chunks[k.TYPE_gAMA]=this._handleGAMA.bind(this),this.read=e.read,this.error=e.error,this.metadata=e.metadata,this.gamma=e.gamma,this.transColor=e.transColor,this.palette=e.palette,this.parsed=e.parsed,this.inflateData=e.inflateData,this.finished=e.finished,this.simpleTransparency=e.simpleTransparency,this.headersFinished=e.headersFinished||function(){}};I.prototype.start=function(){this.read(k.PNG_SIGNATURE.length,this._parseSignature.bind(this))};I.prototype._parseSignature=function(t){let e=k.PNG_SIGNATURE;for(let r=0;r<e.length;r++)if(t[r]!==e[r]){this.error(new Error("Invalid file signature"));return}this.read(8,this._parseChunkBegin.bind(this))};I.prototype._parseChunkBegin=function(t){let e=t.readUInt32BE(0),r=t.readUInt32BE(4),n="";for(let i=4;i<8;i++)n+=String.fromCharCode(t[i]);let s=!!(t[4]&32);if(!this._hasIHDR&&r!==k.TYPE_IHDR){this.error(new Error("Expected IHDR on beggining"));return}if(this._crc=new Vc,this._crc.write(Buffer.from(n)),this._chunks[r])return this._chunks[r](e);if(!s){this.error(new Error("Unsupported critical chunk type "+n));return}this.read(e+4,this._skipChunk.bind(this))};I.prototype._skipChunk=function(){this.read(8,this._parseChunkBegin.bind(this))};I.prototype._handleChunkEnd=function(){this.read(4,this._parseChunkEnd.bind(this))};I.prototype._parseChunkEnd=function(t){let e=t.readInt32BE(0),r=this._crc.crc32();if(this._options.checkCRC&&r!==e){this.error(new Error("Crc error - "+e+" - "+r));return}this._hasIEND||this.read(8,this._parseChunkBegin.bind(this))};I.prototype._handleIHDR=function(t){this.read(t,this._parseIHDR.bind(this))};I.prototype._parseIHDR=function(t){this._crc.write(t);let e=t.readUInt32BE(0),r=t.readUInt32BE(4),n=t[8],s=t[9],i=t[10],o=t[11],a=t[12];if(n!==8&&n!==4&&n!==2&&n!==1&&n!==16){this.error(new Error("Unsupported bit depth "+n));return}if(!(s in k.COLORTYPE_TO_BPP_MAP)){this.error(new Error("Unsupported color type"));return}if(i!==0){this.error(new Error("Unsupported compression method"));return}if(o!==0){this.error(new Error("Unsupported filter method"));return}if(a!==0&&a!==1){this.error(new Error("Unsupported interlace method"));return}this._colorType=s;let l=k.COLORTYPE_TO_BPP_MAP[this._colorType];this._hasIHDR=!0,this.metadata({width:e,height:r,depth:n,interlace:!!a,palette:!!(s&k.COLORTYPE_PALETTE),color:!!(s&k.COLORTYPE_COLOR),alpha:!!(s&k.COLORTYPE_ALPHA),bpp:l,colorType:s}),this._handleChunkEnd()};I.prototype._handlePLTE=function(t){this.read(t,this._parsePLTE.bind(this))};I.prototype._parsePLTE=function(t){this._crc.write(t);let e=Math.floor(t.length/3);for(let r=0;r<e;r++)this._palette.push([t[r*3],t[r*3+1],t[r*3+2],255]);this.palette(this._palette),this._handleChunkEnd()};I.prototype._handleTRNS=function(t){this.simpleTransparency(),this.read(t,this._parseTRNS.bind(this))};I.prototype._parseTRNS=function(t){if(this._crc.write(t),this._colorType===k.COLORTYPE_PALETTE_COLOR){if(this._palette.length===0){this.error(new Error("Transparency chunk must be after palette"));return}if(t.length>this._palette.length){this.error(new Error("More transparent colors than palette size"));return}for(let e=0;e<t.length;e++)this._palette[e][3]=t[e];this.palette(this._palette)}this._colorType===k.COLORTYPE_GRAYSCALE&&this.transColor([t.readUInt16BE(0)]),this._colorType===k.COLORTYPE_COLOR&&this.transColor([t.readUInt16BE(0),t.readUInt16BE(2),t.readUInt16BE(4)]),this._handleChunkEnd()};I.prototype._handleGAMA=function(t){this.read(t,this._parseGAMA.bind(this))};I.prototype._parseGAMA=function(t){this._crc.write(t),this.gamma(t.readUInt32BE(0)/k.GAMMA_DIVISION),this._handleChunkEnd()};I.prototype._handleIDAT=function(t){this._emittedHeadersFinished||(this._emittedHeadersFinished=!0,this.headersFinished()),this.read(-t,this._parseIDAT.bind(this,t))};I.prototype._parseIDAT=function(t,e){if(this._crc.write(e),this._colorType===k.COLORTYPE_PALETTE_COLOR&&this._palette.length===0)throw new Error("Expected palette not found");this.inflateData(e);let r=t-e.length;r>0?this._handleIDAT(r):this._handleChunkEnd()};I.prototype._handleIEND=function(t){this.read(t,this._parseIEND.bind(this))};I.prototype._parseIEND=function(t){this._crc.write(t),this._hasIEND=!0,this._handleChunkEnd(),this.finished&&this.finished()}});var an=g(Bi=>{"use strict";var Pi=Qr(),Kc=[function(){},function(t,e,r,n){if(n===e.length)throw new Error("Ran out of data");let s=e[n];t[r]=s,t[r+1]=s,t[r+2]=s,t[r+3]=255},function(t,e,r,n){if(n+1>=e.length)throw new Error("Ran out of data");let s=e[n];t[r]=s,t[r+1]=s,t[r+2]=s,t[r+3]=e[n+1]},function(t,e,r,n){if(n+2>=e.length)throw new Error("Ran out of data");t[r]=e[n],t[r+1]=e[n+1],t[r+2]=e[n+2],t[r+3]=255},function(t,e,r,n){if(n+3>=e.length)throw new Error("Ran out of data");t[r]=e[n],t[r+1]=e[n+1],t[r+2]=e[n+2],t[r+3]=e[n+3]}],Jc=[function(){},function(t,e,r,n){let s=e[0];t[r]=s,t[r+1]=s,t[r+2]=s,t[r+3]=n},function(t,e,r){let n=e[0];t[r]=n,t[r+1]=n,t[r+2]=n,t[r+3]=e[1]},function(t,e,r,n){t[r]=e[0],t[r+1]=e[1],t[r+2]=e[2],t[r+3]=n},function(t,e,r){t[r]=e[0],t[r+1]=e[1],t[r+2]=e[2],t[r+3]=e[3]}];function Zc(t,e){let r=[],n=0;function s(){if(n===t.length)throw new Error("Ran out of data");let i=t[n];n++;let o,a,l,c,f,u,h,d;switch(e){default:throw new Error("unrecognised depth");case 16:h=t[n],n++,r.push((i<<8)+h);break;case 4:h=i&15,d=i>>4,r.push(d,h);break;case 2:f=i&3,u=i>>2&3,h=i>>4&3,d=i>>6&3,r.push(d,h,u,f);break;case 1:o=i&1,a=i>>1&1,l=i>>2&1,c=i>>3&1,f=i>>4&1,u=i>>5&1,h=i>>6&1,d=i>>7&1,r.push(d,h,u,f,c,l,a,o);break}}return{get:function(i){for(;r.length<i;)s();let o=r.slice(0,i);return r=r.slice(i),o},resetAfterLine:function(){r.length=0},end:function(){if(n!==t.length)throw new Error("extra data found")}}}function Xc(t,e,r,n,s,i){let o=t.width,a=t.height,l=t.index;for(let c=0;c<a;c++)for(let f=0;f<o;f++){let u=r(f,c,l);Kc[n](e,s,u,i),i+=n}return i}function Qc(t,e,r,n,s,i){let o=t.width,a=t.height,l=t.index;for(let c=0;c<a;c++){for(let f=0;f<o;f++){let u=s.get(n),h=r(f,c,l);Jc[n](e,u,h,i)}s.resetAfterLine()}}Bi.dataToBitMap=function(t,e){let r=e.width,n=e.height,s=e.depth,i=e.bpp,o=e.interlace,a;s!==8&&(a=Zc(t,s));let l;s<=8?l=Buffer.alloc(r*n*4):l=new Uint16Array(r*n*4);let c=Math.pow(2,s)-1,f=0,u,h;if(o)u=Pi.getImagePasses(r,n),h=Pi.getInterlaceIterator(r,n);else{let d=0;h=function(){let m=d;return d+=4,m},u=[{width:r,height:n}]}for(let d=0;d<u.length;d++)s===8?f=Xc(u[d],l,h,i,t,f):Qc(u[d],l,h,i,a,c);if(s===8){if(f!==t.length)throw new Error("extra data found")}else a.end();return l}});var ln=g((kp,Li)=>{"use strict";function ef(t,e,r,n,s){let i=0;for(let o=0;o<n;o++)for(let a=0;a<r;a++){let l=s[t[i]];if(!l)throw new Error("index "+t[i]+" not in palette");for(let c=0;c<4;c++)e[i+c]=l[c];i+=4}}function tf(t,e,r,n,s){let i=0;for(let o=0;o<n;o++)for(let a=0;a<r;a++){let l=!1;if(s.length===1?s[0]===t[i]&&(l=!0):s[0]===t[i]&&s[1]===t[i+1]&&s[2]===t[i+2]&&(l=!0),l)for(let c=0;c<4;c++)e[i+c]=0;i+=4}}function rf(t,e,r,n,s){let i=255,o=Math.pow(2,s)-1,a=0;for(let l=0;l<n;l++)for(let c=0;c<r;c++){for(let f=0;f<4;f++)e[a+f]=Math.floor(t[a+f]*i/o+.5);a+=4}}Li.exports=function(t,e){let r=e.depth,n=e.width,s=e.height,i=e.colorType,o=e.transColor,a=e.palette,l=t;return i===3?ef(t,l,n,s,a):(o&&tf(t,l,n,s,o),r!==8&&(r===16&&(l=Buffer.alloc(n*s*4)),rf(t,l,n,s,r))),l}});var Ni=g((Ip,Ri)=>{"use strict";var nf=w("util"),cn=w("zlib"),Oi=Zr(),sf=vi(),of=on(),af=an(),lf=ln(),V=Ri.exports=function(t){Oi.call(this),this._parser=new of(t,{read:this.read.bind(this),error:this._handleError.bind(this),metadata:this._handleMetaData.bind(this),gamma:this.emit.bind(this,"gamma"),palette:this._handlePalette.bind(this),transColor:this._handleTransColor.bind(this),finished:this._finished.bind(this),inflateData:this._inflateData.bind(this),simpleTransparency:this._simpleTransparency.bind(this),headersFinished:this._headersFinished.bind(this)}),this._options=t,this.writable=!0,this._parser.start()};nf.inherits(V,Oi);V.prototype._handleError=function(t){this.emit("error",t),this.writable=!1,this.destroy(),this._inflate&&this._inflate.destroy&&this._inflate.destroy(),this._filter&&(this._filter.destroy(),this._filter.on("error",function(){})),this.errord=!0};V.prototype._inflateData=function(t){if(!this._inflate)if(this._bitmapInfo.interlace)this._inflate=cn.createInflate(),this._inflate.on("error",this.emit.bind(this,"error")),this._filter.on("complete",this._complete.bind(this)),this._inflate.pipe(this._filter);else{let r=((this._bitmapInfo.width*this._bitmapInfo.bpp*this._bitmapInfo.depth+7>>3)+1)*this._bitmapInfo.height,n=Math.max(r,cn.Z_MIN_CHUNK);this._inflate=cn.createInflate({chunkSize:n});let s=r,i=this.emit.bind(this,"error");this._inflate.on("error",function(a){s&&i(a)}),this._filter.on("complete",this._complete.bind(this));let o=this._filter.write.bind(this._filter);this._inflate.on("data",function(a){s&&(a.length>s&&(a=a.slice(0,s)),s-=a.length,o(a))}),this._inflate.on("end",this._filter.end.bind(this._filter))}this._inflate.write(t)};V.prototype._handleMetaData=function(t){this._metaData=t,this._bitmapInfo=Object.create(t),this._filter=new sf(this._bitmapInfo)};V.prototype._handleTransColor=function(t){this._bitmapInfo.transColor=t};V.prototype._handlePalette=function(t){this._bitmapInfo.palette=t};V.prototype._simpleTransparency=function(){this._metaData.alpha=!0};V.prototype._headersFinished=function(){this.emit("metadata",this._metaData)};V.prototype._finished=function(){this.errord||(this._inflate?this._inflate.end():this.emit("error","No Inflate block"))};V.prototype._complete=function(t){if(this.errord)return;let e;try{let r=af.dataToBitMap(t,this._bitmapInfo);e=lf(r,this._bitmapInfo),r=null}catch(r){this._handleError(r);return}this.emit("parsed",e)}});var Ui=g((Ap,Mi)=>{"use strict";var q=qe();Mi.exports=function(t,e,r,n){let s=[q.COLORTYPE_COLOR_ALPHA,q.COLORTYPE_ALPHA].indexOf(n.colorType)!==-1;if(n.colorType===n.inputColorType){let m=(function(){let p=new ArrayBuffer(2);return new DataView(p).setInt16(0,256,!0),new Int16Array(p)[0]!==256})();if(n.bitDepth===8||n.bitDepth===16&&m)return t}let i=n.bitDepth!==16?t:new Uint16Array(t.buffer),o=255,a=q.COLORTYPE_TO_BPP_MAP[n.inputColorType];a===4&&!n.inputHasAlpha&&(a=3);let l=q.COLORTYPE_TO_BPP_MAP[n.colorType];n.bitDepth===16&&(o=65535,l*=2);let c=Buffer.alloc(e*r*l),f=0,u=0,h=n.bgColor||{};h.red===void 0&&(h.red=o),h.green===void 0&&(h.green=o),h.blue===void 0&&(h.blue=o);function d(){let m,p,_,y=o;switch(n.inputColorType){case q.COLORTYPE_COLOR_ALPHA:y=i[f+3],m=i[f],p=i[f+1],_=i[f+2];break;case q.COLORTYPE_COLOR:m=i[f],p=i[f+1],_=i[f+2];break;case q.COLORTYPE_ALPHA:y=i[f+1],m=i[f],p=m,_=m;break;case q.COLORTYPE_GRAYSCALE:m=i[f],p=m,_=m;break;default:throw new Error("input color type:"+n.inputColorType+" is not supported at present")}return n.inputHasAlpha&&(s||(y/=o,m=Math.min(Math.max(Math.round((1-y)*h.red+y*m),0),o),p=Math.min(Math.max(Math.round((1-y)*h.green+y*p),0),o),_=Math.min(Math.max(Math.round((1-y)*h.blue+y*_),0),o))),{red:m,green:p,blue:_,alpha:y}}for(let m=0;m<r;m++)for(let p=0;p<e;p++){let _=d(i,f);switch(n.colorType){case q.COLORTYPE_COLOR_ALPHA:case q.COLORTYPE_COLOR:n.bitDepth===8?(c[u]=_.red,c[u+1]=_.green,c[u+2]=_.blue,s&&(c[u+3]=_.alpha)):(c.writeUInt16BE(_.red,u),c.writeUInt16BE(_.green,u+2),c.writeUInt16BE(_.blue,u+4),s&&c.writeUInt16BE(_.alpha,u+6));break;case q.COLORTYPE_ALPHA:case q.COLORTYPE_GRAYSCALE:{let y=(_.red+_.green+_.blue)/3;n.bitDepth===8?(c[u]=y,s&&(c[u+1]=_.alpha)):(c.writeUInt16BE(y,u),s&&c.writeUInt16BE(_.alpha,u+2));break}default:throw new Error("unrecognised color Type "+n.colorType)}f+=a,u+=l}return c}});var Fi=g((Pp,qi)=>{"use strict";var Di=en();function cf(t,e,r,n,s){for(let i=0;i<r;i++)n[s+i]=t[e+i]}function ff(t,e,r){let n=0,s=e+r;for(let i=e;i<s;i++)n+=Math.abs(t[i]);return n}function uf(t,e,r,n,s,i){for(let o=0;o<r;o++){let a=o>=i?t[e+o-i]:0,l=t[e+o]-a;n[s+o]=l}}function hf(t,e,r,n){let s=0;for(let i=0;i<r;i++){let o=i>=n?t[e+i-n]:0,a=t[e+i]-o;s+=Math.abs(a)}return s}function df(t,e,r,n,s){for(let i=0;i<r;i++){let o=e>0?t[e+i-r]:0,a=t[e+i]-o;n[s+i]=a}}function pf(t,e,r){let n=0,s=e+r;for(let i=e;i<s;i++){let o=e>0?t[i-r]:0,a=t[i]-o;n+=Math.abs(a)}return n}function gf(t,e,r,n,s,i){for(let o=0;o<r;o++){let a=o>=i?t[e+o-i]:0,l=e>0?t[e+o-r]:0,c=t[e+o]-(a+l>>1);n[s+o]=c}}function mf(t,e,r,n){let s=0;for(let i=0;i<r;i++){let o=i>=n?t[e+i-n]:0,a=e>0?t[e+i-r]:0,l=t[e+i]-(o+a>>1);s+=Math.abs(l)}return s}function _f(t,e,r,n,s,i){for(let o=0;o<r;o++){let a=o>=i?t[e+o-i]:0,l=e>0?t[e+o-r]:0,c=e>0&&o>=i?t[e+o-(r+i)]:0,f=t[e+o]-Di(a,l,c);n[s+o]=f}}function yf(t,e,r,n){let s=0;for(let i=0;i<r;i++){let o=i>=n?t[e+i-n]:0,a=e>0?t[e+i-r]:0,l=e>0&&i>=n?t[e+i-(r+n)]:0,c=t[e+i]-Di(o,a,l);s+=Math.abs(c)}return s}var wf={0:cf,1:uf,2:df,3:gf,4:_f},bf={0:ff,1:hf,2:pf,3:mf,4:yf};qi.exports=function(t,e,r,n,s){let i;if(!("filterType"in n)||n.filterType===-1)i=[0,1,2,3,4];else if(typeof n.filterType=="number")i=[n.filterType];else throw new Error("unrecognised filter types");n.bitDepth===16&&(s*=2);let o=e*s,a=0,l=0,c=Buffer.alloc((o+1)*r),f=i[0];for(let u=0;u<r;u++){if(i.length>1){let h=1/0;for(let d=0;d<i.length;d++){let m=bf[i[d]](t,l,o,s);m<h&&(f=i[d],h=m)}}c[a]=f,a++,wf[f](t,l,o,c,a,s),a+=o,l+=o}return c}});var fn=g((Bp,Hi)=>{"use strict";var L=qe(),Ef=sn(),Sf=Ui(),xf=Fi(),Cf=w("zlib"),he=Hi.exports=function(t){if(this._options=t,t.deflateChunkSize=t.deflateChunkSize||32*1024,t.deflateLevel=t.deflateLevel!=null?t.deflateLevel:9,t.deflateStrategy=t.deflateStrategy!=null?t.deflateStrategy:3,t.inputHasAlpha=t.inputHasAlpha!=null?t.inputHasAlpha:!0,t.deflateFactory=t.deflateFactory||Cf.createDeflate,t.bitDepth=t.bitDepth||8,t.colorType=typeof t.colorType=="number"?t.colorType:L.COLORTYPE_COLOR_ALPHA,t.inputColorType=typeof t.inputColorType=="number"?t.inputColorType:L.COLORTYPE_COLOR_ALPHA,[L.COLORTYPE_GRAYSCALE,L.COLORTYPE_COLOR,L.COLORTYPE_COLOR_ALPHA,L.COLORTYPE_ALPHA].indexOf(t.colorType)===-1)throw new Error("option color type:"+t.colorType+" is not supported at present");if([L.COLORTYPE_GRAYSCALE,L.COLORTYPE_COLOR,L.COLORTYPE_COLOR_ALPHA,L.COLORTYPE_ALPHA].indexOf(t.inputColorType)===-1)throw new Error("option input color type:"+t.inputColorType+" is not supported at present");if(t.bitDepth!==8&&t.bitDepth!==16)throw new Error("option bit depth:"+t.bitDepth+" is not supported at present")};he.prototype.getDeflateOptions=function(){return{chunkSize:this._options.deflateChunkSize,level:this._options.deflateLevel,strategy:this._options.deflateStrategy}};he.prototype.createDeflate=function(){return this._options.deflateFactory(this.getDeflateOptions())};he.prototype.filterData=function(t,e,r){let n=Sf(t,e,r,this._options),s=L.COLORTYPE_TO_BPP_MAP[this._options.colorType];return xf(n,e,r,this._options,s)};he.prototype._packChunk=function(t,e){let r=e?e.length:0,n=Buffer.alloc(r+12);return n.writeUInt32BE(r,0),n.writeUInt32BE(t,4),e&&e.copy(n,8),n.writeInt32BE(Ef.crc32(n.slice(4,n.length-4)),n.length-4),n};he.prototype.packGAMA=function(t){let e=Buffer.alloc(4);return e.writeUInt32BE(Math.floor(t*L.GAMMA_DIVISION),0),this._packChunk(L.TYPE_gAMA,e)};he.prototype.packIHDR=function(t,e){let r=Buffer.alloc(13);return r.writeUInt32BE(t,0),r.writeUInt32BE(e,4),r[8]=this._options.bitDepth,r[9]=this._options.colorType,r[10]=0,r[11]=0,r[12]=0,this._packChunk(L.TYPE_IHDR,r)};he.prototype.packIDAT=function(t){return this._packChunk(L.TYPE_IDAT,t)};he.prototype.packIEND=function(){return this._packChunk(L.TYPE_IEND,null)}});var Gi=g((Lp,$i)=>{"use strict";var Tf=w("util"),zi=w("stream"),vf=qe(),kf=fn(),Wi=$i.exports=function(t){zi.call(this);let e=t||{};this._packer=new kf(e),this._deflate=this._packer.createDeflate(),this.readable=!0};Tf.inherits(Wi,zi);Wi.prototype.pack=function(t,e,r,n){this.emit("data",Buffer.from(vf.PNG_SIGNATURE)),this.emit("data",this._packer.packIHDR(e,r)),n&&this.emit("data",this._packer.packGAMA(n));let s=this._packer.filterData(t,e,r);this._deflate.on("error",this.emit.bind(this,"error")),this._deflate.on("data",function(i){this.emit("data",this._packer.packIDAT(i))}.bind(this)),this._deflate.on("end",function(){this.emit("data",this._packer.packIEND()),this.emit("end")}.bind(this)),this._deflate.end(s)}});var Zi=g((ft,Ji)=>{"use strict";var ji=w("assert").ok,Fe=w("zlib"),If=w("util"),Yi=w("buffer").kMaxLength;function be(t){if(!(this instanceof be))return new be(t);t&&t.chunkSize<Fe.Z_MIN_CHUNK&&(t.chunkSize=Fe.Z_MIN_CHUNK),Fe.Inflate.call(this,t),this._offset=this._offset===void 0?this._outOffset:this._offset,this._buffer=this._buffer||this._outBuffer,t&&t.maxLength!=null&&(this._maxLength=t.maxLength)}function Af(t){return new be(t)}function Vi(t,e){e&&process.nextTick(e),t._handle&&(t._handle.close(),t._handle=null)}be.prototype._processChunk=function(t,e,r){if(typeof r=="function")return Fe.Inflate._processChunk.call(this,t,e,r);let n=this,s=t&&t.length,i=this._chunkSize-this._offset,o=this._maxLength,a=0,l=[],c=0,f;this.on("error",function(m){f=m});function u(m,p){if(n._hadError)return;let _=i-p;if(ji(_>=0,"have should not go down"),_>0){let y=n._buffer.slice(n._offset,n._offset+_);if(n._offset+=_,y.length>o&&(y=y.slice(0,o)),l.push(y),c+=y.length,o-=y.length,o===0)return!1}return(p===0||n._offset>=n._chunkSize)&&(i=n._chunkSize,n._offset=0,n._buffer=Buffer.allocUnsafe(n._chunkSize)),p===0?(a+=s-m,s=m,!0):!1}ji(this._handle,"zlib binding closed");let h;do h=this._handle.writeSync(e,t,a,s,this._buffer,this._offset,i),h=h||this._writeState;while(!this._hadError&&u(h[0],h[1]));if(this._hadError)throw f;if(c>=Yi)throw Vi(this),new RangeError("Cannot create final Buffer. It would be larger than 0x"+Yi.toString(16)+" bytes");let d=Buffer.concat(l,c);return Vi(this),d};If.inherits(be,Fe.Inflate);function Pf(t,e){if(typeof e=="string"&&(e=Buffer.from(e)),!(e instanceof Buffer))throw new TypeError("Not a string or buffer");let r=t._finishFlushFlag;return r==null&&(r=Fe.Z_FINISH),t._processChunk(e,r)}function Ki(t,e){return Pf(new be(e),t)}Ji.exports=ft=Ki;ft.Inflate=be;ft.createInflate=Af;ft.inflateSync=Ki});var un=g((Op,Qi)=>{"use strict";var Xi=Qi.exports=function(t){this._buffer=t,this._reads=[]};Xi.prototype.read=function(t,e){this._reads.push({length:Math.abs(t),allowLess:t<0,func:e})};Xi.prototype.process=function(){for(;this._reads.length>0&&this._buffer.length;){let t=this._reads[0];if(this._buffer.length&&(this._buffer.length>=t.length||t.allowLess)){this._reads.shift();let e=this._buffer;this._buffer=e.slice(t.length),t.func.call(this,e.slice(0,t.length))}else break}if(this._reads.length>0)return new Error("There are some read requests waitng on finished stream");if(this._buffer.length>0)return new Error("unrecognised content at end of stream")}});var to=g(eo=>{"use strict";var Bf=un(),Lf=tn();eo.process=function(t,e){let r=[],n=new Bf(t);return new Lf(e,{read:n.read.bind(n),write:function(i){r.push(i)},complete:function(){}}).start(),n.process(),Buffer.concat(r)}});var io=g((Np,so)=>{"use strict";var ro=!0,no=w("zlib"),Of=Zi();no.deflateSync||(ro=!1);var Rf=un(),Nf=to(),Mf=on(),Uf=an(),Df=ln();so.exports=function(t,e){if(!ro)throw new Error("To use the sync capability of this library in old node versions, please pin pngjs to v2.3.0");let r;function n(x){r=x}let s;function i(x){s=x}function o(x){s.transColor=x}function a(x){s.palette=x}function l(){s.alpha=!0}let c;function f(x){c=x}let u=[];function h(x){u.push(x)}let d=new Rf(t);if(new Mf(e,{read:d.read.bind(d),error:n,metadata:i,gamma:f,palette:a,transColor:o,inflateData:h,simpleTransparency:l}).start(),d.process(),r)throw r;let p=Buffer.concat(u);u.length=0;let _;if(s.interlace)_=no.inflateSync(p);else{let T=((s.width*s.bpp*s.depth+7>>3)+1)*s.height;_=Of(p,{chunkSize:T,maxLength:T})}if(p=null,!_||!_.length)throw new Error("bad png - invalid inflate data response");let y=Nf.process(_,s);p=null;let B=Uf.dataToBitMap(y,s);y=null;let O=Df(B,s);return s.data=O,s.gamma=c||0,s}});var co=g((Mp,lo)=>{"use strict";var oo=!0,ao=w("zlib");ao.deflateSync||(oo=!1);var qf=qe(),Ff=fn();lo.exports=function(t,e){if(!oo)throw new Error("To use the sync capability of this library in old node versions, please pin pngjs to v2.3.0");let r=e||{},n=new Ff(r),s=[];s.push(Buffer.from(qf.PNG_SIGNATURE)),s.push(n.packIHDR(t.width,t.height)),t.gamma&&s.push(n.packGAMA(t.gamma));let i=n.filterData(t.data,t.width,t.height),o=ao.deflateSync(i,n.getDeflateOptions());if(i=null,!o||!o.length)throw new Error("bad png - invalid compressed data response");return s.push(n.packIDAT(o)),s.push(n.packIEND()),Buffer.concat(s)}});var fo=g(hn=>{"use strict";var Hf=io(),zf=co();hn.read=function(t,e){return Hf(t,e||{})};hn.write=function(t,e){return zf(t,e)}});var po=g(ho=>{"use strict";var Wf=w("util"),uo=w("stream"),$f=Ni(),Gf=Gi(),jf=fo(),R=ho.PNG=function(t){uo.call(this),t=t||{},this.width=t.width|0,this.height=t.height|0,this.data=this.width>0&&this.height>0?Buffer.alloc(4*this.width*this.height):null,t.fill&&this.data&&this.data.fill(0),this.gamma=0,this.readable=this.writable=!0,this._parser=new $f(t),this._parser.on("error",this.emit.bind(this,"error")),this._parser.on("close",this._handleClose.bind(this)),this._parser.on("metadata",this._metadata.bind(this)),this._parser.on("gamma",this._gamma.bind(this)),this._parser.on("parsed",function(e){this.data=e,this.emit("parsed",e)}.bind(this)),this._packer=new Gf(t),this._packer.on("data",this.emit.bind(this,"data")),this._packer.on("end",this.emit.bind(this,"end")),this._parser.on("close",this._handleClose.bind(this)),this._packer.on("error",this.emit.bind(this,"error"))};Wf.inherits(R,uo);R.sync=jf;R.prototype.pack=function(){return!this.data||!this.data.length?(this.emit("error","No data provided"),this):(process.nextTick(function(){this._packer.pack(this.data,this.width,this.height,this.gamma)}.bind(this)),this)};R.prototype.parse=function(t,e){if(e){let r,n;r=function(s){this.removeListener("error",n),this.data=s,e(null,this)}.bind(this),n=function(s){this.removeListener("parsed",r),e(s,null)}.bind(this),this.once("parsed",r),this.once("error",n)}return this.end(t),this};R.prototype.write=function(t){return this._parser.write(t),!0};R.prototype.end=function(t){this._parser.end(t)};R.prototype._metadata=function(t){this.width=t.width,this.height=t.height,this.emit("metadata",t)};R.prototype._gamma=function(t){this.gamma=t};R.prototype._handleClose=function(){!this._parser.writable&&!this._packer.readable&&this.emit("close")};R.bitblt=function(t,e,r,n,s,i,o,a){if(r|=0,n|=0,s|=0,i|=0,o|=0,a|=0,r>t.width||n>t.height||r+s>t.width||n+i>t.height)throw new Error("bitblt reading outside image");if(o>e.width||a>e.height||o+s>e.width||a+i>e.height)throw new Error("bitblt writing outside image");for(let l=0;l<i;l++)t.data.copy(e.data,(a+l)*e.width+o<<2,(n+l)*t.width+r<<2,(n+l)*t.width+r+s<<2)};R.prototype.bitblt=function(t,e,r,n,s,i,o){return R.bitblt(this,t,e,r,n,s,i,o),this};R.adjustGamma=function(t){if(t.gamma){for(let e=0;e<t.height;e++)for(let r=0;r<t.width;r++){let n=t.width*e+r<<2;for(let s=0;s<3;s++){let i=t.data[n+s]/255;i=Math.pow(i,1/2.2/t.gamma),t.data[n+s]=Math.round(i*255)}}t.gamma=0}};R.prototype.adjustGamma=function(){R.adjustGamma(this)}});var ut=g(Ee=>{function go(t){if(typeof t=="number"&&(t=t.toString()),typeof t!="string")throw new Error("Color should be defined as hex string");let e=t.slice().replace("#","").split("");if(e.length<3||e.length===5||e.length>8)throw new Error("Invalid hex color: "+t);(e.length===3||e.length===4)&&(e=Array.prototype.concat.apply([],e.map(function(n){return[n,n]}))),e.length===6&&e.push("F","F");let r=parseInt(e.join(""),16);return{r:r>>24&255,g:r>>16&255,b:r>>8&255,a:r&255,hex:"#"+e.slice(0,6).join("")}}Ee.getOptions=function(e){e||(e={}),e.color||(e.color={});let r=typeof e.margin>"u"||e.margin===null||e.margin<0?4:e.margin,n=e.width&&e.width>=21?e.width:void 0,s=e.scale||4;return{width:n,scale:n?4:s,margin:r,color:{dark:go(e.color.dark||"#000000ff"),light:go(e.color.light||"#ffffffff")},type:e.type,rendererOpts:e.rendererOpts||{}}};Ee.getScale=function(e,r){return r.width&&r.width>=e+r.margin*2?r.width/(e+r.margin*2):r.scale};Ee.getImageWidth=function(e,r){let n=Ee.getScale(e,r);return Math.floor((e+r.margin*2)*n)};Ee.qrToImageData=function(e,r,n){let s=r.modules.size,i=r.modules.data,o=Ee.getScale(s,n),a=Math.floor((s+n.margin*2)*o),l=n.margin*o,c=[n.color.light,n.color.dark];for(let f=0;f<a;f++)for(let u=0;u<a;u++){let h=(f*a+u)*4,d=n.color.light;if(f>=l&&u>=l&&f<a-l&&u<a-l){let m=Math.floor((f-l)/o),p=Math.floor((u-l)/o);d=c[i[m*s+p]?1:0]}e[h++]=d.r,e[h++]=d.g,e[h++]=d.b,e[h]=d.a}}});var mo=g(K=>{var Yf=w("fs"),Vf=po().PNG,dn=ut();K.render=function(e,r){let n=dn.getOptions(r),s=n.rendererOpts,i=dn.getImageWidth(e.modules.size,n);s.width=i,s.height=i;let o=new Vf(s);return dn.qrToImageData(o.data,e,n),o};K.renderToDataURL=function(e,r,n){typeof n>"u"&&(n=r,r=void 0),K.renderToBuffer(e,r,function(s,i){s&&n(s);let o="data:image/png;base64,";o+=i.toString("base64"),n(null,o)})};K.renderToBuffer=function(e,r,n){typeof n>"u"&&(n=r,r=void 0);let s=K.render(e,r),i=[];s.on("error",n),s.on("data",function(o){i.push(o)}),s.on("end",function(){n(null,Buffer.concat(i))}),s.pack()};K.renderToFile=function(e,r,n,s){typeof s>"u"&&(s=n,n=void 0);let i=!1,o=(...l)=>{i||(i=!0,s.apply(null,l))},a=Yf.createWriteStream(e);a.on("error",o),a.on("close",o),K.renderToFileStream(a,r,n)};K.renderToFileStream=function(e,r,n){K.render(r,n).pack().pipe(e)}});var _o=g(Zt=>{var Kf=ut(),Jf={WW:" ",WB:"\u2584",BB:"\u2588",BW:"\u2580"},Zf={BB:" ",BW:"\u2584",WW:"\u2588",WB:"\u2580"};function Xf(t,e,r){return t&&e?r.BB:t&&!e?r.BW:!t&&e?r.WB:r.WW}Zt.render=function(t,e,r){let n=Kf.getOptions(e),s=Jf;(n.color.dark.hex==="#ffffff"||n.color.light.hex==="#000000")&&(s=Zf);let i=t.modules.size,o=t.modules.data,a="",l=Array(i+n.margin*2+1).join(s.WW);l=Array(n.margin/2+1).join(l+`
|
|
9
|
-
`);let c=Array(n.margin+1).join(
|
|
10
|
-
`}return a+=l.slice(0,-1),typeof r=="function"&&r(null,a),a};
|
|
11
|
-
`;for(let
|
|
7
|
+
Minimum version required to store current data is: `+s+`.
|
|
8
|
+
`);let o=Zc(e,r,i),a=er.getSymbolSize(e),l=new Fc(a);return Vc(l,e),jc(l),Yc(l,e),Qr(l,r,0),e>=7&&Kc(l,e),Jc(l,o),isNaN(n)&&(n=Xr.getBestMask(l,Qr.bind(null,l,r))),Xr.applyMask(n,l),Qr(l,r,n),{modules:l,version:e,errorCorrectionLevel:r,maskPattern:n,segments:i}}xs.create=function(e,r){if(typeof e>"u"||e==="")throw new Error("No input text");let n=Jr.M,i,s;return typeof r<"u"&&(n=Jr.from(r.errorCorrectionLevel,Jr.M),i=Xt.from(r.version),s=Xr.from(r.maskPattern),r.toSJISFunc&&er.setToSJISFunction(r.toSJISFunc)),Xc(e,i,n,s)}});var rn=g(($p,vs)=>{"use strict";var eu=w("util"),Ss=w("stream"),W=vs.exports=function(){Ss.call(this),this._buffers=[],this._buffered=0,this._reads=[],this._paused=!1,this._encoding="utf8",this.writable=!0};eu.inherits(W,Ss);W.prototype.read=function(t,e){this._reads.push({length:Math.abs(t),allowLess:t<0,func:e}),process.nextTick(function(){this._process(),this._paused&&this._reads&&this._reads.length>0&&(this._paused=!1,this.emit("drain"))}.bind(this))};W.prototype.write=function(t,e){if(!this.writable)return this.emit("error",new Error("Stream not writable")),!1;let r;return Buffer.isBuffer(t)?r=t:r=Buffer.from(t,e||this._encoding),this._buffers.push(r),this._buffered+=r.length,this._process(),this._reads&&this._reads.length===0&&(this._paused=!0),this.writable&&!this._paused};W.prototype.end=function(t,e){t&&this.write(t,e),this.writable=!1,this._buffers&&(this._buffers.length===0?this._end():(this._buffers.push(null),this._process()))};W.prototype.destroySoon=W.prototype.end;W.prototype._end=function(){this._reads.length>0&&this.emit("error",new Error("Unexpected end of input")),this.destroy()};W.prototype.destroy=function(){this._buffers&&(this.writable=!1,this._reads=null,this._buffers=null,this.emit("close"))};W.prototype._processReadAllowingLess=function(t){this._reads.shift();let e=this._buffers[0];e.length>t.length?(this._buffered-=t.length,this._buffers[0]=e.slice(t.length),t.func.call(this,e.slice(0,t.length))):(this._buffered-=e.length,this._buffers.shift(),t.func.call(this,e))};W.prototype._processRead=function(t){this._reads.shift();let e=0,r=0,n=Buffer.alloc(t.length);for(;e<t.length;){let i=this._buffers[r++],s=Math.min(i.length,t.length-e);i.copy(n,e,0,s),e+=s,s!==i.length&&(this._buffers[--r]=i.slice(s))}r>0&&this._buffers.splice(0,r),this._buffered-=t.length,t.func.call(this,n)};W.prototype._process=function(){try{for(;this._buffered>0&&this._reads&&this._reads.length>0;){let t=this._reads[0];if(t.allowLess)this._processReadAllowingLess(t);else if(this._buffered>=t.length)this._processRead(t);else break}this._buffers&&!this.writable&&this._end()}catch(t){this.emit("error",t)}}});var sn=g(nn=>{"use strict";var fe=[{x:[0],y:[0]},{x:[4],y:[0]},{x:[0,4],y:[4]},{x:[2,6],y:[0,4]},{x:[0,2,4,6],y:[2,6]},{x:[1,3,5,7],y:[0,2,4,6]},{x:[0,1,2,3,4,5,6,7],y:[1,3,5,7]}];nn.getImagePasses=function(t,e){let r=[],n=t%8,i=e%8,s=(t-n)/8,o=(e-i)/8;for(let a=0;a<fe.length;a++){let l=fe[a],c=s*l.x.length,u=o*l.y.length;for(let f=0;f<l.x.length&&l.x[f]<n;f++)c++;for(let f=0;f<l.y.length&&l.y[f]<i;f++)u++;c>0&&u>0&&r.push({width:c,height:u,index:a})}return r};nn.getInterlaceIterator=function(t){return function(e,r,n){let i=e%fe[n].x.length,s=(e-i)/fe[n].x.length*8+fe[n].x[i],o=r%fe[n].y.length,a=(r-o)/fe[n].y.length*8+fe[n].y[o];return s*4+a*t*4}}});var on=g((Gp,Ts)=>{"use strict";Ts.exports=function(e,r,n){let i=e+r-n,s=Math.abs(i-e),o=Math.abs(i-r),a=Math.abs(i-n);return s<=o&&s<=a?e:o<=a?r:n}});var an=g((Vp,ks)=>{"use strict";var tu=sn(),ru=on();function Cs(t,e,r){let n=t*e;return r!==8&&(n=Math.ceil(n/(8/r))),n}var De=ks.exports=function(t,e){let r=t.width,n=t.height,i=t.interlace,s=t.bpp,o=t.depth;if(this.read=e.read,this.write=e.write,this.complete=e.complete,this._imageIndex=0,this._images=[],i){let a=tu.getImagePasses(r,n);for(let l=0;l<a.length;l++)this._images.push({byteWidth:Cs(a[l].width,s,o),height:a[l].height,lineIndex:0})}else this._images.push({byteWidth:Cs(r,s,o),height:n,lineIndex:0});o===8?this._xComparison=s:o===16?this._xComparison=s*2:this._xComparison=1};De.prototype.start=function(){this.read(this._images[this._imageIndex].byteWidth+1,this._reverseFilterLine.bind(this))};De.prototype._unFilterType1=function(t,e,r){let n=this._xComparison,i=n-1;for(let s=0;s<r;s++){let o=t[1+s],a=s>i?e[s-n]:0;e[s]=o+a}};De.prototype._unFilterType2=function(t,e,r){let n=this._lastLine;for(let i=0;i<r;i++){let s=t[1+i],o=n?n[i]:0;e[i]=s+o}};De.prototype._unFilterType3=function(t,e,r){let n=this._xComparison,i=n-1,s=this._lastLine;for(let o=0;o<r;o++){let a=t[1+o],l=s?s[o]:0,c=o>i?e[o-n]:0,u=Math.floor((c+l)/2);e[o]=a+u}};De.prototype._unFilterType4=function(t,e,r){let n=this._xComparison,i=n-1,s=this._lastLine;for(let o=0;o<r;o++){let a=t[1+o],l=s?s[o]:0,c=o>i?e[o-n]:0,u=o>i&&s?s[o-n]:0,f=ru(c,l,u);e[o]=a+f}};De.prototype._reverseFilterLine=function(t){let e=t[0],r,n=this._images[this._imageIndex],i=n.byteWidth;if(e===0)r=t.slice(1,i+1);else switch(r=Buffer.alloc(i),e){case 1:this._unFilterType1(t,r,i);break;case 2:this._unFilterType2(t,r,i);break;case 3:this._unFilterType3(t,r,i);break;case 4:this._unFilterType4(t,r,i);break;default:throw new Error("Unrecognised filter type - "+e)}this.write(r),n.lineIndex++,n.lineIndex>=n.height?(this._lastLine=null,this._imageIndex++,n=this._images[this._imageIndex]):this._lastLine=r,n?this.read(n.byteWidth+1,this._reverseFilterLine.bind(this)):(this._lastLine=null,this.complete())}});var Ps=g((jp,As)=>{"use strict";var nu=w("util"),Is=rn(),iu=an(),su=As.exports=function(t){Is.call(this);let e=[],r=this;this._filter=new iu(t,{read:this.read.bind(this),write:function(n){e.push(n)},complete:function(){r.emit("complete",Buffer.concat(e))}}),this._filter.start()};nu.inherits(su,Is)});var Fe=g((Yp,Bs)=>{"use strict";Bs.exports={PNG_SIGNATURE:[137,80,78,71,13,10,26,10],TYPE_IHDR:1229472850,TYPE_IEND:1229278788,TYPE_IDAT:1229209940,TYPE_PLTE:1347179589,TYPE_tRNS:1951551059,TYPE_gAMA:1732332865,COLORTYPE_GRAYSCALE:0,COLORTYPE_PALETTE:1,COLORTYPE_COLOR:2,COLORTYPE_ALPHA:4,COLORTYPE_PALETTE_COLOR:3,COLORTYPE_COLOR_ALPHA:6,COLORTYPE_TO_BPP_MAP:{0:1,2:3,3:1,4:2,6:4},GAMMA_DIVISION:1e5}});var un=g((Kp,Ls)=>{"use strict";var ln=[];(function(){for(let t=0;t<256;t++){let e=t;for(let r=0;r<8;r++)e&1?e=3988292384^e>>>1:e=e>>>1;ln[t]=e}})();var cn=Ls.exports=function(){this._crc=-1};cn.prototype.write=function(t){for(let e=0;e<t.length;e++)this._crc=ln[(this._crc^t[e])&255]^this._crc>>>8;return!0};cn.prototype.crc32=function(){return this._crc^-1};cn.crc32=function(t){let e=-1;for(let r=0;r<t.length;r++)e=ln[(e^t[r])&255]^e>>>8;return e^-1}});var fn=g((Jp,Os)=>{"use strict";var k=Fe(),ou=un(),I=Os.exports=function(t,e){this._options=t,t.checkCRC=t.checkCRC!==!1,this._hasIHDR=!1,this._hasIEND=!1,this._emittedHeadersFinished=!1,this._palette=[],this._colorType=0,this._chunks={},this._chunks[k.TYPE_IHDR]=this._handleIHDR.bind(this),this._chunks[k.TYPE_IEND]=this._handleIEND.bind(this),this._chunks[k.TYPE_IDAT]=this._handleIDAT.bind(this),this._chunks[k.TYPE_PLTE]=this._handlePLTE.bind(this),this._chunks[k.TYPE_tRNS]=this._handleTRNS.bind(this),this._chunks[k.TYPE_gAMA]=this._handleGAMA.bind(this),this.read=e.read,this.error=e.error,this.metadata=e.metadata,this.gamma=e.gamma,this.transColor=e.transColor,this.palette=e.palette,this.parsed=e.parsed,this.inflateData=e.inflateData,this.finished=e.finished,this.simpleTransparency=e.simpleTransparency,this.headersFinished=e.headersFinished||function(){}};I.prototype.start=function(){this.read(k.PNG_SIGNATURE.length,this._parseSignature.bind(this))};I.prototype._parseSignature=function(t){let e=k.PNG_SIGNATURE;for(let r=0;r<e.length;r++)if(t[r]!==e[r]){this.error(new Error("Invalid file signature"));return}this.read(8,this._parseChunkBegin.bind(this))};I.prototype._parseChunkBegin=function(t){let e=t.readUInt32BE(0),r=t.readUInt32BE(4),n="";for(let s=4;s<8;s++)n+=String.fromCharCode(t[s]);let i=!!(t[4]&32);if(!this._hasIHDR&&r!==k.TYPE_IHDR){this.error(new Error("Expected IHDR on beggining"));return}if(this._crc=new ou,this._crc.write(Buffer.from(n)),this._chunks[r])return this._chunks[r](e);if(!i){this.error(new Error("Unsupported critical chunk type "+n));return}this.read(e+4,this._skipChunk.bind(this))};I.prototype._skipChunk=function(){this.read(8,this._parseChunkBegin.bind(this))};I.prototype._handleChunkEnd=function(){this.read(4,this._parseChunkEnd.bind(this))};I.prototype._parseChunkEnd=function(t){let e=t.readInt32BE(0),r=this._crc.crc32();if(this._options.checkCRC&&r!==e){this.error(new Error("Crc error - "+e+" - "+r));return}this._hasIEND||this.read(8,this._parseChunkBegin.bind(this))};I.prototype._handleIHDR=function(t){this.read(t,this._parseIHDR.bind(this))};I.prototype._parseIHDR=function(t){this._crc.write(t);let e=t.readUInt32BE(0),r=t.readUInt32BE(4),n=t[8],i=t[9],s=t[10],o=t[11],a=t[12];if(n!==8&&n!==4&&n!==2&&n!==1&&n!==16){this.error(new Error("Unsupported bit depth "+n));return}if(!(i in k.COLORTYPE_TO_BPP_MAP)){this.error(new Error("Unsupported color type"));return}if(s!==0){this.error(new Error("Unsupported compression method"));return}if(o!==0){this.error(new Error("Unsupported filter method"));return}if(a!==0&&a!==1){this.error(new Error("Unsupported interlace method"));return}this._colorType=i;let l=k.COLORTYPE_TO_BPP_MAP[this._colorType];this._hasIHDR=!0,this.metadata({width:e,height:r,depth:n,interlace:!!a,palette:!!(i&k.COLORTYPE_PALETTE),color:!!(i&k.COLORTYPE_COLOR),alpha:!!(i&k.COLORTYPE_ALPHA),bpp:l,colorType:i}),this._handleChunkEnd()};I.prototype._handlePLTE=function(t){this.read(t,this._parsePLTE.bind(this))};I.prototype._parsePLTE=function(t){this._crc.write(t);let e=Math.floor(t.length/3);for(let r=0;r<e;r++)this._palette.push([t[r*3],t[r*3+1],t[r*3+2],255]);this.palette(this._palette),this._handleChunkEnd()};I.prototype._handleTRNS=function(t){this.simpleTransparency(),this.read(t,this._parseTRNS.bind(this))};I.prototype._parseTRNS=function(t){if(this._crc.write(t),this._colorType===k.COLORTYPE_PALETTE_COLOR){if(this._palette.length===0){this.error(new Error("Transparency chunk must be after palette"));return}if(t.length>this._palette.length){this.error(new Error("More transparent colors than palette size"));return}for(let e=0;e<t.length;e++)this._palette[e][3]=t[e];this.palette(this._palette)}this._colorType===k.COLORTYPE_GRAYSCALE&&this.transColor([t.readUInt16BE(0)]),this._colorType===k.COLORTYPE_COLOR&&this.transColor([t.readUInt16BE(0),t.readUInt16BE(2),t.readUInt16BE(4)]),this._handleChunkEnd()};I.prototype._handleGAMA=function(t){this.read(t,this._parseGAMA.bind(this))};I.prototype._parseGAMA=function(t){this._crc.write(t),this.gamma(t.readUInt32BE(0)/k.GAMMA_DIVISION),this._handleChunkEnd()};I.prototype._handleIDAT=function(t){this._emittedHeadersFinished||(this._emittedHeadersFinished=!0,this.headersFinished()),this.read(-t,this._parseIDAT.bind(this,t))};I.prototype._parseIDAT=function(t,e){if(this._crc.write(e),this._colorType===k.COLORTYPE_PALETTE_COLOR&&this._palette.length===0)throw new Error("Expected palette not found");this.inflateData(e);let r=t-e.length;r>0?this._handleIDAT(r):this._handleChunkEnd()};I.prototype._handleIEND=function(t){this.read(t,this._parseIEND.bind(this))};I.prototype._parseIEND=function(t){this._crc.write(t),this._hasIEND=!0,this._handleChunkEnd(),this.finished&&this.finished()}});var hn=g(Ns=>{"use strict";var Rs=sn(),au=[function(){},function(t,e,r,n){if(n===e.length)throw new Error("Ran out of data");let i=e[n];t[r]=i,t[r+1]=i,t[r+2]=i,t[r+3]=255},function(t,e,r,n){if(n+1>=e.length)throw new Error("Ran out of data");let i=e[n];t[r]=i,t[r+1]=i,t[r+2]=i,t[r+3]=e[n+1]},function(t,e,r,n){if(n+2>=e.length)throw new Error("Ran out of data");t[r]=e[n],t[r+1]=e[n+1],t[r+2]=e[n+2],t[r+3]=255},function(t,e,r,n){if(n+3>=e.length)throw new Error("Ran out of data");t[r]=e[n],t[r+1]=e[n+1],t[r+2]=e[n+2],t[r+3]=e[n+3]}],lu=[function(){},function(t,e,r,n){let i=e[0];t[r]=i,t[r+1]=i,t[r+2]=i,t[r+3]=n},function(t,e,r){let n=e[0];t[r]=n,t[r+1]=n,t[r+2]=n,t[r+3]=e[1]},function(t,e,r,n){t[r]=e[0],t[r+1]=e[1],t[r+2]=e[2],t[r+3]=n},function(t,e,r){t[r]=e[0],t[r+1]=e[1],t[r+2]=e[2],t[r+3]=e[3]}];function cu(t,e){let r=[],n=0;function i(){if(n===t.length)throw new Error("Ran out of data");let s=t[n];n++;let o,a,l,c,u,f,h,d;switch(e){default:throw new Error("unrecognised depth");case 16:h=t[n],n++,r.push((s<<8)+h);break;case 4:h=s&15,d=s>>4,r.push(d,h);break;case 2:u=s&3,f=s>>2&3,h=s>>4&3,d=s>>6&3,r.push(d,h,f,u);break;case 1:o=s&1,a=s>>1&1,l=s>>2&1,c=s>>3&1,u=s>>4&1,f=s>>5&1,h=s>>6&1,d=s>>7&1,r.push(d,h,f,u,c,l,a,o);break}}return{get:function(s){for(;r.length<s;)i();let o=r.slice(0,s);return r=r.slice(s),o},resetAfterLine:function(){r.length=0},end:function(){if(n!==t.length)throw new Error("extra data found")}}}function uu(t,e,r,n,i,s){let o=t.width,a=t.height,l=t.index;for(let c=0;c<a;c++)for(let u=0;u<o;u++){let f=r(u,c,l);au[n](e,i,f,s),s+=n}return s}function fu(t,e,r,n,i,s){let o=t.width,a=t.height,l=t.index;for(let c=0;c<a;c++){for(let u=0;u<o;u++){let f=i.get(n),h=r(u,c,l);lu[n](e,f,h,s)}i.resetAfterLine()}}Ns.dataToBitMap=function(t,e){let r=e.width,n=e.height,i=e.depth,s=e.bpp,o=e.interlace,a;i!==8&&(a=cu(t,i));let l;i<=8?l=Buffer.alloc(r*n*4):l=new Uint16Array(r*n*4);let c=Math.pow(2,i)-1,u=0,f,h;if(o)f=Rs.getImagePasses(r,n),h=Rs.getInterlaceIterator(r,n);else{let d=0;h=function(){let m=d;return d+=4,m},f=[{width:r,height:n}]}for(let d=0;d<f.length;d++)i===8?u=uu(f[d],l,h,s,t,u):fu(f[d],l,h,s,a,c);if(i===8){if(u!==t.length)throw new Error("extra data found")}else a.end();return l}});var dn=g((Qp,Ms)=>{"use strict";function hu(t,e,r,n,i){let s=0;for(let o=0;o<n;o++)for(let a=0;a<r;a++){let l=i[t[s]];if(!l)throw new Error("index "+t[s]+" not in palette");for(let c=0;c<4;c++)e[s+c]=l[c];s+=4}}function du(t,e,r,n,i){let s=0;for(let o=0;o<n;o++)for(let a=0;a<r;a++){let l=!1;if(i.length===1?i[0]===t[s]&&(l=!0):i[0]===t[s]&&i[1]===t[s+1]&&i[2]===t[s+2]&&(l=!0),l)for(let c=0;c<4;c++)e[s+c]=0;s+=4}}function pu(t,e,r,n,i){let s=255,o=Math.pow(2,i)-1,a=0;for(let l=0;l<n;l++)for(let c=0;c<r;c++){for(let u=0;u<4;u++)e[a+u]=Math.floor(t[a+u]*s/o+.5);a+=4}}Ms.exports=function(t,e){let r=e.depth,n=e.width,i=e.height,s=e.colorType,o=e.transColor,a=e.palette,l=t;return s===3?hu(t,l,n,i,a):(o&&du(t,l,n,i,o),r!==8&&(r===16&&(l=Buffer.alloc(n*i*4)),pu(t,l,n,i,r))),l}});var Ds=g((Xp,qs)=>{"use strict";var gu=w("util"),pn=w("zlib"),Us=rn(),mu=Ps(),yu=fn(),_u=hn(),wu=dn(),J=qs.exports=function(t){Us.call(this),this._parser=new yu(t,{read:this.read.bind(this),error:this._handleError.bind(this),metadata:this._handleMetaData.bind(this),gamma:this.emit.bind(this,"gamma"),palette:this._handlePalette.bind(this),transColor:this._handleTransColor.bind(this),finished:this._finished.bind(this),inflateData:this._inflateData.bind(this),simpleTransparency:this._simpleTransparency.bind(this),headersFinished:this._headersFinished.bind(this)}),this._options=t,this.writable=!0,this._parser.start()};gu.inherits(J,Us);J.prototype._handleError=function(t){this.emit("error",t),this.writable=!1,this.destroy(),this._inflate&&this._inflate.destroy&&this._inflate.destroy(),this._filter&&(this._filter.destroy(),this._filter.on("error",function(){})),this.errord=!0};J.prototype._inflateData=function(t){if(!this._inflate)if(this._bitmapInfo.interlace)this._inflate=pn.createInflate(),this._inflate.on("error",this.emit.bind(this,"error")),this._filter.on("complete",this._complete.bind(this)),this._inflate.pipe(this._filter);else{let r=((this._bitmapInfo.width*this._bitmapInfo.bpp*this._bitmapInfo.depth+7>>3)+1)*this._bitmapInfo.height,n=Math.max(r,pn.Z_MIN_CHUNK);this._inflate=pn.createInflate({chunkSize:n});let i=r,s=this.emit.bind(this,"error");this._inflate.on("error",function(a){i&&s(a)}),this._filter.on("complete",this._complete.bind(this));let o=this._filter.write.bind(this._filter);this._inflate.on("data",function(a){i&&(a.length>i&&(a=a.slice(0,i)),i-=a.length,o(a))}),this._inflate.on("end",this._filter.end.bind(this._filter))}this._inflate.write(t)};J.prototype._handleMetaData=function(t){this._metaData=t,this._bitmapInfo=Object.create(t),this._filter=new mu(this._bitmapInfo)};J.prototype._handleTransColor=function(t){this._bitmapInfo.transColor=t};J.prototype._handlePalette=function(t){this._bitmapInfo.palette=t};J.prototype._simpleTransparency=function(){this._metaData.alpha=!0};J.prototype._headersFinished=function(){this.emit("metadata",this._metaData)};J.prototype._finished=function(){this.errord||(this._inflate?this._inflate.end():this.emit("error","No Inflate block"))};J.prototype._complete=function(t){if(this.errord)return;let e;try{let r=_u.dataToBitMap(t,this._bitmapInfo);e=wu(r,this._bitmapInfo),r=null}catch(r){this._handleError(r);return}this.emit("parsed",e)}});var Hs=g((eg,Fs)=>{"use strict";var H=Fe();Fs.exports=function(t,e,r,n){let i=[H.COLORTYPE_COLOR_ALPHA,H.COLORTYPE_ALPHA].indexOf(n.colorType)!==-1;if(n.colorType===n.inputColorType){let m=(function(){let p=new ArrayBuffer(2);return new DataView(p).setInt16(0,256,!0),new Int16Array(p)[0]!==256})();if(n.bitDepth===8||n.bitDepth===16&&m)return t}let s=n.bitDepth!==16?t:new Uint16Array(t.buffer),o=255,a=H.COLORTYPE_TO_BPP_MAP[n.inputColorType];a===4&&!n.inputHasAlpha&&(a=3);let l=H.COLORTYPE_TO_BPP_MAP[n.colorType];n.bitDepth===16&&(o=65535,l*=2);let c=Buffer.alloc(e*r*l),u=0,f=0,h=n.bgColor||{};h.red===void 0&&(h.red=o),h.green===void 0&&(h.green=o),h.blue===void 0&&(h.blue=o);function d(){let m,p,y,_=o;switch(n.inputColorType){case H.COLORTYPE_COLOR_ALPHA:_=s[u+3],m=s[u],p=s[u+1],y=s[u+2];break;case H.COLORTYPE_COLOR:m=s[u],p=s[u+1],y=s[u+2];break;case H.COLORTYPE_ALPHA:_=s[u+1],m=s[u],p=m,y=m;break;case H.COLORTYPE_GRAYSCALE:m=s[u],p=m,y=m;break;default:throw new Error("input color type:"+n.inputColorType+" is not supported at present")}return n.inputHasAlpha&&(i||(_/=o,m=Math.min(Math.max(Math.round((1-_)*h.red+_*m),0),o),p=Math.min(Math.max(Math.round((1-_)*h.green+_*p),0),o),y=Math.min(Math.max(Math.round((1-_)*h.blue+_*y),0),o))),{red:m,green:p,blue:y,alpha:_}}for(let m=0;m<r;m++)for(let p=0;p<e;p++){let y=d(s,u);switch(n.colorType){case H.COLORTYPE_COLOR_ALPHA:case H.COLORTYPE_COLOR:n.bitDepth===8?(c[f]=y.red,c[f+1]=y.green,c[f+2]=y.blue,i&&(c[f+3]=y.alpha)):(c.writeUInt16BE(y.red,f),c.writeUInt16BE(y.green,f+2),c.writeUInt16BE(y.blue,f+4),i&&c.writeUInt16BE(y.alpha,f+6));break;case H.COLORTYPE_ALPHA:case H.COLORTYPE_GRAYSCALE:{let _=(y.red+y.green+y.blue)/3;n.bitDepth===8?(c[f]=_,i&&(c[f+1]=y.alpha)):(c.writeUInt16BE(_,f),i&&c.writeUInt16BE(y.alpha,f+2));break}default:throw new Error("unrecognised color Type "+n.colorType)}u+=a,f+=l}return c}});var Ws=g((tg,$s)=>{"use strict";var zs=on();function bu(t,e,r,n,i){for(let s=0;s<r;s++)n[i+s]=t[e+s]}function Eu(t,e,r){let n=0,i=e+r;for(let s=e;s<i;s++)n+=Math.abs(t[s]);return n}function xu(t,e,r,n,i,s){for(let o=0;o<r;o++){let a=o>=s?t[e+o-s]:0,l=t[e+o]-a;n[i+o]=l}}function Su(t,e,r,n){let i=0;for(let s=0;s<r;s++){let o=s>=n?t[e+s-n]:0,a=t[e+s]-o;i+=Math.abs(a)}return i}function vu(t,e,r,n,i){for(let s=0;s<r;s++){let o=e>0?t[e+s-r]:0,a=t[e+s]-o;n[i+s]=a}}function Tu(t,e,r){let n=0,i=e+r;for(let s=e;s<i;s++){let o=e>0?t[s-r]:0,a=t[s]-o;n+=Math.abs(a)}return n}function Cu(t,e,r,n,i,s){for(let o=0;o<r;o++){let a=o>=s?t[e+o-s]:0,l=e>0?t[e+o-r]:0,c=t[e+o]-(a+l>>1);n[i+o]=c}}function ku(t,e,r,n){let i=0;for(let s=0;s<r;s++){let o=s>=n?t[e+s-n]:0,a=e>0?t[e+s-r]:0,l=t[e+s]-(o+a>>1);i+=Math.abs(l)}return i}function Iu(t,e,r,n,i,s){for(let o=0;o<r;o++){let a=o>=s?t[e+o-s]:0,l=e>0?t[e+o-r]:0,c=e>0&&o>=s?t[e+o-(r+s)]:0,u=t[e+o]-zs(a,l,c);n[i+o]=u}}function Au(t,e,r,n){let i=0;for(let s=0;s<r;s++){let o=s>=n?t[e+s-n]:0,a=e>0?t[e+s-r]:0,l=e>0&&s>=n?t[e+s-(r+n)]:0,c=t[e+s]-zs(o,a,l);i+=Math.abs(c)}return i}var Pu={0:bu,1:xu,2:vu,3:Cu,4:Iu},Bu={0:Eu,1:Su,2:Tu,3:ku,4:Au};$s.exports=function(t,e,r,n,i){let s;if(!("filterType"in n)||n.filterType===-1)s=[0,1,2,3,4];else if(typeof n.filterType=="number")s=[n.filterType];else throw new Error("unrecognised filter types");n.bitDepth===16&&(i*=2);let o=e*i,a=0,l=0,c=Buffer.alloc((o+1)*r),u=s[0];for(let f=0;f<r;f++){if(s.length>1){let h=1/0;for(let d=0;d<s.length;d++){let m=Bu[s[d]](t,l,o,i);m<h&&(u=s[d],h=m)}}c[a]=u,a++,Pu[u](t,l,o,c,a,i),a+=o,l+=o}return c}});var gn=g((rg,Gs)=>{"use strict";var L=Fe(),Lu=un(),Ou=Hs(),Ru=Ws(),Nu=w("zlib"),he=Gs.exports=function(t){if(this._options=t,t.deflateChunkSize=t.deflateChunkSize||32*1024,t.deflateLevel=t.deflateLevel!=null?t.deflateLevel:9,t.deflateStrategy=t.deflateStrategy!=null?t.deflateStrategy:3,t.inputHasAlpha=t.inputHasAlpha!=null?t.inputHasAlpha:!0,t.deflateFactory=t.deflateFactory||Nu.createDeflate,t.bitDepth=t.bitDepth||8,t.colorType=typeof t.colorType=="number"?t.colorType:L.COLORTYPE_COLOR_ALPHA,t.inputColorType=typeof t.inputColorType=="number"?t.inputColorType:L.COLORTYPE_COLOR_ALPHA,[L.COLORTYPE_GRAYSCALE,L.COLORTYPE_COLOR,L.COLORTYPE_COLOR_ALPHA,L.COLORTYPE_ALPHA].indexOf(t.colorType)===-1)throw new Error("option color type:"+t.colorType+" is not supported at present");if([L.COLORTYPE_GRAYSCALE,L.COLORTYPE_COLOR,L.COLORTYPE_COLOR_ALPHA,L.COLORTYPE_ALPHA].indexOf(t.inputColorType)===-1)throw new Error("option input color type:"+t.inputColorType+" is not supported at present");if(t.bitDepth!==8&&t.bitDepth!==16)throw new Error("option bit depth:"+t.bitDepth+" is not supported at present")};he.prototype.getDeflateOptions=function(){return{chunkSize:this._options.deflateChunkSize,level:this._options.deflateLevel,strategy:this._options.deflateStrategy}};he.prototype.createDeflate=function(){return this._options.deflateFactory(this.getDeflateOptions())};he.prototype.filterData=function(t,e,r){let n=Ou(t,e,r,this._options),i=L.COLORTYPE_TO_BPP_MAP[this._options.colorType];return Ru(n,e,r,this._options,i)};he.prototype._packChunk=function(t,e){let r=e?e.length:0,n=Buffer.alloc(r+12);return n.writeUInt32BE(r,0),n.writeUInt32BE(t,4),e&&e.copy(n,8),n.writeInt32BE(Lu.crc32(n.slice(4,n.length-4)),n.length-4),n};he.prototype.packGAMA=function(t){let e=Buffer.alloc(4);return e.writeUInt32BE(Math.floor(t*L.GAMMA_DIVISION),0),this._packChunk(L.TYPE_gAMA,e)};he.prototype.packIHDR=function(t,e){let r=Buffer.alloc(13);return r.writeUInt32BE(t,0),r.writeUInt32BE(e,4),r[8]=this._options.bitDepth,r[9]=this._options.colorType,r[10]=0,r[11]=0,r[12]=0,this._packChunk(L.TYPE_IHDR,r)};he.prototype.packIDAT=function(t){return this._packChunk(L.TYPE_IDAT,t)};he.prototype.packIEND=function(){return this._packChunk(L.TYPE_IEND,null)}});var Ks=g((ng,Ys)=>{"use strict";var Mu=w("util"),Vs=w("stream"),Uu=Fe(),qu=gn(),js=Ys.exports=function(t){Vs.call(this);let e=t||{};this._packer=new qu(e),this._deflate=this._packer.createDeflate(),this.readable=!0};Mu.inherits(js,Vs);js.prototype.pack=function(t,e,r,n){this.emit("data",Buffer.from(Uu.PNG_SIGNATURE)),this.emit("data",this._packer.packIHDR(e,r)),n&&this.emit("data",this._packer.packGAMA(n));let i=this._packer.filterData(t,e,r);this._deflate.on("error",this.emit.bind(this,"error")),this._deflate.on("data",function(s){this.emit("data",this._packer.packIDAT(s))}.bind(this)),this._deflate.on("end",function(){this.emit("data",this._packer.packIEND()),this.emit("end")}.bind(this)),this._deflate.end(i)}});var to=g((dt,eo)=>{"use strict";var Js=w("assert").ok,He=w("zlib"),Du=w("util"),Zs=w("buffer").kMaxLength;function be(t){if(!(this instanceof be))return new be(t);t&&t.chunkSize<He.Z_MIN_CHUNK&&(t.chunkSize=He.Z_MIN_CHUNK),He.Inflate.call(this,t),this._offset=this._offset===void 0?this._outOffset:this._offset,this._buffer=this._buffer||this._outBuffer,t&&t.maxLength!=null&&(this._maxLength=t.maxLength)}function Fu(t){return new be(t)}function Qs(t,e){e&&process.nextTick(e),t._handle&&(t._handle.close(),t._handle=null)}be.prototype._processChunk=function(t,e,r){if(typeof r=="function")return He.Inflate._processChunk.call(this,t,e,r);let n=this,i=t&&t.length,s=this._chunkSize-this._offset,o=this._maxLength,a=0,l=[],c=0,u;this.on("error",function(m){u=m});function f(m,p){if(n._hadError)return;let y=s-p;if(Js(y>=0,"have should not go down"),y>0){let _=n._buffer.slice(n._offset,n._offset+y);if(n._offset+=y,_.length>o&&(_=_.slice(0,o)),l.push(_),c+=_.length,o-=_.length,o===0)return!1}return(p===0||n._offset>=n._chunkSize)&&(s=n._chunkSize,n._offset=0,n._buffer=Buffer.allocUnsafe(n._chunkSize)),p===0?(a+=i-m,i=m,!0):!1}Js(this._handle,"zlib binding closed");let h;do h=this._handle.writeSync(e,t,a,i,this._buffer,this._offset,s),h=h||this._writeState;while(!this._hadError&&f(h[0],h[1]));if(this._hadError)throw u;if(c>=Zs)throw Qs(this),new RangeError("Cannot create final Buffer. It would be larger than 0x"+Zs.toString(16)+" bytes");let d=Buffer.concat(l,c);return Qs(this),d};Du.inherits(be,He.Inflate);function Hu(t,e){if(typeof e=="string"&&(e=Buffer.from(e)),!(e instanceof Buffer))throw new TypeError("Not a string or buffer");let r=t._finishFlushFlag;return r==null&&(r=He.Z_FINISH),t._processChunk(e,r)}function Xs(t,e){return Hu(new be(e),t)}eo.exports=dt=Xs;dt.Inflate=be;dt.createInflate=Fu;dt.inflateSync=Xs});var mn=g((ig,no)=>{"use strict";var ro=no.exports=function(t){this._buffer=t,this._reads=[]};ro.prototype.read=function(t,e){this._reads.push({length:Math.abs(t),allowLess:t<0,func:e})};ro.prototype.process=function(){for(;this._reads.length>0&&this._buffer.length;){let t=this._reads[0];if(this._buffer.length&&(this._buffer.length>=t.length||t.allowLess)){this._reads.shift();let e=this._buffer;this._buffer=e.slice(t.length),t.func.call(this,e.slice(0,t.length))}else break}if(this._reads.length>0)return new Error("There are some read requests waitng on finished stream");if(this._buffer.length>0)return new Error("unrecognised content at end of stream")}});var so=g(io=>{"use strict";var zu=mn(),$u=an();io.process=function(t,e){let r=[],n=new zu(t);return new $u(e,{read:n.read.bind(n),write:function(s){r.push(s)},complete:function(){}}).start(),n.process(),Buffer.concat(r)}});var co=g((og,lo)=>{"use strict";var oo=!0,ao=w("zlib"),Wu=to();ao.deflateSync||(oo=!1);var Gu=mn(),Vu=so(),ju=fn(),Yu=hn(),Ku=dn();lo.exports=function(t,e){if(!oo)throw new Error("To use the sync capability of this library in old node versions, please pin pngjs to v2.3.0");let r;function n(S){r=S}let i;function s(S){i=S}function o(S){i.transColor=S}function a(S){i.palette=S}function l(){i.alpha=!0}let c;function u(S){c=S}let f=[];function h(S){f.push(S)}let d=new Gu(t);if(new ju(e,{read:d.read.bind(d),error:n,metadata:s,gamma:u,palette:a,transColor:o,inflateData:h,simpleTransparency:l}).start(),d.process(),r)throw r;let p=Buffer.concat(f);f.length=0;let y;if(i.interlace)y=ao.inflateSync(p);else{let T=((i.width*i.bpp*i.depth+7>>3)+1)*i.height;y=Wu(p,{chunkSize:T,maxLength:T})}if(p=null,!y||!y.length)throw new Error("bad png - invalid inflate data response");let _=Vu.process(y,i);p=null;let B=Yu.dataToBitMap(_,i);_=null;let O=Ku(B,i);return i.data=O,i.gamma=c||0,i}});var po=g((ag,ho)=>{"use strict";var uo=!0,fo=w("zlib");fo.deflateSync||(uo=!1);var Ju=Fe(),Zu=gn();ho.exports=function(t,e){if(!uo)throw new Error("To use the sync capability of this library in old node versions, please pin pngjs to v2.3.0");let r=e||{},n=new Zu(r),i=[];i.push(Buffer.from(Ju.PNG_SIGNATURE)),i.push(n.packIHDR(t.width,t.height)),t.gamma&&i.push(n.packGAMA(t.gamma));let s=n.filterData(t.data,t.width,t.height),o=fo.deflateSync(s,n.getDeflateOptions());if(s=null,!o||!o.length)throw new Error("bad png - invalid compressed data response");return i.push(n.packIDAT(o)),i.push(n.packIEND()),Buffer.concat(i)}});var go=g(yn=>{"use strict";var Qu=co(),Xu=po();yn.read=function(t,e){return Qu(t,e||{})};yn.write=function(t,e){return Xu(t,e)}});var _o=g(yo=>{"use strict";var ef=w("util"),mo=w("stream"),tf=Ds(),rf=Ks(),nf=go(),R=yo.PNG=function(t){mo.call(this),t=t||{},this.width=t.width|0,this.height=t.height|0,this.data=this.width>0&&this.height>0?Buffer.alloc(4*this.width*this.height):null,t.fill&&this.data&&this.data.fill(0),this.gamma=0,this.readable=this.writable=!0,this._parser=new tf(t),this._parser.on("error",this.emit.bind(this,"error")),this._parser.on("close",this._handleClose.bind(this)),this._parser.on("metadata",this._metadata.bind(this)),this._parser.on("gamma",this._gamma.bind(this)),this._parser.on("parsed",function(e){this.data=e,this.emit("parsed",e)}.bind(this)),this._packer=new rf(t),this._packer.on("data",this.emit.bind(this,"data")),this._packer.on("end",this.emit.bind(this,"end")),this._parser.on("close",this._handleClose.bind(this)),this._packer.on("error",this.emit.bind(this,"error"))};ef.inherits(R,mo);R.sync=nf;R.prototype.pack=function(){return!this.data||!this.data.length?(this.emit("error","No data provided"),this):(process.nextTick(function(){this._packer.pack(this.data,this.width,this.height,this.gamma)}.bind(this)),this)};R.prototype.parse=function(t,e){if(e){let r,n;r=function(i){this.removeListener("error",n),this.data=i,e(null,this)}.bind(this),n=function(i){this.removeListener("parsed",r),e(i,null)}.bind(this),this.once("parsed",r),this.once("error",n)}return this.end(t),this};R.prototype.write=function(t){return this._parser.write(t),!0};R.prototype.end=function(t){this._parser.end(t)};R.prototype._metadata=function(t){this.width=t.width,this.height=t.height,this.emit("metadata",t)};R.prototype._gamma=function(t){this.gamma=t};R.prototype._handleClose=function(){!this._parser.writable&&!this._packer.readable&&this.emit("close")};R.bitblt=function(t,e,r,n,i,s,o,a){if(r|=0,n|=0,i|=0,s|=0,o|=0,a|=0,r>t.width||n>t.height||r+i>t.width||n+s>t.height)throw new Error("bitblt reading outside image");if(o>e.width||a>e.height||o+i>e.width||a+s>e.height)throw new Error("bitblt writing outside image");for(let l=0;l<s;l++)t.data.copy(e.data,(a+l)*e.width+o<<2,(n+l)*t.width+r<<2,(n+l)*t.width+r+i<<2)};R.prototype.bitblt=function(t,e,r,n,i,s,o){return R.bitblt(this,t,e,r,n,i,s,o),this};R.adjustGamma=function(t){if(t.gamma){for(let e=0;e<t.height;e++)for(let r=0;r<t.width;r++){let n=t.width*e+r<<2;for(let i=0;i<3;i++){let s=t.data[n+i]/255;s=Math.pow(s,1/2.2/t.gamma),t.data[n+i]=Math.round(s*255)}}t.gamma=0}};R.prototype.adjustGamma=function(){R.adjustGamma(this)}});var pt=g(Ee=>{function wo(t){if(typeof t=="number"&&(t=t.toString()),typeof t!="string")throw new Error("Color should be defined as hex string");let e=t.slice().replace("#","").split("");if(e.length<3||e.length===5||e.length>8)throw new Error("Invalid hex color: "+t);(e.length===3||e.length===4)&&(e=Array.prototype.concat.apply([],e.map(function(n){return[n,n]}))),e.length===6&&e.push("F","F");let r=parseInt(e.join(""),16);return{r:r>>24&255,g:r>>16&255,b:r>>8&255,a:r&255,hex:"#"+e.slice(0,6).join("")}}Ee.getOptions=function(e){e||(e={}),e.color||(e.color={});let r=typeof e.margin>"u"||e.margin===null||e.margin<0?4:e.margin,n=e.width&&e.width>=21?e.width:void 0,i=e.scale||4;return{width:n,scale:n?4:i,margin:r,color:{dark:wo(e.color.dark||"#000000ff"),light:wo(e.color.light||"#ffffffff")},type:e.type,rendererOpts:e.rendererOpts||{}}};Ee.getScale=function(e,r){return r.width&&r.width>=e+r.margin*2?r.width/(e+r.margin*2):r.scale};Ee.getImageWidth=function(e,r){let n=Ee.getScale(e,r);return Math.floor((e+r.margin*2)*n)};Ee.qrToImageData=function(e,r,n){let i=r.modules.size,s=r.modules.data,o=Ee.getScale(i,n),a=Math.floor((i+n.margin*2)*o),l=n.margin*o,c=[n.color.light,n.color.dark];for(let u=0;u<a;u++)for(let f=0;f<a;f++){let h=(u*a+f)*4,d=n.color.light;if(u>=l&&f>=l&&u<a-l&&f<a-l){let m=Math.floor((u-l)/o),p=Math.floor((f-l)/o);d=c[s[m*i+p]?1:0]}e[h++]=d.r,e[h++]=d.g,e[h++]=d.b,e[h]=d.a}}});var bo=g(Z=>{var sf=w("fs"),of=_o().PNG,_n=pt();Z.render=function(e,r){let n=_n.getOptions(r),i=n.rendererOpts,s=_n.getImageWidth(e.modules.size,n);i.width=s,i.height=s;let o=new of(i);return _n.qrToImageData(o.data,e,n),o};Z.renderToDataURL=function(e,r,n){typeof n>"u"&&(n=r,r=void 0),Z.renderToBuffer(e,r,function(i,s){i&&n(i);let o="data:image/png;base64,";o+=s.toString("base64"),n(null,o)})};Z.renderToBuffer=function(e,r,n){typeof n>"u"&&(n=r,r=void 0);let i=Z.render(e,r),s=[];i.on("error",n),i.on("data",function(o){s.push(o)}),i.on("end",function(){n(null,Buffer.concat(s))}),i.pack()};Z.renderToFile=function(e,r,n,i){typeof i>"u"&&(i=n,n=void 0);let s=!1,o=(...l)=>{s||(s=!0,i.apply(null,l))},a=sf.createWriteStream(e);a.on("error",o),a.on("close",o),Z.renderToFileStream(a,r,n)};Z.renderToFileStream=function(e,r,n){Z.render(r,n).pack().pipe(e)}});var Eo=g(tr=>{var af=pt(),lf={WW:" ",WB:"\u2584",BB:"\u2588",BW:"\u2580"},cf={BB:" ",BW:"\u2584",WW:"\u2588",WB:"\u2580"};function uf(t,e,r){return t&&e?r.BB:t&&!e?r.BW:!t&&e?r.WB:r.WW}tr.render=function(t,e,r){let n=af.getOptions(e),i=lf;(n.color.dark.hex==="#ffffff"||n.color.light.hex==="#000000")&&(i=cf);let s=t.modules.size,o=t.modules.data,a="",l=Array(s+n.margin*2+1).join(i.WW);l=Array(n.margin/2+1).join(l+`
|
|
9
|
+
`);let c=Array(n.margin+1).join(i.WW);a+=l;for(let u=0;u<s;u+=2){a+=c;for(let f=0;f<s;f++){let h=o[u*s+f],d=o[(u+1)*s+f];a+=uf(h,d,i)}a+=c+`
|
|
10
|
+
`}return a+=l.slice(0,-1),typeof r=="function"&&r(null,a),a};tr.renderToFile=function(e,r,n,i){typeof i>"u"&&(i=n,n=void 0);let s=w("fs"),o=tr.render(r,n);s.writeFile(e,o,i)}});var So=g(xo=>{xo.render=function(t,e,r){let n=t.modules.size,i=t.modules.data,s="\x1B[40m \x1B[0m",o="\x1B[47m \x1B[0m",a="",l=Array(n+3).join(o),c=Array(2).join(o);a+=l+`
|
|
11
|
+
`;for(let u=0;u<n;++u){a+=o;for(let f=0;f<n;f++)a+=i[u*n+f]?s:o;a+=c+`
|
|
12
12
|
`}return a+=l+`
|
|
13
|
-
`,typeof r=="function"&&r(null,a),a}});var
|
|
14
|
-
`+o,
|
|
15
|
-
`;return typeof n=="function"&&n(null,h),h}});var Io=g(Xt=>{var lu=_n();Xt.render=lu.render;Xt.renderToFile=function(e,r,n,s){typeof s>"u"&&(s=n,n=void 0);let i=w("fs"),a='<?xml version="1.0" encoding="utf-8"?><!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">'+Xt.render(r,n);i.writeFile(e,a,s)}});var Ao=g(Qt=>{var yn=ut();function cu(t,e,r){t.clearRect(0,0,e.width,e.height),e.style||(e.style={}),e.height=r,e.width=r,e.style.height=r+"px",e.style.width=r+"px"}function fu(){try{return document.createElement("canvas")}catch{throw new Error("You need to specify a canvas element")}}Qt.render=function(e,r,n){let s=n,i=r;typeof s>"u"&&(!r||!r.getContext)&&(s=r,r=void 0),r||(i=fu()),s=yn.getOptions(s);let o=yn.getImageWidth(e.modules.size,s),a=i.getContext("2d"),l=a.createImageData(o,o);return yn.qrToImageData(l.data,e,s),cu(a,i,o),a.putImageData(l,0,0),i};Qt.renderToDataURL=function(e,r,n){let s=n;typeof s>"u"&&(!r||!r.getContext)&&(s=r,r=void 0),s||(s={});let i=Qt.render(e,r,s),o=s.type||"image/png",a=s.rendererOpts||{};return i.toDataURL(o,a.quality)}});var Bo=g(ht=>{var uu=Br(),wn=Jr(),Po=Ao(),hu=_n();function bn(t,e,r,n,s){let i=[].slice.call(arguments,1),o=i.length,a=typeof i[o-1]=="function";if(!a&&!uu())throw new Error("Callback required as last argument");if(a){if(o<2)throw new Error("Too few arguments provided");o===2?(s=r,r=e,e=n=void 0):o===3&&(e.getContext&&typeof s>"u"?(s=n,n=void 0):(s=n,n=r,r=e,e=void 0))}else{if(o<1)throw new Error("Too few arguments provided");return o===1?(r=e,e=n=void 0):o===2&&!e.getContext&&(n=r,r=e,e=void 0),new Promise(function(l,c){try{let f=wn.create(r,n);l(t(f,e,n))}catch(f){c(f)}})}try{let l=wn.create(r,n);s(null,t(l,e,n))}catch(l){s(l)}}ht.create=wn.create;ht.toCanvas=bn.bind(null,Po.render);ht.toDataURL=bn.bind(null,Po.renderToDataURL);ht.toString=bn.bind(null,function(t,e,r){return hu.render(t,r)})});var No=g(de=>{var Lo=Br(),En=Jr(),du=mo(),Oo=_o(),pu=To(),Ro=Io();function dt(t,e,r){if(typeof t>"u")throw new Error("String required as first argument");if(typeof r>"u"&&(r=e,e={}),typeof r!="function")if(Lo())e=r||{},r=null;else throw new Error("Callback required as last argument");return{opts:e,cb:r}}function gu(t){return t.slice((t.lastIndexOf(".")-1>>>0)+2).toLowerCase()}function er(t){switch(t){case"svg":return Ro;case"txt":case"utf8":return Oo;case"png":case"image/png":default:return du}}function mu(t){switch(t){case"svg":return Ro;case"terminal":return pu;case"utf8":default:return Oo}}function pt(t,e,r){if(!r.cb)return new Promise(function(n,s){try{let i=En.create(e,r.opts);return t(i,r.opts,function(o,a){return o?s(o):n(a)})}catch(i){s(i)}});try{let n=En.create(e,r.opts);return t(n,r.opts,r.cb)}catch(n){r.cb(n)}}de.create=En.create;de.toCanvas=Bo().toCanvas;de.toString=function(e,r,n){let s=dt(e,r,n),i=s.opts?s.opts.type:void 0,o=mu(i);return pt(o.render,e,s)};de.toDataURL=function(e,r,n){let s=dt(e,r,n),i=er(s.opts.type);return pt(i.renderToDataURL,e,s)};de.toBuffer=function(e,r,n){let s=dt(e,r,n),i=er(s.opts.type);return pt(i.renderToBuffer,e,s)};de.toFile=function(e,r,n,s){if(typeof e!="string"||!(typeof r=="string"||typeof r=="object"))throw new Error("Invalid argument");if(arguments.length<3&&!Lo())throw new Error("Too few arguments provided");let i=dt(r,n,s),o=i.opts.type||gu(e),l=er(o).renderToFile.bind(null,e);return pt(l,r,i)};de.toFileStream=function(e,r,n){if(arguments.length<2)throw new Error("Too few arguments provided");let s=dt(r,n,e.emit.bind(e,"error")),o=er("png").renderToFileStream.bind(null,e);pt(o,r,s)}});var Uo=g((Jp,Mo)=>{Mo.exports=No()});var te=g((ig,Yo)=>{"use strict";var Go=["nodebuffer","arraybuffer","fragments"],jo=typeof Blob<"u";jo&&Go.push("blob");Yo.exports={BINARY_TYPES:Go,CLOSE_TIMEOUT:3e4,EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",hasBlob:jo,kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),NOOP:()=>{}}});var gt=g((og,He)=>{"use strict";var{websocketMask:Vo,websocketUnmask:Tu}=w("http"),{types:{isAnyArrayBuffer:vu}}=w("util"),{EMPTY_BUFFER:ku}=te(),xn=Buffer[Symbol.species];function Iu(t,e){if(t.length===0)return ku;if(t.length===1)return t[0];let r=Buffer.allocUnsafe(e),n=0;for(let s=0;s<t.length;s++){let i=t[s];r.set(i,n),n+=i.length}return n<e?new xn(r.buffer,r.byteOffset,n):r}function Cn(t,e,r,n,s){for(let i=0;i<s;i++)r[n+i]=t[i]^e[i&3]}function Tn(t,e){for(let r=0;r<t.length;r++)t[r]^=e[r&3]}function Au(t){return t.length===t.buffer.byteLength?t.buffer:t.buffer.slice(t.byteOffset,t.byteOffset+t.length)}function vn(t){if(vn.readOnly=!0,Buffer.isBuffer(t))return t;let e;return vu(t)?e=new xn(t):ArrayBuffer.isView(t)?e=new xn(t.buffer,t.byteOffset,t.byteLength):(e=Buffer.from(t),vn.readOnly=!1),e}He.exports={concat:Iu,mask:Cn,toArrayBuffer:Au,toBuffer:vn,unmask:Tn};if(Vo)He.exports.mask=function(t,e,r,n,s){s<24?Cn(t,e,r,n,s):Vo(t,e,r,n,s)},He.exports.unmask=function(t,e){t.length<24?Tn(t,e):Tu(t,e)};else if(!process.env.WS_NO_BUFFER_UTIL)try{let t=w("bufferutil");He.exports.mask=function(e,r,n,s,i){i<48?Cn(e,r,n,s,i):t.mask(e,r,n,s,i)},He.exports.unmask=function(e,r){e.length<32?Tn(e,r):t.unmask(e,r)}}catch{}});var Zo=g((ag,Jo)=>{"use strict";var Ko=Symbol("kDone"),kn=Symbol("kRun"),In=class{constructor(e){this[Ko]=()=>{this.pending--,this[kn]()},this.concurrency=e||1/0,this.jobs=[],this.pending=0}add(e){this.jobs.push(e),this[kn]()}[kn](){if(this.pending!==this.concurrency&&this.jobs.length){let e=this.jobs.shift();this.pending++,e(this[Ko])}}};Jo.exports=In});var $e=g((lg,ra)=>{"use strict";var mt=w("zlib"),Xo=gt(),Pu=Zo(),{kStatusCode:ea}=te(),Bu=Buffer[Symbol.species],Lu=Buffer.from([0,0,255,255]),rr=Symbol("permessage-deflate"),re=Symbol("total-length"),ze=Symbol("callback"),pe=Symbol("buffers"),We=Symbol("error"),Qo=/^(?:[89]|1[0-5])$/,tr,An=class{constructor(e){if(this._options=e||{},this._threshold=this._options.threshold!==void 0?this._options.threshold:1024,this._maxPayload=this._options.maxPayload|0,this._isServer=!!this._options.isServer,this._deflate=null,this._inflate=null,this.params=null,!tr){let r=this._options.concurrencyLimit!==void 0?this._options.concurrencyLimit:10;tr=new Pu(r)}}static get extensionName(){return"permessage-deflate"}offer(){let e={};return this._options.serverNoContextTakeover&&(e.server_no_context_takeover=!0),this._options.clientNoContextTakeover&&(e.client_no_context_takeover=!0),this._options.serverMaxWindowBits&&(e.server_max_window_bits=this._options.serverMaxWindowBits),this._options.clientMaxWindowBits?e.client_max_window_bits=this._options.clientMaxWindowBits:this._options.clientMaxWindowBits==null&&(e.client_max_window_bits=!0),e}accept(e){return e=this.normalizeParams(e),this.params=this._isServer?this.acceptAsServer(e):this.acceptAsClient(e),this.params}cleanup(){if(this._inflate&&(this._inflate.close(),this._inflate=null),this._deflate){let e=this._deflate[ze];this._deflate.close(),this._deflate=null,e&&e(new Error("The deflate stream was closed while data was being processed"))}}acceptAsServer(e){let r=this._options,n=e.find(s=>!(r.serverNoContextTakeover===!1&&s.server_no_context_takeover||s.server_max_window_bits&&(r.serverMaxWindowBits===!1||typeof r.serverMaxWindowBits=="number"&&r.serverMaxWindowBits>s.server_max_window_bits)||typeof r.clientMaxWindowBits=="number"&&(typeof s.client_max_window_bits=="number"?r.clientMaxWindowBits>s.client_max_window_bits:!s.client_max_window_bits)));if(!n)throw new Error("None of the extension offers can be accepted");return r.serverNoContextTakeover&&(n.server_no_context_takeover=!0),r.clientNoContextTakeover&&(n.client_no_context_takeover=!0),typeof r.serverMaxWindowBits=="number"&&(n.server_max_window_bits=r.serverMaxWindowBits),typeof r.clientMaxWindowBits=="number"?n.client_max_window_bits=r.clientMaxWindowBits:(n.client_max_window_bits===!0||r.clientMaxWindowBits===!1)&&delete n.client_max_window_bits,n}acceptAsClient(e){let r=e[0];if(this._options.clientNoContextTakeover===!1&&r.client_no_context_takeover)throw new Error('Unexpected parameter "client_no_context_takeover"');if(!r.client_max_window_bits)typeof this._options.clientMaxWindowBits=="number"&&(r.client_max_window_bits=this._options.clientMaxWindowBits);else if(this._options.clientMaxWindowBits===!1||typeof this._options.clientMaxWindowBits=="number"&&r.client_max_window_bits>this._options.clientMaxWindowBits)throw new Error('Unexpected or invalid parameter "client_max_window_bits"');return r}normalizeParams(e){return e.forEach(r=>{Object.keys(r).forEach(n=>{let s=r[n];if(s.length>1)throw new Error(`Parameter "${n}" must have only a single value`);if(s=s[0],n==="client_max_window_bits"){if(s!==!0){if(!Qo.test(s))throw new TypeError(`Invalid value for parameter "${n}": ${s}`);s=+s}else if(!this._isServer)throw new TypeError(`Invalid value for parameter "${n}": ${s}`)}else if(n==="server_max_window_bits"){if(!Qo.test(s))throw new TypeError(`Invalid value for parameter "${n}": ${s}`);s=+s}else if(n==="client_no_context_takeover"||n==="server_no_context_takeover"){if(s!==!0)throw new TypeError(`Invalid value for parameter "${n}": ${s}`)}else throw new Error(`Unknown parameter "${n}"`);r[n]=s})}),e}decompress(e,r,n){tr.add(s=>{this._decompress(e,r,(i,o)=>{s(),n(i,o)})})}compress(e,r,n){tr.add(s=>{this._compress(e,r,(i,o)=>{s(),n(i,o)})})}_decompress(e,r,n){let s=this._isServer?"client":"server";if(!this._inflate){let i=`${s}_max_window_bits`,o=typeof this.params[i]!="number"?mt.Z_DEFAULT_WINDOWBITS:this.params[i];this._inflate=mt.createInflateRaw({...this._options.zlibInflateOptions,windowBits:o}),this._inflate[rr]=this,this._inflate[re]=0,this._inflate[pe]=[],this._inflate.on("error",Ru),this._inflate.on("data",ta)}this._inflate[ze]=n,this._inflate.write(e),r&&this._inflate.write(Lu),this._inflate.flush(()=>{let i=this._inflate[We];if(i){this._inflate.close(),this._inflate=null,n(i);return}let o=Xo.concat(this._inflate[pe],this._inflate[re]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[re]=0,this._inflate[pe]=[],r&&this.params[`${s}_no_context_takeover`]&&this._inflate.reset()),n(null,o)})}_compress(e,r,n){let s=this._isServer?"server":"client";if(!this._deflate){let i=`${s}_max_window_bits`,o=typeof this.params[i]!="number"?mt.Z_DEFAULT_WINDOWBITS:this.params[i];this._deflate=mt.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:o}),this._deflate[re]=0,this._deflate[pe]=[],this._deflate.on("data",Ou)}this._deflate[ze]=n,this._deflate.write(e),this._deflate.flush(mt.Z_SYNC_FLUSH,()=>{if(!this._deflate)return;let i=Xo.concat(this._deflate[pe],this._deflate[re]);r&&(i=new Bu(i.buffer,i.byteOffset,i.length-4)),this._deflate[ze]=null,this._deflate[re]=0,this._deflate[pe]=[],r&&this.params[`${s}_no_context_takeover`]&&this._deflate.reset(),n(null,i)})}};ra.exports=An;function Ou(t){this[pe].push(t),this[re]+=t.length}function ta(t){if(this[re]+=t.length,this[rr]._maxPayload<1||this[re]<=this[rr]._maxPayload){this[pe].push(t);return}this[We]=new RangeError("Max payload size exceeded"),this[We].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH",this[We][ea]=1009,this.removeListener("data",ta),this.reset()}function Ru(t){if(this[rr]._inflate=null,this[We]){this[ze](this[We]);return}t[ea]=1007,this[ze](t)}});var Ge=g((cg,nr)=>{"use strict";var{isUtf8:na}=w("buffer"),{hasBlob:Nu}=te(),Mu=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,1,1,1,1,1,0,0,1,1,0,1,1,0,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,0,1,0];function Uu(t){return t>=1e3&&t<=1014&&t!==1004&&t!==1005&&t!==1006||t>=3e3&&t<=4999}function Pn(t){let e=t.length,r=0;for(;r<e;)if((t[r]&128)===0)r++;else if((t[r]&224)===192){if(r+1===e||(t[r+1]&192)!==128||(t[r]&254)===192)return!1;r+=2}else if((t[r]&240)===224){if(r+2>=e||(t[r+1]&192)!==128||(t[r+2]&192)!==128||t[r]===224&&(t[r+1]&224)===128||t[r]===237&&(t[r+1]&224)===160)return!1;r+=3}else if((t[r]&248)===240){if(r+3>=e||(t[r+1]&192)!==128||(t[r+2]&192)!==128||(t[r+3]&192)!==128||t[r]===240&&(t[r+1]&240)===128||t[r]===244&&t[r+1]>143||t[r]>244)return!1;r+=4}else return!1;return!0}function Du(t){return Nu&&typeof t=="object"&&typeof t.arrayBuffer=="function"&&typeof t.type=="string"&&typeof t.stream=="function"&&(t[Symbol.toStringTag]==="Blob"||t[Symbol.toStringTag]==="File")}nr.exports={isBlob:Du,isValidStatusCode:Uu,isValidUTF8:Pn,tokenChars:Mu};if(na)nr.exports.isValidUTF8=function(t){return t.length<24?Pn(t):na(t)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{let t=w("utf-8-validate");nr.exports.isValidUTF8=function(e){return e.length<32?Pn(e):t(e)}}catch{}});var Nn=g((fg,fa)=>{"use strict";var{Writable:qu}=w("stream"),sa=$e(),{BINARY_TYPES:Fu,EMPTY_BUFFER:ia,kStatusCode:Hu,kWebSocket:zu}=te(),{concat:Bn,toArrayBuffer:Wu,unmask:$u}=gt(),{isValidStatusCode:Gu,isValidUTF8:oa}=Ge(),_t=Buffer[Symbol.species],F=0,aa=1,la=2,ca=3,Ln=4,On=5,sr=6,Rn=class extends qu{constructor(e={}){super(),this._allowSynchronousEvents=e.allowSynchronousEvents!==void 0?e.allowSynchronousEvents:!0,this._binaryType=e.binaryType||Fu[0],this._extensions=e.extensions||{},this._isServer=!!e.isServer,this._maxBufferedChunks=e.maxBufferedChunks|0,this._maxFragments=e.maxFragments|0,this._maxPayload=e.maxPayload|0,this._skipUTF8Validation=!!e.skipUTF8Validation,this[zu]=void 0,this._bufferedBytes=0,this._buffers=[],this._compressed=!1,this._payloadLength=0,this._mask=void 0,this._fragmented=0,this._masked=!1,this._fin=!1,this._opcode=0,this._totalPayloadLength=0,this._messageLength=0,this._numFragments=0,this._fragments=[],this._errored=!1,this._loop=!1,this._state=F}_write(e,r,n){if(this._opcode===8&&this._state==F)return n();if(this._maxBufferedChunks>0&&this._buffers.length>=this._maxBufferedChunks){n(this.createError(RangeError,"Too many buffered chunks",!1,1008,"WS_ERR_TOO_MANY_BUFFERED_PARTS"));return}this._bufferedBytes+=e.length,this._buffers.push(e),this.startLoop(n)}consume(e){if(this._bufferedBytes-=e,e===this._buffers[0].length)return this._buffers.shift();if(e<this._buffers[0].length){let n=this._buffers[0];return this._buffers[0]=new _t(n.buffer,n.byteOffset+e,n.length-e),new _t(n.buffer,n.byteOffset,e)}let r=Buffer.allocUnsafe(e);do{let n=this._buffers[0],s=r.length-e;e>=n.length?r.set(this._buffers.shift(),s):(r.set(new Uint8Array(n.buffer,n.byteOffset,e),s),this._buffers[0]=new _t(n.buffer,n.byteOffset+e,n.length-e)),e-=n.length}while(e>0);return r}startLoop(e){this._loop=!0;do switch(this._state){case F:this.getInfo(e);break;case aa:this.getPayloadLength16(e);break;case la:this.getPayloadLength64(e);break;case ca:this.getMask();break;case Ln:this.getData(e);break;case On:case sr:this._loop=!1;return}while(this._loop);this._errored||e()}getInfo(e){if(this._bufferedBytes<2){this._loop=!1;return}let r=this._buffers[0];if(r.length>2?(this._bufferedBytes-=2,this._buffers[0]=new _t(r.buffer,r.byteOffset+2,r.length-2)):r=this.consume(2),(r[0]&48)!==0){let s=this.createError(RangeError,"RSV2 and RSV3 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_2_3");e(s);return}let n=(r[0]&64)===64;if(n&&!this._extensions[sa.extensionName]){let s=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(s);return}if(this._fin=(r[0]&128)===128,this._opcode=r[0]&15,this._payloadLength=r[1]&127,this._opcode===0){if(n){let s=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(s);return}if(!this._fragmented){let s=this.createError(RangeError,"invalid opcode 0",!0,1002,"WS_ERR_INVALID_OPCODE");e(s);return}this._opcode=this._fragmented}else if(this._opcode===1||this._opcode===2){if(this._fragmented){let s=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");e(s);return}this._compressed=n}else if(this._opcode>7&&this._opcode<11){if(!this._fin){let s=this.createError(RangeError,"FIN must be set",!0,1002,"WS_ERR_EXPECTED_FIN");e(s);return}if(n){let s=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(s);return}if(this._payloadLength>125||this._opcode===8&&this._payloadLength===1){let s=this.createError(RangeError,`invalid payload length ${this._payloadLength}`,!0,1002,"WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH");e(s);return}}else{let s=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");e(s);return}if(!this._fin&&!this._fragmented&&(this._fragmented=this._opcode),this._masked=(r[1]&128)===128,this._isServer){if(!this._masked){let s=this.createError(RangeError,"MASK must be set",!0,1002,"WS_ERR_EXPECTED_MASK");e(s);return}}else if(this._masked){let s=this.createError(RangeError,"MASK must be clear",!0,1002,"WS_ERR_UNEXPECTED_MASK");e(s);return}this._payloadLength===126?this._state=aa:this._payloadLength===127?this._state=la:this.haveLength(e)}getPayloadLength16(e){if(this._bufferedBytes<2){this._loop=!1;return}this._payloadLength=this.consume(2).readUInt16BE(0),this.haveLength(e)}getPayloadLength64(e){if(this._bufferedBytes<8){this._loop=!1;return}let r=this.consume(8),n=r.readUInt32BE(0);if(n>Math.pow(2,21)-1){let s=this.createError(RangeError,"Unsupported WebSocket frame: payload length > 2^53 - 1",!1,1009,"WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH");e(s);return}this._payloadLength=n*Math.pow(2,32)+r.readUInt32BE(4),this.haveLength(e)}haveLength(e){if(this._payloadLength&&this._opcode<8&&(this._totalPayloadLength+=this._payloadLength,this._totalPayloadLength>this._maxPayload&&this._maxPayload>0)){let r=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");e(r);return}this._masked?this._state=ca:this._state=Ln}getMask(){if(this._bufferedBytes<4){this._loop=!1;return}this._mask=this.consume(4),this._state=Ln}getData(e){let r=ia;if(this._payloadLength){if(this._bufferedBytes<this._payloadLength){this._loop=!1;return}r=this.consume(this._payloadLength),this._masked&&(this._mask[0]|this._mask[1]|this._mask[2]|this._mask[3])!==0&&$u(r,this._mask)}if(this._mask=void 0,this._opcode>7){this.controlMessage(r,e);return}if(this._maxFragments>0&&++this._numFragments>this._maxFragments){let n=this.createError(RangeError,"Too many message fragments",!1,1008,"WS_ERR_TOO_MANY_BUFFERED_PARTS");e(n);return}if(this._compressed){this._state=On,this.decompress(r,e);return}r.length&&(this._messageLength=this._totalPayloadLength,this._fragments.push(r)),this.dataMessage(e)}decompress(e,r){this._extensions[sa.extensionName].decompress(e,this._fin,(s,i)=>{if(s)return r(s);if(i.length){if(this._messageLength+=i.length,this._messageLength>this._maxPayload&&this._maxPayload>0){let o=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");r(o);return}this._fragments.push(i)}this.dataMessage(r),this._state===F&&this.startLoop(r)})}dataMessage(e){if(!this._fin){this._state=F;return}let r=this._messageLength,n=this._fragments;if(this._totalPayloadLength=0,this._messageLength=0,this._fragmented=0,this._numFragments=0,this._fragments=[],this._opcode===2){let s;this._binaryType==="nodebuffer"?s=Bn(n,r):this._binaryType==="arraybuffer"?s=Wu(Bn(n,r)):this._binaryType==="blob"?s=new Blob(n):s=n,this._allowSynchronousEvents?(this.emit("message",s,!0),this._state=F):(this._state=sr,setImmediate(()=>{this.emit("message",s,!0),this._state=F,this.startLoop(e)}))}else{let s=Bn(n,r);if(!this._skipUTF8Validation&&!oa(s)){let i=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");e(i);return}this._state===On||this._allowSynchronousEvents?(this.emit("message",s,!1),this._state=F):(this._state=sr,setImmediate(()=>{this.emit("message",s,!1),this._state=F,this.startLoop(e)}))}}controlMessage(e,r){if(this._opcode===8){if(e.length===0)this._loop=!1,this.emit("conclude",1005,ia),this.end();else{let n=e.readUInt16BE(0);if(!Gu(n)){let i=this.createError(RangeError,`invalid status code ${n}`,!0,1002,"WS_ERR_INVALID_CLOSE_CODE");r(i);return}let s=new _t(e.buffer,e.byteOffset+2,e.length-2);if(!this._skipUTF8Validation&&!oa(s)){let i=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");r(i);return}this._loop=!1,this.emit("conclude",n,s),this.end()}this._state=F;return}this._allowSynchronousEvents?(this.emit(this._opcode===9?"ping":"pong",e),this._state=F):(this._state=sr,setImmediate(()=>{this.emit(this._opcode===9?"ping":"pong",e),this._state=F,this.startLoop(r)}))}createError(e,r,n,s,i){this._loop=!1,this._errored=!0;let o=new e(n?`Invalid WebSocket frame: ${r}`:r);return Error.captureStackTrace(o,this.createError),o.code=i,o[Hu]=s,o}};fa.exports=Rn});var Dn=g((hg,da)=>{"use strict";var{Duplex:ug}=w("stream"),{randomFillSync:ju}=w("crypto"),{types:{isUint8Array:Yu}}=w("util"),ua=$e(),{EMPTY_BUFFER:Vu,kWebSocket:Ku,NOOP:Ju}=te(),{isBlob:je,isValidStatusCode:Zu}=Ge(),{mask:ha,toBuffer:xe}=gt(),H=Symbol("kByteLength"),Xu=Buffer.alloc(4),ir=8*1024,Ce,Ye=ir,$=0,Qu=1,eh=2,Mn=class t{constructor(e,r,n){this._extensions=r||{},n&&(this._generateMask=n,this._maskBuffer=Buffer.alloc(4)),this._socket=e,this._firstFragment=!0,this._compress=!1,this._bufferedBytes=0,this._queue=[],this._state=$,this.onerror=Ju,this[Ku]=void 0}static frame(e,r){let n,s=!1,i=2,o=!1;r.mask&&(n=r.maskBuffer||Xu,r.generateMask?r.generateMask(n):(Ye===ir&&(Ce===void 0&&(Ce=Buffer.alloc(ir)),ju(Ce,0,ir),Ye=0),n[0]=Ce[Ye++],n[1]=Ce[Ye++],n[2]=Ce[Ye++],n[3]=Ce[Ye++]),o=(n[0]|n[1]|n[2]|n[3])===0,i=6);let a;typeof e=="string"?(!r.mask||o)&&r[H]!==void 0?a=r[H]:(e=Buffer.from(e),a=e.length):(a=e.length,s=r.mask&&r.readOnly&&!o);let l=a;a>=65536?(i+=8,l=127):a>125&&(i+=2,l=126);let c=Buffer.allocUnsafe(s?a+i:i);return c[0]=r.fin?r.opcode|128:r.opcode,r.rsv1&&(c[0]|=64),c[1]=l,l===126?c.writeUInt16BE(a,2):l===127&&(c[2]=c[3]=0,c.writeUIntBE(a,4,6)),r.mask?(c[1]|=128,c[i-4]=n[0],c[i-3]=n[1],c[i-2]=n[2],c[i-1]=n[3],a?o?[c,e]:s?(ha(e,n,c,i,a),[c]):(ha(e,n,e,0,a),[c,e]):[c]):a?[c,e]:[c]}close(e,r,n,s){let i;if(e===void 0)i=Vu;else{if(typeof e!="number"||!Zu(e))throw new TypeError("First argument must be a valid error code number");if(r===void 0||!r.length)i=Buffer.allocUnsafe(2),i.writeUInt16BE(e,0);else{let a=Buffer.byteLength(r);if(a>123)throw new RangeError("The message must not be greater than 123 bytes");if(i=Buffer.allocUnsafe(2+a),i.writeUInt16BE(e,0),typeof r=="string")i.write(r,2);else if(Yu(r))i.set(r,2);else throw new TypeError("Second argument must be a string or a Uint8Array")}}let o={[H]:i.length,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};this._state!==$?this.enqueue([this.dispatch,i,!1,o,s]):this.sendFrame(t.frame(i,o),s)}ping(e,r,n){let s,i;if(typeof e=="string"?(s=Buffer.byteLength(e),i=!1):je(e)?(s=e.size,i=!1):(e=xe(e),s=e.length,i=xe.readOnly),s>125)throw new RangeError("The data size must not be greater than 125 bytes");let o={[H]:s,fin:!0,generateMask:this._generateMask,mask:r,maskBuffer:this._maskBuffer,opcode:9,readOnly:i,rsv1:!1};je(e)?this._state!==$?this.enqueue([this.getBlobData,e,!1,o,n]):this.getBlobData(e,!1,o,n):this._state!==$?this.enqueue([this.dispatch,e,!1,o,n]):this.sendFrame(t.frame(e,o),n)}pong(e,r,n){let s,i;if(typeof e=="string"?(s=Buffer.byteLength(e),i=!1):je(e)?(s=e.size,i=!1):(e=xe(e),s=e.length,i=xe.readOnly),s>125)throw new RangeError("The data size must not be greater than 125 bytes");let o={[H]:s,fin:!0,generateMask:this._generateMask,mask:r,maskBuffer:this._maskBuffer,opcode:10,readOnly:i,rsv1:!1};je(e)?this._state!==$?this.enqueue([this.getBlobData,e,!1,o,n]):this.getBlobData(e,!1,o,n):this._state!==$?this.enqueue([this.dispatch,e,!1,o,n]):this.sendFrame(t.frame(e,o),n)}send(e,r,n){let s=this._extensions[ua.extensionName],i=r.binary?2:1,o=r.compress,a,l;typeof e=="string"?(a=Buffer.byteLength(e),l=!1):je(e)?(a=e.size,l=!1):(e=xe(e),a=e.length,l=xe.readOnly),this._firstFragment?(this._firstFragment=!1,o&&s&&s.params[s._isServer?"server_no_context_takeover":"client_no_context_takeover"]&&(o=a>=s._threshold),this._compress=o):(o=!1,i=0),r.fin&&(this._firstFragment=!0);let c={[H]:a,fin:r.fin,generateMask:this._generateMask,mask:r.mask,maskBuffer:this._maskBuffer,opcode:i,readOnly:l,rsv1:o};je(e)?this._state!==$?this.enqueue([this.getBlobData,e,this._compress,c,n]):this.getBlobData(e,this._compress,c,n):this._state!==$?this.enqueue([this.dispatch,e,this._compress,c,n]):this.dispatch(e,this._compress,c,n)}getBlobData(e,r,n,s){this._bufferedBytes+=n[H],this._state=eh,e.arrayBuffer().then(i=>{if(this._socket.destroyed){let a=new Error("The socket was closed while the blob was being read");process.nextTick(Un,this,a,s);return}this._bufferedBytes-=n[H];let o=xe(i);r?this.dispatch(o,r,n,s):(this._state=$,this.sendFrame(t.frame(o,n),s),this.dequeue())}).catch(i=>{process.nextTick(th,this,i,s)})}dispatch(e,r,n,s){if(!r){this.sendFrame(t.frame(e,n),s);return}let i=this._extensions[ua.extensionName];this._bufferedBytes+=n[H],this._state=Qu,i.compress(e,n.fin,(o,a)=>{if(this._socket.destroyed){let l=new Error("The socket was closed while data was being compressed");Un(this,l,s);return}this._bufferedBytes-=n[H],this._state=$,n.readOnly=!1,this.sendFrame(t.frame(a,n),s),this.dequeue()})}dequeue(){for(;this._state===$&&this._queue.length;){let e=this._queue.shift();this._bufferedBytes-=e[3][H],Reflect.apply(e[0],this,e.slice(1))}}enqueue(e){this._bufferedBytes+=e[3][H],this._queue.push(e)}sendFrame(e,r){e.length===2?(this._socket.cork(),this._socket.write(e[0]),this._socket.write(e[1],r),this._socket.uncork()):this._socket.write(e[0],r)}};da.exports=Mn;function Un(t,e,r){typeof r=="function"&&r(e);for(let n=0;n<t._queue.length;n++){let s=t._queue[n],i=s[s.length-1];typeof i=="function"&&i(e)}}function th(t,e,r){Un(t,e,r),t.onerror(e)}});var Sa=g((dg,Ea)=>{"use strict";var{kForOnEventAttribute:yt,kListener:qn}=te(),pa=Symbol("kCode"),ga=Symbol("kData"),ma=Symbol("kError"),_a=Symbol("kMessage"),ya=Symbol("kReason"),Ve=Symbol("kTarget"),wa=Symbol("kType"),ba=Symbol("kWasClean"),ne=class{constructor(e){this[Ve]=null,this[wa]=e}get target(){return this[Ve]}get type(){return this[wa]}};Object.defineProperty(ne.prototype,"target",{enumerable:!0});Object.defineProperty(ne.prototype,"type",{enumerable:!0});var Te=class extends ne{constructor(e,r={}){super(e),this[pa]=r.code===void 0?0:r.code,this[ya]=r.reason===void 0?"":r.reason,this[ba]=r.wasClean===void 0?!1:r.wasClean}get code(){return this[pa]}get reason(){return this[ya]}get wasClean(){return this[ba]}};Object.defineProperty(Te.prototype,"code",{enumerable:!0});Object.defineProperty(Te.prototype,"reason",{enumerable:!0});Object.defineProperty(Te.prototype,"wasClean",{enumerable:!0});var Ke=class extends ne{constructor(e,r={}){super(e),this[ma]=r.error===void 0?null:r.error,this[_a]=r.message===void 0?"":r.message}get error(){return this[ma]}get message(){return this[_a]}};Object.defineProperty(Ke.prototype,"error",{enumerable:!0});Object.defineProperty(Ke.prototype,"message",{enumerable:!0});var wt=class extends ne{constructor(e,r={}){super(e),this[ga]=r.data===void 0?null:r.data}get data(){return this[ga]}};Object.defineProperty(wt.prototype,"data",{enumerable:!0});var rh={addEventListener(t,e,r={}){for(let s of this.listeners(t))if(!r[yt]&&s[qn]===e&&!s[yt])return;let n;if(t==="message")n=function(i,o){let a=new wt("message",{data:o?i:i.toString()});a[Ve]=this,or(e,this,a)};else if(t==="close")n=function(i,o){let a=new Te("close",{code:i,reason:o.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});a[Ve]=this,or(e,this,a)};else if(t==="error")n=function(i){let o=new Ke("error",{error:i,message:i.message});o[Ve]=this,or(e,this,o)};else if(t==="open")n=function(){let i=new ne("open");i[Ve]=this,or(e,this,i)};else return;n[yt]=!!r[yt],n[qn]=e,r.once?this.once(t,n):this.on(t,n)},removeEventListener(t,e){for(let r of this.listeners(t))if(r[qn]===e&&!r[yt]){this.removeListener(t,r);break}}};Ea.exports={CloseEvent:Te,ErrorEvent:Ke,Event:ne,EventTarget:rh,MessageEvent:wt};function or(t,e,r){typeof t=="object"&&t.handleEvent?t.handleEvent.call(t,r):t.call(e,r)}});var ar=g((pg,xa)=>{"use strict";var{tokenChars:bt}=Ge();function J(t,e,r){t[e]===void 0?t[e]=[r]:t[e].push(r)}function nh(t){let e=Object.create(null),r=Object.create(null),n=!1,s=!1,i=!1,o,a,l=-1,c=-1,f=-1,u=0;for(;u<t.length;u++)if(c=t.charCodeAt(u),o===void 0)if(f===-1&&bt[c]===1)l===-1&&(l=u);else if(u!==0&&(c===32||c===9))f===-1&&l!==-1&&(f=u);else if(c===59||c===44){if(l===-1)throw new SyntaxError(`Unexpected character at index ${u}`);f===-1&&(f=u);let d=t.slice(l,f);c===44?(J(e,d,r),r=Object.create(null)):o=d,l=f=-1}else throw new SyntaxError(`Unexpected character at index ${u}`);else if(a===void 0)if(f===-1&&bt[c]===1)l===-1&&(l=u);else if(c===32||c===9)f===-1&&l!==-1&&(f=u);else if(c===59||c===44){if(l===-1)throw new SyntaxError(`Unexpected character at index ${u}`);f===-1&&(f=u),J(r,t.slice(l,f),!0),c===44&&(J(e,o,r),r=Object.create(null),o=void 0),l=f=-1}else if(c===61&&l!==-1&&f===-1)a=t.slice(l,u),l=f=-1;else throw new SyntaxError(`Unexpected character at index ${u}`);else if(s){if(bt[c]!==1)throw new SyntaxError(`Unexpected character at index ${u}`);l===-1?l=u:n||(n=!0),s=!1}else if(i)if(bt[c]===1)l===-1&&(l=u);else if(c===34&&l!==-1)i=!1,f=u;else if(c===92)s=!0;else throw new SyntaxError(`Unexpected character at index ${u}`);else if(c===34&&t.charCodeAt(u-1)===61)i=!0;else if(f===-1&&bt[c]===1)l===-1&&(l=u);else if(l!==-1&&(c===32||c===9))f===-1&&(f=u);else if(c===59||c===44){if(l===-1)throw new SyntaxError(`Unexpected character at index ${u}`);f===-1&&(f=u);let d=t.slice(l,f);n&&(d=d.replace(/\\/g,""),n=!1),J(r,a,d),c===44&&(J(e,o,r),r=Object.create(null),o=void 0),a=void 0,l=f=-1}else throw new SyntaxError(`Unexpected character at index ${u}`);if(l===-1||i||c===32||c===9)throw new SyntaxError("Unexpected end of input");f===-1&&(f=u);let h=t.slice(l,f);return o===void 0?J(e,h,r):(a===void 0?J(r,h,!0):n?J(r,a,h.replace(/\\/g,"")):J(r,a,h),J(e,o,r)),e}function sh(t){return Object.keys(t).map(e=>{let r=t[e];return Array.isArray(r)||(r=[r]),r.map(n=>[e].concat(Object.keys(n).map(s=>{let i=n[s];return Array.isArray(i)||(i=[i]),i.map(o=>o===!0?s:`${s}=${o}`).join("; ")})).join("; ")).join(", ")}).join(", ")}xa.exports={format:sh,parse:nh}});var fr=g((_g,Na)=>{"use strict";var ih=w("events"),oh=w("https"),ah=w("http"),ka=w("net"),Ca=w("querystring"),lh=w("tls"),{randomBytes:ch,createHash:fh}=w("crypto"),{Duplex:gg,Readable:mg}=w("stream"),{URL:lr}=w("url"),ge=$e(),uh=Nn(),hh=Dn(),{isBlob:dh}=Ge(),{BINARY_TYPES:Ta,CLOSE_TIMEOUT:ph,EMPTY_BUFFER:Et,GUID:gh,kForOnEventAttribute:Fn,kListener:mh,kStatusCode:_h,kWebSocket:A,NOOP:yh}=te(),{EventTarget:{addEventListener:wh,removeEventListener:bh}}=Sa(),{format:Eh,parse:Sh}=ar(),{toBuffer:xh}=gt(),Ia=Symbol("kAborted"),Hn=[8,13],se=["CONNECTING","OPEN","CLOSING","CLOSED"],Ch=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/,C=class t extends ih{constructor(e,r,n){super(),this._binaryType=Ta[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=Et,this._closeTimer=null,this._errorEmitted=!1,this._extensions={},this._paused=!1,this._protocol="",this._readyState=t.CONNECTING,this._receiver=null,this._sender=null,this._socket=null,e!==null?(this._bufferedAmount=0,this._isServer=!1,this._redirects=0,r===void 0?!n||n.protocols===void 0?r=[]:Array.isArray(n.protocols)?r=n.protocols:r=[n.protocols]:Array.isArray(r)||(typeof r=="object"&&r!==null?(n=r,n.protocols===void 0?r=[]:Array.isArray(n.protocols)?r=n.protocols:r=[n.protocols]):r=[r]),n=Aa(this,e,r,n)):this._isServer=!0,n.autoPong&&(this._autoPong=!0,this._autoPongComplete=()=>Lh(this),this._pendingAutoPongs=0,this._maxPendingAutoPongs=n.maxPendingAutoPongs|0),this._closeTimeout=n.closeTimeout}get binaryType(){return this._binaryType}set binaryType(e){Ta.includes(e)&&(this._binaryType=e,this._receiver&&(this._receiver._binaryType=e))}get bufferedAmount(){return this._socket?this._socket._writableState.length+this._sender._bufferedBytes:this._bufferedAmount}get extensions(){return Object.keys(this._extensions).join()}get isPaused(){return this._paused}get onclose(){return null}get onerror(){return null}get onopen(){return null}get onmessage(){return null}get protocol(){return this._protocol}get readyState(){return this._readyState}get url(){return this._url}setSocket(e,r,n){let s=new uh({allowSynchronousEvents:n.allowSynchronousEvents,binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxBufferedChunks:n.maxBufferedChunks,maxFragments:n.maxFragments,maxPayload:n.maxPayload,skipUTF8Validation:n.skipUTF8Validation}),i=new hh(e,this._extensions,n.generateMask);this._receiver=s,this._sender=i,this._socket=e,s[A]=this,i[A]=this,e[A]=this,s.on("conclude",kh),s.on("drain",Ih),s.on("error",Ah),s.on("message",Ph),s.on("ping",Bh),s.on("pong",Oh),i.onerror=Rh,e.setTimeout&&e.setTimeout(0),e.setNoDelay&&e.setNoDelay(),r.length>0&&e.unshift(r),e.on("close",La),e.on("data",cr),e.on("end",Oa),e.on("error",Ra),this._readyState=t.OPEN,this.emit("open")}emitClose(){if(!this._socket){this._readyState=t.CLOSED,this.emit("close",this._closeCode,this._closeMessage);return}this._extensions[ge.extensionName]&&this._extensions[ge.extensionName].cleanup(),this._receiver.removeAllListeners(),this._readyState=t.CLOSED,this.emit("close",this._closeCode,this._closeMessage)}close(e,r){if(this.readyState!==t.CLOSED){if(this.readyState===t.CONNECTING){M(this,this._req,"WebSocket was closed before the connection was established");return}if(this.readyState===t.CLOSING){this._closeFrameSent&&(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end();return}this._sender.close(e,r,!this._isServer,n=>{n||(this._closeFrameSent=!0,(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end())}),this._readyState=t.CLOSING,Ba(this)}}pause(){this.readyState===t.CONNECTING||this.readyState===t.CLOSED||(this._paused=!0,this._socket.pause())}ping(e,r,n){if(this.readyState===t.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof e=="function"?(n=e,e=r=void 0):typeof r=="function"&&(n=r,r=void 0),typeof e=="number"&&(e=e.toString()),this.readyState!==t.OPEN){zn(this,e,n);return}r===void 0&&(r=!this._isServer),this._sender.ping(e||Et,r,n)}pong(e,r,n){if(this.readyState===t.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof e=="function"?(n=e,e=r=void 0):typeof r=="function"&&(n=r,r=void 0),typeof e=="number"&&(e=e.toString()),this.readyState!==t.OPEN){zn(this,e,n);return}r===void 0&&(r=!this._isServer),this._sender.pong(e||Et,r,n)}resume(){this.readyState===t.CONNECTING||this.readyState===t.CLOSED||(this._paused=!1,this._receiver._writableState.needDrain||this._socket.resume())}send(e,r,n){if(this.readyState===t.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof r=="function"&&(n=r,r={}),typeof e=="number"&&(e=e.toString()),this.readyState!==t.OPEN){zn(this,e,n);return}let s={binary:typeof e!="string",mask:!this._isServer,compress:!0,fin:!0,...r};this._extensions[ge.extensionName]||(s.compress=!1),this._sender.send(e||Et,s,n)}terminate(){if(this.readyState!==t.CLOSED){if(this.readyState===t.CONNECTING){M(this,this._req,"WebSocket was closed before the connection was established");return}this._socket&&(this._readyState=t.CLOSING,this._socket.destroy())}}};Object.defineProperty(C,"CONNECTING",{enumerable:!0,value:se.indexOf("CONNECTING")});Object.defineProperty(C.prototype,"CONNECTING",{enumerable:!0,value:se.indexOf("CONNECTING")});Object.defineProperty(C,"OPEN",{enumerable:!0,value:se.indexOf("OPEN")});Object.defineProperty(C.prototype,"OPEN",{enumerable:!0,value:se.indexOf("OPEN")});Object.defineProperty(C,"CLOSING",{enumerable:!0,value:se.indexOf("CLOSING")});Object.defineProperty(C.prototype,"CLOSING",{enumerable:!0,value:se.indexOf("CLOSING")});Object.defineProperty(C,"CLOSED",{enumerable:!0,value:se.indexOf("CLOSED")});Object.defineProperty(C.prototype,"CLOSED",{enumerable:!0,value:se.indexOf("CLOSED")});["binaryType","bufferedAmount","extensions","isPaused","protocol","readyState","url"].forEach(t=>{Object.defineProperty(C.prototype,t,{enumerable:!0})});["open","error","close","message"].forEach(t=>{Object.defineProperty(C.prototype,`on${t}`,{enumerable:!0,get(){for(let e of this.listeners(t))if(e[Fn])return e[mh];return null},set(e){for(let r of this.listeners(t))if(r[Fn]){this.removeListener(t,r);break}typeof e=="function"&&this.addEventListener(t,e,{[Fn]:!0})}})});C.prototype.addEventListener=wh;C.prototype.removeEventListener=bh;Na.exports=C;function Aa(t,e,r,n){let s={allowSynchronousEvents:!0,autoPong:!0,closeTimeout:ph,protocolVersion:Hn[1],maxBufferedChunks:262144,maxFragments:16384,maxPayload:104857600,maxPendingAutoPongs:60,skipUTF8Validation:!1,perMessageDeflate:!0,followRedirects:!1,maxRedirects:10,...n,socketPath:void 0,hostname:void 0,protocol:void 0,protocols:void 0,timeout:void 0,method:"GET",host:void 0,path:void 0,port:void 0};if(!Hn.includes(s.protocolVersion))throw new RangeError(`Unsupported protocol version: ${s.protocolVersion} (supported versions: ${Hn.join(", ")})`);let i;if(e instanceof lr)i=e;else try{i=new lr(e)}catch{throw new SyntaxError(`Invalid URL: ${e}`)}(i.protocol==="http:"||i.protocol==="https:")&&(i=new lr(i),i.protocol=i.protocol==="http:"?"ws:":"wss:"),t._url=i.href;let o=i.protocol==="wss:",a=i.protocol==="ws+unix:",l;if(i.protocol!=="ws:"&&!o&&!a?l=`The URL's protocol must be one of "ws:", "wss:", "http:", "https:", or "ws+unix:"`:a&&!i.pathname?l="The URL's pathname is empty":i.hash&&(l="The URL contains a fragment identifier"),l){let p=new SyntaxError(l);if(t._redirects===0)throw p;St(t,p);return}let c=o?443:80,f=ch(16).toString("base64"),u=o?oh.request:ah.request,h=new Set,d;if(s.createConnection=s.createConnection||(o?vh:Th),s.defaultPort=s.defaultPort||c,s.port=i.port||c,s.host=i.hostname.startsWith("[")?i.hostname.slice(1,-1):i.hostname,s.headers={...s.headers,"Sec-WebSocket-Version":s.protocolVersion,"Sec-WebSocket-Key":f,Connection:"Upgrade",Upgrade:"websocket"},s.path=i.pathname+i.search,s.timeout=s.handshakeTimeout,s.perMessageDeflate&&(d=new ge({...s.perMessageDeflate,isServer:!1,maxPayload:s.maxPayload}),s.headers["Sec-WebSocket-Extensions"]=Eh({[ge.extensionName]:d.offer()})),r.length){for(let p of r){if(typeof p!="string"||!Ch.test(p)||h.has(p))throw new SyntaxError("An invalid or duplicated subprotocol was specified");h.add(p)}s.headers["Sec-WebSocket-Protocol"]=r.join(",")}if(s.origin&&(s.protocolVersion<13?s.headers["Sec-WebSocket-Origin"]=s.origin:s.headers.Origin=s.origin),i.username||i.password){let p=Ca.unescape(i.username),_=Ca.unescape(i.password);s.auth=`${p}:${_}`}if(a){let p=s.path.indexOf(":");p===-1?(s.socketPath=s.path,s.path=""):(s.socketPath=s.path.slice(0,p),s.path=s.path.slice(p+1))}let m;if(s.followRedirects){if(t._redirects===0){t._originalIpc=a,t._originalSecure=o,t._originalHostOrSocketPath=a?s.socketPath:i.host;let p=n&&n.headers;if(n={...n,headers:{}},p)for(let[_,y]of Object.entries(p))n.headers[_.toLowerCase()]=y}else if(t.listenerCount("redirect")===0){let p=a?t._originalIpc?s.socketPath===t._originalHostOrSocketPath:!1:t._originalIpc?!1:i.host===t._originalHostOrSocketPath;(!p||t._originalSecure&&!o)&&(delete s.headers.authorization,delete s.headers.cookie,p||delete s.headers.host,s.auth=void 0)}s.auth&&!n.headers.authorization&&(n.headers.authorization="Basic "+Buffer.from(s.auth).toString("base64"));try{m=t._req=u(s)}catch(p){if(t._redirects===0)throw p;St(t,p);return}t._redirects&&t.emit("redirect",t.url,m)}else m=t._req=u(s);return s.timeout&&m.on("timeout",()=>{M(t,m,"Opening handshake has timed out")}),m.on("error",p=>{m===null||m[Ia]||(m=t._req=null,St(t,p))}),m.on("response",p=>{let _=p.headers.location,y=p.statusCode;if(_&&s.followRedirects&&y>=300&&y<400){if(++t._redirects>s.maxRedirects){M(t,m,"Maximum redirects exceeded");return}m.abort();let B;try{B=new lr(_,e)}catch{let x=new SyntaxError(`Invalid URL: ${_}`);St(t,x);return}Aa(t,B,r,n)}else t.emit("unexpected-response",m,p)||M(t,m,`Unexpected server response: ${p.statusCode}`)}),m.on("upgrade",(p,_,y)=>{if(t.emit("upgrade",p),t.readyState!==C.CONNECTING)return;m=t._req=null;let B=p.headers.upgrade;if(B===void 0||B.toLowerCase()!=="websocket"){M(t,_,"Invalid Upgrade header");return}let O=fh("sha1").update(f+gh).digest("base64");if(p.headers["sec-websocket-accept"]!==O){M(t,_,"Invalid Sec-WebSocket-Accept header");return}let x=p.headers["sec-websocket-protocol"],T;if(x!==void 0?h.size?h.has(x)||(T="Server sent an invalid subprotocol"):T="Server sent a subprotocol but none was requested":h.size&&(T="Server sent no subprotocol"),T){M(t,_,T);return}x&&(t._protocol=x);let E=p.headers["sec-websocket-extensions"];if(E!==void 0){if(!d){M(t,_,"Server sent a Sec-WebSocket-Extensions header but no extension was requested");return}let U;try{U=Sh(E)}catch{M(t,_,"Invalid Sec-WebSocket-Extensions header");return}let Ie=Object.keys(U);if(Ie.length!==1||Ie[0]!==ge.extensionName){M(t,_,"Server indicated an extension that was not requested");return}try{d.accept(U[ge.extensionName])}catch{M(t,_,"Invalid Sec-WebSocket-Extensions header");return}t._extensions[ge.extensionName]=d}t.setSocket(_,y,{allowSynchronousEvents:s.allowSynchronousEvents,generateMask:s.generateMask,maxBufferedChunks:s.maxBufferedChunks,maxFragments:s.maxFragments,maxPayload:s.maxPayload,skipUTF8Validation:s.skipUTF8Validation})}),s.finishRequest?s.finishRequest(m,t):m.end(),s}function St(t,e){t._readyState=C.CLOSING,t._errorEmitted=!0,t.emit("error",e),t.emitClose()}function Th(t){return t.path=t.socketPath,ka.connect(t)}function vh(t){return t.path=void 0,!t.servername&&t.servername!==""&&(t.servername=ka.isIP(t.host)?"":t.host),lh.connect(t)}function M(t,e,r){t._readyState=C.CLOSING;let n=new Error(r);Error.captureStackTrace(n,M),e.setHeader?(e[Ia]=!0,e.abort(),e.socket&&!e.socket.destroyed&&e.socket.destroy(),process.nextTick(St,t,n)):(e.destroy(n),e.once("error",t.emit.bind(t,"error")),e.once("close",t.emitClose.bind(t)))}function zn(t,e,r){if(e){let n=dh(e)?e.size:xh(e).length;t._socket?t._sender._bufferedBytes+=n:t._bufferedAmount+=n}if(r){let n=new Error(`WebSocket is not open: readyState ${t.readyState} (${se[t.readyState]})`);process.nextTick(r,n)}}function kh(t,e){let r=this[A];r._closeFrameReceived=!0,r._closeCode=t,e.length===0?r._closeMessage=Et:(r._closeMessage=Buffer.allocUnsafeSlow(e.length),r._closeMessage.set(e)),r._socket[A]!==void 0&&(r._socket.removeListener("data",cr),process.nextTick(Pa,r._socket),t===1005?r.close():r.close(t,e))}function Ih(){let t=this[A];t.isPaused||t._socket.resume()}function Ah(t){let e=this[A];e._socket[A]!==void 0&&(e._socket.removeListener("data",cr),process.nextTick(Pa,e._socket),e.close(t[_h])),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",t))}function va(){this[A].emitClose()}function Ph(t,e){this[A].emit("message",t,e)}function Bh(t){let e=this[A];e._autoPong&&e.readyState===C.OPEN&&(e._maxPendingAutoPongs>0&&e._pendingAutoPongs>=e._maxPendingAutoPongs?e.terminate():(e._pendingAutoPongs++,e.pong(t,!this._isServer,e._autoPongComplete))),e.emit("ping",t)}function Lh(t){t._pendingAutoPongs--}function Oh(t){this[A].emit("pong",t)}function Pa(t){t.resume()}function Rh(t){let e=this[A];e.readyState!==C.CLOSED&&(e.readyState===C.OPEN&&(e._readyState=C.CLOSING,Ba(e)),this._socket.end(),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",t)))}function Ba(t){t._closeTimer=setTimeout(t._socket.destroy.bind(t._socket),t._closeTimeout)}function La(){let t=this[A];if(this.removeListener("close",La),this.removeListener("data",cr),this.removeListener("end",Oa),t._readyState=C.CLOSING,!this._readableState.endEmitted&&!t._closeFrameReceived&&!t._receiver._writableState.errorEmitted&&this._readableState.length!==0){let e=this.read(this._readableState.length);t._receiver.write(e)}t._receiver.end(),this[A]=void 0,clearTimeout(t._closeTimer),t._receiver._writableState.finished||t._receiver._writableState.errorEmitted?t.emitClose():(t._receiver.on("error",va),t._receiver.on("finish",va))}function cr(t){this[A]._receiver.write(t)||this.pause()}function Oa(){let t=this[A];t._readyState=C.CLOSING,t._receiver.end(),this.end()}function Ra(){let t=this[A];this.removeListener("error",Ra),this.on("error",yh),t&&(t._readyState=C.CLOSING,this.destroy())}});var qa=g((wg,Da)=>{"use strict";var yg=fr(),{Duplex:Nh}=w("stream");function Ma(t){t.emit("close")}function Mh(){!this.destroyed&&this._writableState.finished&&this.destroy()}function Ua(t){this.removeListener("error",Ua),this.destroy(),this.listenerCount("error")===0&&this.emit("error",t)}function Uh(t,e){let r=!0,n=new Nh({...e,autoDestroy:!1,emitClose:!1,objectMode:!1,writableObjectMode:!1});return t.on("message",function(i,o){let a=!o&&n._readableState.objectMode?i.toString():i;n.push(a)||t.pause()}),t.once("error",function(i){n.destroyed||(r=!1,n.destroy(i))}),t.once("close",function(){n.destroyed||n.push(null)}),n._destroy=function(s,i){if(t.readyState===t.CLOSED){i(s),process.nextTick(Ma,n);return}let o=!1;t.once("error",function(l){o=!0,i(l)}),t.once("close",function(){o||i(s),process.nextTick(Ma,n)}),r&&t.terminate()},n._final=function(s){if(t.readyState===t.CONNECTING){t.once("open",function(){n._final(s)});return}t._socket!==null&&(t._socket._writableState.finished?(s(),n._readableState.endEmitted&&n.destroy()):(t._socket.once("finish",function(){s()}),t.close()))},n._read=function(){t.isPaused&&t.resume()},n._write=function(s,i,o){if(t.readyState===t.CONNECTING){t.once("open",function(){n._write(s,i,o)});return}t.send(s,o)},n.on("end",Mh),n.on("error",Ua),n}Da.exports=Uh});var Wn=g((bg,Fa)=>{"use strict";var{tokenChars:Dh}=Ge();function qh(t){let e=new Set,r=-1,n=-1,s=0;for(s;s<t.length;s++){let o=t.charCodeAt(s);if(n===-1&&Dh[o]===1)r===-1&&(r=s);else if(s!==0&&(o===32||o===9))n===-1&&r!==-1&&(n=s);else if(o===44){if(r===-1)throw new SyntaxError(`Unexpected character at index ${s}`);n===-1&&(n=s);let a=t.slice(r,n);if(e.has(a))throw new SyntaxError(`The "${a}" subprotocol is duplicated`);e.add(a),r=n=-1}else throw new SyntaxError(`Unexpected character at index ${s}`)}if(r===-1||n!==-1)throw new SyntaxError("Unexpected end of input");let i=t.slice(r,s);if(e.has(i))throw new SyntaxError(`The "${i}" subprotocol is duplicated`);return e.add(i),e}Fa.exports={parse:qh}});var Ya=g((Sg,ja)=>{"use strict";var Fh=w("events"),ur=w("http"),{Duplex:Eg}=w("stream"),{createHash:Hh}=w("crypto"),Ha=ar(),ve=$e(),zh=Wn(),Wh=fr(),{CLOSE_TIMEOUT:$h,GUID:Gh,kWebSocket:jh}=te(),Yh=/^[+/0-9A-Za-z]{22}==$/,za=0,Wa=1,Ga=2,$n=class extends Fh{constructor(e,r){if(super(),e={allowSynchronousEvents:!0,autoPong:!0,maxBufferedChunks:256*1024,maxFragments:16*1024,maxPayload:100*1024*1024,maxPendingAutoPongs:60,skipUTF8Validation:!1,perMessageDeflate:!1,handleProtocols:null,clientTracking:!0,closeTimeout:$h,verifyClient:null,noServer:!1,backlog:null,server:null,host:null,path:null,port:null,WebSocket:Wh,...e},e.port==null&&!e.server&&!e.noServer||e.port!=null&&(e.server||e.noServer)||e.server&&e.noServer)throw new TypeError('One and only one of the "port", "server", or "noServer" options must be specified');if(e.port!=null?(this._server=ur.createServer((n,s)=>{let i=ur.STATUS_CODES[426];s.writeHead(426,{"Content-Length":i.length,"Content-Type":"text/plain"}),s.end(i)}),this._server.listen(e.port,e.host,e.backlog,r)):e.server&&(this._server=e.server),this._server){let n=this.emit.bind(this,"connection");this._removeListeners=Vh(this._server,{listening:this.emit.bind(this,"listening"),error:this.emit.bind(this,"error"),upgrade:(s,i,o)=>{this.handleUpgrade(s,i,o,n)}})}e.perMessageDeflate===!0&&(e.perMessageDeflate={}),e.clientTracking&&(this.clients=new Set,this._shouldEmitClose=!1),this.options=e,this._state=za}address(){if(this.options.noServer)throw new Error('The server is operating in "noServer" mode');return this._server?this._server.address():null}close(e){if(this._state===Ga){e&&this.once("close",()=>{e(new Error("The server is not running"))}),process.nextTick(xt,this);return}if(e&&this.once("close",e),this._state!==Wa)if(this._state=Wa,this.options.noServer||this.options.server)this._server&&(this._removeListeners(),this._removeListeners=this._server=null),this.clients?this.clients.size?this._shouldEmitClose=!0:process.nextTick(xt,this):process.nextTick(xt,this);else{let r=this._server;this._removeListeners(),this._removeListeners=this._server=null,r.close(()=>{xt(this)})}}shouldHandle(e){if(this.options.path){let r=e.url.indexOf("?");if((r!==-1?e.url.slice(0,r):e.url)!==this.options.path)return!1}return!0}handleUpgrade(e,r,n,s){r.on("error",$a);let i=e.headers["sec-websocket-key"],o=e.headers.upgrade,a=e.headers["sec-websocket-version"];if(e.method!=="GET"){ke(this,e,r,405,"Invalid HTTP method");return}if(o===void 0||o.toLowerCase()!=="websocket"){ke(this,e,r,400,"Invalid Upgrade header");return}if(i===void 0||!Yh.test(i)){ke(this,e,r,400,"Missing or invalid Sec-WebSocket-Key header");return}if(a!=="13"&&a!=="8"){ke(this,e,r,400,"Missing or invalid Sec-WebSocket-Version header",{"Sec-WebSocket-Version":"13, 8"});return}if(!this.shouldHandle(e)){Ct(r,400);return}let l=e.headers["sec-websocket-protocol"],c=new Set;if(l!==void 0)try{c=zh.parse(l)}catch{ke(this,e,r,400,"Invalid Sec-WebSocket-Protocol header");return}let f=e.headers["sec-websocket-extensions"],u={};if(this.options.perMessageDeflate&&f!==void 0){let h=new ve({...this.options.perMessageDeflate,isServer:!0,maxPayload:this.options.maxPayload});try{let d=Ha.parse(f);d[ve.extensionName]&&(h.accept(d[ve.extensionName]),u[ve.extensionName]=h)}catch{ke(this,e,r,400,"Invalid or unacceptable Sec-WebSocket-Extensions header");return}}if(this.options.verifyClient){let h={origin:e.headers[`${a==="8"?"sec-websocket-origin":"origin"}`],secure:!!(e.socket.authorized||e.socket.encrypted),req:e};if(this.options.verifyClient.length===2){this.options.verifyClient(h,(d,m,p,_)=>{if(!d)return Ct(r,m||401,p,_);this.completeUpgrade(u,i,c,e,r,n,s)});return}if(!this.options.verifyClient(h))return Ct(r,401)}this.completeUpgrade(u,i,c,e,r,n,s)}completeUpgrade(e,r,n,s,i,o,a){if(!i.readable||!i.writable)return i.destroy();if(i[jh])throw new Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");if(this._state>za)return Ct(i,503);let c=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${Hh("sha1").update(r+Gh).digest("base64")}`],f=new this.options.WebSocket(null,void 0,this.options);if(n.size){let u=this.options.handleProtocols?this.options.handleProtocols(n,s):n.values().next().value;u&&(c.push(`Sec-WebSocket-Protocol: ${u}`),f._protocol=u)}if(e[ve.extensionName]){let u=e[ve.extensionName].params,h=Ha.format({[ve.extensionName]:[u]});c.push(`Sec-WebSocket-Extensions: ${h}`),f._extensions=e}this.emit("headers",c,s),i.write(c.concat(`\r
|
|
13
|
+
`,typeof r=="function"&&r(null,a),a}});var ko=g(Co=>{var ff="\x1B[47m",hf="\x1B[40m",wn="\x1B[37m",bn="\x1B[30m",xe="\x1B[0m",df=ff+bn,pf=hf+wn,gf=function(t,e,r){return{"00":xe+" "+t,"01":xe+e+"\u2584"+t,"02":xe+r+"\u2584"+t,10:xe+e+"\u2580"+t,11:" ",12:"\u2584",20:xe+r+"\u2580"+t,21:"\u2580",22:"\u2588"}},vo=function(t,e,r,n){let i=e+1;if(r>=i||n>=i||n<-1||r<-1)return"0";if(r>=e||n>=e||n<0||r<0)return"1";let s=n*e+r;return t[s]?"2":"1"},To=function(t,e,r,n){return vo(t,e,r,n)+vo(t,e,r,n+1)};Co.render=function(t,e,r){let n=t.modules.size,i=t.modules.data,s=!!(e&&e.inverse),o=e&&e.inverse?pf:df,c=gf(o,s?bn:wn,s?wn:bn),u=xe+`
|
|
14
|
+
`+o,f=o;for(let h=-1;h<n+1;h+=2){for(let d=-1;d<n;d++)f+=c[To(i,n,d,h)];f+=c[To(i,n,n,h)]+u}return f+=xe,typeof r=="function"&&r(null,f),f}});var Ao=g(Io=>{var mf=So(),yf=ko();Io.render=function(t,e,r){return e&&e.small?yf.render(t,e,r):mf.render(t,e,r)}});var xn=g(Bo=>{var _f=pt();function Po(t,e){let r=t.a/255,n=e+'="'+t.hex+'"';return r<1?n+" "+e+'-opacity="'+r.toFixed(2).slice(1)+'"':n}function En(t,e,r){let n=t+e;return typeof r<"u"&&(n+=" "+r),n}function wf(t,e,r){let n="",i=0,s=!1,o=0;for(let a=0;a<t.length;a++){let l=Math.floor(a%e),c=Math.floor(a/e);!l&&!s&&(s=!0),t[a]?(o++,a>0&&l>0&&t[a-1]||(n+=s?En("M",l+r,.5+c+r):En("m",i,0),i=0,s=!1),l+1<e&&t[a+1]||(n+=En("h",o),o=0)):i++}return n}Bo.render=function(e,r,n){let i=_f.getOptions(r),s=e.modules.size,o=e.modules.data,a=s+i.margin*2,l=i.color.light.a?"<path "+Po(i.color.light,"fill")+' d="M0 0h'+a+"v"+a+'H0z"/>':"",c="<path "+Po(i.color.dark,"stroke")+' d="'+wf(o,s,i.margin)+'"/>',u='viewBox="0 0 '+a+" "+a+'"',h='<svg xmlns="http://www.w3.org/2000/svg" '+(i.width?'width="'+i.width+'" height="'+i.width+'" ':"")+u+' shape-rendering="crispEdges">'+l+c+`</svg>
|
|
15
|
+
`;return typeof n=="function"&&n(null,h),h}});var Lo=g(rr=>{var bf=xn();rr.render=bf.render;rr.renderToFile=function(e,r,n,i){typeof i>"u"&&(i=n,n=void 0);let s=w("fs"),a='<?xml version="1.0" encoding="utf-8"?><!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">'+rr.render(r,n);s.writeFile(e,a,i)}});var Oo=g(nr=>{var Sn=pt();function Ef(t,e,r){t.clearRect(0,0,e.width,e.height),e.style||(e.style={}),e.height=r,e.width=r,e.style.height=r+"px",e.style.width=r+"px"}function xf(){try{return document.createElement("canvas")}catch{throw new Error("You need to specify a canvas element")}}nr.render=function(e,r,n){let i=n,s=r;typeof i>"u"&&(!r||!r.getContext)&&(i=r,r=void 0),r||(s=xf()),i=Sn.getOptions(i);let o=Sn.getImageWidth(e.modules.size,i),a=s.getContext("2d"),l=a.createImageData(o,o);return Sn.qrToImageData(l.data,e,i),Ef(a,s,o),a.putImageData(l,0,0),s};nr.renderToDataURL=function(e,r,n){let i=n;typeof i>"u"&&(!r||!r.getContext)&&(i=r,r=void 0),i||(i={});let s=nr.render(e,r,i),o=i.type||"image/png",a=i.rendererOpts||{};return s.toDataURL(o,a.quality)}});var No=g(gt=>{var Sf=Mr(),vn=tn(),Ro=Oo(),vf=xn();function Tn(t,e,r,n,i){let s=[].slice.call(arguments,1),o=s.length,a=typeof s[o-1]=="function";if(!a&&!Sf())throw new Error("Callback required as last argument");if(a){if(o<2)throw new Error("Too few arguments provided");o===2?(i=r,r=e,e=n=void 0):o===3&&(e.getContext&&typeof i>"u"?(i=n,n=void 0):(i=n,n=r,r=e,e=void 0))}else{if(o<1)throw new Error("Too few arguments provided");return o===1?(r=e,e=n=void 0):o===2&&!e.getContext&&(n=r,r=e,e=void 0),new Promise(function(l,c){try{let u=vn.create(r,n);l(t(u,e,n))}catch(u){c(u)}})}try{let l=vn.create(r,n);i(null,t(l,e,n))}catch(l){i(l)}}gt.create=vn.create;gt.toCanvas=Tn.bind(null,Ro.render);gt.toDataURL=Tn.bind(null,Ro.renderToDataURL);gt.toString=Tn.bind(null,function(t,e,r){return vf.render(t,r)})});var Do=g(de=>{var Mo=Mr(),Cn=tn(),Tf=bo(),Uo=Eo(),Cf=Ao(),qo=Lo();function mt(t,e,r){if(typeof t>"u")throw new Error("String required as first argument");if(typeof r>"u"&&(r=e,e={}),typeof r!="function")if(Mo())e=r||{},r=null;else throw new Error("Callback required as last argument");return{opts:e,cb:r}}function kf(t){return t.slice((t.lastIndexOf(".")-1>>>0)+2).toLowerCase()}function ir(t){switch(t){case"svg":return qo;case"txt":case"utf8":return Uo;case"png":case"image/png":default:return Tf}}function If(t){switch(t){case"svg":return qo;case"terminal":return Cf;case"utf8":default:return Uo}}function yt(t,e,r){if(!r.cb)return new Promise(function(n,i){try{let s=Cn.create(e,r.opts);return t(s,r.opts,function(o,a){return o?i(o):n(a)})}catch(s){i(s)}});try{let n=Cn.create(e,r.opts);return t(n,r.opts,r.cb)}catch(n){r.cb(n)}}de.create=Cn.create;de.toCanvas=No().toCanvas;de.toString=function(e,r,n){let i=mt(e,r,n),s=i.opts?i.opts.type:void 0,o=If(s);return yt(o.render,e,i)};de.toDataURL=function(e,r,n){let i=mt(e,r,n),s=ir(i.opts.type);return yt(s.renderToDataURL,e,i)};de.toBuffer=function(e,r,n){let i=mt(e,r,n),s=ir(i.opts.type);return yt(s.renderToBuffer,e,i)};de.toFile=function(e,r,n,i){if(typeof e!="string"||!(typeof r=="string"||typeof r=="object"))throw new Error("Invalid argument");if(arguments.length<3&&!Mo())throw new Error("Too few arguments provided");let s=mt(r,n,i),o=s.opts.type||kf(e),l=ir(o).renderToFile.bind(null,e);return yt(l,r,s)};de.toFileStream=function(e,r,n){if(arguments.length<2)throw new Error("Too few arguments provided");let i=mt(r,n,e.emit.bind(e,"error")),o=ir("png").renderToFileStream.bind(null,e);yt(o,r,i)}});var Ho=g((Eg,Fo)=>{Fo.exports=Do()});var re=g((Pg,Zo)=>{"use strict";var Ko=["nodebuffer","arraybuffer","fragments"],Jo=typeof Blob<"u";Jo&&Ko.push("blob");Zo.exports={BINARY_TYPES:Ko,CLOSE_TIMEOUT:3e4,EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",hasBlob:Jo,kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),NOOP:()=>{}}});var _t=g((Bg,ze)=>{"use strict";var{websocketMask:Qo,websocketUnmask:Uf}=w("http"),{types:{isAnyArrayBuffer:qf}}=w("util"),{EMPTY_BUFFER:Df}=re(),In=Buffer[Symbol.species];function Ff(t,e){if(t.length===0)return Df;if(t.length===1)return t[0];let r=Buffer.allocUnsafe(e),n=0;for(let i=0;i<t.length;i++){let s=t[i];r.set(s,n),n+=s.length}return n<e?new In(r.buffer,r.byteOffset,n):r}function An(t,e,r,n,i){for(let s=0;s<i;s++)r[n+s]=t[s]^e[s&3]}function Pn(t,e){for(let r=0;r<t.length;r++)t[r]^=e[r&3]}function Hf(t){return t.length===t.buffer.byteLength?t.buffer:t.buffer.slice(t.byteOffset,t.byteOffset+t.length)}function Bn(t){if(Bn.readOnly=!0,Buffer.isBuffer(t))return t;let e;return qf(t)?e=new In(t):ArrayBuffer.isView(t)?e=new In(t.buffer,t.byteOffset,t.byteLength):(e=Buffer.from(t),Bn.readOnly=!1),e}ze.exports={concat:Ff,mask:An,toArrayBuffer:Hf,toBuffer:Bn,unmask:Pn};if(Qo)ze.exports.mask=function(t,e,r,n,i){i<24?An(t,e,r,n,i):Qo(t,e,r,n,i)},ze.exports.unmask=function(t,e){t.length<24?Pn(t,e):Uf(t,e)};else if(!process.env.WS_NO_BUFFER_UTIL)try{let t=w("bufferutil");ze.exports.mask=function(e,r,n,i,s){s<48?An(e,r,n,i,s):t.mask(e,r,n,i,s)},ze.exports.unmask=function(e,r){e.length<32?Pn(e,r):t.unmask(e,r)}}catch{}});var ta=g((Lg,ea)=>{"use strict";var Xo=Symbol("kDone"),Ln=Symbol("kRun"),On=class{constructor(e){this[Xo]=()=>{this.pending--,this[Ln]()},this.concurrency=e||1/0,this.jobs=[],this.pending=0}add(e){this.jobs.push(e),this[Ln]()}[Ln](){if(this.pending!==this.concurrency&&this.jobs.length){let e=this.jobs.shift();this.pending++,e(this[Xo])}}};ea.exports=On});var Ge=g((Og,oa)=>{"use strict";var wt=w("zlib"),ra=_t(),zf=ta(),{kStatusCode:ia}=re(),$f=Buffer[Symbol.species],Wf=Buffer.from([0,0,255,255]),or=Symbol("permessage-deflate"),ne=Symbol("total-length"),$e=Symbol("callback"),pe=Symbol("buffers"),We=Symbol("error"),na=/^(?:[89]|1[0-5])$/,sr,Rn=class{constructor(e){if(this._options=e||{},this._threshold=this._options.threshold!==void 0?this._options.threshold:1024,this._maxPayload=this._options.maxPayload|0,this._isServer=!!this._options.isServer,this._deflate=null,this._inflate=null,this.params=null,!sr){let r=this._options.concurrencyLimit!==void 0?this._options.concurrencyLimit:10;sr=new zf(r)}}static get extensionName(){return"permessage-deflate"}offer(){let e={};return this._options.serverNoContextTakeover&&(e.server_no_context_takeover=!0),this._options.clientNoContextTakeover&&(e.client_no_context_takeover=!0),this._options.serverMaxWindowBits&&(e.server_max_window_bits=this._options.serverMaxWindowBits),this._options.clientMaxWindowBits?e.client_max_window_bits=this._options.clientMaxWindowBits:this._options.clientMaxWindowBits==null&&(e.client_max_window_bits=!0),e}accept(e){return e=this.normalizeParams(e),this.params=this._isServer?this.acceptAsServer(e):this.acceptAsClient(e),this.params}cleanup(){if(this._inflate&&(this._inflate.close(),this._inflate=null),this._deflate){let e=this._deflate[$e];this._deflate.close(),this._deflate=null,e&&e(new Error("The deflate stream was closed while data was being processed"))}}acceptAsServer(e){let r=this._options,n=e.find(i=>!(r.serverNoContextTakeover===!1&&i.server_no_context_takeover||i.server_max_window_bits&&(r.serverMaxWindowBits===!1||typeof r.serverMaxWindowBits=="number"&&r.serverMaxWindowBits>i.server_max_window_bits)||typeof r.clientMaxWindowBits=="number"&&(typeof i.client_max_window_bits=="number"?r.clientMaxWindowBits>i.client_max_window_bits:!i.client_max_window_bits)));if(!n)throw new Error("None of the extension offers can be accepted");return r.serverNoContextTakeover&&(n.server_no_context_takeover=!0),r.clientNoContextTakeover&&(n.client_no_context_takeover=!0),typeof r.serverMaxWindowBits=="number"&&(n.server_max_window_bits=r.serverMaxWindowBits),typeof r.clientMaxWindowBits=="number"?n.client_max_window_bits=r.clientMaxWindowBits:(n.client_max_window_bits===!0||r.clientMaxWindowBits===!1)&&delete n.client_max_window_bits,n}acceptAsClient(e){let r=e[0];if(this._options.clientNoContextTakeover===!1&&r.client_no_context_takeover)throw new Error('Unexpected parameter "client_no_context_takeover"');if(!r.client_max_window_bits)typeof this._options.clientMaxWindowBits=="number"&&(r.client_max_window_bits=this._options.clientMaxWindowBits);else if(this._options.clientMaxWindowBits===!1||typeof this._options.clientMaxWindowBits=="number"&&r.client_max_window_bits>this._options.clientMaxWindowBits)throw new Error('Unexpected or invalid parameter "client_max_window_bits"');return r}normalizeParams(e){return e.forEach(r=>{Object.keys(r).forEach(n=>{let i=r[n];if(i.length>1)throw new Error(`Parameter "${n}" must have only a single value`);if(i=i[0],n==="client_max_window_bits"){if(i!==!0){if(!na.test(i))throw new TypeError(`Invalid value for parameter "${n}": ${i}`);i=+i}else if(!this._isServer)throw new TypeError(`Invalid value for parameter "${n}": ${i}`)}else if(n==="server_max_window_bits"){if(!na.test(i))throw new TypeError(`Invalid value for parameter "${n}": ${i}`);i=+i}else if(n==="client_no_context_takeover"||n==="server_no_context_takeover"){if(i!==!0)throw new TypeError(`Invalid value for parameter "${n}": ${i}`)}else throw new Error(`Unknown parameter "${n}"`);r[n]=i})}),e}decompress(e,r,n){sr.add(i=>{this._decompress(e,r,(s,o)=>{i(),n(s,o)})})}compress(e,r,n){sr.add(i=>{this._compress(e,r,(s,o)=>{i(),n(s,o)})})}_decompress(e,r,n){let i=this._isServer?"client":"server";if(!this._inflate){let s=`${i}_max_window_bits`,o=typeof this.params[s]!="number"?wt.Z_DEFAULT_WINDOWBITS:this.params[s];this._inflate=wt.createInflateRaw({...this._options.zlibInflateOptions,windowBits:o}),this._inflate[or]=this,this._inflate[ne]=0,this._inflate[pe]=[],this._inflate.on("error",Vf),this._inflate.on("data",sa)}this._inflate[$e]=n,this._inflate.write(e),r&&this._inflate.write(Wf),this._inflate.flush(()=>{let s=this._inflate[We];if(s){this._inflate.close(),this._inflate=null,n(s);return}let o=ra.concat(this._inflate[pe],this._inflate[ne]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[ne]=0,this._inflate[pe]=[],r&&this.params[`${i}_no_context_takeover`]&&this._inflate.reset()),n(null,o)})}_compress(e,r,n){let i=this._isServer?"server":"client";if(!this._deflate){let s=`${i}_max_window_bits`,o=typeof this.params[s]!="number"?wt.Z_DEFAULT_WINDOWBITS:this.params[s];this._deflate=wt.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:o}),this._deflate[ne]=0,this._deflate[pe]=[],this._deflate.on("data",Gf)}this._deflate[$e]=n,this._deflate.write(e),this._deflate.flush(wt.Z_SYNC_FLUSH,()=>{if(!this._deflate)return;let s=ra.concat(this._deflate[pe],this._deflate[ne]);r&&(s=new $f(s.buffer,s.byteOffset,s.length-4)),this._deflate[$e]=null,this._deflate[ne]=0,this._deflate[pe]=[],r&&this.params[`${i}_no_context_takeover`]&&this._deflate.reset(),n(null,s)})}};oa.exports=Rn;function Gf(t){this[pe].push(t),this[ne]+=t.length}function sa(t){if(this[ne]+=t.length,this[or]._maxPayload<1||this[ne]<=this[or]._maxPayload){this[pe].push(t);return}this[We]=new RangeError("Max payload size exceeded"),this[We].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH",this[We][ia]=1009,this.removeListener("data",sa),this.reset()}function Vf(t){if(this[or]._inflate=null,this[We]){this[$e](this[We]);return}t[ia]=1007,this[$e](t)}});var Ve=g((Rg,ar)=>{"use strict";var{isUtf8:aa}=w("buffer"),{hasBlob:jf}=re(),Yf=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,1,1,1,1,1,0,0,1,1,0,1,1,0,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,0,1,0];function Kf(t){return t>=1e3&&t<=1014&&t!==1004&&t!==1005&&t!==1006||t>=3e3&&t<=4999}function Nn(t){let e=t.length,r=0;for(;r<e;)if((t[r]&128)===0)r++;else if((t[r]&224)===192){if(r+1===e||(t[r+1]&192)!==128||(t[r]&254)===192)return!1;r+=2}else if((t[r]&240)===224){if(r+2>=e||(t[r+1]&192)!==128||(t[r+2]&192)!==128||t[r]===224&&(t[r+1]&224)===128||t[r]===237&&(t[r+1]&224)===160)return!1;r+=3}else if((t[r]&248)===240){if(r+3>=e||(t[r+1]&192)!==128||(t[r+2]&192)!==128||(t[r+3]&192)!==128||t[r]===240&&(t[r+1]&240)===128||t[r]===244&&t[r+1]>143||t[r]>244)return!1;r+=4}else return!1;return!0}function Jf(t){return jf&&typeof t=="object"&&typeof t.arrayBuffer=="function"&&typeof t.type=="string"&&typeof t.stream=="function"&&(t[Symbol.toStringTag]==="Blob"||t[Symbol.toStringTag]==="File")}ar.exports={isBlob:Jf,isValidStatusCode:Kf,isValidUTF8:Nn,tokenChars:Yf};if(aa)ar.exports.isValidUTF8=function(t){return t.length<24?Nn(t):aa(t)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{let t=w("utf-8-validate");ar.exports.isValidUTF8=function(e){return e.length<32?Nn(e):t(e)}}catch{}});var Fn=g((Ng,pa)=>{"use strict";var{Writable:Zf}=w("stream"),la=Ge(),{BINARY_TYPES:Qf,EMPTY_BUFFER:ca,kStatusCode:Xf,kWebSocket:eh}=re(),{concat:Mn,toArrayBuffer:th,unmask:rh}=_t(),{isValidStatusCode:nh,isValidUTF8:ua}=Ve(),bt=Buffer[Symbol.species],z=0,fa=1,ha=2,da=3,Un=4,qn=5,lr=6,Dn=class extends Zf{constructor(e={}){super(),this._allowSynchronousEvents=e.allowSynchronousEvents!==void 0?e.allowSynchronousEvents:!0,this._binaryType=e.binaryType||Qf[0],this._extensions=e.extensions||{},this._isServer=!!e.isServer,this._maxBufferedChunks=e.maxBufferedChunks|0,this._maxFragments=e.maxFragments|0,this._maxPayload=e.maxPayload|0,this._skipUTF8Validation=!!e.skipUTF8Validation,this[eh]=void 0,this._bufferedBytes=0,this._buffers=[],this._compressed=!1,this._payloadLength=0,this._mask=void 0,this._fragmented=0,this._masked=!1,this._fin=!1,this._opcode=0,this._totalPayloadLength=0,this._messageLength=0,this._numFragments=0,this._fragments=[],this._errored=!1,this._loop=!1,this._state=z}_write(e,r,n){if(this._opcode===8&&this._state==z)return n();if(this._maxBufferedChunks>0&&this._buffers.length>=this._maxBufferedChunks){n(this.createError(RangeError,"Too many buffered chunks",!1,1008,"WS_ERR_TOO_MANY_BUFFERED_PARTS"));return}this._bufferedBytes+=e.length,this._buffers.push(e),this.startLoop(n)}consume(e){if(this._bufferedBytes-=e,e===this._buffers[0].length)return this._buffers.shift();if(e<this._buffers[0].length){let n=this._buffers[0];return this._buffers[0]=new bt(n.buffer,n.byteOffset+e,n.length-e),new bt(n.buffer,n.byteOffset,e)}let r=Buffer.allocUnsafe(e);do{let n=this._buffers[0],i=r.length-e;e>=n.length?r.set(this._buffers.shift(),i):(r.set(new Uint8Array(n.buffer,n.byteOffset,e),i),this._buffers[0]=new bt(n.buffer,n.byteOffset+e,n.length-e)),e-=n.length}while(e>0);return r}startLoop(e){this._loop=!0;do switch(this._state){case z:this.getInfo(e);break;case fa:this.getPayloadLength16(e);break;case ha:this.getPayloadLength64(e);break;case da:this.getMask();break;case Un:this.getData(e);break;case qn:case lr:this._loop=!1;return}while(this._loop);this._errored||e()}getInfo(e){if(this._bufferedBytes<2){this._loop=!1;return}let r=this._buffers[0];if(r.length>2?(this._bufferedBytes-=2,this._buffers[0]=new bt(r.buffer,r.byteOffset+2,r.length-2)):r=this.consume(2),(r[0]&48)!==0){let i=this.createError(RangeError,"RSV2 and RSV3 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_2_3");e(i);return}let n=(r[0]&64)===64;if(n&&!this._extensions[la.extensionName]){let i=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(i);return}if(this._fin=(r[0]&128)===128,this._opcode=r[0]&15,this._payloadLength=r[1]&127,this._opcode===0){if(n){let i=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(i);return}if(!this._fragmented){let i=this.createError(RangeError,"invalid opcode 0",!0,1002,"WS_ERR_INVALID_OPCODE");e(i);return}this._opcode=this._fragmented}else if(this._opcode===1||this._opcode===2){if(this._fragmented){let i=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");e(i);return}this._compressed=n}else if(this._opcode>7&&this._opcode<11){if(!this._fin){let i=this.createError(RangeError,"FIN must be set",!0,1002,"WS_ERR_EXPECTED_FIN");e(i);return}if(n){let i=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(i);return}if(this._payloadLength>125||this._opcode===8&&this._payloadLength===1){let i=this.createError(RangeError,`invalid payload length ${this._payloadLength}`,!0,1002,"WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH");e(i);return}}else{let i=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");e(i);return}if(!this._fin&&!this._fragmented&&(this._fragmented=this._opcode),this._masked=(r[1]&128)===128,this._isServer){if(!this._masked){let i=this.createError(RangeError,"MASK must be set",!0,1002,"WS_ERR_EXPECTED_MASK");e(i);return}}else if(this._masked){let i=this.createError(RangeError,"MASK must be clear",!0,1002,"WS_ERR_UNEXPECTED_MASK");e(i);return}this._payloadLength===126?this._state=fa:this._payloadLength===127?this._state=ha:this.haveLength(e)}getPayloadLength16(e){if(this._bufferedBytes<2){this._loop=!1;return}this._payloadLength=this.consume(2).readUInt16BE(0),this.haveLength(e)}getPayloadLength64(e){if(this._bufferedBytes<8){this._loop=!1;return}let r=this.consume(8),n=r.readUInt32BE(0);if(n>Math.pow(2,21)-1){let i=this.createError(RangeError,"Unsupported WebSocket frame: payload length > 2^53 - 1",!1,1009,"WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH");e(i);return}this._payloadLength=n*Math.pow(2,32)+r.readUInt32BE(4),this.haveLength(e)}haveLength(e){if(this._payloadLength&&this._opcode<8&&(this._totalPayloadLength+=this._payloadLength,this._totalPayloadLength>this._maxPayload&&this._maxPayload>0)){let r=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");e(r);return}this._masked?this._state=da:this._state=Un}getMask(){if(this._bufferedBytes<4){this._loop=!1;return}this._mask=this.consume(4),this._state=Un}getData(e){let r=ca;if(this._payloadLength){if(this._bufferedBytes<this._payloadLength){this._loop=!1;return}r=this.consume(this._payloadLength),this._masked&&(this._mask[0]|this._mask[1]|this._mask[2]|this._mask[3])!==0&&rh(r,this._mask)}if(this._mask=void 0,this._opcode>7){this.controlMessage(r,e);return}if(this._maxFragments>0&&++this._numFragments>this._maxFragments){let n=this.createError(RangeError,"Too many message fragments",!1,1008,"WS_ERR_TOO_MANY_BUFFERED_PARTS");e(n);return}if(this._compressed){this._state=qn,this.decompress(r,e);return}r.length&&(this._messageLength=this._totalPayloadLength,this._fragments.push(r)),this.dataMessage(e)}decompress(e,r){this._extensions[la.extensionName].decompress(e,this._fin,(i,s)=>{if(i)return r(i);if(s.length){if(this._messageLength+=s.length,this._messageLength>this._maxPayload&&this._maxPayload>0){let o=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");r(o);return}this._fragments.push(s)}this.dataMessage(r),this._state===z&&this.startLoop(r)})}dataMessage(e){if(!this._fin){this._state=z;return}let r=this._messageLength,n=this._fragments;if(this._totalPayloadLength=0,this._messageLength=0,this._fragmented=0,this._numFragments=0,this._fragments=[],this._opcode===2){let i;this._binaryType==="nodebuffer"?i=Mn(n,r):this._binaryType==="arraybuffer"?i=th(Mn(n,r)):this._binaryType==="blob"?i=new Blob(n):i=n,this._allowSynchronousEvents?(this.emit("message",i,!0),this._state=z):(this._state=lr,setImmediate(()=>{this.emit("message",i,!0),this._state=z,this.startLoop(e)}))}else{let i=Mn(n,r);if(!this._skipUTF8Validation&&!ua(i)){let s=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");e(s);return}this._state===qn||this._allowSynchronousEvents?(this.emit("message",i,!1),this._state=z):(this._state=lr,setImmediate(()=>{this.emit("message",i,!1),this._state=z,this.startLoop(e)}))}}controlMessage(e,r){if(this._opcode===8){if(e.length===0)this._loop=!1,this.emit("conclude",1005,ca),this.end();else{let n=e.readUInt16BE(0);if(!nh(n)){let s=this.createError(RangeError,`invalid status code ${n}`,!0,1002,"WS_ERR_INVALID_CLOSE_CODE");r(s);return}let i=new bt(e.buffer,e.byteOffset+2,e.length-2);if(!this._skipUTF8Validation&&!ua(i)){let s=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");r(s);return}this._loop=!1,this.emit("conclude",n,i),this.end()}this._state=z;return}this._allowSynchronousEvents?(this.emit(this._opcode===9?"ping":"pong",e),this._state=z):(this._state=lr,setImmediate(()=>{this.emit(this._opcode===9?"ping":"pong",e),this._state=z,this.startLoop(r)}))}createError(e,r,n,i,s){this._loop=!1,this._errored=!0;let o=new e(n?`Invalid WebSocket frame: ${r}`:r);return Error.captureStackTrace(o,this.createError),o.code=s,o[Xf]=i,o}};pa.exports=Dn});var $n=g((Ug,ya)=>{"use strict";var{Duplex:Mg}=w("stream"),{randomFillSync:ih}=w("crypto"),{types:{isUint8Array:sh}}=w("util"),ga=Ge(),{EMPTY_BUFFER:oh,kWebSocket:ah,NOOP:lh}=re(),{isBlob:je,isValidStatusCode:ch}=Ve(),{mask:ma,toBuffer:Se}=_t(),$=Symbol("kByteLength"),uh=Buffer.alloc(4),cr=8*1024,ve,Ye=cr,G=0,fh=1,hh=2,Hn=class t{constructor(e,r,n){this._extensions=r||{},n&&(this._generateMask=n,this._maskBuffer=Buffer.alloc(4)),this._socket=e,this._firstFragment=!0,this._compress=!1,this._bufferedBytes=0,this._queue=[],this._state=G,this.onerror=lh,this[ah]=void 0}static frame(e,r){let n,i=!1,s=2,o=!1;r.mask&&(n=r.maskBuffer||uh,r.generateMask?r.generateMask(n):(Ye===cr&&(ve===void 0&&(ve=Buffer.alloc(cr)),ih(ve,0,cr),Ye=0),n[0]=ve[Ye++],n[1]=ve[Ye++],n[2]=ve[Ye++],n[3]=ve[Ye++]),o=(n[0]|n[1]|n[2]|n[3])===0,s=6);let a;typeof e=="string"?(!r.mask||o)&&r[$]!==void 0?a=r[$]:(e=Buffer.from(e),a=e.length):(a=e.length,i=r.mask&&r.readOnly&&!o);let l=a;a>=65536?(s+=8,l=127):a>125&&(s+=2,l=126);let c=Buffer.allocUnsafe(i?a+s:s);return c[0]=r.fin?r.opcode|128:r.opcode,r.rsv1&&(c[0]|=64),c[1]=l,l===126?c.writeUInt16BE(a,2):l===127&&(c[2]=c[3]=0,c.writeUIntBE(a,4,6)),r.mask?(c[1]|=128,c[s-4]=n[0],c[s-3]=n[1],c[s-2]=n[2],c[s-1]=n[3],a?o?[c,e]:i?(ma(e,n,c,s,a),[c]):(ma(e,n,e,0,a),[c,e]):[c]):a?[c,e]:[c]}close(e,r,n,i){let s;if(e===void 0)s=oh;else{if(typeof e!="number"||!ch(e))throw new TypeError("First argument must be a valid error code number");if(r===void 0||!r.length)s=Buffer.allocUnsafe(2),s.writeUInt16BE(e,0);else{let a=Buffer.byteLength(r);if(a>123)throw new RangeError("The message must not be greater than 123 bytes");if(s=Buffer.allocUnsafe(2+a),s.writeUInt16BE(e,0),typeof r=="string")s.write(r,2);else if(sh(r))s.set(r,2);else throw new TypeError("Second argument must be a string or a Uint8Array")}}let o={[$]:s.length,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};this._state!==G?this.enqueue([this.dispatch,s,!1,o,i]):this.sendFrame(t.frame(s,o),i)}ping(e,r,n){let i,s;if(typeof e=="string"?(i=Buffer.byteLength(e),s=!1):je(e)?(i=e.size,s=!1):(e=Se(e),i=e.length,s=Se.readOnly),i>125)throw new RangeError("The data size must not be greater than 125 bytes");let o={[$]:i,fin:!0,generateMask:this._generateMask,mask:r,maskBuffer:this._maskBuffer,opcode:9,readOnly:s,rsv1:!1};je(e)?this._state!==G?this.enqueue([this.getBlobData,e,!1,o,n]):this.getBlobData(e,!1,o,n):this._state!==G?this.enqueue([this.dispatch,e,!1,o,n]):this.sendFrame(t.frame(e,o),n)}pong(e,r,n){let i,s;if(typeof e=="string"?(i=Buffer.byteLength(e),s=!1):je(e)?(i=e.size,s=!1):(e=Se(e),i=e.length,s=Se.readOnly),i>125)throw new RangeError("The data size must not be greater than 125 bytes");let o={[$]:i,fin:!0,generateMask:this._generateMask,mask:r,maskBuffer:this._maskBuffer,opcode:10,readOnly:s,rsv1:!1};je(e)?this._state!==G?this.enqueue([this.getBlobData,e,!1,o,n]):this.getBlobData(e,!1,o,n):this._state!==G?this.enqueue([this.dispatch,e,!1,o,n]):this.sendFrame(t.frame(e,o),n)}send(e,r,n){let i=this._extensions[ga.extensionName],s=r.binary?2:1,o=r.compress,a,l;typeof e=="string"?(a=Buffer.byteLength(e),l=!1):je(e)?(a=e.size,l=!1):(e=Se(e),a=e.length,l=Se.readOnly),this._firstFragment?(this._firstFragment=!1,o&&i&&i.params[i._isServer?"server_no_context_takeover":"client_no_context_takeover"]&&(o=a>=i._threshold),this._compress=o):(o=!1,s=0),r.fin&&(this._firstFragment=!0);let c={[$]:a,fin:r.fin,generateMask:this._generateMask,mask:r.mask,maskBuffer:this._maskBuffer,opcode:s,readOnly:l,rsv1:o};je(e)?this._state!==G?this.enqueue([this.getBlobData,e,this._compress,c,n]):this.getBlobData(e,this._compress,c,n):this._state!==G?this.enqueue([this.dispatch,e,this._compress,c,n]):this.dispatch(e,this._compress,c,n)}getBlobData(e,r,n,i){this._bufferedBytes+=n[$],this._state=hh,e.arrayBuffer().then(s=>{if(this._socket.destroyed){let a=new Error("The socket was closed while the blob was being read");process.nextTick(zn,this,a,i);return}this._bufferedBytes-=n[$];let o=Se(s);r?this.dispatch(o,r,n,i):(this._state=G,this.sendFrame(t.frame(o,n),i),this.dequeue())}).catch(s=>{process.nextTick(dh,this,s,i)})}dispatch(e,r,n,i){if(!r){this.sendFrame(t.frame(e,n),i);return}let s=this._extensions[ga.extensionName];this._bufferedBytes+=n[$],this._state=fh,s.compress(e,n.fin,(o,a)=>{if(this._socket.destroyed){let l=new Error("The socket was closed while data was being compressed");zn(this,l,i);return}this._bufferedBytes-=n[$],this._state=G,n.readOnly=!1,this.sendFrame(t.frame(a,n),i),this.dequeue()})}dequeue(){for(;this._state===G&&this._queue.length;){let e=this._queue.shift();this._bufferedBytes-=e[3][$],Reflect.apply(e[0],this,e.slice(1))}}enqueue(e){this._bufferedBytes+=e[3][$],this._queue.push(e)}sendFrame(e,r){e.length===2?(this._socket.cork(),this._socket.write(e[0]),this._socket.write(e[1],r),this._socket.uncork()):this._socket.write(e[0],r)}};ya.exports=Hn;function zn(t,e,r){typeof r=="function"&&r(e);for(let n=0;n<t._queue.length;n++){let i=t._queue[n],s=i[i.length-1];typeof s=="function"&&s(e)}}function dh(t,e,r){zn(t,e,r),t.onerror(e)}});var Ca=g((qg,Ta)=>{"use strict";var{kForOnEventAttribute:Et,kListener:Wn}=re(),_a=Symbol("kCode"),wa=Symbol("kData"),ba=Symbol("kError"),Ea=Symbol("kMessage"),xa=Symbol("kReason"),Ke=Symbol("kTarget"),Sa=Symbol("kType"),va=Symbol("kWasClean"),ie=class{constructor(e){this[Ke]=null,this[Sa]=e}get target(){return this[Ke]}get type(){return this[Sa]}};Object.defineProperty(ie.prototype,"target",{enumerable:!0});Object.defineProperty(ie.prototype,"type",{enumerable:!0});var Te=class extends ie{constructor(e,r={}){super(e),this[_a]=r.code===void 0?0:r.code,this[xa]=r.reason===void 0?"":r.reason,this[va]=r.wasClean===void 0?!1:r.wasClean}get code(){return this[_a]}get reason(){return this[xa]}get wasClean(){return this[va]}};Object.defineProperty(Te.prototype,"code",{enumerable:!0});Object.defineProperty(Te.prototype,"reason",{enumerable:!0});Object.defineProperty(Te.prototype,"wasClean",{enumerable:!0});var Je=class extends ie{constructor(e,r={}){super(e),this[ba]=r.error===void 0?null:r.error,this[Ea]=r.message===void 0?"":r.message}get error(){return this[ba]}get message(){return this[Ea]}};Object.defineProperty(Je.prototype,"error",{enumerable:!0});Object.defineProperty(Je.prototype,"message",{enumerable:!0});var xt=class extends ie{constructor(e,r={}){super(e),this[wa]=r.data===void 0?null:r.data}get data(){return this[wa]}};Object.defineProperty(xt.prototype,"data",{enumerable:!0});var ph={addEventListener(t,e,r={}){for(let i of this.listeners(t))if(!r[Et]&&i[Wn]===e&&!i[Et])return;let n;if(t==="message")n=function(s,o){let a=new xt("message",{data:o?s:s.toString()});a[Ke]=this,ur(e,this,a)};else if(t==="close")n=function(s,o){let a=new Te("close",{code:s,reason:o.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});a[Ke]=this,ur(e,this,a)};else if(t==="error")n=function(s){let o=new Je("error",{error:s,message:s.message});o[Ke]=this,ur(e,this,o)};else if(t==="open")n=function(){let s=new ie("open");s[Ke]=this,ur(e,this,s)};else return;n[Et]=!!r[Et],n[Wn]=e,r.once?this.once(t,n):this.on(t,n)},removeEventListener(t,e){for(let r of this.listeners(t))if(r[Wn]===e&&!r[Et]){this.removeListener(t,r);break}}};Ta.exports={CloseEvent:Te,ErrorEvent:Je,Event:ie,EventTarget:ph,MessageEvent:xt};function ur(t,e,r){typeof t=="object"&&t.handleEvent?t.handleEvent.call(t,r):t.call(e,r)}});var fr=g((Dg,ka)=>{"use strict";var{tokenChars:St}=Ve();function Q(t,e,r){t[e]===void 0?t[e]=[r]:t[e].push(r)}function gh(t){let e=Object.create(null),r=Object.create(null),n=!1,i=!1,s=!1,o,a,l=-1,c=-1,u=-1,f=0;for(;f<t.length;f++)if(c=t.charCodeAt(f),o===void 0)if(u===-1&&St[c]===1)l===-1&&(l=f);else if(f!==0&&(c===32||c===9))u===-1&&l!==-1&&(u=f);else if(c===59||c===44){if(l===-1)throw new SyntaxError(`Unexpected character at index ${f}`);u===-1&&(u=f);let d=t.slice(l,u);c===44?(Q(e,d,r),r=Object.create(null)):o=d,l=u=-1}else throw new SyntaxError(`Unexpected character at index ${f}`);else if(a===void 0)if(u===-1&&St[c]===1)l===-1&&(l=f);else if(c===32||c===9)u===-1&&l!==-1&&(u=f);else if(c===59||c===44){if(l===-1)throw new SyntaxError(`Unexpected character at index ${f}`);u===-1&&(u=f),Q(r,t.slice(l,u),!0),c===44&&(Q(e,o,r),r=Object.create(null),o=void 0),l=u=-1}else if(c===61&&l!==-1&&u===-1)a=t.slice(l,f),l=u=-1;else throw new SyntaxError(`Unexpected character at index ${f}`);else if(i){if(St[c]!==1)throw new SyntaxError(`Unexpected character at index ${f}`);l===-1?l=f:n||(n=!0),i=!1}else if(s)if(St[c]===1)l===-1&&(l=f);else if(c===34&&l!==-1)s=!1,u=f;else if(c===92)i=!0;else throw new SyntaxError(`Unexpected character at index ${f}`);else if(c===34&&t.charCodeAt(f-1)===61)s=!0;else if(u===-1&&St[c]===1)l===-1&&(l=f);else if(l!==-1&&(c===32||c===9))u===-1&&(u=f);else if(c===59||c===44){if(l===-1)throw new SyntaxError(`Unexpected character at index ${f}`);u===-1&&(u=f);let d=t.slice(l,u);n&&(d=d.replace(/\\/g,""),n=!1),Q(r,a,d),c===44&&(Q(e,o,r),r=Object.create(null),o=void 0),a=void 0,l=u=-1}else throw new SyntaxError(`Unexpected character at index ${f}`);if(l===-1||s||c===32||c===9)throw new SyntaxError("Unexpected end of input");u===-1&&(u=f);let h=t.slice(l,u);return o===void 0?Q(e,h,r):(a===void 0?Q(r,h,!0):n?Q(r,a,h.replace(/\\/g,"")):Q(r,a,h),Q(e,o,r)),e}function mh(t){return Object.keys(t).map(e=>{let r=t[e];return Array.isArray(r)||(r=[r]),r.map(n=>[e].concat(Object.keys(n).map(i=>{let s=n[i];return Array.isArray(s)||(s=[s]),s.map(o=>o===!0?i:`${i}=${o}`).join("; ")})).join("; ")).join(", ")}).join(", ")}ka.exports={format:mh,parse:gh}});var pr=g((zg,Da)=>{"use strict";var yh=w("events"),_h=w("https"),wh=w("http"),Ba=w("net"),Ia=w("querystring"),bh=w("tls"),{randomBytes:Eh,createHash:xh}=w("crypto"),{Duplex:Fg,Readable:Hg}=w("stream"),{URL:hr}=w("url"),ge=Ge(),Sh=Fn(),vh=$n(),{isBlob:Th}=Ve(),{BINARY_TYPES:Aa,CLOSE_TIMEOUT:Ch,EMPTY_BUFFER:vt,GUID:kh,kForOnEventAttribute:Gn,kListener:Ih,kStatusCode:Ah,kWebSocket:A,NOOP:Ph}=re(),{EventTarget:{addEventListener:Bh,removeEventListener:Lh}}=Ca(),{format:Oh,parse:Rh}=fr(),{toBuffer:Nh}=_t(),La=Symbol("kAborted"),Vn=[8,13],se=["CONNECTING","OPEN","CLOSING","CLOSED"],Mh=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/,v=class t extends yh{constructor(e,r,n){super(),this._binaryType=Aa[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=vt,this._closeTimer=null,this._errorEmitted=!1,this._extensions={},this._paused=!1,this._protocol="",this._readyState=t.CONNECTING,this._receiver=null,this._sender=null,this._socket=null,e!==null?(this._bufferedAmount=0,this._isServer=!1,this._redirects=0,r===void 0?!n||n.protocols===void 0?r=[]:Array.isArray(n.protocols)?r=n.protocols:r=[n.protocols]:Array.isArray(r)||(typeof r=="object"&&r!==null?(n=r,n.protocols===void 0?r=[]:Array.isArray(n.protocols)?r=n.protocols:r=[n.protocols]):r=[r]),n=Oa(this,e,r,n)):this._isServer=!0,n.autoPong&&(this._autoPong=!0,this._autoPongComplete=()=>Wh(this),this._pendingAutoPongs=0,this._maxPendingAutoPongs=n.maxPendingAutoPongs|0),this._closeTimeout=n.closeTimeout}get binaryType(){return this._binaryType}set binaryType(e){Aa.includes(e)&&(this._binaryType=e,this._receiver&&(this._receiver._binaryType=e))}get bufferedAmount(){return this._socket?this._socket._writableState.length+this._sender._bufferedBytes:this._bufferedAmount}get extensions(){return Object.keys(this._extensions).join()}get isPaused(){return this._paused}get onclose(){return null}get onerror(){return null}get onopen(){return null}get onmessage(){return null}get protocol(){return this._protocol}get readyState(){return this._readyState}get url(){return this._url}setSocket(e,r,n){let i=new Sh({allowSynchronousEvents:n.allowSynchronousEvents,binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxBufferedChunks:n.maxBufferedChunks,maxFragments:n.maxFragments,maxPayload:n.maxPayload,skipUTF8Validation:n.skipUTF8Validation}),s=new vh(e,this._extensions,n.generateMask);this._receiver=i,this._sender=s,this._socket=e,i[A]=this,s[A]=this,e[A]=this,i.on("conclude",Dh),i.on("drain",Fh),i.on("error",Hh),i.on("message",zh),i.on("ping",$h),i.on("pong",Gh),s.onerror=Vh,e.setTimeout&&e.setTimeout(0),e.setNoDelay&&e.setNoDelay(),r.length>0&&e.unshift(r),e.on("close",Ma),e.on("data",dr),e.on("end",Ua),e.on("error",qa),this._readyState=t.OPEN,this.emit("open")}emitClose(){if(!this._socket){this._readyState=t.CLOSED,this.emit("close",this._closeCode,this._closeMessage);return}this._extensions[ge.extensionName]&&this._extensions[ge.extensionName].cleanup(),this._receiver.removeAllListeners(),this._readyState=t.CLOSED,this.emit("close",this._closeCode,this._closeMessage)}close(e,r){if(this.readyState!==t.CLOSED){if(this.readyState===t.CONNECTING){M(this,this._req,"WebSocket was closed before the connection was established");return}if(this.readyState===t.CLOSING){this._closeFrameSent&&(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end();return}this._sender.close(e,r,!this._isServer,n=>{n||(this._closeFrameSent=!0,(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end())}),this._readyState=t.CLOSING,Na(this)}}pause(){this.readyState===t.CONNECTING||this.readyState===t.CLOSED||(this._paused=!0,this._socket.pause())}ping(e,r,n){if(this.readyState===t.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof e=="function"?(n=e,e=r=void 0):typeof r=="function"&&(n=r,r=void 0),typeof e=="number"&&(e=e.toString()),this.readyState!==t.OPEN){jn(this,e,n);return}r===void 0&&(r=!this._isServer),this._sender.ping(e||vt,r,n)}pong(e,r,n){if(this.readyState===t.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof e=="function"?(n=e,e=r=void 0):typeof r=="function"&&(n=r,r=void 0),typeof e=="number"&&(e=e.toString()),this.readyState!==t.OPEN){jn(this,e,n);return}r===void 0&&(r=!this._isServer),this._sender.pong(e||vt,r,n)}resume(){this.readyState===t.CONNECTING||this.readyState===t.CLOSED||(this._paused=!1,this._receiver._writableState.needDrain||this._socket.resume())}send(e,r,n){if(this.readyState===t.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof r=="function"&&(n=r,r={}),typeof e=="number"&&(e=e.toString()),this.readyState!==t.OPEN){jn(this,e,n);return}let i={binary:typeof e!="string",mask:!this._isServer,compress:!0,fin:!0,...r};this._extensions[ge.extensionName]||(i.compress=!1),this._sender.send(e||vt,i,n)}terminate(){if(this.readyState!==t.CLOSED){if(this.readyState===t.CONNECTING){M(this,this._req,"WebSocket was closed before the connection was established");return}this._socket&&(this._readyState=t.CLOSING,this._socket.destroy())}}};Object.defineProperty(v,"CONNECTING",{enumerable:!0,value:se.indexOf("CONNECTING")});Object.defineProperty(v.prototype,"CONNECTING",{enumerable:!0,value:se.indexOf("CONNECTING")});Object.defineProperty(v,"OPEN",{enumerable:!0,value:se.indexOf("OPEN")});Object.defineProperty(v.prototype,"OPEN",{enumerable:!0,value:se.indexOf("OPEN")});Object.defineProperty(v,"CLOSING",{enumerable:!0,value:se.indexOf("CLOSING")});Object.defineProperty(v.prototype,"CLOSING",{enumerable:!0,value:se.indexOf("CLOSING")});Object.defineProperty(v,"CLOSED",{enumerable:!0,value:se.indexOf("CLOSED")});Object.defineProperty(v.prototype,"CLOSED",{enumerable:!0,value:se.indexOf("CLOSED")});["binaryType","bufferedAmount","extensions","isPaused","protocol","readyState","url"].forEach(t=>{Object.defineProperty(v.prototype,t,{enumerable:!0})});["open","error","close","message"].forEach(t=>{Object.defineProperty(v.prototype,`on${t}`,{enumerable:!0,get(){for(let e of this.listeners(t))if(e[Gn])return e[Ih];return null},set(e){for(let r of this.listeners(t))if(r[Gn]){this.removeListener(t,r);break}typeof e=="function"&&this.addEventListener(t,e,{[Gn]:!0})}})});v.prototype.addEventListener=Bh;v.prototype.removeEventListener=Lh;Da.exports=v;function Oa(t,e,r,n){let i={allowSynchronousEvents:!0,autoPong:!0,closeTimeout:Ch,protocolVersion:Vn[1],maxBufferedChunks:262144,maxFragments:16384,maxPayload:104857600,maxPendingAutoPongs:60,skipUTF8Validation:!1,perMessageDeflate:!0,followRedirects:!1,maxRedirects:10,...n,socketPath:void 0,hostname:void 0,protocol:void 0,protocols:void 0,timeout:void 0,method:"GET",host:void 0,path:void 0,port:void 0};if(!Vn.includes(i.protocolVersion))throw new RangeError(`Unsupported protocol version: ${i.protocolVersion} (supported versions: ${Vn.join(", ")})`);let s;if(e instanceof hr)s=e;else try{s=new hr(e)}catch{throw new SyntaxError(`Invalid URL: ${e}`)}(s.protocol==="http:"||s.protocol==="https:")&&(s=new hr(s),s.protocol=s.protocol==="http:"?"ws:":"wss:"),t._url=s.href;let o=s.protocol==="wss:",a=s.protocol==="ws+unix:",l;if(s.protocol!=="ws:"&&!o&&!a?l=`The URL's protocol must be one of "ws:", "wss:", "http:", "https:", or "ws+unix:"`:a&&!s.pathname?l="The URL's pathname is empty":s.hash&&(l="The URL contains a fragment identifier"),l){let p=new SyntaxError(l);if(t._redirects===0)throw p;Tt(t,p);return}let c=o?443:80,u=Eh(16).toString("base64"),f=o?_h.request:wh.request,h=new Set,d;if(i.createConnection=i.createConnection||(o?qh:Uh),i.defaultPort=i.defaultPort||c,i.port=s.port||c,i.host=s.hostname.startsWith("[")?s.hostname.slice(1,-1):s.hostname,i.headers={...i.headers,"Sec-WebSocket-Version":i.protocolVersion,"Sec-WebSocket-Key":u,Connection:"Upgrade",Upgrade:"websocket"},i.path=s.pathname+s.search,i.timeout=i.handshakeTimeout,i.perMessageDeflate&&(d=new ge({...i.perMessageDeflate,isServer:!1,maxPayload:i.maxPayload}),i.headers["Sec-WebSocket-Extensions"]=Oh({[ge.extensionName]:d.offer()})),r.length){for(let p of r){if(typeof p!="string"||!Mh.test(p)||h.has(p))throw new SyntaxError("An invalid or duplicated subprotocol was specified");h.add(p)}i.headers["Sec-WebSocket-Protocol"]=r.join(",")}if(i.origin&&(i.protocolVersion<13?i.headers["Sec-WebSocket-Origin"]=i.origin:i.headers.Origin=i.origin),s.username||s.password){let p=Ia.unescape(s.username),y=Ia.unescape(s.password);i.auth=`${p}:${y}`}if(a){let p=i.path.indexOf(":");p===-1?(i.socketPath=i.path,i.path=""):(i.socketPath=i.path.slice(0,p),i.path=i.path.slice(p+1))}let m;if(i.followRedirects){if(t._redirects===0){t._originalIpc=a,t._originalSecure=o,t._originalHostOrSocketPath=a?i.socketPath:s.host;let p=n&&n.headers;if(n={...n,headers:{}},p)for(let[y,_]of Object.entries(p))n.headers[y.toLowerCase()]=_}else if(t.listenerCount("redirect")===0){let p=a?t._originalIpc?i.socketPath===t._originalHostOrSocketPath:!1:t._originalIpc?!1:s.host===t._originalHostOrSocketPath;(!p||t._originalSecure&&!o)&&(delete i.headers.authorization,delete i.headers.cookie,p||delete i.headers.host,i.auth=void 0)}i.auth&&!n.headers.authorization&&(n.headers.authorization="Basic "+Buffer.from(i.auth).toString("base64"));try{m=t._req=f(i)}catch(p){if(t._redirects===0)throw p;Tt(t,p);return}t._redirects&&t.emit("redirect",t.url,m)}else m=t._req=f(i);return i.timeout&&m.on("timeout",()=>{M(t,m,"Opening handshake has timed out")}),m.on("error",p=>{m===null||m[La]||(m=t._req=null,Tt(t,p))}),m.on("response",p=>{let y=p.headers.location,_=p.statusCode;if(y&&i.followRedirects&&_>=300&&_<400){if(++t._redirects>i.maxRedirects){M(t,m,"Maximum redirects exceeded");return}m.abort();let B;try{B=new hr(y,e)}catch{let S=new SyntaxError(`Invalid URL: ${y}`);Tt(t,S);return}Oa(t,B,r,n)}else t.emit("unexpected-response",m,p)||M(t,m,`Unexpected server response: ${p.statusCode}`)}),m.on("upgrade",(p,y,_)=>{if(t.emit("upgrade",p),t.readyState!==v.CONNECTING)return;m=t._req=null;let B=p.headers.upgrade;if(B===void 0||B.toLowerCase()!=="websocket"){M(t,y,"Invalid Upgrade header");return}let O=xh("sha1").update(u+kh).digest("base64");if(p.headers["sec-websocket-accept"]!==O){M(t,y,"Invalid Sec-WebSocket-Accept header");return}let S=p.headers["sec-websocket-protocol"],T;if(S!==void 0?h.size?h.has(S)||(T="Server sent an invalid subprotocol"):T="Server sent a subprotocol but none was requested":h.size&&(T="Server sent no subprotocol"),T){M(t,y,T);return}S&&(t._protocol=S);let E=p.headers["sec-websocket-extensions"];if(E!==void 0){if(!d){M(t,y,"Server sent a Sec-WebSocket-Extensions header but no extension was requested");return}let U;try{U=Rh(E)}catch{M(t,y,"Invalid Sec-WebSocket-Extensions header");return}let Ae=Object.keys(U);if(Ae.length!==1||Ae[0]!==ge.extensionName){M(t,y,"Server indicated an extension that was not requested");return}try{d.accept(U[ge.extensionName])}catch{M(t,y,"Invalid Sec-WebSocket-Extensions header");return}t._extensions[ge.extensionName]=d}t.setSocket(y,_,{allowSynchronousEvents:i.allowSynchronousEvents,generateMask:i.generateMask,maxBufferedChunks:i.maxBufferedChunks,maxFragments:i.maxFragments,maxPayload:i.maxPayload,skipUTF8Validation:i.skipUTF8Validation})}),i.finishRequest?i.finishRequest(m,t):m.end(),i}function Tt(t,e){t._readyState=v.CLOSING,t._errorEmitted=!0,t.emit("error",e),t.emitClose()}function Uh(t){return t.path=t.socketPath,Ba.connect(t)}function qh(t){return t.path=void 0,!t.servername&&t.servername!==""&&(t.servername=Ba.isIP(t.host)?"":t.host),bh.connect(t)}function M(t,e,r){t._readyState=v.CLOSING;let n=new Error(r);Error.captureStackTrace(n,M),e.setHeader?(e[La]=!0,e.abort(),e.socket&&!e.socket.destroyed&&e.socket.destroy(),process.nextTick(Tt,t,n)):(e.destroy(n),e.once("error",t.emit.bind(t,"error")),e.once("close",t.emitClose.bind(t)))}function jn(t,e,r){if(e){let n=Th(e)?e.size:Nh(e).length;t._socket?t._sender._bufferedBytes+=n:t._bufferedAmount+=n}if(r){let n=new Error(`WebSocket is not open: readyState ${t.readyState} (${se[t.readyState]})`);process.nextTick(r,n)}}function Dh(t,e){let r=this[A];r._closeFrameReceived=!0,r._closeCode=t,e.length===0?r._closeMessage=vt:(r._closeMessage=Buffer.allocUnsafeSlow(e.length),r._closeMessage.set(e)),r._socket[A]!==void 0&&(r._socket.removeListener("data",dr),process.nextTick(Ra,r._socket),t===1005?r.close():r.close(t,e))}function Fh(){let t=this[A];t.isPaused||t._socket.resume()}function Hh(t){let e=this[A];e._socket[A]!==void 0&&(e._socket.removeListener("data",dr),process.nextTick(Ra,e._socket),e.close(t[Ah])),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",t))}function Pa(){this[A].emitClose()}function zh(t,e){this[A].emit("message",t,e)}function $h(t){let e=this[A];e._autoPong&&e.readyState===v.OPEN&&(e._maxPendingAutoPongs>0&&e._pendingAutoPongs>=e._maxPendingAutoPongs?e.terminate():(e._pendingAutoPongs++,e.pong(t,!this._isServer,e._autoPongComplete))),e.emit("ping",t)}function Wh(t){t._pendingAutoPongs--}function Gh(t){this[A].emit("pong",t)}function Ra(t){t.resume()}function Vh(t){let e=this[A];e.readyState!==v.CLOSED&&(e.readyState===v.OPEN&&(e._readyState=v.CLOSING,Na(e)),this._socket.end(),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",t)))}function Na(t){t._closeTimer=setTimeout(t._socket.destroy.bind(t._socket),t._closeTimeout)}function Ma(){let t=this[A];if(this.removeListener("close",Ma),this.removeListener("data",dr),this.removeListener("end",Ua),t._readyState=v.CLOSING,!this._readableState.endEmitted&&!t._closeFrameReceived&&!t._receiver._writableState.errorEmitted&&this._readableState.length!==0){let e=this.read(this._readableState.length);t._receiver.write(e)}t._receiver.end(),this[A]=void 0,clearTimeout(t._closeTimer),t._receiver._writableState.finished||t._receiver._writableState.errorEmitted?t.emitClose():(t._receiver.on("error",Pa),t._receiver.on("finish",Pa))}function dr(t){this[A]._receiver.write(t)||this.pause()}function Ua(){let t=this[A];t._readyState=v.CLOSING,t._receiver.end(),this.end()}function qa(){let t=this[A];this.removeListener("error",qa),this.on("error",Ph),t&&(t._readyState=v.CLOSING,this.destroy())}});var $a=g((Wg,za)=>{"use strict";var $g=pr(),{Duplex:jh}=w("stream");function Fa(t){t.emit("close")}function Yh(){!this.destroyed&&this._writableState.finished&&this.destroy()}function Ha(t){this.removeListener("error",Ha),this.destroy(),this.listenerCount("error")===0&&this.emit("error",t)}function Kh(t,e){let r=!0,n=new jh({...e,autoDestroy:!1,emitClose:!1,objectMode:!1,writableObjectMode:!1});return t.on("message",function(s,o){let a=!o&&n._readableState.objectMode?s.toString():s;n.push(a)||t.pause()}),t.once("error",function(s){n.destroyed||(r=!1,n.destroy(s))}),t.once("close",function(){n.destroyed||n.push(null)}),n._destroy=function(i,s){if(t.readyState===t.CLOSED){s(i),process.nextTick(Fa,n);return}let o=!1;t.once("error",function(l){o=!0,s(l)}),t.once("close",function(){o||s(i),process.nextTick(Fa,n)}),r&&t.terminate()},n._final=function(i){if(t.readyState===t.CONNECTING){t.once("open",function(){n._final(i)});return}t._socket!==null&&(t._socket._writableState.finished?(i(),n._readableState.endEmitted&&n.destroy()):(t._socket.once("finish",function(){i()}),t.close()))},n._read=function(){t.isPaused&&t.resume()},n._write=function(i,s,o){if(t.readyState===t.CONNECTING){t.once("open",function(){n._write(i,s,o)});return}t.send(i,o)},n.on("end",Yh),n.on("error",Ha),n}za.exports=Kh});var Yn=g((Gg,Wa)=>{"use strict";var{tokenChars:Jh}=Ve();function Zh(t){let e=new Set,r=-1,n=-1,i=0;for(i;i<t.length;i++){let o=t.charCodeAt(i);if(n===-1&&Jh[o]===1)r===-1&&(r=i);else if(i!==0&&(o===32||o===9))n===-1&&r!==-1&&(n=i);else if(o===44){if(r===-1)throw new SyntaxError(`Unexpected character at index ${i}`);n===-1&&(n=i);let a=t.slice(r,n);if(e.has(a))throw new SyntaxError(`The "${a}" subprotocol is duplicated`);e.add(a),r=n=-1}else throw new SyntaxError(`Unexpected character at index ${i}`)}if(r===-1||n!==-1)throw new SyntaxError("Unexpected end of input");let s=t.slice(r,i);if(e.has(s))throw new SyntaxError(`The "${s}" subprotocol is duplicated`);return e.add(s),e}Wa.exports={parse:Zh}});var Za=g((jg,Ja)=>{"use strict";var Qh=w("events"),gr=w("http"),{Duplex:Vg}=w("stream"),{createHash:Xh}=w("crypto"),Ga=fr(),Ce=Ge(),ed=Yn(),td=pr(),{CLOSE_TIMEOUT:rd,GUID:nd,kWebSocket:id}=re(),sd=/^[+/0-9A-Za-z]{22}==$/,Va=0,ja=1,Ka=2,Kn=class extends Qh{constructor(e,r){if(super(),e={allowSynchronousEvents:!0,autoPong:!0,maxBufferedChunks:256*1024,maxFragments:16*1024,maxPayload:100*1024*1024,maxPendingAutoPongs:60,skipUTF8Validation:!1,perMessageDeflate:!1,handleProtocols:null,clientTracking:!0,closeTimeout:rd,verifyClient:null,noServer:!1,backlog:null,server:null,host:null,path:null,port:null,WebSocket:td,...e},e.port==null&&!e.server&&!e.noServer||e.port!=null&&(e.server||e.noServer)||e.server&&e.noServer)throw new TypeError('One and only one of the "port", "server", or "noServer" options must be specified');if(e.port!=null?(this._server=gr.createServer((n,i)=>{let s=gr.STATUS_CODES[426];i.writeHead(426,{"Content-Length":s.length,"Content-Type":"text/plain"}),i.end(s)}),this._server.listen(e.port,e.host,e.backlog,r)):e.server&&(this._server=e.server),this._server){let n=this.emit.bind(this,"connection");this._removeListeners=od(this._server,{listening:this.emit.bind(this,"listening"),error:this.emit.bind(this,"error"),upgrade:(i,s,o)=>{this.handleUpgrade(i,s,o,n)}})}e.perMessageDeflate===!0&&(e.perMessageDeflate={}),e.clientTracking&&(this.clients=new Set,this._shouldEmitClose=!1),this.options=e,this._state=Va}address(){if(this.options.noServer)throw new Error('The server is operating in "noServer" mode');return this._server?this._server.address():null}close(e){if(this._state===Ka){e&&this.once("close",()=>{e(new Error("The server is not running"))}),process.nextTick(Ct,this);return}if(e&&this.once("close",e),this._state!==ja)if(this._state=ja,this.options.noServer||this.options.server)this._server&&(this._removeListeners(),this._removeListeners=this._server=null),this.clients?this.clients.size?this._shouldEmitClose=!0:process.nextTick(Ct,this):process.nextTick(Ct,this);else{let r=this._server;this._removeListeners(),this._removeListeners=this._server=null,r.close(()=>{Ct(this)})}}shouldHandle(e){if(this.options.path){let r=e.url.indexOf("?");if((r!==-1?e.url.slice(0,r):e.url)!==this.options.path)return!1}return!0}handleUpgrade(e,r,n,i){r.on("error",Ya);let s=e.headers["sec-websocket-key"],o=e.headers.upgrade,a=e.headers["sec-websocket-version"];if(e.method!=="GET"){ke(this,e,r,405,"Invalid HTTP method");return}if(o===void 0||o.toLowerCase()!=="websocket"){ke(this,e,r,400,"Invalid Upgrade header");return}if(s===void 0||!sd.test(s)){ke(this,e,r,400,"Missing or invalid Sec-WebSocket-Key header");return}if(a!=="13"&&a!=="8"){ke(this,e,r,400,"Missing or invalid Sec-WebSocket-Version header",{"Sec-WebSocket-Version":"13, 8"});return}if(!this.shouldHandle(e)){kt(r,400);return}let l=e.headers["sec-websocket-protocol"],c=new Set;if(l!==void 0)try{c=ed.parse(l)}catch{ke(this,e,r,400,"Invalid Sec-WebSocket-Protocol header");return}let u=e.headers["sec-websocket-extensions"],f={};if(this.options.perMessageDeflate&&u!==void 0){let h=new Ce({...this.options.perMessageDeflate,isServer:!0,maxPayload:this.options.maxPayload});try{let d=Ga.parse(u);d[Ce.extensionName]&&(h.accept(d[Ce.extensionName]),f[Ce.extensionName]=h)}catch{ke(this,e,r,400,"Invalid or unacceptable Sec-WebSocket-Extensions header");return}}if(this.options.verifyClient){let h={origin:e.headers[`${a==="8"?"sec-websocket-origin":"origin"}`],secure:!!(e.socket.authorized||e.socket.encrypted),req:e};if(this.options.verifyClient.length===2){this.options.verifyClient(h,(d,m,p,y)=>{if(!d)return kt(r,m||401,p,y);this.completeUpgrade(f,s,c,e,r,n,i)});return}if(!this.options.verifyClient(h))return kt(r,401)}this.completeUpgrade(f,s,c,e,r,n,i)}completeUpgrade(e,r,n,i,s,o,a){if(!s.readable||!s.writable)return s.destroy();if(s[id])throw new Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");if(this._state>Va)return kt(s,503);let c=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${Xh("sha1").update(r+nd).digest("base64")}`],u=new this.options.WebSocket(null,void 0,this.options);if(n.size){let f=this.options.handleProtocols?this.options.handleProtocols(n,i):n.values().next().value;f&&(c.push(`Sec-WebSocket-Protocol: ${f}`),u._protocol=f)}if(e[Ce.extensionName]){let f=e[Ce.extensionName].params,h=Ga.format({[Ce.extensionName]:[f]});c.push(`Sec-WebSocket-Extensions: ${h}`),u._extensions=e}this.emit("headers",c,i),s.write(c.concat(`\r
|
|
16
16
|
`).join(`\r
|
|
17
|
-
`)),
|
|
18
|
-
`+Object.keys(n).map(
|
|
17
|
+
`)),s.removeListener("error",Ya),u.setSocket(s,o,{allowSynchronousEvents:this.options.allowSynchronousEvents,maxBufferedChunks:this.options.maxBufferedChunks,maxFragments:this.options.maxFragments,maxPayload:this.options.maxPayload,skipUTF8Validation:this.options.skipUTF8Validation}),this.clients&&(this.clients.add(u),u.on("close",()=>{this.clients.delete(u),this._shouldEmitClose&&!this.clients.size&&process.nextTick(Ct,this)})),a(u,i)}};Ja.exports=Kn;function od(t,e){for(let r of Object.keys(e))t.on(r,e[r]);return function(){for(let n of Object.keys(e))t.removeListener(n,e[n])}}function Ct(t){t._state=Ka,t.emit("close")}function Ya(){this.destroy()}function kt(t,e,r,n){r=r||gr.STATUS_CODES[e],n={Connection:"close","Content-Type":"text/html","Content-Length":Buffer.byteLength(r),...n},t.once("finish",t.destroy),t.end(`HTTP/1.1 ${e} ${gr.STATUS_CODES[e]}\r
|
|
18
|
+
`+Object.keys(n).map(i=>`${i}: ${n[i]}`).join(`\r
|
|
19
19
|
`)+`\r
|
|
20
20
|
\r
|
|
21
|
-
`+r)}function ke(t,e,r,n,s,i){if(t.listenerCount("wsClientError")){let o=new Error(s);Error.captureStackTrace(o,ke),t.emit("wsClientError",o,r,e)}else Ct(r,n,s,i)}});import{basename as od}from"node:path";import{chmodSync as sl,existsSync as il,mkdirSync as ol,readFileSync as al,rmSync as ll,writeFileSync as cl}from"node:fs";import{homedir as fl}from"node:os";import{join as Kn}from"node:path";var Jn="https://api.amplibee.com/v1",Zn=()=>process.env.AMPLIBEE_HOME||Kn(fl(),".amplibee"),kt=()=>Kn(Zn(),"config.json");function ie(){try{let t=JSON.parse(al(kt(),"utf8"));if(typeof t?.apiUrl=="string"&&typeof t.deviceId=="string"&&typeof t.secret=="string")return t}catch{}return null}function X(t){let e=Zn();il(e)||ol(e,{recursive:!0,mode:448}),cl(kt(),JSON.stringify(t,null,2),{mode:384});try{sl(kt(),384)}catch{}}function Xn(){ll(kt(),{force:!0})}var N=globalThis.crypto.subtle,At=new TextEncoder,ul=new TextDecoder,yr={name:"ECDH",namedCurve:"P-256"},hl="amplibee-e2e-v1",dl=4e5;function G(t){let e="";for(let r=0;r<t.length;r+=32768)e+=String.fromCharCode(...t.subarray(r,r+32768));return btoa(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function z(t){let e=t.replace(/-/g,"+").replace(/_/g,"/"),r=atob(e+"=".repeat((4-e.length%4)%4)),n=new Uint8Array(r.length);for(let s=0;s<r.length;s++)n[s]=r.charCodeAt(s);return n}var _r=(...t)=>{let e=new Uint8Array(t.reduce((n,s)=>n+s.length,0)),r=0;for(let n of t)e.set(n,r),r+=n.length;return e};async function Ze(t=!1){let e=await N.generateKey(yr,t,["deriveBits"]);return{pub:new Uint8Array(await N.exportKey("raw",e.publicKey)),priv:e.privateKey}}async function Pt(t){return{pub:G(t.pub),priv:await N.exportKey("jwk",t.priv)}}async function ss(t){let e=await N.importKey("jwk",t.priv,yr,!1,["deriveBits"]);return{pub:z(t.pub),priv:e}}var pl="BCDFGHJKLMNPQRSTVWXZ";async function Q(t){let e=new Uint8Array(await N.digest("SHA-256",t)),r=0n;for(let s=0;s<8;s++)r=r<<8n|BigInt(e[s]);let n="";for(let s=0;s<12;s++)n+=pl[Number(r%20n)],r/=20n;return`${n.slice(0,4)}-${n.slice(4,8)}-${n.slice(8,12)}`}var is=(t,e)=>{let r=n=>n.toUpperCase().replace(/[^A-Z]/g,"");return r(t).length===12&&r(t)===r(e)},Qn=t=>{if(typeof t!="string"||!/^[A-Za-z0-9_-]{87}$/.test(t))return!1;try{let e=z(t);return e.length===65&&e[0]===4}catch{return!1}};async function es(t,e){if(e.length!==65||e[0]!==4)throw new Error("bad key");let r=await N.importKey("raw",e,yr,!0,[]);return new Uint8Array(await N.deriveBits({name:"ECDH",public:r},t,256))}async function gl(t,e,r,n){let s=await N.importKey("raw",t,"HKDF",!1,["deriveBits"]);return new Uint8Array(await N.deriveBits({name:"HKDF",hash:"SHA-256",salt:e,info:r},s,n*8))}var ts=At.encode("app>agent"),rs=At.encode("agent>app"),It=class{sendN=0;recvN=0;sq=Promise.resolve();rq=Promise.resolve();sendKey;recvKey;sendDir;recvDir;constructor(e,r,n,s){this.sendKey=e,this.recvKey=r,this.sendDir=n,this.recvDir=s}seal(e){let r=++this.sendN,n=this.sq.then(async()=>{let s=await N.encrypt({name:"AES-GCM",iv:ns(r),additionalData:this.sendDir},this.sendKey,At.encode(JSON.stringify(e)));return{n:r,c:G(new Uint8Array(s))}});return this.sq=n.catch(()=>{}),n}open(e){let r=this.rq.then(async()=>{let{n,c:s}=e;if(typeof n!="number"||!Number.isSafeInteger(n)||n<=this.recvN||typeof s!="string"||s.length>dl)return null;try{let i=await N.decrypt({name:"AES-GCM",iv:ns(n),additionalData:this.recvDir},this.recvKey,z(s)),o=JSON.parse(ul.decode(i));return!o||typeof o!="object"||Array.isArray(o)?null:(this.recvN=n,o)}catch{return null}});return this.rq=r.catch(()=>{}),r}};function ns(t){let e=new Uint8Array(12);return new DataView(e.buffer).setBigUint64(4,BigInt(t)),e}async function ml(t,e){let r=_r(At.encode(hl),t.appPub,t.agentPub,t.ephA,t.ephB),n=await gl(_r(t.ss,t.ee),_r(t.nonceA,t.nonceB),r,64),s=await N.importKey("raw",n.slice(0,32),"AES-GCM",!1,["encrypt","decrypt"]),i=await N.importKey("raw",n.slice(32),"AES-GCM",!1,["encrypt","decrypt"]);return e==="app"?new It(s,i,ts,rs):new It(i,s,rs,ts)}var _l=t=>globalThis.crypto.getRandomValues(new Uint8Array(t));async function os(t,e,r){if(!Qn(e.pub)||!Qn(e.eph)||typeof e.nonce!="string")return null;let n=z(e.pub);if(!r(n))return null;let s=z(e.nonce);if(s.length!==16)return null;let i=z(e.eph),o=await Ze(!1),a=_l(16),l=await es(t.priv,n),c=await es(o.priv,i),f=await ml({ss:l,ee:c,appPub:n,agentPub:t.pub,ephA:i,ephB:o.pub,nonceA:s,nonceB:a},"agent");return{accept:{eph:G(o.pub),nonce:G(a)},channel:f,appPub:n}}var j={frameBytes:256*1024,cols:{min:10,max:500},rows:{min:4,max:200},scrollbackBytes:256*1024,fileViewBytes:96*1024};function Ae(t,e){let r=Math.round(Number(t)),n=Math.round(Number(e));return{cols:Math.min(j.cols.max,Math.max(j.cols.min,Number.isFinite(r)?r:80)),rows:Math.min(j.rows.max,Math.max(j.rows.min,Number.isFinite(n)?n:24))}}import{existsSync as yl,statSync as wl}from"node:fs";import{delimiter as bl,extname as El,join as Sl}from"node:path";var xl={claude:{label:"Claude Code",command:"claude"},codex:{label:"Codex",command:"codex"},gemini:{label:"Gemini CLI",command:"gemini"},opencode:{label:"OpenCode",command:"opencode"},aider:{label:"Aider",command:"aider"},goose:{label:"Goose",command:"goose"}},Xe="shell",Bt=/^[a-z0-9][a-z0-9_-]{0,23}$/;function Cl(){return process.platform==="win32"?{label:"Terminal",command:"powershell.exe"}:{label:"Terminal",command:process.env.SHELL||"/bin/bash"}}function oe(t,e){let r={...xl};for(let[n,s]of Object.entries(t.harnesses??{}))Bt.test(n)&&n!==Xe&&(r[n]={...r[n],...s});e&&(r[Xe]=Cl());for(let n of Object.keys(r))r[n].disabled&&delete r[n];return r}function as(t,e=process.env){let r=process.platform==="win32"?(e.PATHEXT??".COM;.EXE;.BAT;.CMD").split(";"):[],s=t.includes("/")||t.includes("\\")?[""]:(e.PATH??e.Path??"").split(bl).filter(Boolean);for(let i of s){let o=i?Sl(i,t):t,a=process.platform==="win32"?El(t)?[""]:r:[""];for(let l of a){let c=o+l;try{if(yl(c)&&wl(c).isFile())return c}catch{}}}return null}function Qe(t){return Object.entries(t).map(([e,r])=>({id:e,label:r.label??e,available:as(r.command)!==null}))}function Lt(t){let e=as(t.command);if(!e)return null;let r=t.args??[];return process.platform==="win32"&&/\.(cmd|bat)$/i.test(e)?{file:process.env.COMSPEC||"cmd.exe",args:["/d","/s","/c",e,...r]}:{file:e,args:r}}import{execFile as Tl}from"node:child_process";var Ot=(t,e)=>new Promise(r=>Tl(t,e,{timeout:4e3,windowsHide:!0,maxBuffer:4*1024*1024},(n,s)=>r(n?"":String(s)))),wr=new Set(["*","0.0.0.0","127.0.0.1","[::]","[::1]","::","::1","localhost"]),vl=new Set(["system","svchost.exe","lsass.exe","services.exe","wininit.exe","spoolsv.exe","system idle process"]);function kl(t){let e=[];for(let r of t.split(/\r?\n/)){let n=/^\s*TCP\s+(\S+):(\d+)\s+\S+\s+LISTENING\s+(\d+)/i.exec(r);n&&wr.has(n[1])&&e.push({port:Number(n[2]),pid:Number(n[3])})}return e}function Il(t){let e=new Map;for(let r of t.split(/\r?\n/)){let n=/^"([^"]+)","(\d+)"/.exec(r);n&&e.set(Number(n[2]),n[1])}return e}function Al(t){let e=[],r="";for(let n of t.split(/\r?\n/))if(n.startsWith("c"))r=n.slice(1);else if(n.startsWith("n")){let s=n.lastIndexOf(":");s>0&&wr.has(n.slice(1,s))&&e.push({port:Number(n.slice(s+1)),process:r})}return e}function Pl(t){let e=[];for(let r of t.split(/\r?\n/)){let n=r.trim().split(/\s+/);if(n[0]!=="LISTEN"||n.length<5)continue;let s=n[3],i=s.lastIndexOf(":");i<0||!wr.has(s.slice(0,i))||e.push({port:Number(s.slice(i+1)),process:/users:\(\("([^"]+)"/.exec(r)?.[1]??""})}return e}function Bl(t){let e=new Map;for(let r of t)!Number.isInteger(r.port)||r.port<1024||r.port>65535||process.platform==="win32"&&r.port>=49152||(!e.has(r.port)||!e.get(r.port).process&&r.process)&&e.set(r.port,{port:r.port,process:r.process.slice(0,60)});return[...e.values()].sort((r,n)=>r.port-n.port).slice(0,40)}var et=null;async function br(){if(et&&Date.now()-et.at<2e3)return et.list;let t=[];if(process.platform==="win32"){let[e,r]=await Promise.all([Ot("netstat",["-ano","-p","tcp"]),Ot("tasklist",["/FO","CSV","/NH"])]),n=Il(r);t=kl(e).map(s=>({port:s.port,process:n.get(s.pid)??""})).filter(s=>!vl.has(s.process.toLowerCase())).map(s=>({port:s.port,process:s.process.replace(/\.exe$/i,"")}))}else t=Al(await Ot("lsof",["-nP","-iTCP","-sTCP:LISTEN","-Fpcn"])),t.length===0&&(t=Pl(await Ot("ss",["-ltnpH"])));return et={at:Date.now(),list:Bl(t)},et.list}import{request as Ll}from"node:http";import{createBrotliDecompress as Ol,createGunzip as Rl,createInflate as Nl}from"node:zlib";var Rt=90*1024,Ml=32*1024*1024,Ul=3e4,ls=new Set(["GET","HEAD","POST","PUT","PATCH","DELETE","OPTIONS"]),Dl=/^(accept|accept-language|authorization|cache-control|content-type|if-[a-z-]+|pragma|range|user-agent|x-[a-z0-9-]+)$/i,ql=new Set(["connection","keep-alive","transfer-encoding","content-length","content-encoding","set-cookie","set-cookie2","x-frame-options","content-security-policy","content-security-policy-report-only","strict-transport-security","upgrade","trailer","te"]);function Fl(t,e,r){let n={};for(let[s,i]of Object.entries(t))typeof i=="string"&&i.length<4096&&Dl.test(s)&&(n[s.toLowerCase()]=i);return n.host=`localhost:${e}`,n["accept-encoding"]="gzip, deflate, br",r>0&&(n["content-length"]=String(r)),n}function Hl(t){let e={};for(let[r,n]of Object.entries(t))ql.has(r.toLowerCase())||n===void 0||(e[r.toLowerCase()]=Array.isArray(n)?n.join(", "):n);return e}var Er=[],Sr=!1;function Nt(t){if(Er.push(t),Sr)return;Sr=!0;let e=()=>{Er.shift()?.(),Er.length?setTimeout(e,6):Sr=!1};setTimeout(e,0)}function cs(t,e,r,n,s){let i=!1,o=()=>{i||(i=!0,n())},a=c=>{i||(Nt(()=>r({t:"error",code:"proxy_failed",message:c,reqId:e.reqId})),o())},l=Ll({host:t,port:e.port,method:e.method,path:e.path,headers:Fl(e.headers,e.port,e.body?.length??0),timeout:Ul},c=>{let f=String(c.headers["content-encoding"]??"").toLowerCase(),u=f==="gzip"||f==="x-gzip"?c.pipe(Rl()):f==="deflate"?c.pipe(Nl()):f==="br"?c.pipe(Ol()):c;Nt(()=>r({t:"http.head",reqId:e.reqId,status:c.statusCode??502,headers:Hl(c.headers)}));let h=[],d=0,m=0,p=_=>{let y=Buffer.concat(h);h=[],d=0,Nt(()=>r({t:"http.chunk",reqId:e.reqId,data:y.toString("base64"),last:_}))};u.on("data",_=>{if(m+=_.length,m>Ml)return c.destroy(),a("That response is too large to preview.");for(h.push(_),d+=_.length;d>=Rt;){let y=Buffer.concat(h);h=[y.subarray(Rt)],d=y.length-Rt,Nt(()=>r({t:"http.chunk",reqId:e.reqId,data:y.subarray(0,Rt).toString("base64"),last:!1}))}}),u.on("end",()=>{i||(p(!0),o())}),u.on("error",()=>a("The page could not be read."))});l.on("timeout",()=>{l.destroy(),a("The server did not answer in time.")}),l.on("error",c=>{if(s&&c.code==="ECONNREFUSED")return cs("::1",e,r,n,!1);a(c.code==="ECONNREFUSED"?"Nothing is listening on that port any more.":"Could not reach that server.")}),e.body&&e.body.length>0&&l.write(e.body),l.end()}function fs(t,e,r){cs("127.0.0.1",t,e,r,!0)}import{closeSync as zl,lstatSync as hs,openSync as Wl,readSync as $l,readdirSync as ds,realpathSync as Gl,renameSync as ps,rmdirSync as jl,statSync as Pe,unlinkSync as gs,writeFileSync as Yl}from"node:fs";import{homedir as Vl}from"node:os";import{basename as xr,dirname as Cr,isAbsolute as Tr,join as vr,resolve as Mt,sep as us}from"node:path";var Be=t=>process.platform==="win32"||process.platform==="darwin"?t.toLowerCase():t;function Y(t){try{return Gl(t)}catch{return null}}function Le(t){return t==="~"||t.startsWith("~/")||t.startsWith("~\\")?Mt(Vl(),t.slice(2)):Mt(t)}function Ut(t,e){if(!Tr(e))return null;let r=Y(e);if(!r)return null;try{if(!Pe(r).isDirectory())return null}catch{return null}return kr(t,r)?r:null}function kr(t,e){let r=Be(e);for(let n of t){let s=Be(n);if(r===s||r.startsWith(s.endsWith(us)?s:s+us))return!0}return!1}function Ir(t,e){if(!Tr(e))return null;let r=Y(e);if(!r)return null;try{if(!Pe(r).isFile())return null}catch{return null}return kr(t,r)?r:null}var Kl=/^(id_(rsa|dsa|ecdsa|ed25519)|\.env.*|\.npmrc|\.netrc|credentials|.*\.(pem|key|p12|pfx|keystore|kdbx))$/i,tt=t=>Kl.test(xr(t));function ms(t,e){return t.some(r=>Be(r)===Be(e))}function _s(t){try{return ds(t,{withFileTypes:!0}).filter(e=>e.isDirectory()&&!e.name.startsWith(".")&&e.name!=="node_modules").map(e=>e.name).sort((e,r)=>e.localeCompare(r)).slice(0,300)}catch{return[]}}function ys(t){let e=[],r=[];try{for(let s of ds(t,{withFileTypes:!0}))if(!(s.name.startsWith(".")||s.name==="node_modules")){if(s.isDirectory())e.push(s.name);else if(s.isFile()){let i=0;try{i=Pe(Mt(t,s.name)).size}catch{}r.push({name:s.name,size:i})}}}catch{}let n=(s,i)=>(typeof s=="string"?s:s.name).localeCompare(typeof i=="string"?i:i.name);return{dirs:e.sort(n).slice(0,300),files:r.sort(n).slice(0,500)}}function ws(t,e){let r=Pe(t),n=r.size,s=Math.floor(r.mtimeMs),i=Wl(t,"r");try{let o=Buffer.alloc(Math.min(n,e)),a=$l(i,o,0,o.length,0),l=o.subarray(0,a);if(l.includes(0))return{size:n,mtime:s,text:null,binary:!0,truncated:!1};let c=l.toString("utf8"),f=n>a;return!f&&!Buffer.from(c,"utf8").equals(l)?{size:n,mtime:s,text:null,binary:!0,truncated:!1}:{size:n,mtime:s,text:c,binary:!1,truncated:f}}finally{zl(i)}}function bs(t,e,r){let n=Pe(t);if(Math.floor(n.mtimeMs)!==Math.floor(r))throw Object.assign(new Error("The file changed on the workspace."),{code:"conflict"});let s=vr(Cr(t),`.${xr(t)}.amplibee-${process.pid}.tmp`);Yl(s,e,{mode:n.mode&511});try{ps(s,t)}catch(o){try{gs(s)}catch{}throw o}let i=Pe(t);return{size:i.size,mtime:Math.floor(i.mtimeMs)}}function Es(t,e){if(!Tr(e))return null;let r=Y(Cr(Mt(e)));if(!r||!kr(t,r))return null;let n=vr(r,xr(e)),s;try{s=hs(n)}catch{return null}return!s.isSymbolicLink()&&ms(t,Y(n)??n)?null:{entry:n,folder:r,isDir:s.isDirectory()}}var Jl=/[\\/:*?"<>|\0]/;function Ss(t,e,r){let n=Es(t,e);if(!n)throw Object.assign(new Error("outside"),{code:"bad_file"});if(!r||r.length>200||r==="."||r===".."||Jl.test(r)||r!==r.trim())throw Object.assign(new Error("bad name"),{code:"bad_name"});let s=vr(n.folder,r);try{if(hs(s),Be(s)!==Be(n.entry))throw Object.assign(new Error("exists"),{code:"exists"})}catch(i){if(i.code==="exists")throw i}return ps(n.entry,s),s}function xs(t,e){let r=Es(t,e);if(!r)throw Object.assign(new Error("outside"),{code:"bad_file"});if(r.isDir){try{jl(r.entry)}catch{throw Object.assign(new Error("not empty"),{code:"not_empty"})}return}gs(r.entry)}var Ar=(t,e)=>ms(t,e)?null:Cr(e);var Dt=(t,e)=>typeof t=="string"&&t.length>0&&t.length<=e?t:null,Zl=64*1024,Xl=10,Ql=200,ec=12,Cs=16*1024,qt=class{constructor(e){this.o=e;this.roots=e.roots.map(r=>Y(Le(r))??Le(r)),e.manager.onChange=()=>this.o.send({t:"sessions",sessions:e.manager.list()})}roots;subs=new Map;proxying=0;proxyWaiting=[];pending=new Map;host(){return{name:this.o.cfg.name,platform:process.platform,agentVersion:this.o.version,roots:this.roots,harnesses:Qe(oe(this.o.cfg,this.o.allowShell))}}connected(){this.subs.clear()}watch(e){e.onData(r=>{let n=this.subs.get(e.id);if(!n||n.size===0)return;let s=this.pending.get(e.id);s?s.buf+=r:this.pending.set(e.id,{buf:r,timer:setTimeout(()=>this.flush(e.id),ec)})}),e.onExit(r=>{this.flush(e.id);for(let n of this.subs.get(e.id)??[])this.o.send({t:"session.exit",id:e.id,code:r,cid:n})})}flush(e){let r=this.pending.get(e);if(r){clearTimeout(r.timer),this.pending.delete(e);for(let n of this.subs.get(e)??[])this.output(e,n,r.buf,!1)}}output(e,r,n,s){if(n.length<=Cs)return this.o.send({t:"session.output",id:e,data:n,replay:s||void 0,cid:r});for(let i=0;i<n.length;){let o=Math.min(i+Cs,n.length),a=n.charCodeAt(o-1);o<n.length&&a>=55296&&a<=56319&&o--,this.o.send({t:"session.output",id:e,data:n.slice(i,o),replay:s&&i===0?!0:void 0,cid:r}),i=o}}subscribe(e,r){let n=this.subs.get(e);n||this.subs.set(e,n=new Set),n.add(r)}handle(e){let r=typeof e.cid=="string"?e.cid:void 0,n=i=>this.o.send({...i,cid:r}),s=(i,o)=>n({t:"error",code:i,message:o,reqId:typeof e.reqId=="string"?e.reqId:void 0});if(r)try{this.dispatch(e,r,n,s)}catch(i){s("failed",i instanceof Error?i.message:"Something went wrong on the workspace.")}}dispatch(e,r,n,s){let i=this.o.manager,o=()=>{let a=Dt(e.id,40),l=a?i.get(a):void 0;return l||s("no_session","That session no longer exists."),l??null};switch(e.t){case"app.left":for(let a of this.subs.values())a.delete(r);return;case"host.get":return n({t:"host",host:this.host()});case"sessions.list":return n({t:"sessions",sessions:i.list()});case"session.start":{let a=Dt(e.harness,24),l=a?oe(this.o.cfg,this.o.allowShell)[a]:void 0;if(!a||!l)return s("unknown_harness","That agent is not enabled on this workspace.");let c=Lt(l);if(!c)return s("not_installed",`"${l.command}" is not installed on this workspace.`);let f=e.cwd===void 0?this.roots[0]:Ut(this.roots,String(e.cwd));if(!f)return s("bad_folder","That folder is outside the folders this workspace shares.");let{cols:u,rows:h}=Ae(e.cols,e.rows),d=i.start({harness:a,title:l.label??a,file:c.file,args:c.args,cwd:f,cols:u,rows:h});return this.watch(d),this.subscribe(d.id,r),n({t:"session.started",session:d.info,reqId:typeof e.reqId=="string"?e.reqId:void 0})}case"session.attach":{let a=o();if(!a)return;if(this.subscribe(a.id,r),!a.opts.local&&e.cols!==void 0){let l=Ae(e.cols,e.rows);a.resize(l.cols,l.rows)}this.output(a.id,r,a.scrollback(),!0),a.running||n({t:"session.exit",id:a.id,code:a.exitCode});return}case"session.input":{let a=o(),l=typeof e.data=="string"&&e.data.length<=Zl?e.data:null;a&&l!==null&&a.write(l);return}case"session.resize":{let a=o();a&&!a.opts.local&&a.resize(Number(e.cols),Number(e.rows));return}case"session.kill":return o()?.kill();case"session.remove":{let a=Dt(e.id,40);a&&(i.remove(a),this.subs.delete(a));return}case"dir.list":{let a=e.path===void 0||e.path===""?this.roots[0]:Ut(this.roots,String(e.path));return a?n({t:"dirs",path:a,parent:Ar(this.roots,a),entries:_s(a),reqId:typeof e.reqId=="string"?e.reqId:void 0}):s("bad_folder","That folder is outside the folders this workspace shares.")}case"fs.list":{let a=e.path===void 0||e.path===""?this.roots[0]:Ut(this.roots,String(e.path));if(!a)return s("bad_folder","That folder is outside the folders this workspace shares.");let{dirs:l,files:c}=ys(a);return n({t:"fs.entries",path:a,parent:Ar(this.roots,a),dirs:l,files:c,reqId:typeof e.reqId=="string"?e.reqId:void 0})}case"fs.read":{let a=Ir(this.roots,String(e.path??""));if(!a)return s("bad_file","That file is outside the folders this workspace shares.");if(tt(a))return s("secret_file","Files that usually hold secrets (keys, .env) are never shown here.");let l=ws(a,j.fileViewBytes);return n({t:"fs.file",path:a,...l,reqId:typeof e.reqId=="string"?e.reqId:void 0})}case"fs.write":{let a=Ir(this.roots,String(e.path??""));if(!a)return s("bad_file","That file is outside the folders this workspace shares.");if(tt(a))return s("secret_file","Files that usually hold secrets (keys, .env) are never edited here.");if(typeof e.text!="string"||Buffer.byteLength(e.text,"utf8")>j.fileViewBytes)return s("too_large",`Files can be edited here up to ${Math.round(j.fileViewBytes/1024)} KB.`);try{let l=bs(a,e.text,Number(e.mtime));return n({t:"fs.saved",path:a,...l,reqId:typeof e.reqId=="string"?e.reqId:void 0})}catch(l){return l.code==="conflict"?s("conflict","This file changed on the workspace since you opened it. Reload it to see the new version."):s("write_failed","Could not save the file. It may be read-only on the workspace.")}}case"fs.rename":{let a=String(e.path??""),l=typeof e.name=="string"?e.name:"";if(tt(a))return s("secret_file","Files that usually hold secrets (keys, .env) are never changed here.");try{let c=Ss(this.roots,a,l);return n({t:"fs.done",op:"rename",path:a,newPath:c,reqId:typeof e.reqId=="string"?e.reqId:void 0})}catch(c){let f=c.code;return f==="bad_file"?s("bad_file","That is outside the folders this workspace shares."):f==="bad_name"?s("bad_name",'Use a plain name: no slashes and none of : * ? " < > |'):f==="exists"?s("exists","Something with that name already exists here."):s("failed","Could not rename it.")}}case"fs.remove":{let a=String(e.path??"");if(tt(a))return s("secret_file","Files that usually hold secrets (keys, .env) are never changed here.");try{return xs(this.roots,a),n({t:"fs.done",op:"remove",path:a,reqId:typeof e.reqId=="string"?e.reqId:void 0})}catch(l){let c=l.code;return c==="bad_file"?s("bad_file","That is outside the folders this workspace shares."):c==="not_empty"?s("not_empty","Only empty folders can be removed here. Delete what is inside first."):s("failed","Could not delete it.")}}case"ports.list":{(this.o.ports??br)().then(a=>n({t:"ports",ports:a,reqId:typeof e.reqId=="string"?e.reqId:void 0}));return}case"http.fetch":{let a=Dt(e.reqId,80),l=Number(e.port),c=String(e.method??"").toUpperCase(),f=typeof e.path=="string"?e.path:"";if(!a)return s("bad_request","Missing request id.");if(!Number.isInteger(l)||!ls.has(c)||!/^\/[^\s]*$/.test(f)||f.length>4e3)return s("bad_request","That request is not allowed.");let u=typeof e.body=="string"&&e.body.length>0?Buffer.from(e.body,"base64"):null;if(u&&u.length>150*1024)return s("too_large","That request body is too large for the preview.");if(this.proxyWaiting.length>=Ql)return s("busy","Too many requests at once. Try again.");let h=e.headers&&typeof e.headers=="object"?e.headers:{},d=()=>{this.proxying++;let m=()=>{this.proxying--,this.proxyWaiting.shift()?.()};(this.o.ports??br)().then(p=>{if(!p.some(_=>_.port===l))return m(),n({t:"error",code:"no_server",message:"Nothing is listening on that port.",reqId:a});fs({reqId:a,port:l,method:c,path:f,headers:h,body:u},n,m)},m)};this.proxying>=Xl?this.proxyWaiting.push(d):d();return}default:return s("unknown_message","Unknown message.")}}};var Ts=20;async function Ft(t){if(t.identity)try{return await ss(t.identity)}catch{}let e=await Ze(!0);return t.identity=await Pt(e),t.apps=[],X(t),e}var rt={at:0,keys:[]};function vs(){return Date.now()-rt.at>2e3&&(rt={at:Date.now(),keys:(ie()?.apps??[]).map(t=>t.pub)}),rt.keys}async function Pr(t){z(t);let e=ie();if(!e)throw new Error("This workspace is not logged in.");let r=(e.apps??[]).filter(s=>s.pub!==t);if(r.length>=Ts)throw new Error(`You can link up to ${Ts} browsers. Remove one with "amplibee apps remove <fingerprint>".`);let n={pub:t,fingerprint:await Q(z(t)),addedAt:new Date().toISOString()};return e.apps=[...r,n],X(e),rt={at:0,keys:[]},n}function ks(t){let e=ie();if(!e)return 0;let r=s=>s.toUpperCase().replace(/[^A-Z]/g,""),n=e.apps??[];return e.apps=n.filter(s=>r(s.fingerprint)!==r(t)),X(e),rt={at:0,keys:[]},n.length-e.apps.length}var Do=Z(Uo(),1);import{createHash as _u,randomBytes as yu}from"node:crypto";import{spawn as wu}from"node:child_process";import{hostname as bu,platform as Eu,release as Su}from"node:os";import{createInterface as xu}from"node:readline/promises";async function Sn(t,e,r,n={}){let s;try{s=await fetch(t+e,{method:"POST",headers:{"content-type":"application/json",...n},body:JSON.stringify(r),signal:AbortSignal.timeout(2e4)})}catch{throw new Error(`Could not reach ${t}. Check your internet connection.`)}let i=null;try{i=await s.json()}catch{}if(!s.ok||!i?.ok||i.data===null)throw Object.assign(new Error(i?.error?.message??`The server answered with status ${s.status}.`),{status:s.status,code:i?.error?.code});return i.data}function qo(t){try{let[e,r]=process.platform==="win32"?["cmd",["/c","start","",t]]:process.platform==="darwin"?["open",[t]]:["xdg-open",[t]];wu(e,r,{stdio:"ignore",detached:!0}).on("error",()=>{}).unref()}catch{}}async function Fo(t,e){let r=Date.now()+e.expires_in*1e3;for(;Date.now()<r;){await new Promise(n=>setTimeout(n,e.interval*1e3));try{let n=await Sn(t,"/devices/pair/poll",{device_code:e.device_code});if(n.status==="approved")return n}catch(n){let s=n.status;if(s===410)break;if(s&&s<500&&s!==429)throw n}}throw new Error("The code expired. Run the command again.")}async function Cu(t){let e=xu({input:process.stdin,output:process.stdout});try{return await e.question(t)}finally{e.close()}}async function Ho(t,e,r){let n;try{n=await Q(z(t))}catch{return r(" The app sent a key that is not valid, so nothing was linked."),!1}if(r(""),r(" The app approved. Check that it shows the same fingerprint for this browser:"),r(""),r(` ${n}`),r(""),e.trustApp){let i=is(e.trustApp,n);return r(i?" It matches --trust-app.":" It does NOT match --trust-app, so the browser was not linked."),i}if(!process.stdin.isTTY)return r(" There is nobody here to confirm it. Run this in a terminal, or pass --trust-app <fingerprint>."),!1;let s=await Cu(' Type "yes" only if it is exactly the same: ');return/^y(es)?$/i.test(s.trim())}async function zo(t,e,r,n){n(""),n(` ${r}`),n(` ${t.verification_url}`);try{let s=await Do.default.toString(t.verification_url,{type:"utf8",errorCorrectionLevel:"L"});n("");for(let i of s.split(/\r?\n/))n(` ${i}`)}catch{}n(""),n(` Code: ${t.user_code}`),n(` Fingerprint: ${e}`),n(""),n(" The app shows this fingerprint too. Continue only if they are the same."),n(` Waiting for approval (the code works for ${Math.round(t.expires_in/60)} minutes)...`)}async function Wo(t){let e=t.log??console.log,r=yu(32).toString("hex"),n=(t.name||bu()||"my workspace").slice(0,60),s=await Ze(!0),i=await Sn(t.apiUrl,"/devices/pair",{name:n,platform:`${Eu()} ${Su()}`.slice(0,40),agent_version:t.version,token_hash:_u("sha256").update(r).digest("hex"),agent_pub:G(s.pub)});await zo(i,await Q(s.pub),"Scan the QR code with your phone, or open this page and confirm the code:",e),t.openBrowser&&qo(i.verification_url);let o=await Fo(t.apiUrl,i),a={apiUrl:t.apiUrl,deviceId:o.device_id,secret:r,name:n,identity:await Pt(s),apps:[]};X(a);let l=await Ho(o.app_pub,t,e);return l&&await Pr(o.app_pub),{cfg:a,linked:l}}async function $o(t,e){let r=e.log??console.log,n=await Ft(t),s=await Sn(t.apiUrl,"/devices/link",{agent_pub:G(n.pub),agent_version:e.version},{authorization:`Bearer ${t.secret}`});await zo(s,await Q(n.pub),'Open the workspace in the Amplibee app and choose "Link this browser", or scan the QR code:',r),e.openBrowser&&qo(s.verification_url);let i=await Fo(t.apiUrl,s),o=await Ho(i.app_pub,{...e,apiUrl:t.apiUrl},r);return o&&await Pr(i.app_pub),o}var Kh=Z(qa(),1),Jh=Z(ar(),1),Zh=Z($e(),1),Xh=Z(Nn(),1),Qh=Z(Dn(),1),ed=Z(Wn(),1),Va=Z(fr(),1),td=Z(Ya(),1);var Gn=Va.default;var Tt=class extends Error{};function rd(t){return t.replace(/^http/,"ws").replace(/\/$/,"")+"/relay/agent"}var hr=class{constructor(e){this.o=e;this.fatal=new Promise(r=>this.die=r)}ws=null;attempt=0;stopped=!1;watchdog;retry;fatal;die;get connected(){return this.ws?.readyState===Gn.OPEN}start(){this.open()}stop(){this.stopped=!0,clearTimeout(this.retry),clearInterval(this.watchdog),this.ws?.close(1e3)}send(e){return this.connected?(this.ws.send(JSON.stringify(e)),!0):!1}open(){if(this.stopped)return;let e=new Gn(rd(this.o.apiUrl),{headers:{authorization:`Bearer ${this.o.secret}`,"x-amplibee-agent":this.o.version},handshakeTimeout:15e3,maxPayload:512*1024});this.ws=e;let r=Date.now();e.on("open",()=>{this.attempt=0,r=Date.now(),this.o.log("connected to Amplibee"),this.o.onUp()}),e.on("ping",()=>r=Date.now()),e.on("message",n=>{r=Date.now();try{let s=JSON.parse(n.toString());s&&typeof s.t=="string"&&this.o.onMessage(s)}catch{}}),e.on("unexpected-response",(n,s)=>{s.resume(),s.statusCode===401?this.die(new Tt('This workspace was removed from your account (or its login is no longer valid). Run "amplibee login" again.')):this.o.log(`relay answered ${s.statusCode}`),e.terminate()}),e.on("error",n=>this.o.log(`connection problem: ${n.message}`)),e.on("close",n=>{if(clearInterval(this.watchdog),this.o.onDown(),n===4001)return this.die(new Tt('This workspace was removed from your account. Run "amplibee login" to connect it again.'));if(n===4e3)return this.die(new Tt("Another amplibee process for this workspace connected, so this one stopped. Run only one at a time."));this.schedule()}),clearInterval(this.watchdog),this.watchdog=setInterval(()=>{Date.now()-r>75e3&&e.terminate()},1e4)}schedule(){if(this.stopped)return;let e=Math.min(3e4,1e3*2**Math.min(this.attempt++,5)),r=e/2+Math.random()*(e/2);this.o.log(`reconnecting in ${Math.round(r/1e3)}s`),this.retry=setTimeout(()=>this.open(),r)}};var nd=32,dr=class{chans=new Map;o;constructor(e){this.o=e}reset(){this.chans.clear()}get channels(){return this.chans.size}async fromRelay(e){let r=typeof e.cid=="string"&&e.cid.length>0&&e.cid.length<=32?e.cid:null;if(r){if(e.t==="app.left")return this.chans.delete(r),this.o.deliver({t:"app.left",cid:r});if(e.t==="e2e.hello")return this.hello(r,e);if(e.t==="e2e.data")return this.data(r,{n:e.n,c:e.c})}}async hello(e,r){if(!this.chans.has(e)&&this.chans.size>=nd)return;let n=null;try{let s=this.o.trusted();n=await os(this.o.identity,r,i=>s.includes(G(i)))}catch{}if(!n)return this.o.transmit({t:"e2e.reject",cid:e,code:"not_linked"});this.chans.set(e,{chan:n.channel,app:G(n.appPub)}),this.o.transmit({t:"e2e.accept",cid:e,...n.accept}),this.sendTo(e,{t:"secure"})}async data(e,r){let n=this.chans.get(e);if(!n)return;if(!this.o.trusted().includes(n.app))return this.chans.delete(e),this.o.transmit({t:"e2e.reject",cid:e,code:"not_linked"});let s=await n.chan.open(r);s&&typeof s.t=="string"&&s.t.length<=40&&this.o.deliver({...s,t:s.t,cid:e})}send(e){let{cid:r,...n}=e;if(r)this.sendTo(r,n);else for(let s of[...this.chans.keys()])this.sendTo(s,n)}sendTo(e,r){let n=this.chans.get(e);n&&n.chan.seal(r).then(s=>this.o.transmit({t:"e2e.data",cid:e,...s})).catch(()=>{})}};import{randomBytes as sd}from"node:crypto";var Ka=8,id=24,jn=class{constructor(e,r){this.pty=e;this.opts=r;this.cols=r.cols,this.rows=r.rows,e.onData(n=>{this.keep(n);for(let s of this.listeners)s(n)}),e.onExit(n=>{this.running=!1,this.exitCode=n.exitCode;for(let s of this.exitListeners)s(n.exitCode)})}id=sd(6).toString("hex");startedAt=Date.now();running=!0;exitCode=null;cols;rows;chunks=[];size=0;listeners=new Set;exitListeners=new Set;get info(){return{id:this.id,harness:this.opts.harness,title:this.opts.title,cwd:this.opts.cwd,cols:this.cols,rows:this.rows,startedAt:this.startedAt,running:this.running,exitCode:this.exitCode,local:!!this.opts.local}}keep(e){for(this.chunks.push(e),this.size+=e.length;this.size>j.scrollbackBytes&&this.chunks.length>1;)this.size-=this.chunks.shift().length}scrollback(){return this.chunks.join("")}onData(e){return this.listeners.add(e),()=>this.listeners.delete(e)}onExit(e){return this.exitListeners.add(e),()=>this.exitListeners.delete(e)}write(e){this.running&&this.pty.write(e)}resize(e,r){let n=Ae(e,r);if(this.cols=n.cols,this.rows=n.rows,this.running)try{this.pty.resize(n.cols,n.rows)}catch{}}kill(){this.running&&this.pty.kill()}},vt=class{constructor(e){this.spawn=e}sessions=new Map;onChange=()=>{};list(){return[...this.sessions.values()].map(e=>e.info)}get(e){return this.sessions.get(e)}runningCount(){return[...this.sessions.values()].filter(e=>e.running).length}start(e){if(this.runningCount()>=Ka)throw new Error(`At most ${Ka} sessions can run at once. Close one first.`);let r=Ae(e.cols,e.rows),n={};for(let[o,a]of Object.entries(process.env))typeof a=="string"&&(n[o]=a);n.TERM="xterm-256color",n.COLORTERM="truecolor",n.AMPLIBEE_SESSION="1";let s=this.spawn(e.file,e.args,{cwd:e.cwd,cols:r.cols,rows:r.rows,env:n}),i=new jn(s,{...e,...r});return this.sessions.set(i.id,i),i.onExit(()=>this.onChange()),this.trim(),this.onChange(),i}remove(e){let r=this.sessions.get(e);return r?(r.kill(),this.sessions.delete(e),this.onChange(),!0):!1}killAll(){for(let e of this.sessions.values())e.kill()}trim(){let e=[...this.sessions.values()].filter(r=>!r.running);for(let r of e.slice(0,Math.max(0,this.sessions.size-id)))this.sessions.delete(r.id)}};async function Yn(){let t=await import("@lydell/node-pty");return(e,r,n)=>{let s=t.spawn(e,r,{name:"xterm-256color",cols:n.cols,rows:n.rows,cwd:n.cwd,env:n.env});return{onData:i=>void s.onData(i),onExit:i=>void s.onExit(i),write:i=>s.write(i),resize:(i,o)=>s.resize(i,o),kill:()=>s.kill()}}}var me="0.1.2",ad=`amplibee ${me}: steer Claude Code, Codex or any terminal agent from your phone.
|
|
21
|
+
`+r)}function ke(t,e,r,n,i,s){if(t.listenerCount("wsClientError")){let o=new Error(i);Error.captureStackTrace(o,ke),t.emit("wsClientError",o,r,e)}else kt(r,n,i,s)}});import{basename as Ed}from"node:path";import{chmodSync as cl,existsSync as ul,mkdirSync as fl,readFileSync as hl,rmSync as dl,writeFileSync as pl}from"node:fs";import{homedir as gl}from"node:os";import{join as ei}from"node:path";var ti="https://api.amplibee.com/v1",ri=()=>process.env.AMPLIBEE_HOME||ei(gl(),".amplibee"),Bt=()=>ei(ri(),"config.json");function V(){try{let t=JSON.parse(hl(Bt(),"utf8"));if(typeof t?.apiUrl=="string"&&typeof t.deviceId=="string"&&typeof t.secret=="string")return t}catch{}return null}function j(t){let e=ri();ul(e)||fl(e,{recursive:!0,mode:448}),pl(Bt(),JSON.stringify(t,null,2),{mode:384});try{cl(Bt(),384)}catch{}}function ni(){dl(Bt(),{force:!0})}var N=globalThis.crypto.subtle,Ot=new TextEncoder,ml=new TextDecoder,Er={name:"ECDH",namedCurve:"P-256"},yl="amplibee-e2e-v1",_l=4e5;function D(t){let e="";for(let r=0;r<t.length;r+=32768)e+=String.fromCharCode(...t.subarray(r,r+32768));return btoa(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function q(t){let e=t.replace(/-/g,"+").replace(/_/g,"/"),r=atob(e+"=".repeat((4-e.length%4)%4)),n=new Uint8Array(r.length);for(let i=0;i<r.length;i++)n[i]=r.charCodeAt(i);return n}var br=(...t)=>{let e=new Uint8Array(t.reduce((n,i)=>n+i.length,0)),r=0;for(let n of t)e.set(n,r),r+=n.length;return e};async function Qe(t=!1){let e=await N.generateKey(Er,t,["deriveBits"]);return{pub:new Uint8Array(await N.exportKey("raw",e.publicKey)),priv:e.privateKey}}async function Xe(t){return{pub:D(t.pub),priv:await N.exportKey("jwk",t.priv)}}async function xr(t){let e=await N.importKey("jwk",t.priv,Er,!1,["deriveBits"]);return{pub:q(t.pub),priv:e}}var wl="BCDFGHJKLMNPQRSTVWXZ";async function ee(t){let e=new Uint8Array(await N.digest("SHA-256",t)),r=0n;for(let i=0;i<8;i++)r=r<<8n|BigInt(e[i]);let n="";for(let i=0;i<12;i++)n+=wl[Number(r%20n)],r/=20n;return`${n.slice(0,4)}-${n.slice(4,8)}-${n.slice(8,12)}`}var li=(t,e)=>{let r=n=>n.toUpperCase().replace(/[^A-Z]/g,"");return r(t).length===12&&r(t)===r(e)},Ze=t=>{if(typeof t!="string"||!/^[A-Za-z0-9_-]{87}$/.test(t))return!1;try{let e=q(t);return e.length===65&&e[0]===4}catch{return!1}};async function ii(t,e){if(e.length!==65||e[0]!==4)throw new Error("bad key");let r=await N.importKey("raw",e,Er,!0,[]);return new Uint8Array(await N.deriveBits({name:"ECDH",public:r},t,256))}async function bl(t,e,r,n){let i=await N.importKey("raw",t,"HKDF",!1,["deriveBits"]);return new Uint8Array(await N.deriveBits({name:"HKDF",hash:"SHA-256",salt:e,info:r},i,n*8))}var si=Ot.encode("app>agent"),oi=Ot.encode("agent>app"),Lt=class{sendN=0;recvN=0;sq=Promise.resolve();rq=Promise.resolve();sendKey;recvKey;sendDir;recvDir;constructor(e,r,n,i){this.sendKey=e,this.recvKey=r,this.sendDir=n,this.recvDir=i}seal(e){let r=++this.sendN,n=this.sq.then(async()=>{let i=await N.encrypt({name:"AES-GCM",iv:ai(r),additionalData:this.sendDir},this.sendKey,Ot.encode(JSON.stringify(e)));return{n:r,c:D(new Uint8Array(i))}});return this.sq=n.catch(()=>{}),n}open(e){let r=this.rq.then(async()=>{let{n,c:i}=e;if(typeof n!="number"||!Number.isSafeInteger(n)||n<=this.recvN||typeof i!="string"||i.length>_l)return null;try{let s=await N.decrypt({name:"AES-GCM",iv:ai(n),additionalData:this.recvDir},this.recvKey,q(i)),o=JSON.parse(ml.decode(s));return!o||typeof o!="object"||Array.isArray(o)?null:(this.recvN=n,o)}catch{return null}});return this.rq=r.catch(()=>{}),r}};function ai(t){let e=new Uint8Array(12);return new DataView(e.buffer).setBigUint64(4,BigInt(t)),e}async function El(t,e){let r=br(Ot.encode(yl),t.appPub,t.agentPub,t.ephA,t.ephB),n=await bl(br(t.ss,t.ee),br(t.nonceA,t.nonceB),r,64),i=await N.importKey("raw",n.slice(0,32),"AES-GCM",!1,["encrypt","decrypt"]),s=await N.importKey("raw",n.slice(32),"AES-GCM",!1,["encrypt","decrypt"]);return e==="app"?new Lt(i,s,si,oi):new Lt(s,i,oi,si)}var xl=t=>globalThis.crypto.getRandomValues(new Uint8Array(t));async function ci(t,e,r){if(!Ze(e.pub)||!Ze(e.eph)||typeof e.nonce!="string")return null;let n=q(e.pub);if(!r(n))return null;let i=q(e.nonce);if(i.length!==16)return null;let s=q(e.eph),o=await Qe(!1),a=xl(16),l=await ii(t.priv,n),c=await ii(o.priv,s),u=await El({ss:l,ee:c,appPub:n,agentPub:t.pub,ephA:s,ephB:o.pub,nonceA:i,nonceB:a},"agent");return{accept:{eph:D(o.pub),nonce:D(a)},channel:u,appPub:n}}var zd=globalThis.crypto.subtle,Sl=new TextEncoder,$d=new TextDecoder,Wd=Sl.encode("amplibee-vault-v1");var Y={frameBytes:256*1024,cols:{min:10,max:500},rows:{min:4,max:200},scrollbackBytes:256*1024,fileViewBytes:96*1024};function Pe(t,e){let r=Math.round(Number(t)),n=Math.round(Number(e));return{cols:Math.min(Y.cols.max,Math.max(Y.cols.min,Number.isFinite(r)?r:80)),rows:Math.min(Y.rows.max,Math.max(Y.rows.min,Number.isFinite(n)?n:24))}}import{existsSync as vl,statSync as Tl}from"node:fs";import{delimiter as Cl,extname as kl,join as Il}from"node:path";var Al={claude:{label:"Claude Code",command:"claude"},codex:{label:"Codex",command:"codex"},gemini:{label:"Gemini CLI",command:"gemini"},opencode:{label:"OpenCode",command:"opencode"},aider:{label:"Aider",command:"aider"},goose:{label:"Goose",command:"goose"}},et="shell",Rt=/^[a-z0-9][a-z0-9_-]{0,23}$/;function Pl(){return process.platform==="win32"?{label:"Terminal",command:"powershell.exe"}:{label:"Terminal",command:process.env.SHELL||"/bin/bash"}}function oe(t,e){let r={...Al};for(let[n,i]of Object.entries(t.harnesses??{}))Rt.test(n)&&n!==et&&(r[n]={...r[n],...i});e&&(r[et]=Pl());for(let n of Object.keys(r))r[n].disabled&&delete r[n];return r}function ui(t,e=process.env){let r=process.platform==="win32"?(e.PATHEXT??".COM;.EXE;.BAT;.CMD").split(";"):[],i=t.includes("/")||t.includes("\\")?[""]:(e.PATH??e.Path??"").split(Cl).filter(Boolean);for(let s of i){let o=s?Il(s,t):t,a=process.platform==="win32"?kl(t)?[""]:r:[""];for(let l of a){let c=o+l;try{if(vl(c)&&Tl(c).isFile())return c}catch{}}}return null}function tt(t){return Object.entries(t).map(([e,r])=>({id:e,label:r.label??e,available:ui(r.command)!==null}))}function Nt(t){let e=ui(t.command);if(!e)return null;let r=t.args??[];return process.platform==="win32"&&/\.(cmd|bat)$/i.test(e)?{file:process.env.COMSPEC||"cmd.exe",args:["/d","/s","/c",e,...r]}:{file:e,args:r}}var Bl=/\x1b\[[0-9;?<>=]*[ -/]*[@-~]|\x1b\][^\x07\x1b]*(?:\x07|\x1b\\)|\x1b[()][0-9A-Za-z]|\x1b[=>78]/g;function Ll(t){return t.replace(Bl,"").replace(/\r(?!\n)/g,`
|
|
22
|
+
`).replace(/[\x00-\x08\x0b-\x1f\x7f]/g,"")}var hi=[/\[y\/n\]/i,/\(y\/n\)/i,/\by\/n\b/i,/\(yes\/no\)/i,/do you want to/i,/would you like to/i,/\bproceed\?/i,/\ballow\b.*\?/i,/press enter/i,/esc to cancel/i,/^\s*[❯>]\s*1\.\s+yes/im,/\?\s*$/];function Sr(t,e=3){return t.split(`
|
|
23
|
+
`).map(r=>r.trim()).filter(Boolean).slice(-e)}var Ol=t=>{let e=Sr(t,6).join(`
|
|
24
|
+
`);return e.length>0&&hi.some(r=>r.test(e))},fi=(t,e=140)=>t.length>e?`${t.slice(0,e-1)}\u2026`:t,Mt=class{constructor(e){this.o=e}tail="";activity=0;fresh=!1;askTimer;idleTimer;done=!1;feed(e){this.done||(this.tail=(this.tail+Ll(e)).slice(-1500),this.activity+=e.length,this.fresh=!0,this.arm())}input(){this.tail="",this.activity=0,this.fresh=!1,this.clear()}exit(e){this.done||(this.done=!0,this.clear(),this.o.emit("done",e===0||e===null?"It finished.":`It stopped with exit code ${e}.`))}stop(){this.done=!0,this.clear()}clear(){clearTimeout(this.askTimer),clearTimeout(this.idleTimer)}arm(){this.clear(),this.askTimer=setTimeout(()=>this.checkAsk(),this.o.askMs??2500),this.idleTimer=setTimeout(()=>this.checkIdle(),this.o.idleMs??12e3),this.askTimer.unref?.(),this.idleTimer.unref?.()}checkAsk(){if(!this.fresh||this.done||!Ol(this.tail))return;this.fresh=!1,this.activity=0,clearTimeout(this.idleTimer);let e=Sr(this.tail,6),r=[...e].reverse().find(n=>hi.some(i=>i.test(n)))??e.at(-1)??"";this.o.emit("ask",fi(r))}checkIdle(){!this.fresh||this.done||this.activity<(this.o.minActivity??200)||(this.fresh=!1,this.activity=0,this.o.emit("idle",fi(Sr(this.tail,1)[0]??"It stopped printing.")))}};import{execFile as Rl}from"node:child_process";import{connect as Nl}from"node:net";var Ut=(t,e)=>new Promise(r=>Rl(t,e,{timeout:4e3,windowsHide:!0,maxBuffer:4*1024*1024},(n,i)=>r(n?"":String(i)))),vr=new Set(["*","0.0.0.0","127.0.0.1","[::]","[::1]","::","::1","localhost"]),Ml=new Set(["system","svchost.exe","lsass.exe","services.exe","wininit.exe","spoolsv.exe","system idle process"]),Ul=/^(code|code - insiders|cursor|windsurf|nvidia|dbeaver|docker|com\.docker|adobe|creative cloud|onedrive|dropbox|spotify|slack|teams|ms-teams|discord|zoom|chrome|msedge|firefox|brave|steam|epicgames|jetbrains|idea|pycharm|webstorm|rider|postman|figma|notion|obsidian|1password|logi|razer|corsair|asus|armoury|lghub|icloud|itunes|skype)/i;function ql(t){let e=[];for(let r of t.split(/\r?\n/)){let n=/^\s*TCP\s+(\S+):(\d+)\s+\S+\s+LISTENING\s+(\d+)/i.exec(r);n&&vr.has(n[1])&&e.push({port:Number(n[2]),pid:Number(n[3])})}return e}function Dl(t){let e=new Map;for(let r of t.split(/\r?\n/)){let n=/^"([^"]+)","(\d+)"/.exec(r);n&&e.set(Number(n[2]),n[1])}return e}function Fl(t){let e=[],r="";for(let n of t.split(/\r?\n/))if(n.startsWith("c"))r=n.slice(1);else if(n.startsWith("n")){let i=n.lastIndexOf(":");i>0&&vr.has(n.slice(1,i))&&e.push({port:Number(n.slice(i+1)),process:r})}return e}function Hl(t){let e=[];for(let r of t.split(/\r?\n/)){let n=r.trim().split(/\s+/);if(n[0]!=="LISTEN"||n.length<5)continue;let i=n[3],s=i.lastIndexOf(":");s<0||!vr.has(i.slice(0,s))||e.push({port:Number(i.slice(s+1)),process:/users:\(\("([^"]+)"/.exec(r)?.[1]??""})}return e}function zl(t){let e=new Map;for(let r of t)!Number.isInteger(r.port)||r.port<1024||r.port>65535||Ul.test(r.process)||process.platform==="win32"&&r.port>=49152||(!e.has(r.port)||!e.get(r.port).process&&r.process)&&e.set(r.port,{port:r.port,process:r.process.slice(0,60)});return[...e.values()].sort((r,n)=>r.port-n.port).slice(0,40)}function $l(t,e=1200){return new Promise(r=>{let n=!1,i="",s=()=>/^HTTP\/1\.[01] \d{3}/.test(i),o=l=>{n||(n=!0,a.destroy(),r(l))},a=Nl({host:"localhost",port:t,autoSelectFamily:!0});a.setTimeout(e,()=>o(!1)),a.on("error",()=>o(!1)),a.on("connect",()=>a.write(`HEAD / HTTP/1.1\r
|
|
25
|
+
Host: localhost:`+t+`\r
|
|
26
|
+
Connection: close\r
|
|
27
|
+
User-Agent: amplibee\r
|
|
28
|
+
\r
|
|
29
|
+
`)),a.on("data",l=>{i+=l.toString("latin1"),i.length>=12&&o(s())}),a.on("close",()=>o(s()))})}var rt=null;async function Tr(){if(rt&&Date.now()-rt.at<2e3)return rt.list;let t=[];if(process.platform==="win32"){let[n,i]=await Promise.all([Ut("netstat",["-ano","-p","tcp"]),Ut("tasklist",["/FO","CSV","/NH"])]),s=Dl(i);t=ql(n).map(o=>({port:o.port,process:s.get(o.pid)??""})).filter(o=>!Ml.has(o.process.toLowerCase())).map(o=>({port:o.port,process:o.process.replace(/\.exe$/i,"")}))}else t=Fl(await Ut("lsof",["-nP","-iTCP","-sTCP:LISTEN","-Fpcn"])),t.length===0&&(t=Hl(await Ut("ss",["-ltnpH"])));let e=zl(t),r=await Promise.all(e.map(n=>$l(n.port)));return rt={at:Date.now(),list:e.filter((n,i)=>r[i])},rt.list}import{request as Wl}from"node:http";import{createBrotliDecompress as Gl,createGunzip as Vl,createInflate as jl}from"node:zlib";var qt=90*1024,Yl=32*1024*1024,Kl=3e4,di=new Set(["GET","HEAD","POST","PUT","PATCH","DELETE","OPTIONS"]),Jl=/^(accept|accept-language|authorization|cache-control|content-type|if-[a-z-]+|pragma|range|user-agent|x-[a-z0-9-]+)$/i,Zl=new Set(["connection","keep-alive","transfer-encoding","content-length","content-encoding","set-cookie","set-cookie2","x-frame-options","content-security-policy","content-security-policy-report-only","strict-transport-security","upgrade","trailer","te"]);function Ql(t,e,r){let n={};for(let[i,s]of Object.entries(t))typeof s=="string"&&s.length<4096&&Jl.test(i)&&(n[i.toLowerCase()]=s);return n.host=`localhost:${e}`,n["accept-encoding"]="gzip, deflate, br",r>0&&(n["content-length"]=String(r)),n}function Xl(t){let e={};for(let[r,n]of Object.entries(t))Zl.has(r.toLowerCase())||n===void 0||(e[r.toLowerCase()]=Array.isArray(n)?n.join(", "):n);return e}var Cr=[],kr=!1;function Dt(t){if(Cr.push(t),kr)return;kr=!0;let e=()=>{Cr.shift()?.(),Cr.length?setTimeout(e,6):kr=!1};setTimeout(e,0)}function pi(t,e,r,n,i){let s=!1,o=()=>{s||(s=!0,n())},a=c=>{s||(Dt(()=>r({t:"error",code:"proxy_failed",message:c,reqId:e.reqId})),o())},l=Wl({host:t,port:e.port,method:e.method,path:e.path,headers:Ql(e.headers,e.port,e.body?.length??0),timeout:Kl},c=>{let u=String(c.headers["content-encoding"]??"").toLowerCase(),f=u==="gzip"||u==="x-gzip"?c.pipe(Vl()):u==="deflate"?c.pipe(jl()):u==="br"?c.pipe(Gl()):c;Dt(()=>r({t:"http.head",reqId:e.reqId,status:c.statusCode??502,headers:Xl(c.headers)}));let h=[],d=0,m=0,p=y=>{let _=Buffer.concat(h);h=[],d=0,Dt(()=>r({t:"http.chunk",reqId:e.reqId,data:_.toString("base64"),last:y}))};f.on("data",y=>{if(m+=y.length,m>Yl)return c.destroy(),a("That response is too large to preview.");for(h.push(y),d+=y.length;d>=qt;){let _=Buffer.concat(h);h=[_.subarray(qt)],d=_.length-qt,Dt(()=>r({t:"http.chunk",reqId:e.reqId,data:_.subarray(0,qt).toString("base64"),last:!1}))}}),f.on("end",()=>{s||(p(!0),o())}),f.on("error",()=>a("The page could not be read."))});l.on("timeout",()=>{l.destroy(),a("The server did not answer in time.")}),l.on("error",c=>{if(i&&c.code==="ECONNREFUSED")return pi("::1",e,r,n,!1);a(c.code==="ECONNREFUSED"?"Nothing is listening on that port any more.":"Could not reach that server.")}),e.body&&e.body.length>0&&l.write(e.body),l.end()}function gi(t,e,r){pi("127.0.0.1",t,e,r,!0)}import{closeSync as ec,lstatSync as yi,openSync as tc,readSync as rc,readdirSync as _i,realpathSync as nc,renameSync as wi,rmdirSync as ic,statSync as Be,unlinkSync as bi,writeFileSync as sc}from"node:fs";import{homedir as oc}from"node:os";import{basename as Ir,dirname as Ar,isAbsolute as Pr,join as Br,resolve as Ft,sep as mi}from"node:path";var Le=t=>process.platform==="win32"||process.platform==="darwin"?t.toLowerCase():t;function K(t){try{return nc(t)}catch{return null}}function Oe(t){return t==="~"||t.startsWith("~/")||t.startsWith("~\\")?Ft(oc(),t.slice(2)):Ft(t)}function Ht(t,e){if(!Pr(e))return null;let r=K(e);if(!r)return null;try{if(!Be(r).isDirectory())return null}catch{return null}return Lr(t,r)?r:null}function Lr(t,e){let r=Le(e);for(let n of t){let i=Le(n);if(r===i||r.startsWith(i.endsWith(mi)?i:i+mi))return!0}return!1}function Or(t,e){if(!Pr(e))return null;let r=K(e);if(!r)return null;try{if(!Be(r).isFile())return null}catch{return null}return Lr(t,r)?r:null}var ac=/^(id_(rsa|dsa|ecdsa|ed25519)|\.env.*|\.npmrc|\.netrc|credentials|.*\.(pem|key|p12|pfx|keystore|kdbx))$/i,nt=t=>ac.test(Ir(t));function Ei(t,e){return t.some(r=>Le(r)===Le(e))}function xi(t){try{return _i(t,{withFileTypes:!0}).filter(e=>e.isDirectory()&&!e.name.startsWith(".")&&e.name!=="node_modules").map(e=>e.name).sort((e,r)=>e.localeCompare(r)).slice(0,300)}catch{return[]}}function Si(t){let e=[],r=[];try{for(let i of _i(t,{withFileTypes:!0}))if(!(i.name.startsWith(".")||i.name==="node_modules")){if(i.isDirectory())e.push(i.name);else if(i.isFile()){let s=0;try{s=Be(Ft(t,i.name)).size}catch{}r.push({name:i.name,size:s})}}}catch{}let n=(i,s)=>(typeof i=="string"?i:i.name).localeCompare(typeof s=="string"?s:s.name);return{dirs:e.sort(n).slice(0,300),files:r.sort(n).slice(0,500)}}function vi(t,e){let r=Be(t),n=r.size,i=Math.floor(r.mtimeMs),s=tc(t,"r");try{let o=Buffer.alloc(Math.min(n,e)),a=rc(s,o,0,o.length,0),l=o.subarray(0,a);if(l.includes(0))return{size:n,mtime:i,text:null,binary:!0,truncated:!1};let c=l.toString("utf8"),u=n>a;return!u&&!Buffer.from(c,"utf8").equals(l)?{size:n,mtime:i,text:null,binary:!0,truncated:!1}:{size:n,mtime:i,text:c,binary:!1,truncated:u}}finally{ec(s)}}function Ti(t,e,r){let n=Be(t);if(Math.floor(n.mtimeMs)!==Math.floor(r))throw Object.assign(new Error("The file changed on the workspace."),{code:"conflict"});let i=Br(Ar(t),`.${Ir(t)}.amplibee-${process.pid}.tmp`);sc(i,e,{mode:n.mode&511});try{wi(i,t)}catch(o){try{bi(i)}catch{}throw o}let s=Be(t);return{size:s.size,mtime:Math.floor(s.mtimeMs)}}function Ci(t,e){if(!Pr(e))return null;let r=K(Ar(Ft(e)));if(!r||!Lr(t,r))return null;let n=Br(r,Ir(e)),i;try{i=yi(n)}catch{return null}return!i.isSymbolicLink()&&Ei(t,K(n)??n)?null:{entry:n,folder:r,isDir:i.isDirectory()}}var lc=/[\\/:*?"<>|\0]/;function ki(t,e,r){let n=Ci(t,e);if(!n)throw Object.assign(new Error("outside"),{code:"bad_file"});if(!r||r.length>200||r==="."||r===".."||lc.test(r)||r!==r.trim())throw Object.assign(new Error("bad name"),{code:"bad_name"});let i=Br(n.folder,r);try{if(yi(i),Le(i)!==Le(n.entry))throw Object.assign(new Error("exists"),{code:"exists"})}catch(s){if(s.code==="exists")throw s}return wi(n.entry,i),i}function Ii(t,e){let r=Ci(t,e);if(!r)throw Object.assign(new Error("outside"),{code:"bad_file"});if(r.isDir){try{ic(r.entry)}catch{throw Object.assign(new Error("not empty"),{code:"not_empty"})}return}bi(r.entry)}var Rr=(t,e)=>Ei(t,e)?null:Ar(e);var zt=(t,e)=>typeof t=="string"&&t.length>0&&t.length<=e?t:null,cc=64*1024,uc=10,fc=200,hc=12,Ai=16*1024,$t=class{constructor(e){this.o=e;this.roots=e.roots.map(r=>K(Oe(r))??Oe(r)),e.manager.onChange=()=>this.o.send({t:"sessions",sessions:e.manager.list()})}roots;subs=new Map;proxying=0;proxyWaiting=[];pending=new Map;notifiers=new Map;host(){return{name:this.o.cfg.name,platform:process.platform,agentVersion:this.o.version,roots:this.roots,harnesses:tt(oe(this.o.cfg,this.o.allowShell))}}connected(){this.subs.clear()}watch(e){e.info.harness!=="shell"&&this.notifiers.set(e.id,new Mt({emit:(r,n)=>this.o.send({t:"session.notice",id:e.id,kind:r,title:e.info.title,workspace:this.o.cfg.name,detail:n})})),e.onData(r=>{this.notifiers.get(e.id)?.feed(r);let n=this.subs.get(e.id);if(!n||n.size===0)return;let i=this.pending.get(e.id);i?i.buf+=r:this.pending.set(e.id,{buf:r,timer:setTimeout(()=>this.flush(e.id),hc)})}),e.onExit(r=>{this.notifiers.get(e.id)?.exit(r),this.notifiers.delete(e.id),this.flush(e.id);for(let n of this.subs.get(e.id)??[])this.o.send({t:"session.exit",id:e.id,code:r,cid:n})})}flush(e){let r=this.pending.get(e);if(r){clearTimeout(r.timer),this.pending.delete(e);for(let n of this.subs.get(e)??[])this.output(e,n,r.buf,!1)}}output(e,r,n,i){if(n.length<=Ai)return this.o.send({t:"session.output",id:e,data:n,replay:i||void 0,cid:r});for(let s=0;s<n.length;){let o=Math.min(s+Ai,n.length),a=n.charCodeAt(o-1);o<n.length&&a>=55296&&a<=56319&&o--,this.o.send({t:"session.output",id:e,data:n.slice(s,o),replay:i&&s===0?!0:void 0,cid:r}),s=o}}subscribe(e,r){let n=this.subs.get(e);n||this.subs.set(e,n=new Set),n.add(r)}handle(e){let r=typeof e.cid=="string"?e.cid:void 0,n=s=>this.o.send({...s,cid:r}),i=(s,o)=>n({t:"error",code:s,message:o,reqId:typeof e.reqId=="string"?e.reqId:void 0});if(r)try{this.dispatch(e,r,n,i)}catch(s){i("failed",s instanceof Error?s.message:"Something went wrong on the workspace.")}}dispatch(e,r,n,i){let s=this.o.manager,o=()=>{let a=zt(e.id,40),l=a?s.get(a):void 0;return l||i("no_session","That session no longer exists."),l??null};switch(e.t){case"app.left":for(let a of this.subs.values())a.delete(r);return;case"host.get":return n({t:"host",host:this.host()});case"sessions.list":return n({t:"sessions",sessions:s.list()});case"session.start":{let a=zt(e.harness,24),l=a?oe(this.o.cfg,this.o.allowShell)[a]:void 0;if(!a||!l)return i("unknown_harness","That agent is not enabled on this workspace.");let c=Nt(l);if(!c)return i("not_installed",`"${l.command}" is not installed on this workspace.`);let u=e.cwd===void 0?this.roots[0]:Ht(this.roots,String(e.cwd));if(!u)return i("bad_folder","That folder is outside the folders this workspace shares.");let{cols:f,rows:h}=Pe(e.cols,e.rows),d=s.start({harness:a,title:l.label??a,file:c.file,args:c.args,cwd:u,cols:f,rows:h});return this.watch(d),this.subscribe(d.id,r),n({t:"session.started",session:d.info,reqId:typeof e.reqId=="string"?e.reqId:void 0})}case"session.attach":{let a=o();if(!a)return;if(this.subscribe(a.id,r),!a.opts.local&&e.cols!==void 0){let l=Pe(e.cols,e.rows);a.resize(l.cols,l.rows)}this.output(a.id,r,a.scrollback(),!0),a.running||n({t:"session.exit",id:a.id,code:a.exitCode});return}case"session.input":{let a=o(),l=typeof e.data=="string"&&e.data.length<=cc?e.data:null;a&&l!==null&&(this.notifiers.get(a.id)?.input(),a.write(l));return}case"session.resize":{let a=o();a&&a.resize(Number(e.cols),Number(e.rows));return}case"session.kill":return o()?.kill();case"session.remove":{let a=zt(e.id,40);a&&(s.remove(a),this.subs.delete(a));return}case"dir.list":{let a=e.path===void 0||e.path===""?this.roots[0]:Ht(this.roots,String(e.path));return a?n({t:"dirs",path:a,parent:Rr(this.roots,a),entries:xi(a),reqId:typeof e.reqId=="string"?e.reqId:void 0}):i("bad_folder","That folder is outside the folders this workspace shares.")}case"fs.list":{let a=e.path===void 0||e.path===""?this.roots[0]:Ht(this.roots,String(e.path));if(!a)return i("bad_folder","That folder is outside the folders this workspace shares.");let{dirs:l,files:c}=Si(a);return n({t:"fs.entries",path:a,parent:Rr(this.roots,a),dirs:l,files:c,reqId:typeof e.reqId=="string"?e.reqId:void 0})}case"fs.read":{let a=Or(this.roots,String(e.path??""));if(!a)return i("bad_file","That file is outside the folders this workspace shares.");if(nt(a))return i("secret_file","Files that usually hold secrets (keys, .env) are never shown here.");let l=vi(a,Y.fileViewBytes);return n({t:"fs.file",path:a,...l,reqId:typeof e.reqId=="string"?e.reqId:void 0})}case"fs.write":{let a=Or(this.roots,String(e.path??""));if(!a)return i("bad_file","That file is outside the folders this workspace shares.");if(nt(a))return i("secret_file","Files that usually hold secrets (keys, .env) are never edited here.");if(typeof e.text!="string"||Buffer.byteLength(e.text,"utf8")>Y.fileViewBytes)return i("too_large",`Files can be edited here up to ${Math.round(Y.fileViewBytes/1024)} KB.`);try{let l=Ti(a,e.text,Number(e.mtime));return n({t:"fs.saved",path:a,...l,reqId:typeof e.reqId=="string"?e.reqId:void 0})}catch(l){return l.code==="conflict"?i("conflict","This file changed on the workspace since you opened it. Reload it to see the new version."):i("write_failed","Could not save the file. It may be read-only on the workspace.")}}case"fs.rename":{let a=String(e.path??""),l=typeof e.name=="string"?e.name:"";if(nt(a))return i("secret_file","Files that usually hold secrets (keys, .env) are never changed here.");try{let c=ki(this.roots,a,l);return n({t:"fs.done",op:"rename",path:a,newPath:c,reqId:typeof e.reqId=="string"?e.reqId:void 0})}catch(c){let u=c.code;return u==="bad_file"?i("bad_file","That is outside the folders this workspace shares."):u==="bad_name"?i("bad_name",'Use a plain name: no slashes and none of : * ? " < > |'):u==="exists"?i("exists","Something with that name already exists here."):i("failed","Could not rename it.")}}case"fs.remove":{let a=String(e.path??"");if(nt(a))return i("secret_file","Files that usually hold secrets (keys, .env) are never changed here.");try{return Ii(this.roots,a),n({t:"fs.done",op:"remove",path:a,reqId:typeof e.reqId=="string"?e.reqId:void 0})}catch(l){let c=l.code;return c==="bad_file"?i("bad_file","That is outside the folders this workspace shares."):c==="not_empty"?i("not_empty","Only empty folders can be removed here. Delete what is inside first."):i("failed","Could not delete it.")}}case"ports.list":{(this.o.ports??Tr)().then(a=>n({t:"ports",ports:a,reqId:typeof e.reqId=="string"?e.reqId:void 0}));return}case"http.fetch":{let a=zt(e.reqId,80),l=Number(e.port),c=String(e.method??"").toUpperCase(),u=typeof e.path=="string"?e.path:"";if(!a)return i("bad_request","Missing request id.");if(!Number.isInteger(l)||!di.has(c)||!/^\/[^\s]*$/.test(u)||u.length>4e3)return i("bad_request","That request is not allowed.");let f=typeof e.body=="string"&&e.body.length>0?Buffer.from(e.body,"base64"):null;if(f&&f.length>150*1024)return i("too_large","That request body is too large for the preview.");if(this.proxyWaiting.length>=fc)return i("busy","Too many requests at once. Try again.");let h=e.headers&&typeof e.headers=="object"?e.headers:{},d=()=>{this.proxying++;let m=()=>{this.proxying--,this.proxyWaiting.shift()?.()};(this.o.ports??Tr)().then(p=>{if(!p.some(y=>y.port===l))return m(),n({t:"error",code:"no_server",message:"Nothing is listening on that port.",reqId:a});gi({reqId:a,port:l,method:c,path:u,headers:h,body:f},n,m)},m)};this.proxying>=uc?this.proxyWaiting.push(d):d();return}default:return i("unknown_message","Unknown message.")}}};var Pi=20;async function Wt(t){if(t.identity)try{return await xr(t.identity)}catch{}let e=await Qe(!0);return t.identity=await Xe(e),t.apps=[],j(t),e}var it={at:0,keys:[]};function Bi(){return Date.now()-it.at>2e3&&(it={at:Date.now(),keys:(V()?.apps??[]).map(t=>t.pub)}),it.keys}async function st(t){q(t);let e=V();if(!e)throw new Error("This workspace is not logged in.");let r=(e.apps??[]).filter(i=>i.pub!==t);if(r.length>=Pi)throw new Error(`You can link up to ${Pi} browsers. Remove one with "amplibee apps remove <fingerprint>".`);let n={pub:t,fingerprint:await ee(q(t)),addedAt:new Date().toISOString()};return e.apps=[...r,n],j(e),it={at:0,keys:[]},n}function Nr(t){let e=V();if(!e)return 0;let r=i=>i.toUpperCase().replace(/[^A-Z]/g,""),n=e.apps??[];return e.apps=n.filter(i=>r(i.fingerprint)!==r(t)),j(e),it={at:0,keys:[]},n.length-e.apps.length}var zo=X(Ho(),1);import{createHash as Af,randomBytes as Pf}from"node:crypto";import{spawn as Bf}from"node:child_process";import{hostname as Lf,platform as Of,release as Rf}from"node:os";import{createInterface as Nf}from"node:readline/promises";async function kn(t,e,r,n={}){let i;try{i=await fetch(t+e,{method:"POST",headers:{"content-type":"application/json",...n},body:JSON.stringify(r),signal:AbortSignal.timeout(2e4)})}catch{throw new Error(`Could not reach ${t}. Check your internet connection.`)}let s=null;try{s=await i.json()}catch{}if(!i.ok||!s?.ok||s.data===null)throw Object.assign(new Error(s?.error?.message??`The server answered with status ${i.status}.`),{status:i.status,code:s?.error?.code});return s.data}function $o(t){try{let[e,r]=process.platform==="win32"?["cmd",["/c","start","",t]]:process.platform==="darwin"?["open",[t]]:["xdg-open",[t]];Bf(e,r,{stdio:"ignore",detached:!0}).on("error",()=>{}).unref()}catch{}}async function Wo(t,e){let r=Date.now()+e.expires_in*1e3;for(;Date.now()<r;){await new Promise(n=>setTimeout(n,e.interval*1e3));try{let n=await kn(t,"/devices/pair/poll",{device_code:e.device_code});if(n.status==="approved")return n}catch(n){let i=n.status;if(i===410)break;if(i&&i<500&&i!==429)throw n}}throw new Error("The code expired. Run the command again.")}async function Mf(t){let e=Nf({input:process.stdin,output:process.stdout});try{return await e.question(t)}finally{e.close()}}async function Go(t,e,r){let n;try{n=await ee(q(t))}catch{return r(" The app sent a key that is not valid, so nothing was linked."),!1}if(r(""),r(" The app approved. Check that it shows the same fingerprint for this browser:"),r(""),r(` ${n}`),r(""),e.trustApp){let s=li(e.trustApp,n);return r(s?" It matches --trust-app.":" It does NOT match --trust-app, so the browser was not linked."),s}if(!process.stdin.isTTY)return r(" There is nobody here to confirm it. Run this in a terminal, or pass --trust-app <fingerprint>."),!1;let i=await Mf(" Press Enter (or type y) only if it is exactly the same, or n to cancel: ");return/^(y(es)?)?$/i.test(i.trim())}async function Vo(t,e,r,n){n(""),n(` ${r}`),n(` ${t.verification_url}`);try{let i=await zo.default.toString(t.verification_url,{type:"utf8",errorCorrectionLevel:"L"});n("");for(let s of i.split(/\r?\n/))n(` ${s}`)}catch{}n(""),n(` Code: ${t.user_code}`),n(` Fingerprint: ${e}`),n(""),n(" The app shows this fingerprint too. Continue only if they are the same."),n(` Waiting for approval (the code works for ${Math.round(t.expires_in/60)} minutes)...`)}async function jo(t){let e=t.log??console.log,r=Pf(32).toString("hex"),n=(t.name||Lf()||"my workspace").slice(0,60),i=await Qe(!0),s=await kn(t.apiUrl,"/devices/pair",{name:n,platform:`${Of()} ${Rf()}`.slice(0,40),agent_version:t.version,token_hash:Af("sha256").update(r).digest("hex"),agent_pub:D(i.pub)});await Vo(s,await ee(i.pub),"Scan the QR code with your phone, or open this page and confirm the code:",e),t.openBrowser&&$o(s.verification_url);let o=await Wo(t.apiUrl,s),a={apiUrl:t.apiUrl,deviceId:o.device_id,secret:r,name:n,identity:await Xe(i),apps:[]};j(a);let l=await Go(o.app_pub,t,e);return l&&await st(o.app_pub),{cfg:a,linked:l}}async function Yo(t,e){let r=e.log??console.log,n=await Wt(t),i=await kn(t.apiUrl,"/devices/link",{agent_pub:D(n.pub),agent_version:e.version},{authorization:`Bearer ${t.secret}`});await Vo(i,await ee(n.pub),'Open the workspace in the Amplibee app and choose "Link this browser", or scan the QR code:',r),e.openBrowser&&$o(i.verification_url);let s=await Wo(t.apiUrl,i),o=await Go(s.app_pub,{...e,apiUrl:t.apiUrl},r);return o&&await st(s.app_pub),o}var ad=X($a(),1),ld=X(fr(),1),cd=X(Ge(),1),ud=X(Fn(),1),fd=X($n(),1),hd=X(Yn(),1),Qa=X(pr(),1),dd=X(Za(),1);var Jn=Qa.default;var It=class extends Error{};function pd(t){return t.replace(/^http/,"ws").replace(/\/$/,"")+"/relay/agent"}var mr=class{constructor(e){this.o=e;this.fatal=new Promise(r=>this.die=r)}ws=null;attempt=0;stopped=!1;watchdog;retry;fatal;die;get connected(){return this.ws?.readyState===Jn.OPEN}start(){this.open()}stop(){this.stopped=!0,clearTimeout(this.retry),clearInterval(this.watchdog),this.ws?.close(1e3)}send(e){return this.connected?(this.ws.send(JSON.stringify(e)),!0):!1}open(){if(this.stopped)return;let e=new Jn(pd(this.o.apiUrl),{headers:{authorization:`Bearer ${this.o.secret}`,"x-amplibee-agent":this.o.version},handshakeTimeout:15e3,maxPayload:512*1024});this.ws=e;let r=Date.now();e.on("open",()=>{this.attempt=0,r=Date.now(),this.o.log("connected to Amplibee"),this.o.onUp()}),e.on("ping",()=>r=Date.now()),e.on("message",n=>{r=Date.now();try{let i=JSON.parse(n.toString());i&&typeof i.t=="string"&&this.o.onMessage(i)}catch{}}),e.on("unexpected-response",(n,i)=>{i.resume(),i.statusCode===401?this.die(new It('This workspace was removed from your account (or its login is no longer valid). Run "amplibee login" again.')):this.o.log(`relay answered ${i.statusCode}`),e.terminate()}),e.on("error",n=>this.o.log(`connection problem: ${n.message}`)),e.on("close",n=>{if(clearInterval(this.watchdog),this.o.onDown(),n===4001)return this.die(new It('This workspace was removed from your account. Run "amplibee login" to connect it again.'));if(n===4e3)return this.die(new It("Another amplibee process for this workspace connected, so this one stopped. Run only one at a time."));this.schedule()}),clearInterval(this.watchdog),this.watchdog=setInterval(()=>{Date.now()-r>75e3&&e.terminate()},1e4)}schedule(){if(this.stopped)return;let e=Math.min(3e4,1e3*2**Math.min(this.attempt++,5)),r=e/2+Math.random()*(e/2);this.o.log(`reconnecting in ${Math.round(r/1e3)}s`),this.retry=setTimeout(()=>this.open(),r)}};var gd=32,md=5*6e4,yd=5,_d=2e3,yr=class{chans=new Map;requests=new Map;lastAsk=new Map;o;constructor(e){this.o=e}reset(){this.chans.clear(),this.lastAsk.clear()}get channels(){return this.chans.size}async fromRelay(e){let r=typeof e.cid=="string"&&e.cid.length>0&&e.cid.length<=32?e.cid:null;if(r){if(e.t==="app.left")return this.chans.delete(r),this.lastAsk.delete(r),this.o.deliver({t:"app.left",cid:r});if(e.t==="e2e.hello")return this.hello(r,e);if(e.t==="e2e.data")return this.data(r,{n:e.n,c:e.c});if(e.t==="e2e.request")return this.request(r,e.pub)}}async hello(e,r){if(!this.chans.has(e)&&this.chans.size>=gd)return;let n=null;try{let i=this.o.trusted();n=await ci(this.o.identity,r,s=>i.includes(D(s)))}catch{}if(!n)return this.o.transmit({t:"e2e.reject",cid:e,code:"not_linked"});this.chans.set(e,{chan:n.channel,app:D(n.appPub)}),this.o.transmit({t:"e2e.accept",cid:e,...n.accept}),this.sendTo(e,{t:"secure"}),this.sendTo(e,{t:"link.pending",requests:this.pending()})}async data(e,r){let n=this.chans.get(e);if(!n)return;if(!this.o.trusted().includes(n.app))return this.chans.delete(e),this.o.transmit({t:"e2e.reject",cid:e,code:"not_linked"});let i=await n.chan.open(r);if(!(!i||typeof i.t!="string"||i.t.length>40)){if(i.t.startsWith("apps."))return this.manage(e,n,i);this.o.deliver({...i,t:i.t,cid:e})}}pending(){let e=Date.now();for(let[r,n]of this.requests)e-n>md&&this.requests.delete(r);return[...this.requests].map(([r,n])=>({pub:r,at:n}))}tellPending(){this.send({t:"link.pending",requests:this.pending()})}request(e,r){if(!this.o.apps||!Ze(r)||this.o.trusted().includes(r))return;let n=Date.now();if(!(n-(this.lastAsk.get(e)??0)<_d)){if(this.lastAsk.set(e,n),this.pending(),!this.requests.has(r)&&this.requests.size>=yd){let i=[...this.requests].sort((s,o)=>s[1]-o[1])[0];i&&this.requests.delete(i[0])}this.requests.set(r,n),this.o.transmit({t:"e2e.waiting",cid:e,agent:D(this.o.identity.pub)}),this.tellPending()}}async manage(e,r,n){let i=this.o.apps;if(!i)return;let s=(l,c)=>this.sendTo(e,{t:"error",code:l,message:c}),o=()=>i.list().map(l=>({fingerprint:l.fingerprint,addedAt:l.addedAt,current:l.pub===r.app})),a=typeof n.pub=="string"?n.pub:"";switch(n.t){case"apps.list":return this.sendTo(e,{t:"apps",apps:o()});case"apps.approve":{if(n.account===!0&&this.o.requireApproval?.())return s("approval_required","High security is on for this workspace: the passphrase cannot link it. Approve each new browser by comparing fingerprints.");if(!this.pending().some(l=>l.pub===a))return s("no_request","That browser is not waiting any more. Ask it to send the request again.");try{await i.add(a)}catch(l){return s("link_failed",l instanceof Error?l.message:"Could not link that browser.")}return this.requests.delete(a),this.tellPending(),this.sendTo(e,{t:"apps",apps:o()})}case"apps.deny":return this.requests.delete(a),this.tellPending();case"apps.remove":{let l=typeof n.fingerprint=="string"?n.fingerprint:"",c=i.list().find(u=>u.pub===r.app);return c&&c.fingerprint.replace(/[^A-Z]/gi,"").toUpperCase()===l.replace(/[^A-Z]/gi,"").toUpperCase()?s("self",'This is the browser you are using. Remove it from another one, or on the workspace with "amplibee apps remove".'):i.remove(l)===0?s("not_found","No linked browser has that fingerprint."):this.sendTo(e,{t:"apps",apps:o()})}}}send(e){let{cid:r,...n}=e;if(r)this.sendTo(r,n);else for(let i of[...this.chans.keys()])this.sendTo(i,n)}sendTo(e,r){let n=this.chans.get(e);n&&n.chan.seal(r).then(i=>this.o.transmit({t:"e2e.data",cid:e,...i})).catch(()=>{})}};import{randomBytes as wd}from"node:crypto";var Xa=8,bd=24,Zn=class{constructor(e,r){this.pty=e;this.opts=r;this.cols=r.cols,this.rows=r.rows,e.onData(n=>{this.keep(n);for(let i of this.listeners)i(n)}),e.onExit(n=>{this.running=!1,this.exitCode=n.exitCode;for(let i of this.exitListeners)i(n.exitCode)})}id=wd(6).toString("hex");startedAt=Date.now();running=!0;exitCode=null;cols;rows;chunks=[];size=0;onResize=()=>{};listeners=new Set;exitListeners=new Set;get info(){return{id:this.id,harness:this.opts.harness,title:this.opts.title,cwd:this.opts.cwd,cols:this.cols,rows:this.rows,startedAt:this.startedAt,running:this.running,exitCode:this.exitCode,local:!!this.opts.local}}keep(e){for(this.chunks.push(e),this.size+=e.length;this.size>Y.scrollbackBytes&&this.chunks.length>1;)this.size-=this.chunks.shift().length}scrollback(){return this.chunks.join("")}onData(e){return this.listeners.add(e),()=>this.listeners.delete(e)}onExit(e){return this.exitListeners.add(e),()=>this.exitListeners.delete(e)}write(e){this.running&&this.pty.write(e)}resize(e,r){let n=Pe(e,r),i=n.cols!==this.cols||n.rows!==this.rows;if(this.cols=n.cols,this.rows=n.rows,this.running)try{this.pty.resize(n.cols,n.rows)}catch{}i&&this.onResize()}kill(){this.running&&this.pty.kill()}},At=class{constructor(e){this.spawn=e}sessions=new Map;onChange=()=>{};list(){return[...this.sessions.values()].map(e=>e.info)}get(e){return this.sessions.get(e)}runningCount(){return[...this.sessions.values()].filter(e=>e.running).length}start(e){if(this.runningCount()>=Xa)throw new Error(`At most ${Xa} sessions can run at once. Close one first.`);let r=Pe(e.cols,e.rows),n={};for(let[o,a]of Object.entries(process.env))typeof a=="string"&&(n[o]=a);n.TERM="xterm-256color",n.COLORTERM="truecolor",n.AMPLIBEE_SESSION="1";let i=this.spawn(e.file,e.args,{cwd:e.cwd,cols:r.cols,rows:r.rows,env:n}),s=new Zn(i,{...e,...r});return this.sessions.set(s.id,s),s.onExit(()=>this.onChange()),s.onResize=()=>this.onChange(),this.trim(),this.onChange(),s}remove(e){let r=this.sessions.get(e);return r?(r.kill(),this.sessions.delete(e),this.onChange(),!0):!1}killAll(){for(let e of this.sessions.values())e.kill()}trim(){let e=[...this.sessions.values()].filter(r=>!r.running);for(let r of e.slice(0,Math.max(0,this.sessions.size-bd)))this.sessions.delete(r.id)}};async function Qn(){let t=await import("@lydell/node-pty");return(e,r,n)=>{let i=t.spawn(e,r,{name:"xterm-256color",cols:n.cols,rows:n.rows,cwd:n.cwd,env:n.env});return{onData:s=>void i.onData(s),onExit:s=>void i.onExit(s),write:s=>i.write(s),resize:(s,o)=>i.resize(s,o),kill:()=>i.kill()}}}var me="0.1.3",xd=`amplibee ${me}: steer Claude Code, Codex or any terminal agent from your phone.
|
|
22
30
|
|
|
23
31
|
Usage
|
|
24
32
|
amplibee login [--name "My laptop"] [--api URL] [--no-open]
|
|
@@ -26,7 +34,9 @@ Usage
|
|
|
26
34
|
amplibee link [--no-open] [--trust-app FINGERPRINT]
|
|
27
35
|
Link another browser or phone to this workspace. Each one is linked once, by comparing fingerprints.
|
|
28
36
|
amplibee apps [remove <fingerprint>] Browsers that can open sessions on this workspace.
|
|
29
|
-
amplibee
|
|
37
|
+
amplibee approvals [on|off] High security: on = the passphrase cannot link this workspace, every new browser
|
|
38
|
+
is approved by comparing fingerprints. Applies to all new links until you turn it off.
|
|
39
|
+
amplibee start [--root DIR]... [--allow-shell] [--require-approval]
|
|
30
40
|
Stay connected and let the app start agents in the folders you share (default: the current folder).
|
|
31
41
|
amplibee run <agent> [args...] e.g. amplibee run claude
|
|
32
42
|
amplibee run -- <command> [args...] any other terminal program
|
|
@@ -39,45 +49,53 @@ Usage
|
|
|
39
49
|
|
|
40
50
|
Options for start and run
|
|
41
51
|
--root DIR A folder the app may start agents in (repeat for more). Nothing outside these is reachable.
|
|
52
|
+
--require-approval High security for this run only (same as approvals on, without saving it).
|
|
42
53
|
--allow-shell Also offer a plain terminal (powershell or your shell). Off by default.
|
|
43
54
|
|
|
44
|
-
The workspace only makes outgoing connections to Amplibee. Nothing here listens on a port.`,
|
|
55
|
+
The workspace only makes outgoing connections to Amplibee. Nothing here listens on a port.`,el=!1,Sd=new Set(["name","api","root","trust-app"]);function vd(t){let e=new Map,r=[],n="",i=!1;for(let s=0;s<t.length;s++){let o=t[s];if(o==="--"){i=!0,r.push(...t.slice(s+1));break}if(n==="run"&&r.length>0)r.push(o);else if(o.startsWith("--")){let[a,l]=o.slice(2).split("="),c=Sd.has(a)?l??t[++s]??"":"true";e.set(a,[...e.get(a)??[],c])}else n?r.push(o):n=o}return{cmd:n,rest:r,flags:e,dashed:i}}var _r=(t,e)=>t.flags.get(e)?.[0],Ie=(t,e)=>t.flags.has(e);function P(t){console.error(`
|
|
45
56
|
${t}
|
|
46
|
-
`),process.exit(1)}function
|
|
47
|
-
Reinstall with: npm i -g amplibee`))),
|
|
57
|
+
`),process.exit(1)}function Pt(){return V()??P('This workspace is not connected yet. Run "amplibee login" first.')}function Td(t){console.log(`${new Date().toLocaleTimeString()} ${t}`)}async function tl(t,e,r,n){let i=new At(await Qn().catch(l=>P(`The terminal component could not be loaded: ${l.message}
|
|
58
|
+
Reinstall with: npm i -g amplibee`))),s,o=new yr({identity:await Wt(t),trusted:Bi,requireApproval:()=>el||V()?.requireApproval===!0,apps:{list:()=>V()?.apps??[],add:async l=>n(`Linked a new browser (${(await st(l)).fingerprint}), approved from a linked one.`),remove:Nr},deliver:l=>a.handle(l),transmit:l=>void s.send(l)}),a=new $t({cfg:t,roots:e,allowShell:r,version:me,manager:i,send:l=>o.send(l)});return s=new mr({apiUrl:t.apiUrl,secret:t.secret,version:me,log:n,onUp:()=>{o.reset(),a.connected()},onDown:()=>o.reset(),onMessage:l=>void o.fromRelay(l)}),s.start(),{manager:i,daemon:a,relay:s}}async function Cd(t){let e=(_r(t,"api")??process.env.AMPLIBEE_API_URL??ti).replace(/\/$/,"");!/^https:\/\//.test(e)&&!/^http:\/\/(localhost|127\.0\.0\.1)(:|\/|$)/.test(e)&&P("The API address must use https (http is only accepted for localhost).");let{cfg:r,linked:n}=await jo({apiUrl:e,name:_r(t,"name"),version:me,openBrowser:!Ie(t,"no-open"),trustApp:_r(t,"trust-app")});console.log(n?`
|
|
48
59
|
Connected as "${r.name}" and linked the browser. Sessions are end-to-end encrypted. Next:
|
|
49
60
|
amplibee start keep this workspace available from the app
|
|
50
61
|
amplibee run claude run Claude Code here and continue it from your phone
|
|
51
62
|
`:`
|
|
52
63
|
"${r.name}" is connected, but that browser was NOT linked, so it cannot open sessions yet.
|
|
53
64
|
Run "amplibee link" and try again.
|
|
54
|
-
`)}async function
|
|
65
|
+
`)}async function kd(t){let e=Pt(),r=await Yo(e,{version:me,openBrowser:!Ie(t,"no-open"),trustApp:_r(t,"trust-app")});console.log(r?`
|
|
55
66
|
Browser linked. It can open sessions on this workspace now.
|
|
56
67
|
`:`
|
|
57
68
|
Not linked.
|
|
58
|
-
`),r||(process.exitCode=1)}function
|
|
69
|
+
`),r||(process.exitCode=1)}function Id(t){let e=Pt(),[r,n]=t.rest;if(r==="remove"){n||P("Usage: amplibee apps remove <fingerprint>");let s=Nr(n);return console.log(s?`
|
|
59
70
|
Removed. That browser can no longer open sessions here (it is cut off within a couple of seconds).
|
|
60
71
|
`:`
|
|
61
72
|
No linked browser has that fingerprint.
|
|
62
|
-
`)}let
|
|
73
|
+
`)}let i=e.apps??[];if(i.length===0)return console.log(`
|
|
63
74
|
No browser is linked yet. Run "amplibee link".
|
|
64
|
-
`);console.log("");for(let
|
|
75
|
+
`);console.log("");for(let s of i)console.log(` ${s.fingerprint} linked ${new Date(s.addedAt).toLocaleString()}`);console.log(`
|
|
65
76
|
Remove one with: amplibee apps remove <fingerprint>
|
|
66
|
-
`)}async function
|
|
67
|
-
amplibee ${me} "${e.name}" -> ${e.apiUrl}`);let a=e.apps?.length??0;console.log(` Encryption: end to end. Workspace fingerprint ${e.identity?await
|
|
68
|
-
`);let l=()=>{
|
|
77
|
+
`)}async function Ad(t){let e=Pt(),r=(t.flags.get("root")??[process.cwd()]).map(u=>K(Oe(u))??P(`The folder "${u}" does not exist.`)),n=Ie(t,"allow-shell"),{manager:i,daemon:s,relay:o}=await tl(e,r,n,Td);console.log(`
|
|
78
|
+
amplibee ${me} "${e.name}" -> ${e.apiUrl}`);let a=e.apps?.length??0;console.log(` Encryption: end to end. Workspace fingerprint ${e.identity?await ee(Buffer.from(e.identity.pub,"base64url")):"(new)"}, ${a} linked browser${a===1?"":"s"}`),a===0&&console.log(' No browser is linked yet, so the app cannot open sessions. Run "amplibee link" in another terminal.'),console.log(` Shared folders: ${s.roots.join(", ")}`),console.log(` Agents: ${tt(oe(e,n)).filter(u=>u.available).map(u=>u.id).join(", ")||"none found on PATH"}${n?" (plain terminal ON)":""}`),console.log(` Press Ctrl+C to stop; sessions started from the app end with it.
|
|
79
|
+
`);let l=()=>{i.killAll(),o.stop(),process.exit(0)};process.on("SIGINT",l),process.on("SIGTERM",l);let c=await o.fatal;i.killAll(),P(c.message)}async function Pd(t){t.rest.length===0&&P("Say what to run, for example: amplibee run claude");let e=V(),r=e?oe(e,Ie(t,"allow-shell")):oe({},!1),n=t.dashed,[i,...s]=t.rest,o=i,a=i,l=s,c=n?void 0:r[i];c?(a=c.command,l=[...c.args??[],...s]):!n&&!Rt.test(i)&&P(`"${i}" is not a known agent. Use "amplibee run -- ${i}" to run any command.`);let u=Nt({command:a,args:l});u||P(`"${a}" was not found on this workspace.`),o=c?i:Ed(a).replace(/\.\w+$/,"").toLowerCase().replace(/[^a-z0-9_-]/g,"")||"custom";let f=K(process.cwd())??process.cwd(),h=[f,...(t.flags.get("root")??[]).map(E=>K(Oe(E))??P(`The folder "${E}" does not exist.`))],d=()=>{},m=await Qn().catch(E=>P(`The terminal component could not be loaded: ${E.message}`)),p=new At(m),y=null,_=null;if(e){let E=await tl(e,h,Ie(t,"allow-shell"),d);p=E.manager,y=E.relay,_=E.daemon,y.fatal.then(U=>process.stderr.write(`\r
|
|
69
80
|
[amplibee] ${U.message}\r
|
|
70
81
|
`))}else process.stderr.write(`[amplibee] not connected to an account, so this session is not visible in the app. Run "amplibee login".
|
|
71
|
-
`);let B=process.stdout,O=p.start({harness:o,title:c?.label??o,file:
|
|
82
|
+
`);let B=process.stdout,O=p.start({harness:o,title:c?.label??o,file:u.file,args:u.args,cwd:f,cols:B.columns||80,rows:B.rows||24,local:!0});_?.watch(O),O.onData(E=>B.write(E));let S=process.stdin.isTTY;S&&process.stdin.setRawMode(!0),process.stdin.setEncoding("utf8"),process.stdin.on("data",E=>O.write(E)),process.stdin.resume(),B.on("resize",()=>O.resize(B.columns||80,B.rows||24)),O.onExit(E=>{S&&process.stdin.setRawMode(!1),y?.stop(),process.exit(E??0)});let T=()=>{O.kill()};process.on("SIGTERM",T),process.on("SIGHUP",T)}async function Bd(){let t=V();if(!t)return console.log(`
|
|
72
83
|
Not connected. Run "amplibee login".
|
|
73
|
-
`);let e=t.identity?await
|
|
84
|
+
`);let e=t.identity?await ee(Buffer.from(t.identity.pub,"base64url")):'none yet (made on the next "amplibee start")';console.log(`
|
|
74
85
|
Workspace: ${t.name}
|
|
75
86
|
Server: ${t.apiUrl}
|
|
76
87
|
Device: ${t.deviceId}
|
|
77
88
|
Fingerprint: ${e}
|
|
78
89
|
Linked: ${t.apps?.length??0} browser(s) (amplibee apps)
|
|
79
|
-
`)}function
|
|
80
|
-
|
|
81
|
-
|
|
90
|
+
`)}function Ld(t){let e=Pt(),[r]=t.rest;if(r==="on"||r==="off")return e.requireApproval=r==="on",j(e),console.log(r==="on"?`
|
|
91
|
+
High security is ON. The passphrase can no longer link this workspace; approve each new browser by comparing fingerprints.
|
|
92
|
+
Browsers already linked keep working. Applies at once, no restart needed.
|
|
93
|
+
`:`
|
|
94
|
+
High security is OFF. Passphrase unlock can link this workspace again.
|
|
95
|
+
`);r&&P("Usage: amplibee approvals [on|off]"),console.log(`
|
|
96
|
+
High security: ${e.requireApproval?"ON":"off"} (change it with: amplibee approvals on|off)
|
|
97
|
+
`)}function Od(t){let e=Pt(),[r,n,i,...s]=t.rest;if(r==="list"||!r){for(let o of tt(oe(e,!1)))console.log(` ${o.id.padEnd(10)} ${o.label.padEnd(14)} ${o.available?"installed":"not found"}`);return console.log(`
|
|
98
|
+
A plain terminal (id "${et}") is only offered with: amplibee start --allow-shell
|
|
99
|
+
`)}if(r==="add")return(!n||!i)&&P("Usage: amplibee harness add <id> <command> [args...]"),(!Rt.test(n)||n===et)&&P('The id must be lowercase letters, digits, - or _ (up to 24 characters), and not "shell".'),e.harnesses={...e.harnesses,[n]:{label:n,command:i,args:s}},j(e),console.log(` Added "${n}".`);if(r==="remove"){n||P("Usage: amplibee harness remove <id>");let o={...e.harnesses};return o[n]={command:o[n]?.command??n,disabled:!0},e.harnesses=o,j(e),console.log(` "${n}" will no longer be offered.`)}P("Unknown harness command.")}async function Rd(){let t=vd(process.argv.slice(2));if(el=Ie(t,"require-approval"),!t.cmd&&Ie(t,"version"))return console.log(me);switch(t.cmd){case"login":return Cd(t);case"start":return Ad(t);case"run":return Pd(t);case"link":return kd(t);case"apps":return Id(t);case"approvals":return Ld(t);case"status":return Bd();case"harness":return Od(t);case"logout":return ni(),console.log(`
|
|
82
100
|
Logged out on this computer. To fully remove the workspace, also delete it in the Amplibee app.
|
|
83
|
-
`);case"version":case"--version":return console.log(me);case"":case"help":return console.log(
|
|
101
|
+
`);case"version":case"--version":return console.log(me);case"":case"help":return console.log(xd);default:P(`Unknown command "${t.cmd}". Run "amplibee help".`)}}Rd().catch(t=>P(t instanceof Error?t.message:String(t)));
|
package/package.json
CHANGED
|
@@ -1,9 +1,11 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "amplibee",
|
|
3
|
-
"version": "0.1.
|
|
3
|
+
"version": "0.1.3",
|
|
4
4
|
"description": "Connect this workspace to Amplibee so you can steer Claude Code, Codex or any terminal agent from your phone.",
|
|
5
5
|
"license": "SEE LICENSE IN LICENSE",
|
|
6
|
-
"publishConfig": {
|
|
6
|
+
"publishConfig": {
|
|
7
|
+
"access": "public"
|
|
8
|
+
},
|
|
7
9
|
"type": "module",
|
|
8
10
|
"bin": {
|
|
9
11
|
"amplibee": "bin/amplibee.mjs"
|