@openduo/channel-wechat 0.1.0 → 0.1.2
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/README.md +16 -2
- package/dist/plugin.js +58 -42
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -40,6 +40,19 @@ npm start
|
|
|
40
40
|
|
|
41
41
|
The agent monitors stdout for `QRCODE_READY:` and `WECHAT_CONNECTED:` signals.
|
|
42
42
|
|
|
43
|
+
For stdio or TTY workflows, render the current pending QR code as terminal
|
|
44
|
+
characters without parsing logs:
|
|
45
|
+
|
|
46
|
+
```bash
|
|
47
|
+
duoduo-wechat qrcode-terminal --state-dir ~/.aladuo/channel-wechat
|
|
48
|
+
```
|
|
49
|
+
|
|
50
|
+
If you are running from a source checkout or package root:
|
|
51
|
+
|
|
52
|
+
```bash
|
|
53
|
+
node dist/plugin.js qrcode-terminal --state-dir ~/.aladuo/channel-wechat
|
|
54
|
+
```
|
|
55
|
+
|
|
43
56
|
## Environment Variables
|
|
44
57
|
|
|
45
58
|
| Variable | Default | Description |
|
|
@@ -48,7 +61,7 @@ The agent monitors stdout for `QRCODE_READY:` and `WECHAT_CONNECTED:` signals.
|
|
|
48
61
|
| `WECHAT_API_BASE` | `https://ilinkai.weixin.qq.com` | ilink bot API base URL |
|
|
49
62
|
| `WECHAT_DM_POLICY` | `open` | `open` (all users) or `allowlist` |
|
|
50
63
|
| `WECHAT_ALLOW_FROM` | — | Comma-separated WeChat userIds (allowlist mode only) |
|
|
51
|
-
| `WECHAT_STATE_DIR` | `~/.
|
|
64
|
+
| `WECHAT_STATE_DIR` | `~/.aladuo/channel-wechat` | Persisted token and sync cursor |
|
|
52
65
|
| `WECHAT_LOG_LEVEL` | `info` | `error` \| `warn` \| `info` \| `debug` |
|
|
53
66
|
|
|
54
67
|
## Architecture
|
|
@@ -71,13 +84,14 @@ WeChat (ilink bot API)
|
|
|
71
84
|
|
|
72
85
|
## State Directory
|
|
73
86
|
|
|
74
|
-
Default: `~/.
|
|
87
|
+
Default: `~/.aladuo/channel-wechat/`
|
|
75
88
|
|
|
76
89
|
| File | Description |
|
|
77
90
|
|------|-------------|
|
|
78
91
|
| `credentials.json` | Auth token (chmod 600) |
|
|
79
92
|
| `sync-buf.txt` | Message cursor for getupdates |
|
|
80
93
|
| `qrcode.png` | Temporary — deleted after scan |
|
|
94
|
+
| `qrcode.txt` | Temporary raw QR payload for `qrcode-terminal` |
|
|
81
95
|
|
|
82
96
|
## Development
|
|
83
97
|
|
package/dist/plugin.js
CHANGED
|
@@ -1,50 +1,66 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
#!/usr/bin/env node
|
|
3
2
|
import { createRequire as __createRequire } from "node:module";
|
|
4
3
|
const require = __createRequire(import.meta.url);
|
|
5
|
-
var
|
|
6
|
-
]))+`;
|
|
7
|
-
Make sure your charset is UTF-8`);r=(r>>>8&255)*192+(r&255),t.put(r,13)}};
|
|
8
|
-
Suggested mode is: `+
|
|
4
|
+
var fa=Object.create;var Mn=Object.defineProperty;var ca=Object.getOwnPropertyDescriptor;var ha=Object.getOwnPropertyNames;var da=Object.getPrototypeOf,pa=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 P=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports);var ga=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of ha(e))!pa.call(t,i)&&i!==r&&Mn(t,i,{get:()=>e[i],enumerable:!(n=ca(e,i))||n.enumerable});return t};var er=(t,e,r)=>(r=t!=null?fa(da(t)):{},ga(e||!t||!t.__esModule?Mn(r,"default",{value:t,enumerable:!0}):r,t));var rr=P((wc,jn)=>{jn.exports=function(){return typeof Promise=="function"&&Promise.prototype&&Promise.prototype.then}});var ye=P(Ae=>{var nr,ba=[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];Ae.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};Ae.getSymbolTotalCodewords=function(e){return ba[e]};Ae.getBCHDigit=function(t){let e=0;for(;t!==0;)e++,t>>>=1;return e};Ae.setToSJISFunction=function(e){if(typeof e!="function")throw new Error('"toSJISFunc" is not a valid function.');nr=e};Ae.isKanjiModeEnabled=function(){return typeof nr<"u"};Ae.toSJIS=function(e){return nr(e)}});var mt=P(te=>{te.L={bit:1};te.M={bit:0};te.Q={bit:3};te.H={bit:2};function Ca(t){if(typeof t!="string")throw new Error("Param is not a string");switch(t.toLowerCase()){case"l":case"low":return te.L;case"m":case"medium":return te.M;case"q":case"quartile":return te.Q;case"h":case"high":return te.H;default:throw new Error("Unknown EC Level: "+t)}}te.isValid=function(e){return e&&typeof e.bit<"u"&&e.bit>=0&&e.bit<4};te.from=function(e,r){if(te.isValid(e))return e;try{return Ca(e)}catch{return r}}});var Yn=P((Ec,Gn)=>{function Qn(){this.buffer=[],this.length=0}Qn.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++}};Gn.exports=Qn});var Jn=P((Tc,Vn)=>{function Ze(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)}Ze.prototype.set=function(t,e,r,n){let i=t*this.size+e;this.data[i]=r,n&&(this.reservedBit[i]=!0)};Ze.prototype.get=function(t,e){return this.data[t*this.size+e]};Ze.prototype.xor=function(t,e,r){this.data[t*this.size+e]^=r};Ze.prototype.isReserved=function(t,e){return this.reservedBit[t*this.size+e]};Vn.exports=Ze});var Kn=P(yt=>{var Ea=ye().getSymbolSize;yt.getRowColCoords=function(e){if(e===1)return[];let r=Math.floor(e/7)+2,n=Ea(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()};yt.getPositions=function(e){let r=[],n=yt.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 ei=P(Xn=>{var Ta=ye().getSymbolSize,Zn=7;Xn.getPositions=function(e){let r=Ta(e);return[[0,0],[r-Zn,0],[0,r-Zn]]}});var ti=P($=>{$.Patterns={PATTERN000:0,PATTERN001:1,PATTERN010:2,PATTERN011:3,PATTERN100:4,PATTERN101:5,PATTERN110:6,PATTERN111:7};var Ie={N1:3,N2:3,N3:40,N4:10};$.isValid=function(e){return e!=null&&e!==""&&!isNaN(e)&&e>=0&&e<=7};$.from=function(e){return $.isValid(e)?parseInt(e,10):void 0};$.getPenaltyN1=function(e){let r=e.size,n=0,i=0,s=0,o=null,a=null;for(let u=0;u<r;u++){i=s=0,o=a=null;for(let c=0;c<r;c++){let h=e.get(u,c);h===o?i++:(i>=5&&(n+=Ie.N1+(i-5)),o=h,i=1),h=e.get(c,u),h===a?s++:(s>=5&&(n+=Ie.N1+(s-5)),a=h,s=1)}i>=5&&(n+=Ie.N1+(i-5)),s>=5&&(n+=Ie.N1+(s-5))}return n};$.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*Ie.N2};$.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*Ie.N3};$.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)*Ie.N4};function ka(t,e,r){switch(t){case $.Patterns.PATTERN000:return(e+r)%2===0;case $.Patterns.PATTERN001:return e%2===0;case $.Patterns.PATTERN010:return r%3===0;case $.Patterns.PATTERN011:return(e+r)%3===0;case $.Patterns.PATTERN100:return(Math.floor(e/2)+Math.floor(r/3))%2===0;case $.Patterns.PATTERN101:return e*r%2+e*r%3===0;case $.Patterns.PATTERN110:return(e*r%2+e*r%3)%2===0;case $.Patterns.PATTERN111:return(e*r%3+(e+r)%2)%2===0;default:throw new Error("bad maskPattern:"+t)}}$.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,ka(e,s,i))};$.getBestMask=function(e,r){let n=Object.keys($.Patterns).length,i=0,s=1/0;for(let o=0;o<n;o++){r(o),$.applyMask(o,e);let a=$.getPenaltyN1(e)+$.getPenaltyN2(e)+$.getPenaltyN3(e)+$.getPenaltyN4(e);$.applyMask(o,e),a<s&&(s=a,i=o)}return i}});var sr=P(ir=>{var _e=mt(),_t=[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],wt=[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];ir.getBlocksCount=function(e,r){switch(r){case _e.L:return _t[(e-1)*4+0];case _e.M:return _t[(e-1)*4+1];case _e.Q:return _t[(e-1)*4+2];case _e.H:return _t[(e-1)*4+3];default:return}};ir.getTotalCodewordsCount=function(e,r){switch(r){case _e.L:return wt[(e-1)*4+0];case _e.M:return wt[(e-1)*4+1];case _e.Q:return wt[(e-1)*4+2];case _e.H:return wt[(e-1)*4+3];default:return}}});var ri=P(Ct=>{var Xe=new Uint8Array(512),bt=new Uint8Array(256);(function(){let e=1;for(let r=0;r<255;r++)Xe[r]=e,bt[e]=r,e<<=1,e&256&&(e^=285);for(let r=255;r<512;r++)Xe[r]=Xe[r-255]})();Ct.log=function(e){if(e<1)throw new Error("log("+e+")");return bt[e]};Ct.exp=function(e){return Xe[e]};Ct.mul=function(e,r){return e===0||r===0?0:Xe[bt[e]+bt[r]]}});var ni=P(et=>{var or=ri();et.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]^=or.mul(e[i],r[s]);return n};et.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]^=or.mul(r[o],i);let s=0;for(;s<n.length&&n[s]===0;)s++;n=n.slice(s)}return n};et.generateECPolynomial=function(e){let r=new Uint8Array([1]);for(let n=0;n<e;n++)r=et.mul(r,new Uint8Array([1,or.exp(n)]));return r}});var oi=P((Ac,si)=>{var ii=ni();function ar(t){this.genPoly=void 0,this.degree=t,this.degree&&this.initialize(this.degree)}ar.prototype.initialize=function(e){this.degree=e,this.genPoly=ii.generateECPolynomial(this.degree)};ar.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=ii.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};si.exports=ar});var lr=P(ai=>{ai.isValid=function(e){return!isNaN(e)&&e>=1&&e<=40}});var ur=P(de=>{var li="[0-9]+",Pa="[A-Z $%*+\\-./:]+",tt="(?:[u3000-u303F]|[u3040-u309F]|[u30A0-u30FF]|[uFF00-uFFEF]|[u4E00-u9FAF]|[u2605-u2606]|[u2190-u2195]|u203B|[u2010u2015u2018u2019u2025u2026u201Cu201Du2225u2260]|[u0391-u0451]|[u00A7u00A8u00B1u00B4u00D7u00F7])+";tt=tt.replace(/u/g,"\\u");var Sa="(?:(?![A-Z0-9 $%*+\\-./:]|"+tt+`)(?:.|[\r
|
|
5
|
+
]))+`;de.KANJI=new RegExp(tt,"g");de.BYTE_KANJI=new RegExp("[^A-Z0-9 $%*+\\-./:]+","g");de.BYTE=new RegExp(Sa,"g");de.NUMERIC=new RegExp(li,"g");de.ALPHANUMERIC=new RegExp(Pa,"g");var xa=new RegExp("^"+tt+"$"),Ba=new RegExp("^"+li+"$"),Ra=new RegExp("^[A-Z0-9 $%*+\\-./:]+$");de.testKanji=function(e){return xa.test(e)};de.testNumeric=function(e){return Ba.test(e)};de.testAlphanumeric=function(e){return Ra.test(e)}});var we=P(H=>{var Aa=lr(),fr=ur();H.NUMERIC={id:"Numeric",bit:1,ccBits:[10,12,14]};H.ALPHANUMERIC={id:"Alphanumeric",bit:2,ccBits:[9,11,13]};H.BYTE={id:"Byte",bit:4,ccBits:[8,16,16]};H.KANJI={id:"Kanji",bit:8,ccBits:[8,10,12]};H.MIXED={bit:-1};H.getCharCountIndicator=function(e,r){if(!e.ccBits)throw new Error("Invalid mode: "+e);if(!Aa.isValid(r))throw new Error("Invalid version: "+r);return r>=1&&r<10?e.ccBits[0]:r<27?e.ccBits[1]:e.ccBits[2]};H.getBestModeForData=function(e){return fr.testNumeric(e)?H.NUMERIC:fr.testAlphanumeric(e)?H.ALPHANUMERIC:fr.testKanji(e)?H.KANJI:H.BYTE};H.toString=function(e){if(e&&e.id)return e.id;throw new Error("Invalid mode")};H.isValid=function(e){return e&&e.bit&&e.ccBits};function Ia(t){if(typeof t!="string")throw new Error("Param is not a string");switch(t.toLowerCase()){case"numeric":return H.NUMERIC;case"alphanumeric":return H.ALPHANUMERIC;case"kanji":return H.KANJI;case"byte":return H.BYTE;default:throw new Error("Unknown mode: "+t)}}H.from=function(e,r){if(H.isValid(e))return e;try{return Ia(e)}catch{return r}}});var di=P(ve=>{var Et=ye(),va=sr(),ui=mt(),be=we(),cr=lr(),ci=7973,fi=Et.getBCHDigit(ci);function Oa(t,e,r){for(let n=1;n<=40;n++)if(e<=ve.getCapacity(n,r,t))return n}function hi(t,e){return be.getCharCountIndicator(t,e)+4}function La(t,e){let r=0;return t.forEach(function(n){let i=hi(n.mode,e);r+=i+n.getBitsLength()}),r}function Ma(t,e){for(let r=1;r<=40;r++)if(La(t,r)<=ve.getCapacity(r,e,be.MIXED))return r}ve.from=function(e,r){return cr.isValid(e)?parseInt(e,10):r};ve.getCapacity=function(e,r,n){if(!cr.isValid(e))throw new Error("Invalid QR Code version");typeof n>"u"&&(n=be.BYTE);let i=Et.getSymbolTotalCodewords(e),s=va.getTotalCodewordsCount(e,r),o=(i-s)*8;if(n===be.MIXED)return o;let a=o-hi(n,e);switch(n){case be.NUMERIC:return Math.floor(a/10*3);case be.ALPHANUMERIC:return Math.floor(a/11*2);case be.KANJI:return Math.floor(a/13);case be.BYTE:default:return Math.floor(a/8)}};ve.getBestVersionForData=function(e,r){let n,i=ui.from(r,ui.M);if(Array.isArray(e)){if(e.length>1)return Ma(e,i);if(e.length===0)return 1;n=e[0]}else n=e;return Oa(n.mode,n.getLength(),i)};ve.getEncodedBits=function(e){if(!cr.isValid(e)||e<7)throw new Error("Invalid QR Code version");let r=e<<12;for(;Et.getBCHDigit(r)-fi>=0;)r^=ci<<Et.getBCHDigit(r)-fi;return e<<12|r}});var yi=P(mi=>{var hr=ye(),gi=1335,Na=21522,pi=hr.getBCHDigit(gi);mi.getEncodedBits=function(e,r){let n=e.bit<<3|r,i=n<<10;for(;hr.getBCHDigit(i)-pi>=0;)i^=gi<<hr.getBCHDigit(i)-pi;return(n<<10|i)^Na}});var wi=P((Nc,_i)=>{var $a=we();function Fe(t){this.mode=$a.NUMERIC,this.data=t.toString()}Fe.getBitsLength=function(e){return 10*Math.floor(e/3)+(e%3?e%3*3+1:0)};Fe.prototype.getLength=function(){return this.data.length};Fe.prototype.getBitsLength=function(){return Fe.getBitsLength(this.data.length)};Fe.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))};_i.exports=Fe});var Ci=P(($c,bi)=>{var Ua=we(),dr=["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 qe(t){this.mode=Ua.ALPHANUMERIC,this.data=t}qe.getBitsLength=function(e){return 11*Math.floor(e/2)+6*(e%2)};qe.prototype.getLength=function(){return this.data.length};qe.prototype.getBitsLength=function(){return qe.getBitsLength(this.data.length)};qe.prototype.write=function(e){let r;for(r=0;r+2<=this.data.length;r+=2){let n=dr.indexOf(this.data[r])*45;n+=dr.indexOf(this.data[r+1]),e.put(n,11)}this.data.length%2&&e.put(dr.indexOf(this.data[r]),6)};bi.exports=qe});var Ti=P((Uc,Ei)=>{var Fa=we();function De(t){this.mode=Fa.BYTE,typeof t=="string"?this.data=new TextEncoder().encode(t):this.data=new Uint8Array(t)}De.getBitsLength=function(e){return e*8};De.prototype.getLength=function(){return this.data.length};De.prototype.getBitsLength=function(){return De.getBitsLength(this.data.length)};De.prototype.write=function(t){for(let e=0,r=this.data.length;e<r;e++)t.put(this.data[e],8)};Ei.exports=De});var Pi=P((Fc,ki)=>{var qa=we(),Da=ye();function We(t){this.mode=qa.KANJI,this.data=t}We.getBitsLength=function(e){return e*13};We.prototype.getLength=function(){return this.data.length};We.prototype.getBitsLength=function(){return We.getBitsLength(this.data.length)};We.prototype.write=function(t){let e;for(e=0;e<this.data.length;e++){let r=Da.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]+`
|
|
6
|
+
Make sure your charset is UTF-8`);r=(r>>>8&255)*192+(r&255),t.put(r,13)}};ki.exports=We});var Si=P((qc,pr)=>{"use strict";var rt={single_source_shortest_paths:function(t,e,r){var n={},i={};i[e]=0;var s=rt.PriorityQueue.make();s.push(e,0);for(var o,a,u,c,h,y,_,b,g;!s.empty();){o=s.pop(),a=o.value,c=o.cost,h=t[a]||{};for(u in h)h.hasOwnProperty(u)&&(y=h[u],_=c+y,b=i[u],g=typeof i[u]>"u",(g||b>_)&&(i[u]=_,s.push(u,_),n[u]=a))}if(typeof r<"u"&&typeof i[r]>"u"){var w=["Could not find a path from ",e," to ",r,"."].join("");throw new Error(w)}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=rt.single_source_shortest_paths(t,e,r);return rt.extract_shortest_path_from_predecessor_list(n,r)},PriorityQueue:{make:function(t){var e=rt.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 pr<"u"&&(pr.exports=rt)});var Li=P(He=>{var M=we(),Ri=wi(),Ai=Ci(),Ii=Ti(),vi=Pi(),nt=ur(),Tt=ye(),Wa=Si();function xi(t){return unescape(encodeURIComponent(t)).length}function it(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 Oi(t){let e=it(nt.NUMERIC,M.NUMERIC,t),r=it(nt.ALPHANUMERIC,M.ALPHANUMERIC,t),n,i;return Tt.isKanjiModeEnabled()?(n=it(nt.BYTE,M.BYTE,t),i=it(nt.KANJI,M.KANJI,t)):(n=it(nt.BYTE_KANJI,M.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 gr(t,e){switch(e){case M.NUMERIC:return Ri.getBitsLength(t);case M.ALPHANUMERIC:return Ai.getBitsLength(t);case M.KANJI:return vi.getBitsLength(t);case M.BYTE:return Ii.getBitsLength(t)}}function Ha(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 za(t){let e=[];for(let r=0;r<t.length;r++){let n=t[r];switch(n.mode){case M.NUMERIC:e.push([n,{data:n.data,mode:M.ALPHANUMERIC,length:n.length},{data:n.data,mode:M.BYTE,length:n.length}]);break;case M.ALPHANUMERIC:e.push([n,{data:n.data,mode:M.BYTE,length:n.length}]);break;case M.KANJI:e.push([n,{data:n.data,mode:M.BYTE,length:xi(n.data)}]);break;case M.BYTE:e.push([{data:n.data,mode:M.BYTE,length:xi(n.data)}])}}return e}function ja(t,e){let r={},n={start:{}},i=["start"];for(let s=0;s<t.length;s++){let o=t[s],a=[];for(let u=0;u<o.length;u++){let c=o[u],h=""+s+u;a.push(h),r[h]={node:c,lastCount:0},n[h]={};for(let y=0;y<i.length;y++){let _=i[y];r[_]&&r[_].node.mode===c.mode?(n[_][h]=gr(r[_].lastCount+c.length,c.mode)-gr(r[_].lastCount,c.mode),r[_].lastCount+=c.length):(r[_]&&(r[_].lastCount=c.length),n[_][h]=gr(c.length,c.mode)+4+M.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 Bi(t,e){let r,n=M.getBestModeForData(t);if(r=M.from(e,n),r!==M.BYTE&&r.bit<n.bit)throw new Error('"'+t+'" cannot be encoded with mode '+M.toString(r)+`.
|
|
7
|
+
Suggested mode is: `+M.toString(n));switch(r===M.KANJI&&!Tt.isKanjiModeEnabled()&&(r=M.BYTE),r){case M.NUMERIC:return new Ri(t);case M.ALPHANUMERIC:return new Ai(t);case M.KANJI:return new vi(t);case M.BYTE:return new Ii(t)}}He.fromArray=function(e){return e.reduce(function(r,n){return typeof n=="string"?r.push(Bi(n,null)):n.data&&r.push(Bi(n.data,n.mode)),r},[])};He.fromString=function(e,r){let n=Oi(e,Tt.isKanjiModeEnabled()),i=za(n),s=ja(i,r),o=Wa.find_path(s.map,"start","end"),a=[];for(let u=1;u<o.length-1;u++)a.push(s.table[o[u]].node);return He.fromArray(Ha(a))};He.rawSplit=function(e){return He.fromArray(Oi(e,Tt.isKanjiModeEnabled()))}});var Cr=P(Mi=>{var Pt=ye(),mr=mt(),Qa=Yn(),Ga=Jn(),Ya=Kn(),Va=ei(),wr=ti(),br=sr(),Ja=oi(),kt=di(),Ka=yi(),Za=we(),yr=Li();function Xa(t,e){let r=t.size,n=Va.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 u=-1;u<=7;u++)o+u<=-1||r<=o+u||(a>=0&&a<=6&&(u===0||u===6)||u>=0&&u<=6&&(a===0||a===6)||a>=2&&a<=4&&u>=2&&u<=4?t.set(s+a,o+u,!0,!0):t.set(s+a,o+u,!1,!0))}}function el(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 tl(t,e){let r=Ya.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 rl(t,e){let r=t.size,n=kt.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 _r(t,e,r){let n=t.size,i=Ka.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 nl(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 u=0;u<2;u++)if(!t.isReserved(i,a-u)){let c=!1;o<e.length&&(c=(e[o]>>>s&1)===1),t.set(i,a-u,c),s--,s===-1&&(o++,s=7)}if(i+=n,i<0||r<=i){i-=n,n=-n;break}}}function il(t,e,r){let n=new Qa;r.forEach(function(u){n.put(u.mode.bit,4),n.put(u.getLength(),Za.getCharCountIndicator(u.mode,t)),u.write(n)});let i=Pt.getSymbolTotalCodewords(t),s=br.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 u=0;u<a;u++)n.put(u%2?17:236,8);return sl(n,t,e)}function sl(t,e,r){let n=Pt.getSymbolTotalCodewords(e),i=br.getTotalCodewordsCount(e,r),s=n-i,o=br.getBlocksCount(e,r),a=n%o,u=o-a,c=Math.floor(n/o),h=Math.floor(s/o),y=h+1,_=c-h,b=new Ja(_),g=0,w=new Array(o),C=new Array(o),E=0,x=new Uint8Array(t.buffer);for(let L=0;L<o;L++){let G=L<u?h:y;w[L]=x.slice(g,g+G),C[L]=b.encode(w[L]),g+=G,E=Math.max(E,G)}let I=new Uint8Array(n),O=0,N,v;for(N=0;N<E;N++)for(v=0;v<o;v++)N<w[v].length&&(I[O++]=w[v][N]);for(N=0;N<_;N++)for(v=0;v<o;v++)I[O++]=C[v][N];return I}function ol(t,e,r,n){let i;if(Array.isArray(t))i=yr.fromArray(t);else if(typeof t=="string"){let c=e;if(!c){let h=yr.rawSplit(t);c=kt.getBestVersionForData(h,r)}i=yr.fromString(t,c||40)}else throw new Error("Invalid data");let s=kt.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(`
|
|
9
8
|
The chosen QR Code version cannot contain this amount of data.
|
|
10
|
-
Minimum version required to store current data is: `+
|
|
11
|
-
`);let s=za(e,r,i),a=yt.getSymbolSize(e),u=new va(a);return $a(u,e),qa(u),Da(u,e),sr(u,r,0),e>=7&&Wa(u,e),Ha(u,s),isNaN(n)&&(n=ar.getBestMask(u,sr.bind(null,u,r))),ar.applyMask(n,u),sr(u,r,n),{modules:u,version:e,errorCorrectionLevel:r,maskPattern:n,segments:i}}ki.create=function(e,r){if(typeof e>"u"||e==="")throw new Error("No input text");let n=ir.M,i,o;return typeof r<"u"&&(n=ir.from(r.errorCorrectionLevel,ir.M),i=mt.from(r.version),o=ar.from(r.maskPattern),r.toSJISFunc&&yt.setToSJISFunction(r.toSJISFunc)),Ga(e,i,n,o)}});var fr=k((uc,Si)=>{"use strict";var Ya=$("util"),Pi=$("stream"),re=Si.exports=function(){Pi.call(this),this._buffers=[],this._buffered=0,this._reads=[],this._paused=!1,this._encoding="utf8",this.writable=!0};Ya.inherits(re,Pi);re.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))};re.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};re.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()))};re.prototype.destroySoon=re.prototype.end;re.prototype._end=function(){this._reads.length>0&&this.emit("error",new Error("Unexpected end of input")),this.destroy()};re.prototype.destroy=function(){this._buffers&&(this.writable=!1,this._reads=null,this._buffers=null,this.emit("close"))};re.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))};re.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++],o=Math.min(i.length,t.length-e);i.copy(n,e,0,o),e+=o,o!==i.length&&(this._buffers[--r]=i.slice(o))}r>0&&this._buffers.splice(0,r),this._buffered-=t.length,t.func.call(this,n)};re.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 hr=k(cr=>{"use strict";var pe=[{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]}];cr.getImagePasses=function(t,e){let r=[],n=t%8,i=e%8,o=(t-n)/8,s=(e-i)/8;for(let a=0;a<pe.length;a++){let u=pe[a],c=o*u.x.length,h=s*u.y.length;for(let _=0;_<u.x.length&&u.x[_]<n;_++)c++;for(let _=0;_<u.y.length&&u.y[_]<i;_++)h++;c>0&&h>0&&r.push({width:c,height:h,index:a})}return r};cr.getInterlaceIterator=function(t){return function(e,r,n){let i=e%pe[n].x.length,o=(e-i)/pe[n].x.length*8+pe[n].x[i],s=r%pe[n].y.length,a=(r-s)/pe[n].y.length*8+pe[n].y[s];return o*4+a*t*4}}});var dr=k((cc,Ai)=>{"use strict";Ai.exports=function(e,r,n){let i=e+r-n,o=Math.abs(i-e),s=Math.abs(i-r),a=Math.abs(i-n);return o<=s&&o<=a?e:s<=a?r:n}});var pr=k((hc,xi)=>{"use strict";var Ja=hr(),Va=dr();function Ri(t,e,r){let n=t*e;return r!==8&&(n=Math.ceil(n/(8/r))),n}var Me=xi.exports=function(t,e){let r=t.width,n=t.height,i=t.interlace,o=t.bpp,s=t.depth;if(this.read=e.read,this.write=e.write,this.complete=e.complete,this._imageIndex=0,this._images=[],i){let a=Ja.getImagePasses(r,n);for(let u=0;u<a.length;u++)this._images.push({byteWidth:Ri(a[u].width,o,s),height:a[u].height,lineIndex:0})}else this._images.push({byteWidth:Ri(r,o,s),height:n,lineIndex:0});s===8?this._xComparison=o:s===16?this._xComparison=o*2:this._xComparison=1};Me.prototype.start=function(){this.read(this._images[this._imageIndex].byteWidth+1,this._reverseFilterLine.bind(this))};Me.prototype._unFilterType1=function(t,e,r){let n=this._xComparison,i=n-1;for(let o=0;o<r;o++){let s=t[1+o],a=o>i?e[o-n]:0;e[o]=s+a}};Me.prototype._unFilterType2=function(t,e,r){let n=this._lastLine;for(let i=0;i<r;i++){let o=t[1+i],s=n?n[i]:0;e[i]=o+s}};Me.prototype._unFilterType3=function(t,e,r){let n=this._xComparison,i=n-1,o=this._lastLine;for(let s=0;s<r;s++){let a=t[1+s],u=o?o[s]:0,c=s>i?e[s-n]:0,h=Math.floor((c+u)/2);e[s]=a+h}};Me.prototype._unFilterType4=function(t,e,r){let n=this._xComparison,i=n-1,o=this._lastLine;for(let s=0;s<r;s++){let a=t[1+s],u=o?o[s]:0,c=s>i?e[s-n]:0,h=s>i&&o?o[s-n]:0,_=Va(c,u,h);e[s]=a+_}};Me.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 Oi=k((dc,Ii)=>{"use strict";var Ka=$("util"),Bi=fr(),Qa=pr(),Za=Ii.exports=function(t){Bi.call(this);let e=[],r=this;this._filter=new Qa(t,{read:this.read.bind(this),write:function(n){e.push(n)},complete:function(){r.emit("complete",Buffer.concat(e))}}),this._filter.start()};Ka.inherits(Za,Bi)});var Ne=k((pc,vi)=>{"use strict";vi.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 yr=k((gc,Li)=>{"use strict";var gr=[];(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;gr[t]=e}})();var mr=Li.exports=function(){this._crc=-1};mr.prototype.write=function(t){for(let e=0;e<t.length;e++)this._crc=gr[(this._crc^t[e])&255]^this._crc>>>8;return!0};mr.prototype.crc32=function(){return this._crc^-1};mr.crc32=function(t){let e=-1;for(let r=0;r<t.length;r++)e=gr[(e^t[r])&255]^e>>>8;return e^-1}});var _r=k((mc,Mi)=>{"use strict";var D=Ne(),Xa=yr(),z=Mi.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[D.TYPE_IHDR]=this._handleIHDR.bind(this),this._chunks[D.TYPE_IEND]=this._handleIEND.bind(this),this._chunks[D.TYPE_IDAT]=this._handleIDAT.bind(this),this._chunks[D.TYPE_PLTE]=this._handlePLTE.bind(this),this._chunks[D.TYPE_tRNS]=this._handleTRNS.bind(this),this._chunks[D.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(){}};z.prototype.start=function(){this.read(D.PNG_SIGNATURE.length,this._parseSignature.bind(this))};z.prototype._parseSignature=function(t){let e=D.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))};z.prototype._parseChunkBegin=function(t){let e=t.readUInt32BE(0),r=t.readUInt32BE(4),n="";for(let o=4;o<8;o++)n+=String.fromCharCode(t[o]);let i=!!(t[4]&32);if(!this._hasIHDR&&r!==D.TYPE_IHDR){this.error(new Error("Expected IHDR on beggining"));return}if(this._crc=new Xa,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))};z.prototype._skipChunk=function(){this.read(8,this._parseChunkBegin.bind(this))};z.prototype._handleChunkEnd=function(){this.read(4,this._parseChunkEnd.bind(this))};z.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))};z.prototype._handleIHDR=function(t){this.read(t,this._parseIHDR.bind(this))};z.prototype._parseIHDR=function(t){this._crc.write(t);let e=t.readUInt32BE(0),r=t.readUInt32BE(4),n=t[8],i=t[9],o=t[10],s=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 D.COLORTYPE_TO_BPP_MAP)){this.error(new Error("Unsupported color type"));return}if(o!==0){this.error(new Error("Unsupported compression method"));return}if(s!==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 u=D.COLORTYPE_TO_BPP_MAP[this._colorType];this._hasIHDR=!0,this.metadata({width:e,height:r,depth:n,interlace:!!a,palette:!!(i&D.COLORTYPE_PALETTE),color:!!(i&D.COLORTYPE_COLOR),alpha:!!(i&D.COLORTYPE_ALPHA),bpp:u,colorType:i}),this._handleChunkEnd()};z.prototype._handlePLTE=function(t){this.read(t,this._parsePLTE.bind(this))};z.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()};z.prototype._handleTRNS=function(t){this.simpleTransparency(),this.read(t,this._parseTRNS.bind(this))};z.prototype._parseTRNS=function(t){if(this._crc.write(t),this._colorType===D.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===D.COLORTYPE_GRAYSCALE&&this.transColor([t.readUInt16BE(0)]),this._colorType===D.COLORTYPE_COLOR&&this.transColor([t.readUInt16BE(0),t.readUInt16BE(2),t.readUInt16BE(4)]),this._handleChunkEnd()};z.prototype._handleGAMA=function(t){this.read(t,this._parseGAMA.bind(this))};z.prototype._parseGAMA=function(t){this._crc.write(t),this.gamma(t.readUInt32BE(0)/D.GAMMA_DIVISION),this._handleChunkEnd()};z.prototype._handleIDAT=function(t){this._emittedHeadersFinished||(this._emittedHeadersFinished=!0,this.headersFinished()),this.read(-t,this._parseIDAT.bind(this,t))};z.prototype._parseIDAT=function(t,e){if(this._crc.write(e),this._colorType===D.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()};z.prototype._handleIEND=function(t){this.read(t,this._parseIEND.bind(this))};z.prototype._parseIEND=function(t){this._crc.write(t),this._hasIEND=!0,this._handleChunkEnd(),this.finished&&this.finished()}});var wr=k(Fi=>{"use strict";var Ni=hr(),el=[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]}],tl=[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 rl(t,e){let r=[],n=0;function i(){if(n===t.length)throw new Error("Ran out of data");let o=t[n];n++;let s,a,u,c,h,_,g,y;switch(e){default:throw new Error("unrecognised depth");case 16:g=t[n],n++,r.push((o<<8)+g);break;case 4:g=o&15,y=o>>4,r.push(y,g);break;case 2:h=o&3,_=o>>2&3,g=o>>4&3,y=o>>6&3,r.push(y,g,_,h);break;case 1:s=o&1,a=o>>1&1,u=o>>2&1,c=o>>3&1,h=o>>4&1,_=o>>5&1,g=o>>6&1,y=o>>7&1,r.push(y,g,_,h,c,u,a,s);break}}return{get:function(o){for(;r.length<o;)i();let s=r.slice(0,o);return r=r.slice(o),s},resetAfterLine:function(){r.length=0},end:function(){if(n!==t.length)throw new Error("extra data found")}}}function nl(t,e,r,n,i,o){let s=t.width,a=t.height,u=t.index;for(let c=0;c<a;c++)for(let h=0;h<s;h++){let _=r(h,c,u);el[n](e,i,_,o),o+=n}return o}function il(t,e,r,n,i,o){let s=t.width,a=t.height,u=t.index;for(let c=0;c<a;c++){for(let h=0;h<s;h++){let _=i.get(n),g=r(h,c,u);tl[n](e,_,g,o)}i.resetAfterLine()}}Fi.dataToBitMap=function(t,e){let r=e.width,n=e.height,i=e.depth,o=e.bpp,s=e.interlace,a;i!==8&&(a=rl(t,i));let u;i<=8?u=Buffer.alloc(r*n*4):u=new Uint16Array(r*n*4);let c=Math.pow(2,i)-1,h=0,_,g;if(s)_=Ni.getImagePasses(r,n),g=Ni.getInterlaceIterator(r,n);else{let y=0;g=function(){let w=y;return y+=4,w},_=[{width:r,height:n}]}for(let y=0;y<_.length;y++)i===8?h=nl(_[y],u,g,o,t,h):il(_[y],u,g,o,a,c);if(i===8){if(h!==t.length)throw new Error("extra data found")}else a.end();return u}});var br=k((_c,Ui)=>{"use strict";function ol(t,e,r,n,i){let o=0;for(let s=0;s<n;s++)for(let a=0;a<r;a++){let u=i[t[o]];if(!u)throw new Error("index "+t[o]+" not in palette");for(let c=0;c<4;c++)e[o+c]=u[c];o+=4}}function sl(t,e,r,n,i){let o=0;for(let s=0;s<n;s++)for(let a=0;a<r;a++){let u=!1;if(i.length===1?i[0]===t[o]&&(u=!0):i[0]===t[o]&&i[1]===t[o+1]&&i[2]===t[o+2]&&(u=!0),u)for(let c=0;c<4;c++)e[o+c]=0;o+=4}}function al(t,e,r,n,i){let o=255,s=Math.pow(2,i)-1,a=0;for(let u=0;u<n;u++)for(let c=0;c<r;c++){for(let h=0;h<4;h++)e[a+h]=Math.floor(t[a+h]*o/s+.5);a+=4}}Ui.exports=function(t,e){let r=e.depth,n=e.width,i=e.height,o=e.colorType,s=e.transColor,a=e.palette,u=t;return o===3?ol(t,u,n,i,a):(s&&sl(t,u,n,i,s),r!==8&&(r===16&&(u=Buffer.alloc(n*i*4)),al(t,u,n,i,r))),u}});var Di=k((wc,qi)=>{"use strict";var ll=$("util"),Cr=$("zlib"),$i=fr(),ul=Oi(),fl=_r(),cl=wr(),hl=br(),ie=qi.exports=function(t){$i.call(this),this._parser=new fl(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()};ll.inherits(ie,$i);ie.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};ie.prototype._inflateData=function(t){if(!this._inflate)if(this._bitmapInfo.interlace)this._inflate=Cr.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,Cr.Z_MIN_CHUNK);this._inflate=Cr.createInflate({chunkSize:n});let i=r,o=this.emit.bind(this,"error");this._inflate.on("error",function(a){i&&o(a)}),this._filter.on("complete",this._complete.bind(this));let s=this._filter.write.bind(this._filter);this._inflate.on("data",function(a){i&&(a.length>i&&(a=a.slice(0,i)),i-=a.length,s(a))}),this._inflate.on("end",this._filter.end.bind(this._filter))}this._inflate.write(t)};ie.prototype._handleMetaData=function(t){this._metaData=t,this._bitmapInfo=Object.create(t),this._filter=new ul(this._bitmapInfo)};ie.prototype._handleTransColor=function(t){this._bitmapInfo.transColor=t};ie.prototype._handlePalette=function(t){this._bitmapInfo.palette=t};ie.prototype._simpleTransparency=function(){this._metaData.alpha=!0};ie.prototype._headersFinished=function(){this.emit("metadata",this._metaData)};ie.prototype._finished=function(){this.errord||(this._inflate?this._inflate.end():this.emit("error","No Inflate block"))};ie.prototype._complete=function(t){if(this.errord)return;let e;try{let r=cl.dataToBitMap(t,this._bitmapInfo);e=hl(r,this._bitmapInfo),r=null}catch(r){this._handleError(r);return}this.emit("parsed",e)}});var Hi=k((bc,Wi)=>{"use strict";var Z=Ne();Wi.exports=function(t,e,r,n){let i=[Z.COLORTYPE_COLOR_ALPHA,Z.COLORTYPE_ALPHA].indexOf(n.colorType)!==-1;if(n.colorType===n.inputColorType){let w=(function(){let b=new ArrayBuffer(2);return new DataView(b).setInt16(0,256,!0),new Int16Array(b)[0]!==256})();if(n.bitDepth===8||n.bitDepth===16&&w)return t}let o=n.bitDepth!==16?t:new Uint16Array(t.buffer),s=255,a=Z.COLORTYPE_TO_BPP_MAP[n.inputColorType];a===4&&!n.inputHasAlpha&&(a=3);let u=Z.COLORTYPE_TO_BPP_MAP[n.colorType];n.bitDepth===16&&(s=65535,u*=2);let c=Buffer.alloc(e*r*u),h=0,_=0,g=n.bgColor||{};g.red===void 0&&(g.red=s),g.green===void 0&&(g.green=s),g.blue===void 0&&(g.blue=s);function y(){let w,b,C,S=s;switch(n.inputColorType){case Z.COLORTYPE_COLOR_ALPHA:S=o[h+3],w=o[h],b=o[h+1],C=o[h+2];break;case Z.COLORTYPE_COLOR:w=o[h],b=o[h+1],C=o[h+2];break;case Z.COLORTYPE_ALPHA:S=o[h+1],w=o[h],b=w,C=w;break;case Z.COLORTYPE_GRAYSCALE:w=o[h],b=w,C=w;break;default:throw new Error("input color type:"+n.inputColorType+" is not supported at present")}return n.inputHasAlpha&&(i||(S/=s,w=Math.min(Math.max(Math.round((1-S)*g.red+S*w),0),s),b=Math.min(Math.max(Math.round((1-S)*g.green+S*b),0),s),C=Math.min(Math.max(Math.round((1-S)*g.blue+S*C),0),s))),{red:w,green:b,blue:C,alpha:S}}for(let w=0;w<r;w++)for(let b=0;b<e;b++){let C=y(o,h);switch(n.colorType){case Z.COLORTYPE_COLOR_ALPHA:case Z.COLORTYPE_COLOR:n.bitDepth===8?(c[_]=C.red,c[_+1]=C.green,c[_+2]=C.blue,i&&(c[_+3]=C.alpha)):(c.writeUInt16BE(C.red,_),c.writeUInt16BE(C.green,_+2),c.writeUInt16BE(C.blue,_+4),i&&c.writeUInt16BE(C.alpha,_+6));break;case Z.COLORTYPE_ALPHA:case Z.COLORTYPE_GRAYSCALE:{let S=(C.red+C.green+C.blue)/3;n.bitDepth===8?(c[_]=S,i&&(c[_+1]=C.alpha)):(c.writeUInt16BE(S,_),i&&c.writeUInt16BE(C.alpha,_+2));break}default:throw new Error("unrecognised color Type "+n.colorType)}h+=a,_+=u}return c}});var Gi=k((Cc,ji)=>{"use strict";var zi=dr();function dl(t,e,r,n,i){for(let o=0;o<r;o++)n[i+o]=t[e+o]}function pl(t,e,r){let n=0,i=e+r;for(let o=e;o<i;o++)n+=Math.abs(t[o]);return n}function gl(t,e,r,n,i,o){for(let s=0;s<r;s++){let a=s>=o?t[e+s-o]:0,u=t[e+s]-a;n[i+s]=u}}function ml(t,e,r,n){let i=0;for(let o=0;o<r;o++){let s=o>=n?t[e+o-n]:0,a=t[e+o]-s;i+=Math.abs(a)}return i}function yl(t,e,r,n,i){for(let o=0;o<r;o++){let s=e>0?t[e+o-r]:0,a=t[e+o]-s;n[i+o]=a}}function _l(t,e,r){let n=0,i=e+r;for(let o=e;o<i;o++){let s=e>0?t[o-r]:0,a=t[o]-s;n+=Math.abs(a)}return n}function wl(t,e,r,n,i,o){for(let s=0;s<r;s++){let a=s>=o?t[e+s-o]:0,u=e>0?t[e+s-r]:0,c=t[e+s]-(a+u>>1);n[i+s]=c}}function bl(t,e,r,n){let i=0;for(let o=0;o<r;o++){let s=o>=n?t[e+o-n]:0,a=e>0?t[e+o-r]:0,u=t[e+o]-(s+a>>1);i+=Math.abs(u)}return i}function Cl(t,e,r,n,i,o){for(let s=0;s<r;s++){let a=s>=o?t[e+s-o]:0,u=e>0?t[e+s-r]:0,c=e>0&&s>=o?t[e+s-(r+o)]:0,h=t[e+s]-zi(a,u,c);n[i+s]=h}}function El(t,e,r,n){let i=0;for(let o=0;o<r;o++){let s=o>=n?t[e+o-n]:0,a=e>0?t[e+o-r]:0,u=e>0&&o>=n?t[e+o-(r+n)]:0,c=t[e+o]-zi(s,a,u);i+=Math.abs(c)}return i}var Tl={0:dl,1:gl,2:yl,3:wl,4:Cl},kl={0:pl,1:ml,2:_l,3:bl,4:El};ji.exports=function(t,e,r,n,i){let o;if(!("filterType"in n)||n.filterType===-1)o=[0,1,2,3,4];else if(typeof n.filterType=="number")o=[n.filterType];else throw new Error("unrecognised filter types");n.bitDepth===16&&(i*=2);let s=e*i,a=0,u=0,c=Buffer.alloc((s+1)*r),h=o[0];for(let _=0;_<r;_++){if(o.length>1){let g=1/0;for(let y=0;y<o.length;y++){let w=kl[o[y]](t,u,s,i);w<g&&(h=o[y],g=w)}}c[a]=h,a++,Tl[h](t,u,s,c,a,i),a+=s,u+=s}return c}});var Er=k((Ec,Yi)=>{"use strict";var G=Ne(),Pl=yr(),Sl=Hi(),Al=Gi(),Rl=$("zlib"),ge=Yi.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||Rl.createDeflate,t.bitDepth=t.bitDepth||8,t.colorType=typeof t.colorType=="number"?t.colorType:G.COLORTYPE_COLOR_ALPHA,t.inputColorType=typeof t.inputColorType=="number"?t.inputColorType:G.COLORTYPE_COLOR_ALPHA,[G.COLORTYPE_GRAYSCALE,G.COLORTYPE_COLOR,G.COLORTYPE_COLOR_ALPHA,G.COLORTYPE_ALPHA].indexOf(t.colorType)===-1)throw new Error("option color type:"+t.colorType+" is not supported at present");if([G.COLORTYPE_GRAYSCALE,G.COLORTYPE_COLOR,G.COLORTYPE_COLOR_ALPHA,G.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")};ge.prototype.getDeflateOptions=function(){return{chunkSize:this._options.deflateChunkSize,level:this._options.deflateLevel,strategy:this._options.deflateStrategy}};ge.prototype.createDeflate=function(){return this._options.deflateFactory(this.getDeflateOptions())};ge.prototype.filterData=function(t,e,r){let n=Sl(t,e,r,this._options),i=G.COLORTYPE_TO_BPP_MAP[this._options.colorType];return Al(n,e,r,this._options,i)};ge.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(Pl.crc32(n.slice(4,n.length-4)),n.length-4),n};ge.prototype.packGAMA=function(t){let e=Buffer.alloc(4);return e.writeUInt32BE(Math.floor(t*G.GAMMA_DIVISION),0),this._packChunk(G.TYPE_gAMA,e)};ge.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(G.TYPE_IHDR,r)};ge.prototype.packIDAT=function(t){return this._packChunk(G.TYPE_IDAT,t)};ge.prototype.packIEND=function(){return this._packChunk(G.TYPE_IEND,null)}});var Qi=k((Tc,Ki)=>{"use strict";var xl=$("util"),Ji=$("stream"),Bl=Ne(),Il=Er(),Vi=Ki.exports=function(t){Ji.call(this);let e=t||{};this._packer=new Il(e),this._deflate=this._packer.createDeflate(),this.readable=!0};xl.inherits(Vi,Ji);Vi.prototype.pack=function(t,e,r,n){this.emit("data",Buffer.from(Bl.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(o){this.emit("data",this._packer.packIDAT(o))}.bind(this)),this._deflate.on("end",function(){this.emit("data",this._packer.packIEND()),this.emit("end")}.bind(this)),this._deflate.end(i)}});var no=k((Ke,ro)=>{"use strict";var Zi=$("assert").ok,Fe=$("zlib"),Ol=$("util"),Xi=$("buffer").kMaxLength;function Se(t){if(!(this instanceof Se))return new Se(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 vl(t){return new Se(t)}function eo(t,e){e&&process.nextTick(e),t._handle&&(t._handle.close(),t._handle=null)}Se.prototype._processChunk=function(t,e,r){if(typeof r=="function")return Fe.Inflate._processChunk.call(this,t,e,r);let n=this,i=t&&t.length,o=this._chunkSize-this._offset,s=this._maxLength,a=0,u=[],c=0,h;this.on("error",function(w){h=w});function _(w,b){if(n._hadError)return;let C=o-b;if(Zi(C>=0,"have should not go down"),C>0){let S=n._buffer.slice(n._offset,n._offset+C);if(n._offset+=C,S.length>s&&(S=S.slice(0,s)),u.push(S),c+=S.length,s-=S.length,s===0)return!1}return(b===0||n._offset>=n._chunkSize)&&(o=n._chunkSize,n._offset=0,n._buffer=Buffer.allocUnsafe(n._chunkSize)),b===0?(a+=i-w,i=w,!0):!1}Zi(this._handle,"zlib binding closed");let g;do g=this._handle.writeSync(e,t,a,i,this._buffer,this._offset,o),g=g||this._writeState;while(!this._hadError&&_(g[0],g[1]));if(this._hadError)throw h;if(c>=Xi)throw eo(this),new RangeError("Cannot create final Buffer. It would be larger than 0x"+Xi.toString(16)+" bytes");let y=Buffer.concat(u,c);return eo(this),y};Ol.inherits(Se,Fe.Inflate);function Ll(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 to(t,e){return Ll(new Se(e),t)}ro.exports=Ke=to;Ke.Inflate=Se;Ke.createInflate=vl;Ke.inflateSync=to});var Tr=k((kc,oo)=>{"use strict";var io=oo.exports=function(t){this._buffer=t,this._reads=[]};io.prototype.read=function(t,e){this._reads.push({length:Math.abs(t),allowLess:t<0,func:e})};io.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 ao=k(so=>{"use strict";var Ml=Tr(),Nl=pr();so.process=function(t,e){let r=[],n=new Ml(t);return new Nl(e,{read:n.read.bind(n),write:function(o){r.push(o)},complete:function(){}}).start(),n.process(),Buffer.concat(r)}});var co=k((Sc,fo)=>{"use strict";var lo=!0,uo=$("zlib"),Fl=no();uo.deflateSync||(lo=!1);var Ul=Tr(),$l=ao(),ql=_r(),Dl=wr(),Wl=br();fo.exports=function(t,e){if(!lo)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(B){r=B}let i;function o(B){i=B}function s(B){i.transColor=B}function a(B){i.palette=B}function u(){i.alpha=!0}let c;function h(B){c=B}let _=[];function g(B){_.push(B)}let y=new Ul(t);if(new ql(e,{read:y.read.bind(y),error:n,metadata:o,gamma:h,palette:a,transColor:s,inflateData:g,simpleTransparency:u}).start(),y.process(),r)throw r;let b=Buffer.concat(_);_.length=0;let C;if(i.interlace)C=uo.inflateSync(b);else{let W=((i.width*i.bpp*i.depth+7>>3)+1)*i.height;C=Fl(b,{chunkSize:W,maxLength:W})}if(b=null,!C||!C.length)throw new Error("bad png - invalid inflate data response");let S=$l.process(C,i);b=null;let N=Dl.dataToBitMap(S,i);S=null;let U=Wl(N,i);return i.data=U,i.gamma=c||0,i}});var mo=k((Ac,go)=>{"use strict";var ho=!0,po=$("zlib");po.deflateSync||(ho=!1);var Hl=Ne(),zl=Er();go.exports=function(t,e){if(!ho)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 zl(r),i=[];i.push(Buffer.from(Hl.PNG_SIGNATURE)),i.push(n.packIHDR(t.width,t.height)),t.gamma&&i.push(n.packGAMA(t.gamma));let o=n.filterData(t.data,t.width,t.height),s=po.deflateSync(o,n.getDeflateOptions());if(o=null,!s||!s.length)throw new Error("bad png - invalid compressed data response");return i.push(n.packIDAT(s)),i.push(n.packIEND()),Buffer.concat(i)}});var yo=k(kr=>{"use strict";var jl=co(),Gl=mo();kr.read=function(t,e){return jl(t,e||{})};kr.write=function(t,e){return Gl(t,e)}});var bo=k(wo=>{"use strict";var Yl=$("util"),_o=$("stream"),Jl=Di(),Vl=Qi(),Kl=yo(),Y=wo.PNG=function(t){_o.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 Jl(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 Vl(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"))};Yl.inherits(Y,_o);Y.sync=Kl;Y.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)};Y.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};Y.prototype.write=function(t){return this._parser.write(t),!0};Y.prototype.end=function(t){this._parser.end(t)};Y.prototype._metadata=function(t){this.width=t.width,this.height=t.height,this.emit("metadata",t)};Y.prototype._gamma=function(t){this.gamma=t};Y.prototype._handleClose=function(){!this._parser.writable&&!this._packer.readable&&this.emit("close")};Y.bitblt=function(t,e,r,n,i,o,s,a){if(r|=0,n|=0,i|=0,o|=0,s|=0,a|=0,r>t.width||n>t.height||r+i>t.width||n+o>t.height)throw new Error("bitblt reading outside image");if(s>e.width||a>e.height||s+i>e.width||a+o>e.height)throw new Error("bitblt writing outside image");for(let u=0;u<o;u++)t.data.copy(e.data,(a+u)*e.width+s<<2,(n+u)*t.width+r<<2,(n+u)*t.width+r+i<<2)};Y.prototype.bitblt=function(t,e,r,n,i,o,s){return Y.bitblt(this,t,e,r,n,i,o,s),this};Y.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 o=t.data[n+i]/255;o=Math.pow(o,1/2.2/t.gamma),t.data[n+i]=Math.round(o*255)}}t.gamma=0}};Y.prototype.adjustGamma=function(){Y.adjustGamma(this)}});var Qe=k(Ae=>{function Co(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("")}}Ae.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:Co(e.color.dark||"#000000ff"),light:Co(e.color.light||"#ffffffff")},type:e.type,rendererOpts:e.rendererOpts||{}}};Ae.getScale=function(e,r){return r.width&&r.width>=e+r.margin*2?r.width/(e+r.margin*2):r.scale};Ae.getImageWidth=function(e,r){let n=Ae.getScale(e,r);return Math.floor((e+r.margin*2)*n)};Ae.qrToImageData=function(e,r,n){let i=r.modules.size,o=r.modules.data,s=Ae.getScale(i,n),a=Math.floor((i+n.margin*2)*s),u=n.margin*s,c=[n.color.light,n.color.dark];for(let h=0;h<a;h++)for(let _=0;_<a;_++){let g=(h*a+_)*4,y=n.color.light;if(h>=u&&_>=u&&h<a-u&&_<a-u){let w=Math.floor((h-u)/s),b=Math.floor((_-u)/s);y=c[o[w*i+b]?1:0]}e[g++]=y.r,e[g++]=y.g,e[g++]=y.b,e[g]=y.a}}});var Eo=k(oe=>{var Ql=$("fs"),Zl=bo().PNG,Pr=Qe();oe.render=function(e,r){let n=Pr.getOptions(r),i=n.rendererOpts,o=Pr.getImageWidth(e.modules.size,n);i.width=o,i.height=o;let s=new Zl(i);return Pr.qrToImageData(s.data,e,n),s};oe.renderToDataURL=function(e,r,n){typeof n>"u"&&(n=r,r=void 0),oe.renderToBuffer(e,r,function(i,o){i&&n(i);let s="data:image/png;base64,";s+=o.toString("base64"),n(null,s)})};oe.renderToBuffer=function(e,r,n){typeof n>"u"&&(n=r,r=void 0);let i=oe.render(e,r),o=[];i.on("error",n),i.on("data",function(s){o.push(s)}),i.on("end",function(){n(null,Buffer.concat(o))}),i.pack()};oe.renderToFile=function(e,r,n,i){typeof i>"u"&&(i=n,n=void 0);let o=!1,s=(...u)=>{o||(o=!0,i.apply(null,u))},a=Ql.createWriteStream(e);a.on("error",s),a.on("close",s),oe.renderToFileStream(a,r,n)};oe.renderToFileStream=function(e,r,n){oe.render(r,n).pack().pipe(e)}});var To=k(_t=>{var Xl=Qe(),eu={WW:" ",WB:"\u2584",BB:"\u2588",BW:"\u2580"},tu={BB:" ",BW:"\u2584",WW:"\u2588",WB:"\u2580"};function ru(t,e,r){return t&&e?r.BB:t&&!e?r.BW:!t&&e?r.WB:r.WW}_t.render=function(t,e,r){let n=Xl.getOptions(e),i=eu;(n.color.dark.hex==="#ffffff"||n.color.light.hex==="#000000")&&(i=tu);let o=t.modules.size,s=t.modules.data,a="",u=Array(o+n.margin*2+1).join(i.WW);u=Array(n.margin/2+1).join(u+`
|
|
12
|
-
`);let c=Array(n.margin+1).join(i.WW);a+=u;for(let h=0;h<
|
|
13
|
-
`}return a+=u.slice(0,-1),typeof r=="function"&&r(null,a),a};
|
|
14
|
-
`;for(let h=0;h<n;++h){a+=
|
|
9
|
+
Minimum version required to store current data is: `+s+`.
|
|
10
|
+
`);let o=il(e,r,i),a=Pt.getSymbolSize(e),u=new Ga(a);return Xa(u,e),el(u),tl(u,e),_r(u,r,0),e>=7&&rl(u,e),nl(u,o),isNaN(n)&&(n=wr.getBestMask(u,_r.bind(null,u,r))),wr.applyMask(n,u),_r(u,r,n),{modules:u,version:e,errorCorrectionLevel:r,maskPattern:n,segments:i}}Mi.create=function(e,r){if(typeof e>"u"||e==="")throw new Error("No input text");let n=mr.M,i,s;return typeof r<"u"&&(n=mr.from(r.errorCorrectionLevel,mr.M),i=kt.from(r.version),s=wr.from(r.maskPattern),r.toSJISFunc&&Pt.setToSJISFunction(r.toSJISFunc)),ol(e,i,n,s)}});var Er=P((Hc,$i)=>{"use strict";var al=W("util"),Ni=W("stream"),oe=$i.exports=function(){Ni.call(this),this._buffers=[],this._buffered=0,this._reads=[],this._paused=!1,this._encoding="utf8",this.writable=!0};al.inherits(oe,Ni);oe.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))};oe.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};oe.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()))};oe.prototype.destroySoon=oe.prototype.end;oe.prototype._end=function(){this._reads.length>0&&this.emit("error",new Error("Unexpected end of input")),this.destroy()};oe.prototype.destroy=function(){this._buffers&&(this.writable=!1,this._reads=null,this._buffers=null,this.emit("close"))};oe.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))};oe.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)};oe.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 kr=P(Tr=>{"use strict";var Ce=[{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]}];Tr.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<Ce.length;a++){let u=Ce[a],c=s*u.x.length,h=o*u.y.length;for(let y=0;y<u.x.length&&u.x[y]<n;y++)c++;for(let y=0;y<u.y.length&&u.y[y]<i;y++)h++;c>0&&h>0&&r.push({width:c,height:h,index:a})}return r};Tr.getInterlaceIterator=function(t){return function(e,r,n){let i=e%Ce[n].x.length,s=(e-i)/Ce[n].x.length*8+Ce[n].x[i],o=r%Ce[n].y.length,a=(r-o)/Ce[n].y.length*8+Ce[n].y[o];return s*4+a*t*4}}});var Pr=P((jc,Ui)=>{"use strict";Ui.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 Sr=P((Qc,qi)=>{"use strict";var ll=kr(),ul=Pr();function Fi(t,e,r){let n=t*e;return r!==8&&(n=Math.ceil(n/(8/r))),n}var ze=qi.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=ll.getImagePasses(r,n);for(let u=0;u<a.length;u++)this._images.push({byteWidth:Fi(a[u].width,s,o),height:a[u].height,lineIndex:0})}else this._images.push({byteWidth:Fi(r,s,o),height:n,lineIndex:0});o===8?this._xComparison=s:o===16?this._xComparison=s*2:this._xComparison=1};ze.prototype.start=function(){this.read(this._images[this._imageIndex].byteWidth+1,this._reverseFilterLine.bind(this))};ze.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}};ze.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}};ze.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],u=s?s[o]:0,c=o>i?e[o-n]:0,h=Math.floor((c+u)/2);e[o]=a+h}};ze.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],u=s?s[o]:0,c=o>i?e[o-n]:0,h=o>i&&s?s[o-n]:0,y=ul(c,u,h);e[o]=a+y}};ze.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 Hi=P((Gc,Wi)=>{"use strict";var fl=W("util"),Di=Er(),cl=Sr(),hl=Wi.exports=function(t){Di.call(this);let e=[],r=this;this._filter=new cl(t,{read:this.read.bind(this),write:function(n){e.push(n)},complete:function(){r.emit("complete",Buffer.concat(e))}}),this._filter.start()};fl.inherits(hl,Di)});var je=P((Yc,zi)=>{"use strict";zi.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 Rr=P((Vc,ji)=>{"use strict";var xr=[];(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;xr[t]=e}})();var Br=ji.exports=function(){this._crc=-1};Br.prototype.write=function(t){for(let e=0;e<t.length;e++)this._crc=xr[(this._crc^t[e])&255]^this._crc>>>8;return!0};Br.prototype.crc32=function(){return this._crc^-1};Br.crc32=function(t){let e=-1;for(let r=0;r<t.length;r++)e=xr[(e^t[r])&255]^e>>>8;return e^-1}});var Ar=P((Jc,Qi)=>{"use strict";var j=je(),dl=Rr(),Q=Qi.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[j.TYPE_IHDR]=this._handleIHDR.bind(this),this._chunks[j.TYPE_IEND]=this._handleIEND.bind(this),this._chunks[j.TYPE_IDAT]=this._handleIDAT.bind(this),this._chunks[j.TYPE_PLTE]=this._handlePLTE.bind(this),this._chunks[j.TYPE_tRNS]=this._handleTRNS.bind(this),this._chunks[j.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(){}};Q.prototype.start=function(){this.read(j.PNG_SIGNATURE.length,this._parseSignature.bind(this))};Q.prototype._parseSignature=function(t){let e=j.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))};Q.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!==j.TYPE_IHDR){this.error(new Error("Expected IHDR on beggining"));return}if(this._crc=new dl,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))};Q.prototype._skipChunk=function(){this.read(8,this._parseChunkBegin.bind(this))};Q.prototype._handleChunkEnd=function(){this.read(4,this._parseChunkEnd.bind(this))};Q.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))};Q.prototype._handleIHDR=function(t){this.read(t,this._parseIHDR.bind(this))};Q.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 j.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 u=j.COLORTYPE_TO_BPP_MAP[this._colorType];this._hasIHDR=!0,this.metadata({width:e,height:r,depth:n,interlace:!!a,palette:!!(i&j.COLORTYPE_PALETTE),color:!!(i&j.COLORTYPE_COLOR),alpha:!!(i&j.COLORTYPE_ALPHA),bpp:u,colorType:i}),this._handleChunkEnd()};Q.prototype._handlePLTE=function(t){this.read(t,this._parsePLTE.bind(this))};Q.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()};Q.prototype._handleTRNS=function(t){this.simpleTransparency(),this.read(t,this._parseTRNS.bind(this))};Q.prototype._parseTRNS=function(t){if(this._crc.write(t),this._colorType===j.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===j.COLORTYPE_GRAYSCALE&&this.transColor([t.readUInt16BE(0)]),this._colorType===j.COLORTYPE_COLOR&&this.transColor([t.readUInt16BE(0),t.readUInt16BE(2),t.readUInt16BE(4)]),this._handleChunkEnd()};Q.prototype._handleGAMA=function(t){this.read(t,this._parseGAMA.bind(this))};Q.prototype._parseGAMA=function(t){this._crc.write(t),this.gamma(t.readUInt32BE(0)/j.GAMMA_DIVISION),this._handleChunkEnd()};Q.prototype._handleIDAT=function(t){this._emittedHeadersFinished||(this._emittedHeadersFinished=!0,this.headersFinished()),this.read(-t,this._parseIDAT.bind(this,t))};Q.prototype._parseIDAT=function(t,e){if(this._crc.write(e),this._colorType===j.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()};Q.prototype._handleIEND=function(t){this.read(t,this._parseIEND.bind(this))};Q.prototype._parseIEND=function(t){this._crc.write(t),this._hasIEND=!0,this._handleChunkEnd(),this.finished&&this.finished()}});var Ir=P(Yi=>{"use strict";var Gi=kr(),pl=[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]}],gl=[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 ml(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,u,c,h,y,_,b;switch(e){default:throw new Error("unrecognised depth");case 16:_=t[n],n++,r.push((s<<8)+_);break;case 4:_=s&15,b=s>>4,r.push(b,_);break;case 2:h=s&3,y=s>>2&3,_=s>>4&3,b=s>>6&3,r.push(b,_,y,h);break;case 1:o=s&1,a=s>>1&1,u=s>>2&1,c=s>>3&1,h=s>>4&1,y=s>>5&1,_=s>>6&1,b=s>>7&1,r.push(b,_,y,h,c,u,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 yl(t,e,r,n,i,s){let o=t.width,a=t.height,u=t.index;for(let c=0;c<a;c++)for(let h=0;h<o;h++){let y=r(h,c,u);pl[n](e,i,y,s),s+=n}return s}function _l(t,e,r,n,i,s){let o=t.width,a=t.height,u=t.index;for(let c=0;c<a;c++){for(let h=0;h<o;h++){let y=i.get(n),_=r(h,c,u);gl[n](e,y,_,s)}i.resetAfterLine()}}Yi.dataToBitMap=function(t,e){let r=e.width,n=e.height,i=e.depth,s=e.bpp,o=e.interlace,a;i!==8&&(a=ml(t,i));let u;i<=8?u=Buffer.alloc(r*n*4):u=new Uint16Array(r*n*4);let c=Math.pow(2,i)-1,h=0,y,_;if(o)y=Gi.getImagePasses(r,n),_=Gi.getInterlaceIterator(r,n);else{let b=0;_=function(){let g=b;return b+=4,g},y=[{width:r,height:n}]}for(let b=0;b<y.length;b++)i===8?h=yl(y[b],u,_,s,t,h):_l(y[b],u,_,s,a,c);if(i===8){if(h!==t.length)throw new Error("extra data found")}else a.end();return u}});var vr=P((Zc,Vi)=>{"use strict";function wl(t,e,r,n,i){let s=0;for(let o=0;o<n;o++)for(let a=0;a<r;a++){let u=i[t[s]];if(!u)throw new Error("index "+t[s]+" not in palette");for(let c=0;c<4;c++)e[s+c]=u[c];s+=4}}function bl(t,e,r,n,i){let s=0;for(let o=0;o<n;o++)for(let a=0;a<r;a++){let u=!1;if(i.length===1?i[0]===t[s]&&(u=!0):i[0]===t[s]&&i[1]===t[s+1]&&i[2]===t[s+2]&&(u=!0),u)for(let c=0;c<4;c++)e[s+c]=0;s+=4}}function Cl(t,e,r,n,i){let s=255,o=Math.pow(2,i)-1,a=0;for(let u=0;u<n;u++)for(let c=0;c<r;c++){for(let h=0;h<4;h++)e[a+h]=Math.floor(t[a+h]*s/o+.5);a+=4}}Vi.exports=function(t,e){let r=e.depth,n=e.width,i=e.height,s=e.colorType,o=e.transColor,a=e.palette,u=t;return s===3?wl(t,u,n,i,a):(o&&bl(t,u,n,i,o),r!==8&&(r===16&&(u=Buffer.alloc(n*i*4)),Cl(t,u,n,i,r))),u}});var Zi=P((Xc,Ki)=>{"use strict";var El=W("util"),Or=W("zlib"),Ji=Er(),Tl=Hi(),kl=Ar(),Pl=Ir(),Sl=vr(),ue=Ki.exports=function(t){Ji.call(this),this._parser=new kl(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()};El.inherits(ue,Ji);ue.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};ue.prototype._inflateData=function(t){if(!this._inflate)if(this._bitmapInfo.interlace)this._inflate=Or.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,Or.Z_MIN_CHUNK);this._inflate=Or.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)};ue.prototype._handleMetaData=function(t){this._metaData=t,this._bitmapInfo=Object.create(t),this._filter=new Tl(this._bitmapInfo)};ue.prototype._handleTransColor=function(t){this._bitmapInfo.transColor=t};ue.prototype._handlePalette=function(t){this._bitmapInfo.palette=t};ue.prototype._simpleTransparency=function(){this._metaData.alpha=!0};ue.prototype._headersFinished=function(){this.emit("metadata",this._metaData)};ue.prototype._finished=function(){this.errord||(this._inflate?this._inflate.end():this.emit("error","No Inflate block"))};ue.prototype._complete=function(t){if(this.errord)return;let e;try{let r=Pl.dataToBitMap(t,this._bitmapInfo);e=Sl(r,this._bitmapInfo),r=null}catch(r){this._handleError(r);return}this.emit("parsed",e)}});var es=P((eh,Xi)=>{"use strict";var re=je();Xi.exports=function(t,e,r,n){let i=[re.COLORTYPE_COLOR_ALPHA,re.COLORTYPE_ALPHA].indexOf(n.colorType)!==-1;if(n.colorType===n.inputColorType){let g=(function(){let w=new ArrayBuffer(2);return new DataView(w).setInt16(0,256,!0),new Int16Array(w)[0]!==256})();if(n.bitDepth===8||n.bitDepth===16&&g)return t}let s=n.bitDepth!==16?t:new Uint16Array(t.buffer),o=255,a=re.COLORTYPE_TO_BPP_MAP[n.inputColorType];a===4&&!n.inputHasAlpha&&(a=3);let u=re.COLORTYPE_TO_BPP_MAP[n.colorType];n.bitDepth===16&&(o=65535,u*=2);let c=Buffer.alloc(e*r*u),h=0,y=0,_=n.bgColor||{};_.red===void 0&&(_.red=o),_.green===void 0&&(_.green=o),_.blue===void 0&&(_.blue=o);function b(){let g,w,C,E=o;switch(n.inputColorType){case re.COLORTYPE_COLOR_ALPHA:E=s[h+3],g=s[h],w=s[h+1],C=s[h+2];break;case re.COLORTYPE_COLOR:g=s[h],w=s[h+1],C=s[h+2];break;case re.COLORTYPE_ALPHA:E=s[h+1],g=s[h],w=g,C=g;break;case re.COLORTYPE_GRAYSCALE:g=s[h],w=g,C=g;break;default:throw new Error("input color type:"+n.inputColorType+" is not supported at present")}return n.inputHasAlpha&&(i||(E/=o,g=Math.min(Math.max(Math.round((1-E)*_.red+E*g),0),o),w=Math.min(Math.max(Math.round((1-E)*_.green+E*w),0),o),C=Math.min(Math.max(Math.round((1-E)*_.blue+E*C),0),o))),{red:g,green:w,blue:C,alpha:E}}for(let g=0;g<r;g++)for(let w=0;w<e;w++){let C=b(s,h);switch(n.colorType){case re.COLORTYPE_COLOR_ALPHA:case re.COLORTYPE_COLOR:n.bitDepth===8?(c[y]=C.red,c[y+1]=C.green,c[y+2]=C.blue,i&&(c[y+3]=C.alpha)):(c.writeUInt16BE(C.red,y),c.writeUInt16BE(C.green,y+2),c.writeUInt16BE(C.blue,y+4),i&&c.writeUInt16BE(C.alpha,y+6));break;case re.COLORTYPE_ALPHA:case re.COLORTYPE_GRAYSCALE:{let E=(C.red+C.green+C.blue)/3;n.bitDepth===8?(c[y]=E,i&&(c[y+1]=C.alpha)):(c.writeUInt16BE(E,y),i&&c.writeUInt16BE(C.alpha,y+2));break}default:throw new Error("unrecognised color Type "+n.colorType)}h+=a,y+=u}return c}});var ns=P((th,rs)=>{"use strict";var ts=Pr();function xl(t,e,r,n,i){for(let s=0;s<r;s++)n[i+s]=t[e+s]}function Bl(t,e,r){let n=0,i=e+r;for(let s=e;s<i;s++)n+=Math.abs(t[s]);return n}function Rl(t,e,r,n,i,s){for(let o=0;o<r;o++){let a=o>=s?t[e+o-s]:0,u=t[e+o]-a;n[i+o]=u}}function Al(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 Il(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 vl(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 Ol(t,e,r,n,i,s){for(let o=0;o<r;o++){let a=o>=s?t[e+o-s]:0,u=e>0?t[e+o-r]:0,c=t[e+o]-(a+u>>1);n[i+o]=c}}function Ll(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,u=t[e+s]-(o+a>>1);i+=Math.abs(u)}return i}function Ml(t,e,r,n,i,s){for(let o=0;o<r;o++){let a=o>=s?t[e+o-s]:0,u=e>0?t[e+o-r]:0,c=e>0&&o>=s?t[e+o-(r+s)]:0,h=t[e+o]-ts(a,u,c);n[i+o]=h}}function Nl(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,u=e>0&&s>=n?t[e+s-(r+n)]:0,c=t[e+s]-ts(o,a,u);i+=Math.abs(c)}return i}var $l={0:xl,1:Rl,2:Il,3:Ol,4:Ml},Ul={0:Bl,1:Al,2:vl,3:Ll,4:Nl};rs.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,u=0,c=Buffer.alloc((o+1)*r),h=s[0];for(let y=0;y<r;y++){if(s.length>1){let _=1/0;for(let b=0;b<s.length;b++){let g=Ul[s[b]](t,u,o,i);g<_&&(h=s[b],_=g)}}c[a]=h,a++,$l[h](t,u,o,c,a,i),a+=o,u+=o}return c}});var Lr=P((rh,is)=>{"use strict";var Y=je(),Fl=Rr(),ql=es(),Dl=ns(),Wl=W("zlib"),Ee=is.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||Wl.createDeflate,t.bitDepth=t.bitDepth||8,t.colorType=typeof t.colorType=="number"?t.colorType:Y.COLORTYPE_COLOR_ALPHA,t.inputColorType=typeof t.inputColorType=="number"?t.inputColorType:Y.COLORTYPE_COLOR_ALPHA,[Y.COLORTYPE_GRAYSCALE,Y.COLORTYPE_COLOR,Y.COLORTYPE_COLOR_ALPHA,Y.COLORTYPE_ALPHA].indexOf(t.colorType)===-1)throw new Error("option color type:"+t.colorType+" is not supported at present");if([Y.COLORTYPE_GRAYSCALE,Y.COLORTYPE_COLOR,Y.COLORTYPE_COLOR_ALPHA,Y.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")};Ee.prototype.getDeflateOptions=function(){return{chunkSize:this._options.deflateChunkSize,level:this._options.deflateLevel,strategy:this._options.deflateStrategy}};Ee.prototype.createDeflate=function(){return this._options.deflateFactory(this.getDeflateOptions())};Ee.prototype.filterData=function(t,e,r){let n=ql(t,e,r,this._options),i=Y.COLORTYPE_TO_BPP_MAP[this._options.colorType];return Dl(n,e,r,this._options,i)};Ee.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(Fl.crc32(n.slice(4,n.length-4)),n.length-4),n};Ee.prototype.packGAMA=function(t){let e=Buffer.alloc(4);return e.writeUInt32BE(Math.floor(t*Y.GAMMA_DIVISION),0),this._packChunk(Y.TYPE_gAMA,e)};Ee.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(Y.TYPE_IHDR,r)};Ee.prototype.packIDAT=function(t){return this._packChunk(Y.TYPE_IDAT,t)};Ee.prototype.packIEND=function(){return this._packChunk(Y.TYPE_IEND,null)}});var ls=P((nh,as)=>{"use strict";var Hl=W("util"),ss=W("stream"),zl=je(),jl=Lr(),os=as.exports=function(t){ss.call(this);let e=t||{};this._packer=new jl(e),this._deflate=this._packer.createDeflate(),this.readable=!0};Hl.inherits(os,ss);os.prototype.pack=function(t,e,r,n){this.emit("data",Buffer.from(zl.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 ps=P((st,ds)=>{"use strict";var us=W("assert").ok,Qe=W("zlib"),Ql=W("util"),fs=W("buffer").kMaxLength;function Oe(t){if(!(this instanceof Oe))return new Oe(t);t&&t.chunkSize<Qe.Z_MIN_CHUNK&&(t.chunkSize=Qe.Z_MIN_CHUNK),Qe.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 Gl(t){return new Oe(t)}function cs(t,e){e&&process.nextTick(e),t._handle&&(t._handle.close(),t._handle=null)}Oe.prototype._processChunk=function(t,e,r){if(typeof r=="function")return Qe.Inflate._processChunk.call(this,t,e,r);let n=this,i=t&&t.length,s=this._chunkSize-this._offset,o=this._maxLength,a=0,u=[],c=0,h;this.on("error",function(g){h=g});function y(g,w){if(n._hadError)return;let C=s-w;if(us(C>=0,"have should not go down"),C>0){let E=n._buffer.slice(n._offset,n._offset+C);if(n._offset+=C,E.length>o&&(E=E.slice(0,o)),u.push(E),c+=E.length,o-=E.length,o===0)return!1}return(w===0||n._offset>=n._chunkSize)&&(s=n._chunkSize,n._offset=0,n._buffer=Buffer.allocUnsafe(n._chunkSize)),w===0?(a+=i-g,i=g,!0):!1}us(this._handle,"zlib binding closed");let _;do _=this._handle.writeSync(e,t,a,i,this._buffer,this._offset,s),_=_||this._writeState;while(!this._hadError&&y(_[0],_[1]));if(this._hadError)throw h;if(c>=fs)throw cs(this),new RangeError("Cannot create final Buffer. It would be larger than 0x"+fs.toString(16)+" bytes");let b=Buffer.concat(u,c);return cs(this),b};Ql.inherits(Oe,Qe.Inflate);function Yl(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=Qe.Z_FINISH),t._processChunk(e,r)}function hs(t,e){return Yl(new Oe(e),t)}ds.exports=st=hs;st.Inflate=Oe;st.createInflate=Gl;st.inflateSync=hs});var Mr=P((ih,ms)=>{"use strict";var gs=ms.exports=function(t){this._buffer=t,this._reads=[]};gs.prototype.read=function(t,e){this._reads.push({length:Math.abs(t),allowLess:t<0,func:e})};gs.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 _s=P(ys=>{"use strict";var Vl=Mr(),Jl=Sr();ys.process=function(t,e){let r=[],n=new Vl(t);return new Jl(e,{read:n.read.bind(n),write:function(s){r.push(s)},complete:function(){}}).start(),n.process(),Buffer.concat(r)}});var Es=P((oh,Cs)=>{"use strict";var ws=!0,bs=W("zlib"),Kl=ps();bs.deflateSync||(ws=!1);var Zl=Mr(),Xl=_s(),eu=Ar(),tu=Ir(),ru=vr();Cs.exports=function(t,e){if(!ws)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(O){r=O}let i;function s(O){i=O}function o(O){i.transColor=O}function a(O){i.palette=O}function u(){i.alpha=!0}let c;function h(O){c=O}let y=[];function _(O){y.push(O)}let b=new Zl(t);if(new eu(e,{read:b.read.bind(b),error:n,metadata:s,gamma:h,palette:a,transColor:o,inflateData:_,simpleTransparency:u}).start(),b.process(),r)throw r;let w=Buffer.concat(y);y.length=0;let C;if(i.interlace)C=bs.inflateSync(w);else{let N=((i.width*i.bpp*i.depth+7>>3)+1)*i.height;C=Kl(w,{chunkSize:N,maxLength:N})}if(w=null,!C||!C.length)throw new Error("bad png - invalid inflate data response");let E=Xl.process(C,i);w=null;let x=tu.dataToBitMap(E,i);E=null;let I=ru(x,i);return i.data=I,i.gamma=c||0,i}});var Ss=P((ah,Ps)=>{"use strict";var Ts=!0,ks=W("zlib");ks.deflateSync||(Ts=!1);var nu=je(),iu=Lr();Ps.exports=function(t,e){if(!Ts)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 iu(r),i=[];i.push(Buffer.from(nu.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=ks.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 xs=P(Nr=>{"use strict";var su=Es(),ou=Ss();Nr.read=function(t,e){return su(t,e||{})};Nr.write=function(t,e){return ou(t,e)}});var As=P(Rs=>{"use strict";var au=W("util"),Bs=W("stream"),lu=Zi(),uu=ls(),fu=xs(),V=Rs.PNG=function(t){Bs.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 lu(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 uu(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"))};au.inherits(V,Bs);V.sync=fu;V.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)};V.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};V.prototype.write=function(t){return this._parser.write(t),!0};V.prototype.end=function(t){this._parser.end(t)};V.prototype._metadata=function(t){this.width=t.width,this.height=t.height,this.emit("metadata",t)};V.prototype._gamma=function(t){this.gamma=t};V.prototype._handleClose=function(){!this._parser.writable&&!this._packer.readable&&this.emit("close")};V.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 u=0;u<s;u++)t.data.copy(e.data,(a+u)*e.width+o<<2,(n+u)*t.width+r<<2,(n+u)*t.width+r+i<<2)};V.prototype.bitblt=function(t,e,r,n,i,s,o){return V.bitblt(this,t,e,r,n,i,s,o),this};V.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}};V.prototype.adjustGamma=function(){V.adjustGamma(this)}});var ot=P(Le=>{function Is(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("")}}Le.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:Is(e.color.dark||"#000000ff"),light:Is(e.color.light||"#ffffffff")},type:e.type,rendererOpts:e.rendererOpts||{}}};Le.getScale=function(e,r){return r.width&&r.width>=e+r.margin*2?r.width/(e+r.margin*2):r.scale};Le.getImageWidth=function(e,r){let n=Le.getScale(e,r);return Math.floor((e+r.margin*2)*n)};Le.qrToImageData=function(e,r,n){let i=r.modules.size,s=r.modules.data,o=Le.getScale(i,n),a=Math.floor((i+n.margin*2)*o),u=n.margin*o,c=[n.color.light,n.color.dark];for(let h=0;h<a;h++)for(let y=0;y<a;y++){let _=(h*a+y)*4,b=n.color.light;if(h>=u&&y>=u&&h<a-u&&y<a-u){let g=Math.floor((h-u)/o),w=Math.floor((y-u)/o);b=c[s[g*i+w]?1:0]}e[_++]=b.r,e[_++]=b.g,e[_++]=b.b,e[_]=b.a}}});var vs=P(fe=>{var cu=W("fs"),hu=As().PNG,$r=ot();fe.render=function(e,r){let n=$r.getOptions(r),i=n.rendererOpts,s=$r.getImageWidth(e.modules.size,n);i.width=s,i.height=s;let o=new hu(i);return $r.qrToImageData(o.data,e,n),o};fe.renderToDataURL=function(e,r,n){typeof n>"u"&&(n=r,r=void 0),fe.renderToBuffer(e,r,function(i,s){i&&n(i);let o="data:image/png;base64,";o+=s.toString("base64"),n(null,o)})};fe.renderToBuffer=function(e,r,n){typeof n>"u"&&(n=r,r=void 0);let i=fe.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()};fe.renderToFile=function(e,r,n,i){typeof i>"u"&&(i=n,n=void 0);let s=!1,o=(...u)=>{s||(s=!0,i.apply(null,u))},a=cu.createWriteStream(e);a.on("error",o),a.on("close",o),fe.renderToFileStream(a,r,n)};fe.renderToFileStream=function(e,r,n){fe.render(r,n).pack().pipe(e)}});var Os=P(St=>{var du=ot(),pu={WW:" ",WB:"\u2584",BB:"\u2588",BW:"\u2580"},gu={BB:" ",BW:"\u2584",WW:"\u2588",WB:"\u2580"};function mu(t,e,r){return t&&e?r.BB:t&&!e?r.BW:!t&&e?r.WB:r.WW}St.render=function(t,e,r){let n=du.getOptions(e),i=pu;(n.color.dark.hex==="#ffffff"||n.color.light.hex==="#000000")&&(i=gu);let s=t.modules.size,o=t.modules.data,a="",u=Array(s+n.margin*2+1).join(i.WW);u=Array(n.margin/2+1).join(u+`
|
|
11
|
+
`);let c=Array(n.margin+1).join(i.WW);a+=u;for(let h=0;h<s;h+=2){a+=c;for(let y=0;y<s;y++){let _=o[h*s+y],b=o[(h+1)*s+y];a+=mu(_,b,i)}a+=c+`
|
|
12
|
+
`}return a+=u.slice(0,-1),typeof r=="function"&&r(null,a),a};St.renderToFile=function(e,r,n,i){typeof i>"u"&&(i=n,n=void 0);let s=W("fs"),o=St.render(r,n);s.writeFile(e,o,i)}});var Ms=P(Ls=>{Ls.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="",u=Array(n+3).join(o),c=Array(2).join(o);a+=u+`
|
|
13
|
+
`;for(let h=0;h<n;++h){a+=o;for(let y=0;y<n;y++)a+=i[h*n+y]?s:o;a+=c+`
|
|
15
14
|
`}return a+=u+`
|
|
16
|
-
`,typeof r=="function"&&r(null,a),a}});var
|
|
17
|
-
`+
|
|
18
|
-
`;return typeof n=="function"&&n(null,g),g}});var Lo=k(wt=>{var hu=xr();wt.render=hu.render;wt.renderToFile=function(e,r,n,i){typeof i>"u"&&(i=n,n=void 0);let o=$("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">'+wt.render(r,n);o.writeFile(e,a,i)}});var Mo=k(bt=>{var Br=Qe();function du(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 pu(){try{return document.createElement("canvas")}catch{throw new Error("You need to specify a canvas element")}}bt.render=function(e,r,n){let i=n,o=r;typeof i>"u"&&(!r||!r.getContext)&&(i=r,r=void 0),r||(o=pu()),i=Br.getOptions(i);let s=Br.getImageWidth(e.modules.size,i),a=o.getContext("2d"),u=a.createImageData(s,s);return Br.qrToImageData(u.data,e,i),du(a,o,s),a.putImageData(u,0,0),o};bt.renderToDataURL=function(e,r,n){let i=n;typeof i>"u"&&(!r||!r.getContext)&&(i=r,r=void 0),i||(i={});let o=bt.render(e,r,i),s=i.type||"image/png",a=i.rendererOpts||{};return o.toDataURL(s,a.quality)}});var Fo=k(Ze=>{var gu=zt(),Ir=ur(),No=Mo(),mu=xr();function Or(t,e,r,n,i){let o=[].slice.call(arguments,1),s=o.length,a=typeof o[s-1]=="function";if(!a&&!gu())throw new Error("Callback required as last argument");if(a){if(s<2)throw new Error("Too few arguments provided");s===2?(i=r,r=e,e=n=void 0):s===3&&(e.getContext&&typeof i>"u"?(i=n,n=void 0):(i=n,n=r,r=e,e=void 0))}else{if(s<1)throw new Error("Too few arguments provided");return s===1?(r=e,e=n=void 0):s===2&&!e.getContext&&(n=r,r=e,e=void 0),new Promise(function(u,c){try{let h=Ir.create(r,n);u(t(h,e,n))}catch(h){c(h)}})}try{let u=Ir.create(r,n);i(null,t(u,e,n))}catch(u){i(u)}}Ze.create=Ir.create;Ze.toCanvas=Or.bind(null,No.render);Ze.toDataURL=Or.bind(null,No.renderToDataURL);Ze.toString=Or.bind(null,function(t,e,r){return mu.render(t,r)})});var Do=k(me=>{var Uo=zt(),vr=ur(),yu=Eo(),$o=To(),_u=Io(),qo=Lo();function Xe(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(Uo())e=r||{},r=null;else throw new Error("Callback required as last argument");return{opts:e,cb:r}}function wu(t){return t.slice((t.lastIndexOf(".")-1>>>0)+2).toLowerCase()}function Ct(t){switch(t){case"svg":return qo;case"txt":case"utf8":return $o;default:return yu}}function bu(t){switch(t){case"svg":return qo;case"terminal":return _u;default:return $o}}function et(t,e,r){if(!r.cb)return new Promise(function(n,i){try{let o=vr.create(e,r.opts);return t(o,r.opts,function(s,a){return s?i(s):n(a)})}catch(o){i(o)}});try{let n=vr.create(e,r.opts);return t(n,r.opts,r.cb)}catch(n){r.cb(n)}}me.create=vr.create;me.toCanvas=Fo().toCanvas;me.toString=function(e,r,n){let i=Xe(e,r,n),o=i.opts?i.opts.type:void 0,s=bu(o);return et(s.render,e,i)};me.toDataURL=function(e,r,n){let i=Xe(e,r,n),o=Ct(i.opts.type);return et(o.renderToDataURL,e,i)};me.toBuffer=function(e,r,n){let i=Xe(e,r,n),o=Ct(i.opts.type);return et(o.renderToBuffer,e,i)};me.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&&!Uo())throw new Error("Too few arguments provided");let o=Xe(r,n,i),s=o.opts.type||wu(e),u=Ct(s).renderToFile.bind(null,e);return et(u,r,o)};me.toFileStream=function(e,r,n){if(arguments.length<2)throw new Error("Too few arguments provided");let i=Xe(r,n,e.emit.bind(e,"error")),s=Ct("png").renderToFileStream.bind(null,e);et(s,r,i)}});var Ho=k((Dc,Wo)=>{Wo.exports=Do()});var os=k((Nh,is)=>{"use strict";var Wr=Object.defineProperty,Lu=Object.getOwnPropertyDescriptor,Mu=Object.getOwnPropertyNames,Nu=Object.prototype.hasOwnProperty,Fu=(t,e)=>{for(var r in e)Wr(t,r,{get:e[r],enumerable:!0})},Uu=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of Mu(e))!Nu.call(t,i)&&i!==r&&Wr(t,i,{get:()=>e[i],enumerable:!(n=Lu(e,i))||n.enumerable});return t},$u=t=>Uu(Wr({},"__esModule",{value:!0}),t),Xo={};Fu(Xo,{decode:()=>rf,encode:()=>tf,getDuration:()=>nf,getWavFileInfo:()=>sf,isSilk:()=>af,isWav:()=>of});is.exports=$u(Xo);var qr=$("url").pathToFileURL(__filename).href,qu=async function(t={}){var e,r=t,n,i,o=new Promise((l,f)=>{n=l,i=f}),s=typeof window=="object",a=typeof WorkerGlobalScope<"u",u=typeof process=="object"&&typeof process.versions=="object"&&typeof process.versions.node=="string"&&process.type!="renderer";if(u){let{createRequire:l}=await import("module");var c=l(qr)}var h=(l,f)=>{throw f},_=qr,g="",y,w;if(u){var b=c("fs"),C=c("path");_.startsWith("file:")&&(g=C.dirname(c("url").fileURLToPath(_))+"/"),w=l=>(l=it(l)?new URL(l):l,b.readFileSync(l)),y=async l=>(l=it(l)?new URL(l):l,b.readFileSync(l,void 0)),process.argv.slice(2),h=(l,f)=>{throw process.exitCode=l,f}}else if(s||a){try{g=new URL(".",_).href}catch{}a&&(w=l=>{var f=new XMLHttpRequest;return f.open("GET",l,!1),f.responseType="arraybuffer",f.send(null),new Uint8Array(f.response)}),y=async l=>{if(it(l))return new Promise((p,d)=>{var m=new XMLHttpRequest;m.open("GET",l,!0),m.responseType="arraybuffer",m.onload=()=>{m.status==200||m.status==0&&m.response?p(m.response):d(m.status)},m.onerror=d,m.send(null)});var f=await fetch(l,{credentials:"same-origin"});if(f.ok)return f.arrayBuffer();throw Error(f.status+" : "+f.url)}}console.log.bind(console);var S=console.error.bind(console),N,U,B=!1,W,v,L,j,ye,_e,H,Vr,Kr,Qr,Zr,it=l=>l.startsWith("file://");function Xr(){var l=U.buffer;v=new Int8Array(l),j=new Int16Array(l),L=new Uint8Array(l),ye=new Uint16Array(l),_e=new Int32Array(l),H=new Uint32Array(l),Vr=new Float32Array(l),Zr=new Float64Array(l),Kr=new BigInt64Array(l),Qr=new BigUint64Array(l)}var we=0,Ue=null;function en(l){throw r.onAbort?.(l),l="Aborted("+l+")",S(l),B=!0,l=new WebAssembly.RuntimeError(l+". Build with -sASSERTIONS for more info."),i(l),l}var vt;async function ys(l){if(!N)try{var f=await y(l);return new Uint8Array(f)}catch{}if(l==vt&&N)l=new Uint8Array(N);else if(w)l=w(l);else throw"both async and sync fetching of the wasm failed";return l}async function _s(l,f){try{var p=await ys(l);return await WebAssembly.instantiate(p,f)}catch(d){S(`failed to asynchronously prepare wasm: ${d}`),en(d)}}async function ws(l){var f=vt;if(!N&&typeof WebAssembly.instantiateStreaming=="function"&&!it(f)&&!u)try{var p=fetch(f,{credentials:"same-origin"});return await WebAssembly.instantiateStreaming(p,l)}catch(d){S(`wasm streaming compile failed: ${d}`),S("falling back to ArrayBuffer instantiation")}return _s(f,l)}class Lt{name="ExitStatus";constructor(f){this.message=`Program terminated with exit(${f})`,this.status=f}}var tn=l=>{for(;0<l.length;)l.shift()(r)},rn=[],nn=[],bs=()=>{var l=r.preRun.shift();nn.push(l)},ot=!0;class Cs{constructor(f){this.I=f-24}}var on=0,Es=0,sn,X=l=>{for(var f="";L[l];)f+=sn[L[l++]];return f},xe={},be={},st={},V=r.BindingError=class extends Error{constructor(l){super(l),this.name="BindingError"}},Ts=l=>{throw new V(l)};function ks(l,f,p={}){var d=f.name;if(!l)throw new V(`type "${d}" must have a positive integer typeid pointer`);if(be.hasOwnProperty(l)){if(p.K)return;throw new V(`Cannot register type '${d}' twice`)}be[l]=f,delete st[l],xe.hasOwnProperty(l)&&(f=xe[l],delete xe[l],f.forEach(m=>m()))}function ee(l,f,p={}){return ks(l,f,p)}var an=(l,f,p)=>{switch(f){case 1:return p?d=>v[d]:d=>L[d];case 2:return p?d=>j[d>>1]:d=>ye[d>>1];case 4:return p?d=>_e[d>>2]:d=>H[d>>2];case 8:return p?d=>Kr[d>>3]:d=>Qr[d>>3];default:throw new TypeError(`invalid integer width (${f}): ${l}`)}},Mt=[],se=[],Nt=l=>{9<l&&--se[l+1]===0&&(se[l]=void 0,Mt.push(l))},Ft=l=>{if(!l)throw new V(`Cannot use deleted val. handle = ${l}`);return se[l]},Ut=l=>{switch(l){case void 0:return 2;case null:return 4;case!0:return 6;case!1:return 8;default:let f=Mt.pop()||se.length;return se[f]=l,se[f+1]=1,f}};function $t(l){return this.fromWireType(H[l>>2])}var ln={name:"emscripten::val",fromWireType:l=>{var f=Ft(l);return Nt(l),f},toWireType:(l,f)=>Ut(f),H:8,readValueFromPointer:$t,G:null},Ps=(l,f)=>{switch(f){case 4:return function(p){return this.fromWireType(Vr[p>>2])};case 8:return function(p){return this.fromWireType(Zr[p>>3])};default:throw new TypeError(`invalid float width (${f}): ${l}`)}},un=l=>{for(;l.length;){var f=l.pop();l.pop()(f)}};function fn(l){for(var f=1;f<l.length;++f)if(l[f]!==null&&l[f].G===void 0)return!0;return!1}var Ss=(l,f)=>{if(r[l].F===void 0){var p=r[l];r[l]=function(...d){if(!r[l].F.hasOwnProperty(d.length))throw new V(`Function '${f}' called with an invalid number of arguments (${d.length}) - expects one of (${r[l].F})!`);return r[l].F[d.length].apply(this,d)},r[l].F=[],r[l].F[p.J]=p}},As=(l,f,p)=>{if(r.hasOwnProperty(l)){if(p===void 0||r[l].F!==void 0&&r[l].F[p]!==void 0)throw new V(`Cannot register public name '${l}' twice`);if(Ss(l,l),r[l].F.hasOwnProperty(p))throw new V(`Cannot register multiple overloads of a function with the same number of arguments (${p})!`);r[l].F[p]=f}else r[l]=f,r[l].J=p},Rs=(l,f)=>{for(var p=[],d=0;d<l;d++)p.push(H[f+4*d>>2]);return p},cn=r.InternalError=class extends Error{constructor(l){super(l),this.name="InternalError"}},hn=[],dn,xs=(l,f)=>{l=X(l);var p;if((p=hn[f])||(hn[f]=p=dn.get(f)),typeof p!="function")throw new V(`unknown function pointer with signature ${l}: ${f}`);return p};class Bs extends Error{}for(var pn=l=>{l=Gs(l);var f=X(l);return Ce(l),f},Is=(l,f)=>{function p(E){m[E]||be[E]||(st[E]?st[E].forEach(p):(d.push(E),m[E]=!0))}var d=[],m={};throw f.forEach(p),new Bs(`${l}: `+d.map(pn).join([", "]))},Os=(l,f)=>{function p(T){if(T=f(T),T.length!==d.length)throw new cn("Mismatched type converter count");for(var A=0;A<d.length;++A)ee(d[A],T[A])}var d=[];d.forEach(T=>st[T]=l);var m=Array(l.length),E=[],R=0;l.forEach((T,A)=>{be.hasOwnProperty(T)?m[A]=be[T]:(E.push(T),xe.hasOwnProperty(T)||(xe[T]=[]),xe[T].push(()=>{m[A]=be[T],++R,R===E.length&&p(m)}))}),E.length===0&&p(m)},vs=l=>{l=l.trim();let f=l.indexOf("(");return f===-1?l:l.slice(0,f)},gn=typeof TextDecoder<"u"?new TextDecoder:void 0,Ls=(l=0,f=NaN)=>{var p=L,d=l+f;for(f=l;p[f]&&!(f>=d);)++f;if(16<f-l&&p.buffer&&gn)return gn.decode(p.subarray(l,f));for(d="";l<f;){var m=p[l++];if(m&128){var E=p[l++]&63;if((m&224)==192)d+=String.fromCharCode((m&31)<<6|E);else{var R=p[l++]&63;m=(m&240)==224?(m&15)<<12|E<<6|R:(m&7)<<18|E<<12|R<<6|p[l++]&63,65536>m?d+=String.fromCharCode(m):(m-=65536,d+=String.fromCharCode(55296|m>>10,56320|m&1023))}}else d+=String.fromCharCode(m)}return d},mn=typeof TextDecoder<"u"?new TextDecoder("utf-16le"):void 0,Ms=(l,f)=>{for(var p=l>>1,d=p+f/2;!(p>=d)&&ye[p];)++p;if(p<<=1,32<p-l&&mn)return mn.decode(L.subarray(l,p));for(p="",d=0;!(d>=f/2);++d){var m=j[l+2*d>>1];if(m==0)break;p+=String.fromCharCode(m)}return p},Ns=(l,f,p)=>{if(p??=2147483647,2>p)return 0;p-=2;var d=f;p=p<2*l.length?p/2:l.length;for(var m=0;m<p;++m)j[f>>1]=l.charCodeAt(m),f+=2;return j[f>>1]=0,f-d},Fs=l=>2*l.length,Us=(l,f)=>{for(var p=0,d="";!(p>=f/4);){var m=_e[l+4*p>>2];if(m==0)break;++p,65536<=m?(m-=65536,d+=String.fromCharCode(55296|m>>10,56320|m&1023)):d+=String.fromCharCode(m)}return d},$s=(l,f,p)=>{if(p??=2147483647,4>p)return 0;var d=f;p=d+p-4;for(var m=0;m<l.length;++m){var E=l.charCodeAt(m);if(55296<=E&&57343>=E){var R=l.charCodeAt(++m);E=65536+((E&1023)<<10)|R&1023}if(_e[f>>2]=E,f+=4,f+4>p)break}return _e[f>>2]=0,f-d},qs=l=>{for(var f=0,p=0;p<l.length;++p){var d=l.charCodeAt(p);55296<=d&&57343>=d&&++p,f+=4}return f},qt=0,Dt=[],Ds=l=>{var f=Dt.length;return Dt.push(l),f},yn=(l,f)=>{var p=be[l];if(p===void 0)throw l=`${f} has unknown type ${pn(l)}`,new V(l);return p},Ws=(l,f)=>{for(var p=Array(l),d=0;d<l;++d)p[d]=yn(H[f+4*d>>2],`parameter ${d}`);return p},Hs=(l,f,p)=>{var d=[];return l=l.toWireType(d,p),d.length&&(H[f>>2]=Ut(d)),l},$e={},_n=l=>{W=l,ot||0<qt||(r.onExit?.(l),B=!0),h(l,new Lt(l))},zs=l=>{if(!B)try{if(l(),!(ot||0<qt))try{W=l=W,_n(l)}catch(f){f instanceof Lt||f=="unwind"||h(1,f)}}catch(f){f instanceof Lt||f=="unwind"||h(1,f)}},wn=Array(256),at=0;256>at;++at)wn[at]=String.fromCharCode(at);sn=wn,se.push(0,1,void 0,1,null,1,!0,1,!1,1),r.count_emval_handles=()=>se.length/2-5-Mt.length,r.noExitRuntime&&(ot=r.noExitRuntime),r.printErr&&(S=r.printErr),r.wasmBinary&&(N=r.wasmBinary);var js={u:(l,f,p)=>{var d=new Cs(l);throw H[d.I+16>>2]=0,H[d.I+4>>2]=f,H[d.I+8>>2]=p,on=l,Es++,on},v:()=>en(""),l:(l,f,p)=>{f=X(f),ee(l,{name:f,fromWireType:d=>d,toWireType:function(d,m){if(typeof m!="bigint"&&typeof m!="number")throw m===null?m="null":(d=typeof m,m=d==="object"||d==="array"||d==="function"?m.toString():""+m),new TypeError(`Cannot convert "${m}" to ${this.name}`);return typeof m=="number"&&(m=BigInt(m)),m},H:8,readValueFromPointer:an(f,p,f.indexOf("u")==-1),G:null})},o:(l,f,p,d)=>{f=X(f),ee(l,{name:f,fromWireType:function(m){return!!m},toWireType:function(m,E){return E?p:d},H:8,readValueFromPointer:function(m){return this.fromWireType(L[m])},G:null})},m:l=>ee(l,ln),k:(l,f,p)=>{f=X(f),ee(l,{name:f,fromWireType:d=>d,toWireType:(d,m)=>m,H:8,readValueFromPointer:Ps(f,p),G:null})},c:(l,f,p,d,m,E,R)=>{var T=Rs(f,p);l=X(l),l=vs(l),m=xs(d,m),As(l,function(){Is(`Cannot call ${l} due to unbound types`,T)},f-1),Os(T,A=>{var P=[A[0],null].concat(A.slice(1));A=l;var F=l,ne=m,M=P.length;if(2>M)throw new V("argTypes array size mismatch! Must at least get return value and 'this' types!");var ue=P[1]!==null&&!1,qe=fn(P),Cn=P[0].name!=="void";ne=[F,Ts,ne,E,un,P[0],P[1]];for(var te=0;te<M-2;++te)ne.push(P[te+2]);if(!qe)for(te=ue?1:2;te<P.length;++te)P[te].G!==null&&ne.push(P[te].G);qe=fn(P),te=P.length-2;var J=[],De=["fn"];for(ue&&De.push("thisWired"),M=0;M<te;++M)J.push(`arg${M}`),De.push(`arg${M}Wired`);J=J.join(","),De=De.join(","),J=`return function (${J}) {
|
|
19
|
-
`,
|
|
20
|
-
`);var
|
|
21
|
-
`),
|
|
22
|
-
`,
|
|
23
|
-
`,
|
|
24
|
-
`;else for(
|
|
25
|
-
`,
|
|
15
|
+
`,typeof r=="function"&&r(null,a),a}});var Fs=P(Us=>{var yu="\x1B[47m",_u="\x1B[40m",Ur="\x1B[37m",Fr="\x1B[30m",Me="\x1B[0m",wu=yu+Fr,bu=_u+Ur,Cu=function(t,e,r){return{"00":Me+" "+t,"01":Me+e+"\u2584"+t,"02":Me+r+"\u2584"+t,10:Me+e+"\u2580"+t,11:" ",12:"\u2584",20:Me+r+"\u2580"+t,21:"\u2580",22:"\u2588"}},Ns=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"},$s=function(t,e,r,n){return Ns(t,e,r,n)+Ns(t,e,r,n+1)};Us.render=function(t,e,r){let n=t.modules.size,i=t.modules.data,s=!!(e&&e.inverse),o=e&&e.inverse?bu:wu,c=Cu(o,s?Fr:Ur,s?Ur:Fr),h=Me+`
|
|
16
|
+
`+o,y=o;for(let _=-1;_<n+1;_+=2){for(let b=-1;b<n;b++)y+=c[$s(i,n,b,_)];y+=c[$s(i,n,n,_)]+h}return y+=Me,typeof r=="function"&&r(null,y),y}});var Ds=P(qs=>{var Eu=Ms(),Tu=Fs();qs.render=function(t,e,r){return e&&e.small?Tu.render(t,e,r):Eu.render(t,e,r)}});var Dr=P(Hs=>{var ku=ot();function Ws(t,e){let r=t.a/255,n=e+'="'+t.hex+'"';return r<1?n+" "+e+'-opacity="'+r.toFixed(2).slice(1)+'"':n}function qr(t,e,r){let n=t+e;return typeof r<"u"&&(n+=" "+r),n}function Pu(t,e,r){let n="",i=0,s=!1,o=0;for(let a=0;a<t.length;a++){let u=Math.floor(a%e),c=Math.floor(a/e);!u&&!s&&(s=!0),t[a]?(o++,a>0&&u>0&&t[a-1]||(n+=s?qr("M",u+r,.5+c+r):qr("m",i,0),i=0,s=!1),u+1<e&&t[a+1]||(n+=qr("h",o),o=0)):i++}return n}Hs.render=function(e,r,n){let i=ku.getOptions(r),s=e.modules.size,o=e.modules.data,a=s+i.margin*2,u=i.color.light.a?"<path "+Ws(i.color.light,"fill")+' d="M0 0h'+a+"v"+a+'H0z"/>':"",c="<path "+Ws(i.color.dark,"stroke")+' d="'+Pu(o,s,i.margin)+'"/>',h='viewBox="0 0 '+a+" "+a+'"',_='<svg xmlns="http://www.w3.org/2000/svg" '+(i.width?'width="'+i.width+'" height="'+i.width+'" ':"")+h+' shape-rendering="crispEdges">'+u+c+`</svg>
|
|
17
|
+
`;return typeof n=="function"&&n(null,_),_}});var zs=P(xt=>{var Su=Dr();xt.render=Su.render;xt.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">'+xt.render(r,n);s.writeFile(e,a,i)}});var js=P(Bt=>{var Wr=ot();function xu(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 Bu(){try{return document.createElement("canvas")}catch{throw new Error("You need to specify a canvas element")}}Bt.render=function(e,r,n){let i=n,s=r;typeof i>"u"&&(!r||!r.getContext)&&(i=r,r=void 0),r||(s=Bu()),i=Wr.getOptions(i);let o=Wr.getImageWidth(e.modules.size,i),a=s.getContext("2d"),u=a.createImageData(o,o);return Wr.qrToImageData(u.data,e,i),xu(a,s,o),a.putImageData(u,0,0),s};Bt.renderToDataURL=function(e,r,n){let i=n;typeof i>"u"&&(!r||!r.getContext)&&(i=r,r=void 0),i||(i={});let s=Bt.render(e,r,i),o=i.type||"image/png",a=i.rendererOpts||{};return s.toDataURL(o,a.quality)}});var Gs=P(at=>{var Ru=rr(),Hr=Cr(),Qs=js(),Au=Dr();function zr(t,e,r,n,i){let s=[].slice.call(arguments,1),o=s.length,a=typeof s[o-1]=="function";if(!a&&!Ru())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(u,c){try{let h=Hr.create(r,n);u(t(h,e,n))}catch(h){c(h)}})}try{let u=Hr.create(r,n);i(null,t(u,e,n))}catch(u){i(u)}}at.create=Hr.create;at.toCanvas=zr.bind(null,Qs.render);at.toDataURL=zr.bind(null,Qs.renderToDataURL);at.toString=zr.bind(null,function(t,e,r){return Au.render(t,r)})});var Ks=P(Te=>{var Ys=rr(),jr=Cr(),Iu=vs(),Vs=Os(),vu=Ds(),Js=zs();function lt(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(Ys())e=r||{},r=null;else throw new Error("Callback required as last argument");return{opts:e,cb:r}}function Ou(t){return t.slice((t.lastIndexOf(".")-1>>>0)+2).toLowerCase()}function Rt(t){switch(t){case"svg":return Js;case"txt":case"utf8":return Vs;default:return Iu}}function Lu(t){switch(t){case"svg":return Js;case"terminal":return vu;default:return Vs}}function ut(t,e,r){if(!r.cb)return new Promise(function(n,i){try{let s=jr.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=jr.create(e,r.opts);return t(n,r.opts,r.cb)}catch(n){r.cb(n)}}Te.create=jr.create;Te.toCanvas=Gs().toCanvas;Te.toString=function(e,r,n){let i=lt(e,r,n),s=i.opts?i.opts.type:void 0,o=Lu(s);return ut(o.render,e,i)};Te.toDataURL=function(e,r,n){let i=lt(e,r,n),s=Rt(i.opts.type);return ut(s.renderToDataURL,e,i)};Te.toBuffer=function(e,r,n){let i=lt(e,r,n),s=Rt(i.opts.type);return ut(s.renderToBuffer,e,i)};Te.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&&!Ys())throw new Error("Too few arguments provided");let s=lt(r,n,i),o=s.opts.type||Ou(e),u=Rt(o).renderToFile.bind(null,e);return ut(u,r,s)};Te.toFileStream=function(e,r,n){if(arguments.length<2)throw new Error("Too few arguments provided");let i=lt(r,n,e.emit.bind(e,"error")),o=Rt("png").renderToFileStream.bind(null,e);ut(o,r,i)}});var Qr=P((Ch,Zs)=>{Zs.exports=Ks()});var wo=P((Cd,_o)=>{"use strict";var rn=Object.defineProperty,rf=Object.getOwnPropertyDescriptor,nf=Object.getOwnPropertyNames,sf=Object.prototype.hasOwnProperty,of=(t,e)=>{for(var r in e)rn(t,r,{get:e[r],enumerable:!0})},af=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of nf(e))!sf.call(t,i)&&i!==r&&rn(t,i,{get:()=>e[i],enumerable:!(n=rf(e,i))||n.enumerable});return t},lf=t=>af(rn({},"__esModule",{value:!0}),t),ho={};of(ho,{decode:()=>Pf,encode:()=>kf,getDuration:()=>Sf,getWavFileInfo:()=>Bf,isSilk:()=>Rf,isWav:()=>xf});_o.exports=lf(ho);var en=W("url").pathToFileURL(__filename).href,uf=async function(t={}){var e,r=t,n,i,s=new Promise((l,f)=>{n=l,i=f}),o=typeof window=="object",a=typeof WorkerGlobalScope<"u",u=typeof process=="object"&&typeof process.versions=="object"&&typeof process.versions.node=="string"&&process.type!="renderer";if(u){let{createRequire:l}=await import("module");var c=l(en)}var h=(l,f)=>{throw f},y=en,_="",b,g;if(u){var w=c("fs"),C=c("path");y.startsWith("file:")&&(_=C.dirname(c("url").fileURLToPath(y))+"/"),g=l=>(l=Se(l)?new URL(l):l,w.readFileSync(l)),b=async l=>(l=Se(l)?new URL(l):l,w.readFileSync(l,void 0)),process.argv.slice(2),h=(l,f)=>{throw process.exitCode=l,f}}else if(o||a){try{_=new URL(".",y).href}catch{}a&&(g=l=>{var f=new XMLHttpRequest;return f.open("GET",l,!1),f.responseType="arraybuffer",f.send(null),new Uint8Array(f.response)}),b=async l=>{if(Se(l))return new Promise((p,d)=>{var m=new XMLHttpRequest;m.open("GET",l,!0),m.responseType="arraybuffer",m.onload=()=>{m.status==200||m.status==0&&m.response?p(m.response):d(m.status)},m.onerror=d,m.send(null)});var f=await fetch(l,{credentials:"same-origin"});if(f.ok)return f.arrayBuffer();throw Error(f.status+" : "+f.url)}}console.log.bind(console);var E=console.error.bind(console),x,I,O=!1,N,v,L,G,z,U,F,X,Ne,J,$e,Se=l=>l.startsWith("file://");function hn(){var l=I.buffer;v=new Int8Array(l),G=new Int16Array(l),L=new Uint8Array(l),z=new Uint16Array(l),U=new Int32Array(l),F=new Uint32Array(l),X=new Float32Array(l),$e=new Float64Array(l),Ne=new BigInt64Array(l),J=new BigUint64Array(l)}var xe=0,Ge=null;function dn(l){throw r.onAbort?.(l),l="Aborted("+l+")",E(l),O=!0,l=new WebAssembly.RuntimeError(l+". Build with -sASSERTIONS for more info."),i(l),l}var Ht;async function Io(l){if(!x)try{var f=await b(l);return new Uint8Array(f)}catch{}if(l==Ht&&x)l=new Uint8Array(x);else if(g)l=g(l);else throw"both async and sync fetching of the wasm failed";return l}async function vo(l,f){try{var p=await Io(l);return await WebAssembly.instantiate(p,f)}catch(d){E(`failed to asynchronously prepare wasm: ${d}`),dn(d)}}async function Oo(l){var f=Ht;if(!x&&typeof WebAssembly.instantiateStreaming=="function"&&!Se(f)&&!u)try{var p=fetch(f,{credentials:"same-origin"});return await WebAssembly.instantiateStreaming(p,l)}catch(d){E(`wasm streaming compile failed: ${d}`),E("falling back to ArrayBuffer instantiation")}return vo(f,l)}class zt{name="ExitStatus";constructor(f){this.message=`Program terminated with exit(${f})`,this.status=f}}var pn=l=>{for(;0<l.length;)l.shift()(r)},gn=[],mn=[],Lo=()=>{var l=r.preRun.shift();mn.push(l)},dt=!0;class Mo{constructor(f){this.I=f-24}}var yn=0,No=0,_n,ne=l=>{for(var f="";L[l];)f+=_n[L[l++]];return f},Ue={},Be={},pt={},ee=r.BindingError=class extends Error{constructor(l){super(l),this.name="BindingError"}},$o=l=>{throw new ee(l)};function Uo(l,f,p={}){var d=f.name;if(!l)throw new ee(`type "${d}" must have a positive integer typeid pointer`);if(Be.hasOwnProperty(l)){if(p.K)return;throw new ee(`Cannot register type '${d}' twice`)}Be[l]=f,delete pt[l],Ue.hasOwnProperty(l)&&(f=Ue[l],delete Ue[l],f.forEach(m=>m()))}function ie(l,f,p={}){return Uo(l,f,p)}var wn=(l,f,p)=>{switch(f){case 1:return p?d=>v[d]:d=>L[d];case 2:return p?d=>G[d>>1]:d=>z[d>>1];case 4:return p?d=>U[d>>2]:d=>F[d>>2];case 8:return p?d=>Ne[d>>3]:d=>J[d>>3];default:throw new TypeError(`invalid integer width (${f}): ${l}`)}},jt=[],ce=[],Qt=l=>{9<l&&--ce[l+1]===0&&(ce[l]=void 0,jt.push(l))},Gt=l=>{if(!l)throw new ee(`Cannot use deleted val. handle = ${l}`);return ce[l]},Yt=l=>{switch(l){case void 0:return 2;case null:return 4;case!0:return 6;case!1:return 8;default:let f=jt.pop()||ce.length;return ce[f]=l,ce[f+1]=1,f}};function Vt(l){return this.fromWireType(F[l>>2])}var bn={name:"emscripten::val",fromWireType:l=>{var f=Gt(l);return Qt(l),f},toWireType:(l,f)=>Yt(f),H:8,readValueFromPointer:Vt,G:null},Fo=(l,f)=>{switch(f){case 4:return function(p){return this.fromWireType(X[p>>2])};case 8:return function(p){return this.fromWireType($e[p>>3])};default:throw new TypeError(`invalid float width (${f}): ${l}`)}},Cn=l=>{for(;l.length;){var f=l.pop();l.pop()(f)}};function En(l){for(var f=1;f<l.length;++f)if(l[f]!==null&&l[f].G===void 0)return!0;return!1}var qo=(l,f)=>{if(r[l].F===void 0){var p=r[l];r[l]=function(...d){if(!r[l].F.hasOwnProperty(d.length))throw new ee(`Function '${f}' called with an invalid number of arguments (${d.length}) - expects one of (${r[l].F})!`);return r[l].F[d.length].apply(this,d)},r[l].F=[],r[l].F[p.J]=p}},Do=(l,f,p)=>{if(r.hasOwnProperty(l)){if(p===void 0||r[l].F!==void 0&&r[l].F[p]!==void 0)throw new ee(`Cannot register public name '${l}' twice`);if(qo(l,l),r[l].F.hasOwnProperty(p))throw new ee(`Cannot register multiple overloads of a function with the same number of arguments (${p})!`);r[l].F[p]=f}else r[l]=f,r[l].J=p},Wo=(l,f)=>{for(var p=[],d=0;d<l;d++)p.push(F[f+4*d>>2]);return p},Tn=r.InternalError=class extends Error{constructor(l){super(l),this.name="InternalError"}},kn=[],Pn,Ho=(l,f)=>{l=ne(l);var p;if((p=kn[f])||(kn[f]=p=Pn.get(f)),typeof p!="function")throw new ee(`unknown function pointer with signature ${l}: ${f}`);return p};class zo extends Error{}for(var Sn=l=>{l=oa(l);var f=ne(l);return Re(l),f},jo=(l,f)=>{function p(T){m[T]||Be[T]||(pt[T]?pt[T].forEach(p):(d.push(T),m[T]=!0))}var d=[],m={};throw f.forEach(p),new zo(`${l}: `+d.map(Sn).join([", "]))},Qo=(l,f)=>{function p(k){if(k=f(k),k.length!==d.length)throw new Tn("Mismatched type converter count");for(var B=0;B<d.length;++B)ie(d[B],k[B])}var d=[];d.forEach(k=>pt[k]=l);var m=Array(l.length),T=[],R=0;l.forEach((k,B)=>{Be.hasOwnProperty(k)?m[B]=Be[k]:(T.push(k),Ue.hasOwnProperty(k)||(Ue[k]=[]),Ue[k].push(()=>{m[B]=Be[k],++R,R===T.length&&p(m)}))}),T.length===0&&p(m)},Go=l=>{l=l.trim();let f=l.indexOf("(");return f===-1?l:l.slice(0,f)},xn=typeof TextDecoder<"u"?new TextDecoder:void 0,Yo=(l=0,f=NaN)=>{var p=L,d=l+f;for(f=l;p[f]&&!(f>=d);)++f;if(16<f-l&&p.buffer&&xn)return xn.decode(p.subarray(l,f));for(d="";l<f;){var m=p[l++];if(m&128){var T=p[l++]&63;if((m&224)==192)d+=String.fromCharCode((m&31)<<6|T);else{var R=p[l++]&63;m=(m&240)==224?(m&15)<<12|T<<6|R:(m&7)<<18|T<<12|R<<6|p[l++]&63,65536>m?d+=String.fromCharCode(m):(m-=65536,d+=String.fromCharCode(55296|m>>10,56320|m&1023))}}else d+=String.fromCharCode(m)}return d},Bn=typeof TextDecoder<"u"?new TextDecoder("utf-16le"):void 0,Vo=(l,f)=>{for(var p=l>>1,d=p+f/2;!(p>=d)&&z[p];)++p;if(p<<=1,32<p-l&&Bn)return Bn.decode(L.subarray(l,p));for(p="",d=0;!(d>=f/2);++d){var m=G[l+2*d>>1];if(m==0)break;p+=String.fromCharCode(m)}return p},Jo=(l,f,p)=>{if(p??=2147483647,2>p)return 0;p-=2;var d=f;p=p<2*l.length?p/2:l.length;for(var m=0;m<p;++m)G[f>>1]=l.charCodeAt(m),f+=2;return G[f>>1]=0,f-d},Ko=l=>2*l.length,Zo=(l,f)=>{for(var p=0,d="";!(p>=f/4);){var m=U[l+4*p>>2];if(m==0)break;++p,65536<=m?(m-=65536,d+=String.fromCharCode(55296|m>>10,56320|m&1023)):d+=String.fromCharCode(m)}return d},Xo=(l,f,p)=>{if(p??=2147483647,4>p)return 0;var d=f;p=d+p-4;for(var m=0;m<l.length;++m){var T=l.charCodeAt(m);if(55296<=T&&57343>=T){var R=l.charCodeAt(++m);T=65536+((T&1023)<<10)|R&1023}if(U[f>>2]=T,f+=4,f+4>p)break}return U[f>>2]=0,f-d},ea=l=>{for(var f=0,p=0;p<l.length;++p){var d=l.charCodeAt(p);55296<=d&&57343>=d&&++p,f+=4}return f},Jt=0,Kt=[],ta=l=>{var f=Kt.length;return Kt.push(l),f},Rn=(l,f)=>{var p=Be[l];if(p===void 0)throw l=`${f} has unknown type ${Sn(l)}`,new ee(l);return p},ra=(l,f)=>{for(var p=Array(l),d=0;d<l;++d)p[d]=Rn(F[f+4*d>>2],`parameter ${d}`);return p},na=(l,f,p)=>{var d=[];return l=l.toWireType(d,p),d.length&&(F[f>>2]=Yt(d)),l},Ye={},An=l=>{N=l,dt||0<Jt||(r.onExit?.(l),O=!0),h(l,new zt(l))},ia=l=>{if(!O)try{if(l(),!(dt||0<Jt))try{N=l=N,An(l)}catch(f){f instanceof zt||f=="unwind"||h(1,f)}}catch(f){f instanceof zt||f=="unwind"||h(1,f)}},In=Array(256),gt=0;256>gt;++gt)In[gt]=String.fromCharCode(gt);_n=In,ce.push(0,1,void 0,1,null,1,!0,1,!1,1),r.count_emval_handles=()=>ce.length/2-5-jt.length,r.noExitRuntime&&(dt=r.noExitRuntime),r.printErr&&(E=r.printErr),r.wasmBinary&&(x=r.wasmBinary);var sa={u:(l,f,p)=>{var d=new Mo(l);throw F[d.I+16>>2]=0,F[d.I+4>>2]=f,F[d.I+8>>2]=p,yn=l,No++,yn},v:()=>dn(""),l:(l,f,p)=>{f=ne(f),ie(l,{name:f,fromWireType:d=>d,toWireType:function(d,m){if(typeof m!="bigint"&&typeof m!="number")throw m===null?m="null":(d=typeof m,m=d==="object"||d==="array"||d==="function"?m.toString():""+m),new TypeError(`Cannot convert "${m}" to ${this.name}`);return typeof m=="number"&&(m=BigInt(m)),m},H:8,readValueFromPointer:wn(f,p,f.indexOf("u")==-1),G:null})},o:(l,f,p,d)=>{f=ne(f),ie(l,{name:f,fromWireType:function(m){return!!m},toWireType:function(m,T){return T?p:d},H:8,readValueFromPointer:function(m){return this.fromWireType(L[m])},G:null})},m:l=>ie(l,bn),k:(l,f,p)=>{f=ne(f),ie(l,{name:f,fromWireType:d=>d,toWireType:(d,m)=>m,H:8,readValueFromPointer:Fo(f,p),G:null})},c:(l,f,p,d,m,T,R)=>{var k=Wo(f,p);l=ne(l),l=Go(l),m=Ho(d,m),Do(l,function(){jo(`Cannot call ${l} due to unbound types`,k)},f-1),Qo(k,B=>{var S=[B[0],null].concat(B.slice(1));B=l;var D=l,ae=m,q=S.length;if(2>q)throw new ee("argTypes array size mismatch! Must at least get return value and 'this' types!");var me=S[1]!==null&&!1,Ve=En(S),On=S[0].name!=="void";ae=[D,$o,ae,T,Cn,S[0],S[1]];for(var se=0;se<q-2;++se)ae.push(S[se+2]);if(!Ve)for(se=me?1:2;se<S.length;++se)S[se].G!==null&&ae.push(S[se].G);Ve=En(S),se=S.length-2;var K=[],Je=["fn"];for(me&&Je.push("thisWired"),q=0;q<se;++q)K.push(`arg${q}`),Je.push(`arg${q}Wired`);K=K.join(","),Je=Je.join(","),K=`return function (${K}) {
|
|
18
|
+
`,Ve&&(K+=`var destructors = [];
|
|
19
|
+
`);var Ln=Ve?"destructors":"null",Xt="humanName throwBindingError invoker fn runDestructors retType classParam".split(" ");for(me&&(K+=`var thisWired = classParam['toWireType'](${Ln}, this);
|
|
20
|
+
`),q=0;q<se;++q)K+=`var arg${q}Wired = argType${q}['toWireType'](${Ln}, arg${q});
|
|
21
|
+
`,Xt.push(`argType${q}`);if(K+=(On||R?"var rv = ":"")+`invoker(${Je});
|
|
22
|
+
`,Ve)K+=`runDestructors(destructors);
|
|
23
|
+
`;else for(q=me?1:2;q<S.length;++q)me=q===1?"thisWired":"arg"+(q-2)+"Wired",S[q].G!==null&&(K+=`${me}_dtor(${me});
|
|
24
|
+
`,Xt.push(`${me}_dtor`));On&&(K+=`var ret = retType['fromWireType'](rv);
|
|
26
25
|
return ret;
|
|
27
|
-
`);let[
|
|
28
|
-
`];if(
|
|
29
|
-
`,
|
|
30
|
-
`,
|
|
31
|
-
`,d.L||(
|
|
32
|
-
`),l=new Function(...
|
|
33
|
-
`)(...A),p=`methodCaller<(${f.map(F=>F.name).join(", ")}) => ${d.name}>`,Ds(Object.defineProperty(l,"name",{value:p}))},q:l=>{9<l&&(se[l+1]+=1)},g:l=>{var f=Ft(l);un(f),Nt(l)},j:(l,f)=>(l=yn(l,"_emval_take_value"),l=l.readValueFromPointer(f),Ut(l)),t:(l,f)=>{if($e[l]&&(clearTimeout($e[l].id),delete $e[l]),!f)return 0;var p=setTimeout(()=>{delete $e[l],zs(()=>Ys(l,performance.now()))},f);return $e[l]={id:p,M:f},0},w:l=>{var f=L.length;if(l>>>=0,2147483648<l)return!1;for(var p=1;4>=p;p*=2){var d=f*(1+.2/p);d=Math.min(d,l+100663296);e:{d=(Math.min(2147483648,65536*Math.ceil(Math.max(l,d)/65536))-U.buffer.byteLength+65535)/65536|0;try{U.grow(d),Xr();var m=1;break e}catch{}m=void 0}if(m)return!0}return!1},r:_n},ae=await(async function(){function l(d){return ae=d.exports,U=ae.x,Xr(),dn=ae.D,we--,r.monitorRunDependencies?.(we),we==0&&Ue&&(d=Ue,Ue=null,d()),ae}we++,r.monitorRunDependencies?.(we);var f={a:js};if(r.instantiateWasm)return new Promise(d=>{r.instantiateWasm(f,(m,E)=>{d(l(m,E))})});vt??=r.locateFile?r.locateFile?r.locateFile("silk.wasm",g):g+"silk.wasm":new URL("silk.wasm",qr).href;try{var p=await ws(f);return l(p.instance)}catch(d){return i(d),Promise.reject(d)}})(),Gs=ae.z,bn=ae.A,Ce=ae.B,Ys=ae.C;function Wt(){function l(){if(r.calledRun=!0,!B){if(ae.y(),n(r),r.onRuntimeInitialized?.(),r.postRun)for(typeof r.postRun=="function"&&(r.postRun=[r.postRun]);r.postRun.length;){var f=r.postRun.shift();rn.push(f)}tn(rn)}}if(0<we)Ue=Wt;else{if(r.preRun)for(typeof r.preRun=="function"&&(r.preRun=[r.preRun]);r.preRun.length;)bs();tn(nn),0<we?Ue=Wt:r.setStatus?(r.setStatus("Running..."),setTimeout(()=>{setTimeout(()=>r.setStatus(""),1),l()},1)):l()}}if(r.preInit)for(typeof r.preInit=="function"&&(r.preInit=[r.preInit]);0<r.preInit.length;)r.preInit.shift()();return Wt(),e=o,e},es=qu;function ts(t){try{let e=Hr(t),r=zr(e.get("fmt")),n=e.get("data");return rs(r),ns(n,r),!0}catch{return!1}}var Du=["int","float"],Wu=[0,0,0,1];function Hu(t){let e=Hr(t),r=zr(e.get("fmt")),n=e.get("data"),i=rs(r),o=Wu[i],s=Du[o]+r.bitsPerSample;return ns(n,r),{channelData:ju(n,r,i),sampleRate:r.sampleRate,numberOfChannels:r.numberOfChannels,audioEncoding:o,bitsPerSample:r.bitsPerSample,wavFileTypeName:s}}function Hr(t){let e;t instanceof ArrayBuffer?e=new DataView(t):e=new DataView(t.buffer,t.byteOffset,t.byteLength);let r=e.byteLength;if(r<20)throw new Error("WAV file is too short.");if(Dr(e,0,4)!="RIFF")throw new Error("Not a valid WAV file (no RIFF header).");let n=e.getUint32(4,!0);if(8+n!=r)throw new Error(`Main chunk length of WAV file (${8+n}) does not match file size (${r}).`);if(Dr(e,8,4)!="WAVE")throw new Error("RIFF file is not a WAV file.");let i=new Map,o=12;for(;o<r;){if(o+8>r)throw new Error(`Incomplete chunk prefix in WAV file at offset ${o}.`);let s=Dr(e,o,4).trim(),a=e.getUint32(o+4,!0);if(o+8+a>r)throw new Error(`Incomplete chunk data in WAV file at offset ${o}.`);let u=new DataView(e.buffer,e.byteOffset+o+8,a);i.set(s,u);let c=a%2;o+=8+a+c}return i}function Dr(t,e,r){let n=new Uint8Array(t.buffer,t.byteOffset+e,r);return String.fromCharCode.apply(null,n)}function zu(t,e){let r=t.getInt8(e+2)*65536,n=t.getUint16(e,!0);return r+n}function zr(t){if(!t)throw new Error("No format chunk found in WAV file.");if(t.byteLength<16)throw new Error("Format chunk of WAV file is too short.");let e={};return e.formatCode=t.getUint16(0,!0),e.numberOfChannels=t.getUint16(2,!0),e.sampleRate=t.getUint32(4,!0),e.bytesPerSec=t.getUint32(8,!0),e.bytesPerFrame=t.getUint16(12,!0),e.bitsPerSample=t.getUint16(14,!0),e}function rs(t){if(t.numberOfChannels<1||t.numberOfChannels>999)throw new Error("Invalid number of channels in WAV file.");let e=Math.ceil(t.bitsPerSample/8),r=t.numberOfChannels*e;if(t.formatCode==1&&t.bitsPerSample>=1&&t.bitsPerSample<=8&&t.bytesPerFrame==r)return 0;if(t.formatCode==1&&t.bitsPerSample>=9&&t.bitsPerSample<=16&&t.bytesPerFrame==r)return 1;if(t.formatCode==1&&t.bitsPerSample>=17&&t.bitsPerSample<=24&&t.bytesPerFrame==r)return 2;if(t.formatCode==3&&t.bitsPerSample==32&&t.bytesPerFrame==r)return 3;throw new Error(`Unsupported WAV file type, formatCode=${t.formatCode}, bitsPerSample=${t.bitsPerSample}, bytesPerFrame=${t.bytesPerFrame}, numberOfChannels=${t.numberOfChannels}.`)}function ju(t,e,r){switch(r){case 0:return Yu(t,e);case 1:return Gu(t,e);case 2:return Ju(t,e);case 3:return Vu(t,e);default:throw new Error("No decoder.")}}function Gu(t,e){let r=kt(t.byteLength,e),n=e.numberOfChannels,i=r[0].length,o=0;for(let s=0;s<i;s++)for(let a=0;a<n;a++){let u=t.getInt16(o,!0)/32768;r[a][s]=u,o+=2}return r}function Yu(t,e){let r=kt(t.byteLength,e),n=e.numberOfChannels,i=r[0].length,o=0;for(let s=0;s<i;s++)for(let a=0;a<n;a++){let u=(t.getUint8(o)-128)/128;r[a][s]=u,o+=1}return r}function Ju(t,e){let r=kt(t.byteLength,e),n=e.numberOfChannels,i=r[0].length,o=0;for(let s=0;s<i;s++)for(let a=0;a<n;a++){let u=zu(t,o)/8388608;r[a][s]=u,o+=3}return r}function Vu(t,e){let r=kt(t.byteLength,e),n=e.numberOfChannels,i=r[0].length,o=0;for(let s=0;s<i;s++)for(let a=0;a<n;a++){let u=t.getFloat32(o,!0);r[a][s]=u,o+=4}return r}function kt(t,e){let r=Math.floor(t/e.bytesPerFrame),n=new Array(e.numberOfChannels);for(let i=0;i<e.numberOfChannels;i++)n[i]=new Float32Array(r);return n}function ns(t,e){if(!t)throw new Error("No data chunk found in WAV file.");if(t.byteLength%e.bytesPerFrame!=0)throw new Error("WAV file data chunk length is not a multiple of frame size.")}function Ku(t){let e=Hr(t),r=Qu(e),n=zr(e.get("fmt"));return{chunkInfo:r,fmt:n}}function Qu(t){let e=[];for(let r of t){let n={};n.chunkId=r[0],n.dataOffset=r[1].byteOffset,n.dataLength=r[1].byteLength,e.push(n)}return e.sort((r,n)=>r.dataOffset-n.dataOffset),e}function Zu(t){let{length:e}=t;if(e===1)return t[0];let r=new Float32Array(t[0].length);for(let n=0;n<r.length;n++){let i=0;for(let o=0;o<e;o++)i+=t[o][n];r[n]=i/e}return r}function Xu(t){let e=new Int16Array(t.length);for(let r=0;r<t.length;r++){let n=~~(t[r]*32768);e[r]=n>32767?32767:n}return e.buffer}function ef(t,e=0,r=t.byteLength){return new TextDecoder().decode(t.slice(e,r))}function Pt(t){return ArrayBuffer.isView(t)?t.buffer.slice(t.byteOffset,t.byteOffset+t.byteLength):t}async function tf(t,e){let r=await es(),n=Pt(t);if(!n?.byteLength)throw new Error("input data length is 0");if(ts(t)){let{channelData:s,sampleRate:a}=Hu(t);e||=a,n=Xu(Zu(s))}let i=new Uint8Array,o=r.silk_encode(n,e,s=>{i=s.slice()});if(o===0)throw new Error("silk encoding failure");return{data:i,duration:o}}async function rf(t,e){let r=await es(),n=Pt(t);if(!n?.byteLength)throw new Error("input data length is 0");let i=new Uint8Array,o=r.silk_decode(n,e,s=>{s.length>0&&(i=s.slice())});if(o===0)throw new Error("silk decoding failure");return{data:i,duration:o}}function nf(t,e=20){let r=Pt(t),n=new DataView(r),i=n.byteLength,o=n.getUint8(0)===2?10:9,s=0;for(;o<i;){let a=n.getUint16(o,!0);s+=1,o+=a+2}return s*e}function of(t){return ts(t)}function sf(t){return Ku(t)}function af(t){let e=Pt(t);return e.byteLength<7?!1:ef(e,0,7).includes("#!SILK")}});import{writeFileSync as Sf,readFileSync as Af,unlinkSync as Rf,existsSync as xf}from"node:fs";import{join as Bf}from"node:path";import{homedir as ra}from"node:os";import{resolve as Pn}from"node:path";function Sn(){let t=process.env.WECHAT_DM_POLICY??"open";if(t!=="open"&&t!=="allowlist")throw new Error(`WECHAT_DM_POLICY must be 'open' or 'allowlist', got: ${t}`);let r=(process.env.WECHAT_ALLOW_FROM??"").split(",").map(s=>s.trim()).filter(Boolean);if(t==="allowlist"&&r.length===0)throw new Error("WECHAT_DM_POLICY=allowlist requires WECHAT_ALLOW_FROM to be set");let n=process.env.WECHAT_STATE_DIR??"~/.aladuo/channel-wechat",i=n.startsWith("~")?Pn(ra(),n.slice(2)):Pn(n),o=process.env.WECHAT_LOG_LEVEL??"info";if(!["error","warn","info","debug"].includes(o))throw new Error(`WECHAT_LOG_LEVEL must be one of error|warn|info|debug, got: ${o}`);return{daemonUrl:process.env.ALADUO_DAEMON_URL??"http://127.0.0.1:20233",apiBase:process.env.WECHAT_API_BASE??"https://ilinkai.weixin.qq.com",cdnBase:process.env.WECHAT_CDN_BASE??"https://novac2c.cdn.weixin.qq.com/c2c",dmPolicy:t,allowFrom:r,stateDir:i,logLevel:o}}import{mkdir as Cu,readFile as zo,writeFile as jo,chmod as Eu,unlink as Go}from"node:fs/promises";import{existsSync as Tu}from"node:fs";import{resolve as Lr}from"node:path";import{randomBytes as Rn}from"node:crypto";var na=4e3,K=class extends Error{constructor(r,n){super(`WechatApiError[${r}]: ${n}`);this.errcode=r;this.name="WechatApiError"}};function ia(){let t=Rn(4).readUInt32BE(0);return Buffer.from(String(t),"utf-8").toString("base64")}function We(t,e){let r={"Content-Type":"application/json","Content-Length":String(Buffer.byteLength(e,"utf-8")),AuthorizationType:"ilink_bot_token","X-WECHAT-UIN":ia()};return t&&(r.Authorization=`Bearer ${t}`),r}async function xn(t,e=fetch){let n=`${t.endsWith("/")?t:`${t}/`}ilink/bot/get_bot_qrcode?bot_type=3`,i=await e(n,{method:"GET"});if(!i.ok)throw new Error(`HTTP ${i.status} from getQrCode`);let o=await i.json();return{qrcode:o.qrcode,qrcodeImgUrl:o.qrcode_img_content}}async function Bn(t,e,r=fetch){let i=`${t.endsWith("/")?t:`${t}/`}ilink/bot/get_qrcode_status?qrcode=${encodeURIComponent(e)}`,o;try{o=await r(i,{method:"GET",headers:{"iLink-App-ClientVersion":"1"},signal:AbortSignal.timeout(35e3)})}catch(a){if(a instanceof Error&&a.name==="AbortError")return{status:"wait"};throw a}if(!o.ok)throw new Error(`HTTP ${o.status} from pollQrStatus`);let s=await o.json();return{status:s.status,token:s.bot_token,botId:s.ilink_bot_id,userId:s.ilink_user_id,resolvedBaseUrl:s.baseurl}}async function In(t,e,r,n=fetch){let i=t.endsWith("/")?t:`${t}/`,o=JSON.stringify({get_updates_buf:r,base_info:{channel_version:"claude-code-1.0"}}),s;try{let c=await n(`${i}ilink/bot/getupdates`,{method:"POST",headers:We(e,o),body:o,signal:AbortSignal.timeout(4e4)});if(s=await c.text(),!c.ok)throw new Error(`getUpdates HTTP ${c.status}: ${s}`)}catch(c){if(c instanceof Error&&c.name==="AbortError")return{msgs:[],syncBuf:r};throw c}let a=JSON.parse(s),u=a.ret??a.errcode??0;if(u!==0)throw new K(u,a.errmsg??"unknown");return{msgs:a.msgs??[],syncBuf:a.get_updates_buf??r}}function An(){return`cc-wx-${Date.now()}-${Rn(4).toString("hex")}`}async function Ee(t,e,r,n,i,o=fetch,s){let a=t.endsWith("/")?t:`${t}/`;if(s){let u;if("kind"in s&&s.kind==="file"){let w=s.item;u=[{type:4,file_item:{media:{encrypt_query_param:w.encryptQueryParam,aes_key:w.aesKeyBase64,encrypt_type:1},file_name:w.fileName,md5:"",len:String(w.fileSize)}}]}else if("kind"in s&&s.kind==="voice"){let w=s.item;u=[{type:3,voice_item:{media:{encrypt_query_param:w.encryptQueryParam,aes_key:w.aesKeyBase64,encrypt_type:1},encode_type:w.encodeType??6,sample_rate:w.sampleRate??16e3,bits_per_sample:w.bitsPerSample??16,playtime:w.playtimeMs??0}}]}else{let w=s;u=[{type:2,image_item:{media:{encrypt_query_param:w.encryptQueryParam,aes_key:w.aesKeyBase64,encrypt_type:1},mid_size:w.midSize}}]}let c={from_user_id:"",to_user_id:r,client_id:An(),message_type:2,message_state:2,item_list:u};i&&(c.context_token=i);let h=JSON.stringify({msg:c,base_info:{channel_version:"claude-code-1.0"}}),_=await o(`${a}ilink/bot/sendmessage`,{method:"POST",headers:We(e,h),body:h});if(!_.ok)throw new Error(`sendMessage HTTP ${_.status}`);let g=await _.json(),y=g.ret??g.errcode??0;if(y!==0)throw new K(y,g.errmsg??"unknown");n&&await Ee(t,e,r,n,i,o);return}for(let u of oa(n)){let c={from_user_id:"",to_user_id:r,client_id:An(),message_type:2,message_state:2,item_list:[{type:1,text_item:{text:u}}]};i&&(c.context_token=i);let h=JSON.stringify({msg:c,base_info:{channel_version:"claude-code-1.0"}}),_=await o(`${a}ilink/bot/sendmessage`,{method:"POST",headers:We(e,h),body:h});if(!_.ok)throw new Error(`sendMessage HTTP ${_.status}`);let g=await _.json(),y=g.ret??g.errcode??0;if(y!==0)throw new K(y,g.errmsg??"unknown")}}function oa(t,e=na){if(t.length<=e)return[t];let r=[],n=0;for(;n<t.length;)r.push(t.slice(n,n+e)),n+=e;return r}async function On(t,e,r,n,i=fetch){let o=t.endsWith("/")?t:`${t}/`,s=JSON.stringify({ilink_user_id:r,context_token:n,base_info:{}}),a=await i(`${o}ilink/bot/getconfig`,{method:"POST",headers:We(e,s),body:s});if(!a.ok)throw new Error(`getConfig HTTP ${a.status}`);return await a.json()}async function vn(t,e,r,n,i,o=fetch){let s=t.endsWith("/")?t:`${t}/`,a=JSON.stringify({ilink_user_id:r,typing_ticket:n,status:i,base_info:{}});try{await o(`${s}ilink/bot/sendtyping`,{method:"POST",headers:We(e,a),body:a})}catch{}}var Et=class t{constructor(e,r,n=fetch,i=2e3){this.stateDir=e;this.apiBase=r;this.fetchFn=n;this.pollIntervalMs=i;this.credFile=Lr(e,"credentials.json"),this.syncBufFile=Lr(e,"sync-buf.txt"),this.qrcodePng=Lr(e,"qrcode.png")}credFile;syncBufFile;qrcodePng;cached=null;tokenObtainedAt=0;static PROACTIVE_REFRESH_MS=720*60*1e3;silentRefreshInProgress=!1;async getToken(){if(this.cached)return this.tokenObtainedAt>0&&Date.now()-this.tokenObtainedAt>t.PROACTIVE_REFRESH_MS&&!this.silentRefreshInProgress&&this.silentRefresh(),this.cached.token;let e=await this.loadCredentials();return e?(this.cached=e,this.tokenObtainedAt===0&&(this.tokenObtainedAt=Date.now()),e.token):this.startQrLogin()}async startQrLogin(){let{qrcode:e,qrcodeImgUrl:r}=await xn(this.apiBase,this.fetchFn);await this.ensureStateDir(),await(await Promise.resolve().then(()=>kn(Ho(),1))).default.toFile(this.qrcodePng,r,{type:"png",width:300}),process.stdout.write(`QRCODE_READY:${this.qrcodePng}
|
|
34
|
-
`)
|
|
35
|
-
`)
|
|
36
|
-
|
|
26
|
+
`);let[la,ua]=[Xt,K+`}
|
|
27
|
+
`];if(S=new Function(...la,ua)(...ae),D=Object.defineProperty(S,"name",{value:D}),S=f-1,!r.hasOwnProperty(B))throw new Tn("Replacing nonexistent public symbol");return r[B].F!==void 0&&S!==void 0?r[B].F[S]=D:(r[B]=D,r[B].J=S),[]})},b:(l,f,p,d,m)=>{if(f=ne(f),m===-1&&(m=4294967295),m=k=>k,d===0){var T=32-8*p;m=k=>k<<T>>>T}var R=f.includes("unsigned")?function(k,B){return B>>>0}:function(k,B){return B};ie(l,{name:f,fromWireType:m,toWireType:R,H:8,readValueFromPointer:wn(f,p,d!==0),G:null})},a:(l,f,p)=>{function d(T){return new m(v.buffer,F[T+4>>2],F[T>>2])}var m=[Int8Array,Uint8Array,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array,BigInt64Array,BigUint64Array][f];p=ne(p),ie(l,{name:p,fromWireType:d,H:8,readValueFromPointer:d},{K:!0})},n:(l,f)=>{f=ne(f),ie(l,{name:f,fromWireType:function(p){for(var d=F[p>>2],m=p+4,T,R=m,k=0;k<=d;++k){var B=m+k;(k==d||L[B]==0)&&(R=R?Yo(R,B-R):"",T===void 0?T=R:(T+="\0",T+=R),R=B+1)}return Re(p),T},toWireType:function(p,d){d instanceof ArrayBuffer&&(d=new Uint8Array(d));var m,T=typeof d=="string";if(!(T||ArrayBuffer.isView(d)&&d.BYTES_PER_ELEMENT==1))throw new ee("Cannot pass non-string to std::string");var R;if(T)for(m=R=0;m<d.length;++m){var k=d.charCodeAt(m);127>=k?R++:2047>=k?R+=2:55296<=k&&57343>=k?(R+=4,++m):R+=3}else R=d.length;if(m=R,R=vn(4+m+1),k=R+4,F[R>>2]=m,T){if(T=k,k=m+1,m=L,0<k){k=T+k-1;for(var B=0;B<d.length;++B){var S=d.charCodeAt(B);if(55296<=S&&57343>=S){var D=d.charCodeAt(++B);S=65536+((S&1023)<<10)|D&1023}if(127>=S){if(T>=k)break;m[T++]=S}else{if(2047>=S){if(T+1>=k)break;m[T++]=192|S>>6}else{if(65535>=S){if(T+2>=k)break;m[T++]=224|S>>12}else{if(T+3>=k)break;m[T++]=240|S>>18,m[T++]=128|S>>12&63}m[T++]=128|S>>6&63}m[T++]=128|S&63}}m[T]=0}}else L.set(d,k);return p!==null&&p.push(Re,R),R},H:8,readValueFromPointer:Vt,G(p){Re(p)}})},e:(l,f,p)=>{if(p=ne(p),f===2)var d=Vo,m=Jo,T=Ko,R=k=>z[k>>1];else f===4&&(d=Zo,m=Xo,T=ea,R=k=>F[k>>2]);ie(l,{name:p,fromWireType:k=>{for(var B=F[k>>2],S,D=k+4,ae=0;ae<=B;++ae){var q=k+4+ae*f;(ae==B||R(q)==0)&&(D=d(D,q-D),S===void 0?S=D:(S+="\0",S+=D),D=q+f)}return Re(k),S},toWireType:(k,B)=>{if(typeof B!="string")throw new ee(`Cannot pass non-string to C++ string type ${p}`);var S=T(B),D=vn(4+S+f);return F[D>>2]=S/f,m(B,D+4,S+f),k!==null&&k.push(Re,D),D},H:8,readValueFromPointer:Vt,G(k){Re(k)}})},f:l=>{ie(l,bn)},p:(l,f)=>{f=ne(f),ie(l,{L:!0,name:f,H:0,fromWireType:()=>{},toWireType:()=>{}})},s:()=>{dt=!1,Jt=0},i:(l,f,p,d)=>(l=Kt[l],f=Gt(f),l(null,f,p,d)),d:Qt,h:(l,f,p)=>{f=ra(l,f);var d=f.shift();l--;var m=`return function (obj, func, destructorsRef, args) {
|
|
28
|
+
`,T=0,R=[];p===0&&R.push("obj");for(var k=["retType"],B=[d],S=0;S<l;++S)R.push(`arg${S}`),k.push(`argType${S}`),B.push(f[S]),m+=` var arg${S} = argType${S}.readValueFromPointer(args${T?"+"+T:""});
|
|
29
|
+
`,T+=f[S].H;return m+=` var rv = ${p===1?"new func":"func.call"}(${R.join(", ")});
|
|
30
|
+
`,d.L||(k.push("emval_returnValue"),B.push(na),m+=` return emval_returnValue(retType, destructorsRef, rv);
|
|
31
|
+
`),l=new Function(...k,m+`};
|
|
32
|
+
`)(...B),p=`methodCaller<(${f.map(D=>D.name).join(", ")}) => ${d.name}>`,ta(Object.defineProperty(l,"name",{value:p}))},q:l=>{9<l&&(ce[l+1]+=1)},g:l=>{var f=Gt(l);Cn(f),Qt(l)},j:(l,f)=>(l=Rn(l,"_emval_take_value"),l=l.readValueFromPointer(f),Yt(l)),t:(l,f)=>{if(Ye[l]&&(clearTimeout(Ye[l].id),delete Ye[l]),!f)return 0;var p=setTimeout(()=>{delete Ye[l],ia(()=>aa(l,performance.now()))},f);return Ye[l]={id:p,M:f},0},w:l=>{var f=L.length;if(l>>>=0,2147483648<l)return!1;for(var p=1;4>=p;p*=2){var d=f*(1+.2/p);d=Math.min(d,l+100663296);e:{d=(Math.min(2147483648,65536*Math.ceil(Math.max(l,d)/65536))-I.buffer.byteLength+65535)/65536|0;try{I.grow(d),hn();var m=1;break e}catch{}m=void 0}if(m)return!0}return!1},r:An},he=await(async function(){function l(d){return he=d.exports,I=he.x,hn(),Pn=he.D,xe--,r.monitorRunDependencies?.(xe),xe==0&&Ge&&(d=Ge,Ge=null,d()),he}xe++,r.monitorRunDependencies?.(xe);var f={a:sa};if(r.instantiateWasm)return new Promise(d=>{r.instantiateWasm(f,(m,T)=>{d(l(m,T))})});Ht??=r.locateFile?r.locateFile?r.locateFile("silk.wasm",_):_+"silk.wasm":new URL("silk.wasm",en).href;try{var p=await Oo(f);return l(p.instance)}catch(d){return i(d),Promise.reject(d)}})(),oa=he.z,vn=he.A,Re=he.B,aa=he.C;function Zt(){function l(){if(r.calledRun=!0,!O){if(he.y(),n(r),r.onRuntimeInitialized?.(),r.postRun)for(typeof r.postRun=="function"&&(r.postRun=[r.postRun]);r.postRun.length;){var f=r.postRun.shift();gn.push(f)}pn(gn)}}if(0<xe)Ge=Zt;else{if(r.preRun)for(typeof r.preRun=="function"&&(r.preRun=[r.preRun]);r.preRun.length;)Lo();pn(mn),0<xe?Ge=Zt:r.setStatus?(r.setStatus("Running..."),setTimeout(()=>{setTimeout(()=>r.setStatus(""),1),l()},1)):l()}}if(r.preInit)for(typeof r.preInit=="function"&&(r.preInit=[r.preInit]);0<r.preInit.length;)r.preInit.shift()();return Zt(),e=s,e},po=uf;function go(t){try{let e=nn(t),r=sn(e.get("fmt")),n=e.get("data");return mo(r),yo(n,r),!0}catch{return!1}}var ff=["int","float"],cf=[0,0,0,1];function hf(t){let e=nn(t),r=sn(e.get("fmt")),n=e.get("data"),i=mo(r),s=cf[i],o=ff[s]+r.bitsPerSample;return yo(n,r),{channelData:pf(n,r,i),sampleRate:r.sampleRate,numberOfChannels:r.numberOfChannels,audioEncoding:s,bitsPerSample:r.bitsPerSample,wavFileTypeName:o}}function nn(t){let e;t instanceof ArrayBuffer?e=new DataView(t):e=new DataView(t.buffer,t.byteOffset,t.byteLength);let r=e.byteLength;if(r<20)throw new Error("WAV file is too short.");if(tn(e,0,4)!="RIFF")throw new Error("Not a valid WAV file (no RIFF header).");let n=e.getUint32(4,!0);if(8+n!=r)throw new Error(`Main chunk length of WAV file (${8+n}) does not match file size (${r}).`);if(tn(e,8,4)!="WAVE")throw new Error("RIFF file is not a WAV file.");let i=new Map,s=12;for(;s<r;){if(s+8>r)throw new Error(`Incomplete chunk prefix in WAV file at offset ${s}.`);let o=tn(e,s,4).trim(),a=e.getUint32(s+4,!0);if(s+8+a>r)throw new Error(`Incomplete chunk data in WAV file at offset ${s}.`);let u=new DataView(e.buffer,e.byteOffset+s+8,a);i.set(o,u);let c=a%2;s+=8+a+c}return i}function tn(t,e,r){let n=new Uint8Array(t.buffer,t.byteOffset+e,r);return String.fromCharCode.apply(null,n)}function df(t,e){let r=t.getInt8(e+2)*65536,n=t.getUint16(e,!0);return r+n}function sn(t){if(!t)throw new Error("No format chunk found in WAV file.");if(t.byteLength<16)throw new Error("Format chunk of WAV file is too short.");let e={};return e.formatCode=t.getUint16(0,!0),e.numberOfChannels=t.getUint16(2,!0),e.sampleRate=t.getUint32(4,!0),e.bytesPerSec=t.getUint32(8,!0),e.bytesPerFrame=t.getUint16(12,!0),e.bitsPerSample=t.getUint16(14,!0),e}function mo(t){if(t.numberOfChannels<1||t.numberOfChannels>999)throw new Error("Invalid number of channels in WAV file.");let e=Math.ceil(t.bitsPerSample/8),r=t.numberOfChannels*e;if(t.formatCode==1&&t.bitsPerSample>=1&&t.bitsPerSample<=8&&t.bytesPerFrame==r)return 0;if(t.formatCode==1&&t.bitsPerSample>=9&&t.bitsPerSample<=16&&t.bytesPerFrame==r)return 1;if(t.formatCode==1&&t.bitsPerSample>=17&&t.bitsPerSample<=24&&t.bytesPerFrame==r)return 2;if(t.formatCode==3&&t.bitsPerSample==32&&t.bytesPerFrame==r)return 3;throw new Error(`Unsupported WAV file type, formatCode=${t.formatCode}, bitsPerSample=${t.bitsPerSample}, bytesPerFrame=${t.bytesPerFrame}, numberOfChannels=${t.numberOfChannels}.`)}function pf(t,e,r){switch(r){case 0:return mf(t,e);case 1:return gf(t,e);case 2:return yf(t,e);case 3:return _f(t,e);default:throw new Error("No decoder.")}}function gf(t,e){let r=Lt(t.byteLength,e),n=e.numberOfChannels,i=r[0].length,s=0;for(let o=0;o<i;o++)for(let a=0;a<n;a++){let u=t.getInt16(s,!0)/32768;r[a][o]=u,s+=2}return r}function mf(t,e){let r=Lt(t.byteLength,e),n=e.numberOfChannels,i=r[0].length,s=0;for(let o=0;o<i;o++)for(let a=0;a<n;a++){let u=(t.getUint8(s)-128)/128;r[a][o]=u,s+=1}return r}function yf(t,e){let r=Lt(t.byteLength,e),n=e.numberOfChannels,i=r[0].length,s=0;for(let o=0;o<i;o++)for(let a=0;a<n;a++){let u=df(t,s)/8388608;r[a][o]=u,s+=3}return r}function _f(t,e){let r=Lt(t.byteLength,e),n=e.numberOfChannels,i=r[0].length,s=0;for(let o=0;o<i;o++)for(let a=0;a<n;a++){let u=t.getFloat32(s,!0);r[a][o]=u,s+=4}return r}function Lt(t,e){let r=Math.floor(t/e.bytesPerFrame),n=new Array(e.numberOfChannels);for(let i=0;i<e.numberOfChannels;i++)n[i]=new Float32Array(r);return n}function yo(t,e){if(!t)throw new Error("No data chunk found in WAV file.");if(t.byteLength%e.bytesPerFrame!=0)throw new Error("WAV file data chunk length is not a multiple of frame size.")}function wf(t){let e=nn(t),r=bf(e),n=sn(e.get("fmt"));return{chunkInfo:r,fmt:n}}function bf(t){let e=[];for(let r of t){let n={};n.chunkId=r[0],n.dataOffset=r[1].byteOffset,n.dataLength=r[1].byteLength,e.push(n)}return e.sort((r,n)=>r.dataOffset-n.dataOffset),e}function Cf(t){let{length:e}=t;if(e===1)return t[0];let r=new Float32Array(t[0].length);for(let n=0;n<r.length;n++){let i=0;for(let s=0;s<e;s++)i+=t[s][n];r[n]=i/e}return r}function Ef(t){let e=new Int16Array(t.length);for(let r=0;r<t.length;r++){let n=~~(t[r]*32768);e[r]=n>32767?32767:n}return e.buffer}function Tf(t,e=0,r=t.byteLength){return new TextDecoder().decode(t.slice(e,r))}function Mt(t){return ArrayBuffer.isView(t)?t.buffer.slice(t.byteOffset,t.byteOffset+t.byteLength):t}async function kf(t,e){let r=await po(),n=Mt(t);if(!n?.byteLength)throw new Error("input data length is 0");if(go(t)){let{channelData:o,sampleRate:a}=hf(t);e||=a,n=Ef(Cf(o))}let i=new Uint8Array,s=r.silk_encode(n,e,o=>{i=o.slice()});if(s===0)throw new Error("silk encoding failure");return{data:i,duration:s}}async function Pf(t,e){let r=await po(),n=Mt(t);if(!n?.byteLength)throw new Error("input data length is 0");let i=new Uint8Array,s=r.silk_decode(n,e,o=>{o.length>0&&(i=o.slice())});if(s===0)throw new Error("silk decoding failure");return{data:i,duration:s}}function Sf(t,e=20){let r=Mt(t),n=new DataView(r),i=n.byteLength,s=n.getUint8(0)===2?10:9,o=0;for(;s<i;){let a=n.getUint16(s,!0);o+=1,s+=a+2}return o*e}function xf(t){return go(t)}function Bf(t){return wf(t)}function Rf(t){let e=Mt(t);return e.byteLength<7?!1:Tf(e,0,7).includes("#!SILK")}});import{writeFileSync as tc,readFileSync as rc,unlinkSync as nc,existsSync as ic}from"node:fs";import{join as sc}from"node:path";import{pathToFileURL as oc}from"node:url";import{homedir as ma}from"node:os";import{resolve as Nn}from"node:path";function tr(t=process.env){let e=t.WECHAT_STATE_DIR??"~/.aladuo/channel-wechat";return e.startsWith("~")?Nn(ma(),e.slice(2)):Nn(e)}function $n(){let t=process.env.WECHAT_DM_POLICY??"open";if(t!=="open"&&t!=="allowlist")throw new Error(`WECHAT_DM_POLICY must be 'open' or 'allowlist', got: ${t}`);let r=(process.env.WECHAT_ALLOW_FROM??"").split(",").map(s=>s.trim()).filter(Boolean);if(t==="allowlist"&&r.length===0)throw new Error("WECHAT_DM_POLICY=allowlist requires WECHAT_ALLOW_FROM to be set");let n=tr(),i=process.env.WECHAT_LOG_LEVEL??"info";if(!["error","warn","info","debug"].includes(i))throw new Error(`WECHAT_LOG_LEVEL must be one of error|warn|info|debug, got: ${i}`);return{daemonUrl:process.env.ALADUO_DAEMON_URL??"http://127.0.0.1:20233",apiBase:process.env.WECHAT_API_BASE??"https://ilinkai.weixin.qq.com",cdnBase:process.env.WECHAT_CDN_BASE??"https://novac2c.cdn.weixin.qq.com/c2c",dmPolicy:t,allowFrom:r,stateDir:n,logLevel:i}}import{mkdir as Du,readFile as so,writeFile as oo,chmod as Wu,unlink as Hu}from"node:fs/promises";import{existsSync as zu}from"node:fs";import{resolve as ao}from"node:path";import{randomBytes as Fn}from"node:crypto";var ya=4e3,Z=class extends Error{constructor(r,n){super(`WechatApiError[${r}]: ${n}`);this.errcode=r;this.name="WechatApiError"}};function _a(){let t=Fn(4).readUInt32BE(0);return Buffer.from(String(t),"utf-8").toString("base64")}function Ke(t,e){let r={"Content-Type":"application/json","Content-Length":String(Buffer.byteLength(e,"utf-8")),AuthorizationType:"ilink_bot_token","X-WECHAT-UIN":_a()};return t&&(r.Authorization=`Bearer ${t}`),r}async function qn(t,e=fetch){let n=`${t.endsWith("/")?t:`${t}/`}ilink/bot/get_bot_qrcode?bot_type=3`,i=await e(n,{method:"GET"});if(!i.ok)throw new Error(`HTTP ${i.status} from getQrCode`);let s=await i.json();return{qrcode:s.qrcode,qrcodeImgUrl:s.qrcode_img_content}}async function Dn(t,e,r=fetch){let i=`${t.endsWith("/")?t:`${t}/`}ilink/bot/get_qrcode_status?qrcode=${encodeURIComponent(e)}`,s;try{s=await r(i,{method:"GET",headers:{"iLink-App-ClientVersion":"1"},signal:AbortSignal.timeout(35e3)})}catch(a){if(a instanceof Error&&a.name==="AbortError")return{status:"wait"};throw a}if(!s.ok)throw new Error(`HTTP ${s.status} from pollQrStatus`);let o=await s.json();return{status:o.status,token:o.bot_token,botId:o.ilink_bot_id,userId:o.ilink_user_id,resolvedBaseUrl:o.baseurl,redirectHost:o.redirect_host}}async function Wn(t,e,r,n=fetch){let i=t.endsWith("/")?t:`${t}/`,s=JSON.stringify({get_updates_buf:r,base_info:{channel_version:"claude-code-1.0"}}),o;try{let c=await n(`${i}ilink/bot/getupdates`,{method:"POST",headers:Ke(e,s),body:s,signal:AbortSignal.timeout(4e4)});if(o=await c.text(),!c.ok)throw new Error(`getUpdates HTTP ${c.status}: ${o}`)}catch(c){if(c instanceof Error&&c.name==="AbortError")return{msgs:[],syncBuf:r};throw c}let a=JSON.parse(o),u=a.ret??a.errcode??0;if(u!==0)throw new Z(u,a.errmsg??"unknown");return{msgs:a.msgs??[],syncBuf:a.get_updates_buf??r}}function Un(){return`cc-wx-${Date.now()}-${Fn(4).toString("hex")}`}async function le(t,e,r,n,i,s=fetch,o){let a=t.endsWith("/")?t:`${t}/`;if(o){let u;if("kind"in o&&o.kind==="file"){let g=o.item;u=[{type:4,file_item:{media:{encrypt_query_param:g.encryptQueryParam,aes_key:g.aesKeyBase64,encrypt_type:1},file_name:g.fileName,md5:"",len:String(g.fileSize)}}]}else if("kind"in o&&o.kind==="voice"){let g=o.item;u=[{type:3,voice_item:{media:{encrypt_query_param:g.encryptQueryParam,aes_key:g.aesKeyBase64,encrypt_type:1},encode_type:g.encodeType??6,sample_rate:g.sampleRate??16e3,bits_per_sample:g.bitsPerSample??16,playtime:g.playtimeMs??0}}]}else if("kind"in o&&o.kind==="video"){let g=o.item;u=[{type:5,video_item:{media:{encrypt_query_param:g.encryptQueryParam,aes_key:g.aesKeyBase64,encrypt_type:1},video_size:g.videoSize}}]}else{let g=o;u=[{type:2,image_item:{media:{encrypt_query_param:g.encryptQueryParam,aes_key:g.aesKeyBase64,encrypt_type:1},mid_size:g.midSize}}]}let c={from_user_id:"",to_user_id:r,client_id:Un(),message_type:2,message_state:2,item_list:u};i&&(c.context_token=i);let h=JSON.stringify({msg:c,base_info:{channel_version:"claude-code-1.0"}}),y=await s(`${a}ilink/bot/sendmessage`,{method:"POST",headers:Ke(e,h),body:h});if(!y.ok)throw new Error(`sendMessage HTTP ${y.status}`);let _=await y.json(),b=_.ret??_.errcode??0;if(b!==0)throw new Z(b,_.errmsg??"unknown");n&&await le(t,e,r,n,i,s);return}for(let u of wa(n)){let c={from_user_id:"",to_user_id:r,client_id:Un(),message_type:2,message_state:2,item_list:[{type:1,text_item:{text:u}}]};i&&(c.context_token=i);let h=JSON.stringify({msg:c,base_info:{channel_version:"claude-code-1.0"}}),y=await s(`${a}ilink/bot/sendmessage`,{method:"POST",headers:Ke(e,h),body:h});if(!y.ok)throw new Error(`sendMessage HTTP ${y.status}`);let _=await y.json(),b=_.ret??_.errcode??0;if(b!==0)throw new Z(b,_.errmsg??"unknown")}}function wa(t,e=ya){if(t.length<=e)return[t];let r=[],n=0;for(;n<t.length;)r.push(t.slice(n,n+e)),n+=e;return r}async function Hn(t,e,r,n,i=fetch){let s=t.endsWith("/")?t:`${t}/`,o=JSON.stringify({ilink_user_id:r,context_token:n,base_info:{}}),a=await i(`${s}ilink/bot/getconfig`,{method:"POST",headers:Ke(e,o),body:o});if(!a.ok)throw new Error(`getConfig HTTP ${a.status}`);return await a.json()}async function zn(t,e,r,n,i,s=fetch){let o=t.endsWith("/")?t:`${t}/`,a=JSON.stringify({ilink_user_id:r,typing_ticket:n,status:i,base_info:{}});try{await s(`${o}ilink/bot/sendtyping`,{method:"POST",headers:Ke(e,a),body:a})}catch{}}import{mkdir as Mu,readFile as Nu,unlink as Xs,writeFile as $u}from"node:fs/promises";import{existsSync as eo}from"node:fs";import{resolve as Uu}from"node:path";var Fu="qrcode.png",qu="qrcode.txt";function to(t,e){return Uu(t,e)}function At(t){return to(t,Fu)}function Gr(t){return to(t,qu)}async function ro(t,e){eo(t)||await Mu(t,{recursive:!0}),await $u(Gr(t),e,"utf8")}async function no(t){await Promise.all([Xs(At(t)).catch(()=>{}),Xs(Gr(t)).catch(()=>{})])}async function io(t,e=r=>process.stdout.write(r)){let r=Gr(t),n;try{n=(await Nu(r,"utf8")).trim()}catch(o){if(o.code==="ENOENT"){let a=At(t);throw eo(a)?new Error(`No current pending QR code found in ${t}. Existing ${a} is likely stale; trigger a fresh QR login before using qrcode-terminal.`):new Error(`No current pending QR code found in ${t}. Start a fresh QR login before using qrcode-terminal.`)}throw o}if(!n)throw new Error(`No current pending QR code found in ${t}. Start a fresh QR login before using qrcode-terminal.`);let s=await(await Promise.resolve().then(()=>er(Qr(),1))).default.toString(n,{type:"terminal",small:!0});e(s.endsWith(`
|
|
33
|
+
`)?s:`${s}
|
|
34
|
+
`)}var It=class t{constructor(e,r,n=fetch,i=2e3){this.stateDir=e;this.fetchFn=n;this.pollIntervalMs=i;this.apiBase=r,this.credFile=ao(e,"credentials.json"),this.syncBufFile=ao(e,"sync-buf.txt"),this.qrcodePng=At(e)}credFile;syncBufFile;qrcodePng;cached=null;apiBase;tokenObtainedAt=0;static PROACTIVE_REFRESH_MS=720*60*1e3;silentRefreshInProgress=!1;async getToken(){if(this.cached)return await this.cleanupQrPng(),this.tokenObtainedAt>0&&Date.now()-this.tokenObtainedAt>t.PROACTIVE_REFRESH_MS&&!this.silentRefreshInProgress&&this.silentRefresh(),this.cached.token;let e=await this.loadCredentials();return e?(await this.cleanupQrPng(),this.cached=e,e.apiBase&&(this.apiBase=e.apiBase),this.tokenObtainedAt===0&&(this.tokenObtainedAt=Date.now()),e.token):this.startQrLogin()}getApiBase(){return this.apiBase}async startQrLogin(){let{qrcode:e,qrcodeImgUrl:r}=await qn(this.apiBase,this.fetchFn);await this.ensureStateDir(),await ro(this.stateDir,r);let n=(await Promise.resolve().then(()=>er(Qr(),1))).default;await n.toFile(this.qrcodePng,r,{type:"png",width:300});let i=await n.toString(r,{type:"terminal",small:!0});process.stdout.write(`QRCODE_READY:${this.qrcodePng}
|
|
35
|
+
`),process.stdout.write(`QRCODE_TERMINAL_BEGIN
|
|
36
|
+
`),process.stdout.write(i.endsWith(`
|
|
37
|
+
`)?i:`${i}
|
|
38
|
+
`),process.stdout.write(`QRCODE_TERMINAL_END
|
|
39
|
+
`);let s=Date.now()+480*1e3;for(;Date.now()<s;){await ju(this.pollIntervalMs);let o;try{o=await Dn(this.apiBase,e,this.fetchFn)}catch(a){if(a instanceof Z&&a.errcode===-14)return await this.cleanupQrPng(),this.startQrLogin();throw a}if(o.status==="confirmed"&&o.token){o.resolvedBaseUrl&&(this.apiBase=o.resolvedBaseUrl);let a={token:o.token,botId:o.botId,apiBase:this.apiBase};await this.saveCredentials(a),this.cached=a,this.tokenObtainedAt=Date.now();let u=o.botId??"unknown";return process.stdout.write(`WECHAT_CONNECTED:${u}
|
|
40
|
+
`),await this.cleanupQrPng(),a.token}if(o.status==="scaned_but_redirect"&&o.redirectHost){this.apiBase=Qu(o.redirectHost);continue}if(o.status==="expired")return await this.cleanupQrPng(),this.startQrLogin()}throw await this.cleanupQrPng(),new Error("QR login timed out after 8 minutes")}async getSyncBuf(){try{return(await so(this.syncBufFile,"utf-8")).trim()}catch{return""}}async saveSyncBuf(e){await this.ensureStateDir(),await oo(this.syncBufFile,e,"utf-8")}invalidateToken(){this.cached=null,this.tokenObtainedAt=0,Hu(this.credFile).catch(()=>{})}async silentRefresh(){this.silentRefreshInProgress=!0;try{this.tokenObtainedAt=Date.now()}finally{this.silentRefreshInProgress=!1}}async relogin(){return this.cached=null,this.startQrLogin()}async loadCredentials(){try{let e=await so(this.credFile,"utf-8");return JSON.parse(e)}catch{return null}}async saveCredentials(e){await this.ensureStateDir(),await oo(this.credFile,JSON.stringify(e),"utf-8"),await Wu(this.credFile,384)}async cleanupQrPng(){await no(this.stateDir)}async ensureStateDir(){zu(this.stateDir)||await Du(this.stateDir,{recursive:!0})}};function ju(t){return new Promise(e=>setTimeout(e,t))}function Qu(t){return t.includes("://")?t:`https://${t}`}import{mkdir as $f,readFile as Uf,writeFile as ke}from"node:fs/promises";import{randomBytes as Pe}from"node:crypto";import{extname as fn,basename as Ft,resolve as Ff}from"node:path";import{createCipheriv as Gu,createDecipheriv as Yu,createHash as Vu,randomBytes as Yr}from"node:crypto";import{readFile as Ju}from"node:fs/promises";function Ku(t,e){let r=Gu("aes-128-ecb",e,null);return Buffer.concat([r.update(t),r.final()])}function Zu(t,e){let r=Yu("aes-128-ecb",e,null);return Buffer.concat([r.update(t),r.final()])}function Xu(t){return Math.ceil((t+1)/16)*16}function ef(t){let e=Buffer.from(t,"base64");if(e.length===16)return e;if(e.length===32&&/^[0-9a-fA-F]{32}$/.test(e.toString("ascii")))return Buffer.from(e.toString("ascii"),"hex");throw new Error(`aes_key must decode to 16 raw bytes or 32-char hex string, got ${e.length} bytes`)}async function pe(t){let{cdnBaseUrl:e,encryptQueryParam:r,fullUrl:n,aesKeyBase64:i,fetchFn:s=fetch}=t,o=e.endsWith("/")?e.slice(0,-1):e,a=n||(r?`${o}/download?encrypted_query_param=${encodeURIComponent(r)}`:void 0);if(!a)throw new Error("downloadMedia requires fullUrl or encryptQueryParam");let u=await s(a);if(!u.ok){let y=await u.text().catch(()=>"(unreadable)");throw new Error(`CDN download failed: ${u.status} ${u.statusText} body=${y}`)}let c=Buffer.from(await u.arrayBuffer());if(!i)return c;let h=ef(i);return Zu(c,h)}var vt=1,Vr=2,Jr=3,Kr=4;async function ft(t){let{apiBase:e,cdnBase:r,token:n,filePath:i,toUserId:s,mediaType:o=vt,fetchFn:a=fetch}=t,u=Buffer.isBuffer(i)?i:await Ju(i),c=u.length,h=Vu("md5").update(u).digest("hex"),y=Xu(c),_=Yr(16).toString("hex"),b=Yr(16),g=e.endsWith("/")?e:`${e}/`,w=JSON.stringify({filekey:_,media_type:o,to_user_id:s,rawsize:c,rawfilemd5:h,filesize:y,no_need_thumb:!0,aeskey:b.toString("hex"),base_info:{channel_version:"claude-code-1.0"}}),C=Buffer.from(String(Yr(4).readUInt32BE(0))).toString("base64"),E=await a(`${g}ilink/bot/getuploadurl`,{method:"POST",headers:{"Content-Type":"application/json","Content-Length":String(Buffer.byteLength(w,"utf-8")),AuthorizationType:"ilink_bot_token",Authorization:`Bearer ${n}`,"X-WECHAT-UIN":C},body:w});if(!E.ok)throw new Error(`getuploadurl HTTP ${E.status}`);let x=await E.json(),I=x.ret??x.errcode??0;if(I!==0)throw new Error(`getuploadurl error ${I}: ${x.errmsg??"unknown"}`);let O=x.upload_param,N=x.upload_full_url?.trim();if(!O&&!N)throw new Error("getuploadurl returned no upload destination");let v=r.endsWith("/")?r.slice(0,-1):r,L=N||`${v}/upload?encrypted_query_param=${encodeURIComponent(O)}&filekey=${encodeURIComponent(_)}`,G=Ku(u,b),z=await a(L,{method:"POST",headers:{"Content-Type":"application/octet-stream"},body:new Uint8Array(G)});if(!z.ok){let X=z.headers.get("x-error-message")??`status ${z.status}`;throw new Error(`CDN upload failed: ${X}`)}let U=z.headers.get("x-encrypted-param");if(!U)throw new Error("CDN upload response missing x-encrypted-param header");let F=Buffer.from(b.toString("hex")).toString("base64");return{encryptQueryParam:U,aesKeyBase64:F,fileSizeCiphertext:y,rawSize:c}}function Zr(t){return{sessionKey:t.session_key,text:t.payload.text??"",attachments:t.payload.attachments,raw:t}}function Xr(t){let e=t.daemonUrl.replace(/^http/,"ws")+"/ws",r=new WebSocket(e),n=1;return r.addEventListener("open",()=>{let i={jsonrpc:"2.0",id:`pull_${n++}`,method:"channel.pull",params:{session_key:t.sessionKey,consumer_id:t.consumerId,cursor:t.cursor||void 0,return_mask:["final"],source_kind:t.sourceKind??"wechat",channel_id:t.sessionKey,channel_capabilities:{outbound:{accept_mime:["*/*"]}}}};r.send(JSON.stringify(i))}),r.addEventListener("message",async i=>{let s;try{s=JSON.parse(i.data)}catch{return}if(s.method==="session.output"){let o=s.params;if(o?.record){let a=Zr(o.record);try{await t.onOutput(a)}finally{if(o.record.id){let u={jsonrpc:"2.0",id:`ack_${n++}`,method:"channel.ack",params:{session_key:t.sessionKey,consumer_id:t.consumerId,cursor:o.record.id}};r.send(JSON.stringify(u)),t.onAck(o.record.id)}}}return}s.error&&t.onError(new Ot(s.error.code,s.error.message))}),r.addEventListener("error",()=>{t.onError(new Error("WebSocket error"))}),r.addEventListener("close",()=>{t.onClose()}),()=>{try{r.close()}catch{}}}var tf=1,Ot=class extends Error{constructor(r,n){super(`DaemonError[${r}]: ${n}`);this.code=r;this.name="DaemonError"}};async function uo(t,e,r,n=fetch){let s={jsonrpc:"2.0",id:tf++,method:e,params:r},o=await n(`${t}/rpc`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(s)});if(!o.ok)throw new Error(`Daemon HTTP ${o.status} for method ${e}`);let a=await o.json();if(a.error)throw new Ot(a.error.code,a.error.message);return a.result}async function fo(t,e,r=fetch){await uo(t,"channel.ingress",e,r)}async function co(t,e,r=fetch){let n=await uo(t,"channel.file.download",{path:e},r);return Buffer.from(n.content_base64,"base64")}import{spawn as an}from"node:child_process";import{writeFile as Af,unlink as bo}from"node:fs/promises";import{tmpdir as on}from"node:os";import{join as Co}from"node:path";import{randomBytes as If}from"node:crypto";var Nt=16e3;async function ln(t,e){if(e==="audio/silk"||Mf(t)){let a=Nf(t);return{silk:t,playtimeMs:a}}let r=await vf(t),{encode:n}=await Promise.resolve().then(()=>er(wo(),1)),i=await n(r,Nt),s=Buffer.from(i.data),o=Math.round(r.length/(Nt*2)*1e3);return{silk:s,playtimeMs:o}}function vf(t){return new Promise((e,r)=>{let n=an("ffmpeg",["-v","quiet","-i","pipe:0","-f","s16le","-acodec","pcm_s16le","-ar",String(Nt),"-ac","1","pipe:1"]),i=[],s=[];n.stdout.on("data",o=>i.push(o)),n.stderr.on("data",o=>s.push(o)),n.on("close",o=>{if(o!==0){let a=Buffer.concat(s).toString("utf-8").slice(-500);return r(new Error(`ffmpeg exited ${o}: ${a}`))}e(Buffer.concat(i))}),n.on("error",o=>r(new Error(`ffmpeg spawn failed: ${o.message}`))),n.stdin.write(t),n.stdin.end()})}async function Eo(t){let e=Co(on(),`wechat-voice-${If(4).toString("hex")}.wav`);try{let r=await Of(t);return await Af(e,r),await Lf(e)||null}finally{bo(e).catch(()=>{})}}function Of(t){return new Promise((e,r)=>{let n=an("ffmpeg",["-v","quiet","-i","pipe:0","-f","wav","-acodec","pcm_s16le","-ar",String(Nt),"-ac","1","pipe:1"]),i=[],s=[];n.stdout.on("data",o=>i.push(o)),n.stderr.on("data",o=>s.push(o)),n.on("close",o=>{if(o!==0){let a=Buffer.concat(s).toString("utf-8").slice(-500);return r(new Error(`ffmpeg (toWav) exited ${o}: ${a}`))}e(Buffer.concat(i))}),n.on("error",o=>r(new Error(`ffmpeg spawn failed: ${o.message}`))),n.stdin.write(t),n.stdin.end()})}function Lf(t){return new Promise((e,r)=>{let n=an("whisper",[t,"--model","base","--language","zh","--output_format","txt","--output_dir",on(),"--fp16","False"]),i=[];n.stderr.on("data",s=>i.push(s)),n.on("close",async s=>{if(s!==0){let a=Buffer.concat(i).toString("utf-8").slice(-500);return r(new Error(`whisper exited ${s}: ${a}`))}let o=Co(on(),t.replace(/\\/g,"/").split("/").pop().replace(/\.wav$/,".txt"));try{let{readFile:a}=await import("node:fs/promises"),u=await a(o,"utf-8");bo(o).catch(()=>{}),e(u.trim())}catch{e("")}}),n.on("error",s=>r(new Error(`whisper spawn failed: ${s.message}`)))})}function Mf(t){if(t.length<9)return!1;let e=t.subarray(0,9).toString("ascii");return e.startsWith("#!SILK_V3")||e.startsWith("#!SILK")}function Nf(t){return Math.round(t.length/3)}var $t=class t{buffer="";inFence=!1;atLineStart=!0;inline=null;feed(e){return this.buffer+=e,this.pump(!1)}flush(){return this.pump(!0)}pump(e){let r="";for(;this.buffer;){let n=this.buffer,i=this.atLineStart,s=this.inFence,o=this.inline;if(this.inFence?r+=this.pumpFence(e):this.inline?r+=this.pumpInline(e):this.atLineStart?r+=this.pumpLineStart(e):r+=this.pumpBody(e),this.buffer===n&&this.atLineStart===i&&this.inFence===s&&this.inline===o)break}return e&&this.inline&&(r+=`${{image:"![",bold3:"***",italic:"*",ubold3:"___",uitalic:"_"}[this.inline.type]??""}${this.inline.acc}`,this.inline=null),r}pumpFence(e){if(this.atLineStart){if(this.buffer.length<3&&!e)return"";if(this.buffer.startsWith("```")){let i=this.buffer.indexOf(`
|
|
41
|
+
`,3);if(i!==-1){let s=this.buffer.slice(0,i+1);return this.buffer=this.buffer.slice(i+1),this.atLineStart=!0,this.inFence=!1,s}if(e){let s=this.buffer;return this.buffer="",this.atLineStart=!1,this.inFence=!1,s}return""}this.atLineStart=!1}let r=this.buffer.indexOf(`
|
|
42
|
+
`);if(r!==-1){let i=this.buffer.slice(0,r+1);return this.buffer=this.buffer.slice(r+1),this.atLineStart=!0,i}let n=this.buffer;return this.buffer="",n}pumpLineStart(e){let r=this.buffer;if(r[0]===`
|
|
43
|
+
`)return this.buffer=r.slice(1),`
|
|
44
|
+
`;if(r[0]==="`"){if(r.length<3&&!e)return"";if(r.startsWith("```")){let n=r.indexOf(`
|
|
45
|
+
`,3);if(n!==-1){let i=r.slice(0,n+1);return this.buffer=r.slice(n+1),this.atLineStart=!0,this.inFence=!0,i}return e?(this.buffer="",r):""}return this.atLineStart=!1,""}if(r[0]==="#"){let n=0;for(;n<r.length&&r[n]==="#";)n++;return n===r.length&&!e?"":n>=5&&n<=6&&n<r.length&&r[n]===" "?(this.buffer=r.slice(n+1),this.atLineStart=!1,""):(this.atLineStart=!1,"")}if(r[0]===" "||r[0]===" ")return r.search(/[^ \t]/)===-1&&!e||(this.atLineStart=!1),"";if(r[0]==="-"||r[0]==="*"||r[0]==="_"){let n=r[0],i=0;for(;i<r.length&&(r[i]===n||r[i]===" ");)i++;if(i===r.length&&!e)return"";if(i===r.length||r[i]===`
|
|
46
|
+
`){let s=0;for(let o=0;o<i;o++)r[o]===n&&s++;if(s>=3)return i<r.length?(this.buffer=r.slice(i+1),this.atLineStart=!0,r.slice(0,i+1)):(this.buffer="",r)}return this.atLineStart=!1,""}return this.atLineStart=!1,""}pumpBody(e){let r="",n=0;for(;n<this.buffer.length;){let s=this.buffer[n];if(s===`
|
|
47
|
+
`)return r+=this.buffer.slice(0,n+1),this.buffer=this.buffer.slice(n+1),this.atLineStart=!0,r;if(s==="!"&&n+1<this.buffer.length&&this.buffer[n+1]==="[")return r+=this.buffer.slice(0,n),this.buffer=this.buffer.slice(n+2),this.inline={type:"image",acc:""},r;if(s==="~"){n++;continue}if(s==="*"){if(n+2<this.buffer.length&&this.buffer[n+1]==="*"&&this.buffer[n+2]==="*")return r+=this.buffer.slice(0,n),this.buffer=this.buffer.slice(n+3),this.inline={type:"bold3",acc:""},r;if(n+1<this.buffer.length&&this.buffer[n+1]==="*"){n+=2;continue}if(n+1<this.buffer.length&&this.buffer[n+1]!==" "&&this.buffer[n+1]!==`
|
|
48
|
+
`)return r+=this.buffer.slice(0,n),this.buffer=this.buffer.slice(n+1),this.inline={type:"italic",acc:""},r;n++;continue}if(s==="_"){if(n+2<this.buffer.length&&this.buffer[n+1]==="_"&&this.buffer[n+2]==="_")return r+=this.buffer.slice(0,n),this.buffer=this.buffer.slice(n+3),this.inline={type:"ubold3",acc:""},r;if(n+1<this.buffer.length&&this.buffer[n+1]==="_"){n+=2;continue}if(n+1<this.buffer.length&&this.buffer[n+1]!==" "&&this.buffer[n+1]!==`
|
|
49
|
+
`)return r+=this.buffer.slice(0,n),this.buffer=this.buffer.slice(n+1),this.inline={type:"uitalic",acc:""},r;n++;continue}n++}let i=0;return e||(this.buffer.endsWith("**")||this.buffer.endsWith("__")?i=2:(this.buffer.endsWith("*")||this.buffer.endsWith("_")||this.buffer.endsWith("!"))&&(i=1)),r+=this.buffer.slice(0,this.buffer.length-i),this.buffer=i>0?this.buffer.slice(-i):"",r}pumpInline(e){if(!this.inline)return"";switch(this.inline.acc+=this.buffer,this.buffer="",this.inline.type){case"bold3":{let r=this.inline.acc.indexOf("***");if(r===-1)return"";let n=this.inline.acc.slice(0,r);return this.buffer=this.inline.acc.slice(r+3),this.inline=null,t.containsCjk(n)?n:`***${n}***`}case"ubold3":{let r=this.inline.acc.indexOf("___");if(r===-1)return"";let n=this.inline.acc.slice(0,r);return this.buffer=this.inline.acc.slice(r+3),this.inline=null,t.containsCjk(n)?n:`___${n}___`}case"italic":{for(let r=0;r<this.inline.acc.length;r++){let n=this.inline.acc[r];if(n===`
|
|
50
|
+
`){let i=`*${this.inline.acc.slice(0,r+1)}`;return this.buffer=this.inline.acc.slice(r+1),this.inline=null,this.atLineStart=!0,i}if(n==="*"){if(r+1<this.inline.acc.length&&this.inline.acc[r+1]==="*"){r++;continue}let i=this.inline.acc.slice(0,r);return this.buffer=this.inline.acc.slice(r+1),this.inline=null,t.containsCjk(i)?i:`*${i}*`}}return""}case"uitalic":{for(let r=0;r<this.inline.acc.length;r++){let n=this.inline.acc[r];if(n===`
|
|
51
|
+
`){let i=`_${this.inline.acc.slice(0,r+1)}`;return this.buffer=this.inline.acc.slice(r+1),this.inline=null,this.atLineStart=!0,i}if(n==="_"){if(r+1<this.inline.acc.length&&this.inline.acc[r+1]==="_"){r++;continue}let i=this.inline.acc.slice(0,r);return this.buffer=this.inline.acc.slice(r+1),this.inline=null,t.containsCjk(i)?i:`_${i}_`}}return""}case"image":{let r=this.inline.acc.indexOf("]");if(r===-1||r+1>=this.inline.acc.length)return"";if(this.inline.acc[r+1]!=="("){let i=`![${this.inline.acc.slice(0,r+1)}`;return this.buffer=this.inline.acc.slice(r+1),this.inline=null,i}let n=this.inline.acc.indexOf(")",r+2);return n===-1||(this.buffer=this.inline.acc.slice(n+1),this.inline=null),""}}return""}static containsCjk(e){return/[\u2E80-\u9FFF\uAC00-\uD7AF\uF900-\uFAFF]/.test(e)}};var ge="/tmp/channel-wechat-media",To="channel-wechat",ko=3e3,qf=3e4,un=5,Po=3e4;function A(t,e,r){let n=["error","warn","info","debug"],i=r?.logLevel??"info";n.indexOf(t)<=n.indexOf(i)&&console.log(`[${t.toUpperCase()}] [wechat-channel] ${e}`)}function Df(t){return t?t.text_item?.text?t.text_item.text:t.voice_item?.text?t.voice_item.text:t.file_item?.file_name?t.file_item.file_name:"":""}function So(t){return!!(t&&(t.image_item?.media?.encrypt_query_param||t.image_item?.media?.full_url||t.voice_item?.media?.encrypt_query_param||t.voice_item?.media?.full_url||t.file_item?.media?.encrypt_query_param||t.file_item?.media?.full_url||t.video_item?.media?.encrypt_query_param||t.video_item?.media?.full_url))}function Wf(t){for(let e of t??[])if(So(e))return;for(let e of t??[])if(e.ref_msg?.message_item&&So(e.ref_msg.message_item))return e.ref_msg.message_item}function Hf(t){let r=t.raw?.payload?.data;if(!r)return[];let n=[];if(typeof r.mediaUrl=="string"&&r.mediaUrl.trim()&&n.push(r.mediaUrl.trim()),Array.isArray(r.mediaUrls))for(let i of r.mediaUrls)typeof i=="string"&&i.trim()&&n.push(i.trim());return n}function zf(t){if(t){if(t.startsWith("file://"))return new URL(t).pathname;if(!t.includes("://"))return Ff(t)}}var qt=class{constructor(e,r,n=fetch,i){this.config=e;this.auth=r;this.fetchFn=n;this.outbox=i}running=!1;abortController=new AbortController;sessions=new Map;typingTickets=new Map;TYPING_TICKET_TTL_MS=1200*60*1e3;start(){this.running=!0,this.abortController=new AbortController;let e=this.abortController.signal,r=this.fetchFn,n=(i,s)=>r(i,{...s,signal:e});this.ingressLoop(n),this.pullLoop(n),this.outbox&&this.replayOutbox(n)}stop(){this.running=!1,this.abortController.abort()}async ingressLoop(e){let r=0;for(A("info","ingressLoop started",this.config);this.running;){A("debug","ingressLoop tick",this.config);try{let n=await this.auth.getToken(),i=await this.auth.getSyncBuf(),s=this.auth.getApiBase(),{msgs:o,syncBuf:a}=await Wn(s,n,i,e);await this.auth.saveSyncBuf(a),r=0,o.length>0&&A("debug",`getUpdates: ${o.length} msgs, types=${o.map(u=>`msg_type=${u.message_type} items=[${u.item_list?.map(c=>c.type).join(",")}]`).join(" | ")}`,this.config);for(let u of o){if(u.message_type===2)continue;if(!this.isAllowed(u.from_user_id)){A("debug",`Blocked message from ${u.from_user_id}`,this.config);continue}A("debug",`raw item_list from ${u.from_user_id}: ${JSON.stringify(u.item_list)}`,this.config);let c=u.item_list?.filter(g=>g.type===1&&g.text_item?.text).map(g=>g.text_item.text).join("")??"";for(let g of u.item_list??[])if(g.ref_msg){let w=g.ref_msg,C=[];w.title&&C.push(w.title);let E=Df(w.message_item);if(E&&C.push(E),C.length>0){let x=`<quoted_message>
|
|
52
|
+
${C.join(`
|
|
37
53
|
`)}
|
|
38
|
-
</quoted_message>`;
|
|
39
|
-
${
|
|
40
|
-
${
|
|
41
|
-
</voice_transcript>`;
|
|
42
|
-
${
|
|
43
|
-
${
|
|
44
|
-
</voice_transcript>`;
|
|
45
|
-
${S}`:S,x("info",`Whisper transcript: "${C}"`,this.config)}}catch(C){x("warn",`Whisper failed, no transcript injected: ${C}`,this.config)}}else if(g.type===4&&g.file_item?.media?.encrypt_query_param&&g.file_item.media.aes_key){let y=g.file_item,w=await tt({cdnBaseUrl:this.config.cdnBase,encryptQueryParam:y.media.encrypt_query_param,aesKeyBase64:y.media.aes_key,fetchFn:e}),b=y.file_name??"file.bin",C=ds(b)||".bin",S=yf(b),N=`${nt}/${Date.now()}-${Rt(4).toString("hex")}${C}`;await At(N,w),c.push({path:N,mime:S}),x("info",`Downloaded file "${b}" \u2192 ${N} (${w.length}B)`,this.config)}else if(g.type===5&&g.video_item?.media?.encrypt_query_param&&g.video_item.media.aes_key){let y=g.video_item,w=await tt({cdnBaseUrl:this.config.cdnBase,encryptQueryParam:y.media.encrypt_query_param,aesKeyBase64:y.media.aes_key,fetchFn:e}),b=`${nt}/${Date.now()}-${Rt(4).toString("hex")}.mp4`;await At(b,w),c.push({path:b,mime:"video/mp4"}),x("info",`Downloaded video \u2192 ${b} (${w.length}B)`,this.config)}}catch(y){x("warn",`Failed to download media item type=${g.type}: ${String(y)}`,this.config)}if(!u&&c.length===0){x("debug",`Non-text/media message from ${a.from_user_id}, skipping`,this.config);continue}let h=`wechat:${a.from_user_id}`,_=this.sessions.get(h);_?a.context_token&&(_.contextToken=a.context_token):this.sessions.set(h,{toUser:a.from_user_id,contextToken:a.context_token,cursor:""}),x("info",`Ingress from ${a.from_user_id} text=${JSON.stringify(u.slice(0,80))} attachments=${c.length}`,this.config),this.getTypingTicket(a.from_user_id,a.context_token,e).then(g=>{if(!g)return;let y=this.sessions.get(h);y&&(y.stopTyping?.(),y.stopTyping=this.startTyping(a.from_user_id,g,e))});try{await Qo(this.config.daemonUrl,{session_key:h,text:u||void 0,attachments:c,idempotency_key:String(a.message_id),source_kind:"wechat",channel_id:`wechat-${a.from_user_id.replace(/[^A-Za-z0-9_-]/g,"_")}`},e)}catch(g){x("error",`ingress failed for ${h}: ${String(g)}`,this.config)}}}catch(n){if(n?.name==="AbortError")return;if(r++,n instanceof K&&n.errcode===-14){x("warn","Token invalid (-14), triggering re-login",this.config),this.auth.invalidateToken(),r=0;continue}x("error",`ingressLoop error (${r}): ${String(n)}`,this.config),r>=Yr&&(x("warn",`Backing off ${hs}ms after ${Yr} errors`,this.config),await xt(hs),r=0)}}}async pullLoop(e){x("info","pullLoop started (WebSocket mode)",this.config);let r="wechat:__cap_heartbeat__",n;n=null;let i=()=>{n||(x("debug","Registering capability heartbeat WS",this.config),n=$r({daemonUrl:this.config.daemonUrl,sessionKey:r,consumerId:fs,sourceKind:"wechat",onOutput:async()=>{},onAck:()=>{},onError:()=>{},onClose:()=>{n=null,this.running&&setTimeout(i,cs)}}))};i();let o=new Map,s=new Map,a=(c,h)=>{if(o.has(c))return;x("info",`WS subscribing for ${c}`,this.config);let _=$r({daemonUrl:this.config.daemonUrl,sessionKey:c,consumerId:fs,cursor:h.cursor||void 0,sourceKind:"wechat",onOutput:async g=>{let y=await this.auth.getToken(),w=g.attachments??[];if(w.length>0)for(let b=0;b<w.length;b++){let C=w[b],S=b===w.length-1,N=S?g.text??"":"";x("info",`Sending attachment to ${h.toUser}: ${C.path} (${C.mime})`,this.config);try{let U=await Zo(this.config.daemonUrl,C.path,e),B=C.mime.startsWith("image/");if(C.mime.startsWith("audio/")){let{silk:v,playtimeMs:L}=await ls(U,C.mime),j=await this.withRetry(()=>Fr({apiBase:this.config.apiBase,cdnBase:this.config.cdnBase,token:y,filePath:v,toUserId:h.toUser,mediaType:Jo,fetchFn:e}),"uploadMedia(voice)");await this.withRetry(()=>Ee(this.config.apiBase,y,h.toUser,N,h.contextToken,e,{kind:"voice",item:{encryptQueryParam:j.encryptQueryParam,aesKeyBase64:j.aesKeyBase64,playtimeMs:L}}),"sendMessage(voice)")}else{let v=await this.withRetry(()=>Fr({apiBase:this.config.apiBase,cdnBase:this.config.cdnBase,token:y,filePath:U,toUserId:h.toUser,mediaType:B?Nr:Yo,fetchFn:e}),B?"uploadMedia(image)":"uploadMedia(file)"),L=C.path.split("/").pop()??"file";await this.withRetry(()=>Ee(this.config.apiBase,y,h.toUser,N,h.contextToken,e,B?{encryptQueryParam:v.encryptQueryParam,aesKeyBase64:v.aesKeyBase64,midSize:v.fileSizeCiphertext}:{kind:"file",item:{encryptQueryParam:v.encryptQueryParam,aesKeyBase64:v.aesKeyBase64,fileName:L,fileSize:v.rawSize}}),B?"sendMessage(image)":"sendMessage(file)")}}catch(U){U instanceof K&&U.errcode===-14&&this.auth.invalidateToken(),x("error",`sendAttachment failed to ${h.toUser}: ${String(U)}`,this.config),S&&g.text&&await this.withRetry(()=>Ee(this.config.apiBase,y,h.toUser,g.text,h.contextToken,e),"sendMessage(fallback)").catch(B=>x("error",`sendMessage fallback failed: ${String(B)}`,this.config))}}else if(g.text){x("info",`Sending reply to ${h.toUser}: ${g.text.slice(0,60)}`,this.config);try{await this.withRetry(()=>Ee(this.config.apiBase,y,h.toUser,g.text,h.contextToken,e),"sendMessage(text)")}catch(b){b instanceof K&&b.errcode===-14&&this.auth.invalidateToken(),x("error",`sendMessage failed to ${h.toUser}: ${String(b)}`,this.config),this.outbox&&await this.outbox.enqueue({sessionKey:c,toUser:h.toUser,contextToken:h.contextToken,text:g.text,attachments:[]}).catch(C=>x("warn",`outbox.enqueue failed: ${String(C)}`,this.config))}}h.stopTyping&&(h.stopTyping(),h.stopTyping=void 0)},onAck:g=>{h.cursor=g,s.set(c,0)},onError:g=>{let y=(s.get(c)??0)+1;s.set(c,y),x("error",`WS error for ${c} (${y}): ${String(g)}`,this.config)},onClose:()=>{if(o.delete(c),!this.running)return;let y=(s.get(c)??0)>=Yr?mf:cs;x("info",`WS closed for ${c}, reconnecting in ${y}ms`,this.config),setTimeout(()=>{if(this.running&&this.sessions.has(c)){let w=this.sessions.get(c);a(c,w)}},y)}});o.set(c,_)};for(;this.running;){for(let[c,h]of this.sessions)a(c,h);for(let[c,h]of o)this.sessions.has(c)||(h(),o.delete(c));await xt(1e3,this.abortController.signal)}let u=n;n=null,u?.();for(let c of o.values())c();o.clear()}async getTypingTicket(e,r,n){let i=this.typingTickets.get(e);if(i&&Date.now()-i.fetchedAt<this.TYPING_TICKET_TTL_MS)return i.ticket;try{let o=await this.auth.getToken(),s=await On(this.config.apiBase,o,e,r,n);if(s.typing_ticket)return this.typingTickets.set(e,{ticket:s.typing_ticket,fetchedAt:Date.now()}),s.typing_ticket}catch(o){x("debug",`getTypingTicket failed for ${e}: ${String(o)}`,this.config)}}startTyping(e,r,n){let i=async s=>{try{let a=await this.auth.getToken();await vn(this.config.apiBase,a,e,r,s,n)}catch{}};i(1);let o=setInterval(()=>{i(1)},5e3);return()=>{clearInterval(o),i(2)}}async withRetry(e,r,n={}){let i=n.maxAttempts??3,o=n.baseMs??500,s;for(let a=1;a<=i;a++)try{return await e()}catch(u){if(s=u,u instanceof K&&[-14,400,403].includes(u.errcode))throw u;if(a<i){let c=o*Math.pow(2,a-1);x("warn",`${r} attempt ${a}/${i} failed, retry in ${c}ms: ${String(u)}`,this.config),await xt(c)}}throw s}async replayOutbox(e){if(!this.outbox)return;await xt(5e3);let r=await this.outbox.getPending();if(r.length!==0){x("info",`Replaying ${r.length} outbox pending records`,this.config);for(let n of r){if(!this.running)break;try{let i=await this.auth.getToken();await this.withRetry(()=>Ee(this.config.apiBase,i,n.toUser,n.text,n.contextToken,e),"outbox.replay"),await this.outbox.markSent(n.id),x("info",`Outbox replayed ${n.id} to ${n.toUser}`,this.config)}catch(i){await this.outbox.markFailed(n.id,String(i)),x("warn",`Outbox replay failed for ${n.id}: ${String(i)}`,this.config)}}}}isAllowed(e){return this.config.dmPolicy==="open"?!0:this.config.allowFrom.includes(e)}};function yf(t){let e=ds(t).toLowerCase();return{".pdf":"application/pdf",".doc":"application/msword",".docx":"application/vnd.openxmlformats-officedocument.wordprocessingml.document",".xls":"application/vnd.ms-excel",".xlsx":"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",".ppt":"application/vnd.ms-powerpoint",".pptx":"application/vnd.openxmlformats-officedocument.presentationml.presentation",".zip":"application/zip",".txt":"text/plain",".csv":"text/csv",".json":"application/json",".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".webp":"image/webp",".mp4":"video/mp4",".mov":"video/quicktime",".mp3":"audio/mpeg",".m4a":"audio/mp4",".wav":"audio/wav"}[e]??"application/octet-stream"}function xt(t,e){return new Promise(r=>{let n=setTimeout(r,t);e?.addEventListener("abort",()=>{clearTimeout(n),r()},{once:!0})})}import _f from"node:http";function ps(t,e){let r=_f.createServer((n,i)=>{if(n.method!=="GET"||n.url!=="/health"){i.writeHead(404),i.end("Not Found");return}if(!t.running){i.writeHead(503,{"Content-Type":"application/json"}),i.end(JSON.stringify({status:"unavailable",reason:"gateway_stopped"}));return}let o=t.tokenObtainedAt>0?Date.now()-t.tokenObtainedAt:1/0;if(o>72e6){i.writeHead(503,{"Content-Type":"application/json"}),i.end(JSON.stringify({status:"token_stale",token_age_hours:Math.floor(o/36e5)}));return}i.writeHead(200,{"Content-Type":"application/json"}),i.end(JSON.stringify({status:"ok",uptime_seconds:Math.floor(process.uptime()),token_age_hours:Math.floor(o/36e5)}))});return r.listen(e,()=>{console.log(`[INFO] [wechat-channel] Health check listening on :${e}/health`)}),r}import{appendFile as wf,readFile as bf,writeFile as Cf,mkdir as gs,rename as Ef}from"node:fs/promises";import{existsSync as Tf}from"node:fs";import{dirname as ms}from"node:path";import{randomBytes as kf}from"node:crypto";var Pf=3,It=class{constructor(e){this.filePath=e}writeChain=Promise.resolve();async enqueue(e){let r=kf(8).toString("hex"),n={...e,id:r,createdAt:Date.now(),attempts:0},i=JSON.stringify(n)+`
|
|
46
|
-
`;return this.writeChain=this.writeChain.then(async()=>{await
|
|
47
|
-
`)){let i=n.trim();if(i)try{r.push(JSON.parse(i))}catch{}}return r}async rewrite(e){this.writeChain=this.writeChain.then(async()=>{await
|
|
54
|
+
</quoted_message>`;c=c?`${x}
|
|
55
|
+
${c}`:x,A("info",`Quoted message context: "${C.join(" | ")}"`,this.config)}break}await $f(ge,{recursive:!0});let h=[];for(let g of u.item_list??[])try{if(g.type===2&&(g.image_item?.media?.encrypt_query_param||g.image_item?.media?.full_url)){let w=g.image_item,C=w.media.aes_key??(w.aeskey?Buffer.from(w.aeskey,"hex").toString("base64"):void 0),E=await pe({cdnBaseUrl:this.config.cdnBase,encryptQueryParam:w.media.encrypt_query_param,fullUrl:w.media.full_url,aesKeyBase64:C,fetchFn:e}),x=`${ge}/${Date.now()}-${Pe(4).toString("hex")}.jpg`;await ke(x,E),h.push({path:x,mime:"image/jpeg"}),A("info",`Downloaded image \u2192 ${x} (${E.length}B)`,this.config)}else if(g.type===3&&(g.voice_item?.media?.encrypt_query_param||g.voice_item?.media?.full_url)&&g.voice_item.media.aes_key){let w=g.voice_item,C=await pe({cdnBaseUrl:this.config.cdnBase,encryptQueryParam:w.media.encrypt_query_param,fullUrl:w.media.full_url,aesKeyBase64:w.media.aes_key,fetchFn:e}),E=`${ge}/${Date.now()}-${Pe(4).toString("hex")}.silk`;if(await ke(E,C),h.push({path:E,mime:"audio/silk"}),A("info",`Downloaded voice \u2192 ${E} (${C.length}B)`,this.config),w.text){let x=`<voice_transcript>
|
|
56
|
+
${w.text}
|
|
57
|
+
</voice_transcript>`;c=c?`${c}
|
|
58
|
+
${x}`:x,A("info",`Voice transcription from WeChat: "${w.text}"`,this.config)}else try{let x=await Eo(C);if(x){let I=`<voice_transcript>
|
|
59
|
+
${x}
|
|
60
|
+
</voice_transcript>`;c=c?`${c}
|
|
61
|
+
${I}`:I,A("info",`Whisper transcript: "${x}"`,this.config)}}catch(x){A("warn",`Whisper failed, no transcript injected: ${x}`,this.config)}}else if(g.type===4&&(g.file_item?.media?.encrypt_query_param||g.file_item?.media?.full_url)&&g.file_item.media.aes_key){let w=g.file_item,C=await pe({cdnBaseUrl:this.config.cdnBase,encryptQueryParam:w.media.encrypt_query_param,fullUrl:w.media.full_url,aesKeyBase64:w.media.aes_key,fetchFn:e}),E=w.file_name??"file.bin",x=fn(E)||".bin",I=ht(E),O=`${ge}/${Date.now()}-${Pe(4).toString("hex")}${x}`;await ke(O,C),h.push({path:O,mime:I}),A("info",`Downloaded file "${E}" \u2192 ${O} (${C.length}B)`,this.config)}else if(g.type===5&&(g.video_item?.media?.encrypt_query_param||g.video_item?.media?.full_url)&&g.video_item.media.aes_key){let w=g.video_item,C=await pe({cdnBaseUrl:this.config.cdnBase,encryptQueryParam:w.media.encrypt_query_param,fullUrl:w.media.full_url,aesKeyBase64:w.media.aes_key,fetchFn:e}),E=`${ge}/${Date.now()}-${Pe(4).toString("hex")}.mp4`;await ke(E,C),h.push({path:E,mime:"video/mp4"}),A("info",`Downloaded video \u2192 ${E} (${C.length}B)`,this.config)}}catch(w){A("warn",`Failed to download media item type=${g.type}: ${String(w)}`,this.config)}let y=h.length===0?Wf(u.item_list):void 0;if(y)try{if(y.type===2&&y.image_item?.media){let g=y.image_item,w=g.media;if(!w)continue;let C=w.aes_key??(g.aeskey?Buffer.from(g.aeskey,"hex").toString("base64"):void 0),E=await pe({cdnBaseUrl:this.config.cdnBase,encryptQueryParam:w.encrypt_query_param,fullUrl:w.full_url,aesKeyBase64:C,fetchFn:e}),x=`${ge}/${Date.now()}-${Pe(4).toString("hex")}.jpg`;await ke(x,E),h.push({path:x,mime:"image/jpeg"})}else if(y.type===3&&y.voice_item?.media?.aes_key){let g=y.voice_item,w=await pe({cdnBaseUrl:this.config.cdnBase,encryptQueryParam:g.media.encrypt_query_param,fullUrl:g.media.full_url,aesKeyBase64:g.media.aes_key,fetchFn:e}),C=`${ge}/${Date.now()}-${Pe(4).toString("hex")}.silk`;await ke(C,w),h.push({path:C,mime:"audio/silk"})}else if(y.type===4&&y.file_item?.media?.aes_key){let g=y.file_item,w=await pe({cdnBaseUrl:this.config.cdnBase,encryptQueryParam:g.media.encrypt_query_param,fullUrl:g.media.full_url,aesKeyBase64:g.media.aes_key,fetchFn:e}),C=g.file_name??"file.bin",E=fn(C)||".bin",x=ht(C),I=`${ge}/${Date.now()}-${Pe(4).toString("hex")}${E}`;await ke(I,w),h.push({path:I,mime:x})}else if(y.type===5&&y.video_item?.media?.aes_key){let g=y.video_item,w=await pe({cdnBaseUrl:this.config.cdnBase,encryptQueryParam:g.media.encrypt_query_param,fullUrl:g.media.full_url,aesKeyBase64:g.media.aes_key,fetchFn:e}),C=`${ge}/${Date.now()}-${Pe(4).toString("hex")}.mp4`;await ke(C,w),h.push({path:C,mime:"video/mp4"})}}catch(g){A("warn",`Failed to download quoted media type=${y.type}: ${String(g)}`,this.config)}if(!c&&h.length===0){A("debug",`Non-text/media message from ${u.from_user_id}, skipping`,this.config);continue}let _=`wechat:${u.from_user_id}`,b=this.sessions.get(_);b?u.context_token&&(b.contextToken=u.context_token):this.sessions.set(_,{toUser:u.from_user_id,contextToken:u.context_token,cursor:""}),A("info",`Ingress from ${u.from_user_id} text=${JSON.stringify(c.slice(0,80))} attachments=${h.length}`,this.config),this.getTypingTicket(u.from_user_id,u.context_token,e).then(g=>{if(!g)return;let w=this.sessions.get(_);w&&(w.stopTyping?.(),w.stopTyping=this.startTyping(u.from_user_id,g,e))});try{await fo(this.config.daemonUrl,{session_key:_,text:c||void 0,attachments:h,idempotency_key:String(u.message_id),source_kind:"wechat",channel_id:`wechat-${u.from_user_id.replace(/[^A-Za-z0-9_-]/g,"_")}`},e)}catch(g){A("error",`ingress failed for ${_}: ${String(g)}`,this.config)}}}catch(n){if(n?.name==="AbortError")return;if(r++,n instanceof Z&&n.errcode===-14){A("warn","Token invalid (-14), triggering re-login",this.config),this.auth.invalidateToken(),r=0;continue}A("error",`ingressLoop error (${r}): ${String(n)}`,this.config),r>=un&&(A("warn",`Backing off ${Po}ms after ${un} errors`,this.config),await Ut(Po),r=0)}}}async pullLoop(e){A("info","pullLoop started (WebSocket mode)",this.config);let r="wechat:__cap_heartbeat__",n;n=null;let i=()=>{n||(A("debug","Registering capability heartbeat WS",this.config),n=Xr({daemonUrl:this.config.daemonUrl,sessionKey:r,consumerId:To,sourceKind:"wechat",onOutput:async()=>{},onAck:()=>{},onError:()=>{},onClose:()=>{n=null,this.running&&setTimeout(i,ko)}}))};i();let s=new Map,o=new Map,a=(c,h)=>{if(s.has(c))return;A("info",`WS subscribing for ${c}`,this.config);let y=Xr({daemonUrl:this.config.daemonUrl,sessionKey:c,consumerId:To,cursor:h.cursor||void 0,sourceKind:"wechat",onOutput:async _=>{let b=await this.auth.getToken(),g=this.auth.getApiBase(),w=this.filterOutboundText(_.text??""),C=_.attachments??[],E=C.length===0?Hf(_):[];if(C.length>0)for(let x=0;x<C.length;x++){let I=C[x],O=x===C.length-1,N=O?w:"";A("info",`Sending attachment to ${h.toUser}: ${I.path} (${I.mime})`,this.config);try{let v=await co(this.config.daemonUrl,I.path,e),L=I.mime.startsWith("image/"),G=I.mime.startsWith("audio/"),z=I.mime.startsWith("video/");if(G){let{silk:U,playtimeMs:F}=await ln(v,I.mime),X=await this.withRetry(()=>ft({apiBase:g,cdnBase:this.config.cdnBase,token:b,filePath:U,toUserId:h.toUser,mediaType:Kr,fetchFn:e}),"uploadMedia(voice)");await this.withRetry(()=>le(g,b,h.toUser,N,h.contextToken,e,{kind:"voice",item:{encryptQueryParam:X.encryptQueryParam,aesKeyBase64:X.aesKeyBase64,playtimeMs:F}}),"sendMessage(voice)")}else{let U=await this.withRetry(()=>ft({apiBase:g,cdnBase:this.config.cdnBase,token:b,filePath:v,toUserId:h.toUser,mediaType:L?vt:z?Vr:Jr,fetchFn:e}),L?"uploadMedia(image)":z?"uploadMedia(video)":"uploadMedia(file)"),F=Ft(I.path)||"file";await this.withRetry(()=>le(g,b,h.toUser,N,h.contextToken,e,L?{encryptQueryParam:U.encryptQueryParam,aesKeyBase64:U.aesKeyBase64,midSize:U.fileSizeCiphertext}:z?{kind:"video",item:{encryptQueryParam:U.encryptQueryParam,aesKeyBase64:U.aesKeyBase64,videoSize:U.fileSizeCiphertext}}:{kind:"file",item:{encryptQueryParam:U.encryptQueryParam,aesKeyBase64:U.aesKeyBase64,fileName:F,fileSize:U.rawSize}}),L?"sendMessage(image)":z?"sendMessage(video)":"sendMessage(file)")}}catch(v){v instanceof Z&&v.errcode===-14&&this.auth.invalidateToken(),A("error",`sendAttachment failed to ${h.toUser}: ${String(v)}`,this.config),O&&_.text&&await this.withRetry(()=>le(g,b,h.toUser,w,h.contextToken,e),"sendMessage(fallback)").catch(L=>A("error",`sendMessage fallback failed: ${String(L)}`,this.config))}}else if(E.length>0)for(let x=0;x<E.length;x++){let I=E[x],O=x===E.length-1,N=O?w:"";try{let v=zf(I),L=v?void 0:await this.downloadRemoteMedia(I,e),G=L?.buffer,z=v?ht(v):L?.mime??"application/octet-stream",U=z.startsWith("image/"),F=z.startsWith("audio/"),X=z.startsWith("video/");if(F){let Ne=G??await this.readLocalMedia(v),{silk:J,playtimeMs:$e}=await ln(Ne,z),Se=await this.withRetry(()=>ft({apiBase:g,cdnBase:this.config.cdnBase,token:b,filePath:J,toUserId:h.toUser,mediaType:Kr,fetchFn:e}),"uploadMedia(voice-url)");await this.withRetry(()=>le(g,b,h.toUser,N,h.contextToken,e,{kind:"voice",item:{encryptQueryParam:Se.encryptQueryParam,aesKeyBase64:Se.aesKeyBase64,playtimeMs:$e}}),"sendMessage(voice-url)")}else{let Ne=G??v,J=await this.withRetry(()=>ft({apiBase:g,cdnBase:this.config.cdnBase,token:b,filePath:Ne,toUserId:h.toUser,mediaType:U?vt:X?Vr:Jr,fetchFn:e}),U?"uploadMedia(image-url)":X?"uploadMedia(video-url)":"uploadMedia(file-url)"),$e=v?Ft(v):L?.fileName??Ft(I.split("?")[0]??"file");await this.withRetry(()=>le(g,b,h.toUser,N,h.contextToken,e,U?{encryptQueryParam:J.encryptQueryParam,aesKeyBase64:J.aesKeyBase64,midSize:J.fileSizeCiphertext}:X?{kind:"video",item:{encryptQueryParam:J.encryptQueryParam,aesKeyBase64:J.aesKeyBase64,videoSize:J.fileSizeCiphertext}}:{kind:"file",item:{encryptQueryParam:J.encryptQueryParam,aesKeyBase64:J.aesKeyBase64,fileName:$e,fileSize:J.rawSize}}),U?"sendMessage(image-url)":X?"sendMessage(video-url)":"sendMessage(file-url)")}}catch(v){v instanceof Z&&v.errcode===-14&&this.auth.invalidateToken(),A("error",`sendMediaUrl failed to ${h.toUser}: ${String(v)}`,this.config),O&&_.text&&await this.withRetry(()=>le(g,b,h.toUser,w,h.contextToken,e),"sendMessage(mediaUrl-fallback)").catch(L=>A("error",`sendMessage mediaUrl fallback failed: ${String(L)}`,this.config))}}else if(w){A("info",`Sending reply to ${h.toUser}: ${w.slice(0,60)}`,this.config);try{await this.withRetry(()=>le(g,b,h.toUser,w,h.contextToken,e),"sendMessage(text)")}catch(x){x instanceof Z&&x.errcode===-14&&this.auth.invalidateToken(),A("error",`sendMessage failed to ${h.toUser}: ${String(x)}`,this.config),this.outbox&&await this.outbox.enqueue({sessionKey:c,toUser:h.toUser,contextToken:h.contextToken,text:w,attachments:[]}).catch(I=>A("warn",`outbox.enqueue failed: ${String(I)}`,this.config))}}h.stopTyping&&(h.stopTyping(),h.stopTyping=void 0)},onAck:_=>{h.cursor=_,o.set(c,0)},onError:_=>{let b=(o.get(c)??0)+1;o.set(c,b),A("error",`WS error for ${c} (${b}): ${String(_)}`,this.config)},onClose:()=>{if(s.delete(c),!this.running)return;let b=(o.get(c)??0)>=un?qf:ko;A("info",`WS closed for ${c}, reconnecting in ${b}ms`,this.config),setTimeout(()=>{if(this.running&&this.sessions.has(c)){let g=this.sessions.get(c);a(c,g)}},b)}});s.set(c,y)};for(;this.running;){for(let[c,h]of this.sessions)a(c,h);for(let[c,h]of s)this.sessions.has(c)||(h(),s.delete(c));await Ut(1e3,this.abortController.signal)}let u=n;n=null,u?.();for(let c of s.values())c();s.clear()}async getTypingTicket(e,r,n){let i=this.typingTickets.get(e);if(i&&Date.now()-i.fetchedAt<this.TYPING_TICKET_TTL_MS)return i.ticket;try{let s=await this.auth.getToken(),o=await Hn(this.auth.getApiBase(),s,e,r,n);if(o.typing_ticket)return this.typingTickets.set(e,{ticket:o.typing_ticket,fetchedAt:Date.now()}),o.typing_ticket}catch(s){A("debug",`getTypingTicket failed for ${e}: ${String(s)}`,this.config)}}startTyping(e,r,n){let i=async o=>{try{let a=await this.auth.getToken();await zn(this.auth.getApiBase(),a,e,r,o,n)}catch{}};i(1);let s=setInterval(()=>{i(1)},5e3);return()=>{clearInterval(s),i(2)}}async readLocalMedia(e){return Uf(e)}async downloadRemoteMedia(e,r){let n=await r(e);if(!n.ok){let a=await n.text().catch(()=>"(unreadable)");throw new Error(`Remote media download failed: ${n.status} ${n.statusText} body=${a}`)}let s=n.headers?.get("content-type")?.split(";")[0]?.trim().toLowerCase()||ht(new URL(e).pathname),o=Qf(e,s);return{buffer:Buffer.from(await n.arrayBuffer()),mime:s,fileName:o}}filterOutboundText(e){let r=new $t;return r.feed(e)+r.flush()}async withRetry(e,r,n={}){let i=n.maxAttempts??3,s=n.baseMs??500,o;for(let a=1;a<=i;a++)try{return await e()}catch(u){if(o=u,u instanceof Z&&[-14,400,403].includes(u.errcode))throw u;if(a<i){let c=s*Math.pow(2,a-1);A("warn",`${r} attempt ${a}/${i} failed, retry in ${c}ms: ${String(u)}`,this.config),await Ut(c)}}throw o}async replayOutbox(e){if(!this.outbox)return;await Ut(5e3);let r=await this.outbox.getPending();if(r.length!==0){A("info",`Replaying ${r.length} outbox pending records`,this.config);for(let n of r){if(!this.running)break;try{let i=await this.auth.getToken(),s=this.auth.getApiBase();await this.withRetry(()=>le(s,i,n.toUser,n.text,n.contextToken,e),"outbox.replay"),await this.outbox.markSent(n.id),A("info",`Outbox replayed ${n.id} to ${n.toUser}`,this.config)}catch(i){await this.outbox.markFailed(n.id,String(i)),A("warn",`Outbox replay failed for ${n.id}: ${String(i)}`,this.config)}}}}isAllowed(e){return this.config.dmPolicy==="open"?!0:this.config.allowFrom.includes(e)}};function ht(t){let e=fn(t).toLowerCase();return{".pdf":"application/pdf",".doc":"application/msword",".docx":"application/vnd.openxmlformats-officedocument.wordprocessingml.document",".xls":"application/vnd.ms-excel",".xlsx":"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",".ppt":"application/vnd.ms-powerpoint",".pptx":"application/vnd.openxmlformats-officedocument.presentationml.presentation",".zip":"application/zip",".txt":"text/plain",".csv":"text/csv",".json":"application/json",".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".webp":"image/webp",".mp4":"video/mp4",".mov":"video/quicktime",".mp3":"audio/mpeg",".m4a":"audio/mp4",".wav":"audio/wav"}[e]??"application/octet-stream"}function jf(t){return{"application/pdf":".pdf","application/msword":".doc","application/vnd.openxmlformats-officedocument.wordprocessingml.document":".docx","application/vnd.ms-excel":".xls","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet":".xlsx","application/vnd.ms-powerpoint":".ppt","application/vnd.openxmlformats-officedocument.presentationml.presentation":".pptx","application/zip":".zip","text/plain":".txt","text/csv":".csv","application/json":".json","image/png":".png","image/jpeg":".jpg","image/gif":".gif","image/webp":".webp","video/mp4":".mp4","video/quicktime":".mov","audio/mpeg":".mp3","audio/mp4":".m4a","audio/wav":".wav"}[t]}function Qf(t,e){let r=new URL(t).pathname,n=Ft(r)||"file";if(ht(n)!=="application/octet-stream")return n;let i=jf(e);return i?`${n}${i}`:n}function Ut(t,e){return new Promise(r=>{let n=setTimeout(r,t);e?.addEventListener("abort",()=>{clearTimeout(n),r()},{once:!0})})}import Gf from"node:http";function xo(t,e){let r=Gf.createServer((n,i)=>{if(n.method!=="GET"||n.url!=="/health"){i.writeHead(404),i.end("Not Found");return}if(!t.running){i.writeHead(503,{"Content-Type":"application/json"}),i.end(JSON.stringify({status:"unavailable",reason:"gateway_stopped"}));return}let s=t.tokenObtainedAt>0?Date.now()-t.tokenObtainedAt:1/0;if(s>72e6){i.writeHead(503,{"Content-Type":"application/json"}),i.end(JSON.stringify({status:"token_stale",token_age_hours:Math.floor(s/36e5)}));return}i.writeHead(200,{"Content-Type":"application/json"}),i.end(JSON.stringify({status:"ok",uptime_seconds:Math.floor(process.uptime()),token_age_hours:Math.floor(s/36e5)}))});return r.listen(e,()=>{console.log(`[INFO] [wechat-channel] Health check listening on :${e}/health`)}),r}import{appendFile as Yf,readFile as Vf,writeFile as Jf,mkdir as Bo,rename as Kf}from"node:fs/promises";import{existsSync as Zf}from"node:fs";import{dirname as Ro}from"node:path";import{randomBytes as Xf}from"node:crypto";var ec=3,Dt=class{constructor(e){this.filePath=e}writeChain=Promise.resolve();async enqueue(e){let r=Xf(8).toString("hex"),n={...e,id:r,createdAt:Date.now(),attempts:0},i=JSON.stringify(n)+`
|
|
62
|
+
`;return this.writeChain=this.writeChain.then(async()=>{await Bo(Ro(this.filePath),{recursive:!0}),await Yf(this.filePath,i,"utf8")}),await this.writeChain,r}async getPending(e=ec){return(await this.readAll()).filter(n=>n.attempts<e).sort((n,i)=>n.createdAt-i.createdAt)}async markSent(e){await this.rewrite(r=>r.filter(n=>n.id!==e))}async markFailed(e,r){await this.rewrite(n=>n.map(i=>i.id===e?{...i,attempts:i.attempts+1,lastError:r}:i))}async readAll(){if(!Zf(this.filePath))return[];let e=await Vf(this.filePath,"utf8"),r=[];for(let n of e.split(`
|
|
63
|
+
`)){let i=n.trim();if(i)try{r.push(JSON.parse(i))}catch{}}return r}async rewrite(e){this.writeChain=this.writeChain.then(async()=>{await Bo(Ro(this.filePath),{recursive:!0});let r=await this.readAll(),n=e(r),i=n.map(o=>JSON.stringify(o)).join(`
|
|
48
64
|
`)+(n.length>0?`
|
|
49
|
-
`:""),
|
|
50
|
-
[INFO] [wechat-channel] Received ${u}, shutting down\u2026`),
|
|
65
|
+
`:""),s=this.filePath+".tmp";await Jf(s,i,"utf8"),await Kf(s,this.filePath)}),await this.writeChain}};var Wt="/tmp/channel-wechat.pid";function ac(){if(ic(Wt)){let t=parseInt(rc(Wt,"utf-8").trim(),10);try{process.kill(t,0),console.error(`[ERROR] Another channel-wechat process is already running (PID ${t}). Exiting.`),process.exit(1)}catch{console.warn(`[WARN] Stale pidfile found (PID ${t} is dead), overwriting.`)}}tc(Wt,String(process.pid),"utf-8")}function cn(){try{nc(Wt)}catch{}}function lc(t){for(let e=0;e<t.length;e+=1){let r=t[e];if(r==="--state-dir")return t[e+1];if(r.startsWith("--state-dir="))return r.slice(12)}}async function uc(t){let e=lc(t)??tr();await io(e)}async function fc(){ac();let t;try{t=$n()}catch(u){cn(),console.error(`[ERROR] Configuration error: ${String(u)}`),process.exit(1)}console.log("[INFO] [wechat-channel] Starting openduo WeChat channel adapter"),console.log(`[INFO] [wechat-channel] Daemon: ${t.daemonUrl}`),console.log(`[INFO] [wechat-channel] DM policy: ${t.dmPolicy}`),console.log(`[INFO] [wechat-channel] State dir: ${t.stateDir}`);let e=new It(t.stateDir,t.apiBase);try{await e.getToken()}catch(u){console.error(`[ERROR] Authentication failed: ${String(u)}`),process.exit(1)}let r=new Dt(sc(t.stateDir,"outbox.jsonl")),n=new qt(t,e,fetch,r);n.start();let i=parseInt(process.env.WECHAT_HEALTH_PORT??"8765",10),s={running:!0,tokenObtainedAt:e.tokenObtainedAt},o=xo(s,i),a=setInterval(()=>{s.tokenObtainedAt=e.tokenObtainedAt},6e4);for(let u of["SIGINT","SIGTERM"])process.on(u,()=>{console.log(`
|
|
66
|
+
[INFO] [wechat-channel] Received ${u}, shutting down\u2026`),s.running=!1,clearInterval(a),o.close(),n.stop(),cn(),process.exit(0)});process.on("exit",cn)}async function cc(t=process.argv.slice(2)){let[e,...r]=t;if(e==="qrcode-terminal"){await uc(r);return}await fc()}var Ao=process.argv[1],hc=!!Ao&&import.meta.url===oc(Ao).href;hc&&cc().catch(t=>{console.error("[FATAL]",t),process.exit(1)});export{cc as runCli};
|