imapkit 5.3.0 → 5.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,8 +1,8 @@
1
- var jl=Object.create;var Rr=Object.defineProperty;var Vl=Object.getOwnPropertyDescriptor;var ql=Object.getOwnPropertyNames;var Ql=Object.getPrototypeOf,Yl=Object.prototype.hasOwnProperty;var Lr=(s,e,t)=>()=>{if(t)throw t[0];try{return s&&(e=s(s=0)),e}catch(r){throw t=[r],r}};var as=(s,e)=>()=>{try{return e||s((e={exports:{}}).exports,e),e.exports}catch(t){throw e=0,t}},Kl=(s,e)=>{for(var t in e)Rr(s,t,{get:e[t],enumerable:!0})},zl=(s,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of ql(e))!Yl.call(s,n)&&n!==t&&Rr(s,n,{get:()=>e[n],enumerable:!(r=Vl(e,n))||r.enumerable});return s};var Ut=(s,e,t)=>(t=s!=null?jl(Ql(s)):{},zl(e||!s||!s.__esModule?Rr(t,"default",{value:s,enumerable:!0}):t,s));var Xo=as(us=>{"use strict";g();us.byteLength=$l;us.toByteArray=Zl;us.fromByteArray=sc;var Ue=[],Oe=[],Wl=typeof Uint8Array<"u"?Uint8Array:Array,Dr="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";for(Ze=0,_o=Dr.length;Ze<_o;++Ze)Ue[Ze]=Dr[Ze],Oe[Dr.charCodeAt(Ze)]=Ze;var Ze,_o;Oe[45]=62;Oe[95]=63;function Go(s){var e=s.length;if(e%4>0)throw new Error("Invalid string. Length must be a multiple of 4");var t=s.indexOf("=");t===-1&&(t=e);var r=t===e?0:4-t%4;return[t,r]}function $l(s){var e=Go(s),t=e[0],r=e[1];return(t+r)*3/4-r}function Jl(s,e,t){return(e+t)*3/4-t}function Zl(s){var e,t=Go(s),r=t[0],n=t[1],i=new Wl(Jl(s,r,n)),o=0,a=n>0?r-4:r,u;for(u=0;u<a;u+=4)e=Oe[s.charCodeAt(u)]<<18|Oe[s.charCodeAt(u+1)]<<12|Oe[s.charCodeAt(u+2)]<<6|Oe[s.charCodeAt(u+3)],i[o++]=e>>16&255,i[o++]=e>>8&255,i[o++]=e&255;return n===2&&(e=Oe[s.charCodeAt(u)]<<2|Oe[s.charCodeAt(u+1)]>>4,i[o++]=e&255),n===1&&(e=Oe[s.charCodeAt(u)]<<10|Oe[s.charCodeAt(u+1)]<<4|Oe[s.charCodeAt(u+2)]>>2,i[o++]=e>>8&255,i[o++]=e&255),i}function ec(s){return Ue[s>>18&63]+Ue[s>>12&63]+Ue[s>>6&63]+Ue[s&63]}function tc(s,e,t){for(var r,n=[],i=e;i<t;i+=3)r=(s[i]<<16&16711680)+(s[i+1]<<8&65280)+(s[i+2]&255),n.push(ec(r));return n.join("")}function sc(s){for(var e,t=s.length,r=t%3,n=[],i=16383,o=0,a=t-r;o<a;o+=i)n.push(tc(s,o,o+i>a?a:o+i));return r===1?(e=s[t-1],n.push(Ue[e>>2]+Ue[e<<4&63]+"==")):r===2&&(e=(s[t-2]<<8)+s[t-1],n.push(Ue[e>>10]+Ue[e>>4&63]+Ue[e<<2&63]+"=")),n.join("")}});var jo=as(Ur=>{g();Ur.read=function(s,e,t,r,n){var i,o,a=n*8-r-1,u=(1<<a)-1,l=u>>1,c=-7,f=t?n-1:0,p=t?-1:1,y=s[e+f];for(f+=p,i=y&(1<<-c)-1,y>>=-c,c+=a;c>0;i=i*256+s[e+f],f+=p,c-=8);for(o=i&(1<<-c)-1,i>>=-c,c+=r;c>0;o=o*256+s[e+f],f+=p,c-=8);if(i===0)i=1-l;else{if(i===u)return o?NaN:(y?-1:1)*(1/0);o=o+Math.pow(2,r),i=i-l}return(y?-1:1)*o*Math.pow(2,i-r)};Ur.write=function(s,e,t,r,n,i){var o,a,u,l=i*8-n-1,c=(1<<l)-1,f=c>>1,p=n===23?Math.pow(2,-24)-Math.pow(2,-77):0,y=r?0:i-1,A=r?1:-1,m=e<0||e===0&&1/e<0?1:0;for(e=Math.abs(e),isNaN(e)||e===1/0?(a=isNaN(e)?1:0,o=c):(o=Math.floor(Math.log(e)/Math.LN2),e*(u=Math.pow(2,-o))<1&&(o--,u*=2),o+f>=1?e+=p/u:e+=p*Math.pow(2,1-f),e*u>=2&&(o++,u/=2),o+f>=c?(a=0,o=c):o+f>=1?(a=(e*u-1)*Math.pow(2,n),o=o+f):(a=e*Math.pow(2,f-1)*Math.pow(2,n),o=0));n>=8;s[t+y]=a&255,y+=A,a/=256,n-=8);for(o=o<<n|a,l+=n;l>0;s[t+y]=o&255,y+=A,o/=256,l-=8);s[t+y-A]|=m*128}});var Xr=as(gt=>{"use strict";g();var vr=Xo(),pt=jo(),Vo=typeof Symbol=="function"&&typeof Symbol.for=="function"?Symbol.for("nodejs.util.inspect.custom"):null;gt.Buffer=B;gt.SlowBuffer=uc;gt.INSPECT_MAX_BYTES=50;var ls=2147483647;gt.kMaxLength=ls;B.TYPED_ARRAY_SUPPORT=rc();!B.TYPED_ARRAY_SUPPORT&&typeof console<"u"&&typeof console.error=="function"&&console.error("This browser lacks typed array (Uint8Array) support which is required by `buffer` v5.x. Use `buffer` v4.x if you require old browser support.");function rc(){try{let s=new Uint8Array(1),e={foo:function(){return 42}};return Object.setPrototypeOf(e,Uint8Array.prototype),Object.setPrototypeOf(s,e),s.foo()===42}catch{return!1}}Object.defineProperty(B.prototype,"parent",{enumerable:!0,get:function(){if(B.isBuffer(this))return this.buffer}});Object.defineProperty(B.prototype,"offset",{enumerable:!0,get:function(){if(B.isBuffer(this))return this.byteOffset}});function Pe(s){if(s>ls)throw new RangeError('The value "'+s+'" is invalid for option "size"');let e=new Uint8Array(s);return Object.setPrototypeOf(e,B.prototype),e}function B(s,e,t){if(typeof s=="number"){if(typeof e=="string")throw new TypeError('The "string" argument must be of type string. Received type number');return Pr(s)}return Ko(s,e,t)}B.poolSize=8192;function Ko(s,e,t){if(typeof s=="string")return ic(s,e);if(ArrayBuffer.isView(s))return oc(s);if(s==null)throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof s);if(ve(s,ArrayBuffer)||s&&ve(s.buffer,ArrayBuffer)||typeof SharedArrayBuffer<"u"&&(ve(s,SharedArrayBuffer)||s&&ve(s.buffer,SharedArrayBuffer)))return Hr(s,e,t);if(typeof s=="number")throw new TypeError('The "value" argument must not be of type number. Received type number');let r=s.valueOf&&s.valueOf();if(r!=null&&r!==s)return B.from(r,e,t);let n=ac(s);if(n)return n;if(typeof Symbol<"u"&&Symbol.toPrimitive!=null&&typeof s[Symbol.toPrimitive]=="function")return B.from(s[Symbol.toPrimitive]("string"),e,t);throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof s)}B.from=function(s,e,t){return Ko(s,e,t)};Object.setPrototypeOf(B.prototype,Uint8Array.prototype);Object.setPrototypeOf(B,Uint8Array);function zo(s){if(typeof s!="number")throw new TypeError('"size" argument must be of type number');if(s<0)throw new RangeError('The value "'+s+'" is invalid for option "size"')}function nc(s,e,t){return zo(s),s<=0?Pe(s):e!==void 0?typeof t=="string"?Pe(s).fill(e,t):Pe(s).fill(e):Pe(s)}B.alloc=function(s,e,t){return nc(s,e,t)};function Pr(s){return zo(s),Pe(s<0?0:Fr(s)|0)}B.allocUnsafe=function(s){return Pr(s)};B.allocUnsafeSlow=function(s){return Pr(s)};function ic(s,e){if((typeof e!="string"||e==="")&&(e="utf8"),!B.isEncoding(e))throw new TypeError("Unknown encoding: "+e);let t=Wo(s,e)|0,r=Pe(t),n=r.write(s,e);return n!==t&&(r=r.slice(0,n)),r}function Br(s){let e=s.length<0?0:Fr(s.length)|0,t=Pe(e);for(let r=0;r<e;r+=1)t[r]=s[r]&255;return t}function oc(s){if(ve(s,Uint8Array)){let e=new Uint8Array(s);return Hr(e.buffer,e.byteOffset,e.byteLength)}return Br(s)}function Hr(s,e,t){if(e<0||s.byteLength<e)throw new RangeError('"offset" is outside of buffer bounds');if(s.byteLength<e+(t||0))throw new RangeError('"length" is outside of buffer bounds');let r;return e===void 0&&t===void 0?r=new Uint8Array(s):t===void 0?r=new Uint8Array(s,e):r=new Uint8Array(s,e,t),Object.setPrototypeOf(r,B.prototype),r}function ac(s){if(B.isBuffer(s)){let e=Fr(s.length)|0,t=Pe(e);return t.length===0||s.copy(t,0,0,e),t}if(s.length!==void 0)return typeof s.length!="number"||Gr(s.length)?Pe(0):Br(s);if(s.type==="Buffer"&&Array.isArray(s.data))return Br(s.data)}function Fr(s){if(s>=ls)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+ls.toString(16)+" bytes");return s|0}function uc(s){return+s!=s&&(s=0),B.alloc(+s)}B.isBuffer=function(e){return e!=null&&e._isBuffer===!0&&e!==B.prototype};B.compare=function(e,t){if(ve(e,Uint8Array)&&(e=B.from(e,e.offset,e.byteLength)),ve(t,Uint8Array)&&(t=B.from(t,t.offset,t.byteLength)),!B.isBuffer(e)||!B.isBuffer(t))throw new TypeError('The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array');if(e===t)return 0;let r=e.length,n=t.length;for(let i=0,o=Math.min(r,n);i<o;++i)if(e[i]!==t[i]){r=e[i],n=t[i];break}return r<n?-1:n<r?1:0};B.isEncoding=function(e){switch(String(e).toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"latin1":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return!0;default:return!1}};B.concat=function(e,t){if(!Array.isArray(e))throw new TypeError('"list" argument must be an Array of Buffers');if(e.length===0)return B.alloc(0);let r;if(t===void 0)for(t=0,r=0;r<e.length;++r)t+=e[r].length;let n=B.allocUnsafe(t),i=0;for(r=0;r<e.length;++r){let o=e[r];if(ve(o,Uint8Array))i+o.length>n.length?(B.isBuffer(o)||(o=B.from(o)),o.copy(n,i)):Uint8Array.prototype.set.call(n,o,i);else if(B.isBuffer(o))o.copy(n,i);else throw new TypeError('"list" argument must be an Array of Buffers');i+=o.length}return n};function Wo(s,e){if(B.isBuffer(s))return s.length;if(ArrayBuffer.isView(s)||ve(s,ArrayBuffer))return s.byteLength;if(typeof s!="string")throw new TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type '+typeof s);let t=s.length,r=arguments.length>2&&arguments[2]===!0;if(!r&&t===0)return 0;let n=!1;for(;;)switch(e){case"ascii":case"latin1":case"binary":return t;case"utf8":case"utf-8":return kr(s).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return t*2;case"hex":return t>>>1;case"base64":return ia(s).length;default:if(n)return r?-1:kr(s).length;e=(""+e).toLowerCase(),n=!0}}B.byteLength=Wo;function lc(s,e,t){let r=!1;if((e===void 0||e<0)&&(e=0),e>this.length||((t===void 0||t>this.length)&&(t=this.length),t<=0)||(t>>>=0,e>>>=0,t<=e))return"";for(s||(s="utf8");;)switch(s){case"hex":return yc(this,e,t);case"utf8":case"utf-8":return Jo(this,e,t);case"ascii":return Ec(this,e,t);case"latin1":case"binary":return Ac(this,e,t);case"base64":return mc(this,e,t);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return bc(this,e,t);default:if(r)throw new TypeError("Unknown encoding: "+s);s=(s+"").toLowerCase(),r=!0}}B.prototype._isBuffer=!0;function et(s,e,t){let r=s[e];s[e]=s[t],s[t]=r}B.prototype.swap16=function(){let e=this.length;if(e%2!==0)throw new RangeError("Buffer size must be a multiple of 16-bits");for(let t=0;t<e;t+=2)et(this,t,t+1);return this};B.prototype.swap32=function(){let e=this.length;if(e%4!==0)throw new RangeError("Buffer size must be a multiple of 32-bits");for(let t=0;t<e;t+=4)et(this,t,t+3),et(this,t+1,t+2);return this};B.prototype.swap64=function(){let e=this.length;if(e%8!==0)throw new RangeError("Buffer size must be a multiple of 64-bits");for(let t=0;t<e;t+=8)et(this,t,t+7),et(this,t+1,t+6),et(this,t+2,t+5),et(this,t+3,t+4);return this};B.prototype.toString=function(){let e=this.length;return e===0?"":arguments.length===0?Jo(this,0,e):lc.apply(this,arguments)};B.prototype.toLocaleString=B.prototype.toString;B.prototype.equals=function(e){if(!B.isBuffer(e))throw new TypeError("Argument must be a Buffer");return this===e?!0:B.compare(this,e)===0};B.prototype.inspect=function(){let e="",t=gt.INSPECT_MAX_BYTES;return e=this.toString("hex",0,t).replace(/(.{2})/g,"$1 ").trim(),this.length>t&&(e+=" ... "),"<Buffer "+e+">"};Vo&&(B.prototype[Vo]=B.prototype.inspect);B.prototype.compare=function(e,t,r,n,i){if(ve(e,Uint8Array)&&(e=B.from(e,e.offset,e.byteLength)),!B.isBuffer(e))throw new TypeError('The "target" argument must be one of type Buffer or Uint8Array. Received type '+typeof e);if(t===void 0&&(t=0),r===void 0&&(r=e?e.length:0),n===void 0&&(n=0),i===void 0&&(i=this.length),t<0||r>e.length||n<0||i>this.length)throw new RangeError("out of range index");if(n>=i&&t>=r)return 0;if(n>=i)return-1;if(t>=r)return 1;if(t>>>=0,r>>>=0,n>>>=0,i>>>=0,this===e)return 0;let o=i-n,a=r-t,u=Math.min(o,a),l=this.slice(n,i),c=e.slice(t,r);for(let f=0;f<u;++f)if(l[f]!==c[f]){o=l[f],a=c[f];break}return o<a?-1:a<o?1:0};function $o(s,e,t,r,n){if(s.length===0)return-1;if(typeof t=="string"?(r=t,t=0):t>2147483647?t=2147483647:t<-2147483648&&(t=-2147483648),t=+t,Gr(t)&&(t=n?0:s.length-1),t<0&&(t=s.length+t),t>=s.length){if(n)return-1;t=s.length-1}else if(t<0)if(n)t=0;else return-1;if(typeof e=="string"&&(e=B.from(e,r)),B.isBuffer(e))return e.length===0?-1:qo(s,e,t,r,n);if(typeof e=="number")return e=e&255,typeof Uint8Array.prototype.indexOf=="function"?n?Uint8Array.prototype.indexOf.call(s,e,t):Uint8Array.prototype.lastIndexOf.call(s,e,t):qo(s,[e],t,r,n);throw new TypeError("val must be string, number or Buffer")}function qo(s,e,t,r,n){let i=1,o=s.length,a=e.length;if(r!==void 0&&(r=String(r).toLowerCase(),r==="ucs2"||r==="ucs-2"||r==="utf16le"||r==="utf-16le")){if(s.length<2||e.length<2)return-1;i=2,o/=2,a/=2,t/=2}function u(c,f){return i===1?c[f]:c.readUInt16BE(f*i)}let l;if(n){let c=-1;for(l=t;l<o;l++)if(u(s,l)===u(e,c===-1?0:l-c)){if(c===-1&&(c=l),l-c+1===a)return c*i}else c!==-1&&(l-=l-c),c=-1}else for(t+a>o&&(t=o-a),l=t;l>=0;l--){let c=!0;for(let f=0;f<a;f++)if(u(s,l+f)!==u(e,f)){c=!1;break}if(c)return l}return-1}B.prototype.includes=function(e,t,r){return this.indexOf(e,t,r)!==-1};B.prototype.indexOf=function(e,t,r){return $o(this,e,t,r,!0)};B.prototype.lastIndexOf=function(e,t,r){return $o(this,e,t,r,!1)};function cc(s,e,t,r){t=Number(t)||0;let n=s.length-t;r?(r=Number(r),r>n&&(r=n)):r=n;let i=e.length;r>i/2&&(r=i/2);let o;for(o=0;o<r;++o){let a=parseInt(e.substr(o*2,2),16);if(Gr(a))return o;s[t+o]=a}return o}function fc(s,e,t,r){return cs(kr(e,s.length-t),s,t,r)}function hc(s,e,t,r){return cs(Oc(e),s,t,r)}function dc(s,e,t,r){return cs(ia(e),s,t,r)}function pc(s,e,t,r){return cs(xc(e,s.length-t),s,t,r)}B.prototype.write=function(e,t,r,n){if(t===void 0)n="utf8",r=this.length,t=0;else if(r===void 0&&typeof t=="string")n=t,r=this.length,t=0;else if(isFinite(t))t=t>>>0,isFinite(r)?(r=r>>>0,n===void 0&&(n="utf8")):(n=r,r=void 0);else throw new Error("Buffer.write(string, encoding, offset[, length]) is no longer supported");let i=this.length-t;if((r===void 0||r>i)&&(r=i),e.length>0&&(r<0||t<0)||t>this.length)throw new RangeError("Attempt to write outside buffer bounds");n||(n="utf8");let o=!1;for(;;)switch(n){case"hex":return cc(this,e,t,r);case"utf8":case"utf-8":return fc(this,e,t,r);case"ascii":case"latin1":case"binary":return hc(this,e,t,r);case"base64":return dc(this,e,t,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return pc(this,e,t,r);default:if(o)throw new TypeError("Unknown encoding: "+n);n=(""+n).toLowerCase(),o=!0}};B.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};function mc(s,e,t){return e===0&&t===s.length?vr.fromByteArray(s):vr.fromByteArray(s.slice(e,t))}function Jo(s,e,t){t=Math.min(s.length,t);let r=[],n=e;for(;n<t;){let i=s[n],o=null,a=i>239?4:i>223?3:i>191?2:1;if(n+a<=t){let u,l,c,f;switch(a){case 1:i<128&&(o=i);break;case 2:u=s[n+1],(u&192)===128&&(f=(i&31)<<6|u&63,f>127&&(o=f));break;case 3:u=s[n+1],l=s[n+2],(u&192)===128&&(l&192)===128&&(f=(i&15)<<12|(u&63)<<6|l&63,f>2047&&(f<55296||f>57343)&&(o=f));break;case 4:u=s[n+1],l=s[n+2],c=s[n+3],(u&192)===128&&(l&192)===128&&(c&192)===128&&(f=(i&15)<<18|(u&63)<<12|(l&63)<<6|c&63,f>65535&&f<1114112&&(o=f))}}o===null?(o=65533,a=1):o>65535&&(o-=65536,r.push(o>>>10&1023|55296),o=56320|o&1023),r.push(o),n+=a}return gc(r)}var Qo=4096;function gc(s){let e=s.length;if(e<=Qo)return String.fromCharCode.apply(String,s);let t="",r=0;for(;r<e;)t+=String.fromCharCode.apply(String,s.slice(r,r+=Qo));return t}function Ec(s,e,t){let r="";t=Math.min(s.length,t);for(let n=e;n<t;++n)r+=String.fromCharCode(s[n]&127);return r}function Ac(s,e,t){let r="";t=Math.min(s.length,t);for(let n=e;n<t;++n)r+=String.fromCharCode(s[n]);return r}function yc(s,e,t){let r=s.length;(!e||e<0)&&(e=0),(!t||t<0||t>r)&&(t=r);let n="";for(let i=e;i<t;++i)n+=Cc[s[i]];return n}function bc(s,e,t){let r=s.slice(e,t),n="";for(let i=0;i<r.length-1;i+=2)n+=String.fromCharCode(r[i]+r[i+1]*256);return n}B.prototype.slice=function(e,t){let r=this.length;e=~~e,t=t===void 0?r:~~t,e<0?(e+=r,e<0&&(e=0)):e>r&&(e=r),t<0?(t+=r,t<0&&(t=0)):t>r&&(t=r),t<e&&(t=e);let n=this.subarray(e,t);return Object.setPrototypeOf(n,B.prototype),n};function le(s,e,t){if(s%1!==0||s<0)throw new RangeError("offset is not uint");if(s+e>t)throw new RangeError("Trying to access beyond buffer length")}B.prototype.readUintLE=B.prototype.readUIntLE=function(e,t,r){e=e>>>0,t=t>>>0,r||le(e,t,this.length);let n=this[e],i=1,o=0;for(;++o<t&&(i*=256);)n+=this[e+o]*i;return n};B.prototype.readUintBE=B.prototype.readUIntBE=function(e,t,r){e=e>>>0,t=t>>>0,r||le(e,t,this.length);let n=this[e+--t],i=1;for(;t>0&&(i*=256);)n+=this[e+--t]*i;return n};B.prototype.readUint8=B.prototype.readUInt8=function(e,t){return e=e>>>0,t||le(e,1,this.length),this[e]};B.prototype.readUint16LE=B.prototype.readUInt16LE=function(e,t){return e=e>>>0,t||le(e,2,this.length),this[e]|this[e+1]<<8};B.prototype.readUint16BE=B.prototype.readUInt16BE=function(e,t){return e=e>>>0,t||le(e,2,this.length),this[e]<<8|this[e+1]};B.prototype.readUint32LE=B.prototype.readUInt32LE=function(e,t){return e=e>>>0,t||le(e,4,this.length),(this[e]|this[e+1]<<8|this[e+2]<<16)+this[e+3]*16777216};B.prototype.readUint32BE=B.prototype.readUInt32BE=function(e,t){return e=e>>>0,t||le(e,4,this.length),this[e]*16777216+(this[e+1]<<16|this[e+2]<<8|this[e+3])};B.prototype.readBigUInt64LE=qe(function(e){e=e>>>0,mt(e,"offset");let t=this[e],r=this[e+7];(t===void 0||r===void 0)&&vt(e,this.length-8);let n=t+this[++e]*2**8+this[++e]*2**16+this[++e]*2**24,i=this[++e]+this[++e]*2**8+this[++e]*2**16+r*2**24;return BigInt(n)+(BigInt(i)<<BigInt(32))});B.prototype.readBigUInt64BE=qe(function(e){e=e>>>0,mt(e,"offset");let t=this[e],r=this[e+7];(t===void 0||r===void 0)&&vt(e,this.length-8);let n=t*2**24+this[++e]*2**16+this[++e]*2**8+this[++e],i=this[++e]*2**24+this[++e]*2**16+this[++e]*2**8+r;return(BigInt(n)<<BigInt(32))+BigInt(i)});B.prototype.readIntLE=function(e,t,r){e=e>>>0,t=t>>>0,r||le(e,t,this.length);let n=this[e],i=1,o=0;for(;++o<t&&(i*=256);)n+=this[e+o]*i;return i*=128,n>=i&&(n-=Math.pow(2,8*t)),n};B.prototype.readIntBE=function(e,t,r){e=e>>>0,t=t>>>0,r||le(e,t,this.length);let n=t,i=1,o=this[e+--n];for(;n>0&&(i*=256);)o+=this[e+--n]*i;return i*=128,o>=i&&(o-=Math.pow(2,8*t)),o};B.prototype.readInt8=function(e,t){return e=e>>>0,t||le(e,1,this.length),this[e]&128?(255-this[e]+1)*-1:this[e]};B.prototype.readInt16LE=function(e,t){e=e>>>0,t||le(e,2,this.length);let r=this[e]|this[e+1]<<8;return r&32768?r|4294901760:r};B.prototype.readInt16BE=function(e,t){e=e>>>0,t||le(e,2,this.length);let r=this[e+1]|this[e]<<8;return r&32768?r|4294901760:r};B.prototype.readInt32LE=function(e,t){return e=e>>>0,t||le(e,4,this.length),this[e]|this[e+1]<<8|this[e+2]<<16|this[e+3]<<24};B.prototype.readInt32BE=function(e,t){return e=e>>>0,t||le(e,4,this.length),this[e]<<24|this[e+1]<<16|this[e+2]<<8|this[e+3]};B.prototype.readBigInt64LE=qe(function(e){e=e>>>0,mt(e,"offset");let t=this[e],r=this[e+7];(t===void 0||r===void 0)&&vt(e,this.length-8);let n=this[e+4]+this[e+5]*2**8+this[e+6]*2**16+(r<<24);return(BigInt(n)<<BigInt(32))+BigInt(t+this[++e]*2**8+this[++e]*2**16+this[++e]*2**24)});B.prototype.readBigInt64BE=qe(function(e){e=e>>>0,mt(e,"offset");let t=this[e],r=this[e+7];(t===void 0||r===void 0)&&vt(e,this.length-8);let n=(t<<24)+this[++e]*2**16+this[++e]*2**8+this[++e];return(BigInt(n)<<BigInt(32))+BigInt(this[++e]*2**24+this[++e]*2**16+this[++e]*2**8+r)});B.prototype.readFloatLE=function(e,t){return e=e>>>0,t||le(e,4,this.length),pt.read(this,e,!0,23,4)};B.prototype.readFloatBE=function(e,t){return e=e>>>0,t||le(e,4,this.length),pt.read(this,e,!1,23,4)};B.prototype.readDoubleLE=function(e,t){return e=e>>>0,t||le(e,8,this.length),pt.read(this,e,!0,52,8)};B.prototype.readDoubleBE=function(e,t){return e=e>>>0,t||le(e,8,this.length),pt.read(this,e,!1,52,8)};function Ee(s,e,t,r,n,i){if(!B.isBuffer(s))throw new TypeError('"buffer" argument must be a Buffer instance');if(e>n||e<i)throw new RangeError('"value" argument is out of bounds');if(t+r>s.length)throw new RangeError("Index out of range")}B.prototype.writeUintLE=B.prototype.writeUIntLE=function(e,t,r,n){if(e=+e,t=t>>>0,r=r>>>0,!n){let a=Math.pow(2,8*r)-1;Ee(this,e,t,r,a,0)}let i=1,o=0;for(this[t]=e&255;++o<r&&(i*=256);)this[t+o]=e/i&255;return t+r};B.prototype.writeUintBE=B.prototype.writeUIntBE=function(e,t,r,n){if(e=+e,t=t>>>0,r=r>>>0,!n){let a=Math.pow(2,8*r)-1;Ee(this,e,t,r,a,0)}let i=r-1,o=1;for(this[t+i]=e&255;--i>=0&&(o*=256);)this[t+i]=e/o&255;return t+r};B.prototype.writeUint8=B.prototype.writeUInt8=function(e,t,r){return e=+e,t=t>>>0,r||Ee(this,e,t,1,255,0),this[t]=e&255,t+1};B.prototype.writeUint16LE=B.prototype.writeUInt16LE=function(e,t,r){return e=+e,t=t>>>0,r||Ee(this,e,t,2,65535,0),this[t]=e&255,this[t+1]=e>>>8,t+2};B.prototype.writeUint16BE=B.prototype.writeUInt16BE=function(e,t,r){return e=+e,t=t>>>0,r||Ee(this,e,t,2,65535,0),this[t]=e>>>8,this[t+1]=e&255,t+2};B.prototype.writeUint32LE=B.prototype.writeUInt32LE=function(e,t,r){return e=+e,t=t>>>0,r||Ee(this,e,t,4,4294967295,0),this[t+3]=e>>>24,this[t+2]=e>>>16,this[t+1]=e>>>8,this[t]=e&255,t+4};B.prototype.writeUint32BE=B.prototype.writeUInt32BE=function(e,t,r){return e=+e,t=t>>>0,r||Ee(this,e,t,4,4294967295,0),this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=e&255,t+4};function Zo(s,e,t,r,n){na(e,r,n,s,t,7);let i=Number(e&BigInt(4294967295));s[t++]=i,i=i>>8,s[t++]=i,i=i>>8,s[t++]=i,i=i>>8,s[t++]=i;let o=Number(e>>BigInt(32)&BigInt(4294967295));return s[t++]=o,o=o>>8,s[t++]=o,o=o>>8,s[t++]=o,o=o>>8,s[t++]=o,t}function ea(s,e,t,r,n){na(e,r,n,s,t,7);let i=Number(e&BigInt(4294967295));s[t+7]=i,i=i>>8,s[t+6]=i,i=i>>8,s[t+5]=i,i=i>>8,s[t+4]=i;let o=Number(e>>BigInt(32)&BigInt(4294967295));return s[t+3]=o,o=o>>8,s[t+2]=o,o=o>>8,s[t+1]=o,o=o>>8,s[t]=o,t+8}B.prototype.writeBigUInt64LE=qe(function(e,t=0){return Zo(this,e,t,BigInt(0),BigInt("0xffffffffffffffff"))});B.prototype.writeBigUInt64BE=qe(function(e,t=0){return ea(this,e,t,BigInt(0),BigInt("0xffffffffffffffff"))});B.prototype.writeIntLE=function(e,t,r,n){if(e=+e,t=t>>>0,!n){let u=Math.pow(2,8*r-1);Ee(this,e,t,r,u-1,-u)}let i=0,o=1,a=0;for(this[t]=e&255;++i<r&&(o*=256);)e<0&&a===0&&this[t+i-1]!==0&&(a=1),this[t+i]=(e/o>>0)-a&255;return t+r};B.prototype.writeIntBE=function(e,t,r,n){if(e=+e,t=t>>>0,!n){let u=Math.pow(2,8*r-1);Ee(this,e,t,r,u-1,-u)}let i=r-1,o=1,a=0;for(this[t+i]=e&255;--i>=0&&(o*=256);)e<0&&a===0&&this[t+i+1]!==0&&(a=1),this[t+i]=(e/o>>0)-a&255;return t+r};B.prototype.writeInt8=function(e,t,r){return e=+e,t=t>>>0,r||Ee(this,e,t,1,127,-128),e<0&&(e=255+e+1),this[t]=e&255,t+1};B.prototype.writeInt16LE=function(e,t,r){return e=+e,t=t>>>0,r||Ee(this,e,t,2,32767,-32768),this[t]=e&255,this[t+1]=e>>>8,t+2};B.prototype.writeInt16BE=function(e,t,r){return e=+e,t=t>>>0,r||Ee(this,e,t,2,32767,-32768),this[t]=e>>>8,this[t+1]=e&255,t+2};B.prototype.writeInt32LE=function(e,t,r){return e=+e,t=t>>>0,r||Ee(this,e,t,4,2147483647,-2147483648),this[t]=e&255,this[t+1]=e>>>8,this[t+2]=e>>>16,this[t+3]=e>>>24,t+4};B.prototype.writeInt32BE=function(e,t,r){return e=+e,t=t>>>0,r||Ee(this,e,t,4,2147483647,-2147483648),e<0&&(e=4294967295+e+1),this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=e&255,t+4};B.prototype.writeBigInt64LE=qe(function(e,t=0){return Zo(this,e,t,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))});B.prototype.writeBigInt64BE=qe(function(e,t=0){return ea(this,e,t,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))});function ta(s,e,t,r,n,i){if(t+r>s.length)throw new RangeError("Index out of range");if(t<0)throw new RangeError("Index out of range")}function sa(s,e,t,r,n){return e=+e,t=t>>>0,n||ta(s,e,t,4,34028234663852886e22,-34028234663852886e22),pt.write(s,e,t,r,23,4),t+4}B.prototype.writeFloatLE=function(e,t,r){return sa(this,e,t,!0,r)};B.prototype.writeFloatBE=function(e,t,r){return sa(this,e,t,!1,r)};function ra(s,e,t,r,n){return e=+e,t=t>>>0,n||ta(s,e,t,8,17976931348623157e292,-17976931348623157e292),pt.write(s,e,t,r,52,8),t+8}B.prototype.writeDoubleLE=function(e,t,r){return ra(this,e,t,!0,r)};B.prototype.writeDoubleBE=function(e,t,r){return ra(this,e,t,!1,r)};B.prototype.copy=function(e,t,r,n){if(!B.isBuffer(e))throw new TypeError("argument should be a Buffer");if(r||(r=0),!n&&n!==0&&(n=this.length),t>=e.length&&(t=e.length),t||(t=0),n>0&&n<r&&(n=r),n===r||e.length===0||this.length===0)return 0;if(t<0)throw new RangeError("targetStart out of bounds");if(r<0||r>=this.length)throw new RangeError("Index out of range");if(n<0)throw new RangeError("sourceEnd out of bounds");n>this.length&&(n=this.length),e.length-t<n-r&&(n=e.length-t+r);let i=n-r;return this===e&&typeof Uint8Array.prototype.copyWithin=="function"?this.copyWithin(t,r,n):Uint8Array.prototype.set.call(e,this.subarray(r,n),t),i};B.prototype.fill=function(e,t,r,n){if(typeof e=="string"){if(typeof t=="string"?(n=t,t=0,r=this.length):typeof r=="string"&&(n=r,r=this.length),n!==void 0&&typeof n!="string")throw new TypeError("encoding must be a string");if(typeof n=="string"&&!B.isEncoding(n))throw new TypeError("Unknown encoding: "+n);if(e.length===1){let o=e.charCodeAt(0);(n==="utf8"&&o<128||n==="latin1")&&(e=o)}}else typeof e=="number"?e=e&255:typeof e=="boolean"&&(e=Number(e));if(t<0||this.length<t||this.length<r)throw new RangeError("Out of range index");if(r<=t)return this;t=t>>>0,r=r===void 0?this.length:r>>>0,e||(e=0);let i;if(typeof e=="number")for(i=t;i<r;++i)this[i]=e;else{let o=B.isBuffer(e)?e:B.from(e,n),a=o.length;if(a===0)throw new TypeError('The value "'+e+'" is invalid for argument "value"');for(i=0;i<r-t;++i)this[i+t]=o[i%a]}return this};var dt={};function _r(s,e,t){dt[s]=class extends t{constructor(){super(),Object.defineProperty(this,"message",{value:e.apply(this,arguments),writable:!0,configurable:!0}),this.name=`${this.name} [${s}]`,this.stack,delete this.name}get code(){return s}set code(n){Object.defineProperty(this,"code",{configurable:!0,enumerable:!0,value:n,writable:!0})}toString(){return`${this.name} [${s}]: ${this.message}`}}}_r("ERR_BUFFER_OUT_OF_BOUNDS",function(s){return s?`${s} is outside of buffer bounds`:"Attempt to access memory outside buffer bounds"},RangeError);_r("ERR_INVALID_ARG_TYPE",function(s,e){return`The "${s}" argument must be of type number. Received type ${typeof e}`},TypeError);_r("ERR_OUT_OF_RANGE",function(s,e,t){let r=`The value of "${s}" is out of range.`,n=t;return Number.isInteger(t)&&Math.abs(t)>2**32?n=Yo(String(t)):typeof t=="bigint"&&(n=String(t),(t>BigInt(2)**BigInt(32)||t<-(BigInt(2)**BigInt(32)))&&(n=Yo(n)),n+="n"),r+=` It must be ${e}. Received ${n}`,r},RangeError);function Yo(s){let e="",t=s.length,r=s[0]==="-"?1:0;for(;t>=r+4;t-=3)e=`_${s.slice(t-3,t)}${e}`;return`${s.slice(0,t)}${e}`}function Tc(s,e,t){mt(e,"offset"),(s[e]===void 0||s[e+t]===void 0)&&vt(e,s.length-(t+1))}function na(s,e,t,r,n,i){if(s>t||s<e){let o=typeof e=="bigint"?"n":"",a;throw i>3?e===0||e===BigInt(0)?a=`>= 0${o} and < 2${o} ** ${(i+1)*8}${o}`:a=`>= -(2${o} ** ${(i+1)*8-1}${o}) and < 2 ** ${(i+1)*8-1}${o}`:a=`>= ${e}${o} and <= ${t}${o}`,new dt.ERR_OUT_OF_RANGE("value",a,s)}Tc(r,n,i)}function mt(s,e){if(typeof s!="number")throw new dt.ERR_INVALID_ARG_TYPE(e,"number",s)}function vt(s,e,t){throw Math.floor(s)!==s?(mt(s,t),new dt.ERR_OUT_OF_RANGE(t||"offset","an integer",s)):e<0?new dt.ERR_BUFFER_OUT_OF_BOUNDS:new dt.ERR_OUT_OF_RANGE(t||"offset",`>= ${t?1:0} and <= ${e}`,s)}var Sc=/[^+/0-9A-Za-z-_]/g;function Ic(s){if(s=s.split("=")[0],s=s.trim().replace(Sc,""),s.length<2)return"";for(;s.length%4!==0;)s=s+"=";return s}function kr(s,e){e=e||1/0;let t,r=s.length,n=null,i=[];for(let o=0;o<r;++o){if(t=s.charCodeAt(o),t>55295&&t<57344){if(!n){if(t>56319){(e-=3)>-1&&i.push(239,191,189);continue}else if(o+1===r){(e-=3)>-1&&i.push(239,191,189);continue}n=t;continue}if(t<56320){(e-=3)>-1&&i.push(239,191,189),n=t;continue}t=(n-55296<<10|t-56320)+65536}else n&&(e-=3)>-1&&i.push(239,191,189);if(n=null,t<128){if((e-=1)<0)break;i.push(t)}else if(t<2048){if((e-=2)<0)break;i.push(t>>6|192,t&63|128)}else if(t<65536){if((e-=3)<0)break;i.push(t>>12|224,t>>6&63|128,t&63|128)}else if(t<1114112){if((e-=4)<0)break;i.push(t>>18|240,t>>12&63|128,t>>6&63|128,t&63|128)}else throw new Error("Invalid code point")}return i}function Oc(s){let e=[];for(let t=0;t<s.length;++t)e.push(s.charCodeAt(t)&255);return e}function xc(s,e){let t,r,n,i=[];for(let o=0;o<s.length&&!((e-=2)<0);++o)t=s.charCodeAt(o),r=t>>8,n=t%256,i.push(n),i.push(r);return i}function ia(s){return vr.toByteArray(Ic(s))}function cs(s,e,t,r){let n;for(n=0;n<r&&!(n+t>=e.length||n>=s.length);++n)e[n+t]=s[n];return n}function ve(s,e){return s instanceof e||s!=null&&s.constructor!=null&&s.constructor.name!=null&&s.constructor.name===e.name}function Gr(s){return s!==s}var Cc=(function(){let s="0123456789abcdef",e=new Array(256);for(let t=0;t<16;++t){let r=t*16;for(let n=0;n<16;++n)e[r+n]=s[t]+s[n]}return e})();function qe(s){return typeof BigInt>"u"?wc:s}function wc(){throw new Error("BigInt not supported")}});function oa(){let s=jr.shift();jr.length||Et?.port1.unref?.(),s&&!s.cleared&&s.fn(...s.args)}function R(s,...e){if(typeof globalThis.setImmediate=="function")return globalThis.setImmediate(s,...e);let t={fn:s,args:e,cleared:!1};return jr.push(t),typeof MessageChannel=="function"?(Et||(Et=new MessageChannel,Et.port1.onmessage=oa),Et.port1.ref?.(),Et.port2.postMessage(null)):setTimeout(oa,0),t}function D(s){if(typeof globalThis.clearImmediate=="function")return globalThis.clearImmediate(s);s&&typeof s=="object"&&(s.cleared=!0)}var b,jr,Et,U,g=Lr(()=>{"use strict";b=Ut(Xr(),1),jr=[],Et=null;U=globalThis.process||{env:{},nextTick:(s,...e)=>queueMicrotask(()=>s(...e))}});var ds=as((yp,Vr)=>{"use strict";g();var At=typeof Reflect=="object"?Reflect:null,aa=At&&typeof At.apply=="function"?At.apply:function(e,t,r){return Function.prototype.apply.call(e,t,r)},fs;At&&typeof At.ownKeys=="function"?fs=At.ownKeys:Object.getOwnPropertySymbols?fs=function(e){return Object.getOwnPropertyNames(e).concat(Object.getOwnPropertySymbols(e))}:fs=function(e){return Object.getOwnPropertyNames(e)};function Nc(s){console&&console.warn&&console.warn(s)}var la=Number.isNaN||function(e){return e!==e};function oe(){oe.init.call(this)}Vr.exports=oe;Vr.exports.once=Dc;oe.EventEmitter=oe;oe.prototype._events=void 0;oe.prototype._eventsCount=0;oe.prototype._maxListeners=void 0;var ua=10;function hs(s){if(typeof s!="function")throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof s)}Object.defineProperty(oe,"defaultMaxListeners",{enumerable:!0,get:function(){return ua},set:function(s){if(typeof s!="number"||s<0||la(s))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+s+".");ua=s}});oe.init=function(){(this._events===void 0||this._events===Object.getPrototypeOf(this)._events)&&(this._events=Object.create(null),this._eventsCount=0),this._maxListeners=this._maxListeners||void 0};oe.prototype.setMaxListeners=function(e){if(typeof e!="number"||e<0||la(e))throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received '+e+".");return this._maxListeners=e,this};function ca(s){return s._maxListeners===void 0?oe.defaultMaxListeners:s._maxListeners}oe.prototype.getMaxListeners=function(){return ca(this)};oe.prototype.emit=function(e){for(var t=[],r=1;r<arguments.length;r++)t.push(arguments[r]);var n=e==="error",i=this._events;if(i!==void 0)n=n&&i.error===void 0;else if(!n)return!1;if(n){var o;if(t.length>0&&(o=t[0]),o instanceof Error)throw o;var a=new Error("Unhandled error."+(o?" ("+o.message+")":""));throw a.context=o,a}var u=i[e];if(u===void 0)return!1;if(typeof u=="function")aa(u,this,t);else for(var l=u.length,c=ma(u,l),r=0;r<l;++r)aa(c[r],this,t);return!0};function fa(s,e,t,r){var n,i,o;if(hs(t),i=s._events,i===void 0?(i=s._events=Object.create(null),s._eventsCount=0):(i.newListener!==void 0&&(s.emit("newListener",e,t.listener?t.listener:t),i=s._events),o=i[e]),o===void 0)o=i[e]=t,++s._eventsCount;else if(typeof o=="function"?o=i[e]=r?[t,o]:[o,t]:r?o.unshift(t):o.push(t),n=ca(s),n>0&&o.length>n&&!o.warned){o.warned=!0;var a=new Error("Possible EventEmitter memory leak detected. "+o.length+" "+String(e)+" listeners added. Use emitter.setMaxListeners() to increase limit");a.name="MaxListenersExceededWarning",a.emitter=s,a.type=e,a.count=o.length,Nc(a)}return s}oe.prototype.addListener=function(e,t){return fa(this,e,t,!1)};oe.prototype.on=oe.prototype.addListener;oe.prototype.prependListener=function(e,t){return fa(this,e,t,!0)};function Mc(){if(!this.fired)return this.target.removeListener(this.type,this.wrapFn),this.fired=!0,arguments.length===0?this.listener.call(this.target):this.listener.apply(this.target,arguments)}function ha(s,e,t){var r={fired:!1,wrapFn:void 0,target:s,type:e,listener:t},n=Mc.bind(r);return n.listener=t,r.wrapFn=n,n}oe.prototype.once=function(e,t){return hs(t),this.on(e,ha(this,e,t)),this};oe.prototype.prependOnceListener=function(e,t){return hs(t),this.prependListener(e,ha(this,e,t)),this};oe.prototype.removeListener=function(e,t){var r,n,i,o,a;if(hs(t),n=this._events,n===void 0)return this;if(r=n[e],r===void 0)return this;if(r===t||r.listener===t)--this._eventsCount===0?this._events=Object.create(null):(delete n[e],n.removeListener&&this.emit("removeListener",e,r.listener||t));else if(typeof r!="function"){for(i=-1,o=r.length-1;o>=0;o--)if(r[o]===t||r[o].listener===t){a=r[o].listener,i=o;break}if(i<0)return this;i===0?r.shift():Rc(r,i),r.length===1&&(n[e]=r[0]),n.removeListener!==void 0&&this.emit("removeListener",e,a||t)}return this};oe.prototype.off=oe.prototype.removeListener;oe.prototype.removeAllListeners=function(e){var t,r,n;if(r=this._events,r===void 0)return this;if(r.removeListener===void 0)return arguments.length===0?(this._events=Object.create(null),this._eventsCount=0):r[e]!==void 0&&(--this._eventsCount===0?this._events=Object.create(null):delete r[e]),this;if(arguments.length===0){var i=Object.keys(r),o;for(n=0;n<i.length;++n)o=i[n],o!=="removeListener"&&this.removeAllListeners(o);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if(t=r[e],typeof t=="function")this.removeListener(e,t);else if(t!==void 0)for(n=t.length-1;n>=0;n--)this.removeListener(e,t[n]);return this};function da(s,e,t){var r=s._events;if(r===void 0)return[];var n=r[e];return n===void 0?[]:typeof n=="function"?t?[n.listener||n]:[n]:t?Lc(n):ma(n,n.length)}oe.prototype.listeners=function(e){return da(this,e,!0)};oe.prototype.rawListeners=function(e){return da(this,e,!1)};oe.listenerCount=function(s,e){return typeof s.listenerCount=="function"?s.listenerCount(e):pa.call(s,e)};oe.prototype.listenerCount=pa;function pa(s){var e=this._events;if(e!==void 0){var t=e[s];if(typeof t=="function")return 1;if(t!==void 0)return t.length}return 0}oe.prototype.eventNames=function(){return this._eventsCount>0?fs(this._events):[]};function ma(s,e){for(var t=new Array(e),r=0;r<e;++r)t[r]=s[r];return t}function Rc(s,e){for(;e+1<s.length;e++)s[e]=s[e+1];s.pop()}function Lc(s){for(var e=new Array(s.length),t=0;t<e.length;++t)e[t]=s[t].listener||s[t];return e}function Dc(s,e){return new Promise(function(t,r){function n(o){s.removeListener(e,i),r(o)}function i(){typeof s.removeListener=="function"&&s.removeListener("error",n),t([].slice.call(arguments))}ga(s,e,i,{once:!0}),e!=="error"&&Uc(s,n,{once:!0})})}function Uc(s,e,t){typeof s.on=="function"&&ga(s,"error",e,t)}function ga(s,e,t,r){if(typeof s.on=="function")r.once?s.once(e,t):s.on(e,t);else if(typeof s.addEventListener=="function")s.addEventListener(e,function n(i){r.once&&s.removeEventListener(e,n),t(i)});else throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof s)}});var Cr,Ml=Lr(()=>{g();Cr=class{constructor(){throw new Error("SMTP is not available in the browser")}}});var Rl={};Kl(Rl,{startSMTPServer:()=>zd});function zd(s,e,t,r){let n=e.getCredentials(),i=new Cr({banner:"ImapKit",key:n.key,cert:n.cert,authOptional:!0,authMethods:e.oauth?["PLAIN","LOGIN","XOAUTH2"]:["PLAIN","LOGIN"],logger:!1,onAuth(a,u,l){if(a.method!=="XOAUTH2")return l(null,{user:a.username});let c=e.checkAccessToken(a.accessToken||"",a.username,"smtp");if("error"in c)return l(null,{data:{status:"401",schemes:"bearer",scope:e.oauth.mailScope}});l(null,{user:c.user})},onData(a,u,l){let c=[];a.on("data",f=>c.push(f)),a.on("error",l),a.on("end",()=>{e.appendMessage("INBOX",[],!1,b.Buffer.concat(c).toString("binary")),l()})}});i.on("error",a=>{e.options.debug&&console.error("SMTP server error: %s",a.message)});let o=()=>t?.(i.server.address().port);return r?i.listen(s,r,o):i.listen(s,o),i}var Ll=Lr(()=>{"use strict";g();Ml()});g();g();g();var Ea=Ut(ds()),ps=class extends Ea.default{};g();var Qr=Ut(ds()),Yr=s=>()=>{throw new Error(s+" is not available in the browser, open connections with server.connect()")},ms=class extends Qr.default{},qr=class extends ms{constructor(){super(),Yr("TLS")()}},gs=class extends Qr.default{listen(){Yr("listen()")()}close(e){return e&&queueMicrotask(()=>e()),this}address(){return null}},vc=()=>new gs,Bc=Yr("TLS"),Qe={Socket:ms,TLSSocket:qr,Server:gs,createServer:vc,createSecureContext:Bc};g();g();g();var Hc=Ut(Xr());function Ye(s){try{return new TextDecoder("utf-8",{fatal:!0}).decode(s),!0}catch{return!1}}g();var xe=s=>{let e;return()=>(e===void 0&&(e=s()),e)},tt=(s,e)=>{let t=[];for(let r=s;r<=e;r++)t.push(r);return String.fromCharCode(...t)},Es=(s,e)=>Array.from(s).filter(t=>!e.includes(t)).join(""),kc=xe(()=>new Set(me["ATOM-CHAR"]())),me={CHAR:xe(()=>tt(1,127)),CHAR8:xe(()=>tt(1,255)),SP:()=>" ",CTL:xe(()=>tt(0,31)+"\x7F"),DQUOTE:()=>'"',ALPHA:xe(()=>tt(65,90)+tt(97,122)),DIGIT:xe(()=>tt(48,57)),"ATOM-CHAR":xe(()=>Es(me.CHAR(),me["atom-specials"]())),"ASTRING-CHAR":xe(()=>me["ATOM-CHAR"]()+me["resp-specials"]()),"TEXT-CHAR":xe(()=>Es(me.CHAR(),`\r
1
+ var jl=Object.create;var Rr=Object.defineProperty;var Vl=Object.getOwnPropertyDescriptor;var ql=Object.getOwnPropertyNames;var Ql=Object.getPrototypeOf,Yl=Object.prototype.hasOwnProperty;var Lr=(s,e,t)=>()=>{if(t)throw t[0];try{return s&&(e=s(s=0)),e}catch(r){throw t=[r],r}};var as=(s,e)=>()=>{try{return e||s((e={exports:{}}).exports,e),e.exports}catch(t){throw e=0,t}},Kl=(s,e)=>{for(var t in e)Rr(s,t,{get:e[t],enumerable:!0})},zl=(s,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of ql(e))!Yl.call(s,n)&&n!==t&&Rr(s,n,{get:()=>e[n],enumerable:!(r=Vl(e,n))||r.enumerable});return s};var Ut=(s,e,t)=>(t=s!=null?jl(Ql(s)):{},zl(e||!s||!s.__esModule?Rr(t,"default",{value:s,enumerable:!0}):t,s));var Xo=as(us=>{"use strict";E();us.byteLength=$l;us.toByteArray=Zl;us.fromByteArray=sc;var Ue=[],Oe=[],Wl=typeof Uint8Array<"u"?Uint8Array:Array,Dr="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";for(Ze=0,_o=Dr.length;Ze<_o;++Ze)Ue[Ze]=Dr[Ze],Oe[Dr.charCodeAt(Ze)]=Ze;var Ze,_o;Oe[45]=62;Oe[95]=63;function Go(s){var e=s.length;if(e%4>0)throw new Error("Invalid string. Length must be a multiple of 4");var t=s.indexOf("=");t===-1&&(t=e);var r=t===e?0:4-t%4;return[t,r]}function $l(s){var e=Go(s),t=e[0],r=e[1];return(t+r)*3/4-r}function Jl(s,e,t){return(e+t)*3/4-t}function Zl(s){var e,t=Go(s),r=t[0],n=t[1],i=new Wl(Jl(s,r,n)),o=0,a=n>0?r-4:r,u;for(u=0;u<a;u+=4)e=Oe[s.charCodeAt(u)]<<18|Oe[s.charCodeAt(u+1)]<<12|Oe[s.charCodeAt(u+2)]<<6|Oe[s.charCodeAt(u+3)],i[o++]=e>>16&255,i[o++]=e>>8&255,i[o++]=e&255;return n===2&&(e=Oe[s.charCodeAt(u)]<<2|Oe[s.charCodeAt(u+1)]>>4,i[o++]=e&255),n===1&&(e=Oe[s.charCodeAt(u)]<<10|Oe[s.charCodeAt(u+1)]<<4|Oe[s.charCodeAt(u+2)]>>2,i[o++]=e>>8&255,i[o++]=e&255),i}function ec(s){return Ue[s>>18&63]+Ue[s>>12&63]+Ue[s>>6&63]+Ue[s&63]}function tc(s,e,t){for(var r,n=[],i=e;i<t;i+=3)r=(s[i]<<16&16711680)+(s[i+1]<<8&65280)+(s[i+2]&255),n.push(ec(r));return n.join("")}function sc(s){for(var e,t=s.length,r=t%3,n=[],i=16383,o=0,a=t-r;o<a;o+=i)n.push(tc(s,o,o+i>a?a:o+i));return r===1?(e=s[t-1],n.push(Ue[e>>2]+Ue[e<<4&63]+"==")):r===2&&(e=(s[t-2]<<8)+s[t-1],n.push(Ue[e>>10]+Ue[e>>4&63]+Ue[e<<2&63]+"=")),n.join("")}});var jo=as(Ur=>{E();Ur.read=function(s,e,t,r,n){var i,o,a=n*8-r-1,u=(1<<a)-1,l=u>>1,c=-7,f=t?n-1:0,p=t?-1:1,y=s[e+f];for(f+=p,i=y&(1<<-c)-1,y>>=-c,c+=a;c>0;i=i*256+s[e+f],f+=p,c-=8);for(o=i&(1<<-c)-1,i>>=-c,c+=r;c>0;o=o*256+s[e+f],f+=p,c-=8);if(i===0)i=1-l;else{if(i===u)return o?NaN:(y?-1:1)*(1/0);o=o+Math.pow(2,r),i=i-l}return(y?-1:1)*o*Math.pow(2,i-r)};Ur.write=function(s,e,t,r,n,i){var o,a,u,l=i*8-n-1,c=(1<<l)-1,f=c>>1,p=n===23?Math.pow(2,-24)-Math.pow(2,-77):0,y=r?0:i-1,A=r?1:-1,m=e<0||e===0&&1/e<0?1:0;for(e=Math.abs(e),isNaN(e)||e===1/0?(a=isNaN(e)?1:0,o=c):(o=Math.floor(Math.log(e)/Math.LN2),e*(u=Math.pow(2,-o))<1&&(o--,u*=2),o+f>=1?e+=p/u:e+=p*Math.pow(2,1-f),e*u>=2&&(o++,u/=2),o+f>=c?(a=0,o=c):o+f>=1?(a=(e*u-1)*Math.pow(2,n),o=o+f):(a=e*Math.pow(2,f-1)*Math.pow(2,n),o=0));n>=8;s[t+y]=a&255,y+=A,a/=256,n-=8);for(o=o<<n|a,l+=n;l>0;s[t+y]=o&255,y+=A,o/=256,l-=8);s[t+y-A]|=m*128}});var Xr=as(gt=>{"use strict";E();var vr=Xo(),pt=jo(),Vo=typeof Symbol=="function"&&typeof Symbol.for=="function"?Symbol.for("nodejs.util.inspect.custom"):null;gt.Buffer=B;gt.SlowBuffer=uc;gt.INSPECT_MAX_BYTES=50;var ls=2147483647;gt.kMaxLength=ls;B.TYPED_ARRAY_SUPPORT=rc();!B.TYPED_ARRAY_SUPPORT&&typeof console<"u"&&typeof console.error=="function"&&console.error("This browser lacks typed array (Uint8Array) support which is required by `buffer` v5.x. Use `buffer` v4.x if you require old browser support.");function rc(){try{let s=new Uint8Array(1),e={foo:function(){return 42}};return Object.setPrototypeOf(e,Uint8Array.prototype),Object.setPrototypeOf(s,e),s.foo()===42}catch{return!1}}Object.defineProperty(B.prototype,"parent",{enumerable:!0,get:function(){if(B.isBuffer(this))return this.buffer}});Object.defineProperty(B.prototype,"offset",{enumerable:!0,get:function(){if(B.isBuffer(this))return this.byteOffset}});function Pe(s){if(s>ls)throw new RangeError('The value "'+s+'" is invalid for option "size"');let e=new Uint8Array(s);return Object.setPrototypeOf(e,B.prototype),e}function B(s,e,t){if(typeof s=="number"){if(typeof e=="string")throw new TypeError('The "string" argument must be of type string. Received type number');return Pr(s)}return Ko(s,e,t)}B.poolSize=8192;function Ko(s,e,t){if(typeof s=="string")return ic(s,e);if(ArrayBuffer.isView(s))return oc(s);if(s==null)throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof s);if(ve(s,ArrayBuffer)||s&&ve(s.buffer,ArrayBuffer)||typeof SharedArrayBuffer<"u"&&(ve(s,SharedArrayBuffer)||s&&ve(s.buffer,SharedArrayBuffer)))return Hr(s,e,t);if(typeof s=="number")throw new TypeError('The "value" argument must not be of type number. Received type number');let r=s.valueOf&&s.valueOf();if(r!=null&&r!==s)return B.from(r,e,t);let n=ac(s);if(n)return n;if(typeof Symbol<"u"&&Symbol.toPrimitive!=null&&typeof s[Symbol.toPrimitive]=="function")return B.from(s[Symbol.toPrimitive]("string"),e,t);throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof s)}B.from=function(s,e,t){return Ko(s,e,t)};Object.setPrototypeOf(B.prototype,Uint8Array.prototype);Object.setPrototypeOf(B,Uint8Array);function zo(s){if(typeof s!="number")throw new TypeError('"size" argument must be of type number');if(s<0)throw new RangeError('The value "'+s+'" is invalid for option "size"')}function nc(s,e,t){return zo(s),s<=0?Pe(s):e!==void 0?typeof t=="string"?Pe(s).fill(e,t):Pe(s).fill(e):Pe(s)}B.alloc=function(s,e,t){return nc(s,e,t)};function Pr(s){return zo(s),Pe(s<0?0:Fr(s)|0)}B.allocUnsafe=function(s){return Pr(s)};B.allocUnsafeSlow=function(s){return Pr(s)};function ic(s,e){if((typeof e!="string"||e==="")&&(e="utf8"),!B.isEncoding(e))throw new TypeError("Unknown encoding: "+e);let t=Wo(s,e)|0,r=Pe(t),n=r.write(s,e);return n!==t&&(r=r.slice(0,n)),r}function Br(s){let e=s.length<0?0:Fr(s.length)|0,t=Pe(e);for(let r=0;r<e;r+=1)t[r]=s[r]&255;return t}function oc(s){if(ve(s,Uint8Array)){let e=new Uint8Array(s);return Hr(e.buffer,e.byteOffset,e.byteLength)}return Br(s)}function Hr(s,e,t){if(e<0||s.byteLength<e)throw new RangeError('"offset" is outside of buffer bounds');if(s.byteLength<e+(t||0))throw new RangeError('"length" is outside of buffer bounds');let r;return e===void 0&&t===void 0?r=new Uint8Array(s):t===void 0?r=new Uint8Array(s,e):r=new Uint8Array(s,e,t),Object.setPrototypeOf(r,B.prototype),r}function ac(s){if(B.isBuffer(s)){let e=Fr(s.length)|0,t=Pe(e);return t.length===0||s.copy(t,0,0,e),t}if(s.length!==void 0)return typeof s.length!="number"||Gr(s.length)?Pe(0):Br(s);if(s.type==="Buffer"&&Array.isArray(s.data))return Br(s.data)}function Fr(s){if(s>=ls)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+ls.toString(16)+" bytes");return s|0}function uc(s){return+s!=s&&(s=0),B.alloc(+s)}B.isBuffer=function(e){return e!=null&&e._isBuffer===!0&&e!==B.prototype};B.compare=function(e,t){if(ve(e,Uint8Array)&&(e=B.from(e,e.offset,e.byteLength)),ve(t,Uint8Array)&&(t=B.from(t,t.offset,t.byteLength)),!B.isBuffer(e)||!B.isBuffer(t))throw new TypeError('The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array');if(e===t)return 0;let r=e.length,n=t.length;for(let i=0,o=Math.min(r,n);i<o;++i)if(e[i]!==t[i]){r=e[i],n=t[i];break}return r<n?-1:n<r?1:0};B.isEncoding=function(e){switch(String(e).toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"latin1":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return!0;default:return!1}};B.concat=function(e,t){if(!Array.isArray(e))throw new TypeError('"list" argument must be an Array of Buffers');if(e.length===0)return B.alloc(0);let r;if(t===void 0)for(t=0,r=0;r<e.length;++r)t+=e[r].length;let n=B.allocUnsafe(t),i=0;for(r=0;r<e.length;++r){let o=e[r];if(ve(o,Uint8Array))i+o.length>n.length?(B.isBuffer(o)||(o=B.from(o)),o.copy(n,i)):Uint8Array.prototype.set.call(n,o,i);else if(B.isBuffer(o))o.copy(n,i);else throw new TypeError('"list" argument must be an Array of Buffers');i+=o.length}return n};function Wo(s,e){if(B.isBuffer(s))return s.length;if(ArrayBuffer.isView(s)||ve(s,ArrayBuffer))return s.byteLength;if(typeof s!="string")throw new TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type '+typeof s);let t=s.length,r=arguments.length>2&&arguments[2]===!0;if(!r&&t===0)return 0;let n=!1;for(;;)switch(e){case"ascii":case"latin1":case"binary":return t;case"utf8":case"utf-8":return kr(s).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return t*2;case"hex":return t>>>1;case"base64":return ia(s).length;default:if(n)return r?-1:kr(s).length;e=(""+e).toLowerCase(),n=!0}}B.byteLength=Wo;function lc(s,e,t){let r=!1;if((e===void 0||e<0)&&(e=0),e>this.length||((t===void 0||t>this.length)&&(t=this.length),t<=0)||(t>>>=0,e>>>=0,t<=e))return"";for(s||(s="utf8");;)switch(s){case"hex":return yc(this,e,t);case"utf8":case"utf-8":return Jo(this,e,t);case"ascii":return Ec(this,e,t);case"latin1":case"binary":return Ac(this,e,t);case"base64":return mc(this,e,t);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return bc(this,e,t);default:if(r)throw new TypeError("Unknown encoding: "+s);s=(s+"").toLowerCase(),r=!0}}B.prototype._isBuffer=!0;function et(s,e,t){let r=s[e];s[e]=s[t],s[t]=r}B.prototype.swap16=function(){let e=this.length;if(e%2!==0)throw new RangeError("Buffer size must be a multiple of 16-bits");for(let t=0;t<e;t+=2)et(this,t,t+1);return this};B.prototype.swap32=function(){let e=this.length;if(e%4!==0)throw new RangeError("Buffer size must be a multiple of 32-bits");for(let t=0;t<e;t+=4)et(this,t,t+3),et(this,t+1,t+2);return this};B.prototype.swap64=function(){let e=this.length;if(e%8!==0)throw new RangeError("Buffer size must be a multiple of 64-bits");for(let t=0;t<e;t+=8)et(this,t,t+7),et(this,t+1,t+6),et(this,t+2,t+5),et(this,t+3,t+4);return this};B.prototype.toString=function(){let e=this.length;return e===0?"":arguments.length===0?Jo(this,0,e):lc.apply(this,arguments)};B.prototype.toLocaleString=B.prototype.toString;B.prototype.equals=function(e){if(!B.isBuffer(e))throw new TypeError("Argument must be a Buffer");return this===e?!0:B.compare(this,e)===0};B.prototype.inspect=function(){let e="",t=gt.INSPECT_MAX_BYTES;return e=this.toString("hex",0,t).replace(/(.{2})/g,"$1 ").trim(),this.length>t&&(e+=" ... "),"<Buffer "+e+">"};Vo&&(B.prototype[Vo]=B.prototype.inspect);B.prototype.compare=function(e,t,r,n,i){if(ve(e,Uint8Array)&&(e=B.from(e,e.offset,e.byteLength)),!B.isBuffer(e))throw new TypeError('The "target" argument must be one of type Buffer or Uint8Array. Received type '+typeof e);if(t===void 0&&(t=0),r===void 0&&(r=e?e.length:0),n===void 0&&(n=0),i===void 0&&(i=this.length),t<0||r>e.length||n<0||i>this.length)throw new RangeError("out of range index");if(n>=i&&t>=r)return 0;if(n>=i)return-1;if(t>=r)return 1;if(t>>>=0,r>>>=0,n>>>=0,i>>>=0,this===e)return 0;let o=i-n,a=r-t,u=Math.min(o,a),l=this.slice(n,i),c=e.slice(t,r);for(let f=0;f<u;++f)if(l[f]!==c[f]){o=l[f],a=c[f];break}return o<a?-1:a<o?1:0};function $o(s,e,t,r,n){if(s.length===0)return-1;if(typeof t=="string"?(r=t,t=0):t>2147483647?t=2147483647:t<-2147483648&&(t=-2147483648),t=+t,Gr(t)&&(t=n?0:s.length-1),t<0&&(t=s.length+t),t>=s.length){if(n)return-1;t=s.length-1}else if(t<0)if(n)t=0;else return-1;if(typeof e=="string"&&(e=B.from(e,r)),B.isBuffer(e))return e.length===0?-1:qo(s,e,t,r,n);if(typeof e=="number")return e=e&255,typeof Uint8Array.prototype.indexOf=="function"?n?Uint8Array.prototype.indexOf.call(s,e,t):Uint8Array.prototype.lastIndexOf.call(s,e,t):qo(s,[e],t,r,n);throw new TypeError("val must be string, number or Buffer")}function qo(s,e,t,r,n){let i=1,o=s.length,a=e.length;if(r!==void 0&&(r=String(r).toLowerCase(),r==="ucs2"||r==="ucs-2"||r==="utf16le"||r==="utf-16le")){if(s.length<2||e.length<2)return-1;i=2,o/=2,a/=2,t/=2}function u(c,f){return i===1?c[f]:c.readUInt16BE(f*i)}let l;if(n){let c=-1;for(l=t;l<o;l++)if(u(s,l)===u(e,c===-1?0:l-c)){if(c===-1&&(c=l),l-c+1===a)return c*i}else c!==-1&&(l-=l-c),c=-1}else for(t+a>o&&(t=o-a),l=t;l>=0;l--){let c=!0;for(let f=0;f<a;f++)if(u(s,l+f)!==u(e,f)){c=!1;break}if(c)return l}return-1}B.prototype.includes=function(e,t,r){return this.indexOf(e,t,r)!==-1};B.prototype.indexOf=function(e,t,r){return $o(this,e,t,r,!0)};B.prototype.lastIndexOf=function(e,t,r){return $o(this,e,t,r,!1)};function cc(s,e,t,r){t=Number(t)||0;let n=s.length-t;r?(r=Number(r),r>n&&(r=n)):r=n;let i=e.length;r>i/2&&(r=i/2);let o;for(o=0;o<r;++o){let a=parseInt(e.substr(o*2,2),16);if(Gr(a))return o;s[t+o]=a}return o}function fc(s,e,t,r){return cs(kr(e,s.length-t),s,t,r)}function hc(s,e,t,r){return cs(Oc(e),s,t,r)}function dc(s,e,t,r){return cs(ia(e),s,t,r)}function pc(s,e,t,r){return cs(xc(e,s.length-t),s,t,r)}B.prototype.write=function(e,t,r,n){if(t===void 0)n="utf8",r=this.length,t=0;else if(r===void 0&&typeof t=="string")n=t,r=this.length,t=0;else if(isFinite(t))t=t>>>0,isFinite(r)?(r=r>>>0,n===void 0&&(n="utf8")):(n=r,r=void 0);else throw new Error("Buffer.write(string, encoding, offset[, length]) is no longer supported");let i=this.length-t;if((r===void 0||r>i)&&(r=i),e.length>0&&(r<0||t<0)||t>this.length)throw new RangeError("Attempt to write outside buffer bounds");n||(n="utf8");let o=!1;for(;;)switch(n){case"hex":return cc(this,e,t,r);case"utf8":case"utf-8":return fc(this,e,t,r);case"ascii":case"latin1":case"binary":return hc(this,e,t,r);case"base64":return dc(this,e,t,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return pc(this,e,t,r);default:if(o)throw new TypeError("Unknown encoding: "+n);n=(""+n).toLowerCase(),o=!0}};B.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};function mc(s,e,t){return e===0&&t===s.length?vr.fromByteArray(s):vr.fromByteArray(s.slice(e,t))}function Jo(s,e,t){t=Math.min(s.length,t);let r=[],n=e;for(;n<t;){let i=s[n],o=null,a=i>239?4:i>223?3:i>191?2:1;if(n+a<=t){let u,l,c,f;switch(a){case 1:i<128&&(o=i);break;case 2:u=s[n+1],(u&192)===128&&(f=(i&31)<<6|u&63,f>127&&(o=f));break;case 3:u=s[n+1],l=s[n+2],(u&192)===128&&(l&192)===128&&(f=(i&15)<<12|(u&63)<<6|l&63,f>2047&&(f<55296||f>57343)&&(o=f));break;case 4:u=s[n+1],l=s[n+2],c=s[n+3],(u&192)===128&&(l&192)===128&&(c&192)===128&&(f=(i&15)<<18|(u&63)<<12|(l&63)<<6|c&63,f>65535&&f<1114112&&(o=f))}}o===null?(o=65533,a=1):o>65535&&(o-=65536,r.push(o>>>10&1023|55296),o=56320|o&1023),r.push(o),n+=a}return gc(r)}var Qo=4096;function gc(s){let e=s.length;if(e<=Qo)return String.fromCharCode.apply(String,s);let t="",r=0;for(;r<e;)t+=String.fromCharCode.apply(String,s.slice(r,r+=Qo));return t}function Ec(s,e,t){let r="";t=Math.min(s.length,t);for(let n=e;n<t;++n)r+=String.fromCharCode(s[n]&127);return r}function Ac(s,e,t){let r="";t=Math.min(s.length,t);for(let n=e;n<t;++n)r+=String.fromCharCode(s[n]);return r}function yc(s,e,t){let r=s.length;(!e||e<0)&&(e=0),(!t||t<0||t>r)&&(t=r);let n="";for(let i=e;i<t;++i)n+=Cc[s[i]];return n}function bc(s,e,t){let r=s.slice(e,t),n="";for(let i=0;i<r.length-1;i+=2)n+=String.fromCharCode(r[i]+r[i+1]*256);return n}B.prototype.slice=function(e,t){let r=this.length;e=~~e,t=t===void 0?r:~~t,e<0?(e+=r,e<0&&(e=0)):e>r&&(e=r),t<0?(t+=r,t<0&&(t=0)):t>r&&(t=r),t<e&&(t=e);let n=this.subarray(e,t);return Object.setPrototypeOf(n,B.prototype),n};function le(s,e,t){if(s%1!==0||s<0)throw new RangeError("offset is not uint");if(s+e>t)throw new RangeError("Trying to access beyond buffer length")}B.prototype.readUintLE=B.prototype.readUIntLE=function(e,t,r){e=e>>>0,t=t>>>0,r||le(e,t,this.length);let n=this[e],i=1,o=0;for(;++o<t&&(i*=256);)n+=this[e+o]*i;return n};B.prototype.readUintBE=B.prototype.readUIntBE=function(e,t,r){e=e>>>0,t=t>>>0,r||le(e,t,this.length);let n=this[e+--t],i=1;for(;t>0&&(i*=256);)n+=this[e+--t]*i;return n};B.prototype.readUint8=B.prototype.readUInt8=function(e,t){return e=e>>>0,t||le(e,1,this.length),this[e]};B.prototype.readUint16LE=B.prototype.readUInt16LE=function(e,t){return e=e>>>0,t||le(e,2,this.length),this[e]|this[e+1]<<8};B.prototype.readUint16BE=B.prototype.readUInt16BE=function(e,t){return e=e>>>0,t||le(e,2,this.length),this[e]<<8|this[e+1]};B.prototype.readUint32LE=B.prototype.readUInt32LE=function(e,t){return e=e>>>0,t||le(e,4,this.length),(this[e]|this[e+1]<<8|this[e+2]<<16)+this[e+3]*16777216};B.prototype.readUint32BE=B.prototype.readUInt32BE=function(e,t){return e=e>>>0,t||le(e,4,this.length),this[e]*16777216+(this[e+1]<<16|this[e+2]<<8|this[e+3])};B.prototype.readBigUInt64LE=qe(function(e){e=e>>>0,mt(e,"offset");let t=this[e],r=this[e+7];(t===void 0||r===void 0)&&vt(e,this.length-8);let n=t+this[++e]*2**8+this[++e]*2**16+this[++e]*2**24,i=this[++e]+this[++e]*2**8+this[++e]*2**16+r*2**24;return BigInt(n)+(BigInt(i)<<BigInt(32))});B.prototype.readBigUInt64BE=qe(function(e){e=e>>>0,mt(e,"offset");let t=this[e],r=this[e+7];(t===void 0||r===void 0)&&vt(e,this.length-8);let n=t*2**24+this[++e]*2**16+this[++e]*2**8+this[++e],i=this[++e]*2**24+this[++e]*2**16+this[++e]*2**8+r;return(BigInt(n)<<BigInt(32))+BigInt(i)});B.prototype.readIntLE=function(e,t,r){e=e>>>0,t=t>>>0,r||le(e,t,this.length);let n=this[e],i=1,o=0;for(;++o<t&&(i*=256);)n+=this[e+o]*i;return i*=128,n>=i&&(n-=Math.pow(2,8*t)),n};B.prototype.readIntBE=function(e,t,r){e=e>>>0,t=t>>>0,r||le(e,t,this.length);let n=t,i=1,o=this[e+--n];for(;n>0&&(i*=256);)o+=this[e+--n]*i;return i*=128,o>=i&&(o-=Math.pow(2,8*t)),o};B.prototype.readInt8=function(e,t){return e=e>>>0,t||le(e,1,this.length),this[e]&128?(255-this[e]+1)*-1:this[e]};B.prototype.readInt16LE=function(e,t){e=e>>>0,t||le(e,2,this.length);let r=this[e]|this[e+1]<<8;return r&32768?r|4294901760:r};B.prototype.readInt16BE=function(e,t){e=e>>>0,t||le(e,2,this.length);let r=this[e+1]|this[e]<<8;return r&32768?r|4294901760:r};B.prototype.readInt32LE=function(e,t){return e=e>>>0,t||le(e,4,this.length),this[e]|this[e+1]<<8|this[e+2]<<16|this[e+3]<<24};B.prototype.readInt32BE=function(e,t){return e=e>>>0,t||le(e,4,this.length),this[e]<<24|this[e+1]<<16|this[e+2]<<8|this[e+3]};B.prototype.readBigInt64LE=qe(function(e){e=e>>>0,mt(e,"offset");let t=this[e],r=this[e+7];(t===void 0||r===void 0)&&vt(e,this.length-8);let n=this[e+4]+this[e+5]*2**8+this[e+6]*2**16+(r<<24);return(BigInt(n)<<BigInt(32))+BigInt(t+this[++e]*2**8+this[++e]*2**16+this[++e]*2**24)});B.prototype.readBigInt64BE=qe(function(e){e=e>>>0,mt(e,"offset");let t=this[e],r=this[e+7];(t===void 0||r===void 0)&&vt(e,this.length-8);let n=(t<<24)+this[++e]*2**16+this[++e]*2**8+this[++e];return(BigInt(n)<<BigInt(32))+BigInt(this[++e]*2**24+this[++e]*2**16+this[++e]*2**8+r)});B.prototype.readFloatLE=function(e,t){return e=e>>>0,t||le(e,4,this.length),pt.read(this,e,!0,23,4)};B.prototype.readFloatBE=function(e,t){return e=e>>>0,t||le(e,4,this.length),pt.read(this,e,!1,23,4)};B.prototype.readDoubleLE=function(e,t){return e=e>>>0,t||le(e,8,this.length),pt.read(this,e,!0,52,8)};B.prototype.readDoubleBE=function(e,t){return e=e>>>0,t||le(e,8,this.length),pt.read(this,e,!1,52,8)};function Ee(s,e,t,r,n,i){if(!B.isBuffer(s))throw new TypeError('"buffer" argument must be a Buffer instance');if(e>n||e<i)throw new RangeError('"value" argument is out of bounds');if(t+r>s.length)throw new RangeError("Index out of range")}B.prototype.writeUintLE=B.prototype.writeUIntLE=function(e,t,r,n){if(e=+e,t=t>>>0,r=r>>>0,!n){let a=Math.pow(2,8*r)-1;Ee(this,e,t,r,a,0)}let i=1,o=0;for(this[t]=e&255;++o<r&&(i*=256);)this[t+o]=e/i&255;return t+r};B.prototype.writeUintBE=B.prototype.writeUIntBE=function(e,t,r,n){if(e=+e,t=t>>>0,r=r>>>0,!n){let a=Math.pow(2,8*r)-1;Ee(this,e,t,r,a,0)}let i=r-1,o=1;for(this[t+i]=e&255;--i>=0&&(o*=256);)this[t+i]=e/o&255;return t+r};B.prototype.writeUint8=B.prototype.writeUInt8=function(e,t,r){return e=+e,t=t>>>0,r||Ee(this,e,t,1,255,0),this[t]=e&255,t+1};B.prototype.writeUint16LE=B.prototype.writeUInt16LE=function(e,t,r){return e=+e,t=t>>>0,r||Ee(this,e,t,2,65535,0),this[t]=e&255,this[t+1]=e>>>8,t+2};B.prototype.writeUint16BE=B.prototype.writeUInt16BE=function(e,t,r){return e=+e,t=t>>>0,r||Ee(this,e,t,2,65535,0),this[t]=e>>>8,this[t+1]=e&255,t+2};B.prototype.writeUint32LE=B.prototype.writeUInt32LE=function(e,t,r){return e=+e,t=t>>>0,r||Ee(this,e,t,4,4294967295,0),this[t+3]=e>>>24,this[t+2]=e>>>16,this[t+1]=e>>>8,this[t]=e&255,t+4};B.prototype.writeUint32BE=B.prototype.writeUInt32BE=function(e,t,r){return e=+e,t=t>>>0,r||Ee(this,e,t,4,4294967295,0),this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=e&255,t+4};function Zo(s,e,t,r,n){na(e,r,n,s,t,7);let i=Number(e&BigInt(4294967295));s[t++]=i,i=i>>8,s[t++]=i,i=i>>8,s[t++]=i,i=i>>8,s[t++]=i;let o=Number(e>>BigInt(32)&BigInt(4294967295));return s[t++]=o,o=o>>8,s[t++]=o,o=o>>8,s[t++]=o,o=o>>8,s[t++]=o,t}function ea(s,e,t,r,n){na(e,r,n,s,t,7);let i=Number(e&BigInt(4294967295));s[t+7]=i,i=i>>8,s[t+6]=i,i=i>>8,s[t+5]=i,i=i>>8,s[t+4]=i;let o=Number(e>>BigInt(32)&BigInt(4294967295));return s[t+3]=o,o=o>>8,s[t+2]=o,o=o>>8,s[t+1]=o,o=o>>8,s[t]=o,t+8}B.prototype.writeBigUInt64LE=qe(function(e,t=0){return Zo(this,e,t,BigInt(0),BigInt("0xffffffffffffffff"))});B.prototype.writeBigUInt64BE=qe(function(e,t=0){return ea(this,e,t,BigInt(0),BigInt("0xffffffffffffffff"))});B.prototype.writeIntLE=function(e,t,r,n){if(e=+e,t=t>>>0,!n){let u=Math.pow(2,8*r-1);Ee(this,e,t,r,u-1,-u)}let i=0,o=1,a=0;for(this[t]=e&255;++i<r&&(o*=256);)e<0&&a===0&&this[t+i-1]!==0&&(a=1),this[t+i]=(e/o>>0)-a&255;return t+r};B.prototype.writeIntBE=function(e,t,r,n){if(e=+e,t=t>>>0,!n){let u=Math.pow(2,8*r-1);Ee(this,e,t,r,u-1,-u)}let i=r-1,o=1,a=0;for(this[t+i]=e&255;--i>=0&&(o*=256);)e<0&&a===0&&this[t+i+1]!==0&&(a=1),this[t+i]=(e/o>>0)-a&255;return t+r};B.prototype.writeInt8=function(e,t,r){return e=+e,t=t>>>0,r||Ee(this,e,t,1,127,-128),e<0&&(e=255+e+1),this[t]=e&255,t+1};B.prototype.writeInt16LE=function(e,t,r){return e=+e,t=t>>>0,r||Ee(this,e,t,2,32767,-32768),this[t]=e&255,this[t+1]=e>>>8,t+2};B.prototype.writeInt16BE=function(e,t,r){return e=+e,t=t>>>0,r||Ee(this,e,t,2,32767,-32768),this[t]=e>>>8,this[t+1]=e&255,t+2};B.prototype.writeInt32LE=function(e,t,r){return e=+e,t=t>>>0,r||Ee(this,e,t,4,2147483647,-2147483648),this[t]=e&255,this[t+1]=e>>>8,this[t+2]=e>>>16,this[t+3]=e>>>24,t+4};B.prototype.writeInt32BE=function(e,t,r){return e=+e,t=t>>>0,r||Ee(this,e,t,4,2147483647,-2147483648),e<0&&(e=4294967295+e+1),this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=e&255,t+4};B.prototype.writeBigInt64LE=qe(function(e,t=0){return Zo(this,e,t,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))});B.prototype.writeBigInt64BE=qe(function(e,t=0){return ea(this,e,t,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))});function ta(s,e,t,r,n,i){if(t+r>s.length)throw new RangeError("Index out of range");if(t<0)throw new RangeError("Index out of range")}function sa(s,e,t,r,n){return e=+e,t=t>>>0,n||ta(s,e,t,4,34028234663852886e22,-34028234663852886e22),pt.write(s,e,t,r,23,4),t+4}B.prototype.writeFloatLE=function(e,t,r){return sa(this,e,t,!0,r)};B.prototype.writeFloatBE=function(e,t,r){return sa(this,e,t,!1,r)};function ra(s,e,t,r,n){return e=+e,t=t>>>0,n||ta(s,e,t,8,17976931348623157e292,-17976931348623157e292),pt.write(s,e,t,r,52,8),t+8}B.prototype.writeDoubleLE=function(e,t,r){return ra(this,e,t,!0,r)};B.prototype.writeDoubleBE=function(e,t,r){return ra(this,e,t,!1,r)};B.prototype.copy=function(e,t,r,n){if(!B.isBuffer(e))throw new TypeError("argument should be a Buffer");if(r||(r=0),!n&&n!==0&&(n=this.length),t>=e.length&&(t=e.length),t||(t=0),n>0&&n<r&&(n=r),n===r||e.length===0||this.length===0)return 0;if(t<0)throw new RangeError("targetStart out of bounds");if(r<0||r>=this.length)throw new RangeError("Index out of range");if(n<0)throw new RangeError("sourceEnd out of bounds");n>this.length&&(n=this.length),e.length-t<n-r&&(n=e.length-t+r);let i=n-r;return this===e&&typeof Uint8Array.prototype.copyWithin=="function"?this.copyWithin(t,r,n):Uint8Array.prototype.set.call(e,this.subarray(r,n),t),i};B.prototype.fill=function(e,t,r,n){if(typeof e=="string"){if(typeof t=="string"?(n=t,t=0,r=this.length):typeof r=="string"&&(n=r,r=this.length),n!==void 0&&typeof n!="string")throw new TypeError("encoding must be a string");if(typeof n=="string"&&!B.isEncoding(n))throw new TypeError("Unknown encoding: "+n);if(e.length===1){let o=e.charCodeAt(0);(n==="utf8"&&o<128||n==="latin1")&&(e=o)}}else typeof e=="number"?e=e&255:typeof e=="boolean"&&(e=Number(e));if(t<0||this.length<t||this.length<r)throw new RangeError("Out of range index");if(r<=t)return this;t=t>>>0,r=r===void 0?this.length:r>>>0,e||(e=0);let i;if(typeof e=="number")for(i=t;i<r;++i)this[i]=e;else{let o=B.isBuffer(e)?e:B.from(e,n),a=o.length;if(a===0)throw new TypeError('The value "'+e+'" is invalid for argument "value"');for(i=0;i<r-t;++i)this[i+t]=o[i%a]}return this};var dt={};function _r(s,e,t){dt[s]=class extends t{constructor(){super(),Object.defineProperty(this,"message",{value:e.apply(this,arguments),writable:!0,configurable:!0}),this.name=`${this.name} [${s}]`,this.stack,delete this.name}get code(){return s}set code(n){Object.defineProperty(this,"code",{configurable:!0,enumerable:!0,value:n,writable:!0})}toString(){return`${this.name} [${s}]: ${this.message}`}}}_r("ERR_BUFFER_OUT_OF_BOUNDS",function(s){return s?`${s} is outside of buffer bounds`:"Attempt to access memory outside buffer bounds"},RangeError);_r("ERR_INVALID_ARG_TYPE",function(s,e){return`The "${s}" argument must be of type number. Received type ${typeof e}`},TypeError);_r("ERR_OUT_OF_RANGE",function(s,e,t){let r=`The value of "${s}" is out of range.`,n=t;return Number.isInteger(t)&&Math.abs(t)>2**32?n=Yo(String(t)):typeof t=="bigint"&&(n=String(t),(t>BigInt(2)**BigInt(32)||t<-(BigInt(2)**BigInt(32)))&&(n=Yo(n)),n+="n"),r+=` It must be ${e}. Received ${n}`,r},RangeError);function Yo(s){let e="",t=s.length,r=s[0]==="-"?1:0;for(;t>=r+4;t-=3)e=`_${s.slice(t-3,t)}${e}`;return`${s.slice(0,t)}${e}`}function Tc(s,e,t){mt(e,"offset"),(s[e]===void 0||s[e+t]===void 0)&&vt(e,s.length-(t+1))}function na(s,e,t,r,n,i){if(s>t||s<e){let o=typeof e=="bigint"?"n":"",a;throw i>3?e===0||e===BigInt(0)?a=`>= 0${o} and < 2${o} ** ${(i+1)*8}${o}`:a=`>= -(2${o} ** ${(i+1)*8-1}${o}) and < 2 ** ${(i+1)*8-1}${o}`:a=`>= ${e}${o} and <= ${t}${o}`,new dt.ERR_OUT_OF_RANGE("value",a,s)}Tc(r,n,i)}function mt(s,e){if(typeof s!="number")throw new dt.ERR_INVALID_ARG_TYPE(e,"number",s)}function vt(s,e,t){throw Math.floor(s)!==s?(mt(s,t),new dt.ERR_OUT_OF_RANGE(t||"offset","an integer",s)):e<0?new dt.ERR_BUFFER_OUT_OF_BOUNDS:new dt.ERR_OUT_OF_RANGE(t||"offset",`>= ${t?1:0} and <= ${e}`,s)}var Sc=/[^+/0-9A-Za-z-_]/g;function Ic(s){if(s=s.split("=")[0],s=s.trim().replace(Sc,""),s.length<2)return"";for(;s.length%4!==0;)s=s+"=";return s}function kr(s,e){e=e||1/0;let t,r=s.length,n=null,i=[];for(let o=0;o<r;++o){if(t=s.charCodeAt(o),t>55295&&t<57344){if(!n){if(t>56319){(e-=3)>-1&&i.push(239,191,189);continue}else if(o+1===r){(e-=3)>-1&&i.push(239,191,189);continue}n=t;continue}if(t<56320){(e-=3)>-1&&i.push(239,191,189),n=t;continue}t=(n-55296<<10|t-56320)+65536}else n&&(e-=3)>-1&&i.push(239,191,189);if(n=null,t<128){if((e-=1)<0)break;i.push(t)}else if(t<2048){if((e-=2)<0)break;i.push(t>>6|192,t&63|128)}else if(t<65536){if((e-=3)<0)break;i.push(t>>12|224,t>>6&63|128,t&63|128)}else if(t<1114112){if((e-=4)<0)break;i.push(t>>18|240,t>>12&63|128,t>>6&63|128,t&63|128)}else throw new Error("Invalid code point")}return i}function Oc(s){let e=[];for(let t=0;t<s.length;++t)e.push(s.charCodeAt(t)&255);return e}function xc(s,e){let t,r,n,i=[];for(let o=0;o<s.length&&!((e-=2)<0);++o)t=s.charCodeAt(o),r=t>>8,n=t%256,i.push(n),i.push(r);return i}function ia(s){return vr.toByteArray(Ic(s))}function cs(s,e,t,r){let n;for(n=0;n<r&&!(n+t>=e.length||n>=s.length);++n)e[n+t]=s[n];return n}function ve(s,e){return s instanceof e||s!=null&&s.constructor!=null&&s.constructor.name!=null&&s.constructor.name===e.name}function Gr(s){return s!==s}var Cc=(function(){let s="0123456789abcdef",e=new Array(256);for(let t=0;t<16;++t){let r=t*16;for(let n=0;n<16;++n)e[r+n]=s[t]+s[n]}return e})();function qe(s){return typeof BigInt>"u"?wc:s}function wc(){throw new Error("BigInt not supported")}});function oa(){let s=jr.shift();jr.length||Et?.port1.unref?.(),s&&!s.cleared&&s.fn(...s.args)}function R(s,...e){if(typeof globalThis.setImmediate=="function")return globalThis.setImmediate(s,...e);let t={fn:s,args:e,cleared:!1};return jr.push(t),typeof MessageChannel=="function"?(Et||(Et=new MessageChannel,Et.port1.onmessage=oa),Et.port1.ref?.(),Et.port2.postMessage(null)):setTimeout(oa,0),t}function D(s){if(typeof globalThis.clearImmediate=="function")return globalThis.clearImmediate(s);s&&typeof s=="object"&&(s.cleared=!0)}var b,jr,Et,U,E=Lr(()=>{"use strict";b=Ut(Xr(),1),jr=[],Et=null;U=globalThis.process||{env:{},nextTick:(s,...e)=>queueMicrotask(()=>s(...e))}});var ds=as((yp,Vr)=>{"use strict";E();var At=typeof Reflect=="object"?Reflect:null,aa=At&&typeof At.apply=="function"?At.apply:function(e,t,r){return Function.prototype.apply.call(e,t,r)},fs;At&&typeof At.ownKeys=="function"?fs=At.ownKeys:Object.getOwnPropertySymbols?fs=function(e){return Object.getOwnPropertyNames(e).concat(Object.getOwnPropertySymbols(e))}:fs=function(e){return Object.getOwnPropertyNames(e)};function Nc(s){console&&console.warn&&console.warn(s)}var la=Number.isNaN||function(e){return e!==e};function oe(){oe.init.call(this)}Vr.exports=oe;Vr.exports.once=Dc;oe.EventEmitter=oe;oe.prototype._events=void 0;oe.prototype._eventsCount=0;oe.prototype._maxListeners=void 0;var ua=10;function hs(s){if(typeof s!="function")throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof s)}Object.defineProperty(oe,"defaultMaxListeners",{enumerable:!0,get:function(){return ua},set:function(s){if(typeof s!="number"||s<0||la(s))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+s+".");ua=s}});oe.init=function(){(this._events===void 0||this._events===Object.getPrototypeOf(this)._events)&&(this._events=Object.create(null),this._eventsCount=0),this._maxListeners=this._maxListeners||void 0};oe.prototype.setMaxListeners=function(e){if(typeof e!="number"||e<0||la(e))throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received '+e+".");return this._maxListeners=e,this};function ca(s){return s._maxListeners===void 0?oe.defaultMaxListeners:s._maxListeners}oe.prototype.getMaxListeners=function(){return ca(this)};oe.prototype.emit=function(e){for(var t=[],r=1;r<arguments.length;r++)t.push(arguments[r]);var n=e==="error",i=this._events;if(i!==void 0)n=n&&i.error===void 0;else if(!n)return!1;if(n){var o;if(t.length>0&&(o=t[0]),o instanceof Error)throw o;var a=new Error("Unhandled error."+(o?" ("+o.message+")":""));throw a.context=o,a}var u=i[e];if(u===void 0)return!1;if(typeof u=="function")aa(u,this,t);else for(var l=u.length,c=ma(u,l),r=0;r<l;++r)aa(c[r],this,t);return!0};function fa(s,e,t,r){var n,i,o;if(hs(t),i=s._events,i===void 0?(i=s._events=Object.create(null),s._eventsCount=0):(i.newListener!==void 0&&(s.emit("newListener",e,t.listener?t.listener:t),i=s._events),o=i[e]),o===void 0)o=i[e]=t,++s._eventsCount;else if(typeof o=="function"?o=i[e]=r?[t,o]:[o,t]:r?o.unshift(t):o.push(t),n=ca(s),n>0&&o.length>n&&!o.warned){o.warned=!0;var a=new Error("Possible EventEmitter memory leak detected. "+o.length+" "+String(e)+" listeners added. Use emitter.setMaxListeners() to increase limit");a.name="MaxListenersExceededWarning",a.emitter=s,a.type=e,a.count=o.length,Nc(a)}return s}oe.prototype.addListener=function(e,t){return fa(this,e,t,!1)};oe.prototype.on=oe.prototype.addListener;oe.prototype.prependListener=function(e,t){return fa(this,e,t,!0)};function Mc(){if(!this.fired)return this.target.removeListener(this.type,this.wrapFn),this.fired=!0,arguments.length===0?this.listener.call(this.target):this.listener.apply(this.target,arguments)}function ha(s,e,t){var r={fired:!1,wrapFn:void 0,target:s,type:e,listener:t},n=Mc.bind(r);return n.listener=t,r.wrapFn=n,n}oe.prototype.once=function(e,t){return hs(t),this.on(e,ha(this,e,t)),this};oe.prototype.prependOnceListener=function(e,t){return hs(t),this.prependListener(e,ha(this,e,t)),this};oe.prototype.removeListener=function(e,t){var r,n,i,o,a;if(hs(t),n=this._events,n===void 0)return this;if(r=n[e],r===void 0)return this;if(r===t||r.listener===t)--this._eventsCount===0?this._events=Object.create(null):(delete n[e],n.removeListener&&this.emit("removeListener",e,r.listener||t));else if(typeof r!="function"){for(i=-1,o=r.length-1;o>=0;o--)if(r[o]===t||r[o].listener===t){a=r[o].listener,i=o;break}if(i<0)return this;i===0?r.shift():Rc(r,i),r.length===1&&(n[e]=r[0]),n.removeListener!==void 0&&this.emit("removeListener",e,a||t)}return this};oe.prototype.off=oe.prototype.removeListener;oe.prototype.removeAllListeners=function(e){var t,r,n;if(r=this._events,r===void 0)return this;if(r.removeListener===void 0)return arguments.length===0?(this._events=Object.create(null),this._eventsCount=0):r[e]!==void 0&&(--this._eventsCount===0?this._events=Object.create(null):delete r[e]),this;if(arguments.length===0){var i=Object.keys(r),o;for(n=0;n<i.length;++n)o=i[n],o!=="removeListener"&&this.removeAllListeners(o);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if(t=r[e],typeof t=="function")this.removeListener(e,t);else if(t!==void 0)for(n=t.length-1;n>=0;n--)this.removeListener(e,t[n]);return this};function da(s,e,t){var r=s._events;if(r===void 0)return[];var n=r[e];return n===void 0?[]:typeof n=="function"?t?[n.listener||n]:[n]:t?Lc(n):ma(n,n.length)}oe.prototype.listeners=function(e){return da(this,e,!0)};oe.prototype.rawListeners=function(e){return da(this,e,!1)};oe.listenerCount=function(s,e){return typeof s.listenerCount=="function"?s.listenerCount(e):pa.call(s,e)};oe.prototype.listenerCount=pa;function pa(s){var e=this._events;if(e!==void 0){var t=e[s];if(typeof t=="function")return 1;if(t!==void 0)return t.length}return 0}oe.prototype.eventNames=function(){return this._eventsCount>0?fs(this._events):[]};function ma(s,e){for(var t=new Array(e),r=0;r<e;++r)t[r]=s[r];return t}function Rc(s,e){for(;e+1<s.length;e++)s[e]=s[e+1];s.pop()}function Lc(s){for(var e=new Array(s.length),t=0;t<e.length;++t)e[t]=s[t].listener||s[t];return e}function Dc(s,e){return new Promise(function(t,r){function n(o){s.removeListener(e,i),r(o)}function i(){typeof s.removeListener=="function"&&s.removeListener("error",n),t([].slice.call(arguments))}ga(s,e,i,{once:!0}),e!=="error"&&Uc(s,n,{once:!0})})}function Uc(s,e,t){typeof s.on=="function"&&ga(s,"error",e,t)}function ga(s,e,t,r){if(typeof s.on=="function")r.once?s.once(e,t):s.on(e,t);else if(typeof s.addEventListener=="function")s.addEventListener(e,function n(i){r.once&&s.removeEventListener(e,n),t(i)});else throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof s)}});var Cr,Ml=Lr(()=>{E();Cr=class{constructor(){throw new Error("SMTP is not available in the browser")}}});var Rl={};Kl(Rl,{startSMTPServer:()=>zd});function zd(s,e,t,r){let n=e.getCredentials(),i=new Cr({banner:"ImapKit",key:n.key,cert:n.cert,authOptional:!0,authMethods:e.oauth?["PLAIN","LOGIN","XOAUTH2"]:["PLAIN","LOGIN"],logger:!1,onAuth(a,u,l){if(a.method!=="XOAUTH2")return l(null,{user:a.username});let c=e.checkAccessToken(a.accessToken||"",a.username,"smtp");if("error"in c)return l(null,{data:{status:"401",schemes:"bearer",scope:e.oauth.mailScope}});l(null,{user:c.user})},onData(a,u,l){let c=[];a.on("data",f=>c.push(f)),a.on("error",l),a.on("end",()=>{e.appendMessage("INBOX",[],!1,b.Buffer.concat(c).toString("binary")),l()})}});i.on("error",a=>{e.options.debug&&console.error("SMTP server error: %s",a.message)});let o=()=>t?.(i.server.address().port);return r?i.listen(s,r,o):i.listen(s,o),i}var Ll=Lr(()=>{"use strict";E();Ml()});E();E();E();var Ea=Ut(ds()),ps=class extends Ea.default{};E();var Qr=Ut(ds()),Yr=s=>()=>{throw new Error(s+" is not available in the browser, open connections with server.connect()")},ms=class extends Qr.default{},qr=class extends ms{constructor(){super(),Yr("TLS")()}},gs=class extends Qr.default{listen(){Yr("listen()")()}close(e){return e&&queueMicrotask(()=>e()),this}address(){return null}},vc=()=>new gs,Bc=Yr("TLS"),Qe={Socket:ms,TLSSocket:qr,Server:gs,createServer:vc,createSecureContext:Bc};E();E();E();var Hc=Ut(Xr());function Ye(s){try{return new TextDecoder("utf-8",{fatal:!0}).decode(s),!0}catch{return!1}}E();var xe=s=>{let e;return()=>(e===void 0&&(e=s()),e)},tt=(s,e)=>{let t=[];for(let r=s;r<=e;r++)t.push(r);return String.fromCharCode(...t)},Es=(s,e)=>Array.from(s).filter(t=>!e.includes(t)).join(""),kc=xe(()=>new Set(me["ATOM-CHAR"]())),me={CHAR:xe(()=>tt(1,127)),CHAR8:xe(()=>tt(1,255)),SP:()=>" ",CTL:xe(()=>tt(0,31)+"\x7F"),DQUOTE:()=>'"',ALPHA:xe(()=>tt(65,90)+tt(97,122)),DIGIT:xe(()=>tt(48,57)),"ATOM-CHAR":xe(()=>Es(me.CHAR(),me["atom-specials"]())),"ASTRING-CHAR":xe(()=>me["ATOM-CHAR"]()+me["resp-specials"]()),"TEXT-CHAR":xe(()=>Es(me.CHAR(),`\r
2
2
  `)),"atom-specials":xe(()=>"(){"+me.SP()+me.CTL()+me["list-wildcards"]()+me["quoted-specials"]()+me["resp-specials"]()),"list-wildcards":()=>"%*","quoted-specials":()=>me.DQUOTE()+"\\","resp-specials":()=>"]",tag:xe(()=>Es(me["ASTRING-CHAR"](),"+")),command:xe(()=>me["ATOM-CHAR"]()),_expandRange:tt,_excludeChars:Es,isAtomChar(s){return kc().has(s)},isSequenceSet(s){return!!s&&s.split(",").every(e=>/^(?:\d+|\*)(?::(?:\d+|\*))?$/.test(e))},verify(s,e){for(let t=0,r=s.length;t<r;t++)if(e.indexOf(s.charAt(t))<0)return t;return-1}},he=me;var Pc=4294967295,Fc=Number.MAX_SAFE_INTEGER,_c=25,Gc=s=>he.isAtomChar(s),Kr=s=>s>=48&&s<=57,Xc=s=>he.isSequenceSet(s),ae=(s,e,t)=>{let r=new Error(s+" at position "+e);return r.code=t||"ParserError",r.pos=e,r};function $r(s,e){let t={...e,allowSection:e?.allowSection||["BODY","BODY.PEEK"],multiWords:e?.multiWords||["UID","AUTHENTICATE"],allowUntagged:!!e?.allowUntagged},r=new zr(s,t),n=r.getTag();r.getSpace();let i={tag:n,command:r.getCommand()};return t.multiWords.indexOf((i.command||"").toUpperCase())>=0&&(r.getSpace(),i.command+=" "+r.getElement(he.command())),r.remainder.length&&(r.getSpace(),i.attributes=r.getAttributes()),i}var zr=class{constructor(e,t){this.input=(e||"").toString(),this.options=t,this.remainder=this.input,this.pos=0}getTag(){return this.tag||(this.tag=this.getElement(he.tag()+(this.options.allowUntagged?"*":""))),this.tag}getCommand(){return this.command||(this.command=this.getElement(he.command())),this.command}getElement(e){let t;if(this.remainder.match(/^\s/))throw ae("Unexpected whitespace",this.pos);let r=this.remainder.match(/^[^\s]+(?=\s|$)/);if(!r)throw ae("Unexpected end of input",this.pos);let n=r[0];if((t=he.verify(n,e))>=0)throw ae("Unexpected char",this.pos+t);return this.pos+=n.length,this.remainder=this.remainder.substring(n.length),n}getSpace(){if(!this.remainder.length)throw ae("Unexpected end of input",this.pos);if(he.verify(this.remainder.charAt(0),he.SP())>=0)throw ae("Unexpected char",this.pos);this.pos++,this.remainder=this.remainder.substring(1)}getAttributes(){if(!this.remainder.length)throw ae("Unexpected end of input",this.pos);if(this.remainder.match(/^\s/))throw ae("Unexpected whitespace",this.pos);return new Wr(this.pos,this.remainder,this.options).getAttributes()}},Wr=class{constructor(e,t,r){this.str=(t||"").toString(),this.options=r,this.pos=e||0,this.maxSectionName=Math.max(0,...this.options.allowSection.map(n=>n.length)),this.maxNumber=this.options.number64?Fc:Pc,this.tree=this.currentNode=this.createNode(),this.currentNode.type="TREE",this.processString()}getAttributes(){let e=[],t=e,r=()=>t[t.length-1],n=i=>{let o,a=t;if(!i.closed)throw ae("Unexpected end of input",this.pos+this.str.length);switch(i.type){case"LITERAL":case"LITERAL8":case"ATOM":case"STRING":case"SEQUENCE":if(i.type==="ATOM"&&i.value.toUpperCase()==="NIL"){t.push(null);break}o={type:i.type,value:i.value},t.push(o);break;case"SECTION":t=r().section=[];break;case"LIST":o=[],t.push(o),t=o;break;case"PARTIAL":r().partial=i.value.split(".").map(Number);break}i.childNodes.forEach(n),t=a};return n(this.tree),e}createNode(e,t){let r={childNodes:[],type:!1,value:"",closed:!0,depth:e?e.depth+1:0};if(r.depth>_c)throw ae("Too much nesting",t,"MaxNestingReached");return e&&(r.parentNode=e,e.childNodes.push(r)),typeof t=="number"&&(r.startPos=t),r}addValue(e,t,r,n){let i=this.createNode(this.currentNode,this.pos+r);return i.type=e,i.value=t,i.endPos=this.pos+n-1,i}closeNode(e){this.currentNode.closed=!0,this.currentNode.endPos=this.pos+e,this.currentNode=this.currentNode.parentNode}unexpected(e){return ae(e>=this.str.length?"Unexpected end of input":"Unexpected char",this.pos+e)}afterValue(e){let t=this.str;if(e>=t.length)return e;let r=t.charAt(e);if(r===" "){let n=t.charAt(e+1);if(e+1>=t.length||n===" "||n===")"||n==="]"&&this.currentNode.type==="SECTION")throw ae("Unexpected whitespace",this.pos+e);return e+1}if(r===")"&&this.currentNode.type==="LIST"||r==="]"&&this.currentNode.type==="SECTION")return e;throw ae("Unexpected char",this.pos+e)}processString(){let e=this.str,t=e.length,r=0;for(;r<t;)switch(e.charAt(r)){case" ":throw ae("Unexpected whitespace",this.pos+r);case'"':r=this.readString(r);break;case"(":this.currentNode=this.createNode(this.currentNode,this.pos+r),this.currentNode.type="LIST",this.currentNode.closed=!1,r++;break;case")":if(this.currentNode.type!=="LIST")throw ae("Unexpected list terminator )",this.pos+r);this.closeNode(r),r=this.afterValue(r+1);break;case"]":if(this.currentNode.type!=="SECTION"){r=this.readAtom(r);break}this.closeNode(r),r=this.str.charAt(r+1)==="<"?this.readPartial(r+1):this.afterValue(r+1);break;case"{":r=this.readLiteral(r,!1);break;case"~":r=this.options.literal8&&e.charAt(r+1)==="{"?this.readLiteral(r,!0):this.readAtom(r);break;default:r=this.readAtom(r);break}}readAtom(e){let t=this.str,r=t.length,n=this.currentNode.type,i=!0,o=!0,a;for(a=e;a<r;a++){let c=t.charAt(a),f=t.charCodeAt(a);if(c===" "||c===")"&&n==="LIST"||c==="]"&&n==="SECTION")break;if(c==="["&&a>e&&a-e<=this.maxSectionName&&this.options.allowSection.indexOf(t.slice(e,a).toUpperCase())>=0)return this.addValue("ATOM",t.slice(e,a),e,a),this.currentNode=this.createNode(this.currentNode,this.pos+a),this.currentNode.type="SECTION",this.currentNode.closed=!1,a+1;if(!Gc(c)&&c!=="%"&&c!=="*"&&c!=="]"&&!(c==="\\"&&a===e))throw ae("Unexpected char",this.pos+a);Kr(f)||(o=!1,c!==":"&&c!==","&&c!=="*"&&(i=!1))}if(a===e)throw ae("Unexpected char",this.pos+a);let u=t.slice(e,a),l="ATOM";return i&&!o&&u!=="*"&&Xc(u)&&(l="SEQUENCE"),this.addValue(l,u,e,a),this.afterValue(a)}readString(e){let t=this.str,r=t.length,n=!!this.options.utf8,i=!1,o="",a=e+1;for(let u=e+1;u<r;u++){let l=t.charCodeAt(u);if(l===34){if(i&&!Ye(b.Buffer.from(t.slice(e+1,u),"binary")))throw ae("Invalid UTF-8",this.pos+e+1);return o+=t.slice(a,u),this.addValue("STRING",o,e,u+1),this.afterValue(u+1)}if(l===92){if(u+1>=r)throw ae("Unexpected end of input",this.pos+u+1);let c=t.charAt(u+1);if(c!=='"'&&c!=="\\")throw ae("Unexpected escaped char",this.pos+u+1);o+=t.slice(a,u)+c,u++,a=u+1;continue}if(n&&l>127&&l<=255){i=!0;continue}if(l===0||l===10||l===13||l>127)throw ae("Unexpected char",this.pos+u)}throw ae("Unexpected end of input",this.pos+r)}readLiteral(e,t){let r=this.str,n=r.length,i=e+(t?2:1),o=i;for(;o<n&&Kr(r.charCodeAt(o));)o++;if(o===i)throw this.unexpected(o);let a=Number(r.slice(i,o));if(r.charAt(o)==="+"&&this.options.literalPlus&&o++,r.charAt(o)!=="}")throw this.unexpected(o);if(o++,r.charAt(o)===`
3
3
  `)o++;else if(r.charAt(o)==="\r"&&r.charAt(o+1)===`
4
- `)o+=2;else throw this.unexpected(o);if(a>this.maxNumber||o+a>n)throw ae("Unexpected end of input",this.pos+n);let u=r.substring(o,o+a);if(!t){let l=u.indexOf("\0");if(l>=0)throw ae("Unexpected \\x00",this.pos+o+l)}return this.addValue(t?"LITERAL8":"LITERAL",u,e,o+a),this.afterValue(o+a)}readPartial(e){let t=this.str,r=t.length,n=e+1,i=o=>{let a=n;for(;n<r&&Kr(t.charCodeAt(n));)n++;if(n===a)throw this.unexpected(n);if(o&&t.charAt(a)==="0")throw ae("Invalid partial",this.pos+a);if(Number(t.slice(a,n))>this.maxNumber)throw ae("Invalid partial",this.pos+a)};if(i(!1),t.charAt(n)==="."&&(n++,i(!0)),t.charAt(n)!==">")throw this.unexpected(n);return this.addValue("PARTIAL",t.slice(e+1,n),e,n+1),this.afterValue(n+1)}};g();var ya=/[\x00\r\n\x80-\uffff]/,ba=/[\x00\r\n\u0100-\uffff]/,jc=s=>{for(let e=0,t=s.length;e<t;e++)if(!he.isAtomChar(s.charAt(e)))return!1;return!!s.length},Vc=s=>s==="\\*"||jc(s.charAt(0)==="\\"?s.slice(1):s),qc=s=>s==="$"||he.isSequenceSet(s),Jr=s=>{let e=Math.round(Number(s));return Number.isSafeInteger(e)&&e>=0?e:0},Fe=s=>b.Buffer.isBuffer(s)?s.toString("binary"):s==null?"":String(s),As=s=>"{"+s.length+`}\r
5
- `+s,Ta=s=>'"'+s.replace(/["\\]/g,"\\$&")+'"',Qc=s=>"~"+As(s),Yc=s=>ya.test(s)?As(s):Ta(s),Kc=s=>!ya.test(s)||!ba.test(s)&&Ye(b.Buffer.from(s,"binary"))?Ta(s):As(s),en=(s,e)=>{let t=new Error(s);return t.code=e,t},Zr=(s,e)=>{if(ba.test(s))throw en("Line break or NUL in "+e,"InvalidTextValue");return s},Aa=s=>[].concat(s||[]);function tn(s,e){let t=e&&e.utf8?Kc:Yc,r=Zr(Fe(s.tag),"tag")+(s.command?" "+Zr(Fe(s.command),"command"):""),n=!1,i=o=>{if(n||(r+=" "),n=!1,Array.isArray(o)){let u=o;r+="(",n=!0;let l=0;if(u.adjacentLists)for(;l<u.length&&Array.isArray(u[l]);)l++;u.forEach((c,f)=>{f&&f<l&&(n=!0),i(c)}),r+=")",n=!1;return}if(b.Buffer.isBuffer(o)){r+=t(Fe(o));return}if(!o&&typeof o!="string"&&typeof o!="number"){r+="NIL";return}if(typeof o=="string"){r+=t(o);return}if(typeof o=="number"){r+=Jr(o);return}let a;switch(typeof o.type=="string"?o.type.toUpperCase():""){case"LITERAL":r+=As(Fe(o.value));break;case"LITERAL8":r+=Qc(Fe(o.value));break;case"STRING":r+=t(Fe(o.value));break;case"TEXT":r+=Zr(Fe(o.value),"TEXT value");break;case"SEQUENCE":if(a=Fe(o.value),!qc(a))throw en("Invalid sequence set","InvalidSequenceSet");r+=a;break;case"NUMBER":r+=Jr(o.value);break;case"ATOM":case"SECTION":a=Fe(o.value),(a||!o.section)&&(r+=Vc(a)?a:t(a)),o.section&&(r+="[",n=!0,o.section.forEach(i),r+="]",n=!1),o.partial&&(r+="<"+Aa(o.partial).map(Jr).join(".")+">");break;default:throw en("Unknown node type "+JSON.stringify(o.type),"InvalidNodeType")}};return Aa(s.attributes).forEach(i),r}var st={parser:$r,compiler:tn};g();g();g();g();var ys=["Not Authenticated","Authenticated","Selected"],bs=["Not Authenticated"],Ce=["Authenticated","Selected"],Re=["Selected"];function re(s){let e=(Array.isArray(s)?{states:s}:s)||{};return{states:e.states?[].concat(e.states):!1,noArguments:!!e.noArguments,mailboxArguments:[].concat(e.mailboxArguments||[]),astringArguments:[].concat(e.astringArguments||[]),searchCriteria:typeof e.searchCriteria=="number"?e.searchCriteria:!1,sequenceSet:typeof e.sequenceSet=="number"?e.sequenceSet:!1,noExpunge:!!e.noExpunge,literal8:e.literal8===!0||typeof e.literal8=="string"?e.literal8:!1,noPipelining:!!e.noPipelining,appendMessage:!!e.appendMessage}}var Sa={CAPABILITY:re({states:ys,noArguments:!0}),NOOP:re({states:ys,noArguments:!0}),LOGOUT:re({states:ys,noArguments:!0}),STARTTLS:re({states:bs,noArguments:!0,noPipelining:!0}),LOGIN:re({states:bs,astringArguments:[0,1]}),SELECT:re({states:Ce,mailboxArguments:[0]}),EXAMINE:re({states:Ce,mailboxArguments:[0]}),CREATE:re({states:Ce,mailboxArguments:[0]}),DELETE:re({states:Ce,mailboxArguments:[0]}),RENAME:re({states:Ce,mailboxArguments:[0,1]}),SUBSCRIBE:re({states:Ce,mailboxArguments:[0]}),UNSUBSCRIBE:re({states:Ce,mailboxArguments:[0]}),LIST:re({states:Ce,astringArguments:[0,1]}),LSUB:re({states:Ce,astringArguments:[0,1]}),STATUS:re({states:Ce,mailboxArguments:[0]}),APPEND:re({states:Ce,mailboxArguments:[0],literal8:"BINARY",appendMessage:!0}),CHECK:re({states:Re,noArguments:!0}),CLOSE:re({states:Re,noArguments:!0}),EXPUNGE:re({states:Re,noArguments:!0}),SEARCH:re({states:Re,searchCriteria:0,noExpunge:!0}),FETCH:re({states:Re,sequenceSet:0,noExpunge:!0}),STORE:re({states:Re,sequenceSet:0,noExpunge:!0}),COPY:re({states:Re,sequenceSet:0,mailboxArguments:[1]}),"UID COPY":re({states:Re,mailboxArguments:[1]}),"UID SEARCH":re({states:Re,searchCriteria:0})},zc=re({states:Re}),Wc=re({states:bs});function Ia(s){return Object.hasOwn(Sa,s)?Sa[s]:/^UID /.test(s)?zc:/^AUTHENTICATE /.test(s)?Wc:!1}var Z={ANY:ys,NOT_AUTHENTICATED:bs,AUTHENTICATED:Ce,SELECTED:Re};g();var sn=/[\x00-\x1f\x7f (){%*"\\\]]/;function be(s){return s.charAt(0)==="\\"&&(s=s.charAt(0)+s.charAt(1).toUpperCase()+s.substr(2).toLowerCase()),s}function we(s,e){if(e.charAt(0)==="\\"){if(s.systemFlags.indexOf(e)<0)throw new Error("Invalid system flag "+e)}else if(!e||sn.test(e))throw new Error("Invalid flag keyword "+JSON.stringify(e))}g();var rt={},Ts=rt;function Oa(s,e,t){let r=s.selectedMailbox,n=[];[].concat(t).forEach(i=>{i=be(typeof i=="string"?i:String(i.value||"")),we(s.server,i),s.server.isPermanentFlag(r,i)&&n.indexOf(i)<0&&n.push(i)}),e.flags=n,s.server.rememberFlags(r,n)}function xa(s,e,t){let r=s.selectedMailbox;[].concat(t).forEach(n=>{n=be(typeof n=="string"?n:String(n.value||"")),we(s.server,n),s.server.isPermanentFlag(r,n)&&e.flags.indexOf(n)<0&&e.flags.push(n)}),s.server.rememberFlags(r,e.flags)}function Ca(s,e,t){[].concat(t).forEach(r=>{if(r=be(typeof r=="string"?r:String(r.value||"")),we(s.server,r),e.flags.indexOf(r)>=0){for(let n=0;n<e.flags.length;n++)if(e.flags[n]===r){e.flags.splice(n,1);break}}})}function rn(s,e,t,r,n){let i=[{type:"ATOM",value:"FLAGS"},s.getFlags(n).map(o=>({type:"ATOM",value:o}))];(e.command||"").toUpperCase()==="UID STORE"&&(i.push({type:"ATOM",value:"UID"}),i.push(n.uid)),s.send({tag:"*",attributes:[r,{type:"ATOM",value:"FETCH"},i]},"FLAG UPDATE",e,t,n)}rt.FLAGS=function(s,e,t,r,n,i){Oa(s,e,t),rn(s,n,i,r,e)};rt["+FLAGS"]=function(s,e,t,r,n,i){xa(s,e,t),rn(s,n,i,r,e)};rt["-FLAGS"]=function(s,e,t,r,n,i){Ca(s,e,t),rn(s,n,i,r,e)};rt["FLAGS.SILENT"]=function(s,e,t){Oa(s,e,t)};rt["+FLAGS.SILENT"]=function(s,e,t){xa(s,e,t)};rt["-FLAGS.SILENT"]=function(s,e,t){Ca(s,e,t)};g();function Ke(s){return s.listExtensions||(s.listExtensions={enabled:!1,selectionOptions:Object.create(null),returnOptions:Object.create(null)}),s.listExtensions}g();function nn(s,e,t,r){return an(s,e,t,r,!1)}function on(s,e,t){s.everSelected=!0,s.state==="Selected"&&s.server.closedChecks.some(r=>r(s))&&s.send({tag:"*",command:"OK",attributes:[{type:"SECTION",section:[{type:"ATOM",value:"CLOSED"}]},{type:"TEXT",value:"Previous mailbox closed"}]},"CLOSED",e,t)}function an(s,e,t,r,n){let i=n?"EXAMINE":"SELECT";if(!e.attributes||e.attributes.length!==1||!e.attributes[0]||["STRING","LITERAL","ATOM"].indexOf(e.attributes[0].type)<0)return s.send({tag:e.tag,command:"BAD",attributes:[{type:"TEXT",value:i+" expects 1 mailbox argument"}]},"INVALID COMMAND",e,t),r();let o=e.attributes[0].value;on(s,e,t);let a=s.server.getMailbox(o);if(!a||a.flags.indexOf("\\Noselect")>=0)return s.closeMailbox(),s.sendStatus(e,t,"NO","Mailbox does not exist","NONEXISTENT",i+" FAILED"),r();s.state="Selected",s.selectedMailbox=a,s.readOnly=n,s.emitSession("select"),s.notificationQueue=[];let u=new Set;s.recent=u,a.messages.forEach(p=>{p.recent&&(u.add(p),n||delete p.recent)});let c=s.server.getStatus(a).permanentFlags.map(p=>({type:"ATOM",value:p}));s.send({tag:"*",command:"FLAGS",attributes:[c]},i+" FLAGS",e,t),a.allowPermanentFlags&&c.push({type:"TEXT",value:"\\*"}),s.send({tag:"*",command:"OK",attributes:[{type:"SECTION",section:[{type:"ATOM",value:"PERMANENTFLAGS"},n?[]:c]},{type:"TEXT",value:n?"No permanent flags permitted":"Flags permitted"}]},i+" PERMANENTFLAGS",e,t),s.send({tag:"*",attributes:[a.messages.length,{type:"ATOM",value:"EXISTS"}]},i+" EXISTS",e,t),s.send({tag:"*",attributes:[s.recent.size,{type:"ATOM",value:"RECENT"}]},i+" RECENT",e,t);let f=a.messages.findIndex(p=>p.flags.indexOf("\\Seen")<0);return f>=0&&s.send({tag:"*",command:"OK",attributes:[{type:"SECTION",section:[{type:"ATOM",value:"UNSEEN"},f+1]},{type:"TEXT",value:"First unseen message"}]},i+" UNSEEN",e,t),s.send({tag:"*",command:"OK",attributes:[{type:"SECTION",section:[{type:"ATOM",value:"UIDVALIDITY"},a.uidvalidity]},{type:"TEXT",value:"UIDs valid"}]},i+" UIDVALIDITY",e,t),s.send({tag:"*",command:"OK",attributes:[{type:"SECTION",section:[{type:"ATOM",value:"UIDNEXT"},a.uidnext]},{type:"TEXT",value:"Predicted next UID"}]},i+" UIDNEXT",e,t),s.send({tag:e.tag,command:"OK",attributes:[{type:"SECTION",section:[{type:"ATOM",value:n?"READ-ONLY":"READ-WRITE"}]},{type:"TEXT",value:"Completed"}]},i,e,t),r()}g();g();function J(s,e){return!!s&&!Array.isArray(s)&&s.type==="ATOM"&&(e===void 0||String(s.value).toUpperCase()===e)}function ue(s){return!!s&&!Array.isArray(s)&&["ATOM","STRING","LITERAL"].indexOf(s.type)>=0&&!s.section&&!s.partial}var wa=/[\s()[\]{"%*\\<]/;function $c(s){let e=[],t=0;for(;t<s.length;){let r=s.charAt(t);if(r==='"'){for(t++;t<s.length&&s.charAt(t)!=='"';t++)s.charAt(t)==="\\"&&t++;t++;continue}let n=(r==="{"||r==="~")&&s.substr(t,32).match(/^~?\{(\d+)\+?\}\r\n/);if(n){t+=n[0].length+Number(n[1]);continue}if(wa.test(r)){t++;continue}let i=t;for(;i<s.length&&!wa.test(s.charAt(i));)i++;let o=s.substring(t,i);/^nil$/i.test(o)&&e.push(o),t=i}return e}function yt(s,e,t){if(!s.attributes||!/nil/i.test(e||""))return;let r=[],n=(o,a)=>{o.forEach((u,l)=>{u===null?r.push({list:o,index:l,path:a.concat(l)}):Array.isArray(u)?n(u,a.concat(l)):u&&Array.isArray(u.section)&&n(u.section,a.concat(l,"section"))})};if(n(s.attributes,[]),!r.length)return;let i=$c(e).slice(-r.length);r.forEach((o,a)=>{t(o.path)&&(o.list[o.index]={type:"ATOM",value:i.length===r.length?i[a]:"NIL"})})}function nt(s,e,t,r){let n=new Error(s);return n.imapResponse=r||"NO",n.responseCode=e||!1,n.responseCodeArgs=t||[],n}var _e=s=>nt(s,!1,!1,"BAD");function Jc(s,e){try{return e.map(t=>{if(!t||t.type!=="ATOM")throw new Error("Invalid flags argument");let r=be(t.value);return we(s.server,r),r})}catch{throw _e("Invalid flags argument")}}function Zc(s,e,t){let r=s.server,n=[];for(let i=0;i<e.length;){let o={flags:[],internaldate:!1,raw:!1};if(Array.isArray(e[i])&&(o.flags=Jc(s,e[i++])),e[i]&&e[i].type==="STRING"){if(!r.validateInternalDate(e[i].value))throw _e("Invalid internaldate argument");o.internaldate=e[i++].value}let a=e[i++],u=a&&a.type==="ATOM"?String(a.value).toUpperCase():"";if(a&&a.type==="LITERAL")o.raw=a.value;else if(a&&a.type==="LITERAL8"&&r.appendLiteral8)o.raw=a.value,o.literal8=!0;else if(u&&Object.hasOwn(r.appendDataHandlers,u)&&i<e.length)o.resolve=r.appendDataHandlers[u](s,e[i++]);else throw _e("Invalid message source argument");n.push(o)}if(!n.length)throw _e("Missing message argument");if(n.length>t)throw _e("Only a single message can be appended");return n}function ef(s,e,t,r,n){let i=[];r.responseCode&&i.push({type:"SECTION",section:[{type:"ATOM",value:r.responseCode}].concat(r.responseCodeArgs)}),i.push({type:"TEXT",value:r.message}),s.send({tag:e.tag,command:r.imapResponse,attributes:i},r.imapResponse==="BAD"?"INVALID COMMAND":n,e,t)}function Bt(s,e,t){let r=s.server.getCommandOptions(e);if(!r.appendMessage)return!1;let n=r.mailboxArguments[0];if(/[ (]URL $/i.test(t.slice(-5)))return!1;let i=l=>{l=l.replace(/ $/,"");for(let c of["",")"])try{let f=st.parser(l+c);return yt(f,l,p=>p.length===1&&p[0]===n),f.attributes||[]}catch{}return[]},o=t.match(/(~?)\{(\d+)\+?\}\r\n/),a=i(o?t.substr(0,o.index):t);a.length<=n&&o&&!o[1]&&(a=i(t.substr(0,o.index+o[0].length+Number(o[2]))));let u=a[n];if(!ue(u))return!1;try{return s.importMailboxName(u.value)}catch{return!1}}function Na(s,e,t){let r=!s.isBusy()&&Bt(s,e,t);return r!==!1&&s.server.targetRefusal(r)}function un(s,e,t,r,n,i){let o=i.command+" FAILED",a=i.maxMessages||(s.server.multiAppend?1/0:1);try{if(!r||["STRING","ATOM","LITERAL"].indexOf(r.type)<0)throw _e("Invalid mailbox argument");let u=Zc(s,n,a),l=s.getTargetMailbox(r.value,e,t,o);if(!l)return!1;u.forEach(f=>{f.resolve?f.raw=f.resolve():f.literal8&&(f.raw=s.server.appendLiteral8(f.raw))});let c=u;return s.checkAppend(l,c,e,t,o,{command:i.command,replaced:i.replaced})?{mailbox:l,messages:c}:!1}catch(u){let l=u;if(!l.imapResponse)throw l;return ef(s,e,t,l,o),!1}}function ln(s,e){let t=e.messages.map(r=>s.server.appendMessage(e.mailbox,r.flags,r.internaldate,r.raw).message);return{mailbox:e.mailbox,message:t[t.length-1],messages:t}}function cn(s,e,t,r){let n=[].concat(e.attributes||[]),i=un(s,e,t,n.shift(),n,{command:"APPEND"});if(!i)return r();let o=ln(s,i);s.send({tag:e.tag,command:"OK",attributes:[{type:"TEXT",value:"APPEND Completed"}]},"APPEND",e,t,o),r()}g();g();function Ss(s){let e=s>>>0;return()=>{e=e+1831565813>>>0;let t=e;return t=Math.imul(t^t>>>15,t|1),t^=t+Math.imul(t^t>>>7,t|61),((t^t>>>14)>>>0)/4294967296}}g();var Ge=2n**63n-1n;function Ae(s,e){let t=String(e===void 0?4294967295:e);return typeof s!="string"||!/^\d+$/.test(s)||s.replace(/^0+(?=\d)/,"").length>t.length?!1:BigInt(s)<=BigInt(t)}function Le(s,e){return Ae(s,e)&&/^[1-9]/.test(s)}function Is(s,e){return typeof s!="string"||!/^[\d*]+(:[\d*]+)?(,[\d*]+(:[\d*]+)?)*$/.test(s)?!1:s.split(/[,:]/).every(t=>t==="*"?!e:Le(t))}var Os=3600*1e3,z=class extends Error{constructor(e,t){super(e),this.name="ImapKitError",this.code=t}};function K(s,e){return new z(s,e)}function it(s,e,t,r={}){let n;if(Array.isArray(t)){let c=new Set(t);n=f=>c.has(f)}else n=t;let i=[],o=[];if(e.messages.forEach((c,f)=>{n(c)?(c.ghost=!0,i.push({seq:r.highestFirst?f+1:o.length+1,message:c})):o.push(c)}),!i.length)return[];let a=e.messages.slice();o.forEach((c,f)=>{e.messages[f]=c}),e.messages.length=o.length;let u=i.map(c=>c.message),l=r.origin!==void 0?r.origin:s.activeConnection;return s.emit("expunge",e,u,l),(r.highestFirst?i.slice().reverse():i).forEach(c=>{s.notify({tag:"*",attributes:[c.seq,{type:"ATOM",value:"EXPUNGE"}],message:c.message},e,r.skip)}),s.notify({tag:"*",attributes:[e.messages.length,{type:"ATOM",value:"EXISTS"}],mailboxCopy:a},e,r.skip||r.skipExists),u}function fn(s,e,t,r){t.length&&s.notify({tag:"*",flagUpdate:t},e,r)}function hn(s,e,t,r){if(!Array.isArray(t))throw K("Flags must be an array","INVALID");let n=[];return t.forEach(i=>{if(typeof i!="string")throw K("Flags must be strings","INVALID");let o=be(i);try{we(s,o)}catch(a){throw K(a.message,"INVALID")}if(r&&!s.isPermanentFlag(e,o))throw K("Flag "+o+" is not a permanent flag of "+e.path,"INVALID");n.indexOf(o)<0&&n.push(o)}),n}function Ma(s,e,t,r,n){if(["set","add","remove"].indexOf(n)<0)throw K("Invalid flag mode "+JSON.stringify(n)+", expected set, add or remove","INVALID");let i=hn(s,e,r,n!=="remove"),o=[];return t.forEach(a=>{let u=a.flags.join(" ");n==="set"?a.flags=i.slice():n==="add"?i.forEach(l=>s.ensureFlag(a.flags,l)):i.forEach(l=>s.removeFlag(a.flags,l)),s.rememberFlags(e,a.flags),a.flags.join(" ")!==u&&o.push(a)}),o.length&&(s.emit("flags",e,o,s.activeConnection),fn(s,e,o,null)),o}function xs(s,e){let t=new Set(Object.keys(s.folderCache)),r=s.createMailbox(e),n=Object.keys(s.folderCache).filter(i=>!t.has(i)).sort((i,o)=>i.length-o.length);return s.mailboxChanged("create",r.path,{created:n}),r}function Cs(s,e){let t=s.getMailbox(e);if(!t)throw K("Mailbox does not exist","NONEXISTENT");s.deleteMailbox(e),s.mailboxChanged("delete",t.path,{mailbox:t}),Ra(s,t,"Selected mailbox was deleted","MAILBOX DELETED")}function Ra(s,e,t,r){let n=s.activeConnection;s.connections.forEach(i=>{i!==n&&i.selectedMailbox===e&&i.bye(t,r)})}function ws(s,e,t){let r=s.getMailbox(e),n=s.getMailbox(t);if(!r||r.flags.indexOf("\\Noselect")>=0)throw K("Mailbox does not exist","NONEXISTENT");if(n&&n.flags.indexOf("\\Noselect")<0)throw K("Mailbox already exists","ALREADYEXISTS");let i=s.getSeparator(r);if(t.substr(0,r.path.length+i.length)===r.path+i)throw K("Can not move a mailbox into itself","CANNOT");let o=r.path,a;if(e.toUpperCase()==="INBOX"){let u=s.createMailbox(t);a=u.path,r.messages.forEach(l=>{s.copyMessage(u,l)}),it(s,r,()=>!0)}else{s.deleteMailbox(e,!0);try{s.createMailbox(t,r)}catch(u){throw s.createMailbox(e,r),s.indexFolders(),u}s.indexFolders(),a=r.path}return s.mailboxChanged("rename",a,{oldPath:o}),{path:a,mailbox:r}}function La(s,e,t={}){let r=t.uids||"keep";if(["keep","renumber","shuffle","offset"].indexOf(r)<0)throw K("Invalid UID mode "+JSON.stringify(r)+", expected keep, renumber, shuffle or offset","INVALID");let n=t.offset===void 0?0:t.offset;if(!Number.isSafeInteger(n)||n<0)throw K("Offset must be a non-negative integer","INVALID");let i=t.uidvalidity;if(i===void 0)i=Math.max(e.uidvalidity,s.uidvalidityCounter)+1;else if(!Number.isSafeInteger(i)||i<=e.uidvalidity||i>4294967295)throw K("UIDVALIDITY must be an integer above "+e.uidvalidity+" and below 2^32","INVALID");if(t.seed!==void 0&&!Number.isSafeInteger(t.seed))throw K("Seed must be an integer","INVALID");Ra(s,e,"UIDVALIDITY of the selected mailbox changed","UIDVALIDITY CHANGED");let o=e.messages,a=o.map(l=>l.uid),u=a;if(r==="renumber"||r==="shuffle"){if(u=o.map((l,c)=>c+1),r==="shuffle"){let l=Ss(t.seed===void 0?Math.floor(Math.random()*4294967295):t.seed);for(let c=u.length-1;c>0;c--){let f=Math.floor(l()*(c+1));[u[c],u[f]]=[u[f],u[c]]}}e.uidnext=o.length+1}else if(r==="offset"){let l=e.uidnext-1+n;u=a.map(c=>c+l),e.uidnext+=l}return o.forEach((l,c)=>{l.uid=u[c]}),r==="shuffle"&&o.sort((l,c)=>l.uid-c.uid),e.uidvalidity=i,s.uidvalidityCounter=Math.max(s.uidvalidityCounter,i),{uidvalidity:i,uidnext:e.uidnext,uids:a.map((l,c)=>({uid:l,newUid:u[c]}))}}function Ht(s,e){let t=s.getMailbox(e);if(!t||t.flags.indexOf("\\Noselect")>=0)throw K("Mailbox does not exist","NONEXISTENT");return t.subscribed?!1:(t.subscribed=!0,s.mailboxChanged("subscribe",t.path),!0)}function Ns(s,e){return e.toUpperCase()==="INBOX"&&(e="INBOX"),s.subscriptions.delete(e)?(s.mailboxChanged("unsubscribe",e),!0):!1}var mn="lrswipkxtea",Pt=new Set(mn),Ft={c:"kx",d:"et"},tf=["i","e","s","w","t"],Da=["s","w","t"],sf=["l","r","i","k","x","a"],Ua=["FLAGS","+FLAGS","-FLAGS","FLAGS.SILENT","+FLAGS.SILENT","-FLAGS.SILENT"];function rf(s){return s=b.Buffer.from(s,"utf-8").toString("binary"),s&&s.charAt(0)!=="\\"&&!/^NIL$/i.test(s)?{type:"ATOM",value:s}:s}function va(s){let e=new Error(s);return e.imapResponse="BAD",e}function dn(s){let e=new Set;for(let t of s)if(Pt.has(t))e.add(t);else if(Object.hasOwn(Ft,t))Ft[t].split("").forEach(r=>e.add(r));else throw/^[A-Z]$/.test(t)?va("Uppercase rights are not allowed"):va("The "+(/^[\x21-\x7e]$/.test(t)?t+" ":"")+"right is not supported");return e}function pn(s,e){return[{type:"MAILBOX",value:s.path}].concat(e.map(t=>rf(t)))}function kt(s){let e=mn.split("").filter(t=>s.has(t)).join("");return Object.keys(Ft).forEach(t=>{Ft[t].split("").some(r=>s.has(r))&&(e+=t)}),e}function nf(s){if(!s||s==="-")return"Empty identifier";if(/[\x00-\x1f\x7f]/.test(s))return"Identifier contains control characters";let e=b.Buffer.from(s,"binary").toString("utf-8");return b.Buffer.from(e,"utf-8").toString("binary")!==s?"Identifier is not valid UTF-8":!1}function gn(s){s.registerCapability("ACL"),s.registerCapability("RIGHTS=texk");let e=typeof s.options.aclOwner=="string"?s.options.aclOwner:"testuser",t=S=>S.username===e,r=S=>{if(!(S.acl instanceof Map)){let T=new Map,O=S.acl&&typeof S.acl=="object"?S.acl:{};Object.keys(O).forEach(M=>{try{T.set(M,dn(String(O[M])))}catch(k){throw new Error("Invalid ACL in storage for "+S.path+": "+k.message,{cause:k})}}),S.acl=T}return S.acl},n=(S,T,O)=>{let M=S.username;if(M===e)return Pt;O=O||r(T);let k=["anyone"].concat(typeof M=="string"&&M?M:[]),P=new Set;return k.forEach(j=>(O.get(j)||[]).forEach(Y=>P.add(Y))),k.forEach(j=>(O.get("-"+j)||[]).forEach(Y=>P.delete(Y))),P};s.acl={getRights:n,isOwner:t};let i=(S,T)=>{let O=r(S),M=new Map(O);T(O),s.emit("acl",S,M)},o=(S,T,O,M)=>{i(S,k=>{let P=new Set(k.get(T)||[]);O==="+"?M.forEach(Y=>P.add(Y)):O==="-"&&M.forEach(Y=>P.delete(Y));let j=O?P:M;j.size?k.set(T,j):k.delete(T)})};s.urlAccessChecks.push((S,T)=>{let O=n(S,T);return O.has("r")?!1:{text:O.has("l")?"Permission denied":"Mailbox does not exist"}}),s.searchAccessChecks.push((S,T,O)=>{let M=n(S,T);return M.has("r")&&(O||M.has("l"))});let a=S=>S.aclRights||Pt,u=S=>(S=be(S),S==="\\Deleted"?"t":S==="\\Seen"?"s":"w"),l=S=>typeof S=="string"?S:String(S&&S.value||""),c=(S,T)=>S.has(u(l(T))),f=(S,T)=>{let O=(S.attributes||[])[T];return ue(O)?O.value:!1},p=(S,T)=>{let O=f(S,T);return O!==!1&&s.getMailbox(O)||!1},y=(S,T,O,M)=>S.sendStatus(T,O,"NO","Permission denied","NOPERM",M),A=(S,T,O,M,k,P)=>{M.has("l")?y(S,T,O,k):P==="TRYCREATE"?S.sendStatus(T,O,"NO","Target mailbox does not exist","TRYCREATE",k):S.sendStatus(T,O,"NO","Mailbox does not exist","NONEXISTENT",k)},m=S=>{for(let T=s.getParentPath(S);T;T=s.getParentPath(T)){let O=s.getMailbox(T);if(O)return O}return!1},h=(S,T,O,M,k)=>{if(!M)return S.sendStatus(T,O,"NO","Mailbox does not exist","NONEXISTENT"),!1;let P=n(S,M);return k(P)?!0:(A(S,T,O,P),!1)},d=S=>S.has("a"),E=(S,T,O,M)=>{let k=T.attributes||[],P=T.command.toUpperCase();if(k.length!==M||k.some(Y=>!ue(Y)))return S.sendStatus(T,O,"BAD",P+" expects "+(M===1?"a mailbox name":M+" string arguments")),!1;let j=M>1&&nf(k[1].value);return j?(S.sendStatus(T,O,"BAD",j),!1):(M>1&&(k[1].value=b.Buffer.from(k[1].value,"binary").toString("utf-8")),!0)},I=(S,T,O)=>{let M=T.attributes[1].value;return M!==e&&M!=="-"+e?!1:(S.sendStatus(T,O,"NO","Rights of the mailbox owner can not be changed","CANNOT"),!0)},C=(S,T)=>(O,M,k,P)=>{E(O,M,k,S)&&T(O,M,k,s.getMailbox(M.attributes[0].value)),P()},H={states:Z.AUTHENTICATED,mailboxArguments:[0]},N=Object.assign({astringArguments:[1]},H),w=(S,T,O,M)=>S.send({tag:"*",command:"MYRIGHTS",attributes:pn(T,[kt(n(S,T))])},"MYRIGHTS",O,M,T),G=Ke(s);s.registerCapability("LIST-MYRIGHTS",()=>G.enabled),G.returnOptions.MYRIGHTS={onItem:(S,T,O,M,k,P)=>{M.matched&&M.exists&&w(S,T,k,P)}},s.setCommandHandler("SETACL",C(3,(S,T,O,M)=>{let k=T.attributes[1].value,P=T.attributes[2].value,j=/^[+-]/.test(P)?P.charAt(0):"",Y=dn(P.substr(j.length));!h(S,T,O,M,d)||I(S,T,O)||(o(M,k,j,Y),S.sendStatus(T,O,"OK","Setacl complete"))}),Object.assign({astringArguments:[1,2]},H)),s.setCommandHandler("DELETEACL",C(2,(S,T,O,M)=>{!h(S,T,O,M,d)||I(S,T,O)||(i(M,k=>k.delete(T.attributes[1].value)),S.sendStatus(T,O,"OK","Deleteacl complete"))}),N),s.setCommandHandler("GETACL",C(1,(S,T,O,M)=>{if(!h(S,T,O,M,d))return;let k=[e,kt(Pt)];r(M).forEach((P,j)=>{k.push(j,kt(P))}),S.send({tag:"*",command:"ACL",attributes:pn(M,k)},"ACL",T,O,M),S.sendStatus(T,O,"OK","Getacl complete")}),H),s.setCommandHandler("LISTRIGHTS",C(2,(S,T,O,M)=>{if(!h(S,T,O,M,d))return;let k=T.attributes[1].value,P;k===e?P=[k,kt(Pt)]:P=[k,""].concat(mn.split(""),Object.keys(Ft)),S.send({tag:"*",command:"LISTRIGHTS",attributes:pn(M,P)},"LISTRIGHTS",T,O,M),S.sendStatus(T,O,"OK","Listrights complete")}),N),s.setCommandHandler("MYRIGHTS",C(1,(S,T,O,M)=>{h(S,T,O,M,k=>sf.some(P=>k.has(P)))&&(w(S,M,T,O),S.sendStatus(T,O,"OK","Myrights complete"))}),H);let F={},W={},x=()=>{Object.keys(F).forEach(S=>{let T=s.getCommandHandler(S);T&&(W[S]=T,s.setCommandHandler(S,(O,M,k,P)=>t(O)?T(O,M,k,P):F[S](T,O,M,k,P)))}),Object.keys(G.returnOptions).forEach(S=>{let T=G.returnOptions[S];if(typeof T.onItem!="function")return;let O=T.onItem,M=S==="STATUS"?"r":"l";T.onItem=(k,P,...j)=>{if(t(k))return O(k,P,...j);let Y=n(k,P);if(Y.has("l")&&Y.has(M))return O(k,P,...j)}}),Ua.forEach(S=>{let T=s.storeHandlers[S]||Ts[S];s.storeHandlers[S]=(O,M,k,...P)=>{let j=a(O);if(Da.every($=>j.has($)))return T(O,M,k,...P);k=[].concat(k),k.forEach($=>we(O.server,be(l($))));let Y=k.filter($=>c(j,$));return S.charAt(0)!=="+"&&S.charAt(0)!=="-"&&(Y=M.flags.filter($=>!c(j,$)).concat(Y)),T(O,M,Y,...P)}})};s.once("pluginsLoaded",x);let L=(S,T,O,M,k)=>{let P=p(O,0);if(!P)return S(T,O,M,k);let j=O.command.toUpperCase(),Y=n(T,P);return Y.has("r")?(T.aclRights=Y,j==="SELECT"&&!tf.some($=>Y.has($))?W.EXAMINE(T,O,M,k):S(T,O,M,k)):(on(T,O,M),T.closeMailbox(),A(T,O,M,Y,j+" FAILED"),k())};F.SELECT=L,F.EXAMINE=L;let v=(S,T,O)=>(M,k,P)=>{let j=p(k,T),Y=j&&n(M,j);return Y&&!Y.has(S)?(A(M,k,P,Y,void 0,O),!1):!0},V=(S,T,O)=>{let M=v(S,T,O);return(k,P,j,Y,$)=>M(P,j,Y)?k(P,j,Y,$):$()};F.STATUS=V("r",0),F.SUBSCRIBE=V("l",0),F.DELETE=V("x",0);let _=(S,T,O,M)=>{let k=m(M);return!k||!n(S,k).has("k")?(y(S,T,O),!1):!0};F.CREATE=(S,T,O,M,k)=>{let P=f(O,0);return P!==!1&&!_(T,O,M,P)?k():S(T,O,M,k)};let X=v("x",0);F.RENAME=(S,T,O,M,k)=>{if(!X(T,O,M))return k();let P=f(O,1);return P!==!1&&p(O,0)&&!_(T,O,M,P)?k():S(T,O,M,k)},F.APPEND=(S,T,O,M,k)=>{let P=p(O,0);if(!P)return S(T,O,M,k);let j=n(T,P);if(!j.has("i"))return A(T,O,M,j,"APPEND FAILED","TRYCREATE"),k();let Y=O.attributes[1];if(Array.isArray(Y)&&Y.every($=>$&&$.type==="ATOM"))try{Y.forEach($=>we(T.server,be($.value))),O.attributes[1]=Y.filter($=>c(j,$))}catch{}return S(T,O,M,k)};let q=(S,T)=>{let O=T?n(S,T):!1;return!O||O.has("i")?!1:O.has("l")?{command:"NO",code:"NOPERM",text:"Permission denied"}:{command:"NO",code:"TRYCREATE",text:"Target mailbox does not exist"}},se=V("i",1,"TRYCREATE"),ee=S=>(T,O,M,k,P)=>{let j=M.command.toUpperCase();if(S&&!O.readOnly){let Y=a(O);if(!Y.has("t")||!Y.has("e"))return y(O,M,k,j+" FAIL"),P()}return se(T,O,M,k,P)};F.COPY=ee(!1),F["UID COPY"]=ee(!1),F.MOVE=ee(!0),F["UID MOVE"]=ee(!0);let fe=(S,T)=>{let O=a(S);return!S.readOnly&&(!O.has("t")||!O.has("e"))?{command:"NO",code:"NOPERM",text:"Permission denied"}:q(S,T)},is=(S,T,O,M,k)=>{let P=fe(T,p(O,1));return P?(T.sendStatus(O,M,P.command,P.text,P.code,O.command.toUpperCase()+" FAILED"),k()):S(T,O,M,k)};F.REPLACE=is,F["UID REPLACE"]=is,s.literalFilters.unshift((S,T,O)=>{if(t(S)||S.isBusy())return!1;let M=Bt(S,T,O),k=M!==!1&&s.getMailbox(M);return k?T==="APPEND"?q(S,k):fe(S,k):!1});let Nr=["r","s","w","i","p"],Lt=S=>S.has("l")&&Nr.some(T=>S.has(T)),ko=(S,T,O,M,k)=>{let P=O.attributes||[],j=O.command.toUpperCase()==="GETMETADATA"&&Array.isArray(P[0])?1:0,Y=p(O,j);if(Y&&f(O,j)!==""){let $=n(T,Y);if(!Lt($))return A(T,O,M,$),k()}return S(T,O,M,k)};F.GETMETADATA=ko,F.SETMETADATA=ko,s.notifyFilters.push((S,T)=>{let O=T.command||{};if(O.command!=="METADATA"||t(S))return!0;let M=O.attributes&&O.attributes[0],k=M&&typeof M=="object"?M.value:M,P=typeof k=="string"&&k!==""&&s.getMailbox(k);return!P||Lt(n(S,P))}),F.GETQUOTAROOT=(S,T,O,M,k)=>{let P=p(O,0);return(!P||!n(T,P).has("r"))&&(O.aclQuotaMailboxOnly=!0),S(T,O,M,k)},F.SETQUOTA=(S,T,O,M,k)=>{let P=O.attributes||[];return P.length===2&&Array.isArray(P[1])&&!Object.keys(s.folderCache).every(Y=>{let $=s.folderCache[Y];return!s.isPersonal($)||n(T,$).has("a")})?(y(T,O,M),k()):S(T,O,M,k)};let Po=(S,T,O,M,k)=>!T.readOnly&&!a(T).has("e")?(y(T,O,M),k()):S(T,O,M,k);F.EXPUNGE=Po,F["UID EXPUNGE"]=Po,s.resetHandlers.push(S=>{S.aclRights=null}),s.connectionHandlers.push(S=>{let T=S.canSetSeen,O=S.canExpunge;S.canSetSeen=()=>T.call(S)&&a(S).has("s"),S.canExpunge=()=>O.call(S)&&a(S).has("e")});let Fo=(S,T,O,M,k)=>{let P=a(T),j=O.attributes||[],Y=j.length>=3&&j[j.length-2]&&j[j.length-2].type==="ATOM"&&j[j.length-2].value.toUpperCase();if(T.readOnly||!Y)return S(T,O,M,k);if(Ua.indexOf(Y)<0)return Object.hasOwn(s.storeHandlers,Y)&&!P.has("w")?(y(T,O,M),k()):S(T,O,M,k);let $=[].concat(j[j.length-1]||[]);try{$.forEach(Dt=>we(T.server,be(l(Dt))))}catch{return S(T,O,M,k)}let Me;return Y.charAt(0)==="+"||Y.charAt(0)==="-"?Me=!$.length||$.some(Dt=>c(P,Dt)):Me=Da.some(Dt=>P.has(Dt)),Me?S(T,O,M,k):(y(T,O,M),k())};F.STORE=Fo,F["UID STORE"]=Fo;let Pl=S=>{let T=S&&S.attributes||[];return T.some((O,M)=>O&&O.type==="ATOM"&&/^RETURN$/i.test(O.value)&&Array.isArray(T[M+1])&&T[M+1].some(k=>k&&k.type==="ATOM"&&/^STATUS$/i.test(k.value)))},Fl=(S,T)=>s.hasDescendant(T.path,O=>n(S,O).has("l"));s.outputHandlers.push((S,T,O,M,k,P)=>{if(!t(S)){if((O==="LIST ITEM"||O==="LSUB ITEM")&&P&&P.path){if(!n(S,P).has("l")){T.skipResponse=!0;return}let j=T.attributes[0];if(!Array.isArray(j))return;T.attributes[0]=j.slice();let Y=j.findIndex(Me=>Me&&Me.value==="\\HasChildren");Y>=0&&!Fl(S,P)&&(T.attributes[0][Y]={type:"ATOM",value:"\\HasNoChildren"}),!j.some(Me=>Me&&/^\\(Noselect|NonExistent)$/i.test(Me.value))&&Pl(M)&&!n(S,P).has("r")&&T.attributes[0].push({type:"ATOM",value:"\\Noselect"});return}if(O==="QUOTA"&&M&&M.aclQuotaMailboxOnly&&Array.isArray(T.attributes[1])){let j=T.attributes[1],Y=[];for(let $=0;$<j.length;$+=3)j[$]&&String(j[$].value).toUpperCase()==="MAILBOX"&&Y.push(j[$],j[$+1],j[$+2]);Y.length?T.attributes[1]=Y:T.skipResponse=!0;return}if(O==="SELECT PERMANENTFLAGS"){let j=T.attributes[0]&&T.attributes[0].section,Y=a(S);j&&Array.isArray(j[1])&&(j[1]=j[1].filter($=>$.value==="\\*"?Y.has("w"):c(Y,$)));return}if(P&&P.targetUids&&P.mailbox&&/^(UID )?(COPY|MOVE COPYUID)$/.test(O)){let j=n(S,P.mailbox),Y=new Set(P.targetUids);P.mailbox.messages.forEach($=>{Y.has($.uid)&&($.flags=$.flags.filter(Me=>c(j,Me)))})}}}),s.on("mailbox",S=>{if(S.type==="delete"){let T=s.getMailbox(S.path);T&&T!==S.mailbox&&delete T.acl}else S.type==="create"&&(S.created||[]).forEach(T=>{let O=m(T),M=s.folderCache[T];if(O&&M&&O!==M){let k=new Map;r(O).forEach((P,j)=>k.set(j,new Set(P))),M.acl=k}})});let os=S=>{let T={};return r(S).forEach((O,M)=>{T[M]=kt(O)}),T},Mr=S=>s.control.requireMailbox(S);s.control.snapshotHandlers.push((S,T)=>{S.acl instanceof Map&&(T.acl=os(S))});let _l=S=>os(Mr(S)),Gl=(S,T,O)=>{let M=Mr(S);if(typeof T!="string"||!T||typeof O!="string")throw K("setAcl expects an identifier and a rights string","INVALID");let k=/^[+-]/.test(O)?O.charAt(0):"",P;try{P=dn(O.substr(k.length))}catch(j){throw K(j.message,"INVALID")}return o(M,T,k,P),os(M)},Xl=(S,T)=>{let O=Mr(S);if(typeof T!="string"||!r(O).has(T))throw K("No ACL entry for "+JSON.stringify(T),"NONEXISTENT");return i(O,M=>M.delete(T)),os(O)};s.control.register("getAcl",_l,[{method:"GET",path:"/v1/mailboxes/{path}/acl",summary:"The ACL of a mailbox (ACL plugin)",handler:({params:S})=>s.control.getAcl(S.path)}]),s.control.register("setAcl",Gl,[{method:"PUT",path:"/v1/mailboxes/{path}/acl/{identifier}",summary:'Sets the rights of an identifier ({ rights }, "+" or "-" in front adds or removes, ACL plugin)',handler:({params:S,body:T})=>s.control.setAcl(S.path,S.identifier,T.rights)}]),s.control.register("deleteAcl",Xl,[{method:"DELETE",path:"/v1/mailboxes/{path}/acl/{identifier}",summary:"Removes an identifier from the ACL (ACL plugin)",handler:({params:S})=>s.control.deleteAcl(S.path,S.identifier)}])}g();function En(s){let e="appendLimit"in s.options?s.options.appendLimit:null;if(e!==null&&!Ba(e))throw new TypeError("Invalid appendLimit option, expecting a non-negative integer");let t=o=>Object.hasOwn(o,"appendLimit"),r=()=>Object.values(s.folderCache).some(t),n=o=>t(o)?Ba(o.appendLimit)?o.appendLimit:null:e,i=(o,a)=>{let u=n(o);return u!==null&&(a>u||u===0)};e!==null&&s.registerCapability("APPENDLIMIT="+e,()=>!r()),s.registerCapability("APPENDLIMIT",()=>e===null||r()),s.appendChecks.push((o,a,u,l)=>l.command&&u.some(c=>i(a,c.raw.length))?{code:"TOOBIG",text:"Message exceeds the APPENDLIMIT of the mailbox"}:!1),s.literalFilters.push((o,a,u,l)=>{let c=Bt(o,a,u),f=c!==!1&&s.getMailbox(c);return f&&i(f,l)?{command:"NO",code:"TOOBIG",text:"Message exceeds the APPENDLIMIT of the mailbox"}:!1}),s.allowedStatus.push("APPENDLIMIT"),s.statusHandlers.APPENDLIMIT=(o,a)=>n(a)}function Ba(s){return Number.isSafeInteger(s)&&s>=0}g();var of=new TextDecoder("utf-8",{fatal:!0});function An(s){s.registerCapability("AUTH=PLAIN",t=>t.state==="Not Authenticated");let e=(t,r,n,i)=>{let o=t.decodeSaslResponse(i);if(!o)return t.sendStatus(r,n,"BAD","Invalid base64 in SASL response",!1,"AUTHENTICATE PLAIN FAILED");let a;try{a=of.decode(o)}catch{return t.sendStatus(r,n,"BAD","Invalid UTF-8 in SASL PLAIN message",!1,"AUTHENTICATE PLAIN FAILED")}let u=a.split("\0"),l=u[0]||"",c=u[1]||"",f=u[2]||"",p=t.server.getUser(c);if(u.length!==3||!p||p.password!==f)return t.sendStatus(r,n,"NO","Login failed: authentication failure","AUTHENTICATIONFAILED","AUTHENTICATE PLAIN FAILED");if(l&&l!==c)return t.sendStatus(r,n,"NO","Can not act as "+l,"AUTHORIZATIONFAILED","AUTHENTICATE PLAIN FAILED");t.state="Authenticated",t.username=c,t.sendStatus(r,n,"OK","User logged in",!1,"AUTHENTICATE PLAIN SUCCESS")};s.setCommandHandler("AUTHENTICATE PLAIN",(t,r,n,i)=>{if(!r.attributes)t.inputHandler=function(o){if(t.inputHandler=!1,o==="*")return t.sendStatus(r,n,"BAD","Authentication cancelled",!1,"AUTHENTICATE PLAIN FAILED");e(t,r,n,o)},t.sendContinuation("","AUTHENTICATE PLAIN");else if(r.attributes.length===1&&r.attributes[0].type==="ATOM"){if(!s.capabilities["SASL-IR"]||!s.capabilities["SASL-IR"](t))return t.sendStatus(r,n,"BAD","SASL-IR must be enabled to send Initial Response with the request",!1,"AUTHENTICATE PLAIN FAILED"),i();e(t,r,n,r.attributes[0].value)}else t.sendStatus(r,n,"BAD","Invalid attributes for AUTHENTICATE PLAIN",!1,"AUTHENTICATE PLAIN FAILED");return i()})}g();g();g();function Rs(s,e){let r=new Ms(s).tokenize(),n=[],i=[],o=[];return r.forEach(a=>{a.type==="operator"&&(a.value===","||a.value===";")?(i.length&&n.push(i),i=[]):i.push(a)}),i.length&&n.push(i),n.forEach(a=>{let u=af(a,e);u.length&&(o=o.concat(u))}),o}function af(s,e){let t,r=!1,n="text",i=[],o={address:[],comment:[],group:[],text:[]},a,u;for(a=0,u=s.length;a<u;a++)if(t=s[a],t.type==="operator")switch(t.value){case"<":n="address";break;case"(":n="comment";break;case":":if(e){n="text";break}n="group",r=!0;break;default:n="text"}else t.value&&o[n].push(t.value);if(!o.text.length&&o.comment.length&&(o.text=o.comment,o.comment=[]),r){let l=o.text.join(" ");i.push({name:l,group:o.group.length?Rs(o.group.join(","),!0):[]})}else{if(!o.address.length&&o.text.length){for(a=o.text.length-1;a>=0;a--)if(o.text[a].match(/^[^@\s]+@[^@\s]+$/)){o.address=o.text.splice(a,1);break}let p=function(y){return o.address.length?y:(o.address=[y.trim()]," ")};if(!o.address.length)for(a=o.text.length-1;a>=0&&(o.text[a]=o.text[a].replace(/\s*\b[^@\s]+@[^@\s]+\b\s*/,p).trim(),!o.address.length);a--);}!o.text.length&&o.comment.length&&(o.text=o.comment,o.comment=[]),o.address.length>1&&(o.text=o.text.concat(o.address.splice(1)));let l=o.text.join(" "),c=o.address.join(" "),f={address:c||l||"",name:l||c||""};f.address===f.name&&((f.address||"").match(/@/)?f.name="":f.address=""),i.push(f)}return i}var Ms=class{constructor(e){this.str=(e||"").toString(),this.operatorCurrent="",this.operatorExpecting="",this.node=null,this.escaped=!1,this.list=[]}tokenize(){let e,t=[];for(let r=0,n=this.str.length;r<n;r++)e=this.str.charAt(r),this.checkChar(e);return this.list.forEach(r=>{r.value=(r.value||"").toString().trim(),r.value&&t.push(r)}),t}checkChar(e){if((e in this.operators||e==="\\")&&this.escaped)this.escaped=!1;else if(this.operatorExpecting&&e===this.operatorExpecting){this.node={type:"operator",value:e},this.list.push(this.node),this.node=null,this.operatorExpecting="",this.escaped=!1;return}else if(!this.operatorExpecting&&e in this.operators){this.node={type:"operator",value:e},this.list.push(this.node),this.node=null,this.operatorExpecting=this.operators[e],this.escaped=!1;return}if(!this.escaped&&e==="\\"){this.escaped=!0;return}this.node||(this.node={type:"text",value:""},this.list.push(this.node)),this.escaped&&e!=="\\"&&(this.node.value+="\\"),this.node.value+=e,this.escaped=!1}};Ms.prototype.operators={'"':'"',"(":")","<":">",",":"",":":";"};var Ha=/^[a-zA-Z0-9\-*]{1,99}$/,Ls=["7bit","8bit","binary"],uf=32;function _t(s){let e=b.Buffer.isBuffer(s)?s.toString("binary"):s||"";return/(?:^|[^\r])\n/.test(e)?e.replace(/\r?\n/g,`\r
4
+ `)o+=2;else throw this.unexpected(o);if(a>this.maxNumber||o+a>n)throw ae("Unexpected end of input",this.pos+n);let u=r.substring(o,o+a);if(!t){let l=u.indexOf("\0");if(l>=0)throw ae("Unexpected \\x00",this.pos+o+l)}return this.addValue(t?"LITERAL8":"LITERAL",u,e,o+a),this.afterValue(o+a)}readPartial(e){let t=this.str,r=t.length,n=e+1,i=o=>{let a=n;for(;n<r&&Kr(t.charCodeAt(n));)n++;if(n===a)throw this.unexpected(n);if(o&&t.charAt(a)==="0")throw ae("Invalid partial",this.pos+a);if(Number(t.slice(a,n))>this.maxNumber)throw ae("Invalid partial",this.pos+a)};if(i(!1),t.charAt(n)==="."&&(n++,i(!0)),t.charAt(n)!==">")throw this.unexpected(n);return this.addValue("PARTIAL",t.slice(e+1,n),e,n+1),this.afterValue(n+1)}};E();var ya=/[\x00\r\n\x80-\uffff]/,ba=/[\x00\r\n\u0100-\uffff]/,jc=s=>{for(let e=0,t=s.length;e<t;e++)if(!he.isAtomChar(s.charAt(e)))return!1;return!!s.length},Vc=s=>s==="\\*"||jc(s.charAt(0)==="\\"?s.slice(1):s),qc=s=>s==="$"||he.isSequenceSet(s),Jr=s=>{let e=Math.round(Number(s));return Number.isSafeInteger(e)&&e>=0?e:0},Fe=s=>b.Buffer.isBuffer(s)?s.toString("binary"):s==null?"":String(s),As=s=>"{"+s.length+`}\r
5
+ `+s,Ta=s=>'"'+s.replace(/["\\]/g,"\\$&")+'"',Qc=s=>"~"+As(s),Yc=s=>ya.test(s)?As(s):Ta(s),Kc=s=>!ya.test(s)||!ba.test(s)&&Ye(b.Buffer.from(s,"binary"))?Ta(s):As(s),en=(s,e)=>{let t=new Error(s);return t.code=e,t},Zr=(s,e)=>{if(ba.test(s))throw en("Line break or NUL in "+e,"InvalidTextValue");return s},Aa=s=>[].concat(s||[]);function tn(s,e){let t=e&&e.utf8?Kc:Yc,r=Zr(Fe(s.tag),"tag")+(s.command?" "+Zr(Fe(s.command),"command"):""),n=!1,i=o=>{if(n||(r+=" "),n=!1,Array.isArray(o)){let u=o;r+="(",n=!0;let l=0;if(u.adjacentLists)for(;l<u.length&&Array.isArray(u[l]);)l++;u.forEach((c,f)=>{f&&f<l&&(n=!0),i(c)}),r+=")",n=!1;return}if(b.Buffer.isBuffer(o)){r+=t(Fe(o));return}if(!o&&typeof o!="string"&&typeof o!="number"){r+="NIL";return}if(typeof o=="string"){r+=t(o);return}if(typeof o=="number"){r+=Jr(o);return}let a;switch(typeof o.type=="string"?o.type.toUpperCase():""){case"LITERAL":r+=As(Fe(o.value));break;case"LITERAL8":r+=Qc(Fe(o.value));break;case"STRING":r+=t(Fe(o.value));break;case"TEXT":r+=Zr(Fe(o.value),"TEXT value");break;case"SEQUENCE":if(a=Fe(o.value),!qc(a))throw en("Invalid sequence set","InvalidSequenceSet");r+=a;break;case"NUMBER":r+=Jr(o.value);break;case"ATOM":case"SECTION":a=Fe(o.value),(a||!o.section)&&(r+=Vc(a)?a:t(a)),o.section&&(r+="[",n=!0,o.section.forEach(i),r+="]",n=!1),o.partial&&(r+="<"+Aa(o.partial).map(Jr).join(".")+">");break;default:throw en("Unknown node type "+JSON.stringify(o.type),"InvalidNodeType")}};return Aa(s.attributes).forEach(i),r}var st={parser:$r,compiler:tn};E();E();E();E();var ys=["Not Authenticated","Authenticated","Selected"],bs=["Not Authenticated"],Ce=["Authenticated","Selected"],Re=["Selected"];function re(s){let e=(Array.isArray(s)?{states:s}:s)||{};return{states:e.states?[].concat(e.states):!1,noArguments:!!e.noArguments,mailboxArguments:[].concat(e.mailboxArguments||[]),astringArguments:[].concat(e.astringArguments||[]),searchCriteria:typeof e.searchCriteria=="number"?e.searchCriteria:!1,sequenceSet:typeof e.sequenceSet=="number"?e.sequenceSet:!1,noExpunge:!!e.noExpunge,literal8:e.literal8===!0||typeof e.literal8=="string"?e.literal8:!1,noPipelining:!!e.noPipelining,appendMessage:!!e.appendMessage}}var Sa={CAPABILITY:re({states:ys,noArguments:!0}),NOOP:re({states:ys,noArguments:!0}),LOGOUT:re({states:ys,noArguments:!0}),STARTTLS:re({states:bs,noArguments:!0,noPipelining:!0}),LOGIN:re({states:bs,astringArguments:[0,1]}),SELECT:re({states:Ce,mailboxArguments:[0]}),EXAMINE:re({states:Ce,mailboxArguments:[0]}),CREATE:re({states:Ce,mailboxArguments:[0]}),DELETE:re({states:Ce,mailboxArguments:[0]}),RENAME:re({states:Ce,mailboxArguments:[0,1]}),SUBSCRIBE:re({states:Ce,mailboxArguments:[0]}),UNSUBSCRIBE:re({states:Ce,mailboxArguments:[0]}),LIST:re({states:Ce,astringArguments:[0,1]}),LSUB:re({states:Ce,astringArguments:[0,1]}),STATUS:re({states:Ce,mailboxArguments:[0]}),APPEND:re({states:Ce,mailboxArguments:[0],literal8:"BINARY",appendMessage:!0}),CHECK:re({states:Re,noArguments:!0}),CLOSE:re({states:Re,noArguments:!0}),EXPUNGE:re({states:Re,noArguments:!0}),SEARCH:re({states:Re,searchCriteria:0,noExpunge:!0}),FETCH:re({states:Re,sequenceSet:0,noExpunge:!0}),STORE:re({states:Re,sequenceSet:0,noExpunge:!0}),COPY:re({states:Re,sequenceSet:0,mailboxArguments:[1]}),"UID COPY":re({states:Re,mailboxArguments:[1]}),"UID SEARCH":re({states:Re,searchCriteria:0})},zc=re({states:Re}),Wc=re({states:bs});function Ia(s){return Object.hasOwn(Sa,s)?Sa[s]:/^UID /.test(s)?zc:/^AUTHENTICATE /.test(s)?Wc:!1}var Z={ANY:ys,NOT_AUTHENTICATED:bs,AUTHENTICATED:Ce,SELECTED:Re};E();var sn=/[\x00-\x1f\x7f (){%*"\\\]]/;function be(s){return s.charAt(0)==="\\"&&(s=s.charAt(0)+s.charAt(1).toUpperCase()+s.substr(2).toLowerCase()),s}function we(s,e){if(e.charAt(0)==="\\"){if(s.systemFlags.indexOf(e)<0)throw new Error("Invalid system flag "+e)}else if(!e||sn.test(e))throw new Error("Invalid flag keyword "+JSON.stringify(e))}E();var rt={},Ts=rt;function Oa(s,e,t){let r=s.selectedMailbox,n=[];[].concat(t).forEach(i=>{i=be(typeof i=="string"?i:String(i.value||"")),we(s.server,i),s.server.isPermanentFlag(r,i)&&n.indexOf(i)<0&&n.push(i)}),e.flags=n,s.server.rememberFlags(r,n)}function xa(s,e,t){let r=s.selectedMailbox;[].concat(t).forEach(n=>{n=be(typeof n=="string"?n:String(n.value||"")),we(s.server,n),s.server.isPermanentFlag(r,n)&&e.flags.indexOf(n)<0&&e.flags.push(n)}),s.server.rememberFlags(r,e.flags)}function Ca(s,e,t){[].concat(t).forEach(r=>{if(r=be(typeof r=="string"?r:String(r.value||"")),we(s.server,r),e.flags.indexOf(r)>=0){for(let n=0;n<e.flags.length;n++)if(e.flags[n]===r){e.flags.splice(n,1);break}}})}function rn(s,e,t,r,n){let i=[{type:"ATOM",value:"FLAGS"},s.getFlags(n).map(o=>({type:"ATOM",value:o}))];(e.command||"").toUpperCase()==="UID STORE"&&(i.push({type:"ATOM",value:"UID"}),i.push(n.uid)),s.send({tag:"*",attributes:[r,{type:"ATOM",value:"FETCH"},i]},"FLAG UPDATE",e,t,n)}rt.FLAGS=function(s,e,t,r,n,i){Oa(s,e,t),rn(s,n,i,r,e)};rt["+FLAGS"]=function(s,e,t,r,n,i){xa(s,e,t),rn(s,n,i,r,e)};rt["-FLAGS"]=function(s,e,t,r,n,i){Ca(s,e,t),rn(s,n,i,r,e)};rt["FLAGS.SILENT"]=function(s,e,t){Oa(s,e,t)};rt["+FLAGS.SILENT"]=function(s,e,t){xa(s,e,t)};rt["-FLAGS.SILENT"]=function(s,e,t){Ca(s,e,t)};E();function Ke(s){return s.listExtensions||(s.listExtensions={enabled:!1,selectionOptions:Object.create(null),returnOptions:Object.create(null)}),s.listExtensions}E();function nn(s,e,t,r){return an(s,e,t,r,!1)}function on(s,e,t){s.everSelected=!0,s.state==="Selected"&&s.server.closedChecks.some(r=>r(s))&&s.send({tag:"*",command:"OK",attributes:[{type:"SECTION",section:[{type:"ATOM",value:"CLOSED"}]},{type:"TEXT",value:"Previous mailbox closed"}]},"CLOSED",e,t)}function an(s,e,t,r,n){let i=n?"EXAMINE":"SELECT";if(!e.attributes||e.attributes.length!==1||!e.attributes[0]||["STRING","LITERAL","ATOM"].indexOf(e.attributes[0].type)<0)return s.send({tag:e.tag,command:"BAD",attributes:[{type:"TEXT",value:i+" expects 1 mailbox argument"}]},"INVALID COMMAND",e,t),r();let o=e.attributes[0].value;on(s,e,t);let a=s.server.getMailbox(o);if(!a||a.flags.indexOf("\\Noselect")>=0)return s.closeMailbox(),s.sendStatus(e,t,"NO","Mailbox does not exist","NONEXISTENT",i+" FAILED"),r();s.state="Selected",s.selectedMailbox=a,s.readOnly=n,s.emitSession("select"),s.notificationQueue=[];let u=new Set;s.recent=u,a.messages.forEach(p=>{p.recent&&(u.add(p),n||delete p.recent)});let c=s.server.getStatus(a).permanentFlags.map(p=>({type:"ATOM",value:p}));s.send({tag:"*",command:"FLAGS",attributes:[c]},i+" FLAGS",e,t),a.allowPermanentFlags&&c.push({type:"TEXT",value:"\\*"}),s.send({tag:"*",command:"OK",attributes:[{type:"SECTION",section:[{type:"ATOM",value:"PERMANENTFLAGS"},n?[]:c]},{type:"TEXT",value:n?"No permanent flags permitted":"Flags permitted"}]},i+" PERMANENTFLAGS",e,t),s.send({tag:"*",attributes:[a.messages.length,{type:"ATOM",value:"EXISTS"}]},i+" EXISTS",e,t),s.send({tag:"*",attributes:[s.recent.size,{type:"ATOM",value:"RECENT"}]},i+" RECENT",e,t);let f=a.messages.findIndex(p=>p.flags.indexOf("\\Seen")<0);return f>=0&&s.send({tag:"*",command:"OK",attributes:[{type:"SECTION",section:[{type:"ATOM",value:"UNSEEN"},f+1]},{type:"TEXT",value:"First unseen message"}]},i+" UNSEEN",e,t),s.send({tag:"*",command:"OK",attributes:[{type:"SECTION",section:[{type:"ATOM",value:"UIDVALIDITY"},a.uidvalidity]},{type:"TEXT",value:"UIDs valid"}]},i+" UIDVALIDITY",e,t),s.send({tag:"*",command:"OK",attributes:[{type:"SECTION",section:[{type:"ATOM",value:"UIDNEXT"},a.uidnext]},{type:"TEXT",value:"Predicted next UID"}]},i+" UIDNEXT",e,t),s.send({tag:e.tag,command:"OK",attributes:[{type:"SECTION",section:[{type:"ATOM",value:n?"READ-ONLY":"READ-WRITE"}]},{type:"TEXT",value:"Completed"}]},i,e,t),r()}E();E();function J(s,e){return!!s&&!Array.isArray(s)&&s.type==="ATOM"&&(e===void 0||String(s.value).toUpperCase()===e)}function ue(s){return!!s&&!Array.isArray(s)&&["ATOM","STRING","LITERAL"].indexOf(s.type)>=0&&!s.section&&!s.partial}var wa=/[\s()[\]{"%*\\<]/;function $c(s){let e=[],t=0;for(;t<s.length;){let r=s.charAt(t);if(r==='"'){for(t++;t<s.length&&s.charAt(t)!=='"';t++)s.charAt(t)==="\\"&&t++;t++;continue}let n=(r==="{"||r==="~")&&s.substr(t,32).match(/^~?\{(\d+)\+?\}\r\n/);if(n){t+=n[0].length+Number(n[1]);continue}if(wa.test(r)){t++;continue}let i=t;for(;i<s.length&&!wa.test(s.charAt(i));)i++;let o=s.substring(t,i);/^nil$/i.test(o)&&e.push(o),t=i}return e}function yt(s,e,t){if(!s.attributes||!/nil/i.test(e||""))return;let r=[],n=(o,a)=>{o.forEach((u,l)=>{u===null?r.push({list:o,index:l,path:a.concat(l)}):Array.isArray(u)?n(u,a.concat(l)):u&&Array.isArray(u.section)&&n(u.section,a.concat(l,"section"))})};if(n(s.attributes,[]),!r.length)return;let i=$c(e).slice(-r.length);r.forEach((o,a)=>{t(o.path)&&(o.list[o.index]={type:"ATOM",value:i.length===r.length?i[a]:"NIL"})})}function nt(s,e,t,r){let n=new Error(s);return n.imapResponse=r||"NO",n.responseCode=e||!1,n.responseCodeArgs=t||[],n}var _e=s=>nt(s,!1,!1,"BAD");function Jc(s,e){try{return e.map(t=>{if(!t||t.type!=="ATOM")throw new Error("Invalid flags argument");let r=be(t.value);return we(s.server,r),r})}catch{throw _e("Invalid flags argument")}}function Zc(s,e,t){let r=s.server,n=[];for(let i=0;i<e.length;){let o={flags:[],internaldate:!1,raw:!1};if(Array.isArray(e[i])&&(o.flags=Jc(s,e[i++])),e[i]&&e[i].type==="STRING"){if(!r.validateInternalDate(e[i].value))throw _e("Invalid internaldate argument");o.internaldate=e[i++].value}let a=e[i++],u=a&&a.type==="ATOM"?String(a.value).toUpperCase():"";if(a&&a.type==="LITERAL")o.raw=a.value;else if(a&&a.type==="LITERAL8"&&r.appendLiteral8)o.raw=a.value,o.literal8=!0;else if(u&&Object.hasOwn(r.appendDataHandlers,u)&&i<e.length)o.resolve=r.appendDataHandlers[u](s,e[i++]);else throw _e("Invalid message source argument");n.push(o)}if(!n.length)throw _e("Missing message argument");if(n.length>t)throw _e("Only a single message can be appended");return n}function ef(s,e,t,r,n){let i=[];r.responseCode&&i.push({type:"SECTION",section:[{type:"ATOM",value:r.responseCode}].concat(r.responseCodeArgs)}),i.push({type:"TEXT",value:r.message}),s.send({tag:e.tag,command:r.imapResponse,attributes:i},r.imapResponse==="BAD"?"INVALID COMMAND":n,e,t)}function Bt(s,e,t){let r=s.server.getCommandOptions(e);if(!r.appendMessage)return!1;let n=r.mailboxArguments[0];if(/[ (]URL $/i.test(t.slice(-5)))return!1;let i=l=>{l=l.replace(/ $/,"");for(let c of["",")"])try{let f=st.parser(l+c);return yt(f,l,p=>p.length===1&&p[0]===n),f.attributes||[]}catch{}return[]},o=t.match(/(~?)\{(\d+)\+?\}\r\n/),a=i(o?t.substr(0,o.index):t);a.length<=n&&o&&!o[1]&&(a=i(t.substr(0,o.index+o[0].length+Number(o[2]))));let u=a[n];if(!ue(u))return!1;try{return s.importMailboxName(u.value)}catch{return!1}}function Na(s,e,t){let r=!s.isBusy()&&Bt(s,e,t);return r!==!1&&s.server.targetRefusal(r)}function un(s,e,t,r,n,i){let o=i.command+" FAILED",a=i.maxMessages||(s.server.multiAppend?1/0:1);try{if(!r||["STRING","ATOM","LITERAL"].indexOf(r.type)<0)throw _e("Invalid mailbox argument");let u=Zc(s,n,a),l=s.getTargetMailbox(r.value,e,t,o);if(!l)return!1;u.forEach(f=>{f.resolve?f.raw=f.resolve():f.literal8&&(f.raw=s.server.appendLiteral8(f.raw))});let c=u;return s.checkAppend(l,c,e,t,o,{command:i.command,replaced:i.replaced})?{mailbox:l,messages:c}:!1}catch(u){let l=u;if(!l.imapResponse)throw l;return ef(s,e,t,l,o),!1}}function ln(s,e){let t=e.messages.map(r=>s.server.appendMessage(e.mailbox,r.flags,r.internaldate,r.raw).message);return{mailbox:e.mailbox,message:t[t.length-1],messages:t}}function cn(s,e,t,r){let n=[].concat(e.attributes||[]),i=un(s,e,t,n.shift(),n,{command:"APPEND"});if(!i)return r();let o=ln(s,i);s.send({tag:e.tag,command:"OK",attributes:[{type:"TEXT",value:"APPEND Completed"}]},"APPEND",e,t,o),r()}E();E();function Ss(s){let e=s>>>0;return()=>{e=e+1831565813>>>0;let t=e;return t=Math.imul(t^t>>>15,t|1),t^=t+Math.imul(t^t>>>7,t|61),((t^t>>>14)>>>0)/4294967296}}E();var Ge=2n**63n-1n;function Ae(s,e){let t=String(e===void 0?4294967295:e);return typeof s!="string"||!/^\d+$/.test(s)||s.replace(/^0+(?=\d)/,"").length>t.length?!1:BigInt(s)<=BigInt(t)}function Le(s,e){return Ae(s,e)&&/^[1-9]/.test(s)}function Is(s,e){return typeof s!="string"||!/^[\d*]+(:[\d*]+)?(,[\d*]+(:[\d*]+)?)*$/.test(s)?!1:s.split(/[,:]/).every(t=>t==="*"?!e:Le(t))}var Os=3600*1e3,z=class extends Error{constructor(e,t){super(e),this.name="ImapKitError",this.code=t}};function K(s,e){return new z(s,e)}function it(s,e,t,r={}){let n;if(Array.isArray(t)){let c=new Set(t);n=f=>c.has(f)}else n=t;let i=[],o=[];if(e.messages.forEach((c,f)=>{n(c)?(c.ghost=!0,i.push({seq:r.highestFirst?f+1:o.length+1,message:c})):o.push(c)}),!i.length)return[];let a=e.messages.slice();o.forEach((c,f)=>{e.messages[f]=c}),e.messages.length=o.length;let u=i.map(c=>c.message),l=r.origin!==void 0?r.origin:s.activeConnection;return s.emit("expunge",e,u,l),(r.highestFirst?i.slice().reverse():i).forEach(c=>{s.notify({tag:"*",attributes:[c.seq,{type:"ATOM",value:"EXPUNGE"}],message:c.message},e,r.skip)}),s.notify({tag:"*",attributes:[e.messages.length,{type:"ATOM",value:"EXISTS"}],mailboxCopy:a},e,r.skip||r.skipExists),u}function fn(s,e,t,r){t.length&&s.notify({tag:"*",flagUpdate:t},e,r)}function hn(s,e,t,r){if(!Array.isArray(t))throw K("Flags must be an array","INVALID");let n=[];return t.forEach(i=>{if(typeof i!="string")throw K("Flags must be strings","INVALID");let o=be(i);try{we(s,o)}catch(a){throw K(a.message,"INVALID")}if(r&&!s.isPermanentFlag(e,o))throw K("Flag "+o+" is not a permanent flag of "+e.path,"INVALID");n.indexOf(o)<0&&n.push(o)}),n}function Ma(s,e,t,r,n){if(["set","add","remove"].indexOf(n)<0)throw K("Invalid flag mode "+JSON.stringify(n)+", expected set, add or remove","INVALID");let i=hn(s,e,r,n!=="remove"),o=[];return t.forEach(a=>{let u=a.flags.join(" ");n==="set"?a.flags=i.slice():n==="add"?i.forEach(l=>s.ensureFlag(a.flags,l)):i.forEach(l=>s.removeFlag(a.flags,l)),s.rememberFlags(e,a.flags),a.flags.join(" ")!==u&&o.push(a)}),o.length&&(s.emit("flags",e,o,s.activeConnection),fn(s,e,o,null)),o}function xs(s,e){let t=new Set(Object.keys(s.folderCache)),r=s.createMailbox(e),n=Object.keys(s.folderCache).filter(i=>!t.has(i)).sort((i,o)=>i.length-o.length);return s.mailboxChanged("create",r.path,{created:n}),r}function Cs(s,e){let t=s.getMailbox(e);if(!t)throw K("Mailbox does not exist","NONEXISTENT");s.deleteMailbox(e),s.mailboxChanged("delete",t.path,{mailbox:t}),Ra(s,t,"Selected mailbox was deleted","MAILBOX DELETED")}function Ra(s,e,t,r){let n=s.activeConnection;s.connections.forEach(i=>{i!==n&&i.selectedMailbox===e&&i.bye(t,r)})}function ws(s,e,t){let r=s.getMailbox(e),n=s.getMailbox(t);if(!r||r.flags.indexOf("\\Noselect")>=0)throw K("Mailbox does not exist","NONEXISTENT");if(n&&n.flags.indexOf("\\Noselect")<0)throw K("Mailbox already exists","ALREADYEXISTS");let i=s.getSeparator(r);if(t.substr(0,r.path.length+i.length)===r.path+i)throw K("Can not move a mailbox into itself","CANNOT");let o=r.path,a;if(e.toUpperCase()==="INBOX"){let u=s.createMailbox(t);a=u.path,r.messages.forEach(l=>{s.copyMessage(u,l)}),it(s,r,()=>!0)}else{s.deleteMailbox(e,!0);try{s.createMailbox(t,r)}catch(u){throw s.createMailbox(e,r),s.indexFolders(),u}s.indexFolders(),a=r.path}return s.mailboxChanged("rename",a,{oldPath:o}),{path:a,mailbox:r}}function La(s,e,t={}){let r=t.uids||"keep";if(["keep","renumber","shuffle","offset"].indexOf(r)<0)throw K("Invalid UID mode "+JSON.stringify(r)+", expected keep, renumber, shuffle or offset","INVALID");let n=t.offset===void 0?0:t.offset;if(!Number.isSafeInteger(n)||n<0)throw K("Offset must be a non-negative integer","INVALID");let i=t.uidvalidity;if(i===void 0)i=Math.max(e.uidvalidity,s.uidvalidityCounter)+1;else if(!Number.isSafeInteger(i)||i<=e.uidvalidity||i>4294967295)throw K("UIDVALIDITY must be an integer above "+e.uidvalidity+" and below 2^32","INVALID");if(t.seed!==void 0&&!Number.isSafeInteger(t.seed))throw K("Seed must be an integer","INVALID");Ra(s,e,"UIDVALIDITY of the selected mailbox changed","UIDVALIDITY CHANGED");let o=e.messages,a=o.map(l=>l.uid),u=a;if(r==="renumber"||r==="shuffle"){if(u=o.map((l,c)=>c+1),r==="shuffle"){let l=Ss(t.seed===void 0?Math.floor(Math.random()*4294967295):t.seed);for(let c=u.length-1;c>0;c--){let f=Math.floor(l()*(c+1));[u[c],u[f]]=[u[f],u[c]]}}e.uidnext=o.length+1}else if(r==="offset"){let l=e.uidnext-1+n;u=a.map(c=>c+l),e.uidnext+=l}return o.forEach((l,c)=>{l.uid=u[c]}),r==="shuffle"&&o.sort((l,c)=>l.uid-c.uid),e.uidvalidity=i,s.uidvalidityCounter=Math.max(s.uidvalidityCounter,i),{uidvalidity:i,uidnext:e.uidnext,uids:a.map((l,c)=>({uid:l,newUid:u[c]}))}}function Ht(s,e){let t=s.getMailbox(e);if(!t||t.flags.indexOf("\\Noselect")>=0)throw K("Mailbox does not exist","NONEXISTENT");return t.subscribed?!1:(t.subscribed=!0,s.mailboxChanged("subscribe",t.path),!0)}function Ns(s,e){return e.toUpperCase()==="INBOX"&&(e="INBOX"),s.subscriptions.delete(e)?(s.mailboxChanged("unsubscribe",e),!0):!1}var mn="lrswipkxtea",Pt=new Set(mn),Ft={c:"kx",d:"et"},tf=["i","e","s","w","t"],Da=["s","w","t"],sf=["l","r","i","k","x","a"],Ua=["FLAGS","+FLAGS","-FLAGS","FLAGS.SILENT","+FLAGS.SILENT","-FLAGS.SILENT"];function rf(s){return s=b.Buffer.from(s,"utf-8").toString("binary"),s&&s.charAt(0)!=="\\"&&!/^NIL$/i.test(s)?{type:"ATOM",value:s}:s}function va(s){let e=new Error(s);return e.imapResponse="BAD",e}function dn(s){let e=new Set;for(let t of s)if(Pt.has(t))e.add(t);else if(Object.hasOwn(Ft,t))Ft[t].split("").forEach(r=>e.add(r));else throw/^[A-Z]$/.test(t)?va("Uppercase rights are not allowed"):va("The "+(/^[\x21-\x7e]$/.test(t)?t+" ":"")+"right is not supported");return e}function pn(s,e){return[{type:"MAILBOX",value:s.path}].concat(e.map(t=>rf(t)))}function kt(s){let e=mn.split("").filter(t=>s.has(t)).join("");return Object.keys(Ft).forEach(t=>{Ft[t].split("").some(r=>s.has(r))&&(e+=t)}),e}function nf(s){if(!s||s==="-")return"Empty identifier";if(/[\x00-\x1f\x7f]/.test(s))return"Identifier contains control characters";let e=b.Buffer.from(s,"binary").toString("utf-8");return b.Buffer.from(e,"utf-8").toString("binary")!==s?"Identifier is not valid UTF-8":!1}function gn(s){s.registerCapability("ACL"),s.registerCapability("RIGHTS=texk");let e=typeof s.options.aclOwner=="string"?s.options.aclOwner:"testuser",t=I=>I.username===e,r=I=>{if(!(I.acl instanceof Map)){let S=new Map,O=I.acl&&typeof I.acl=="object"?I.acl:{};Object.keys(O).forEach(M=>{try{S.set(M,dn(String(O[M])))}catch(k){throw new Error("Invalid ACL in storage for "+I.path+": "+k.message,{cause:k})}}),I.acl=S}return I.acl},n=(I,S,O)=>{let M=I.username;if(M===e)return Pt;O=O||r(S);let k=["anyone"].concat(typeof M=="string"&&M?M:[]),P=new Set;return k.forEach(j=>(O.get(j)||[]).forEach(Y=>P.add(Y))),k.forEach(j=>(O.get("-"+j)||[]).forEach(Y=>P.delete(Y))),P};s.acl={getRights:n,isOwner:t};let i=(I,S)=>{let O=r(I),M=new Map(O);S(O),s.emit("acl",I,M)},o=(I,S,O,M)=>{i(I,k=>{let P=new Set(k.get(S)||[]);O==="+"?M.forEach(Y=>P.add(Y)):O==="-"&&M.forEach(Y=>P.delete(Y));let j=O?P:M;j.size?k.set(S,j):k.delete(S)})};s.urlAccessChecks.push((I,S)=>{let O=n(I,S);return O.has("r")?!1:{text:O.has("l")?"Permission denied":"Mailbox does not exist"}}),s.searchAccessChecks.push((I,S,O)=>{let M=n(I,S);return M.has("r")&&(O||M.has("l"))});let a=I=>I.aclRights||Pt,u=I=>(I=be(I),I==="\\Deleted"?"t":I==="\\Seen"?"s":"w"),l=I=>typeof I=="string"?I:String(I&&I.value||""),c=(I,S)=>I.has(u(l(S))),f=(I,S)=>{let O=(I.attributes||[])[S];return ue(O)?O.value:!1},p=(I,S)=>{let O=f(I,S);return O!==!1&&s.getMailbox(O)||!1},y=(I,S,O,M)=>I.sendStatus(S,O,"NO","Permission denied","NOPERM",M),A=(I,S,O,M,k,P)=>{M.has("l")?y(I,S,O,k):P==="TRYCREATE"?I.sendStatus(S,O,"NO","Target mailbox does not exist","TRYCREATE",k):I.sendStatus(S,O,"NO","Mailbox does not exist","NONEXISTENT",k)},m=I=>{for(let S=s.getParentPath(I);S;S=s.getParentPath(S)){let O=s.getMailbox(S);if(O)return O}return!1},h=(I,S,O,M,k)=>{if(!M)return I.sendStatus(S,O,"NO","Mailbox does not exist","NONEXISTENT"),!1;let P=n(I,M);return k(P)?!0:(A(I,S,O,P),!1)},d=I=>I.has("a"),g=(I,S,O,M)=>{let k=S.attributes||[],P=S.command.toUpperCase();if(k.length!==M||k.some(Y=>!ue(Y)))return I.sendStatus(S,O,"BAD",P+" expects "+(M===1?"a mailbox name":M+" string arguments")),!1;let j=M>1&&nf(k[1].value);return j?(I.sendStatus(S,O,"BAD",j),!1):(M>1&&(k[1].value=b.Buffer.from(k[1].value,"binary").toString("utf-8")),!0)},T=(I,S,O)=>{let M=S.attributes[1].value;return M!==e&&M!=="-"+e?!1:(I.sendStatus(S,O,"NO","Rights of the mailbox owner can not be changed","CANNOT"),!0)},C=(I,S)=>(O,M,k,P)=>{g(O,M,k,I)&&S(O,M,k,s.getMailbox(M.attributes[0].value)),P()},H={states:Z.AUTHENTICATED,mailboxArguments:[0]},N=Object.assign({astringArguments:[1]},H),w=(I,S,O,M)=>I.send({tag:"*",command:"MYRIGHTS",attributes:pn(S,[kt(n(I,S))])},"MYRIGHTS",O,M,S),G=Ke(s);s.registerCapability("LIST-MYRIGHTS",()=>G.enabled),G.returnOptions.MYRIGHTS={onItem:(I,S,O,M,k,P)=>{M.matched&&M.exists&&w(I,S,k,P)}},s.setCommandHandler("SETACL",C(3,(I,S,O,M)=>{let k=S.attributes[1].value,P=S.attributes[2].value,j=/^[+-]/.test(P)?P.charAt(0):"",Y=dn(P.substr(j.length));!h(I,S,O,M,d)||T(I,S,O)||(o(M,k,j,Y),I.sendStatus(S,O,"OK","Setacl complete"))}),Object.assign({astringArguments:[1,2]},H)),s.setCommandHandler("DELETEACL",C(2,(I,S,O,M)=>{!h(I,S,O,M,d)||T(I,S,O)||(i(M,k=>k.delete(S.attributes[1].value)),I.sendStatus(S,O,"OK","Deleteacl complete"))}),N),s.setCommandHandler("GETACL",C(1,(I,S,O,M)=>{if(!h(I,S,O,M,d))return;let k=[e,kt(Pt)];r(M).forEach((P,j)=>{k.push(j,kt(P))}),I.send({tag:"*",command:"ACL",attributes:pn(M,k)},"ACL",S,O,M),I.sendStatus(S,O,"OK","Getacl complete")}),H),s.setCommandHandler("LISTRIGHTS",C(2,(I,S,O,M)=>{if(!h(I,S,O,M,d))return;let k=S.attributes[1].value,P;k===e?P=[k,kt(Pt)]:P=[k,""].concat(mn.split(""),Object.keys(Ft)),I.send({tag:"*",command:"LISTRIGHTS",attributes:pn(M,P)},"LISTRIGHTS",S,O,M),I.sendStatus(S,O,"OK","Listrights complete")}),N),s.setCommandHandler("MYRIGHTS",C(1,(I,S,O,M)=>{h(I,S,O,M,k=>sf.some(P=>k.has(P)))&&(w(I,M,S,O),I.sendStatus(S,O,"OK","Myrights complete"))}),H);let F={},W={},x=()=>{Object.keys(F).forEach(I=>{let S=s.getCommandHandler(I);S&&(W[I]=S,s.setCommandHandler(I,(O,M,k,P)=>t(O)?S(O,M,k,P):F[I](S,O,M,k,P)))}),Object.keys(G.returnOptions).forEach(I=>{let S=G.returnOptions[I];if(typeof S.onItem!="function")return;let O=S.onItem,M=I==="STATUS"?"r":"l";S.onItem=(k,P,...j)=>{if(t(k))return O(k,P,...j);let Y=n(k,P);if(Y.has("l")&&Y.has(M))return O(k,P,...j)}}),Ua.forEach(I=>{let S=s.storeHandlers[I]||Ts[I];s.storeHandlers[I]=(O,M,k,...P)=>{let j=a(O);if(Da.every($=>j.has($)))return S(O,M,k,...P);k=[].concat(k),k.forEach($=>we(O.server,be(l($))));let Y=k.filter($=>c(j,$));return I.charAt(0)!=="+"&&I.charAt(0)!=="-"&&(Y=M.flags.filter($=>!c(j,$)).concat(Y)),S(O,M,Y,...P)}})};s.once("pluginsLoaded",x);let L=(I,S,O,M,k)=>{let P=p(O,0);if(!P)return I(S,O,M,k);let j=O.command.toUpperCase(),Y=n(S,P);return Y.has("r")?(S.aclRights=Y,j==="SELECT"&&!tf.some($=>Y.has($))?W.EXAMINE(S,O,M,k):I(S,O,M,k)):(on(S,O,M),S.closeMailbox(),A(S,O,M,Y,j+" FAILED"),k())};F.SELECT=L,F.EXAMINE=L;let v=(I,S,O)=>(M,k,P)=>{let j=p(k,S),Y=j&&n(M,j);return Y&&!Y.has(I)?(A(M,k,P,Y,void 0,O),!1):!0},V=(I,S,O)=>{let M=v(I,S,O);return(k,P,j,Y,$)=>M(P,j,Y)?k(P,j,Y,$):$()};F.STATUS=V("r",0),F.SUBSCRIBE=V("l",0),F.DELETE=V("x",0);let _=(I,S,O,M)=>{let k=m(M);return!k||!n(I,k).has("k")?(y(I,S,O),!1):!0};F.CREATE=(I,S,O,M,k)=>{let P=f(O,0);return P!==!1&&!_(S,O,M,P)?k():I(S,O,M,k)};let X=v("x",0);F.RENAME=(I,S,O,M,k)=>{if(!X(S,O,M))return k();let P=f(O,1);return P!==!1&&p(O,0)&&!_(S,O,M,P)?k():I(S,O,M,k)},F.APPEND=(I,S,O,M,k)=>{let P=p(O,0);if(!P)return I(S,O,M,k);let j=n(S,P);if(!j.has("i"))return A(S,O,M,j,"APPEND FAILED","TRYCREATE"),k();let Y=O.attributes[1];if(Array.isArray(Y)&&Y.every($=>$&&$.type==="ATOM"))try{Y.forEach($=>we(S.server,be($.value))),O.attributes[1]=Y.filter($=>c(j,$))}catch{}return I(S,O,M,k)};let q=(I,S)=>{let O=S?n(I,S):!1;return!O||O.has("i")?!1:O.has("l")?{command:"NO",code:"NOPERM",text:"Permission denied"}:{command:"NO",code:"TRYCREATE",text:"Target mailbox does not exist"}},se=V("i",1,"TRYCREATE"),ee=I=>(S,O,M,k,P)=>{let j=M.command.toUpperCase();if(I&&!O.readOnly){let Y=a(O);if(!Y.has("t")||!Y.has("e"))return y(O,M,k,j+" FAIL"),P()}return se(S,O,M,k,P)};F.COPY=ee(!1),F["UID COPY"]=ee(!1),F.MOVE=ee(!0),F["UID MOVE"]=ee(!0);let fe=(I,S)=>{let O=a(I);return!I.readOnly&&(!O.has("t")||!O.has("e"))?{command:"NO",code:"NOPERM",text:"Permission denied"}:q(I,S)},is=(I,S,O,M,k)=>{let P=fe(S,p(O,1));return P?(S.sendStatus(O,M,P.command,P.text,P.code,O.command.toUpperCase()+" FAILED"),k()):I(S,O,M,k)};F.REPLACE=is,F["UID REPLACE"]=is,s.literalFilters.unshift((I,S,O)=>{if(t(I)||I.isBusy())return!1;let M=Bt(I,S,O),k=M!==!1&&s.getMailbox(M);return k?S==="APPEND"?q(I,k):fe(I,k):!1});let Nr=["r","s","w","i","p"],Lt=I=>I.has("l")&&Nr.some(S=>I.has(S)),ko=(I,S,O,M,k)=>{let P=O.attributes||[],j=O.command.toUpperCase()==="GETMETADATA"&&Array.isArray(P[0])?1:0,Y=p(O,j);if(Y&&f(O,j)!==""){let $=n(S,Y);if(!Lt($))return A(S,O,M,$),k()}return I(S,O,M,k)};F.GETMETADATA=ko,F.SETMETADATA=ko,s.notifyFilters.push((I,S)=>{let O=S.command||{};if(O.command!=="METADATA"||t(I))return!0;let M=O.attributes&&O.attributes[0],k=M&&typeof M=="object"?M.value:M,P=typeof k=="string"&&k!==""&&s.getMailbox(k);return!P||Lt(n(I,P))}),F.GETQUOTAROOT=(I,S,O,M,k)=>{let P=p(O,0);return(!P||!n(S,P).has("r"))&&(O.aclQuotaMailboxOnly=!0),I(S,O,M,k)},F.SETQUOTA=(I,S,O,M,k)=>{let P=O.attributes||[];return P.length===2&&Array.isArray(P[1])&&!Object.keys(s.folderCache).every(Y=>{let $=s.folderCache[Y];return!s.isPersonal($)||n(S,$).has("a")})?(y(S,O,M),k()):I(S,O,M,k)};let Po=(I,S,O,M,k)=>!S.readOnly&&!a(S).has("e")?(y(S,O,M),k()):I(S,O,M,k);F.EXPUNGE=Po,F["UID EXPUNGE"]=Po,s.resetHandlers.push(I=>{I.aclRights=null}),s.connectionHandlers.push(I=>{let S=I.canSetSeen,O=I.canExpunge;I.canSetSeen=()=>S.call(I)&&a(I).has("s"),I.canExpunge=()=>O.call(I)&&a(I).has("e")});let Fo=(I,S,O,M,k)=>{let P=a(S),j=O.attributes||[],Y=j.length>=3&&j[j.length-2]&&j[j.length-2].type==="ATOM"&&j[j.length-2].value.toUpperCase();if(S.readOnly||!Y)return I(S,O,M,k);if(Ua.indexOf(Y)<0)return Object.hasOwn(s.storeHandlers,Y)&&!P.has("w")?(y(S,O,M),k()):I(S,O,M,k);let $=[].concat(j[j.length-1]||[]);try{$.forEach(Dt=>we(S.server,be(l(Dt))))}catch{return I(S,O,M,k)}let Me;return Y.charAt(0)==="+"||Y.charAt(0)==="-"?Me=!$.length||$.some(Dt=>c(P,Dt)):Me=Da.some(Dt=>P.has(Dt)),Me?I(S,O,M,k):(y(S,O,M),k())};F.STORE=Fo,F["UID STORE"]=Fo;let Pl=I=>{let S=I&&I.attributes||[];return S.some((O,M)=>O&&O.type==="ATOM"&&/^RETURN$/i.test(O.value)&&Array.isArray(S[M+1])&&S[M+1].some(k=>k&&k.type==="ATOM"&&/^STATUS$/i.test(k.value)))},Fl=(I,S)=>s.hasDescendant(S.path,O=>n(I,O).has("l"));s.outputHandlers.push((I,S,O,M,k,P)=>{if(!t(I)){if((O==="LIST ITEM"||O==="LSUB ITEM")&&P&&P.path){if(!n(I,P).has("l")){S.skipResponse=!0;return}let j=S.attributes[0];if(!Array.isArray(j))return;S.attributes[0]=j.slice();let Y=j.findIndex(Me=>Me&&Me.value==="\\HasChildren");Y>=0&&!Fl(I,P)&&(S.attributes[0][Y]={type:"ATOM",value:"\\HasNoChildren"}),!j.some(Me=>Me&&/^\\(Noselect|NonExistent)$/i.test(Me.value))&&Pl(M)&&!n(I,P).has("r")&&S.attributes[0].push({type:"ATOM",value:"\\Noselect"});return}if(O==="QUOTA"&&M&&M.aclQuotaMailboxOnly&&Array.isArray(S.attributes[1])){let j=S.attributes[1],Y=[];for(let $=0;$<j.length;$+=3)j[$]&&String(j[$].value).toUpperCase()==="MAILBOX"&&Y.push(j[$],j[$+1],j[$+2]);Y.length?S.attributes[1]=Y:S.skipResponse=!0;return}if(O==="SELECT PERMANENTFLAGS"){let j=S.attributes[0]&&S.attributes[0].section,Y=a(I);j&&Array.isArray(j[1])&&(j[1]=j[1].filter($=>$.value==="\\*"?Y.has("w"):c(Y,$)));return}if(P&&P.targetUids&&P.mailbox&&/^(UID )?(COPY|MOVE COPYUID)$/.test(O)){let j=n(I,P.mailbox),Y=new Set(P.targetUids);P.mailbox.messages.forEach($=>{Y.has($.uid)&&($.flags=$.flags.filter(Me=>c(j,Me)))})}}}),s.on("mailbox",I=>{if(I.type==="delete"){let S=s.getMailbox(I.path);S&&S!==I.mailbox&&delete S.acl}else I.type==="create"&&(I.created||[]).forEach(S=>{let O=m(S),M=s.folderCache[S];if(O&&M&&O!==M){let k=new Map;r(O).forEach((P,j)=>k.set(j,new Set(P))),M.acl=k}})});let os=I=>{let S={};return r(I).forEach((O,M)=>{S[M]=kt(O)}),S},Mr=I=>s.control.requireMailbox(I);s.control.snapshotHandlers.push((I,S)=>{I.acl instanceof Map&&(S.acl=os(I))});let _l=I=>os(Mr(I)),Gl=(I,S,O)=>{let M=Mr(I);if(typeof S!="string"||!S||typeof O!="string")throw K("setAcl expects an identifier and a rights string","INVALID");let k=/^[+-]/.test(O)?O.charAt(0):"",P;try{P=dn(O.substr(k.length))}catch(j){throw K(j.message,"INVALID")}return o(M,S,k,P),os(M)},Xl=(I,S)=>{let O=Mr(I);if(typeof S!="string"||!r(O).has(S))throw K("No ACL entry for "+JSON.stringify(S),"NONEXISTENT");return i(O,M=>M.delete(S)),os(O)};s.control.register("getAcl",_l,[{method:"GET",path:"/v1/mailboxes/{path}/acl",summary:"The ACL of a mailbox (ACL plugin)",handler:({params:I})=>s.control.getAcl(I.path)}]),s.control.register("setAcl",Gl,[{method:"PUT",path:"/v1/mailboxes/{path}/acl/{identifier}",summary:'Sets the rights of an identifier ({ rights }, "+" or "-" in front adds or removes, ACL plugin)',handler:({params:I,body:S})=>s.control.setAcl(I.path,I.identifier,S.rights)}]),s.control.register("deleteAcl",Xl,[{method:"DELETE",path:"/v1/mailboxes/{path}/acl/{identifier}",summary:"Removes an identifier from the ACL (ACL plugin)",handler:({params:I})=>s.control.deleteAcl(I.path,I.identifier)}])}E();function En(s){let e="appendLimit"in s.options?s.options.appendLimit:null;if(e!==null&&!Ba(e))throw new TypeError("Invalid appendLimit option, expecting a non-negative integer");let t=o=>Object.hasOwn(o,"appendLimit"),r=()=>Object.values(s.folderCache).some(t),n=o=>t(o)?Ba(o.appendLimit)?o.appendLimit:null:e,i=(o,a)=>{let u=n(o);return u!==null&&(a>u||u===0)};e!==null&&s.registerCapability("APPENDLIMIT="+e,()=>!r()),s.registerCapability("APPENDLIMIT",()=>e===null||r()),s.appendChecks.push((o,a,u,l)=>l.command&&u.some(c=>i(a,c.raw.length))?{code:"TOOBIG",text:"Message exceeds the APPENDLIMIT of the mailbox"}:!1),s.literalFilters.push((o,a,u,l)=>{let c=Bt(o,a,u),f=c!==!1&&s.getMailbox(c);return f&&i(f,l)?{command:"NO",code:"TOOBIG",text:"Message exceeds the APPENDLIMIT of the mailbox"}:!1}),s.allowedStatus.push("APPENDLIMIT"),s.statusHandlers.APPENDLIMIT=(o,a)=>n(a)}function Ba(s){return Number.isSafeInteger(s)&&s>=0}E();var of=new TextDecoder("utf-8",{fatal:!0});function An(s){s.registerCapability("AUTH=PLAIN",t=>t.state==="Not Authenticated");let e=(t,r,n,i)=>{let o=t.decodeSaslResponse(i);if(!o)return t.sendStatus(r,n,"BAD","Invalid base64 in SASL response",!1,"AUTHENTICATE PLAIN FAILED");let a;try{a=of.decode(o)}catch{return t.sendStatus(r,n,"BAD","Invalid UTF-8 in SASL PLAIN message",!1,"AUTHENTICATE PLAIN FAILED")}let u=a.split("\0"),l=u[0]||"",c=u[1]||"",f=u[2]||"",p=t.server.getUser(c);if(u.length!==3||!p||p.password!==f)return t.sendStatus(r,n,"NO","Login failed: authentication failure","AUTHENTICATIONFAILED","AUTHENTICATE PLAIN FAILED");if(l&&l!==c)return t.sendStatus(r,n,"NO","Can not act as "+l,"AUTHORIZATIONFAILED","AUTHENTICATE PLAIN FAILED");t.state="Authenticated",t.username=c,t.sendStatus(r,n,"OK","User logged in",!1,"AUTHENTICATE PLAIN SUCCESS")};s.setCommandHandler("AUTHENTICATE PLAIN",(t,r,n,i)=>{if(!r.attributes)t.inputHandler=function(o){if(t.inputHandler=!1,o==="*")return t.sendStatus(r,n,"BAD","Authentication cancelled",!1,"AUTHENTICATE PLAIN FAILED");e(t,r,n,o)},t.sendContinuation("","AUTHENTICATE PLAIN");else if(r.attributes.length===1&&r.attributes[0].type==="ATOM"){if(!s.capabilities["SASL-IR"]||!s.capabilities["SASL-IR"](t))return t.sendStatus(r,n,"BAD","SASL-IR must be enabled to send Initial Response with the request",!1,"AUTHENTICATE PLAIN FAILED"),i();e(t,r,n,r.attributes[0].value)}else t.sendStatus(r,n,"BAD","Invalid attributes for AUTHENTICATE PLAIN",!1,"AUTHENTICATE PLAIN FAILED");return i()})}E();E();E();function Rs(s,e){let r=new Ms(s).tokenize(),n=[],i=[],o=[];return r.forEach(a=>{a.type==="operator"&&(a.value===","||a.value===";")?(i.length&&n.push(i),i=[]):i.push(a)}),i.length&&n.push(i),n.forEach(a=>{let u=af(a,e);u.length&&(o=o.concat(u))}),o}function af(s,e){let t,r=!1,n="text",i=[],o={address:[],comment:[],group:[],text:[]},a,u;for(a=0,u=s.length;a<u;a++)if(t=s[a],t.type==="operator")switch(t.value){case"<":n="address";break;case"(":n="comment";break;case":":if(e){n="text";break}n="group",r=!0;break;default:n="text"}else t.value&&o[n].push(t.value);if(!o.text.length&&o.comment.length&&(o.text=o.comment,o.comment=[]),r){let l=o.text.join(" ");i.push({name:l,group:o.group.length?Rs(o.group.join(","),!0):[]})}else{if(!o.address.length&&o.text.length){for(a=o.text.length-1;a>=0;a--)if(o.text[a].match(/^[^@\s]+@[^@\s]+$/)){o.address=o.text.splice(a,1);break}let p=function(y){return o.address.length?y:(o.address=[y.trim()]," ")};if(!o.address.length)for(a=o.text.length-1;a>=0&&(o.text[a]=o.text[a].replace(/\s*\b[^@\s]+@[^@\s]+\b\s*/,p).trim(),!o.address.length);a--);}!o.text.length&&o.comment.length&&(o.text=o.comment,o.comment=[]),o.address.length>1&&(o.text=o.text.concat(o.address.splice(1)));let l=o.text.join(" "),c=o.address.join(" "),f={address:c||l||"",name:l||c||""};f.address===f.name&&((f.address||"").match(/@/)?f.name="":f.address=""),i.push(f)}return i}var Ms=class{constructor(e){this.str=(e||"").toString(),this.operatorCurrent="",this.operatorExpecting="",this.node=null,this.escaped=!1,this.list=[]}tokenize(){let e,t=[];for(let r=0,n=this.str.length;r<n;r++)e=this.str.charAt(r),this.checkChar(e);return this.list.forEach(r=>{r.value=(r.value||"").toString().trim(),r.value&&t.push(r)}),t}checkChar(e){if((e in this.operators||e==="\\")&&this.escaped)this.escaped=!1;else if(this.operatorExpecting&&e===this.operatorExpecting){this.node={type:"operator",value:e},this.list.push(this.node),this.node=null,this.operatorExpecting="",this.escaped=!1;return}else if(!this.operatorExpecting&&e in this.operators){this.node={type:"operator",value:e},this.list.push(this.node),this.node=null,this.operatorExpecting=this.operators[e],this.escaped=!1;return}if(!this.escaped&&e==="\\"){this.escaped=!0;return}this.node||(this.node={type:"text",value:""},this.list.push(this.node)),this.escaped&&e!=="\\"&&(this.node.value+="\\"),this.node.value+=e,this.escaped=!1}};Ms.prototype.operators={'"':'"',"(":")","<":">",",":"",":":";"};var Ha=/^[a-zA-Z0-9\-*]{1,99}$/,Ls=["7bit","8bit","binary"],uf=32;function _t(s){let e=b.Buffer.isBuffer(s)?s.toString("binary"):s||"";return/(?:^|[^\r])\n/.test(e)?e.replace(/\r?\n/g,`\r
6
6
  `):e}function ka(s,e){let t=[],r="",n=!1,i=0;for(let o=0;o<s.length;o++){let a=s.charAt(o);if(n){r+=a,a==="\\"&&o+1<s.length?r+=s.charAt(++o):a==='"'&&(n=!1);continue}if(i){a==="\\"?o++:a==="("?i++:a===")"&&i--;continue}a==='"'?(n=!0,r+=a):a==="("?i=1:e&&a===e?(t.push(r),r=""):r+=a}return t.push(r),t}function Pa(s,e){let t=e.replace(/%([0-9a-fA-F]{2})/g,(r,n)=>String.fromCharCode(parseInt(n,16)));switch((s||"").trim().toLowerCase()){case"":case"utf-8":case"utf8":case"us-ascii":case"ascii":return t;case"iso-8859-1":case"latin1":return b.Buffer.from(t,"utf-8").toString("binary");default:return"=?"+s.toUpperCase()+"?Q?"+e.replace(/%/g,"=")+"?="}}var yn=class{constructor(e,t){this.rfc822=e||"",this.depth=t||0,this._br="",this._pos=0,this.tree={childNodes:[]},this._node=this.createNode(this.tree)}parse(){let e,t="";for(;typeof this._br=="string";){e=this.readLine();let r=this.matchDelimiter(e);if(r)this.endPart(r,t);else switch(this._node.state){case"header":e?this._node.header.push(e):this.endHeader();break;case"body":this._node.body.push((this._node.body.length?t:"")+e);break;case"epilogue":this._node.epilogue||(this._node.epilogue=[]),this._node.epilogue.push(t+e);break;default:throw new Error("Unexpected state")}t=this._br}}readLine(){let e=this.rfc822.indexOf(`
7
7
  `,this._pos);if(e<0){let n=this.rfc822.slice(this._pos);return this._pos=this.rfc822.length,this._br=!1,n}let t=e;t>this._pos&&this.rfc822.charCodeAt(t-1)===13&&t--;let r=this.rfc822.slice(this._pos,t);return this._br=this.rfc822.slice(t,e+1),this._pos=e+1,r}endHeader(){this.processNodeHeader(),this.processContentType(),this._node.state="body"}matchDelimiter(e){if(!e.startsWith("--"))return!1;let t=this._node,r=t.boundary?t:t.parentNode;for(let n=r;n.boundary;n=n.parentNode){let i="--"+n.boundary;if(!e.startsWith(i))continue;let o=e.slice(i.length),a=o.startsWith("--");if(a&&(o=o.slice(2)),!/[^ \t]/.test(o))return n.state==="epilogue"?!1:{multipart:n,close:a,pad:o}}return!1}endPart(e,t){let r=this._node,n=e.multipart;if(r!==n){if(r.state==="header"){this.endHeader();for(let i=r;i!==n;i=i.parentNode)i.bare=!0}}else r.body.length&&(r.body[r.body.length-1]+=t);if(e.close)e.pad&&(n.closePad=e.pad),delete n.unterminated,n.state="epilogue",this._node=n;else{let i=this.createNode(n);e.pad&&(i.pad=e.pad),this._node=i}}parseEmbeddedMessage(e){let t=e.parsedHeader["content-type"],r=(t&&t.value||"").toLowerCase();if(r!=="message/rfc822"&&r!=="message/global"||this.depth>=uf)return;let n=(e.parsedHeader["content-transfer-encoding"]||"").toString().trim().toLowerCase();n&&!Ls.includes(n)||(e[r==="message/rfc822"?"message":"globalMessage"]=Gt(e.body,this.depth+1))}finalizeTree(){this._node.state==="header"&&(this.endHeader(),this._node.header.length&&!this.rfc822.endsWith(`
8
8
  `)&&(this._node.headerUnterminated=!0));let e=[...this.tree.childNodes];for(;e.length;){let t=e.pop(),r=t,n=t.body,i=r.boundary&&!r.unterminated;n.length||t.childNodes.length||i||(r.hasBody=!1),r.lineCount=n.length?n.length-1:0,r.body=n.join(""),r.size=r.body.length,this.parseEmbeddedMessage(r),t.epilogue&&(r.epilogue=t.epilogue.join("")),t.childNodes.forEach(o=>e.push(o)),delete t.parentNode,delete t.state,r.childNodes.length||delete r.childNodes}}createNode(e){let t={state:"header",childNodes:[],header:[],parsedHeader:Object.create(null),body:[],multipart:!1,boundary:!1,parentNode:e};return e.childNodes.push(t),t}processNodeHeader(){let e=this._node,t=e.parsedHeader,r=[];for(let n of e.header)r.length&&/^\s/.test(n)?r[r.length-1]+=`\r
@@ -19,29 +19,29 @@ var jl=Object.create;var Rr=Object.defineProperty;var Vl=Object.getOwnPropertyDe
19
19
  `))}if(n.hasBody===!1||(i&&t.push(`\r
20
20
  `),t.push(n.body||""),!n.boundary))return;let o=n.childNodes||[];for(let a=0;a<o.length;a++){let u=o[a];t.push("--"+n.boundary+(u.pad||"")+`\r
21
21
  `),r(u,!0),(!n.unterminated||a<o.length-1)&&!u.bare&&t.push(`\r
22
- `)}n.unterminated||(t.push("--"+n.boundary+"--"+(n.closePad||"")),t.push(n.epilogue||""))};return r(s,!e),t.join("")}var Fa=new WeakMap;function ne(s){let e=Fa.get(s);if(!e||e.source!==s.raw){let t=_t(s.raw);e={source:s.raw,raw:t,tree:Gt(t)},Fa.set(s,e)}return e}g();g();g();var cf=/^[\s,]*(@(?:[^:[]|\[[^\]]*\])*):/;function ff(s){let e=s.match(cf);return e?[e[1].split(",").map(r=>r.trim()).filter(r=>r).join(","),s.substr(e[0].length).trim()]:[null,s]}function Xt(s){let e=s.subject;return[s.date||null,typeof e=="string"?e:null,Xe(s.from),Xe(s.sender,s.from),Xe(s["reply-to"],s.from),Xe(s.to),Xe(s.cc),Xe(s.bcc),s["in-reply-to"]||null,s["message-id"]||null]}function Xe(s,e){let t=[].concat(s||[]);if(t.length||(t=[].concat(e||[])),!t.length)return null;let r=[];return t.forEach(n=>{if(n.group){r.push([null,null,n.name||"",null]),r=r.concat(Xe(n.group)||[]),r.push([null,null,null,null]);return}let i=n.name||null,o=n.address||"";if(!o&&i&&(o=i,i=null),!o)return;let[a,u]=ff(o);o=u;let l=o.lastIndexOf("@"),c=l>=0?o.substr(0,l):o,f=(l>=0?o.substr(l+1):"")||"MISSING_DOMAIN";r.push([i,a,c||null,f])}),Object.defineProperty(r,"adjacentLists",{value:!0}),r.length?r:null}var bn=hf;function hf(s,e){e=e||{};let t=l=>e.upperCaseKeys&&typeof l=="string"?l.toUpperCase():l,r=l=>{if(!l||!l.hasParams)return null;let c=[],f=l.params;return Object.keys(f).forEach(p=>{c.push(t(p),f[p])}),c.length?c:null},n=l=>{let c=l.parsedHeader["content-type"]||{},f=c.type||null,p=c.subtype||null;return(!f||!p)&&(f==="text"||p==="plain"?(f="text",p="plain"):(f="application",p="octet-stream")),[t(f),t(p),r(c),l.parsedHeader["content-id"]||null,l.parsedHeader["content-description"]||null,t(l.parsedHeader["content-transfer-encoding"]||"7bit"),l.size]},i=l=>{let c=l.parsedHeader["content-language"]&&l.parsedHeader["content-language"].replace(/[ ,]+/g,",").replace(/^,+|,+$/g,""),f=c&&c.split(",")||null,p=l.parsedHeader["content-disposition"],y=[p&&[t(p.value),r(p)]||null,f];return e.skipContentLocation||y.push(l.parsedHeader["content-location"]||null),y},o=(l,c)=>{let f=n(l).concat(c);return e.body||(f=f.concat([l.parsedHeader["content-md5"]||null],i(l))),f},a=l=>{let c=ot(l).map(u).concat([t(l.multipart)]);return e.body||(c=c.concat([r(l.parsedHeader["content-type"])],i(l))),Object.defineProperty(c,"adjacentLists",{value:!0}),c},u=l=>{switch((l.parsedHeader["content-type"]||{}).type){case"multipart":return ot(l)?a(l):o(l,[]);case"text":return o(l,[l.lineCount]);case"message":{let f=at(l,e.messageGlobal);return f?o(l,[Xt(f.parsedHeader),u(f),l.lineCount]):o(l,[])}default:return o(l,[])}};return u(s)}var pe={},Te=pe;Object.defineProperty(pe,"applyPartial",{value:Us});pe.UID=function(s,e){return e.uid};pe.FLAGS=function(s,e){return s.getFlags(e).map(t=>({type:"ATOM",value:t}))};pe.BODYSTRUCTURE=function(s,e){return bn(ne(e).tree,{upperCaseKeys:!0,skipContentLocation:!0,messageGlobal:s.messageGlobal})};pe.ENVELOPE=function(s,e){return Xt(ne(e).tree.parsedHeader)};pe["BODY.PEEK"]=function(s,e,t){if(!t.section)throw new Error("BODY.PEEK requires ans argument list");return pe.BODY(s,e,t)};function df(s,e){if(s.section.length!==2||!Array.isArray(s.section[1])||!s.section[1].length)throw new Error(e+" expects a list of header fields");return s.section[1].map(t=>{if(["ATOM","STRING","LITERAL"].indexOf(t.type)<0)throw new Error("Invalid header field name in list");return t.type="ATOM",t.value.toUpperCase()})}function pf(s,e,t){if(!e.section.length)return s.raw;if(e.section[0].type!=="ATOM")throw new Error("Invalid BODY[<section>] identifier"+(e.section[0].value?" "+e.section[0].type:""));let r=(e.section[0].value||"").toUpperCase().match(/^((?:[1-9]\d*)(?:\.[1-9]\d*)*)?(?:(?:^|\.)(HEADER|HEADER\.FIELDS|HEADER\.FIELDS\.NOT|TEXT|MIME))?$/);if(!r||r[2]==="MIME"&&!r[1])throw new Error("Invalid BODY[<section>] identifier "+e.section[0].value);let n=r[1]||"",i=r[2]||"",o=[];if(["HEADER.FIELDS","HEADER.FIELDS.NOT"].indexOf(i)>=0)o=df(e,i);else if(e.section.length>1)throw new Error((i||"Part number")+" does not take any arguments");let a=n?bt(s.tree,n,t):s.tree;if(!a)return"";let u=n?at(a,t):a;switch(i){case"":return Be(a,!0);case"MIME":return Ds(a);case"TEXT":return u?Be(u,!0):"";case"HEADER":return u?Ds(u):"";default:{if(!u)return"";let l=i==="HEADER.FIELDS",c="";return(u.header||[]).forEach(f=>{let p=f.split(":")[0].toUpperCase().trim();o.indexOf(p)>=0===l&&(c+=f+`\r
22
+ `)}n.unterminated||(t.push("--"+n.boundary+"--"+(n.closePad||"")),t.push(n.epilogue||""))};return r(s,!e),t.join("")}var Fa=new WeakMap;function ne(s){let e=Fa.get(s);if(!e||e.source!==s.raw){let t=_t(s.raw);e={source:s.raw,raw:t,tree:Gt(t)},Fa.set(s,e)}return e}E();E();E();var cf=/^[\s,]*(@(?:[^:[]|\[[^\]]*\])*):/;function ff(s){let e=s.match(cf);return e?[e[1].split(",").map(r=>r.trim()).filter(r=>r).join(","),s.substr(e[0].length).trim()]:[null,s]}function Xt(s){let e=s.subject;return[s.date||null,typeof e=="string"?e:null,Xe(s.from),Xe(s.sender,s.from),Xe(s["reply-to"],s.from),Xe(s.to),Xe(s.cc),Xe(s.bcc),s["in-reply-to"]||null,s["message-id"]||null]}function Xe(s,e){let t=[].concat(s||[]);if(t.length||(t=[].concat(e||[])),!t.length)return null;let r=[];return t.forEach(n=>{if(n.group){r.push([null,null,n.name||"",null]),r=r.concat(Xe(n.group)||[]),r.push([null,null,null,null]);return}let i=n.name||null,o=n.address||"";if(!o&&i&&(o=i,i=null),!o)return;let[a,u]=ff(o);o=u;let l=o.lastIndexOf("@"),c=l>=0?o.substr(0,l):o,f=(l>=0?o.substr(l+1):"")||"MISSING_DOMAIN";r.push([i,a,c||null,f])}),Object.defineProperty(r,"adjacentLists",{value:!0}),r.length?r:null}var bn=hf;function hf(s,e){e=e||{};let t=l=>e.upperCaseKeys&&typeof l=="string"?l.toUpperCase():l,r=l=>{if(!l||!l.hasParams)return null;let c=[],f=l.params;return Object.keys(f).forEach(p=>{c.push(t(p),f[p])}),c.length?c:null},n=l=>{let c=l.parsedHeader["content-type"]||{},f=c.type||null,p=c.subtype||null;return(!f||!p)&&(f==="text"||p==="plain"?(f="text",p="plain"):(f="application",p="octet-stream")),[t(f),t(p),r(c),l.parsedHeader["content-id"]||null,l.parsedHeader["content-description"]||null,t(l.parsedHeader["content-transfer-encoding"]||"7bit"),l.size]},i=l=>{let c=l.parsedHeader["content-language"]&&l.parsedHeader["content-language"].replace(/[ ,]+/g,",").replace(/^,+|,+$/g,""),f=c&&c.split(",")||null,p=l.parsedHeader["content-disposition"],y=[p&&[t(p.value),r(p)]||null,f];return e.skipContentLocation||y.push(l.parsedHeader["content-location"]||null),y},o=(l,c)=>{let f=n(l).concat(c);return e.body||(f=f.concat([l.parsedHeader["content-md5"]||null],i(l))),f},a=l=>{let c=ot(l).map(u).concat([t(l.multipart)]);return e.body||(c=c.concat([r(l.parsedHeader["content-type"])],i(l))),Object.defineProperty(c,"adjacentLists",{value:!0}),c},u=l=>{switch((l.parsedHeader["content-type"]||{}).type){case"multipart":return ot(l)?a(l):o(l,[]);case"text":return o(l,[l.lineCount]);case"message":{let f=at(l,e.messageGlobal);return f?o(l,[Xt(f.parsedHeader),u(f),l.lineCount]):o(l,[])}default:return o(l,[])}};return u(s)}var pe={},Te=pe;Object.defineProperty(pe,"applyPartial",{value:Us});pe.UID=function(s,e){return e.uid};pe.FLAGS=function(s,e){return s.getFlags(e).map(t=>({type:"ATOM",value:t}))};pe.BODYSTRUCTURE=function(s,e){return bn(ne(e).tree,{upperCaseKeys:!0,skipContentLocation:!0,messageGlobal:s.messageGlobal})};pe.ENVELOPE=function(s,e){return Xt(ne(e).tree.parsedHeader)};pe["BODY.PEEK"]=function(s,e,t){if(!t.section)throw new Error("BODY.PEEK requires ans argument list");return pe.BODY(s,e,t)};function df(s,e){if(s.section.length!==2||!Array.isArray(s.section[1])||!s.section[1].length)throw new Error(e+" expects a list of header fields");return s.section[1].map(t=>{if(["ATOM","STRING","LITERAL"].indexOf(t.type)<0)throw new Error("Invalid header field name in list");return t.type="ATOM",t.value.toUpperCase()})}function pf(s,e,t){if(!e.section.length)return s.raw;if(e.section[0].type!=="ATOM")throw new Error("Invalid BODY[<section>] identifier"+(e.section[0].value?" "+e.section[0].type:""));let r=(e.section[0].value||"").toUpperCase().match(/^((?:[1-9]\d*)(?:\.[1-9]\d*)*)?(?:(?:^|\.)(HEADER|HEADER\.FIELDS|HEADER\.FIELDS\.NOT|TEXT|MIME))?$/);if(!r||r[2]==="MIME"&&!r[1])throw new Error("Invalid BODY[<section>] identifier "+e.section[0].value);let n=r[1]||"",i=r[2]||"",o=[];if(["HEADER.FIELDS","HEADER.FIELDS.NOT"].indexOf(i)>=0)o=df(e,i);else if(e.section.length>1)throw new Error((i||"Part number")+" does not take any arguments");let a=n?bt(s.tree,n,t):s.tree;if(!a)return"";let u=n?at(a,t):a;switch(i){case"":return Be(a,!0);case"MIME":return Ds(a);case"TEXT":return u?Be(u,!0):"";case"HEADER":return u?Ds(u):"";default:{if(!u)return"";let l=i==="HEADER.FIELDS",c="";return(u.header||[]).forEach(f=>{let p=f.split(":")[0].toUpperCase().trim();o.indexOf(p)>=0===l&&(c+=f+`\r
23
23
  `)}),c+`\r
24
24
  `}}}function Us(s,e){if(!e)return s;if(e.length!==2||!(e[1]>0))throw new Error("Invalid partial range, expecting <start.length>");return s.substr(e[0],e[1])}pe.BODY=function(s,e,t){let r=ne(e);if(!t.section){if(t.partial)throw new Error("BODY without a section does not take a partial range");return bn(r.tree,{body:!0,upperCaseKeys:!0,messageGlobal:s.messageGlobal})}return{type:"LITERAL",value:Us(pf(r,t,s.messageGlobal),t.partial)}};pe.INTERNALDATE=function(s,e){return e.internaldate};pe.RFC822=function(s,e){return{type:"LITERAL",value:ne(e).raw}};pe.RFC822.setsSeen=!0;pe["RFC822.SIZE"]=function(s,e){return ne(e).raw.length};pe["RFC822.HEADER"]=function(s,e){return{type:"LITERAL",value:Ds(ne(e).tree)}};pe["RFC822.TEXT"]=function(s,e){return{type:"LITERAL",value:Be(ne(e).tree,!0)}};pe["RFC822.TEXT"].setsSeen=!0;var mf=/^[1-9]\d*(?:\.[1-9]\d*)*$/,Tn=new WeakMap;function _a(s){let e=new Error(s);return e.imapResponse="NO",e.code="UNKNOWN-CTE",e}function Ga(s){let e=s.parsedHeader["content-type"];return(e&&e.value||"").toLowerCase()}function Xa(s){return(s.parsedHeader["content-transfer-encoding"]||"7bit").toString().trim().toLowerCase()}function ja(s,e){let t=Ga(s);return!s.boundary&&!/^multipart\//.test(t)&&t!=="message/rfc822"&&(!e||t!=="message/global")}function gf(s){let e=s.replace(/[^A-Za-z0-9+/=]/g,"").split("=")[0];return e.length%4===1&&(e=e.slice(0,-1)),b.Buffer.from(e,"base64").toString("binary")}function Ef(s){return s.replace(/[ \t]+(?=\r\n|$)/g,"").replace(/=(?:\r\n|$)/g,"").replace(/=([0-9A-Fa-f]{2})/g,(e,t)=>String.fromCharCode(parseInt(t,16)))}function Va(s,e,t){let r=t.value.toUpperCase(),n=t.section;if(!n)throw new Error(r+" requires a section");if(!n.length)throw new Error(r+"[] is not allowed, BINARY applies to leaf body parts only (RFC 9051 section 6.4.5)");if(n.length!==1||n[0].type!=="ATOM"||!mf.test(n[0].value))throw new Error("Invalid "+r+" section, expecting a part number (RFC 3516 section 7)");let i=bt(ne(e).tree,n[0].value,s.messageGlobal);if(!i)return"";if(!ja(i,s.messageGlobal))throw new Error(r+"["+n[0].value+"] is not a leaf body part (RFC 9051 section 6.4.5)");return Tn.has(i)||Tn.set(i,Af(i)),Tn.get(i)}function Af(s){let e=Be(s,!0),t=Xa(s),r;if(Ls.includes(t))r=e;else if(t==="base64")r=gf(e);else if(t==="quoted-printable")r=Ef(e);else throw _a("Unknown Content-Transfer-Encoding "+JSON.stringify(t).replace(/[^\x20-\x7e]/g,"?"));return/^text\//.test(Ga(s))?_t(r):r}function Sn(s,e,t){let r=Us(Va(s,e,t),t.partial);return{type:r.indexOf("\0")>=0?"LITERAL8":"LITERAL",value:r}}Sn.setsSeen=!0;function yf(s,e,t){if(t.partial)throw new Error("BINARY.SIZE does not take a partial range");return Va(s,e,t).length}function bf(s){let e=Gt(s),t=n=>{if(n.childNodes)return n.childNodes.map(t).includes(!0);let i=at(n,!0);if(i)return t(i)?(n.body=Be(i),!0):!1;let o=Xa(n);return!ja(n,!0)||!n.body||!(o==="binary"||Ls.includes(o)&&n.body.indexOf("\0")>=0)?!1:(n.body=b.Buffer.from(n.body,"binary").toString("base64").match(/.{1,76}/g).join(`\r
25
- `),n.header=n.header.filter(a=>!/^content-transfer-encoding\s*:/i.test(a)).concat("Content-Transfer-Encoding: base64"),!0)},r=t(e)?Be(e):s;if(r.indexOf("\0")>=0)throw _a("NUL octets are only allowed in the body of a part with the binary, 7bit or 8bit encoding");return r}function In(s){s.registerCapability("BINARY"),s.parserOptions.literal8=!0,s.parserOptions.allowSection.push("BINARY","BINARY.PEEK","BINARY.SIZE"),s.fetchHandlers.BINARY=Sn,s.fetchHandlers["BINARY.PEEK"]=(e,t,r)=>Sn(e,t,r),s.fetchHandlers["BINARY.SIZE"]=yf,s.appendLiteral8=e=>{try{return bf(e)}catch(t){throw nt(t.message,t.code)}}}g();g();var Tf="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+,";function qa(s){if(typeof s!="string")return"Invalid mailbox name";let e=0;for(;e<s.length;){let t=s.charCodeAt(e);if(t<32||t>126)return"Mailbox name must use modified UTF-7 for non-ASCII characters (RFC 3501 section 5.1.3)";if(s.charAt(e)!=="&"){e++;continue}if(s.charAt(e+1)==="-"){e+=2;continue}let r=s.indexOf("-",e+1);if(r<0)return'Modified BASE64 in mailbox name must end with "-" (RFC 3501 section 5.1.3)';let n=Sf(s.slice(e+1,r));if(n)return n;if(s.charAt(r+1)==="&"&&s.charAt(r+2)!=="-")return"Mailbox name contains a superfluous shift (RFC 3501 section 5.1.3)";e=r+1}return!1}function Sf(s){let e=0,t=0,r=[];for(let n=0;n<s.length;n++){let i=Tf.indexOf(s.charAt(n));if(i<0)return"Invalid modified BASE64 in mailbox name (RFC 3501 section 5.1.3)";e=e<<6|i,t+=6,t>=16&&(t-=16,r.push(e>>t&65535),e&=(1<<t)-1)}if(!r.length||t>=6||e!==0)return"Invalid modified BASE64 in mailbox name (RFC 3501 section 5.1.3)";for(let n=0;n<r.length;n++){let i=r[n];if(i>=32&&i<=126)return"Modified BASE64 must not encode printable US-ASCII (RFC 3501 section 5.1.3)";if(i>=55296&&i<=56319){if(!(r[n+1]>=56320&&r[n+1]<=57343))return"Invalid UTF-16 in mailbox name";n++}else if(i>=56320&&i<=57343)return"Invalid UTF-16 in mailbox name"}return!1}function vs(s){return s.replace(/&|[^\x20-\x7e]+/g,e=>e==="&"?"&-":"&"+b.Buffer.from(e,"utf16le").swap16().toString("base64").replace(/=+$/,"").replace(/\//g,",")+"-")}function On(s){return qa(s)?!1:s.replace(/&([^-]*)-/g,(e,t)=>t?b.Buffer.from(t.replace(/,/g,"/"),"base64").swap16().toString("utf16le"):"&")}var Tt=qa;function xn(s){s.registerCapability("CATENATE"),s.registerCapability("URL-PARTIAL"),s.appendDataHandlers.CATENATE=(e,t)=>{if(!Array.isArray(t)||!t.length||t.length%2)throw _e("CATENATE expects a list of TEXT literals and URLs");let r=[];for(let n=0;n<t.length;n+=2){let i=t[n]&&t[n].type==="ATOM"?String(t[n].value).toUpperCase():"",o=t[n+1];if(i==="TEXT"&&o&&o.type==="LITERAL")r.push({text:o.value});else if(i==="URL"&&o&&["ATOM","STRING","LITERAL"].indexOf(o.type)>=0)r.push({url:o.value});else throw _e("Invalid CATENATE part "+(n/2+1))}return()=>{let n=e.getMaxLiteralSize(),i="";for(let o of r)if(i+="text"in o?o.text:wf(e,o.url),i.length>n)throw nt("Catenated message is too large","TOOBIG");return i}}}var If=/^[A-Za-z0-9\-._~!$'()*+,&=:@/;%]*$/,Of=/^\/([^;]+?)(?:;UIDVALIDITY=([^/;]*))?\/;UID=([^/;]*)(?:\/;SECTION=([^/;]*))?(?:\/;PARTIAL=([^/;]*))?$/i;function Se(s,e){if(!s)return nt(e);let t=s.replace(/[^\x20-\x5c\x5e-\x7e]/g,r=>"%"+r.charCodeAt(0).toString(16).toUpperCase().padStart(2,"0"));return nt(e,"BADURL",[{type:"TEXT",value:t}])}function xf(s){let e=s.split("/").slice(1),t=[];return e.forEach((r,n)=>{let i=n===e.length-1;if(r==="."||r===".."){r===".."&&t.pop(),i&&t.push("");return}t.push(r)}),"/"+t.join("/")}function Qa(s){return s.replace(/%([0-9a-f]{2})/gi,(e,t)=>String.fromCharCode(parseInt(t,16)))}function Cf(s,e,t){if(!t||!/^[\x20-\x7e]+$/.test(t))return!1;let r;try{let o=st.parser("X FETCH 1 BODY.PEEK["+t+"]");r=o.attributes.length===2&&!o.attributes[1].partial&&o.attributes[1]}catch{return!1}if(!r||!r.section||!r.section.length||r.section[0].type!=="ATOM")return!1;let n=String(r.section[0].value).toUpperCase(),i=(n.match(/^[1-9]\d*(?:\.[1-9]\d*)*/)||[""])[0];if(i){let o=bt(ne(e).tree,i),a=n.substr(i.length+1);if(!o||a&&a!=="MIME"&&!o.message)return!1}try{return Te.BODY(s,e,{section:r.section}).value}catch{return!1}}function wf(s,e){if(!e)throw Se(e,"Empty URL does not refer to a message");if(/^[a-z][a-z0-9+.-]*:/i.test(e)||e.substr(0,2)==="//")throw Se(e,"Only absolute-path URLs of this server are supported, e.g. /INBOX/;UID=1");if(e.charAt(0)!=="/")throw Se(e,"Relative-path URLs are not allowed (RFC 5092 section 7.2)");if(!If.test(e)||/%(?![0-9a-f]{2})/i.test(e))throw Se(e,"Invalid characters in URL");let t=xf(e).match(Of);if(!t)throw Se(e,"URL does not refer to a message or a message part");let[,r,n,i,o,a]=t;if(n!==void 0&&!Le(n)||!Le(i))throw Se(e,"Invalid UIDVALIDITY or UID in URL");let u;try{u=new TextDecoder("utf-8",{fatal:!0}).decode(b.Buffer.from(Qa(r),"binary"))}catch{throw Se(e,"Mailbox name in URL is not valid UTF-8")}let l=s.server.getMailbox(vs(u));if(!l||l.flags.indexOf("\\Noselect")>=0)throw Se(e,"Mailbox does not exist");for(let p of s.server.urlAccessChecks){let y=p(s,l,e);if(y)throw Se(e,y.text||"Permission denied")}if(n!==void 0&&Number(n)!==l.uidvalidity)throw Se(e,"UIDVALIDITY does not match");let c=l.messages.find(p=>p.uid===Number(i));if(!c)throw Se(e,"Message does not exist");let f=c.raw;if(o!==void 0&&(f=Cf(s,c,Qa(o)),f===!1))throw Se(e,"Invalid section or the message part does not exist");if(a!==void 0){let p=a.match(/^(\d+)(?:\.(\d+))?$/);if(!p||!Ae(p[1])||p[2]!==void 0&&!Le(p[2]))throw Se(e,"Invalid partial range");f=f.substr(Number(p[1]),p[2]?Number(p[2]):void 0)}return f}g();function Cn(){throw new Error("The COMPRESS plugin is not available in the browser")}g();g();var jt={ALL:["FLAGS","INTERNALDATE","RFC822.SIZE","ENVELOPE"],FAST:["FLAGS","INTERNALDATE","RFC822.SIZE"],FULL:["FLAGS","INTERNALDATE","RFC822.SIZE","ENVELOPE","BODY"]};function Ya(s){return s.map(e=>{let t=Object.assign({},e,{value:e.value.replace(/\.PEEK\b/i,"")});return t.partial&&(t.partial=t.partial.slice(0,1)),t})}function Ka(s,e){return e.map((t,r)=>{let n=(t.value||"").toUpperCase(),i=s.server.fetchHandlers[n]||Te[n];if(!i)throw new Error("Invalid FETCH argument "+(n||"#"+(r+1)));return i})}function Bs(s,e,t,r,n){let i=r||Ka(s,t),o=n||Ya(t),a=[];return t.forEach((u,l)=>a.push(o[l],i[l](s,e,u))),a}function wn(s,e,t,r,n){let i=s?"UID FETCH":"FETCH";if(!t.attributes||t.attributes.length!==2||!t.attributes[0]||["ATOM","SEQUENCE"].indexOf(t.attributes[0].type)<0||!t.attributes[1]||["ATOM"].indexOf(t.attributes[1].type)<0&&!Array.isArray(t.attributes[1]))return e.send({tag:t.tag,command:"BAD",attributes:[{type:"TEXT",value:i+" expects sequence set and message item names"}]},"INVALID COMMAND",t,r),n();let o=e.limitRange(t,e.getCommandRange(t.attributes[0].value,s)),a=[].concat(t.attributes[1]||[]);t.attributes[1].type==="ATOM"&&Object.prototype.hasOwnProperty.call(jt,t.attributes[1].value.toUpperCase())&&(a=jt[t.attributes[1].value.toUpperCase()].slice());let u=[],l=[],c=[];try{let f=!1,p=!1,y=!1;a.forEach((h,d)=>{if(!h||typeof h!="string"&&h.type!=="ATOM")throw new Error("Invalid FETCH argument #"+(d+1));typeof h=="string"&&(h=a[d]={type:"ATOM",value:h});let E=h.value.toUpperCase();E==="FLAGS"&&(p=!0),E==="UID"&&(f=!0);let I=e.server.fetchHandlers[E]||Te[E];e.canSetSeen()&&(E==="BODY"&&h.section||I&&I.setsSeen)&&(y=!0)}),y&&!p&&a.push({type:"ATOM",value:"FLAGS"}),s&&!f&&a.push({type:"ATOM",value:"UID"});let A=Ka(e,a),m=Ya(a);o.forEach(h=>{for(let E=0,I=e.server.fetchFilters.length;E<I;E++)if(!e.server.fetchFilters[E](e,h[1],t,h[0]))return;y&&h[1].flags.indexOf("\\Seen")<0&&(h[1].flags.push("\\Seen"),u.push(h[1]));let d=Bs(e,h[1],a,A,m);c.push(h[1]),l.push({tag:"*",attributes:[h[0],{type:"ATOM",value:"FETCH"},d]})})}catch(f){let p=f;return u.forEach(y=>e.server.removeFlag(y.flags,"\\Seen")),e.sendStatus(t,r,p.imapResponse==="NO"?"NO":"BAD",p.message,p.code,i+" FAILED"),n()}return l.forEach((f,p)=>e.send(f,i,t,r,c[p])),e.send({tag:t.tag,command:"OK",attributes:[{type:"TEXT",value:i+" Completed"}]},i,t,r),e.notifyFlagChanges(u),n()}var Nf=(s,e,t,r)=>wn(!1,s,e,t,r),za=Nf;g();g();var St=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];function ze(s){let e=String(s||"").toLowerCase();return St.findIndex(t=>t.toLowerCase()===e)}function It(s,e,t){return s=Number(s),t=Number(t),e<0||e>11||!Number.isInteger(s)||s<1?!1:s<=new Date(Date.UTC(t,e+1,0)).getUTCDate()}function Hs(s,e,t){return It(s,e,t)?String(t).padStart(4,"0")+"-"+String(e+1).padStart(2,"0")+"-"+String(s).padStart(2,"0"):!1}function ks(s){if(!s||typeof s!="string")return!1;let e=s.match(/^( \d|\d\d)-(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)-(\d{4}) (\d{2}):(\d{2}):(\d{2}) [-+](\d{2})(\d{2})$/i);return e?It(e[1],ze(e[2]),e[3])&&Number(e[4])<24&&Number(e[5])<60&&Number(e[6])<61&&Number(e[8])<60:!1}function Ps(s){let e=String(s||"").match(/^\s*(\d{1,2})-([A-Za-z]{3})-(\d{4})(?: (\d{2}):(\d{2}):(\d{2}) ([+-]\d{4}))?/);if(!e||!It(e[1],ze(e[2]),e[3]))return null;let t=e[4]===void 0?{}:{hours:Number(e[4]),minutes:Number(e[5]),seconds:Number(e[6]),zone:e[7]};return Object.assign({day:Number(e[1]),month:ze(e[2]),year:Number(e[3])},t)}function Fs(s){let e=(s||"").toString().replace(/\([^()]*\)/g," ").match(/^\s*(?:[A-Za-z]+\s*,)?\s*(\d{1,2})\s+([A-Za-z]{3})\s+(\d{2,4})(?:\s+(\d{1,2})\s*:\s*(\d{2})(?:\s*:\s*(\d{2}))?(?:\s+([+-]\d{4}|[A-Za-z]+))?)?/);if(!e)return null;let t=Number(e[3]);e[3].length===2?t+=t<50?2e3:1900:e[3].length===3&&(t+=1900);let r=Number(e[1]),n=ze(e[2]);if(!It(r,n,t))return null;let i=e[4]===void 0?{}:{hours:Number(e[4]),minutes:Number(e[5]),seconds:Number(e[6]||0),zone:e[7]};return Object.assign({day:r,month:n,year:t},i)}var Wa={UT:0,GMT:0,EST:-5,EDT:-4,CST:-6,CDT:-5,MST:-7,MDT:-6,PST:-8,PDT:-7};function Nn(s){let e=s.zone||"",t=0;if(/^[+-]\d{4}$/.test(e)){let r=e.charAt(0)==="-"?-1:1,n=Number(e.substr(1,2)),i=Number(e.substr(3,2));i<60&&(t=r*(n*60+i))}else Object.hasOwn(Wa,e.toUpperCase())&&(t=Wa[e.toUpperCase()]*60);return Date.UTC(s.year,s.month,s.day,s.hours||0,s.minutes||0,s.seconds||0)-t*60*1e3}g();var Mn=/=\?([^?\s*]+)(?:\*[^?\s]*)?\?([BbQq])\?([^?\s]*)\?=/g,Mf=new TextDecoder("utf-8");function _s(s){return Mf.decode(b.Buffer.from(s,"binary"))}var Rn=new Map;function Rf(s,e){if(s=s.toLowerCase(),!Rn.has(s)){let r=!1;try{r=new TextDecoder(s)}catch{}Rn.set(s,r)}let t=Rn.get(s);return t?t.decode(e):!1}function ut(s){let e=String(s||"");if(e.indexOf("=?")<0&&!/[\u0080-\u00ff]/.test(e))return e;let t="",r=null,n=0,i=()=>{if(r){let a=Rf(r.charset,b.Buffer.concat(r.octets));t+=a===!1?r.source:a,r=null}};Mn.lastIndex=0;let o;for(;o=Mn.exec(e);){let a=e.substring(n,o.index);r&&/^\s*$/.test(a)||(i(),t+=_s(a)),n=Mn.lastIndex;let l=o[2].toUpperCase()==="B"?b.Buffer.from(o[3],"base64"):b.Buffer.from(o[3].replace(/_/g," ").replace(/=([0-9a-fA-F]{2})/g,(c,f)=>String.fromCharCode(parseInt(f,16))),"binary");r&&r.charset.toLowerCase()!==o[1].toLowerCase()&&i(),r||(r={charset:o[1],octets:[],source:""}),r.octets.push(l),r.source+=(r.source?a:"")+o[0]}return i(),t+_s(e.substr(n))}var Lf={ALL:[],ANSWERED:[],BCC:["string"],BEFORE:["date"],BODY:["string"],CC:["string"],DELETED:[],DRAFT:[],FLAGGED:[],FROM:["string"],HEADER:["string","string"],KEYWORD:["string"],LARGER:["number64"],NEW:[],NOT:["key"],OLD:[],ON:["date"],OR:["key","key"],RECENT:[],SEEN:[],SENTBEFORE:["date"],SENTON:["date"],SENTSINCE:["date"],SINCE:["date"],SMALLER:["number64"],SUBJECT:["string"],TEXT:["string"],TO:["string"],UID:["sequence"],UNANSWERED:[],UNDELETED:[],UNDRAFT:[],UNFLAGGED:[],UNKEYWORD:["string"],UNSEEN:[]},$a=["US-ASCII","UTF-8"];function Q(s){let e=new Error(s);return e.imapResponse="BAD",e}function Df(s){let e=(s||"").toString().match(/^(\d{1,2})-([A-Za-z]{3})-(\d{4})$/),t=e&&Hs(Number(e[1]),ze(e[2]),Number(e[3]));if(!t)throw Q("Invalid date argument "+s);return t}function vn(s){let e=Ps(s);return e?Hs(e.day,e.month,e.year):!1}function Gs(s){return vn(s.internaldate)}function Ln(s){let e=Fs(ne(s).tree.parsedHeader.date);return e?Hs(e.day,e.month,e.year):Gs(s)}function Ot(s){let e=(t,r)=>{if(Array.isArray(t))return t.map(e);if(!t||["STRING","ATOM","LITERAL","SEQUENCE"].indexOf(t.type)<0)throw Q("Invalid search criteria argument #"+(r+1));return t.value};return s.map(e)}function xt(s,e,t,r,n){let i=[];r.code==="BADCHARSET"?i.push({type:"SECTION",section:[{type:"ATOM",value:"BADCHARSET"},r.charsets.map(o=>({type:"ATOM",value:o}))]}):r.responseCode&&i.push({type:"SECTION",section:r.responseCode.map(o=>({type:"ATOM",value:String(o)}))}),i.push({type:"TEXT",value:r.message}),s.send({tag:e.tag,command:r.imapResponse==="BAD"?"BAD":"NO",attributes:i},n,e,t)}function Un(s){return s.replace(/[A-Z]+/g,e=>e.toLowerCase())}function Dn(s,e){return Un(s).indexOf(e)>=0}function Ja(s){let e=Object.assign({},Lf),t=s.searchHandlers;return Object.keys(t).forEach(r=>{if(!(r in e)){let n=t[r];e[r]=typeof n.argumentTypes=="function"?n.argumentTypes:new Array(Math.max(n.length-3,0)).fill("string")}}),e}function Za(s,e){let t=Ja(s),r=n=>{let i=0;return n.some((o,a)=>{if(Array.isArray(o))return r(o);if(i)return i--,!1;let u=(o&&o.value||"").toString(),l=u.toUpperCase();if(l==="CHARSET"&&a===0)i=1;else if(Object.hasOwn(t,l)){let c=t[l];typeof c=="function"&&(c=c(n.slice(a+1).map(f=>Array.isArray(f)?f:(f&&f.value||"").toString()))),i=c.filter(f=>f!=="key").length}else if(/^[\d*][\d*,:]*$/.test(u))return!0;return!1})};return r([].concat(e||[]))}function De(s,e,t,r){let n=r||((N,w)=>s.getMessageRange(N,w)),i={},o=new Set,a=Ja(s.server),u=s.server.searchHandlers;t=[].concat(t||[]);let l=s.searchCharset||s.defaultSearchCharset||"US-ASCII";if(typeof t[0]=="string"&&t[0].toUpperCase()==="CHARSET"){if(s.searchCharset)throw Q("CHARSET is not allowed, search strings are always "+s.searchCharset+" in this session");t.shift();let N=t.shift();if(typeof N!="string")throw Q("CHARSET expects a charset name");if($a.indexOf(N.toUpperCase())<0){let w=new Error("Unsupported charset "+N);throw w.imapResponse="NO",w.code="BADCHARSET",w.charsets=$a,w}l=N.toUpperCase()}let c=(N,w)=>{if(l==="US-ASCII"&&/[\u0080-\u00ff]/.test(w))throw Q(N+" argument has 8-bit characters, use CHARSET UTF-8");if(l==="UTF-8"&&!Ye(b.Buffer.from(w,"binary")))throw Q(N+" argument is not valid UTF-8");return w};if(!t.length)throw Q("SEARCH expects search criteria, empty query given");let f=N=>{if(!N.length)throw Q("Unexpected end of search criteria");let w=N.shift();if(Array.isArray(w))return{key:"AND",args:p([].concat(w))};let G=w.toUpperCase();if(!Object.prototype.hasOwnProperty.call(a,G)||s.disabledSearchKeys&&s.disabledSearchKeys.has(G)){let L;try{L=n(w,!1)}catch(v){throw/^[\d,:*]+$/.test(w)?v:Q("Invalid search key "+w)}return{key:"_SEQ",args:[L]}}o.add(G);let F=a[G],W=typeof F=="function"?F(N):F,x=W.map(L=>{if(L==="key")return f(N);if(!N.length||typeof N[0]!="string")throw Q(G+" expects "+W.length+" argument"+(W.length>1?"s":""));let v=N.shift();if(typeof L=="function")return L(v);switch(L){case"date":return Df(v);case"number":case"number64":{let V=L==="number64"&&s.number64;if(!Ae(v,V?Ge:4294967295))throw Q(G+" expects a number"+(V?"64":""));return Number(v)}case"sequence":return n(v,!0);default:return c(G,v)}});return{key:G,args:x}},p=N=>{if(!N.length)throw Q("Empty search criteria list");let w=[];for(;N.length;)w.push(f(N));return w},y={key:"AND",args:p(t)},A=N=>new Set(N.map(w=>w[1])),m=N=>{(N.key==="_SEQ"||N.key==="UID")&&(N.set=A(N.args[0])),["BODY","TEXT"].indexOf(N.key)>=0?N.needle=Un(N.args[0]):["BCC","CC","FROM","HEADER","SUBJECT","TO"].indexOf(N.key)>=0&&(N.needle=Un(_s(N.args[N.key==="HEADER"?1:0]))),N.args.forEach(w=>{w&&typeof w=="object"&&w.key&&m(w)})};m(y);let h=(N,w)=>N.flags.indexOf(w)>=0,d=(N,w,G)=>(w=w.toLowerCase(),(ne(N).tree.header||[]).some(F=>{let W=F.indexOf(":"),x=(W<0?F:F.substr(0,W)).trim().toLowerCase(),L=W<0?"":F.substr(W+1).replace(/\r?\n(?=[ \t])/g,"");return x===w&&Dn(ut(L),G)})),E=(N,w,G)=>{let F=N.args;if(Object.prototype.hasOwnProperty.call(u,N.key))return!!u[N.key](s,w,G,...F);switch(N.key){case"AND":return F.every(W=>E(W,w,G));case"_SEQ":case"UID":return N.set.has(w);case"ALL":return!0;case"ANSWERED":return h(w,"\\Answered");case"BCC":case"CC":case"FROM":case"SUBJECT":case"TO":return d(w,N.key,N.needle);case"HEADER":return d(w,F[0],N.needle);case"BEFORE":{let W=Gs(w);return!!W&&W<F[0]}case"ON":return Gs(w)===F[0];case"SINCE":{let W=Gs(w);return!!W&&W>=F[0]}case"SENTBEFORE":{let W=Ln(w);return!!W&&W<F[0]}case"SENTON":return Ln(w)===F[0];case"SENTSINCE":{let W=Ln(w);return!!W&&W>=F[0]}case"BODY":return Dn(Be(ne(w).tree,!0),N.needle);case"TEXT":return Dn(ne(w).raw,N.needle);case"DELETED":return h(w,"\\Deleted");case"DRAFT":return h(w,"\\Draft");case"FLAGGED":return h(w,"\\Flagged");case"KEYWORD":return h(w,F[0]);case"LARGER":return ne(w).raw.length>F[0];case"SMALLER":return ne(w).raw.length<F[0];case"NEW":return s.isRecent(w)&&!h(w,"\\Seen");case"OLD":return!s.isRecent(w);case"RECENT":return s.isRecent(w);case"SEEN":return h(w,"\\Seen");case"NOT":return!E(F[0],w,G);case"OR":return E(F[0],w,G)||E(F[1],w,G);case"UNANSWERED":return!h(w,"\\Answered");case"UNDELETED":return!h(w,"\\Deleted");case"UNDRAFT":return!h(w,"\\Draft");case"UNFLAGGED":return!h(w,"\\Flagged");case"UNKEYWORD":return!h(w,F[0]);case"UNSEEN":return!h(w,"\\Seen");default:return!1}},I=s.server.searchLimits.reduce((N,w)=>w(s,N,y)||N,e),C=I!==e&&new Set(I),H=[];return e.forEach((N,w)=>{C&&!C.has(N)||E(y,N,w+1)&&(i[N.uid]=w+1,H.push(N))}),{list:H,numbers:i,keys:o,matches:(N,w)=>E(y,N,w)}}g();function Ne(s,e){s.enableAvailable=s.enableAvailable||[],s.enableAvailable.indexOf(e)<0&&s.enableAvailable.push(e)}function ye(s,e){return!!s.enabled&&s.enabled.indexOf(e)>=0}function Bn(s){s.registerCapability("ENABLE"),s.enableAvailable=s.enableAvailable||[],s.connectionHandlers.push(e=>{e.enabled=e.enabled||[]}),s.resetHandlers.push(e=>{e.enabled=[]}),s.setCommandHandler("ENABLE",(e,t,r,n)=>{let i,o,a;if(e.everSelected)return e.sendStatus(t,r,"BAD","ENABLE is not allowed after SELECT or EXAMINE"),n();if(!t.attributes)return e.send({tag:t.tag,command:"BAD",attributes:[{type:"TEXT",value:"ENABLE expects capability list"}]},"INVALID COMMAND",t,r),n();for(o=0,a=t.attributes.length;o<a;o++)if(!t.attributes[o]||t.attributes[o].type!=="ATOM")return e.send({tag:t.tag,command:"BAD",attributes:[{type:"TEXT",value:"Attribute nr "+(o+1)+" is not an ATOM"}]},"INVALID COMMAND",t,r),n();let u=[];for(o=0,a=t.attributes.length;o<a;o++){let l=t.attributes[o].value.toUpperCase();i=s.enableAvailable.find(c=>c.toUpperCase()===l),i&&e.enabled.indexOf(i)<0&&(e.enabled.push(i),u.push(i))}return e.send({tag:"*",command:"ENABLED",attributes:u.map(l=>({type:"ATOM",value:l}))},"ENABLED",t,r,u),e.send({tag:t.tag,command:"OK",attributes:[{type:"TEXT",value:"ENABLE completed"}]},"ENABLE",t,r),n()},{states:Z.AUTHENTICATED})}function kn(s){s.registerCapability("CONDSTORE"),Ne(s,"CONDSTORE");let e=m=>Math.max(Number(m.HIGHESTMODSEQ)||0,1),t=m=>(m.HIGHESTMODSEQ=e(m)+1,m.HIGHESTMODSEQ);s.resetHandlers.push(m=>{m.condstoreEnabled=!1});let r=m=>!!m.condstoreEnabled||ye(m,"CONDSTORE")||ye(m,"QRESYNC");s.condstore={isEnabled:r,getHighestModseq:e};let n=(m,h,d,E)=>{m.send({tag:"*",command:"OK",attributes:[{type:"SECTION",section:[{type:"ATOM",value:"HIGHESTMODSEQ"},e(h)]},{type:"TEXT",value:"Highest"}]},"CONDSTORE INFO",d,E)},i=(m,h,d)=>{if(r(m)){m.condstoreEnabled=!0;return}m.condstoreEnabled=!0,m.state==="Selected"&&m.selectedMailbox&&n(m,m.selectedMailbox,h,d)};s.messageHandlers.push((m,h,d)=>{let E=Number(h.MODSEQ);E>0&&Number.isSafeInteger(E)?(h.MODSEQ=E,d.HIGHESTMODSEQ=Math.max(e(d),E)):h.MODSEQ=t(d)}),s.on("expunge",m=>{t(m)}),s.on("flags",(m,h)=>{h.forEach(d=>{d.MODSEQ=t(m)})}),s.closedChecks.push(()=>!0),s.allowedStatus.push("HIGHESTMODSEQ"),s.statusHandlers.HIGHESTMODSEQ=(m,h)=>e(h);let o=(m,h)=>{let d=s.getCommandHandler(m);d&&s.setCommandHandler(m,(E,I,C,H)=>h(d,E,I,C,H))},a=(m,h,d,E,I)=>(m.sendStatus(h,d,"BAD",I,!1,"CONDSTORE FAILED"),E()),u=(m,h)=>!!m&&m.type==="ATOM"&&Ae(m.value,Ge)&&(h||BigInt(m.value)>0n),l=(m,h,d,E,I)=>{Hf(d.attributes&&d.attributes[1],d.attributes,1)&&(h.condstoreEnabled=!0,d.condstoreOption=!0),m(h,d,E,I)};o("SELECT",l),o("EXAMINE",l),o("STATUS",(m,h,d,E,I)=>{let C=d.attributes&&d.attributes[1];Array.isArray(C)&&C.some(H=>H&&H.type==="ATOM"&&String(H.value).toUpperCase()==="HIGHESTMODSEQ")&&i(h,d,E),m(h,d,E,I)});let c=(m,h,d,E,I)=>{let C=d.attributes||[],H=Math.max(C.length-1,2),N=nu(C[H],"CHANGEDSINCE",C,H);if(N){if(!u(N))return a(h,d,E,I,"Invalid syntax for CHANGEDSINCE, number expected");d.changedsince=Number(N.value),Bf(d)}(N||iu(d))&&i(h,d,E),m(h,d,E,I)};o("FETCH",c),o("UID FETCH",c);let f=(m,h,d,E,I)=>{let C=nu(d.attributes&&d.attributes[1],"UNCHANGEDSINCE",d.attributes,1);if(C){if(!u(C,!0))return a(h,d,E,I,"Invalid syntax for UNCHANGEDSINCE, number expected");d.unchangedsince=Number(C.value),i(h,d,E)}d.condstoreStore={isUid:(d.command||"").toUpperCase()==="UID STORE",messages:new Map,modified:[],done:!1},m(h,d,E,I)};o("STORE",f),o("UID STORE",f);let p=(m,h,d,...E)=>h.MODSEQ>=E[E.length-1];p.argumentTypes=m=>typeof m[0]=="string"&&/^\d+$/.test(m[0])?[eu]:[Uf,vf,eu],s.searchHandlers.MODSEQ=p;let y=m=>m.reduce((h,d)=>Math.max(h,d.MODSEQ),0);s.fetchHandlers.MODSEQ=function(m,h){return[h.MODSEQ]},s.fetchFilters.push((m,h,d,E)=>"changedsince"in d&&!(d.changedsince<h.MODSEQ)?!1:(d.condstoreFetch||(d.condstoreFetch=new Map),d.condstoreFetch.set(E,{message:h,seen:h.flags.indexOf("\\Seen")>=0}),!0)),s.storeFilters.push((m,h,d,E)=>{let I=d.condstoreStore;return I?"unchangedsince"in d&&h.MODSEQ>d.unchangedsince?(I.modified.push(I.isUid?h.uid:E),!1):(I.messages.set(h,{index:E,before:tu(h),bumped:!1,reported:!1}),!0):!0});let A=(m,h,d)=>{!d.bumped&&tu(h)!==d.before&&(d.bumped=!0,h.MODSEQ=t(m.selectedMailbox))};s.outputHandlers.push((m,h,d,E,I,C)=>{if(d==="FLAG NOTIFICATION"&&h&&C&&r(m)){Hn(h.attributes[2],C.MODSEQ);return}if(!E||!h)return;if(d==="FLAG UPDATE"&&E.condstoreStore&&C&&E.condstoreStore.messages.has(C)){let N=E.condstoreStore.messages.get(C);A(m,C,N),N.reported=!0,r(m)&&(Hn(h.attributes[2],C.MODSEQ),su(h.attributes[2],C.uid));return}let H=["SEARCH","SORT","THREAD"].includes(h.command)&&[h.command,"UID "+h.command].includes(d);if((H||d==="ESEARCH")&&h.tag==="*"&&C&&C.keys&&C.keys.has("MODSEQ")){if(i(m,E,I),C.list.length&&h.command!=="THREAD"){let N=[{type:"ATOM",value:"MODSEQ"},y(C.list)];h.attributes.push(...H?[N]:N)}return}if(h.tag==="*"&&E.condstoreFetch&&h.attributes&&h.attributes[1]&&h.attributes[1].value==="FETCH"&&E.condstoreFetch.has(h.attributes[0])){let N=E.condstoreFetch.get(h.attributes[0]),w=N.message,G=!1;!N.seen&&w.flags.indexOf("\\Seen")>=0&&m.selectedMailbox&&(N.seen=!0,w.MODSEQ=t(m.selectedMailbox),G=!0);let F=h.attributes[2];Array.isArray(F)&&(Pn(F,"MODSEQ")>=0||G&&r(m))&&Hn(F,w.MODSEQ),Array.isArray(F)&&G&&r(m)&&su(F,w.uid);return}if(h.tag===E.tag&&E.condstoreStore&&!E.condstoreStore.done){let N=E.condstoreStore;N.done=!0,N.messages.forEach((w,G)=>{if(A(m,G,w),!w.reported&&r(m)&&(w.bumped||"unchangedsince"in E)){let F=[{type:"ATOM",value:"MODSEQ"},[G.MODSEQ]];F.unshift({type:"ATOM",value:"UID"},G.uid),m.send({tag:"*",attributes:[w.index,{type:"ATOM",value:"FETCH"},F]},"CONDSTORE MODSEQ UPDATE",E,I,G)}}),(h.command==="OK"||h.command==="NO")&&N.modified.length&&(h.attributes=[{type:"SECTION",section:[{type:"ATOM",value:"MODIFIED"},{type:"SEQUENCE",value:N.modified.sort((w,G)=>w-G).join(",")}]}].concat((h.attributes||[]).filter(w=>h.command==="OK"||!w||w.type!=="SECTION")));return}if(d==="ENABLED"&&Array.isArray(C)&&C.indexOf("CONDSTORE")>=0){m.condstoreEnabled||(m.condstoreEnabled=!0,m.state==="Selected"&&m.selectedMailbox&&(E.condstoreReportHighest=!0));return}if(d==="ENABLE"&&E.condstoreReportHighest&&m.selectedMailbox){E.condstoreReportHighest=!1,n(m,m.selectedMailbox,E,I);return}if((d==="EXAMINE"||d==="SELECT")&&h.tag===E.tag&&m.selectedMailbox){if(E.condstoreOption){let N=h.attributes&&h.attributes.slice(-1)[0];!N||N.type!=="TEXT"?h.attributes=(h.attributes||[]).concat({type:"TEXT",value:"CONDSTORE is now enabled"}):N.value+=", CONDSTORE is now enabled"}n(m,m.selectedMailbox,E,I)}})}function eu(s){if(!Ae(s,Ge))throw Q("MODSEQ expects a mod-sequence value");return Number(s)}function Uf(s){let e=s.match(/^\/flags\/(\\?)(.+)$/i);if(!e||sn.test(e[2])||e[1]&&e[2].toUpperCase()==="RECENT")throw Q('MODSEQ expects an entry name like "/flags/\\\\seen"');return s}function vf(s){if(!["PRIV","SHARED","ALL"].includes(s.toUpperCase()))throw Q("MODSEQ expects entry type priv, shared or all");return s}function tu(s){return JSON.stringify([s.flags||[],s["X-GM-LABELS"]||[]])}function Pn(s,e){if(!Array.isArray(s))return-1;for(let t=0;t<s.length;t+=2)if(s[t]&&s[t].type==="ATOM"&&String(s[t].value).toUpperCase()===e)return t;return-1}function Hn(s,e){if(!Array.isArray(s))return;let t=Pn(s,"MODSEQ");t>=0?s[t+1]=[e]:s.push({type:"ATOM",value:"MODSEQ"},[e])}function su(s,e){Array.isArray(s)&&Pn(s,"UID")<0&&s.push({type:"ATOM",value:"UID"},e)}function ru(s){return!!s&&s.type==="ATOM"&&String(s.value).toUpperCase()==="MODSEQ"}function iu(s){let e=s.attributes&&s.attributes[1];return Array.isArray(e)?e.some(ru):ru(e)}function Bf(s){if(!s.attributes||!s.attributes[1]||iu(s))return;let e=s.attributes[1];if(!Array.isArray(e)){let t=String(e.value).toUpperCase(),r=e.type==="ATOM"&&Object.hasOwn(jt,t)&&jt[t];e=r?r.map(n=>({type:"ATOM",value:n})):[e].concat(s.attributes.splice(2))}s.attributes[1]=e.concat({type:"ATOM",value:"MODSEQ"})}function Hf(s,e,t){if(!s)return!1;let r=!1;if(Array.isArray(s)){for(let n=s.length-1;n>=0;n--)if(s[n]&&s[n].type==="ATOM"&&s[n].value.toUpperCase()==="CONDSTORE"){s.splice(n,1),r=!0;break}s.length||e.splice(t,1)}return!!r}function nu(s,e,t,r){if(!s)return!1;let n=!1;if(Array.isArray(s)){for(let i=0;i<s.length;i+=2)if(s[i]&&s[i].type==="ATOM"&&s[i].value.toUpperCase()===e.toUpperCase()){n=s[i+1]||{type:"NIL"},s.splice(i,2);break}s.length||t.splice(r,1)}return n}g();g();g();function lt(s){return Xs(Array.from(new Set(s)).sort((e,t)=>e-t))}function Xs(s){let e=[];return s.forEach(t=>{let r=e[e.length-1];r&&r[1]+1===t?r[1]=t:e.push([t,t])}),e.map(t=>t[0]===t[1]?String(t[0]):t[0]+":"+t[1]).join(",")}function Vt(s,e){let t=s&&["ATOM","SEQUENCE"].includes(s.type)?String(s.value):"",r=t.match(/^(-?)([1-9][0-9]*):(-?)([1-9][0-9]*)$/);if(!r||r[1]!==r[3]||r[1]&&!e)throw Q("PARTIAL expects a range like 1:100"+(e?" or -1:-100":""));let n=Number(r[2]),i=Number(r[4]);if(n>4294967295||i>4294967295)throw Q("PARTIAL range is out of bounds");return{range:t,from:Math.min(n,i),to:Math.max(n,i),fromEnd:!!r[1]}}function js(s,e){return e.fromEnd?s.slice(Math.max(s.length-e.to,0),Math.max(s.length-e.from+1,0)):s.slice(e.from-1,e.to)}function Vs(s){s.searchReturnOptions.has("PARTIAL")||(s.searchReturnOptions.set("PARTIAL",{data:!0,once:!0,parse:e=>Vt(e,!!s.partialRangeLast)}),s.searchReturnOptions.set("ALL",Object.assign({},s.searchReturnOptions.get("ALL"),{once:!0})),s.searchReturnChecks.push(e=>e.has("PARTIAL")&&e.has("ALL")&&"PARTIAL and ALL can not be used together"))}function je(s,e){let t=e.get("PARTIAL");if(!s.length||e.has("ALL")||e.has("COUNT")||!t&&!e.has("MIN")&&!e.has("MAX"))return s;let r=new Set(t?js(s,t):[]);return e.has("MIN")&&r.add(s[0]),e.has("MAX")&&r.add(s[s.length-1]),s.filter(n=>r.has(n))}function Fn(s,e){let t=[{type:"ATOM",value:"TAG"},{type:"STRING",value:s}];return e&&t.push({type:"ATOM",value:"MAILBOX"},{type:"MAILBOX",value:e.path},{type:"ATOM",value:"UIDVALIDITY"},e.uidvalidity),t}function Ct(s,e,t,r,n,i){let o=(i||t.list).map(c=>e?c.uid:t.numbers[c.uid]);i||o.sort((c,f)=>c-f);let a=i?Xs:lt,u=[Fn(s,n)];e&&u.push({type:"ATOM",value:"UID"});let l=(c,f)=>u.push({type:"ATOM",value:c},f);if(o.length&&r.has("MIN")&&l("MIN",o[0]),o.length&&r.has("MAX")&&l("MAX",o[o.length-1]),o.length&&(r.has("ALL")||!r.size)&&l("ALL",{type:"SEQUENCE",value:a(o)}),r.has("PARTIAL")){let c=r.get("PARTIAL"),f=js(o,c);l("PARTIAL",[{type:"ATOM",value:c.range},f.length?{type:"SEQUENCE",value:a(f)}:null])}return r.has("COUNT")&&l("COUNT",o.length),{tag:"*",command:"ESEARCH",attributes:u}}var ou=s=>{let e=s&&s[0];return!!e&&e.type==="ATOM"&&String(e.value).toUpperCase()==="RETURN"};function Ie(s){if(s.searchReturnOptions)return;s.registerCapability("ESEARCH"),s.searchReturnOptions=new Map(["MIN","MAX","ALL","COUNT"].map(t=>[t,{data:!0}])),s.searchReturnChecks=[],s.parseSearchReturn=(t,r,n)=>{if(!Array.isArray(t))throw Q("RETURN expects a parenthesized list of result options");let i=new Map,o=new Set;for(let a=0;a<t.length;a++){let u=t[a],l=u&&u.type==="ATOM"?String(u.value).toUpperCase():"",c=s.searchReturnOptions.get(l);if(!c)throw Q("Unknown SEARCH result option"+(l?" "+l:""));if(c.once&&i.has(l))throw Q("SEARCH result option "+l+" can be used only once");o.add(l);let f=c.parse?c.parse(t[++a]):!0;c.hint||i.set(l,f)}for(let a of s.searchReturnChecks){let u=a(i,r,n,o);if(u)throw Q(u)}return i},s.isSilentReturn=t=>t.size>0&&![...t.keys()].some(r=>{let n=s.searchReturnOptions.get(r);return n.data||n.response});let e=(t,r,n,i,o)=>{if(!ou(n.attributes))return t(r,n,i,o);try{n.searchReturn=s.parseSearchReturn(n.attributes[1],r,n)}catch(a){return r.sendStatus(n,i,"BAD",a.message,!1,(n.command||"").toUpperCase()+" FAILED"),o()}n.attributes=n.attributes.slice(2),t(r,n,i,o)};s.acceptSearchReturn=t=>{let r=s.getCommandHandler(t);s.setCommandHandler(t,(n,i,o,a)=>e(r,n,i,o,a))},s.acceptSearchReturn("SEARCH"),s.acceptSearchReturn("UID SEARCH"),s.connectionHandlers.push(t=>{let r=t.usesSequenceNumbers;t.usesSequenceNumbers=function(n){return ou(n.attributes)&&(n=Object.assign({},n,{attributes:n.attributes.slice(2)})),r.call(this,n)}}),s.outputHandlers.push((t,r,n,i,o,a)=>{if(!i||!i.searchReturn||r.tag!=="*"||r.command!=="SEARCH"||n!=="SEARCH"&&n!=="UID SEARCH"||!a||!Array.isArray(a.list))return;r.skipResponse=!0;let u=i.searchReturn;s.isSilentReturn(u)||t.send(Ct(i.tag,n==="UID SEARCH",a,u),"ESEARCH",i,o,Object.assign({},a,{list:je(a.list,u)}))})}var kf=10,au=new Set(["SELECT","EXAMINE","CLOSE","UNSELECT"]),Pf=new Set(["SEARCH","UID SEARCH","SORT","UID SORT"]),_n=s=>(s.searchContexts||(s.searchContexts=new Map),s.searchContexts),uu=(s,e)=>{let t=[];s.forEach(([n,i])=>{let o=t[t.length-1],a=o&&(e||!n?o.position:o.position+o.values.length);o&&n===a?o.values.push(i):t.push({position:n,values:[i]})});let r=[];return t.forEach(n=>{let i=n.position?Xs(n.values):lt(n.values);r.push(n.position,{type:"SEQUENCE",value:i})}),r},lu=(s,e,t,r)=>{let n=[Fn(e.tag,e.correlatorMailbox)];e.isUid&&n.push({type:"ATOM",value:"UID"}),t.length&&n.push({type:"ATOM",value:"REMOVEFROM"},uu(t,!0)),r.length&&n.push({type:"ATOM",value:"ADDTO"},uu(r,!1)),s.send({tag:"*",command:"ESEARCH",attributes:n},"ESEARCH UPDATE",null,null,e)},Ff=s=>{let e=s.searchContexts,t=s.selectedMailbox,r=t?t.messages:[],n=new Map(r.map((i,o)=>[i,o+1]));e.forEach((i,o)=>{if(i.mailbox!==t){e.delete(o);return}let a=r.filter((p,y)=>i.matches(p,y+1)),u=p=>i.isUid?p.uid:n.get(p),l=new Set(a),c=[],f=[];if(!i.compare)i.results.forEach(p=>{!l.has(p)&&n.has(p)&&c.push([0,u(p)])}),a.forEach(p=>{i.results.has(p)||f.push([0,u(p)])});else{let p=0;i.order.forEach(y=>{l.has(y)?p++:n.has(y)&&c.push([p+1,u(y)])}),i.order=a.sort(i.compare),i.order.forEach((y,A)=>{i.results.has(y)||f.push([A+1,u(y)])})}i.results=l,(c.length||f.length)&&lu(s,i,c,f)})},_f=(s,e,t)=>{s.searchContexts.forEach(r=>{if(r.mailbox!==s.selectedMailbox)return;let n=[];e.forEach(i=>{if(!r.results.delete(i))return;let o=0;r.order&&(o=r.order.indexOf(i)+1,r.order.splice(o-1,1)),(r.isUid||t)&&n.push([o,r.isUid?i.uid:t])}),n.length&&lu(s,r,n,[])})};function qt(s){if(s.addSearchContext)return;Ie(s),s.registerCapability("CONTEXT=SEARCH");let e=Math.max(Number(s.options.maxSearchContexts)||kf,1);s.searchReturnOptions.set("CONTEXT",{hint:!0}),s.searchReturnOptions.set("UPDATE",{data:!1,response:!0,once:!0}),Vs(s),s.searchReturnChecks.push((t,r,n)=>t.has("UPDATE")&&_n(r).has(n.tag)&&"Tag "+n.tag+" is already in use by an updating search"),s.addSearchContext=(t,r,n,i,o,a)=>{let u=_n(t);if(u.size>=e){t.send({tag:"*",command:"NO",attributes:[{type:"SECTION",section:[{type:"ATOM",value:"NOUPDATE"},{type:"STRING",value:r.tag}]},{type:"TEXT",value:"Too many updating contexts"}]},"NOUPDATE",r,n);return}u.set(r.tag,{tag:r.tag,isUid:o,matches:i.matches,results:new Set(i.list),compare:i.compare||null,order:i.compare?i.sorted.slice():null,mailbox:t.selectedMailbox,correlatorMailbox:a||null})},s.setCommandHandler("CANCELUPDATE",(t,r,n,i)=>{let o=r.attributes||[];if(!o.length||o.some(l=>!l||l.type!=="STRING"))return t.sendStatus(r,n,"BAD","CANCELUPDATE expects one or more quoted tags",!1,"CANCELUPDATE FAILED"),i();let a=_n(t);return o.find(l=>!a.has(l.value))?(t.sendStatus(r,n,"NO","Unknown tag",!1,"CANCELUPDATE FAILED"),i()):(o.forEach(l=>a.delete(l.value)),t.sendStatus(r,n,"OK","Updates cancelled",!1,"CANCELUPDATE"),i())},{states:Z.SELECTED}),s.resetHandlers.push(t=>{t.searchContexts=null}),s.connectionHandlers.push(t=>{let r=t.processNotifications;t.processNotifications=function(n,i){r.call(this,n,i);let o=(n&&n.command||"").toUpperCase();this.searchContexts&&this.searchContexts.size&&!this.notificationQueue.length&&!au.has(o)&&Ff(this)}}),s.outputHandlers.push((t,r,n,i,o,a)=>{let u=r.tag==="*"&&(r.message?[r.message]:r.command==="VANISHED"&&r.messages);if(u&&t.searchContexts){_f(t,u,r.message?r.attributes[0]:null);return}if(!i)return;let l=(i.command||"").toUpperCase();if(r.tag===i.tag&&au.has(l)){t.searchContexts=null;return}if(!(!Pf.has(l)||!i.searchReturn||!i.searchReturn.has("UPDATE"))){if(r.tag==="*"&&l.endsWith(String(r.command))&&n===l&&a&&Array.isArray(a.list)){i.contextResult=a;return}r.tag===i.tag&&r.command==="OK"&&i.contextResult&&s.addSearchContext(t,i,o,i.contextResult,l.startsWith("UID "))}})}g();g();g();g();var Gn=new Map([[452,453],[454,453],[455,456],[457,456],[458,459],[460,459],[497,498],[499,498],[8115,8124],[8131,8140],[8179,8188]]);for(let s of[8064,8080,8096])for(let e=0;e<8;e++)Gn.set(s+e,s+e+8);function He(s){let e="";for(let t of s){let r=t.codePointAt(0);if(Gn.has(r)){e+=String.fromCodePoint(Gn.get(r));continue}let n=t.toUpperCase();e+=[...n].length===1?n:t}return b.Buffer.from(e.normalize("NFKD"),"utf-8")}var Xn="\\[[^[\\]]*\\] *",Gf=new RegExp("^(?:"+Xn+")*(?:re|fwd?) *(?:"+Xn+")?:","i"),Xf=new RegExp("^"+Xn);function qs(s){let e=!1,t=ut(s).replace(/\r?\n(?=[ \t])/g,"").replace(/[\t\r\n]/g," ").replace(/ {2,}/g," ");for(;;){let r=t.length;for(;;)if(t.charAt(r-1)===" ")r--;else if(r>=5&&t.substring(r-5,r).toLowerCase()==="(fwd)")e=!0,r-=5;else break;for(t=t.substring(0,r);;){let n;if(t.charAt(0)===" ")t=t.substr(1);else if(n=t.match(Gf))e=!0,t=t.substr(n[0].length);else if((n=t.match(Xf))&&n[0].length<t.length)t=t.substr(n[0].length);else break}if(/^\[fwd:/i.test(t)&&/\]$/.test(t)){e=!0,t=t.slice(5,-1);continue}return{subject:t,isReply:e}}}function jn(s){let e=Ps(s.internaldate);return e?Nn(e):0}function Qs(s){let e=Fs(ne(s).tree.parsedHeader.date);return e?((e.hours===void 0||e.hours>23||e.minutes>59||e.seconds>60)&&Object.assign(e,{hours:0,minutes:0,seconds:0}),Nn(e)):jn(s)}function cu(s,e){let t=Xe(ne(s).tree.parsedHeader[e]);return t&&t[0]||null}function Ys(s,e){let t=cu(s,e);return t&&t[2]?ut(t[2]):""}function Vn(s,e){let t=cu(s,e),r=t&&t[0]?ut(t[0]):"";return r||!t||!t[2]?r:ut(t[3]?t[2]+"@"+t[3]:t[2])}function Ks(s){let e=[].concat(s||[]).join(" "),t=[],r=0,n=!1,i=null;for(let o=0;o<e.length;o++){let a=e.charAt(o);if(n)a==="\\"?(i!==null&&(i+=e.charAt(o+1)),o++):a==='"'?n=!1:i!==null&&(i+=a);else if(r)a==="\\"?o++:a==="("?r++:a===")"&&r--;else if(a==='"')n=!0;else if(a==="(")r++;else if(a==="<")i="";else if(a===">"){if(i!==null){let u=i.lastIndexOf("@");u>0&&u<i.length-1&&t.push(i)}i=null}else i!==null&&!/\s/.test(a)&&(i+=a)}return t}function zs(s,e,t,r){let n=e.command.toUpperCase(),i=r[0];try{if(r.length<2)throw Q(n+" expects a charset and search criteria");if(!i||["ATOM","STRING"].indexOf(i.type)<0)throw Q("Charset must be an atom or a quoted string");let o=Ot(r.slice(1));if(s.searchCharset){if(i.value.toUpperCase()!==s.searchCharset)throw Q("Charset must be "+s.searchCharset+" in this session");return De(s,s.getSessionMessages(),o)}let a=["CHARSET",i.value].concat(o);return De(s,s.getSessionMessages(),a)}catch(o){return xt(s,e,t,o,n+" FAILED"),!1}}function ct(s){if(s.sortKeys)return;s.registerCapability("SORT"),s.sortKeys={ARRIVAL:r=>jn(r),CC:r=>He(Ys(r,"cc")),DATE:r=>Qs(r),FROM:r=>He(Ys(r,"from")),SIZE:r=>ne(r).raw.length,SUBJECT:r=>He(qs(ne(r).tree.parsedHeader.subject).subject),TO:r=>He(Ys(r,"to"))};let e=(r,n)=>b.Buffer.isBuffer(r)?b.Buffer.compare(r,n):r-n;s.sortComparator=r=>{let n=new WeakMap,i=o=>(n.has(o)||n.set(o,r.map(a=>s.sortKeys[a.key](o))),n.get(o));return(o,a)=>{let u=i(o),l=i(a);for(let c=0;c<r.length;c++){let f=e(u[c],l[c]);if(f)return r[c].reverse?-f:f}return o.uid-a.uid}};let t=(r,n,i,o,a)=>{let u=r?"UID SORT":"SORT",l=i.attributes||[],c=h=>(n.sendStatus(i,o,"BAD",h,!1,u+" FAILED"),a());if(!Array.isArray(l[0])||!l[0].length)return c(u+" expects a list of sort criteria");let f=[],p=!1;for(let h of l[0]){let d=h&&h.type==="ATOM"?h.value.toUpperCase():"";if(d==="REVERSE"&&!p){p=!0;continue}if(!Object.hasOwn(s.sortKeys,d))return c("Invalid sort criterion "+(h&&typeof h.value=="string"?h.value:""));f.push({key:d,reverse:p}),p=!1}if(p)return c("REVERSE must be followed by a sort key");let y=zs(n,i,o,l.slice(1));if(!y)return a();let A=s.sortComparator(f),m=y.list.slice().sort(A);return n.send({tag:"*",command:"SORT",attributes:m.map(h=>r?h.uid:y.numbers[h.uid])},u,i,o,Object.assign(y,{sorted:m,compare:A})),n.sendStatus(i,o,"OK",u+" completed",!1,u),a()};s.setCommandHandler("SORT",t.bind(null,!1),{states:Z.SELECTED,searchCriteria:2,noExpunge:!0}),s.setCommandHandler("UID SORT",t.bind(null,!0),{states:Z.SELECTED,searchCriteria:2})}var fu=s=>s==="SORT"||s==="UID SORT";function Qt(s){s.esortLoaded||(s.esortLoaded=!0,ct(s),Ie(s),s.registerCapability("ESORT"),s.acceptSearchReturn("SORT"),s.acceptSearchReturn("UID SORT"),s.searchReturnChecks.push((e,t,r,n)=>{if(!fu((r.command||"").toUpperCase())||s.contextSort)return!1;let i=["CONTEXT","UPDATE","PARTIAL"].find(o=>n.has(o)&&(o!=="PARTIAL"||!s.partialRangeLast));return!!i&&i+" is not supported for SORT"}),s.outputHandlers.push((e,t,r,n,i,o)=>{if(!n||!n.searchReturn||t.tag!=="*"||t.command!=="SORT"||!fu(r)||!o||!o.sorted)return;t.skipResponse=!0;let a=n.searchReturn;s.isSilentReturn(a)||e.send(Ct(n.tag,r==="UID SORT",o,a,null,o.sorted),"ESEARCH",n,i,Object.assign({},o,{list:je(o.sorted,a)}))}))}function qn(s){Qt(s),qt(s),s.registerCapability("CONTEXT=SORT"),s.contextSort=!0}g();var jf=new RegExp("^\\\\["+he["ATOM-CHAR"]().replace(/[\\\]^-]/g,"\\$&")+"]+$");function Qn(s){s.registerCapability("CREATE-SPECIAL-USE");let e=s.getCommandHandler("CREATE"),t=[].concat(s.options["special-use"]||["\\Archive","\\Drafts","\\Flagged","\\Junk","\\Sent","\\Trash"]);s.setCommandHandler("CREATE",(r,n,i,o)=>{let a,u,l,c=[];if(n.attributes&&Array.isArray(n.attributes[1])){for(a=0;a<n.attributes[1].length;a+=2)n.attributes[1][a]&&n.attributes[1][a].type==="ATOM"&&n.attributes[1][a].value.toUpperCase()==="USE"&&Array.isArray(n.attributes[1][a+1])&&(l=n.attributes[1][a+1],n.attributes[1].splice(a,2),a-=2);n.attributes[1].length||n.attributes.splice(1,1)}if(l)for(a=0,u=l.length;a<u;a++){let f=l[a];if(!J(f)||!jf.test(f.value))return r.send({tag:n.tag,command:"BAD",attributes:[{type:"TEXT",value:"Invalid syntax for special use flag #"+(a+1)}]},"CREATE-SPECIAL-USE FAILED",n,i),o();let p=t.find(y=>y.toLowerCase()===String(l[a].value).toLowerCase());if(!p)return r.send({tag:n.tag,command:"NO",attributes:[{type:"SECTION",section:[{type:"ATOM",value:"USEATTR"}]},{type:"TEXT",value:l[a].value+" not supported"}]},"CREATE-SPECIAL-USE FAILED",n,i),o();c.indexOf(p)<0&&c.push(p)}c.length&&(n.mailboxSpecialUse=c),e(r,n,i,o)}),s.outputHandlers.push((r,n,i,o,a,u)=>{i==="CREATE"&&u&&o.mailboxSpecialUse&&(u["special-use"]=o.mailboxSpecialUse)})}g();function Yn(s){s.registerCapability("ID"),s.setCommandHandler("ID",(e,t,r,n)=>{let i=Object.create(null),o=null,a,u,l="";if(!t.attributes||t.attributes.length!==1)return We("ID expects 1 attribute",e,t,r,n);let c=t.attributes[0];if(c&&!Array.isArray(c)||c&&c.length%2)return We("ID expects valid parameter list",e,t,r,n);if(c&&c.length>60)return We("ID allows at most 30 field-value pairs",e,t,r,n);if(c&&c.length)for(a=0,u=c.length;a<u;a++)if(a%2===0)if(c[a]&&["STRING","LITERAL"].indexOf(c[a].type)>=0){if(l=c[a].value,l.length>30)return We("ID field names can be at most 30 octets",e,t,r,n);if(Object.keys(i).some(f=>f.toLowerCase()===l.toLowerCase()))return We("ID field names must not repeat",e,t,r,n)}else return We("ID expects valid parameter list",e,t,r,n);else if(!c[a]||["STRING","LITERAL"].indexOf(c[a].type)>=0){if(c[a]&&c[a].value.length>1024)return We("ID values can be at most 1024 octets",e,t,r,n);i[l]=c[a]&&c[a].value||null}else return We("ID expects valid parameter list",e,t,r,n);if(s.options.id){let f=[];o=f,Object.keys(s.options.id).forEach(p=>{f.push({type:"STRING",value:p}),f.push({type:"STRING",value:(s.options.id[p]||"").toString()})})}e.send({tag:"*",command:"ID",attributes:[o]},"ID",t,r,i),e.send({tag:t.tag,command:"OK",attributes:[{type:"TEXT",value:"ID command completed"}]},"ID",t,r,i),n()},{states:Z.ANY})}function We(s,e,t,r,n){return e.send({tag:t.tag,command:"BAD",attributes:[{type:"TEXT",value:s}]},"INVALID COMMAND",t,r),n()}g();function Kn(s){s.registerCapability("IDLE"),s.setCommandHandler("IDLE",(e,t,r,n)=>{let i=setTimeout(()=>{e.socket&&!e.socket.destroyed&&(e.send({tag:"*",command:"BYE",attributes:[{type:"TEXT",value:"IDLE terminated"}]},"IDLE EXPIRED",t,r),e.end())},18e5);i.unref?.();let o=()=>clearTimeout(i),a=e.socket;return a&&a.once("close",o),e.directNotifications=!0,e.inputHandler=function(u){o(),a&&a.removeListener("close",o),e.inputHandler=!1,e.directNotifications=!1,u.toUpperCase()==="DONE"?e.send({tag:t.tag,command:"OK",attributes:[{type:"TEXT",value:"IDLE terminated"}]},"IDLE",t,r):e.send({tag:t.tag,command:"BAD",attributes:[{type:"TEXT",value:"Invalid Idle continuation"}]},"INVALID IDLE",t,r)},e.sendContinuation("idling","IDLE"),e.processNotifications(),n()},{states:Z.AUTHENTICATED,noArguments:!0})}g();g();var Vf=/[\u0000-\u001f\u007f-\u009f\u2028\u2029]|^\ufeff|\p{Cn}/u;function zn(s){let e=new Error(s);return e.imapResponse="BAD",e}function hu(s){if(s===!1||Vf.test(s))throw zn("Mailbox name must be valid Net-Unicode without control characters (RFC 9755 section 3)");if(s.normalize("NFC")!==s)throw zn("Mailbox name must be in Unicode Normalization Form C (RFC 5198 section 2, RFC 9051 section 5.1)");return s}function qf(s){let e=Tt(s);if(e)throw zn(e);return hu(On(s)),s}function Qf(s){let e=b.Buffer.from(s,"binary");return vs(hu(Ye(e)&&e.toString("utf-8")))}function Yf(s){let e=On(s);return e===!1?s:b.Buffer.from(e,"utf-8").toString("binary")}function wt(s){let e=s.server,t=ye(s,"UTF8=ACCEPT"),r=ye(s,"IMAP4rev2"),n=t||r;if(s.utf8Enabled=n,s.parserOptions.utf8=!!e.utf8Accept||r,s.compilerOptions.utf8=n,s.searchCharset=t?"UTF-8":!1,s.defaultSearchCharset=r?"UTF-8":!1,n)s.importMailboxName=Qf,s.exportMailboxName=Yf;else{let i=s;delete i.exportMailboxName,e.utf8Accept?s.importMailboxName=qf:delete i.importMailboxName}}g();function Yt(s){if(s.capabilities["LITERAL+"])throw new Error("LITERAL- can not be enabled together with LITERAL+");s.registerCapability("LITERAL-"),s.impliedLiteralMinus=!1,s.literalPlus=!0,s.nonSyncLiteralLimit=4096}var Wn="IMAP4rev2",Kf=new Set(["NEW","OLD","RECENT","UNRECENT"]),zf=new Set(["RECENT"]),Wf=new Set(["DELETED"]),$f=new Set(["RFC822","RFC822.HEADER","RFC822.TEXT"]),Jf=["$Forwarded","$MDNSent","$Junk","$NotJunk","$Phishing"],Nt=s=>!!s.imap4rev2,du=s=>s&&s.type==="ATOM"?String(s.value).toUpperCase():"";function Ws(s){s.registerCapability("IMAP4rev2"),Ne(s,Wn),!s.capabilities["LITERAL+"]&&!s.capabilities["LITERAL-"]&&(Yt(s),s.impliedLiteralMinus=!0),s.mailboxHandlers.push((a,u)=>{u.allowPermanentFlags||Jf.forEach(l=>a.ensureFlag(u.permanentFlags,l))});let e=a=>{let u=a.imap4rev2=ye(a,Wn);wt(a),a.messageGlobal=u,a.disabledSearchKeys=u?Kf:null,a.number64=a.parserOptions.number64=u,a.disabledStatusItems=u?zf:null,a.addedStatusItems=u?Wf:null,u?a.getFlags=l=>l.flags:delete a.getFlags};s.connectionHandlers.push(e),s.resetHandlers.push(e);let t=(a,u,l,c,f)=>(a.sendStatus(u,l,"BAD",f),c()),r=(a,u)=>{let l=s.getCommandHandler(a);s.setCommandHandler(a,(c,f,p,y)=>u(l,c,f,p,y))};Object.entries({CHECK:"NOOP",LSUB:"LIST (SUBSCRIBED)"}).forEach(([a,u])=>{r(a,(l,c,f,p,y)=>{if(Nt(c))return t(c,f,p,y,a+" is not part of IMAP4rev2, use "+u+" (RFC 9051 Appendix E)");l(c,f,p,y)})});let n=(a,u,l,c,f)=>{let p=(l.attributes||[])[1];if(Nt(u)&&[].concat(p||[]).some(y=>$f.has(du(y))))return t(u,l,c,f,"RFC822, RFC822.HEADER and RFC822.TEXT are not part of IMAP4rev2, use BODY[] (RFC 9051 Appendix E)");a(u,l,c,f)};r("FETCH",n),r("UID FETCH",n);let i=(a,u,l,c,f)=>{Nt(u)&&du((l.attributes||[])[0])!=="RETURN"&&(l.searchReturn=s.parseSearchReturn([],u,l)),a(u,l,c,f)};r("SEARCH",i),r("UID SEARCH",i),s.closedChecks.push(Nt);let o=(a,u,l,c)=>{let f=u.flags.concat(u["special-use"]||[]);a.send({tag:"*",command:"LIST",attributes:[f.map(p=>({type:"ATOM",value:p})),s.getSeparator(u),{type:"MAILBOX",value:u.path}]},"SELECT LIST",l,c,u)};s.outputHandlers.push((a,u,l,c,f)=>{if(l==="RECENT NOTIFICATION"&&Nt(a)){u.skipResponse=!0;return}if(!c||!u||!Nt(a))return;let p=String(c.command||"").toUpperCase();if(!(p!=="SELECT"&&p!=="EXAMINE")){if(l===p+" RECENT"||l===p+" UNSEEN"){u.skipResponse=!0;return}l===p&&u.tag===c.tag&&u.command==="OK"&&a.selectedMailbox&&o(a,a.selectedMailbox,c,f)}}),s.outputHandlers.push((a,u,l,c,f,p)=>{l==="ENABLED"&&Array.isArray(p)&&p.indexOf(Wn)>=0&&e(a)})}Ws.requires=["ENABLE","NAMESPACE","UNSELECT","UIDPLUS","ESEARCH","SEARCHRES","IDLE","SASL-IR","LIST-EXTENDED","LIST-STATUS","MOVE","BINARY","SPECIAL-USE","STATUS=SIZE","AUTH=PLAIN"];g();g();function $s(s,e){if(Object.is(s,e))return!0;if(!s||!e||typeof s!="object"||typeof e!="object"||Object.getPrototypeOf(s)!==Object.getPrototypeOf(e))return!1;if(s instanceof Map||s instanceof Set)return $s(Array.from(s),Array.from(e));let t=Object.keys(s);return t.length===Object.keys(e).length&&t.every(r=>Object.prototype.hasOwnProperty.call(e,r)&&$s(s[r],e[r]))}var Zf=s=>Array.isArray(s[0])||Array.isArray(s[1])||s.length>2;function Kt(s){let e=Ke(s);if(e.enabled)return;e.enabled=!0,s.registerCapability("LIST-EXTENDED"),e.selectionOptions.SUBSCRIBED={type:"base",returnOption:"SUBSCRIBED",includeNonExistent:!0,match:a=>!!a.subscribed},e.selectionOptions.REMOTE={type:"independent"},e.selectionOptions.RECURSIVEMATCH={type:"modifier"},e.returnOptions.SUBSCRIBED={},e.returnOptions.CHILDREN={};let t=(a,u,l,c)=>{let f=new Map;for(let p=0;p<a.length;p++){let y=a[p];if(!y||y.type!=="ATOM")throw new Error("Invalid "+l+" option");let A=y.value.toUpperCase(),m=u[A];if(!m)throw new Error("Unknown "+l+" option "+A);let h=!0;if(m.parse){if(!Array.isArray(a[p+1]))throw new Error(A+" "+l+" option requires a value");h=m.parse(a[++p],c)}else if(Array.isArray(a[p+1]))throw new Error(A+" "+l+" option takes no value");if(f.has(A)&&!$s(f.get(A),h))throw new Error(A+" "+l+" option is repeated with a different value");f.set(A,h)}return f},r=(a,u)=>{let l=new Map,c=new Map,f=0;Array.isArray(a[0])&&(l=t(a[0],e.selectionOptions,"selection",u),f++);let p=a[f],y=a[f+1],A=a.slice(f+2);if(!ue(p))throw new Error("LIST expects a reference name");if(y=Array.isArray(y)?y:[y],!y.length||!y.every(ue))throw new Error("LIST expects a mailbox pattern or a list of patterns");if(A.length){if(A.length!==2||!A[0]||A[0].type!=="ATOM"||A[0].value.toUpperCase()!=="RETURN"||!Array.isArray(A[1]))throw new Error("LIST expects RETURN and a list of return options after the patterns");c=t(A[1],e.returnOptions,"return",u)}let m=[...l.keys()].map(h=>e.selectionOptions[h].type);if(m.includes("modifier")&&!m.includes("base"))throw new Error("RECURSIVEMATCH must be used together with a selection option like SUBSCRIBED");return l.forEach((h,d)=>{let E=e.selectionOptions[d].returnOption;E&&!c.has(E)&&c.set(E,!0)}),{selection:l,reference:p.value,patterns:y.map(h=>h.value).filter(h=>h),returns:c}},n=a=>a.flags.indexOf("\\Noselect")<0,i=(a,u,l,c)=>s.listAttributes(a,{exists:u,subscribed:c.has("SUBSCRIBED")&&a.subscribed,hasChildren:l}).map(f=>({type:"ATOM",value:f})),o=s.getCommandHandler("LIST");s.setCommandHandler("LIST",(a,u,l,c)=>{let f=u.attributes||[];if(!Zf(f))return o(a,u,l,c);let p;try{p=r(f,a)}catch(H){return a.sendStatus(u,l,"BAD",H.message,!1,"INVALID COMMAND"),c()}let y=[...p.selection.keys()].map(H=>({name:H,...e.selectionOptions[H]})),A=y.filter(H=>H.match),m=y.some(H=>H.includeNonExistent),h=p.selection.has("RECURSIVEMATCH"),d=y.filter(H=>H.type==="base").map(H=>({type:"STRING",value:H.name})),E=H=>(m||n(H))&&A.every(N=>N.match(H,a)),I=s.folderCache;m&&(I=Object.assign(Object.create(null),I,s.getSubscriptionTree()));let C=new Set;return p.patterns.forEach(H=>{s.matchFolders(p.reference,H,N=>a.exportMailboxName(N),I).forEach(N=>C.add(N))}),C.forEach(H=>{let N=n(H),w=E(H),G=s.getDescendants(H.path,I),F=G.some(n),W=!1;if(h&&(W=G.some(v=>E(v)&&(w||!C.has(v)))),!(w||W||!A.length&&!N&&F))return;let L=[i(H,N,F,p.returns),s.getSeparator(H),a.exportMailboxName(H.path)];W&&L.push([{type:"STRING",value:"CHILDINFO"},d]),a.send({tag:"*",command:"LIST",attributes:L},"LIST ITEM",u,l,H),p.returns.forEach((v,V)=>{let _=e.returnOptions[V];_.onItem&&_.onItem(a,H,v,{matched:w,exists:N},u,l)})}),a.sendStatus(u,l,"OK","Completed",!1,"LIST"),c()})}g();g();var eh={MESSAGES:(s,e)=>e.messages.length,RECENT:(s,e,t)=>t.recent,UIDNEXT:(s,e)=>e.uidnext,UIDVALIDITY:(s,e)=>e.uidvalidity,UNSEEN:(s,e,t)=>t.unseen||0,DELETED:(s,e,t)=>t.flags["\\Deleted"]||0};function Js(s,e,t){if(!Array.isArray(e)||!e.length)throw new Error("Expecting a list of status items");let r=t&&t.disabledStatusItems,n=t&&t.addedStatusItems;return e.map((i,o)=>{let a=i&&i.type==="ATOM"&&i.value.toUpperCase();if(!a||s.allowedStatus.indexOf(a)<0&&!(n&&n.has(a))||r&&r.has(a))throw new Error("Invalid status element ("+(o+1)+")");return a})}function Zs(s,e,t,r,n,i){s.send(er(s,e,t,r),"STATUS",n,i)}function er(s,e,t,r){let n=s.server,i=n.getStatus(t),o=[];return r.forEach(a=>{o.push({type:"ATOM",value:a},(n.statusHandlers[a]||eh[a])(s,t,i))}),{tag:"*",command:"STATUS",attributes:[{type:"MAILBOX",value:e},o]}}function $n(s){Kt(s),s.registerCapability("LIST-STATUS"),Ke(s).returnOptions.STATUS={parse:(e,t)=>Js(s,e,t),onItem:(e,t,r,n,i,o)=>{n.matched&&n.exists&&Zs(e,t.path,t,r,i,o)}}}g();function Jn(s){if(s.capabilities["LITERAL-"]&&!s.impliedLiteralMinus)throw new Error("LITERAL+ can not be enabled together with LITERAL-");delete s.capabilities["LITERAL-"],s.registerCapability("LITERAL+"),s.literalPlus=!0,s.nonSyncLiteralLimit=1/0}g();function Zn(s){s.registerCapability("LOGINDISABLED",t=>!t.secureConnection&&t.state==="Not Authenticated");let e=s.getCommandHandler("LOGIN");s.setCommandHandler("LOGIN",(t,r,n,i)=>{if(!t.secureConnection)return t.send({tag:r.tag,command:"NO",attributes:[{type:"SECTION",section:[{type:"ATOM",value:"PRIVACYREQUIRED"}]},{type:"TEXT",value:"Run STARTTLS first"}]},"LOGIN FAILED",r,n),i();e(t,r,n,i)})}g();var th=1e3,sh=new Set(["FETCH","UID FETCH","STORE","UID STORE","MOVE","UID MOVE","UID EXPUNGE"]),rh=new Set(["SEARCH","UID SEARCH"]),pu=new Set(["SORT","UID SORT","THREAD","UID THREAD"]);function ei(s,e){if(s.messageLimit)throw new Error(e+" can not be enabled together with "+s.messageLimit.name);let t="messageLimit"in s.options?s.options.messageLimit:th;if(!Number.isSafeInteger(t)||t<1||t>4294967295)throw new TypeError("Invalid messageLimit option, expecting a positive integer");return s.messageLimit={name:e,limit:t},t}function ti(s,e){s.appendChecks.push((t,r,n,i)=>{if(n.length<=e)return!1;if(i.command)return{code:["MESSAGELIMIT",e],text:i.command+" exceeds the limit of "+e+" messages, nothing was appended"};if(!i.move){let o=n[n.length-e].uid;return{code:["MESSAGELIMIT",e,o],text:"Too many messages to copy, try a smaller subset"}}return!1})}function si(s){let e=ei(s,"MESSAGELIMIT");s.registerCapability("MESSAGELIMIT="+e),ti(s,e);let t=a=>String(a.command||"").toUpperCase();s.rangeLimits.push((a,u,l)=>{let c=t(u);if(!sh.has(c)||u.partialFetch)return!1;let f=c==="UID EXPUNGE"?l.filter(y=>y[1].flags.indexOf("\\Deleted")>=0):l;if(f.length<=e)return!1;let p=new Set(f.slice(0,-e));return u.messageLimitUid=f[f.length-e][1].uid,u.highestFirst=!0,l.filter(y=>!p.has(y)).reverse()}),s.commandChecks.push((a,u)=>{let l=s.capabilities.PARTIAL&&u.attributes&&u.attributes[2],c=t(u);if(!Array.isArray(l)||c!=="FETCH"&&c!=="UID FETCH")return!1;let f=l.findIndex((y,A)=>!(A%2)&&y&&y.type==="ATOM"&&String(y.value).toUpperCase()==="PARTIAL"),p;try{p=f>=0&&Vt(l[f+1],!0)}catch{return!1}return p&&p.to-p.from+1>e?{command:"NO",code:["MESSAGELIMIT",e],text:c+" exceeds the limit of "+e+" messages"}:!1}),s.searchLimits.push((a,u,l)=>{let c=a._runningCommand&&a._runningCommand.parsed,f=c?t(c):"";if(u.length<=e||!rh.has(f)&&!pu.has(f))return!1;let p=u.filter(y=>mu(l,y));if(p.length<=e)return!1;if(pu.has(f)){let y=new Error(f+" exceeds the limit of "+e+" messages, narrow it down with UIDAFTER or UIDBEFORE");throw y.imapResponse="NO",y.responseCode=["MESSAGELIMIT",e],y}return c.messageLimitUid=p[p.length-e].uid,p.slice(-e)});let r=a=>{if(!Le(a))throw Q("UIDAFTER and UIDBEFORE expect a UID");return Number(a)},n=(a,u,l,c)=>u.uid>c;n.argumentTypes=()=>[r];let i=(a,u,l,c)=>u.uid<c;i.argumentTypes=()=>[r],s.searchHandlers.UIDAFTER=n,s.searchHandlers.UIDBEFORE=i;let o=(a,u,l,c,f)=>{if(c&&c.messageLimitUid&&u.tag==="*"&&u.command==="SEARCH"&&Array.isArray(u.attributes)){let m=u.attributes.filter(Array.isArray);u.attributes=u.attributes.filter(h=>!Array.isArray(h)).reverse().concat(m);return}if(!c||!c.messageLimitUid||u.tag!==c.tag)return;let p=c.messageLimitUid;if(c.messageLimitUid=!1,u.command!=="OK")return;let y={type:"SECTION",section:[{type:"ATOM",value:"MESSAGELIMIT"},e,p]},A=u.attributes||[];if(A[0]&&A[0].type==="SECTION"){a.send({tag:"*",command:"NO",attributes:[y,{type:"TEXT",value:"Only the last "+e+" messages were processed"}]},"MESSAGELIMIT",c,f);return}u.attributes=[y].concat(A)};s.once("pluginsLoaded",()=>s.outputHandlers.push(o))}function mu(s,e){return s.args.every(t=>{switch(t.key){case"AND":return mu(t,e);case"_SEQ":case"UID":return t.set.has(e);case"UIDAFTER":return e.uid>t.args[0];case"UIDBEFORE":return e.uid<t.args[0];default:return!0}})}g();var nh=64*1024,ih=100,oh=new Set(["/shared/admin"]),ah="/private/specialuse";function tr(s,e){if(typeof s!="string"||s.charAt(0)!=="/")return'Entry name must begin with "/"';if(/[^\x20-\x7f]/.test(s))return"Entry name must not contain non-ASCII or control characters";if(/[*%]/.test(s))return'Entry name must not contain "*" or "%"';if(s.indexOf("//")>=0)return'Entry name must not contain consecutive "/" characters';if(s.charAt(s.length-1)==="/")return'Entry name must not end with "/"';let t=s.toLowerCase().substr(1).split("/");return t[0]!=="private"&&t[0]!=="shared"?"Entry name must begin with /private or /shared":e&&t.length<2?"Entry name must have at least 2 components":e&&t[1]==="vendor"&&t.length<4?"Vendor entry names must have at least 4 components":!1}function uh(s,e){if(e==null)return null;if(e instanceof Uint8Array)e=b.Buffer.from(e).toString("binary");else if(typeof e=="string")/[Ā-￿]/.test(e)&&(e=b.Buffer.from(e,"utf-8").toString("binary"));else throw new Error("Invalid value for metadata entry "+s+", expecting a string");return e}function gu(s){return{type:"MAILBOX",value:s}}function ri(s,e){if(s.metadataState){e&&!s.metadataState.mailboxes&&(s.metadataState.mailboxes=!0,delete s.capabilities["METADATA-SERVER"],s.registerCapability("METADATA"),s.enableAvailable.splice(s.enableAvailable.indexOf("METADATA-SERVER"),1,"METADATA"));return}s.parserOptions.literal8=!0;let t=e?"METADATA":"METADATA-SERVER";s.registerCapability(t),Ne(s,t);let r=s.options,n=s.metadataState={mailboxes:e,maxSize:Number(r.metadataMaxSize)||nh,maxEntries:Number(r.metadataMaxEntries)||ih,allowPrivate:r.metadataPrivate!==!1,server:{path:"",metadata:r.metadata}},i=new WeakSet,o=h=>{if(!h.metadata)return Object.create(null);if(i.has(h.metadata))return h.metadata;let d=Object.create(null),E=h.metadata;return Object.keys(E).forEach(I=>{let C=tr(I,!0);if(C)throw new Error("Invalid metadata entry name "+JSON.stringify(I)+": "+C);let H=uh(I,E[I]);H!==null&&(d[I.toLowerCase()]=H)}),a(h,d)},a=(h,d)=>(i.add(d),h.metadata=d,d),u=h=>{let d=Object.create(null);if(h.path&&s.capabilities["SPECIAL-USE"]){let E=[].concat(h["special-use"]||[]);d[ah]=E.length?E.join(" "):null}return d},l=h=>ye(h,n.mailboxes?"METADATA":"METADATA-SERVER"),c=(h,d,E,I)=>{if(I==="")return n.server;if(!n.mailboxes)return h.sendStatus(d,E,"NO","Mailbox annotations are not supported, only server annotations"),!1;let C=h.server.getMailbox(I);return!C||C.flags.indexOf("\\NonExistent")>=0?(h.sendStatus(d,E,"NO","Mailbox does not exist","NONEXISTENT"),!1):C},f=(h,d,E,I,C)=>(h.sendStatus(d,E,"BAD",I),C());s.setCommandHandler("GETMETADATA",(h,d,E,I)=>{let C=d.attributes||[],H=Array.isArray(C[0])?1:0,N=!1,w=0;if(C.length!==H+2||!ue(C[H]))return f(h,d,E,"GETMETADATA expects options, a mailbox name and entries",I);if(H){let X=C[0];if(!X.length)return f(h,d,E,"Empty option list",I);for(let q=0;q<X.length;q+=2){let se=X[q]&&X[q].type==="ATOM"?X[q].value.toUpperCase():!1,ee=X[q+1]&&X[q+1].type==="ATOM"?X[q+1].value:!1;if(se==="MAXSIZE"){if(!Ae(ee))return f(h,d,E,"Invalid value for MAXSIZE",I);N=Number(ee)}else if(se==="DEPTH"){if(!ee||!/^(0|1|infinity)$/i.test(ee))return f(h,d,E,"Invalid value for DEPTH",I);w=ee.toLowerCase()==="infinity"?1/0:Number(ee)}else return f(h,d,E,"Unknown GETMETADATA option",I)}}let G;try{G=h.importMailboxName(C[H].value)}catch(X){return f(h,d,E,X.message,I)}let F=[].concat(C[H+1]);if(!F.length||!F.every(ue))return f(h,d,E,"GETMETADATA expects an entry name or a list of entry names",I);for(let X of F){let q=tr(X.value);if(q)return f(h,d,E,q,I)}let W=c(h,d,E,G);if(!W)return I();let x=Object.assign(Object.create(null),o(W),u(W)),L=w?Object.keys(x).filter(X=>x[X]!==null).sort():[],v=new Map;for(let X of F){let q=X.value.toLowerCase(),se=x[q]??null;(!w||se!==null)&&v.set(q,se);let ee=q+"/";L.forEach(fe=>{fe.startsWith(ee)&&(w===1/0||fe.indexOf("/",ee.length)<0)&&v.set(fe,x[fe])})}let V=-1,_=[];return v.forEach((X,q)=>{if(N!==!1&&X!==null&&X.length>N){V=Math.max(V,X.length);return}_.push({type:"ATOM",value:q},X===null?null:{type:X.indexOf("\0")>=0?"LITERAL8":"STRING",value:X})}),_.length&&h.send({tag:"*",command:"METADATA",attributes:[gu(W.path),_]},"METADATA",d,E,W),h.sendStatus(d,E,"OK","GETMETADATA completed",V>=0&&["METADATA","LONGENTRIES",V]),I()},{states:Z.AUTHENTICATED});let p=(h,d)=>{let E=s.activeConnection,I=o(h),C=u(h),H=Object.assign(Object.create(null),I),N=[];for(let[G,F]of d){if(!h.path&&E&&oh.has(G)||G in C)return{text:"The "+G+" entry is read-only",code:"CANNOT"};if(!n.allowPrivate&&G.startsWith("/private/"))return{text:"Private annotations are not supported",code:["METADATA","NOPRIVATE"]};if(F!==null&&F.length>n.maxSize)return{text:"Value of "+G+" is too large",code:["METADATA","MAXSIZE",n.maxSize]};(I[G]??null)!==F&&N.push(G),F===null?delete H[G]:H[G]=F}let w=Object.keys(H).length;return w>n.maxEntries&&w>Object.keys(I).length?{text:"Too many annotations",code:["METADATA","TOOMANY"]}:(a(h,H),N.length&&s.notify({tag:"*",command:"METADATA",attributes:[gu(h.path)].concat(N.map(G=>({type:"ATOM",value:G})))},!1,E,l),null)};s.setCommandHandler("SETMETADATA",(h,d,E,I)=>{let C=d.attributes||[];if(C.length!==2||!ue(C[0])||!Array.isArray(C[1]))return f(h,d,E,"SETMETADATA expects a mailbox name and a list of entries and values",I);let H=C[1];if(!H.length||H.length%2)return f(h,d,E,"SETMETADATA expects entry and value pairs",I);let N=new Map;for(let F=0;F<H.length;F+=2){if(!ue(H[F]))return f(h,d,E,"Entry name must be a string",I);let W=tr(H[F].value,!0);if(W)return f(h,d,E,W,I);let x=H[F+1];if(x!==null&&(!x||["STRING","LITERAL","LITERAL8"].indexOf(x.type)<0))return f(h,d,E,"Entry value must be a string, a literal, a literal8 or NIL",I);if(x&&x.type!=="LITERAL8"&&/\r(?!\n)|(?:^|[^\r])\n/.test(x.value))return f(h,d,E,"Line ends in a value must be CRLF",I);N.set(H[F].value.toLowerCase(),x?x.value:null)}let w=c(h,d,E,C[0].value);if(!w)return I();let G=p(w,N);return G?(h.sendStatus(d,E,"NO",G.text,G.code),I()):(h.sendStatus(d,E,"OK","SETMETADATA completed"),I())},{states:Z.AUTHENTICATED,mailboxArguments:[0],literal8:!0}),s.on("mailbox",h=>{if(h.type==="rename"&&h.oldPath==="INBOX"){let d=s.getMailbox("INBOX"),E=s.getMailbox(h.path);d&&E&&E!==d&&d.metadata&&a(E,Object.assign(Object.create(null),o(d)))}else if(h.type==="delete"){let d=s.getMailbox(h.path);d&&d!==h.mailbox&&delete d.metadata}}),s.on("reset",()=>{n.server={path:"",metadata:r.metadata}});let y=h=>{if(h==="")return n.server;if(!n.mailboxes)throw K("Mailbox annotations need the METADATA plugin, METADATA-SERVER has server annotations only","INVALID");return s.control.requireMailbox(h)},A=h=>{let d=o(y(h)),E={};return Object.keys(d).forEach(I=>{E[I]=b.Buffer.from(d[I],"binary").toString("utf-8")}),E},m=(h,d)=>{let E=y(h);if(!d||typeof d!="object"||Array.isArray(d))throw K("setMetadata expects an object of entry names and values (null removes an entry)","INVALID");let I=new Map;Object.keys(d).forEach(H=>{let N=d[H],w=tr(H,!0);if(w)throw K(w,"INVALID");if(N!==null&&typeof N!="string")throw K("Value of "+H+" must be a string or null","INVALID");I.set(H.toLowerCase(),N===null?null:b.Buffer.from(N,"utf-8").toString("binary"))});let C=p(E,I);if(C)throw K(C.text,typeof C.code=="string"?C.code:"INVALID");return A(h)};s.control.register("getMetadata",A,[{method:"GET",path:"/v1/metadata",summary:"Server annotations (METADATA plugins)",handler:()=>s.control.getMetadata("")},{method:"GET",path:"/v1/mailboxes/{path}/metadata",summary:"Mailbox annotations (METADATA plugin)",handler:({params:h})=>s.control.getMetadata(h.path)}]),s.control.register("setMetadata",m,[{method:"PUT",path:"/v1/metadata",summary:'Sets server annotations ({ "/shared/comment": "text" }, null removes one, METADATA plugins)',handler:({body:h})=>s.control.setMetadata("",h)},{method:"PUT",path:"/v1/mailboxes/{path}/metadata",summary:"Sets mailbox annotations (METADATA plugin)",handler:({params:h,body:d})=>s.control.setMetadata(h.path,d)}])}function sr(s){ri(s,!0)}sr.requires=["ENABLE"];g();function rr(s){ri(s,!1)}rr.requires=["ENABLE"];g();g();function ni(s,e,t,r){return ii(s,e,t,r,!1)}function ii(s,e,t,r,n){let i=n?"UID COPY":"COPY";if(!e.attributes||e.attributes.length!==2||!e.attributes[0]||["ATOM","SEQUENCE"].indexOf(e.attributes[0].type)<0||!e.attributes[1]||["ATOM","STRING","LITERAL"].indexOf(e.attributes[1].type)<0)return s.send({tag:e.tag,command:"BAD",attributes:[{type:"TEXT",value:i+" expects sequence set and a mailbox name"}]},"INVALID COMMAND",e,t),r();let o=oi(s,e,t,n,i+" FAIL");if(!o)return r();s.send({tag:e.tag,command:"OK",attributes:[{type:"TEXT",value:i+" Completed"}]},i,e,t,o),r()}function oi(s,e,t,r,n,i){let o=e.attributes,a=s.limitRange(e,s.getCommandRange(o[0].value,r)),u=s.getTargetMailbox(o[1].value,e,t,n);if(!u)return!1;let l=a.map(p=>p[1]);if(l.some(p=>p.ghost))return s.sendStatus(e,t,"NO","Some of the requested messages no longer exist","EXPUNGEISSUED",n),!1;if(!s.checkAppend(u,l,e,t,n,{move:!!i,source:s.selectedMailbox}))return!1;let c=[],f=[];return(e.highestFirst?l.slice().reverse():l).forEach(p=>{c.push(p.uid),f.push(s.server.copyMessage(u,p).message.uid)}),{mailbox:u,sourceUids:c,targetUids:f,messages:l}}function ai(s){s.registerCapability("MOVE");let e=function(r,n,i,o,a){function u(c){return r?"UID "+c:c}if(!i.attributes||i.attributes.length!==2||!i.attributes[0]||["ATOM","SEQUENCE"].indexOf(i.attributes[0].type)<0||!i.attributes[1]||["ATOM","STRING","LITERAL"].indexOf(i.attributes[1].type)<0)return n.send({tag:i.tag,command:"BAD",attributes:[{type:"TEXT",value:u("MOVE expects sequence set and a mailbox name")}]},"INVALID COMMAND",i,o),a();if(n.refuseReadOnly(i,o,u("MOVE FAIL")))return a();let l=oi(n,i,o,r,u("MOVE FAIL"),!0);if(!l)return a();n.send({tag:"*",command:"OK",attributes:[{type:"TEXT",value:"Copied"}],skipResponse:!0},u("MOVE COPYUID"),i,o,l),n.expungeSpecificMessages(n.selectedMailbox,l.messages,!1,!0,!!i.highestFirst),n.send({tag:i.tag,command:"OK",attributes:[{type:"TEXT",value:"Done"}]},u("MOVE OK"),i,o),a()},t={states:Z.SELECTED,mailboxArguments:[1]};s.setCommandHandler("MOVE",e.bind(null,!1),Object.assign({sequenceSet:0},t)),s.setCommandHandler("UID MOVE",e.bind(null,!0),t)}g();function ui(s){s.registerCapability("MULTIAPPEND"),s.multiAppend=!0,s.appendChecks.push((e,t,r,n)=>n.command&&r.some(i=>!i.resolve&&!i.raw.length)?{text:"Zero-length message literal, APPEND cancelled"}:!1)}g();var Eu={SELECTED:!1,INBOXES:!1,PERSONAL:!1,SUBSCRIBED:!1,SUBTREE:!0,"SUBTREE-ONE":!0,MAILBOXES:!0};function lh(s,e){if(!Array.isArray(e)||!e.length)throw Q("IN expects a parenthesized list of mailbox specifiers");let t=[];for(let r=0;r<e.length;r++){let n=e[r];if(Array.isArray(n))throw Q("Unknown ESEARCH scope option");let i=n&&n.type==="ATOM"?String(n.value).toUpperCase():"";if(!Object.hasOwn(Eu,i))throw Q("Invalid mailbox specifier"+(i?" "+n.value:""));let o={filter:i,names:[]};if(Eu[i]){let a=e[++r],u=Array.isArray(a)?a:[a];if(!u.length||!u.every(ue))throw Q(i.toLowerCase()+" expects a mailbox name or a list of mailbox names");u.forEach(l=>o.names.push(s.importMailboxName(l.value)))}t.push(o)}return t}function ch(s,e){let t=e||[];return J(t[0],"IN")?{sources:lh(s,t[1]),attributes:t.slice(2)}:{sources:null,attributes:t}}function li(s){Ie(s),s.registerCapability("MULTISEARCH");let e=o=>!!o&&o.flags.indexOf("\\Noselect")<0,t=()=>Object.keys(s.folderCache).map(a=>s.folderCache[a]).sort((a,u)=>a.path==="INBOX"?-1:u.path==="INBOX"?1:0),r=(o,a,u)=>{if(!u(o)||!a||!o.folders)return;let l=o.folders;Object.keys(l).forEach(c=>r(l[c],a-1,u))},n=(o,a)=>{let u=[],l=new Set,c=(f,p)=>{!f||l.has(f)||!e(f)||s.searchAccessChecks.every(y=>y(o,f,!!p))&&(l.add(f),u.push(f))};return a.forEach(f=>{switch(f.filter){case"SELECTED":c(o.selectedMailbox,!0);break;case"INBOXES":c(s.getMailbox("INBOX"),!1);break;case"PERSONAL":t().filter(p=>s.isPersonal(p)).forEach(p=>c(p,!1));break;case"SUBSCRIBED":t().filter(p=>p.subscribed).forEach(p=>c(p,!1));break;case"MAILBOXES":f.names.forEach(p=>c(s.getMailbox(p),!0));break;default:{let p=f.filter==="SUBTREE"?1/0:1,y=new Set;f.names.forEach(A=>{let m=s.getMailbox(A);m&&r(m,p,h=>y.has(h)?!1:(y.add(h),c(h,h===m),!0))})}}}),u},i=(o,a,u,l)=>{let c=(I,C)=>(o.sendStatus(a,u,I,C,!1,"ESEARCH FAILED"),l()),f,p=new Map,y;try{let I=ch(o,a.attributes);f=I.sources||[{filter:"SELECTED",names:[]}];let C=I.attributes;if(J(C[0],"RETURN")&&(p=a.searchReturn=s.parseSearchReturn(C[1],o,a),C=C.slice(2)),!C.length)throw Q("ESEARCH expects search criteria");y=Ot(C)}catch(I){return c("BAD",I.message)}let A=f.every(I=>I.filter==="SELECTED");if(f.some(I=>I.filter==="SELECTED")&&!o.selectedMailbox)return c("BAD","No mailbox is selected");if(p.has("SAVE")&&!A)return c("BAD","SAVE can only be used when searching the selected mailbox");if(p.has("UPDATE")&&!o.selectedMailbox)return c("BAD","UPDATE needs a selected mailbox");let m=n(o,f),h=[];try{let I=C=>{if(C&&C===o.selectedMailbox)return De(o,o.getSessionMessages(),y);let H=C?C.messages:[];return De(o,H,y,(N,w)=>s.getMessageRange(H,N,w))};m.length||I(o.selectedMailbox||null),m.forEach(C=>h.push({mailbox:C,result:I(C)}))}catch(I){return xt(o,a,u,I,"ESEARCH FAILED"),l()}let d=s.isSilentReturn(p);h.forEach(({mailbox:I,result:C})=>{!C.list.length||d||o.send(Ct(a.tag,!0,C,p,I),"ESEARCH",a,u,Object.assign({},C,{list:je(C.list,p)}))});let E=h.find(I=>I.mailbox===o.selectedMailbox);return p.has("SAVE")&&(a.searchresFound=E?je(E.result.list,p):[]),p.has("UPDATE")&&E&&s.addSearchContext(o,a,u,E.result,!0,E.mailbox),o.sendStatus(a,u,"OK","ESEARCH completed",!1,"ESEARCH"),l()};s.setCommandHandler("ESEARCH",i,{states:Z.AUTHENTICATED,searchCriteria:0}),s.connectionHandlers.push(o=>{let a=o.usesSequenceNumbers;o.usesSequenceNumbers=function(u){return(u.command||"").toUpperCase()==="ESEARCH"&&J((u.attributes||[])[0],"IN")&&(u=Object.assign({},u,{attributes:u.attributes.slice(2)})),a.call(this,u)}})}g();function ci(s){s.registerCapability("NAMESPACE"),s.setCommandHandler("NAMESPACE",(e,t,r,n)=>{let i={personal:[],user:[],shared:[]};return Object.keys(s.storage).forEach(o=>{let a=s.storage[o];o==="INBOX"||!a||Object.hasOwn(i,a.type)&&i[a.type].push([e.exportMailboxName(o),a.separator])}),e.send({tag:"*",command:"NAMESPACE",attributes:[i.personal.length?i.personal:null,i.user.length?i.user:null,i.shared.length?i.shared:null]},"NAMESPACE",t,r,i),e.send({tag:t.tag,command:"OK",attributes:[{type:"TEXT",value:"Completed"}]},"NAMESPACE",t,r,i),n()},{states:Z.AUTHENTICATED,noArguments:!0})}g();var nr=["MessageNew","MessageExpunge","FlagChange","AnnotationChange"],fh=new Map(nr.concat(["MailboxName","SubscriptionChange","MailboxMetadataChange","ServerMetadataChange"]).map(s=>[s.toUpperCase(),s])),hh=["SELECTED","SELECTED-DELAYED"],dh=["INBOXES","PERSONAL","SUBSCRIBED","SUBTREE","MAILBOXES"],ph=["BODY","BODY.PEEK","BINARY","BINARY.PEEK","BINARY.SIZE"];function fi(s){s.registerCapability("NOTIFY");let e=x=>!!x.notifyState,t=()=>{let x=["MessageNew","MessageExpunge","FlagChange","MailboxName","SubscriptionChange"];return s.capabilities.METADATA&&x.push("MailboxMetadataChange"),(s.capabilities.METADATA||s.capabilities["METADATA-SERVER"])&&x.push("ServerMetadataChange"),x},r=(x,L,v,V)=>{let _=s.acl&&s.acl.getRights(x,L,V);return!_||[...v].every(X=>_.has(X))},n=(x,L,v)=>r(x,L,"l",v),i=(x,L,v)=>r(x,L,"lr",v),o=x=>x.toUpperCase()==="INBOX"?"INBOX":x,a=(x,L,v,V)=>{switch(x.filter){case"INBOXES":case"PERSONAL":return s.isPersonal(L);case"SUBSCRIBED":return!!V||!!(v&&v.subscribed);case"SUBTREE":return x.paths.indexOf(L)>=0||x.prefixes.some(_=>L.substr(0,_.length)===_);case"MAILBOXES":return x.paths.indexOf(L)>=0}return!1},u=(x,L,v,V)=>{let _=new Set;return x.notifyState.groups.forEach(X=>{a(X,L,v,V)&&X.events.forEach(q=>_.add(q))}),v&&v===x.selectedMailbox&&nr.forEach(X=>_.delete(X)),_},l=x=>!!(x.notifyState.selected&&x.notifyState.selected.delayed)&&!x.directNotifications&&x.hasPendingExpunge(),c=x=>{!x.socket||!x.notificationQueue.length||x._runningCommand||!e(x)||l(x)||x.processNotifications()},f=x=>{x.notifyFlushPending||(x.notifyFlushPending=!0,R(()=>{x.notifyFlushPending=!1,c(x)}))},p=(x,L)=>{let v=L;if(v.tag="*",v.notification=!0,!x._runningCommand&&l(x)){x.send(v,"NOTIFY EVENT");return}x.notificationQueue.push(v),f(x)},y=x=>[...s.connections].filter(L=>L!==x&&e(L)),A=(x,L,v,V)=>{if(v=v.slice(),V.has("FlagChange")){let _=s.getStatus(L),X=_&&_.unseen||0;x.notifyState.unseen.get(L)!==X&&(x.notifyState.unseen.set(L,X),v.push("UNSEEN"))}return s.condstore&&s.condstore.isEnabled(x)&&v.push("HIGHESTMODSEQ"),v.length?er(x,L.path,L,v):!1},m=(x,L,v,V)=>{y(V).forEach(_=>{if(x===_.selectedMailbox||!i(_,x))return;let X=u(_,x.path,x);if(!X.has(L))return;let q=A(_,x,L==="FlagChange"&&s.condstore&&s.condstore.isEnabled(_)?["UIDVALIDITY"]:v,X);q&&p(_,q)})},h=(x,L)=>s.hasDescendant(L,v=>n(x,v)&&v.flags.indexOf("\\NonExistent")<0),d=(x,L,v)=>{v=v||{};let V=s.getMailbox(L),_=v.exists!==!1&&!!V&&n(x,V),q=[s.listAttributes(_?V:null,{exists:_,subscribed:_&&V.subscribed,extra:v.noAccess?["\\NoAccess"]:[],hasChildren:h(x,L)}).map(se=>({type:"ATOM",value:se})),s.getSeparator(L),{type:"MAILBOX",value:L}];return v.oldPath&&q.push([{type:"STRING",value:"OLDNAME"},[{type:"STRING",value:x.exportMailboxName(v.oldPath)}]]),{tag:"*",command:"LIST",attributes:q}},E=(x,L,v,V)=>{[L,s.getParentPath(L)].forEach(_=>{if(!_)return;let X=_===L?v:s.getMailbox(_);u(x,_,X).has("MailboxName")&&p(x,d(x,_,_===L?{exists:V}:{}))})},I=(x,L)=>{L!==x.selectedMailbox&&i(x,L)&&u(x,L.path,L).has("FlagChange")&&p(x,A(x,L,["MESSAGES","UIDNEXT","UIDVALIDITY"],new Set(["FlagChange"])))};s.on("mailbox",x=>{let L=s.getMailbox(x.path);y(x.origin).forEach(v=>{switch(x.type){case"create":L&&n(v,L)&&(E(v,x.path,L,!0),I(v,L));break;case"delete":x.mailbox&&n(v,x.mailbox)&&E(v,x.path,L,!!L);break;case"rename":if(L&&n(v,L)){let V=u(v,x.path,L);u(v,x.oldPath).forEach(_=>V.add(_)),V.has("MailboxName")&&p(v,d(v,x.path,{oldPath:x.oldPath})),I(v,L)}break;case"subscribe":case"unsubscribe":L&&n(v,L)&&u(v,x.path,L,!0).has("SubscriptionChange")&&p(v,d(v,x.path));break}})}),s.on("acl",(x,L)=>{y(null).forEach(v=>{let V={list:n(v,x,L),read:i(v,x,L)},_={list:n(v,x),read:i(v,x)};if(V.list!==_.list)E(v,x.path,x,_.list);else if(_.list&&V.read!==_.read){let X=u(v,x.path,x);nr.some(q=>X.has(q))&&p(v,d(v,x.path,{noAccess:!_.read}))}})}),s.on("expunge",(x,L,v)=>m(x,"MessageExpunge",["MESSAGES","UIDNEXT"],v)),s.on("notify",x=>{let L=x.command||{},v=typeof x.mailbox=="string"?s.getMailbox(x.mailbox):x.mailbox;if(v&&L.flagUpdate)m(v,"FlagChange",[],x.origin);else if(v&&L.message&&J(L.attributes&&L.attributes[1],"EXISTS"))m(v,"MessageNew",["MESSAGES","UIDNEXT"],x.origin);else if(L.command==="METADATA"&&L.attributes&&L.attributes[0]){let V=L.attributes[0].value,_=V===""?null:s.getMailbox(V);y(x.origin).forEach(X=>{let q;V===""?q=X.notifyState.groups.some(se=>se.events.has("ServerMetadataChange")):q=!!_&&i(X,_)&&u(X,V,_).has("MailboxMetadataChange"),q&&(x.notifyHandled=x.notifyHandled||new Set,x.notifyHandled.add(X),p(X,Object.assign({},L)))})}}),s.notifyFilters.push((x,L)=>!(L.notifyHandled&&L.notifyHandled.has(x)));let C=x=>{if(x.flagUpdate)return"FlagChange";let L=x.attributes&&x.attributes[1];return J(L,"EXPUNGE")?"MessageExpunge":J(L,"EXISTS")?x.message?"MessageNew":"MessageExpunge":!1},H=(x,L,v,V)=>{let _=L.map(q=>Object.assign({},q)),X;try{X=Bs(x,V,_)}catch{return!1}return{tag:"*",notification:!0,attributes:[v,{type:"ATOM",value:"FETCH"},X],fetchedMessage:V}};s.connectionHandlers.push(x=>{x.notifyState=null;let L=x.queueNotification;x.queueNotification=function(v,V){let _=V&&V.mailbox&&C(v);if(!e(this)||!_||V.origin===this)return L.call(this,v,V);let X=this.notifyState.selected;if(!(!X||!X.events.has(_)||!i(this,this.selectedMailbox))){if(this.notificationQueue.push(v),_==="MessageNew"&&X.fetch){let q=H(this,X.fetch,v.attributes[0],v.message);q&&this.notificationQueue.push(q)}f(this)}}}),s.resetHandlers.push(x=>{x.notifyState=null}),s.outputHandlers.push((x,L)=>{L.tag!=="*"&&!L.notification&&e(x)&&x.notificationQueue.length&&f(x)}),s.notifyOverflow=x=>{y(null).filter(L=>!x||L===x).forEach(L=>{L.notifyState={selected:null,groups:[],unseen:new WeakMap},p(L,{command:"OK",attributes:[{type:"SECTION",section:[{type:"ATOM",value:"NOTIFICATIONOVERFLOW"}]},{type:"TEXT",value:"Too many notifications, NOTIFY is turned off"}]})})};let N=(x,L)=>{if(!L.length)throw Q("MessageNew expects a list of fetch attributes");return L.map(v=>{let V=J(v)&&v.value.toUpperCase();if(!V||!(s.fetchHandlers[V]||Te[V]))throw Q("Invalid fetch attribute for MessageNew");if((v.section||v.partial)&&ph.indexOf(V)>=0){let _=[Object.assign({},v)];try{Bs(x,{raw:`Subject: test\r
25
+ `),n.header=n.header.filter(a=>!/^content-transfer-encoding\s*:/i.test(a)).concat("Content-Transfer-Encoding: base64"),!0)},r=t(e)?Be(e):s;if(r.indexOf("\0")>=0)throw _a("NUL octets are only allowed in the body of a part with the binary, 7bit or 8bit encoding");return r}function In(s){s.registerCapability("BINARY"),s.parserOptions.literal8=!0,s.parserOptions.allowSection.push("BINARY","BINARY.PEEK","BINARY.SIZE"),s.fetchHandlers.BINARY=Sn,s.fetchHandlers["BINARY.PEEK"]=(e,t,r)=>Sn(e,t,r),s.fetchHandlers["BINARY.SIZE"]=yf,s.appendLiteral8=e=>{try{return bf(e)}catch(t){throw nt(t.message,t.code)}}}E();E();var Tf="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+,";function qa(s){if(typeof s!="string")return"Invalid mailbox name";let e=0;for(;e<s.length;){let t=s.charCodeAt(e);if(t<32||t>126)return"Mailbox name must use modified UTF-7 for non-ASCII characters (RFC 3501 section 5.1.3)";if(s.charAt(e)!=="&"){e++;continue}if(s.charAt(e+1)==="-"){e+=2;continue}let r=s.indexOf("-",e+1);if(r<0)return'Modified BASE64 in mailbox name must end with "-" (RFC 3501 section 5.1.3)';let n=Sf(s.slice(e+1,r));if(n)return n;if(s.charAt(r+1)==="&"&&s.charAt(r+2)!=="-")return"Mailbox name contains a superfluous shift (RFC 3501 section 5.1.3)";e=r+1}return!1}function Sf(s){let e=0,t=0,r=[];for(let n=0;n<s.length;n++){let i=Tf.indexOf(s.charAt(n));if(i<0)return"Invalid modified BASE64 in mailbox name (RFC 3501 section 5.1.3)";e=e<<6|i,t+=6,t>=16&&(t-=16,r.push(e>>t&65535),e&=(1<<t)-1)}if(!r.length||t>=6||e!==0)return"Invalid modified BASE64 in mailbox name (RFC 3501 section 5.1.3)";for(let n=0;n<r.length;n++){let i=r[n];if(i>=32&&i<=126)return"Modified BASE64 must not encode printable US-ASCII (RFC 3501 section 5.1.3)";if(i>=55296&&i<=56319){if(!(r[n+1]>=56320&&r[n+1]<=57343))return"Invalid UTF-16 in mailbox name";n++}else if(i>=56320&&i<=57343)return"Invalid UTF-16 in mailbox name"}return!1}function vs(s){return s.replace(/&|[^\x20-\x7e]+/g,e=>e==="&"?"&-":"&"+b.Buffer.from(e,"utf16le").swap16().toString("base64").replace(/=+$/,"").replace(/\//g,",")+"-")}function On(s){return qa(s)?!1:s.replace(/&([^-]*)-/g,(e,t)=>t?b.Buffer.from(t.replace(/,/g,"/"),"base64").swap16().toString("utf16le"):"&")}var Tt=qa;function xn(s){s.registerCapability("CATENATE"),s.registerCapability("URL-PARTIAL"),s.appendDataHandlers.CATENATE=(e,t)=>{if(!Array.isArray(t)||!t.length||t.length%2)throw _e("CATENATE expects a list of TEXT literals and URLs");let r=[];for(let n=0;n<t.length;n+=2){let i=t[n]&&t[n].type==="ATOM"?String(t[n].value).toUpperCase():"",o=t[n+1];if(i==="TEXT"&&o&&o.type==="LITERAL")r.push({text:o.value});else if(i==="URL"&&o&&["ATOM","STRING","LITERAL"].indexOf(o.type)>=0)r.push({url:o.value});else throw _e("Invalid CATENATE part "+(n/2+1))}return()=>{let n=e.getMaxLiteralSize(),i="";for(let o of r)if(i+="text"in o?o.text:wf(e,o.url),i.length>n)throw nt("Catenated message is too large","TOOBIG");return i}}}var If=/^[A-Za-z0-9\-._~!$'()*+,&=:@/;%]*$/,Of=/^\/([^;]+?)(?:;UIDVALIDITY=([^/;]*))?\/;UID=([^/;]*)(?:\/;SECTION=([^/;]*))?(?:\/;PARTIAL=([^/;]*))?$/i;function Se(s,e){if(!s)return nt(e);let t=s.replace(/[^\x20-\x5c\x5e-\x7e]/g,r=>"%"+r.charCodeAt(0).toString(16).toUpperCase().padStart(2,"0"));return nt(e,"BADURL",[{type:"TEXT",value:t}])}function xf(s){let e=s.split("/").slice(1),t=[];return e.forEach((r,n)=>{let i=n===e.length-1;if(r==="."||r===".."){r===".."&&t.pop(),i&&t.push("");return}t.push(r)}),"/"+t.join("/")}function Qa(s){return s.replace(/%([0-9a-f]{2})/gi,(e,t)=>String.fromCharCode(parseInt(t,16)))}function Cf(s,e,t){if(!t||!/^[\x20-\x7e]+$/.test(t))return!1;let r;try{let o=st.parser("X FETCH 1 BODY.PEEK["+t+"]");r=o.attributes.length===2&&!o.attributes[1].partial&&o.attributes[1]}catch{return!1}if(!r||!r.section||!r.section.length||r.section[0].type!=="ATOM")return!1;let n=String(r.section[0].value).toUpperCase(),i=(n.match(/^[1-9]\d*(?:\.[1-9]\d*)*/)||[""])[0];if(i){let o=bt(ne(e).tree,i),a=n.substr(i.length+1);if(!o||a&&a!=="MIME"&&!o.message)return!1}try{return Te.BODY(s,e,{section:r.section}).value}catch{return!1}}function wf(s,e){if(!e)throw Se(e,"Empty URL does not refer to a message");if(/^[a-z][a-z0-9+.-]*:/i.test(e)||e.substr(0,2)==="//")throw Se(e,"Only absolute-path URLs of this server are supported, e.g. /INBOX/;UID=1");if(e.charAt(0)!=="/")throw Se(e,"Relative-path URLs are not allowed (RFC 5092 section 7.2)");if(!If.test(e)||/%(?![0-9a-f]{2})/i.test(e))throw Se(e,"Invalid characters in URL");let t=xf(e).match(Of);if(!t)throw Se(e,"URL does not refer to a message or a message part");let[,r,n,i,o,a]=t;if(n!==void 0&&!Le(n)||!Le(i))throw Se(e,"Invalid UIDVALIDITY or UID in URL");let u;try{u=new TextDecoder("utf-8",{fatal:!0}).decode(b.Buffer.from(Qa(r),"binary"))}catch{throw Se(e,"Mailbox name in URL is not valid UTF-8")}let l=s.server.getMailbox(vs(u));if(!l||l.flags.indexOf("\\Noselect")>=0)throw Se(e,"Mailbox does not exist");for(let p of s.server.urlAccessChecks){let y=p(s,l,e);if(y)throw Se(e,y.text||"Permission denied")}if(n!==void 0&&Number(n)!==l.uidvalidity)throw Se(e,"UIDVALIDITY does not match");let c=l.messages.find(p=>p.uid===Number(i));if(!c)throw Se(e,"Message does not exist");let f=c.raw;if(o!==void 0&&(f=Cf(s,c,Qa(o)),f===!1))throw Se(e,"Invalid section or the message part does not exist");if(a!==void 0){let p=a.match(/^(\d+)(?:\.(\d+))?$/);if(!p||!Ae(p[1])||p[2]!==void 0&&!Le(p[2]))throw Se(e,"Invalid partial range");f=f.substr(Number(p[1]),p[2]?Number(p[2]):void 0)}return f}E();function Cn(){throw new Error("The COMPRESS plugin is not available in the browser")}E();E();var jt={ALL:["FLAGS","INTERNALDATE","RFC822.SIZE","ENVELOPE"],FAST:["FLAGS","INTERNALDATE","RFC822.SIZE"],FULL:["FLAGS","INTERNALDATE","RFC822.SIZE","ENVELOPE","BODY"]};function Ya(s){return s.map(e=>{let t=Object.assign({},e,{value:e.value.replace(/\.PEEK\b/i,"")});return t.partial&&(t.partial=t.partial.slice(0,1)),t})}function Ka(s,e){return e.map((t,r)=>{let n=(t.value||"").toUpperCase(),i=s.server.fetchHandlers[n]||Te[n];if(!i)throw new Error("Invalid FETCH argument "+(n||"#"+(r+1)));return i})}function Bs(s,e,t,r,n){let i=r||Ka(s,t),o=n||Ya(t),a=[];return t.forEach((u,l)=>a.push(o[l],i[l](s,e,u))),a}function wn(s,e,t,r,n){let i=s?"UID FETCH":"FETCH";if(!t.attributes||t.attributes.length!==2||!t.attributes[0]||["ATOM","SEQUENCE"].indexOf(t.attributes[0].type)<0||!t.attributes[1]||["ATOM"].indexOf(t.attributes[1].type)<0&&!Array.isArray(t.attributes[1]))return e.send({tag:t.tag,command:"BAD",attributes:[{type:"TEXT",value:i+" expects sequence set and message item names"}]},"INVALID COMMAND",t,r),n();let o=e.limitRange(t,e.getCommandRange(t.attributes[0].value,s)),a=[].concat(t.attributes[1]||[]);t.attributes[1].type==="ATOM"&&Object.prototype.hasOwnProperty.call(jt,t.attributes[1].value.toUpperCase())&&(a=jt[t.attributes[1].value.toUpperCase()].slice());let u=[],l=[],c=[];try{let f=!1,p=!1,y=!1;a.forEach((h,d)=>{if(!h||typeof h!="string"&&h.type!=="ATOM")throw new Error("Invalid FETCH argument #"+(d+1));typeof h=="string"&&(h=a[d]={type:"ATOM",value:h});let g=h.value.toUpperCase();g==="FLAGS"&&(p=!0),g==="UID"&&(f=!0);let T=e.server.fetchHandlers[g]||Te[g];e.canSetSeen()&&(g==="BODY"&&h.section||T&&T.setsSeen)&&(y=!0)}),y&&!p&&a.push({type:"ATOM",value:"FLAGS"}),s&&!f&&a.push({type:"ATOM",value:"UID"});let A=Ka(e,a),m=Ya(a);o.forEach(h=>{for(let g=0,T=e.server.fetchFilters.length;g<T;g++)if(!e.server.fetchFilters[g](e,h[1],t,h[0]))return;y&&h[1].flags.indexOf("\\Seen")<0&&(h[1].flags.push("\\Seen"),u.push(h[1]));let d=Bs(e,h[1],a,A,m);c.push(h[1]),l.push({tag:"*",attributes:[h[0],{type:"ATOM",value:"FETCH"},d]})})}catch(f){let p=f;return u.forEach(y=>e.server.removeFlag(y.flags,"\\Seen")),e.sendStatus(t,r,p.imapResponse==="NO"?"NO":"BAD",p.message,p.code,i+" FAILED"),n()}return l.forEach((f,p)=>e.send(f,i,t,r,c[p])),e.send({tag:t.tag,command:"OK",attributes:[{type:"TEXT",value:i+" Completed"}]},i,t,r),e.notifyFlagChanges(u),n()}var Nf=(s,e,t,r)=>wn(!1,s,e,t,r),za=Nf;E();E();var St=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];function ze(s){let e=String(s||"").toLowerCase();return St.findIndex(t=>t.toLowerCase()===e)}function It(s,e,t){return s=Number(s),t=Number(t),e<0||e>11||!Number.isInteger(s)||s<1?!1:s<=new Date(Date.UTC(t,e+1,0)).getUTCDate()}function Hs(s,e,t){return It(s,e,t)?String(t).padStart(4,"0")+"-"+String(e+1).padStart(2,"0")+"-"+String(s).padStart(2,"0"):!1}function ks(s){if(!s||typeof s!="string")return!1;let e=s.match(/^( \d|\d\d)-(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)-(\d{4}) (\d{2}):(\d{2}):(\d{2}) [-+](\d{2})(\d{2})$/i);return e?It(e[1],ze(e[2]),e[3])&&Number(e[4])<24&&Number(e[5])<60&&Number(e[6])<61&&Number(e[8])<60:!1}function Ps(s){let e=String(s||"").match(/^\s*(\d{1,2})-([A-Za-z]{3})-(\d{4})(?: (\d{2}):(\d{2}):(\d{2}) ([+-]\d{4}))?/);if(!e||!It(e[1],ze(e[2]),e[3]))return null;let t=e[4]===void 0?{}:{hours:Number(e[4]),minutes:Number(e[5]),seconds:Number(e[6]),zone:e[7]};return Object.assign({day:Number(e[1]),month:ze(e[2]),year:Number(e[3])},t)}function Fs(s){let e=(s||"").toString().replace(/\([^()]*\)/g," ").match(/^\s*(?:[A-Za-z]+\s*,)?\s*(\d{1,2})\s+([A-Za-z]{3})\s+(\d{2,4})(?:\s+(\d{1,2})\s*:\s*(\d{2})(?:\s*:\s*(\d{2}))?(?:\s+([+-]\d{4}|[A-Za-z]+))?)?/);if(!e)return null;let t=Number(e[3]);e[3].length===2?t+=t<50?2e3:1900:e[3].length===3&&(t+=1900);let r=Number(e[1]),n=ze(e[2]);if(!It(r,n,t))return null;let i=e[4]===void 0?{}:{hours:Number(e[4]),minutes:Number(e[5]),seconds:Number(e[6]||0),zone:e[7]};return Object.assign({day:r,month:n,year:t},i)}var Wa={UT:0,GMT:0,EST:-5,EDT:-4,CST:-6,CDT:-5,MST:-7,MDT:-6,PST:-8,PDT:-7};function Nn(s){let e=s.zone||"",t=0;if(/^[+-]\d{4}$/.test(e)){let r=e.charAt(0)==="-"?-1:1,n=Number(e.substr(1,2)),i=Number(e.substr(3,2));i<60&&(t=r*(n*60+i))}else Object.hasOwn(Wa,e.toUpperCase())&&(t=Wa[e.toUpperCase()]*60);return Date.UTC(s.year,s.month,s.day,s.hours||0,s.minutes||0,s.seconds||0)-t*60*1e3}E();var Mn=/=\?([^?\s*]+)(?:\*[^?\s]*)?\?([BbQq])\?([^?\s]*)\?=/g,Mf=new TextDecoder("utf-8");function _s(s){return Mf.decode(b.Buffer.from(s,"binary"))}var Rn=new Map;function Rf(s,e){if(s=s.toLowerCase(),!Rn.has(s)){let r=!1;try{r=new TextDecoder(s)}catch{}Rn.set(s,r)}let t=Rn.get(s);return t?t.decode(e):!1}function ut(s){let e=String(s||"");if(e.indexOf("=?")<0&&!/[\u0080-\u00ff]/.test(e))return e;let t="",r=null,n=0,i=()=>{if(r){let a=Rf(r.charset,b.Buffer.concat(r.octets));t+=a===!1?r.source:a,r=null}};Mn.lastIndex=0;let o;for(;o=Mn.exec(e);){let a=e.substring(n,o.index);r&&/^\s*$/.test(a)||(i(),t+=_s(a)),n=Mn.lastIndex;let l=o[2].toUpperCase()==="B"?b.Buffer.from(o[3],"base64"):b.Buffer.from(o[3].replace(/_/g," ").replace(/=([0-9a-fA-F]{2})/g,(c,f)=>String.fromCharCode(parseInt(f,16))),"binary");r&&r.charset.toLowerCase()!==o[1].toLowerCase()&&i(),r||(r={charset:o[1],octets:[],source:""}),r.octets.push(l),r.source+=(r.source?a:"")+o[0]}return i(),t+_s(e.substr(n))}var Lf={ALL:[],ANSWERED:[],BCC:["string"],BEFORE:["date"],BODY:["string"],CC:["string"],DELETED:[],DRAFT:[],FLAGGED:[],FROM:["string"],HEADER:["string","string"],KEYWORD:["string"],LARGER:["number64"],NEW:[],NOT:["key"],OLD:[],ON:["date"],OR:["key","key"],RECENT:[],SEEN:[],SENTBEFORE:["date"],SENTON:["date"],SENTSINCE:["date"],SINCE:["date"],SMALLER:["number64"],SUBJECT:["string"],TEXT:["string"],TO:["string"],UID:["sequence"],UNANSWERED:[],UNDELETED:[],UNDRAFT:[],UNFLAGGED:[],UNKEYWORD:["string"],UNSEEN:[]},$a=["US-ASCII","UTF-8"];function Q(s){let e=new Error(s);return e.imapResponse="BAD",e}function Df(s){let e=(s||"").toString().match(/^(\d{1,2})-([A-Za-z]{3})-(\d{4})$/),t=e&&Hs(Number(e[1]),ze(e[2]),Number(e[3]));if(!t)throw Q("Invalid date argument "+s);return t}function vn(s){let e=Ps(s);return e?Hs(e.day,e.month,e.year):!1}function Gs(s){return vn(s.internaldate)}function Ln(s){let e=Fs(ne(s).tree.parsedHeader.date);return e?Hs(e.day,e.month,e.year):Gs(s)}function Ot(s){let e=(t,r)=>{if(Array.isArray(t))return t.map(e);if(!t||["STRING","ATOM","LITERAL","SEQUENCE"].indexOf(t.type)<0)throw Q("Invalid search criteria argument #"+(r+1));return t.value};return s.map(e)}function xt(s,e,t,r,n){let i=[];r.code==="BADCHARSET"?i.push({type:"SECTION",section:[{type:"ATOM",value:"BADCHARSET"},r.charsets.map(o=>({type:"ATOM",value:o}))]}):r.responseCode&&i.push({type:"SECTION",section:r.responseCode.map(o=>({type:"ATOM",value:String(o)}))}),i.push({type:"TEXT",value:r.message}),s.send({tag:e.tag,command:r.imapResponse==="BAD"?"BAD":"NO",attributes:i},n,e,t)}function Un(s){return s.replace(/[A-Z]+/g,e=>e.toLowerCase())}function Dn(s,e){return Un(s).indexOf(e)>=0}function Ja(s){let e=Object.assign({},Lf),t=s.searchHandlers;return Object.keys(t).forEach(r=>{if(!(r in e)){let n=t[r];e[r]=typeof n.argumentTypes=="function"?n.argumentTypes:new Array(Math.max(n.length-3,0)).fill("string")}}),e}function Za(s,e){let t=Ja(s),r=n=>{let i=0;return n.some((o,a)=>{if(Array.isArray(o))return r(o);if(i)return i--,!1;let u=(o&&o.value||"").toString(),l=u.toUpperCase();if(l==="CHARSET"&&a===0)i=1;else if(Object.hasOwn(t,l)){let c=t[l];typeof c=="function"&&(c=c(n.slice(a+1).map(f=>Array.isArray(f)?f:(f&&f.value||"").toString()))),i=c.filter(f=>f!=="key").length}else if(/^[\d*][\d*,:]*$/.test(u))return!0;return!1})};return r([].concat(e||[]))}function De(s,e,t,r){let n=r||((N,w)=>s.getMessageRange(N,w)),i={},o=new Set,a=Ja(s.server),u=s.server.searchHandlers;t=[].concat(t||[]);let l=s.searchCharset||s.defaultSearchCharset||"US-ASCII";if(typeof t[0]=="string"&&t[0].toUpperCase()==="CHARSET"){if(s.searchCharset)throw Q("CHARSET is not allowed, search strings are always "+s.searchCharset+" in this session");t.shift();let N=t.shift();if(typeof N!="string")throw Q("CHARSET expects a charset name");if($a.indexOf(N.toUpperCase())<0){let w=new Error("Unsupported charset "+N);throw w.imapResponse="NO",w.code="BADCHARSET",w.charsets=$a,w}l=N.toUpperCase()}let c=(N,w)=>{if(l==="US-ASCII"&&/[\u0080-\u00ff]/.test(w))throw Q(N+" argument has 8-bit characters, use CHARSET UTF-8");if(l==="UTF-8"&&!Ye(b.Buffer.from(w,"binary")))throw Q(N+" argument is not valid UTF-8");return w};if(!t.length)throw Q("SEARCH expects search criteria, empty query given");let f=N=>{if(!N.length)throw Q("Unexpected end of search criteria");let w=N.shift();if(Array.isArray(w))return{key:"AND",args:p([].concat(w))};let G=w.toUpperCase();if(!Object.prototype.hasOwnProperty.call(a,G)||s.disabledSearchKeys&&s.disabledSearchKeys.has(G)){let L;try{L=n(w,!1)}catch(v){throw/^[\d,:*]+$/.test(w)?v:Q("Invalid search key "+w)}return{key:"_SEQ",args:[L]}}o.add(G);let F=a[G],W=typeof F=="function"?F(N):F,x=W.map(L=>{if(L==="key")return f(N);if(!N.length||typeof N[0]!="string")throw Q(G+" expects "+W.length+" argument"+(W.length>1?"s":""));let v=N.shift();if(typeof L=="function")return L(v);switch(L){case"date":return Df(v);case"number":case"number64":{let V=L==="number64"&&s.number64;if(!Ae(v,V?Ge:4294967295))throw Q(G+" expects a number"+(V?"64":""));return Number(v)}case"sequence":return n(v,!0);default:return c(G,v)}});return{key:G,args:x}},p=N=>{if(!N.length)throw Q("Empty search criteria list");let w=[];for(;N.length;)w.push(f(N));return w},y={key:"AND",args:p(t)},A=N=>new Set(N.map(w=>w[1])),m=N=>{(N.key==="_SEQ"||N.key==="UID")&&(N.set=A(N.args[0])),["BODY","TEXT"].indexOf(N.key)>=0?N.needle=Un(N.args[0]):["BCC","CC","FROM","HEADER","SUBJECT","TO"].indexOf(N.key)>=0&&(N.needle=Un(_s(N.args[N.key==="HEADER"?1:0]))),N.args.forEach(w=>{w&&typeof w=="object"&&w.key&&m(w)})};m(y);let h=(N,w)=>N.flags.indexOf(w)>=0,d=(N,w,G)=>(w=w.toLowerCase(),(ne(N).tree.header||[]).some(F=>{let W=F.indexOf(":"),x=(W<0?F:F.substr(0,W)).trim().toLowerCase(),L=W<0?"":F.substr(W+1).replace(/\r?\n(?=[ \t])/g,"");return x===w&&Dn(ut(L),G)})),g=(N,w,G)=>{let F=N.args;if(Object.prototype.hasOwnProperty.call(u,N.key))return!!u[N.key](s,w,G,...F);switch(N.key){case"AND":return F.every(W=>g(W,w,G));case"_SEQ":case"UID":return N.set.has(w);case"ALL":return!0;case"ANSWERED":return h(w,"\\Answered");case"BCC":case"CC":case"FROM":case"SUBJECT":case"TO":return d(w,N.key,N.needle);case"HEADER":return d(w,F[0],N.needle);case"BEFORE":{let W=Gs(w);return!!W&&W<F[0]}case"ON":return Gs(w)===F[0];case"SINCE":{let W=Gs(w);return!!W&&W>=F[0]}case"SENTBEFORE":{let W=Ln(w);return!!W&&W<F[0]}case"SENTON":return Ln(w)===F[0];case"SENTSINCE":{let W=Ln(w);return!!W&&W>=F[0]}case"BODY":return Dn(Be(ne(w).tree,!0),N.needle);case"TEXT":return Dn(ne(w).raw,N.needle);case"DELETED":return h(w,"\\Deleted");case"DRAFT":return h(w,"\\Draft");case"FLAGGED":return h(w,"\\Flagged");case"KEYWORD":return h(w,F[0]);case"LARGER":return ne(w).raw.length>F[0];case"SMALLER":return ne(w).raw.length<F[0];case"NEW":return s.isRecent(w)&&!h(w,"\\Seen");case"OLD":return!s.isRecent(w);case"RECENT":return s.isRecent(w);case"SEEN":return h(w,"\\Seen");case"NOT":return!g(F[0],w,G);case"OR":return g(F[0],w,G)||g(F[1],w,G);case"UNANSWERED":return!h(w,"\\Answered");case"UNDELETED":return!h(w,"\\Deleted");case"UNDRAFT":return!h(w,"\\Draft");case"UNFLAGGED":return!h(w,"\\Flagged");case"UNKEYWORD":return!h(w,F[0]);case"UNSEEN":return!h(w,"\\Seen");default:return!1}},T=s.server.searchLimits.reduce((N,w)=>w(s,N,y)||N,e),C=T!==e&&new Set(T),H=[];return e.forEach((N,w)=>{C&&!C.has(N)||g(y,N,w+1)&&(i[N.uid]=w+1,H.push(N))}),{list:H,numbers:i,keys:o,matches:(N,w)=>g(y,N,w)}}E();function Ne(s,e){s.enableAvailable=s.enableAvailable||[],s.enableAvailable.indexOf(e)<0&&s.enableAvailable.push(e)}function ye(s,e){return!!s.enabled&&s.enabled.indexOf(e)>=0}function Bn(s){s.registerCapability("ENABLE"),s.enableAvailable=s.enableAvailable||[],s.connectionHandlers.push(e=>{e.enabled=e.enabled||[]}),s.resetHandlers.push(e=>{e.enabled=[]}),s.setCommandHandler("ENABLE",(e,t,r,n)=>{let i,o,a;if(e.everSelected)return e.sendStatus(t,r,"BAD","ENABLE is not allowed after SELECT or EXAMINE"),n();if(!t.attributes)return e.send({tag:t.tag,command:"BAD",attributes:[{type:"TEXT",value:"ENABLE expects capability list"}]},"INVALID COMMAND",t,r),n();for(o=0,a=t.attributes.length;o<a;o++)if(!t.attributes[o]||t.attributes[o].type!=="ATOM")return e.send({tag:t.tag,command:"BAD",attributes:[{type:"TEXT",value:"Attribute nr "+(o+1)+" is not an ATOM"}]},"INVALID COMMAND",t,r),n();let u=[];for(o=0,a=t.attributes.length;o<a;o++){let l=t.attributes[o].value.toUpperCase();i=s.enableAvailable.find(c=>c.toUpperCase()===l),i&&e.enabled.indexOf(i)<0&&(e.enabled.push(i),u.push(i))}return e.send({tag:"*",command:"ENABLED",attributes:u.map(l=>({type:"ATOM",value:l}))},"ENABLED",t,r,u),e.send({tag:t.tag,command:"OK",attributes:[{type:"TEXT",value:"ENABLE completed"}]},"ENABLE",t,r),n()},{states:Z.AUTHENTICATED})}function kn(s){s.registerCapability("CONDSTORE"),Ne(s,"CONDSTORE");let e=m=>Math.max(Number(m.HIGHESTMODSEQ)||0,1),t=m=>(m.HIGHESTMODSEQ=e(m)+1,m.HIGHESTMODSEQ);s.resetHandlers.push(m=>{m.condstoreEnabled=!1});let r=m=>!!m.condstoreEnabled||ye(m,"CONDSTORE")||ye(m,"QRESYNC");s.condstore={isEnabled:r,getHighestModseq:e};let n=(m,h,d,g)=>{m.send({tag:"*",command:"OK",attributes:[{type:"SECTION",section:[{type:"ATOM",value:"HIGHESTMODSEQ"},e(h)]},{type:"TEXT",value:"Highest"}]},"CONDSTORE INFO",d,g)},i=(m,h,d)=>{if(r(m)){m.condstoreEnabled=!0;return}m.condstoreEnabled=!0,m.state==="Selected"&&m.selectedMailbox&&n(m,m.selectedMailbox,h,d)};s.messageHandlers.push((m,h,d)=>{let g=Number(h.MODSEQ);g>0&&Number.isSafeInteger(g)?(h.MODSEQ=g,d.HIGHESTMODSEQ=Math.max(e(d),g)):h.MODSEQ=t(d)}),s.on("expunge",m=>{t(m)}),s.on("flags",(m,h)=>{h.forEach(d=>{d.MODSEQ=t(m)})}),s.closedChecks.push(()=>!0),s.allowedStatus.push("HIGHESTMODSEQ"),s.statusHandlers.HIGHESTMODSEQ=(m,h)=>e(h);let o=(m,h)=>{let d=s.getCommandHandler(m);d&&s.setCommandHandler(m,(g,T,C,H)=>h(d,g,T,C,H))},a=(m,h,d,g,T)=>(m.sendStatus(h,d,"BAD",T,!1,"CONDSTORE FAILED"),g()),u=(m,h)=>!!m&&m.type==="ATOM"&&Ae(m.value,Ge)&&(h||BigInt(m.value)>0n),l=(m,h,d,g,T)=>{Hf(d.attributes&&d.attributes[1],d.attributes,1)&&(h.condstoreEnabled=!0,d.condstoreOption=!0),m(h,d,g,T)};o("SELECT",l),o("EXAMINE",l),o("STATUS",(m,h,d,g,T)=>{let C=d.attributes&&d.attributes[1];Array.isArray(C)&&C.some(H=>H&&H.type==="ATOM"&&String(H.value).toUpperCase()==="HIGHESTMODSEQ")&&i(h,d,g),m(h,d,g,T)});let c=(m,h,d,g,T)=>{let C=d.attributes||[],H=Math.max(C.length-1,2),N=nu(C[H],"CHANGEDSINCE",C,H);if(N){if(!u(N))return a(h,d,g,T,"Invalid syntax for CHANGEDSINCE, number expected");d.changedsince=Number(N.value),Bf(d)}(N||iu(d))&&i(h,d,g),m(h,d,g,T)};o("FETCH",c),o("UID FETCH",c);let f=(m,h,d,g,T)=>{let C=nu(d.attributes&&d.attributes[1],"UNCHANGEDSINCE",d.attributes,1);if(C){if(!u(C,!0))return a(h,d,g,T,"Invalid syntax for UNCHANGEDSINCE, number expected");d.unchangedsince=Number(C.value),i(h,d,g)}d.condstoreStore={isUid:(d.command||"").toUpperCase()==="UID STORE",messages:new Map,modified:[],done:!1},m(h,d,g,T)};o("STORE",f),o("UID STORE",f);let p=(m,h,d,...g)=>h.MODSEQ>=g[g.length-1];p.argumentTypes=m=>typeof m[0]=="string"&&/^\d+$/.test(m[0])?[eu]:[Uf,vf,eu],s.searchHandlers.MODSEQ=p;let y=m=>m.reduce((h,d)=>Math.max(h,d.MODSEQ),0);s.fetchHandlers.MODSEQ=function(m,h){return[h.MODSEQ]},s.fetchFilters.push((m,h,d,g)=>"changedsince"in d&&!(d.changedsince<h.MODSEQ)?!1:(d.condstoreFetch||(d.condstoreFetch=new Map),d.condstoreFetch.set(g,{message:h,seen:h.flags.indexOf("\\Seen")>=0}),!0)),s.storeFilters.push((m,h,d,g)=>{let T=d.condstoreStore;return T?"unchangedsince"in d&&h.MODSEQ>d.unchangedsince?(T.modified.push(T.isUid?h.uid:g),!1):(T.messages.set(h,{index:g,before:tu(h),bumped:!1,reported:!1}),!0):!0});let A=(m,h,d)=>{!d.bumped&&tu(h)!==d.before&&(d.bumped=!0,h.MODSEQ=t(m.selectedMailbox))};s.outputHandlers.push((m,h,d,g,T,C)=>{if(d==="FLAG NOTIFICATION"&&h&&C&&r(m)){Hn(h.attributes[2],C.MODSEQ);return}if(!g||!h)return;if(d==="FLAG UPDATE"&&g.condstoreStore&&C&&g.condstoreStore.messages.has(C)){let N=g.condstoreStore.messages.get(C);A(m,C,N),N.reported=!0,r(m)&&(Hn(h.attributes[2],C.MODSEQ),su(h.attributes[2],C.uid));return}let H=["SEARCH","SORT","THREAD"].includes(h.command)&&[h.command,"UID "+h.command].includes(d);if((H||d==="ESEARCH")&&h.tag==="*"&&C&&C.keys&&C.keys.has("MODSEQ")){if(i(m,g,T),C.list.length&&h.command!=="THREAD"){let N=[{type:"ATOM",value:"MODSEQ"},y(C.list)];h.attributes.push(...H?[N]:N)}return}if(h.tag==="*"&&g.condstoreFetch&&h.attributes&&h.attributes[1]&&h.attributes[1].value==="FETCH"&&g.condstoreFetch.has(h.attributes[0])){let N=g.condstoreFetch.get(h.attributes[0]),w=N.message,G=!1;!N.seen&&w.flags.indexOf("\\Seen")>=0&&m.selectedMailbox&&(N.seen=!0,w.MODSEQ=t(m.selectedMailbox),G=!0);let F=h.attributes[2];Array.isArray(F)&&(Pn(F,"MODSEQ")>=0||G&&r(m))&&Hn(F,w.MODSEQ),Array.isArray(F)&&G&&r(m)&&su(F,w.uid);return}if(h.tag===g.tag&&g.condstoreStore&&!g.condstoreStore.done){let N=g.condstoreStore;N.done=!0,N.messages.forEach((w,G)=>{if(A(m,G,w),!w.reported&&r(m)&&(w.bumped||"unchangedsince"in g)){let F=[{type:"ATOM",value:"MODSEQ"},[G.MODSEQ]];F.unshift({type:"ATOM",value:"UID"},G.uid),m.send({tag:"*",attributes:[w.index,{type:"ATOM",value:"FETCH"},F]},"CONDSTORE MODSEQ UPDATE",g,T,G)}}),(h.command==="OK"||h.command==="NO")&&N.modified.length&&(h.attributes=[{type:"SECTION",section:[{type:"ATOM",value:"MODIFIED"},{type:"SEQUENCE",value:N.modified.sort((w,G)=>w-G).join(",")}]}].concat((h.attributes||[]).filter(w=>h.command==="OK"||!w||w.type!=="SECTION")));return}if(d==="ENABLED"&&Array.isArray(C)&&C.indexOf("CONDSTORE")>=0){m.condstoreEnabled||(m.condstoreEnabled=!0,m.state==="Selected"&&m.selectedMailbox&&(g.condstoreReportHighest=!0));return}if(d==="ENABLE"&&g.condstoreReportHighest&&m.selectedMailbox){g.condstoreReportHighest=!1,n(m,m.selectedMailbox,g,T);return}if((d==="EXAMINE"||d==="SELECT")&&h.tag===g.tag&&m.selectedMailbox){if(g.condstoreOption){let N=h.attributes&&h.attributes.slice(-1)[0];!N||N.type!=="TEXT"?h.attributes=(h.attributes||[]).concat({type:"TEXT",value:"CONDSTORE is now enabled"}):N.value+=", CONDSTORE is now enabled"}n(m,m.selectedMailbox,g,T)}})}function eu(s){if(!Ae(s,Ge))throw Q("MODSEQ expects a mod-sequence value");return Number(s)}function Uf(s){let e=s.match(/^\/flags\/(\\?)(.+)$/i);if(!e||sn.test(e[2])||e[1]&&e[2].toUpperCase()==="RECENT")throw Q('MODSEQ expects an entry name like "/flags/\\\\seen"');return s}function vf(s){if(!["PRIV","SHARED","ALL"].includes(s.toUpperCase()))throw Q("MODSEQ expects entry type priv, shared or all");return s}function tu(s){return JSON.stringify([s.flags||[],s["X-GM-LABELS"]||[]])}function Pn(s,e){if(!Array.isArray(s))return-1;for(let t=0;t<s.length;t+=2)if(s[t]&&s[t].type==="ATOM"&&String(s[t].value).toUpperCase()===e)return t;return-1}function Hn(s,e){if(!Array.isArray(s))return;let t=Pn(s,"MODSEQ");t>=0?s[t+1]=[e]:s.push({type:"ATOM",value:"MODSEQ"},[e])}function su(s,e){Array.isArray(s)&&Pn(s,"UID")<0&&s.push({type:"ATOM",value:"UID"},e)}function ru(s){return!!s&&s.type==="ATOM"&&String(s.value).toUpperCase()==="MODSEQ"}function iu(s){let e=s.attributes&&s.attributes[1];return Array.isArray(e)?e.some(ru):ru(e)}function Bf(s){if(!s.attributes||!s.attributes[1]||iu(s))return;let e=s.attributes[1];if(!Array.isArray(e)){let t=String(e.value).toUpperCase(),r=e.type==="ATOM"&&Object.hasOwn(jt,t)&&jt[t];e=r?r.map(n=>({type:"ATOM",value:n})):[e].concat(s.attributes.splice(2))}s.attributes[1]=e.concat({type:"ATOM",value:"MODSEQ"})}function Hf(s,e,t){if(!s)return!1;let r=!1;if(Array.isArray(s)){for(let n=s.length-1;n>=0;n--)if(s[n]&&s[n].type==="ATOM"&&s[n].value.toUpperCase()==="CONDSTORE"){s.splice(n,1),r=!0;break}s.length||e.splice(t,1)}return!!r}function nu(s,e,t,r){if(!s)return!1;let n=!1;if(Array.isArray(s)){for(let i=0;i<s.length;i+=2)if(s[i]&&s[i].type==="ATOM"&&s[i].value.toUpperCase()===e.toUpperCase()){n=s[i+1]||{type:"NIL"},s.splice(i,2);break}s.length||t.splice(r,1)}return n}E();E();E();function lt(s){return Xs(Array.from(new Set(s)).sort((e,t)=>e-t))}function Xs(s){let e=[];return s.forEach(t=>{let r=e[e.length-1];r&&r[1]+1===t?r[1]=t:e.push([t,t])}),e.map(t=>t[0]===t[1]?String(t[0]):t[0]+":"+t[1]).join(",")}function Vt(s,e){let t=s&&["ATOM","SEQUENCE"].includes(s.type)?String(s.value):"",r=t.match(/^(-?)([1-9][0-9]*):(-?)([1-9][0-9]*)$/);if(!r||r[1]!==r[3]||r[1]&&!e)throw Q("PARTIAL expects a range like 1:100"+(e?" or -1:-100":""));let n=Number(r[2]),i=Number(r[4]);if(n>4294967295||i>4294967295)throw Q("PARTIAL range is out of bounds");return{range:t,from:Math.min(n,i),to:Math.max(n,i),fromEnd:!!r[1]}}function js(s,e){return e.fromEnd?s.slice(Math.max(s.length-e.to,0),Math.max(s.length-e.from+1,0)):s.slice(e.from-1,e.to)}function Vs(s){s.searchReturnOptions.has("PARTIAL")||(s.searchReturnOptions.set("PARTIAL",{data:!0,once:!0,parse:e=>Vt(e,!!s.partialRangeLast)}),s.searchReturnOptions.set("ALL",Object.assign({},s.searchReturnOptions.get("ALL"),{once:!0})),s.searchReturnChecks.push(e=>e.has("PARTIAL")&&e.has("ALL")&&"PARTIAL and ALL can not be used together"))}function je(s,e){let t=e.get("PARTIAL");if(!s.length||e.has("ALL")||e.has("COUNT")||!t&&!e.has("MIN")&&!e.has("MAX"))return s;let r=new Set(t?js(s,t):[]);return e.has("MIN")&&r.add(s[0]),e.has("MAX")&&r.add(s[s.length-1]),s.filter(n=>r.has(n))}function Fn(s,e){let t=[{type:"ATOM",value:"TAG"},{type:"STRING",value:s}];return e&&t.push({type:"ATOM",value:"MAILBOX"},{type:"MAILBOX",value:e.path},{type:"ATOM",value:"UIDVALIDITY"},e.uidvalidity),t}function Ct(s,e,t,r,n,i){let o=(i||t.list).map(c=>e?c.uid:t.numbers[c.uid]);i||o.sort((c,f)=>c-f);let a=i?Xs:lt,u=[Fn(s,n)];e&&u.push({type:"ATOM",value:"UID"});let l=(c,f)=>u.push({type:"ATOM",value:c},f);if(o.length&&r.has("MIN")&&l("MIN",o[0]),o.length&&r.has("MAX")&&l("MAX",o[o.length-1]),o.length&&(r.has("ALL")||!r.size)&&l("ALL",{type:"SEQUENCE",value:a(o)}),r.has("PARTIAL")){let c=r.get("PARTIAL"),f=js(o,c);l("PARTIAL",[{type:"ATOM",value:c.range},f.length?{type:"SEQUENCE",value:a(f)}:null])}return r.has("COUNT")&&l("COUNT",o.length),{tag:"*",command:"ESEARCH",attributes:u}}var ou=s=>{let e=s&&s[0];return!!e&&e.type==="ATOM"&&String(e.value).toUpperCase()==="RETURN"};function Ie(s){if(s.searchReturnOptions)return;s.registerCapability("ESEARCH"),s.searchReturnOptions=new Map(["MIN","MAX","ALL","COUNT"].map(t=>[t,{data:!0}])),s.searchReturnChecks=[],s.parseSearchReturn=(t,r,n)=>{if(!Array.isArray(t))throw Q("RETURN expects a parenthesized list of result options");let i=new Map,o=new Set;for(let a=0;a<t.length;a++){let u=t[a],l=u&&u.type==="ATOM"?String(u.value).toUpperCase():"",c=s.searchReturnOptions.get(l);if(!c)throw Q("Unknown SEARCH result option"+(l?" "+l:""));if(c.once&&i.has(l))throw Q("SEARCH result option "+l+" can be used only once");o.add(l);let f=c.parse?c.parse(t[++a]):!0;c.hint||i.set(l,f)}for(let a of s.searchReturnChecks){let u=a(i,r,n,o);if(u)throw Q(u)}return i},s.isSilentReturn=t=>t.size>0&&![...t.keys()].some(r=>{let n=s.searchReturnOptions.get(r);return n.data||n.response});let e=(t,r,n,i,o)=>{if(!ou(n.attributes))return t(r,n,i,o);try{n.searchReturn=s.parseSearchReturn(n.attributes[1],r,n)}catch(a){return r.sendStatus(n,i,"BAD",a.message,!1,(n.command||"").toUpperCase()+" FAILED"),o()}n.attributes=n.attributes.slice(2),t(r,n,i,o)};s.acceptSearchReturn=t=>{let r=s.getCommandHandler(t);s.setCommandHandler(t,(n,i,o,a)=>e(r,n,i,o,a))},s.acceptSearchReturn("SEARCH"),s.acceptSearchReturn("UID SEARCH"),s.connectionHandlers.push(t=>{let r=t.usesSequenceNumbers;t.usesSequenceNumbers=function(n){return ou(n.attributes)&&(n=Object.assign({},n,{attributes:n.attributes.slice(2)})),r.call(this,n)}}),s.outputHandlers.push((t,r,n,i,o,a)=>{if(!i||!i.searchReturn||r.tag!=="*"||r.command!=="SEARCH"||n!=="SEARCH"&&n!=="UID SEARCH"||!a||!Array.isArray(a.list))return;r.skipResponse=!0;let u=i.searchReturn;s.isSilentReturn(u)||t.send(Ct(i.tag,n==="UID SEARCH",a,u),"ESEARCH",i,o,Object.assign({},a,{list:je(a.list,u)}))})}var kf=10,au=new Set(["SELECT","EXAMINE","CLOSE","UNSELECT"]),Pf=new Set(["SEARCH","UID SEARCH","SORT","UID SORT"]),_n=s=>(s.searchContexts||(s.searchContexts=new Map),s.searchContexts),uu=(s,e)=>{let t=[];s.forEach(([n,i])=>{let o=t[t.length-1],a=o&&(e||!n?o.position:o.position+o.values.length);o&&n===a?o.values.push(i):t.push({position:n,values:[i]})});let r=[];return t.forEach(n=>{let i=n.position?Xs(n.values):lt(n.values);r.push(n.position,{type:"SEQUENCE",value:i})}),r},lu=(s,e,t,r)=>{let n=[Fn(e.tag,e.correlatorMailbox)];e.isUid&&n.push({type:"ATOM",value:"UID"}),t.length&&n.push({type:"ATOM",value:"REMOVEFROM"},uu(t,!0)),r.length&&n.push({type:"ATOM",value:"ADDTO"},uu(r,!1)),s.send({tag:"*",command:"ESEARCH",attributes:n},"ESEARCH UPDATE",null,null,e)},Ff=s=>{let e=s.searchContexts,t=s.selectedMailbox,r=t?t.messages:[],n=new Map(r.map((i,o)=>[i,o+1]));e.forEach((i,o)=>{if(i.mailbox!==t){e.delete(o);return}let a=r.filter((p,y)=>i.matches(p,y+1)),u=p=>i.isUid?p.uid:n.get(p),l=new Set(a),c=[],f=[];if(!i.compare)i.results.forEach(p=>{!l.has(p)&&n.has(p)&&c.push([0,u(p)])}),a.forEach(p=>{i.results.has(p)||f.push([0,u(p)])});else{let p=0;i.order.forEach(y=>{l.has(y)?p++:n.has(y)&&c.push([p+1,u(y)])}),i.order=a.sort(i.compare),i.order.forEach((y,A)=>{i.results.has(y)||f.push([A+1,u(y)])})}i.results=l,(c.length||f.length)&&lu(s,i,c,f)})},_f=(s,e,t)=>{s.searchContexts.forEach(r=>{if(r.mailbox!==s.selectedMailbox)return;let n=[];e.forEach(i=>{if(!r.results.delete(i))return;let o=0;r.order&&(o=r.order.indexOf(i)+1,r.order.splice(o-1,1)),(r.isUid||t)&&n.push([o,r.isUid?i.uid:t])}),n.length&&lu(s,r,n,[])})};function qt(s){if(s.addSearchContext)return;Ie(s),s.registerCapability("CONTEXT=SEARCH");let e=Math.max(Number(s.options.maxSearchContexts)||kf,1);s.searchReturnOptions.set("CONTEXT",{hint:!0}),s.searchReturnOptions.set("UPDATE",{data:!1,response:!0,once:!0}),Vs(s),s.searchReturnChecks.push((t,r,n)=>t.has("UPDATE")&&_n(r).has(n.tag)&&"Tag "+n.tag+" is already in use by an updating search"),s.addSearchContext=(t,r,n,i,o,a)=>{let u=_n(t);if(u.size>=e){t.send({tag:"*",command:"NO",attributes:[{type:"SECTION",section:[{type:"ATOM",value:"NOUPDATE"},{type:"STRING",value:r.tag}]},{type:"TEXT",value:"Too many updating contexts"}]},"NOUPDATE",r,n);return}u.set(r.tag,{tag:r.tag,isUid:o,matches:i.matches,results:new Set(i.list),compare:i.compare||null,order:i.compare?i.sorted.slice():null,mailbox:t.selectedMailbox,correlatorMailbox:a||null})},s.setCommandHandler("CANCELUPDATE",(t,r,n,i)=>{let o=r.attributes||[];if(!o.length||o.some(l=>!l||l.type!=="STRING"))return t.sendStatus(r,n,"BAD","CANCELUPDATE expects one or more quoted tags",!1,"CANCELUPDATE FAILED"),i();let a=_n(t);return o.find(l=>!a.has(l.value))?(t.sendStatus(r,n,"NO","Unknown tag",!1,"CANCELUPDATE FAILED"),i()):(o.forEach(l=>a.delete(l.value)),t.sendStatus(r,n,"OK","Updates cancelled",!1,"CANCELUPDATE"),i())},{states:Z.SELECTED}),s.resetHandlers.push(t=>{t.searchContexts=null}),s.connectionHandlers.push(t=>{let r=t.processNotifications;t.processNotifications=function(n,i){r.call(this,n,i);let o=(n&&n.command||"").toUpperCase();this.searchContexts&&this.searchContexts.size&&!this.notificationQueue.length&&!au.has(o)&&Ff(this)}}),s.outputHandlers.push((t,r,n,i,o,a)=>{let u=r.tag==="*"&&(r.message?[r.message]:r.command==="VANISHED"&&r.messages);if(u&&t.searchContexts){_f(t,u,r.message?r.attributes[0]:null);return}if(!i)return;let l=(i.command||"").toUpperCase();if(r.tag===i.tag&&au.has(l)){t.searchContexts=null;return}if(!(!Pf.has(l)||!i.searchReturn||!i.searchReturn.has("UPDATE"))){if(r.tag==="*"&&l.endsWith(String(r.command))&&n===l&&a&&Array.isArray(a.list)){i.contextResult=a;return}r.tag===i.tag&&r.command==="OK"&&i.contextResult&&s.addSearchContext(t,i,o,i.contextResult,l.startsWith("UID "))}})}E();E();E();E();var Gn=new Map([[452,453],[454,453],[455,456],[457,456],[458,459],[460,459],[497,498],[499,498],[8115,8124],[8131,8140],[8179,8188]]);for(let s of[8064,8080,8096])for(let e=0;e<8;e++)Gn.set(s+e,s+e+8);function He(s){let e="";for(let t of s){let r=t.codePointAt(0);if(Gn.has(r)){e+=String.fromCodePoint(Gn.get(r));continue}let n=t.toUpperCase();e+=[...n].length===1?n:t}return b.Buffer.from(e.normalize("NFKD"),"utf-8")}var Xn="\\[[^[\\]]*\\] *",Gf=new RegExp("^(?:"+Xn+")*(?:re|fwd?) *(?:"+Xn+")?:","i"),Xf=new RegExp("^"+Xn);function qs(s){let e=!1,t=ut(s).replace(/\r?\n(?=[ \t])/g,"").replace(/[\t\r\n]/g," ").replace(/ {2,}/g," ");for(;;){let r=t.length;for(;;)if(t.charAt(r-1)===" ")r--;else if(r>=5&&t.substring(r-5,r).toLowerCase()==="(fwd)")e=!0,r-=5;else break;for(t=t.substring(0,r);;){let n;if(t.charAt(0)===" ")t=t.substr(1);else if(n=t.match(Gf))e=!0,t=t.substr(n[0].length);else if((n=t.match(Xf))&&n[0].length<t.length)t=t.substr(n[0].length);else break}if(/^\[fwd:/i.test(t)&&/\]$/.test(t)){e=!0,t=t.slice(5,-1);continue}return{subject:t,isReply:e}}}function jn(s){let e=Ps(s.internaldate);return e?Nn(e):0}function Qs(s){let e=Fs(ne(s).tree.parsedHeader.date);return e?((e.hours===void 0||e.hours>23||e.minutes>59||e.seconds>60)&&Object.assign(e,{hours:0,minutes:0,seconds:0}),Nn(e)):jn(s)}function cu(s,e){let t=Xe(ne(s).tree.parsedHeader[e]);return t&&t[0]||null}function Ys(s,e){let t=cu(s,e);return t&&t[2]?ut(t[2]):""}function Vn(s,e){let t=cu(s,e),r=t&&t[0]?ut(t[0]):"";return r||!t||!t[2]?r:ut(t[3]?t[2]+"@"+t[3]:t[2])}function Ks(s){let e=[].concat(s||[]).join(" "),t=[],r=0,n=!1,i=null;for(let o=0;o<e.length;o++){let a=e.charAt(o);if(n)a==="\\"?(i!==null&&(i+=e.charAt(o+1)),o++):a==='"'?n=!1:i!==null&&(i+=a);else if(r)a==="\\"?o++:a==="("?r++:a===")"&&r--;else if(a==='"')n=!0;else if(a==="(")r++;else if(a==="<")i="";else if(a===">"){if(i!==null){let u=i.lastIndexOf("@");u>0&&u<i.length-1&&t.push(i)}i=null}else i!==null&&!/\s/.test(a)&&(i+=a)}return t}function zs(s,e,t,r){let n=e.command.toUpperCase(),i=r[0];try{if(r.length<2)throw Q(n+" expects a charset and search criteria");if(!i||["ATOM","STRING"].indexOf(i.type)<0)throw Q("Charset must be an atom or a quoted string");let o=Ot(r.slice(1));if(s.searchCharset){if(i.value.toUpperCase()!==s.searchCharset)throw Q("Charset must be "+s.searchCharset+" in this session");return De(s,s.getSessionMessages(),o)}let a=["CHARSET",i.value].concat(o);return De(s,s.getSessionMessages(),a)}catch(o){return xt(s,e,t,o,n+" FAILED"),!1}}function ct(s){if(s.sortKeys)return;s.registerCapability("SORT"),s.sortKeys={ARRIVAL:r=>jn(r),CC:r=>He(Ys(r,"cc")),DATE:r=>Qs(r),FROM:r=>He(Ys(r,"from")),SIZE:r=>ne(r).raw.length,SUBJECT:r=>He(qs(ne(r).tree.parsedHeader.subject).subject),TO:r=>He(Ys(r,"to"))};let e=(r,n)=>b.Buffer.isBuffer(r)?b.Buffer.compare(r,n):r-n;s.sortComparator=r=>{let n=new WeakMap,i=o=>(n.has(o)||n.set(o,r.map(a=>s.sortKeys[a.key](o))),n.get(o));return(o,a)=>{let u=i(o),l=i(a);for(let c=0;c<r.length;c++){let f=e(u[c],l[c]);if(f)return r[c].reverse?-f:f}return o.uid-a.uid}};let t=(r,n,i,o,a)=>{let u=r?"UID SORT":"SORT",l=i.attributes||[],c=h=>(n.sendStatus(i,o,"BAD",h,!1,u+" FAILED"),a());if(!Array.isArray(l[0])||!l[0].length)return c(u+" expects a list of sort criteria");let f=[],p=!1;for(let h of l[0]){let d=h&&h.type==="ATOM"?h.value.toUpperCase():"";if(d==="REVERSE"&&!p){p=!0;continue}if(!Object.hasOwn(s.sortKeys,d))return c("Invalid sort criterion "+(h&&typeof h.value=="string"?h.value:""));f.push({key:d,reverse:p}),p=!1}if(p)return c("REVERSE must be followed by a sort key");let y=zs(n,i,o,l.slice(1));if(!y)return a();let A=s.sortComparator(f),m=y.list.slice().sort(A);return n.send({tag:"*",command:"SORT",attributes:m.map(h=>r?h.uid:y.numbers[h.uid])},u,i,o,Object.assign(y,{sorted:m,compare:A})),n.sendStatus(i,o,"OK",u+" completed",!1,u),a()};s.setCommandHandler("SORT",t.bind(null,!1),{states:Z.SELECTED,searchCriteria:2,noExpunge:!0}),s.setCommandHandler("UID SORT",t.bind(null,!0),{states:Z.SELECTED,searchCriteria:2})}var fu=s=>s==="SORT"||s==="UID SORT";function Qt(s){s.esortLoaded||(s.esortLoaded=!0,ct(s),Ie(s),s.registerCapability("ESORT"),s.acceptSearchReturn("SORT"),s.acceptSearchReturn("UID SORT"),s.searchReturnChecks.push((e,t,r,n)=>{if(!fu((r.command||"").toUpperCase())||s.contextSort)return!1;let i=["CONTEXT","UPDATE","PARTIAL"].find(o=>n.has(o)&&(o!=="PARTIAL"||!s.partialRangeLast));return!!i&&i+" is not supported for SORT"}),s.outputHandlers.push((e,t,r,n,i,o)=>{if(!n||!n.searchReturn||t.tag!=="*"||t.command!=="SORT"||!fu(r)||!o||!o.sorted)return;t.skipResponse=!0;let a=n.searchReturn;s.isSilentReturn(a)||e.send(Ct(n.tag,r==="UID SORT",o,a,null,o.sorted),"ESEARCH",n,i,Object.assign({},o,{list:je(o.sorted,a)}))}))}function qn(s){Qt(s),qt(s),s.registerCapability("CONTEXT=SORT"),s.contextSort=!0}E();var jf=new RegExp("^\\\\["+he["ATOM-CHAR"]().replace(/[\\\]^-]/g,"\\$&")+"]+$");function Qn(s){s.registerCapability("CREATE-SPECIAL-USE");let e=s.getCommandHandler("CREATE"),t=[].concat(s.options["special-use"]||["\\Archive","\\Drafts","\\Flagged","\\Junk","\\Sent","\\Trash"]);s.setCommandHandler("CREATE",(r,n,i,o)=>{let a,u,l,c=[];if(n.attributes&&Array.isArray(n.attributes[1])){for(a=0;a<n.attributes[1].length;a+=2)n.attributes[1][a]&&n.attributes[1][a].type==="ATOM"&&n.attributes[1][a].value.toUpperCase()==="USE"&&Array.isArray(n.attributes[1][a+1])&&(l=n.attributes[1][a+1],n.attributes[1].splice(a,2),a-=2);n.attributes[1].length||n.attributes.splice(1,1)}if(l)for(a=0,u=l.length;a<u;a++){let f=l[a];if(!J(f)||!jf.test(f.value))return r.send({tag:n.tag,command:"BAD",attributes:[{type:"TEXT",value:"Invalid syntax for special use flag #"+(a+1)}]},"CREATE-SPECIAL-USE FAILED",n,i),o();let p=t.find(y=>y.toLowerCase()===String(l[a].value).toLowerCase());if(!p)return r.send({tag:n.tag,command:"NO",attributes:[{type:"SECTION",section:[{type:"ATOM",value:"USEATTR"}]},{type:"TEXT",value:l[a].value+" not supported"}]},"CREATE-SPECIAL-USE FAILED",n,i),o();c.indexOf(p)<0&&c.push(p)}c.length&&(n.mailboxSpecialUse=c),e(r,n,i,o)}),s.outputHandlers.push((r,n,i,o,a,u)=>{i==="CREATE"&&u&&o.mailboxSpecialUse&&(u["special-use"]=o.mailboxSpecialUse)})}E();function Yn(s){s.registerCapability("ID"),s.setCommandHandler("ID",(e,t,r,n)=>{let i=Object.create(null),o=null,a,u,l="";if(!t.attributes||t.attributes.length!==1)return We("ID expects 1 attribute",e,t,r,n);let c=t.attributes[0];if(c&&!Array.isArray(c)||c&&c.length%2)return We("ID expects valid parameter list",e,t,r,n);if(c&&c.length>60)return We("ID allows at most 30 field-value pairs",e,t,r,n);if(c&&c.length)for(a=0,u=c.length;a<u;a++)if(a%2===0)if(c[a]&&["STRING","LITERAL"].indexOf(c[a].type)>=0){if(l=c[a].value,l.length>30)return We("ID field names can be at most 30 octets",e,t,r,n);if(Object.keys(i).some(f=>f.toLowerCase()===l.toLowerCase()))return We("ID field names must not repeat",e,t,r,n)}else return We("ID expects valid parameter list",e,t,r,n);else if(!c[a]||["STRING","LITERAL"].indexOf(c[a].type)>=0){if(c[a]&&c[a].value.length>1024)return We("ID values can be at most 1024 octets",e,t,r,n);i[l]=c[a]&&c[a].value||null}else return We("ID expects valid parameter list",e,t,r,n);if(s.options.id){let f=[];o=f,Object.keys(s.options.id).forEach(p=>{f.push({type:"STRING",value:p}),f.push({type:"STRING",value:(s.options.id[p]||"").toString()})})}e.send({tag:"*",command:"ID",attributes:[o]},"ID",t,r,i),e.send({tag:t.tag,command:"OK",attributes:[{type:"TEXT",value:"ID command completed"}]},"ID",t,r,i),n()},{states:Z.ANY})}function We(s,e,t,r,n){return e.send({tag:t.tag,command:"BAD",attributes:[{type:"TEXT",value:s}]},"INVALID COMMAND",t,r),n()}E();function Kn(s){s.registerCapability("IDLE"),s.setCommandHandler("IDLE",(e,t,r,n)=>{let i=setTimeout(()=>{e.socket&&!e.socket.destroyed&&(e.send({tag:"*",command:"BYE",attributes:[{type:"TEXT",value:"IDLE terminated"}]},"IDLE EXPIRED",t,r),e.end())},18e5);i.unref?.();let o=()=>clearTimeout(i),a=e.socket;return a&&a.once("close",o),e.directNotifications=!0,e.inputHandler=function(u){o(),a&&a.removeListener("close",o),e.inputHandler=!1,e.directNotifications=!1,u.toUpperCase()==="DONE"?e.send({tag:t.tag,command:"OK",attributes:[{type:"TEXT",value:"IDLE terminated"}]},"IDLE",t,r):e.send({tag:t.tag,command:"BAD",attributes:[{type:"TEXT",value:"Invalid Idle continuation"}]},"INVALID IDLE",t,r)},e.sendContinuation("idling","IDLE"),e.processNotifications(),n()},{states:Z.AUTHENTICATED,noArguments:!0})}E();E();var Vf=/[\u0000-\u001f\u007f-\u009f\u2028\u2029]|^\ufeff|\p{Cn}/u;function zn(s){let e=new Error(s);return e.imapResponse="BAD",e}function hu(s){if(s===!1||Vf.test(s))throw zn("Mailbox name must be valid Net-Unicode without control characters (RFC 9755 section 3)");if(s.normalize("NFC")!==s)throw zn("Mailbox name must be in Unicode Normalization Form C (RFC 5198 section 2, RFC 9051 section 5.1)");return s}function qf(s){let e=Tt(s);if(e)throw zn(e);return hu(On(s)),s}function Qf(s){let e=b.Buffer.from(s,"binary");return vs(hu(Ye(e)&&e.toString("utf-8")))}function Yf(s){let e=On(s);return e===!1?s:b.Buffer.from(e,"utf-8").toString("binary")}function wt(s){let e=s.server,t=ye(s,"UTF8=ACCEPT"),r=ye(s,"IMAP4rev2"),n=t||r;if(s.utf8Enabled=n,s.parserOptions.utf8=!!e.utf8Accept||r,s.compilerOptions.utf8=n,s.searchCharset=t?"UTF-8":!1,s.defaultSearchCharset=r?"UTF-8":!1,n)s.importMailboxName=Qf,s.exportMailboxName=Yf;else{let i=s;delete i.exportMailboxName,e.utf8Accept?s.importMailboxName=qf:delete i.importMailboxName}}E();function Yt(s){if(s.capabilities["LITERAL+"])throw new Error("LITERAL- can not be enabled together with LITERAL+");s.registerCapability("LITERAL-"),s.impliedLiteralMinus=!1,s.literalPlus=!0,s.nonSyncLiteralLimit=4096}var Wn="IMAP4rev2",Kf=new Set(["NEW","OLD","RECENT","UNRECENT"]),zf=new Set(["RECENT"]),Wf=new Set(["DELETED"]),$f=new Set(["RFC822","RFC822.HEADER","RFC822.TEXT"]),Jf=["$Forwarded","$MDNSent","$Junk","$NotJunk","$Phishing"],Nt=s=>!!s.imap4rev2,du=s=>s&&s.type==="ATOM"?String(s.value).toUpperCase():"";function Ws(s){s.registerCapability("IMAP4rev2"),Ne(s,Wn),!s.capabilities["LITERAL+"]&&!s.capabilities["LITERAL-"]&&(Yt(s),s.impliedLiteralMinus=!0),s.mailboxHandlers.push((a,u)=>{u.allowPermanentFlags||Jf.forEach(l=>a.ensureFlag(u.permanentFlags,l))});let e=a=>{let u=a.imap4rev2=ye(a,Wn);wt(a),a.messageGlobal=u,a.disabledSearchKeys=u?Kf:null,a.number64=a.parserOptions.number64=u,a.disabledStatusItems=u?zf:null,a.addedStatusItems=u?Wf:null,u?a.getFlags=l=>l.flags:delete a.getFlags};s.connectionHandlers.push(e),s.resetHandlers.push(e);let t=(a,u,l,c,f)=>(a.sendStatus(u,l,"BAD",f),c()),r=(a,u)=>{let l=s.getCommandHandler(a);s.setCommandHandler(a,(c,f,p,y)=>u(l,c,f,p,y))};Object.entries({CHECK:"NOOP",LSUB:"LIST (SUBSCRIBED)"}).forEach(([a,u])=>{r(a,(l,c,f,p,y)=>{if(Nt(c))return t(c,f,p,y,a+" is not part of IMAP4rev2, use "+u+" (RFC 9051 Appendix E)");l(c,f,p,y)})});let n=(a,u,l,c,f)=>{let p=(l.attributes||[])[1];if(Nt(u)&&[].concat(p||[]).some(y=>$f.has(du(y))))return t(u,l,c,f,"RFC822, RFC822.HEADER and RFC822.TEXT are not part of IMAP4rev2, use BODY[] (RFC 9051 Appendix E)");a(u,l,c,f)};r("FETCH",n),r("UID FETCH",n);let i=(a,u,l,c,f)=>{Nt(u)&&du((l.attributes||[])[0])!=="RETURN"&&(l.searchReturn=s.parseSearchReturn([],u,l)),a(u,l,c,f)};r("SEARCH",i),r("UID SEARCH",i),s.closedChecks.push(Nt);let o=(a,u,l,c)=>{let f=u.flags.concat(u["special-use"]||[]);a.send({tag:"*",command:"LIST",attributes:[f.map(p=>({type:"ATOM",value:p})),s.getSeparator(u),{type:"MAILBOX",value:u.path}]},"SELECT LIST",l,c,u)};s.outputHandlers.push((a,u,l,c,f)=>{if(l==="RECENT NOTIFICATION"&&Nt(a)){u.skipResponse=!0;return}if(!c||!u||!Nt(a))return;let p=String(c.command||"").toUpperCase();if(!(p!=="SELECT"&&p!=="EXAMINE")){if(l===p+" RECENT"||l===p+" UNSEEN"){u.skipResponse=!0;return}l===p&&u.tag===c.tag&&u.command==="OK"&&a.selectedMailbox&&o(a,a.selectedMailbox,c,f)}}),s.outputHandlers.push((a,u,l,c,f,p)=>{l==="ENABLED"&&Array.isArray(p)&&p.indexOf(Wn)>=0&&e(a)})}Ws.requires=["ENABLE","NAMESPACE","UNSELECT","UIDPLUS","ESEARCH","SEARCHRES","IDLE","SASL-IR","LIST-EXTENDED","LIST-STATUS","MOVE","BINARY","SPECIAL-USE","STATUS=SIZE","AUTH=PLAIN"];E();E();function $s(s,e){if(Object.is(s,e))return!0;if(!s||!e||typeof s!="object"||typeof e!="object"||Object.getPrototypeOf(s)!==Object.getPrototypeOf(e))return!1;if(s instanceof Map||s instanceof Set)return $s(Array.from(s),Array.from(e));let t=Object.keys(s);return t.length===Object.keys(e).length&&t.every(r=>Object.prototype.hasOwnProperty.call(e,r)&&$s(s[r],e[r]))}var Zf=s=>Array.isArray(s[0])||Array.isArray(s[1])||s.length>2;function Kt(s){let e=Ke(s);if(e.enabled)return;e.enabled=!0,s.registerCapability("LIST-EXTENDED"),e.selectionOptions.SUBSCRIBED={type:"base",returnOption:"SUBSCRIBED",includeNonExistent:!0,match:a=>!!a.subscribed},e.selectionOptions.REMOTE={type:"independent"},e.selectionOptions.RECURSIVEMATCH={type:"modifier"},e.returnOptions.SUBSCRIBED={},e.returnOptions.CHILDREN={};let t=(a,u,l,c)=>{let f=new Map;for(let p=0;p<a.length;p++){let y=a[p];if(!y||y.type!=="ATOM")throw new Error("Invalid "+l+" option");let A=y.value.toUpperCase(),m=u[A];if(!m)throw new Error("Unknown "+l+" option "+A);let h=!0;if(m.parse){if(!Array.isArray(a[p+1]))throw new Error(A+" "+l+" option requires a value");h=m.parse(a[++p],c)}else if(Array.isArray(a[p+1]))throw new Error(A+" "+l+" option takes no value");if(f.has(A)&&!$s(f.get(A),h))throw new Error(A+" "+l+" option is repeated with a different value");f.set(A,h)}return f},r=(a,u)=>{let l=new Map,c=new Map,f=0;Array.isArray(a[0])&&(l=t(a[0],e.selectionOptions,"selection",u),f++);let p=a[f],y=a[f+1],A=a.slice(f+2);if(!ue(p))throw new Error("LIST expects a reference name");if(y=Array.isArray(y)?y:[y],!y.length||!y.every(ue))throw new Error("LIST expects a mailbox pattern or a list of patterns");if(A.length){if(A.length!==2||!A[0]||A[0].type!=="ATOM"||A[0].value.toUpperCase()!=="RETURN"||!Array.isArray(A[1]))throw new Error("LIST expects RETURN and a list of return options after the patterns");c=t(A[1],e.returnOptions,"return",u)}let m=[...l.keys()].map(h=>e.selectionOptions[h].type);if(m.includes("modifier")&&!m.includes("base"))throw new Error("RECURSIVEMATCH must be used together with a selection option like SUBSCRIBED");return l.forEach((h,d)=>{let g=e.selectionOptions[d].returnOption;g&&!c.has(g)&&c.set(g,!0)}),{selection:l,reference:p.value,patterns:y.map(h=>h.value).filter(h=>h),returns:c}},n=a=>a.flags.indexOf("\\Noselect")<0,i=(a,u,l,c)=>s.listAttributes(a,{exists:u,subscribed:c.has("SUBSCRIBED")&&a.subscribed,hasChildren:l}).map(f=>({type:"ATOM",value:f})),o=s.getCommandHandler("LIST");s.setCommandHandler("LIST",(a,u,l,c)=>{let f=u.attributes||[];if(!Zf(f))return o(a,u,l,c);let p;try{p=r(f,a)}catch(H){return a.sendStatus(u,l,"BAD",H.message,!1,"INVALID COMMAND"),c()}let y=[...p.selection.keys()].map(H=>({name:H,...e.selectionOptions[H]})),A=y.filter(H=>H.match),m=y.some(H=>H.includeNonExistent),h=p.selection.has("RECURSIVEMATCH"),d=y.filter(H=>H.type==="base").map(H=>({type:"STRING",value:H.name})),g=H=>(m||n(H))&&A.every(N=>N.match(H,a)),T=s.folderCache;m&&(T=Object.assign(Object.create(null),T,s.getSubscriptionTree()));let C=new Set;return p.patterns.forEach(H=>{s.matchFolders(p.reference,H,N=>a.exportMailboxName(N),T).forEach(N=>C.add(N))}),C.forEach(H=>{let N=n(H),w=g(H),G=s.getDescendants(H.path,T),F=G.some(n),W=!1;if(h&&(W=G.some(v=>g(v)&&(w||!C.has(v)))),!(w||W||!A.length&&!N&&F))return;let L=[i(H,N,F,p.returns),s.getSeparator(H),a.exportMailboxName(H.path)];W&&L.push([{type:"STRING",value:"CHILDINFO"},d]),a.send({tag:"*",command:"LIST",attributes:L},"LIST ITEM",u,l,H),p.returns.forEach((v,V)=>{let _=e.returnOptions[V];_.onItem&&_.onItem(a,H,v,{matched:w,exists:N},u,l)})}),a.sendStatus(u,l,"OK","Completed",!1,"LIST"),c()})}E();E();var eh={MESSAGES:(s,e)=>e.messages.length,RECENT:(s,e,t)=>t.recent,UIDNEXT:(s,e)=>e.uidnext,UIDVALIDITY:(s,e)=>e.uidvalidity,UNSEEN:(s,e,t)=>t.unseen||0,DELETED:(s,e,t)=>t.flags["\\Deleted"]||0};function Js(s,e,t){if(!Array.isArray(e)||!e.length)throw new Error("Expecting a list of status items");let r=t&&t.disabledStatusItems,n=t&&t.addedStatusItems;return e.map((i,o)=>{let a=i&&i.type==="ATOM"&&i.value.toUpperCase();if(!a||s.allowedStatus.indexOf(a)<0&&!(n&&n.has(a))||r&&r.has(a))throw new Error("Invalid status element ("+(o+1)+")");return a})}function Zs(s,e,t,r,n,i){s.send(er(s,e,t,r),"STATUS",n,i)}function er(s,e,t,r){let n=s.server,i=n.getStatus(t),o=[];return r.forEach(a=>{o.push({type:"ATOM",value:a},(n.statusHandlers[a]||eh[a])(s,t,i))}),{tag:"*",command:"STATUS",attributes:[{type:"MAILBOX",value:e},o]}}function $n(s){Kt(s),s.registerCapability("LIST-STATUS"),Ke(s).returnOptions.STATUS={parse:(e,t)=>Js(s,e,t),onItem:(e,t,r,n,i,o)=>{n.matched&&n.exists&&Zs(e,t.path,t,r,i,o)}}}E();function Jn(s){if(s.capabilities["LITERAL-"]&&!s.impliedLiteralMinus)throw new Error("LITERAL+ can not be enabled together with LITERAL-");delete s.capabilities["LITERAL-"],s.registerCapability("LITERAL+"),s.literalPlus=!0,s.nonSyncLiteralLimit=1/0}E();function Zn(s){s.registerCapability("LOGINDISABLED",t=>!t.secureConnection&&t.state==="Not Authenticated");let e=s.getCommandHandler("LOGIN");s.setCommandHandler("LOGIN",(t,r,n,i)=>{if(!t.secureConnection)return t.send({tag:r.tag,command:"NO",attributes:[{type:"SECTION",section:[{type:"ATOM",value:"PRIVACYREQUIRED"}]},{type:"TEXT",value:"Run STARTTLS first"}]},"LOGIN FAILED",r,n),i();e(t,r,n,i)})}E();var th=1e3,sh=new Set(["FETCH","UID FETCH","STORE","UID STORE","MOVE","UID MOVE","UID EXPUNGE"]),rh=new Set(["SEARCH","UID SEARCH"]),pu=new Set(["SORT","UID SORT","THREAD","UID THREAD"]);function ei(s,e){if(s.messageLimit)throw new Error(e+" can not be enabled together with "+s.messageLimit.name);let t="messageLimit"in s.options?s.options.messageLimit:th;if(!Number.isSafeInteger(t)||t<1||t>4294967295)throw new TypeError("Invalid messageLimit option, expecting a positive integer");return s.messageLimit={name:e,limit:t},t}function ti(s,e){s.appendChecks.push((t,r,n,i)=>{if(n.length<=e)return!1;if(i.command)return{code:["MESSAGELIMIT",e],text:i.command+" exceeds the limit of "+e+" messages, nothing was appended"};if(!i.move){let o=n[n.length-e].uid;return{code:["MESSAGELIMIT",e,o],text:"Too many messages to copy, try a smaller subset"}}return!1})}function si(s){let e=ei(s,"MESSAGELIMIT");s.registerCapability("MESSAGELIMIT="+e),ti(s,e);let t=a=>String(a.command||"").toUpperCase();s.rangeLimits.push((a,u,l)=>{let c=t(u);if(!sh.has(c)||u.partialFetch)return!1;let f=c==="UID EXPUNGE"?l.filter(y=>y[1].flags.indexOf("\\Deleted")>=0):l;if(f.length<=e)return!1;let p=new Set(f.slice(0,-e));return u.messageLimitUid=f[f.length-e][1].uid,u.highestFirst=!0,l.filter(y=>!p.has(y)).reverse()}),s.commandChecks.push((a,u)=>{let l=s.capabilities.PARTIAL&&u.attributes&&u.attributes[2],c=t(u);if(!Array.isArray(l)||c!=="FETCH"&&c!=="UID FETCH")return!1;let f=l.findIndex((y,A)=>!(A%2)&&y&&y.type==="ATOM"&&String(y.value).toUpperCase()==="PARTIAL"),p;try{p=f>=0&&Vt(l[f+1],!0)}catch{return!1}return p&&p.to-p.from+1>e?{command:"NO",code:["MESSAGELIMIT",e],text:c+" exceeds the limit of "+e+" messages"}:!1}),s.searchLimits.push((a,u,l)=>{let c=a._runningCommand&&a._runningCommand.parsed,f=c?t(c):"";if(u.length<=e||!rh.has(f)&&!pu.has(f))return!1;let p=u.filter(y=>mu(l,y));if(p.length<=e)return!1;if(pu.has(f)){let y=new Error(f+" exceeds the limit of "+e+" messages, narrow it down with UIDAFTER or UIDBEFORE");throw y.imapResponse="NO",y.responseCode=["MESSAGELIMIT",e],y}return c.messageLimitUid=p[p.length-e].uid,p.slice(-e)});let r=a=>{if(!Le(a))throw Q("UIDAFTER and UIDBEFORE expect a UID");return Number(a)},n=(a,u,l,c)=>u.uid>c;n.argumentTypes=()=>[r];let i=(a,u,l,c)=>u.uid<c;i.argumentTypes=()=>[r],s.searchHandlers.UIDAFTER=n,s.searchHandlers.UIDBEFORE=i;let o=(a,u,l,c,f)=>{if(c&&c.messageLimitUid&&u.tag==="*"&&u.command==="SEARCH"&&Array.isArray(u.attributes)){let m=u.attributes.filter(Array.isArray);u.attributes=u.attributes.filter(h=>!Array.isArray(h)).reverse().concat(m);return}if(!c||!c.messageLimitUid||u.tag!==c.tag)return;let p=c.messageLimitUid;if(c.messageLimitUid=!1,u.command!=="OK")return;let y={type:"SECTION",section:[{type:"ATOM",value:"MESSAGELIMIT"},e,p]},A=u.attributes||[];if(A[0]&&A[0].type==="SECTION"){a.send({tag:"*",command:"NO",attributes:[y,{type:"TEXT",value:"Only the last "+e+" messages were processed"}]},"MESSAGELIMIT",c,f);return}u.attributes=[y].concat(A)};s.once("pluginsLoaded",()=>s.outputHandlers.push(o))}function mu(s,e){return s.args.every(t=>{switch(t.key){case"AND":return mu(t,e);case"_SEQ":case"UID":return t.set.has(e);case"UIDAFTER":return e.uid>t.args[0];case"UIDBEFORE":return e.uid<t.args[0];default:return!0}})}E();var nh=64*1024,ih=100,oh=new Set(["/shared/admin"]),ah="/private/specialuse";function tr(s,e){if(typeof s!="string"||s.charAt(0)!=="/")return'Entry name must begin with "/"';if(/[^\x20-\x7f]/.test(s))return"Entry name must not contain non-ASCII or control characters";if(/[*%]/.test(s))return'Entry name must not contain "*" or "%"';if(s.indexOf("//")>=0)return'Entry name must not contain consecutive "/" characters';if(s.charAt(s.length-1)==="/")return'Entry name must not end with "/"';let t=s.toLowerCase().substr(1).split("/");return t[0]!=="private"&&t[0]!=="shared"?"Entry name must begin with /private or /shared":e&&t.length<2?"Entry name must have at least 2 components":e&&t[1]==="vendor"&&t.length<4?"Vendor entry names must have at least 4 components":!1}function uh(s,e){if(e==null)return null;if(e instanceof Uint8Array)e=b.Buffer.from(e).toString("binary");else if(typeof e=="string")/[Ā-￿]/.test(e)&&(e=b.Buffer.from(e,"utf-8").toString("binary"));else throw new Error("Invalid value for metadata entry "+s+", expecting a string");return e}function gu(s){return{type:"MAILBOX",value:s}}function ri(s,e){if(s.metadataState){e&&!s.metadataState.mailboxes&&(s.metadataState.mailboxes=!0,delete s.capabilities["METADATA-SERVER"],s.registerCapability("METADATA"),s.enableAvailable.splice(s.enableAvailable.indexOf("METADATA-SERVER"),1,"METADATA"));return}s.parserOptions.literal8=!0;let t=e?"METADATA":"METADATA-SERVER";s.registerCapability(t),Ne(s,t);let r=s.options,n=s.metadataState={mailboxes:e,maxSize:Number(r.metadataMaxSize)||nh,maxEntries:Number(r.metadataMaxEntries)||ih,allowPrivate:r.metadataPrivate!==!1,server:{path:"",metadata:r.metadata}},i=new WeakSet,o=h=>{if(!h.metadata)return Object.create(null);if(i.has(h.metadata))return h.metadata;let d=Object.create(null),g=h.metadata;return Object.keys(g).forEach(T=>{let C=tr(T,!0);if(C)throw new Error("Invalid metadata entry name "+JSON.stringify(T)+": "+C);let H=uh(T,g[T]);H!==null&&(d[T.toLowerCase()]=H)}),a(h,d)},a=(h,d)=>(i.add(d),h.metadata=d,d),u=h=>{let d=Object.create(null);if(h.path&&s.capabilities["SPECIAL-USE"]){let g=[].concat(h["special-use"]||[]);d[ah]=g.length?g.join(" "):null}return d},l=h=>ye(h,n.mailboxes?"METADATA":"METADATA-SERVER"),c=(h,d,g,T)=>{if(T==="")return n.server;if(!n.mailboxes)return h.sendStatus(d,g,"NO","Mailbox annotations are not supported, only server annotations"),!1;let C=h.server.getMailbox(T);return!C||C.flags.indexOf("\\NonExistent")>=0?(h.sendStatus(d,g,"NO","Mailbox does not exist","NONEXISTENT"),!1):C},f=(h,d,g,T,C)=>(h.sendStatus(d,g,"BAD",T),C());s.setCommandHandler("GETMETADATA",(h,d,g,T)=>{let C=d.attributes||[],H=Array.isArray(C[0])?1:0,N=!1,w=0;if(C.length!==H+2||!ue(C[H]))return f(h,d,g,"GETMETADATA expects options, a mailbox name and entries",T);if(H){let X=C[0];if(!X.length)return f(h,d,g,"Empty option list",T);for(let q=0;q<X.length;q+=2){let se=X[q]&&X[q].type==="ATOM"?X[q].value.toUpperCase():!1,ee=X[q+1]&&X[q+1].type==="ATOM"?X[q+1].value:!1;if(se==="MAXSIZE"){if(!Ae(ee))return f(h,d,g,"Invalid value for MAXSIZE",T);N=Number(ee)}else if(se==="DEPTH"){if(!ee||!/^(0|1|infinity)$/i.test(ee))return f(h,d,g,"Invalid value for DEPTH",T);w=ee.toLowerCase()==="infinity"?1/0:Number(ee)}else return f(h,d,g,"Unknown GETMETADATA option",T)}}let G;try{G=h.importMailboxName(C[H].value)}catch(X){return f(h,d,g,X.message,T)}let F=[].concat(C[H+1]);if(!F.length||!F.every(ue))return f(h,d,g,"GETMETADATA expects an entry name or a list of entry names",T);for(let X of F){let q=tr(X.value);if(q)return f(h,d,g,q,T)}let W=c(h,d,g,G);if(!W)return T();let x=Object.assign(Object.create(null),o(W),u(W)),L=w?Object.keys(x).filter(X=>x[X]!==null).sort():[],v=new Map;for(let X of F){let q=X.value.toLowerCase(),se=x[q]??null;(!w||se!==null)&&v.set(q,se);let ee=q+"/";L.forEach(fe=>{fe.startsWith(ee)&&(w===1/0||fe.indexOf("/",ee.length)<0)&&v.set(fe,x[fe])})}let V=-1,_=[];return v.forEach((X,q)=>{if(N!==!1&&X!==null&&X.length>N){V=Math.max(V,X.length);return}_.push({type:"ATOM",value:q},X===null?null:{type:X.indexOf("\0")>=0?"LITERAL8":"STRING",value:X})}),_.length&&h.send({tag:"*",command:"METADATA",attributes:[gu(W.path),_]},"METADATA",d,g,W),h.sendStatus(d,g,"OK","GETMETADATA completed",V>=0&&["METADATA","LONGENTRIES",V]),T()},{states:Z.AUTHENTICATED});let p=(h,d)=>{let g=s.activeConnection,T=o(h),C=u(h),H=Object.assign(Object.create(null),T),N=[];for(let[G,F]of d){if(!h.path&&g&&oh.has(G)||G in C)return{text:"The "+G+" entry is read-only",code:"CANNOT"};if(!n.allowPrivate&&G.startsWith("/private/"))return{text:"Private annotations are not supported",code:["METADATA","NOPRIVATE"]};if(F!==null&&F.length>n.maxSize)return{text:"Value of "+G+" is too large",code:["METADATA","MAXSIZE",n.maxSize]};(T[G]??null)!==F&&N.push(G),F===null?delete H[G]:H[G]=F}let w=Object.keys(H).length;return w>n.maxEntries&&w>Object.keys(T).length?{text:"Too many annotations",code:["METADATA","TOOMANY"]}:(a(h,H),N.length&&s.notify({tag:"*",command:"METADATA",attributes:[gu(h.path)].concat(N.map(G=>({type:"ATOM",value:G})))},!1,g,l),null)};s.setCommandHandler("SETMETADATA",(h,d,g,T)=>{let C=d.attributes||[];if(C.length!==2||!ue(C[0])||!Array.isArray(C[1]))return f(h,d,g,"SETMETADATA expects a mailbox name and a list of entries and values",T);let H=C[1];if(!H.length||H.length%2)return f(h,d,g,"SETMETADATA expects entry and value pairs",T);let N=new Map;for(let F=0;F<H.length;F+=2){if(!ue(H[F]))return f(h,d,g,"Entry name must be a string",T);let W=tr(H[F].value,!0);if(W)return f(h,d,g,W,T);let x=H[F+1];if(x!==null&&(!x||["STRING","LITERAL","LITERAL8"].indexOf(x.type)<0))return f(h,d,g,"Entry value must be a string, a literal, a literal8 or NIL",T);if(x&&x.type!=="LITERAL8"&&/\r(?!\n)|(?:^|[^\r])\n/.test(x.value))return f(h,d,g,"Line ends in a value must be CRLF",T);N.set(H[F].value.toLowerCase(),x?x.value:null)}let w=c(h,d,g,C[0].value);if(!w)return T();let G=p(w,N);return G?(h.sendStatus(d,g,"NO",G.text,G.code),T()):(h.sendStatus(d,g,"OK","SETMETADATA completed"),T())},{states:Z.AUTHENTICATED,mailboxArguments:[0],literal8:!0}),s.on("mailbox",h=>{if(h.type==="rename"&&h.oldPath==="INBOX"){let d=s.getMailbox("INBOX"),g=s.getMailbox(h.path);d&&g&&g!==d&&d.metadata&&a(g,Object.assign(Object.create(null),o(d)))}else if(h.type==="delete"){let d=s.getMailbox(h.path);d&&d!==h.mailbox&&delete d.metadata}}),s.on("reset",()=>{n.server={path:"",metadata:r.metadata}});let y=h=>{if(h==="")return n.server;if(!n.mailboxes)throw K("Mailbox annotations need the METADATA plugin, METADATA-SERVER has server annotations only","INVALID");return s.control.requireMailbox(h)},A=h=>{let d=o(y(h)),g={};return Object.keys(d).forEach(T=>{g[T]=b.Buffer.from(d[T],"binary").toString("utf-8")}),g},m=(h,d)=>{let g=y(h);if(!d||typeof d!="object"||Array.isArray(d))throw K("setMetadata expects an object of entry names and values (null removes an entry)","INVALID");let T=new Map;Object.keys(d).forEach(H=>{let N=d[H],w=tr(H,!0);if(w)throw K(w,"INVALID");if(N!==null&&typeof N!="string")throw K("Value of "+H+" must be a string or null","INVALID");T.set(H.toLowerCase(),N===null?null:b.Buffer.from(N,"utf-8").toString("binary"))});let C=p(g,T);if(C)throw K(C.text,typeof C.code=="string"?C.code:"INVALID");return A(h)};s.control.register("getMetadata",A,[{method:"GET",path:"/v1/metadata",summary:"Server annotations (METADATA plugins)",handler:()=>s.control.getMetadata("")},{method:"GET",path:"/v1/mailboxes/{path}/metadata",summary:"Mailbox annotations (METADATA plugin)",handler:({params:h})=>s.control.getMetadata(h.path)}]),s.control.register("setMetadata",m,[{method:"PUT",path:"/v1/metadata",summary:'Sets server annotations ({ "/shared/comment": "text" }, null removes one, METADATA plugins)',handler:({body:h})=>s.control.setMetadata("",h)},{method:"PUT",path:"/v1/mailboxes/{path}/metadata",summary:"Sets mailbox annotations (METADATA plugin)",handler:({params:h,body:d})=>s.control.setMetadata(h.path,d)}])}function sr(s){ri(s,!0)}sr.requires=["ENABLE"];E();function rr(s){ri(s,!1)}rr.requires=["ENABLE"];E();E();function ni(s,e,t,r){return ii(s,e,t,r,!1)}function ii(s,e,t,r,n){let i=n?"UID COPY":"COPY";if(!e.attributes||e.attributes.length!==2||!e.attributes[0]||["ATOM","SEQUENCE"].indexOf(e.attributes[0].type)<0||!e.attributes[1]||["ATOM","STRING","LITERAL"].indexOf(e.attributes[1].type)<0)return s.send({tag:e.tag,command:"BAD",attributes:[{type:"TEXT",value:i+" expects sequence set and a mailbox name"}]},"INVALID COMMAND",e,t),r();let o=oi(s,e,t,n,i+" FAIL");if(!o)return r();s.send({tag:e.tag,command:"OK",attributes:[{type:"TEXT",value:i+" Completed"}]},i,e,t,o),r()}function oi(s,e,t,r,n,i){let o=e.attributes,a=s.limitRange(e,s.getCommandRange(o[0].value,r)),u=s.getTargetMailbox(o[1].value,e,t,n);if(!u)return!1;let l=a.map(p=>p[1]);if(l.some(p=>p.ghost))return s.sendStatus(e,t,"NO","Some of the requested messages no longer exist","EXPUNGEISSUED",n),!1;if(!s.checkAppend(u,l,e,t,n,{move:!!i,source:s.selectedMailbox}))return!1;let c=[],f=[];return(e.highestFirst?l.slice().reverse():l).forEach(p=>{c.push(p.uid),f.push(s.server.copyMessage(u,p).message.uid)}),{mailbox:u,sourceUids:c,targetUids:f,messages:l}}function ai(s){s.registerCapability("MOVE");let e=function(r,n,i,o,a){function u(c){return r?"UID "+c:c}if(!i.attributes||i.attributes.length!==2||!i.attributes[0]||["ATOM","SEQUENCE"].indexOf(i.attributes[0].type)<0||!i.attributes[1]||["ATOM","STRING","LITERAL"].indexOf(i.attributes[1].type)<0)return n.send({tag:i.tag,command:"BAD",attributes:[{type:"TEXT",value:u("MOVE expects sequence set and a mailbox name")}]},"INVALID COMMAND",i,o),a();if(n.refuseReadOnly(i,o,u("MOVE FAIL")))return a();let l=oi(n,i,o,r,u("MOVE FAIL"),!0);if(!l)return a();n.send({tag:"*",command:"OK",attributes:[{type:"TEXT",value:"Copied"}],skipResponse:!0},u("MOVE COPYUID"),i,o,l),n.expungeSpecificMessages(n.selectedMailbox,l.messages,!1,!0,!!i.highestFirst),n.send({tag:i.tag,command:"OK",attributes:[{type:"TEXT",value:"Done"}]},u("MOVE OK"),i,o),a()},t={states:Z.SELECTED,mailboxArguments:[1]};s.setCommandHandler("MOVE",e.bind(null,!1),Object.assign({sequenceSet:0},t)),s.setCommandHandler("UID MOVE",e.bind(null,!0),t)}E();function ui(s){s.registerCapability("MULTIAPPEND"),s.multiAppend=!0,s.appendChecks.push((e,t,r,n)=>n.command&&r.some(i=>!i.resolve&&!i.raw.length)?{text:"Zero-length message literal, APPEND cancelled"}:!1)}E();var Eu={SELECTED:!1,INBOXES:!1,PERSONAL:!1,SUBSCRIBED:!1,SUBTREE:!0,"SUBTREE-ONE":!0,MAILBOXES:!0};function lh(s,e){if(!Array.isArray(e)||!e.length)throw Q("IN expects a parenthesized list of mailbox specifiers");let t=[];for(let r=0;r<e.length;r++){let n=e[r];if(Array.isArray(n))throw Q("Unknown ESEARCH scope option");let i=n&&n.type==="ATOM"?String(n.value).toUpperCase():"";if(!Object.hasOwn(Eu,i))throw Q("Invalid mailbox specifier"+(i?" "+n.value:""));let o={filter:i,names:[]};if(Eu[i]){let a=e[++r],u=Array.isArray(a)?a:[a];if(!u.length||!u.every(ue))throw Q(i.toLowerCase()+" expects a mailbox name or a list of mailbox names");u.forEach(l=>o.names.push(s.importMailboxName(l.value)))}t.push(o)}return t}function ch(s,e){let t=e||[];return J(t[0],"IN")?{sources:lh(s,t[1]),attributes:t.slice(2)}:{sources:null,attributes:t}}function li(s){Ie(s),s.registerCapability("MULTISEARCH");let e=o=>!!o&&o.flags.indexOf("\\Noselect")<0,t=()=>Object.keys(s.folderCache).map(a=>s.folderCache[a]).sort((a,u)=>a.path==="INBOX"?-1:u.path==="INBOX"?1:0),r=(o,a,u)=>{if(!u(o)||!a||!o.folders)return;let l=o.folders;Object.keys(l).forEach(c=>r(l[c],a-1,u))},n=(o,a)=>{let u=[],l=new Set,c=(f,p)=>{!f||l.has(f)||!e(f)||s.searchAccessChecks.every(y=>y(o,f,!!p))&&(l.add(f),u.push(f))};return a.forEach(f=>{switch(f.filter){case"SELECTED":c(o.selectedMailbox,!0);break;case"INBOXES":c(s.getMailbox("INBOX"),!1);break;case"PERSONAL":t().filter(p=>s.isPersonal(p)).forEach(p=>c(p,!1));break;case"SUBSCRIBED":t().filter(p=>p.subscribed).forEach(p=>c(p,!1));break;case"MAILBOXES":f.names.forEach(p=>c(s.getMailbox(p),!0));break;default:{let p=f.filter==="SUBTREE"?1/0:1,y=new Set;f.names.forEach(A=>{let m=s.getMailbox(A);m&&r(m,p,h=>y.has(h)?!1:(y.add(h),c(h,h===m),!0))})}}}),u},i=(o,a,u,l)=>{let c=(T,C)=>(o.sendStatus(a,u,T,C,!1,"ESEARCH FAILED"),l()),f,p=new Map,y;try{let T=ch(o,a.attributes);f=T.sources||[{filter:"SELECTED",names:[]}];let C=T.attributes;if(J(C[0],"RETURN")&&(p=a.searchReturn=s.parseSearchReturn(C[1],o,a),C=C.slice(2)),!C.length)throw Q("ESEARCH expects search criteria");y=Ot(C)}catch(T){return c("BAD",T.message)}let A=f.every(T=>T.filter==="SELECTED");if(f.some(T=>T.filter==="SELECTED")&&!o.selectedMailbox)return c("BAD","No mailbox is selected");if(p.has("SAVE")&&!A)return c("BAD","SAVE can only be used when searching the selected mailbox");if(p.has("UPDATE")&&!o.selectedMailbox)return c("BAD","UPDATE needs a selected mailbox");let m=n(o,f),h=[];try{let T=C=>{if(C&&C===o.selectedMailbox)return De(o,o.getSessionMessages(),y);let H=C?C.messages:[];return De(o,H,y,(N,w)=>s.getMessageRange(H,N,w))};m.length||T(o.selectedMailbox||null),m.forEach(C=>h.push({mailbox:C,result:T(C)}))}catch(T){return xt(o,a,u,T,"ESEARCH FAILED"),l()}let d=s.isSilentReturn(p);h.forEach(({mailbox:T,result:C})=>{!C.list.length||d||o.send(Ct(a.tag,!0,C,p,T),"ESEARCH",a,u,Object.assign({},C,{list:je(C.list,p)}))});let g=h.find(T=>T.mailbox===o.selectedMailbox);return p.has("SAVE")&&(a.searchresFound=g?je(g.result.list,p):[]),p.has("UPDATE")&&g&&s.addSearchContext(o,a,u,g.result,!0,g.mailbox),o.sendStatus(a,u,"OK","ESEARCH completed",!1,"ESEARCH"),l()};s.setCommandHandler("ESEARCH",i,{states:Z.AUTHENTICATED,searchCriteria:0}),s.connectionHandlers.push(o=>{let a=o.usesSequenceNumbers;o.usesSequenceNumbers=function(u){return(u.command||"").toUpperCase()==="ESEARCH"&&J((u.attributes||[])[0],"IN")&&(u=Object.assign({},u,{attributes:u.attributes.slice(2)})),a.call(this,u)}})}E();function ci(s){s.registerCapability("NAMESPACE"),s.setCommandHandler("NAMESPACE",(e,t,r,n)=>{let i={personal:[],user:[],shared:[]};return Object.keys(s.storage).forEach(o=>{let a=s.storage[o];o==="INBOX"||!a||Object.hasOwn(i,a.type)&&i[a.type].push([e.exportMailboxName(o),a.separator])}),e.send({tag:"*",command:"NAMESPACE",attributes:[i.personal.length?i.personal:null,i.user.length?i.user:null,i.shared.length?i.shared:null]},"NAMESPACE",t,r,i),e.send({tag:t.tag,command:"OK",attributes:[{type:"TEXT",value:"Completed"}]},"NAMESPACE",t,r,i),n()},{states:Z.AUTHENTICATED,noArguments:!0})}E();var nr=["MessageNew","MessageExpunge","FlagChange","AnnotationChange"],fh=new Map(nr.concat(["MailboxName","SubscriptionChange","MailboxMetadataChange","ServerMetadataChange"]).map(s=>[s.toUpperCase(),s])),hh=["SELECTED","SELECTED-DELAYED"],dh=["INBOXES","PERSONAL","SUBSCRIBED","SUBTREE","MAILBOXES"],ph=["BODY","BODY.PEEK","BINARY","BINARY.PEEK","BINARY.SIZE"];function fi(s){s.registerCapability("NOTIFY");let e=x=>!!x.notifyState,t=()=>{let x=["MessageNew","MessageExpunge","FlagChange","MailboxName","SubscriptionChange"];return s.capabilities.METADATA&&x.push("MailboxMetadataChange"),(s.capabilities.METADATA||s.capabilities["METADATA-SERVER"])&&x.push("ServerMetadataChange"),x},r=(x,L,v,V)=>{let _=s.acl&&s.acl.getRights(x,L,V);return!_||[...v].every(X=>_.has(X))},n=(x,L,v)=>r(x,L,"l",v),i=(x,L,v)=>r(x,L,"lr",v),o=x=>x.toUpperCase()==="INBOX"?"INBOX":x,a=(x,L,v,V)=>{switch(x.filter){case"INBOXES":case"PERSONAL":return s.isPersonal(L);case"SUBSCRIBED":return!!V||!!(v&&v.subscribed);case"SUBTREE":return x.paths.indexOf(L)>=0||x.prefixes.some(_=>L.substr(0,_.length)===_);case"MAILBOXES":return x.paths.indexOf(L)>=0}return!1},u=(x,L,v,V)=>{let _=new Set;return x.notifyState.groups.forEach(X=>{a(X,L,v,V)&&X.events.forEach(q=>_.add(q))}),v&&v===x.selectedMailbox&&nr.forEach(X=>_.delete(X)),_},l=x=>!!(x.notifyState.selected&&x.notifyState.selected.delayed)&&!x.directNotifications&&x.hasPendingExpunge(),c=x=>{!x.socket||!x.notificationQueue.length||x._runningCommand||!e(x)||l(x)||x.processNotifications()},f=x=>{x.notifyFlushPending||(x.notifyFlushPending=!0,R(()=>{x.notifyFlushPending=!1,c(x)}))},p=(x,L)=>{let v=L;if(v.tag="*",v.notification=!0,!x._runningCommand&&l(x)){x.send(v,"NOTIFY EVENT");return}x.notificationQueue.push(v),f(x)},y=x=>[...s.connections].filter(L=>L!==x&&e(L)),A=(x,L,v,V)=>{if(v=v.slice(),V.has("FlagChange")){let _=s.getStatus(L),X=_&&_.unseen||0;x.notifyState.unseen.get(L)!==X&&(x.notifyState.unseen.set(L,X),v.push("UNSEEN"))}return s.condstore&&s.condstore.isEnabled(x)&&v.push("HIGHESTMODSEQ"),v.length?er(x,L.path,L,v):!1},m=(x,L,v,V)=>{y(V).forEach(_=>{if(x===_.selectedMailbox||!i(_,x))return;let X=u(_,x.path,x);if(!X.has(L))return;let q=A(_,x,L==="FlagChange"&&s.condstore&&s.condstore.isEnabled(_)?["UIDVALIDITY"]:v,X);q&&p(_,q)})},h=(x,L)=>s.hasDescendant(L,v=>n(x,v)&&v.flags.indexOf("\\NonExistent")<0),d=(x,L,v)=>{v=v||{};let V=s.getMailbox(L),_=v.exists!==!1&&!!V&&n(x,V),q=[s.listAttributes(_?V:null,{exists:_,subscribed:_&&V.subscribed,extra:v.noAccess?["\\NoAccess"]:[],hasChildren:h(x,L)}).map(se=>({type:"ATOM",value:se})),s.getSeparator(L),{type:"MAILBOX",value:L}];return v.oldPath&&q.push([{type:"STRING",value:"OLDNAME"},[{type:"STRING",value:x.exportMailboxName(v.oldPath)}]]),{tag:"*",command:"LIST",attributes:q}},g=(x,L,v,V)=>{[L,s.getParentPath(L)].forEach(_=>{if(!_)return;let X=_===L?v:s.getMailbox(_);u(x,_,X).has("MailboxName")&&p(x,d(x,_,_===L?{exists:V}:{}))})},T=(x,L)=>{L!==x.selectedMailbox&&i(x,L)&&u(x,L.path,L).has("FlagChange")&&p(x,A(x,L,["MESSAGES","UIDNEXT","UIDVALIDITY"],new Set(["FlagChange"])))};s.on("mailbox",x=>{let L=s.getMailbox(x.path);y(x.origin).forEach(v=>{switch(x.type){case"create":L&&n(v,L)&&(g(v,x.path,L,!0),T(v,L));break;case"delete":x.mailbox&&n(v,x.mailbox)&&g(v,x.path,L,!!L);break;case"rename":if(L&&n(v,L)){let V=u(v,x.path,L);u(v,x.oldPath).forEach(_=>V.add(_)),V.has("MailboxName")&&p(v,d(v,x.path,{oldPath:x.oldPath})),T(v,L)}break;case"subscribe":case"unsubscribe":L&&n(v,L)&&u(v,x.path,L,!0).has("SubscriptionChange")&&p(v,d(v,x.path));break}})}),s.on("acl",(x,L)=>{y(null).forEach(v=>{let V={list:n(v,x,L),read:i(v,x,L)},_={list:n(v,x),read:i(v,x)};if(V.list!==_.list)g(v,x.path,x,_.list);else if(_.list&&V.read!==_.read){let X=u(v,x.path,x);nr.some(q=>X.has(q))&&p(v,d(v,x.path,{noAccess:!_.read}))}})}),s.on("expunge",(x,L,v)=>m(x,"MessageExpunge",["MESSAGES","UIDNEXT"],v)),s.on("notify",x=>{let L=x.command||{},v=typeof x.mailbox=="string"?s.getMailbox(x.mailbox):x.mailbox;if(v&&L.flagUpdate)m(v,"FlagChange",[],x.origin);else if(v&&L.message&&J(L.attributes&&L.attributes[1],"EXISTS"))m(v,"MessageNew",["MESSAGES","UIDNEXT"],x.origin);else if(L.command==="METADATA"&&L.attributes&&L.attributes[0]){let V=L.attributes[0].value,_=V===""?null:s.getMailbox(V);y(x.origin).forEach(X=>{let q;V===""?q=X.notifyState.groups.some(se=>se.events.has("ServerMetadataChange")):q=!!_&&i(X,_)&&u(X,V,_).has("MailboxMetadataChange"),q&&(x.notifyHandled=x.notifyHandled||new Set,x.notifyHandled.add(X),p(X,Object.assign({},L)))})}}),s.notifyFilters.push((x,L)=>!(L.notifyHandled&&L.notifyHandled.has(x)));let C=x=>{if(x.flagUpdate)return"FlagChange";let L=x.attributes&&x.attributes[1];return J(L,"EXPUNGE")?"MessageExpunge":J(L,"EXISTS")?x.message?"MessageNew":"MessageExpunge":!1},H=(x,L,v,V)=>{let _=L.map(q=>Object.assign({},q)),X;try{X=Bs(x,V,_)}catch{return!1}return{tag:"*",notification:!0,attributes:[v,{type:"ATOM",value:"FETCH"},X],fetchedMessage:V}};s.connectionHandlers.push(x=>{x.notifyState=null;let L=x.queueNotification;x.queueNotification=function(v,V){let _=V&&V.mailbox&&C(v);if(!e(this)||!_||V.origin===this)return L.call(this,v,V);let X=this.notifyState.selected;if(!(!X||!X.events.has(_)||!i(this,this.selectedMailbox))){if(this.notificationQueue.push(v),_==="MessageNew"&&X.fetch){let q=H(this,X.fetch,v.attributes[0],v.message);q&&this.notificationQueue.push(q)}f(this)}}}),s.resetHandlers.push(x=>{x.notifyState=null}),s.outputHandlers.push((x,L)=>{L.tag!=="*"&&!L.notification&&e(x)&&x.notificationQueue.length&&f(x)}),s.notifyOverflow=x=>{y(null).filter(L=>!x||L===x).forEach(L=>{L.notifyState={selected:null,groups:[],unseen:new WeakMap},p(L,{command:"OK",attributes:[{type:"SECTION",section:[{type:"ATOM",value:"NOTIFICATIONOVERFLOW"}]},{type:"TEXT",value:"Too many notifications, NOTIFY is turned off"}]})})};let N=(x,L)=>{if(!L.length)throw Q("MessageNew expects a list of fetch attributes");return L.map(v=>{let V=J(v)&&v.value.toUpperCase();if(!V||!(s.fetchHandlers[V]||Te[V]))throw Q("Invalid fetch attribute for MessageNew");if((v.section||v.partial)&&ph.indexOf(V)>=0){let _=[Object.assign({},v)];try{Bs(x,{raw:`Subject: test\r
26
26
  \r
27
27
  Test\r
28
- `,flags:[],uid:1},_)}catch(X){throw Q(X.message)}}return v})},w=(x,L,v,V)=>{let _=new Set,X=null;if(J(L,"NONE"))return{events:_,fetch:X};if(!Array.isArray(L)||!L.length)throw Q("Expecting a list of events or NONE");for(let q=0;q<L.length;q++){let se=L[q];if(!J(se)||se.section||se.partial)throw Q("Invalid event");let ee=fh.get(se.value.toUpperCase());if(Array.isArray(L[q+1])&&ee==="MessageNew"){if(!v)throw Q("Fetch attributes for MessageNew are only allowed with SELECTED or SELECTED-DELAYED");X=N(x,L[++q])}if(!ee){V.push(se.value);continue}if(v&&nr.indexOf(ee)<0)throw Q(ee+" can not be used with SELECTED or SELECTED-DELAYED");_.add(ee)}if(_.has("MessageNew")!==_.has("MessageExpunge"))throw Q("MessageNew and MessageExpunge must be used together");if((_.has("FlagChange")||_.has("AnnotationChange"))&&!_.has("MessageNew"))throw Q("FlagChange and AnnotationChange require MessageNew and MessageExpunge");return{events:_,fetch:X}},G=(x,L)=>{let v=Array.isArray(L)?L:[L];if(!v.length||!v.every(ue))throw Q("Expecting a mailbox name or a list of mailbox names");return v.map(V=>o(x.importMailboxName(V.value)))},F=(x,L)=>{let v={selected:null,groups:[],unseen:new WeakMap},V=[];if(J(L[0],"NONE")){if(L.length!==1)throw Q("NOTIFY NONE does not take any arguments");return{state:v,status:!1,unknown:V}}if(!J(L[0],"SET"))throw Q("NOTIFY expects SET or NONE");let _=J(L[1],"STATUS"),X=L.slice(_?2:1);if(!X.length)throw Q("NOTIFY SET expects event groups");return X.forEach(q=>{if(!Array.isArray(q)||!J(q[0]))throw Q("Invalid event group");let se=q[0].value.toUpperCase();if(hh.indexOf(se)>=0){if(q.length!==2)throw Q("Invalid event group");if(v.selected)throw Q("Only one of SELECTED and SELECTED-DELAYED can be used");v.selected=Object.assign({delayed:se==="SELECTED-DELAYED"},w(x,q[1],!0,V))}else if(dh.indexOf(se)>=0){let ee=se==="SUBTREE"||se==="MAILBOXES";if(q.length!==(ee?3:2))throw Q("Invalid event group");let fe=ee?G(x,q[1]):[],{events:is}=w(x,q[q.length-1],!1,V),Nr=se==="SUBTREE"?fe.map(Lt=>Lt+s.getSeparator(Lt)):[];v.groups.push({filter:se,paths:fe,prefixes:Nr,events:is})}else throw Q("Unknown mailbox filter "+q[0].value)}),{state:v,status:_,unknown:V}},W=(x,L,v,V)=>{Object.keys(s.folderCache).sort((X,q)=>X==="INBOX"?-1:q==="INBOX"?1:X.localeCompare(q)).forEach(X=>{let q=s.folderCache[X];if(q===x.selectedMailbox||q.flags.some(fe=>/^\\(Noselect|NonExistent)$/i.test(fe)))return;let se=u(x,X,q);if(!se.size||!n(x,q))return;if(!i(x,q)){x.send(d(x,X,{noAccess:!0}),"NOTIFY LIST",v,V);return}if(!L||!se.has("MessageNew"))return;let ee=["MESSAGES","UIDNEXT","UIDVALIDITY"];if(se.has("FlagChange")){ee.push("UNSEEN");let fe=s.getStatus(q);x.notifyState.unseen.set(q,fe&&fe.unseen||0),s.condstore&&ee.push("HIGHESTMODSEQ")}x.send(er(x,X,q,ee),"NOTIFY STATUS",v,V)})};s.setCommandHandler("NOTIFY",(x,L,v,V)=>{let _;try{_=F(x,L.attributes||[])}catch(ee){return x.sendStatus(L,v,"BAD",ee.imapResponse==="BAD"?ee.message:"Invalid NOTIFY arguments"),V()}let X=t(),q=[_.state.selected].concat(_.state.groups).filter(ee=>!!ee);return _.unknown.concat(...q.map(ee=>[...ee.events].filter(fe=>X.indexOf(fe)<0))).length?(x.send({tag:L.tag,command:"NO",attributes:[{type:"SECTION",section:[{type:"ATOM",value:"BADEVENT"},X.map(ee=>({type:"ATOM",value:ee}))]},{type:"TEXT",value:"Unsupported NOTIFY events"}]},"NOTIFY FAILED",L,v),V()):(x.notifyState=_.state,W(x,_.status,L,v),x.sendStatus(L,v,"OK","NOTIFY completed"),V())},{states:Z.AUTHENTICATED})}g();var mh=new TextDecoder("utf-8",{fatal:!0});function gh(s){let e=s.toString("binary");if(e==="")return{kvsepOnly:!0};let t=e.match(/^(?:F,)?(n|y|p=[A-Za-z0-9.-]+),(?:a=([^,]+))?,/);if(!t||e.charAt(t[0].length)!=="")return{error:"Invalid GS2 header"};let r=!1;if(t[2]){if(/=(?!2C|3D)/.test(t[2])||t[2].includes("\0"))return{error:"Invalid authorization identity"};try{r=mh.decode(b.Buffer.from(t[2].replace(/=2C/g,",").replace(/=3D/g,"="),"binary"))}catch{return{error:"Invalid UTF-8 in the authorization identity"}}}let n=e.substr(t[0].length+1).split("");if(n.pop()!==""||n.pop()!=="")return{error:"The client response must end with %x01"};let i=Object.create(null);for(let o of n){let a=o.match(/^([A-Za-z]+)=([\x20-\x7e\t\r\n]*)$/);if(!a)return{error:"Invalid key/value pair"};i[a[1]]=a[2]}return{channelBinding:t[1].charAt(0)==="p",authzid:r,pairs:i}}function hi(s){s.registerCapability("AUTH=OAUTHBEARER",a=>a.state==="Not Authenticated");let e=(a,u,l,c,f)=>{a.sendStatus(u,l,c,f,c==="NO"&&"AUTHENTICATIONFAILED","AUTHENTICATE OAUTHBEARER FAILED")},t=a=>{if(a.channelBinding)return"invalid_request";let{auth:u,port:l}=a.pairs;if(typeof l=="string"&&!/^[1-9][0-9]*$/.test(l))return"invalid_request";let c=typeof u=="string"&&u.match(/^Bearer +([A-Za-z0-9\-._~+/]+=*)$/i);if(!c)return u===""?"invalid_token":"invalid_request";let f=c[1],p=s.checkAccessToken(f,a.authzid===!1?void 0:a.authzid);return"error"in p?p.error:(a.username=p.user,!1)},r=a=>s.oauth&&s.oauth.issuer?{status:a,scope:s.oauth.mailScope,"openid-configuration":s.oauth.discoveryUrl()}:{status:a},n=(a,u,l,c)=>{let f=a.decodeSaslResponse(c);return f||e(a,u,l,"BAD","Invalid base64 in SASL response"),f},i=(a,u,l,c)=>{a.inputHandler=f=>{if(a.inputHandler=!1,f==="*")return e(a,u,l,"BAD","Authentication cancelled");let p=n(a,u,l,f);p&&c(p)}},o=(a,u,l,c)=>{let f=gh(c);if(f.error)return e(a,u,l,"BAD",f.error+" in the OAUTHBEARER client response");if(f.kvsepOnly)return e(a,u,l,"NO","SASL authentication failed");let p=t(f);if(!p)return a.state="Authenticated",a.username=f.username,a.sendStatus(u,l,"OK","SASL authentication succeeded",!1,"AUTHENTICATE OAUTHBEARER SUCCESS");i(a,u,l,y=>{if(y.toString("binary")!=="")return e(a,u,l,"BAD","The client must answer the error result with a single %x01 (RFC 7628 section 3.2.3)");e(a,u,l,"NO","SASL authentication failed")}),a.send({tag:"+",attributes:[{type:"ATOM",value:b.Buffer.from(JSON.stringify(r(p))).toString("base64")}]},"AUTHENTICATE OAUTHBEARER CHALLENGE",u,l)};s.setCommandHandler("AUTHENTICATE OAUTHBEARER",(a,u,l,c)=>{let f=u.attributes||[];if(!f.length)return i(a,u,l,y=>o(a,u,l,y)),a.sendContinuation("","AUTHENTICATE OAUTHBEARER"),c();if(f.length!==1||!f[0]||f[0].type!=="ATOM")return e(a,u,l,"BAD","Invalid arguments for AUTHENTICATE OAUTHBEARER"),c();if(!s.capabilities["SASL-IR"]||!s.capabilities["SASL-IR"](a))return e(a,u,l,"BAD","SASL-IR must be enabled to send Initial Response with the request"),c();let p=n(a,u,l,f[0].value);return p&&o(a,u,l,p),c()})}g();var Au=/^[A-Za-z0-9_-]{1,255}$/,Eh=/^Message-ID[ \t]*:(.*)$/im,Ah=/^References[ \t]*:(.*)$/im,yh=/^In-Reply-To[ \t]*:(.*)$/im,ir=Symbol("mailboxid-uidvalidity");function di(s){s.registerCapability("OBJECTID");let e=new Map,t={F:0,M:0,T:0},r=new Map,n=new Map,i=new Map,o=A=>{let m;do m=A+ ++t[A];while(e.has(m));return e.set(m,A),m},a=(A,m,h)=>{if(typeof A!="string"||!Au.test(A))throw new Error("Invalid "+m+" value "+JSON.stringify(A)+" in "+h)},u=(A,m)=>{if(e.has(A)&&e.get(A)!==m)throw new Error("Object identifier "+JSON.stringify(A)+" is already used for another kind of object");e.set(A,m)},l=A=>{if(A[ir]===A.uidvalidity&&r.get(A.MAILBOXID)===A)return A.MAILBOXID;let m;return A.MAILBOXID&&A[ir]===void 0&&!r.has(A.MAILBOXID)?(m=A.MAILBOXID,a(m,"MAILBOXID","mailbox "+A.path),u(m,"F")):m=o("F"),A.MAILBOXID=m,A[ir]=A.uidvalidity,r.set(m,A),m};s.mailboxHandlers.push((A,m)=>{if(!(m.flags.indexOf("\\Noselect")>=0)){if(m.MAILBOXID&&m[ir]===void 0&&r.has(m.MAILBOXID))throw new Error("Duplicate MAILBOXID value "+JSON.stringify(m.MAILBOXID)+" in mailbox "+m.path);l(m)}}),s.control.mailboxInfoHandlers.push((A,m)=>{A.flags.indexOf("\\Noselect")<0&&(m.mailboxId=l(A))}),s.control.messageInfoHandlers.push((A,m)=>{m.emailId=A.EMAILID,m.threadId=A.THREADID}),s.messageHandlers.push((A,m,h)=>{let d="a message of mailbox "+h.path;m.EMAILID?(a(m.EMAILID,"EMAILID",d),u(m.EMAILID,"M")):m.EMAILID=o("M"),m.THREADID&&(a(m.THREADID,"THREADID",d),u(m.THREADID,"T"));let E=n.get(m.EMAILID);if(E&&m.THREADID&&m.THREADID!==E)throw new Error("Messages with EMAILID "+JSON.stringify(m.EMAILID)+" must have the same THREADID");let I=bh(m.raw);m.THREADID=m.THREADID||E||c(I.references)||o("T"),n.set(m.EMAILID,m.THREADID),[I.messageId].concat(I.references).forEach(C=>{C&&!i.has(C)&&i.set(C,m.THREADID)})});let c=A=>{for(let m=A.length-1;m>=0;m--)if(i.has(A[m]))return i.get(A[m]);return!1};s.copyHandlers.push((A,m,h)=>{m.EMAILID&&(h.EMAILID=m.EMAILID,h.THREADID=m.THREADID)}),s.allowedStatus.push("MAILBOXID"),s.statusHandlers.MAILBOXID=(A,m)=>[{type:"ATOM",value:l(m)}],s.fetchHandlers.EMAILID=(A,m)=>[{type:"ATOM",value:m.EMAILID}],s.fetchHandlers.THREADID=(A,m)=>[{type:"ATOM",value:m.THREADID}];let f=A=>{if(!Au.test(A))throw Q("Invalid object identifier");return A},p=A=>{let m=(h,d,E,I)=>d[A]===I;m.argumentTypes=()=>[f],s.searchHandlers[A]=m};p("EMAILID"),p("THREADID");let y=A=>({type:"SECTION",section:[{type:"ATOM",value:"MAILBOXID"},[{type:"ATOM",value:l(A)}]]});s.outputHandlers.push((A,m,h,d,E,I)=>{if(h==="CREATE"&&m.command==="OK"&&I){m.attributes=[y(I)].concat(m.attributes||[]);return}(h==="SELECT"||h==="EXAMINE")&&d&&m.tag===d.tag&&m.command==="OK"&&A.selectedMailbox&&A.send({tag:"*",command:"OK",attributes:[y(A.selectedMailbox),{type:"TEXT",value:"Ok"}]},h+" MAILBOXID",d,E)})}function bh(s){s=s||"";let e=s.search(/\r?\n\r?\n/),t=(e>=0?s.substr(0,e):s).replace(/\r?\n(?=[ \t])/g,""),r=n=>{let i=t.match(n);return i?i[1].match(/<[^<>\s]+>/g)||[]:[]};return{messageId:r(Eh)[0]||!1,references:r(Ah).concat(r(yh))}}g();var Th=s=>!!s&&s.type==="ATOM"&&String(s.value).toUpperCase()==="PARTIAL";function pi(s){Ie(s),s.registerCapability("PARTIAL"),s.partialRangeLast=!0,Vs(s);let e=(t,r,n,i,o)=>{let a=n.attributes&&n.attributes[2];if(Array.isArray(a)){for(let u=0;u<a.length;u+=2)if(Th(a[u])){try{if(n.partialFetch)throw new Error("PARTIAL can be used only once");n.partialFetch=Vt(a[u+1],!0)}catch(l){return r.sendStatus(n,i,"BAD",l.message,!1,(n.command||"").toUpperCase()+" FAILED"),o()}a.splice(u,2),u-=2}a.length||n.attributes.splice(2,1)}t(r,n,i,o)};["FETCH","UID FETCH"].forEach(t=>{let r=s.getCommandHandler(t);s.setCommandHandler(t,(n,i,o,a)=>e(r,n,i,o,a))}),s.fetchFilters.unshift((t,r,n)=>{if(!n.partialFetch)return!0;if(!n.partialFetchSet){let i=(n.command||"").toUpperCase()==="UID FETCH",o=t.getMessageRange(n.attributes[0].value,i).map(a=>a[1]);n.partialFetchSet=new Set(js(o,n.partialFetch))}return n.partialFetchSet.has(r)})}g();function Ei(s){s.registerCapability("PREVIEW");let e=new WeakMap,t=r=>{if(typeof r.preview=="string")return Iu(r.preview,Ih);let n=e.get(r);return n&&n.source===r.raw?n.preview:void 0};s.fetchHandlers.PREVIEW=function(r,n,i){let o=t(n);if(o===void 0){if(i.previewLazy)return null;o=xh(ne(n).tree),e.set(n,{source:n.raw,preview:o})}return b.Buffer.from(o,"utf8").toString("binary")},["FETCH","UID FETCH"].forEach(r=>{let n=s.getCommandHandler(r);s.setCommandHandler(r,(i,o,a,u)=>{try{Oh(o)}catch(l){return i.sendStatus(o,a,"BAD",l.message,!1,"PREVIEW FAILED"),u()}n(i,o,a,u)})})}var Sh=200,Ih=256,mi=64*1024,Su=s=>Array.isArray(s)&&s.length>0&&s.every(e=>J(e,"LAZY"));function yu(s,e){if(!e.length)throw new Error("PREVIEW modifier list can not be empty");if(!Su(e))throw new Error("Unknown PREVIEW modifier");return Object.assign({},s,{previewLazy:!0})}function Oh(s){let e=s.attributes;if(!Array.isArray(e))return;let t=e[1];if(Array.isArray(t)){for(let r=t.length-2;r>=0;r--)J(t[r],"PREVIEW")&&Array.isArray(t[r+1])&&(t[r]=yu(t[r],t[r+1]),t.splice(r+1,1));return}J(t,"PREVIEW")&&Array.isArray(e[2])&&(e.length>3||Su(e[2]))&&(e[1]=yu(t,e[2]),e.splice(2,1))}function xh(s){let e=gi(s);if(!e)return"";let t=Ch(e);return t===!1?"":Iu(e.parsedHeader["content-type"].subtype==="html"?Lh(t):Nh(t),Sh)}function gi(s){let{type:e,subtype:t}=s.parsedHeader["content-type"],r=s.parsedHeader["content-disposition"];if(r&&r.type==="attachment")return!1;if(e==="multipart"){if(t==="encrypted")return!1;let n=ot(s)||[];if(t==="alternative"){let i=n.map(gi).filter(o=>!!o);return i.find(o=>o.parsedHeader["content-type"].subtype==="plain")||i[0]||!1}for(let i of n){let o=gi(i);if(o)return o}return!1}return e==="text"&&(t==="plain"||t==="html")?s:!1}function Ch(s){let e=String(s.parsedHeader["content-transfer-encoding"]||"7bit").toLowerCase(),t=s.body,r;switch(e){case"7bit":case"8bit":case"binary":r=b.Buffer.from(t.slice(0,mi),"binary");break;case"base64":r=b.Buffer.from(t.slice(0,mi*4/3),"base64");break;case"quoted-printable":r=wh(t.slice(0,mi));break;default:return!1}let n=String(s.parsedHeader["content-type"].params.charset||"").trim().toLowerCase(),i;if(n&&!["us-ascii","ascii"].includes(n))try{i=new TextDecoder(n)}catch{}return(i||new TextDecoder("utf-8")).decode(r)}function wh(s){let e=s.split(`\r
28
+ `,flags:[],uid:1},_)}catch(X){throw Q(X.message)}}return v})},w=(x,L,v,V)=>{let _=new Set,X=null;if(J(L,"NONE"))return{events:_,fetch:X};if(!Array.isArray(L)||!L.length)throw Q("Expecting a list of events or NONE");for(let q=0;q<L.length;q++){let se=L[q];if(!J(se)||se.section||se.partial)throw Q("Invalid event");let ee=fh.get(se.value.toUpperCase());if(Array.isArray(L[q+1])&&ee==="MessageNew"){if(!v)throw Q("Fetch attributes for MessageNew are only allowed with SELECTED or SELECTED-DELAYED");X=N(x,L[++q])}if(!ee){V.push(se.value);continue}if(v&&nr.indexOf(ee)<0)throw Q(ee+" can not be used with SELECTED or SELECTED-DELAYED");_.add(ee)}if(_.has("MessageNew")!==_.has("MessageExpunge"))throw Q("MessageNew and MessageExpunge must be used together");if((_.has("FlagChange")||_.has("AnnotationChange"))&&!_.has("MessageNew"))throw Q("FlagChange and AnnotationChange require MessageNew and MessageExpunge");return{events:_,fetch:X}},G=(x,L)=>{let v=Array.isArray(L)?L:[L];if(!v.length||!v.every(ue))throw Q("Expecting a mailbox name or a list of mailbox names");return v.map(V=>o(x.importMailboxName(V.value)))},F=(x,L)=>{let v={selected:null,groups:[],unseen:new WeakMap},V=[];if(J(L[0],"NONE")){if(L.length!==1)throw Q("NOTIFY NONE does not take any arguments");return{state:v,status:!1,unknown:V}}if(!J(L[0],"SET"))throw Q("NOTIFY expects SET or NONE");let _=J(L[1],"STATUS"),X=L.slice(_?2:1);if(!X.length)throw Q("NOTIFY SET expects event groups");return X.forEach(q=>{if(!Array.isArray(q)||!J(q[0]))throw Q("Invalid event group");let se=q[0].value.toUpperCase();if(hh.indexOf(se)>=0){if(q.length!==2)throw Q("Invalid event group");if(v.selected)throw Q("Only one of SELECTED and SELECTED-DELAYED can be used");v.selected=Object.assign({delayed:se==="SELECTED-DELAYED"},w(x,q[1],!0,V))}else if(dh.indexOf(se)>=0){let ee=se==="SUBTREE"||se==="MAILBOXES";if(q.length!==(ee?3:2))throw Q("Invalid event group");let fe=ee?G(x,q[1]):[],{events:is}=w(x,q[q.length-1],!1,V),Nr=se==="SUBTREE"?fe.map(Lt=>Lt+s.getSeparator(Lt)):[];v.groups.push({filter:se,paths:fe,prefixes:Nr,events:is})}else throw Q("Unknown mailbox filter "+q[0].value)}),{state:v,status:_,unknown:V}},W=(x,L,v,V)=>{Object.keys(s.folderCache).sort((X,q)=>X==="INBOX"?-1:q==="INBOX"?1:X.localeCompare(q)).forEach(X=>{let q=s.folderCache[X];if(q===x.selectedMailbox||q.flags.some(fe=>/^\\(Noselect|NonExistent)$/i.test(fe)))return;let se=u(x,X,q);if(!se.size||!n(x,q))return;if(!i(x,q)){x.send(d(x,X,{noAccess:!0}),"NOTIFY LIST",v,V);return}if(!L||!se.has("MessageNew"))return;let ee=["MESSAGES","UIDNEXT","UIDVALIDITY"];if(se.has("FlagChange")){ee.push("UNSEEN");let fe=s.getStatus(q);x.notifyState.unseen.set(q,fe&&fe.unseen||0),s.condstore&&ee.push("HIGHESTMODSEQ")}x.send(er(x,X,q,ee),"NOTIFY STATUS",v,V)})};s.setCommandHandler("NOTIFY",(x,L,v,V)=>{let _;try{_=F(x,L.attributes||[])}catch(ee){return x.sendStatus(L,v,"BAD",ee.imapResponse==="BAD"?ee.message:"Invalid NOTIFY arguments"),V()}let X=t(),q=[_.state.selected].concat(_.state.groups).filter(ee=>!!ee);return _.unknown.concat(...q.map(ee=>[...ee.events].filter(fe=>X.indexOf(fe)<0))).length?(x.send({tag:L.tag,command:"NO",attributes:[{type:"SECTION",section:[{type:"ATOM",value:"BADEVENT"},X.map(ee=>({type:"ATOM",value:ee}))]},{type:"TEXT",value:"Unsupported NOTIFY events"}]},"NOTIFY FAILED",L,v),V()):(x.notifyState=_.state,W(x,_.status,L,v),x.sendStatus(L,v,"OK","NOTIFY completed"),V())},{states:Z.AUTHENTICATED})}E();var mh=new TextDecoder("utf-8",{fatal:!0});function gh(s){let e=s.toString("binary");if(e==="")return{kvsepOnly:!0};let t=e.match(/^(?:F,)?(n|y|p=[A-Za-z0-9.-]+),(?:a=([^,]+))?,/);if(!t||e.charAt(t[0].length)!=="")return{error:"Invalid GS2 header"};let r=!1;if(t[2]){if(/=(?!2C|3D)/.test(t[2])||t[2].includes("\0"))return{error:"Invalid authorization identity"};try{r=mh.decode(b.Buffer.from(t[2].replace(/=2C/g,",").replace(/=3D/g,"="),"binary"))}catch{return{error:"Invalid UTF-8 in the authorization identity"}}}let n=e.substr(t[0].length+1).split("");if(n.pop()!==""||n.pop()!=="")return{error:"The client response must end with %x01"};let i=Object.create(null);for(let o of n){let a=o.match(/^([A-Za-z]+)=([\x20-\x7e\t\r\n]*)$/);if(!a)return{error:"Invalid key/value pair"};i[a[1]]=a[2]}return{channelBinding:t[1].charAt(0)==="p",authzid:r,pairs:i}}function hi(s){s.registerCapability("AUTH=OAUTHBEARER",a=>a.state==="Not Authenticated");let e=(a,u,l,c,f)=>{a.sendStatus(u,l,c,f,c==="NO"&&"AUTHENTICATIONFAILED","AUTHENTICATE OAUTHBEARER FAILED")},t=a=>{if(a.channelBinding)return"invalid_request";let{auth:u,port:l}=a.pairs;if(typeof l=="string"&&!/^[1-9][0-9]*$/.test(l))return"invalid_request";let c=typeof u=="string"&&u.match(/^Bearer +([A-Za-z0-9\-._~+/]+=*)$/i);if(!c)return u===""?"invalid_token":"invalid_request";let f=c[1],p=s.checkAccessToken(f,a.authzid===!1?void 0:a.authzid);return"error"in p?p.error:(a.username=p.user,!1)},r=a=>s.oauth&&s.oauth.issuer?{status:a,scope:s.oauth.mailScope,"openid-configuration":s.oauth.discoveryUrl()}:{status:a},n=(a,u,l,c)=>{let f=a.decodeSaslResponse(c);return f||e(a,u,l,"BAD","Invalid base64 in SASL response"),f},i=(a,u,l,c)=>{a.inputHandler=f=>{if(a.inputHandler=!1,f==="*")return e(a,u,l,"BAD","Authentication cancelled");let p=n(a,u,l,f);p&&c(p)}},o=(a,u,l,c)=>{let f=gh(c);if(f.error)return e(a,u,l,"BAD",f.error+" in the OAUTHBEARER client response");if(f.kvsepOnly)return e(a,u,l,"NO","SASL authentication failed");let p=t(f);if(!p)return a.state="Authenticated",a.username=f.username,a.sendStatus(u,l,"OK","SASL authentication succeeded",!1,"AUTHENTICATE OAUTHBEARER SUCCESS");i(a,u,l,y=>{if(y.toString("binary")!=="")return e(a,u,l,"BAD","The client must answer the error result with a single %x01 (RFC 7628 section 3.2.3)");e(a,u,l,"NO","SASL authentication failed")}),a.send({tag:"+",attributes:[{type:"ATOM",value:b.Buffer.from(JSON.stringify(r(p))).toString("base64")}]},"AUTHENTICATE OAUTHBEARER CHALLENGE",u,l)};s.setCommandHandler("AUTHENTICATE OAUTHBEARER",(a,u,l,c)=>{let f=u.attributes||[];if(!f.length)return i(a,u,l,y=>o(a,u,l,y)),a.sendContinuation("","AUTHENTICATE OAUTHBEARER"),c();if(f.length!==1||!f[0]||f[0].type!=="ATOM")return e(a,u,l,"BAD","Invalid arguments for AUTHENTICATE OAUTHBEARER"),c();if(!s.capabilities["SASL-IR"]||!s.capabilities["SASL-IR"](a))return e(a,u,l,"BAD","SASL-IR must be enabled to send Initial Response with the request"),c();let p=n(a,u,l,f[0].value);return p&&o(a,u,l,p),c()})}E();var Au=/^[A-Za-z0-9_-]{1,255}$/,Eh=/^Message-ID[ \t]*:(.*)$/im,Ah=/^References[ \t]*:(.*)$/im,yh=/^In-Reply-To[ \t]*:(.*)$/im,ir=Symbol("mailboxid-uidvalidity");function di(s){s.registerCapability("OBJECTID");let e=new Map,t={F:0,M:0,T:0},r=new Map,n=new Map,i=new Map,o=A=>{let m;do m=A+ ++t[A];while(e.has(m));return e.set(m,A),m},a=(A,m,h)=>{if(typeof A!="string"||!Au.test(A))throw new Error("Invalid "+m+" value "+JSON.stringify(A)+" in "+h)},u=(A,m)=>{if(e.has(A)&&e.get(A)!==m)throw new Error("Object identifier "+JSON.stringify(A)+" is already used for another kind of object");e.set(A,m)},l=A=>{if(A[ir]===A.uidvalidity&&r.get(A.MAILBOXID)===A)return A.MAILBOXID;let m;return A.MAILBOXID&&A[ir]===void 0&&!r.has(A.MAILBOXID)?(m=A.MAILBOXID,a(m,"MAILBOXID","mailbox "+A.path),u(m,"F")):m=o("F"),A.MAILBOXID=m,A[ir]=A.uidvalidity,r.set(m,A),m};s.mailboxHandlers.push((A,m)=>{if(!(m.flags.indexOf("\\Noselect")>=0)){if(m.MAILBOXID&&m[ir]===void 0&&r.has(m.MAILBOXID))throw new Error("Duplicate MAILBOXID value "+JSON.stringify(m.MAILBOXID)+" in mailbox "+m.path);l(m)}}),s.control.mailboxInfoHandlers.push((A,m)=>{A.flags.indexOf("\\Noselect")<0&&(m.mailboxId=l(A))}),s.control.messageInfoHandlers.push((A,m)=>{m.emailId=A.EMAILID,m.threadId=A.THREADID}),s.messageHandlers.push((A,m,h)=>{let d="a message of mailbox "+h.path;m.EMAILID?(a(m.EMAILID,"EMAILID",d),u(m.EMAILID,"M")):m.EMAILID=o("M"),m.THREADID&&(a(m.THREADID,"THREADID",d),u(m.THREADID,"T"));let g=n.get(m.EMAILID);if(g&&m.THREADID&&m.THREADID!==g)throw new Error("Messages with EMAILID "+JSON.stringify(m.EMAILID)+" must have the same THREADID");let T=bh(m.raw);m.THREADID=m.THREADID||g||c(T.references)||o("T"),n.set(m.EMAILID,m.THREADID),[T.messageId].concat(T.references).forEach(C=>{C&&!i.has(C)&&i.set(C,m.THREADID)})});let c=A=>{for(let m=A.length-1;m>=0;m--)if(i.has(A[m]))return i.get(A[m]);return!1};s.copyHandlers.push((A,m,h)=>{m.EMAILID&&(h.EMAILID=m.EMAILID,h.THREADID=m.THREADID)}),s.allowedStatus.push("MAILBOXID"),s.statusHandlers.MAILBOXID=(A,m)=>[{type:"ATOM",value:l(m)}],s.fetchHandlers.EMAILID=(A,m)=>[{type:"ATOM",value:m.EMAILID}],s.fetchHandlers.THREADID=(A,m)=>[{type:"ATOM",value:m.THREADID}];let f=A=>{if(!Au.test(A))throw Q("Invalid object identifier");return A},p=A=>{let m=(h,d,g,T)=>d[A]===T;m.argumentTypes=()=>[f],s.searchHandlers[A]=m};p("EMAILID"),p("THREADID");let y=A=>({type:"SECTION",section:[{type:"ATOM",value:"MAILBOXID"},[{type:"ATOM",value:l(A)}]]});s.outputHandlers.push((A,m,h,d,g,T)=>{if(h==="CREATE"&&m.command==="OK"&&T){m.attributes=[y(T)].concat(m.attributes||[]);return}(h==="SELECT"||h==="EXAMINE")&&d&&m.tag===d.tag&&m.command==="OK"&&A.selectedMailbox&&A.send({tag:"*",command:"OK",attributes:[y(A.selectedMailbox),{type:"TEXT",value:"Ok"}]},h+" MAILBOXID",d,g)})}function bh(s){s=s||"";let e=s.search(/\r?\n\r?\n/),t=(e>=0?s.substr(0,e):s).replace(/\r?\n(?=[ \t])/g,""),r=n=>{let i=t.match(n);return i?i[1].match(/<[^<>\s]+>/g)||[]:[]};return{messageId:r(Eh)[0]||!1,references:r(Ah).concat(r(yh))}}E();var Th=s=>!!s&&s.type==="ATOM"&&String(s.value).toUpperCase()==="PARTIAL";function pi(s){Ie(s),s.registerCapability("PARTIAL"),s.partialRangeLast=!0,Vs(s);let e=(t,r,n,i,o)=>{let a=n.attributes&&n.attributes[2];if(Array.isArray(a)){for(let u=0;u<a.length;u+=2)if(Th(a[u])){try{if(n.partialFetch)throw new Error("PARTIAL can be used only once");n.partialFetch=Vt(a[u+1],!0)}catch(l){return r.sendStatus(n,i,"BAD",l.message,!1,(n.command||"").toUpperCase()+" FAILED"),o()}a.splice(u,2),u-=2}a.length||n.attributes.splice(2,1)}t(r,n,i,o)};["FETCH","UID FETCH"].forEach(t=>{let r=s.getCommandHandler(t);s.setCommandHandler(t,(n,i,o,a)=>e(r,n,i,o,a))}),s.fetchFilters.unshift((t,r,n)=>{if(!n.partialFetch)return!0;if(!n.partialFetchSet){let i=(n.command||"").toUpperCase()==="UID FETCH",o=t.getMessageRange(n.attributes[0].value,i).map(a=>a[1]);n.partialFetchSet=new Set(js(o,n.partialFetch))}return n.partialFetchSet.has(r)})}E();function Ei(s){s.registerCapability("PREVIEW");let e=new WeakMap,t=r=>{if(typeof r.preview=="string")return Iu(r.preview,Ih);let n=e.get(r);return n&&n.source===r.raw?n.preview:void 0};s.fetchHandlers.PREVIEW=function(r,n,i){let o=t(n);if(o===void 0){if(i.previewLazy)return null;o=xh(ne(n).tree),e.set(n,{source:n.raw,preview:o})}return b.Buffer.from(o,"utf8").toString("binary")},["FETCH","UID FETCH"].forEach(r=>{let n=s.getCommandHandler(r);s.setCommandHandler(r,(i,o,a,u)=>{try{Oh(o)}catch(l){return i.sendStatus(o,a,"BAD",l.message,!1,"PREVIEW FAILED"),u()}n(i,o,a,u)})})}var Sh=200,Ih=256,mi=64*1024,Su=s=>Array.isArray(s)&&s.length>0&&s.every(e=>J(e,"LAZY"));function yu(s,e){if(!e.length)throw new Error("PREVIEW modifier list can not be empty");if(!Su(e))throw new Error("Unknown PREVIEW modifier");return Object.assign({},s,{previewLazy:!0})}function Oh(s){let e=s.attributes;if(!Array.isArray(e))return;let t=e[1];if(Array.isArray(t)){for(let r=t.length-2;r>=0;r--)J(t[r],"PREVIEW")&&Array.isArray(t[r+1])&&(t[r]=yu(t[r],t[r+1]),t.splice(r+1,1));return}J(t,"PREVIEW")&&Array.isArray(e[2])&&(e.length>3||Su(e[2]))&&(e[1]=yu(t,e[2]),e.splice(2,1))}function xh(s){let e=gi(s);if(!e)return"";let t=Ch(e);return t===!1?"":Iu(e.parsedHeader["content-type"].subtype==="html"?Lh(t):Nh(t),Sh)}function gi(s){let{type:e,subtype:t}=s.parsedHeader["content-type"],r=s.parsedHeader["content-disposition"];if(r&&r.type==="attachment")return!1;if(e==="multipart"){if(t==="encrypted")return!1;let n=ot(s)||[];if(t==="alternative"){let i=n.map(gi).filter(o=>!!o);return i.find(o=>o.parsedHeader["content-type"].subtype==="plain")||i[0]||!1}for(let i of n){let o=gi(i);if(o)return o}return!1}return e==="text"&&(t==="plain"||t==="html")?s:!1}function Ch(s){let e=String(s.parsedHeader["content-transfer-encoding"]||"7bit").toLowerCase(),t=s.body,r;switch(e){case"7bit":case"8bit":case"binary":r=b.Buffer.from(t.slice(0,mi),"binary");break;case"base64":r=b.Buffer.from(t.slice(0,mi*4/3),"base64");break;case"quoted-printable":r=wh(t.slice(0,mi));break;default:return!1}let n=String(s.parsedHeader["content-type"].params.charset||"").trim().toLowerCase(),i;if(n&&!["us-ascii","ascii"].includes(n))try{i=new TextDecoder(n)}catch{}return(i||new TextDecoder("utf-8")).decode(r)}function wh(s){let e=s.split(`\r
29
29
  `).map(t=>{let r=t.length;for(;r>0&&(t[r-1]===" "||t[r-1]===" ");)r--;return t.slice(0,r)}).join(`\r
30
30
  `).replace(/=\r\n/g,"").replace(/=([0-9A-Fa-f]{2})/g,(t,r)=>String.fromCharCode(parseInt(r,16)));return b.Buffer.from(e,"binary")}function Nh(s){let e=s.split(/\r?\n/).filter(t=>!/^>/.test(t)).join(`
31
- `);return e.trim()?e:s}var Mh=new Set(["a","abbr","b","bdi","bdo","big","cite","code","del","dfn","em","font","i","ins","kbd","mark","q","s","samp","small","span","strike","strong","sub","sup","time","tt","u","var","wbr"]),Rh="nbsp iexcl cent pound curren yen brvbar sect uml copy ordf laquo not shy reg macr deg plusmn sup2 sup3 acute micro para middot cedil sup1 ordm raquo frac14 frac12 frac34 iquest Agrave Aacute Acirc Atilde Auml Aring AElig Ccedil Egrave Eacute Ecirc Euml Igrave Iacute Icirc Iuml ETH Ntilde Ograve Oacute Ocirc Otilde Ouml times Oslash Ugrave Uacute Ucirc Uuml Yacute THORN szlig agrave aacute acirc atilde auml aring aelig ccedil egrave eacute ecirc euml igrave iacute icirc iuml eth ntilde ograve oacute ocirc otilde ouml divide oslash ugrave uacute ucirc uuml yacute thorn yuml",bu=Object.assign(Object.fromEntries(Rh.split(" ").map((s,e)=>[s,String.fromCharCode(160+e)])),{amp:"&",lt:"<",gt:">",quot:'"',apos:"'",trade:"\u2122",hellip:"\u2026",mdash:"\u2014",ndash:"\u2013",lsquo:"\u2018",rsquo:"\u2019",ldquo:"\u201C",rdquo:"\u201D",bull:"\u2022",euro:"\u20AC",zwnj:"\u200C",zwj:"\u200D"});function Lh(s){s=s.replace(/<!--[\s\S]*?(?:-->|$)/g," ").replace(/<(head|script|style|title|template)\b[^<>]*>[\s\S]*?(?:<\/\1\s*>|$)/gi," ");let e=Tu(Dh(s));return e.trim()?e:Tu(s)}function Dh(s){let e=/<(\/?)blockquote\b[^<>]*>?/gi,t="",r=0,n=0,i;for(;i=e.exec(s);)r||(t+=s.slice(n,i.index)+" "),r=i[1]?Math.max(r-1,0):r+1,n=e.lastIndex;return r?t:t+s.slice(n)}function Tu(s){return s.replace(/<!\[CDATA\[([\s\S]*?)(?:\]\]>|$)/g,"$1").replace(/<\/?([A-Za-z][A-Za-z0-9-]*)(?![A-Za-z0-9-])[^<>]*>|<[!?][^<>]*>/g,(e,t)=>t&&Mh.has(t.toLowerCase())?"":" ").replace(/&(#[0-9]+|#[xX][0-9A-Fa-f]+|[A-Za-z][A-Za-z0-9]*);/g,(e,t)=>{if(t[0]==="#"){let r=/^#x/i.test(t)?parseInt(t.slice(2),16):parseInt(t.slice(1),10);return r>0&&r<=1114111&&(r<55296||r>57343)?String.fromCodePoint(r):"\uFFFD"}return Object.hasOwn(bu,t)?bu[t]:e})}function Iu(s,e){let t=s.replace(/[^\P{Cc}\t\n\v\f\r]|\u00ad/gu,"").replace(/[\s\u200b]+/g," ").trim();return Array.from(t).slice(0,e).join("").trimEnd()}g();g();function or(s){let e=!!s.message&&!!s.attributes&&s.attributes[1];return!!e&&e.type==="ATOM"&&String(e.value).toUpperCase()==="EXPUNGE"}function ar(s){if(!s.some(or))return s;let e=[];return s.forEach(t=>{or(t)?Array.isArray(e[e.length-1])?e[e.length-1].push(t.message):e.push([t.message]):e.push(t)}),e.map(t=>Array.isArray(t)?{tag:"*",command:"VANISHED",attributes:[{type:"SEQUENCE",value:lt(t.map(r=>r.uid))}],notification:!0,messages:t}:t)}var Uh=new Set(["EXPUNGE","UID EXPUNGE","MOVE","UID MOVE","REPLACE","UID REPLACE"]);function ur(s){s.registerCapability("QRESYNC"),Ne(s,"QRESYNC"),s.resetHandlers.push(m=>{m.qresyncExpunged=!1});let e=new WeakMap,t=m=>ye(m,"QRESYNC"),{isEnabled:r,getHighestModseq:n}=s.condstore,i=(m,h)=>((!m.qresyncExpunged||m.qresyncExpunged.uidvalidity!==m.uidvalidity)&&(m.qresyncExpunged={uidvalidity:m.uidvalidity,since:h||n(m),list:[]}),m.qresyncExpunged),o=s.indexFolders;s.indexFolders=function(...m){let h=o.apply(this,m);return Object.keys(this.folderCache).forEach(d=>i(this.folderCache[d])),h},s.on("expunge",(m,h,d)=>{let E=n(m),I=i(m,E-1).list;h.forEach(C=>{let H=I[I.length-1];H&&H.modseq===E&&H.to+1===C.uid?H.to=C.uid:I.push({from:C.uid,to:C.uid,modseq:E}),e.set(C,E)}),d&&(d.qresyncExpunged=!0)});let a=(m,h,d,E,I)=>{let{since:C,list:H}=i(m),N;return E>=C?N=Ou(yi(H.filter(w=>w.modseq>E).map(w=>[w.from,w.to])),d):N=Ou(d,[[(I||0)+1,m.uidnext-1]]),Bh(N,h).map(w=>w[0]===w[1]?String(w[0]):w[0]+":"+w[1]).join(",")},u=(m,h,d,E,I)=>(m.sendStatus(h,d,"BAD",I,!1,"QRESYNC FAILED"),E()),l=(m,h)=>{let d=s.getCommandHandler(m);d&&s.setCommandHandler(m,(E,I,C,H)=>h(d,E,I,C,H))},c=(m,h,d,E,I)=>{let C=d.attributes&&d.attributes[1],H=G=>J(G,"QRESYNC"),N=Array.isArray(C)?C.findIndex(H):-1;if(N<0)return m(h,d,E,I);if(!t(h))return u(h,d,E,I,"QRESYNC parameter requires ENABLE QRESYNC");if(C.findLastIndex(H)!==N)return u(h,d,E,I,"QRESYNC parameter can be used only once");let w;try{w=Hh(C[N+1])}catch(G){return u(h,d,E,I,G.message)}C.splice(N,2),C.length||d.attributes.splice(1,1),d.qresync=w,m(h,d,E,I)};l("SELECT",c),l("EXAMINE",c);let f=(m,h,d,E,I,C)=>{let H=E.attributes&&E.attributes[2],N=G=>J(G,"VANISHED"),w=Array.isArray(H)?H.findIndex(N):-1;if(w<0)return h(d,E,I,C);if(!m)return u(d,E,I,C,"VANISHED is only allowed with UID FETCH");if(!t(d))return u(d,E,I,C,"VANISHED requires ENABLE QRESYNC");if(H.findLastIndex(N)!==w)return u(d,E,I,C,"VANISHED can be used only once");if(!H.some(G=>J(G,"CHANGEDSINCE")))return u(d,E,I,C,"VANISHED requires CHANGEDSINCE");H.splice(w,1),E.qresyncVanished=!0,h(d,E,I,C)};l("FETCH",f.bind(null,!1)),l("UID FETCH",f.bind(null,!0)),s.connectionHandlers.push(m=>{let h=m.prepareNotifications;m.prepareNotifications=function(d){return d=h.call(this,d),t(this)?ar(d):d}});let p=(m,h,d,E)=>{h&&m.send({tag:"*",command:"VANISHED",attributes:[[{type:"ATOM",value:"EARLIER"}],{type:"SEQUENCE",value:h}]},"VANISHED EARLIER",d,E)},y=(m,h,d)=>{let E=m.selectedMailbox,I=h.qresync;if(I.uidvalidity!==E.uidvalidity)return;let C=I.knownUids||(E.uidnext>1?[[1,E.uidnext-1]]:[]),H=0;if(I.seqMatch){let w=xu(I.seqMatch.uids);for(let G of xu(I.seqMatch.sequences)){let F=w.next().value,W=E.messages[G-1];if(!W||W.uid!==F)break;H=F}}p(m,a(E,E.messages,C,I.modseq,H),h,d);let N=s.fetchHandlers.FLAGS||Te.FLAGS;E.messages.forEach((w,G)=>{w.MODSEQ<=I.modseq||!kh(C,w.uid)||m.send({tag:"*",attributes:[G+1,{type:"ATOM",value:"FETCH"},[{type:"ATOM",value:"UID"},w.uid,{type:"ATOM",value:"FLAGS"},N(m,w,{type:"ATOM",value:"FLAGS"}),{type:"ATOM",value:"MODSEQ"},[w.MODSEQ]]]},"QRESYNC FETCH",h,d,w)})},A=m=>({type:"SECTION",section:[{type:"ATOM",value:"HIGHESTMODSEQ"},m]});s.outputHandlers.push((m,h,d,E,I)=>{if(!E||!h||h.tag==="+")return;let C=h.tag!=="*"&&h.tag===E.tag;if(E.qresyncVanished&&(h.tag==="*"&&d==="UID FETCH"||C&&h.command==="OK")){E.qresyncVanished=!1;let N=m.selectedMailbox,w=vh(E.attributes[0].value,N.uidnext-1);w&&p(m,a(N,m.getSessionMessages(),w,E.changedsince),E,I);return}if(!C)return;if(E.qresync&&h.command==="OK"&&(d==="SELECT"||d==="EXAMINE")&&m.selectedMailbox){y(m,E,I);return}let H=m.qresyncExpunged;if(m.qresyncExpunged=!1,H&&h.command==="OK"&&Uh.has(String(E.command).toUpperCase())&&m.selectedMailbox&&r(m)){h.attributes&&h.attributes[0]&&h.attributes[0].type==="SECTION"||(h.attributes=[A(n(m.selectedMailbox))].concat(h.attributes||[]));return}if(r(m)){let N=0;m.notificationQueue.forEach(w=>{let G=or(w)&&w.message&&e.get(w.message);G&&(!N||G<N)&&(N=G)}),N>1&&m.send({tag:"*",command:"OK",attributes:[A(N-1),{type:"TEXT",value:"Expunges not reported yet"}]},"QRESYNC HIGHESTMODSEQ",E,I)}})}function Ai(s,e){if(!s||Array.isArray(s)||["ATOM","SEQUENCE"].indexOf(s.type)<0||!Is(s.value,!0))throw new Error("Invalid QRESYNC "+e+', a sequence set without "*" expected');return s.value.split(",").map(t=>{let r=t.split(":").map(Number);return[r[0],r.length>1?r[1]:r[0]]})}function vh(s,e){return/^[\d*:,]+$/.test(String(s))?yi(String(s).split(",").map(t=>t.split(":").map(r=>r==="*"?e:Number(r)))):!1}function Ou(s,e){let t=[],r=0,n=0;for(;r<s.length&&n<e.length;){let i=Math.max(s[r][0],e[n][0]),o=Math.min(s[r][1],e[n][1]);i<=o&&t.push([i,o]),s[r][1]<e[n][1]?r++:n++}return t}function Bh(s,e){let t=[],r=0;return s.forEach(([n,i])=>{let o=n;for(;r<e.length&&e[r].uid<n;)r++;for(;r<e.length&&e[r].uid<=i;r++)e[r].uid>o&&t.push([o,e[r].uid-1]),o=e[r].uid+1;o<=i&&t.push([o,i])}),t}function yi(s){let e=s.map(r=>[Math.min(...r),Math.max(...r)]).sort((r,n)=>r[0]-n[0]),t=[];return e.forEach(r=>{let n=t[t.length-1];n&&r[0]<=n[1]+1?n[1]=Math.max(n[1],r[1]):t.push(r)}),t}function*xu(s){for(let[e,t]of s)for(let r=e;r<=t;r++)yield r}function Cu(s,e){let t=0,r=0;return s.forEach(([n,i])=>{if(n>i||n<=t)throw new Error("Invalid QRESYNC "+e+", numbers must be in ascending order");t=i,r+=i-n+1}),r}function Hh(s){if(!Array.isArray(s)||s.length<2||s.length>4)throw new Error("QRESYNC expects (uidvalidity modseq [known-uids] [(known-sequence-set known-uid-set)])");let[e,t]=s;if(!J(e)||!Le(e.value))throw new Error("Invalid QRESYNC uidvalidity, a non-zero number expected");if(!J(t)||!Ae(t.value,Ge)||BigInt(t.value)<1n)throw new Error("Invalid QRESYNC mod-sequence, a positive number expected");let r={uidvalidity:Number(e.value),modseq:Number(t.value),knownUids:!1,seqMatch:!1},n=s.slice(2);if(n.length&&!Array.isArray(n[0])&&(r.knownUids=yi(Ai(n.shift(),"known-uids"))),n.length){let i=n.shift();if(!Array.isArray(i)||i.length!==2||n.length)throw new Error("Invalid QRESYNC parameters, (known-sequence-set known-uid-set) expected last");let o=Ai(i[0],"known-sequence-set"),a=Ai(i[1],"known-uid-set"),u=Cu(o,"known-sequence-set");if(Cu(a,"known-uid-set")!==u)throw new Error("Invalid QRESYNC sets, known-sequence-set and known-uid-set must have as many numbers");r.seqMatch={sequences:o,uids:a}}return r}function kh(s,e){return s.some(t=>e>=t[0]&&e<=t[1])}ur.requires=["ENABLE","CONDSTORE"];g();var Mt=["STORAGE","MESSAGE","MAILBOX"],Ph="User quota";function bi(s){let e=s.options.quota||{},t={name:typeof e.root=="string"?e.root:Ph,soft:!!e.soft,limits:{}},r={};Mt.forEach(h=>{if(e[h]===void 0||e[h]===null)return;let d=Number(e[h]);if(!Number.isSafeInteger(d)||d<0)throw new Error("Invalid quota limit for "+h+": "+JSON.stringify(e[h]));r[h]=d});let n=()=>{t.limits=Object.assign({},r)};n(),s.on("reset",n),s.registerCapability("QUOTA"),Mt.forEach(h=>s.registerCapability("QUOTA=RES-"+h)),s.registerCapability("QUOTASET");let i=h=>s.isPersonal(h),o=h=>h.flags.indexOf("\\Noselect")<0,a=h=>h.reduce((d,E)=>d+_t(E.raw).length,0),u=()=>{let h={MESSAGE:0,MAILBOX:0,bytes:0};return Object.keys(s.folderCache).forEach(d=>{let E=s.folderCache[d];!o(E)||!i(E)||(h.MAILBOX++,h.MESSAGE+=E.messages.length,h.bytes+=a(E.messages))}),h},l=(h,d,E)=>{let I=u();I.STORAGE=Math.ceil(I.bytes/1024);let C=[];Mt.forEach(H=>{H in t.limits&&C.push({type:"ATOM",value:H},I[H],t.limits[H])}),h.send({tag:"*",command:"QUOTA",attributes:[{type:"STRING",value:t.name},C]},"QUOTA",d,E)},c=h=>{if(!(h.MESSAGE&&"MESSAGE"in t.limits||h.bytes&&"STORAGE"in t.limits||h.MAILBOX&&"MAILBOX"in t.limits))return;let E=u();if(h.MESSAGE&&"MESSAGE"in t.limits&&E.MESSAGE+h.MESSAGE>t.limits.MESSAGE||h.bytes&&"STORAGE"in t.limits&&E.bytes+h.bytes>t.limits.STORAGE*1024||h.MAILBOX&&"MAILBOX"in t.limits&&E.MAILBOX+h.MAILBOX>t.limits.MAILBOX)return t.soft?{code:"OVERQUOTA",text:"Soft quota has been exceeded",soft:!0}:{code:"OVERQUOTA",text:"Quota exceeded"}};s.appendChecks.push((h,d,E,I)=>{if(!E.length||!i(d)||I.move&&I.source&&i(I.source))return;let C={MESSAGE:E.length,bytes:a(E)};return I.replaced&&h&&h.selectedMailbox&&i(h.selectedMailbox)&&(C.MESSAGE--,C.bytes-=a([I.replaced])),c(C)});let f=h=>{let d=s.getMailbox(s.stripSeparator(h,s.getSeparator(h))),E=!d||!o(d)?1:0;for(let I=s.getParentPath(h);I;I=s.getParentPath(I))s.getMailbox(I)||E++;return E},p=(h,d)=>{let E=s.getCommandHandler(h);s.setCommandHandler(h,(I,C,H,N)=>{let w=d(C.attributes);if(typeof w=="string"&&w.toUpperCase()!=="INBOX"&&i(w)&&!I.applyChecks([c({MAILBOX:f(w)})],C,H,h+" FAILED"))return N();E(I,C,H,N)})},y=(h,d)=>ue((h||[])[d])&&h[d].value;p("CREATE",h=>h&&h.length===1?y(h,0):!1),p("RENAME",h=>{let d=y(h,0);return h&&h.length===2&&typeof d=="string"&&d.toUpperCase()==="INBOX"?y(h,1):!1}),s.setCommandHandler("GETQUOTA",(h,d,E,I)=>!d.attributes||d.attributes.length!==1||!ue(d.attributes[0])?(h.sendStatus(d,E,"BAD","GETQUOTA expects a quota root name"),I()):d.attributes[0].value!==t.name?(h.sendStatus(d,E,"NO","Quota root does not exist","NONEXISTENT"),I()):(l(h,d,E),h.sendStatus(d,E,"OK","GETQUOTA completed"),I()),{states:Z.AUTHENTICATED,astringArguments:[0]}),s.setCommandHandler("GETQUOTAROOT",(h,d,E,I)=>{if(!d.attributes||d.attributes.length!==1||!ue(d.attributes[0]))return h.sendStatus(d,E,"BAD","GETQUOTAROOT expects a mailbox name"),I();let C=d.attributes[0].value;C.toUpperCase()==="INBOX"&&(C="INBOX");let H=i(C);return h.send({tag:"*",command:"QUOTAROOT",attributes:[{type:"MAILBOX",value:C}].concat(H?{type:"STRING",value:t.name}:[])},"QUOTAROOT",d,E),H&&l(h,d,E),h.sendStatus(d,E,"OK","GETQUOTAROOT completed"),I()},{states:Z.AUTHENTICATED,mailboxArguments:[0]}),s.setCommandHandler("SETQUOTA",(h,d,E,I)=>{let C=d.attributes&&d.attributes[1];if(!d.attributes||d.attributes.length!==2||!ue(d.attributes[0])||!Array.isArray(C)||C.length%2)return h.sendStatus(d,E,"BAD","SETQUOTA expects a quota root name and a list of resource limits"),I();let H={};for(let N=0;N<C.length;N+=2){let w=C[N],G=C[N+1];if(!w||w.type!=="ATOM"||!G||G.type!=="ATOM"||!Ae(G.value,Ge))return h.sendStatus(d,E,"BAD","Invalid resource limit"),I();let F=w.value.toUpperCase();if(Mt.indexOf(F)<0||F in H)return h.sendStatus(d,E,"NO","Can not set a limit for "+F,"CANNOT"),I();let W=Number(G.value);if(!Number.isSafeInteger(W))return h.sendStatus(d,E,"NO","Limit is too large for "+F,"LIMIT"),I();H[F]=W}return d.attributes[0].value!==t.name?(h.sendStatus(d,E,"NO","Quota root does not exist","NONEXISTENT"),I()):(t.limits=H,l(h,d,E),h.sendStatus(d,E,"OK","SETQUOTA completed"),I())},{states:Z.AUTHENTICATED,astringArguments:[0]}),["DELETED","DELETED-STORAGE"].forEach(h=>{s.allowedStatus.indexOf(h)<0&&s.allowedStatus.push(h)}),s.statusHandlers["DELETED-STORAGE"]=(h,d)=>a(d.messages.filter(E=>E.flags.indexOf("\\Deleted")>=0));let A=()=>{let h=u();return{root:t.name,limits:Object.assign({},t.limits),usage:{STORAGE:Math.ceil(h.bytes/1024),MESSAGE:h.MESSAGE,MAILBOX:h.MAILBOX}}},m=h=>{if(!h||typeof h!="object"||Array.isArray(h))throw K("setQuota expects an object of resource limits, e.g. { STORAGE: 1024 }","INVALID");let d={};return Object.keys(h).forEach(E=>{let I=E.toUpperCase(),C=h[E];if(Mt.indexOf(I)<0)throw K("Unknown quota resource "+E+", expected "+Mt.join(", "),"INVALID");if(typeof C!="number"||!Number.isSafeInteger(C)||C<0)throw K("Limit of "+I+" must be a non-negative integer","INVALID");d[I]=C}),t.limits=d,A()};s.control.register("getQuota",A,[{method:"GET",path:"/v1/quota",summary:"Quota root, limits and usage (QUOTA plugin)",handler:()=>s.control.getQuota()}]),s.control.register("setQuota",m,[{method:"PUT",path:"/v1/quota",summary:"Replaces the quota limits ({ STORAGE, MESSAGE, MAILBOX }, QUOTA plugin)",handler:({body:h})=>s.control.setQuota(h)}])}g();var wu=s=>s==="*"||Le(s);function Ti(s){s.registerCapability("REPLACE");let e=function(r,n,i,o,a){let u=r?"UID REPLACE":"REPLACE",l=[].concat(i.attributes||[]),c=l.shift(),f=l.shift();if(!c||["ATOM","SEQUENCE"].indexOf(c.type)<0||!wu(String(c.value)))return n.sendStatus(i,o,"BAD",u+" expects a message number, a mailbox name and a message",!1,"INVALID COMMAND"),a();let p=Nu(n,r,c.value);if(p.error)return n.sendStatus(i,o,p.error.command,p.error.text,p.error.code||!1,p.error.command==="BAD"?"INVALID COMMAND":u+" FAILED"),a();let y=p.message,A=un(n,i,o,f,l,{command:u,maxMessages:1,replaced:y});if(!A)return a();let m=ln(n,A);n.send({tag:"*",command:"OK",attributes:[{type:"TEXT",value:"Replacement message saved"}],skipResponse:!0},"REPLACE APPENDUID",i,o,m),n.expungeSpecificMessages(n.selectedMailbox,[y],!1,!0),n.sendStatus(i,o,"OK",u+" completed",!1,u),a()};s.literalFilters.push((r,n,i)=>{if(n!=="REPLACE"&&n!=="UID REPLACE"||r.isBusy())return!1;let o=i.match(/^\S+ (?:UID )?REPLACE ([^ ]+) /i);return o&&wu(o[1])&&Nu(r,n==="UID REPLACE",o[1]).error||!1});let t={states:Z.SELECTED,mailboxArguments:[1],literal8:"BINARY",appendMessage:!0};s.setCommandHandler("REPLACE",e.bind(null,!1),Object.assign({sequenceSet:0},t)),s.setCommandHandler("UID REPLACE",e.bind(null,!0),t)}function Nu(s,e,t){let r=s.getSessionMessages(),n;if(e){let o=t==="*"?r.length?r[r.length-1].uid:0:Number(t);n=r.find(a=>a.uid===o)}else{let o=t==="*"?r.length:Number(t);if(!o||o>r.length)return{error:{command:"BAD",text:"Invalid message sequence number"}};n=r[o-1]}if(!n||n.ghost)return{error:{command:"NO",text:"No such message"}};let i=s.readOnlyRefusal();return i?{error:i}:{message:n}}g();function Si(s){s.registerCapability("SASL-IR",e=>e.state==="Not Authenticated")}g();function Ii(s){s.registerCapability("SAVEDATE");let e=r=>!!r&&r.SAVEDATE!==!1;s.messageHandlers.push((r,n,i)=>{if(!e(i)){delete n.SAVEDATE;return}let o=r.normalizeDateTime(n.SAVEDATE||r.now());if(!r.validateInternalDate(o))throw new Error("Invalid SAVEDATE value "+JSON.stringify(o)+" in mailbox "+i.path);n.SAVEDATE=o}),s.fetchHandlers.SAVEDATE=(r,n)=>n.SAVEDATE||null;let t=(r,n)=>{let i=(o,a,u,l)=>{let c=vn(a.SAVEDATE||a.internaldate);return!!c&&n(c,l)};i.argumentTypes=()=>["date"],s.searchHandlers[r]=i};t("SAVEDBEFORE",(r,n)=>r<n),t("SAVEDON",(r,n)=>r===n),t("SAVEDSINCE",(r,n)=>r>=n),s.searchHandlers.SAVEDATESUPPORTED=r=>e(r.selectedMailbox)}g();function Oi(s){let e=ei(s,"SAVELIMIT");s.registerCapability("SAVELIMIT="+e),ti(s,e)}g();var Fh=new Set(["SELECT","EXAMINE","CLOSE","UNSELECT"]),_h=s=>["SEARCH","UID SEARCH","SORT","UID SORT","ESEARCH"].includes(s);function xi(s){Ie(s),s.registerCapability("SEARCHRES"),s.searchReturnOptions.set("SAVE",{data:!1}),s.connectionHandlers.push(e=>{let t=e.getMessageRange;e.getMessageRange=function(r,n){if(r!=="$")return t.call(this,r,n);let i=this.searchResult||new Set,o=[];return this.getSessionMessages().forEach((a,u)=>{i.has(a)&&o.push([u+1,a])}),o}}),s.resetHandlers.push(e=>{e.searchResult=null}),s.outputHandlers.push((e,t,r,n,i,o)=>{if(!n||!t||t.tag!==n.tag&&t.command!=="SEARCH"&&t.command!=="SORT")return;let a=(n.command||"").toUpperCase(),u=_h(a)&&n.searchReturn&&n.searchReturn.has("SAVE");if(u&&t.tag==="*"&&(t.command==="SEARCH"||t.command==="SORT")&&r===a&&o&&Array.isArray(o.list)){n.searchresFound=je(o.sorted||o.list,n.searchReturn);return}if(t.tag===n.tag){if(Fh.has(a)){e.searchResult=null;return}u&&t.command!=="BAD"&&(e.searchResult=new Set(t.command==="OK"?n.searchresFound:[]))}})}g();function Ci(s){ct(s),s.registerCapability("SORT=DISPLAY"),s.sortKeys.DISPLAYFROM=e=>He(Vn(e,"from")),s.sortKeys.DISPLAYTO=e=>He(Vn(e,"to"))}g();var Mu=new Set(["\\All","\\Archive","\\Drafts","\\Flagged","\\Junk","\\Sent","\\Trash","\\Important"]);function wi(s){s.registerCapability("SPECIAL-USE");let e=i=>[].concat(i&&i["special-use"]||[]),t=Ke(s);t.selectionOptions["SPECIAL-USE"]={type:"independent",returnOption:"SPECIAL-USE",match:i=>i.flags.indexOf("\\Noselect")<0&&e(i).length>0},t.returnOptions["SPECIAL-USE"]={};let r=s.getCommandHandler("LIST");s.setCommandHandler("LIST",(i,o,a,u)=>{if(t.enabled)return r(i,o,a,u);let l;if(o.attributes&&Array.isArray(o.attributes[0])){for(l=o.attributes[0].length-1;l>=0;l--)o.attributes[0][l]&&o.attributes[0][l].type==="ATOM"&&o.attributes[0][l].value.toUpperCase()==="SPECIAL-USE"&&(o.attributes[0].splice(l,1),o.listSpecialUseOnly=!0);o.attributes[0].length||o.attributes.splice(0,1)}if(o.attributes&&o.attributes[2]&&o.attributes[2].type==="ATOM"&&o.attributes[2].value.toUpperCase()==="RETURN"&&Array.isArray(o.attributes[3])){for(l=o.attributes[3].length-1;l>=0;l--)o.attributes[3][l]&&o.attributes[3][l].type==="ATOM"&&o.attributes[3][l].value.toUpperCase()==="SPECIAL-USE"&&o.attributes[3].splice(l,1);o.attributes[3].length||o.attributes.splice(2,2)}r(i,o,a,u)}),s.outputHandlers.push((i,o,a,u,l,c)=>{let f=e(c).map(p=>({type:"ATOM",value:p}));(a==="LIST ITEM"||a==="LSUB ITEM")&&c&&o.attributes&&Array.isArray(o.attributes[0])&&(f.length?o.attributes[0]=o.attributes[0].concat(f):u.listSpecialUseOnly&&(o.skipResponse=!0))}),s.control.mailboxInfoHandlers.push((i,o)=>{o.specialUse=e(i)});let n=(i,o)=>{let a=s.control.requireMailbox(i,!0);if(!Array.isArray(o)||o.some(u=>typeof u!="string"||!Mu.has(u)))throw K("Special-use attributes must be a list of "+[...Mu].join(", "),"INVALID");return a["special-use"]=[...new Set(o)],s.control.getMailbox(a.path)};s.control.register("setSpecialUse",n,[{method:"PUT",path:"/v1/mailboxes/{path}/special-use",summary:'Sets the special-use attributes of a mailbox ({ specialUse: ["\\Sent"] }, SPECIAL-USE plugin)',handler:({params:i,body:o})=>s.control.setSpecialUse(i.path,o.specialUse)}])}g();function Ni(s){s.registerCapability("STARTTLS",e=>!e.secureConnection),s.setCommandHandler("STARTTLS",(e,t,r,n)=>{if(e.secureConnection)return Gh("Connection is already secured",e,t,r,n);e.send({tag:t.tag,command:"OK",attributes:[{type:"TEXT",value:"Server ready to start TLS negotiation"}]},"STARTTLS INIT",t,r),e.upgradeConnection(n)})}function Gh(s,e,t,r,n){return e.send({tag:t.tag,command:"BAD",attributes:[{type:"TEXT",value:s}]},"INVALID COMMAND",t,r),n()}g();function Mi(s){s.registerCapability("STATUS=SIZE"),s.allowedStatus.push("SIZE"),s.statusHandlers.SIZE=(e,t)=>t.messages.reduce((r,n)=>r+Te["RFC822.SIZE"](e,n),0)}g();g();function Wt(s){return{entry:s||null,parent:null,children:[]}}function zt(s,e){for(;!s.entry&&s.children.length;)s=s.children[0];for(;!e.entry&&e.children.length;)e=e.children[0];return s.entry.date-e.entry.date||s.entry.seq-e.entry.seq}function Ru(s){let e=[],t=s.slice().reverse();for(;t.length;){let r=t.pop();e.push(r);for(let n=r.children.length-1;n>=0;n--)t.push(r.children[n])}return e}function Xh(s,e){let t=[],r=[],n=i=>{for(let o=i.length-1;o>=0;o--)r.push(")",i[o],"(")};for(n(s);r.length;){let i=r.pop();if(typeof i=="string"){t.push(i);continue}let o=i.children;o.length===1?r.push(o[0]):n(o),i.entry&&(o.length&&r.push(" "),t.push(e?i.entry.message.uid:i.entry.seq))}return t.join("")}function jh(s){let e=(i,o)=>i.subject.id<o.subject.id?-1:i.subject.id>o.subject.id?1:0,t=s.slice().sort((i,o)=>e(i,o)||i.date-o.date||i.seq-o.seq),r=[],n=null;for(let i of t)n&&n.entry.subject.id===i.subject.id?n.children.push(Wt(i)):(n=Wt(i),r.push(n));return r.sort(zt)}function Vh(s){let e=new Map,t=[],r=A=>{if(!e.has(A)){let m=Wt();e.set(A,m),t.push(m)}return e.get(A)},n=(A,m)=>{for(let h=A;h;h=h.parent)if(h===m)return!0;return!1},i=A=>{A.parent&&(A.parent.children.splice(A.parent.children.indexOf(A),1),A.parent=null)},o=(A,m)=>{A!==m&&(!m.children.length||!n(A,m))&&(A.children.push(m),m.parent=A)};for(let A of s){let m=ne(A.message).tree.parsedHeader,h=Ks(m["message-id"])[0],d=h!==void 0&&r(h);(!d||d.entry)&&(d=Wt(),t.push(d)),d.entry=A;let E=Ks(m.references);E.length||(E=Ks(m["in-reply-to"]).slice(0,1));let I=E.map(r);for(let H=1;H<I.length;H++)I[H].parent||o(I[H-1],I[H]);let C=I[I.length-1]||null;d.parent!==C&&(i(d),C&&o(C,d))}let a=t.filter(A=>!A.parent),u=(A,m)=>A.entry?[A]:A.children.length?m&&A.children.length>1?[A]:A.children:[];for(let A of Ru(a).reverse())A.children=A.children.flatMap(m=>u(m,!1)),A.children.forEach(m=>{m.parent=A});let l=a.flatMap(A=>u(A,!0));l.forEach(A=>{A.parent=null}),l.forEach(A=>{A.entry||A.children.sort(zt)}),l.sort(zt);let c=A=>A.entry?A.entry.subject:A.children[0].entry.subject,f=A=>!!A.entry&&A.entry.subject.isReply,p=new Map;for(let A of l){let m=c(A);if(!m.id)continue;let h=p.get(m.id);(!h||h.entry&&(!A.entry||f(h)&&!f(A)))&&p.set(m.id,A)}let y=new Set;for(let A of l){let m=c(A);if(!m.id)continue;let h=p.get(m.id);if(h!==A)if(y.add(A),!h.entry&&!A.entry)A.children.forEach(d=>o(h,d));else if(!h.entry||f(A)&&!f(h))o(h,A);else{let d=Wt();l[l.indexOf(h)]=d,o(d,h),o(d,A),p.set(m.id,d)}}l=l.filter(A=>!y.has(A));for(let A of Ru(l).reverse())A.children.sort(zt);return l.sort(zt),l}var Lu={ORDEREDSUBJECT:jh,REFERENCES:Vh};function lr(s,e){if(s.registerCapability("THREAD="+e),s.threadAlgorithms){s.threadAlgorithms[e]=Lu[e];return}s.threadAlgorithms={[e]:Lu[e]};let t=(r,n,i,o,a)=>{let u=r?"UID THREAD":"THREAD",l=i.attributes||[],c=l[0]&&l[0].type==="ATOM"?l[0].value.toUpperCase():"";if(!Object.hasOwn(s.threadAlgorithms,c))return n.sendStatus(i,o,"BAD",c?"Unsupported threading algorithm "+c:u+" expects a threading algorithm atom",!1,u+" FAILED"),a();let f=zs(n,i,o,l.slice(1));if(!f)return a();let p=f.list.map(y=>{let A=qs(ne(y).tree.parsedHeader.subject);return{message:y,seq:f.numbers[y.uid],date:Qs(y),subject:{id:He(A.subject).toString("binary"),isReply:A.isReply}}});return n.send({tag:"*",command:"THREAD",attributes:p.length?[{type:"TEXT",value:Xh(s.threadAlgorithms[c](p),r)}]:[]},u,i,o,f),n.sendStatus(i,o,"OK",u+" completed",!1,u),a()};s.setCommandHandler("THREAD",t.bind(null,!1),{states:Z.SELECTED,searchCriteria:2,noExpunge:!0}),s.setCommandHandler("UID THREAD",t.bind(null,!0),{states:Z.SELECTED,searchCriteria:2})}function Ri(s){lr(s,"ORDEREDSUBJECT")}g();function Li(s){lr(s,"REFERENCES")}g();function cr(s){s.registerCapability("UIDONLY"),Ne(s,"UIDONLY");let e=i=>ye(i,"UIDONLY"),t=i=>({command:"BAD",code:"UIDREQUIRED",text:i}),r=(i,o)=>{let a=String(o.command||"").toUpperCase(),u=s.getCommandOptions(a),l=/^UID /.test(a)||a==="ESEARCH";if(!l&&(u.sequenceSet!==!1||u.searchCriteria!==!1))return t(a+" is not allowed once UIDONLY is enabled, use UID "+a);if(l&&u.searchCriteria!==!1&&i.usesSequenceNumbers(o))return t("Message numbers are not allowed in the search criteria once UIDONLY is enabled, use UID <sequence set>");if((a==="SELECT"||a==="EXAMINE")&&o.attributes&&Array.isArray(o.attributes[1])){let c=o.attributes[1],f=c.findIndex(y=>J(y,"QRESYNC")),p=f>=0&&c[f+1];if(Array.isArray(p)&&p.slice(2).some(Array.isArray))return t("QRESYNC message sequence match data is not allowed once UIDONLY is enabled")}return!1};s.commandChecks.push((i,o)=>e(i)&&r(i,o)),s.literalFilters.unshift((i,o)=>e(i)&&r(i,{command:o})),s.connectionHandlers.push(i=>{let o=i.isAmbiguous;i.isAmbiguous=function(u){return!e(this)&&o.call(this,u)};let a=i.prepareNotifications;i.prepareNotifications=function(u){return u=a.call(this,u),e(this)?ar(u):u}});let n=(i,o,a,u,l,c)=>{if(!o||o.tag!=="*"||!Array.isArray(o.attributes)||!e(i))return;let f=o.attributes;if(o.command==="OK"&&f[0]&&f[0].type==="SECTION"&&J(f[0].section[0],"UNSEEN")){o.skipResponse=!0;return}if(!J(f[1],"FETCH")||!Array.isArray(f[2]))return;let p=f[2],y=p.findIndex((d,E)=>!(E%2)&&J(d,"UID")),A=c&&typeof c.uid=="number"&&c||o.fetchedMessage,m=A?A.uid:y>=0&&p[y+1];if(!m){o.skipResponse=!0;return}u&&!("uidonlyKeepUid"in u)&&(u.uidonlyKeepUid=qh(u));let h=p;y>=0&&p.length>2&&!(u&&u.uidonlyKeepUid)&&(h=p.slice(0,y).concat(p.slice(y+2))),o.attributes=[m,{type:"ATOM",value:"UIDFETCH"},h]};s.once("pluginsLoaded",()=>s.outputHandlers.push(n))}function qh(s){return String(s.command||"").toUpperCase()!=="UID FETCH"||!s.attributes?!1:[].concat(s.attributes[1]||[]).some(e=>J(e,"UID"))}cr.requires=["ENABLE"];g();function Di(s){s.registerCapability("UIDPLUS"),s.setCommandHandler("UID EXPUNGE",(e,t,r,n)=>{if(!t.attributes||t.attributes.length!==1||!t.attributes[0]||["ATOM","SEQUENCE"].indexOf(t.attributes[0].type)<0)return e.send({tag:t.tag,command:"BAD",attributes:[{type:"TEXT",value:"UID EXPUNGE expects uid sequence set"}]},"INVALID COMMAND",t,r),n();if(e.refuseReadOnly(t,r,"UID EXPUNGE FAILED"))return n();let i=t.attributes[0].value,a=e.limitRange(t,e.getMessageRange(i,!0)).map(u=>u[1]).filter(u=>u.flags.indexOf("\\Deleted")>=0);e.expungeSpecificMessages(e.selectedMailbox,a,!1,!0,!!t.highestFirst),e.send({tag:t.tag,command:"OK",attributes:[{type:"TEXT",value:"UID EXPUNGE completed"}]},"UID EXPUNGE",t,r),n()}),s.outputHandlers.push((e,t,r,n,i,o)=>{if(r==="APPEND"||r==="REPLACE APPENDUID"){let a=o.messages.map(u=>u.uid);t.attributes=[{type:"SECTION",section:[{type:"ATOM",value:"APPENDUID"},o.mailbox.uidvalidity,a.length>1?{type:"SEQUENCE",value:lt(a)}:a[0]]}].concat(t.attributes),t.skipResponse=!1;return}if(r==="COPY"||r==="UID COPY"||r==="MOVE COPYUID"||r==="UID MOVE COPYUID"){if(!o||!o.sourceUids||!o.sourceUids.length)return;t.attributes=[{type:"SECTION",section:[{type:"ATOM",value:"COPYUID"},o.mailbox.uidvalidity,{type:"SEQUENCE",value:o.sourceUids.join(",")},{type:"SEQUENCE",value:o.targetUids.join(",")}]}].concat(t.attributes),t.skipResponse=!1;return}})}g();function Ui(s){s.registerCapability("UNAUTHENTICATE"),s.setCommandHandler("UNAUTHENTICATE",(e,t,r,n)=>(e.sendStatus(t,r,"OK","Completed, now in not authenticated state"),e.resetSession(),n()),{states:Z.AUTHENTICATED,noArguments:!0})}g();function vi(s){s.registerCapability("UNSELECT"),s.setCommandHandler("UNSELECT",(e,t,r,n)=>(e.send({tag:t.tag,command:"OK",attributes:[{type:"TEXT",value:"Mailbox closed"}]},"CLOSE",t,r),e.closeMailbox(),n()),{states:Z.SELECTED,noArguments:!0})}g();function Qh(s){let e=s.match(/\r?\n\r?\n/);return/[\x80-\xff]/.test(e?s.substr(0,e.index):s)}function fr(s){s.registerCapability("UTF8=ACCEPT"),Ne(s,"UTF8=ACCEPT"),s.utf8Accept=!0,s.connectionHandlers.push(wt),s.resetHandlers.push(wt),s.outputHandlers.push((t,r,n,i,o,a)=>{n==="ENABLED"&&Array.isArray(a)&&a.indexOf("UTF8=ACCEPT")>=0&&wt(t)});let e=s.getCommandHandler("APPEND");s.setCommandHandler("APPEND",(t,r,n,i)=>{let o=r.attributes||[],a=o[o.length-1];return!t.utf8Enabled&&o.length>=2&&a&&["LITERAL","LITERAL8"].indexOf(a.type)>=0&&Qh(a.value||"")?(t.sendStatus(r,n,"NO","Message header has 8-bit characters, ENABLE UTF8=ACCEPT first (RFC 9755 section 4)"),i()):e(t,r,n,i)})}fr.requires=["ENABLE"];g();var Yh="1278455344230334865",Kh=2n**64n-1n,Du={"in:inbox":["X-GM-LABELS","\\Inbox"],"in:sent":["X-GM-LABELS","\\Sent"],"in:drafts":["X-GM-LABELS","\\Drafts"],"in:trash":["X-GM-LABELS","\\Trash"],"in:spam":["X-GM-LABELS","\\Junk"],"in:anywhere":["ALL"],"is:unread":["UNSEEN"],"is:read":["SEEN"],"is:starred":["FLAGGED"],"is:important":["X-GM-LABELS","\\Important"]},Uu={from:"FROM",to:"TO",cc:"CC",bcc:"BCC",subject:"SUBJECT",label:"X-GM-LABELS",larger:"LARGER",smaller:"SMALLER",after:"SINCE",before:"BEFORE",rfc822msgid:"HEADER"},zh=["is","has","list","filename","around","size","older","newer","older_than","newer_than","deliveredto","category"];function Bi(s){s.registerCapability("X-GM-EXT-1"),s["HIGHESTX-GM-MSGID"]=BigInt(s.options["HIGHESTX-GM-MSGID"]||Yh),s.messageHandlers.push((a,u,l)=>{let c;u["X-GM-MSGID"]?/^\d+$/.test(u["X-GM-MSGID"])&&BigInt(u["X-GM-MSGID"])>a["HIGHESTX-GM-MSGID"]&&(a["HIGHESTX-GM-MSGID"]=BigInt(u["X-GM-MSGID"])):(a["HIGHESTX-GM-MSGID"]+=1n,u["X-GM-MSGID"]=a["HIGHESTX-GM-MSGID"].toString()),u["X-GM-LABELS"]=[].concat(u["X-GM-LABELS"]||[]),l.path.toUpperCase()==="INBOX"?c=["\\Inbox"]:l["special-use"]&&l["special-use"].length?c=[].concat(l["special-use"]):c=[Hu(l.path)],c.forEach(f=>{a.ensureFlag(u["X-GM-LABELS"],f)})});let e=new Map;s.once("pluginsLoaded",()=>{s.messageHandlers.push((a,u)=>{let l=u.THREADID&&e.get(u.THREADID);u["X-GM-THRID"]||(u["X-GM-THRID"]=l||u["X-GM-MSGID"]),u.THREADID&&!l&&e.set(u.THREADID,u["X-GM-THRID"])})}),s.fetchHandlers["X-GM-MSGID"]=function(a,u){return{type:"ATOM",value:u["X-GM-MSGID"]}},s.fetchHandlers["X-GM-LABELS"]=function(a,u){return Pu(u)};let t=()=>[a=>{if(!/^\d{1,20}$/.test(a)||BigInt(a)>Kh)throw Q("Expected a 64 bit unsigned number");return BigInt(a).toString()}];s.searchHandlers["X-GM-MSGID"]=function(a,u,l,c){return u["X-GM-MSGID"]===c},s.searchHandlers["X-GM-MSGID"].argumentTypes=t,s.fetchHandlers["X-GM-THRID"]=function(a,u){return{type:"ATOM",value:u["X-GM-THRID"]}},s.searchHandlers["X-GM-THRID"]=function(a,u,l,c){return u["X-GM-THRID"]===c},s.searchHandlers["X-GM-THRID"].argumentTypes=t,s.searchHandlers["X-GM-LABELS"]=function(a,u,l,c){return u["X-GM-LABELS"].some(f=>Bu(f)?f.toLowerCase()===c.toLowerCase():a.exportMailboxName(ku(f))===c)};let r=new WeakMap;s.searchHandlers["X-GM-RAW"]=function(a,u,l,c){if(!r.has(c)){let f=a.searchCharset?c:["CHARSET","UTF-8"].concat(c);r.set(c,De(a,[],f,()=>[]).matches)}return r.get(c)(u,l)},s.searchHandlers["X-GM-RAW"].argumentTypes=()=>[$h];let n=(a,u)=>{a["X-GM-LABELS"]=[],i(a,u)},i=(a,u)=>{u.forEach(l=>s.ensureFlag(a["X-GM-LABELS"],l))};[["X-GM-LABELS",n],["+X-GM-LABELS",i],["-X-GM-LABELS",(a,u)=>{u.forEach(l=>s.removeFlag(a["X-GM-LABELS"],l))}]].forEach(([a,u])=>{let l=(c,f,p)=>u(f,p.map(y=>Wh(c,y)));s.storeHandlers[a]=function(c,f,p,y,A,m){l(c,f,p),Jh(c,A,m,y,f)},s.storeHandlers[a+".SILENT"]=l,s.storeHandlers[a].astringValues=s.storeHandlers[a+".SILENT"].astringValues=!0}),s.copyHandlers.push((a,u,l)=>{u["X-GM-MSGID"]&&(l["X-GM-MSGID"]=u["X-GM-MSGID"],l["X-GM-THRID"]=u["X-GM-THRID"])})}var Bu=s=>s.charAt(0)==="\\"&&s.charAt(1)!=="\\",Hu=s=>s.charAt(0)==="\\"?"\\"+s:s,ku=s=>s.charAt(0)==="\\"?s.substr(1):s;function Wh(s,e){let t=String(e&&e.value||"");return e.type==="ATOM"&&t.charAt(0)==="\\"?t:Hu(s.importMailboxName(t))}function Pu(s){return s["X-GM-LABELS"].map(e=>Bu(e)?{type:"ATOM",value:e}:{type:"MAILBOX",value:ku(e)})}function $h(s){let e=[],t=/\s*(?:([(){}])|"([^"]*)"|([^\s(){}"]+?:)"([^"]*)"|([^\s(){}"]+))/gy,r,n=0;for(;n<s.length&&(r=t.exec(s));)n=t.lastIndex,r[1]?e.push({type:r[1]}):typeof r[2]=="string"?e.push({type:"word",value:r[2]}):r[3]?e.push({type:"word",value:r[3]+r[4],operator:r[3].slice(0,-1),operand:r[4]}):e.push({type:"word",value:r[5]});if(s.slice(n).trim())throw Q("X-GM-RAW query has an unterminated quoted string");let i=0,o=()=>e[i],a=c=>{let f=[];for(;i<e.length&&(!o()||o().type!==c);)f.push(u());if(c){if(!o()||o().type!==c)throw Q('X-GM-RAW query is missing "'+c+'"');i++}if(!f.length)throw Q("X-GM-RAW query is empty");return f.length===1?f[0]:f},u=()=>{let c=l();for(;o()&&o().type==="word"&&o().value==="OR"&&e[i+1];)i++,c=["OR",c,l()];return c},l=()=>{let c=e[i++];if(!c||c.type===")"||c.type==="}")throw Q("Unexpected end of X-GM-RAW query");if(c.type==="(")return a(")");if(c.type==="{"){let p=[];for(;o()&&o().type!=="}";)p.push(l());if(!o()||!p.length)throw Q("X-GM-RAW query has an empty or unterminated { } group");return i++,p.reduce((y,A)=>["OR",y,A])}let f=c.value;return f==="-"&&o()&&(o().type==="("||o().type==="{")?["NOT",l()]:f.charAt(0)==="-"&&f.length>1?["NOT",vu(Fu(f.substr(1)))]:vu(c)};return[a()]}function Fu(s){let e=s.match(/^([a-z_0-9]+):(.+)$/i);return e?{value:s,operator:e[1],operand:e[2]}:{value:s,operator:!1,operand:!1}}function vu(s){let e=s.operator?s:Fu(s.value),t=e.operator;if(!t)return["TEXT",s.value];let r=e.operand,n=t.toLowerCase(),i=n+":"+r.toLowerCase(),o=Object.hasOwn(Du,i)&&Du[i];if(o)return o;let a=Object.hasOwn(Uu,n)&&Uu[n];if(a)switch(a){case"LARGER":case"SMALLER":{let u=r.match(/^(\d+)([km]?)$/i);if(!u)throw Q("X-GM-RAW "+n+": expects a size");return[a,String(Number(u[1])*{"":1,k:1024,m:1024*1024}[u[2].toLowerCase()])]}case"SINCE":case"BEFORE":{let u=r.match(/^(\d{4})[/-](\d{1,2})[/-](\d{1,2})$/);if(!u||!It(Number(u[3]),Number(u[2])-1,Number(u[1])))throw Q("X-GM-RAW "+n+": expects a date as YYYY/MM/DD");return[a,Number(u[3])+"-"+St[Number(u[2])-1]+"-"+u[1]]}case"HEADER":return[a,"Message-ID",r];default:return[a,r]}if(n==="in")return["X-GM-LABELS",r];if(zh.indexOf(n)>=0){let u=new Error("X-GM-RAW operator "+n+":"+r+" is not supported by imapkit");throw u.imapResponse="NO",u}return["TEXT",s.value]}function Jh(s,e,t,r,n){let i=[{type:"ATOM",value:"X-GM-LABELS"},Pu(n)];(e.command||"").toUpperCase()==="UID STORE"&&(i.push({type:"ATOM",value:"UID"}),i.push(n.uid)),s.send({tag:"*",attributes:[r,{type:"ATOM",value:"FETCH"},i]},"FLAG UPDATE",e,t,n)}g();var Zh=new TextDecoder("utf-8",{fatal:!0});function Hi(s){s.registerCapability("AUTH=XOAUTH2",e=>e.state==="Not Authenticated"),s.setCommandHandler("AUTHENTICATE XOAUTH2",(e,t,r,n)=>{if(!s.capabilities["SASL-IR"]||!s.capabilities["SASL-IR"](e))return e.send({tag:t.tag,command:"BAD",attributes:[{type:"TEXT",value:"SASL-IR must be enabled to support XOAUTH2"}]},"AUTHENTICATE XOAUTH2 FAILED",t,r),n();if(!t.attributes||t.attributes.length!==1||!t.attributes[0]||["STRING","ATOM"].indexOf(t.attributes[0].type)<0)return e.send({tag:t.tag,command:"NO",attributes:[{type:"TEXT",value:"Invalid SASL argument"}]},"AUTHENTICATE XOAUTH2 FAILED",t,r),n();let i=e.decodeSaslResponse(t.attributes[0].value);if(!i)return e.sendStatus(t,r,"BAD","Invalid base64 in SASL response",!1,"AUTHENTICATE XOAUTH2 FAILED"),n();let o=[];try{o=Zh.decode(i).split("")}catch{}let a=(o[0]||"").substr(5),u=(o[1]||"").substr(12);return o.length!==4||!o[0].match(/^user=/)||!o[1].match(/^auth=Bearer /)||!a||!u||o[2]||o[3]?(e.send({tag:t.tag,command:"NO",attributes:[{type:"TEXT",value:"Invalid SASL argument."}]},"AUTHENTICATE XOAUTH2 FAILED",t,r),n()):e.server.getUser(a)?("error"in s.checkAccessToken(u,a)?(e.send({tag:"+",attributes:[{type:"ATOM",value:b.Buffer.from(JSON.stringify({status:"400",schemes:"Bearer",scope:s.oauth?s.oauth.mailScope:"https://mail.google.com/"})).toString("base64")}]},"AUTHENTICATE XOAUTH2 FAILED",t,r),e.inputHandler=function(){e.inputHandler=!1,e.send({tag:t.tag,command:"NO",attributes:[{type:"SECTION",section:[{type:"ATOM",value:"AUTHENTICATIONFAILED"}]},{type:"TEXT",value:"SASL authentication failed"}]},"AUTHENTICATE XOAUTH2 FAILED",t,r)}):(e.state="Authenticated",e.username=a,e.send({tag:t.tag,command:"OK",attributes:[{type:"TEXT",value:"User logged in"}]},"AUTHENTICATE XOAUTH2 SUCCESS",t,r)),n()):(e.send({tag:t.tag,command:"NO",attributes:[{type:"SECTION",section:[{type:"ATOM",value:"AUTHENTICATIONFAILED"}]},{type:"TEXT",value:"Invalid credentials"}]},"AUTHENTICATE XOAUTH2 FAILED",t,r),n())})}var $t={acl:gn,appendlimit:En,"auth-plain":An,binary:In,catenate:xn,compress:Cn,condstore:kn,"context-search":qt,"context-sort":qn,"create-special-use":Qn,enable:Bn,esearch:Ie,esort:Qt,id:Yn,idle:Kn,imap4rev2:Ws,"list-extended":Kt,"list-status":$n,literalminus:Yt,literalplus:Jn,logindisabled:Zn,messagelimit:si,metadata:sr,"metadata-server":rr,move:ai,multiappend:ui,multisearch:li,namespace:ci,notify:fi,oauthbearer:hi,objectid:di,partial:pi,preview:Ei,qresync:ur,quota:bi,replace:Ti,"sasl-ir":Si,savedate:Ii,savelimit:Oi,searchres:xi,sort:ct,"sort-display":Ci,"special-use":wi,starttls:Ni,"status-size":Mi,"thread-orderedsubject":Ri,"thread-references":Li,uidonly:cr,uidplus:Di,unauthenticate:Ui,unselect:vi,"utf8-accept":fr,"x-gm-ext-1":Bi,xoauth2:Hi};var _u={"literal+":"literalplus","literal-":"literalminus","compress=deflate":"compress","auth=plain":"auth-plain","auth=xoauth2":"xoauth2","status=size":"status-size","sort=display":"sort-display","thread=orderedsubject":"thread-orderedsubject","thread=references":"thread-references","auth=oauthbearer":"oauthbearer","utf8=accept":"utf8-accept","context=search":"context-search","context=sort":"context-sort"};function ed(){return Object.keys($t)}function Gu(s){let e=String(s).trim().toLowerCase();return Object.hasOwn(_u,e)&&(e=_u[e]),Object.hasOwn($t,e)?e:!1}function td(s,e,t){let r=new Set,n=new Map;(t||new Map).forEach((o,a)=>{let u=Gu(a);u&&n.set($t[u],o)});let i=(o,a)=>{let u=o;if(typeof u=="string"){let f=Gu(u);if(!f&&u.toUpperCase()==="XTOYBIRD")throw new Error("XTOYBIRD was removed in 5.0.0, use the control API (server.control.snapshot(), server.control.addUser() ...) instead, see the README");if(!f)throw new Error('Unknown plugin "'+u+'". Available plugins: '+ed().join(", "));u=$t[f]}if(typeof u!="function")throw new TypeError("Invalid plugin, expecting a plugin name or a function");let l=n.get(u);if(l){if(a)throw new Error(a+" requires "+o+', which the "'+l+'" quirk removes');return}if(r.has(u))return;r.add(u);let c=typeof o=="string"?o.trim():u.name;[].concat(u.requires||[]).forEach(f=>i(f,c)),u(s)};[].concat(e||[]).forEach(o=>i(o)),s.emit("pluginsLoaded")}var Xu=td;g();g();function ki(s,e,t,r){let n=["IMAP4rev1"];Object.keys(s.server.capabilities).forEach(i=>{s.server.capabilities[i](s)&&n.push(i)}),s.send({tag:"*",command:"CAPABILITY",attributes:n.map(i=>({type:"TEXT",value:i}))},"CAPABILITY LIST",e,t,n),s.send({tag:e.tag,command:"OK",attributes:[{type:"TEXT",value:"Completed"}]},"CAPABILITY COMPLETED",e,t,n),r()}g();function Pi(s,e,t,r){s.send({tag:e.tag,command:"OK",attributes:[{type:"TEXT",value:"Completed"}]},"CHECK",e,t),r()}g();function Fi(s,e,t,r){return s.canExpunge()&&s.expungeDeleted(s.selectedMailbox,!0),s.notificationQueue=[],s.send({tag:e.tag,command:"OK",attributes:[{type:"TEXT",value:"Mailbox closed"}]},"CLOSE",e,t),s.closeMailbox(),r()}g();function _i(s,e,t,r){if(!e.attributes||e.attributes.length!==1||!e.attributes[0]||["STRING","LITERAL","ATOM"].indexOf(e.attributes[0].type)<0)return s.send({tag:e.tag,command:"BAD",attributes:[{type:"TEXT",value:"CREATE expects mailbox name"}]},"INVALID COMMAND",e,t),r();let n=e.attributes[0].value,i;try{i=xs(s.server,n)}catch(o){let a=o;return s.sendStatus(e,t,"NO",a.message,a.code,"CREATE FAILED"),r()}return s.send({tag:e.tag,command:"OK",attributes:[{type:"TEXT",value:"CREATE completed"}]},"CREATE",e,t,i),r()}g();function Gi(s,e,t,r){if(!e.attributes||e.attributes.length!==1||!e.attributes[0]||["STRING","LITERAL","ATOM"].indexOf(e.attributes[0].type)<0)return s.send({tag:e.tag,command:"BAD",attributes:[{type:"TEXT",value:"DELETE expects mailbox name"}]},"INVALID COMMAND",e,t),r();let n=e.attributes[0].value;try{Cs(s.server,n)}catch(i){let o=i;return s.sendStatus(e,t,"NO",o.message,o.code,"DELETE FAILED"),r()}return s.send({tag:e.tag,command:"OK",attributes:[{type:"TEXT",value:"DELETE completed"}]},"DELETE",e,t),r()}g();function Xi(s,e,t,r){return an(s,e,t,r,!0)}g();function ji(s,e,t,r){if(s.refuseReadOnly(e,t,"EXPUNGE FAILED"))return r();s.expungeDeleted(s.selectedMailbox,!1,!0),s.send({tag:e.tag,command:"OK",attributes:[{type:"TEXT",value:"EXPUNGE Completed"}]},"EXPUNGE",e,t),r()}g();function Vi(s,e,t,r){let n;if(!e.attributes||e.attributes.length!==2||!e.attributes[0]||["STRING","LITERAL","ATOM"].indexOf(e.attributes[0].type)<0||!e.attributes[1]||["STRING","LITERAL","ATOM"].indexOf(e.attributes[1].type)<0)return s.send({tag:e.tag,command:"BAD",attributes:[{type:"TEXT",value:"LIST expects 2 string arguments"}]},"INVALID COMMAND",e,t),r();if(e.attributes[1].value)n=s.server.matchFolders(e.attributes[0].value,e.attributes[1].value,i=>s.exportMailboxName(i)),n.forEach(i=>{s.send({tag:"*",command:"LIST",attributes:[i.flags.map(o=>({type:"ATOM",value:o})),s.server.getSeparator(i),s.exportMailboxName(i.path)]},"LIST ITEM",e,t,i)});else{let i=s.server,o=e.attributes[0].value||"",a=i.referenceNamespace;try{a=i.getNamespace(s.importMailboxName(o))||a}catch{}let u=a!==!1?i.storage[a]:void 0,l=a!==!1&&a!==i.referenceNamespace?s.exportMailboxName(a):"";u&&s.send({tag:"*",command:"LIST",attributes:[[{type:"ATOM",value:"\\Noselect"}],u.separator,l]},"LIST ITEM",e,t)}return s.send({tag:e.tag,command:"OK",attributes:[{type:"TEXT",value:"Completed"}]},"LIST",e,t),r()}g();function qi(s,e,t,r){if(!e.attributes||e.attributes.length!==2||!e.attributes[0]||!e.attributes[1]||["STRING","LITERAL","ATOM"].indexOf(e.attributes[0].type)<0||["STRING","LITERAL","ATOM"].indexOf(e.attributes[1].type)<0)return s.send({tag:e.tag,command:"BAD",attributes:[{type:"TEXT",value:"LOGIN takes 2 string arguments"}]},"INVALID COMMAND",e,t),r();if(e.attributes.some(i=>/[\x80-\xff]/.test(i.value)))return s.sendStatus(e,t,"BAD","LOGIN does not take UTF-8 user names or passwords, use AUTHENTICATE (RFC 9755 section 5)"),r();let n=s.server.getUser(e.attributes[0].value);if(!n||n.password!==e.attributes[1].value)return s.sendStatus(e,t,"NO","Login failed: authentication failure","AUTHENTICATIONFAILED","LOGIN FAILED"),r();s.state="Authenticated",s.username=e.attributes[0].value,s.send({tag:e.tag,command:"OK",attributes:[{type:"TEXT",value:"User logged in"}]},"LOGIN SUCCESS",e,t),r()}g();function Qi(s,e,t,r){s.state="Logout",s.send({tag:"*",command:"BYE",attributes:[{type:"TEXT",value:"LOGOUT received"}]},"LOGOUT UNTAGGED",e,t),s.send({tag:e.tag,command:"OK",attributes:[{type:"TEXT",value:"Completed"}]},"LOGOUT COMPLETED",e,t),s.end(),r()}g();function Yi(s,e,t,r){if(!e.attributes||e.attributes.length!==2||!e.attributes[0]||["STRING","LITERAL","ATOM"].indexOf(e.attributes[0].type)<0||!e.attributes[1]||["STRING","LITERAL","ATOM"].indexOf(e.attributes[1].type)<0)return s.send({tag:e.tag,command:"BAD",attributes:[{type:"TEXT",value:"LSUB expects 2 string arguments"}]},"INVALID COMMAND",e,t),r();let n=s.server,i=e.attributes[1].value;return n.matchFolders(e.attributes[0].value,i,a=>s.exportMailboxName(a),n.getSubscriptionTree()).forEach(a=>{let u;if(a.subscribed)u=a.flags.filter(l=>l!=="\\Noselect");else if(i.substr(-1)==="%")u=["\\Noselect"];else return;s.send({tag:"*",command:"LSUB",attributes:[u.map(l=>({type:"ATOM",value:l})),n.getSeparator(a),s.exportMailboxName(a.path)]},"LSUB ITEM",e,t,a)}),s.send({tag:e.tag,command:"OK",attributes:[{type:"TEXT",value:"Completed"}]},"LSUB",e,t),r()}g();function Ki(s,e,t,r){s.send({tag:e.tag,command:"OK",attributes:[{type:"TEXT",value:"Completed"}]},"NOOP completed",e,t),r()}g();function zi(s,e,t,r){if(!e.attributes||e.attributes.length!==2||!e.attributes[0]||["STRING","LITERAL","ATOM"].indexOf(e.attributes[0].type)<0||!e.attributes[1]||["STRING","LITERAL","ATOM"].indexOf(e.attributes[1].type)<0)return s.send({tag:e.tag,command:"BAD",attributes:[{type:"TEXT",value:"RENAME expects mailbox source and destination names"}]},"INVALID COMMAND",e,t),r();let n=e.attributes[0].value,i=e.attributes[1].value,o;try{o=ws(s.server,n,i)}catch(a){let u=a;return s.sendStatus(e,t,"NO",u.message,u.code,"RENAME FAILED"),r()}return s.send({tag:e.tag,command:"OK",attributes:[{type:"TEXT",value:"RENAME completed"}]},"RENAME",e,t,o.mailbox),r()}g();function Wi(s,e,t,r,n){let i=s?"UID SEARCH":"SEARCH";if(!t.attributes||!t.attributes.length)return e.send({tag:t.tag,command:"BAD",attributes:[{type:"TEXT",value:i+" expects search criteria, empty query given"}]},i+" FAILED",t,r),n();let o;try{o=De(e,e.getSessionMessages(),Ot(t.attributes))}catch(a){return xt(e,t,r,a,i+" FAILED"),n()}return e.send({tag:"*",command:"SEARCH",attributes:o.list.map(a=>s?a.uid:o.numbers[a.uid])},i,t,r,o),e.send({tag:t.tag,command:"OK",attributes:[{type:"TEXT",value:i+" completed"}]},i,t,r),n()}var sd=(s,e,t,r)=>Wi(!1,s,e,t,r),ju=sd;g();function $i(s,e,t,r){if(!e.attributes||e.attributes.length!==2||!e.attributes[0]||["STRING","LITERAL","ATOM"].indexOf(e.attributes[0].type)<0||!Array.isArray(e.attributes[1])||!e.attributes[1].length)return s.send({tag:e.tag,command:"BAD",attributes:[{type:"TEXT",value:"STATUS expects mailbox argument and a list of status items"}]},"INVALID COMMAND",e,t),r();let n=e.attributes[0].value,i;try{i=Js(s.server,e.attributes[1],s)}catch(u){return s.sendStatus(e,t,"BAD",u.message,!1,"STATUS FAILED"),r()}let o=s.server.getMailbox(n);if(!o||o.flags.indexOf("\\Noselect")>=0)return s.sendStatus(e,t,"NO","Mailbox does not exist","NONEXISTENT","STATUS FAILED"),r();Zs(s,n,o,i,e,t);let a=s.state==="Selected"&&s.selectedMailbox===o;return s.sendStatus(e,t,"OK",a?"Status completed, STATUS SHOULD NOT be used on the selected mailbox":"Status completed",a&&"CLIENTBUG"),r()}g();function Vu(s,e){return e=String(e).toUpperCase(),s.server.storeHandlers[e]||Ts[e]}function Ji(s,e,t,r,n){let i=s?"UID STORE":"STORE",o=t.attributes&&t.attributes[1],a=J(o)&&Vu(e,o.value),u=!!(a&&a.astringValues),l=u?["ATOM","STRING","LITERAL"]:["ATOM","STRING"];if(u&&yt(t,r,h=>h[0]===2),!t.attributes||t.attributes.length!==3||!t.attributes[0]||["ATOM","SEQUENCE"].indexOf(t.attributes[0].type)<0||!t.attributes[1]||["ATOM"].indexOf(t.attributes[1].type)<0||!t.attributes[2]||!(l.indexOf(t.attributes[2].type)>=0||Array.isArray(t.attributes[2])))return e.send({tag:t.tag,command:"BAD",attributes:[{type:"TEXT",value:i+" expects sequence set, item name and item value"}]},"INVALID COMMAND",t,r),n();if(e.refuseReadOnly(t,r,i+" FAILED"))return n();let c=e.limitRange(t,e.getCommandRange(t.attributes[0].value,s)),f=(t.attributes[1].value||"").toUpperCase(),p=[].concat(t.attributes[2]||[]),y=[],A=!1;try{p.forEach((d,E)=>{if(!d||l.indexOf(d.type)<0)throw new Error("Invalid item value #"+(E+1))});let h=a||Vu(e,f);if(!h)throw new Error("Invalid STORE argument "+f);c.forEach(d=>{if(d[1].ghost){A=!0;return}for(let E=0,I=e.server.storeFilters.length;E<I;E++)if(!e.server.storeFilters[E](e,d[1],t,d[0]))return;h(e,d[1],p,d[0],t,r),y.push(d[1])})}catch(h){let d=h;return e.send({tag:t.tag,command:"BAD",attributes:[{type:"TEXT",value:d.message}]},i+" FAILED",t,r),n()}let m=A&&!/\.SILENT$/.test(f);e.send({tag:t.tag,command:m?"NO":"OK",attributes:[].concat(m?{type:"SECTION",section:[{type:"ATOM",value:"EXPUNGEISSUED"}]}:[],{type:"TEXT",value:m?"Some of the messages no longer exist":i+" completed"})},i+(m?" FAILED":" COMPLETE"),t,r,y),e.notifyFlagChanges(y),n()}var rd=(s,e,t,r)=>Ji(!1,s,e,t,r),qu=rd;g();function Zi(s,e,t,r){if(!e.attributes||e.attributes.length!==1||!e.attributes[0]||["STRING","LITERAL","ATOM"].indexOf(e.attributes[0].type)<0)return s.send({tag:e.tag,command:"BAD",attributes:[{type:"TEXT",value:"SUBSCRIBE expects mailbox name"}]},"INVALID COMMAND",e,t),r();try{Ht(s.server,e.attributes[0].value)}catch(n){let i=n;return s.sendStatus(e,t,"NO",i.message,i.code,"SUBSCRIBE FAILED"),r()}return s.send({tag:e.tag,command:"OK",attributes:[{type:"TEXT",value:"SUBSCRIBE completed"}]},"SUBSCRIBE",e,t),r()}g();function eo(s,e,t,r){return ii(s,e,t,r,!0)}g();var nd=(s,e,t,r)=>wn(!0,s,e,t,r),Qu=nd;g();var id=(s,e,t,r)=>Wi(!0,s,e,t,r),Yu=id;g();var od=(s,e,t,r)=>Ji(!0,s,e,t,r),Ku=od;g();function to(s,e,t,r){return!e.attributes||e.attributes.length!==1||!e.attributes[0]||["STRING","LITERAL","ATOM"].indexOf(e.attributes[0].type)<0?(s.send({tag:e.tag,command:"BAD",attributes:[{type:"TEXT",value:"UNSUBSCRIBE expects mailbox name"}]},"INVALID COMMAND",e,t),r()):(Ns(s.server,e.attributes[0].value),s.send({tag:e.tag,command:"OK",attributes:[{type:"TEXT",value:"UNSUBSCRIBE completed"}]},"UNSUBSCRIBE",e,t),r())}var zu={APPEND:cn,CAPABILITY:ki,CHECK:Pi,CLOSE:Fi,COPY:ni,CREATE:_i,DELETE:Gi,EXAMINE:Xi,EXPUNGE:ji,FETCH:za,LIST:Vi,LOGIN:qi,LOGOUT:Qi,LSUB:Yi,NOOP:Ki,RENAME:zi,SEARCH:ju,SELECT:nn,STATUS:$i,STORE:qu,SUBSCRIBE:Zi,"UID COPY":eo,"UID FETCH":Qu,"UID SEARCH":Yu,"UID STORE":Ku,UNSUBSCRIBE:to};g();g();var Ju=/^[\x20\x21\x23-\x5b\x5d-\x7e]*$/,so=s=>s.replace(/[^\x20\x21\x23-\x5b\x5d-\x7e]/g," "),ro=s=>typeof s=="string"&&s!==""&&Ju.test(s),Wu=["prompt","approve","deny"],$u=["wrong-state","wrong-iss","no-redirect"];function $e(s,e,t=!1){if(typeof s=="string"&&(Wu.includes(s)||t&&$u.includes(s)))return s;if(s&&typeof s=="object"&&!Array.isArray(s)){let{error:n,description:i}=s;if(ro(n)){if(i!==void 0&&(typeof i!="string"||!Ju.test(i)))throw new z(e+': description must be printable ASCII without " and \\ (RFC 6749 section 4.1.2.1)',"INVALID");return i===void 0?{error:n}:{error:n,description:i}}}let r=Wu.concat(t?$u:[]).map(n=>'"'+n+'"');throw new z(e+" must be "+r.join(", ")+' or { error, description }, e.g. { error: "access_denied" }',"INVALID")}function Jt(s){return typeof s=="string"?s:"error "+s.error}function ad(s){if(!(s===void 0||typeof s=="function"))return s===null||typeof s!="object"?s:JSON.parse(JSON.stringify(s))}function no(s,e){let t={};return Object.keys(s).forEach(r=>{let n=e.has(r)?void 0:ad(s[r]);n!==void 0&&(t[r]=n)}),t}var ud=new Set(["ghost"]),ld=new Set(["folders"]),cd=new Set(["path","namespace","messages","folders","subscribed","flags"]),fd=new Set(["\\HasChildren","\\HasNoChildren"]);function io(s,e){if(!s||typeof s!="object"||Array.isArray(s))throw new z(e+" must be { consent }","INVALID");let{consent:t}=s;return t===void 0?{}:{consent:$e(t,e+".consent")}}var hr=class{constructor(e){this.server=e,this.routes=[],this.snapshotHandlers=[],this.mailboxInfoHandlers=[],this.messageInfoHandlers=[]}register(e,t,r){if(e in this)throw new Error("Control operation "+e+" exists already");this[e]=(...n)=>this.run(()=>t(...n)),this.routes.push(...r||[])}run(e){return this.server.withOrigin(null,e)}requireMailbox(e,t){let r=typeof e=="string"&&e?this.server.getMailbox(e):void 0;if(!r||t&&r.flags.indexOf("\\Noselect")>=0)throw new z("Mailbox "+JSON.stringify(e)+" does not exist","NONEXISTENT");return r}checkName(e){this.checkPath(e);let t=Tt(e);if(t)throw new z(t,"INVALID")}checkPath(e){if(typeof e!="string"||!e)throw new z("Mailbox name must be a non-empty string","INVALID")}requireMessages(e,t){if(!Array.isArray(t)||t.some(i=>!Number.isSafeInteger(i)||i<1))throw new z("UIDs must be an array of positive integers","INVALID");let r=new Map(e.messages.map(i=>[i.uid,i])),n=t.filter(i=>!r.has(i));if(n.length)throw new z("No message with UID "+n.join(", ")+" in "+e.path,"NONEXISTENT");return[...new Set(t)].map(i=>r.get(i))}findSessions(e){let t=typeof e=="number"?{session:e}:e||{};if(t.session===void 0&&t.user===void 0)throw new z("Select sessions by number or user","INVALID");return[...this.server.connections].filter(r=>r.isOpen()&&(t.session===void 0||r.sessionNumber===t.session)&&(t.user===void 0||r.username===t.user))}snapshot(){let e=this.server,t=i=>{let o=no(i,cd);return this.snapshotHandlers.forEach(a=>a(i,o)),o.flags=i.flags.filter(a=>!fd.has(a)),o.subscribed=!!i.subscribed,o.messages=i.messages.map(a=>no(a,ud)),i.folders&&(o.folders=r(i.folders)),o},r=i=>{let o={};return Object.keys(i).forEach(a=>{o[a]=t(i[a])}),o},n={};return Object.keys(e.storage).forEach(i=>{if(i==="INBOX"){n.INBOX=t(e.storage.INBOX);return}let o=e.storage[i];n[i]=Object.assign(no(o,ld),{folders:r(o.folders||{})})}),n}listMailboxes(){return Object.keys(this.server.folderCache).sort().map(e=>this.describeMailbox(this.server.folderCache[e]))}getMailbox(e){return this.describeMailbox(this.requireMailbox(e))}describeMailbox(e){let t=this.server.getStatus(e),r={path:e.path,delimiter:this.server.getSeparator(e),flags:e.flags.slice(),selectable:e.flags.indexOf("\\Noselect")<0,subscribed:!!e.subscribed,messages:e.messages.length,unseen:t?t.unseen:0,uidnext:e.uidnext,uidvalidity:e.uidvalidity,permanentFlags:t?t.permanentFlags.slice():[]};return this.server.condstore&&typeof e.HIGHESTMODSEQ=="number"&&(r.highestModseq=e.HIGHESTMODSEQ),this.mailboxInfoHandlers.forEach(n=>n(e,r)),r}listMessages(e,t={}){let r=this.requireMailbox(e,!0);return(t.uids?this.requireMessages(r,t.uids).sort((i,o)=>i.uid-o.uid):r.messages).map(i=>this.describeMessage(i,!!t.raw))}getMessage(e,t,r={}){let n=this.requireMailbox(e,!0);return this.describeMessage(this.requireMessages(n,[t])[0],r.raw!==!1)}describeMessage(e,t){let r={uid:e.uid,flags:e.flags.slice(),internaldate:e.internaldate,size:e.raw.length};return this.server.condstore&&typeof e.MODSEQ=="number"&&(r.modseq=e.MODSEQ),t&&(r.raw=b.Buffer.from(e.raw,"binary")),this.messageInfoHandlers.forEach(n=>n(e,r)),r}sessions(){return[...this.server.connections].map(e=>e.describe()).sort((e,t)=>e.session-t.session)}addMessage(e,t,r={}){let n=this.requireMailbox(e,!0),{raw:i,flags:o,internaldate:a}=t||{},u;if(typeof i=="string")u=b.Buffer.from(i,"utf-8").toString("binary");else if(i instanceof Uint8Array)u=b.Buffer.from(i).toString("binary");else throw new z("Message source (raw) must be a string or a Buffer","INVALID");if(!u.length)throw new z("Message source (raw) can not be empty","INVALID");let l=hn(this.server,n,o||[],!0);if(a!==void 0&&!(a instanceof Date&&!isNaN(a.getTime()))&&!this.server.validateInternalDate(a))throw new z('Internal date must be a Date or a date-time string like "17-Jul-1996 02:44:25 -0700"',"INVALID");if(r.checks){let f=this.server.appendChecks.map(p=>p(null,n,[{raw:u,flags:l,internaldate:a}],{command:"APPEND"})).find(p=>p&&!p.soft);if(f){let p=Array.isArray(f.code)?f.code[0]:f.code;throw new z(f.text,typeof p=="string"?p:"CANNOT")}}return{uid:this.run(()=>this.server.appendMessage(n,l,a||null,u)).message.uid,uidvalidity:n.uidvalidity}}setFlags(e,t,r,n="set"){let i=this.requireMailbox(e,!0),o=this.requireMessages(i,t);return this.run(()=>Ma(this.server,i,o,r,n)),o.map(a=>({uid:a.uid,flags:a.flags.slice()}))}expungeMessages(e,t){let r=this.requireMailbox(e,!0),n=this.requireMessages(r,t);return this.run(()=>it(this.server,r,n)).map(i=>i.uid)}copyMessages(e,t,r){return this.transfer(e,t,r,!1)}moveMessages(e,t,r){return this.transfer(e,t,r,!0)}transfer(e,t,r,n){let i=this.requireMailbox(e,!0),o=this.requireMailbox(r,!0),a=this.requireMessages(i,t).sort((u,l)=>u.uid-l.uid);return this.run(()=>{let u=a.map(l=>({uid:l.uid,targetUid:this.server.copyMessage(o,l).message.uid}));return n&&it(this.server,i,a),{uidvalidity:o.uidvalidity,uids:u}})}replaceMessage(e,t,r){let n=this.requireMailbox(e,!0),i=this.requireMessages(n,[t])[0],o=this.addMessage(e,{raw:r&&r.raw,flags:r&&r.flags?r.flags:i.flags.slice(),internaldate:r&&r.internaldate?r.internaldate:i.internaldate});return this.run(()=>it(this.server,n,[i])),o}createMailbox(e,t={}){this.checkName(e);let r=this.run(()=>{let n=xs(this.server,e);return t.subscribed&&Ht(this.server,n.path),n});return this.describeMailbox(r)}deleteMailbox(e){this.checkPath(e),this.run(()=>Cs(this.server,e))}renameMailbox(e,t){this.checkPath(e),this.checkName(t);let r=this.run(()=>ws(this.server,e,t));return this.getMailbox(r.path)}resetUidValidity(e,t={}){let r=this.requireMailbox(e,!0);return this.run(()=>La(this.server,r,t||{}))}subscribe(e){return this.checkPath(e),this.run(()=>Ht(this.server,e))}unsubscribe(e){return this.checkPath(e),this.run(()=>Ns(this.server,e))}listUsers(){return Object.keys(this.server.users).sort().map(e=>({name:e,xoauth2:!!(this.server.users[e].xoauth2&&this.server.users[e].xoauth2.accessToken)}))}addUser(e,t){if(typeof e!="string"||!e)throw new z("User name must be a non-empty string","INVALID");if(Object.hasOwn(this.server.users,e))throw new z("User "+JSON.stringify(e)+" already exists","ALREADYEXISTS");this.server.users[e]=this.userData({},t)}updateUser(e,t){this.server.users[e]=this.userData(this.requireUser(e),t)}deleteUser(e,t={}){this.requireUser(e),delete this.server.users[e],t.disconnect!==!1&&this.findSessions({user:e}).forEach(r=>r.bye("User was deleted","USER DELETED"))}requireUser(e){if(typeof e!="string"||!Object.hasOwn(this.server.users,e))throw new z("User "+JSON.stringify(e)+" does not exist","NONEXISTENT");return this.server.users[e]}userData(e,t){let{password:r,xoauth2:n,displayName:i,oauth:o}=t||{},a=Object.assign({},e);if(i===null)delete a.displayName;else if(i!==void 0){if(typeof i!="string")throw new z("displayName must be a string","INVALID");a.displayName=i}if(o===null?delete a.oauth:o!==void 0&&(a.oauth=io(o,"oauth")),r!==void 0){if(typeof r!="string")throw new z("Password must be a string","INVALID");a.password=r}if(n===null)delete a.xoauth2;else if(n!==void 0){if(typeof n!="object"||typeof n.accessToken!="string")throw new z("xoauth2 must be { accessToken, sessionTimeout }","INVALID");a.xoauth2={accessToken:n.accessToken,sessionTimeout:Number(n.sessionTimeout)||Os}}return a}disconnect(e,t={}){let r=this.findSessions(e);return r.forEach(n=>{t.reset?n.closeNow("reset"):n.bye(t.text||"Disconnected by the server","DISCONNECT")}),r.length}inject(e,t){let r=this.findSessions({session:e})[0];if(!r)throw new z("Session "+e+" does not exist","NONEXISTENT");if(typeof t!="string"&&!(t instanceof Uint8Array))throw new z("Data must be a string or a Buffer","INVALID");r.write(b.Buffer.from(t))}reset(){this.server.connections.forEach(e=>{e.isOpen()&&e.bye("Server reset","RESET")}),this.run(()=>{this.server.loadUsers(),this.server.loadStorage(),this.server.emit("reset")})}shutdown(e={}){return new Promise((t,r)=>{let n=i=>i&&i.code!=="ERR_SERVER_NOT_RUNNING"?r(i):t();e.graceful===!1?this.server.close(n):(this.server.closeListeners(!1),this.server.closeImapListeners(n))})}};g();var oo=["FETCH","UID FETCH"];function hd(s){return String(s[0]&&s[0].value||"").toUpperCase().replace(/(^|\.)(MIME|HEADER(\.FIELDS(\.NOT)?)?|TEXT)$/,"")}function Zu(s,e){let t=s.attributes&&s.attributes[2];if(!Array.isArray(t)||!s.attributes[1]||s.attributes[1].value!=="FETCH")return;let r=t.slice();for(let n=0;n<r.length-1;n+=2){let i=r[n];i&&i.type==="ATOM"&&String(i.value).toUpperCase()==="BODY"&&Array.isArray(i.section)&&(r[n+1]=e(i,r[n+1]))}return Object.assign({},s,{attributes:[s.attributes[0],s.attributes[1],r]})}var Zt={"james-fetchgroup":{description:"Apache James FetchGroup: only the first section asked for a part in one FETCH is answered, later ones for the same part come back empty. BODY[2.MIME] BODY[2] gives a zero-length body, the reverse order loses the headers",rules:[{on:"response",command:oo,untagged:!0,mutate:s=>{let e=new Set;return Zu(s,(t,r)=>{let n=hd(t.section);return e.has(n)?{type:"LITERAL",value:""}:(e.add(n),r)})}}]},"james-late-fetch":{description:"Apache James: now and then (1 in 4) a FETCH response comes after the tagged OK of its command",rules:[{on:"response",command:oo,untagged:!0,chance:.25,defer:"tagged"}]},"yahoo-quoted-sections":{description:"Yahoo: short body sections (up to 100 octets without line breaks) are quoted strings instead of literals",rules:[{on:"response",command:oo,untagged:!0,mutate:s=>Zu(s,(e,t)=>t&&t.type==="LITERAL"&&typeof t.value=="string"&&t.value.length<=100&&/^[\x20-\x7e]*$/.test(t.value)?{type:"STRING",value:t.value}:t)}]},"m365-throttle":{description:'Microsoft 365: 1 in 10 commands (not LOGOUT) is refused with "BAD Request is throttled. Suggested Backoff Time: 1000 milliseconds"',rules:[{on:"command",chance:.1,when:s=>s.command!=="LOGOUT",send:`$TAG BAD Request is throttled. Suggested Backoff Time: 1000 milliseconds\r
32
- `}]},"no-uidplus":{description:"A server without UIDPLUS: no APPENDUID, COPYUID or UID EXPUNGE, even when the plugins list it",removePlugins:["UIDPLUS"]},"no-move":{description:"A server without MOVE, clients have to COPY, STORE \\Deleted and EXPUNGE",removePlugins:["MOVE"]}};function el(s){let e=[],t=new Map;return[].concat(s||[]).forEach(r=>{let n=String(r).toLowerCase(),i=Object.hasOwn(Zt,n)?Zt[n]:null;if(!i)throw new Error('Unknown quirk "'+r+'". Available quirks: '+Object.keys(Zt).join(", "));e.push(...i.rules||[]),(i.removePlugins||[]).forEach(o=>t.set(o,n))}),{rules:e,removePlugins:t}}g();var dd=["acl","metadata","special-use","MAILBOXID","HIGHESTMODSEQ","qresyncExpunged","appendLimit","SAVEDATE","MODSEQ","EMAILID","THREADID","X-GM-LABELS","X-GM-MSGID","X-GM-THRID"],dr={type:"array",items:{type:"string"}},ao={type:"integer",minimum:1,maximum:4294967295},lo={$schema:"https://json-schema.org/draft/2020-12/schema",title:"ImapKit storage",description:'Namespaces by prefix ("INBOX", "", "INBOX.", "#shared/" ...), INBOX is a mailbox of its own',type:"object",properties:{INBOX:{$ref:"#/$defs/mailbox"}},additionalProperties:{$ref:"#/$defs/namespace"},$defs:{message:{oneOf:[{type:"string",description:"the message source"},{type:"object",properties:{raw:{type:"string",description:"the message source (a Buffer also works in JavaScript)"},uid:ao,flags:{oneOf:[{type:"string"},dr]},internaldate:{type:"string",description:'RFC 3501 date-time, e.g. "14-Sep-2013 21:22:28 -0300" (a Date also works in JavaScript)'},recent:{type:"boolean"}}}]},mailbox:{type:"object",properties:{uid:{type:"integer"},uidvalidity:ao,uidnext:ao,flags:dr,permanentFlags:dr,allowPermanentFlags:{type:"boolean"},subscribed:{type:"boolean"},knownFlags:dr,messages:{type:"array",items:{$ref:"#/$defs/message"}},folders:{type:"object",additionalProperties:{$ref:"#/$defs/mailbox"}}}},namespace:{type:"object",properties:{separator:{type:"string",minLength:1,maxLength:1},type:{enum:["personal","user","shared"]},folders:{type:"object",additionalProperties:{$ref:"#/$defs/mailbox"}}}}}},uo=Object.keys(lo.$defs.mailbox.properties),pd=["separator","type"],md=Object.keys(lo.$defs.message.oneOf[1].properties);function gd(s,e){return e.includes(s)||dd.includes(s)?null:e.find(t=>t.toLowerCase()===s.toLowerCase()||s.length>3&&Ed(t,s)===1)||null}function Ed(s,e){let t=Array.from({length:e.length+1},(r,n)=>n);for(let r=1;r<=s.length;r++){let n=t[0];t[0]=r;for(let i=1;i<=e.length;i++){let o=t[i];t[i]=Math.min(t[i]+1,t[i-1]+1,n+(s[r-1]===e[i-1]?0:1)),n=o}}return t[e.length]}var pr=s=>!!s&&typeof s=="object"&&!Array.isArray(s),tl=s=>Array.isArray(s)&&s.every(e=>typeof e=="string"),sl=s=>Number.isSafeInteger(s)&&s>=1&&s<=4294967295;function co(s){let e=(i,o)=>{throw new Error("Invalid storage at "+i+": "+o)},t=(i,o,a)=>{Object.keys(i).forEach(u=>{let l=gd(u,a);l&&e(o,"unknown key "+JSON.stringify(u)+", did you mean "+JSON.stringify(l)+"?")})},r=(i,o)=>{if(!(typeof i=="string"||i instanceof Uint8Array)){if(!pr(i))return e(o,"a message is a string or an object");t(i,o,md),i.raw!==void 0&&typeof i.raw!="string"&&!(i.raw instanceof Uint8Array)&&e(o+".raw","must be a string"),i.uid!==void 0&&!sl(i.uid)&&e(o+".uid","must be an integer from 1 to "+4294967295),i.flags!==void 0&&typeof i.flags!="string"&&!tl(i.flags)&&e(o+".flags","must be a flag or a list of flags");for(let a of["internaldate","SAVEDATE"]){let u=i[a];u===void 0||u===!1||a==="SAVEDATE"&&u===null||(u instanceof Date?isNaN(u.getTime()):!ks(u))&&e(o+"."+a,'must be a date-time string like "14-Sep-2013 21:22:28 -0300" or a Date, not '+JSON.stringify(u))}i.recent!==void 0&&typeof i.recent!="boolean"&&e(o+".recent","must be true or false")}},n=(i,o,a)=>{if(!pr(i))return e(o,"a mailbox is an object");t(i,o,a);for(let u of["uidvalidity","uidnext"])i[u]!==void 0&&!sl(i[u])&&e(o+"."+u,"must be an integer from 1 to "+4294967295);for(let u of["flags","permanentFlags","knownFlags"])i[u]!==void 0&&!tl(i[u])&&e(o+"."+u,"must be a list of strings");for(let u of["allowPermanentFlags","subscribed"])i[u]!==void 0&&typeof i[u]!="boolean"&&e(o+"."+u,"must be true or false");i.messages!==void 0&&(Array.isArray(i.messages)||e(o+".messages","must be a list of messages"),i.messages.forEach((u,l)=>r(u,o+".messages["+l+"]"))),i.folders!==void 0&&(pr(i.folders)||e(o+".folders","must be an object of mailboxes by name"),Object.keys(i.folders).forEach(u=>n(i.folders[u],o+".folders["+JSON.stringify(u)+"]",uo)))};pr(s)||e("the top level","storage is an object of namespaces"),Object.keys(s).forEach(i=>{let o=s[i],a=JSON.stringify(i);if(i==="INBOX")return n(o,a,uo.concat("separator"));n(o,a,uo.concat(pd));let u=o;u.separator!==void 0&&(typeof u.separator!="string"||u.separator.length!==1)&&e(a+".separator","must be a single character"),u.type!==void 0&&!["personal","user","shared"].includes(u.type)&&e(a+".type",'must be "personal", "user" or "shared"')})}g();g();var fo=s=>()=>{throw new Error(s+" is not available in the browser")},Ad=fo("The REST API and the OAuth provider"),yd=fo("The REST API"),bd=fo("The REST API"),ce={createServer:Ad,createHash:yd,timingSafeEqual:bd};var Td=64*1024*1024,Sd={NONEXISTENT:404,NOTFOUND:404,ALREADYEXISTS:409,INVALID:400,UNAUTHORIZED:401,METHOD:405,TOOBIG:413,UNSUPPORTED:415};function ke(s){let e=s.replace(/^\[|\]$/g,"").toLowerCase();return e==="localhost"||e==="::1"||/^(::ffff:)?127\.\d+\.\d+\.\d+$/.test(e)}var es=s=>/^\d+$/.test(s)?Number(s):NaN;function rl(s){let{raw:e,...t}=s;return e?Object.assign(t,{raw:e.toString("base64"),encoding:"base64"}):t}function Id(s,e){if(e!==void 0&&e!=="base64"&&e!=="utf-8")throw K('encoding must be "utf-8" or "base64"',"INVALID");return e==="base64"&&typeof s=="string"?b.Buffer.from(s,"base64"):s}var ho=["session","command","mailbox","append","expunge","flags","acl","script","reset","oauth"],nl=["trace"],po=s=>s?s.sessionNumber:null;function Od(s,e){switch(s){case"mailbox":{let{type:t,path:r,oldPath:n,origin:i}=e[0];return{type:t,path:r,oldPath:n,origin:po(i)}}case"append":case"expunge":return{path:e[0].path,uids:e[1].map(t=>t.uid),origin:po(e[2])};case"trace":{let{session:t,direction:r,data:n}=e[0];return{session:t,direction:r,data:b.Buffer.from(n).toString("base64"),encoding:"base64"}}case"flags":return{path:e[0].path,messages:e[1].map(t=>({uid:t.uid,flags:t.flags.slice()})),origin:po(e[2])};case"acl":return{path:e[0].path};default:return e[0]||{}}}function xd(s,e,t){return(r,n)=>{t.add(r),r.writeHead(200,{"Content-Type":"text/event-stream; charset=utf-8","Cache-Control":"no-store"}),r.write(`: connected
31
+ `);return e.trim()?e:s}var Mh=new Set(["a","abbr","b","bdi","bdo","big","cite","code","del","dfn","em","font","i","ins","kbd","mark","q","s","samp","small","span","strike","strong","sub","sup","time","tt","u","var","wbr"]),Rh="nbsp iexcl cent pound curren yen brvbar sect uml copy ordf laquo not shy reg macr deg plusmn sup2 sup3 acute micro para middot cedil sup1 ordm raquo frac14 frac12 frac34 iquest Agrave Aacute Acirc Atilde Auml Aring AElig Ccedil Egrave Eacute Ecirc Euml Igrave Iacute Icirc Iuml ETH Ntilde Ograve Oacute Ocirc Otilde Ouml times Oslash Ugrave Uacute Ucirc Uuml Yacute THORN szlig agrave aacute acirc atilde auml aring aelig ccedil egrave eacute ecirc euml igrave iacute icirc iuml eth ntilde ograve oacute ocirc otilde ouml divide oslash ugrave uacute ucirc uuml yacute thorn yuml",bu=Object.assign(Object.fromEntries(Rh.split(" ").map((s,e)=>[s,String.fromCharCode(160+e)])),{amp:"&",lt:"<",gt:">",quot:'"',apos:"'",trade:"\u2122",hellip:"\u2026",mdash:"\u2014",ndash:"\u2013",lsquo:"\u2018",rsquo:"\u2019",ldquo:"\u201C",rdquo:"\u201D",bull:"\u2022",euro:"\u20AC",zwnj:"\u200C",zwj:"\u200D"});function Lh(s){s=s.replace(/<!--[\s\S]*?(?:-->|$)/g," ").replace(/<(head|script|style|title|template)\b[^<>]*>[\s\S]*?(?:<\/\1\s*>|$)/gi," ");let e=Tu(Dh(s));return e.trim()?e:Tu(s)}function Dh(s){let e=/<(\/?)blockquote\b[^<>]*>?/gi,t="",r=0,n=0,i;for(;i=e.exec(s);)r||(t+=s.slice(n,i.index)+" "),r=i[1]?Math.max(r-1,0):r+1,n=e.lastIndex;return r?t:t+s.slice(n)}function Tu(s){return s.replace(/<!\[CDATA\[([\s\S]*?)(?:\]\]>|$)/g,"$1").replace(/<\/?([A-Za-z][A-Za-z0-9-]*)(?![A-Za-z0-9-])[^<>]*>|<[!?][^<>]*>/g,(e,t)=>t&&Mh.has(t.toLowerCase())?"":" ").replace(/&(#[0-9]+|#[xX][0-9A-Fa-f]+|[A-Za-z][A-Za-z0-9]*);/g,(e,t)=>{if(t[0]==="#"){let r=/^#x/i.test(t)?parseInt(t.slice(2),16):parseInt(t.slice(1),10);return r>0&&r<=1114111&&(r<55296||r>57343)?String.fromCodePoint(r):"\uFFFD"}return Object.hasOwn(bu,t)?bu[t]:e})}function Iu(s,e){let t=s.replace(/[^\P{Cc}\t\n\v\f\r]|\u00ad/gu,"").replace(/[\s\u200b]+/g," ").trim();return Array.from(t).slice(0,e).join("").trimEnd()}E();E();function or(s){let e=!!s.message&&!!s.attributes&&s.attributes[1];return!!e&&e.type==="ATOM"&&String(e.value).toUpperCase()==="EXPUNGE"}function ar(s){if(!s.some(or))return s;let e=[];return s.forEach(t=>{or(t)?Array.isArray(e[e.length-1])?e[e.length-1].push(t.message):e.push([t.message]):e.push(t)}),e.map(t=>Array.isArray(t)?{tag:"*",command:"VANISHED",attributes:[{type:"SEQUENCE",value:lt(t.map(r=>r.uid))}],notification:!0,messages:t}:t)}var Uh=new Set(["EXPUNGE","UID EXPUNGE","MOVE","UID MOVE","REPLACE","UID REPLACE"]);function ur(s){s.registerCapability("QRESYNC"),Ne(s,"QRESYNC"),s.resetHandlers.push(m=>{m.qresyncExpunged=!1});let e=new WeakMap,t=m=>ye(m,"QRESYNC"),{isEnabled:r,getHighestModseq:n}=s.condstore,i=(m,h)=>((!m.qresyncExpunged||m.qresyncExpunged.uidvalidity!==m.uidvalidity)&&(m.qresyncExpunged={uidvalidity:m.uidvalidity,since:h||n(m),list:[]}),m.qresyncExpunged),o=s.indexFolders;s.indexFolders=function(...m){let h=o.apply(this,m);return Object.keys(this.folderCache).forEach(d=>i(this.folderCache[d])),h},s.on("expunge",(m,h,d)=>{let g=n(m),T=i(m,g-1).list;h.forEach(C=>{let H=T[T.length-1];H&&H.modseq===g&&H.to+1===C.uid?H.to=C.uid:T.push({from:C.uid,to:C.uid,modseq:g}),e.set(C,g)}),d&&(d.qresyncExpunged=!0)});let a=(m,h,d,g,T)=>{let{since:C,list:H}=i(m),N;return g>=C?N=Ou(yi(H.filter(w=>w.modseq>g).map(w=>[w.from,w.to])),d):N=Ou(d,[[(T||0)+1,m.uidnext-1]]),Bh(N,h).map(w=>w[0]===w[1]?String(w[0]):w[0]+":"+w[1]).join(",")},u=(m,h,d,g,T)=>(m.sendStatus(h,d,"BAD",T,!1,"QRESYNC FAILED"),g()),l=(m,h)=>{let d=s.getCommandHandler(m);d&&s.setCommandHandler(m,(g,T,C,H)=>h(d,g,T,C,H))},c=(m,h,d,g,T)=>{let C=d.attributes&&d.attributes[1],H=G=>J(G,"QRESYNC"),N=Array.isArray(C)?C.findIndex(H):-1;if(N<0)return m(h,d,g,T);if(!t(h))return u(h,d,g,T,"QRESYNC parameter requires ENABLE QRESYNC");if(C.findLastIndex(H)!==N)return u(h,d,g,T,"QRESYNC parameter can be used only once");let w;try{w=Hh(C[N+1])}catch(G){return u(h,d,g,T,G.message)}C.splice(N,2),C.length||d.attributes.splice(1,1),d.qresync=w,m(h,d,g,T)};l("SELECT",c),l("EXAMINE",c);let f=(m,h,d,g,T,C)=>{let H=g.attributes&&g.attributes[2],N=G=>J(G,"VANISHED"),w=Array.isArray(H)?H.findIndex(N):-1;if(w<0)return h(d,g,T,C);if(!m)return u(d,g,T,C,"VANISHED is only allowed with UID FETCH");if(!t(d))return u(d,g,T,C,"VANISHED requires ENABLE QRESYNC");if(H.findLastIndex(N)!==w)return u(d,g,T,C,"VANISHED can be used only once");if(!H.some(G=>J(G,"CHANGEDSINCE")))return u(d,g,T,C,"VANISHED requires CHANGEDSINCE");H.splice(w,1),g.qresyncVanished=!0,h(d,g,T,C)};l("FETCH",f.bind(null,!1)),l("UID FETCH",f.bind(null,!0)),s.connectionHandlers.push(m=>{let h=m.prepareNotifications;m.prepareNotifications=function(d){return d=h.call(this,d),t(this)?ar(d):d}});let p=(m,h,d,g)=>{h&&m.send({tag:"*",command:"VANISHED",attributes:[[{type:"ATOM",value:"EARLIER"}],{type:"SEQUENCE",value:h}]},"VANISHED EARLIER",d,g)},y=(m,h,d)=>{let g=m.selectedMailbox,T=h.qresync;if(T.uidvalidity!==g.uidvalidity)return;let C=T.knownUids||(g.uidnext>1?[[1,g.uidnext-1]]:[]),H=0;if(T.seqMatch){let w=xu(T.seqMatch.uids);for(let G of xu(T.seqMatch.sequences)){let F=w.next().value,W=g.messages[G-1];if(!W||W.uid!==F)break;H=F}}p(m,a(g,g.messages,C,T.modseq,H),h,d);let N=s.fetchHandlers.FLAGS||Te.FLAGS;g.messages.forEach((w,G)=>{w.MODSEQ<=T.modseq||!kh(C,w.uid)||m.send({tag:"*",attributes:[G+1,{type:"ATOM",value:"FETCH"},[{type:"ATOM",value:"UID"},w.uid,{type:"ATOM",value:"FLAGS"},N(m,w,{type:"ATOM",value:"FLAGS"}),{type:"ATOM",value:"MODSEQ"},[w.MODSEQ]]]},"QRESYNC FETCH",h,d,w)})},A=m=>({type:"SECTION",section:[{type:"ATOM",value:"HIGHESTMODSEQ"},m]});s.outputHandlers.push((m,h,d,g,T)=>{if(!g||!h||h.tag==="+")return;let C=h.tag!=="*"&&h.tag===g.tag;if(g.qresyncVanished&&(h.tag==="*"&&d==="UID FETCH"||C&&h.command==="OK")){g.qresyncVanished=!1;let N=m.selectedMailbox,w=vh(g.attributes[0].value,N.uidnext-1);w&&p(m,a(N,m.getSessionMessages(),w,g.changedsince),g,T);return}if(!C)return;if(g.qresync&&h.command==="OK"&&(d==="SELECT"||d==="EXAMINE")&&m.selectedMailbox){y(m,g,T);return}let H=m.qresyncExpunged;if(m.qresyncExpunged=!1,H&&h.command==="OK"&&Uh.has(String(g.command).toUpperCase())&&m.selectedMailbox&&r(m)){h.attributes&&h.attributes[0]&&h.attributes[0].type==="SECTION"||(h.attributes=[A(n(m.selectedMailbox))].concat(h.attributes||[]));return}if(r(m)){let N=0;m.notificationQueue.forEach(w=>{let G=or(w)&&w.message&&e.get(w.message);G&&(!N||G<N)&&(N=G)}),N>1&&m.send({tag:"*",command:"OK",attributes:[A(N-1),{type:"TEXT",value:"Expunges not reported yet"}]},"QRESYNC HIGHESTMODSEQ",g,T)}})}function Ai(s,e){if(!s||Array.isArray(s)||["ATOM","SEQUENCE"].indexOf(s.type)<0||!Is(s.value,!0))throw new Error("Invalid QRESYNC "+e+', a sequence set without "*" expected');return s.value.split(",").map(t=>{let r=t.split(":").map(Number);return[r[0],r.length>1?r[1]:r[0]]})}function vh(s,e){return/^[\d*:,]+$/.test(String(s))?yi(String(s).split(",").map(t=>t.split(":").map(r=>r==="*"?e:Number(r)))):!1}function Ou(s,e){let t=[],r=0,n=0;for(;r<s.length&&n<e.length;){let i=Math.max(s[r][0],e[n][0]),o=Math.min(s[r][1],e[n][1]);i<=o&&t.push([i,o]),s[r][1]<e[n][1]?r++:n++}return t}function Bh(s,e){let t=[],r=0;return s.forEach(([n,i])=>{let o=n;for(;r<e.length&&e[r].uid<n;)r++;for(;r<e.length&&e[r].uid<=i;r++)e[r].uid>o&&t.push([o,e[r].uid-1]),o=e[r].uid+1;o<=i&&t.push([o,i])}),t}function yi(s){let e=s.map(r=>[Math.min(...r),Math.max(...r)]).sort((r,n)=>r[0]-n[0]),t=[];return e.forEach(r=>{let n=t[t.length-1];n&&r[0]<=n[1]+1?n[1]=Math.max(n[1],r[1]):t.push(r)}),t}function*xu(s){for(let[e,t]of s)for(let r=e;r<=t;r++)yield r}function Cu(s,e){let t=0,r=0;return s.forEach(([n,i])=>{if(n>i||n<=t)throw new Error("Invalid QRESYNC "+e+", numbers must be in ascending order");t=i,r+=i-n+1}),r}function Hh(s){if(!Array.isArray(s)||s.length<2||s.length>4)throw new Error("QRESYNC expects (uidvalidity modseq [known-uids] [(known-sequence-set known-uid-set)])");let[e,t]=s;if(!J(e)||!Le(e.value))throw new Error("Invalid QRESYNC uidvalidity, a non-zero number expected");if(!J(t)||!Ae(t.value,Ge)||BigInt(t.value)<1n)throw new Error("Invalid QRESYNC mod-sequence, a positive number expected");let r={uidvalidity:Number(e.value),modseq:Number(t.value),knownUids:!1,seqMatch:!1},n=s.slice(2);if(n.length&&!Array.isArray(n[0])&&(r.knownUids=yi(Ai(n.shift(),"known-uids"))),n.length){let i=n.shift();if(!Array.isArray(i)||i.length!==2||n.length)throw new Error("Invalid QRESYNC parameters, (known-sequence-set known-uid-set) expected last");let o=Ai(i[0],"known-sequence-set"),a=Ai(i[1],"known-uid-set"),u=Cu(o,"known-sequence-set");if(Cu(a,"known-uid-set")!==u)throw new Error("Invalid QRESYNC sets, known-sequence-set and known-uid-set must have as many numbers");r.seqMatch={sequences:o,uids:a}}return r}function kh(s,e){return s.some(t=>e>=t[0]&&e<=t[1])}ur.requires=["ENABLE","CONDSTORE"];E();var Mt=["STORAGE","MESSAGE","MAILBOX"],Ph="User quota";function bi(s){let e=s.options.quota||{},t={name:typeof e.root=="string"?e.root:Ph,soft:!!e.soft,limits:{}},r={};Mt.forEach(h=>{if(e[h]===void 0||e[h]===null)return;let d=Number(e[h]);if(!Number.isSafeInteger(d)||d<0)throw new Error("Invalid quota limit for "+h+": "+JSON.stringify(e[h]));r[h]=d});let n=()=>{t.limits=Object.assign({},r)};n(),s.on("reset",n),s.registerCapability("QUOTA"),Mt.forEach(h=>s.registerCapability("QUOTA=RES-"+h)),s.registerCapability("QUOTASET");let i=h=>s.isPersonal(h),o=h=>h.flags.indexOf("\\Noselect")<0,a=h=>h.reduce((d,g)=>d+_t(g.raw).length,0),u=()=>{let h={MESSAGE:0,MAILBOX:0,bytes:0};return Object.keys(s.folderCache).forEach(d=>{let g=s.folderCache[d];!o(g)||!i(g)||(h.MAILBOX++,h.MESSAGE+=g.messages.length,h.bytes+=a(g.messages))}),h},l=(h,d,g)=>{let T=u();T.STORAGE=Math.ceil(T.bytes/1024);let C=[];Mt.forEach(H=>{H in t.limits&&C.push({type:"ATOM",value:H},T[H],t.limits[H])}),h.send({tag:"*",command:"QUOTA",attributes:[{type:"STRING",value:t.name},C]},"QUOTA",d,g)},c=h=>{if(!(h.MESSAGE&&"MESSAGE"in t.limits||h.bytes&&"STORAGE"in t.limits||h.MAILBOX&&"MAILBOX"in t.limits))return;let g=u();if(h.MESSAGE&&"MESSAGE"in t.limits&&g.MESSAGE+h.MESSAGE>t.limits.MESSAGE||h.bytes&&"STORAGE"in t.limits&&g.bytes+h.bytes>t.limits.STORAGE*1024||h.MAILBOX&&"MAILBOX"in t.limits&&g.MAILBOX+h.MAILBOX>t.limits.MAILBOX)return t.soft?{code:"OVERQUOTA",text:"Soft quota has been exceeded",soft:!0}:{code:"OVERQUOTA",text:"Quota exceeded"}};s.appendChecks.push((h,d,g,T)=>{if(!g.length||!i(d)||T.move&&T.source&&i(T.source))return;let C={MESSAGE:g.length,bytes:a(g)};return T.replaced&&h&&h.selectedMailbox&&i(h.selectedMailbox)&&(C.MESSAGE--,C.bytes-=a([T.replaced])),c(C)});let f=h=>{let d=s.getMailbox(s.stripSeparator(h,s.getSeparator(h))),g=!d||!o(d)?1:0;for(let T=s.getParentPath(h);T;T=s.getParentPath(T))s.getMailbox(T)||g++;return g},p=(h,d)=>{let g=s.getCommandHandler(h);s.setCommandHandler(h,(T,C,H,N)=>{let w=d(C.attributes);if(typeof w=="string"&&w.toUpperCase()!=="INBOX"&&i(w)&&!T.applyChecks([c({MAILBOX:f(w)})],C,H,h+" FAILED"))return N();g(T,C,H,N)})},y=(h,d)=>ue((h||[])[d])&&h[d].value;p("CREATE",h=>h&&h.length===1?y(h,0):!1),p("RENAME",h=>{let d=y(h,0);return h&&h.length===2&&typeof d=="string"&&d.toUpperCase()==="INBOX"?y(h,1):!1}),s.setCommandHandler("GETQUOTA",(h,d,g,T)=>!d.attributes||d.attributes.length!==1||!ue(d.attributes[0])?(h.sendStatus(d,g,"BAD","GETQUOTA expects a quota root name"),T()):d.attributes[0].value!==t.name?(h.sendStatus(d,g,"NO","Quota root does not exist","NONEXISTENT"),T()):(l(h,d,g),h.sendStatus(d,g,"OK","GETQUOTA completed"),T()),{states:Z.AUTHENTICATED,astringArguments:[0]}),s.setCommandHandler("GETQUOTAROOT",(h,d,g,T)=>{if(!d.attributes||d.attributes.length!==1||!ue(d.attributes[0]))return h.sendStatus(d,g,"BAD","GETQUOTAROOT expects a mailbox name"),T();let C=d.attributes[0].value;C.toUpperCase()==="INBOX"&&(C="INBOX");let H=i(C);return h.send({tag:"*",command:"QUOTAROOT",attributes:[{type:"MAILBOX",value:C}].concat(H?{type:"STRING",value:t.name}:[])},"QUOTAROOT",d,g),H&&l(h,d,g),h.sendStatus(d,g,"OK","GETQUOTAROOT completed"),T()},{states:Z.AUTHENTICATED,mailboxArguments:[0]}),s.setCommandHandler("SETQUOTA",(h,d,g,T)=>{let C=d.attributes&&d.attributes[1];if(!d.attributes||d.attributes.length!==2||!ue(d.attributes[0])||!Array.isArray(C)||C.length%2)return h.sendStatus(d,g,"BAD","SETQUOTA expects a quota root name and a list of resource limits"),T();let H={};for(let N=0;N<C.length;N+=2){let w=C[N],G=C[N+1];if(!w||w.type!=="ATOM"||!G||G.type!=="ATOM"||!Ae(G.value,Ge))return h.sendStatus(d,g,"BAD","Invalid resource limit"),T();let F=w.value.toUpperCase();if(Mt.indexOf(F)<0||F in H)return h.sendStatus(d,g,"NO","Can not set a limit for "+F,"CANNOT"),T();let W=Number(G.value);if(!Number.isSafeInteger(W))return h.sendStatus(d,g,"NO","Limit is too large for "+F,"LIMIT"),T();H[F]=W}return d.attributes[0].value!==t.name?(h.sendStatus(d,g,"NO","Quota root does not exist","NONEXISTENT"),T()):(t.limits=H,l(h,d,g),h.sendStatus(d,g,"OK","SETQUOTA completed"),T())},{states:Z.AUTHENTICATED,astringArguments:[0]}),["DELETED","DELETED-STORAGE"].forEach(h=>{s.allowedStatus.indexOf(h)<0&&s.allowedStatus.push(h)}),s.statusHandlers["DELETED-STORAGE"]=(h,d)=>a(d.messages.filter(g=>g.flags.indexOf("\\Deleted")>=0));let A=()=>{let h=u();return{root:t.name,limits:Object.assign({},t.limits),usage:{STORAGE:Math.ceil(h.bytes/1024),MESSAGE:h.MESSAGE,MAILBOX:h.MAILBOX}}},m=h=>{if(!h||typeof h!="object"||Array.isArray(h))throw K("setQuota expects an object of resource limits, e.g. { STORAGE: 1024 }","INVALID");let d={};return Object.keys(h).forEach(g=>{let T=g.toUpperCase(),C=h[g];if(Mt.indexOf(T)<0)throw K("Unknown quota resource "+g+", expected "+Mt.join(", "),"INVALID");if(typeof C!="number"||!Number.isSafeInteger(C)||C<0)throw K("Limit of "+T+" must be a non-negative integer","INVALID");d[T]=C}),t.limits=d,A()};s.control.register("getQuota",A,[{method:"GET",path:"/v1/quota",summary:"Quota root, limits and usage (QUOTA plugin)",handler:()=>s.control.getQuota()}]),s.control.register("setQuota",m,[{method:"PUT",path:"/v1/quota",summary:"Replaces the quota limits ({ STORAGE, MESSAGE, MAILBOX }, QUOTA plugin)",handler:({body:h})=>s.control.setQuota(h)}])}E();var wu=s=>s==="*"||Le(s);function Ti(s){s.registerCapability("REPLACE");let e=function(r,n,i,o,a){let u=r?"UID REPLACE":"REPLACE",l=[].concat(i.attributes||[]),c=l.shift(),f=l.shift();if(!c||["ATOM","SEQUENCE"].indexOf(c.type)<0||!wu(String(c.value)))return n.sendStatus(i,o,"BAD",u+" expects a message number, a mailbox name and a message",!1,"INVALID COMMAND"),a();let p=Nu(n,r,c.value);if(p.error)return n.sendStatus(i,o,p.error.command,p.error.text,p.error.code||!1,p.error.command==="BAD"?"INVALID COMMAND":u+" FAILED"),a();let y=p.message,A=un(n,i,o,f,l,{command:u,maxMessages:1,replaced:y});if(!A)return a();let m=ln(n,A);n.send({tag:"*",command:"OK",attributes:[{type:"TEXT",value:"Replacement message saved"}],skipResponse:!0},"REPLACE APPENDUID",i,o,m),n.expungeSpecificMessages(n.selectedMailbox,[y],!1,!0),n.sendStatus(i,o,"OK",u+" completed",!1,u),a()};s.literalFilters.push((r,n,i)=>{if(n!=="REPLACE"&&n!=="UID REPLACE"||r.isBusy())return!1;let o=i.match(/^\S+ (?:UID )?REPLACE ([^ ]+) /i);return o&&wu(o[1])&&Nu(r,n==="UID REPLACE",o[1]).error||!1});let t={states:Z.SELECTED,mailboxArguments:[1],literal8:"BINARY",appendMessage:!0};s.setCommandHandler("REPLACE",e.bind(null,!1),Object.assign({sequenceSet:0},t)),s.setCommandHandler("UID REPLACE",e.bind(null,!0),t)}function Nu(s,e,t){let r=s.getSessionMessages(),n;if(e){let o=t==="*"?r.length?r[r.length-1].uid:0:Number(t);n=r.find(a=>a.uid===o)}else{let o=t==="*"?r.length:Number(t);if(!o||o>r.length)return{error:{command:"BAD",text:"Invalid message sequence number"}};n=r[o-1]}if(!n||n.ghost)return{error:{command:"NO",text:"No such message"}};let i=s.readOnlyRefusal();return i?{error:i}:{message:n}}E();function Si(s){s.registerCapability("SASL-IR",e=>e.state==="Not Authenticated")}E();function Ii(s){s.registerCapability("SAVEDATE");let e=r=>!!r&&r.SAVEDATE!==!1;s.messageHandlers.push((r,n,i)=>{if(!e(i)){delete n.SAVEDATE;return}let o=r.normalizeDateTime(n.SAVEDATE||r.now());if(!r.validateInternalDate(o))throw new Error("Invalid SAVEDATE value "+JSON.stringify(o)+" in mailbox "+i.path);n.SAVEDATE=o}),s.fetchHandlers.SAVEDATE=(r,n)=>n.SAVEDATE||null;let t=(r,n)=>{let i=(o,a,u,l)=>{let c=vn(a.SAVEDATE||a.internaldate);return!!c&&n(c,l)};i.argumentTypes=()=>["date"],s.searchHandlers[r]=i};t("SAVEDBEFORE",(r,n)=>r<n),t("SAVEDON",(r,n)=>r===n),t("SAVEDSINCE",(r,n)=>r>=n),s.searchHandlers.SAVEDATESUPPORTED=r=>e(r.selectedMailbox)}E();function Oi(s){let e=ei(s,"SAVELIMIT");s.registerCapability("SAVELIMIT="+e),ti(s,e)}E();var Fh=new Set(["SELECT","EXAMINE","CLOSE","UNSELECT"]),_h=s=>["SEARCH","UID SEARCH","SORT","UID SORT","ESEARCH"].includes(s);function xi(s){Ie(s),s.registerCapability("SEARCHRES"),s.searchReturnOptions.set("SAVE",{data:!1}),s.connectionHandlers.push(e=>{let t=e.getMessageRange;e.getMessageRange=function(r,n){if(r!=="$")return t.call(this,r,n);let i=this.searchResult||new Set,o=[];return this.getSessionMessages().forEach((a,u)=>{i.has(a)&&o.push([u+1,a])}),o}}),s.resetHandlers.push(e=>{e.searchResult=null}),s.outputHandlers.push((e,t,r,n,i,o)=>{if(!n||!t||t.tag!==n.tag&&t.command!=="SEARCH"&&t.command!=="SORT")return;let a=(n.command||"").toUpperCase(),u=_h(a)&&n.searchReturn&&n.searchReturn.has("SAVE");if(u&&t.tag==="*"&&(t.command==="SEARCH"||t.command==="SORT")&&r===a&&o&&Array.isArray(o.list)){n.searchresFound=je(o.sorted||o.list,n.searchReturn);return}if(t.tag===n.tag){if(Fh.has(a)){e.searchResult=null;return}u&&t.command!=="BAD"&&(e.searchResult=new Set(t.command==="OK"?n.searchresFound:[]))}})}E();function Ci(s){ct(s),s.registerCapability("SORT=DISPLAY"),s.sortKeys.DISPLAYFROM=e=>He(Vn(e,"from")),s.sortKeys.DISPLAYTO=e=>He(Vn(e,"to"))}E();var Mu=new Set(["\\All","\\Archive","\\Drafts","\\Flagged","\\Junk","\\Sent","\\Trash","\\Important"]);function wi(s){s.registerCapability("SPECIAL-USE");let e=i=>[].concat(i&&i["special-use"]||[]),t=Ke(s);t.selectionOptions["SPECIAL-USE"]={type:"independent",returnOption:"SPECIAL-USE",match:i=>i.flags.indexOf("\\Noselect")<0&&e(i).length>0},t.returnOptions["SPECIAL-USE"]={};let r=s.getCommandHandler("LIST");s.setCommandHandler("LIST",(i,o,a,u)=>{if(t.enabled)return r(i,o,a,u);let l;if(o.attributes&&Array.isArray(o.attributes[0])){for(l=o.attributes[0].length-1;l>=0;l--)o.attributes[0][l]&&o.attributes[0][l].type==="ATOM"&&o.attributes[0][l].value.toUpperCase()==="SPECIAL-USE"&&(o.attributes[0].splice(l,1),o.listSpecialUseOnly=!0);o.attributes[0].length||o.attributes.splice(0,1)}if(o.attributes&&o.attributes[2]&&o.attributes[2].type==="ATOM"&&o.attributes[2].value.toUpperCase()==="RETURN"&&Array.isArray(o.attributes[3])){for(l=o.attributes[3].length-1;l>=0;l--)o.attributes[3][l]&&o.attributes[3][l].type==="ATOM"&&o.attributes[3][l].value.toUpperCase()==="SPECIAL-USE"&&o.attributes[3].splice(l,1);o.attributes[3].length||o.attributes.splice(2,2)}r(i,o,a,u)}),s.outputHandlers.push((i,o,a,u,l,c)=>{let f=e(c).map(p=>({type:"ATOM",value:p}));(a==="LIST ITEM"||a==="LSUB ITEM")&&c&&o.attributes&&Array.isArray(o.attributes[0])&&(f.length?o.attributes[0]=o.attributes[0].concat(f):u.listSpecialUseOnly&&(o.skipResponse=!0))}),s.control.mailboxInfoHandlers.push((i,o)=>{o.specialUse=e(i)});let n=(i,o)=>{let a=s.control.requireMailbox(i,!0);if(!Array.isArray(o)||o.some(u=>typeof u!="string"||!Mu.has(u)))throw K("Special-use attributes must be a list of "+[...Mu].join(", "),"INVALID");return a["special-use"]=[...new Set(o)],s.control.getMailbox(a.path)};s.control.register("setSpecialUse",n,[{method:"PUT",path:"/v1/mailboxes/{path}/special-use",summary:'Sets the special-use attributes of a mailbox ({ specialUse: ["\\Sent"] }, SPECIAL-USE plugin)',handler:({params:i,body:o})=>s.control.setSpecialUse(i.path,o.specialUse)}])}E();function Ni(s){s.registerCapability("STARTTLS",e=>!e.secureConnection),s.setCommandHandler("STARTTLS",(e,t,r,n)=>{if(e.secureConnection)return Gh("Connection is already secured",e,t,r,n);e.send({tag:t.tag,command:"OK",attributes:[{type:"TEXT",value:"Server ready to start TLS negotiation"}]},"STARTTLS INIT",t,r),e.upgradeConnection(n)})}function Gh(s,e,t,r,n){return e.send({tag:t.tag,command:"BAD",attributes:[{type:"TEXT",value:s}]},"INVALID COMMAND",t,r),n()}E();function Mi(s){s.registerCapability("STATUS=SIZE"),s.allowedStatus.push("SIZE"),s.statusHandlers.SIZE=(e,t)=>t.messages.reduce((r,n)=>r+Te["RFC822.SIZE"](e,n),0)}E();E();function Wt(s){return{entry:s||null,parent:null,children:[]}}function zt(s,e){for(;!s.entry&&s.children.length;)s=s.children[0];for(;!e.entry&&e.children.length;)e=e.children[0];return s.entry.date-e.entry.date||s.entry.seq-e.entry.seq}function Ru(s){let e=[],t=s.slice().reverse();for(;t.length;){let r=t.pop();e.push(r);for(let n=r.children.length-1;n>=0;n--)t.push(r.children[n])}return e}function Xh(s,e){let t=[],r=[],n=i=>{for(let o=i.length-1;o>=0;o--)r.push(")",i[o],"(")};for(n(s);r.length;){let i=r.pop();if(typeof i=="string"){t.push(i);continue}let o=i.children;o.length===1?r.push(o[0]):n(o),i.entry&&(o.length&&r.push(" "),t.push(e?i.entry.message.uid:i.entry.seq))}return t.join("")}function jh(s){let e=(i,o)=>i.subject.id<o.subject.id?-1:i.subject.id>o.subject.id?1:0,t=s.slice().sort((i,o)=>e(i,o)||i.date-o.date||i.seq-o.seq),r=[],n=null;for(let i of t)n&&n.entry.subject.id===i.subject.id?n.children.push(Wt(i)):(n=Wt(i),r.push(n));return r.sort(zt)}function Vh(s){let e=new Map,t=[],r=A=>{if(!e.has(A)){let m=Wt();e.set(A,m),t.push(m)}return e.get(A)},n=(A,m)=>{for(let h=A;h;h=h.parent)if(h===m)return!0;return!1},i=A=>{A.parent&&(A.parent.children.splice(A.parent.children.indexOf(A),1),A.parent=null)},o=(A,m)=>{A!==m&&(!m.children.length||!n(A,m))&&(A.children.push(m),m.parent=A)};for(let A of s){let m=ne(A.message).tree.parsedHeader,h=Ks(m["message-id"])[0],d=h!==void 0&&r(h);(!d||d.entry)&&(d=Wt(),t.push(d)),d.entry=A;let g=Ks(m.references);g.length||(g=Ks(m["in-reply-to"]).slice(0,1));let T=g.map(r);for(let H=1;H<T.length;H++)T[H].parent||o(T[H-1],T[H]);let C=T[T.length-1]||null;d.parent!==C&&(i(d),C&&o(C,d))}let a=t.filter(A=>!A.parent),u=(A,m)=>A.entry?[A]:A.children.length?m&&A.children.length>1?[A]:A.children:[];for(let A of Ru(a).reverse())A.children=A.children.flatMap(m=>u(m,!1)),A.children.forEach(m=>{m.parent=A});let l=a.flatMap(A=>u(A,!0));l.forEach(A=>{A.parent=null}),l.forEach(A=>{A.entry||A.children.sort(zt)}),l.sort(zt);let c=A=>A.entry?A.entry.subject:A.children[0].entry.subject,f=A=>!!A.entry&&A.entry.subject.isReply,p=new Map;for(let A of l){let m=c(A);if(!m.id)continue;let h=p.get(m.id);(!h||h.entry&&(!A.entry||f(h)&&!f(A)))&&p.set(m.id,A)}let y=new Set;for(let A of l){let m=c(A);if(!m.id)continue;let h=p.get(m.id);if(h!==A)if(y.add(A),!h.entry&&!A.entry)A.children.forEach(d=>o(h,d));else if(!h.entry||f(A)&&!f(h))o(h,A);else{let d=Wt();l[l.indexOf(h)]=d,o(d,h),o(d,A),p.set(m.id,d)}}l=l.filter(A=>!y.has(A));for(let A of Ru(l).reverse())A.children.sort(zt);return l.sort(zt),l}var Lu={ORDEREDSUBJECT:jh,REFERENCES:Vh};function lr(s,e){if(s.registerCapability("THREAD="+e),s.threadAlgorithms){s.threadAlgorithms[e]=Lu[e];return}s.threadAlgorithms={[e]:Lu[e]};let t=(r,n,i,o,a)=>{let u=r?"UID THREAD":"THREAD",l=i.attributes||[],c=l[0]&&l[0].type==="ATOM"?l[0].value.toUpperCase():"";if(!Object.hasOwn(s.threadAlgorithms,c))return n.sendStatus(i,o,"BAD",c?"Unsupported threading algorithm "+c:u+" expects a threading algorithm atom",!1,u+" FAILED"),a();let f=zs(n,i,o,l.slice(1));if(!f)return a();let p=f.list.map(y=>{let A=qs(ne(y).tree.parsedHeader.subject);return{message:y,seq:f.numbers[y.uid],date:Qs(y),subject:{id:He(A.subject).toString("binary"),isReply:A.isReply}}});return n.send({tag:"*",command:"THREAD",attributes:p.length?[{type:"TEXT",value:Xh(s.threadAlgorithms[c](p),r)}]:[]},u,i,o,f),n.sendStatus(i,o,"OK",u+" completed",!1,u),a()};s.setCommandHandler("THREAD",t.bind(null,!1),{states:Z.SELECTED,searchCriteria:2,noExpunge:!0}),s.setCommandHandler("UID THREAD",t.bind(null,!0),{states:Z.SELECTED,searchCriteria:2})}function Ri(s){lr(s,"ORDEREDSUBJECT")}E();function Li(s){lr(s,"REFERENCES")}E();function cr(s){s.registerCapability("UIDONLY"),Ne(s,"UIDONLY");let e=i=>ye(i,"UIDONLY"),t=i=>({command:"BAD",code:"UIDREQUIRED",text:i}),r=(i,o)=>{let a=String(o.command||"").toUpperCase(),u=s.getCommandOptions(a),l=/^UID /.test(a)||a==="ESEARCH";if(!l&&(u.sequenceSet!==!1||u.searchCriteria!==!1))return t(a+" is not allowed once UIDONLY is enabled, use UID "+a);if(l&&u.searchCriteria!==!1&&i.usesSequenceNumbers(o))return t("Message numbers are not allowed in the search criteria once UIDONLY is enabled, use UID <sequence set>");if((a==="SELECT"||a==="EXAMINE")&&o.attributes&&Array.isArray(o.attributes[1])){let c=o.attributes[1],f=c.findIndex(y=>J(y,"QRESYNC")),p=f>=0&&c[f+1];if(Array.isArray(p)&&p.slice(2).some(Array.isArray))return t("QRESYNC message sequence match data is not allowed once UIDONLY is enabled")}return!1};s.commandChecks.push((i,o)=>e(i)&&r(i,o)),s.literalFilters.unshift((i,o)=>e(i)&&r(i,{command:o})),s.connectionHandlers.push(i=>{let o=i.isAmbiguous;i.isAmbiguous=function(u){return!e(this)&&o.call(this,u)};let a=i.prepareNotifications;i.prepareNotifications=function(u){return u=a.call(this,u),e(this)?ar(u):u}});let n=(i,o,a,u,l,c)=>{if(!o||o.tag!=="*"||!Array.isArray(o.attributes)||!e(i))return;let f=o.attributes;if(o.command==="OK"&&f[0]&&f[0].type==="SECTION"&&J(f[0].section[0],"UNSEEN")){o.skipResponse=!0;return}if(!J(f[1],"FETCH")||!Array.isArray(f[2]))return;let p=f[2],y=p.findIndex((d,g)=>!(g%2)&&J(d,"UID")),A=c&&typeof c.uid=="number"&&c||o.fetchedMessage,m=A?A.uid:y>=0&&p[y+1];if(!m){o.skipResponse=!0;return}u&&!("uidonlyKeepUid"in u)&&(u.uidonlyKeepUid=qh(u));let h=p;y>=0&&p.length>2&&!(u&&u.uidonlyKeepUid)&&(h=p.slice(0,y).concat(p.slice(y+2))),o.attributes=[m,{type:"ATOM",value:"UIDFETCH"},h]};s.once("pluginsLoaded",()=>s.outputHandlers.push(n))}function qh(s){return String(s.command||"").toUpperCase()!=="UID FETCH"||!s.attributes?!1:[].concat(s.attributes[1]||[]).some(e=>J(e,"UID"))}cr.requires=["ENABLE"];E();function Di(s){s.registerCapability("UIDPLUS"),s.setCommandHandler("UID EXPUNGE",(e,t,r,n)=>{if(!t.attributes||t.attributes.length!==1||!t.attributes[0]||["ATOM","SEQUENCE"].indexOf(t.attributes[0].type)<0)return e.send({tag:t.tag,command:"BAD",attributes:[{type:"TEXT",value:"UID EXPUNGE expects uid sequence set"}]},"INVALID COMMAND",t,r),n();if(e.refuseReadOnly(t,r,"UID EXPUNGE FAILED"))return n();let i=t.attributes[0].value,a=e.limitRange(t,e.getMessageRange(i,!0)).map(u=>u[1]).filter(u=>u.flags.indexOf("\\Deleted")>=0);e.expungeSpecificMessages(e.selectedMailbox,a,!1,!0,!!t.highestFirst),e.send({tag:t.tag,command:"OK",attributes:[{type:"TEXT",value:"UID EXPUNGE completed"}]},"UID EXPUNGE",t,r),n()}),s.outputHandlers.push((e,t,r,n,i,o)=>{if(r==="APPEND"||r==="REPLACE APPENDUID"){let a=o.messages.map(u=>u.uid);t.attributes=[{type:"SECTION",section:[{type:"ATOM",value:"APPENDUID"},o.mailbox.uidvalidity,a.length>1?{type:"SEQUENCE",value:lt(a)}:a[0]]}].concat(t.attributes),t.skipResponse=!1;return}if(r==="COPY"||r==="UID COPY"||r==="MOVE COPYUID"||r==="UID MOVE COPYUID"){if(!o||!o.sourceUids||!o.sourceUids.length)return;t.attributes=[{type:"SECTION",section:[{type:"ATOM",value:"COPYUID"},o.mailbox.uidvalidity,{type:"SEQUENCE",value:o.sourceUids.join(",")},{type:"SEQUENCE",value:o.targetUids.join(",")}]}].concat(t.attributes),t.skipResponse=!1;return}})}E();function Ui(s){s.registerCapability("UNAUTHENTICATE"),s.setCommandHandler("UNAUTHENTICATE",(e,t,r,n)=>(e.sendStatus(t,r,"OK","Completed, now in not authenticated state"),e.resetSession(),n()),{states:Z.AUTHENTICATED,noArguments:!0})}E();function vi(s){s.registerCapability("UNSELECT"),s.setCommandHandler("UNSELECT",(e,t,r,n)=>(e.send({tag:t.tag,command:"OK",attributes:[{type:"TEXT",value:"Mailbox closed"}]},"CLOSE",t,r),e.closeMailbox(),n()),{states:Z.SELECTED,noArguments:!0})}E();function Qh(s){let e=s.match(/\r?\n\r?\n/);return/[\x80-\xff]/.test(e?s.substr(0,e.index):s)}function fr(s){s.registerCapability("UTF8=ACCEPT"),Ne(s,"UTF8=ACCEPT"),s.utf8Accept=!0,s.connectionHandlers.push(wt),s.resetHandlers.push(wt),s.outputHandlers.push((t,r,n,i,o,a)=>{n==="ENABLED"&&Array.isArray(a)&&a.indexOf("UTF8=ACCEPT")>=0&&wt(t)});let e=s.getCommandHandler("APPEND");s.setCommandHandler("APPEND",(t,r,n,i)=>{let o=r.attributes||[],a=o[o.length-1];return!t.utf8Enabled&&o.length>=2&&a&&["LITERAL","LITERAL8"].indexOf(a.type)>=0&&Qh(a.value||"")?(t.sendStatus(r,n,"NO","Message header has 8-bit characters, ENABLE UTF8=ACCEPT first (RFC 9755 section 4)"),i()):e(t,r,n,i)})}fr.requires=["ENABLE"];E();var Yh="1278455344230334865",Kh=2n**64n-1n,Du={"in:inbox":["X-GM-LABELS","\\Inbox"],"in:sent":["X-GM-LABELS","\\Sent"],"in:drafts":["X-GM-LABELS","\\Drafts"],"in:trash":["X-GM-LABELS","\\Trash"],"in:spam":["X-GM-LABELS","\\Junk"],"in:anywhere":["ALL"],"is:unread":["UNSEEN"],"is:read":["SEEN"],"is:starred":["FLAGGED"],"is:important":["X-GM-LABELS","\\Important"]},Uu={from:"FROM",to:"TO",cc:"CC",bcc:"BCC",subject:"SUBJECT",label:"X-GM-LABELS",larger:"LARGER",smaller:"SMALLER",after:"SINCE",before:"BEFORE",rfc822msgid:"HEADER"},zh=["is","has","list","filename","around","size","older","newer","older_than","newer_than","deliveredto","category"];function Bi(s){s.registerCapability("X-GM-EXT-1"),s["HIGHESTX-GM-MSGID"]=BigInt(s.options["HIGHESTX-GM-MSGID"]||Yh),s.messageHandlers.push((a,u,l)=>{let c;u["X-GM-MSGID"]?/^\d+$/.test(u["X-GM-MSGID"])&&BigInt(u["X-GM-MSGID"])>a["HIGHESTX-GM-MSGID"]&&(a["HIGHESTX-GM-MSGID"]=BigInt(u["X-GM-MSGID"])):(a["HIGHESTX-GM-MSGID"]+=1n,u["X-GM-MSGID"]=a["HIGHESTX-GM-MSGID"].toString()),u["X-GM-LABELS"]=[].concat(u["X-GM-LABELS"]||[]),l.path.toUpperCase()==="INBOX"?c=["\\Inbox"]:l["special-use"]&&l["special-use"].length?c=[].concat(l["special-use"]):c=[Hu(l.path)],c.forEach(f=>{a.ensureFlag(u["X-GM-LABELS"],f)})});let e=new Map;s.once("pluginsLoaded",()=>{s.messageHandlers.push((a,u)=>{let l=u.THREADID&&e.get(u.THREADID);u["X-GM-THRID"]||(u["X-GM-THRID"]=l||u["X-GM-MSGID"]),u.THREADID&&!l&&e.set(u.THREADID,u["X-GM-THRID"])})}),s.fetchHandlers["X-GM-MSGID"]=function(a,u){return{type:"ATOM",value:u["X-GM-MSGID"]}},s.fetchHandlers["X-GM-LABELS"]=function(a,u){return Pu(u)};let t=()=>[a=>{if(!/^\d{1,20}$/.test(a)||BigInt(a)>Kh)throw Q("Expected a 64 bit unsigned number");return BigInt(a).toString()}];s.searchHandlers["X-GM-MSGID"]=function(a,u,l,c){return u["X-GM-MSGID"]===c},s.searchHandlers["X-GM-MSGID"].argumentTypes=t,s.fetchHandlers["X-GM-THRID"]=function(a,u){return{type:"ATOM",value:u["X-GM-THRID"]}},s.searchHandlers["X-GM-THRID"]=function(a,u,l,c){return u["X-GM-THRID"]===c},s.searchHandlers["X-GM-THRID"].argumentTypes=t,s.searchHandlers["X-GM-LABELS"]=function(a,u,l,c){return u["X-GM-LABELS"].some(f=>Bu(f)?f.toLowerCase()===c.toLowerCase():a.exportMailboxName(ku(f))===c)};let r=new WeakMap;s.searchHandlers["X-GM-RAW"]=function(a,u,l,c){if(!r.has(c)){let f=a.searchCharset?c:["CHARSET","UTF-8"].concat(c);r.set(c,De(a,[],f,()=>[]).matches)}return r.get(c)(u,l)},s.searchHandlers["X-GM-RAW"].argumentTypes=()=>[$h];let n=(a,u)=>{a["X-GM-LABELS"]=[],i(a,u)},i=(a,u)=>{u.forEach(l=>s.ensureFlag(a["X-GM-LABELS"],l))};[["X-GM-LABELS",n],["+X-GM-LABELS",i],["-X-GM-LABELS",(a,u)=>{u.forEach(l=>s.removeFlag(a["X-GM-LABELS"],l))}]].forEach(([a,u])=>{let l=(c,f,p)=>u(f,p.map(y=>Wh(c,y)));s.storeHandlers[a]=function(c,f,p,y,A,m){l(c,f,p),Jh(c,A,m,y,f)},s.storeHandlers[a+".SILENT"]=l,s.storeHandlers[a].astringValues=s.storeHandlers[a+".SILENT"].astringValues=!0}),s.copyHandlers.push((a,u,l)=>{u["X-GM-MSGID"]&&(l["X-GM-MSGID"]=u["X-GM-MSGID"],l["X-GM-THRID"]=u["X-GM-THRID"])})}var Bu=s=>s.charAt(0)==="\\"&&s.charAt(1)!=="\\",Hu=s=>s.charAt(0)==="\\"?"\\"+s:s,ku=s=>s.charAt(0)==="\\"?s.substr(1):s;function Wh(s,e){let t=String(e&&e.value||"");return e.type==="ATOM"&&t.charAt(0)==="\\"?t:Hu(s.importMailboxName(t))}function Pu(s){return s["X-GM-LABELS"].map(e=>Bu(e)?{type:"ATOM",value:e}:{type:"MAILBOX",value:ku(e)})}function $h(s){let e=[],t=/\s*(?:([(){}])|"([^"]*)"|([^\s(){}"]+?:)"([^"]*)"|([^\s(){}"]+))/gy,r,n=0;for(;n<s.length&&(r=t.exec(s));)n=t.lastIndex,r[1]?e.push({type:r[1]}):typeof r[2]=="string"?e.push({type:"word",value:r[2]}):r[3]?e.push({type:"word",value:r[3]+r[4],operator:r[3].slice(0,-1),operand:r[4]}):e.push({type:"word",value:r[5]});if(s.slice(n).trim())throw Q("X-GM-RAW query has an unterminated quoted string");let i=0,o=()=>e[i],a=c=>{let f=[];for(;i<e.length&&(!o()||o().type!==c);)f.push(u());if(c){if(!o()||o().type!==c)throw Q('X-GM-RAW query is missing "'+c+'"');i++}if(!f.length)throw Q("X-GM-RAW query is empty");return f.length===1?f[0]:f},u=()=>{let c=l();for(;o()&&o().type==="word"&&o().value==="OR"&&e[i+1];)i++,c=["OR",c,l()];return c},l=()=>{let c=e[i++];if(!c||c.type===")"||c.type==="}")throw Q("Unexpected end of X-GM-RAW query");if(c.type==="(")return a(")");if(c.type==="{"){let p=[];for(;o()&&o().type!=="}";)p.push(l());if(!o()||!p.length)throw Q("X-GM-RAW query has an empty or unterminated { } group");return i++,p.reduce((y,A)=>["OR",y,A])}let f=c.value;return f==="-"&&o()&&(o().type==="("||o().type==="{")?["NOT",l()]:f.charAt(0)==="-"&&f.length>1?["NOT",vu(Fu(f.substr(1)))]:vu(c)};return[a()]}function Fu(s){let e=s.match(/^([a-z_0-9]+):(.+)$/i);return e?{value:s,operator:e[1],operand:e[2]}:{value:s,operator:!1,operand:!1}}function vu(s){let e=s.operator?s:Fu(s.value),t=e.operator;if(!t)return["TEXT",s.value];let r=e.operand,n=t.toLowerCase(),i=n+":"+r.toLowerCase(),o=Object.hasOwn(Du,i)&&Du[i];if(o)return o;let a=Object.hasOwn(Uu,n)&&Uu[n];if(a)switch(a){case"LARGER":case"SMALLER":{let u=r.match(/^(\d+)([km]?)$/i);if(!u)throw Q("X-GM-RAW "+n+": expects a size");return[a,String(Number(u[1])*{"":1,k:1024,m:1024*1024}[u[2].toLowerCase()])]}case"SINCE":case"BEFORE":{let u=r.match(/^(\d{4})[/-](\d{1,2})[/-](\d{1,2})$/);if(!u||!It(Number(u[3]),Number(u[2])-1,Number(u[1])))throw Q("X-GM-RAW "+n+": expects a date as YYYY/MM/DD");return[a,Number(u[3])+"-"+St[Number(u[2])-1]+"-"+u[1]]}case"HEADER":return[a,"Message-ID",r];default:return[a,r]}if(n==="in")return["X-GM-LABELS",r];if(zh.indexOf(n)>=0){let u=new Error("X-GM-RAW operator "+n+":"+r+" is not supported by imapkit");throw u.imapResponse="NO",u}return["TEXT",s.value]}function Jh(s,e,t,r,n){let i=[{type:"ATOM",value:"X-GM-LABELS"},Pu(n)];(e.command||"").toUpperCase()==="UID STORE"&&(i.push({type:"ATOM",value:"UID"}),i.push(n.uid)),s.send({tag:"*",attributes:[r,{type:"ATOM",value:"FETCH"},i]},"FLAG UPDATE",e,t,n)}E();var Zh=new TextDecoder("utf-8",{fatal:!0});function Hi(s){s.registerCapability("AUTH=XOAUTH2",e=>e.state==="Not Authenticated"),s.setCommandHandler("AUTHENTICATE XOAUTH2",(e,t,r,n)=>{if(!s.capabilities["SASL-IR"]||!s.capabilities["SASL-IR"](e))return e.send({tag:t.tag,command:"BAD",attributes:[{type:"TEXT",value:"SASL-IR must be enabled to support XOAUTH2"}]},"AUTHENTICATE XOAUTH2 FAILED",t,r),n();if(!t.attributes||t.attributes.length!==1||!t.attributes[0]||["STRING","ATOM"].indexOf(t.attributes[0].type)<0)return e.send({tag:t.tag,command:"NO",attributes:[{type:"TEXT",value:"Invalid SASL argument"}]},"AUTHENTICATE XOAUTH2 FAILED",t,r),n();let i=e.decodeSaslResponse(t.attributes[0].value);if(!i)return e.sendStatus(t,r,"BAD","Invalid base64 in SASL response",!1,"AUTHENTICATE XOAUTH2 FAILED"),n();let o=[];try{o=Zh.decode(i).split("")}catch{}let a=(o[0]||"").substr(5),u=(o[1]||"").substr(12);return o.length!==4||!o[0].match(/^user=/)||!o[1].match(/^auth=Bearer /)||!a||!u||o[2]||o[3]?(e.send({tag:t.tag,command:"NO",attributes:[{type:"TEXT",value:"Invalid SASL argument."}]},"AUTHENTICATE XOAUTH2 FAILED",t,r),n()):e.server.getUser(a)?("error"in s.checkAccessToken(u,a)?(e.send({tag:"+",attributes:[{type:"ATOM",value:b.Buffer.from(JSON.stringify({status:"400",schemes:"Bearer",scope:s.oauth?s.oauth.mailScope:"https://mail.google.com/"})).toString("base64")}]},"AUTHENTICATE XOAUTH2 FAILED",t,r),e.inputHandler=function(){e.inputHandler=!1,e.send({tag:t.tag,command:"NO",attributes:[{type:"SECTION",section:[{type:"ATOM",value:"AUTHENTICATIONFAILED"}]},{type:"TEXT",value:"SASL authentication failed"}]},"AUTHENTICATE XOAUTH2 FAILED",t,r)}):(e.state="Authenticated",e.username=a,e.send({tag:t.tag,command:"OK",attributes:[{type:"TEXT",value:"User logged in"}]},"AUTHENTICATE XOAUTH2 SUCCESS",t,r)),n()):(e.send({tag:t.tag,command:"NO",attributes:[{type:"SECTION",section:[{type:"ATOM",value:"AUTHENTICATIONFAILED"}]},{type:"TEXT",value:"Invalid credentials"}]},"AUTHENTICATE XOAUTH2 FAILED",t,r),n())})}var $t={acl:gn,appendlimit:En,"auth-plain":An,binary:In,catenate:xn,compress:Cn,condstore:kn,"context-search":qt,"context-sort":qn,"create-special-use":Qn,enable:Bn,esearch:Ie,esort:Qt,id:Yn,idle:Kn,imap4rev2:Ws,"list-extended":Kt,"list-status":$n,literalminus:Yt,literalplus:Jn,logindisabled:Zn,messagelimit:si,metadata:sr,"metadata-server":rr,move:ai,multiappend:ui,multisearch:li,namespace:ci,notify:fi,oauthbearer:hi,objectid:di,partial:pi,preview:Ei,qresync:ur,quota:bi,replace:Ti,"sasl-ir":Si,savedate:Ii,savelimit:Oi,searchres:xi,sort:ct,"sort-display":Ci,"special-use":wi,starttls:Ni,"status-size":Mi,"thread-orderedsubject":Ri,"thread-references":Li,uidonly:cr,uidplus:Di,unauthenticate:Ui,unselect:vi,"utf8-accept":fr,"x-gm-ext-1":Bi,xoauth2:Hi};var _u={"literal+":"literalplus","literal-":"literalminus","compress=deflate":"compress","auth=plain":"auth-plain","auth=xoauth2":"xoauth2","status=size":"status-size","sort=display":"sort-display","thread=orderedsubject":"thread-orderedsubject","thread=references":"thread-references","auth=oauthbearer":"oauthbearer","utf8=accept":"utf8-accept","context=search":"context-search","context=sort":"context-sort"};function ed(){return Object.keys($t)}function Gu(s){let e=String(s).trim().toLowerCase();return Object.hasOwn(_u,e)&&(e=_u[e]),Object.hasOwn($t,e)?e:!1}function td(s,e,t){let r=new Set,n=new Map;(t||new Map).forEach((o,a)=>{let u=Gu(a);u&&n.set($t[u],o)});let i=(o,a)=>{let u=o;if(typeof u=="string"){let f=Gu(u);if(!f&&u.toUpperCase()==="XTOYBIRD")throw new Error("XTOYBIRD was removed in 5.0.0, use the control API (server.control.snapshot(), server.control.addUser() ...) instead, see the README");if(!f)throw new Error('Unknown plugin "'+u+'". Available plugins: '+ed().join(", "));u=$t[f]}if(typeof u!="function")throw new TypeError("Invalid plugin, expecting a plugin name or a function");let l=n.get(u);if(l){if(a)throw new Error(a+" requires "+o+', which the "'+l+'" quirk removes');return}if(r.has(u))return;r.add(u);let c=typeof o=="string"?o.trim():u.name;[].concat(u.requires||[]).forEach(f=>i(f,c)),u(s)};[].concat(e||[]).forEach(o=>i(o)),s.emit("pluginsLoaded")}var Xu=td;E();E();function ki(s,e,t,r){let n=["IMAP4rev1"];Object.keys(s.server.capabilities).forEach(i=>{s.server.capabilities[i](s)&&n.push(i)}),s.send({tag:"*",command:"CAPABILITY",attributes:n.map(i=>({type:"TEXT",value:i}))},"CAPABILITY LIST",e,t,n),s.send({tag:e.tag,command:"OK",attributes:[{type:"TEXT",value:"Completed"}]},"CAPABILITY COMPLETED",e,t,n),r()}E();function Pi(s,e,t,r){s.send({tag:e.tag,command:"OK",attributes:[{type:"TEXT",value:"Completed"}]},"CHECK",e,t),r()}E();function Fi(s,e,t,r){return s.canExpunge()&&s.expungeDeleted(s.selectedMailbox,!0),s.notificationQueue=[],s.send({tag:e.tag,command:"OK",attributes:[{type:"TEXT",value:"Mailbox closed"}]},"CLOSE",e,t),s.closeMailbox(),r()}E();function _i(s,e,t,r){if(!e.attributes||e.attributes.length!==1||!e.attributes[0]||["STRING","LITERAL","ATOM"].indexOf(e.attributes[0].type)<0)return s.send({tag:e.tag,command:"BAD",attributes:[{type:"TEXT",value:"CREATE expects mailbox name"}]},"INVALID COMMAND",e,t),r();let n=e.attributes[0].value,i;try{i=xs(s.server,n)}catch(o){let a=o;return s.sendStatus(e,t,"NO",a.message,a.code,"CREATE FAILED"),r()}return s.send({tag:e.tag,command:"OK",attributes:[{type:"TEXT",value:"CREATE completed"}]},"CREATE",e,t,i),r()}E();function Gi(s,e,t,r){if(!e.attributes||e.attributes.length!==1||!e.attributes[0]||["STRING","LITERAL","ATOM"].indexOf(e.attributes[0].type)<0)return s.send({tag:e.tag,command:"BAD",attributes:[{type:"TEXT",value:"DELETE expects mailbox name"}]},"INVALID COMMAND",e,t),r();let n=e.attributes[0].value;try{Cs(s.server,n)}catch(i){let o=i;return s.sendStatus(e,t,"NO",o.message,o.code,"DELETE FAILED"),r()}return s.send({tag:e.tag,command:"OK",attributes:[{type:"TEXT",value:"DELETE completed"}]},"DELETE",e,t),r()}E();function Xi(s,e,t,r){return an(s,e,t,r,!0)}E();function ji(s,e,t,r){if(s.refuseReadOnly(e,t,"EXPUNGE FAILED"))return r();s.expungeDeleted(s.selectedMailbox,!1,!0),s.send({tag:e.tag,command:"OK",attributes:[{type:"TEXT",value:"EXPUNGE Completed"}]},"EXPUNGE",e,t),r()}E();function Vi(s,e,t,r){let n;if(!e.attributes||e.attributes.length!==2||!e.attributes[0]||["STRING","LITERAL","ATOM"].indexOf(e.attributes[0].type)<0||!e.attributes[1]||["STRING","LITERAL","ATOM"].indexOf(e.attributes[1].type)<0)return s.send({tag:e.tag,command:"BAD",attributes:[{type:"TEXT",value:"LIST expects 2 string arguments"}]},"INVALID COMMAND",e,t),r();if(e.attributes[1].value)n=s.server.matchFolders(e.attributes[0].value,e.attributes[1].value,i=>s.exportMailboxName(i)),n.forEach(i=>{s.send({tag:"*",command:"LIST",attributes:[i.flags.map(o=>({type:"ATOM",value:o})),s.server.getSeparator(i),s.exportMailboxName(i.path)]},"LIST ITEM",e,t,i)});else{let i=s.server,o=e.attributes[0].value||"",a=i.referenceNamespace;try{a=i.getNamespace(s.importMailboxName(o))||a}catch{}let u=a!==!1?i.storage[a]:void 0,l=a!==!1&&a!==i.referenceNamespace?s.exportMailboxName(a):"";u&&s.send({tag:"*",command:"LIST",attributes:[[{type:"ATOM",value:"\\Noselect"}],u.separator,l]},"LIST ITEM",e,t)}return s.send({tag:e.tag,command:"OK",attributes:[{type:"TEXT",value:"Completed"}]},"LIST",e,t),r()}E();function qi(s,e,t,r){if(!e.attributes||e.attributes.length!==2||!e.attributes[0]||!e.attributes[1]||["STRING","LITERAL","ATOM"].indexOf(e.attributes[0].type)<0||["STRING","LITERAL","ATOM"].indexOf(e.attributes[1].type)<0)return s.send({tag:e.tag,command:"BAD",attributes:[{type:"TEXT",value:"LOGIN takes 2 string arguments"}]},"INVALID COMMAND",e,t),r();if(e.attributes.some(i=>/[\x80-\xff]/.test(i.value)))return s.sendStatus(e,t,"BAD","LOGIN does not take UTF-8 user names or passwords, use AUTHENTICATE (RFC 9755 section 5)"),r();let n=s.server.getUser(e.attributes[0].value);if(!n||n.password!==e.attributes[1].value)return s.sendStatus(e,t,"NO","Login failed: authentication failure","AUTHENTICATIONFAILED","LOGIN FAILED"),r();s.state="Authenticated",s.username=e.attributes[0].value,s.send({tag:e.tag,command:"OK",attributes:[{type:"TEXT",value:"User logged in"}]},"LOGIN SUCCESS",e,t),r()}E();function Qi(s,e,t,r){s.state="Logout",s.send({tag:"*",command:"BYE",attributes:[{type:"TEXT",value:"LOGOUT received"}]},"LOGOUT UNTAGGED",e,t),s.send({tag:e.tag,command:"OK",attributes:[{type:"TEXT",value:"Completed"}]},"LOGOUT COMPLETED",e,t),s.end(),r()}E();function Yi(s,e,t,r){if(!e.attributes||e.attributes.length!==2||!e.attributes[0]||["STRING","LITERAL","ATOM"].indexOf(e.attributes[0].type)<0||!e.attributes[1]||["STRING","LITERAL","ATOM"].indexOf(e.attributes[1].type)<0)return s.send({tag:e.tag,command:"BAD",attributes:[{type:"TEXT",value:"LSUB expects 2 string arguments"}]},"INVALID COMMAND",e,t),r();let n=s.server,i=e.attributes[1].value;return n.matchFolders(e.attributes[0].value,i,a=>s.exportMailboxName(a),n.getSubscriptionTree()).forEach(a=>{let u;if(a.subscribed)u=a.flags.filter(l=>l!=="\\Noselect");else if(i.substr(-1)==="%")u=["\\Noselect"];else return;s.send({tag:"*",command:"LSUB",attributes:[u.map(l=>({type:"ATOM",value:l})),n.getSeparator(a),s.exportMailboxName(a.path)]},"LSUB ITEM",e,t,a)}),s.send({tag:e.tag,command:"OK",attributes:[{type:"TEXT",value:"Completed"}]},"LSUB",e,t),r()}E();function Ki(s,e,t,r){s.send({tag:e.tag,command:"OK",attributes:[{type:"TEXT",value:"Completed"}]},"NOOP completed",e,t),r()}E();function zi(s,e,t,r){if(!e.attributes||e.attributes.length!==2||!e.attributes[0]||["STRING","LITERAL","ATOM"].indexOf(e.attributes[0].type)<0||!e.attributes[1]||["STRING","LITERAL","ATOM"].indexOf(e.attributes[1].type)<0)return s.send({tag:e.tag,command:"BAD",attributes:[{type:"TEXT",value:"RENAME expects mailbox source and destination names"}]},"INVALID COMMAND",e,t),r();let n=e.attributes[0].value,i=e.attributes[1].value,o;try{o=ws(s.server,n,i)}catch(a){let u=a;return s.sendStatus(e,t,"NO",u.message,u.code,"RENAME FAILED"),r()}return s.send({tag:e.tag,command:"OK",attributes:[{type:"TEXT",value:"RENAME completed"}]},"RENAME",e,t,o.mailbox),r()}E();function Wi(s,e,t,r,n){let i=s?"UID SEARCH":"SEARCH";if(!t.attributes||!t.attributes.length)return e.send({tag:t.tag,command:"BAD",attributes:[{type:"TEXT",value:i+" expects search criteria, empty query given"}]},i+" FAILED",t,r),n();let o;try{o=De(e,e.getSessionMessages(),Ot(t.attributes))}catch(a){return xt(e,t,r,a,i+" FAILED"),n()}return e.send({tag:"*",command:"SEARCH",attributes:o.list.map(a=>s?a.uid:o.numbers[a.uid])},i,t,r,o),e.send({tag:t.tag,command:"OK",attributes:[{type:"TEXT",value:i+" completed"}]},i,t,r),n()}var sd=(s,e,t,r)=>Wi(!1,s,e,t,r),ju=sd;E();function $i(s,e,t,r){if(!e.attributes||e.attributes.length!==2||!e.attributes[0]||["STRING","LITERAL","ATOM"].indexOf(e.attributes[0].type)<0||!Array.isArray(e.attributes[1])||!e.attributes[1].length)return s.send({tag:e.tag,command:"BAD",attributes:[{type:"TEXT",value:"STATUS expects mailbox argument and a list of status items"}]},"INVALID COMMAND",e,t),r();let n=e.attributes[0].value,i;try{i=Js(s.server,e.attributes[1],s)}catch(u){return s.sendStatus(e,t,"BAD",u.message,!1,"STATUS FAILED"),r()}let o=s.server.getMailbox(n);if(!o||o.flags.indexOf("\\Noselect")>=0)return s.sendStatus(e,t,"NO","Mailbox does not exist","NONEXISTENT","STATUS FAILED"),r();Zs(s,n,o,i,e,t);let a=s.state==="Selected"&&s.selectedMailbox===o;return s.sendStatus(e,t,"OK",a?"Status completed, STATUS SHOULD NOT be used on the selected mailbox":"Status completed",a&&"CLIENTBUG"),r()}E();function Vu(s,e){return e=String(e).toUpperCase(),s.server.storeHandlers[e]||Ts[e]}function Ji(s,e,t,r,n){let i=s?"UID STORE":"STORE",o=t.attributes&&t.attributes[1],a=J(o)&&Vu(e,o.value),u=!!(a&&a.astringValues),l=u?["ATOM","STRING","LITERAL"]:["ATOM","STRING"];if(u&&yt(t,r,h=>h[0]===2),!t.attributes||t.attributes.length!==3||!t.attributes[0]||["ATOM","SEQUENCE"].indexOf(t.attributes[0].type)<0||!t.attributes[1]||["ATOM"].indexOf(t.attributes[1].type)<0||!t.attributes[2]||!(l.indexOf(t.attributes[2].type)>=0||Array.isArray(t.attributes[2])))return e.send({tag:t.tag,command:"BAD",attributes:[{type:"TEXT",value:i+" expects sequence set, item name and item value"}]},"INVALID COMMAND",t,r),n();if(e.refuseReadOnly(t,r,i+" FAILED"))return n();let c=e.limitRange(t,e.getCommandRange(t.attributes[0].value,s)),f=(t.attributes[1].value||"").toUpperCase(),p=[].concat(t.attributes[2]||[]),y=[],A=!1;try{p.forEach((d,g)=>{if(!d||l.indexOf(d.type)<0)throw new Error("Invalid item value #"+(g+1))});let h=a||Vu(e,f);if(!h)throw new Error("Invalid STORE argument "+f);c.forEach(d=>{if(d[1].ghost){A=!0;return}for(let g=0,T=e.server.storeFilters.length;g<T;g++)if(!e.server.storeFilters[g](e,d[1],t,d[0]))return;h(e,d[1],p,d[0],t,r),y.push(d[1])})}catch(h){let d=h;return e.send({tag:t.tag,command:"BAD",attributes:[{type:"TEXT",value:d.message}]},i+" FAILED",t,r),n()}let m=A&&!/\.SILENT$/.test(f);e.send({tag:t.tag,command:m?"NO":"OK",attributes:[].concat(m?{type:"SECTION",section:[{type:"ATOM",value:"EXPUNGEISSUED"}]}:[],{type:"TEXT",value:m?"Some of the messages no longer exist":i+" completed"})},i+(m?" FAILED":" COMPLETE"),t,r,y),e.notifyFlagChanges(y),n()}var rd=(s,e,t,r)=>Ji(!1,s,e,t,r),qu=rd;E();function Zi(s,e,t,r){if(!e.attributes||e.attributes.length!==1||!e.attributes[0]||["STRING","LITERAL","ATOM"].indexOf(e.attributes[0].type)<0)return s.send({tag:e.tag,command:"BAD",attributes:[{type:"TEXT",value:"SUBSCRIBE expects mailbox name"}]},"INVALID COMMAND",e,t),r();try{Ht(s.server,e.attributes[0].value)}catch(n){let i=n;return s.sendStatus(e,t,"NO",i.message,i.code,"SUBSCRIBE FAILED"),r()}return s.send({tag:e.tag,command:"OK",attributes:[{type:"TEXT",value:"SUBSCRIBE completed"}]},"SUBSCRIBE",e,t),r()}E();function eo(s,e,t,r){return ii(s,e,t,r,!0)}E();var nd=(s,e,t,r)=>wn(!0,s,e,t,r),Qu=nd;E();var id=(s,e,t,r)=>Wi(!0,s,e,t,r),Yu=id;E();var od=(s,e,t,r)=>Ji(!0,s,e,t,r),Ku=od;E();function to(s,e,t,r){return!e.attributes||e.attributes.length!==1||!e.attributes[0]||["STRING","LITERAL","ATOM"].indexOf(e.attributes[0].type)<0?(s.send({tag:e.tag,command:"BAD",attributes:[{type:"TEXT",value:"UNSUBSCRIBE expects mailbox name"}]},"INVALID COMMAND",e,t),r()):(Ns(s.server,e.attributes[0].value),s.send({tag:e.tag,command:"OK",attributes:[{type:"TEXT",value:"UNSUBSCRIBE completed"}]},"UNSUBSCRIBE",e,t),r())}var zu={APPEND:cn,CAPABILITY:ki,CHECK:Pi,CLOSE:Fi,COPY:ni,CREATE:_i,DELETE:Gi,EXAMINE:Xi,EXPUNGE:ji,FETCH:za,LIST:Vi,LOGIN:qi,LOGOUT:Qi,LSUB:Yi,NOOP:Ki,RENAME:zi,SEARCH:ju,SELECT:nn,STATUS:$i,STORE:qu,SUBSCRIBE:Zi,"UID COPY":eo,"UID FETCH":Qu,"UID SEARCH":Yu,"UID STORE":Ku,UNSUBSCRIBE:to};E();E();var Ju=/^[\x20\x21\x23-\x5b\x5d-\x7e]*$/,so=s=>s.replace(/[^\x20\x21\x23-\x5b\x5d-\x7e]/g," "),ro=s=>typeof s=="string"&&s!==""&&Ju.test(s),Wu=["prompt","approve","deny"],$u=["wrong-state","wrong-iss","no-redirect"];function $e(s,e,t=!1){if(typeof s=="string"&&(Wu.includes(s)||t&&$u.includes(s)))return s;if(s&&typeof s=="object"&&!Array.isArray(s)){let{error:n,description:i}=s;if(ro(n)){if(i!==void 0&&(typeof i!="string"||!Ju.test(i)))throw new z(e+': description must be printable ASCII without " and \\ (RFC 6749 section 4.1.2.1)',"INVALID");return i===void 0?{error:n}:{error:n,description:i}}}let r=Wu.concat(t?$u:[]).map(n=>'"'+n+'"');throw new z(e+" must be "+r.join(", ")+' or { error, description }, e.g. { error: "access_denied" }',"INVALID")}function Jt(s){return typeof s=="string"?s:"error "+s.error}function ad(s){if(!(s===void 0||typeof s=="function"))return s===null||typeof s!="object"?s:JSON.parse(JSON.stringify(s))}function no(s,e){let t={};return Object.keys(s).forEach(r=>{let n=e.has(r)?void 0:ad(s[r]);n!==void 0&&(t[r]=n)}),t}var ud=new Set(["ghost"]),ld=new Set(["folders"]),cd=new Set(["path","namespace","messages","folders","subscribed","flags"]),fd=new Set(["\\HasChildren","\\HasNoChildren"]);function io(s,e){if(!s||typeof s!="object"||Array.isArray(s))throw new z(e+" must be { consent }","INVALID");let{consent:t}=s;return t===void 0?{}:{consent:$e(t,e+".consent")}}var hr=class{constructor(e){this.server=e,this.routes=[],this.snapshotHandlers=[],this.mailboxInfoHandlers=[],this.messageInfoHandlers=[]}register(e,t,r){if(e in this)throw new Error("Control operation "+e+" exists already");this[e]=(...n)=>this.run(()=>t(...n)),this.routes.push(...r||[])}run(e){return this.server.withOrigin(null,e)}requireMailbox(e,t){let r=typeof e=="string"&&e?this.server.getMailbox(e):void 0;if(!r||t&&r.flags.indexOf("\\Noselect")>=0)throw new z("Mailbox "+JSON.stringify(e)+" does not exist","NONEXISTENT");return r}checkName(e){this.checkPath(e);let t=Tt(e);if(t)throw new z(t,"INVALID")}checkPath(e){if(typeof e!="string"||!e)throw new z("Mailbox name must be a non-empty string","INVALID")}requireMessages(e,t){if(!Array.isArray(t)||t.some(i=>!Number.isSafeInteger(i)||i<1))throw new z("UIDs must be an array of positive integers","INVALID");let r=new Map(e.messages.map(i=>[i.uid,i])),n=t.filter(i=>!r.has(i));if(n.length)throw new z("No message with UID "+n.join(", ")+" in "+e.path,"NONEXISTENT");return[...new Set(t)].map(i=>r.get(i))}findSessions(e){let t=typeof e=="number"?{session:e}:e||{};if(t.session===void 0&&t.user===void 0)throw new z("Select sessions by number or user","INVALID");return[...this.server.connections].filter(r=>r.isOpen()&&(t.session===void 0||r.sessionNumber===t.session)&&(t.user===void 0||r.username===t.user))}snapshot(){let e=this.server,t=i=>{let o=no(i,cd);return this.snapshotHandlers.forEach(a=>a(i,o)),o.flags=i.flags.filter(a=>!fd.has(a)),o.subscribed=!!i.subscribed,o.messages=i.messages.map(a=>no(a,ud)),i.folders&&(o.folders=r(i.folders)),o},r=i=>{let o={};return Object.keys(i).forEach(a=>{o[a]=t(i[a])}),o},n={};return Object.keys(e.storage).forEach(i=>{if(i==="INBOX"){n.INBOX=t(e.storage.INBOX);return}let o=e.storage[i];n[i]=Object.assign(no(o,ld),{folders:r(o.folders||{})})}),n}listMailboxes(){return Object.keys(this.server.folderCache).sort().map(e=>this.describeMailbox(this.server.folderCache[e]))}getMailbox(e){return this.describeMailbox(this.requireMailbox(e))}describeMailbox(e){let t=this.server.getStatus(e),r={path:e.path,delimiter:this.server.getSeparator(e),flags:e.flags.slice(),selectable:e.flags.indexOf("\\Noselect")<0,subscribed:!!e.subscribed,messages:e.messages.length,unseen:t?t.unseen:0,uidnext:e.uidnext,uidvalidity:e.uidvalidity,permanentFlags:t?t.permanentFlags.slice():[]};return this.server.condstore&&typeof e.HIGHESTMODSEQ=="number"&&(r.highestModseq=e.HIGHESTMODSEQ),this.mailboxInfoHandlers.forEach(n=>n(e,r)),r}listMessages(e,t={}){let r=this.requireMailbox(e,!0);return(t.uids?this.requireMessages(r,t.uids).sort((i,o)=>i.uid-o.uid):r.messages).map(i=>this.describeMessage(i,!!t.raw))}getMessage(e,t,r={}){let n=this.requireMailbox(e,!0);return this.describeMessage(this.requireMessages(n,[t])[0],r.raw!==!1)}describeMessage(e,t){let r={uid:e.uid,flags:e.flags.slice(),internaldate:e.internaldate,size:e.raw.length};return this.server.condstore&&typeof e.MODSEQ=="number"&&(r.modseq=e.MODSEQ),t&&(r.raw=b.Buffer.from(e.raw,"binary")),this.messageInfoHandlers.forEach(n=>n(e,r)),r}sessions(){return[...this.server.connections].map(e=>e.describe()).sort((e,t)=>e.session-t.session)}addMessage(e,t,r={}){let n=this.requireMailbox(e,!0),{raw:i,flags:o,internaldate:a}=t||{},u;if(typeof i=="string")u=b.Buffer.from(i,"utf-8").toString("binary");else if(i instanceof Uint8Array)u=b.Buffer.from(i).toString("binary");else throw new z("Message source (raw) must be a string or a Buffer","INVALID");if(!u.length)throw new z("Message source (raw) can not be empty","INVALID");let l=hn(this.server,n,o||[],!0);if(a!==void 0&&!(a instanceof Date&&!isNaN(a.getTime()))&&!this.server.validateInternalDate(a))throw new z('Internal date must be a Date or a date-time string like "17-Jul-1996 02:44:25 -0700"',"INVALID");if(r.checks){let f=this.server.appendChecks.map(p=>p(null,n,[{raw:u,flags:l,internaldate:a}],{command:"APPEND"})).find(p=>p&&!p.soft);if(f){let p=Array.isArray(f.code)?f.code[0]:f.code;throw new z(f.text,typeof p=="string"?p:"CANNOT")}}return{uid:this.run(()=>this.server.appendMessage(n,l,a||null,u)).message.uid,uidvalidity:n.uidvalidity}}setFlags(e,t,r,n="set"){let i=this.requireMailbox(e,!0),o=this.requireMessages(i,t);return this.run(()=>Ma(this.server,i,o,r,n)),o.map(a=>({uid:a.uid,flags:a.flags.slice()}))}expungeMessages(e,t){let r=this.requireMailbox(e,!0),n=this.requireMessages(r,t);return this.run(()=>it(this.server,r,n)).map(i=>i.uid)}copyMessages(e,t,r){return this.transfer(e,t,r,!1)}moveMessages(e,t,r){return this.transfer(e,t,r,!0)}transfer(e,t,r,n){let i=this.requireMailbox(e,!0),o=this.requireMailbox(r,!0),a=this.requireMessages(i,t).sort((u,l)=>u.uid-l.uid);return this.run(()=>{let u=a.map(l=>({uid:l.uid,targetUid:this.server.copyMessage(o,l).message.uid}));return n&&it(this.server,i,a),{uidvalidity:o.uidvalidity,uids:u}})}replaceMessage(e,t,r){let n=this.requireMailbox(e,!0),i=this.requireMessages(n,[t])[0],o=this.addMessage(e,{raw:r&&r.raw,flags:r&&r.flags?r.flags:i.flags.slice(),internaldate:r&&r.internaldate?r.internaldate:i.internaldate});return this.run(()=>it(this.server,n,[i])),o}createMailbox(e,t={}){this.checkName(e);let r=this.run(()=>{let n=xs(this.server,e);return t.subscribed&&Ht(this.server,n.path),n});return this.describeMailbox(r)}deleteMailbox(e){this.checkPath(e),this.run(()=>Cs(this.server,e))}renameMailbox(e,t){this.checkPath(e),this.checkName(t);let r=this.run(()=>ws(this.server,e,t));return this.getMailbox(r.path)}resetUidValidity(e,t={}){let r=this.requireMailbox(e,!0);return this.run(()=>La(this.server,r,t||{}))}subscribe(e){return this.checkPath(e),this.run(()=>Ht(this.server,e))}unsubscribe(e){return this.checkPath(e),this.run(()=>Ns(this.server,e))}listUsers(){return Object.keys(this.server.users).sort().map(e=>({name:e,xoauth2:!!(this.server.users[e].xoauth2&&this.server.users[e].xoauth2.accessToken)}))}addUser(e,t){if(typeof e!="string"||!e)throw new z("User name must be a non-empty string","INVALID");if(Object.hasOwn(this.server.users,e))throw new z("User "+JSON.stringify(e)+" already exists","ALREADYEXISTS");this.server.users[e]=this.userData({},t)}updateUser(e,t){this.server.users[e]=this.userData(this.requireUser(e),t)}deleteUser(e,t={}){this.requireUser(e),delete this.server.users[e],t.disconnect!==!1&&this.findSessions({user:e}).forEach(r=>r.bye("User was deleted","USER DELETED"))}requireUser(e){if(typeof e!="string"||!Object.hasOwn(this.server.users,e))throw new z("User "+JSON.stringify(e)+" does not exist","NONEXISTENT");return this.server.users[e]}userData(e,t){let{password:r,xoauth2:n,displayName:i,oauth:o}=t||{},a=Object.assign({},e);if(i===null)delete a.displayName;else if(i!==void 0){if(typeof i!="string")throw new z("displayName must be a string","INVALID");a.displayName=i}if(o===null?delete a.oauth:o!==void 0&&(a.oauth=io(o,"oauth")),r!==void 0){if(typeof r!="string")throw new z("Password must be a string","INVALID");a.password=r}if(n===null)delete a.xoauth2;else if(n!==void 0){if(typeof n!="object"||typeof n.accessToken!="string")throw new z("xoauth2 must be { accessToken, sessionTimeout }","INVALID");a.xoauth2={accessToken:n.accessToken,sessionTimeout:Number(n.sessionTimeout)||Os}}return a}disconnect(e,t={}){let r=this.findSessions(e);return r.forEach(n=>{t.reset?n.closeNow("reset"):n.bye(t.text||"Disconnected by the server","DISCONNECT")}),r.length}inject(e,t){let r=this.findSessions({session:e})[0];if(!r)throw new z("Session "+e+" does not exist","NONEXISTENT");if(typeof t!="string"&&!(t instanceof Uint8Array))throw new z("Data must be a string or a Buffer","INVALID");r.write(b.Buffer.from(t))}reset(){this.server.connections.forEach(e=>{e.isOpen()&&e.bye("Server reset","RESET")}),this.run(()=>{this.server.loadUsers(),this.server.loadStorage(),this.server.emit("reset")})}shutdown(e={}){return new Promise((t,r)=>{let n=i=>i&&i.code!=="ERR_SERVER_NOT_RUNNING"?r(i):t();e.graceful===!1?this.server.close(n):(this.server.closeListeners(!1),this.server.closeImapListeners(n))})}};E();var oo=["FETCH","UID FETCH"];function hd(s){return String(s[0]&&s[0].value||"").toUpperCase().replace(/(^|\.)(MIME|HEADER(\.FIELDS(\.NOT)?)?|TEXT)$/,"")}function Zu(s,e){let t=s.attributes&&s.attributes[2];if(!Array.isArray(t)||!s.attributes[1]||s.attributes[1].value!=="FETCH")return;let r=t.slice();for(let n=0;n<r.length-1;n+=2){let i=r[n];i&&i.type==="ATOM"&&String(i.value).toUpperCase()==="BODY"&&Array.isArray(i.section)&&(r[n+1]=e(i,r[n+1]))}return Object.assign({},s,{attributes:[s.attributes[0],s.attributes[1],r]})}var Zt={"james-fetchgroup":{description:"Apache James FetchGroup: only the first section asked for a part in one FETCH is answered, later ones for the same part come back empty. BODY[2.MIME] BODY[2] gives a zero-length body, the reverse order loses the headers",rules:[{on:"response",command:oo,untagged:!0,mutate:s=>{let e=new Set;return Zu(s,(t,r)=>{let n=hd(t.section);return e.has(n)?{type:"LITERAL",value:""}:(e.add(n),r)})}}]},"james-late-fetch":{description:"Apache James: now and then (1 in 4) a FETCH response comes after the tagged OK of its command",rules:[{on:"response",command:oo,untagged:!0,chance:.25,defer:"tagged"}]},"yahoo-quoted-sections":{description:"Yahoo: short body sections (up to 100 octets without line breaks) are quoted strings instead of literals",rules:[{on:"response",command:oo,untagged:!0,mutate:s=>Zu(s,(e,t)=>t&&t.type==="LITERAL"&&typeof t.value=="string"&&t.value.length<=100&&/^[\x20-\x7e]*$/.test(t.value)?{type:"STRING",value:t.value}:t)}]},"m365-throttle":{description:'Microsoft 365: 1 in 10 commands (not LOGOUT) is refused with "BAD Request is throttled. Suggested Backoff Time: 1000 milliseconds"',rules:[{on:"command",chance:.1,when:s=>s.command!=="LOGOUT",send:`$TAG BAD Request is throttled. Suggested Backoff Time: 1000 milliseconds\r
32
+ `}]},"no-uidplus":{description:"A server without UIDPLUS: no APPENDUID, COPYUID or UID EXPUNGE, even when the plugins list it",removePlugins:["UIDPLUS"]},"no-move":{description:"A server without MOVE, clients have to COPY, STORE \\Deleted and EXPUNGE",removePlugins:["MOVE"]}};function el(s){let e=[],t=new Map;return[].concat(s||[]).forEach(r=>{let n=String(r).toLowerCase(),i=Object.hasOwn(Zt,n)?Zt[n]:null;if(!i)throw new Error('Unknown quirk "'+r+'". Available quirks: '+Object.keys(Zt).join(", "));e.push(...i.rules||[]),(i.removePlugins||[]).forEach(o=>t.set(o,n))}),{rules:e,removePlugins:t}}E();var dd=["acl","metadata","special-use","MAILBOXID","HIGHESTMODSEQ","qresyncExpunged","appendLimit","SAVEDATE","MODSEQ","EMAILID","THREADID","X-GM-LABELS","X-GM-MSGID","X-GM-THRID"],dr={type:"array",items:{type:"string"}},ao={type:"integer",minimum:1,maximum:4294967295},lo={$schema:"https://json-schema.org/draft/2020-12/schema",title:"ImapKit storage",description:'Namespaces by prefix ("INBOX", "", "INBOX.", "#shared/" ...), INBOX is a mailbox of its own',type:"object",properties:{INBOX:{$ref:"#/$defs/mailbox"}},additionalProperties:{$ref:"#/$defs/namespace"},$defs:{message:{oneOf:[{type:"string",description:"the message source"},{type:"object",properties:{raw:{type:"string",description:"the message source (a Buffer also works in JavaScript)"},uid:ao,flags:{oneOf:[{type:"string"},dr]},internaldate:{type:"string",description:'RFC 3501 date-time, e.g. "14-Sep-2013 21:22:28 -0300" (a Date also works in JavaScript)'},recent:{type:"boolean"}}}]},mailbox:{type:"object",properties:{uid:{type:"integer"},uidvalidity:ao,uidnext:ao,flags:dr,permanentFlags:dr,allowPermanentFlags:{type:"boolean"},subscribed:{type:"boolean"},knownFlags:dr,messages:{type:"array",items:{$ref:"#/$defs/message"}},folders:{type:"object",additionalProperties:{$ref:"#/$defs/mailbox"}}}},namespace:{type:"object",properties:{separator:{type:"string",minLength:1,maxLength:1},type:{enum:["personal","user","shared"]},folders:{type:"object",additionalProperties:{$ref:"#/$defs/mailbox"}}}}}},uo=Object.keys(lo.$defs.mailbox.properties),pd=["separator","type"],md=Object.keys(lo.$defs.message.oneOf[1].properties);function gd(s,e){return e.includes(s)||dd.includes(s)?null:e.find(t=>t.toLowerCase()===s.toLowerCase()||s.length>3&&Ed(t,s)===1)||null}function Ed(s,e){let t=Array.from({length:e.length+1},(r,n)=>n);for(let r=1;r<=s.length;r++){let n=t[0];t[0]=r;for(let i=1;i<=e.length;i++){let o=t[i];t[i]=Math.min(t[i]+1,t[i-1]+1,n+(s[r-1]===e[i-1]?0:1)),n=o}}return t[e.length]}var pr=s=>!!s&&typeof s=="object"&&!Array.isArray(s),tl=s=>Array.isArray(s)&&s.every(e=>typeof e=="string"),sl=s=>Number.isSafeInteger(s)&&s>=1&&s<=4294967295;function co(s){let e=(i,o)=>{throw new Error("Invalid storage at "+i+": "+o)},t=(i,o,a)=>{Object.keys(i).forEach(u=>{let l=gd(u,a);l&&e(o,"unknown key "+JSON.stringify(u)+", did you mean "+JSON.stringify(l)+"?")})},r=(i,o)=>{if(!(typeof i=="string"||i instanceof Uint8Array)){if(!pr(i))return e(o,"a message is a string or an object");t(i,o,md),i.raw!==void 0&&typeof i.raw!="string"&&!(i.raw instanceof Uint8Array)&&e(o+".raw","must be a string"),i.uid!==void 0&&!sl(i.uid)&&e(o+".uid","must be an integer from 1 to "+4294967295),i.flags!==void 0&&typeof i.flags!="string"&&!tl(i.flags)&&e(o+".flags","must be a flag or a list of flags");for(let a of["internaldate","SAVEDATE"]){let u=i[a];u===void 0||u===!1||a==="SAVEDATE"&&u===null||(u instanceof Date?isNaN(u.getTime()):!ks(u))&&e(o+"."+a,'must be a date-time string like "14-Sep-2013 21:22:28 -0300" or a Date, not '+JSON.stringify(u))}i.recent!==void 0&&typeof i.recent!="boolean"&&e(o+".recent","must be true or false")}},n=(i,o,a)=>{if(!pr(i))return e(o,"a mailbox is an object");t(i,o,a);for(let u of["uidvalidity","uidnext"])i[u]!==void 0&&!sl(i[u])&&e(o+"."+u,"must be an integer from 1 to "+4294967295);for(let u of["flags","permanentFlags","knownFlags"])i[u]!==void 0&&!tl(i[u])&&e(o+"."+u,"must be a list of strings");for(let u of["allowPermanentFlags","subscribed"])i[u]!==void 0&&typeof i[u]!="boolean"&&e(o+"."+u,"must be true or false");i.messages!==void 0&&(Array.isArray(i.messages)||e(o+".messages","must be a list of messages"),i.messages.forEach((u,l)=>r(u,o+".messages["+l+"]"))),i.folders!==void 0&&(pr(i.folders)||e(o+".folders","must be an object of mailboxes by name"),Object.keys(i.folders).forEach(u=>n(i.folders[u],o+".folders["+JSON.stringify(u)+"]",uo)))};pr(s)||e("the top level","storage is an object of namespaces"),Object.keys(s).forEach(i=>{let o=s[i],a=JSON.stringify(i);if(i==="INBOX")return n(o,a,uo.concat("separator"));n(o,a,uo.concat(pd));let u=o;u.separator!==void 0&&(typeof u.separator!="string"||u.separator.length!==1)&&e(a+".separator","must be a single character"),u.type!==void 0&&!["personal","user","shared"].includes(u.type)&&e(a+".type",'must be "personal", "user" or "shared"')})}E();E();var fo=s=>()=>{throw new Error(s+" is not available in the browser")},Ad=fo("The REST API and the OAuth provider"),yd=fo("The REST API"),bd=fo("The REST API"),ce={createServer:Ad,createHash:yd,timingSafeEqual:bd};var Td=64*1024*1024,Sd={NONEXISTENT:404,NOTFOUND:404,ALREADYEXISTS:409,INVALID:400,UNAUTHORIZED:401,METHOD:405,TOOBIG:413,UNSUPPORTED:415};function ke(s){let e=s.replace(/^\[|\]$/g,"").toLowerCase();return e==="localhost"||e==="::1"||/^(::ffff:)?127\.\d+\.\d+\.\d+$/.test(e)}var es=s=>/^\d+$/.test(s)?Number(s):NaN;function rl(s){let{raw:e,...t}=s;return e?Object.assign(t,{raw:e.toString("base64"),encoding:"base64"}):t}function Id(s,e){if(e!==void 0&&e!=="base64"&&e!=="utf-8")throw K('encoding must be "utf-8" or "base64"',"INVALID");return e==="base64"&&typeof s=="string"?b.Buffer.from(s,"base64"):s}var ho=["session","command","mailbox","append","expunge","flags","acl","script","reset","oauth"],nl=["trace"],po=s=>s?s.sessionNumber:null;function Od(s,e){switch(s){case"mailbox":{let{type:t,path:r,oldPath:n,origin:i}=e[0];return{type:t,path:r,oldPath:n,origin:po(i)}}case"append":case"expunge":return{path:e[0].path,uids:e[1].map(t=>t.uid),origin:po(e[2])};case"trace":{let{session:t,direction:r,data:n}=e[0];return{session:t,direction:r,data:b.Buffer.from(n).toString("base64"),encoding:"base64"}}case"flags":return{path:e[0].path,messages:e[1].map(t=>({uid:t.uid,flags:t.flags.slice()})),origin:po(e[2])};case"acl":return{path:e[0].path};default:return e[0]||{}}}function xd(s,e,t){return(r,n)=>{t.add(r),r.writeHead(200,{"Content-Type":"text/event-stream; charset=utf-8","Cache-Control":"no-store"}),r.write(`: connected
33
33
 
34
34
  `);let i=e.map(a=>{let u=(...l)=>r.write("event: "+a+`
35
35
  data: `+JSON.stringify(Od(a,l))+`
36
36
 
37
37
  `);return s.on(a,u),{type:a,listener:u}}),o=setInterval(()=>r.write(`: ping
38
38
 
39
- `),15e3);o.unref(),n.on("close",()=>{t.delete(r),clearInterval(o),i.forEach(({type:a,listener:u})=>s.removeListener(a,u))})}}function Cd(s,e=new Set){let t=s.control,r=i=>({id:i.id,rule:i.rule,matched:i.matched,hits:i.hits}),n=[{method:"GET",path:"/v1/snapshot",summary:"The storage in the shape of the storage option",handler:()=>t.snapshot()},{method:"POST",path:"/v1/reset",summary:"Restores the mailboxes and users of the server options, disconnects every session",handler:()=>(t.reset(),{reset:!0})},{method:"POST",path:"/v1/shutdown",summary:"Stops accepting connections, the server closes once the last client is gone ({ graceful: false } closes them)",handler:({body:i})=>(R(()=>t.shutdown({graceful:i.graceful!==!1}).catch(()=>!1)),{status:202,body:{shutdown:!0}})},{method:"GET",path:"/v1/sessions",summary:"Connected sessions",handler:()=>t.sessions()},{method:"GET",path:"/v1/events",summary:"Server events as Server-Sent Events (?types=session,command to choose: "+ho.concat(nl).join(", ")+", trace only when asked for)",handler:({query:i})=>{let o=i.get("types"),a=o===null?ho:o.split(","),u=ho.concat(nl),l=a.filter(c=>u.indexOf(c)<0);if(l.length)throw K("Unknown event type "+l.join(", ")+", expected "+u.join(", "),"INVALID");return{stream:xd(s,a,e)}}},{method:"DELETE",path:"/v1/sessions/{session}",summary:"Disconnects a session with BYE ({ text }) or a TCP reset ({ reset: true })",handler:({params:i,body:o})=>{if(!t.disconnect(es(i.session),{text:o.text,reset:o.reset}))throw K("Session "+i.session+" does not exist","NONEXISTENT");return{disconnected:!0}}},{method:"POST",path:"/v1/sessions/{session}/inject",summary:"Writes bytes to a session as they are ({ data, encoding })",handler:({params:i,body:o})=>(t.inject(es(i.session),o.encoding==="base64"&&typeof o.data=="string"?b.Buffer.from(o.data,"base64"):o.data),{injected:!0})},{method:"GET",path:"/v1/users",summary:"Users, without credentials",handler:()=>t.listUsers()},{method:"POST",path:"/v1/users",summary:"Adds a user ({ name, password, xoauth2, displayName, oauth })",handler:({body:i})=>(t.addUser(i.name,{password:i.password,xoauth2:i.xoauth2,displayName:i.displayName,oauth:i.oauth}),{status:201,body:{name:i.name}})},{method:"PUT",path:"/v1/users/{name}",summary:"Changes the password, the XOAUTH2 token, the display name (displayName) or the OAuth settings ({ oauth: { consent } }) of a user",handler:({params:i,body:o})=>(t.updateUser(i.name,{password:o.password,xoauth2:o.xoauth2,displayName:o.displayName,oauth:o.oauth}),{name:i.name})},{method:"DELETE",path:"/v1/users/{name}",summary:"Deletes a user and disconnects its sessions ({ disconnect: false } keeps them)",handler:({params:i,body:o})=>(t.deleteUser(i.name,{disconnect:o.disconnect}),{deleted:!0})},{method:"GET",path:"/v1/mailboxes",summary:"Every mailbox",handler:()=>t.listMailboxes()},{method:"POST",path:"/v1/mailboxes",summary:"Creates a mailbox ({ path, subscribed })",handler:({body:i})=>({status:201,body:t.createMailbox(i.path,{subscribed:i.subscribed})})},{method:"GET",path:"/v1/mailboxes/{path}",summary:"A mailbox",handler:({params:i})=>t.getMailbox(i.path)},{method:"DELETE",path:"/v1/mailboxes/{path}",summary:"Deletes a mailbox, sessions that have it selected get BYE",handler:({params:i})=>(t.deleteMailbox(i.path),{deleted:!0})},{method:"POST",path:"/v1/mailboxes/{path}/rename",summary:"Renames a mailbox ({ newPath })",handler:({params:i,body:o})=>t.renameMailbox(i.path,o.newPath)},{method:"PUT",path:"/v1/mailboxes/{path}/subscription",summary:"Subscribes a mailbox",handler:({params:i})=>({changed:t.subscribe(i.path)})},{method:"DELETE",path:"/v1/mailboxes/{path}/subscription",summary:"Unsubscribes a name",handler:({params:i})=>({changed:t.unsubscribe(i.path)})},{method:"POST",path:"/v1/mailboxes/{path}/uidvalidity",summary:"Gives the mailbox a new UIDVALIDITY ({ uidvalidity, uids, offset, seed })",handler:({params:i,body:o})=>t.resetUidValidity(i.path,o)},{method:"GET",path:"/v1/mailboxes/{path}/messages",summary:"Messages (?uids=1,2 to choose, ?raw=true for the base64 source)",handler:({params:i,query:o})=>{let a=o.get("uids");return t.listMessages(i.path,{uids:a===null?void 0:a.split(",").map(es),raw:o.get("raw")==="true"}).map(rl)}},{method:"POST",path:"/v1/mailboxes/{path}/messages",summary:"Adds a message ({ raw, encoding, flags, internaldate, checks }), like a delivery, checks: true refuses it like APPEND would (quota)",handler:({params:i,body:o})=>({status:201,body:t.addMessage(i.path,{raw:Id(o.raw,o.encoding),flags:o.flags,internaldate:o.internaldate},{checks:o.checks})})},{method:"POST",path:"/v1/mailboxes/{path}/messages/flags",summary:"Changes flags ({ uids, flags, mode }), mode is set, add or remove",handler:({params:i,body:o})=>t.setFlags(i.path,o.uids,o.flags,o.mode||"set")},{method:"POST",path:"/v1/mailboxes/{path}/messages/expunge",summary:"Removes messages ({ uids })",handler:({params:i,body:o})=>({uids:t.expungeMessages(i.path,o.uids)})},{method:"POST",path:"/v1/mailboxes/{path}/messages/copy",summary:"Copies messages ({ uids, target })",handler:({params:i,body:o})=>t.copyMessages(i.path,o.uids,o.target)},{method:"POST",path:"/v1/mailboxes/{path}/messages/move",summary:"Moves messages ({ uids, target })",handler:({params:i,body:o})=>t.moveMessages(i.path,o.uids,o.target)},{method:"GET",path:"/v1/mailboxes/{path}/messages/{uid}",summary:"A message with its base64 source",handler:({params:i})=>rl(t.getMessage(i.path,es(i.uid)))},{method:"DELETE",path:"/v1/mailboxes/{path}/messages/{uid}",summary:"Removes a message",handler:({params:i})=>({uids:t.expungeMessages(i.path,[es(i.uid)])})},{method:"GET",path:"/v1/script/rules",summary:"Script rules with their hit counts",handler:()=>s.script.rules.map(r)},{method:"POST",path:"/v1/script/rules",summary:"Adds a script rule or a list of them, in the JSON form of the --script file",handler:({body:i})=>{let o;try{o=s.script.add(i)}catch(a){throw K(a.message,"INVALID")}return{status:201,body:Array.isArray(o)?o.map(r):r(o)}}},{method:"DELETE",path:"/v1/script/rules",summary:"Removes every script rule",handler:()=>(s.script.clear(),{deleted:!0})},{method:"DELETE",path:"/v1/script/rules/{id}",summary:"Removes a script rule",handler:({params:i})=>{let o=s.script.rules.find(a=>String(a.id)===i.id);if(!o)throw K("Script rule "+i.id+" does not exist","NONEXISTENT");return o.remove(),{deleted:!0}}}];return n.push(...t.routes),n.push({method:"GET",path:"/v1/openapi.json",summary:"This API as an OpenAPI document",handler:()=>wd(n)}),n}function wd(s){let e={};return s.forEach(t=>{let r=(t.path.match(/\{(\w+)\}/g)||[]).map(n=>({name:n.slice(1,-1),in:"path",required:!0,schema:{type:"string"},description:n==="{path}"?'Storage name of the mailbox (modified UTF-7), URL encoded, a "/" in it as %2F':void 0}));e[t.path]=e[t.path]||{},e[t.path][t.method.toLowerCase()]={summary:t.summary,parameters:r,responses:{default:{description:"JSON, errors as { error: { code, message } }"}}}}),{openapi:"3.1.0",info:{title:"ImapKit REST API",version:"1"},components:{securitySchemes:{bearer:{type:"http",scheme:"bearer"}}},paths:e}}function Nd(s,e,t){let r=t.split("/"),n=!1;for(let i of s){let o=i.path.split("/");if(o.length!==r.length)continue;let a={},u=!0;for(let l=0;l<o.length&&u;l++)if(o[l].startsWith("{")){try{a[o[l].slice(1,-1)]=decodeURIComponent(r[l])}catch{throw K("Invalid URL encoding","INVALID")}u=r[l]!==""}else u=o[l]===r[l];if(u){if(i.method===e)return{route:i,params:a};n=!0}}throw n?K("Method "+e+" is not allowed here","METHOD"):K("No such endpoint","NOTFOUND")}function Md(s,e){let t=/^Bearer (.+)$/i.exec(s||"");return!!t&&mr(t[1],e)}function mr(s,e){let t=r=>ce.createHash("sha256").update(r).digest();return ce.timingSafeEqual(t(s),t(e))}function mo(s,e,t){return new Promise((r,n)=>{let i=[],o=0;s.on("data",a=>{if(o+=a.length,o>e){n(t()),s.destroy();return}i.push(a)}),s.on("error",n),s.on("end",()=>r(b.Buffer.concat(i)))})}async function Rd(s){let e=(await mo(s,Td,()=>K("Request body is larger than 64 MiB","TOOBIG"))).toString("utf-8");if(!e)return{};let t;try{t=JSON.parse(e)}catch{throw K("Request body is not valid JSON","INVALID")}if(!t||typeof t!="object")throw K("Request body must be a JSON object or array","INVALID");return t}function il(s,e){let t=e.host||"127.0.0.1",r=e.token;if(r!==void 0&&(typeof r!="string"||!r))throw new Error("The REST API token must be a non-empty string");if(!r&&!ke(t))throw new Error("The REST API controls the whole server, it needs a token (rest.token, --rest-token) to listen on "+t);let n=new Set,i=Cd(s,n),o=(l,c,f)=>{let p=JSON.stringify(f);l.writeHead(c,{"Content-Type":"application/json; charset=utf-8","Content-Length":b.Buffer.byteLength(p),"Cache-Control":"no-store"}),l.end(p)},a=async(l,c)=>{if(r){if(!Md(l.headers.authorization,r))throw c.setHeader("WWW-Authenticate","Bearer"),K("Missing or wrong bearer token","UNAUTHORIZED")}else if(!ke((l.headers.host||"").replace(/:\d+$/,"")))throw K("Requests must use a loopback host name","UNAUTHORIZED");let f=new URL(l.url||"/","http://localhost"),p=(l.method||"GET").toUpperCase(),{route:y,params:A}=Nd(i,p,f.pathname),m={};if(p!=="GET"){let d=Number(l.headers["content-length"]||0)>0||!!l.headers["transfer-encoding"];if(!/^application\/json\b/i.test(l.headers["content-type"]||"")&&(d||p==="POST"))throw K("Requests must be application/json","UNSUPPORTED");m=await Rd(l)}let h=y.handler({params:A,query:f.searchParams,body:m});if(h&&typeof h=="object"&&typeof h.stream=="function")return h.stream(c,l);if(h&&typeof h=="object"&&"status"in h&&"body"in h){let{status:d,body:E}=h;return o(c,d,E)}o(c,200,h===void 0?{}:h)},u=ce.createServer((l,c)=>{a(l,c).catch(f=>{let p=f instanceof z?f.code:"SERVERERROR",y=Sd[p]||(f instanceof z?409:500);c.headersSent||o(c,y,{error:{code:p,message:f.message}})})});return u.endStreams=()=>n.forEach(l=>l.end()),u}g();g();var gr=s=>b.Buffer.from(s).toString("base64url");function Eo(s){let e=s?ce.createPrivateKey(s):ce.generateKeyPairSync("rsa",{modulusLength:2048}).privateKey;if(e.asymmetricKeyType!=="rsa")throw new Error("oauth.signingKey must be an RSA private key, ID tokens are signed with RS256");let{n:t,e:r}=ce.createPublicKey(e).export({format:"jwk"}),n=gr(ce.createHash("sha256").update(JSON.stringify({e:r,kty:"RSA",n:t})).digest());return{privateKey:e,kid:n,jwk:{kty:"RSA",use:"sig",alg:"RS256",kid:n,n:t,e:r}}}var go=null;function Ao(){return go||(go=Eo()),go}function ol(s,e){let t=gr(JSON.stringify({alg:"RS256",typ:"JWT",kid:s.kid}))+"."+gr(JSON.stringify(e));return t+"."+gr(ce.sign("sha256",b.Buffer.from(t),s.privateKey))}var Er=["http://127.0.0.1/*","http://localhost/*","http://[::1]/*"],Ld={imapkit:{name:"ImapKit test client",redirectUris:Er},"imapkit-approve":{name:"ImapKit test client (always allows)",redirectUris:Er,consent:"approve"},"imapkit-deny":{name:"ImapKit test client (always denies)",redirectUris:Er,consent:"deny"}},Dd={openid:"Confirm who you are (OpenID Connect ID token)",email:"See your email address",profile:"See your name",offline_access:"Stay signed in (a refresh token)"},al=["none","login","consent","select_account"],yo=/^[\x21\x23-\x5b\x5d-\x7e]+$/,ul=/^[A-Za-z0-9\-._~]{43,128}$/,Ud=new Set(["response_type","client_id","redirect_uri","scope","state","code_challenge","code_challenge_method","nonce","login_hint","prompt","response_mode","request","request_uri"]),ll=600*1e3,vd=24*3600*1e3,ts=(s=32)=>ce.randomBytes(s).toString("base64url");function bo(s){let e=Object.create(null),t=new Set;for(let[r,n]of s)n!==""&&(r in e&&t.add(r),e[r]=n);return{values:e,duplicates:[...t]}}function Bd(s,e){let t=s.endsWith("*"),r=t?s.slice(0,-1):s,n=(a,u)=>t?a.startsWith(u):a===u,i,o;try{i=new URL(r),o=new URL(e)}catch{return!1}return i.protocol==="http:"&&ke(i.hostname)&&!i.port?o.protocol==="http:"&&o.hostname===i.hostname&&n(o.pathname+o.search,i.pathname+i.search):n(e,r)}function Hd(s){let e=new Map;for(let t of Object.keys(s))e.set(t,hl(t,s[t]));return e}function hl(s,e){if(typeof s!="string"||!/^[\x20-\x7e]+$/.test(s))throw new z("OAuth client ID must be a non-empty string of printable ASCII","INVALID");let t="OAuth client "+JSON.stringify(s);if(!e||typeof e!="object")throw new z(t+" must be an object","INVALID");let{name:r,secret:n,redirectUris:i,consent:o}=e;if(r!==void 0&&(typeof r!="string"||!r))throw new z(t+": name must be a non-empty string","INVALID");if(n!==void 0&&(typeof n!="string"||!/^[\x20-\x7e]+$/.test(n)))throw new z(t+": secret must be a non-empty string of printable ASCII","INVALID");let a=i===void 0?Er:i;if(!Array.isArray(a)||!a.length)throw new z(t+": redirectUris must be a non-empty list","INVALID");for(let u of a){let l=typeof u=="string"?u.replace(/\*$/,""):"",c=!!l&&!l.includes("#");try{new URL(l)}catch{c=!1}if(!c)throw new z(t+": redirect URI "+JSON.stringify(u)+" must be an absolute URI without a fragment","INVALID")}return{id:s,name:r||s,secret:n===void 0?null:n,redirectUris:a.slice(),consent:o==null?null:$e(o,t+": consent")}}function cl(s,e,t,r=1/0){if(s===void 0)return e;if(typeof s!="number"||!(s>0)||s>r)throw new Error(t+" must be a positive number"+(r<1/0?" of at most "+r:""));return s}var Ar=class{constructor(e,t){if(this.server=e,this.options=t&&typeof t=="object"?t:{},this.issuer=this.options.issuer?this.checkIssuer(this.options.issuer):"",this.mailScope=this.options.mailScope===void 0?"mail":this.options.mailScope,typeof this.mailScope!="string"||!yo.test(this.mailScope))throw new Error("oauth.mailScope must be a scope token (RFC 6749 section 3.3)");this.scopes=Object.assign({},Dd,{[this.mailScope]:"Read, send and manage your mail over IMAP and SMTP"});for(let[i,o]of Object.entries(this.options.scopes||{})){if(!yo.test(i)||typeof o!="string")throw new Error("oauth.scopes maps scope tokens (RFC 6749 section 3.3) to descriptions, "+JSON.stringify(i)+" is not one");this.scopes[i]=o}this.accessTokenTtl=cl(this.options.accessTokenTtl,3600,"oauth.accessTokenTtl"),this.codeTtl=cl(this.options.codeTtl,60,"oauth.codeTtl",600);let{unknownScopes:r,refreshTokens:n}=this.options;if(r!==void 0&&r!=="refuse"&&r!=="drop")throw new Error('oauth.unknownScopes must be "refuse" or "drop"');if(n!==void 0&&n!=="offline_access"&&n!=="always")throw new Error('oauth.refreshTokens must be "offline_access" or "always"');this.queueCounter=0,this.key=this.options.signingKey?Eo(this.options.signingKey):null,this.reset(),e.on("reset",()=>this.reset()),this.registerControl()}checkIssuer(e){let t=null;try{t=new URL(String(e))}catch{}if(!t||!/^https?:$/.test(t.protocol)||t.search||t.hash||typeof e!="string")throw new Error("oauth.issuer must be an http or https URL without a query or fragment");return e.replace(/\/+$/,"")}reset(){this.clients=Hd(this.options.clients||Ld),this.consent=this.options.consent===void 0?"prompt":$e(this.options.consent,"oauth.consent"),this.decisions=[],this.tokenFaults=[],this.pending=new Map,this.codes=new Map,this.tokens=new Map}nowMs(){return this.server.now().getTime()}listening(e,t){if(!this.options.issuer){let r=e==="0.0.0.0"||e==="::"?"127.0.0.1":e.includes(":")?"["+e+"]":e;this.issuer=(this.options.secure?"https":"http")+"://"+r+":"+t}}discoveryUrl(){return this.issuer+"/.well-known/openid-configuration"}pageUsers(){return this.userNames().map(e=>{let t=this.server.getUser(e)||{};return{name:e,displayName:t.displayName||void 0,consent:t.oauth&&t.oauth.consent}})}endToken(e,t){e[t]=!0,e.endedAt=e.endedAt===null?this.nowMs():e.endedAt}emit(e,t){let r=Object.assign({type:e},t);this.server.options.debug&&console.log("[OAuth] %s %s",e,JSON.stringify(t)),this.server.emit("oauth",r)}authorize(e){this.prune();let{values:t,duplicates:r}=bo(e);if(r.includes("client_id")||r.includes("redirect_uri"))return this.errorPage("client_id or redirect_uri is sent more than once","Every parameter may only be sent once (RFC 6749 section 3.1).");if(!t.client_id)return this.errorPage("The request has no client_id","Add the client_id of a registered client.",this.clientList());let n=this.clients.get(t.client_id);if(!n)return this.errorPage("Unknown client_id "+JSON.stringify(t.client_id),"This client is not registered.",this.clientList());let i=this.resolveRedirect(n,t.redirect_uri);if(typeof i!="string")return i;let o={redirectUri:i,state:t.state},a=(f,p)=>(this.emit("authorize",{client:n.id,result:f,description:p}),this.redirectError(o,f,p)),u=this.checkRequest(n,i,t,r,a);if("type"in u)return u;let{outcome:l,source:c}=this.decide(u);return this.emit("authorize",{client:n.id,user:u.hintUser||null,decision:Jt(l),source:c,prompt:u.prompt}),this.finish(u,l,c)}checkRequest(e,t,r,n,i){if(n.length)return i("invalid_request",n.join(", ")+" sent more than once (RFC 6749 section 3.1)");if(r.request)return i("request_not_supported","Request objects are not supported (OpenID Connect Core 1.0 section 6.1)");if(r.request_uri)return i("request_uri_not_supported","request_uri is not supported (OpenID Connect Core 1.0 section 6.2)");if(!r.response_type)return i("invalid_request","response_type is missing (RFC 6749 section 4.1.1)");if(r.response_type!=="code")return i("unsupported_response_type","Only the authorization code flow, response_type=code, is supported");if(r.response_mode&&r.response_mode!=="query")return i("invalid_request","Only response_mode=query is supported");let o=[],a=this.checkScope(r.scope,o);if(typeof a=="string")return i("invalid_scope",a);let u=this.checkPkce(e,r,o);if(u)return i("invalid_request",u);let l=r.prompt?r.prompt.split(" "):[],c=l.find(p=>!al.includes(p));if(c!==void 0)return i("invalid_request","Unknown prompt value "+JSON.stringify(c)+" (OpenID Connect Core 1.0 section 3.1.2.1)");if(l.includes("none")&&l.length>1)return i("invalid_request","prompt=none can not be combined with other values (OpenID Connect Core 1.0 section 3.1.2.1)");o.push(r.state?{level:"ok",text:"state is present ("+r.state.length+" characters)"}:{level:"warn",text:"no state: the client can not tell this redirect from a forged one (RFC 6749 section 10.12)"}),a.includes("openid")&&o.push(r.nonce?{level:"ok",text:"nonce is present, the ID token carries it"}:{level:"note",text:"no nonce: allowed for the code flow, the ID token carries none"});let f=r.login_hint===void 0?void 0:this.server.getUser(r.login_hint)?r.login_hint:null;return f===null?o.push({level:"warn",text:"login_hint "+JSON.stringify(r.login_hint)+" is not a user of this server"}):f&&o.push({level:"ok",text:"login_hint matches the user "+f}),{client:e,redirectUri:t,redirectUriSent:r.redirect_uri!==void 0,state:r.state,scope:a,codeChallenge:r.code_challenge,codeChallengeMethod:r.code_challenge?r.code_challenge_method||"plain":void 0,nonce:r.nonce,loginHint:r.login_hint,hintUser:f,prompt:l,checks:o,ignored:Object.keys(r).filter(p=>!Ud.has(p))}}resolveRedirect(e,t){let r=e.redirectUris.map(n=>" "+n).join(`
39
+ `),15e3);o.unref(),n.on("close",()=>{t.delete(r),clearInterval(o),i.forEach(({type:a,listener:u})=>s.removeListener(a,u))})}}function Cd(s,e=new Set){let t=s.control,r=i=>({id:i.id,rule:i.rule,matched:i.matched,hits:i.hits}),n=[{method:"GET",path:"/v1/snapshot",summary:"The storage in the shape of the storage option",handler:()=>t.snapshot()},{method:"POST",path:"/v1/reset",summary:"Restores the mailboxes and users of the server options, disconnects every session",handler:()=>(t.reset(),{reset:!0})},{method:"POST",path:"/v1/shutdown",summary:"Stops accepting connections, the server closes once the last client is gone ({ graceful: false } closes them)",handler:({body:i})=>(R(()=>t.shutdown({graceful:i.graceful!==!1}).catch(()=>!1)),{status:202,body:{shutdown:!0}})},{method:"GET",path:"/v1/sessions",summary:"Connected sessions",handler:()=>t.sessions()},{method:"GET",path:"/v1/events",summary:"Server events as Server-Sent Events (?types=session,command to choose: "+ho.concat(nl).join(", ")+", trace only when asked for)",handler:({query:i})=>{let o=i.get("types"),a=o===null?ho:o.split(","),u=ho.concat(nl),l=a.filter(c=>u.indexOf(c)<0);if(l.length)throw K("Unknown event type "+l.join(", ")+", expected "+u.join(", "),"INVALID");return{stream:xd(s,a,e)}}},{method:"DELETE",path:"/v1/sessions/{session}",summary:"Disconnects a session with BYE ({ text }) or a TCP reset ({ reset: true })",handler:({params:i,body:o})=>{if(!t.disconnect(es(i.session),{text:o.text,reset:o.reset}))throw K("Session "+i.session+" does not exist","NONEXISTENT");return{disconnected:!0}}},{method:"POST",path:"/v1/sessions/{session}/inject",summary:"Writes bytes to a session as they are ({ data, encoding })",handler:({params:i,body:o})=>(t.inject(es(i.session),o.encoding==="base64"&&typeof o.data=="string"?b.Buffer.from(o.data,"base64"):o.data),{injected:!0})},{method:"GET",path:"/v1/users",summary:"Users, without credentials",handler:()=>t.listUsers()},{method:"POST",path:"/v1/users",summary:"Adds a user ({ name, password, xoauth2, displayName, oauth })",handler:({body:i})=>(t.addUser(i.name,{password:i.password,xoauth2:i.xoauth2,displayName:i.displayName,oauth:i.oauth}),{status:201,body:{name:i.name}})},{method:"PUT",path:"/v1/users/{name}",summary:"Changes the password, the XOAUTH2 token, the display name (displayName) or the OAuth settings ({ oauth: { consent } }) of a user",handler:({params:i,body:o})=>(t.updateUser(i.name,{password:o.password,xoauth2:o.xoauth2,displayName:o.displayName,oauth:o.oauth}),{name:i.name})},{method:"DELETE",path:"/v1/users/{name}",summary:"Deletes a user and disconnects its sessions ({ disconnect: false } keeps them)",handler:({params:i,body:o})=>(t.deleteUser(i.name,{disconnect:o.disconnect}),{deleted:!0})},{method:"GET",path:"/v1/mailboxes",summary:"Every mailbox",handler:()=>t.listMailboxes()},{method:"POST",path:"/v1/mailboxes",summary:"Creates a mailbox ({ path, subscribed })",handler:({body:i})=>({status:201,body:t.createMailbox(i.path,{subscribed:i.subscribed})})},{method:"GET",path:"/v1/mailboxes/{path}",summary:"A mailbox",handler:({params:i})=>t.getMailbox(i.path)},{method:"DELETE",path:"/v1/mailboxes/{path}",summary:"Deletes a mailbox, sessions that have it selected get BYE",handler:({params:i})=>(t.deleteMailbox(i.path),{deleted:!0})},{method:"POST",path:"/v1/mailboxes/{path}/rename",summary:"Renames a mailbox ({ newPath })",handler:({params:i,body:o})=>t.renameMailbox(i.path,o.newPath)},{method:"PUT",path:"/v1/mailboxes/{path}/subscription",summary:"Subscribes a mailbox",handler:({params:i})=>({changed:t.subscribe(i.path)})},{method:"DELETE",path:"/v1/mailboxes/{path}/subscription",summary:"Unsubscribes a name",handler:({params:i})=>({changed:t.unsubscribe(i.path)})},{method:"POST",path:"/v1/mailboxes/{path}/uidvalidity",summary:"Gives the mailbox a new UIDVALIDITY ({ uidvalidity, uids, offset, seed })",handler:({params:i,body:o})=>t.resetUidValidity(i.path,o)},{method:"GET",path:"/v1/mailboxes/{path}/messages",summary:"Messages (?uids=1,2 to choose, ?raw=true for the base64 source)",handler:({params:i,query:o})=>{let a=o.get("uids");return t.listMessages(i.path,{uids:a===null?void 0:a.split(",").map(es),raw:o.get("raw")==="true"}).map(rl)}},{method:"POST",path:"/v1/mailboxes/{path}/messages",summary:"Adds a message ({ raw, encoding, flags, internaldate, checks }), like a delivery, checks: true refuses it like APPEND would (quota)",handler:({params:i,body:o})=>({status:201,body:t.addMessage(i.path,{raw:Id(o.raw,o.encoding),flags:o.flags,internaldate:o.internaldate},{checks:o.checks})})},{method:"POST",path:"/v1/mailboxes/{path}/messages/flags",summary:"Changes flags ({ uids, flags, mode }), mode is set, add or remove",handler:({params:i,body:o})=>t.setFlags(i.path,o.uids,o.flags,o.mode||"set")},{method:"POST",path:"/v1/mailboxes/{path}/messages/expunge",summary:"Removes messages ({ uids })",handler:({params:i,body:o})=>({uids:t.expungeMessages(i.path,o.uids)})},{method:"POST",path:"/v1/mailboxes/{path}/messages/copy",summary:"Copies messages ({ uids, target })",handler:({params:i,body:o})=>t.copyMessages(i.path,o.uids,o.target)},{method:"POST",path:"/v1/mailboxes/{path}/messages/move",summary:"Moves messages ({ uids, target })",handler:({params:i,body:o})=>t.moveMessages(i.path,o.uids,o.target)},{method:"GET",path:"/v1/mailboxes/{path}/messages/{uid}",summary:"A message with its base64 source",handler:({params:i})=>rl(t.getMessage(i.path,es(i.uid)))},{method:"DELETE",path:"/v1/mailboxes/{path}/messages/{uid}",summary:"Removes a message",handler:({params:i})=>({uids:t.expungeMessages(i.path,[es(i.uid)])})},{method:"GET",path:"/v1/script/rules",summary:"Script rules with their hit counts",handler:()=>s.script.rules.map(r)},{method:"POST",path:"/v1/script/rules",summary:"Adds a script rule or a list of them, in the JSON form of the --script file",handler:({body:i})=>{let o;try{o=s.script.add(i)}catch(a){throw K(a.message,"INVALID")}return{status:201,body:Array.isArray(o)?o.map(r):r(o)}}},{method:"DELETE",path:"/v1/script/rules",summary:"Removes every script rule",handler:()=>(s.script.clear(),{deleted:!0})},{method:"DELETE",path:"/v1/script/rules/{id}",summary:"Removes a script rule",handler:({params:i})=>{let o=s.script.rules.find(a=>String(a.id)===i.id);if(!o)throw K("Script rule "+i.id+" does not exist","NONEXISTENT");return o.remove(),{deleted:!0}}}];return n.push(...t.routes),n.push({method:"GET",path:"/v1/openapi.json",summary:"This API as an OpenAPI document",handler:()=>wd(n)}),n}function wd(s){let e={};return s.forEach(t=>{let r=(t.path.match(/\{(\w+)\}/g)||[]).map(n=>({name:n.slice(1,-1),in:"path",required:!0,schema:{type:"string"},description:n==="{path}"?'Storage name of the mailbox (modified UTF-7), URL encoded, a "/" in it as %2F':void 0}));e[t.path]=e[t.path]||{},e[t.path][t.method.toLowerCase()]={summary:t.summary,parameters:r,responses:{default:{description:"JSON, errors as { error: { code, message } }"}}}}),{openapi:"3.1.0",info:{title:"ImapKit REST API",version:"1"},components:{securitySchemes:{bearer:{type:"http",scheme:"bearer"}}},paths:e}}function Nd(s,e,t){let r=t.split("/"),n=!1;for(let i of s){let o=i.path.split("/");if(o.length!==r.length)continue;let a={},u=!0;for(let l=0;l<o.length&&u;l++)if(o[l].startsWith("{")){try{a[o[l].slice(1,-1)]=decodeURIComponent(r[l])}catch{throw K("Invalid URL encoding","INVALID")}u=r[l]!==""}else u=o[l]===r[l];if(u){if(i.method===e)return{route:i,params:a};n=!0}}throw n?K("Method "+e+" is not allowed here","METHOD"):K("No such endpoint","NOTFOUND")}function Md(s,e){let t=/^Bearer (.+)$/i.exec(s||"");return!!t&&mr(t[1],e)}function mr(s,e){let t=r=>ce.createHash("sha256").update(r).digest();return ce.timingSafeEqual(t(s),t(e))}function mo(s,e,t){return new Promise((r,n)=>{let i=[],o=0;s.on("data",a=>{if(o+=a.length,o>e){n(t()),s.destroy();return}i.push(a)}),s.on("error",n),s.on("end",()=>r(b.Buffer.concat(i)))})}async function Rd(s){let e=(await mo(s,Td,()=>K("Request body is larger than 64 MiB","TOOBIG"))).toString("utf-8");if(!e)return{};let t;try{t=JSON.parse(e)}catch{throw K("Request body is not valid JSON","INVALID")}if(!t||typeof t!="object")throw K("Request body must be a JSON object or array","INVALID");return t}function il(s,e){let t=e.host||"127.0.0.1",r=e.token;if(r!==void 0&&(typeof r!="string"||!r))throw new Error("The REST API token must be a non-empty string");if(!r&&!ke(t))throw new Error("The REST API controls the whole server, it needs a token (rest.token, --rest-token) to listen on "+t);let n=new Set,i=Cd(s,n),o=(l,c,f)=>{let p=JSON.stringify(f);l.writeHead(c,{"Content-Type":"application/json; charset=utf-8","Content-Length":b.Buffer.byteLength(p),"Cache-Control":"no-store"}),l.end(p)},a=async(l,c)=>{if(r){if(!Md(l.headers.authorization,r))throw c.setHeader("WWW-Authenticate","Bearer"),K("Missing or wrong bearer token","UNAUTHORIZED")}else if(!ke((l.headers.host||"").replace(/:\d+$/,"")))throw K("Requests must use a loopback host name","UNAUTHORIZED");let f=new URL(l.url||"/","http://localhost"),p=(l.method||"GET").toUpperCase(),{route:y,params:A}=Nd(i,p,f.pathname),m={};if(p!=="GET"){let d=Number(l.headers["content-length"]||0)>0||!!l.headers["transfer-encoding"];if(!/^application\/json\b/i.test(l.headers["content-type"]||"")&&(d||p==="POST"))throw K("Requests must be application/json","UNSUPPORTED");m=await Rd(l)}let h=y.handler({params:A,query:f.searchParams,body:m});if(h&&typeof h=="object"&&typeof h.stream=="function")return h.stream(c,l);if(h&&typeof h=="object"&&"status"in h&&"body"in h){let{status:d,body:g}=h;return o(c,d,g)}o(c,200,h===void 0?{}:h)},u=ce.createServer((l,c)=>{a(l,c).catch(f=>{let p=f instanceof z?f.code:"SERVERERROR",y=Sd[p]||(f instanceof z?409:500);c.headersSent||o(c,y,{error:{code:p,message:f.message}})})});return u.endStreams=()=>n.forEach(l=>l.end()),u}E();E();var gr=s=>b.Buffer.from(s).toString("base64url");function Eo(s){let e=s?ce.createPrivateKey(s):ce.generateKeyPairSync("rsa",{modulusLength:2048}).privateKey;if(e.asymmetricKeyType!=="rsa")throw new Error("oauth.signingKey must be an RSA private key, ID tokens are signed with RS256");let{n:t,e:r}=ce.createPublicKey(e).export({format:"jwk"}),n=gr(ce.createHash("sha256").update(JSON.stringify({e:r,kty:"RSA",n:t})).digest());return{privateKey:e,kid:n,jwk:{kty:"RSA",use:"sig",alg:"RS256",kid:n,n:t,e:r}}}var go=null;function Ao(){return go||(go=Eo()),go}function ol(s,e){let t=gr(JSON.stringify({alg:"RS256",typ:"JWT",kid:s.kid}))+"."+gr(JSON.stringify(e));return t+"."+gr(ce.sign("sha256",b.Buffer.from(t),s.privateKey))}var Er=["http://127.0.0.1/*","http://localhost/*","http://[::1]/*"],Ld={imapkit:{name:"ImapKit test client",redirectUris:Er},"imapkit-approve":{name:"ImapKit test client (always allows)",redirectUris:Er,consent:"approve"},"imapkit-deny":{name:"ImapKit test client (always denies)",redirectUris:Er,consent:"deny"}},Dd={openid:"Confirm who you are (OpenID Connect ID token)",email:"See your email address",profile:"See your name",offline_access:"Stay signed in (a refresh token)"},al=["none","login","consent","select_account"],yo=/^[\x21\x23-\x5b\x5d-\x7e]+$/,ul=/^[A-Za-z0-9\-._~]{43,128}$/,Ud=new Set(["response_type","client_id","redirect_uri","scope","state","code_challenge","code_challenge_method","nonce","login_hint","prompt","response_mode","request","request_uri"]),ll=600*1e3,vd=24*3600*1e3,ts=(s=32)=>ce.randomBytes(s).toString("base64url");function bo(s){let e=Object.create(null),t=new Set;for(let[r,n]of s)n!==""&&(r in e&&t.add(r),e[r]=n);return{values:e,duplicates:[...t]}}function Bd(s,e){let t=s.endsWith("*"),r=t?s.slice(0,-1):s,n=(a,u)=>t?a.startsWith(u):a===u,i,o;try{i=new URL(r),o=new URL(e)}catch{return!1}return i.protocol==="http:"&&ke(i.hostname)&&!i.port?o.protocol==="http:"&&o.hostname===i.hostname&&n(o.pathname+o.search,i.pathname+i.search):n(e,r)}function Hd(s){let e=new Map;for(let t of Object.keys(s))e.set(t,hl(t,s[t]));return e}function hl(s,e){if(typeof s!="string"||!/^[\x20-\x7e]+$/.test(s))throw new z("OAuth client ID must be a non-empty string of printable ASCII","INVALID");let t="OAuth client "+JSON.stringify(s);if(!e||typeof e!="object")throw new z(t+" must be an object","INVALID");let{name:r,secret:n,redirectUris:i,consent:o}=e;if(r!==void 0&&(typeof r!="string"||!r))throw new z(t+": name must be a non-empty string","INVALID");if(n!==void 0&&(typeof n!="string"||!/^[\x20-\x7e]+$/.test(n)))throw new z(t+": secret must be a non-empty string of printable ASCII","INVALID");let a=i===void 0?Er:i;if(!Array.isArray(a)||!a.length)throw new z(t+": redirectUris must be a non-empty list","INVALID");for(let u of a){let l=typeof u=="string"?u.replace(/\*$/,""):"",c=!!l&&!l.includes("#");try{new URL(l)}catch{c=!1}if(!c)throw new z(t+": redirect URI "+JSON.stringify(u)+" must be an absolute URI without a fragment","INVALID")}return{id:s,name:r||s,secret:n===void 0?null:n,redirectUris:a.slice(),consent:o==null?null:$e(o,t+": consent")}}function cl(s,e,t,r=1/0){if(s===void 0)return e;if(typeof s!="number"||!(s>0)||s>r)throw new Error(t+" must be a positive number"+(r<1/0?" of at most "+r:""));return s}var Ar=class{constructor(e,t){if(this.server=e,this.options=t&&typeof t=="object"?t:{},this.issuer=this.options.issuer?this.checkIssuer(this.options.issuer):"",this.mailScope=this.options.mailScope===void 0?"mail":this.options.mailScope,typeof this.mailScope!="string"||!yo.test(this.mailScope))throw new Error("oauth.mailScope must be a scope token (RFC 6749 section 3.3)");this.scopes=Object.assign({},Dd,{[this.mailScope]:"Read, send and manage your mail over IMAP and SMTP"});for(let[i,o]of Object.entries(this.options.scopes||{})){if(!yo.test(i)||typeof o!="string")throw new Error("oauth.scopes maps scope tokens (RFC 6749 section 3.3) to descriptions, "+JSON.stringify(i)+" is not one");this.scopes[i]=o}this.accessTokenTtl=cl(this.options.accessTokenTtl,3600,"oauth.accessTokenTtl"),this.codeTtl=cl(this.options.codeTtl,60,"oauth.codeTtl",600);let{unknownScopes:r,refreshTokens:n}=this.options;if(r!==void 0&&r!=="refuse"&&r!=="drop")throw new Error('oauth.unknownScopes must be "refuse" or "drop"');if(n!==void 0&&n!=="offline_access"&&n!=="always")throw new Error('oauth.refreshTokens must be "offline_access" or "always"');this.queueCounter=0,this.key=this.options.signingKey?Eo(this.options.signingKey):null,this.reset(),e.on("reset",()=>this.reset()),this.registerControl()}checkIssuer(e){let t=null;try{t=new URL(String(e))}catch{}if(!t||!/^https?:$/.test(t.protocol)||t.search||t.hash||typeof e!="string")throw new Error("oauth.issuer must be an http or https URL without a query or fragment");return e.replace(/\/+$/,"")}reset(){this.clients=Hd(this.options.clients||Ld),this.consent=this.options.consent===void 0?"prompt":$e(this.options.consent,"oauth.consent"),this.decisions=[],this.tokenFaults=[],this.pending=new Map,this.codes=new Map,this.tokens=new Map}nowMs(){return this.server.now().getTime()}listening(e,t){if(!this.options.issuer){let r=e==="0.0.0.0"||e==="::"?"127.0.0.1":e.includes(":")?"["+e+"]":e;this.issuer=(this.options.secure?"https":"http")+"://"+r+":"+t}}discoveryUrl(){return this.issuer+"/.well-known/openid-configuration"}pageUsers(){return this.userNames().map(e=>{let t=this.server.getUser(e)||{};return{name:e,displayName:t.displayName||void 0,consent:t.oauth&&t.oauth.consent}})}endToken(e,t){e[t]=!0,e.endedAt=e.endedAt===null?this.nowMs():e.endedAt}emit(e,t){let r=Object.assign({type:e},t);this.server.options.debug&&console.log("[OAuth] %s %s",e,JSON.stringify(t)),this.server.emit("oauth",r)}authorize(e){this.prune();let{values:t,duplicates:r}=bo(e);if(r.includes("client_id")||r.includes("redirect_uri"))return this.errorPage("client_id or redirect_uri is sent more than once","Every parameter may only be sent once (RFC 6749 section 3.1).");if(!t.client_id)return this.errorPage("The request has no client_id","Add the client_id of a registered client.",this.clientList());let n=this.clients.get(t.client_id);if(!n)return this.errorPage("Unknown client_id "+JSON.stringify(t.client_id),"This client is not registered.",this.clientList());let i=this.resolveRedirect(n,t.redirect_uri);if(typeof i!="string")return i;let o={redirectUri:i,state:t.state},a=(f,p)=>(this.emit("authorize",{client:n.id,result:f,description:p}),this.redirectError(o,f,p)),u=this.checkRequest(n,i,t,r,a);if("type"in u)return u;let{outcome:l,source:c}=this.decide(u);return this.emit("authorize",{client:n.id,user:u.hintUser||null,decision:Jt(l),source:c,prompt:u.prompt}),this.finish(u,l,c)}checkRequest(e,t,r,n,i){if(n.length)return i("invalid_request",n.join(", ")+" sent more than once (RFC 6749 section 3.1)");if(r.request)return i("request_not_supported","Request objects are not supported (OpenID Connect Core 1.0 section 6.1)");if(r.request_uri)return i("request_uri_not_supported","request_uri is not supported (OpenID Connect Core 1.0 section 6.2)");if(!r.response_type)return i("invalid_request","response_type is missing (RFC 6749 section 4.1.1)");if(r.response_type!=="code")return i("unsupported_response_type","Only the authorization code flow, response_type=code, is supported");if(r.response_mode&&r.response_mode!=="query")return i("invalid_request","Only response_mode=query is supported");let o=[],a=this.checkScope(r.scope,o);if(typeof a=="string")return i("invalid_scope",a);let u=this.checkPkce(e,r,o);if(u)return i("invalid_request",u);let l=r.prompt?r.prompt.split(" "):[],c=l.find(p=>!al.includes(p));if(c!==void 0)return i("invalid_request","Unknown prompt value "+JSON.stringify(c)+" (OpenID Connect Core 1.0 section 3.1.2.1)");if(l.includes("none")&&l.length>1)return i("invalid_request","prompt=none can not be combined with other values (OpenID Connect Core 1.0 section 3.1.2.1)");o.push(r.state?{level:"ok",text:"state is present ("+r.state.length+" characters)"}:{level:"warn",text:"no state: the client can not tell this redirect from a forged one (RFC 6749 section 10.12)"}),a.includes("openid")&&o.push(r.nonce?{level:"ok",text:"nonce is present, the ID token carries it"}:{level:"note",text:"no nonce: allowed for the code flow, the ID token carries none"});let f=r.login_hint===void 0?void 0:this.server.getUser(r.login_hint)?r.login_hint:null;return f===null?o.push({level:"warn",text:"login_hint "+JSON.stringify(r.login_hint)+" is not a user of this server"}):f&&o.push({level:"ok",text:"login_hint matches the user "+f}),{client:e,redirectUri:t,redirectUriSent:r.redirect_uri!==void 0,state:r.state,scope:a,codeChallenge:r.code_challenge,codeChallengeMethod:r.code_challenge?r.code_challenge_method||"plain":void 0,nonce:r.nonce,loginHint:r.login_hint,hintUser:f,prompt:l,checks:o,ignored:Object.keys(r).filter(p=>!Ud.has(p))}}resolveRedirect(e,t){let r=e.redirectUris.map(n=>" "+n).join(`
40
40
  `);if(t===void 0){let n=e.redirectUris.length===1&&!e.redirectUris[0].endsWith("*")?e.redirectUris[0]:null;return n||this.errorPage("The request has no redirect_uri","Client "+e.id+" has more than one possible redirect URI, the request must name one.",["Registered for "+e.id+`:
41
41
  `+r])}return t.includes("#")?this.errorPage("redirect_uri has a fragment","A redirect URI must not include a fragment (RFC 6749 section 3.1.2).",["Received: "+t]):e.redirectUris.some(n=>Bd(n,t))?t:this.errorPage("redirect_uri is not registered for "+e.id,"The authorization server must not redirect to it (RFC 6749 section 4.1.2.1).",["Received: "+t,`Registered (a loopback http URI matches any port, RFC 8252 section 7.3):
42
42
  `+r])}checkScope(e,t){if(!e)return"scope is missing, ImapKit has no default scope (RFC 6749 section 3.3)";let r=[...new Set(e.split(" ").filter(Boolean))],n=r.find(a=>!yo.test(a));if(n!==void 0||!r.length)return"Invalid scope "+JSON.stringify(n===void 0?e:n)+" (RFC 6749 section 3.3)";let i=r.filter(a=>!Object.hasOwn(this.scopes,a));if(i.length&&this.options.unknownScopes!=="drop")return"Unknown scope "+i.join(" ")+", known: "+Object.keys(this.scopes).join(" ");let o=r.filter(a=>Object.hasOwn(this.scopes,a));return o.length?(t.push(i.length?{level:"warn",text:"unknown scopes are left out of the grant: "+i.join(" ")}:{level:"ok",text:"every scope is known"}),o.includes(this.mailScope)||t.push({level:"warn",text:"the "+this.mailScope+" scope is missing: IMAP and SMTP will refuse the token"}),o):"None of the requested scopes is known, known: "+Object.keys(this.scopes).join(" ")}checkPkce(e,t,r){let n=t.code_challenge;if(!n)return t.code_challenge_method?"code_challenge_method without code_challenge (RFC 7636 section 4.3)":e.secret?(r.push({level:"warn",text:"no PKCE: confidential clients should use it too (RFC 9700 section 2.1.1)"}),null):"code_challenge is missing, public clients must use PKCE (RFC 9700 section 2.1.1)";let i=t.code_challenge_method||"plain";return i!=="S256"&&i!=="plain"?"Unknown code_challenge_method "+JSON.stringify(i)+" (RFC 7636 section 4.3)":i==="plain"&&!this.options.allowPlainPkce?(t.code_challenge_method?"code_challenge_method=plain":"code_challenge_method is missing, which means plain,")+" but a client that can use S256 must use it (RFC 7636 section 4.2)":!ul.test(n)||i==="S256"&&n.length!==43?"Invalid code_challenge, "+(i==="S256"?"S256 gives 43 base64url characters":"it must be 43 to 128 unreserved characters")+" (RFC 7636 section 4.2)":(r.push({level:i==="S256"?"ok":"warn",text:"PKCE "+i+" code challenge"}),null)}decide(e){let t=this.decisions.find(i=>(i.client===void 0||i.client===e.client.id)&&(i.user===void 0||i.user===e.hintUser));if(t)return--t.remaining<=0&&this.decisions.splice(this.decisions.indexOf(t),1),{outcome:t.decision,source:"queued decision "+t.id};let r=e.hintUser?this.server.getUser(e.hintUser):!1,n=r&&r.oauth&&r.oauth.consent;return n?{outcome:n,source:"user "+e.hintUser}:e.client.consent?{outcome:e.client.consent,source:"client "+e.client.id}:{outcome:this.consent,source:"server default"}}finish(e,t,r,n){let i=(l,c)=>this.redirectError(e,l,c);if(t==="prompt"){if(e.prompt.includes("none"))return i("consent_required","prompt=none, but the consent policy ("+r+") shows the consent page");let l=Object.assign({},e,{id:ts(18),expiresAt:this.nowMs()+ll,source:r});return this.pending.set(l.id,l),{type:"consent",request:l}}if(t==="deny")return i("access_denied","The sign-in was denied ("+r+")");if(typeof t=="object")return i(t.error,t.description||"Answered by "+r);if(t==="no-redirect")return{type:"page",page:{status:200,tone:"info",title:"Not redirecting",message:"The decision ("+r+") leaves this sign-in unanswered, so the client never gets its redirect. Use it to test how the client times out."}};let o=n||this.pickUser(e);if(!o)return i("access_denied",e.loginHint===void 0?"The server has no users":"login_hint "+JSON.stringify(e.loginHint)+" is not a user of this server");let a=this.issueCode(e,o);this.emit("code",{client:e.client.id,user:o,scope:e.scope.join(" "),source:r,fault:t==="approve"?null:t});let u={code:a};return(e.state!==void 0||t==="wrong-state")&&(u.state=t==="wrong-state"?(e.state||"")+"x-wrong-state":e.state),{type:"redirect",location:this.redirectUrl(e.redirectUri,u,t==="wrong-iss")}}pickUser(e){return e.loginHint!==void 0?e.hintUser||null:this.userNames()[0]||null}userNames(){return Object.keys(this.server.users).sort((e,t)=>e==="testuser"?-1:t==="testuser"?1:e.localeCompare(t))}answerConsent(e){this.prune();let t=e.get("request")||"",r=this.pending.get(t);if(!r)return this.errorPage("This sign-in is no longer open","It was answered already, it expired after 10 minutes, or the server was reset or restarted. Start the sign-in again from the client.");let n=e.get("action"),i=e.get("user")||"";if(n!=="allow"&&n!=="deny"&&n!=="outcome")return this.errorPage("Unknown action","The form sent action "+JSON.stringify(n)+".");if(n!=="deny"&&!this.server.getUser(i))return this.errorPage("Choose an account","User "+JSON.stringify(i)+" does not exist. Go back and pick an account.");let o=n==="allow"?"approve":"deny";if(n==="outcome"){let a=e.get("outcome")||"",u=e.get("description")||void 0;try{o=$e(a.startsWith("error:")?{error:a.slice(6),description:u}:a,"outcome",!0)}catch(l){return this.errorPage("Unknown outcome",l.message)}}return this.pending.delete(t),e.get("remember")==="on"&&(o==="approve"||o==="deny")&&(r.client.consent=o,this.emit("remember",{client:r.client.id,consent:o})),this.emit("consent",{client:r.client.id,user:n==="deny"?null:i,decision:Jt(o)}),this.finish(r,o,"consent page",i)}prune(){let e=this.nowMs();this.tokens.forEach((t,r)=>{let n=t.endedAt!==null?t.endedAt:t.expiresAt;n!==null&&n+vd<=e&&this.tokens.delete(r)}),this.pending.forEach((t,r)=>t.expiresAt<=e&&this.pending.delete(r)),this.codes.forEach((t,r)=>t.expiresAt+ll<=e&&this.codes.delete(r))}issueCode(e,t){let r=ts();return this.codes.set(r,{clientId:e.client.id,user:t,redirectUri:e.redirectUri,redirectUriSent:e.redirectUriSent,scope:e.scope,challenge:e.codeChallenge,method:e.codeChallengeMethod,nonce:e.nonce,expiresAt:this.nowMs()+this.codeTtl*1e3,authTime:Math.floor(this.nowMs()/1e3),grantId:ts(12),used:!1}),r}redirectUrl(e,t,r=!1){let n=new URL(e);for(let[i,o]of Object.entries(t))n.searchParams.set(i,o);return n.searchParams.set("iss",r?"https://wrong-issuer.invalid":this.issuer),n.toString()}redirectError(e,t,r){let n={error:t,error_description:so(r)};return e.state!==void 0&&(n.state=e.state),{type:"redirect",location:this.redirectUrl(e.redirectUri,n)}}errorPage(e,t,r){return this.emit("authorize",{client:null,result:"error page",description:e}),{type:"page",page:{status:400,tone:"error",title:e,message:t,details:r}}}clientList(){return[`Registered clients:
43
43
  `+[...this.clients.values()].map(e=>" "+e.id+" ("+e.name+")").join(`
44
- `)]}async token(e,t){this.prune();let{values:r,duplicates:n}=bo(e);if(n.length)return te("invalid_request",n.join(", ")+" sent more than once (RFC 6749 section 3.2)");let i=r.grant_type,o=this.takeTokenFault(i);if(o&&o.delay&&await new Promise(f=>setTimeout(f,o.delay)),o&&(o.error||o.html||o.status))return this.emit("token",{grant:i||null,result:"fault",fault:o.id}),o.html?{status:o.status||500,body:null,htmlError:!0}:te(o.error||"server_error",o.description||"Queued token fault "+o.id,o.status||400);let a=this.authenticateClient(r,t);if("status"in a)return a;let u=a.client,l;i?i==="authorization_code"?l=this.exchangeCode(u,r,o):i==="refresh_token"?l=this.refresh(u,r):l=te("unsupported_grant_type","Supported grant types: authorization_code, refresh_token"):l=te("invalid_request","grant_type is missing (RFC 6749 section 4.1.3)");let c=l.body;return this.emit("token",{grant:i||null,client:u.id,result:l.status===200?"ok":c.error,description:c.error_description}),l}authenticateClient(e,t){let r=e.client_id,n=e.client_secret,i=/^Basic +([A-Za-z0-9+/=]+)$/i.exec(t||"");if(t&&!i)return te("invalid_request","Only Basic authentication is supported in the Authorization header (RFC 6749 section 2.3.1)");if(i){if(n!==void 0)return te("invalid_request","The client used Basic authentication and client_secret, only one method is allowed (RFC 6749 section 2.3)");let u=b.Buffer.from(i[1],"base64").toString("utf-8"),l=u.indexOf(":"),c=y=>{try{return decodeURIComponent(y.replace(/\+/g," "))}catch{return null}},f=l<0?null:c(u.slice(0,l)),p=l<0?null:c(u.slice(l+1));if(f===null||p===null)return te("invalid_client","Malformed Basic credentials",401,{"WWW-Authenticate":'Basic realm="imapkit"'});if(r!==void 0&&r!==f)return te("invalid_request","client_id differs from the client of the Authorization header");r=f,n=p}let o=i?{"WWW-Authenticate":'Basic realm="imapkit"'}:void 0;if(!r)return te("invalid_client","No client authentication and no client_id (RFC 6749 section 4.1.3)",401,o);let a=this.clients.get(r);return a?a.secret===null?n!==void 0?te("invalid_client","Client "+r+" is a public client without a secret, leave client_secret out",401,o):{client:a}:n===void 0||!mr(n,a.secret)?te("invalid_client",n===void 0?"Client "+r+" is confidential, it must send its secret":"Wrong client secret",401,o):{client:a}:te("invalid_client","Unknown client "+JSON.stringify(r),401,o)}exchangeCode(e,t,r){if(!t.code)return te("invalid_request","code is missing (RFC 6749 section 4.1.3)");let n=this.codes.get(t.code);if(!n||n.expiresAt<=this.nowMs())return n&&this.codes.delete(t.code),te("invalid_grant",n?"The authorization code expired ("+this.codeTtl+" seconds, RFC 6749 section 4.1.2)":"Unknown authorization code");if(n.clientId!==e.id)return te("invalid_grant","The authorization code was issued to another client (RFC 6749 section 4.1.3)");if(n.used){let o=this.revokeGrant(n.grantId);return this.emit("revoke",{client:e.id,user:n.user,reason:"authorization code reused",tokens:o}),te("invalid_grant","The authorization code was used already, its tokens are revoked now (RFC 6749 section 4.1.2)")}if((n.redirectUriSent||t.redirect_uri!==void 0)&&t.redirect_uri!==n.redirectUri)return te("invalid_grant",(t.redirect_uri===void 0?"redirect_uri is missing":"redirect_uri differs from the authorization request")+", it must be identical (RFC 6749 section 4.1.3)");let i=t.code_verifier;if(n.challenge){if(!i)return te("invalid_grant","code_verifier is missing, the authorization request had a code_challenge (RFC 7636 section 4.5)");if(!ul.test(i))return te("invalid_grant","Invalid code_verifier, it must be 43 to 128 unreserved characters (RFC 7636 section 4.1)");let o=n.method==="S256"?ce.createHash("sha256").update(i).digest("base64url"):i;if(!mr(o,n.challenge))return te("invalid_grant","code_verifier does not match the code_challenge (RFC 7636 section 4.6)")}else if(i!==void 0)return te("invalid_grant","code_verifier without a code_challenge in the authorization request (RFC 9700 section 2.1.1)");return this.server.getUser(n.user)?(n.used=!0,{status:200,body:this.issueTokens(e,n.user,n.scope,n.grantId,{nonce:n.nonce,authTime:n.authTime,fault:r})}):te("invalid_grant","User "+n.user+" does not exist any more")}refresh(e,t){if(!t.refresh_token)return te("invalid_request","refresh_token is missing (RFC 6749 section 6)");let r=this.tokens.get(t.refresh_token);if(!r||r.type!=="refresh"||r.revoked)return te("invalid_grant",r&&r.revoked?"The refresh token was revoked":"Unknown refresh token");if(r.clientId!==e.id)return te("invalid_grant","The refresh token was issued to another client (RFC 6749 section 6)");if(r.rotated){let o=this.revokeGrant(r.grantId);return this.emit("revoke",{client:e.id,user:r.user,reason:"rotated refresh token reused",tokens:o}),te("invalid_grant","This refresh token was replaced by rotation, using it again revoked the grant (RFC 9700 section 4.14.2)")}if(!this.server.getUser(r.user))return te("invalid_grant","User "+r.user+" does not exist any more");let n=r.scope;if(t.scope){let o=[...new Set(t.scope.split(" ").filter(Boolean))],a=o.filter(u=>!r.scope.includes(u));if(a.length||!o.length)return te("invalid_scope","Scope beyond the original grant: "+(a.join(" ")||t.scope)+" (RFC 6749 section 6)");n=o}return{status:200,body:this.issueTokens(e,r.user,n,r.grantId,{refresh:r})}}issueTokens(e,t,r,n,i){let o=this.nowMs(),a=ts();this.tokens.set(a,{token:a,type:"access",clientId:e.id,user:t,scope:r,grantId:n,expiresAt:o+this.accessTokenTtl*1e3,revoked:!1,rotated:!1,endedAt:null});let u={access_token:a,token_type:"Bearer",expires_in:this.accessTokenTtl,scope:r.join(" ")};return i.refresh?this.options.rotateRefreshTokens&&(this.endToken(i.refresh,"rotated"),u.refresh_token=this.newRefreshToken(e,t,i.refresh.scope,n)):(this.options.refreshTokens==="always"||r.includes("offline_access"))&&(u.refresh_token=this.newRefreshToken(e,t,r,n)),!i.refresh&&r.includes("openid")&&(u.id_token=this.idToken(e,t,r,i.nonce,i.authTime,i.fault?i.fault.claims:void 0)),u}newRefreshToken(e,t,r,n){let i=ts();return this.tokens.set(i,{token:i,type:"refresh",clientId:e.id,user:t,scope:r,grantId:n,expiresAt:null,revoked:!1,rotated:!1,endedAt:null}),i}idToken(e,t,r,n,i,o){let a=Math.floor(this.nowMs()/1e3),u=Object.assign({iss:this.issuer,sub:t,aud:e.id,azp:e.id,iat:a,exp:a+this.accessTokenTtl,auth_time:i||a},n===void 0?{}:{nonce:n},this.userClaims(t,r));for(let[l,c]of Object.entries(o||{}))c===null?delete u[l]:u[l]=c;return ol(this.key||Ao(),u)}userClaims(e,t){let r={};t.includes("email")&&(r.email=e,r.email_verified=!0);let n=this.server.getUser(e);return t.includes("profile")&&n&&typeof n.displayName=="string"&&n.displayName&&(r.name=n.displayName),r}jwks(){return{keys:[(this.key||Ao()).jwk]}}takeTokenFault(e){let t=this.tokenFaults.find(r=>r.grant===void 0||r.grant===e);return t?(--t.remaining<=0&&this.tokenFaults.splice(this.tokenFaults.indexOf(t),1),t):null}revokeGrant(e){let t=0;return this.tokens.forEach(r=>{r.grantId===e&&!r.revoked&&(this.endToken(r,"revoked"),t++)}),t}revoke(e,t){let{values:r,duplicates:n}=bo(e);if(n.length)return te("invalid_request",n.join(", ")+" sent more than once");let i=this.authenticateClient(r,t);if("status"in i)return i;if(!r.token)return te("invalid_request","token is missing (RFC 7009 section 2.1)");let o=this.tokens.get(r.token);if(!o)return{status:200,body:{}};if(o.clientId!==i.client.id)return te("invalid_request","The token was issued to another client (RFC 7009 section 2.1)");let a=o.type==="refresh"?this.revokeGrant(o.grantId):+!o.revoked;return this.endToken(o,"revoked"),this.emit("revoke",{client:i.client.id,user:o.user,reason:o.type+" token revoked by the client",tokens:a}),{status:200,body:{}}}userinfo(e){let t=/^Bearer +([A-Za-z0-9\-._~+/]+=*)$/i.exec(e||""),r=(o,a,u)=>({status:u,body:{error:o,error_description:a},headers:{"WWW-Authenticate":"Bearer"+(o?' error="'+o+'", error_description="'+a+'"':"")}});if(!t)return r("invalid_request","Send the access token as Authorization: Bearer <token> (RFC 6750 section 2.1)",401);let n=this.tokens.get(t[1]),i=this.tokenProblem(n);return i||!n?r("invalid_token","The access token is "+(i||"unknown"),401):n.scope.includes("openid")?{status:200,body:Object.assign({sub:n.user},this.userClaims(n.user,n.scope))}:r("insufficient_scope","The access token has no openid scope",403)}tokenProblem(e){return!e||e.type!=="access"?e?"a refresh token, not an access token":"unknown":e.revoked?"revoked":e.expiresAt!==null&&e.expiresAt<=this.nowMs()?"expired":this.server.getUser(e.user)?null:"for a user that does not exist any more"}verifyAccessToken(e,t,r){let n=this.tokens.get(e);if(!n||n.type!=="access")return null;let i,o=this.tokenProblem(n);return o?i={error:"invalid_token",reason:"the access token is "+o}:t!==void 0&&t!==n.user?i={error:"invalid_token",reason:"the access token is for "+n.user+", not "+t}:n.scope.includes(this.mailScope)?i={user:n.user}:i={error:"insufficient_scope",reason:"the access token has no "+this.mailScope+" scope"},this.emit("access",{via:r,client:n.clientId,user:n.user,result:"user"in i?"ok":i.error,reason:"user"in i?null:i.reason}),i}metadata(){let e=["none","client_secret_basic","client_secret_post"];return{issuer:this.issuer,authorization_endpoint:this.issuer+"/authorize",token_endpoint:this.issuer+"/token",userinfo_endpoint:this.issuer+"/userinfo",jwks_uri:this.issuer+"/jwks",revocation_endpoint:this.issuer+"/revoke",scopes_supported:Object.keys(this.scopes),response_types_supported:["code"],response_modes_supported:["query"],grant_types_supported:["authorization_code","refresh_token"],subject_types_supported:["public"],id_token_signing_alg_values_supported:["RS256"],token_endpoint_auth_methods_supported:e,revocation_endpoint_auth_methods_supported:e,code_challenge_methods_supported:this.options.allowPlainPkce?["S256","plain"]:["S256"],claims_supported:["iss","sub","aud","azp","exp","iat","auth_time","nonce","email","email_verified","name"],prompt_values_supported:al,authorization_response_iss_parameter_supported:!0,request_parameter_supported:!1,request_uri_parameter_supported:!1}}describeClient(e){return{id:e.id,name:e.name,confidential:e.secret!==null,redirectUris:e.redirectUris.slice(),consent:e.consent}}describeToken(e){return{type:e.type,token:e.token,user:e.user,client:e.clientId,scope:e.scope.join(" "),expiresAt:e.expiresAt===null?null:new Date(e.expiresAt).toISOString(),expired:e.expiresAt!==null&&e.expiresAt<=this.nowMs(),revoked:e.revoked,rotated:e.rotated}}findTokens(e){let t=e||{};if(To(t,["user","client","token"]),t.type!==void 0&&t.type!=="access"&&t.type!=="refresh")throw new z('type must be "access" or "refresh"',"INVALID");return[...this.tokens.values()].filter(r=>(t.user===void 0||r.user===t.user)&&(t.client===void 0||r.clientId===t.client)&&(t.token===void 0||r.token===t.token)&&(t.type===void 0||r.type===t.type))}queueDecision(e){let t=e||{},r=$e(t.decision,"decision",!0);To(t,["client","user"]);let n=++this.queueCounter;return this.decisions.push({id:n,decision:r,client:t.client,user:t.user,remaining:fl(t.count)}),{id:n}}queueTokenFault(e){let t=e||{},{grant:r,error:n,status:i,html:o,delay:a,claims:u}=t;if(To(t,["description"]),r!==void 0&&r!=="authorization_code"&&r!=="refresh_token")throw new z('grant must be "authorization_code" or "refresh_token"',"INVALID");if(n!==void 0&&!ro(n))throw new z("error must be an OAuth error code","INVALID");if(i!==void 0&&(!Number.isInteger(i)||i<400||i>599))throw new z("status must be an HTTP error status, 400 to 599","INVALID");if(a!==void 0&&(typeof a!="number"||!(a>=0)||a>6e5))throw new z("delay must be milliseconds, at most 600000","INVALID");if(u!==void 0&&(!u||typeof u!="object"||Array.isArray(u)))throw new z("claims must be an object, null values remove claims","INVALID");if(n===void 0&&!o&&i===void 0&&a===void 0&&u===void 0)throw new z("A token fault needs error, status, html, delay or claims","INVALID");let l=++this.queueCounter;return this.tokenFaults.push({id:l,grant:r,error:n,description:t.description,status:i,html:!!o,delay:a||0,claims:u,remaining:fl(t.count)}),{id:l}}listClients(){return[...this.clients.values()].map(e=>this.describeClient(e))}setClient(e,t){let r=hl(e,t);return this.clients.set(r.id,r),this.describeClient(r)}deleteClient(e){if(!this.clients.delete(e))throw new z("OAuth client "+JSON.stringify(e)+" does not exist","NONEXISTENT")}setConsent(e){return this.consent=$e(e,"consent"),{consent:this.consent}}listTokens(e){return this.findTokens(e).map(t=>this.describeToken(t))}expireTokens(e){let t=this.findTokens(Object.assign({},e,{type:"access"})).filter(n=>!this.tokenProblem(n)),r=this.nowMs();return t.forEach(n=>n.expiresAt=r),{expired:t.length}}revokeTokens(e){let t=this.findTokens(e).filter(r=>!r.revoked);return t.forEach(r=>this.endToken(r,"revoked")),t.length&&this.emit("revoke",{reason:"control API",tokens:t.length}),{revoked:t.length}}info(){return{issuer:this.issuer,discovery:this.issuer?this.discoveryUrl():null,consent:this.consent,mailScope:this.mailScope,scopes:Object.keys(this.scopes),clients:this.listClients(),decisions:this.decisions.map(e=>Object.assign({},e)),tokenFaults:this.tokenFaults.map(e=>Object.assign({},e))}}registerControl(){let e=this.server.control,t=o=>({status:201,body:o}),r=()=>({deleted:!0}),n=o=>{let a={};for(let u of["user","client","type"]){let l=o.get(u);l!==null&&(a[u]=l)}return a},i=[["getOAuthInfo",()=>this.info(),"GET","/v1/oauth","OAuth provider: issuer, default consent, clients, queues",()=>e.getOAuthInfo()],["listOAuthClients",()=>this.listClients(),"GET","/v1/oauth/clients","Registered OAuth clients, without secrets",()=>e.listOAuthClients()],["setOAuthClient",(o,a)=>this.setClient(o,a),"PUT","/v1/oauth/clients/{id}","Registers or replaces an OAuth client ({ name, secret, redirectUris, consent })",({params:o,body:a})=>e.setOAuthClient(o.id,a)],["deleteOAuthClient",o=>this.deleteClient(o),"DELETE","/v1/oauth/clients/{id}","Removes an OAuth client",({params:o})=>(e.deleteOAuthClient(o.id),r())],["setOAuthConsent",o=>this.setConsent(o),"PUT","/v1/oauth/consent","Sets the default consent policy ({ consent }: prompt, approve, deny or { error, description })",({body:o})=>e.setOAuthConsent(o.consent)],["queueOAuthDecision",o=>this.queueDecision(o),"POST","/v1/oauth/decisions","Queues the decision of the next sign-ins ({ decision, client, user, count })",({body:o})=>t(e.queueOAuthDecision(o))],["listOAuthDecisions",()=>this.decisions.map(o=>Object.assign({},o)),"GET","/v1/oauth/decisions","Queued sign-in decisions",()=>e.listOAuthDecisions()],["clearOAuthDecisions",()=>{this.decisions=[]},"DELETE","/v1/oauth/decisions","Removes the queued sign-in decisions",()=>(e.clearOAuthDecisions(),r())],["queueOAuthTokenFault",o=>this.queueTokenFault(o),"POST","/v1/oauth/token-faults","Queues a fault of the token endpoint ({ grant, error, description, status, html, delay, claims, count })",({body:o})=>t(e.queueOAuthTokenFault(o))],["clearOAuthTokenFaults",()=>{this.tokenFaults=[]},"DELETE","/v1/oauth/token-faults","Removes the queued token endpoint faults",()=>(e.clearOAuthTokenFaults(),r())],["listOAuthTokens",o=>this.listTokens(o),"GET","/v1/oauth/tokens","Issued tokens (?user=&client=&type=access|refresh to choose)",({query:o})=>e.listOAuthTokens(n(o))],["expireOAuthTokens",o=>this.expireTokens(o),"POST","/v1/oauth/tokens/expire","Lets access tokens expire now ({ user, client, token })",({body:o})=>e.expireOAuthTokens(o)],["revokeOAuthTokens",o=>this.revokeTokens(o),"POST","/v1/oauth/tokens/revoke","Revokes access and refresh tokens ({ user, client, token, type })",({body:o})=>e.revokeOAuthTokens(o)]];for(let[o,a,u,l,c,f]of i)e.register(o,a,[{method:u,path:l,summary:c,handler:f}])}};function To(s,e){for(let t of e)if(s[t]!==void 0&&typeof s[t]!="string")throw new z(t+" must be a string","INVALID")}function fl(s){if(s===void 0)return 1;if(!Number.isInteger(s)||s<1)throw new z("count must be a positive integer","INVALID");return s}function te(s,e,t=400,r){return{status:t,body:{error:s,error_description:so(e)},headers:r}}g();g();var ie=s=>String(s).replace(/[&<>"']/g,e=>({"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"})[e]),So=s=>s?Jt(s):"server default",kd=`
44
+ `)]}async token(e,t){this.prune();let{values:r,duplicates:n}=bo(e);if(n.length)return te("invalid_request",n.join(", ")+" sent more than once (RFC 6749 section 3.2)");let i=r.grant_type,o=this.takeTokenFault(i);if(o&&o.delay&&await new Promise(f=>setTimeout(f,o.delay)),o&&(o.error||o.html||o.status))return this.emit("token",{grant:i||null,result:"fault",fault:o.id}),o.html?{status:o.status||500,body:null,htmlError:!0}:te(o.error||"server_error",o.description||"Queued token fault "+o.id,o.status||400);let a=this.authenticateClient(r,t);if("status"in a)return a;let u=a.client,l;i?i==="authorization_code"?l=this.exchangeCode(u,r,o):i==="refresh_token"?l=this.refresh(u,r):l=te("unsupported_grant_type","Supported grant types: authorization_code, refresh_token"):l=te("invalid_request","grant_type is missing (RFC 6749 section 4.1.3)");let c=l.body;return this.emit("token",{grant:i||null,client:u.id,result:l.status===200?"ok":c.error,description:c.error_description}),l}authenticateClient(e,t){let r=e.client_id,n=e.client_secret,i=/^Basic +([A-Za-z0-9+/=]+)$/i.exec(t||"");if(t&&!i)return te("invalid_request","Only Basic authentication is supported in the Authorization header (RFC 6749 section 2.3.1)");if(i){if(n!==void 0)return te("invalid_request","The client used Basic authentication and client_secret, only one method is allowed (RFC 6749 section 2.3)");let u=b.Buffer.from(i[1],"base64").toString("utf-8"),l=u.indexOf(":"),c=y=>{try{return decodeURIComponent(y.replace(/\+/g," "))}catch{return null}},f=l<0?null:c(u.slice(0,l)),p=l<0?null:c(u.slice(l+1));if(f===null||p===null)return te("invalid_client","Malformed Basic credentials",401,{"WWW-Authenticate":'Basic realm="imapkit"'});if(r!==void 0&&r!==f)return te("invalid_request","client_id differs from the client of the Authorization header");r=f,n=p}let o=i?{"WWW-Authenticate":'Basic realm="imapkit"'}:void 0;if(!r)return te("invalid_client","No client authentication and no client_id (RFC 6749 section 4.1.3)",401,o);let a=this.clients.get(r);return a?a.secret===null?n!==void 0?te("invalid_client","Client "+r+" is a public client without a secret, leave client_secret out",401,o):{client:a}:n===void 0||!mr(n,a.secret)?te("invalid_client",n===void 0?"Client "+r+" is confidential, it must send its secret":"Wrong client secret",401,o):{client:a}:te("invalid_client","Unknown client "+JSON.stringify(r),401,o)}exchangeCode(e,t,r){if(!t.code)return te("invalid_request","code is missing (RFC 6749 section 4.1.3)");let n=this.codes.get(t.code);if(!n||n.expiresAt<=this.nowMs())return n&&this.codes.delete(t.code),te("invalid_grant",n?"The authorization code expired ("+this.codeTtl+" seconds, RFC 6749 section 4.1.2)":"Unknown authorization code");if(n.clientId!==e.id)return te("invalid_grant","The authorization code was issued to another client (RFC 6749 section 4.1.3)");if(n.used){let o=this.revokeGrant(n.grantId);return this.emit("revoke",{client:e.id,user:n.user,reason:"authorization code reused",tokens:o}),te("invalid_grant","The authorization code was used already, its tokens are revoked now (RFC 6749 section 4.1.2)")}if((n.redirectUriSent||t.redirect_uri!==void 0)&&t.redirect_uri!==n.redirectUri)return te("invalid_grant",(t.redirect_uri===void 0?"redirect_uri is missing":"redirect_uri differs from the authorization request")+", it must be identical (RFC 6749 section 4.1.3)");let i=t.code_verifier;if(n.challenge){if(!i)return te("invalid_grant","code_verifier is missing, the authorization request had a code_challenge (RFC 7636 section 4.5)");if(!ul.test(i))return te("invalid_grant","Invalid code_verifier, it must be 43 to 128 unreserved characters (RFC 7636 section 4.1)");let o=n.method==="S256"?ce.createHash("sha256").update(i).digest("base64url"):i;if(!mr(o,n.challenge))return te("invalid_grant","code_verifier does not match the code_challenge (RFC 7636 section 4.6)")}else if(i!==void 0)return te("invalid_grant","code_verifier without a code_challenge in the authorization request (RFC 9700 section 2.1.1)");return this.server.getUser(n.user)?(n.used=!0,{status:200,body:this.issueTokens(e,n.user,n.scope,n.grantId,{nonce:n.nonce,authTime:n.authTime,fault:r})}):te("invalid_grant","User "+n.user+" does not exist any more")}refresh(e,t){if(!t.refresh_token)return te("invalid_request","refresh_token is missing (RFC 6749 section 6)");let r=this.tokens.get(t.refresh_token);if(!r||r.type!=="refresh"||r.revoked)return te("invalid_grant",r&&r.revoked?"The refresh token was revoked":"Unknown refresh token");if(r.clientId!==e.id)return te("invalid_grant","The refresh token was issued to another client (RFC 6749 section 6)");if(r.rotated){let o=this.revokeGrant(r.grantId);return this.emit("revoke",{client:e.id,user:r.user,reason:"rotated refresh token reused",tokens:o}),te("invalid_grant","This refresh token was replaced by rotation, using it again revoked the grant (RFC 9700 section 4.14.2)")}if(!this.server.getUser(r.user))return te("invalid_grant","User "+r.user+" does not exist any more");let n=r.scope;if(t.scope){let o=[...new Set(t.scope.split(" ").filter(Boolean))],a=o.filter(u=>!r.scope.includes(u));if(a.length||!o.length)return te("invalid_scope","Scope beyond the original grant: "+(a.join(" ")||t.scope)+" (RFC 6749 section 6)");n=o}return{status:200,body:this.issueTokens(e,r.user,n,r.grantId,{refresh:r})}}issueTokens(e,t,r,n,i){let o=this.nowMs(),a=ts();this.tokens.set(a,{token:a,type:"access",clientId:e.id,user:t,scope:r,grantId:n,expiresAt:o+this.accessTokenTtl*1e3,revoked:!1,rotated:!1,endedAt:null});let u={access_token:a,token_type:"Bearer",expires_in:this.accessTokenTtl,scope:r.join(" ")};return i.refresh?this.options.rotateRefreshTokens&&(this.endToken(i.refresh,"rotated"),u.refresh_token=this.newRefreshToken(e,t,i.refresh.scope,n)):(this.options.refreshTokens==="always"||r.includes("offline_access"))&&(u.refresh_token=this.newRefreshToken(e,t,r,n)),!i.refresh&&r.includes("openid")&&(u.id_token=this.idToken(e,t,r,i.nonce,i.authTime,i.fault?i.fault.claims:void 0)),u}newRefreshToken(e,t,r,n){let i=ts();return this.tokens.set(i,{token:i,type:"refresh",clientId:e.id,user:t,scope:r,grantId:n,expiresAt:null,revoked:!1,rotated:!1,endedAt:null}),i}idToken(e,t,r,n,i,o){let a=Math.floor(this.nowMs()/1e3),u=Object.assign({iss:this.issuer,sub:t,aud:e.id,azp:e.id,iat:a,exp:a+this.accessTokenTtl,auth_time:i||a},n===void 0?{}:{nonce:n},this.userClaims(t,r));for(let[l,c]of Object.entries(o||{}))c===null?delete u[l]:u[l]=c;return ol(this.key||Ao(),u)}userClaims(e,t){let r={};t.includes("email")&&(r.email=e,r.email_verified=!0);let n=this.server.getUser(e);return t.includes("profile")&&n&&typeof n.displayName=="string"&&n.displayName&&(r.name=n.displayName),r}jwks(){return{keys:[(this.key||Ao()).jwk]}}takeTokenFault(e){let t=this.tokenFaults.find(r=>r.grant===void 0||r.grant===e);return t?(--t.remaining<=0&&this.tokenFaults.splice(this.tokenFaults.indexOf(t),1),t):null}revokeGrant(e){let t=0;return this.tokens.forEach(r=>{r.grantId===e&&!r.revoked&&(this.endToken(r,"revoked"),t++)}),t}revoke(e,t){let{values:r,duplicates:n}=bo(e);if(n.length)return te("invalid_request",n.join(", ")+" sent more than once");let i=this.authenticateClient(r,t);if("status"in i)return i;if(!r.token)return te("invalid_request","token is missing (RFC 7009 section 2.1)");let o=this.tokens.get(r.token);if(!o)return{status:200,body:{}};if(o.clientId!==i.client.id)return te("invalid_request","The token was issued to another client (RFC 7009 section 2.1)");let a=o.type==="refresh"?this.revokeGrant(o.grantId):+!o.revoked;return this.endToken(o,"revoked"),this.emit("revoke",{client:i.client.id,user:o.user,reason:o.type+" token revoked by the client",tokens:a}),{status:200,body:{}}}userinfo(e){let t=/^Bearer +([A-Za-z0-9\-._~+/]+=*)$/i.exec(e||""),r=(o,a,u)=>({status:u,body:{error:o,error_description:a},headers:{"WWW-Authenticate":"Bearer"+(o?' error="'+o+'", error_description="'+a+'"':"")}});if(!t)return r("invalid_request","Send the access token as Authorization: Bearer <token> (RFC 6750 section 2.1)",401);let n=this.tokens.get(t[1]),i=this.tokenProblem(n);return i||!n?r("invalid_token","The access token is "+(i||"unknown"),401):n.scope.includes("openid")?{status:200,body:Object.assign({sub:n.user},this.userClaims(n.user,n.scope))}:r("insufficient_scope","The access token has no openid scope",403)}tokenProblem(e){return!e||e.type!=="access"?e?"a refresh token, not an access token":"unknown":e.revoked?"revoked":e.expiresAt!==null&&e.expiresAt<=this.nowMs()?"expired":this.server.getUser(e.user)?null:"for a user that does not exist any more"}verifyAccessToken(e,t,r){let n=this.tokens.get(e);if(!n||n.type!=="access")return null;let i,o=this.tokenProblem(n);return o?i={error:"invalid_token",reason:"the access token is "+o}:t!==void 0&&t!==n.user?i={error:"invalid_token",reason:"the access token is for "+n.user+", not "+t}:n.scope.includes(this.mailScope)?i={user:n.user}:i={error:"insufficient_scope",reason:"the access token has no "+this.mailScope+" scope"},this.emit("access",{via:r,client:n.clientId,user:n.user,result:"user"in i?"ok":i.error,reason:"user"in i?null:i.reason}),i}metadata(){let e=["none","client_secret_basic","client_secret_post"];return{issuer:this.issuer,authorization_endpoint:this.issuer+"/authorize",token_endpoint:this.issuer+"/token",userinfo_endpoint:this.issuer+"/userinfo",jwks_uri:this.issuer+"/jwks",revocation_endpoint:this.issuer+"/revoke",scopes_supported:Object.keys(this.scopes),response_types_supported:["code"],response_modes_supported:["query"],grant_types_supported:["authorization_code","refresh_token"],subject_types_supported:["public"],id_token_signing_alg_values_supported:["RS256"],token_endpoint_auth_methods_supported:e,revocation_endpoint_auth_methods_supported:e,code_challenge_methods_supported:this.options.allowPlainPkce?["S256","plain"]:["S256"],claims_supported:["iss","sub","aud","azp","exp","iat","auth_time","nonce","email","email_verified","name"],prompt_values_supported:al,authorization_response_iss_parameter_supported:!0,request_parameter_supported:!1,request_uri_parameter_supported:!1}}describeClient(e){return{id:e.id,name:e.name,confidential:e.secret!==null,redirectUris:e.redirectUris.slice(),consent:e.consent}}describeToken(e){return{type:e.type,token:e.token,user:e.user,client:e.clientId,scope:e.scope.join(" "),expiresAt:e.expiresAt===null?null:new Date(e.expiresAt).toISOString(),expired:e.expiresAt!==null&&e.expiresAt<=this.nowMs(),revoked:e.revoked,rotated:e.rotated}}findTokens(e){let t=e||{};if(To(t,["user","client","token"]),t.type!==void 0&&t.type!=="access"&&t.type!=="refresh")throw new z('type must be "access" or "refresh"',"INVALID");return[...this.tokens.values()].filter(r=>(t.user===void 0||r.user===t.user)&&(t.client===void 0||r.clientId===t.client)&&(t.token===void 0||r.token===t.token)&&(t.type===void 0||r.type===t.type))}queueDecision(e){let t=e||{},r=$e(t.decision,"decision",!0);To(t,["client","user"]);let n=++this.queueCounter;return this.decisions.push({id:n,decision:r,client:t.client,user:t.user,remaining:fl(t.count)}),{id:n}}queueTokenFault(e){let t=e||{},{grant:r,error:n,status:i,html:o,delay:a,claims:u}=t;if(To(t,["description"]),r!==void 0&&r!=="authorization_code"&&r!=="refresh_token")throw new z('grant must be "authorization_code" or "refresh_token"',"INVALID");if(n!==void 0&&!ro(n))throw new z("error must be an OAuth error code","INVALID");if(i!==void 0&&(!Number.isInteger(i)||i<400||i>599))throw new z("status must be an HTTP error status, 400 to 599","INVALID");if(a!==void 0&&(typeof a!="number"||!(a>=0)||a>6e5))throw new z("delay must be milliseconds, at most 600000","INVALID");if(u!==void 0&&(!u||typeof u!="object"||Array.isArray(u)))throw new z("claims must be an object, null values remove claims","INVALID");if(n===void 0&&!o&&i===void 0&&a===void 0&&u===void 0)throw new z("A token fault needs error, status, html, delay or claims","INVALID");let l=++this.queueCounter;return this.tokenFaults.push({id:l,grant:r,error:n,description:t.description,status:i,html:!!o,delay:a||0,claims:u,remaining:fl(t.count)}),{id:l}}listClients(){return[...this.clients.values()].map(e=>this.describeClient(e))}setClient(e,t){let r=hl(e,t);return this.clients.set(r.id,r),this.describeClient(r)}deleteClient(e){if(!this.clients.delete(e))throw new z("OAuth client "+JSON.stringify(e)+" does not exist","NONEXISTENT")}setConsent(e){return this.consent=$e(e,"consent"),{consent:this.consent}}listTokens(e){return this.findTokens(e).map(t=>this.describeToken(t))}expireTokens(e){let t=this.findTokens(Object.assign({},e,{type:"access"})).filter(n=>!this.tokenProblem(n)),r=this.nowMs();return t.forEach(n=>n.expiresAt=r),{expired:t.length}}revokeTokens(e){let t=this.findTokens(e).filter(r=>!r.revoked);return t.forEach(r=>this.endToken(r,"revoked")),t.length&&this.emit("revoke",{reason:"control API",tokens:t.length}),{revoked:t.length}}info(){return{issuer:this.issuer,discovery:this.issuer?this.discoveryUrl():null,consent:this.consent,mailScope:this.mailScope,scopes:Object.keys(this.scopes),clients:this.listClients(),decisions:this.decisions.map(e=>Object.assign({},e)),tokenFaults:this.tokenFaults.map(e=>Object.assign({},e))}}registerControl(){let e=this.server.control,t=o=>({status:201,body:o}),r=()=>({deleted:!0}),n=o=>{let a={};for(let u of["user","client","type"]){let l=o.get(u);l!==null&&(a[u]=l)}return a},i=[["getOAuthInfo",()=>this.info(),"GET","/v1/oauth","OAuth provider: issuer, default consent, clients, queues",()=>e.getOAuthInfo()],["listOAuthClients",()=>this.listClients(),"GET","/v1/oauth/clients","Registered OAuth clients, without secrets",()=>e.listOAuthClients()],["setOAuthClient",(o,a)=>this.setClient(o,a),"PUT","/v1/oauth/clients/{id}","Registers or replaces an OAuth client ({ name, secret, redirectUris, consent })",({params:o,body:a})=>e.setOAuthClient(o.id,a)],["deleteOAuthClient",o=>this.deleteClient(o),"DELETE","/v1/oauth/clients/{id}","Removes an OAuth client",({params:o})=>(e.deleteOAuthClient(o.id),r())],["setOAuthConsent",o=>this.setConsent(o),"PUT","/v1/oauth/consent","Sets the default consent policy ({ consent }: prompt, approve, deny or { error, description })",({body:o})=>e.setOAuthConsent(o.consent)],["queueOAuthDecision",o=>this.queueDecision(o),"POST","/v1/oauth/decisions","Queues the decision of the next sign-ins ({ decision, client, user, count })",({body:o})=>t(e.queueOAuthDecision(o))],["listOAuthDecisions",()=>this.decisions.map(o=>Object.assign({},o)),"GET","/v1/oauth/decisions","Queued sign-in decisions",()=>e.listOAuthDecisions()],["clearOAuthDecisions",()=>{this.decisions=[]},"DELETE","/v1/oauth/decisions","Removes the queued sign-in decisions",()=>(e.clearOAuthDecisions(),r())],["queueOAuthTokenFault",o=>this.queueTokenFault(o),"POST","/v1/oauth/token-faults","Queues a fault of the token endpoint ({ grant, error, description, status, html, delay, claims, count })",({body:o})=>t(e.queueOAuthTokenFault(o))],["clearOAuthTokenFaults",()=>{this.tokenFaults=[]},"DELETE","/v1/oauth/token-faults","Removes the queued token endpoint faults",()=>(e.clearOAuthTokenFaults(),r())],["listOAuthTokens",o=>this.listTokens(o),"GET","/v1/oauth/tokens","Issued tokens (?user=&client=&type=access|refresh to choose)",({query:o})=>e.listOAuthTokens(n(o))],["expireOAuthTokens",o=>this.expireTokens(o),"POST","/v1/oauth/tokens/expire","Lets access tokens expire now ({ user, client, token })",({body:o})=>e.expireOAuthTokens(o)],["revokeOAuthTokens",o=>this.revokeTokens(o),"POST","/v1/oauth/tokens/revoke","Revokes access and refresh tokens ({ user, client, token, type })",({body:o})=>e.revokeOAuthTokens(o)]];for(let[o,a,u,l,c,f]of i)e.register(o,a,[{method:u,path:l,summary:c,handler:f}])}};function To(s,e){for(let t of e)if(s[t]!==void 0&&typeof s[t]!="string")throw new z(t+" must be a string","INVALID")}function fl(s){if(s===void 0)return 1;if(!Number.isInteger(s)||s<1)throw new z("count must be a positive integer","INVALID");return s}function te(s,e,t=400,r){return{status:t,body:{error:s,error_description:so(e)},headers:r}}E();E();var ie=s=>String(s).replace(/[&<>"']/g,e=>({"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"})[e]),So=s=>s?Jt(s):"server default",kd=`
45
45
  :root{color-scheme:light dark;--bg:#eef1f6;--card:#fff;--text:#1b2430;--muted:#5d6877;--line:#d9dfe8;--accent:#2457c5;--accent-text:#fff;--accent-soft:#e8eefc;--ok:#1a7f37;--ok-soft:#e6f4ea;--warn:#8a5a00;--warn-soft:#fff4d6;--bad:#b42318;--bad-soft:#fdecea;--code:#f0f2f5;--focus:#2457c5}
46
46
  @media (prefers-color-scheme:dark){:root{--bg:#0d1117;--card:#161b22;--text:#e4e9f0;--muted:#9aa6b6;--line:#2b3440;--accent:#6e9bff;--accent-text:#0d1117;--accent-soft:#1b2640;--ok:#4cc06b;--ok-soft:#14281b;--warn:#e3b341;--warn-soft:#2d2411;--bad:#ff7b6e;--bad-soft:#331a18;--code:#1f252e;--focus:#8db0ff}}
47
47
  *{box-sizing:border-box}
@@ -74,7 +74,8 @@ ul.scopes{list-style:none;padding:0;margin:0 0 12px;border:1px solid var(--line)
74
74
  ul.scopes li{display:flex;gap:10px;padding:8px 12px;border-top:1px solid var(--line);align-items:baseline}
75
75
  ul.scopes li:first-child{border-top:0}
76
76
  .ck{color:var(--ok);font-weight:700}
77
- .raw{margin-left:auto;font-family:ui-monospace,Menlo,monospace;font-size:11.5px;color:var(--muted);text-align:right;overflow-wrap:anywhere}
77
+ ul.scopes li>span:nth-child(2){flex:1;min-width:0}
78
+ .raw{margin-left:auto;font-family:ui-monospace,Menlo,monospace;font-size:11.5px;color:var(--muted);text-align:right;white-space:nowrap}
78
79
  .redir{font-size:13px;color:var(--muted);margin:0 0 16px;overflow-wrap:anywhere}
79
80
  .btns{display:flex;flex-direction:row-reverse;gap:10px;margin:0 0 12px}
80
81
  button{flex:1;font:inherit;font-weight:600;padding:10px 14px;border-radius:8px;border:1px solid var(--line);background:var(--card);color:var(--text);cursor:pointer;text-align:center;text-decoration:none}
@@ -98,9 +99,10 @@ table{width:100%;border-collapse:collapse;font-size:13.5px;margin:0 0 6px}
98
99
  th,td{text-align:left;padding:7px 8px;border-bottom:1px solid var(--line);vertical-align:top}
99
100
  th{font-size:12px;color:var(--muted);text-transform:uppercase;letter-spacing:.04em}
100
101
  footer{border-top:1px solid var(--line);padding:12px 26px;font-size:12.5px;color:var(--muted)}
102
+ footer a{color:var(--accent)}
101
103
  @media (max-width:480px){body{padding:0}main{border-radius:0;border-left:0;border-right:0}.body{padding:20px 16px}footer{padding:12px 16px}}
102
- `,dl=["#7c5cf6","#0e9f6e","#d9480f","#1c7ed6","#c2255c","#5c7cfa","#2b8a3e"];function Pd(s){let e=0;for(let r of s)e=e*31+(r.codePointAt(0)||0)>>>0;let t=(s.match(/[\p{L}\p{N}]/u)||["?"])[0].toUpperCase();return'<span class="av" aria-hidden="true" style="background:'+dl[e%dl.length]+'">'+ie(t)+"</span>"}function Io(s,e,t={}){return'<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><meta name="robots" content="noindex"><title>'+ie(s)+" - ImapKit</title><style>"+kd+"</style></head><body><main"+(t.wide?' class="wide"':"")+'><div class="ribbon" role="note">IMAPKIT TEST SERVER \xB7 NOT A REAL SIGN-IN</div><div class="body">'+e+"</div>"+(t.footer?"<footer>"+t.footer+"</footer>":"")+"</main></body></html>"}function Oo(s){let e=s;try{e=new URL(s).host}catch{}return'<div class="brand"><span class="logo" aria-hidden="true">IK</span><span>ImapKit sign-in \xB7 '+ie(e)+"</span></div>"}var Fd=s=>'<span class="tag '+s.level+'">'+s.level+"</span>",_d=[["error:access_denied","Return access_denied"],["error:invalid_scope","Return invalid_scope"],["error:server_error","Return server_error"],["error:temporarily_unavailable","Return temporarily_unavailable"],["error:consent_required","Return consent_required"],["error:login_required","Return login_required"],["wrong-state","Approve, but redirect with a wrong state"],["wrong-iss","Approve, but redirect with a wrong iss"],["no-redirect","Do not redirect (let the client time out)"]];function pl(s){let{request:e,users:t,scopes:r,issuer:n}=s,i=e.client,o=e.hintUser||t[0]&&t[0].name,a=e.checks.slice();o&&!o.includes("@")&&a.push({level:"note",text:"user name "+JSON.stringify(o)+" has no @: clients that take the email claim as an address may refuse it"}),e.prompt.length&&a.push({level:"note",text:"prompt="+e.prompt.join(" ")+": the consent page is shown because the policy is prompt ("+e.source+")"}),e.ignored.length&&a.push({level:"note",text:"ignored parameters: "+e.ignored.join(", ")});let u=a.filter(d=>d.level==="ok").length,l=a.length-u,c=a.some(d=>d.level==="warn"),f=e.redirectUri,p=!1;try{let d=new URL(e.redirectUri);f=d.origin!=="null"?d.origin+d.pathname:e.redirectUri,p=d.protocol==="http:"&&ke(d.hostname)}catch{}let y=t.length?t.map(d=>{let E=[d.name===e.hintUser?'<span class="tag info">login_hint</span>':"",d.consent?'<span class="tag '+(d.consent==="approve"?"ok":"bad")+'">auto: '+ie(So(d.consent))+"</span>":""].join("");return'<label class="acct"><input type="radio" name="user" value="'+ie(d.name)+'"'+(d.name===o?" checked":"")+" required>"+Pd(d.displayName||d.name)+'<span class="who"><span class="nm">'+ie(d.displayName||d.name)+"</span>"+(d.displayName?'<br><span class="em">'+ie(d.name)+"</span>":"")+"</span>"+E+"</label>"}).join(""):'<p class="muted">This server has no users, so only Deny is possible.</p>',A=e.scope.map(d=>'<li><span class="ck" aria-hidden="true">\u2713</span><span>'+ie(r[d]||d)+'</span><span class="raw">'+ie(d)+"</span></li>").join(""),m=["client_id="+i.id,"response_type=code","scope="+e.scope.join(" "),e.codeChallengeMethod?"code_challenge_method="+e.codeChallengeMethod:"",e.prompt.length?"prompt="+e.prompt.join(" "):"",e.loginHint!==void 0?"login_hint="+e.loginHint:""].filter(Boolean),h=Oo(n)+"<h1>"+ie(i.name)+' wants to access your mailbox</h1><p class="muted small">Choose the account to sign in as. No password needed.'+(i.name!==i.id?" Client ID <code>"+ie(i.id)+"</code>.":"")+'</p><form method="post" action="/authorize/decision"><input type="hidden" name="request" value="'+ie(e.id)+'"><fieldset><legend>Account</legend>'+y+'</fieldset><fieldset><legend>It will be able to</legend><ul class="scopes">'+A+'</ul></fieldset><p class="redir">Returns to <strong>'+ie(f)+"</strong> "+(p?'<span class="tag ok">loopback</span>':"")+'</p><div class="btns">'+(t.length?'<button class="primary" type="submit" name="action" value="allow">Allow</button>':"")+'<button type="submit" name="action" value="deny" formnovalidate>Deny</button></div><label class="remember"><input type="checkbox" name="remember" value="on"> Remember my choice for this app until the server restarts</label><details'+(c?" open":"")+"><summary>Request details ("+u+" passed"+(l?", "+l+" to look at":"")+')</summary><ul class="checks">'+a.map(d=>"<li>"+Fd(d)+"<span>"+ie(d.text)+"</span></li>").join("")+'</ul><p class="kv">'+ie(m.join(" \xB7 "))+'</p><p class="kv">redirect_uri='+ie(e.redirectUri)+'</p></details><details><summary>Other outcomes</summary><p class="muted small" style="margin:8px 0 0">Answer this sign-in with an error or a broken redirect, to test how the client handles it.</p><div class="row"><select id="outcome" name="outcome" aria-label="Outcome">'+_d.map(([d,E])=>'<option value="'+d+'">'+ie(E)+"</option>").join("")+'</select></div><div class="row"><input type="text" name="description" aria-label="error_description" placeholder="error_description (optional)" maxlength="300"><button type="submit" name="action" value="outcome" formnovalidate>Send</button></div></details></form>';return Io("Sign in to "+i.name,h,{footer:"Decision source if not answered here: "+ie(e.source)+". This request stays open for 10 minutes."})}function ml(s,e){let t=Oo(e)+'<div class="mark '+s.tone+'" aria-hidden="true">'+(s.tone==="error"?"!":"i")+"</div><h1>"+ie(s.title)+'</h1><p class="muted">'+ie(s.message)+"</p>"+(s.details||[]).map(r=>"<pre>"+ie(r)+"</pre>").join("");return Io(s.title,t,{footer:s.tone==="error"?"The client was not redirected: there was no safe place to send the answer to.":"You can close this tab."})}function gl(s){let{issuer:e,clients:t,users:r}=s,n=["/.well-known/openid-configuration","/authorize","/token","/userinfo","/jwks","/revoke"],i=Oo(e)+'<h1>ImapKit OAuth 2.0 / OpenID Connect provider</h1><p class="muted">A test identity provider for mail clients. Tokens it issues log in to this ImapKit server over IMAP (XOAUTH2, OAUTHBEARER) and SMTP (AUTH XOAUTH2) with the <code>'+ie(s.mailScope)+"</code> scope. Default consent policy: <strong>"+ie(So(s.consent))+"</strong>.</p><h2>Issuer</h2><pre>"+ie(e)+"</pre><h2>Clients</h2><table><thead><tr><th>Client ID</th><th>Name</th><th>Type</th><th>Consent</th></tr></thead><tbody>"+t.map(o=>"<tr><td><code>"+ie(o.id)+"</code></td><td>"+ie(o.name)+"</td><td>"+(o.secret===null?"public":"confidential")+"</td><td>"+ie(So(o.consent))+"</td></tr>").join("")+'</tbody></table><h2>Users</h2><p class="small">'+(r.length?r.map(o=>"<code>"+ie(o.name)+"</code>").join(" "):"none")+'</p><h2>Endpoints</h2><p class="small">'+n.map(o=>"<code>"+ie(o)+"</code>").join(" ")+"</p>";return Io("OAuth provider",i,{wide:!0,footer:"Documentation: https://imapkit.com/docs/guides/oauth"})}var Gd=64*1024,Je=class extends Error{constructor(e,t){super(t),this.status=e}};async function yr(s){if(!/^application\/x-www-form-urlencoded\b/i.test(s.headers["content-type"]||""))throw s.resume(),new Je(415,"The body must be application/x-www-form-urlencoded (RFC 6749 section 4.1.3)");let e=await mo(s,Gd,()=>new Je(413,"The body is larger than 64 KiB"));return new URLSearchParams(e.toString("utf-8"))}var xo={"Cache-Control":"no-store",Pragma:"no-cache","X-Content-Type-Options":"nosniff","Referrer-Policy":"no-referrer"},El={"Access-Control-Allow-Origin":"*","Access-Control-Allow-Headers":"Authorization, Content-Type","Access-Control-Allow-Methods":"GET, POST, OPTIONS"};function Xd(s){try{let e=new URL(s.redirectUri);return"'self' "+(e.origin!=="null"?e.origin:e.protocol)}catch{return"'self'"}}function br(s,e,t,r="'none'"){s.writeHead(e,{...xo,"Content-Type":"text/html; charset=utf-8","Content-Length":b.Buffer.byteLength(t),"Content-Security-Policy":"default-src 'none'; style-src 'unsafe-inline'; base-uri 'none'; frame-ancestors 'none'; form-action "+r,"X-Frame-Options":"DENY"}),s.end(t)}function ft(s,e){if(e.htmlError){br(s,e.status,"<!doctype html><title>Error</title><h1>Something went wrong</h1>");return}let t=JSON.stringify(e.body);s.writeHead(e.status,{...xo,...El,...e.headers||{},"Content-Type":"application/json; charset=utf-8","Content-Length":b.Buffer.byteLength(t)}),s.end(t)}function jd(s,e,t){if(!s||s==="null"||s===new URL(e).origin)return!0;try{let r=new URL(s);return ke(r.hostname)&&r.host===t}catch{return!1}}function Al(s,e){let t=(o,a,u)=>{if(a.type==="redirect")o.writeHead(u,{...xo,Location:a.location,"Content-Type":"text/plain; charset=utf-8"}),o.end("Redirecting to "+a.location+`
103
- `);else if(a.type==="page")br(o,a.page.status,ml(a.page,s.issuer));else{let l=pl({request:a.request,users:s.pageUsers(),scopes:s.scopes,issuer:s.issuer});br(o,200,l,Xd(a.request))}},r=o=>{if(!ke(e.host))return;let a=(o.headers.host||"").replace(/:\d+$/,""),u="";try{u=new URL(s.issuer).hostname}catch{}if(!ke(a)&&a.replace(/^\[|\]$/g,"")!==u.replace(/^\[|\]$/g,""))throw new Je(421,"Requests must use a loopback host name or the host of the issuer")},n=async(o,a)=>{r(o);let u=new URL(o.url||"/","http://localhost"),l=(o.method||"GET").toUpperCase(),c=l+" "+u.pathname;if(l==="OPTIONS")return a.writeHead(204,{...El,"Access-Control-Max-Age":"600"}),a.end();switch(c){case"GET /":return br(a,200,gl({issuer:s.issuer,consent:s.consent,clients:[...s.clients.values()],users:s.pageUsers(),mailScope:s.mailScope}));case"GET /.well-known/openid-configuration":case"GET /.well-known/oauth-authorization-server":return ft(a,{status:200,body:s.metadata()});case"GET /jwks":return ft(a,{status:200,body:s.jwks()});case"GET /authorize":return t(a,s.authorize(u.searchParams),302);case"POST /authorize":return t(a,s.authorize(await yr(o)),303);case"POST /authorize/decision":{if(!jd(o.headers.origin,s.issuer,o.headers.host))throw new Je(403,"The consent form must come from the consent page");return t(a,s.answerConsent(await yr(o)),303)}case"POST /token":return ft(a,await s.token(await yr(o),o.headers.authorization));case"POST /revoke":return ft(a,s.revoke(await yr(o),o.headers.authorization));case"GET /userinfo":return ft(a,s.userinfo(o.headers.authorization));case"POST /userinfo":return o.resume(),ft(a,s.userinfo(o.headers.authorization));default:{let f=["/","/authorize","/authorize/decision","/token","/revoke","/userinfo","/jwks"],p=u.pathname.startsWith("/.well-known/");throw new Je(f.includes(u.pathname)||p?405:404,f.includes(u.pathname)?"Method not allowed":"Not found")}}},i=(o,a)=>{n(o,a).catch(u=>{let l=u instanceof Je?u.status:500;a.headersSent||ft(a,{status:l,body:{error:l===500?"server_error":"invalid_request",error_description:u.message}})})};return e.secure?ce.createServer(e.credentials,i):ce.createServer(i)}g();var yl=`-----BEGIN PRIVATE KEY-----
104
+ `,dl=["#7c5cf6","#0e9f6e","#d9480f","#1c7ed6","#c2255c","#5c7cfa","#2b8a3e"];function Pd(s){let e=0;for(let r of s)e=e*31+(r.codePointAt(0)||0)>>>0;let t=(s.match(/[\p{L}\p{N}]/u)||["?"])[0].toUpperCase();return'<span class="av" aria-hidden="true" style="background:'+dl[e%dl.length]+'">'+ie(t)+"</span>"}function Io(s,e,t={}){return'<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><meta name="robots" content="noindex"><title>'+ie(s)+" - ImapKit</title><style>"+kd+"</style></head><body><main"+(t.wide?' class="wide"':"")+'><div class="ribbon" role="note">IMAPKIT TEST SERVER \xB7 NOT A REAL SIGN-IN</div><div class="body">'+e+"</div>"+(t.footer?"<footer>"+t.footer+"</footer>":"")+"</main></body></html>"}function Oo(s){let e=s;try{e=new URL(s).host}catch{}return'<div class="brand"><span class="logo" aria-hidden="true">IK</span><span>ImapKit sign-in \xB7 '+ie(e)+"</span></div>"}var Fd=s=>'<span class="tag '+s.level+'">'+s.level+"</span>",_d=[["error:access_denied","Return access_denied"],["error:invalid_scope","Return invalid_scope"],["error:server_error","Return server_error"],["error:temporarily_unavailable","Return temporarily_unavailable"],["error:consent_required","Return consent_required"],["error:login_required","Return login_required"],["wrong-state","Approve, but redirect with a wrong state"],["wrong-iss","Approve, but redirect with a wrong iss"],["no-redirect","Do not redirect (let the client time out)"]];function pl(s){let{request:e,users:t,scopes:r,issuer:n}=s,i=e.client,o=e.hintUser||t[0]&&t[0].name,a=e.checks.slice();o&&!o.includes("@")&&a.push({level:"note",text:"user name "+JSON.stringify(o)+" has no @: clients that take the email claim as an address may refuse it"}),e.prompt.length&&a.push({level:"note",text:"prompt="+e.prompt.join(" ")+": the consent page is shown because the policy is prompt ("+e.source+")"}),e.ignored.length&&a.push({level:"note",text:"ignored parameters: "+e.ignored.join(", ")});let u=a.filter(g=>g.level==="ok").length,l=a.filter(g=>g.level==="warn").length,c=a.length-u-l,f=a.some(g=>g.level==="warn"),p=e.redirectUri,y=!1;try{let g=new URL(e.redirectUri);p=g.origin!=="null"?g.origin+g.pathname:e.redirectUri,y=g.protocol==="http:"&&ke(g.hostname)}catch{}let A=t.length?t.map(g=>{let T=[g.name===e.hintUser?'<span class="tag info">login_hint</span>':"",g.consent?'<span class="tag '+(g.consent==="approve"?"ok":"bad")+'">auto: '+ie(So(g.consent))+"</span>":""].join("");return'<label class="acct"><input type="radio" name="user" value="'+ie(g.name)+'"'+(g.name===o?" checked":"")+" required>"+Pd(g.displayName||g.name)+'<span class="who"><span class="nm">'+ie(g.displayName||g.name)+"</span>"+(g.displayName?'<br><span class="em">'+ie(g.name)+"</span>":"")+"</span>"+T+"</label>"}).join(""):'<p class="muted">This server has no users, so only Deny is possible.</p>',m=e.scope.map(g=>'<li><span class="ck" aria-hidden="true">\u2713</span><span>'+ie(r[g]||g)+'</span><span class="raw">'+ie(g)+"</span></li>").join(""),h=["client_id="+i.id,"response_type=code","scope="+e.scope.join(" "),e.codeChallengeMethod?"code_challenge_method="+e.codeChallengeMethod:"",e.prompt.length?"prompt="+e.prompt.join(" "):"",e.loginHint!==void 0?"login_hint="+e.loginHint:""].filter(Boolean),d=Oo(n)+"<h1>"+ie(i.name)+' wants to access your mailbox</h1><p class="muted small">Choose the account to sign in as. No password needed.'+(i.name!==i.id?" Client ID <code>"+ie(i.id)+"</code>.":"")+'</p><form method="post" action="/authorize/decision"><input type="hidden" name="request" value="'+ie(e.id)+'"><fieldset><legend>Account</legend>'+A+'</fieldset><fieldset><legend>It will be able to</legend><ul class="scopes">'+m+'</ul></fieldset><p class="redir">Returns to <strong>'+ie(p)+"</strong> "+(y?'<span class="tag ok">loopback</span>':"")+'</p><div class="btns">'+(t.length?'<button class="primary" type="submit" name="action" value="allow">Allow</button>':"")+'<button type="submit" name="action" value="deny" formnovalidate>Deny</button></div><label class="remember"><input type="checkbox" name="remember" value="on"> Remember my choice for this app until the server restarts</label><details'+(f?" open":"")+"><summary>Request details ("+u+" passed"+(l?", "+l+(l===1?" warning":" warnings"):"")+(c?", "+c+(c===1?" note":" notes"):"")+')</summary><ul class="checks">'+a.map(g=>"<li>"+Fd(g)+"<span>"+ie(g.text)+"</span></li>").join("")+'</ul><p class="kv">'+ie(h.join(" \xB7 "))+'</p><p class="kv">redirect_uri='+ie(e.redirectUri)+'</p></details><details><summary>Other outcomes</summary><p class="muted small" style="margin:8px 0 0">Answer this sign-in with an error or a broken redirect, to test how the client handles it.</p><div class="row"><select id="outcome" name="outcome" aria-label="Outcome">'+_d.map(([g,T])=>'<option value="'+g+'">'+ie(T)+"</option>").join("")+'</select></div><div class="row"><input type="text" name="description" aria-label="error_description" placeholder="error_description (optional)" maxlength="300"><button type="submit" name="action" value="outcome" formnovalidate>Send</button></div></details></form>';return Io("Sign in to "+i.name,d,{footer:"Shown because the sign-in policy is prompt ("+ie(e.source)+"). This request stays open for 10 minutes."})}function ml(s,e){let t=Oo(e)+'<div class="mark '+s.tone+'" aria-hidden="true">'+(s.tone==="error"?"!":"i")+"</div><h1>"+ie(s.title)+'</h1><p class="muted">'+ie(s.message)+"</p>"+(s.details||[]).map(r=>"<pre>"+ie(r)+"</pre>").join("");return Io(s.title,t,{footer:s.tone==="error"?"The client was not redirected: there was no safe place to send the answer to.":"You can close this tab."})}function gl(s){let{issuer:e,clients:t,users:r}=s,n=["/.well-known/openid-configuration","/authorize","/token","/userinfo","/jwks","/revoke"],i=Oo(e)+'<h1>ImapKit OAuth 2.0 / OpenID Connect provider</h1><p class="muted">A test identity provider for mail clients. Tokens it issues log in to this ImapKit server over IMAP (XOAUTH2, OAUTHBEARER) and SMTP (AUTH XOAUTH2) with the <code>'+ie(s.mailScope)+"</code> scope. Default consent policy: <strong>"+ie(So(s.consent))+"</strong>.</p><h2>Issuer</h2><pre>"+ie(e)+"</pre><h2>Clients</h2><table><thead><tr><th>Client ID</th><th>Name</th><th>Type</th><th>Consent</th></tr></thead><tbody>"+t.map(o=>"<tr><td><code>"+ie(o.id)+"</code></td><td>"+ie(o.name)+"</td><td>"+(o.secret===null?"public":"confidential")+"</td><td>"+ie(So(o.consent))+"</td></tr>").join("")+'</tbody></table><h2>Users</h2><p class="small">'+(r.length?r.map(o=>"<code>"+ie(o.name)+"</code>").join(" "):"none")+'</p><h2>Endpoints</h2><p class="small">'+n.map(o=>"<code>"+ie(o)+"</code>").join(" ")+"</p>";return Io("OAuth provider",i,{wide:!0,footer:'Documentation: <a href="https://imapkit.com/docs/guides/oauth" rel="noreferrer">imapkit.com/docs/guides/oauth</a>'})}var Gd=64*1024,Je=class extends Error{constructor(e,t){super(t),this.status=e}};async function yr(s){if(!/^application\/x-www-form-urlencoded\b/i.test(s.headers["content-type"]||""))throw s.resume(),new Je(415,"The body must be application/x-www-form-urlencoded (RFC 6749 section 4.1.3)");let e=await mo(s,Gd,()=>new Je(413,"The body is larger than 64 KiB"));return new URLSearchParams(e.toString("utf-8"))}var xo={"Cache-Control":"no-store",Pragma:"no-cache","X-Content-Type-Options":"nosniff","Referrer-Policy":"no-referrer"},El={"Access-Control-Allow-Origin":"*","Access-Control-Allow-Headers":"Authorization, Content-Type","Access-Control-Allow-Methods":"GET, POST, OPTIONS"};function Xd(s){try{let e=new URL(s.redirectUri);return"'self' "+(e.origin!=="null"?e.origin:e.protocol)}catch{return"'self'"}}function br(s,e,t,r="'none'"){s.writeHead(e,{...xo,"Content-Type":"text/html; charset=utf-8","Content-Length":b.Buffer.byteLength(t),"Content-Security-Policy":"default-src 'none'; style-src 'unsafe-inline'; base-uri 'none'; frame-ancestors 'none'; form-action "+r,"X-Frame-Options":"DENY"}),s.end(t)}function ft(s,e){if(e.htmlError){br(s,e.status,"<!doctype html><title>Error</title><h1>Something went wrong</h1>");return}let t=JSON.stringify(e.body);s.writeHead(e.status,{...xo,...El,...e.headers||{},"Content-Type":"application/json; charset=utf-8","Content-Length":b.Buffer.byteLength(t)}),s.end(t)}function jd(s,e,t){if(!s||s==="null"||s===new URL(e).origin)return!0;try{let r=new URL(s);return ke(r.hostname)&&r.host===t}catch{return!1}}function Al(s,e){let t=(o,a,u)=>{if(a.type==="redirect")o.writeHead(u,{...xo,Location:a.location,"Content-Type":"text/plain; charset=utf-8"}),o.end("Redirecting to "+a.location+`
105
+ `);else if(a.type==="page")br(o,a.page.status,ml(a.page,s.issuer));else{let l=pl({request:a.request,users:s.pageUsers(),scopes:s.scopes,issuer:s.issuer});br(o,200,l,Xd(a.request))}},r=o=>{if(!ke(e.host))return;let a=(o.headers.host||"").replace(/:\d+$/,""),u="";try{u=new URL(s.issuer).hostname}catch{}if(!ke(a)&&a.replace(/^\[|\]$/g,"")!==u.replace(/^\[|\]$/g,""))throw new Je(421,"Requests must use a loopback host name or the host of the issuer")},n=async(o,a)=>{r(o);let u=new URL(o.url||"/","http://localhost"),l=(o.method||"GET").toUpperCase(),c=l+" "+u.pathname;if(l==="OPTIONS")return a.writeHead(204,{...El,"Access-Control-Max-Age":"600"}),a.end();switch(c){case"GET /":return br(a,200,gl({issuer:s.issuer,consent:s.consent,clients:[...s.clients.values()],users:s.pageUsers(),mailScope:s.mailScope}));case"GET /.well-known/openid-configuration":case"GET /.well-known/oauth-authorization-server":return ft(a,{status:200,body:s.metadata()});case"GET /jwks":return ft(a,{status:200,body:s.jwks()});case"GET /authorize":return t(a,s.authorize(u.searchParams),302);case"POST /authorize":return t(a,s.authorize(await yr(o)),303);case"POST /authorize/decision":{if(!jd(o.headers.origin,s.issuer,o.headers.host))throw new Je(403,"The consent form must come from the consent page");return t(a,s.answerConsent(await yr(o)),303)}case"POST /token":return ft(a,await s.token(await yr(o),o.headers.authorization));case"POST /revoke":return ft(a,s.revoke(await yr(o),o.headers.authorization));case"GET /userinfo":return ft(a,s.userinfo(o.headers.authorization));case"POST /userinfo":return o.resume(),ft(a,s.userinfo(o.headers.authorization));default:{let f=["/","/authorize","/authorize/decision","/token","/revoke","/userinfo","/jwks"],p=u.pathname.startsWith("/.well-known/");throw new Je(f.includes(u.pathname)||p?405:404,f.includes(u.pathname)?"Method not allowed":"Not found")}}},i=(o,a)=>{n(o,a).catch(u=>{let l=u instanceof Je?u.status:500;a.headersSent||ft(a,{status:l,body:{error:l===500?"server_error":"invalid_request",error_description:u.message}})})};return e.secure?ce.createServer(e.credentials,i):ce.createServer(i)}E();var yl=`-----BEGIN PRIVATE KEY-----
104
106
  MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQDN0THQ8qpf3mMo
105
107
  NlVzVvjfsw/QHo22ojmmUO+3QjZDeB7mSmniyGOFw0M8f2g3FM0Kfa51rKMYXWQV
106
108
  cqRTDFkk9zBnCagFIWCi2DI4VgArzWlu4TqOHfRIHcbAH1bTKVh5KnVmQA6j6leK
@@ -148,7 +150,7 @@ ZG83/H0UYur8lN2JxV4ITRovftmtruiVNw3mXH5BZCIsoFAEtf3hssn6rekfEOfc
148
150
  4vty2NskN112OLQzLK1Oq3dl0C6Ns1MdIoelAHrFdeM3O03Y0D2R+PlNw1cU55if
149
151
  EF3engvuSVRtcV8eyxM=
150
152
  -----END CERTIFICATE-----
151
- `;g();g();var Tr=Ut(ds()),tI=Tr.default.once;var Ir=class extends Tr.default{constructor(){super(),this.peer=null,this.destroyed=!1,this.encrypted=!1,this._paused=!1,this._ending=!1,this._encoding=null,this._received=[]}write(e,t,r){if(typeof t=="function"&&(r=t,t=void 0),this.destroyed||this._ending)return!1;let n=typeof e=="string"?b.Buffer.from(e,t||"utf8"):b.Buffer.from(e.buffer,e.byteOffset,e.byteLength);return Sr(()=>{this.peer?.deliver(n),r?.()}),!0}end(e){return e!==void 0&&this.write(e),this.destroyed||this._ending?this:(this._ending=!0,Sr(()=>{let t=this.peer;t&&!t.destroyed&&(t.emit("end"),t.close()),this.close()}),this)}destroy(e){if(this.destroyed)return this;let t=this.peer;return this.close(e),t&&!t.destroyed&&t.close(),this}resetAndDestroy(){let e=this.peer;if(this.destroy(),e){let t=new Error("read ECONNRESET");t.code="ECONNRESET",Sr(()=>e.emit("error",t))}return this}startTls(e){this.encrypted=!0,this.peer&&(this.peer.encrypted=!0),e()}pause(){return this._paused=!0,this}resume(){for(this._paused=!1;this._received.length&&!this._paused&&!this.destroyed;)this.emitData(this._received.shift());return this}setEncoding(e){return this._encoding=e,this}deliver(e){if(!this.destroyed){if(this._paused){this._received.push(e);return}this.emitData(e)}}emitData(e){this.emit("data",this._encoding?e.toString(this._encoding):e)}close(e){this.destroyed||(this.destroyed=!0,this._received=[],Sr(()=>{e&&this.emit("error",e),this.emit("close",!!e)}))}};function Tl(){let s=new Ir,e=new Ir;return s.peer=e,e.peer=s,[s,e]}var Or=[];function Sr(s){Or.push(s),Or.length===1&&R(qd)}function qd(){let s=Or.splice(0,Or.length);for(let e of s)e()}g();var de=["greeting","command","input","response","continuation","quiet"],Co=["greeting","response","continuation"],Sl={on:de,command:["command","input","response","continuation","quiet"],tag:["command","input","response","continuation","quiet"],description:["response","continuation"],session:de,user:de,state:de,mailbox:de,untagged:["response"],match:de,when:de,nth:de,times:de,chance:de,quietFor:["quiet"],mutate:["response","continuation"],literals:["response"],defer:["response"],send:de,before:Co,after:Co,run:["command","input"],drop:["greeting","command","input","response","continuation"],delay:["greeting","command","response","continuation"],chunk:de,chunkDelay:de,truncate:de,close:de},Il=["mutate","literals","defer","send","before","after","run","drop","delay","chunk","truncate","close"],Qd=10,Ol=["command","description","session","state","user","mailbox"];function ss(s,e){if(s===void 0)return null;let t=typeof s=="function"?s(e):s;if(b.Buffer.isBuffer(t))return t;let r=String(t).replace(/\$TAG/g,()=>e.tag||"*");return b.Buffer.from(r,/[\u0100-\uffff]/.test(r)?"utf-8":"binary")}function xl(s){if(!s||typeof s!="object")throw new TypeError("A script rule must be an object");if(!de.includes(s.on))throw new TypeError('Script rule "on" must be one of '+de.join(", "));for(let e of Object.keys(s)){let t=Object.hasOwn(Sl,e)?Sl[e]:null;if(!t)throw new TypeError('Unknown script rule option "'+e+'"');if(!t.includes(s.on))throw new TypeError('Script rule option "'+e+'" can not be used with "on": "'+s.on+'"')}if(s.on==="quiet"&&!(Number.isInteger(s.quietFor)&&s.quietFor>0))throw new TypeError('A quiet rule needs "quietFor", a positive number of milliseconds');if(s.chance!==void 0&&!(typeof s.chance=="number"&&s.chance>=0&&s.chance<=1))throw new TypeError('Script rule option "chance" must be a number from 0 to 1');if(!Il.some(e=>s[e]!==void 0&&s[e]!==!1))throw new TypeError("A script rule needs an action ("+Il.join(", ")+")");if(s.drop&&(s.send!==void 0||s.run))throw new TypeError('Script rule option "drop" can not be combined with "send" or "run"');if(s.run&&(s.close||s.truncate!==void 0))throw new TypeError('Script rule option "run" can not be combined with "close" or "truncate"');if(s.chunkDelay!==void 0&&s.chunk===void 0)throw new TypeError('Script rule option "chunkDelay" needs "chunk"');if(!Co.includes(s.on)&&s.send===void 0&&(s.chunk!==void 0||s.truncate!==void 0))throw new TypeError('Script rule options "chunk" and "truncate" need "send" with "on": "'+s.on+'"');for(let e of["nth","times","chunk"])if(s[e]!==void 0&&!(Number.isInteger(s[e])&&s[e]>0))throw new TypeError('Script rule option "'+e+'" must be a positive integer');for(let e of["delay","chunkDelay","truncate"])if(!(e==="chunkDelay"&&s[e]==="tick")&&s[e]!==void 0&&!(Number.isInteger(s[e])&&s[e]>=0))throw new TypeError('Script rule option "'+e+'" must be a non-negative integer');for(let e of["when","mutate"])if(s[e]!==void 0&&typeof s[e]!="function")throw new TypeError('Script rule option "'+e+'" must be a function');for(let e of["send","before","after"]){let t=s[e];if(t!==void 0&&typeof t!="string"&&typeof t!="function"&&!b.Buffer.isBuffer(t))throw new TypeError('Script rule option "'+e+'" must be a string, a Buffer or a function')}if(s.literals!==void 0&&typeof s.literals!="boolean")throw new TypeError('Script rule option "literals" must be true or false');if(s.defer!==void 0){if(s.defer!=="tagged"&&s.defer!=="next")throw new TypeError('Script rule option "defer" must be "tagged" or "next"');if(s.untagged!==!0)throw new TypeError('Script rule option "defer" needs "untagged": true');let e=["drop","delay","chunk","truncate","close"].find(t=>s[t]!==void 0&&s[t]!==!1);if(e)throw new TypeError('Script rule option "defer" can not be combined with "'+e+'"')}if(s.close!==void 0&&typeof s.close!="boolean"&&s.close!=="reset")throw new TypeError('Script rule option "close" must be true, false or "reset"');if(s.match===void 0)return null;if(s.match instanceof RegExp)return new RegExp(s.match.source,s.match.flags.replace(/[gy]/g,""));if(typeof s.match!="string")throw new TypeError('Script rule option "match" must be a string or a RegExp');try{return new RegExp(s.match)}catch(e){throw new TypeError('Script rule option "match" is not a valid regular expression: '+e.message,{cause:e})}}var xr=class{constructor(e,t){this.server=e,this.entries=[],this.ruleCounter=0;let r=e.options.scriptSeed,n=()=>{this.random=Ss(typeof r=="number"?r:Math.floor(Math.random()*4294967295))};n(),e.on("reset",n),this.watched=new Set,t&&this.add(t)}get rules(){return this.entries.slice()}add(e){if(Array.isArray(e)){let t=e.map(xl);return e.map((r,n)=>this.addEntry(r,t[n]))}return this.addEntry(e,xl(e))}clear(){this.setEntries([])}watches(e){return this.watched.has(e)}check(e,t,r){if(!this.watched.has(t))return null;let n=Yd(e,t,r),i=this.find(n);return i?{rule:i,context:n}:null}setEntries(e){this.entries=e,this.watched=new Set(e.map(t=>t.rule.on)),this.watched.has("quiet")&&this.server.connections?.forEach(t=>t.watchQuiet())}nextQuiet(e){let t=null;for(let r of this.entries){let n=r.rule.quietFor;r.rule.on==="quiet"&&n!==void 0&&n>e&&(t===null||n<t)&&(t=n)}return t}addEntry(e,t){let r=Object.freeze(Object.assign({},e)),n={};for(let o of Ol)if(r[o]!==void 0){let a=[].concat(r[o]);n[o]=new Set(o==="command"?a.map(u=>String(u).toUpperCase()):a)}let i={id:++this.ruleCounter,rule:r,match:t,sets:n,matched:0,hits:0,remove:()=>this.setEntries(this.entries.filter(o=>o!==i))};return this.setEntries(this.entries.concat(i)),i}find(e){for(let t of this.entries){let r=t.rule;if(!(r.on!==e.event||!this.matches(t,e))&&(t.matched++,!(t.matched<(r.nth||1)||r.times!==void 0&&t.hits>=r.times)&&!(r.chance!==void 0&&this.random()>=r.chance)))return t.hits++,this.server.emit("script",{rule:r,event:e.event,session:e.session,tag:e.tag,command:e.command}),r}return null}matches(e,t){let r=e.rule;for(let n of Ol){let i=e.sets[n],o=t[n];if(i&&(o==null||!i.has(o)))return!1}return r.tag!==void 0&&(t.tag===null||(r.tag instanceof RegExp?!r.tag.test(t.tag):r.tag!==t.tag))||r.untagged!==void 0&&r.untagged!==(!t.response||t.response.tag==="*")||r.quietFor!==void 0&&(t.quiet||0)<r.quietFor||e.match&&!e.match.test(t.data)?!1:!r.when||!!r.when(t)}};function Yd(s,e,t){let r=s._runningCommand?s._runningCommand.parsed:s.inputHandler?s.inputCommand:null;return Object.assign({event:e,connection:s,session:s.sessionNumber,state:s.state,user:s.username||null,mailbox:s.selectedMailbox?s.selectedMailbox.path:null,tag:r?r.tag:null,command:r?String(r.command).toUpperCase():null},t)}function Cl(s,e,t,r){let n=e.drop?b.Buffer.alloc(0):ss(e.send,t)||r,i=[ss(e.before,t),n,ss(e.after,t)].filter(o=>!!o);if(e.defer){(s._deferredOutput||=[]).push({mode:e.defer,tag:t.tag,data:b.Buffer.concat(i)});return}Mo(s,e,b.Buffer.concat(i),e.delay)}function No(s,e,t){let r=[],n=[];for(let i of s._deferredOutput)((t?i.mode==="tagged"&&(i.tag===null||i.tag===e):i.mode==="next"&&e!==null&&i.tag!==e)?r:n).push(i);r.length&&(s._deferredOutput=n.length?n:null,r.forEach(i=>s.write(i.data)))}function Ve(s){return typeof s=="string"?{type:"LITERAL",value:s}:Array.isArray(s)?s.map(Ve):s&&typeof s=="object"&&s.type==="STRING"?{type:"LITERAL",value:s.value}:s}var Rt=s=>String(typeof s=="string"?s:s&&typeof s=="object"?s.value:"").toUpperCase();function wo(s){if(!Array.isArray(s))return Ve(s);if(Array.isArray(s[0])){let r=s.findIndex(n=>!Array.isArray(n));return s.map((n,i)=>r<0||i<r?wo(n):Ve(n))}let e=Rt(s[0]),t=e==="MESSAGE"&&["RFC822","GLOBAL"].includes(Rt(s[1]));return s.map((r,n)=>n===0&&(e==="TEXT"||t)||n===1&&t?r:n===8&&t?wo(r):Ve(r))}var Kd=new Set(["INTERNALDATE","SAVEDATE"]);function wl(s){let e=Array.isArray(s.attributes)?s.attributes:null;if(!e)return s;let t=Rt(s.command),r=Rt(e[1]),n;if(r==="FETCH"||r==="UIDFETCH"){let i=Array.isArray(e[2])?e[2]:[],o=i.map((a,u)=>{if(u%2===0)return a;let l=i[u-1],c=l&&!l.section?Rt(l):"";return Kd.has(c)?a:c==="BODY"||c==="BODYSTRUCTURE"?wo(a):Ve(a)});n=e.map((a,u)=>u===2?o:a)}else t==="LIST"||t==="LSUB"?n=e.map((i,o)=>o===1?i:o===3&&Array.isArray(i)?i.map((a,u)=>u%2===1&&Rt(i[u-1])==="CHILDINFO"?a:Ve(a)):Ve(i)):t==="NAMESPACE"?n=e.map(i=>Array.isArray(i)?i.map(o=>Array.isArray(o)?o.map((a,u)=>u===1?a:Ve(a)):o):i):n=e.map(Ve);return Object.assign({},s,{attributes:n})}function Mo(s,e,t,r){s.queueOutput({data:e.truncate===void 0?t:t.subarray(0,e.truncate),delay:r,chunk:e.chunk,chunkDelay:e.chunkDelay===void 0?Qd:e.chunkDelay,close:e.close||(e.truncate===void 0?void 0:!0)})}function Nl(s,e,t){Mo(s,e,ss(e.send,t)||b.Buffer.alloc(0))}function Ro(s,e,t,r){let n=ss(e.send,t);(n||e.close)&&Mo(s,e,n||b.Buffer.alloc(0)),(e.run||!e.drop&&!n&&!e.close)&&r()}var Lo=1024*1024,Wd=20,$d=64*1024*1024,Jd=64*1024,Dl="Literal too large",Zd=new Set(["OK","NO","BAD","BYE","PREAUTH"]),Bo=new RegExp("^["+he.tag().replace(/[\\\]^-]/g,"\\$&")+"]+$"),Uo="["+he["ATOM-CHAR"]().replace(/[\\\]^-]/g,"\\$&")+"]+",ep=new RegExp("^"+Uo+"$"),tp=new RegExp("^"+Uo+"( "+Uo+")?$"),sp=new Map(["\\Noinferiors","\\Noselect","\\Marked","\\Unmarked","\\HasChildren","\\HasNoChildren","\\NonExistent"].map(s=>[s.toLowerCase(),s]));function ht(s){let e=s.indexOf(" "),t=e>=0?s.substr(0,e):s;return t&&Bo.test(t)?t:"*"}function Ul(s,e){return s+" is not allowed in the "+e+" state"}function vl(s){return!!s.mailboxCopy||J(s.attributes&&s.attributes[1],"EXPUNGE")}function Bl(s){return!!s&&!s.command&&J(s.attributes&&s.attributes[1],"EXISTS")}var Hl=new WeakMap,rp=(s,e,t,r)=>{s.sendStatus(e,t,"NO","Unsupported authentication mechanism",!1,"UNKNOWN COMMAND"),r()};function Ho(s){return new rs(s)}var rs=class extends ps{constructor(e){super(),this.options=Object.assign({},e),this.options.secureConnection?this.server=Qe.createServer(this.getCredentials(),this.createClient.bind(this)):this.server=Qe.createServer(this.createClient.bind(this)),this.setMaxListeners(0),this.connections=new Set,this.connectionHandlers=[],this.resetHandlers=[],this.outputHandlers=[],this.messageHandlers=[],this.fetchHandlers={},this.fetchFilters=[],this.searchHandlers={},this.storeHandlers={},this.storeFilters=[],this.notifyFilters=[],this.mailboxHandlers=[],this.appendChecks=[],this.copyHandlers=[],this.appendDataHandlers=Object.create(null),this.literalFilters=[Na],this.urlAccessChecks=[],this.searchAccessChecks=[],this.commandChecks=[],this.rangeLimits=[],this.searchLimits=[],this.closedChecks=[],this.multiAppend=!1,this.commandHandlers=Object.assign(Object.create(null),zu),this.commandOptions=Object.create(null),this.capabilities={},this.allowedStatus=["MESSAGES","RECENT","UIDNEXT","UIDVALIDITY","UNSEEN"],this.statusHandlers={},this.literalPlus=!1,this.nonSyncLiteralLimit=1/0,this.parserOptions={allowSection:["BODY","BODY.PEEK"]},this.referenceNamespace=!1,this.activeConnection=null,this.sessionCounter=0,this.script=new xr(this,this.options.script);let t=el(this.options.quirks);t.rules.length&&this.script.add(t.rules),this.loadUsers(),this.control=new hr(this),this.oauth=this.options.oauth?new Ar(this,this.options.oauth):null,this.oauthServer=null,Xu(this,this.options.plugins,t.removePlugins),this.options.storage&&co(this.options.storage),this.systemFlags=[].concat(this.options.systemFlags||["\\Answered","\\Flagged","\\Draft","\\Deleted","\\Seen"]),this.loadStorage(),this.tlsServer=null,this.smtpServer=null,this.restServer=null}loadUsers(){this.users=Object.assign(Object.create(null),this.options.users?structuredClone(this.options.users):{testuser:{password:"testpass",xoauth2:{accessToken:"testtoken",sessionTimeout:Os}}});for(let e of Object.keys(this.users)){let t=this.users[e];t&&t.oauth!==void 0&&(t.oauth=io(t.oauth,"users["+JSON.stringify(e)+"].oauth"))}}loadStorage(){this.storage=this.options.storage?structuredClone(this.options.storage):{INBOX:{},"":{}},this.referenceNamespace=!1,this.uidvalidityCounter=0,this.subscriptions=new Set,this.folderCache=Object.create(null),this.indexFolders(!0)}async start(e,t){let r=await wr(this.server,e,t);return await Promise.all([this.options.tls?this.startTlsListener(t):null,this.options.smtp?this.startSmtp():null,this.options.rest?this.startRest():null,this.oauth?this.startOAuth():null]),r}startTlsListener(e){let{port:t,host:r}=this.options.tls||{};return this.tlsServer=Qe.createServer(this.getCredentials(),this.createClient.bind(this)),wr(this.tlsServer,t,r||e)}async startRest(){let{port:e,host:t,token:r}=this.options.rest||{};return this.restServer=il(this,{host:t,token:r}),wr(this.restServer,e,t||"127.0.0.1")}async startOAuth(){let e=this.oauth,{port:t,host:r="127.0.0.1",secure:n}=e.options;this.oauthServer=Al(e,{secure:n,host:r,credentials:this.getCredentials()});let i=await wr(this.oauthServer,t,r);return e.listening(r,i),i}checkAccessToken(e,t,r="imap"){let n=this.oauth&&this.oauth.verifyAccessToken(e,t,r);if(n)return n;let i=a=>{let u=this.users[a];return!!(u&&u.xoauth2&&u.xoauth2.accessToken===e)},o=t===void 0?Object.keys(this.users).find(i):i(t)?t:void 0;return o===void 0?{error:"invalid_token",reason:"unknown access token"}:{user:o}}startSmtp(){let{port:e,host:t}=this.options.smtp||{};return this.loadSmtpListener().then(({startSMTPServer:r})=>new Promise((n,i)=>{let o=r(e||0,this,a=>{o.removeListener("error",i),n(a)},t);o.once("error",i),this.smtpServer=o}))}loadSmtpListener(){return Promise.resolve().then(()=>(Ll(),Rl)).catch(e=>{throw new Error("The smtp option needs the smtp-server package, install it with: npm install smtp-server ("+e.message+")")})}stop(){return this.control.shutdown({graceful:!1})}listen(...e){this.server.listen.apply(this.server,e)}close(e){this.closeListeners(!0),this.closeImapListeners(e),this.connections.forEach(t=>{t.socket&&t.socket.destroy()})}closeImapListeners(e){let t=this.tlsServer?[this.server,this.tlsServer]:[this.server];this.tlsServer=null;let r=t.length,n;t.forEach(i=>i.close(o=>{n=n||o,--r===0&&e?.(n)}))}closeListeners(e){this.smtpServer&&(this.smtpServer.close(()=>!1),this.smtpServer=null),this.restServer&&(this.restServer.endStreams?.(),kl(this.restServer,e),this.restServer=null),this.oauthServer&&(kl(this.oauthServer,e),this.oauthServer=null)}getCredentials(){return this.options.credentials||(this.options.credentials={key:yl,cert:bl}),this.options.credentials}address(){return this.server.address()}createClient(e){let t=new ns(this,e);this.connectionHandlers.forEach(r=>{r(t)})}connect(e){let[t,r]=Tl();return t.encrypted=r.encrypted=!e||e.secure!==!1,this.createClient(t),r}registerCapability(e,t){this.capabilities[e]=t||function(){return!0}}setCommandHandler(e,t,r){e=(e||"").toString().toUpperCase(),this.commandHandlers[e]=t,r&&(this.commandOptions[e]=re(r))}getCommandOptions(e){return e=(e||"").toString().toUpperCase(),this.commandOptions[e]||Ia(e)||re()}getCommandStates(e){return this.getCommandOptions(e).states}getUser(e){return typeof e=="string"&&Object.hasOwn(this.users,e)&&this.users[e]||!1}getMailbox(e){return e.toUpperCase()==="INBOX"?this.folderCache.INBOX:this.folderCache[e]}notify(e,t,r,n){e.notification=!0;let i={command:e,mailbox:t,ignoreConnection:r,filter:n,origin:this.activeConnection};this.emit("notify",i)}mailboxChanged(e,t,r){let n=Object.assign({type:e,path:t,oldPath:null,mailbox:null},r,{origin:this.activeConnection});this.emit("mailbox",n)}withOrigin(e,t){let r=this.activeConnection;this.activeConnection=e;try{return t()}finally{this.activeConnection=r}}getCommandHandler(e){return this.commandHandlers[(e||"").toString().toUpperCase()]||!1}getStatus(e){let t=typeof e=="string"?this.getMailbox(e):e;if(!t)return!1;let r={},n=0,i=0,o=this.permanentFlagList(t),a=0,u=[];return this.connections.forEach(l=>{l.selectedMailbox===t&&l.recent&&u.push(l.recent)}),t.messages.forEach(l=>{l.flags.indexOf("\\Seen")<0?i++:n++,(l.recent||u.some(c=>c.has(l)))&&a++,l.flags.forEach(c=>{r[c]?r[c]++:r[c]=1,o.indexOf(c)<0&&o.push(c)})}),{flags:r,seen:n,unseen:i,recent:a,permanentFlags:o}}validateInternalDate(e){return ks(e)}formatInternalDate(e){let t=e.getDate(),r=St[e.getMonth()],n=e.getFullYear(),i=e.getHours(),o=e.getMinutes(),a=e.getSeconds(),u=e.getTimezoneOffset(),l=Math.floor(Math.abs(u)/60),c=Math.abs(u)%60;return(t<10?"0":"")+t+"-"+r+"-"+n+" "+(i<10?"0":"")+i+":"+(o<10?"0":"")+o+":"+(a<10?"0":"")+a+" "+(u>0?"-":"+")+(l<10?"0":"")+l+(c<10?"0":"")+c}createMailbox(e,t){if(!e)throw K("Invalid mailbox name","CANNOT");if(e.toUpperCase()==="INBOX")throw K("INBOX can not be modified","ALREADYEXISTS");let{namespace:r,storage:n}=this.getPersonalNamespace(e);if(e=this.stripSeparator(e,n.separator),this.folderCache[e]&&this.folderCache[e].flags.indexOf("\\Noselect")<0)throw K("Mailbox already exists","ALREADYEXISTS");let i=e.substr(r.length).split(n.separator);if(i.some(u=>!u))throw K("Mailbox names can not have empty hierarchy levels","CANNOT");let o=n,a=r;return a&&(a=a.substr(0,a.length-n.separator.length)),i.forEach(u=>{a+=(a.length?n.separator:"")+u;let l=this.getMailbox(a)||!1;if(l&&l.flags&&l.flags.indexOf("\\Noinferiors")>=0)throw K("Can not create subfolders for "+l.path,"CANNOT");let c=a===e,f=c&&t;if(!l||f||c&&l.flags.indexOf("\\Noselect")>=0){let p=l&&l.folders,y=f?t:{uidvalidity:++this.uidvalidityCounter};p&&(y.folders=Object.assign({},p,y.folders)),this.trackSubscription(y),this.processMailbox(a,y,r),o.folders=o.folders||{},o.folders[u]=y,this.folderCache[a]=y,l=y}o!==n?this.setChildrenFlags(o,!0):l.namespace===this.referenceNamespace&&this.inboxHoldsNamespace()&&this.setChildrenFlags(this.storage.INBOX,!0),o=l}),this.folderCache[e]}deleteMailbox(e,t){if(e.toUpperCase()==="INBOX")throw K("INBOX can not be modified","CANNOT");let{namespace:r,storage:n}=this.getPersonalNamespace(e),i=this.folderCache[this.stripSeparator(e,n.separator)];if(!i)throw K("Mailbox does not exist","NONEXISTENT");if(i.flags.indexOf("\\Noselect")>=0&&Object.keys(i.folders||{}).length)throw K("Mailbox has children, delete them first","HASCHILDREN");let o=i.path.split(n.separator),a=o.pop(),u=o.join(n.separator),l=u!=="INBOX"&&this.folderCache[u]||n;if(i.folders&&Object.keys(i.folders).length&&!t){let c={flags:["\\Noselect"],folders:i.folders};this.trackSubscription(c),this.processMailbox(i.path,c,i.namespace),l.folders[a]=c,this.folderCache[i.path]=c;return}delete this.folderCache[i.path],delete l.folders[a],l!==n?l.flags.indexOf("\\Noselect")>=0&&!Object.keys(l.folders||{}).length?this.deleteMailbox(l.path):this.setChildrenFlags(l,Object.keys(l.folders||{}).length>0):r===this.referenceNamespace&&this.inboxHoldsNamespace()&&this.setChildrenFlags(this.storage.INBOX,Object.keys(n.folders||{}).length>0)}getPersonalNamespace(e){let t="";Object.keys(this.storage).forEach(n=>{if(n==="INBOX")return;let i=n.length?n.substr(0,n.length-this.storage[n].separator.length):n;if(n.length&&(e===i||e.substr(0,n.length)===n)){if(e===i)throw K("Used mailbox name is a namespace value","CANNOT");t=n}else!t&&!n&&this.storage[n].type==="personal"&&(t=n)});let r=this.storage[t];if(!r)throw K("Unknown namespace","CANNOT");if(r.type!=="personal")throw K("Permission denied","NOPERM");return{namespace:t,storage:r}}stripSeparator(e,t){return e.substr(-t.length)===t?e.substr(0,e.length-t.length):e}inboxHoldsNamespace(){let e=this.referenceNamespace;if(e===!1)return!1;let t=this.storage[e];return!!t&&e.substr(0,e.length-t.separator.length).toUpperCase()==="INBOX"}indexFolders(e){let t=Object.create(null),r=(n,i,o,a)=>{Object.keys(o).forEach(u=>{let l=o[u],c=(n?n+(n.substr(-1)!==i?i:""):"")+u;this.processMailbox(c,l,a),t[c]=l,e&&this.processMessages(l),l.folders&&Object.keys(l.folders).length&&r(c,i,l.folders,a)})};this.storage.INBOX||(this.storage.INBOX={}),Object.keys(this.storage).forEach(n=>{n!=="INBOX"&&(this.storage[n].folders=this.storage[n].folders||{},this.storage[n].separator=this.storage[n].separator||(/[^a-z0-9]$/i.test(n)?n.substr(-1):"/"),this.storage[n].type=this.storage[n].type||"personal",this.storage[n].type==="personal"&&this.referenceNamespace===!1&&(this.referenceNamespace=n),r(n,this.storage[n].separator,this.storage[n].folders,n))}),this.referenceNamespace||(this.storage[""]=this.storage[""]||{},this.storage[""].folders=this.storage[""].folders||{},this.storage[""].separator=this.storage[""].separator||"/",this.storage[""].type="personal",this.referenceNamespace=""),this.storage.INBOX.separator||(this.storage.INBOX.separator=this.storage[this.referenceNamespace].separator),t.INBOX=this.storage.INBOX,this.processMailbox("INBOX",this.storage.INBOX,"INBOX"),e&&this.processMessages(this.storage.INBOX),this.storage.INBOX.folders&&Object.keys(this.storage.INBOX.folders).length&&r("INBOX",this.storage.INBOX.separator,this.storage.INBOX.folders,this.referenceNamespace),this.inboxHoldsNamespace()&&this.setChildrenFlags(this.storage.INBOX,Object.keys(this.storage[this.referenceNamespace].folders||{}).length>0),this.folderCache=t}processMessages(e){let t=new Set,r=e.messages;r.forEach((n,i)=>{let o=typeof n=="string"?r[i]={raw:n}:n;if(this.processMessage(o,e),t.has(o.uid))throw new Error("Duplicate UID "+o.uid+" in mailbox "+e.path);t.add(o.uid)}),e.messages.sort((n,i)=>n.uid-i.uid)}processMailbox(e,t,r){t.path=e,t.namespace=r,t.uid=t.uid||1,t.uidvalidity=t.uidvalidity||1,this.uidvalidityCounter=Math.max(this.uidvalidityCounter,t.uidvalidity),t.flags=[].concat(t.flags||[]).map(o=>sp.get(String(o).toLowerCase())||o),t.allowPermanentFlags="allowPermanentFlags"in t?t.allowPermanentFlags:!0,t.permanentFlags=[].concat(t.permanentFlags||this.systemFlags),this.trackSubscription(t,!0);let n=[].concat(t.messages||[]);t.messages=n,t.uidnext=Math.max(...[t.uidnext||1].concat(n.map(o=>((typeof o=="string"?0:o.uid)||0)+1)));let i=t;this.setChildrenFlags(i,Object.keys(i.folders||{}).length>0),this.mailboxHandlers.forEach(o=>{o(this,i)})}trackSubscription(e,t){let r=Object.getOwnPropertyDescriptor(e,"subscribed");if(r&&r.get)return;let n=r?!!r.value:t;Object.defineProperty(e,"subscribed",{enumerable:!0,configurable:!0,get:()=>this.subscriptions.has(e.path),set:i=>{i?this.subscriptions.add(e.path):this.subscriptions.delete(e.path)}}),typeof n=="boolean"&&(e.subscribed=n)}setChildrenFlags(e,t){this.removeFlag(e.flags,"\\HasChildren"),this.removeFlag(e.flags,"\\HasNoChildren"),e.flags.indexOf("\\Noinferiors")<0&&e.flags.push(t?"\\HasChildren":"\\HasNoChildren")}ensureFlag(e,t){e.indexOf(t)<0&&e.push(t)}removeFlag(e,t){let r;if(e.indexOf(t)>=0)for(r=e.length-1;r>=0;r--)e[r]===t&&e.splice(r,1)}rememberFlags(e,t){let r=e.knownFlags=e.knownFlags||[];t.forEach(n=>this.ensureFlag(r,n))}isPermanentFlag(e,t){return e.allowPermanentFlags||(e.permanentFlags||[]).indexOf(t)>=0||!!e.knownFlags&&e.knownFlags.indexOf(t)>=0}permanentFlagList(e){let t=[].concat(e.permanentFlags||[]);return(e.knownFlags||[]).forEach(r=>this.ensureFlag(t,r)),t}now(){let e=this.options.now,t=typeof e=="function"?e():e;return t==null?new Date:new Date(t)}normalizeDateTime(e){return e instanceof Date?this.formatInternalDate(e):typeof e=="string"?e.replace(/-([a-z]{3})-/i,(t,r)=>"-"+(St[ze(r)]||r)+"-"):e}processMessage(e,t){e.internaldate=this.normalizeDateTime(e.internaldate||this.now()),e.flags=[].concat(e.flags||[]),e.flags.indexOf("\\Recent")>=0&&(this.removeFlag(e.flags,"\\Recent"),e.recent=!0),this.rememberFlags(t,e.flags),e.uid=e.uid||t.uidnext++,e.uid>=t.uidnext&&(t.uidnext=e.uid+1),e.raw instanceof Uint8Array?e.raw=b.Buffer.from(e.raw).toString("binary"):typeof e.raw!="string"&&(e.raw=e.raw?String(e.raw):""),/[\u0100-\uffff]/.test(e.raw)&&(e.raw=b.Buffer.from(e.raw,"utf-8").toString("binary"));let r=e;this.messageHandlers.forEach(n=>{n(this,r,t)})}appendMessage(e,t,r,n,i,o){let a=typeof e=="string"?this.getMailbox(e):e,u=Object.assign({},o,{flags:t.filter(l=>this.isPermanentFlag(a,l)),internaldate:r,raw:n,recent:!0});a.messages.push(u),this.processMessage(u,a);for(let l of this.connections)if(l.selectedMailbox===a&&!l.readOnly&&l.recent){l.recent.add(u),delete u.recent;break}return this.emit("append",a,[u],this.activeConnection),this.notify({tag:"*",attributes:[a.messages.length,{type:"ATOM",value:"EXISTS"}],message:u},a,i),{mailbox:a,message:u}}copyMessage(e,t){let r={};return this.copyHandlers.forEach(n=>{n(this,t,r,e)}),this.appendMessage(e,[].concat(t.flags||[]),t.internaldate,t.raw,!1,r)}getNamespace(e){let t=!1;return Object.keys(this.storage).forEach(r=>{r!=="INBOX"&&e.substr(0,r.length)===r&&(t===!1||r.length>t.length)&&(t=r)}),t}targetRefusal(e){let t=this.getMailbox(e);return t?t.flags.indexOf("\\Noselect")>=0?{command:"NO",code:"TRYCREATE",text:"Target mailbox is not selectable"}:!1:{command:"NO",code:"TRYCREATE",text:"Target mailbox does not exist"}}getMailboxNamespace(e){if(e&&typeof e=="object")return e.namespace;if(e.toUpperCase()==="INBOX")return"INBOX";let t=this.getMailbox(e);return t?t.namespace:this.getNamespace(e)}isPersonal(e){let t=this.getMailboxNamespace(e);return t==="INBOX"||t!==!1&&!!this.storage[t]&&this.storage[t].type==="personal"}getSeparator(e){let t=this.getMailboxNamespace(e),r=t===!1?void 0:this.storage[t];return r&&r.separator||this.storage.INBOX.separator||"/"}getParentPath(e){let t=this.getSeparator(e);e=this.stripSeparator(e,t);let r=e.lastIndexOf(t);if(r<=0)return!1;let n=e.substr(0,r);return n.toUpperCase()==="INBOX"?"INBOX":this.storage[n+t]?!1:n}getDescendants(e,t){let r=t||this.folderCache,n=e+this.getSeparator(e);return Object.keys(r).filter(i=>i.substr(0,n.length)===n).map(i=>r[i])}hasDescendant(e,t){let r=e+this.getSeparator(e);for(let n of Object.keys(this.folderCache))if(n.substr(0,r.length)===r&&t(this.folderCache[n]))return!0;return!1}listAttributes(e,t){let r=t.exists!==!1,n=(e&&e.flags||[]).filter(i=>i!=="\\HasChildren"&&i!=="\\HasNoChildren"&&(r||i!=="\\Noselect"));return r||n.push("\\NonExistent"),t.subscribed&&n.push("\\Subscribed"),n.push(...t.extra||[]),n.indexOf("\\Noinferiors")<0&&n.push(t.hasChildren?"\\HasChildren":"\\HasNoChildren"),n}matchFolders(e,t,r,n){let i=n||this.folderCache,o=r||(p=>p),a=t.charAt(0)==="#"?t:(e||"")+t,u=(p,y="")=>new RegExp("^"+a.replace(/([\\^$+?!.():=[\]{}|,-])/g,"\\$1").replace(/[*]/g,".*").replace(/[%]/g,"[^"+p.replace(/([\\^$+*?!.():=[\]{}|,-])/g,"\\$1")+"]*")+"$",y),l=a.replace(/[*%].*$/,""),c=new Map;Object.keys(this.storage).forEach(p=>{let y=o(p),A=p===this.referenceNamespace||l.substr(0,y.length)===y;c.set(p,A?u(this.storage[p].separator):null)});let f=[];return i.INBOX&&u(this.storage.INBOX&&this.storage.INBOX.separator||"/","i").test("INBOX")&&f.push(i.INBOX),Object.keys(i).forEach(p=>{let y=i[p],A=p!=="INBOX"&&y.namespace!==!1&&y.namespace!=="INBOX"?c.get(y.namespace):null;if(!A)return;let m=o(p);A.test(m)&&(y.flags.indexOf("\\NonExistent")<0||m===a)&&f.push(y)}),f}getSubscriptionTree(){let e=Object.create(null),t=(n,i)=>{e[n]=e[n]||this.getMailbox(n)||{path:n,namespace:this.getNamespace(n),flags:["\\Noselect"],subscribed:i}},r=[...this.subscriptions].filter(n=>n==="INBOX"||this.getNamespace(n)!==!1);return r.forEach(n=>t(n,!0)),r.forEach(n=>{for(let i=this.getParentPath(n);i;i=this.getParentPath(i))t(i,!1)}),e}getMessageRange(e,t,r){let n=(t||"").toString(),i=typeof e=="string"?this.getMailbox(e):e;if(!Is(n)){let y=new Error("Invalid sequence set");throw y.imapResponse="BAD",y}let o=[],a=n.split(","),u=Array.isArray(i)?i:i.messages,l,c=u.length,f=0,p=function(y,A,m){for(let h=0,d=A.length;h<d;h++){let E=A[h].split(":"),I=E.shift(),C=Number(I==="*"?m:I)||1,H=E.pop()||C,N=Number(H==="*"&&m||H)||C;if(y>=Math.min(C,N)&&y<=Math.max(C,N))return!0}return!1};u.forEach(y=>{y.uid>f&&(f=y.uid)});for(let y=0,A=u.length;y<A;y++)l=u[y].uid||1,p(r?l:y+1,a,r?f:c)&&o.push([y+1,u[y]]);return o}},ns=class{constructor(e,t){this.server=e,this.socket=t,this.options=this.server.options,this.state="Not Authenticated",this.sessionNumber=++this.server.sessionCounter,this._outputQueue=null,this._outputTimer=null,this._deferredOutput=null,this.secureConnection=!!this.options.secureConnection||t.encrypted===!0,this._remainder="",this._command="",this._literalRemaining=0,this.inputHandler=!1,this.transport=null,this.parserOptions={},this.compilerOptions={},this.messageGlobal=!1,this._commandQueue=[],this._processing=!1,this.options.debug&&typeof this.socket.pipe=="function"&&this.socket.pipe(U.stdout),this.socket.on("data",this.receive.bind(this)),this.socket.on("close",this.onClose.bind(this)),this.socket.on("error",this.onError.bind(this)),this.directNotifications=!1,this._notificationCallback=this.onNotify.bind(this),this.notificationQueue=[],this.server.on("notify",this._notificationCallback),this.server.connections.add(this),this.emitSession("open"),this.scriptOutput("greeting",`* OK ImapKit ready for rumble\r
153
+ `;E();E();var Tr=Ut(ds()),tI=Tr.default.once;var Ir=class extends Tr.default{constructor(){super(),this.peer=null,this.destroyed=!1,this.encrypted=!1,this._paused=!1,this._ending=!1,this._encoding=null,this._received=[]}write(e,t,r){if(typeof t=="function"&&(r=t,t=void 0),this.destroyed||this._ending)return!1;let n=typeof e=="string"?b.Buffer.from(e,t||"utf8"):b.Buffer.from(e.buffer,e.byteOffset,e.byteLength);return Sr(()=>{this.peer?.deliver(n),r?.()}),!0}end(e){return e!==void 0&&this.write(e),this.destroyed||this._ending?this:(this._ending=!0,Sr(()=>{let t=this.peer;t&&!t.destroyed&&(t.emit("end"),t.close()),this.close()}),this)}destroy(e){if(this.destroyed)return this;let t=this.peer;return this.close(e),t&&!t.destroyed&&t.close(),this}resetAndDestroy(){let e=this.peer;if(this.destroy(),e){let t=new Error("read ECONNRESET");t.code="ECONNRESET",Sr(()=>e.emit("error",t))}return this}startTls(e){this.encrypted=!0,this.peer&&(this.peer.encrypted=!0),e()}pause(){return this._paused=!0,this}resume(){for(this._paused=!1;this._received.length&&!this._paused&&!this.destroyed;)this.emitData(this._received.shift());return this}setEncoding(e){return this._encoding=e,this}deliver(e){if(!this.destroyed){if(this._paused){this._received.push(e);return}this.emitData(e)}}emitData(e){this.emit("data",this._encoding?e.toString(this._encoding):e)}close(e){this.destroyed||(this.destroyed=!0,this._received=[],Sr(()=>{e&&this.emit("error",e),this.emit("close",!!e)}))}};function Tl(){let s=new Ir,e=new Ir;return s.peer=e,e.peer=s,[s,e]}var Or=[];function Sr(s){Or.push(s),Or.length===1&&R(qd)}function qd(){let s=Or.splice(0,Or.length);for(let e of s)e()}E();var de=["greeting","command","input","response","continuation","quiet"],Co=["greeting","response","continuation"],Sl={on:de,command:["command","input","response","continuation","quiet"],tag:["command","input","response","continuation","quiet"],description:["response","continuation"],session:de,user:de,state:de,mailbox:de,untagged:["response"],match:de,when:de,nth:de,times:de,chance:de,quietFor:["quiet"],mutate:["response","continuation"],literals:["response"],defer:["response"],send:de,before:Co,after:Co,run:["command","input"],drop:["greeting","command","input","response","continuation"],delay:["greeting","command","response","continuation"],chunk:de,chunkDelay:de,truncate:de,close:de},Il=["mutate","literals","defer","send","before","after","run","drop","delay","chunk","truncate","close"],Qd=10,Ol=["command","description","session","state","user","mailbox"];function ss(s,e){if(s===void 0)return null;let t=typeof s=="function"?s(e):s;if(b.Buffer.isBuffer(t))return t;let r=String(t).replace(/\$TAG/g,()=>e.tag||"*");return b.Buffer.from(r,/[\u0100-\uffff]/.test(r)?"utf-8":"binary")}function xl(s){if(!s||typeof s!="object")throw new TypeError("A script rule must be an object");if(!de.includes(s.on))throw new TypeError('Script rule "on" must be one of '+de.join(", "));for(let e of Object.keys(s)){let t=Object.hasOwn(Sl,e)?Sl[e]:null;if(!t)throw new TypeError('Unknown script rule option "'+e+'"');if(!t.includes(s.on))throw new TypeError('Script rule option "'+e+'" can not be used with "on": "'+s.on+'"')}if(s.on==="quiet"&&!(Number.isInteger(s.quietFor)&&s.quietFor>0))throw new TypeError('A quiet rule needs "quietFor", a positive number of milliseconds');if(s.chance!==void 0&&!(typeof s.chance=="number"&&s.chance>=0&&s.chance<=1))throw new TypeError('Script rule option "chance" must be a number from 0 to 1');if(!Il.some(e=>s[e]!==void 0&&s[e]!==!1))throw new TypeError("A script rule needs an action ("+Il.join(", ")+")");if(s.drop&&(s.send!==void 0||s.run))throw new TypeError('Script rule option "drop" can not be combined with "send" or "run"');if(s.run&&(s.close||s.truncate!==void 0))throw new TypeError('Script rule option "run" can not be combined with "close" or "truncate"');if(s.chunkDelay!==void 0&&s.chunk===void 0)throw new TypeError('Script rule option "chunkDelay" needs "chunk"');if(!Co.includes(s.on)&&s.send===void 0&&(s.chunk!==void 0||s.truncate!==void 0))throw new TypeError('Script rule options "chunk" and "truncate" need "send" with "on": "'+s.on+'"');for(let e of["nth","times","chunk"])if(s[e]!==void 0&&!(Number.isInteger(s[e])&&s[e]>0))throw new TypeError('Script rule option "'+e+'" must be a positive integer');for(let e of["delay","chunkDelay","truncate"])if(!(e==="chunkDelay"&&s[e]==="tick")&&s[e]!==void 0&&!(Number.isInteger(s[e])&&s[e]>=0))throw new TypeError('Script rule option "'+e+'" must be a non-negative integer');for(let e of["when","mutate"])if(s[e]!==void 0&&typeof s[e]!="function")throw new TypeError('Script rule option "'+e+'" must be a function');for(let e of["send","before","after"]){let t=s[e];if(t!==void 0&&typeof t!="string"&&typeof t!="function"&&!b.Buffer.isBuffer(t))throw new TypeError('Script rule option "'+e+'" must be a string, a Buffer or a function')}if(s.literals!==void 0&&typeof s.literals!="boolean")throw new TypeError('Script rule option "literals" must be true or false');if(s.defer!==void 0){if(s.defer!=="tagged"&&s.defer!=="next")throw new TypeError('Script rule option "defer" must be "tagged" or "next"');if(s.untagged!==!0)throw new TypeError('Script rule option "defer" needs "untagged": true');let e=["drop","delay","chunk","truncate","close"].find(t=>s[t]!==void 0&&s[t]!==!1);if(e)throw new TypeError('Script rule option "defer" can not be combined with "'+e+'"')}if(s.close!==void 0&&typeof s.close!="boolean"&&s.close!=="reset")throw new TypeError('Script rule option "close" must be true, false or "reset"');if(s.match===void 0)return null;if(s.match instanceof RegExp)return new RegExp(s.match.source,s.match.flags.replace(/[gy]/g,""));if(typeof s.match!="string")throw new TypeError('Script rule option "match" must be a string or a RegExp');try{return new RegExp(s.match)}catch(e){throw new TypeError('Script rule option "match" is not a valid regular expression: '+e.message,{cause:e})}}var xr=class{constructor(e,t){this.server=e,this.entries=[],this.ruleCounter=0;let r=e.options.scriptSeed,n=()=>{this.random=Ss(typeof r=="number"?r:Math.floor(Math.random()*4294967295))};n(),e.on("reset",n),this.watched=new Set,t&&this.add(t)}get rules(){return this.entries.slice()}add(e){if(Array.isArray(e)){let t=e.map(xl);return e.map((r,n)=>this.addEntry(r,t[n]))}return this.addEntry(e,xl(e))}clear(){this.setEntries([])}watches(e){return this.watched.has(e)}check(e,t,r){if(!this.watched.has(t))return null;let n=Yd(e,t,r),i=this.find(n);return i?{rule:i,context:n}:null}setEntries(e){this.entries=e,this.watched=new Set(e.map(t=>t.rule.on)),this.watched.has("quiet")&&this.server.connections?.forEach(t=>t.watchQuiet())}nextQuiet(e){let t=null;for(let r of this.entries){let n=r.rule.quietFor;r.rule.on==="quiet"&&n!==void 0&&n>e&&(t===null||n<t)&&(t=n)}return t}addEntry(e,t){let r=Object.freeze(Object.assign({},e)),n={};for(let o of Ol)if(r[o]!==void 0){let a=[].concat(r[o]);n[o]=new Set(o==="command"?a.map(u=>String(u).toUpperCase()):a)}let i={id:++this.ruleCounter,rule:r,match:t,sets:n,matched:0,hits:0,remove:()=>this.setEntries(this.entries.filter(o=>o!==i))};return this.setEntries(this.entries.concat(i)),i}find(e){for(let t of this.entries){let r=t.rule;if(!(r.on!==e.event||!this.matches(t,e))&&(t.matched++,!(t.matched<(r.nth||1)||r.times!==void 0&&t.hits>=r.times)&&!(r.chance!==void 0&&this.random()>=r.chance)))return t.hits++,this.server.emit("script",{rule:r,event:e.event,session:e.session,tag:e.tag,command:e.command}),r}return null}matches(e,t){let r=e.rule;for(let n of Ol){let i=e.sets[n],o=t[n];if(i&&(o==null||!i.has(o)))return!1}return r.tag!==void 0&&(t.tag===null||(r.tag instanceof RegExp?!r.tag.test(t.tag):r.tag!==t.tag))||r.untagged!==void 0&&r.untagged!==(!t.response||t.response.tag==="*")||r.quietFor!==void 0&&(t.quiet||0)<r.quietFor||e.match&&!e.match.test(t.data)?!1:!r.when||!!r.when(t)}};function Yd(s,e,t){let r=s._runningCommand?s._runningCommand.parsed:s.inputHandler?s.inputCommand:null;return Object.assign({event:e,connection:s,session:s.sessionNumber,state:s.state,user:s.username||null,mailbox:s.selectedMailbox?s.selectedMailbox.path:null,tag:r?r.tag:null,command:r?String(r.command).toUpperCase():null},t)}function Cl(s,e,t,r){let n=e.drop?b.Buffer.alloc(0):ss(e.send,t)||r,i=[ss(e.before,t),n,ss(e.after,t)].filter(o=>!!o);if(e.defer){(s._deferredOutput||=[]).push({mode:e.defer,tag:t.tag,data:b.Buffer.concat(i)});return}Mo(s,e,b.Buffer.concat(i),e.delay)}function No(s,e,t){let r=[],n=[];for(let i of s._deferredOutput)((t?i.mode==="tagged"&&(i.tag===null||i.tag===e):i.mode==="next"&&e!==null&&i.tag!==e)?r:n).push(i);r.length&&(s._deferredOutput=n.length?n:null,r.forEach(i=>s.write(i.data)))}function Ve(s){return typeof s=="string"?{type:"LITERAL",value:s}:Array.isArray(s)?s.map(Ve):s&&typeof s=="object"&&s.type==="STRING"?{type:"LITERAL",value:s.value}:s}var Rt=s=>String(typeof s=="string"?s:s&&typeof s=="object"?s.value:"").toUpperCase();function wo(s){if(!Array.isArray(s))return Ve(s);if(Array.isArray(s[0])){let r=s.findIndex(n=>!Array.isArray(n));return s.map((n,i)=>r<0||i<r?wo(n):Ve(n))}let e=Rt(s[0]),t=e==="MESSAGE"&&["RFC822","GLOBAL"].includes(Rt(s[1]));return s.map((r,n)=>n===0&&(e==="TEXT"||t)||n===1&&t?r:n===8&&t?wo(r):Ve(r))}var Kd=new Set(["INTERNALDATE","SAVEDATE"]);function wl(s){let e=Array.isArray(s.attributes)?s.attributes:null;if(!e)return s;let t=Rt(s.command),r=Rt(e[1]),n;if(r==="FETCH"||r==="UIDFETCH"){let i=Array.isArray(e[2])?e[2]:[],o=i.map((a,u)=>{if(u%2===0)return a;let l=i[u-1],c=l&&!l.section?Rt(l):"";return Kd.has(c)?a:c==="BODY"||c==="BODYSTRUCTURE"?wo(a):Ve(a)});n=e.map((a,u)=>u===2?o:a)}else t==="LIST"||t==="LSUB"?n=e.map((i,o)=>o===1?i:o===3&&Array.isArray(i)?i.map((a,u)=>u%2===1&&Rt(i[u-1])==="CHILDINFO"?a:Ve(a)):Ve(i)):t==="NAMESPACE"?n=e.map(i=>Array.isArray(i)?i.map(o=>Array.isArray(o)?o.map((a,u)=>u===1?a:Ve(a)):o):i):n=e.map(Ve);return Object.assign({},s,{attributes:n})}function Mo(s,e,t,r){s.queueOutput({data:e.truncate===void 0?t:t.subarray(0,e.truncate),delay:r,chunk:e.chunk,chunkDelay:e.chunkDelay===void 0?Qd:e.chunkDelay,close:e.close||(e.truncate===void 0?void 0:!0)})}function Nl(s,e,t){Mo(s,e,ss(e.send,t)||b.Buffer.alloc(0))}function Ro(s,e,t,r){let n=ss(e.send,t);(n||e.close)&&Mo(s,e,n||b.Buffer.alloc(0)),(e.run||!e.drop&&!n&&!e.close)&&r()}var Lo=1024*1024,Wd=20,$d=64*1024*1024,Jd=64*1024,Dl="Literal too large",Zd=new Set(["OK","NO","BAD","BYE","PREAUTH"]),Bo=new RegExp("^["+he.tag().replace(/[\\\]^-]/g,"\\$&")+"]+$"),Uo="["+he["ATOM-CHAR"]().replace(/[\\\]^-]/g,"\\$&")+"]+",ep=new RegExp("^"+Uo+"$"),tp=new RegExp("^"+Uo+"( "+Uo+")?$"),sp=new Map(["\\Noinferiors","\\Noselect","\\Marked","\\Unmarked","\\HasChildren","\\HasNoChildren","\\NonExistent"].map(s=>[s.toLowerCase(),s]));function ht(s){let e=s.indexOf(" "),t=e>=0?s.substr(0,e):s;return t&&Bo.test(t)?t:"*"}function Ul(s,e){return s+" is not allowed in the "+e+" state"}function vl(s){return!!s.mailboxCopy||J(s.attributes&&s.attributes[1],"EXPUNGE")}function Bl(s){return!!s&&!s.command&&J(s.attributes&&s.attributes[1],"EXISTS")}var Hl=new WeakMap,rp=(s,e,t,r)=>{s.sendStatus(e,t,"NO","Unsupported authentication mechanism",!1,"UNKNOWN COMMAND"),r()};function Ho(s){return new rs(s)}var rs=class extends ps{constructor(e){super(),this.options=Object.assign({},e),this.options.secureConnection?this.server=Qe.createServer(this.getCredentials(),this.createClient.bind(this)):this.server=Qe.createServer(this.createClient.bind(this)),this.setMaxListeners(0),this.connections=new Set,this.connectionHandlers=[],this.resetHandlers=[],this.outputHandlers=[],this.messageHandlers=[],this.fetchHandlers={},this.fetchFilters=[],this.searchHandlers={},this.storeHandlers={},this.storeFilters=[],this.notifyFilters=[],this.mailboxHandlers=[],this.appendChecks=[],this.copyHandlers=[],this.appendDataHandlers=Object.create(null),this.literalFilters=[Na],this.urlAccessChecks=[],this.searchAccessChecks=[],this.commandChecks=[],this.rangeLimits=[],this.searchLimits=[],this.closedChecks=[],this.multiAppend=!1,this.commandHandlers=Object.assign(Object.create(null),zu),this.commandOptions=Object.create(null),this.capabilities={},this.allowedStatus=["MESSAGES","RECENT","UIDNEXT","UIDVALIDITY","UNSEEN"],this.statusHandlers={},this.literalPlus=!1,this.nonSyncLiteralLimit=1/0,this.parserOptions={allowSection:["BODY","BODY.PEEK"]},this.referenceNamespace=!1,this.activeConnection=null,this.sessionCounter=0,this.script=new xr(this,this.options.script);let t=el(this.options.quirks);t.rules.length&&this.script.add(t.rules),this.loadUsers(),this.control=new hr(this),this.oauth=this.options.oauth?new Ar(this,this.options.oauth):null,this.oauthServer=null,Xu(this,this.options.plugins,t.removePlugins),this.options.storage&&co(this.options.storage),this.systemFlags=[].concat(this.options.systemFlags||["\\Answered","\\Flagged","\\Draft","\\Deleted","\\Seen"]),this.loadStorage(),this.tlsServer=null,this.smtpServer=null,this.restServer=null}loadUsers(){this.users=Object.assign(Object.create(null),this.options.users?structuredClone(this.options.users):{testuser:{password:"testpass",xoauth2:{accessToken:"testtoken",sessionTimeout:Os}}});for(let e of Object.keys(this.users)){let t=this.users[e];t&&t.oauth!==void 0&&(t.oauth=io(t.oauth,"users["+JSON.stringify(e)+"].oauth"))}}loadStorage(){this.storage=this.options.storage?structuredClone(this.options.storage):{INBOX:{},"":{}},this.referenceNamespace=!1,this.uidvalidityCounter=0,this.subscriptions=new Set,this.folderCache=Object.create(null),this.indexFolders(!0)}async start(e,t){let r=await wr(this.server,e,t);return await Promise.all([this.options.tls?this.startTlsListener(t):null,this.options.smtp?this.startSmtp():null,this.options.rest?this.startRest():null,this.oauth?this.startOAuth():null]),r}startTlsListener(e){let{port:t,host:r}=this.options.tls||{};return this.tlsServer=Qe.createServer(this.getCredentials(),this.createClient.bind(this)),wr(this.tlsServer,t,r||e)}async startRest(){let{port:e,host:t,token:r}=this.options.rest||{};return this.restServer=il(this,{host:t,token:r}),wr(this.restServer,e,t||"127.0.0.1")}async startOAuth(){let e=this.oauth,{port:t,host:r="127.0.0.1",secure:n}=e.options;this.oauthServer=Al(e,{secure:n,host:r,credentials:this.getCredentials()});let i=await wr(this.oauthServer,t,r);return e.listening(r,i),i}checkAccessToken(e,t,r="imap"){let n=this.oauth&&this.oauth.verifyAccessToken(e,t,r);if(n)return n;let i=a=>{let u=this.users[a];return!!(u&&u.xoauth2&&u.xoauth2.accessToken===e)},o=t===void 0?Object.keys(this.users).find(i):i(t)?t:void 0;return o===void 0?{error:"invalid_token",reason:"unknown access token"}:{user:o}}startSmtp(){let{port:e,host:t}=this.options.smtp||{};return this.loadSmtpListener().then(({startSMTPServer:r})=>new Promise((n,i)=>{let o=r(e||0,this,a=>{o.removeListener("error",i),n(a)},t);o.once("error",i),this.smtpServer=o}))}loadSmtpListener(){return Promise.resolve().then(()=>(Ll(),Rl)).catch(e=>{throw new Error("The smtp option needs the smtp-server package, install it with: npm install smtp-server ("+e.message+")")})}stop(){return this.control.shutdown({graceful:!1})}listen(...e){this.server.listen.apply(this.server,e)}close(e){this.closeListeners(!0),this.closeImapListeners(e),this.connections.forEach(t=>{t.socket&&t.socket.destroy()})}closeImapListeners(e){let t=this.tlsServer?[this.server,this.tlsServer]:[this.server];this.tlsServer=null;let r=t.length,n;t.forEach(i=>i.close(o=>{n=n||o,--r===0&&e?.(n)}))}closeListeners(e){this.smtpServer&&(this.smtpServer.close(()=>!1),this.smtpServer=null),this.restServer&&(this.restServer.endStreams?.(),kl(this.restServer,e),this.restServer=null),this.oauthServer&&(kl(this.oauthServer,e),this.oauthServer=null)}getCredentials(){return this.options.credentials||(this.options.credentials={key:yl,cert:bl}),this.options.credentials}address(){return this.server.address()}createClient(e){let t=new ns(this,e);this.connectionHandlers.forEach(r=>{r(t)})}connect(e){let[t,r]=Tl();return t.encrypted=r.encrypted=!e||e.secure!==!1,this.createClient(t),r}registerCapability(e,t){this.capabilities[e]=t||function(){return!0}}setCommandHandler(e,t,r){e=(e||"").toString().toUpperCase(),this.commandHandlers[e]=t,r&&(this.commandOptions[e]=re(r))}getCommandOptions(e){return e=(e||"").toString().toUpperCase(),this.commandOptions[e]||Ia(e)||re()}getCommandStates(e){return this.getCommandOptions(e).states}getUser(e){return typeof e=="string"&&Object.hasOwn(this.users,e)&&this.users[e]||!1}getMailbox(e){return e.toUpperCase()==="INBOX"?this.folderCache.INBOX:this.folderCache[e]}notify(e,t,r,n){e.notification=!0;let i={command:e,mailbox:t,ignoreConnection:r,filter:n,origin:this.activeConnection};this.emit("notify",i)}mailboxChanged(e,t,r){let n=Object.assign({type:e,path:t,oldPath:null,mailbox:null},r,{origin:this.activeConnection});this.emit("mailbox",n)}withOrigin(e,t){let r=this.activeConnection;this.activeConnection=e;try{return t()}finally{this.activeConnection=r}}getCommandHandler(e){return this.commandHandlers[(e||"").toString().toUpperCase()]||!1}getStatus(e){let t=typeof e=="string"?this.getMailbox(e):e;if(!t)return!1;let r={},n=0,i=0,o=this.permanentFlagList(t),a=0,u=[];return this.connections.forEach(l=>{l.selectedMailbox===t&&l.recent&&u.push(l.recent)}),t.messages.forEach(l=>{l.flags.indexOf("\\Seen")<0?i++:n++,(l.recent||u.some(c=>c.has(l)))&&a++,l.flags.forEach(c=>{r[c]?r[c]++:r[c]=1,o.indexOf(c)<0&&o.push(c)})}),{flags:r,seen:n,unseen:i,recent:a,permanentFlags:o}}validateInternalDate(e){return ks(e)}formatInternalDate(e){let t=e.getDate(),r=St[e.getMonth()],n=e.getFullYear(),i=e.getHours(),o=e.getMinutes(),a=e.getSeconds(),u=e.getTimezoneOffset(),l=Math.floor(Math.abs(u)/60),c=Math.abs(u)%60;return(t<10?"0":"")+t+"-"+r+"-"+n+" "+(i<10?"0":"")+i+":"+(o<10?"0":"")+o+":"+(a<10?"0":"")+a+" "+(u>0?"-":"+")+(l<10?"0":"")+l+(c<10?"0":"")+c}createMailbox(e,t){if(!e)throw K("Invalid mailbox name","CANNOT");if(e.toUpperCase()==="INBOX")throw K("INBOX can not be modified","ALREADYEXISTS");let{namespace:r,storage:n}=this.getPersonalNamespace(e);if(e=this.stripSeparator(e,n.separator),this.folderCache[e]&&this.folderCache[e].flags.indexOf("\\Noselect")<0)throw K("Mailbox already exists","ALREADYEXISTS");let i=e.substr(r.length).split(n.separator);if(i.some(u=>!u))throw K("Mailbox names can not have empty hierarchy levels","CANNOT");let o=n,a=r;return a&&(a=a.substr(0,a.length-n.separator.length)),i.forEach(u=>{a+=(a.length?n.separator:"")+u;let l=this.getMailbox(a)||!1;if(l&&l.flags&&l.flags.indexOf("\\Noinferiors")>=0)throw K("Can not create subfolders for "+l.path,"CANNOT");let c=a===e,f=c&&t;if(!l||f||c&&l.flags.indexOf("\\Noselect")>=0){let p=l&&l.folders,y=f?t:{uidvalidity:++this.uidvalidityCounter};p&&(y.folders=Object.assign({},p,y.folders)),this.trackSubscription(y),this.processMailbox(a,y,r),o.folders=o.folders||{},o.folders[u]=y,this.folderCache[a]=y,l=y}o!==n?this.setChildrenFlags(o,!0):l.namespace===this.referenceNamespace&&this.inboxHoldsNamespace()&&this.setChildrenFlags(this.storage.INBOX,!0),o=l}),this.folderCache[e]}deleteMailbox(e,t){if(e.toUpperCase()==="INBOX")throw K("INBOX can not be modified","CANNOT");let{namespace:r,storage:n}=this.getPersonalNamespace(e),i=this.folderCache[this.stripSeparator(e,n.separator)];if(!i)throw K("Mailbox does not exist","NONEXISTENT");if(i.flags.indexOf("\\Noselect")>=0&&Object.keys(i.folders||{}).length)throw K("Mailbox has children, delete them first","HASCHILDREN");let o=i.path.split(n.separator),a=o.pop(),u=o.join(n.separator),l=u!=="INBOX"&&this.folderCache[u]||n;if(i.folders&&Object.keys(i.folders).length&&!t){let c={flags:["\\Noselect"],folders:i.folders};this.trackSubscription(c),this.processMailbox(i.path,c,i.namespace),l.folders[a]=c,this.folderCache[i.path]=c;return}delete this.folderCache[i.path],delete l.folders[a],l!==n?l.flags.indexOf("\\Noselect")>=0&&!Object.keys(l.folders||{}).length?this.deleteMailbox(l.path):this.setChildrenFlags(l,Object.keys(l.folders||{}).length>0):r===this.referenceNamespace&&this.inboxHoldsNamespace()&&this.setChildrenFlags(this.storage.INBOX,Object.keys(n.folders||{}).length>0)}getPersonalNamespace(e){let t="";Object.keys(this.storage).forEach(n=>{if(n==="INBOX")return;let i=n.length?n.substr(0,n.length-this.storage[n].separator.length):n;if(n.length&&(e===i||e.substr(0,n.length)===n)){if(e===i)throw K("Used mailbox name is a namespace value","CANNOT");t=n}else!t&&!n&&this.storage[n].type==="personal"&&(t=n)});let r=this.storage[t];if(!r)throw K("Unknown namespace","CANNOT");if(r.type!=="personal")throw K("Permission denied","NOPERM");return{namespace:t,storage:r}}stripSeparator(e,t){return e.substr(-t.length)===t?e.substr(0,e.length-t.length):e}inboxHoldsNamespace(){let e=this.referenceNamespace;if(e===!1)return!1;let t=this.storage[e];return!!t&&e.substr(0,e.length-t.separator.length).toUpperCase()==="INBOX"}indexFolders(e){let t=Object.create(null),r=(n,i,o,a)=>{Object.keys(o).forEach(u=>{let l=o[u],c=(n?n+(n.substr(-1)!==i?i:""):"")+u;this.processMailbox(c,l,a),t[c]=l,e&&this.processMessages(l),l.folders&&Object.keys(l.folders).length&&r(c,i,l.folders,a)})};this.storage.INBOX||(this.storage.INBOX={}),Object.keys(this.storage).forEach(n=>{n!=="INBOX"&&(this.storage[n].folders=this.storage[n].folders||{},this.storage[n].separator=this.storage[n].separator||(/[^a-z0-9]$/i.test(n)?n.substr(-1):"/"),this.storage[n].type=this.storage[n].type||"personal",this.storage[n].type==="personal"&&this.referenceNamespace===!1&&(this.referenceNamespace=n),r(n,this.storage[n].separator,this.storage[n].folders,n))}),this.referenceNamespace||(this.storage[""]=this.storage[""]||{},this.storage[""].folders=this.storage[""].folders||{},this.storage[""].separator=this.storage[""].separator||"/",this.storage[""].type="personal",this.referenceNamespace=""),this.storage.INBOX.separator||(this.storage.INBOX.separator=this.storage[this.referenceNamespace].separator),t.INBOX=this.storage.INBOX,this.processMailbox("INBOX",this.storage.INBOX,"INBOX"),e&&this.processMessages(this.storage.INBOX),this.storage.INBOX.folders&&Object.keys(this.storage.INBOX.folders).length&&r("INBOX",this.storage.INBOX.separator,this.storage.INBOX.folders,this.referenceNamespace),this.inboxHoldsNamespace()&&this.setChildrenFlags(this.storage.INBOX,Object.keys(this.storage[this.referenceNamespace].folders||{}).length>0),this.folderCache=t}processMessages(e){let t=new Set,r=e.messages;r.forEach((n,i)=>{let o=typeof n=="string"?r[i]={raw:n}:n;if(this.processMessage(o,e),t.has(o.uid))throw new Error("Duplicate UID "+o.uid+" in mailbox "+e.path);t.add(o.uid)}),e.messages.sort((n,i)=>n.uid-i.uid)}processMailbox(e,t,r){t.path=e,t.namespace=r,t.uid=t.uid||1,t.uidvalidity=t.uidvalidity||1,this.uidvalidityCounter=Math.max(this.uidvalidityCounter,t.uidvalidity),t.flags=[].concat(t.flags||[]).map(o=>sp.get(String(o).toLowerCase())||o),t.allowPermanentFlags="allowPermanentFlags"in t?t.allowPermanentFlags:!0,t.permanentFlags=[].concat(t.permanentFlags||this.systemFlags),this.trackSubscription(t,!0);let n=[].concat(t.messages||[]);t.messages=n,t.uidnext=Math.max(...[t.uidnext||1].concat(n.map(o=>((typeof o=="string"?0:o.uid)||0)+1)));let i=t;this.setChildrenFlags(i,Object.keys(i.folders||{}).length>0),this.mailboxHandlers.forEach(o=>{o(this,i)})}trackSubscription(e,t){let r=Object.getOwnPropertyDescriptor(e,"subscribed");if(r&&r.get)return;let n=r?!!r.value:t;Object.defineProperty(e,"subscribed",{enumerable:!0,configurable:!0,get:()=>this.subscriptions.has(e.path),set:i=>{i?this.subscriptions.add(e.path):this.subscriptions.delete(e.path)}}),typeof n=="boolean"&&(e.subscribed=n)}setChildrenFlags(e,t){this.removeFlag(e.flags,"\\HasChildren"),this.removeFlag(e.flags,"\\HasNoChildren"),e.flags.indexOf("\\Noinferiors")<0&&e.flags.push(t?"\\HasChildren":"\\HasNoChildren")}ensureFlag(e,t){e.indexOf(t)<0&&e.push(t)}removeFlag(e,t){let r;if(e.indexOf(t)>=0)for(r=e.length-1;r>=0;r--)e[r]===t&&e.splice(r,1)}rememberFlags(e,t){let r=e.knownFlags=e.knownFlags||[];t.forEach(n=>this.ensureFlag(r,n))}isPermanentFlag(e,t){return e.allowPermanentFlags||(e.permanentFlags||[]).indexOf(t)>=0||!!e.knownFlags&&e.knownFlags.indexOf(t)>=0}permanentFlagList(e){let t=[].concat(e.permanentFlags||[]);return(e.knownFlags||[]).forEach(r=>this.ensureFlag(t,r)),t}now(){let e=this.options.now,t=typeof e=="function"?e():e;return t==null?new Date:new Date(t)}normalizeDateTime(e){return e instanceof Date?this.formatInternalDate(e):typeof e=="string"?e.replace(/-([a-z]{3})-/i,(t,r)=>"-"+(St[ze(r)]||r)+"-"):e}processMessage(e,t){e.internaldate=this.normalizeDateTime(e.internaldate||this.now()),e.flags=[].concat(e.flags||[]),e.flags.indexOf("\\Recent")>=0&&(this.removeFlag(e.flags,"\\Recent"),e.recent=!0),this.rememberFlags(t,e.flags),e.uid=e.uid||t.uidnext++,e.uid>=t.uidnext&&(t.uidnext=e.uid+1),e.raw instanceof Uint8Array?e.raw=b.Buffer.from(e.raw).toString("binary"):typeof e.raw!="string"&&(e.raw=e.raw?String(e.raw):""),/[\u0100-\uffff]/.test(e.raw)&&(e.raw=b.Buffer.from(e.raw,"utf-8").toString("binary"));let r=e;this.messageHandlers.forEach(n=>{n(this,r,t)})}appendMessage(e,t,r,n,i,o){let a=typeof e=="string"?this.getMailbox(e):e,u=Object.assign({},o,{flags:t.filter(l=>this.isPermanentFlag(a,l)),internaldate:r,raw:n,recent:!0});a.messages.push(u),this.processMessage(u,a);for(let l of this.connections)if(l.selectedMailbox===a&&!l.readOnly&&l.recent){l.recent.add(u),delete u.recent;break}return this.emit("append",a,[u],this.activeConnection),this.notify({tag:"*",attributes:[a.messages.length,{type:"ATOM",value:"EXISTS"}],message:u},a,i),{mailbox:a,message:u}}copyMessage(e,t){let r={};return this.copyHandlers.forEach(n=>{n(this,t,r,e)}),this.appendMessage(e,[].concat(t.flags||[]),t.internaldate,t.raw,!1,r)}getNamespace(e){let t=!1;return Object.keys(this.storage).forEach(r=>{r!=="INBOX"&&e.substr(0,r.length)===r&&(t===!1||r.length>t.length)&&(t=r)}),t}targetRefusal(e){let t=this.getMailbox(e);return t?t.flags.indexOf("\\Noselect")>=0?{command:"NO",code:"TRYCREATE",text:"Target mailbox is not selectable"}:!1:{command:"NO",code:"TRYCREATE",text:"Target mailbox does not exist"}}getMailboxNamespace(e){if(e&&typeof e=="object")return e.namespace;if(e.toUpperCase()==="INBOX")return"INBOX";let t=this.getMailbox(e);return t?t.namespace:this.getNamespace(e)}isPersonal(e){let t=this.getMailboxNamespace(e);return t==="INBOX"||t!==!1&&!!this.storage[t]&&this.storage[t].type==="personal"}getSeparator(e){let t=this.getMailboxNamespace(e),r=t===!1?void 0:this.storage[t];return r&&r.separator||this.storage.INBOX.separator||"/"}getParentPath(e){let t=this.getSeparator(e);e=this.stripSeparator(e,t);let r=e.lastIndexOf(t);if(r<=0)return!1;let n=e.substr(0,r);return n.toUpperCase()==="INBOX"?"INBOX":this.storage[n+t]?!1:n}getDescendants(e,t){let r=t||this.folderCache,n=e+this.getSeparator(e);return Object.keys(r).filter(i=>i.substr(0,n.length)===n).map(i=>r[i])}hasDescendant(e,t){let r=e+this.getSeparator(e);for(let n of Object.keys(this.folderCache))if(n.substr(0,r.length)===r&&t(this.folderCache[n]))return!0;return!1}listAttributes(e,t){let r=t.exists!==!1,n=(e&&e.flags||[]).filter(i=>i!=="\\HasChildren"&&i!=="\\HasNoChildren"&&(r||i!=="\\Noselect"));return r||n.push("\\NonExistent"),t.subscribed&&n.push("\\Subscribed"),n.push(...t.extra||[]),n.indexOf("\\Noinferiors")<0&&n.push(t.hasChildren?"\\HasChildren":"\\HasNoChildren"),n}matchFolders(e,t,r,n){let i=n||this.folderCache,o=r||(p=>p),a=t.charAt(0)==="#"?t:(e||"")+t,u=(p,y="")=>new RegExp("^"+a.replace(/([\\^$+?!.():=[\]{}|,-])/g,"\\$1").replace(/[*]/g,".*").replace(/[%]/g,"[^"+p.replace(/([\\^$+*?!.():=[\]{}|,-])/g,"\\$1")+"]*")+"$",y),l=a.replace(/[*%].*$/,""),c=new Map;Object.keys(this.storage).forEach(p=>{let y=o(p),A=p===this.referenceNamespace||l.substr(0,y.length)===y;c.set(p,A?u(this.storage[p].separator):null)});let f=[];return i.INBOX&&u(this.storage.INBOX&&this.storage.INBOX.separator||"/","i").test("INBOX")&&f.push(i.INBOX),Object.keys(i).forEach(p=>{let y=i[p],A=p!=="INBOX"&&y.namespace!==!1&&y.namespace!=="INBOX"?c.get(y.namespace):null;if(!A)return;let m=o(p);A.test(m)&&(y.flags.indexOf("\\NonExistent")<0||m===a)&&f.push(y)}),f}getSubscriptionTree(){let e=Object.create(null),t=(n,i)=>{e[n]=e[n]||this.getMailbox(n)||{path:n,namespace:this.getNamespace(n),flags:["\\Noselect"],subscribed:i}},r=[...this.subscriptions].filter(n=>n==="INBOX"||this.getNamespace(n)!==!1);return r.forEach(n=>t(n,!0)),r.forEach(n=>{for(let i=this.getParentPath(n);i;i=this.getParentPath(i))t(i,!1)}),e}getMessageRange(e,t,r){let n=(t||"").toString(),i=typeof e=="string"?this.getMailbox(e):e;if(!Is(n)){let y=new Error("Invalid sequence set");throw y.imapResponse="BAD",y}let o=[],a=n.split(","),u=Array.isArray(i)?i:i.messages,l,c=u.length,f=0,p=function(y,A,m){for(let h=0,d=A.length;h<d;h++){let g=A[h].split(":"),T=g.shift(),C=Number(T==="*"?m:T)||1,H=g.pop()||C,N=Number(H==="*"&&m||H)||C;if(y>=Math.min(C,N)&&y<=Math.max(C,N))return!0}return!1};u.forEach(y=>{y.uid>f&&(f=y.uid)});for(let y=0,A=u.length;y<A;y++)l=u[y].uid||1,p(r?l:y+1,a,r?f:c)&&o.push([y+1,u[y]]);return o}},ns=class{constructor(e,t){this.server=e,this.socket=t,this.options=this.server.options,this.state="Not Authenticated",this.sessionNumber=++this.server.sessionCounter,this._outputQueue=null,this._outputTimer=null,this._deferredOutput=null,this.secureConnection=!!this.options.secureConnection||t.encrypted===!0,this._remainder="",this._command="",this._literalRemaining=0,this.inputHandler=!1,this.transport=null,this.parserOptions={},this.compilerOptions={},this.messageGlobal=!1,this._commandQueue=[],this._processing=!1,this.options.debug&&typeof this.socket.pipe=="function"&&this.socket.pipe(U.stdout),this.socket.on("data",this.receive.bind(this)),this.socket.on("close",this.onClose.bind(this)),this.socket.on("error",this.onError.bind(this)),this.directNotifications=!1,this._notificationCallback=this.onNotify.bind(this),this.notificationQueue=[],this.server.on("notify",this._notificationCallback),this.server.connections.add(this),this.emitSession("open"),this.scriptOutput("greeting",`* OK ImapKit ready for rumble\r
152
154
  `,{})}write(e){let t=typeof e=="string"?b.Buffer.from(e,"binary"):e;this._outputQueue?this._outputQueue.push({data:t,transport:this.transport}):this.writeLayer(t,this.transport)}queueOutput(e){if(!this._outputQueue&&!e.delay&&!e.chunk){e.data&&this.writeLayer(e.data,this.transport),e.close&&this.closeNow(e.close);return}this._outputQueue=this._outputQueue||[],this._outputQueue.push(Object.assign({},e,{transport:this.transport})),!this._outputTimer&&!this._outputWaiting&&this.flushOutput()}flushOutput(){let e=this._outputQueue||[];for(;e.length;){let t=e[0];if(t.delay){let r=t.delay;t.delay=0,this._outputTimer=setTimeout(()=>{this._outputTimer=null,this.flushOutput()},r);return}if(t.data&&t.chunk&&t.data.length>t.chunk){let r=t.data.subarray(0,t.chunk);if(t.data=t.data.subarray(t.chunk),!t.chunkDelay||t.chunkDelay==="tick"){this.socket?.setNoDelay?.(!0),this._outputWaiting=!0,this.writeLayer(r,t.transport||null,()=>{this._outputWaiting&&this._outputQueue===e&&(this._outputTimer=ip(()=>{this._outputTimer=null,this._outputWaiting=!1,this.flushOutput()}))});return}t.delay=t.chunkDelay,this.writeLayer(r,t.transport||null);continue}if(t.data&&this.writeLayer(t.data,t.transport||null),e.shift(),t.close){this.closeNow(t.close);return}}this._outputQueue=null}clearOutputQueue(){this._outputTimer&&(clearTimeout(this._outputTimer),D(this._outputTimer),this._outputTimer=null),this._outputWaiting=!1,this._outputQueue=null,this._deferredOutput=null}writeLayer(e,t,r){this.trace("out",e),t?(t.write(e),r&&R(r)):this.writeRaw(e,r)}trace(e,t){this.server.listenerCount("trace")&&this.server.emit("trace",{session:this.sessionNumber,direction:e,data:t})}scriptOutput(e,t,r,n){let i=this.server.script.check(this,e,Object.assign({},r,{data:t}));if(!i){this.write(t);return}let{rule:o,context:a}=i;if((o.mutate||o.literals)&&n&&a.response){let u=a.response;if(o.mutate){let c=vo(u);u=o.mutate(c,a)||c}let l=n(o.literals?wl(u):u);if(l===null)return;a.data=l}Cl(this,o,a,b.Buffer.from(a.data,"binary"))}sendContinuation(e,t,r){let n="+ "+e+`\r
153
155
  `;if(!this.server.script.watches("continuation")){this.write(n);return}let i=r?r():null;this.scriptOutput("continuation",n,i===null?{description:t}:{description:t,tag:ht(i),command:Do(i)})}writeRaw(e,t){this.socket&&!this.socket.destroyed&&(this.socket.write(e,t),this.touch())}touch(){if(!this.server.script.watches("quiet")){this._lastActivity=void 0;return}this._lastActivity=Date.now(),this._quietTimer||this.watchQuiet()}watchQuiet(e=0){if(this._quietTimer||!this.socket||this._closing)return;let t=this._lastActivity||Date.now();this._lastActivity=t;let r=this.server.script.nextQuiet(e);r!==null&&(this._quietTimer=setTimeout(()=>{if(this._quietTimer=null,!this.isOpen()||this._lastActivity!==t)return this.watchQuiet();let n=Math.max(Date.now()-t,r),i=this.server.script.check(this,"quiet",{data:"",quiet:n});i&&Nl(this,i.rule,i.context),this._lastActivity===t&&this.watchQuiet(n)},Math.max(0,r-(Date.now()-t))),this._quietTimer.unref?.())}receive(e){this.touch(),this.transport?this.transport.receive(e):this.onData(e)}end(){if(this._outputQueue&&this.socket){this._closing=!0,this._outputQueue.push({close:!0});return}this.closeNow(!0)}closeNow(e){let t=this.socket;if(t)if(this._closing=!0,this.clearOutputQueue(),e==="reset"){this.discardInput(),this._resetting=!0,t.pause();let r=this.tcpSocket;setTimeout(()=>{t.destroyed||op(t,r)},Wd)}else this.transport?this.transport.end(()=>t.end()):t.end()}bye(e,t){this.sendStatus({tag:"*"},null,"BYE",e,!1,t||"BYE"),this.closeMailbox(),this.state="Logout",this.discardInput(),this.end()}hasPendingInput(){return!!(this._remainder||this._command||this._literalRemaining||this._commandQueue.length)}isBusy(){return!!(this._processing||this._commandQueue.length)}isPipelinedAfterRefusal(){return!!this._pipelinedAfter&&this._pipelinedAfter.read===this._readCount}refusePipelined(e,t){this.sendStatus(e,t,"BAD","Commands must not be pipelined after "+this._pipelinedAfter?.command,!1,"INVALID COMMAND")}discardInput(){this._commandQueue=[],this._remainder="",this._command="",this._literalRemaining=0,this._skipCommand=!1,this._earlyLiteral=!1}resetSession(){this.closeMailbox(),this.state="Not Authenticated",this.username=!1,this.everSelected=!1,this.directNotifications=!1,this.server.resetHandlers.forEach(e=>e(this))}closeMailbox(){let e=!!this.selectedMailbox;this.state="Authenticated",this.selectedMailbox=!1,this.readOnly=!1,this.recent=null,this.notificationQueue=[],e&&this.emitSession("unselect")}onClose(){this.socket&&(this.socket.removeAllListeners(),this.socket=null),this.transport&&(this.transport.destroy(),this.transport=null),this.clearOutputQueue(),this._quietTimer&&(clearTimeout(this._quietTimer),this._quietTimer=null),this.server.removeListener("notify",this._notificationCallback),this.server.connections.delete(this)&&this.emitSession("close")}onError(e){this.options.debug&&(console.log("Socket error event emitted, %s",Date()),console.log(e.stack));try{this.socket?.end()}catch{}}handleInput(e){let t=this.inputHandler,r=this.server.script.check(this,"input",{data:e});r?Ro(this,r.rule,r.context,()=>t(e)):t(e)}onData(e){let t,r;if(this._resetting)return;if(e&&e.length&&this.trace("in",e),this._readCount=(this._readCount||0)+1,r=(e||"").toString("binary"),this._discardLine){let i=r.indexOf(`
154
156
  `);if(i<0)return;let o=this._discardLine;this._discardLine=!1,r=r.substr(i+1),this.sendBad(o,"Command line too long","LINE TOO LONG")}if(this._literalRemaining&&(r=this.readLiteral(r),this._literalRemaining))return;let n=this.server.literalPlus?/(?<marker>(?<tilde>~)?\{(?<size>\d+)(?<plus>\+)?\})?(?<cr>\r?)\n/:/(?<marker>(?<tilde>~)?\{(?<size>\d+)\})?(?<cr>\r?)\n/;for(this._remainder=r=this._remainder+r;t=n.exec(r);){let{marker:i,tilde:o,size:a,plus:u,cr:l}=t.groups;if(t.index>Lo){let f=ht(this._command||r);this.sendBad("*","Command line too long","LINE TOO LONG"),this.sendBad(f,"Command line too long","LINE TOO LONG"),this._remainder=r=r.substr(t.index+t[0].length),this._command="",this._skipCommand=!1;continue}if(!l){let f=this._command+r.substr(0,t.index+t[0].length-1);this._remainder=r=r.substr(t.index+t[0].length),this._command="",this._skipCommand?this._skipCommand=!1:this.sendBad(this.inputHandler?"*":ht(f),"Lines must end with CRLF","INVALID LINE ENDING",f);continue}if(!a||this._skipCommand&&!u){let f=this._command+r.substr(0,t.index);if(this._remainder=r.substr(t.index+t[0].length),this._command="",this._skipCommand?this._skipCommand=!1:this._earlyLiteral?(this._earlyLiteral=!1,this.sendBad(ht(f),"Literal data must wait for the continuation request","LITERAL TOO EARLY",f)):this.inputHandler?this.handleInput(f):this.scheduleCommand(f),this.upgrading)return;r=this._remainder;continue}let c=Number(a);if(!this._skipCommand){let f=this._command+r.substr(0,t.index),p=ht(f+i),y=this.checkLiteral(f,c,!u,!!o);if(y){if(u){this.sendStatus({tag:"*"},f,"BYE",y.text,y.text===Dl&&"TOOBIG","LITERAL REFUSED"),this._remainder=this._command="",this.end();return}this.sendStatus({tag:p},f,y.command,y.text,y.code||!1,"LITERAL REFUSED"),this._remainder=r=r.substr(t.index+t[0].length),this._command="";continue}u&&c>this.server.nonSyncLiteralLimit&&(this.sendStatus({tag:p},f,"BAD","Non-synchronizing literals are limited to "+this.server.nonSyncLiteralLimit+" octets","TOOBIG","LITERAL TOO BIG"),this._skipCommand=!0,this._command="")}if(!u){if(r.length>t.index+t[0].length)this._earlyLiteral=!0;else if(!this._earlyLiteral){let f=r.substr(0,t.index)+i;this.sendContinuation("Go ahead","LITERAL",()=>this._command+f)}}if(this._remainder="",this._skipCommand||(this._command+=r.substr(0,t.index+t[0].length)),this._literalRemaining=c,r=this.readLiteral(r.substr(t.index+t[0].length)),this._literalRemaining)return;this._remainder=r}if(this._remainder.length>Lo){this.sendBad("*","Command line too long","LINE TOO LONG");let i=ht(this._command||this._remainder);this._remainder="",this._command="",this._skipCommand=!1,this._discardLine=i}}readLiteral(e){let t=Math.min(this._literalRemaining,e.length);return this._skipCommand||(this._command+=e.substr(0,t)),this._literalRemaining-=t,e.substr(t)}sendBad(e,t,r,n){this.sendStatus({tag:e},n,"BAD",t,!1,r)}checkLiteral(e,t,r,n){let i=l=>({command:"BAD",text:l}),o=this.getMaxLiteralSize();if(t>o||e.length+t>o+Lo)return i(Dl);if(this.isPipelinedAfterRefusal())return i("Commands must not be pipelined after "+this._pipelinedAfter?.command);if(this.inputHandler)return n?i("Literal8 is not allowed here"):!1;let a=Do(e);if(!tp.test(a)||!this.server.getCommandHandler(a))return i("Unknown command");let u=this.server.getCommandOptions(a);if(u.states&&u.states.indexOf(this.state)<0)return i(Ul(a,this.state));if(n&&!(u.literal8===!0||u.literal8&&Object.hasOwn(this.server.capabilities,u.literal8)))return i("Literal8 is not allowed in "+a);if(r)for(let l of this.server.literalFilters){let c=l(this,a,e,t);if(c)return c}return!1}getMaxLiteralSize(){return this.state==="Not Authenticated"?Jd:Number(this.options.maxLiteralSize)||$d}getSessionMessages(){for(let e=0,t=this.notificationQueue.length;e<t;e++){let r=this.notificationQueue[e].mailboxCopy;if(r)return r}return this.selectedMailbox?this.selectedMailbox.messages:[]}getMessageRange(e,t){return this.server.getMessageRange(this.getSessionMessages(),e,t)}limitRange(e,t){return this.server.rangeLimits.reduce((r,n)=>n(this,e,r)||r,t)}getCommandRange(e,t){let r=this.getMessageRange(e,t);if(t)return r;let n=this.getSessionMessages().length;return String(e).split(/[,:]/).forEach(i=>{if(i==="*"?!n:Number(i)>n){let o=new Error(n?"Message sequence number "+i+" is greater than the number of messages ("+n+")":"The mailbox is empty");throw o.imapResponse="BAD",o}}),r}hasPendingExpunge(){return this.notificationQueue.some(vl)}notifyFlagChanges(e){this.selectedMailbox&&fn(this.server,this.selectedMailbox,e,this)}sendFlagUpdate(e,t,r){let n=this.server.fetchHandlers.FLAGS||Te.FLAGS;e.forEach(i=>{if(!(!t.has(i)||i.ghost)){if(r){if(r.has(i))return;r.add(i)}this.send({tag:"*",notification:!0,attributes:[t.get(i),{type:"ATOM",value:"FETCH"},[{type:"ATOM",value:"UID"},i.uid,{type:"ATOM",value:"FLAGS"},n(this,i,{type:"ATOM",value:"FLAGS"})]]},"FLAG NOTIFICATION",null,null,i)}})}isRecent(e){return!!(this.recent&&this.recent.has(e))}getFlags(e){return this.isRecent(e)?e.flags.concat("\\Recent"):e.flags}canSetSeen(){return!this.readOnly}readOnlyRefusal(){return this.readOnly?{command:"NO",code:"CLIENTBUG",text:"Mailbox is read-only"}:!1}refuseReadOnly(e,t,r){let n=this.readOnlyRefusal();return n&&this.sendStatus(e,t,n.command,n.text,n.code,r),!!n}canExpunge(){return!this.readOnly}onNotify(e){if(e.ignoreConnection===this||e.filter&&!e.filter(this)||!this.server.notifyFilters.every(r=>r(this,e)))return;let t=typeof e.mailbox=="string"?this.server.getMailbox(e.mailbox):e.mailbox;if(!e.mailbox||this.selectedMailbox&&this.selectedMailbox===t){let r=e.command;r.mailboxCopy&&this.notificationQueue.some(n=>n.mailboxCopy)&&(r=Object.assign({},r),delete r.mailboxCopy),this.queueNotification(r,e)}}queueNotification(e,t){this.notificationQueue.push(e),this.directNotifications&&this.processNotifications()}upgradeConnection(e){this.upgrading=!0,this.discardInput();let t=this.socket;if(typeof t.startTls=="function")return t.startTls(()=>{this.secureConnection=!0,this.upgrading=!1,e()});let r=Qe.createSecureContext(this.server.getCredentials()),n={secureContext:r,isServer:!0,server:this.server.server,SNICallback:function(a,u){u(null,r)}};this.tcpSocket=t,t.removeAllListeners(),t.on("error",this.onError.bind(this));let i=new Qe.TLSSocket(t,n),o=a=>{this.options.debug&&console.log("TLS error: %s",a.message),i.destroy()};i.on("close",this.onClose.bind(this)),i.on("error",o),i.on("clientError",o),i.on("secure",()=>{this.secureConnection=!0,this.socket=i,this.upgrading=!1,i.on("data",this.receive.bind(this)),e()})}prepareNotifications(e){return e}holdsExpunge(e){let t=this.server.getCommandOptions(e.command);return t.noExpunge||t.searchCriteria!==!1&&this.usesSequenceNumbers(e)}processNotifications(e,t){if(!this.notificationQueue.length)return;let r=this.notificationQueue,n=r.find(A=>A.mailboxCopy),i=[];if(e&&(this.holdsExpunge(e)||t&&this.usesSequenceNumbers(e))){let A=r.findIndex(vl);if(A>=0&&(i=r.slice(A),r=r.slice(0,A)),!r.length)return}this.notificationQueue=i,r=this.prepareNotifications(r);let o=r.findIndex(A=>A.mailboxCopy),a=new Map,u=A=>{let m=a.get(A);return m||(m=new Map(A.map((h,d)=>[h,d+1])),a.set(A,m)),m},l=this.selectedMailbox?this.selectedMailbox.messages:[],c=new Set,f=A=>n&&(o<0||A<o)?n.mailboxCopy:l,p=-1,y=!1;r.forEach((A,m)=>{A.flagUpdate?this.sendFlagUpdate(A.flagUpdate,u(f(m)),c):this.send(A),Bl(A)&&(p=m,y=y||!!A.message);let h=r[m+1];p<0||Bl(h)||h&&h.fetchedMessage||(y&&this.sendRecent(Number(r[p].attributes[0]),u(f(p))),p=-1,y=!1)})}sendRecent(e,t){let r=0;(this.recent||new Set).forEach(n=>{let i=t.get(n);i&&i<=e&&r++}),this.send({tag:"*",notification:!0,attributes:[r,{type:"ATOM",value:"RECENT"}]},"RECENT NOTIFICATION")}send(e,t,r,n,...i){if(!this.isOpen()||(!e.notification&&e.tag!=="*"&&this.processNotifications(r),this.server.outputHandlers.forEach(c=>{c(this,e,t,r,n,...i)}),this._commandStart&&r&&e.tag===this._commandStart.tag&&r.tag===e.tag&&this.commandCompleted(String(e.command||"").toUpperCase()),e.skipResponse))return;this.notificationQueue.length&&r&&e.tag===r.tag&&e.command==="OK"&&this.hasPendingExpunge()&&this.holdsExpunge(r)&&!(Array.isArray(e.attributes)&&e.attributes.some(c=>c&&c.type==="SECTION"))&&(e.attributes=[{type:"SECTION",section:[{type:"ATOM",value:"EXPUNGEISSUED"}]}].concat(e.attributes||[]));let o=c=>c&&c.type==="MAILBOX",a=c=>c.some(f=>o(f)||Array.isArray(f)&&a(f)),u=c=>c.map(f=>o(f)?ap(this.exportMailboxName(f.value)):Array.isArray(f)?u(f):f);if(Array.isArray(e.attributes)&&a(e.attributes)&&(e=Object.assign({},e,{attributes:u(e.attributes)})),Zd.has((e.command||"").toString().toUpperCase())&&Array.isArray(e.attributes)){let c=f=>f&&f.type==="TEXT"&&typeof f.value=="string"&&/[^\x20-\x7e]/.test(f.value);e.attributes.some(c)&&(e=Object.assign({},e,{attributes:e.attributes.map(f=>c(f)?Object.assign({},f,{value:f.value.replace(/[^\x20-\x7e]/g,"?")}):f)}))}let l=this.compileResponse(e);l!==null&&(this._deferredOutput&&No(this,r&&r.command&&r.tag&&r.tag!=="*"?r.tag:null,!1),this.scriptResponse(e,l,t,r),this._deferredOutput&&e.tag!=="*"&&e.tag!=="+"&&No(this,e.tag,!0))}scriptResponse(e,t,r,n){let i=e.tag==="+"?"continuation":"response";if(!this.server.script.watches(i)){this.write(t);return}this.scriptOutput(i,t,Object.assign({description:r||null,response:e},n&&n.command?{tag:n.tag||null,command:String(n.command).toUpperCase()}:{}),o=>this.compileResponse(o))}compileResponse(e){let t;try{t=st.compiler(e,this.compilerOptions)}catch(r){if(this.options.debug&&console.log("Failed to compile response: %s",r.message),e.tag==="*")return null;t=e.tag+" NO [SERVERBUG] Failed to compile response"}return this.options.debug&&console.log("SEND: %s",t),t+`\r