@openduo/channel-wechat 0.1.0
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 +94 -0
- package/dist/plugin.js +50 -0
- package/package.json +60 -0
package/README.md
ADDED
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
# @openduo/channel-wechat
|
|
2
|
+
|
|
3
|
+
WeChat channel plugin for [duoduo](https://openduo.ai) — connects WeChat (via ilink bot API) to your duoduo agent.
|
|
4
|
+
|
|
5
|
+
## How it works
|
|
6
|
+
|
|
7
|
+
1. Clone this repo, install dependencies, and start the adapter
|
|
8
|
+
2. If no valid session exists, the process outputs: `QRCODE_READY:/path/to/qrcode.png`
|
|
9
|
+
3. A Feishu Agent (duoduo) reads this signal, fetches the PNG, and sends it to the user via Feishu
|
|
10
|
+
4. The user scans the QR code with WeChat
|
|
11
|
+
5. The process outputs: `WECHAT_CONNECTED:<botId>` — the channel is live
|
|
12
|
+
6. All WeChat messages are forwarded to the openduo daemon and responses are sent back
|
|
13
|
+
|
|
14
|
+
**The entire onboarding flow happens inside Feishu — no terminal access required.**
|
|
15
|
+
|
|
16
|
+
## Install
|
|
17
|
+
|
|
18
|
+
```bash
|
|
19
|
+
duoduo channel install @openduo/channel-wechat
|
|
20
|
+
```
|
|
21
|
+
|
|
22
|
+
For a local tarball:
|
|
23
|
+
|
|
24
|
+
```bash
|
|
25
|
+
npm pack
|
|
26
|
+
duoduo channel install ./openduo-channel-wechat-0.1.0.tgz
|
|
27
|
+
```
|
|
28
|
+
|
|
29
|
+
## Quickstart
|
|
30
|
+
|
|
31
|
+
```bash
|
|
32
|
+
gh repo clone winfred5432/channel-wechat
|
|
33
|
+
cd channel-wechat
|
|
34
|
+
npm ci
|
|
35
|
+
npm run build:plugin
|
|
36
|
+
cp .env.example .env
|
|
37
|
+
# edit .env if needed
|
|
38
|
+
npm start
|
|
39
|
+
```
|
|
40
|
+
|
|
41
|
+
The agent monitors stdout for `QRCODE_READY:` and `WECHAT_CONNECTED:` signals.
|
|
42
|
+
|
|
43
|
+
## Environment Variables
|
|
44
|
+
|
|
45
|
+
| Variable | Default | Description |
|
|
46
|
+
|----------|---------|-------------|
|
|
47
|
+
| `ALADUO_DAEMON_URL` | `http://127.0.0.1:20233` | openduo daemon RPC URL |
|
|
48
|
+
| `WECHAT_API_BASE` | `https://ilinkai.weixin.qq.com` | ilink bot API base URL |
|
|
49
|
+
| `WECHAT_DM_POLICY` | `open` | `open` (all users) or `allowlist` |
|
|
50
|
+
| `WECHAT_ALLOW_FROM` | — | Comma-separated WeChat userIds (allowlist mode only) |
|
|
51
|
+
| `WECHAT_STATE_DIR` | `~/.openduo/wechat-channel` | Persisted token and sync cursor |
|
|
52
|
+
| `WECHAT_LOG_LEVEL` | `info` | `error` \| `warn` \| `info` \| `debug` |
|
|
53
|
+
|
|
54
|
+
## Architecture
|
|
55
|
+
|
|
56
|
+
```
|
|
57
|
+
WeChat (ilink bot API)
|
|
58
|
+
│
|
|
59
|
+
▼
|
|
60
|
+
[channel-wechat]
|
|
61
|
+
┌─────────────────────────────────────┐
|
|
62
|
+
│ auth.ts — QR login state machine │
|
|
63
|
+
│ wechat.ts — ilink HTTP client │
|
|
64
|
+
│ gateway.ts — ingress + pull loops │
|
|
65
|
+
│ daemon.ts — openduo RPC client │
|
|
66
|
+
└─────────────────────────────────────┘
|
|
67
|
+
│
|
|
68
|
+
▼
|
|
69
|
+
openduo daemon ←→ Claude / Agent
|
|
70
|
+
```
|
|
71
|
+
|
|
72
|
+
## State Directory
|
|
73
|
+
|
|
74
|
+
Default: `~/.openduo/wechat-channel/`
|
|
75
|
+
|
|
76
|
+
| File | Description |
|
|
77
|
+
|------|-------------|
|
|
78
|
+
| `credentials.json` | Auth token (chmod 600) |
|
|
79
|
+
| `sync-buf.txt` | Message cursor for getupdates |
|
|
80
|
+
| `qrcode.png` | Temporary — deleted after scan |
|
|
81
|
+
|
|
82
|
+
## Development
|
|
83
|
+
|
|
84
|
+
```bash
|
|
85
|
+
npm ci
|
|
86
|
+
npm run dev # run with tsx (hot reload friendly)
|
|
87
|
+
npm test # vitest unit tests
|
|
88
|
+
npm run test:coverage # coverage report
|
|
89
|
+
npm run build # bundle dist/plugin.js
|
|
90
|
+
```
|
|
91
|
+
|
|
92
|
+
## License
|
|
93
|
+
|
|
94
|
+
MIT
|
package/dist/plugin.js
ADDED
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
#!/usr/bin/env node
|
|
3
|
+
import { createRequire as __createRequire } from "node:module";
|
|
4
|
+
const require = __createRequire(import.meta.url);
|
|
5
|
+
var Ks=Object.create;var Tn=Object.defineProperty;var Qs=Object.getOwnPropertyDescriptor;var Zs=Object.getOwnPropertyNames;var Xs=Object.getPrototypeOf,ea=Object.prototype.hasOwnProperty;var $=(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 k=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports);var ta=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of Zs(e))!ea.call(t,i)&&i!==r&&Tn(t,i,{get:()=>e[i],enumerable:!(n=Qs(e,i))||n.enumerable});return t};var kn=(t,e,r)=>(r=t!=null?Ks(Xs(t)):{},ta(e||!t||!t.__esModule?Tn(r,"default",{value:t,enumerable:!0}):r,t));var zt=k(($f,Ln)=>{Ln.exports=function(){return typeof Promise=="function"&&Promise.prototype&&Promise.prototype.then}});var fe=k(Te=>{var jt,sa=[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];Te.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};Te.getSymbolTotalCodewords=function(e){return sa[e]};Te.getBCHDigit=function(t){let e=0;for(;t!==0;)e++,t>>>=1;return e};Te.setToSJISFunction=function(e){if(typeof e!="function")throw new Error('"toSJISFunc" is not a valid function.');jt=e};Te.isKanjiModeEnabled=function(){return typeof jt<"u"};Te.toSJIS=function(e){return jt(e)}});var lt=k(Q=>{Q.L={bit:1};Q.M={bit:0};Q.Q={bit:3};Q.H={bit:2};function aa(t){if(typeof t!="string")throw new Error("Param is not a string");switch(t.toLowerCase()){case"l":case"low":return Q.L;case"m":case"medium":return Q.M;case"q":case"quartile":return Q.Q;case"h":case"high":return Q.H;default:throw new Error("Unknown EC Level: "+t)}}Q.isValid=function(e){return e&&typeof e.bit<"u"&&e.bit>=0&&e.bit<4};Q.from=function(e,r){if(Q.isValid(e))return e;try{return aa(e)}catch{return r}}});var Fn=k((Wf,Nn)=>{function Mn(){this.buffer=[],this.length=0}Mn.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++}};Nn.exports=Mn});var $n=k((Hf,Un)=>{function He(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)}He.prototype.set=function(t,e,r,n){let i=t*this.size+e;this.data[i]=r,n&&(this.reservedBit[i]=!0)};He.prototype.get=function(t,e){return this.data[t*this.size+e]};He.prototype.xor=function(t,e,r){this.data[t*this.size+e]^=r};He.prototype.isReserved=function(t,e){return this.reservedBit[t*this.size+e]};Un.exports=He});var qn=k(ut=>{var la=fe().getSymbolSize;ut.getRowColCoords=function(e){if(e===1)return[];let r=Math.floor(e/7)+2,n=la(e),i=n===145?26:Math.ceil((n-13)/(2*r-2))*2,o=[n-7];for(let s=1;s<r-1;s++)o[s]=o[s-1]-i;return o.push(6),o.reverse()};ut.getPositions=function(e){let r=[],n=ut.getRowColCoords(e),i=n.length;for(let o=0;o<i;o++)for(let s=0;s<i;s++)o===0&&s===0||o===0&&s===i-1||o===i-1&&s===0||r.push([n[o],n[s]]);return r}});var Hn=k(Wn=>{var ua=fe().getSymbolSize,Dn=7;Wn.getPositions=function(e){let r=ua(e);return[[0,0],[r-Dn,0],[0,r-Dn]]}});var zn=k(O=>{O.Patterns={PATTERN000:0,PATTERN001:1,PATTERN010:2,PATTERN011:3,PATTERN100:4,PATTERN101:5,PATTERN110:6,PATTERN111:7};var ke={N1:3,N2:3,N3:40,N4:10};O.isValid=function(e){return e!=null&&e!==""&&!isNaN(e)&&e>=0&&e<=7};O.from=function(e){return O.isValid(e)?parseInt(e,10):void 0};O.getPenaltyN1=function(e){let r=e.size,n=0,i=0,o=0,s=null,a=null;for(let u=0;u<r;u++){i=o=0,s=a=null;for(let c=0;c<r;c++){let h=e.get(u,c);h===s?i++:(i>=5&&(n+=ke.N1+(i-5)),s=h,i=1),h=e.get(c,u),h===a?o++:(o>=5&&(n+=ke.N1+(o-5)),a=h,o=1)}i>=5&&(n+=ke.N1+(i-5)),o>=5&&(n+=ke.N1+(o-5))}return n};O.getPenaltyN2=function(e){let r=e.size,n=0;for(let i=0;i<r-1;i++)for(let o=0;o<r-1;o++){let s=e.get(i,o)+e.get(i,o+1)+e.get(i+1,o)+e.get(i+1,o+1);(s===4||s===0)&&n++}return n*ke.N2};O.getPenaltyN3=function(e){let r=e.size,n=0,i=0,o=0;for(let s=0;s<r;s++){i=o=0;for(let a=0;a<r;a++)i=i<<1&2047|e.get(s,a),a>=10&&(i===1488||i===93)&&n++,o=o<<1&2047|e.get(a,s),a>=10&&(o===1488||o===93)&&n++}return n*ke.N3};O.getPenaltyN4=function(e){let r=0,n=e.data.length;for(let o=0;o<n;o++)r+=e.data[o];return Math.abs(Math.ceil(r*100/n/5)-10)*ke.N4};function fa(t,e,r){switch(t){case O.Patterns.PATTERN000:return(e+r)%2===0;case O.Patterns.PATTERN001:return e%2===0;case O.Patterns.PATTERN010:return r%3===0;case O.Patterns.PATTERN011:return(e+r)%3===0;case O.Patterns.PATTERN100:return(Math.floor(e/2)+Math.floor(r/3))%2===0;case O.Patterns.PATTERN101:return e*r%2+e*r%3===0;case O.Patterns.PATTERN110:return(e*r%2+e*r%3)%2===0;case O.Patterns.PATTERN111:return(e*r%3+(e+r)%2)%2===0;default:throw new Error("bad maskPattern:"+t)}}O.applyMask=function(e,r){let n=r.size;for(let i=0;i<n;i++)for(let o=0;o<n;o++)r.isReserved(o,i)||r.xor(o,i,fa(e,o,i))};O.getBestMask=function(e,r){let n=Object.keys(O.Patterns).length,i=0,o=1/0;for(let s=0;s<n;s++){r(s),O.applyMask(s,e);let a=O.getPenaltyN1(e)+O.getPenaltyN2(e)+O.getPenaltyN3(e)+O.getPenaltyN4(e);O.applyMask(s,e),a<o&&(o=a,i=s)}return i}});var Yt=k(Gt=>{var ce=lt(),ft=[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],ct=[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];Gt.getBlocksCount=function(e,r){switch(r){case ce.L:return ft[(e-1)*4+0];case ce.M:return ft[(e-1)*4+1];case ce.Q:return ft[(e-1)*4+2];case ce.H:return ft[(e-1)*4+3];default:return}};Gt.getTotalCodewordsCount=function(e,r){switch(r){case ce.L:return ct[(e-1)*4+0];case ce.M:return ct[(e-1)*4+1];case ce.Q:return ct[(e-1)*4+2];case ce.H:return ct[(e-1)*4+3];default:return}}});var jn=k(dt=>{var ze=new Uint8Array(512),ht=new Uint8Array(256);(function(){let e=1;for(let r=0;r<255;r++)ze[r]=e,ht[e]=r,e<<=1,e&256&&(e^=285);for(let r=255;r<512;r++)ze[r]=ze[r-255]})();dt.log=function(e){if(e<1)throw new Error("log("+e+")");return ht[e]};dt.exp=function(e){return ze[e]};dt.mul=function(e,r){return e===0||r===0?0:ze[ht[e]+ht[r]]}});var Gn=k(je=>{var Jt=jn();je.mul=function(e,r){let n=new Uint8Array(e.length+r.length-1);for(let i=0;i<e.length;i++)for(let o=0;o<r.length;o++)n[i+o]^=Jt.mul(e[i],r[o]);return n};je.mod=function(e,r){let n=new Uint8Array(e);for(;n.length-r.length>=0;){let i=n[0];for(let s=0;s<r.length;s++)n[s]^=Jt.mul(r[s],i);let o=0;for(;o<n.length&&n[o]===0;)o++;n=n.slice(o)}return n};je.generateECPolynomial=function(e){let r=new Uint8Array([1]);for(let n=0;n<e;n++)r=je.mul(r,new Uint8Array([1,Jt.exp(n)]));return r}});var Vn=k((Kf,Jn)=>{var Yn=Gn();function Vt(t){this.genPoly=void 0,this.degree=t,this.degree&&this.initialize(this.degree)}Vt.prototype.initialize=function(e){this.degree=e,this.genPoly=Yn.generateECPolynomial(this.degree)};Vt.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=Yn.mod(r,this.genPoly),i=this.degree-n.length;if(i>0){let o=new Uint8Array(this.degree);return o.set(n,i),o}return n};Jn.exports=Vt});var Kt=k(Kn=>{Kn.isValid=function(e){return!isNaN(e)&&e>=1&&e<=40}});var Qt=k(le=>{var Qn="[0-9]+",ca="[A-Z $%*+\\-./:]+",Ge="(?:[u3000-u303F]|[u3040-u309F]|[u30A0-u30FF]|[uFF00-uFFEF]|[u4E00-u9FAF]|[u2605-u2606]|[u2190-u2195]|u203B|[u2010u2015u2018u2019u2025u2026u201Cu201Du2225u2260]|[u0391-u0451]|[u00A7u00A8u00B1u00B4u00D7u00F7])+";Ge=Ge.replace(/u/g,"\\u");var ha="(?:(?![A-Z0-9 $%*+\\-./:]|"+Ge+`)(?:.|[\r
|
|
6
|
+
]))+`;le.KANJI=new RegExp(Ge,"g");le.BYTE_KANJI=new RegExp("[^A-Z0-9 $%*+\\-./:]+","g");le.BYTE=new RegExp(ha,"g");le.NUMERIC=new RegExp(Qn,"g");le.ALPHANUMERIC=new RegExp(ca,"g");var da=new RegExp("^"+Ge+"$"),pa=new RegExp("^"+Qn+"$"),ga=new RegExp("^[A-Z0-9 $%*+\\-./:]+$");le.testKanji=function(e){return da.test(e)};le.testNumeric=function(e){return pa.test(e)};le.testAlphanumeric=function(e){return ga.test(e)}});var he=k(q=>{var ma=Kt(),Zt=Qt();q.NUMERIC={id:"Numeric",bit:1,ccBits:[10,12,14]};q.ALPHANUMERIC={id:"Alphanumeric",bit:2,ccBits:[9,11,13]};q.BYTE={id:"Byte",bit:4,ccBits:[8,16,16]};q.KANJI={id:"Kanji",bit:8,ccBits:[8,10,12]};q.MIXED={bit:-1};q.getCharCountIndicator=function(e,r){if(!e.ccBits)throw new Error("Invalid mode: "+e);if(!ma.isValid(r))throw new Error("Invalid version: "+r);return r>=1&&r<10?e.ccBits[0]:r<27?e.ccBits[1]:e.ccBits[2]};q.getBestModeForData=function(e){return Zt.testNumeric(e)?q.NUMERIC:Zt.testAlphanumeric(e)?q.ALPHANUMERIC:Zt.testKanji(e)?q.KANJI:q.BYTE};q.toString=function(e){if(e&&e.id)return e.id;throw new Error("Invalid mode")};q.isValid=function(e){return e&&e.bit&&e.ccBits};function ya(t){if(typeof t!="string")throw new Error("Param is not a string");switch(t.toLowerCase()){case"numeric":return q.NUMERIC;case"alphanumeric":return q.ALPHANUMERIC;case"kanji":return q.KANJI;case"byte":return q.BYTE;default:throw new Error("Unknown mode: "+t)}}q.from=function(e,r){if(q.isValid(e))return e;try{return ya(e)}catch{return r}}});var ri=k(Pe=>{var pt=fe(),_a=Yt(),Zn=lt(),de=he(),Xt=Kt(),ei=7973,Xn=pt.getBCHDigit(ei);function wa(t,e,r){for(let n=1;n<=40;n++)if(e<=Pe.getCapacity(n,r,t))return n}function ti(t,e){return de.getCharCountIndicator(t,e)+4}function ba(t,e){let r=0;return t.forEach(function(n){let i=ti(n.mode,e);r+=i+n.getBitsLength()}),r}function Ca(t,e){for(let r=1;r<=40;r++)if(ba(t,r)<=Pe.getCapacity(r,e,de.MIXED))return r}Pe.from=function(e,r){return Xt.isValid(e)?parseInt(e,10):r};Pe.getCapacity=function(e,r,n){if(!Xt.isValid(e))throw new Error("Invalid QR Code version");typeof n>"u"&&(n=de.BYTE);let i=pt.getSymbolTotalCodewords(e),o=_a.getTotalCodewordsCount(e,r),s=(i-o)*8;if(n===de.MIXED)return s;let a=s-ti(n,e);switch(n){case de.NUMERIC:return Math.floor(a/10*3);case de.ALPHANUMERIC:return Math.floor(a/11*2);case de.KANJI:return Math.floor(a/13);case de.BYTE:default:return Math.floor(a/8)}};Pe.getBestVersionForData=function(e,r){let n,i=Zn.from(r,Zn.M);if(Array.isArray(e)){if(e.length>1)return Ca(e,i);if(e.length===0)return 1;n=e[0]}else n=e;return wa(n.mode,n.getLength(),i)};Pe.getEncodedBits=function(e){if(!Xt.isValid(e)||e<7)throw new Error("Invalid QR Code version");let r=e<<12;for(;pt.getBCHDigit(r)-Xn>=0;)r^=ei<<pt.getBCHDigit(r)-Xn;return e<<12|r}});var si=k(oi=>{var er=fe(),ii=1335,Ea=21522,ni=er.getBCHDigit(ii);oi.getEncodedBits=function(e,r){let n=e.bit<<3|r,i=n<<10;for(;er.getBCHDigit(i)-ni>=0;)i^=ii<<er.getBCHDigit(i)-ni;return(n<<10|i)^Ea}});var li=k((rc,ai)=>{var Ta=he();function Be(t){this.mode=Ta.NUMERIC,this.data=t.toString()}Be.getBitsLength=function(e){return 10*Math.floor(e/3)+(e%3?e%3*3+1:0)};Be.prototype.getLength=function(){return this.data.length};Be.prototype.getBitsLength=function(){return Be.getBitsLength(this.data.length)};Be.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 o=this.data.length-r;o>0&&(n=this.data.substr(r),i=parseInt(n,10),e.put(i,o*3+1))};ai.exports=Be});var fi=k((nc,ui)=>{var ka=he(),tr=["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 Ie(t){this.mode=ka.ALPHANUMERIC,this.data=t}Ie.getBitsLength=function(e){return 11*Math.floor(e/2)+6*(e%2)};Ie.prototype.getLength=function(){return this.data.length};Ie.prototype.getBitsLength=function(){return Ie.getBitsLength(this.data.length)};Ie.prototype.write=function(e){let r;for(r=0;r+2<=this.data.length;r+=2){let n=tr.indexOf(this.data[r])*45;n+=tr.indexOf(this.data[r+1]),e.put(n,11)}this.data.length%2&&e.put(tr.indexOf(this.data[r]),6)};ui.exports=Ie});var hi=k((ic,ci)=>{var Pa=he();function Oe(t){this.mode=Pa.BYTE,typeof t=="string"?this.data=new TextEncoder().encode(t):this.data=new Uint8Array(t)}Oe.getBitsLength=function(e){return e*8};Oe.prototype.getLength=function(){return this.data.length};Oe.prototype.getBitsLength=function(){return Oe.getBitsLength(this.data.length)};Oe.prototype.write=function(t){for(let e=0,r=this.data.length;e<r;e++)t.put(this.data[e],8)};ci.exports=Oe});var pi=k((oc,di)=>{var Sa=he(),Aa=fe();function ve(t){this.mode=Sa.KANJI,this.data=t}ve.getBitsLength=function(e){return e*13};ve.prototype.getLength=function(){return this.data.length};ve.prototype.getBitsLength=function(){return ve.getBitsLength(this.data.length)};ve.prototype.write=function(t){let e;for(e=0;e<this.data.length;e++){let r=Aa.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]+`
|
|
7
|
+
Make sure your charset is UTF-8`);r=(r>>>8&255)*192+(r&255),t.put(r,13)}};di.exports=ve});var gi=k((sc,rr)=>{"use strict";var Ye={single_source_shortest_paths:function(t,e,r){var n={},i={};i[e]=0;var o=Ye.PriorityQueue.make();o.push(e,0);for(var s,a,u,c,h,_,g,y,w;!o.empty();){s=o.pop(),a=s.value,c=s.cost,h=t[a]||{};for(u in h)h.hasOwnProperty(u)&&(_=h[u],g=c+_,y=i[u],w=typeof i[u]>"u",(w||y>g)&&(i[u]=g,o.push(u,g),n[u]=a))}if(typeof r<"u"&&typeof i[r]>"u"){var b=["Could not find a path from ",e," to ",r,"."].join("");throw new Error(b)}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=Ye.single_source_shortest_paths(t,e,r);return Ye.extract_shortest_path_from_predecessor_list(n,r)},PriorityQueue:{make:function(t){var e=Ye.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 rr<"u"&&(rr.exports=Ye)});var Ti=k(Le=>{var I=he(),_i=li(),wi=fi(),bi=hi(),Ci=pi(),Je=Qt(),gt=fe(),Ra=gi();function mi(t){return unescape(encodeURIComponent(t)).length}function Ve(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 Ei(t){let e=Ve(Je.NUMERIC,I.NUMERIC,t),r=Ve(Je.ALPHANUMERIC,I.ALPHANUMERIC,t),n,i;return gt.isKanjiModeEnabled()?(n=Ve(Je.BYTE,I.BYTE,t),i=Ve(Je.KANJI,I.KANJI,t)):(n=Ve(Je.BYTE_KANJI,I.BYTE,t),i=[]),e.concat(r,n,i).sort(function(s,a){return s.index-a.index}).map(function(s){return{data:s.data,mode:s.mode,length:s.length}})}function nr(t,e){switch(e){case I.NUMERIC:return _i.getBitsLength(t);case I.ALPHANUMERIC:return wi.getBitsLength(t);case I.KANJI:return Ci.getBitsLength(t);case I.BYTE:return bi.getBitsLength(t)}}function xa(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 Ba(t){let e=[];for(let r=0;r<t.length;r++){let n=t[r];switch(n.mode){case I.NUMERIC:e.push([n,{data:n.data,mode:I.ALPHANUMERIC,length:n.length},{data:n.data,mode:I.BYTE,length:n.length}]);break;case I.ALPHANUMERIC:e.push([n,{data:n.data,mode:I.BYTE,length:n.length}]);break;case I.KANJI:e.push([n,{data:n.data,mode:I.BYTE,length:mi(n.data)}]);break;case I.BYTE:e.push([{data:n.data,mode:I.BYTE,length:mi(n.data)}])}}return e}function Ia(t,e){let r={},n={start:{}},i=["start"];for(let o=0;o<t.length;o++){let s=t[o],a=[];for(let u=0;u<s.length;u++){let c=s[u],h=""+o+u;a.push(h),r[h]={node:c,lastCount:0},n[h]={};for(let _=0;_<i.length;_++){let g=i[_];r[g]&&r[g].node.mode===c.mode?(n[g][h]=nr(r[g].lastCount+c.length,c.mode)-nr(r[g].lastCount,c.mode),r[g].lastCount+=c.length):(r[g]&&(r[g].lastCount=c.length),n[g][h]=nr(c.length,c.mode)+4+I.getCharCountIndicator(c.mode,e))}}i=a}for(let o=0;o<i.length;o++)n[i[o]].end=0;return{map:n,table:r}}function yi(t,e){let r,n=I.getBestModeForData(t);if(r=I.from(e,n),r!==I.BYTE&&r.bit<n.bit)throw new Error('"'+t+'" cannot be encoded with mode '+I.toString(r)+`.
|
|
8
|
+
Suggested mode is: `+I.toString(n));switch(r===I.KANJI&&!gt.isKanjiModeEnabled()&&(r=I.BYTE),r){case I.NUMERIC:return new _i(t);case I.ALPHANUMERIC:return new wi(t);case I.KANJI:return new Ci(t);case I.BYTE:return new bi(t)}}Le.fromArray=function(e){return e.reduce(function(r,n){return typeof n=="string"?r.push(yi(n,null)):n.data&&r.push(yi(n.data,n.mode)),r},[])};Le.fromString=function(e,r){let n=Ei(e,gt.isKanjiModeEnabled()),i=Ba(n),o=Ia(i,r),s=Ra.find_path(o.map,"start","end"),a=[];for(let u=1;u<s.length-1;u++)a.push(o.table[s[u]].node);return Le.fromArray(xa(a))};Le.rawSplit=function(e){return Le.fromArray(Ei(e,gt.isKanjiModeEnabled()))}});var ur=k(ki=>{var yt=fe(),ir=lt(),Oa=Fn(),va=$n(),La=qn(),Ma=Hn(),ar=zn(),lr=Yt(),Na=Vn(),mt=ri(),Fa=si(),Ua=he(),or=Ti();function $a(t,e){let r=t.size,n=Ma.getPositions(e);for(let i=0;i<n.length;i++){let o=n[i][0],s=n[i][1];for(let a=-1;a<=7;a++)if(!(o+a<=-1||r<=o+a))for(let u=-1;u<=7;u++)s+u<=-1||r<=s+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(o+a,s+u,!0,!0):t.set(o+a,s+u,!1,!0))}}function qa(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 Da(t,e){let r=La.getPositions(e);for(let n=0;n<r.length;n++){let i=r[n][0],o=r[n][1];for(let s=-2;s<=2;s++)for(let a=-2;a<=2;a++)s===-2||s===2||a===-2||a===2||s===0&&a===0?t.set(i+s,o+a,!0,!0):t.set(i+s,o+a,!1,!0)}}function Wa(t,e){let r=t.size,n=mt.getEncodedBits(e),i,o,s;for(let a=0;a<18;a++)i=Math.floor(a/3),o=a%3+r-8-3,s=(n>>a&1)===1,t.set(i,o,s,!0),t.set(o,i,s,!0)}function sr(t,e,r){let n=t.size,i=Fa.getEncodedBits(e,r),o,s;for(o=0;o<15;o++)s=(i>>o&1)===1,o<6?t.set(o,8,s,!0):o<8?t.set(o+1,8,s,!0):t.set(n-15+o,8,s,!0),o<8?t.set(8,n-o-1,s,!0):o<9?t.set(8,15-o-1+1,s,!0):t.set(8,15-o-1,s,!0);t.set(n-8,8,1,!0)}function Ha(t,e){let r=t.size,n=-1,i=r-1,o=7,s=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;s<e.length&&(c=(e[s]>>>o&1)===1),t.set(i,a-u,c),o--,o===-1&&(s++,o=7)}if(i+=n,i<0||r<=i){i-=n,n=-n;break}}}function za(t,e,r){let n=new Oa;r.forEach(function(u){n.put(u.mode.bit,4),n.put(u.getLength(),Ua.getCharCountIndicator(u.mode,t)),u.write(n)});let i=yt.getSymbolTotalCodewords(t),o=lr.getTotalCodewordsCount(t,e),s=(i-o)*8;for(n.getLengthInBits()+4<=s&&n.put(0,4);n.getLengthInBits()%8!==0;)n.putBit(0);let a=(s-n.getLengthInBits())/8;for(let u=0;u<a;u++)n.put(u%2?17:236,8);return ja(n,t,e)}function ja(t,e,r){let n=yt.getSymbolTotalCodewords(e),i=lr.getTotalCodewordsCount(e,r),o=n-i,s=lr.getBlocksCount(e,r),a=n%s,u=s-a,c=Math.floor(n/s),h=Math.floor(o/s),_=h+1,g=c-h,y=new Na(g),w=0,b=new Array(s),C=new Array(s),S=0,N=new Uint8Array(t.buffer);for(let L=0;L<s;L++){let j=L<u?h:_;b[L]=N.slice(w,w+j),C[L]=y.encode(b[L]),w+=j,S=Math.max(S,j)}let U=new Uint8Array(n),B=0,W,v;for(W=0;W<S;W++)for(v=0;v<s;v++)W<b[v].length&&(U[B++]=b[v][W]);for(W=0;W<g;W++)for(v=0;v<s;v++)U[B++]=C[v][W];return U}function Ga(t,e,r,n){let i;if(Array.isArray(t))i=or.fromArray(t);else if(typeof t=="string"){let c=e;if(!c){let h=or.rawSplit(t);c=mt.getBestVersionForData(h,r)}i=or.fromString(t,c||40)}else throw new Error("Invalid data");let o=mt.getBestVersionForData(i,r);if(!o)throw new Error("The amount of data is too big to be stored in a QR Code");if(!e)e=o;else if(e<o)throw new Error(`
|
|
9
|
+
The chosen QR Code version cannot contain this amount of data.
|
|
10
|
+
Minimum version required to store current data is: `+o+`.
|
|
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<o;h+=2){a+=c;for(let _=0;_<o;_++){let g=s[h*o+_],y=s[(h+1)*o+_];a+=ru(g,y,i)}a+=c+`
|
|
13
|
+
`}return a+=u.slice(0,-1),typeof r=="function"&&r(null,a),a};_t.renderToFile=function(e,r,n,i){typeof i>"u"&&(i=n,n=void 0);let o=$("fs"),s=_t.render(r,n);o.writeFile(e,s,i)}});var Po=k(ko=>{ko.render=function(t,e,r){let n=t.modules.size,i=t.modules.data,o="\x1B[40m \x1B[0m",s="\x1B[47m \x1B[0m",a="",u=Array(n+3).join(s),c=Array(2).join(s);a+=u+`
|
|
14
|
+
`;for(let h=0;h<n;++h){a+=s;for(let _=0;_<n;_++)a+=i[h*n+_]?o:s;a+=c+`
|
|
15
|
+
`}return a+=u+`
|
|
16
|
+
`,typeof r=="function"&&r(null,a),a}});var xo=k(Ro=>{var nu="\x1B[47m",iu="\x1B[40m",Sr="\x1B[37m",Ar="\x1B[30m",Re="\x1B[0m",ou=nu+Ar,su=iu+Sr,au=function(t,e,r){return{"00":Re+" "+t,"01":Re+e+"\u2584"+t,"02":Re+r+"\u2584"+t,10:Re+e+"\u2580"+t,11:" ",12:"\u2584",20:Re+r+"\u2580"+t,21:"\u2580",22:"\u2588"}},So=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 o=n*e+r;return t[o]?"2":"1"},Ao=function(t,e,r,n){return So(t,e,r,n)+So(t,e,r,n+1)};Ro.render=function(t,e,r){let n=t.modules.size,i=t.modules.data,o=!!(e&&e.inverse),s=e&&e.inverse?su:ou,c=au(s,o?Ar:Sr,o?Sr:Ar),h=Re+`
|
|
17
|
+
`+s,_=s;for(let g=-1;g<n+1;g+=2){for(let y=-1;y<n;y++)_+=c[Ao(i,n,y,g)];_+=c[Ao(i,n,n,g)]+h}return _+=Re,typeof r=="function"&&r(null,_),_}});var Io=k(Bo=>{var lu=Po(),uu=xo();Bo.render=function(t,e,r){return e&&e.small?uu.render(t,e,r):lu.render(t,e,r)}});var xr=k(vo=>{var fu=Qe();function Oo(t,e){let r=t.a/255,n=e+'="'+t.hex+'"';return r<1?n+" "+e+'-opacity="'+r.toFixed(2).slice(1)+'"':n}function Rr(t,e,r){let n=t+e;return typeof r<"u"&&(n+=" "+r),n}function cu(t,e,r){let n="",i=0,o=!1,s=0;for(let a=0;a<t.length;a++){let u=Math.floor(a%e),c=Math.floor(a/e);!u&&!o&&(o=!0),t[a]?(s++,a>0&&u>0&&t[a-1]||(n+=o?Rr("M",u+r,.5+c+r):Rr("m",i,0),i=0,o=!1),u+1<e&&t[a+1]||(n+=Rr("h",s),s=0)):i++}return n}vo.render=function(e,r,n){let i=fu.getOptions(r),o=e.modules.size,s=e.modules.data,a=o+i.margin*2,u=i.color.light.a?"<path "+Oo(i.color.light,"fill")+' d="M0 0h'+a+"v"+a+'H0z"/>':"",c="<path "+Oo(i.color.dark,"stroke")+' d="'+cu(s,o,i.margin)+'"/>',h='viewBox="0 0 '+a+" "+a+'"',g='<svg xmlns="http://www.w3.org/2000/svg" '+(i.width?'width="'+i.width+'" height="'+i.width+'" ':"")+h+' shape-rendering="crispEdges">'+u+c+`</svg>
|
|
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
|
+
`,qe&&(J+=`var destructors = [];
|
|
20
|
+
`);var En=qe?"destructors":"null",Ht="humanName throwBindingError invoker fn runDestructors retType classParam".split(" ");for(ue&&(J+=`var thisWired = classParam['toWireType'](${En}, this);
|
|
21
|
+
`),M=0;M<te;++M)J+=`var arg${M}Wired = argType${M}['toWireType'](${En}, arg${M});
|
|
22
|
+
`,Ht.push(`argType${M}`);if(J+=(Cn||R?"var rv = ":"")+`invoker(${De});
|
|
23
|
+
`,qe)J+=`runDestructors(destructors);
|
|
24
|
+
`;else for(M=ue?1:2;M<P.length;++M)ue=M===1?"thisWired":"arg"+(M-2)+"Wired",P[M].G!==null&&(J+=`${ue}_dtor(${ue});
|
|
25
|
+
`,Ht.push(`${ue}_dtor`));Cn&&(J+=`var ret = retType['fromWireType'](rv);
|
|
26
|
+
return ret;
|
|
27
|
+
`);let[Js,Vs]=[Ht,J+`}
|
|
28
|
+
`];if(P=new Function(...Js,Vs)(...ne),F=Object.defineProperty(P,"name",{value:F}),P=f-1,!r.hasOwnProperty(A))throw new cn("Replacing nonexistent public symbol");return r[A].F!==void 0&&P!==void 0?r[A].F[P]=F:(r[A]=F,r[A].J=P),[]})},b:(l,f,p,d,m)=>{if(f=X(f),m===-1&&(m=4294967295),m=T=>T,d===0){var E=32-8*p;m=T=>T<<E>>>E}var R=f.includes("unsigned")?function(T,A){return A>>>0}:function(T,A){return A};ee(l,{name:f,fromWireType:m,toWireType:R,H:8,readValueFromPointer:an(f,p,d!==0),G:null})},a:(l,f,p)=>{function d(E){return new m(v.buffer,H[E+4>>2],H[E>>2])}var m=[Int8Array,Uint8Array,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array,BigInt64Array,BigUint64Array][f];p=X(p),ee(l,{name:p,fromWireType:d,H:8,readValueFromPointer:d},{K:!0})},n:(l,f)=>{f=X(f),ee(l,{name:f,fromWireType:function(p){for(var d=H[p>>2],m=p+4,E,R=m,T=0;T<=d;++T){var A=m+T;(T==d||L[A]==0)&&(R=R?Ls(R,A-R):"",E===void 0?E=R:(E+="\0",E+=R),R=A+1)}return Ce(p),E},toWireType:function(p,d){d instanceof ArrayBuffer&&(d=new Uint8Array(d));var m,E=typeof d=="string";if(!(E||ArrayBuffer.isView(d)&&d.BYTES_PER_ELEMENT==1))throw new V("Cannot pass non-string to std::string");var R;if(E)for(m=R=0;m<d.length;++m){var T=d.charCodeAt(m);127>=T?R++:2047>=T?R+=2:55296<=T&&57343>=T?(R+=4,++m):R+=3}else R=d.length;if(m=R,R=bn(4+m+1),T=R+4,H[R>>2]=m,E){if(E=T,T=m+1,m=L,0<T){T=E+T-1;for(var A=0;A<d.length;++A){var P=d.charCodeAt(A);if(55296<=P&&57343>=P){var F=d.charCodeAt(++A);P=65536+((P&1023)<<10)|F&1023}if(127>=P){if(E>=T)break;m[E++]=P}else{if(2047>=P){if(E+1>=T)break;m[E++]=192|P>>6}else{if(65535>=P){if(E+2>=T)break;m[E++]=224|P>>12}else{if(E+3>=T)break;m[E++]=240|P>>18,m[E++]=128|P>>12&63}m[E++]=128|P>>6&63}m[E++]=128|P&63}}m[E]=0}}else L.set(d,T);return p!==null&&p.push(Ce,R),R},H:8,readValueFromPointer:$t,G(p){Ce(p)}})},e:(l,f,p)=>{if(p=X(p),f===2)var d=Ms,m=Ns,E=Fs,R=T=>ye[T>>1];else f===4&&(d=Us,m=$s,E=qs,R=T=>H[T>>2]);ee(l,{name:p,fromWireType:T=>{for(var A=H[T>>2],P,F=T+4,ne=0;ne<=A;++ne){var M=T+4+ne*f;(ne==A||R(M)==0)&&(F=d(F,M-F),P===void 0?P=F:(P+="\0",P+=F),F=M+f)}return Ce(T),P},toWireType:(T,A)=>{if(typeof A!="string")throw new V(`Cannot pass non-string to C++ string type ${p}`);var P=E(A),F=bn(4+P+f);return H[F>>2]=P/f,m(A,F+4,P+f),T!==null&&T.push(Ce,F),F},H:8,readValueFromPointer:$t,G(T){Ce(T)}})},f:l=>{ee(l,ln)},p:(l,f)=>{f=X(f),ee(l,{L:!0,name:f,H:0,fromWireType:()=>{},toWireType:()=>{}})},s:()=>{ot=!1,qt=0},i:(l,f,p,d)=>(l=Dt[l],f=Ft(f),l(null,f,p,d)),d:Nt,h:(l,f,p)=>{f=Ws(l,f);var d=f.shift();l--;var m=`return function (obj, func, destructorsRef, args) {
|
|
29
|
+
`,E=0,R=[];p===0&&R.push("obj");for(var T=["retType"],A=[d],P=0;P<l;++P)R.push(`arg${P}`),T.push(`argType${P}`),A.push(f[P]),m+=` var arg${P} = argType${P}.readValueFromPointer(args${E?"+"+E:""});
|
|
30
|
+
`,E+=f[P].H;return m+=` var rv = ${p===1?"new func":"func.call"}(${R.join(", ")});
|
|
31
|
+
`,d.L||(T.push("emval_returnValue"),A.push(Hs),m+=` return emval_returnValue(retType, destructorsRef, rv);
|
|
32
|
+
`),l=new Function(...T,m+`};
|
|
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
|
+
`);let i=Date.now()+480*1e3;for(;Date.now()<i;){await ku(this.pollIntervalMs);let o;try{o=await Bn(this.apiBase,e,this.fetchFn)}catch(s){if(s instanceof K&&s.errcode===-14)return await this.cleanupQrPng(),this.startQrLogin();throw s}if(o.status==="confirmed"&&o.token){let s={token:o.token,botId:o.botId};await this.saveCredentials(s),this.cached=s,this.tokenObtainedAt=Date.now();let a=o.botId??"unknown";return process.stdout.write(`WECHAT_CONNECTED:${a}
|
|
35
|
+
`),await this.cleanupQrPng(),s.token}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 zo(this.syncBufFile,"utf-8")).trim()}catch{return""}}async saveSyncBuf(e){await this.ensureStateDir(),await jo(this.syncBufFile,e,"utf-8")}invalidateToken(){this.cached=null,this.tokenObtainedAt=0,Go(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 zo(this.credFile,"utf-8");return JSON.parse(e)}catch{return null}}async saveCredentials(e){await this.ensureStateDir(),await jo(this.credFile,JSON.stringify(e),"utf-8"),await Eu(this.credFile,384)}async cleanupQrPng(){try{await Go(this.qrcodePng)}catch{}}async ensureStateDir(){Tu(this.stateDir)||await Cu(this.stateDir,{recursive:!0})}};function ku(t){return new Promise(e=>setTimeout(e,t))}import{mkdir as gf,writeFile as At}from"node:fs/promises";import{randomBytes as Rt}from"node:crypto";import{extname as ds}from"node:path";import{createCipheriv as Pu,createDecipheriv as Su,createHash as Au,randomBytes as Mr}from"node:crypto";import{readFile as Ru}from"node:fs/promises";function xu(t,e){let r=Pu("aes-128-ecb",e,null);return Buffer.concat([r.update(t),r.final()])}function Bu(t,e){let r=Su("aes-128-ecb",e,null);return Buffer.concat([r.update(t),r.final()])}function Iu(t){return Math.ceil((t+1)/16)*16}function Ou(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 tt(t){let{cdnBaseUrl:e,encryptQueryParam:r,aesKeyBase64:n,fetchFn:i=fetch}=t,s=`${e.endsWith("/")?e.slice(0,-1):e}/download?encrypted_query_param=${encodeURIComponent(r)}`,a=await i(s);if(!a.ok){let h=await a.text().catch(()=>"(unreadable)");throw new Error(`CDN download failed: ${a.status} ${a.statusText} body=${h}`)}let u=Buffer.from(await a.arrayBuffer()),c=Ou(n);return Bu(u,c)}var Nr=1,Yo=3,Jo=4;async function Fr(t){let{apiBase:e,cdnBase:r,token:n,filePath:i,toUserId:o,mediaType:s=Nr,fetchFn:a=fetch}=t,u=Buffer.isBuffer(i)?i:await Ru(i),c=u.length,h=Au("md5").update(u).digest("hex"),_=Iu(c),g=Mr(16).toString("hex"),y=Mr(16),w=e.endsWith("/")?e:`${e}/`,b=JSON.stringify({filekey:g,media_type:s,to_user_id:o,rawsize:c,rawfilemd5:h,filesize:_,no_need_thumb:!0,aeskey:y.toString("hex"),base_info:{channel_version:"claude-code-1.0"}}),C=Buffer.from(String(Mr(4).readUInt32BE(0))).toString("base64"),S=await a(`${w}ilink/bot/getuploadurl`,{method:"POST",headers:{"Content-Type":"application/json","Content-Length":String(Buffer.byteLength(b,"utf-8")),AuthorizationType:"ilink_bot_token",Authorization:`Bearer ${n}`,"X-WECHAT-UIN":C},body:b});if(!S.ok)throw new Error(`getuploadurl HTTP ${S.status}`);let N=await S.json(),U=N.ret??N.errcode??0;if(U!==0)throw new Error(`getuploadurl error ${U}: ${N.errmsg??"unknown"}`);let B=N.upload_param;if(!B)throw new Error("getuploadurl returned no upload_param");let v=`${r.endsWith("/")?r.slice(0,-1):r}/upload?encrypted_query_param=${encodeURIComponent(B)}&filekey=${encodeURIComponent(g)}`,L=xu(u,y),j=await a(v,{method:"POST",headers:{"Content-Type":"application/octet-stream"},body:new Uint8Array(L)});if(!j.ok){let H=j.headers.get("x-error-message")??`status ${j.status}`;throw new Error(`CDN upload failed: ${H}`)}let ye=j.headers.get("x-encrypted-param");if(!ye)throw new Error("CDN upload response missing x-encrypted-param header");let _e=Buffer.from(y.toString("hex")).toString("base64");return{encryptQueryParam:ye,aesKeyBase64:_e,fileSizeCiphertext:_,rawSize:c}}function Ur(t){return{sessionKey:t.session_key,text:t.payload.text??"",attachments:t.payload.attachments,raw:t}}function $r(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 o;try{o=JSON.parse(i.data)}catch{return}if(o.method==="session.output"){let s=o.params;if(s?.record){let a=Ur(s.record);try{await t.onOutput(a)}finally{if(s.record.id){let u={jsonrpc:"2.0",id:`ack_${n++}`,method:"channel.ack",params:{session_key:t.sessionKey,consumer_id:t.consumerId,cursor:s.record.id}};r.send(JSON.stringify(u)),t.onAck(s.record.id)}}}return}o.error&&t.onError(new Tt(o.error.code,o.error.message))}),r.addEventListener("error",()=>{t.onError(new Error("WebSocket error"))}),r.addEventListener("close",()=>{t.onClose()}),()=>{try{r.close()}catch{}}}var vu=1,Tt=class extends Error{constructor(r,n){super(`DaemonError[${r}]: ${n}`);this.code=r;this.name="DaemonError"}};async function Ko(t,e,r,n=fetch){let o={jsonrpc:"2.0",id:vu++,method:e,params:r},s=await n(`${t}/rpc`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(o)});if(!s.ok)throw new Error(`Daemon HTTP ${s.status} for method ${e}`);let a=await s.json();if(a.error)throw new Tt(a.error.code,a.error.message);return a.result}async function Qo(t,e,r=fetch){await Ko(t,"channel.ingress",e,r)}async function Zo(t,e,r=fetch){let n=await Ko(t,"channel.file.download",{path:e},r);return Buffer.from(n.content_base64,"base64")}import{spawn as Gr}from"node:child_process";import{writeFile as lf,unlink as ss}from"node:fs/promises";import{tmpdir as jr}from"node:os";import{join as as}from"node:path";import{randomBytes as uf}from"node:crypto";var St=16e3;async function ls(t,e){if(e==="audio/silk"||df(t)){let a=pf(t);return{silk:t,playtimeMs:a}}let r=await ff(t),{encode:n}=await Promise.resolve().then(()=>kn(os(),1)),i=await n(r,St),o=Buffer.from(i.data),s=Math.round(r.length/(St*2)*1e3);return{silk:o,playtimeMs:s}}function ff(t){return new Promise((e,r)=>{let n=Gr("ffmpeg",["-v","quiet","-i","pipe:0","-f","s16le","-acodec","pcm_s16le","-ar",String(St),"-ac","1","pipe:1"]),i=[],o=[];n.stdout.on("data",s=>i.push(s)),n.stderr.on("data",s=>o.push(s)),n.on("close",s=>{if(s!==0){let a=Buffer.concat(o).toString("utf-8").slice(-500);return r(new Error(`ffmpeg exited ${s}: ${a}`))}e(Buffer.concat(i))}),n.on("error",s=>r(new Error(`ffmpeg spawn failed: ${s.message}`))),n.stdin.write(t),n.stdin.end()})}async function us(t){let e=as(jr(),`wechat-voice-${uf(4).toString("hex")}.wav`);try{let r=await cf(t);return await lf(e,r),await hf(e)||null}finally{ss(e).catch(()=>{})}}function cf(t){return new Promise((e,r)=>{let n=Gr("ffmpeg",["-v","quiet","-i","pipe:0","-f","wav","-acodec","pcm_s16le","-ar",String(St),"-ac","1","pipe:1"]),i=[],o=[];n.stdout.on("data",s=>i.push(s)),n.stderr.on("data",s=>o.push(s)),n.on("close",s=>{if(s!==0){let a=Buffer.concat(o).toString("utf-8").slice(-500);return r(new Error(`ffmpeg (toWav) exited ${s}: ${a}`))}e(Buffer.concat(i))}),n.on("error",s=>r(new Error(`ffmpeg spawn failed: ${s.message}`))),n.stdin.write(t),n.stdin.end()})}function hf(t){return new Promise((e,r)=>{let n=Gr("whisper",[t,"--model","base","--language","zh","--output_format","txt","--output_dir",jr(),"--fp16","False"]),i=[];n.stderr.on("data",o=>i.push(o)),n.on("close",async o=>{if(o!==0){let a=Buffer.concat(i).toString("utf-8").slice(-500);return r(new Error(`whisper exited ${o}: ${a}`))}let s=as(jr(),t.replace(/\\/g,"/").split("/").pop().replace(/\.wav$/,".txt"));try{let{readFile:a}=await import("node:fs/promises"),u=await a(s,"utf-8");ss(s).catch(()=>{}),e(u.trim())}catch{e("")}}),n.on("error",o=>r(new Error(`whisper spawn failed: ${o.message}`)))})}function df(t){if(t.length<9)return!1;let e=t.subarray(0,9).toString("ascii");return e.startsWith("#!SILK_V3")||e.startsWith("#!SILK")}function pf(t){return Math.round(t.length/3)}var nt="/tmp/channel-wechat-media",fs="channel-wechat",cs=3e3,mf=3e4,Yr=5,hs=3e4;function x(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}`)}var Bt=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,o)=>r(i,{...o,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(x("info","ingressLoop started",this.config);this.running;){x("debug","ingressLoop tick",this.config);try{let n=await this.auth.getToken(),i=await this.auth.getSyncBuf(),{msgs:o,syncBuf:s}=await In(this.config.apiBase,n,i,e);await this.auth.saveSyncBuf(s),r=0,o.length>0&&x("debug",`getUpdates: ${o.length} msgs, types=${o.map(a=>`msg_type=${a.message_type} items=[${a.item_list?.map(u=>u.type).join(",")}]`).join(" | ")}`,this.config);for(let a of o){if(a.message_type===2)continue;if(!this.isAllowed(a.from_user_id)){x("debug",`Blocked message from ${a.from_user_id}`,this.config);continue}x("debug",`raw item_list from ${a.from_user_id}: ${JSON.stringify(a.item_list)}`,this.config);let u=a.item_list?.filter(g=>g.type===1&&g.text_item?.text).map(g=>g.text_item.text).join("")??"";for(let g of a.item_list??[])if(g.ref_msg){let y=g.ref_msg,w=[];if(y.title&&w.push(y.title),y.message_item?.text_item?.text&&w.push(y.message_item.text_item.text),w.length>0){let b=`<quoted_message>
|
|
36
|
+
${w.join(`
|
|
37
|
+
`)}
|
|
38
|
+
</quoted_message>`;u=u?`${b}
|
|
39
|
+
${u}`:b,x("info",`Quoted message context: "${w.join(" | ")}"`,this.config)}break}await gf(nt,{recursive:!0});let c=[];for(let g of a.item_list??[])try{if(g.type===2&&g.image_item?.media?.encrypt_query_param){let y=g.image_item,w=y.media.aes_key??(y.aeskey?Buffer.from(y.aeskey).toString("base64"):void 0);if(!w)continue;let b=await tt({cdnBaseUrl:this.config.cdnBase,encryptQueryParam:y.media.encrypt_query_param,aesKeyBase64:w,fetchFn:e}),C=`${nt}/${Date.now()}-${Rt(4).toString("hex")}.jpg`;await At(C,b),c.push({path:C,mime:"image/jpeg"}),x("info",`Downloaded image \u2192 ${C} (${b.length}B)`,this.config)}else if(g.type===3&&g.voice_item?.media?.encrypt_query_param&&g.voice_item.media.aes_key){let y=g.voice_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")}.silk`;if(await At(b,w),c.push({path:b,mime:"audio/silk"}),x("info",`Downloaded voice \u2192 ${b} (${w.length}B)`,this.config),y.text){let C=`<voice_transcript>
|
|
40
|
+
${y.text}
|
|
41
|
+
</voice_transcript>`;u=u?`${u}
|
|
42
|
+
${C}`:C,x("info",`Voice transcription from WeChat: "${y.text}"`,this.config)}else try{let C=await us(w);if(C){let S=`<voice_transcript>
|
|
43
|
+
${C}
|
|
44
|
+
</voice_transcript>`;u=u?`${u}
|
|
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 gs(ms(this.filePath),{recursive:!0}),await wf(this.filePath,i,"utf8")}),await this.writeChain,r}async getPending(e=Pf){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(!Tf(this.filePath))return[];let e=await bf(this.filePath,"utf8"),r=[];for(let n of e.split(`
|
|
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 gs(ms(this.filePath),{recursive:!0});let r=await this.readAll(),n=e(r),i=n.map(s=>JSON.stringify(s)).join(`
|
|
48
|
+
`)+(n.length>0?`
|
|
49
|
+
`:""),o=this.filePath+".tmp";await Cf(o,i,"utf8"),await Ef(o,this.filePath)}),await this.writeChain}};var Ot="/tmp/channel-wechat.pid";function If(){if(xf(Ot)){let t=parseInt(Af(Ot,"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.`)}}Sf(Ot,String(process.pid),"utf-8")}function Jr(){try{Rf(Ot)}catch{}}async function Of(){If();let t;try{t=Sn()}catch(u){Jr(),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 Et(t.stateDir,t.apiBase);try{await e.getToken()}catch(u){console.error(`[ERROR] Authentication failed: ${String(u)}`),process.exit(1)}let r=new It(Bf(t.stateDir,"outbox.jsonl")),n=new Bt(t,e,fetch,r);n.start();let i=parseInt(process.env.WECHAT_HEALTH_PORT??"8765",10),o={running:!0,tokenObtainedAt:e.tokenObtainedAt},s=ps(o,i),a=setInterval(()=>{o.tokenObtainedAt=e.tokenObtainedAt},6e4);for(let u of["SIGINT","SIGTERM"])process.on(u,()=>{console.log(`
|
|
50
|
+
[INFO] [wechat-channel] Received ${u}, shutting down\u2026`),o.running=!1,clearInterval(a),s.close(),n.stop(),Jr(),process.exit(0)});process.on("exit",Jr)}Of().catch(t=>{console.error("[FATAL]",t),process.exit(1)});
|
package/package.json
ADDED
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@openduo/channel-wechat",
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"type": "module",
|
|
5
|
+
"description": "WeChat channel plugin for duoduo",
|
|
6
|
+
"publishConfig": {
|
|
7
|
+
"access": "public"
|
|
8
|
+
},
|
|
9
|
+
"main": "dist/plugin.js",
|
|
10
|
+
"files": [
|
|
11
|
+
"dist/",
|
|
12
|
+
"README.md",
|
|
13
|
+
"package.json"
|
|
14
|
+
],
|
|
15
|
+
"bin": {
|
|
16
|
+
"duoduo-wechat": "./dist/plugin.js"
|
|
17
|
+
},
|
|
18
|
+
"aladuo": {
|
|
19
|
+
"channel": {
|
|
20
|
+
"type": "wechat",
|
|
21
|
+
"bin": "dist/plugin.js",
|
|
22
|
+
"envAllowlist": [
|
|
23
|
+
"ALADUO_DAEMON_URL",
|
|
24
|
+
"WECHAT_API_BASE",
|
|
25
|
+
"WECHAT_DM_POLICY",
|
|
26
|
+
"WECHAT_ALLOW_FROM",
|
|
27
|
+
"WECHAT_STATE_DIR",
|
|
28
|
+
"WECHAT_LOG_LEVEL",
|
|
29
|
+
"WECHAT_HEALTH_PORT"
|
|
30
|
+
]
|
|
31
|
+
}
|
|
32
|
+
},
|
|
33
|
+
"scripts": {
|
|
34
|
+
"build": "npm run build:plugin",
|
|
35
|
+
"build:plugin": "node scripts/build-plugin.mjs",
|
|
36
|
+
"prepack": "npm run build:plugin",
|
|
37
|
+
"dev": "tsx src/index.ts",
|
|
38
|
+
"start": "node dist/plugin.js",
|
|
39
|
+
"typecheck": "tsc --noEmit",
|
|
40
|
+
"test": "vitest run",
|
|
41
|
+
"test:coverage": "vitest run --coverage"
|
|
42
|
+
},
|
|
43
|
+
"dependencies": {
|
|
44
|
+
"@openduo/protocol": "^0.2.4",
|
|
45
|
+
"qrcode": "^1.5.3",
|
|
46
|
+
"silk-wasm": "^3.7.1"
|
|
47
|
+
},
|
|
48
|
+
"devDependencies": {
|
|
49
|
+
"@types/node": "^22",
|
|
50
|
+
"@types/qrcode": "^1.5.5",
|
|
51
|
+
"@vitest/coverage-v8": "^2",
|
|
52
|
+
"esbuild": "^0.27.4",
|
|
53
|
+
"tsx": "^4",
|
|
54
|
+
"typescript": "^5",
|
|
55
|
+
"vitest": "^2.1.9"
|
|
56
|
+
},
|
|
57
|
+
"engines": {
|
|
58
|
+
"node": ">=20"
|
|
59
|
+
}
|
|
60
|
+
}
|