skapi-js 2.0.0-rc.6 → 2.0.0-rc.7

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.
@@ -203,8 +203,8 @@
203
203
  limitations under the License.
204
204
 
205
205
  */
206
- var zs=Object.create;var Fe=Object.defineProperty;var Gr=Object.getOwnPropertyDescriptor;var Ys=Object.getOwnPropertyNames;var Xs=Object.getPrototypeOf,Zs=Object.prototype.hasOwnProperty;var eo=(r,e,t)=>e in r?Fe(r,e,{enumerable:true,configurable:true,writable:true,value:t}):r[e]=t;var Qr=(r=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(r,{get:(e,t)=>(typeof require<"u"?require:e)[t]}):r)(function(r){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+r+'" is not supported')});var Oe=(r,e)=>()=>(r&&(e=r(r=0)),e);var W=(r,e)=>()=>(e||r((e={exports:{}}).exports,e),e.exports),dt=(r,e)=>{for(var t in e)Fe(r,t,{get:e[t],enumerable:true});},zr=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of Ys(e))!Zs.call(r,i)&&i!==t&&Fe(r,i,{get:()=>e[i],enumerable:!(n=Gr(e,i))||n.enumerable});return r};var Le=(r,e,t)=>(t=r!=null?zs(Xs(r)):{},zr(!r||!r.__esModule?Fe(t,"default",{value:r,enumerable:true}):t,r)),ne=r=>zr(Fe({},"__esModule",{value:true}),r),v=(r,e,t,n)=>{for(var i=Gr(e,t),s=r.length-1,o;s>=0;s--)(o=r[s])&&(i=(o(e,t,i))||i);return i&&Fe(e,t,i),i};var ue=(r,e,t)=>eo(r,typeof e!="symbol"?e+"":e,t);var Ie={};dt(Ie,{default:()=>ro});var to,ro,Pe=Oe(()=>{to={},ro=to;});var Zr=W(ht=>{ht.byteLength=so;ht.toByteArray=ao;ht.fromByteArray=lo;var ce=[],X=[],io=typeof Uint8Array<"u"?Uint8Array:Array,zt="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";for(xe=0,Yr=zt.length;xe<Yr;++xe)ce[xe]=zt[xe],X[zt.charCodeAt(xe)]=xe;var xe,Yr;X[45]=62;X[95]=63;function Xr(r){var e=r.length;if(e%4>0)throw new Error("Invalid string. Length must be a multiple of 4");var t=r.indexOf("=");t===-1&&(t=e);var n=t===e?0:4-t%4;return [t,n]}function so(r){var e=Xr(r),t=e[0],n=e[1];return (t+n)*3/4-n}function oo(r,e,t){return (e+t)*3/4-t}function ao(r){var e,t=Xr(r),n=t[0],i=t[1],s=new io(oo(r,n,i)),o=0,a=i>0?n-4:n,u;for(u=0;u<a;u+=4)e=X[r.charCodeAt(u)]<<18|X[r.charCodeAt(u+1)]<<12|X[r.charCodeAt(u+2)]<<6|X[r.charCodeAt(u+3)],s[o++]=e>>16&255,s[o++]=e>>8&255,s[o++]=e&255;return i===2&&(e=X[r.charCodeAt(u)]<<2|X[r.charCodeAt(u+1)]>>4,s[o++]=e&255),i===1&&(e=X[r.charCodeAt(u)]<<10|X[r.charCodeAt(u+1)]<<4|X[r.charCodeAt(u+2)]>>2,s[o++]=e>>8&255,s[o++]=e&255),s}function uo(r){return ce[r>>18&63]+ce[r>>12&63]+ce[r>>6&63]+ce[r&63]}function co(r,e,t){for(var n,i=[],s=e;s<t;s+=3)n=(r[s]<<16&16711680)+(r[s+1]<<8&65280)+(r[s+2]&255),i.push(uo(n));return i.join("")}function lo(r){for(var e,t=r.length,n=t%3,i=[],s=16383,o=0,a=t-n;o<a;o+=s)i.push(co(r,o,o+s>a?a:o+s));return n===1?(e=r[t-1],i.push(ce[e>>2]+ce[e<<4&63]+"==")):n===2&&(e=(r[t-2]<<8)+r[t-1],i.push(ce[e>>10]+ce[e>>4&63]+ce[e<<2&63]+"=")),i.join("")}});var en=W(Yt=>{Yt.read=function(r,e,t,n,i){var s,o,a=i*8-n-1,u=(1<<a)-1,c=u>>1,l=-7,d=t?i-1:0,h=t?-1:1,p=r[e+d];for(d+=h,s=p&(1<<-l)-1,p>>=-l,l+=a;l>0;s=s*256+r[e+d],d+=h,l-=8);for(o=s&(1<<-l)-1,s>>=-l,l+=n;l>0;o=o*256+r[e+d],d+=h,l-=8);if(s===0)s=1-c;else {if(s===u)return o?NaN:(p?-1:1)*(1/0);o=o+Math.pow(2,n),s=s-c;}return (p?-1:1)*o*Math.pow(2,s-n)};Yt.write=function(r,e,t,n,i,s){var o,a,u,c=s*8-i-1,l=(1<<c)-1,d=l>>1,h=i===23?Math.pow(2,-24)-Math.pow(2,-77):0,p=n?0:s-1,g=n?1:-1,_=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=l):(o=Math.floor(Math.log(e)/Math.LN2),e*(u=Math.pow(2,-o))<1&&(o--,u*=2),o+d>=1?e+=h/u:e+=h*Math.pow(2,1-d),e*u>=2&&(o++,u/=2),o+d>=l?(a=0,o=l):o+d>=1?(a=(e*u-1)*Math.pow(2,i),o=o+d):(a=e*Math.pow(2,d-1)*Math.pow(2,i),o=0));i>=8;r[t+p]=a&255,p+=g,a/=256,i-=8);for(o=o<<i|a,c+=i;c>0;r[t+p]=o&255,p+=g,o/=256,c-=8);r[t+p-g]|=_*128;};});var rn=W((vc,tn)=>{var fo={}.toString;tn.exports=Array.isArray||function(r){return fo.call(r)=="[object Array]"};});var yt=W(qe=>{var Xt=Zr(),Me=en(),on=rn();qe.Buffer=y;qe.SlowBuffer=bo;qe.INSPECT_MAX_BYTES=50;y.TYPED_ARRAY_SUPPORT=globalThis.TYPED_ARRAY_SUPPORT!==void 0?globalThis.TYPED_ARRAY_SUPPORT:ho();qe.kMaxLength=gt();function ho(){try{var r=new Uint8Array(1);return r.__proto__={__proto__:Uint8Array.prototype,foo:function(){return 42}},r.foo()===42&&typeof r.subarray=="function"&&r.subarray(1,1).byteLength===0}catch{return false}}function gt(){return y.TYPED_ARRAY_SUPPORT?2147483647:1073741823}function be(r,e){if(gt()<e)throw new RangeError("Invalid typed array length");return y.TYPED_ARRAY_SUPPORT?(r=new Uint8Array(e),r.__proto__=y.prototype):(r===null&&(r=new y(e)),r.length=e),r}function y(r,e,t){if(!y.TYPED_ARRAY_SUPPORT&&!(this instanceof y))return new y(r,e,t);if(typeof r=="number"){if(typeof e=="string")throw new Error("If encoding is specified then the first argument must be a string");return er(this,r)}return an(this,r,e,t)}y.poolSize=8192;y._augment=function(r){return r.__proto__=y.prototype,r};function an(r,e,t,n){if(typeof e=="number")throw new TypeError('"value" argument must not be a number');return typeof ArrayBuffer<"u"&&e instanceof ArrayBuffer?mo(r,e,t,n):typeof e=="string"?po(r,e,t):_o(r,e)}y.from=function(r,e,t){return an(null,r,e,t)};y.TYPED_ARRAY_SUPPORT&&(y.prototype.__proto__=Uint8Array.prototype,y.__proto__=Uint8Array,typeof Symbol<"u"&&Symbol.species&&y[Symbol.species]===y&&Object.defineProperty(y,Symbol.species,{value:null,configurable:true}));function un(r){if(typeof r!="number")throw new TypeError('"size" argument must be a number');if(r<0)throw new RangeError('"size" argument must not be negative')}function go(r,e,t,n){return un(e),e<=0?be(r,e):t!==void 0?typeof n=="string"?be(r,e).fill(t,n):be(r,e).fill(t):be(r,e)}y.alloc=function(r,e,t){return go(null,r,e,t)};function er(r,e){if(un(e),r=be(r,e<0?0:tr(e)|0),!y.TYPED_ARRAY_SUPPORT)for(var t=0;t<e;++t)r[t]=0;return r}y.allocUnsafe=function(r){return er(null,r)};y.allocUnsafeSlow=function(r){return er(null,r)};function po(r,e,t){if((typeof t!="string"||t==="")&&(t="utf8"),!y.isEncoding(t))throw new TypeError('"encoding" must be a valid string encoding');var n=cn(e,t)|0;r=be(r,n);var i=r.write(e,t);return i!==n&&(r=r.slice(0,i)),r}function Zt(r,e){var t=e.length<0?0:tr(e.length)|0;r=be(r,t);for(var n=0;n<t;n+=1)r[n]=e[n]&255;return r}function mo(r,e,t,n){if(e.byteLength,t<0||e.byteLength<t)throw new RangeError("'offset' is out of bounds");if(e.byteLength<t+(n||0))throw new RangeError("'length' is out of bounds");return t===void 0&&n===void 0?e=new Uint8Array(e):n===void 0?e=new Uint8Array(e,t):e=new Uint8Array(e,t,n),y.TYPED_ARRAY_SUPPORT?(r=e,r.__proto__=y.prototype):r=Zt(r,e),r}function _o(r,e){if(y.isBuffer(e)){var t=tr(e.length)|0;return r=be(r,t),r.length===0||e.copy(r,0,0,t),r}if(e){if(typeof ArrayBuffer<"u"&&e.buffer instanceof ArrayBuffer||"length"in e)return typeof e.length!="number"||Lo(e.length)?be(r,0):Zt(r,e);if(e.type==="Buffer"&&on(e.data))return Zt(r,e.data)}throw new TypeError("First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.")}function tr(r){if(r>=gt())throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+gt().toString(16)+" bytes");return r|0}function bo(r){return +r!=r&&(r=0),y.alloc(+r)}y.isBuffer=function(e){return !!(e!=null&&e._isBuffer)};y.compare=function(e,t){if(!y.isBuffer(e)||!y.isBuffer(t))throw new TypeError("Arguments must be Buffers");if(e===t)return 0;for(var n=e.length,i=t.length,s=0,o=Math.min(n,i);s<o;++s)if(e[s]!==t[s]){n=e[s],i=t[s];break}return n<i?-1:i<n?1:0};y.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 true;default:return false}};y.concat=function(e,t){if(!on(e))throw new TypeError('"list" argument must be an Array of Buffers');if(e.length===0)return y.alloc(0);var n;if(t===void 0)for(t=0,n=0;n<e.length;++n)t+=e[n].length;var i=y.allocUnsafe(t),s=0;for(n=0;n<e.length;++n){var o=e[n];if(!y.isBuffer(o))throw new TypeError('"list" argument must be an Array of Buffers');o.copy(i,s),s+=o.length;}return i};function cn(r,e){if(y.isBuffer(r))return r.length;if(typeof ArrayBuffer<"u"&&typeof ArrayBuffer.isView=="function"&&(ArrayBuffer.isView(r)||r instanceof ArrayBuffer))return r.byteLength;typeof r!="string"&&(r=""+r);var t=r.length;if(t===0)return 0;for(var n=false;;)switch(e){case "ascii":case "latin1":case "binary":return t;case "utf8":case "utf-8":case void 0:return pt(r).length;case "ucs2":case "ucs-2":case "utf16le":case "utf-16le":return t*2;case "hex":return t>>>1;case "base64":return mn(r).length;default:if(n)return pt(r).length;e=(""+e).toLowerCase(),n=true;}}y.byteLength=cn;function yo(r,e,t){var n=false;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(r||(r="utf8");;)switch(r){case "hex":return xo(this,e,t);case "utf8":case "utf-8":return fn(this,e,t);case "ascii":return Io(this,e,t);case "latin1":case "binary":return Po(this,e,t);case "base64":return To(this,e,t);case "ucs2":case "ucs-2":case "utf16le":case "utf-16le":return Uo(this,e,t);default:if(n)throw new TypeError("Unknown encoding: "+r);r=(r+"").toLowerCase(),n=true;}}y.prototype._isBuffer=true;function Ue(r,e,t){var n=r[e];r[e]=r[t],r[t]=n;}y.prototype.swap16=function(){var e=this.length;if(e%2!==0)throw new RangeError("Buffer size must be a multiple of 16-bits");for(var t=0;t<e;t+=2)Ue(this,t,t+1);return this};y.prototype.swap32=function(){var e=this.length;if(e%4!==0)throw new RangeError("Buffer size must be a multiple of 32-bits");for(var t=0;t<e;t+=4)Ue(this,t,t+3),Ue(this,t+1,t+2);return this};y.prototype.swap64=function(){var e=this.length;if(e%8!==0)throw new RangeError("Buffer size must be a multiple of 64-bits");for(var t=0;t<e;t+=8)Ue(this,t,t+7),Ue(this,t+1,t+6),Ue(this,t+2,t+5),Ue(this,t+3,t+4);return this};y.prototype.toString=function(){var e=this.length|0;return e===0?"":arguments.length===0?fn(this,0,e):yo.apply(this,arguments)};y.prototype.equals=function(e){if(!y.isBuffer(e))throw new TypeError("Argument must be a Buffer");return this===e?true:y.compare(this,e)===0};y.prototype.inspect=function(){var e="",t=qe.INSPECT_MAX_BYTES;return this.length>0&&(e=this.toString("hex",0,t).match(/.{2}/g).join(" "),this.length>t&&(e+=" ... ")),"<Buffer "+e+">"};y.prototype.compare=function(e,t,n,i,s){if(!y.isBuffer(e))throw new TypeError("Argument must be a Buffer");if(t===void 0&&(t=0),n===void 0&&(n=e?e.length:0),i===void 0&&(i=0),s===void 0&&(s=this.length),t<0||n>e.length||i<0||s>this.length)throw new RangeError("out of range index");if(i>=s&&t>=n)return 0;if(i>=s)return -1;if(t>=n)return 1;if(t>>>=0,n>>>=0,i>>>=0,s>>>=0,this===e)return 0;for(var o=s-i,a=n-t,u=Math.min(o,a),c=this.slice(i,s),l=e.slice(t,n),d=0;d<u;++d)if(c[d]!==l[d]){o=c[d],a=l[d];break}return o<a?-1:a<o?1:0};function ln(r,e,t,n,i){if(r.length===0)return -1;if(typeof t=="string"?(n=t,t=0):t>2147483647?t=2147483647:t<-2147483648&&(t=-2147483648),t=+t,isNaN(t)&&(t=i?0:r.length-1),t<0&&(t=r.length+t),t>=r.length){if(i)return -1;t=r.length-1;}else if(t<0)if(i)t=0;else return -1;if(typeof e=="string"&&(e=y.from(e,n)),y.isBuffer(e))return e.length===0?-1:nn(r,e,t,n,i);if(typeof e=="number")return e=e&255,y.TYPED_ARRAY_SUPPORT&&typeof Uint8Array.prototype.indexOf=="function"?i?Uint8Array.prototype.indexOf.call(r,e,t):Uint8Array.prototype.lastIndexOf.call(r,e,t):nn(r,[e],t,n,i);throw new TypeError("val must be string, number or Buffer")}function nn(r,e,t,n,i){var s=1,o=r.length,a=e.length;if(n!==void 0&&(n=String(n).toLowerCase(),n==="ucs2"||n==="ucs-2"||n==="utf16le"||n==="utf-16le")){if(r.length<2||e.length<2)return -1;s=2,o/=2,a/=2,t/=2;}function u(p,g){return s===1?p[g]:p.readUInt16BE(g*s)}var c;if(i){var l=-1;for(c=t;c<o;c++)if(u(r,c)===u(e,l===-1?0:c-l)){if(l===-1&&(l=c),c-l+1===a)return l*s}else l!==-1&&(c-=c-l),l=-1;}else for(t+a>o&&(t=o-a),c=t;c>=0;c--){for(var d=true,h=0;h<a;h++)if(u(r,c+h)!==u(e,h)){d=false;break}if(d)return c}return -1}y.prototype.includes=function(e,t,n){return this.indexOf(e,t,n)!==-1};y.prototype.indexOf=function(e,t,n){return ln(this,e,t,n,true)};y.prototype.lastIndexOf=function(e,t,n){return ln(this,e,t,n,false)};function wo(r,e,t,n){t=Number(t)||0;var i=r.length-t;n?(n=Number(n),n>i&&(n=i)):n=i;var s=e.length;if(s%2!==0)throw new TypeError("Invalid hex string");n>s/2&&(n=s/2);for(var o=0;o<n;++o){var a=parseInt(e.substr(o*2,2),16);if(isNaN(a))return o;r[t+o]=a;}return o}function Eo(r,e,t,n){return bt(pt(e,r.length-t),r,t,n)}function dn(r,e,t,n){return bt(Fo(e),r,t,n)}function Ao(r,e,t,n){return dn(r,e,t,n)}function So(r,e,t,n){return bt(mn(e),r,t,n)}function vo(r,e,t,n){return bt(Oo(e,r.length-t),r,t,n)}y.prototype.write=function(e,t,n,i){if(t===void 0)i="utf8",n=this.length,t=0;else if(n===void 0&&typeof t=="string")i=t,n=this.length,t=0;else if(isFinite(t))t=t|0,isFinite(n)?(n=n|0,i===void 0&&(i="utf8")):(i=n,n=void 0);else throw new Error("Buffer.write(string, encoding, offset[, length]) is no longer supported");var s=this.length-t;if((n===void 0||n>s)&&(n=s),e.length>0&&(n<0||t<0)||t>this.length)throw new RangeError("Attempt to write outside buffer bounds");i||(i="utf8");for(var o=false;;)switch(i){case "hex":return wo(this,e,t,n);case "utf8":case "utf-8":return Eo(this,e,t,n);case "ascii":return dn(this,e,t,n);case "latin1":case "binary":return Ao(this,e,t,n);case "base64":return So(this,e,t,n);case "ucs2":case "ucs-2":case "utf16le":case "utf-16le":return vo(this,e,t,n);default:if(o)throw new TypeError("Unknown encoding: "+i);i=(""+i).toLowerCase(),o=true;}};y.prototype.toJSON=function(){return {type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};function To(r,e,t){return e===0&&t===r.length?Xt.fromByteArray(r):Xt.fromByteArray(r.slice(e,t))}function fn(r,e,t){t=Math.min(r.length,t);for(var n=[],i=e;i<t;){var s=r[i],o=null,a=s>239?4:s>223?3:s>191?2:1;if(i+a<=t){var u,c,l,d;switch(a){case 1:s<128&&(o=s);break;case 2:u=r[i+1],(u&192)===128&&(d=(s&31)<<6|u&63,d>127&&(o=d));break;case 3:u=r[i+1],c=r[i+2],(u&192)===128&&(c&192)===128&&(d=(s&15)<<12|(u&63)<<6|c&63,d>2047&&(d<55296||d>57343)&&(o=d));break;case 4:u=r[i+1],c=r[i+2],l=r[i+3],(u&192)===128&&(c&192)===128&&(l&192)===128&&(d=(s&15)<<18|(u&63)<<12|(c&63)<<6|l&63,d>65535&&d<1114112&&(o=d));}}o===null?(o=65533,a=1):o>65535&&(o-=65536,n.push(o>>>10&1023|55296),o=56320|o&1023),n.push(o),i+=a;}return Ro(n)}var sn=4096;function Ro(r){var e=r.length;if(e<=sn)return String.fromCharCode.apply(String,r);for(var t="",n=0;n<e;)t+=String.fromCharCode.apply(String,r.slice(n,n+=sn));return t}function Io(r,e,t){var n="";t=Math.min(r.length,t);for(var i=e;i<t;++i)n+=String.fromCharCode(r[i]&127);return n}function Po(r,e,t){var n="";t=Math.min(r.length,t);for(var i=e;i<t;++i)n+=String.fromCharCode(r[i]);return n}function xo(r,e,t){var n=r.length;(!e||e<0)&&(e=0),(!t||t<0||t>n)&&(t=n);for(var i="",s=e;s<t;++s)i+=No(r[s]);return i}function Uo(r,e,t){for(var n=r.slice(e,t),i="",s=0;s<n.length;s+=2)i+=String.fromCharCode(n[s]+n[s+1]*256);return i}y.prototype.slice=function(e,t){var n=this.length;e=~~e,t=t===void 0?n:~~t,e<0?(e+=n,e<0&&(e=0)):e>n&&(e=n),t<0?(t+=n,t<0&&(t=0)):t>n&&(t=n),t<e&&(t=e);var i;if(y.TYPED_ARRAY_SUPPORT)i=this.subarray(e,t),i.__proto__=y.prototype;else {var s=t-e;i=new y(s,void 0);for(var o=0;o<s;++o)i[o]=this[o+e];}return i};function B(r,e,t){if(r%1!==0||r<0)throw new RangeError("offset is not uint");if(r+e>t)throw new RangeError("Trying to access beyond buffer length")}y.prototype.readUIntLE=function(e,t,n){e=e|0,t=t|0,n||B(e,t,this.length);for(var i=this[e],s=1,o=0;++o<t&&(s*=256);)i+=this[e+o]*s;return i};y.prototype.readUIntBE=function(e,t,n){e=e|0,t=t|0,n||B(e,t,this.length);for(var i=this[e+--t],s=1;t>0&&(s*=256);)i+=this[e+--t]*s;return i};y.prototype.readUInt8=function(e,t){return t||B(e,1,this.length),this[e]};y.prototype.readUInt16LE=function(e,t){return t||B(e,2,this.length),this[e]|this[e+1]<<8};y.prototype.readUInt16BE=function(e,t){return t||B(e,2,this.length),this[e]<<8|this[e+1]};y.prototype.readUInt32LE=function(e,t){return t||B(e,4,this.length),(this[e]|this[e+1]<<8|this[e+2]<<16)+this[e+3]*16777216};y.prototype.readUInt32BE=function(e,t){return t||B(e,4,this.length),this[e]*16777216+(this[e+1]<<16|this[e+2]<<8|this[e+3])};y.prototype.readIntLE=function(e,t,n){e=e|0,t=t|0,n||B(e,t,this.length);for(var i=this[e],s=1,o=0;++o<t&&(s*=256);)i+=this[e+o]*s;return s*=128,i>=s&&(i-=Math.pow(2,8*t)),i};y.prototype.readIntBE=function(e,t,n){e=e|0,t=t|0,n||B(e,t,this.length);for(var i=t,s=1,o=this[e+--i];i>0&&(s*=256);)o+=this[e+--i]*s;return s*=128,o>=s&&(o-=Math.pow(2,8*t)),o};y.prototype.readInt8=function(e,t){return t||B(e,1,this.length),this[e]&128?(255-this[e]+1)*-1:this[e]};y.prototype.readInt16LE=function(e,t){t||B(e,2,this.length);var n=this[e]|this[e+1]<<8;return n&32768?n|4294901760:n};y.prototype.readInt16BE=function(e,t){t||B(e,2,this.length);var n=this[e+1]|this[e]<<8;return n&32768?n|4294901760:n};y.prototype.readInt32LE=function(e,t){return t||B(e,4,this.length),this[e]|this[e+1]<<8|this[e+2]<<16|this[e+3]<<24};y.prototype.readInt32BE=function(e,t){return t||B(e,4,this.length),this[e]<<24|this[e+1]<<16|this[e+2]<<8|this[e+3]};y.prototype.readFloatLE=function(e,t){return t||B(e,4,this.length),Me.read(this,e,true,23,4)};y.prototype.readFloatBE=function(e,t){return t||B(e,4,this.length),Me.read(this,e,false,23,4)};y.prototype.readDoubleLE=function(e,t){return t||B(e,8,this.length),Me.read(this,e,true,52,8)};y.prototype.readDoubleBE=function(e,t){return t||B(e,8,this.length),Me.read(this,e,false,52,8)};function z(r,e,t,n,i,s){if(!y.isBuffer(r))throw new TypeError('"buffer" argument must be a Buffer instance');if(e>i||e<s)throw new RangeError('"value" argument is out of bounds');if(t+n>r.length)throw new RangeError("Index out of range")}y.prototype.writeUIntLE=function(e,t,n,i){if(e=+e,t=t|0,n=n|0,!i){var s=Math.pow(2,8*n)-1;z(this,e,t,n,s,0);}var o=1,a=0;for(this[t]=e&255;++a<n&&(o*=256);)this[t+a]=e/o&255;return t+n};y.prototype.writeUIntBE=function(e,t,n,i){if(e=+e,t=t|0,n=n|0,!i){var s=Math.pow(2,8*n)-1;z(this,e,t,n,s,0);}var o=n-1,a=1;for(this[t+o]=e&255;--o>=0&&(a*=256);)this[t+o]=e/a&255;return t+n};y.prototype.writeUInt8=function(e,t,n){return e=+e,t=t|0,n||z(this,e,t,1,255,0),y.TYPED_ARRAY_SUPPORT||(e=Math.floor(e)),this[t]=e&255,t+1};function mt(r,e,t,n){e<0&&(e=65535+e+1);for(var i=0,s=Math.min(r.length-t,2);i<s;++i)r[t+i]=(e&255<<8*(n?i:1-i))>>>(n?i:1-i)*8;}y.prototype.writeUInt16LE=function(e,t,n){return e=+e,t=t|0,n||z(this,e,t,2,65535,0),y.TYPED_ARRAY_SUPPORT?(this[t]=e&255,this[t+1]=e>>>8):mt(this,e,t,true),t+2};y.prototype.writeUInt16BE=function(e,t,n){return e=+e,t=t|0,n||z(this,e,t,2,65535,0),y.TYPED_ARRAY_SUPPORT?(this[t]=e>>>8,this[t+1]=e&255):mt(this,e,t,false),t+2};function _t(r,e,t,n){e<0&&(e=4294967295+e+1);for(var i=0,s=Math.min(r.length-t,4);i<s;++i)r[t+i]=e>>>(n?i:3-i)*8&255;}y.prototype.writeUInt32LE=function(e,t,n){return e=+e,t=t|0,n||z(this,e,t,4,4294967295,0),y.TYPED_ARRAY_SUPPORT?(this[t+3]=e>>>24,this[t+2]=e>>>16,this[t+1]=e>>>8,this[t]=e&255):_t(this,e,t,true),t+4};y.prototype.writeUInt32BE=function(e,t,n){return e=+e,t=t|0,n||z(this,e,t,4,4294967295,0),y.TYPED_ARRAY_SUPPORT?(this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=e&255):_t(this,e,t,false),t+4};y.prototype.writeIntLE=function(e,t,n,i){if(e=+e,t=t|0,!i){var s=Math.pow(2,8*n-1);z(this,e,t,n,s-1,-s);}var o=0,a=1,u=0;for(this[t]=e&255;++o<n&&(a*=256);)e<0&&u===0&&this[t+o-1]!==0&&(u=1),this[t+o]=(e/a>>0)-u&255;return t+n};y.prototype.writeIntBE=function(e,t,n,i){if(e=+e,t=t|0,!i){var s=Math.pow(2,8*n-1);z(this,e,t,n,s-1,-s);}var o=n-1,a=1,u=0;for(this[t+o]=e&255;--o>=0&&(a*=256);)e<0&&u===0&&this[t+o+1]!==0&&(u=1),this[t+o]=(e/a>>0)-u&255;return t+n};y.prototype.writeInt8=function(e,t,n){return e=+e,t=t|0,n||z(this,e,t,1,127,-128),y.TYPED_ARRAY_SUPPORT||(e=Math.floor(e)),e<0&&(e=255+e+1),this[t]=e&255,t+1};y.prototype.writeInt16LE=function(e,t,n){return e=+e,t=t|0,n||z(this,e,t,2,32767,-32768),y.TYPED_ARRAY_SUPPORT?(this[t]=e&255,this[t+1]=e>>>8):mt(this,e,t,true),t+2};y.prototype.writeInt16BE=function(e,t,n){return e=+e,t=t|0,n||z(this,e,t,2,32767,-32768),y.TYPED_ARRAY_SUPPORT?(this[t]=e>>>8,this[t+1]=e&255):mt(this,e,t,false),t+2};y.prototype.writeInt32LE=function(e,t,n){return e=+e,t=t|0,n||z(this,e,t,4,2147483647,-2147483648),y.TYPED_ARRAY_SUPPORT?(this[t]=e&255,this[t+1]=e>>>8,this[t+2]=e>>>16,this[t+3]=e>>>24):_t(this,e,t,true),t+4};y.prototype.writeInt32BE=function(e,t,n){return e=+e,t=t|0,n||z(this,e,t,4,2147483647,-2147483648),e<0&&(e=4294967295+e+1),y.TYPED_ARRAY_SUPPORT?(this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=e&255):_t(this,e,t,false),t+4};function hn(r,e,t,n,i,s){if(t+n>r.length)throw new RangeError("Index out of range");if(t<0)throw new RangeError("Index out of range")}function gn(r,e,t,n,i){return i||hn(r,e,t,4),Me.write(r,e,t,n,23,4),t+4}y.prototype.writeFloatLE=function(e,t,n){return gn(this,e,t,true,n)};y.prototype.writeFloatBE=function(e,t,n){return gn(this,e,t,false,n)};function pn(r,e,t,n,i){return i||hn(r,e,t,8),Me.write(r,e,t,n,52,8),t+8}y.prototype.writeDoubleLE=function(e,t,n){return pn(this,e,t,true,n)};y.prototype.writeDoubleBE=function(e,t,n){return pn(this,e,t,false,n)};y.prototype.copy=function(e,t,n,i){if(n||(n=0),!i&&i!==0&&(i=this.length),t>=e.length&&(t=e.length),t||(t=0),i>0&&i<n&&(i=n),i===n||e.length===0||this.length===0)return 0;if(t<0)throw new RangeError("targetStart out of bounds");if(n<0||n>=this.length)throw new RangeError("sourceStart out of bounds");if(i<0)throw new RangeError("sourceEnd out of bounds");i>this.length&&(i=this.length),e.length-t<i-n&&(i=e.length-t+n);var s=i-n,o;if(this===e&&n<t&&t<i)for(o=s-1;o>=0;--o)e[o+t]=this[o+n];else if(s<1e3||!y.TYPED_ARRAY_SUPPORT)for(o=0;o<s;++o)e[o+t]=this[o+n];else Uint8Array.prototype.set.call(e,this.subarray(n,n+s),t);return s};y.prototype.fill=function(e,t,n,i){if(typeof e=="string"){if(typeof t=="string"?(i=t,t=0,n=this.length):typeof n=="string"&&(i=n,n=this.length),e.length===1){var s=e.charCodeAt(0);s<256&&(e=s);}if(i!==void 0&&typeof i!="string")throw new TypeError("encoding must be a string");if(typeof i=="string"&&!y.isEncoding(i))throw new TypeError("Unknown encoding: "+i)}else typeof e=="number"&&(e=e&255);if(t<0||this.length<t||this.length<n)throw new RangeError("Out of range index");if(n<=t)return this;t=t>>>0,n=n===void 0?this.length:n>>>0,e||(e=0);var o;if(typeof e=="number")for(o=t;o<n;++o)this[o]=e;else {var a=y.isBuffer(e)?e:pt(new y(e,i).toString()),u=a.length;for(o=0;o<n-t;++o)this[o+t]=a[o%u];}return this};var Co=/[^+\/0-9A-Za-z-_]/g;function Do(r){if(r=ko(r).replace(Co,""),r.length<2)return "";for(;r.length%4!==0;)r=r+"=";return r}function ko(r){return r.trim?r.trim():r.replace(/^\s+|\s+$/g,"")}function No(r){return r<16?"0"+r.toString(16):r.toString(16)}function pt(r,e){e=e||1/0;for(var t,n=r.length,i=null,s=[],o=0;o<n;++o){if(t=r.charCodeAt(o),t>55295&&t<57344){if(!i){if(t>56319){(e-=3)>-1&&s.push(239,191,189);continue}else if(o+1===n){(e-=3)>-1&&s.push(239,191,189);continue}i=t;continue}if(t<56320){(e-=3)>-1&&s.push(239,191,189),i=t;continue}t=(i-55296<<10|t-56320)+65536;}else i&&(e-=3)>-1&&s.push(239,191,189);if(i=null,t<128){if((e-=1)<0)break;s.push(t);}else if(t<2048){if((e-=2)<0)break;s.push(t>>6|192,t&63|128);}else if(t<65536){if((e-=3)<0)break;s.push(t>>12|224,t>>6&63|128,t&63|128);}else if(t<1114112){if((e-=4)<0)break;s.push(t>>18|240,t>>12&63|128,t>>6&63|128,t&63|128);}else throw new Error("Invalid code point")}return s}function Fo(r){for(var e=[],t=0;t<r.length;++t)e.push(r.charCodeAt(t)&255);return e}function Oo(r,e){for(var t,n,i,s=[],o=0;o<r.length&&!((e-=2)<0);++o)t=r.charCodeAt(o),n=t>>8,i=t%256,s.push(i),s.push(n);return s}function mn(r){return Xt.toByteArray(Do(r))}function bt(r,e,t,n){for(var i=0;i<n&&!(i+t>=e.length||i>=r.length);++i)e[i+t]=r[i];return i}function Lo(r){return r!==r}});var _n=W(()=>{});var ar={};dt(ar,{__assign:()=>sr,__asyncDelegator:()=>Yo,__asyncGenerator:()=>zo,__asyncValues:()=>Xo,__await:()=>Xe,__awaiter:()=>Ko,__classPrivateFieldGet:()=>ra,__classPrivateFieldSet:()=>na,__createBinding:()=>Wo,__decorate:()=>Bo,__exportStar:()=>Jo,__extends:()=>qo,__generator:()=>Ho,__importDefault:()=>ta,__importStar:()=>ea,__makeTemplateObject:()=>Zo,__metadata:()=>jo,__param:()=>$o,__read:()=>bn,__rest:()=>Vo,__spread:()=>Go,__spreadArrays:()=>Qo,__values:()=>or});function qo(r,e){ir(r,e);function t(){this.constructor=r;}r.prototype=e===null?Object.create(e):(t.prototype=e.prototype,new t);}function Vo(r,e){var t={};for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&e.indexOf(n)<0&&(t[n]=r[n]);if(r!=null&&typeof Object.getOwnPropertySymbols=="function")for(var i=0,n=Object.getOwnPropertySymbols(r);i<n.length;i++)e.indexOf(n[i])<0&&Object.prototype.propertyIsEnumerable.call(r,n[i])&&(t[n[i]]=r[n[i]]);return t}function Bo(r,e,t,n){var i=arguments.length,s=i<3?e:n===null?n=Object.getOwnPropertyDescriptor(e,t):n,o;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")s=Reflect.decorate(r,e,t,n);else for(var a=r.length-1;a>=0;a--)(o=r[a])&&(s=(i<3?o(s):i>3?o(e,t,s):o(e,t))||s);return i>3&&s&&Object.defineProperty(e,t,s),s}function $o(r,e){return function(t,n){e(t,n,r);}}function jo(r,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(r,e)}function Ko(r,e,t,n){function i(s){return s instanceof t?s:new t(function(o){o(s);})}return new(t||(t=Promise))(function(s,o){function a(l){try{c(n.next(l));}catch(d){o(d);}}function u(l){try{c(n.throw(l));}catch(d){o(d);}}function c(l){l.done?s(l.value):i(l.value).then(a,u);}c((n=n.apply(r,e||[])).next());})}function Ho(r,e){var t={label:0,sent:function(){if(s[0]&1)throw s[1];return s[1]},trys:[],ops:[]},n,i,s,o;return o={next:a(0),throw:a(1),return:a(2)},typeof Symbol=="function"&&(o[Symbol.iterator]=function(){return this}),o;function a(c){return function(l){return u([c,l])}}function u(c){if(n)throw new TypeError("Generator is already executing.");for(;t;)try{if(n=1,i&&(s=c[0]&2?i.return:c[0]?i.throw||((s=i.return)&&s.call(i),0):i.next)&&!(s=s.call(i,c[1])).done)return s;switch(i=0,s&&(c=[c[0]&2,s.value]),c[0]){case 0:case 1:s=c;break;case 4:return t.label++,{value:c[1],done:!1};case 5:t.label++,i=c[1],c=[0];continue;case 7:c=t.ops.pop(),t.trys.pop();continue;default:if(s=t.trys,!(s=s.length>0&&s[s.length-1])&&(c[0]===6||c[0]===2)){t=0;continue}if(c[0]===3&&(!s||c[1]>s[0]&&c[1]<s[3])){t.label=c[1];break}if(c[0]===6&&t.label<s[1]){t.label=s[1],s=c;break}if(s&&t.label<s[2]){t.label=s[2],t.ops.push(c);break}s[2]&&t.ops.pop(),t.trys.pop();continue}c=e.call(r,t);}catch(l){c=[6,l],i=0;}finally{n=s=0;}if(c[0]&5)throw c[1];return {value:c[0]?c[1]:void 0,done:true}}}function Wo(r,e,t,n){n===void 0&&(n=t),r[n]=e[t];}function Jo(r,e){for(var t in r)t!=="default"&&!e.hasOwnProperty(t)&&(e[t]=r[t]);}function or(r){var e=typeof Symbol=="function"&&Symbol.iterator,t=e&&r[e],n=0;if(t)return t.call(r);if(r&&typeof r.length=="number")return {next:function(){return r&&n>=r.length&&(r=void 0),{value:r&&r[n++],done:!r}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")}function bn(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),i,s=[],o;try{for(;(e===void 0||e-- >0)&&!(i=n.next()).done;)s.push(i.value);}catch(a){o={error:a};}finally{try{i&&!i.done&&(t=n.return)&&t.call(n);}finally{if(o)throw o.error}}return s}function Go(){for(var r=[],e=0;e<arguments.length;e++)r=r.concat(bn(arguments[e]));return r}function Qo(){for(var r=0,e=0,t=arguments.length;e<t;e++)r+=arguments[e].length;for(var n=Array(r),i=0,e=0;e<t;e++)for(var s=arguments[e],o=0,a=s.length;o<a;o++,i++)n[i]=s[o];return n}function Xe(r){return this instanceof Xe?(this.v=r,this):new Xe(r)}function zo(r,e,t){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var n=t.apply(r,e||[]),i,s=[];return i={},o("next"),o("throw"),o("return"),i[Symbol.asyncIterator]=function(){return this},i;function o(h){n[h]&&(i[h]=function(p){return new Promise(function(g,_){s.push([h,p,g,_])>1||a(h,p);})});}function a(h,p){try{u(n[h](p));}catch(g){d(s[0][3],g);}}function u(h){h.value instanceof Xe?Promise.resolve(h.value.v).then(c,l):d(s[0][2],h);}function c(h){a("next",h);}function l(h){a("throw",h);}function d(h,p){h(p),s.shift(),s.length&&a(s[0][0],s[0][1]);}}function Yo(r){var e,t;return e={},n("next"),n("throw",function(i){throw i}),n("return"),e[Symbol.iterator]=function(){return this},e;function n(i,s){e[i]=r[i]?function(o){return (t=!t)?{value:Xe(r[i](o)),done:i==="return"}:s?s(o):o}:s;}}function Xo(r){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var e=r[Symbol.asyncIterator],t;return e?e.call(r):(r=typeof or=="function"?or(r):r[Symbol.iterator](),t={},n("next"),n("throw"),n("return"),t[Symbol.asyncIterator]=function(){return this},t);function n(s){t[s]=r[s]&&function(o){return new Promise(function(a,u){o=r[s](o),i(a,u,o.done,o.value);})};}function i(s,o,a,u){Promise.resolve(u).then(function(c){s({value:c,done:a});},o);}}function Zo(r,e){return Object.defineProperty?Object.defineProperty(r,"raw",{value:e}):r.raw=e,r}function ea(r){if(r&&r.__esModule)return r;var e={};if(r!=null)for(var t in r)Object.hasOwnProperty.call(r,t)&&(e[t]=r[t]);return e.default=r,e}function ta(r){return r&&r.__esModule?r:{default:r}}function ra(r,e){if(!e.has(r))throw new TypeError("attempted to get private field on non-instance");return e.get(r)}function na(r,e,t){if(!e.has(r))throw new TypeError("attempted to set private field on non-instance");return e.set(r,t),t}var ir,sr,ur=Oe(()=>{ir=function(r,e){return ir=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,n){t.__proto__=n;}||function(t,n){for(var i in n)n.hasOwnProperty(i)&&(t[i]=n[i]);},ir(r,e)};sr=function(){return sr=Object.assign||function(e){for(var t,n=1,i=arguments.length;n<i;n++){t=arguments[n];for(var s in t)Object.prototype.hasOwnProperty.call(t,s)&&(e[s]=t[s]);}return e},sr.apply(this,arguments)};});var cr=W(ee=>{Object.defineProperty(ee,"__esModule",{value:true});ee.MAX_HASHABLE_LENGTH=ee.INIT=ee.KEY=ee.DIGEST_LENGTH=ee.BLOCK_SIZE=void 0;ee.BLOCK_SIZE=64;ee.DIGEST_LENGTH=32;ee.KEY=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]);ee.INIT=[1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225];ee.MAX_HASHABLE_LENGTH=Math.pow(2,53)-1;});var yn=W(wt=>{Object.defineProperty(wt,"__esModule",{value:true});wt.RawSha256=void 0;var te=cr(),ia=(function(){function r(){this.state=Int32Array.from(te.INIT),this.temp=new Int32Array(64),this.buffer=new Uint8Array(64),this.bufferLength=0,this.bytesHashed=0,this.finished=false;}return r.prototype.update=function(e){if(this.finished)throw new Error("Attempted to update an already finished hash.");var t=0,n=e.byteLength;if(this.bytesHashed+=n,this.bytesHashed*8>te.MAX_HASHABLE_LENGTH)throw new Error("Cannot hash more than 2^53 - 1 bits");for(;n>0;)this.buffer[this.bufferLength++]=e[t++],n--,this.bufferLength===te.BLOCK_SIZE&&(this.hashBuffer(),this.bufferLength=0);},r.prototype.digest=function(){if(!this.finished){var e=this.bytesHashed*8,t=new DataView(this.buffer.buffer,this.buffer.byteOffset,this.buffer.byteLength),n=this.bufferLength;if(t.setUint8(this.bufferLength++,128),n%te.BLOCK_SIZE>=te.BLOCK_SIZE-8){for(var i=this.bufferLength;i<te.BLOCK_SIZE;i++)t.setUint8(i,0);this.hashBuffer(),this.bufferLength=0;}for(var i=this.bufferLength;i<te.BLOCK_SIZE-8;i++)t.setUint8(i,0);t.setUint32(te.BLOCK_SIZE-8,Math.floor(e/4294967296),true),t.setUint32(te.BLOCK_SIZE-4,e),this.hashBuffer(),this.finished=true;}for(var s=new Uint8Array(te.DIGEST_LENGTH),i=0;i<8;i++)s[i*4]=this.state[i]>>>24&255,s[i*4+1]=this.state[i]>>>16&255,s[i*4+2]=this.state[i]>>>8&255,s[i*4+3]=this.state[i]>>>0&255;return s},r.prototype.hashBuffer=function(){for(var e=this,t=e.buffer,n=e.state,i=n[0],s=n[1],o=n[2],a=n[3],u=n[4],c=n[5],l=n[6],d=n[7],h=0;h<te.BLOCK_SIZE;h++){if(h<16)this.temp[h]=(t[h*4]&255)<<24|(t[h*4+1]&255)<<16|(t[h*4+2]&255)<<8|t[h*4+3]&255;else {var p=this.temp[h-2],g=(p>>>17|p<<15)^(p>>>19|p<<13)^p>>>10;p=this.temp[h-15];var _=(p>>>7|p<<25)^(p>>>18|p<<14)^p>>>3;this.temp[h]=(g+this.temp[h-7]|0)+(_+this.temp[h-16]|0);}var w=(((u>>>6|u<<26)^(u>>>11|u<<21)^(u>>>25|u<<7))+(u&c^~u&l)|0)+(d+(te.KEY[h]+this.temp[h]|0)|0)|0,b=((i>>>2|i<<30)^(i>>>13|i<<19)^(i>>>22|i<<10))+(i&s^i&o^s&o)|0;d=l,l=c,c=u,u=a+w|0,a=o,o=s,s=i,i=w+b|0;}n[0]+=i,n[1]+=s,n[2]+=o,n[3]+=a,n[4]+=u,n[5]+=c,n[6]+=l,n[7]+=d;},r})();wt.RawSha256=ia;});var wn,En,An=Oe(()=>{wn=r=>{let e=[];for(let t=0,n=r.length;t<n;t++){let i=r.charCodeAt(t);if(i<128)e.push(i);else if(i<2048)e.push(i>>6|192,i&63|128);else if(t+1<r.length&&(i&64512)===55296&&(r.charCodeAt(t+1)&64512)===56320){let s=65536+((i&1023)<<10)+(r.charCodeAt(++t)&1023);e.push(s>>18|240,s>>12&63|128,s>>6&63|128,s&63|128);}else e.push(i>>12|224,i>>6&63|128,i&63|128);}return Uint8Array.from(e)},En=r=>{let e="";for(let t=0,n=r.length;t<n;t++){let i=r[t];if(i<128)e+=String.fromCharCode(i);else if(192<=i&&i<224){let s=r[++t];e+=String.fromCharCode((i&31)<<6|s&63);}else if(240<=i&&i<365){let o="%"+[i,r[++t],r[++t],r[++t]].map(a=>a.toString(16)).join("%");e+=decodeURIComponent(o);}else e+=String.fromCharCode((i&15)<<12|(r[++t]&63)<<6|r[++t]&63);}return e};});function Sn(r){return new TextEncoder().encode(r)}function vn(r){return new TextDecoder("utf-8").decode(r)}var Tn=Oe(()=>{});var Rn={};dt(Rn,{fromUtf8:()=>sa,toUtf8:()=>oa});var sa,oa,In=Oe(()=>{An();Tn();sa=r=>typeof TextEncoder=="function"?Sn(r):wn(r),oa=r=>typeof TextDecoder=="function"?vn(r):En(r);});var Pn=W(Et=>{Object.defineProperty(Et,"__esModule",{value:true});Et.convertToBuffer=void 0;var aa=(In(),ne(Rn)),ua=typeof Buffer<"u"&&Buffer.from?function(r){return Buffer.from(r,"utf8")}:aa.fromUtf8;function ca(r){return r instanceof Uint8Array?r:typeof r=="string"?ua(r):ArrayBuffer.isView(r)?new Uint8Array(r.buffer,r.byteOffset,r.byteLength/Uint8Array.BYTES_PER_ELEMENT):new Uint8Array(r)}Et.convertToBuffer=ca;});var xn=W(At=>{Object.defineProperty(At,"__esModule",{value:true});At.isEmptyData=void 0;function la(r){return typeof r=="string"?r.length===0:r.byteLength===0}At.isEmptyData=la;});var Un=W(St=>{Object.defineProperty(St,"__esModule",{value:true});St.numToUint8=void 0;function da(r){return new Uint8Array([(r&4278190080)>>24,(r&16711680)>>16,(r&65280)>>8,r&255])}St.numToUint8=da;});var Cn=W(vt=>{Object.defineProperty(vt,"__esModule",{value:true});vt.uint32ArrayFrom=void 0;function fa(r){if(!Array.from){for(var e=new Uint32Array(r.length),t=0;t<r.length;)e[t]=r[t];return e}return Uint32Array.from(r)}vt.uint32ArrayFrom=fa;});var Dn=W(le=>{Object.defineProperty(le,"__esModule",{value:true});le.uint32ArrayFrom=le.numToUint8=le.isEmptyData=le.convertToBuffer=void 0;var ha=Pn();Object.defineProperty(le,"convertToBuffer",{enumerable:true,get:function(){return ha.convertToBuffer}});var ga=xn();Object.defineProperty(le,"isEmptyData",{enumerable:true,get:function(){return ga.isEmptyData}});var pa=Un();Object.defineProperty(le,"numToUint8",{enumerable:true,get:function(){return pa.numToUint8}});var ma=Cn();Object.defineProperty(le,"uint32ArrayFrom",{enumerable:true,get:function(){return ma.uint32ArrayFrom}});});var Nn=W(Rt=>{Object.defineProperty(Rt,"__esModule",{value:true});Rt.Sha256=void 0;var kn=(ur(),ne(ar)),Tt=cr(),lr=yn(),dr=Dn(),_a=(function(){function r(e){if(this.hash=new lr.RawSha256,e){this.outer=new lr.RawSha256;var t=ba(e),n=new Uint8Array(Tt.BLOCK_SIZE);n.set(t);for(var i=0;i<Tt.BLOCK_SIZE;i++)t[i]^=54,n[i]^=92;this.hash.update(t),this.outer.update(n);for(var i=0;i<t.byteLength;i++)t[i]=0;}}return r.prototype.update=function(e){if(!((0, dr.isEmptyData)(e)||this.error))try{this.hash.update((0,dr.convertToBuffer)(e));}catch(t){this.error=t;}},r.prototype.digestSync=function(){if(this.error)throw this.error;return this.outer?(this.outer.finished||this.outer.update(this.hash.digest()),this.outer.digest()):this.hash.digest()},r.prototype.digest=function(){return (0, kn.__awaiter)(this,void 0,void 0,function(){return (0, kn.__generator)(this,function(e){return [2,this.digestSync()]})})},r})();Rt.Sha256=_a;function ba(r){var e=(0, dr.convertToBuffer)(r);if(e.byteLength>Tt.BLOCK_SIZE){var t=new lr.RawSha256;t.update(e),e=t.digest();}var n=new Uint8Array(Tt.BLOCK_SIZE);return n.set(e),n}});var hr=W(fr=>{Object.defineProperty(fr,"__esModule",{value:true});var ya=(ur(),ne(ar));(0, ya.__exportStar)(Nn(),fr);});var Ar={};dt(Ar,{default:()=>hu});function hu(r,e){return e=e||{},new Promise(function(t,n){var i=new XMLHttpRequest,s=[],o=[],a={},u=function(){return {ok:(i.status/100|0)==2,statusText:i.statusText,status:i.status,url:i.responseURL,text:function(){return Promise.resolve(i.responseText)},json:function(){return Promise.resolve(i.responseText).then(JSON.parse)},blob:function(){return Promise.resolve(new Blob([i.response]))},clone:u,headers:{keys:function(){return s},entries:function(){return o},get:function(l){return a[l.toLowerCase()]},has:function(l){return l.toLowerCase()in a}}}};for(var c in i.open(e.method||"get",r,true),i.onload=function(){i.getAllResponseHeaders().replace(/^(.*?):[^\S\n]*([\s\S]*?)$/gm,function(l,d,h){s.push(d=d.toLowerCase()),o.push([d,h]),a[d]=a[d]?a[d]+","+h:h;}),t(u());},i.onerror=n,i.withCredentials=e.credentials=="include",e.headers)i.setRequestHeader(c,e.headers[c]);i.send(e.body||null);})}var Sr=Oe(()=>{});var jn=W((yl,$n)=>{$n.exports=self.fetch||(self.fetch=(Sr(),ne(Ar)).default||(Sr(),ne(Ar)));});var _e=typeof globalThis<"u"?globalThis:void 0,ft=_e?.window;function no(r){if(Buffer)return Buffer.from(r).toString("base64");let e="",t=new Uint8Array(r),n=32768;for(let i=0;i<t.length;i+=n){let s=t.subarray(i,i+n);e+=String.fromCharCode.apply(null,Array.from(s));}if(typeof btoa=="function")return btoa(e);throw new Error("No base64 encoder available in this environment.")}if(ft)ft.global=ft,ft.global._runningInNodeJS=false;else if(_e&&(_e.global=_e,typeof _e.window>"u")){class r{constructor(){this.result=null;this.error=null;this.onload=null;this.onloadend=null;this.onerror=null;}readAsDataURL(n){n.arrayBuffer().then(i=>{let s=no(i),o=n.type||"application/octet-stream";this.result=`data:${o};base64,${s}`,this.onload&&this.onload({target:this}),this.onloadend&&this.onloadend({target:this});}).catch(i=>{this.error=i,this.onerror&&this.onerror({target:this});});}readAsArrayBuffer(n){n.arrayBuffer().then(i=>{this.result=i,this.onload&&this.onload({target:this}),this.onloadend&&this.onloadend({target:this});}).catch(i=>{this.error=i,this.onerror&&this.onerror({target:this});});}readAsText(n,i="utf-8"){n.text().then(s=>{this.result=s,this.onload&&this.onload({target:this}),this.onloadend&&this.onloadend({target:this});}).catch(s=>{this.error=s,this.onerror&&this.onerror({target:this});});}}_e.FileReader=r;class e{constructor(){this.status=0;this.statusText="";this.readyState=0;this.responseText="";this.response=null;this.responseType="";this.responseURL="";this.timeout=0;this.withCredentials=false;this.onload=null;this.onerror=null;this.onabort=null;this.ontimeout=null;this.onprogress=null;this.onreadystatechange=null;this.upload={onprogress:null};this._method="GET";this._url="";this._headers={};this._aborted=false;}open(n,i){this._method=n,this._url=i,this.readyState=1;}setRequestHeader(n,i){this._headers[n]=i;}getResponseHeader(n){return null}abort(){this._aborted=true,this.onabort&&this.onabort({});}send(n){if(this._aborted)return;let i={method:this._method,headers:this._headers};n&&this._method!=="GET"&&this._method!=="HEAD"&&(i.body=n),fetch(this._url,i).then(async s=>{if(!this._aborted){if(this.status=s.status,this.statusText=s.statusText,this.responseURL=s.url,this.readyState=4,this.responseType==="blob")this.response=await s.blob();else if(this.responseType==="json")try{this.response=await s.json();}catch{this.response=null;}else this.responseType==="arraybuffer"?this.response=await s.arrayBuffer():(this.responseText=await s.text(),this.response=this.responseText);this.onload&&this.onload({});}}).catch(s=>{this._aborted||this.onerror&&this.onerror(s);});}}_e.XMLHttpRequest=e,_e.window={_runningInNodeJS:true,alert:t=>console.error("[Alert]",t),sessionStorage:{getItem:t=>null,setItem:(t,n)=>{},removeItem:t=>{}},localStorage:{getItem:t=>{let n=(Pe(),ne(Ie)),i=(Pe(),ne(Ie));try{let s=i.resolve(process.cwd(),"states","localStorage",`${t}.skapi`);return n.existsSync(s)?n.readFileSync(s,"utf8"):null}catch{return null}},setItem:(t,n)=>{let i=(Pe(),ne(Ie)),s=(Pe(),ne(Ie));try{let o=s.resolve(process.cwd(),"states","localStorage");i.existsSync(o)||i.mkdirSync(o,{recursive:!0});let a=s.resolve(o,`${t}.skapi`);i.writeFileSync(a,n,"utf8");}catch{}},removeItem:t=>{let n=(Pe(),ne(Ie)),i=(Pe(),ne(Ie));try{let s=i.resolve(process.cwd(),"states","localStorage",`${t}.skapi`);n.existsSync(s)&&n.unlinkSync(s);}catch{}}},location:{href:"",origin:"",hostname:"",protocol:"",replace:t=>{}},navigator:{userAgent:`nodejs/${_e?.process?.versions?.node||"unknown"}`,mediaDevices:{getUserMedia:async t=>{throw new Error("getUserMedia is not supported in Node.js environment.")}}},addEventListener:()=>{},removeEventListener:()=>{}};}var Qt=(function(){function r(t){var n=t||{},i=n.ValidationData,s=n.Username,o=n.Password,a=n.AuthParameters,u=n.ClientMetadata;this.validationData=i||{},this.authParameters=a||{},this.clientMetadata=u||{},this.username=s,this.password=o;}var e=r.prototype;return e.getUsername=function(){return this.username},e.getPassword=function(){return this.password},e.getValidationData=function(){return this.validationData},e.getAuthParameters=function(){return this.authParameters},e.getClientMetadata=function(){return this.clientMetadata},r})();var ye=Le(yt());var Z;typeof window<"u"&&window.crypto&&(Z=window.crypto);!Z&&typeof window<"u"&&window.msCrypto&&(Z=window.msCrypto);!Z&&typeof globalThis<"u"&&globalThis.crypto&&(Z=globalThis.crypto);if(!Z&&typeof Qr=="function")try{Z=_n();}catch{}function rr(){if(Z){if(typeof Z.getRandomValues=="function")try{return Z.getRandomValues(new Uint32Array(1))[0]}catch{}if(typeof Z.randomBytes=="function")try{return Z.randomBytes(4).readInt32LE()}catch{}}throw new Error("Native crypto module could not be used to get secure random number.")}function Mo(r){for(var e=r.words,t=r.sigBytes,n=[],i=0;i<t;i++){var s=e[i>>>2]>>>24-i%4*8&255;n.push((s>>>4).toString(16)),n.push((s&15).toString(16));}return n.join("")}var nr=(function(){function r(t,n){t=this.words=t||[],n!=null?this.sigBytes=n:this.sigBytes=t.length*4;}var e=r.prototype;return e.random=function(n){for(var i=[],s=0;s<n;s+=4)i.push(rr());return new r(i,n)},e.toString=function(){return Mo(this)},r})();var Pt=Le(hr());var V=C;function C(r,e){r!=null&&this.fromString(r,e);}function J(){return new C(null)}var Se,wa=0xdeadbeefcafe,Fn=(wa&16777215)==15715070;function Ea(r,e,t,n,i,s){for(;--s>=0;){var o=e*this[r++]+t[n]+i;i=Math.floor(o/67108864),t[n++]=o&67108863;}return i}function Aa(r,e,t,n,i,s){for(var o=e&32767,a=e>>15;--s>=0;){var u=this[r]&32767,c=this[r++]>>15,l=a*u+c*o;u=o*u+((l&32767)<<15)+t[n]+(i&1073741823),i=(u>>>30)+(l>>>15)+a*c+(i>>>30),t[n++]=u&1073741823;}return i}function Sa(r,e,t,n,i,s){for(var o=e&16383,a=e>>14;--s>=0;){var u=this[r]&16383,c=this[r++]>>14,l=a*u+c*o;u=o*u+((l&16383)<<14)+t[n]+i,i=(u>>28)+(l>>14)+a*c,t[n++]=u&268435455;}return i}var On=typeof navigator<"u";On&&Fn&&navigator.appName=="Microsoft Internet Explorer"?(C.prototype.am=Aa,Se=30):On&&Fn&&navigator.appName!="Netscape"?(C.prototype.am=Ea,Se=26):(C.prototype.am=Sa,Se=28);C.prototype.DB=Se;C.prototype.DM=(1<<Se)-1;C.prototype.DV=1<<Se;var gr=52;C.prototype.FV=Math.pow(2,gr);C.prototype.F1=gr-Se;C.prototype.F2=2*Se-gr;var va="0123456789abcdefghijklmnopqrstuvwxyz",It=new Array,Ve,re;Ve=48;for(re=0;re<=9;++re)It[Ve++]=re;Ve=97;for(re=10;re<36;++re)It[Ve++]=re;Ve=65;for(re=10;re<36;++re)It[Ve++]=re;function Ln(r){return va.charAt(r)}function Ta(r,e){var t=It[r.charCodeAt(e)];return t??-1}function Ra(r){for(var e=this.t-1;e>=0;--e)r[e]=this[e];r.t=this.t,r.s=this.s;}function Ia(r){this.t=1,this.s=r<0?-1:0,r>0?this[0]=r:r<-1?this[0]=r+this.DV:this.t=0;}function pr(r){var e=J();return e.fromInt(r),e}function Pa(r,e){var t;if(e==16)t=4;else if(e==8)t=3;else if(e==2)t=1;else if(e==32)t=5;else if(e==4)t=2;else throw new Error("Only radix 2, 4, 8, 16, 32 are supported");this.t=0,this.s=0;for(var n=r.length,i=false,s=0;--n>=0;){var o=Ta(r,n);if(o<0){r.charAt(n)=="-"&&(i=true);continue}i=false,s==0?this[this.t++]=o:s+t>this.DB?(this[this.t-1]|=(o&(1<<this.DB-s)-1)<<s,this[this.t++]=o>>this.DB-s):this[this.t-1]|=o<<s,s+=t,s>=this.DB&&(s-=this.DB);}this.clamp(),i&&C.ZERO.subTo(this,this);}function xa(){for(var r=this.s&this.DM;this.t>0&&this[this.t-1]==r;)--this.t;}function Ua(r){if(this.s<0)return "-"+this.negate().toString(r);var e;if(r==16)e=4;else if(r==8)e=3;else if(r==2)e=1;else if(r==32)e=5;else if(r==4)e=2;else throw new Error("Only radix 2, 4, 8, 16, 32 are supported");var t=(1<<e)-1,n,i=false,s="",o=this.t,a=this.DB-o*this.DB%e;if(o-- >0)for(a<this.DB&&(n=this[o]>>a)>0&&(i=true,s=Ln(n));o>=0;)a<e?(n=(this[o]&(1<<a)-1)<<e-a,n|=this[--o]>>(a+=this.DB-e)):(n=this[o]>>(a-=e)&t,a<=0&&(a+=this.DB,--o)),n>0&&(i=true),i&&(s+=Ln(n));return i?s:"0"}function Ca(){var r=J();return C.ZERO.subTo(this,r),r}function Da(){return this.s<0?this.negate():this}function ka(r){var e=this.s-r.s;if(e!=0)return e;var t=this.t;if(e=t-r.t,e!=0)return this.s<0?-e:e;for(;--t>=0;)if((e=this[t]-r[t])!=0)return e;return 0}function mr(r){var e=1,t;return (t=r>>>16)!=0&&(r=t,e+=16),(t=r>>8)!=0&&(r=t,e+=8),(t=r>>4)!=0&&(r=t,e+=4),(t=r>>2)!=0&&(r=t,e+=2),(t=r>>1)!=0&&(r=t,e+=1),e}function Na(){return this.t<=0?0:this.DB*(this.t-1)+mr(this[this.t-1]^this.s&this.DM)}function Fa(r,e){var t;for(t=this.t-1;t>=0;--t)e[t+r]=this[t];for(t=r-1;t>=0;--t)e[t]=0;e.t=this.t+r,e.s=this.s;}function Oa(r,e){for(var t=r;t<this.t;++t)e[t-r]=this[t];e.t=Math.max(this.t-r,0),e.s=this.s;}function La(r,e){var t=r%this.DB,n=this.DB-t,i=(1<<n)-1,s=Math.floor(r/this.DB),o=this.s<<t&this.DM,a;for(a=this.t-1;a>=0;--a)e[a+s+1]=this[a]>>n|o,o=(this[a]&i)<<t;for(a=s-1;a>=0;--a)e[a]=0;e[s]=o,e.t=this.t+s+1,e.s=this.s,e.clamp();}function Ma(r,e){e.s=this.s;var t=Math.floor(r/this.DB);if(t>=this.t){e.t=0;return}var n=r%this.DB,i=this.DB-n,s=(1<<n)-1;e[0]=this[t]>>n;for(var o=t+1;o<this.t;++o)e[o-t-1]|=(this[o]&s)<<i,e[o-t]=this[o]>>n;n>0&&(e[this.t-t-1]|=(this.s&s)<<i),e.t=this.t-t,e.clamp();}function qa(r,e){for(var t=0,n=0,i=Math.min(r.t,this.t);t<i;)n+=this[t]-r[t],e[t++]=n&this.DM,n>>=this.DB;if(r.t<this.t){for(n-=r.s;t<this.t;)n+=this[t],e[t++]=n&this.DM,n>>=this.DB;n+=this.s;}else {for(n+=this.s;t<r.t;)n-=r[t],e[t++]=n&this.DM,n>>=this.DB;n-=r.s;}e.s=n<0?-1:0,n<-1?e[t++]=this.DV+n:n>0&&(e[t++]=n),e.t=t,e.clamp();}function Va(r,e){var t=this.abs(),n=r.abs(),i=t.t;for(e.t=i+n.t;--i>=0;)e[i]=0;for(i=0;i<n.t;++i)e[i+t.t]=t.am(0,n[i],e,i,0,t.t);e.s=0,e.clamp(),this.s!=r.s&&C.ZERO.subTo(e,e);}function Ba(r){for(var e=this.abs(),t=r.t=2*e.t;--t>=0;)r[t]=0;for(t=0;t<e.t-1;++t){var n=e.am(t,e[t],r,2*t,0,1);(r[t+e.t]+=e.am(t+1,2*e[t],r,2*t+1,n,e.t-t-1))>=e.DV&&(r[t+e.t]-=e.DV,r[t+e.t+1]=1);}r.t>0&&(r[r.t-1]+=e.am(t,e[t],r,2*t,0,1)),r.s=0,r.clamp();}function $a(r,e,t){var n=r.abs();if(!(n.t<=0)){var i=this.abs();if(i.t<n.t){e?.fromInt(0),t!=null&&this.copyTo(t);return}t==null&&(t=J());var s=J(),o=this.s,a=r.s,u=this.DB-mr(n[n.t-1]);u>0?(n.lShiftTo(u,s),i.lShiftTo(u,t)):(n.copyTo(s),i.copyTo(t));var c=s.t,l=s[c-1];if(l!=0){var d=l*(1<<this.F1)+(c>1?s[c-2]>>this.F2:0),h=this.FV/d,p=(1<<this.F1)/d,g=1<<this.F2,_=t.t,w=_-c,b=e??J();for(s.dlShiftTo(w,b),t.compareTo(b)>=0&&(t[t.t++]=1,t.subTo(b,t)),C.ONE.dlShiftTo(c,b),b.subTo(s,s);s.t<c;)s[s.t++]=0;for(;--w>=0;){var A=t[--_]==l?this.DM:Math.floor(t[_]*h+(t[_-1]+g)*p);if((t[_]+=s.am(0,A,t,w,0,c))<A)for(s.dlShiftTo(w,b),t.subTo(b,t);t[_]<--A;)t.subTo(b,t);}e!=null&&(t.drShiftTo(c,e),o!=a&&C.ZERO.subTo(e,e)),t.t=c,t.clamp(),u>0&&t.rShiftTo(u,t),o<0&&C.ZERO.subTo(t,t);}}}function ja(r){var e=J();return this.abs().divRemTo(r,null,e),this.s<0&&e.compareTo(C.ZERO)>0&&r.subTo(e,e),e}function Ka(){if(this.t<1)return 0;var r=this[0];if((r&1)==0)return 0;var e=r&3;return e=e*(2-(r&15)*e)&15,e=e*(2-(r&255)*e)&255,e=e*(2-((r&65535)*e&65535))&65535,e=e*(2-r*e%this.DV)%this.DV,e>0?this.DV-e:-e}function Ha(r){return this.compareTo(r)==0}function Wa(r,e){for(var t=0,n=0,i=Math.min(r.t,this.t);t<i;)n+=this[t]+r[t],e[t++]=n&this.DM,n>>=this.DB;if(r.t<this.t){for(n+=r.s;t<this.t;)n+=this[t],e[t++]=n&this.DM,n>>=this.DB;n+=this.s;}else {for(n+=this.s;t<r.t;)n+=r[t],e[t++]=n&this.DM,n>>=this.DB;n+=r.s;}e.s=n<0?-1:0,n>0?e[t++]=n:n<-1&&(e[t++]=this.DV+n),e.t=t,e.clamp();}function Ja(r){var e=J();return this.addTo(r,e),e}function Ga(r){var e=J();return this.subTo(r,e),e}function Qa(r){var e=J();return this.multiplyTo(r,e),e}function za(r){var e=J();return this.divRemTo(r,e,null),e}function Be(r){this.m=r,this.mp=r.invDigit(),this.mpl=this.mp&32767,this.mph=this.mp>>15,this.um=(1<<r.DB-15)-1,this.mt2=2*r.t;}function Ya(r){var e=J();return r.abs().dlShiftTo(this.m.t,e),e.divRemTo(this.m,null,e),r.s<0&&e.compareTo(C.ZERO)>0&&this.m.subTo(e,e),e}function Xa(r){var e=J();return r.copyTo(e),this.reduce(e),e}function Za(r){for(;r.t<=this.mt2;)r[r.t++]=0;for(var e=0;e<this.m.t;++e){var t=r[e]&32767,n=t*this.mpl+((t*this.mph+(r[e]>>15)*this.mpl&this.um)<<15)&r.DM;for(t=e+this.m.t,r[t]+=this.m.am(0,n,r,e,0,this.m.t);r[t]>=r.DV;)r[t]-=r.DV,r[++t]++;}r.clamp(),r.drShiftTo(this.m.t,r),r.compareTo(this.m)>=0&&r.subTo(this.m,r);}function eu(r,e){r.squareTo(e),this.reduce(e);}function tu(r,e,t){r.multiplyTo(e,t),this.reduce(t);}Be.prototype.convert=Ya;Be.prototype.revert=Xa;Be.prototype.reduce=Za;Be.prototype.mulTo=tu;Be.prototype.sqrTo=eu;function ru(r,e,t){var n=r.bitLength(),i,s=pr(1),o=new Be(e);if(n<=0)return s;n<18?i=1:n<48?i=3:n<144?i=4:n<768?i=5:i=6;var a=new Array,u=3,c=i-1,l=(1<<i)-1;if(a[1]=o.convert(this),i>1){var d=J();for(o.sqrTo(a[1],d);u<=l;)a[u]=J(),o.mulTo(d,a[u-2],a[u]),u+=2;}var h=r.t-1,p,g=true,_=J(),w;for(n=mr(r[h])-1;h>=0;){for(n>=c?p=r[h]>>n-c&l:(p=(r[h]&(1<<n+1)-1)<<c-n,h>0&&(p|=r[h-1]>>this.DB+n-c)),u=i;(p&1)==0;)p>>=1,--u;if((n-=u)<0&&(n+=this.DB,--h),g)a[p].copyTo(s),g=false;else {for(;u>1;)o.sqrTo(s,_),o.sqrTo(_,s),u-=2;u>0?o.sqrTo(s,_):(w=s,s=_,_=w),o.mulTo(_,a[p],s);}for(;h>=0&&(r[h]&1<<n)==0;)o.sqrTo(s,_),w=s,s=_,_=w,--n<0&&(n=this.DB-1,--h);}var b=o.revert(s);return t(null,b),b}C.prototype.copyTo=Ra;C.prototype.fromInt=Ia;C.prototype.fromString=Pa;C.prototype.clamp=xa;C.prototype.dlShiftTo=Fa;C.prototype.drShiftTo=Oa;C.prototype.lShiftTo=La;C.prototype.rShiftTo=Ma;C.prototype.subTo=qa;C.prototype.multiplyTo=Va;C.prototype.squareTo=Ba;C.prototype.divRemTo=$a;C.prototype.invDigit=Ka;C.prototype.addTo=Wa;C.prototype.toString=Ua;C.prototype.negate=Ca;C.prototype.abs=Da;C.prototype.compareTo=ka;C.prototype.bitLength=Na;C.prototype.mod=ja;C.prototype.equals=Ha;C.prototype.add=Ja;C.prototype.subtract=Ga;C.prototype.multiply=Qa;C.prototype.divide=za;C.prototype.modPow=ru;C.ZERO=pr(0);C.ONE=pr(1);function _r(r){return ye.Buffer.from(new nr().random(r).toString(),"hex")}var nu=/^[89a-f]/i,iu="FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E088A67CC74020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7EDEE386BFB5A899FA5AE9F24117C4B1FE649286651ECE45B3DC2007CB8A163BF0598DA48361C55D39A69163FA8FD24CF5F83655D23DCA3AD961C62F356208552BB9ED529077096966D670C354E4ABC9804F1746C08CA18217C32905E462E36CE3BE39E772C180E86039B2783A2EC07A28FB5C55DF06F4C52C9DE2BCBF6955817183995497CEA956AE515D2261898FA051015728E5A8AAAC42DAD33170D04507A33A85521ABDF1CBA64ECFB850458DBEF0A8AEA71575D060C7DB3970F85A6E1E4C7ABF5AE8CDB0933D71E8C94E04A25619DCEE3D2261AD2EE6BF12FFA06D98A0864D87602733EC86A64521F2B18177B200CBBE117577A615D6C770988C0BAD946E208E24FA074E5AB3143DB5BFCE0FD108E4B82D120A93AD2CAFFFFFFFFFFFFFFFF",su="userAttributes.",ve=(function(){function r(t){this.N=new V(iu,16),this.g=new V("2",16),this.k=new V(this.hexHash(""+this.padHex(this.N)+this.padHex(this.g)),16),this.smallAValue=this.generateRandomSmallA(),this.getLargeAValue(function(){}),this.infoBits=ye.Buffer.from("Caldera Derived Key","utf8"),this.poolName=t;}var e=r.prototype;return e.getSmallAValue=function(){return this.smallAValue},e.getLargeAValue=function(n){var i=this;this.largeAValue?n(null,this.largeAValue):this.calculateA(this.smallAValue,function(s,o){s&&n(s,null),i.largeAValue=o,n(null,i.largeAValue);});},e.generateRandomSmallA=function(){var n=_r(128).toString("hex"),i=new V(n,16);return i},e.generateRandomString=function(){return _r(40).toString("base64")},e.getRandomPassword=function(){return this.randomPassword},e.getSaltDevices=function(){return this.SaltToHashDevices},e.getVerifierDevices=function(){return this.verifierDevices},e.generateHashDevice=function(n,i,s){var o=this;this.randomPassword=this.generateRandomString();var a=""+n+i+":"+this.randomPassword,u=this.hash(a),c=_r(16).toString("hex");this.SaltToHashDevices=this.padHex(new V(c,16)),this.g.modPow(new V(this.hexHash(this.SaltToHashDevices+u),16),this.N,function(l,d){l&&s(l,null),o.verifierDevices=o.padHex(d),s(null,null);});},e.calculateA=function(n,i){var s=this;this.g.modPow(n,this.N,function(o,a){o&&i(o,null),a.mod(s.N).equals(V.ZERO)&&i(new Error("Illegal paramater. A mod N cannot be 0."),null),i(null,a);});},e.calculateU=function(n,i){this.UHexHash=this.hexHash(this.padHex(n)+this.padHex(i));var s=new V(this.UHexHash,16);return s},e.hash=function(n){var i=new Pt.Sha256;i.update(n);var s=i.digestSync(),o=ye.Buffer.from(s).toString("hex");return new Array(64-o.length).join("0")+o},e.hexHash=function(n){return this.hash(ye.Buffer.from(n,"hex"))},e.computehkdf=function(n,i){var s=ye.Buffer.concat([this.infoBits,ye.Buffer.from("","utf8")]),o=new Pt.Sha256(i);o.update(n);var a=o.digestSync(),u=new Pt.Sha256(a);u.update(s);var c=u.digestSync(),l=c,d=l.slice(0,16);return d},e.getPasswordAuthenticationKey=function(n,i,s,o,a){var u=this;if(s.mod(this.N).equals(V.ZERO))throw new Error("B cannot be zero.");if(this.UValue=this.calculateU(this.largeAValue,s),this.UValue.equals(V.ZERO))throw new Error("U cannot be zero.");var c=""+this.poolName+n+":"+i,l=this.hash(c),d=new V(this.hexHash(this.padHex(o)+l),16);this.calculateS(d,s,function(h,p){h&&a(h,null);var g=u.computehkdf(ye.Buffer.from(u.padHex(p),"hex"),ye.Buffer.from(u.padHex(u.UValue),"hex"));a(null,g);});},e.calculateS=function(n,i,s){var o=this;this.g.modPow(n,this.N,function(a,u){a&&s(a,null);var c=i.subtract(o.k.multiply(u));c.modPow(o.smallAValue.add(o.UValue.multiply(n)),o.N,function(l,d){l&&s(l,null),s(null,d.mod(o.N));});});},e.getNewPasswordRequiredChallengeUserAttributePrefix=function(){return su},e.padHex=function(n){if(!(n instanceof V))throw new Error("Not a BigInteger");var i=n.compareTo(V.ZERO)<0,s=n.abs().toString(16);if(s=s.length%2!==0?"0"+s:s,s=nu.test(s)?"00"+s:s,i){var o=s.split("").map(function(u){var c=~parseInt(u,16)&15;return "0123456789ABCDEF".charAt(c)}).join(""),a=new V(o,16).add(V.ONE);s=a.toString(16),s.toUpperCase().startsWith("FF8")&&(s=s.substring(2));}return s},r})();var Mn=Le(yt());var xt=(function(){function r(t){this.jwtToken=t||"",this.payload=this.decodePayload();}var e=r.prototype;return e.getJwtToken=function(){return this.jwtToken},e.getExpiration=function(){return this.payload.exp},e.getIssuedAt=function(){return this.payload.iat},e.decodePayload=function(){var n=this.jwtToken.split(".")[1];try{return JSON.parse(Mn.Buffer.from(n,"base64").toString("utf8"))}catch{return {}}},r})();function ou(r,e){r.prototype=Object.create(e.prototype),r.prototype.constructor=r,br(r,e);}function br(r,e){return br=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(t,n){return t.__proto__=n,t},br(r,e)}var $e=(function(r){function e(t){var n=t===void 0?{}:t,i=n.AccessToken;return r.call(this,i||"")||this}return ou(e,r),e})(xt);function au(r,e){r.prototype=Object.create(e.prototype),r.prototype.constructor=r,yr(r,e);}function yr(r,e){return yr=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(t,n){return t.__proto__=n,t},yr(r,e)}var je=(function(r){function e(t){var n=t===void 0?{}:t,i=n.IdToken;return r.call(this,i||"")||this}return au(e,r),e})(xt);var Ke=(function(){function r(t){var n=t===void 0?{}:t,i=n.RefreshToken;this.token=i||"";}var e=r.prototype;return e.getToken=function(){return this.token},r})();var $=Le(yt()),Er=Le(hr());var qn="5.0.4";var uu="aws-amplify/"+qn,wr={userAgent:uu,isReactNative:typeof navigator<"u"&&navigator.product==="ReactNative"},Vn=function(){return wr.userAgent};var He=(function(){function r(t){var n=t===void 0?{}:t,i=n.IdToken,s=n.RefreshToken,o=n.AccessToken,a=n.ClockDrift;if(o==null||i==null)throw new Error("Id token and Access Token must be present.");this.idToken=i,this.refreshToken=s,this.accessToken=o,this.clockDrift=a===void 0?this.calculateClockDrift():a;}var e=r.prototype;return e.getIdToken=function(){return this.idToken},e.getRefreshToken=function(){return this.refreshToken},e.getAccessToken=function(){return this.accessToken},e.getClockDrift=function(){return this.clockDrift},e.calculateClockDrift=function(){var n=Math.floor(new Date/1e3),i=Math.min(this.accessToken.getIssuedAt(),this.idToken.getIssuedAt());return n-i},e.isValid=function(){var n=Math.floor(new Date/1e3),i=n-this.clockDrift;return i<this.accessToken.getExpiration()&&i<this.idToken.getExpiration()},r})();var cu=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],lu=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],Ut=(function(){function r(){}var e=r.prototype;return e.getNowString=function(){var n=new Date,i=lu[n.getUTCDay()],s=cu[n.getUTCMonth()],o=n.getUTCDate(),a=n.getUTCHours();a<10&&(a="0"+a);var u=n.getUTCMinutes();u<10&&(u="0"+u);var c=n.getUTCSeconds();c<10&&(c="0"+c);var l=n.getUTCFullYear(),d=i+" "+s+" "+o+" "+a+":"+u+":"+c+" UTC "+l;return d},r})();var de=(function(){function r(t){var n=t===void 0?{}:t,i=n.Name,s=n.Value;this.Name=i||"",this.Value=s||"";}var e=r.prototype;return e.getValue=function(){return this.Value},e.setValue=function(n){return this.Value=n,this},e.getName=function(){return this.Name},e.setName=function(n){return this.Name=n,this},e.toString=function(){return JSON.stringify(this)},e.toJSON=function(){return {Name:this.Name,Value:this.Value}},r})();var Ce={},du=(function(){function r(){}return r.setItem=function(t,n){return Ce[t]=n,Ce[t]},r.getItem=function(t){return Object.prototype.hasOwnProperty.call(Ce,t)?Ce[t]:void 0},r.removeItem=function(t){return delete Ce[t]},r.clear=function(){return Ce={},Ce},r})(),Ct=(function(){function r(){try{this.storageWindow=window.localStorage,this.storageWindow.setItem("aws.cognito.test-ls",1),this.storageWindow.removeItem("aws.cognito.test-ls");}catch{this.storageWindow=du;}}var e=r.prototype;return e.getStorage=function(){return this.storageWindow},r})();var fu=typeof navigator<"u",Bn=fu?wr.isReactNative?"react-native":navigator.userAgent:"nodejs",we=(function(){function r(t){if(t==null||t.Username==null||t.Pool==null)throw new Error("Username and Pool information are required.");this.username=t.Username||"",this.pool=t.Pool,this.Session=null,this.client=t.Pool.client,this.signInUserSession=null,this.authenticationFlowType="USER_SRP_AUTH",this.storage=t.Storage||new Ct().getStorage(),this.keyPrefix="CognitoIdentityServiceProvider."+this.pool.getClientId(),this.userDataKey=this.keyPrefix+"."+this.username+".userData";}var e=r.prototype;return e.setSignInUserSession=function(n){this.clearCachedUserData(),this.signInUserSession=n,this.cacheTokens();},e.getSignInUserSession=function(){return this.signInUserSession},e.getUsername=function(){return this.username},e.getAuthenticationFlowType=function(){return this.authenticationFlowType},e.setAuthenticationFlowType=function(n){this.authenticationFlowType=n;},e.initiateAuth=function(n,i){var s=this,o=n.getAuthParameters();o.USERNAME=this.username;var a=Object.keys(n.getValidationData()).length!==0?n.getValidationData():n.getClientMetadata(),u={AuthFlow:"CUSTOM_AUTH",ClientId:this.pool.getClientId(),AuthParameters:o,ClientMetadata:a};this.getUserContextData()&&(u.UserContextData=this.getUserContextData()),this.client.request("InitiateAuth",u,function(c,l){if(c)return i.onFailure(c);var d=l.ChallengeName,h=l.ChallengeParameters;return d==="CUSTOM_CHALLENGE"?(s.Session=l.Session,i.customChallenge(h)):(s.signInUserSession=s.getCognitoUserSession(l.AuthenticationResult),s.cacheTokens(),i.onSuccess(s.signInUserSession))});},e.authenticateUser=function(n,i){return this.authenticationFlowType==="USER_PASSWORD_AUTH"?this.authenticateUserPlainUsernamePassword(n,i):this.authenticationFlowType==="USER_SRP_AUTH"||this.authenticationFlowType==="CUSTOM_AUTH"?this.authenticateUserDefaultAuth(n,i):i.onFailure(new Error("Authentication flow type is invalid."))},e.authenticateUserDefaultAuth=function(n,i){var s=this,o=new ve(this.pool.getUserPoolName()),a=new Ut,u,c,l={};this.deviceKey!=null&&(l.DEVICE_KEY=this.deviceKey),l.USERNAME=this.username,o.getLargeAValue(function(d,h){d&&i.onFailure(d),l.SRP_A=h.toString(16),s.authenticationFlowType==="CUSTOM_AUTH"&&(l.CHALLENGE_NAME="SRP_A");var p=Object.keys(n.getValidationData()).length!==0?n.getValidationData():n.getClientMetadata(),g={AuthFlow:s.authenticationFlowType,ClientId:s.pool.getClientId(),AuthParameters:l,ClientMetadata:p};s.getUserContextData(s.username)&&(g.UserContextData=s.getUserContextData(s.username)),s.client.request("InitiateAuth",g,function(_,w){if(_)return i.onFailure(_);var b=w.ChallengeParameters;s.username=b.USER_ID_FOR_SRP,s.userDataKey=s.keyPrefix+"."+s.username+".userData",u=new V(b.SRP_B,16),c=new V(b.SALT,16),s.getCachedDeviceKeyAndPassword(),o.getPasswordAuthenticationKey(s.username,n.getPassword(),u,c,function(A,x){A&&i.onFailure(A);var I=a.getNowString(),D=$.Buffer.concat([$.Buffer.from(s.pool.getUserPoolName(),"utf8"),$.Buffer.from(s.username,"utf8"),$.Buffer.from(b.SECRET_BLOCK,"base64"),$.Buffer.from(I,"utf8")]),F=new Er.Sha256(x);F.update(D);var Q=F.digestSync(),O=$.Buffer.from(Q).toString("base64"),P={};P.USERNAME=s.username,P.PASSWORD_CLAIM_SECRET_BLOCK=b.SECRET_BLOCK,P.TIMESTAMP=I,P.PASSWORD_CLAIM_SIGNATURE=O,s.deviceKey!=null&&(P.DEVICE_KEY=s.deviceKey);var k=function(Ne,Jr){return s.client.request("RespondToAuthChallenge",Ne,function(lt,Qs){return lt&&lt.code==="ResourceNotFoundException"&&lt.message.toLowerCase().indexOf("device")!==-1?(P.DEVICE_KEY=null,s.deviceKey=null,s.randomPassword=null,s.deviceGroupKey=null,s.clearCachedDeviceKeyAndPassword(),k(Ne,Jr)):Jr(lt,Qs)})},N={ChallengeName:"PASSWORD_VERIFIER",ClientId:s.pool.getClientId(),ChallengeResponses:P,Session:w.Session,ClientMetadata:p};s.getUserContextData()&&(N.UserContextData=s.getUserContextData()),k(N,function(L,Ne){return L?i.onFailure(L):s.authenticateUserInternal(Ne,o,i)});});});});},e.authenticateUserPlainUsernamePassword=function(n,i){var s=this,o={};if(o.USERNAME=this.username,o.PASSWORD=n.getPassword(),!o.PASSWORD){i.onFailure(new Error("PASSWORD parameter is required"));return}var a=new ve(this.pool.getUserPoolName());this.getCachedDeviceKeyAndPassword(),this.deviceKey!=null&&(o.DEVICE_KEY=this.deviceKey);var u=Object.keys(n.getValidationData()).length!==0?n.getValidationData():n.getClientMetadata(),c={AuthFlow:"USER_PASSWORD_AUTH",ClientId:this.pool.getClientId(),AuthParameters:o,ClientMetadata:u};this.getUserContextData(this.username)&&(c.UserContextData=this.getUserContextData(this.username)),this.client.request("InitiateAuth",c,function(l,d){return l?i.onFailure(l):s.authenticateUserInternal(d,a,i)});},e.authenticateUserInternal=function(n,i,s){var o=this,a=n.ChallengeName,u=n.ChallengeParameters;if(a==="SMS_MFA")return this.Session=n.Session,s.mfaRequired(a,u);if(a==="SELECT_MFA_TYPE")return this.Session=n.Session,s.selectMFAType(a,u);if(a==="MFA_SETUP")return this.Session=n.Session,s.mfaSetup(a,u);if(a==="SOFTWARE_TOKEN_MFA")return this.Session=n.Session,s.totpRequired(a,u);if(a==="CUSTOM_CHALLENGE")return this.Session=n.Session,s.customChallenge(u);if(a==="NEW_PASSWORD_REQUIRED"){this.Session=n.Session;var c=null,l=null,d=[],h=i.getNewPasswordRequiredChallengeUserAttributePrefix();if(u&&(c=JSON.parse(n.ChallengeParameters.userAttributes),l=JSON.parse(n.ChallengeParameters.requiredAttributes)),l)for(var p=0;p<l.length;p++)d[p]=l[p].substr(h.length);return s.newPasswordRequired(c,d)}if(a==="DEVICE_SRP_AUTH"){this.Session=n.Session,this.getDeviceResponse(s);return}this.signInUserSession=this.getCognitoUserSession(n.AuthenticationResult),this.challengeName=a,this.cacheTokens();var g=n.AuthenticationResult.NewDeviceMetadata;if(g==null)return s.onSuccess(this.signInUserSession);i.generateHashDevice(n.AuthenticationResult.NewDeviceMetadata.DeviceGroupKey,n.AuthenticationResult.NewDeviceMetadata.DeviceKey,function(_){if(_)return s.onFailure(_);var w={Salt:$.Buffer.from(i.getSaltDevices(),"hex").toString("base64"),PasswordVerifier:$.Buffer.from(i.getVerifierDevices(),"hex").toString("base64")};o.verifierDevices=w.PasswordVerifier,o.deviceGroupKey=g.DeviceGroupKey,o.randomPassword=i.getRandomPassword(),o.client.request("ConfirmDevice",{DeviceKey:g.DeviceKey,AccessToken:o.signInUserSession.getAccessToken().getJwtToken(),DeviceSecretVerifierConfig:w,DeviceName:Bn},function(b,A){return b?s.onFailure(b):(o.deviceKey=n.AuthenticationResult.NewDeviceMetadata.DeviceKey,o.cacheDeviceKeyAndPassword(),A.UserConfirmationNecessary===true?s.onSuccess(o.signInUserSession,A.UserConfirmationNecessary):s.onSuccess(o.signInUserSession))});});},e.completeNewPasswordChallenge=function(n,i,s,o){var a=this;if(!n)return s.onFailure(new Error("New password is required."));var u=new ve(this.pool.getUserPoolName()),c=u.getNewPasswordRequiredChallengeUserAttributePrefix(),l={};i&&Object.keys(i).forEach(function(h){l[c+h]=i[h];}),l.NEW_PASSWORD=n,l.USERNAME=this.username;var d={ChallengeName:"NEW_PASSWORD_REQUIRED",ClientId:this.pool.getClientId(),ChallengeResponses:l,Session:this.Session,ClientMetadata:o};this.getUserContextData()&&(d.UserContextData=this.getUserContextData()),this.client.request("RespondToAuthChallenge",d,function(h,p){return h?s.onFailure(h):a.authenticateUserInternal(p,u,s)});},e.getDeviceResponse=function(n,i){var s=this,o=new ve(this.deviceGroupKey),a=new Ut,u={};u.USERNAME=this.username,u.DEVICE_KEY=this.deviceKey,o.getLargeAValue(function(c,l){c&&n.onFailure(c),u.SRP_A=l.toString(16);var d={ChallengeName:"DEVICE_SRP_AUTH",ClientId:s.pool.getClientId(),ChallengeResponses:u,ClientMetadata:i,Session:s.Session};s.getUserContextData()&&(d.UserContextData=s.getUserContextData()),s.client.request("RespondToAuthChallenge",d,function(h,p){if(h)return n.onFailure(h);var g=p.ChallengeParameters,_=new V(g.SRP_B,16),w=new V(g.SALT,16);o.getPasswordAuthenticationKey(s.deviceKey,s.randomPassword,_,w,function(b,A){if(b)return n.onFailure(b);var x=a.getNowString(),I=$.Buffer.concat([$.Buffer.from(s.deviceGroupKey,"utf8"),$.Buffer.from(s.deviceKey,"utf8"),$.Buffer.from(g.SECRET_BLOCK,"base64"),$.Buffer.from(x,"utf8")]),D=new Er.Sha256(A);D.update(I);var F=D.digestSync(),Q=$.Buffer.from(F).toString("base64"),O={};O.USERNAME=s.username,O.PASSWORD_CLAIM_SECRET_BLOCK=g.SECRET_BLOCK,O.TIMESTAMP=x,O.PASSWORD_CLAIM_SIGNATURE=Q,O.DEVICE_KEY=s.deviceKey;var P={ChallengeName:"DEVICE_PASSWORD_VERIFIER",ClientId:s.pool.getClientId(),ChallengeResponses:O,Session:p.Session};s.getUserContextData()&&(P.UserContextData=s.getUserContextData()),s.client.request("RespondToAuthChallenge",P,function(k,N){return k?n.onFailure(k):(s.signInUserSession=s.getCognitoUserSession(N.AuthenticationResult),s.cacheTokens(),n.onSuccess(s.signInUserSession))});});});});},e.confirmRegistration=function(n,i,s,o){var a={ClientId:this.pool.getClientId(),ConfirmationCode:n,Username:this.username,ForceAliasCreation:i,ClientMetadata:o};this.getUserContextData()&&(a.UserContextData=this.getUserContextData()),this.client.request("ConfirmSignUp",a,function(u){return u?s(u,null):s(null,"SUCCESS")});},e.sendCustomChallengeAnswer=function(n,i,s){var o=this,a={};a.USERNAME=this.username,a.ANSWER=n;var u=new ve(this.pool.getUserPoolName());this.getCachedDeviceKeyAndPassword(),this.deviceKey!=null&&(a.DEVICE_KEY=this.deviceKey);var c={ChallengeName:"CUSTOM_CHALLENGE",ChallengeResponses:a,ClientId:this.pool.getClientId(),Session:this.Session,ClientMetadata:s};this.getUserContextData()&&(c.UserContextData=this.getUserContextData()),this.client.request("RespondToAuthChallenge",c,function(l,d){return l?i.onFailure(l):o.authenticateUserInternal(d,u,i)});},e.sendMFACode=function(n,i,s,o){var a=this,u={};u.USERNAME=this.username,u.SMS_MFA_CODE=n;var c=s||"SMS_MFA";c==="SOFTWARE_TOKEN_MFA"&&(u.SOFTWARE_TOKEN_MFA_CODE=n),this.deviceKey!=null&&(u.DEVICE_KEY=this.deviceKey);var l={ChallengeName:c,ChallengeResponses:u,ClientId:this.pool.getClientId(),Session:this.Session,ClientMetadata:o};this.getUserContextData()&&(l.UserContextData=this.getUserContextData()),this.client.request("RespondToAuthChallenge",l,function(d,h){if(d)return i.onFailure(d);var p=h.ChallengeName;if(p==="DEVICE_SRP_AUTH"){a.getDeviceResponse(i);return}if(a.signInUserSession=a.getCognitoUserSession(h.AuthenticationResult),a.cacheTokens(),h.AuthenticationResult.NewDeviceMetadata==null)return i.onSuccess(a.signInUserSession);var g=new ve(a.pool.getUserPoolName());g.generateHashDevice(h.AuthenticationResult.NewDeviceMetadata.DeviceGroupKey,h.AuthenticationResult.NewDeviceMetadata.DeviceKey,function(_){if(_)return i.onFailure(_);var w={Salt:$.Buffer.from(g.getSaltDevices(),"hex").toString("base64"),PasswordVerifier:$.Buffer.from(g.getVerifierDevices(),"hex").toString("base64")};a.verifierDevices=w.PasswordVerifier,a.deviceGroupKey=h.AuthenticationResult.NewDeviceMetadata.DeviceGroupKey,a.randomPassword=g.getRandomPassword(),a.client.request("ConfirmDevice",{DeviceKey:h.AuthenticationResult.NewDeviceMetadata.DeviceKey,AccessToken:a.signInUserSession.getAccessToken().getJwtToken(),DeviceSecretVerifierConfig:w,DeviceName:Bn},function(b,A){return b?i.onFailure(b):(a.deviceKey=h.AuthenticationResult.NewDeviceMetadata.DeviceKey,a.cacheDeviceKeyAndPassword(),A.UserConfirmationNecessary===true?i.onSuccess(a.signInUserSession,A.UserConfirmationNecessary):i.onSuccess(a.signInUserSession))});});});},e.changePassword=function(n,i,s,o){if(!(this.signInUserSession!=null&&this.signInUserSession.isValid()))return s(new Error("User is not authenticated"),null);this.client.request("ChangePassword",{PreviousPassword:n,ProposedPassword:i,AccessToken:this.signInUserSession.getAccessToken().getJwtToken(),ClientMetadata:o},function(a){return a?s(a,null):s(null,"SUCCESS")});},e.enableMFA=function(n){if(this.signInUserSession==null||!this.signInUserSession.isValid())return n(new Error("User is not authenticated"),null);var i=[],s={DeliveryMedium:"SMS",AttributeName:"phone_number"};i.push(s),this.client.request("SetUserSettings",{MFAOptions:i,AccessToken:this.signInUserSession.getAccessToken().getJwtToken()},function(o){return o?n(o,null):n(null,"SUCCESS")});},e.setUserMfaPreference=function(n,i,s){if(this.signInUserSession==null||!this.signInUserSession.isValid())return s(new Error("User is not authenticated"),null);this.client.request("SetUserMFAPreference",{SMSMfaSettings:n,SoftwareTokenMfaSettings:i,AccessToken:this.signInUserSession.getAccessToken().getJwtToken()},function(o){return o?s(o,null):s(null,"SUCCESS")});},e.disableMFA=function(n){if(this.signInUserSession==null||!this.signInUserSession.isValid())return n(new Error("User is not authenticated"),null);var i=[];this.client.request("SetUserSettings",{MFAOptions:i,AccessToken:this.signInUserSession.getAccessToken().getJwtToken()},function(s){return s?n(s,null):n(null,"SUCCESS")});},e.deleteUser=function(n,i){var s=this;if(this.signInUserSession==null||!this.signInUserSession.isValid())return n(new Error("User is not authenticated"),null);this.client.request("DeleteUser",{AccessToken:this.signInUserSession.getAccessToken().getJwtToken(),ClientMetadata:i},function(o){return o?n(o,null):(s.clearCachedUser(),n(null,"SUCCESS"))});},e.updateAttributes=function(n,i,s){var o=this;if(this.signInUserSession==null||!this.signInUserSession.isValid())return i(new Error("User is not authenticated"),null);this.client.request("UpdateUserAttributes",{AccessToken:this.signInUserSession.getAccessToken().getJwtToken(),UserAttributes:n,ClientMetadata:s},function(a,u){return a?i(a,null):o.getUserData(function(){return i(null,"SUCCESS",u)},{bypassCache:true})});},e.getUserAttributes=function(n){if(!(this.signInUserSession!=null&&this.signInUserSession.isValid()))return n(new Error("User is not authenticated"),null);this.client.request("GetUser",{AccessToken:this.signInUserSession.getAccessToken().getJwtToken()},function(i,s){if(i)return n(i,null);for(var o=[],a=0;a<s.UserAttributes.length;a++){var u={Name:s.UserAttributes[a].Name,Value:s.UserAttributes[a].Value},c=new de(u);o.push(c);}return n(null,o)});},e.getMFAOptions=function(n){if(!(this.signInUserSession!=null&&this.signInUserSession.isValid()))return n(new Error("User is not authenticated"),null);this.client.request("GetUser",{AccessToken:this.signInUserSession.getAccessToken().getJwtToken()},function(i,s){return i?n(i,null):n(null,s.MFAOptions)});},e.createGetUserRequest=function(){return this.client.promisifyRequest("GetUser",{AccessToken:this.signInUserSession.getAccessToken().getJwtToken()})},e.refreshSessionIfPossible=function(n){var i=this;return n===void 0&&(n={}),new Promise(function(s){var o=i.signInUserSession.getRefreshToken();o&&o.getToken()?i.refreshSession(o,s,n.clientMetadata):s();})},e.getUserData=function(n,i){var s=this;if(!(this.signInUserSession!=null&&this.signInUserSession.isValid()))return this.clearCachedUserData(),n(new Error("User is not authenticated"),null);var o=this.getUserDataFromCache();if(!o){this.fetchUserData().then(function(a){n(null,a);}).catch(n);return}if(this.isFetchUserDataAndTokenRequired(i)){this.fetchUserData().then(function(a){return s.refreshSessionIfPossible(i).then(function(){return a})}).then(function(a){return n(null,a)}).catch(n);return}try{n(null,JSON.parse(o));return}catch(a){this.clearCachedUserData(),n(a,null);return}},e.getUserDataFromCache=function(){var n=this.storage.getItem(this.userDataKey);return n},e.isFetchUserDataAndTokenRequired=function(n){var i=n||{},s=i.bypassCache,o=s===void 0?false:s;return o},e.fetchUserData=function(){var n=this;return this.createGetUserRequest().then(function(i){return n.cacheUserData(i),i})},e.deleteAttributes=function(n,i){var s=this;if(!(this.signInUserSession!=null&&this.signInUserSession.isValid()))return i(new Error("User is not authenticated"),null);this.client.request("DeleteUserAttributes",{UserAttributeNames:n,AccessToken:this.signInUserSession.getAccessToken().getJwtToken()},function(o){return o?i(o,null):s.getUserData(function(){return i(null,"SUCCESS")},{bypassCache:true})});},e.resendConfirmationCode=function(n,i){var s={ClientId:this.pool.getClientId(),Username:this.username,ClientMetadata:i};this.client.request("ResendConfirmationCode",s,function(o,a){return o?n(o,null):n(null,a)});},e.getSession=function(n,i){if(i===void 0&&(i={}),this.username==null)return n(new Error("Username is null. Cannot retrieve a new session"),null);if(this.signInUserSession!=null&&this.signInUserSession.isValid())return n(null,this.signInUserSession);var s="CognitoIdentityServiceProvider."+this.pool.getClientId()+"."+this.username,o=s+".idToken",a=s+".accessToken",u=s+".refreshToken",c=s+".clockDrift";if(this.storage.getItem(o)){var l=new je({IdToken:this.storage.getItem(o)}),d=new $e({AccessToken:this.storage.getItem(a)}),h=new Ke({RefreshToken:this.storage.getItem(u)}),p=parseInt(this.storage.getItem(c),0)||0,g={IdToken:l,AccessToken:d,RefreshToken:h,ClockDrift:p},_=new He(g);if(_.isValid())return this.signInUserSession=_,n(null,this.signInUserSession);if(!h.getToken())return n(new Error("Cannot retrieve a new session. Please authenticate."),null);this.refreshSession(h,n,i.clientMetadata);}else n(new Error("Local storage is missing an ID Token, Please authenticate"),null);},e.refreshSession=function(n,i,s){var o=this,a=this.pool.wrapRefreshSessionCallback?this.pool.wrapRefreshSessionCallback(i):i,u={};u.REFRESH_TOKEN=n.getToken();var c="CognitoIdentityServiceProvider."+this.pool.getClientId(),l=c+".LastAuthUser";if(this.storage.getItem(l)){this.username=this.storage.getItem(l);var d=c+"."+this.username+".deviceKey";this.deviceKey=this.storage.getItem(d),u.DEVICE_KEY=this.deviceKey;}var h={ClientId:this.pool.getClientId(),AuthFlow:"REFRESH_TOKEN_AUTH",AuthParameters:u,ClientMetadata:s};this.getUserContextData()&&(h.UserContextData=this.getUserContextData()),this.client.requestWithRetry("InitiateAuth",h,function(p,g){if(p)return p.code==="NotAuthorizedException"&&o.clearCachedUser(),a(p,null);if(g){var _=g.AuthenticationResult;return Object.prototype.hasOwnProperty.call(_,"RefreshToken")||(_.RefreshToken=n.getToken()),o.signInUserSession=o.getCognitoUserSession(_),o.cacheTokens(),a(null,o.signInUserSession)}});},e.cacheTokens=function(){var n="CognitoIdentityServiceProvider."+this.pool.getClientId(),i=n+"."+this.username+".idToken",s=n+"."+this.username+".accessToken",o=n+"."+this.username+".refreshToken",a=n+"."+this.username+".clockDrift",u=n+".LastAuthUser";this.storage.setItem(i,this.signInUserSession.getIdToken().getJwtToken()),this.storage.setItem(s,this.signInUserSession.getAccessToken().getJwtToken()),this.storage.setItem(o,this.signInUserSession.getRefreshToken().getToken()),this.storage.setItem(a,""+this.signInUserSession.getClockDrift()),this.storage.setItem(u,this.username);},e.cacheUserData=function(n){this.storage.setItem(this.userDataKey,JSON.stringify(n));},e.clearCachedUserData=function(){this.storage.removeItem(this.userDataKey);},e.clearCachedUser=function(){this.clearCachedTokens(),this.clearCachedUserData();},e.cacheDeviceKeyAndPassword=function(){var n="CognitoIdentityServiceProvider."+this.pool.getClientId()+"."+this.username,i=n+".deviceKey",s=n+".randomPasswordKey",o=n+".deviceGroupKey";this.storage.setItem(i,this.deviceKey),this.storage.setItem(s,this.randomPassword),this.storage.setItem(o,this.deviceGroupKey);},e.getCachedDeviceKeyAndPassword=function(){var n="CognitoIdentityServiceProvider."+this.pool.getClientId()+"."+this.username,i=n+".deviceKey",s=n+".randomPasswordKey",o=n+".deviceGroupKey";this.storage.getItem(i)&&(this.deviceKey=this.storage.getItem(i),this.randomPassword=this.storage.getItem(s),this.deviceGroupKey=this.storage.getItem(o));},e.clearCachedDeviceKeyAndPassword=function(){var n="CognitoIdentityServiceProvider."+this.pool.getClientId()+"."+this.username,i=n+".deviceKey",s=n+".randomPasswordKey",o=n+".deviceGroupKey";this.storage.removeItem(i),this.storage.removeItem(s),this.storage.removeItem(o);},e.clearCachedTokens=function(){var n="CognitoIdentityServiceProvider."+this.pool.getClientId(),i=n+"."+this.username+".idToken",s=n+"."+this.username+".accessToken",o=n+"."+this.username+".refreshToken",a=n+".LastAuthUser",u=n+"."+this.username+".clockDrift";this.storage.removeItem(i),this.storage.removeItem(s),this.storage.removeItem(o),this.storage.removeItem(a),this.storage.removeItem(u);},e.getCognitoUserSession=function(n){var i=new je(n),s=new $e(n),o=new Ke(n),a={IdToken:i,AccessToken:s,RefreshToken:o};return new He(a)},e.forgotPassword=function(n,i){var s={ClientId:this.pool.getClientId(),Username:this.username,ClientMetadata:i};this.getUserContextData()&&(s.UserContextData=this.getUserContextData()),this.client.request("ForgotPassword",s,function(o,a){return o?n.onFailure(o):typeof n.inputVerificationCode=="function"?n.inputVerificationCode(a):n.onSuccess(a)});},e.confirmPassword=function(n,i,s,o){var a={ClientId:this.pool.getClientId(),Username:this.username,ConfirmationCode:n,Password:i,ClientMetadata:o};this.getUserContextData()&&(a.UserContextData=this.getUserContextData()),this.client.request("ConfirmForgotPassword",a,function(u){return u?s.onFailure(u):s.onSuccess("SUCCESS")});},e.getAttributeVerificationCode=function(n,i,s){if(this.signInUserSession==null||!this.signInUserSession.isValid())return i.onFailure(new Error("User is not authenticated"));this.client.request("GetUserAttributeVerificationCode",{AttributeName:n,AccessToken:this.signInUserSession.getAccessToken().getJwtToken(),ClientMetadata:s},function(o,a){return o?i.onFailure(o):typeof i.inputVerificationCode=="function"?i.inputVerificationCode(a):i.onSuccess("SUCCESS")});},e.verifyAttribute=function(n,i,s){if(this.signInUserSession==null||!this.signInUserSession.isValid())return s.onFailure(new Error("User is not authenticated"));this.client.request("VerifyUserAttribute",{AttributeName:n,Code:i,AccessToken:this.signInUserSession.getAccessToken().getJwtToken()},function(o){return o?s.onFailure(o):s.onSuccess("SUCCESS")});},e.getDevice=function(n){if(this.signInUserSession==null||!this.signInUserSession.isValid())return n.onFailure(new Error("User is not authenticated"));this.client.request("GetDevice",{AccessToken:this.signInUserSession.getAccessToken().getJwtToken(),DeviceKey:this.deviceKey},function(i,s){return i?n.onFailure(i):n.onSuccess(s)});},e.forgetSpecificDevice=function(n,i){if(this.signInUserSession==null||!this.signInUserSession.isValid())return i.onFailure(new Error("User is not authenticated"));this.client.request("ForgetDevice",{AccessToken:this.signInUserSession.getAccessToken().getJwtToken(),DeviceKey:n},function(s){return s?i.onFailure(s):i.onSuccess("SUCCESS")});},e.forgetDevice=function(n){var i=this;this.forgetSpecificDevice(this.deviceKey,{onFailure:n.onFailure,onSuccess:function(o){return i.deviceKey=null,i.deviceGroupKey=null,i.randomPassword=null,i.clearCachedDeviceKeyAndPassword(),n.onSuccess(o)}});},e.setDeviceStatusRemembered=function(n){if(this.signInUserSession==null||!this.signInUserSession.isValid())return n.onFailure(new Error("User is not authenticated"));this.client.request("UpdateDeviceStatus",{AccessToken:this.signInUserSession.getAccessToken().getJwtToken(),DeviceKey:this.deviceKey,DeviceRememberedStatus:"remembered"},function(i){return i?n.onFailure(i):n.onSuccess("SUCCESS")});},e.setDeviceStatusNotRemembered=function(n){if(this.signInUserSession==null||!this.signInUserSession.isValid())return n.onFailure(new Error("User is not authenticated"));this.client.request("UpdateDeviceStatus",{AccessToken:this.signInUserSession.getAccessToken().getJwtToken(),DeviceKey:this.deviceKey,DeviceRememberedStatus:"not_remembered"},function(i){return i?n.onFailure(i):n.onSuccess("SUCCESS")});},e.listDevices=function(n,i,s){if(this.signInUserSession==null||!this.signInUserSession.isValid())return s.onFailure(new Error("User is not authenticated"));var o={AccessToken:this.signInUserSession.getAccessToken().getJwtToken(),Limit:n};i&&(o.PaginationToken=i),this.client.request("ListDevices",o,function(a,u){return a?s.onFailure(a):s.onSuccess(u)});},e.globalSignOut=function(n){var i=this;if(this.signInUserSession==null||!this.signInUserSession.isValid())return n.onFailure(new Error("User is not authenticated"));this.client.request("GlobalSignOut",{AccessToken:this.signInUserSession.getAccessToken().getJwtToken()},function(s){return s?n.onFailure(s):(i.clearCachedUser(),n.onSuccess("SUCCESS"))});},e.signOut=function(n){var i=this;if(!n||typeof n!="function"){this.cleanClientData();return}this.getSession(function(s,o){if(s)return n(s);i.revokeTokens(function(a){i.cleanClientData(),n(a);});});},e.revokeTokens=function(n){if(n===void 0&&(n=function(){}),typeof n!="function")throw new Error("Invalid revokeTokenCallback. It should be a function.");if(!this.signInUserSession){var s=new Error("User is not authenticated");return n(s)}if(!this.signInUserSession.getAccessToken()){var o=new Error("No Access token available");return n(o)}var a=this.signInUserSession.getRefreshToken().getToken(),u=this.signInUserSession.getAccessToken();if(this.isSessionRevocable(u)&&a)return this.revokeToken({token:a,callback:n});n();},e.isSessionRevocable=function(n){if(n&&typeof n.decodePayload=="function")try{var i=n.decodePayload(),s=i.origin_jti;return !!s}catch{}return false},e.cleanClientData=function(){this.signInUserSession=null,this.clearCachedUser();},e.revokeToken=function(n){var i=n.token,s=n.callback;this.client.requestWithRetry("RevokeToken",{Token:i,ClientId:this.pool.getClientId()},function(o){if(o)return s(o);s();});},e.sendMFASelectionAnswer=function(n,i){var s=this,o={};o.USERNAME=this.username,o.ANSWER=n;var a={ChallengeName:"SELECT_MFA_TYPE",ChallengeResponses:o,ClientId:this.pool.getClientId(),Session:this.Session};this.getUserContextData()&&(a.UserContextData=this.getUserContextData()),this.client.request("RespondToAuthChallenge",a,function(u,c){if(u)return i.onFailure(u);if(s.Session=c.Session,n==="SMS_MFA")return i.mfaRequired(c.ChallengeName,c.ChallengeParameters);if(n==="SOFTWARE_TOKEN_MFA")return i.totpRequired(c.ChallengeName,c.ChallengeParameters)});},e.getUserContextData=function(){var n=this.pool;return n.getUserContextData(this.username)},e.associateSoftwareToken=function(n){var i=this;this.signInUserSession!=null&&this.signInUserSession.isValid()?this.client.request("AssociateSoftwareToken",{AccessToken:this.signInUserSession.getAccessToken().getJwtToken()},function(s,o){return s?n.onFailure(s):n.associateSecretCode(o.SecretCode)}):this.client.request("AssociateSoftwareToken",{Session:this.Session},function(s,o){return s?n.onFailure(s):(i.Session=o.Session,n.associateSecretCode(o.SecretCode))});},e.verifySoftwareToken=function(n,i,s){var o=this;this.signInUserSession!=null&&this.signInUserSession.isValid()?this.client.request("VerifySoftwareToken",{AccessToken:this.signInUserSession.getAccessToken().getJwtToken(),UserCode:n,FriendlyDeviceName:i},function(a,u){return a?s.onFailure(a):s.onSuccess(u)}):this.client.request("VerifySoftwareToken",{Session:this.Session,UserCode:n,FriendlyDeviceName:i},function(a,u){if(a)return s.onFailure(a);o.Session=u.Session;var c={};c.USERNAME=o.username;var l={ChallengeName:"MFA_SETUP",ClientId:o.pool.getClientId(),ChallengeResponses:c,Session:o.Session};o.getUserContextData()&&(l.UserContextData=o.getUserContextData()),o.client.request("RespondToAuthChallenge",l,function(d,h){return d?s.onFailure(d):(o.signInUserSession=o.getCognitoUserSession(h.AuthenticationResult),o.cacheTokens(),s.onSuccess(o.signInUserSession))});});},r})();Le(jn());function We(){}We.prototype.userAgent=Vn();var Kn=function(e){var t=We.category?" "+We.category:"",n=We.framework?" framework/"+We.framework:"",i=""+We.prototype.userAgent+t+n;return i};function gu(r,e){r.prototype=Object.create(e.prototype),r.prototype.constructor=r,Ze(r,e);}function vr(r){var e=typeof Map=="function"?new Map:void 0;return vr=function(n){if(n===null||!mu(n))return n;if(typeof n!="function")throw new TypeError("Super expression must either be null or a function");if(e!==void 0){if(e.has(n))return e.get(n);e.set(n,i);}function i(){return pu(n,arguments,Tr(this).constructor)}return i.prototype=Object.create(n.prototype,{constructor:{value:i,enumerable:false,writable:true,configurable:true}}),Ze(i,n)},vr(r)}function pu(r,e,t){if(Hn())return Reflect.construct.apply(null,arguments);var n=[null];n.push.apply(n,e);var i=new(r.bind.apply(r,n));return t&&Ze(i,t.prototype),i}function Hn(){try{var r=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}));}catch{}return (Hn=function(){return !!r})()}function mu(r){try{return Function.toString.call(r).indexOf("[native code]")!==-1}catch{return typeof r=="function"}}function Ze(r,e){return Ze=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(t,n){return t.__proto__=n,t},Ze(r,e)}function Tr(r){return Tr=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(e){return e.__proto__||Object.getPrototypeOf(e)},Tr(r)}var _u=(function(r){function e(t,n,i,s){var o;return o=r.call(this,t)||this,o.code=n,o.name=i,o.statusCode=s,o}return gu(e,r),e})(vr(Error)),Wn=(function(){function r(t,n,i){this.endpoint=n||"https://cognito-idp."+t+".amazonaws.com/";var s=i||{},o=s.credentials;this.fetchOptions=o?{credentials:o}:{};}var e=r.prototype;return e.promisifyRequest=function(n,i){var s=this;return new Promise(function(o,a){s.request(n,i,function(u,c){u?a(new _u(u.message,u.code,u.name,u.statusCode)):o(c);});})},e.requestWithRetry=function(n,i,s){var o=this,a=5*1e3;Eu(function(u){return new Promise(function(c,l){o.request(n,u,function(d,h){d?l(d):c(h);});})},[i],a).then(function(u){return s(null,u)}).catch(function(u){return s(u)});},e.request=function(n,i,s){var o={"Content-Type":"application/x-amz-json-1.1","X-Amz-Target":"AWSCognitoIdentityProviderService."+n,"X-Amz-User-Agent":Kn(),"Cache-Control":"no-store"},a=Object.assign({},this.fetchOptions,{headers:o,method:"POST",mode:"cors",body:JSON.stringify(i)}),u;fetch(this.endpoint,a).then(function(l){return u=l,l},function(l){throw l instanceof TypeError?new Error("Network error"):l}).then(function(l){return l.json().catch(function(){return {}})}).then(function(l){if(u.ok)return s(null,l);var d=(l.__type||l.code).split("#").pop(),h=new Error(l.message||l.Message||null);return h.name=d,h.code=d,s(h)}).catch(function(l){if(u&&u.headers&&u.headers.get("x-amzn-errortype"))try{var d=u.headers.get("x-amzn-errortype").split(":")[0],h=new Error(u.status?u.status.toString():null);return h.code=d,h.name=d,h.statusCode=u.status,s(h)}catch{return s(l)}else l instanceof Error&&l.message==="Network error"&&(l.code="NetworkError");return s(l)});},r})();var Dt={debug:function(){}};var bu=function(e){var t="nonRetryable";return e&&e[t]};function Jn(r,e,t,n){if(n===void 0&&(n=1),typeof r!="function")throw Error("functionToRetry must be a function");return Dt.debug(r.name+" attempt #"+n+" with args: "+JSON.stringify(e)),r.apply(void 0,e).catch(function(i){if(Dt.debug("error on "+r.name,i),bu(i))throw Dt.debug(r.name+" non retryable error",i),i;var s=t(n,e,i);if(Dt.debug(r.name+" retrying in "+s+" ms"),s!==false)return new Promise(function(o){return setTimeout(o,s)}).then(function(){return Jn(r,e,t,n+1)});throw i})}function yu(r){var e=100,t=100;return function(n){var i=Math.pow(2,n)*e+t*Math.random();return i>r?false:i}}function Eu(r,e,t){return Jn(r,e,yu(t))}var Au=55,Rr=(function(){function r(t,n){var i=t||{},s=i.UserPoolId,o=i.ClientId,a=i.endpoint,u=i.fetchOptions,c=i.AdvancedSecurityDataCollectionFlag;if(!s||!o)throw new Error("Both UserPoolId and ClientId are required.");if(s.length>Au||!/^[\w-]+_[0-9a-zA-Z]+$/.test(s))throw new Error("Invalid UserPoolId format.");var l=s.split("_")[0];this.userPoolId=s,this.clientId=o,this.client=new Wn(l,a,u),this.advancedSecurityDataCollectionFlag=c!==false,this.storage=t.Storage||new Ct().getStorage(),n&&(this.wrapRefreshSessionCallback=n);}var e=r.prototype;return e.getUserPoolId=function(){return this.userPoolId},e.getUserPoolName=function(){return this.getUserPoolId().split("_")[1]},e.getClientId=function(){return this.clientId},e.signUp=function(n,i,s,o,a,u){var c=this,l={ClientId:this.clientId,Username:n,Password:i,UserAttributes:s,ValidationData:o,ClientMetadata:u};this.getUserContextData(n)&&(l.UserContextData=this.getUserContextData(n)),this.client.request("SignUp",l,function(d,h){if(d)return a(d,null);var p={Username:n,Pool:c,Storage:c.storage},g={user:new we(p),userConfirmed:h.UserConfirmed,userSub:h.UserSub,codeDeliveryDetails:h.CodeDeliveryDetails};return a(null,g)});},e.getCurrentUser=function(){var n="CognitoIdentityServiceProvider."+this.clientId+".LastAuthUser",i=this.storage.getItem(n);if(i){var s={Username:i,Pool:this,Storage:this.storage};return new we(s)}return null},e.getUserContextData=function(n){if(!(typeof AmazonCognitoAdvancedSecurityData>"u")){var i=AmazonCognitoAdvancedSecurityData;if(this.advancedSecurityDataCollectionFlag){var s=i.getData(n,this.userPoolId,this.clientId);if(s){var o={EncodedData:s};return o}}return {}}},r})();function kt(r){for(var e=1;e<arguments.length;e++){var t=arguments[e];for(var n in t)n!=="__proto__"&&(r[n]=t[n]);}return r}var Su={read:function(r){return r[0]==='"'&&(r=r.slice(1,-1)),r.replace(/(%[\dA-F]{2})+/gi,decodeURIComponent)},write:function(r){return encodeURIComponent(r).replace(/%(2[346BF]|3[AC-F]|40|5[BDE]|60|7[BCD])/g,decodeURIComponent)}};function Ir(r,e){function t(i,s,o){if(!(typeof document>"u")){o=kt({},e,o),typeof o.expires=="number"&&(o.expires=new Date(Date.now()+o.expires*864e5)),o.expires&&(o.expires=o.expires.toUTCString()),i=encodeURIComponent(i).replace(/%(2[346B]|5E|60|7C)/g,decodeURIComponent).replace(/[()]/g,escape);var a="";for(var u in o)o[u]&&(a+="; "+u,o[u]!==true&&(a+="="+o[u].split(";")[0]));return document.cookie=i+"="+r.write(s,i)+a}}function n(i){if(!(typeof document>"u"||arguments.length&&!i)){for(var s=document.cookie?document.cookie.split("; "):[],o={},a=0;a<s.length;a++){var u=s[a].split("="),c=u.slice(1).join("=");try{var l=decodeURIComponent(u[0]);if(l in o||(o[l]=r.read(c,l)),i===l)break}catch{}}return i?o[i]:o}}return Object.create({set:t,get:n,remove:function(i,s){t(i,"",kt({},s,{expires:-1}));},withAttributes:function(i){return Ir(this.converter,kt({},this.attributes,i))},withConverter:function(i){return Ir(kt({},this.converter,i),this.attributes)}},{attributes:{value:Object.freeze(e)},converter:{value:Object.freeze(r)}})}Ir(Su,{path:"/"});var f=class extends Error{constructor(e,t){if(Array.isArray(e)&&e.length<=2){let n=e[1];if(e.length>2)for(let i=2;i<e.length&&typeof e[i]=="string";i++)n+=e[i];super((n||"Something went wrong.").trim()),this.name=t?.name||"SKAPI",this.code=t?.code||e[0]||"ERROR",t?.cause&&(this.cause=t.cause);}else super((e?.message||(typeof e=="string"?e:"Something went wrong.")).trim()),typeof e=="string"?(this.name=t?.name||"SKAPI",this.code=t?.code||"ERROR",t?.cause&&(this.cause=t.cause)):e instanceof Error?(this.cause=e,this.name=e.name,e.hasOwnProperty("code")&&(this.code=e.code)):typeof e=="object"&&e?.code&&e?.message&&(this.name=t?.name||"SKAPI",this.code=t?.code||"ERROR",this.cause=e?.cause);}};var Ee="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",Pr=BigInt(Ee.length),Tu=2*1024*1024,Ru=["aud","cognito:username","event_id","exp","iat","iss","jti","origin_jti","secret_key","token_use"],Gn={auth_time:"log",sub:"user_id"},Iu=["0","1","2","3","4","5","6","7","8","9","a","b","c","d","e","f","g","h","i","j","k","l"],Zn=["us31","us72","ap51","ap22","ap41","eu71","ap21","us32","us71","af51","ap31","ap43","ap23","ap42","ca01","eu01","eu72","eu51","eu73","eu11","me51","sa31"],Qn=typeof TextEncoder<"u"?new TextEncoder:null;function Pu(){if(typeof globalThis<"u")return globalThis.Buffer}function xu(r){if(Qn)return Qn.encode(r);let e=unescape(encodeURIComponent(r)),t=new Uint8Array(e.length);for(let n=0;n<e.length;n++)t[n]=e.charCodeAt(n);return t}function Uu(r){if(r instanceof Uint8Array)return r;if(typeof r=="string")return xu(r);if(typeof ArrayBuffer<"u"&&r instanceof ArrayBuffer)return new Uint8Array(r);if(typeof ArrayBuffer<"u"&&ArrayBuffer.isView(r))return new Uint8Array(r.buffer,r.byteOffset,r.byteLength);if(Array.isArray(r))return Uint8Array.from(r);let e=Pu();if(e)return new Uint8Array(e.from(r));throw new Error("No byte conversion available in this environment.")}var E=class E{static hash(e){typeof e!="string"&&(console.warn("coercing non-string value to empty string"),e="");let t=E.sb(e),n=1732584193,i=-271733879,s=-1732584194,o=271733878,a,u,c,l;for(let d=0;d<t.length;d+=16)a=n,u=i,c=s,l=o,n=E.ff(n,i,s,o,t[d],7,-680876936),o=E.ff(o,n,i,s,t[d+1],12,-389564586),s=E.ff(s,o,n,i,t[d+2],17,606105819),i=E.ff(i,s,o,n,t[d+3],22,-1044525330),n=E.ff(n,i,s,o,t[d+4],7,-176418897),o=E.ff(o,n,i,s,t[d+5],12,1200080426),s=E.ff(s,o,n,i,t[d+6],17,-1473231341),i=E.ff(i,s,o,n,t[d+7],22,-45705983),n=E.ff(n,i,s,o,t[d+8],7,1770035416),o=E.ff(o,n,i,s,t[d+9],12,-1958414417),s=E.ff(s,o,n,i,t[d+10],17,-42063),i=E.ff(i,s,o,n,t[d+11],22,-1990404162),n=E.ff(n,i,s,o,t[d+12],7,1804603682),o=E.ff(o,n,i,s,t[d+13],12,-40341101),s=E.ff(s,o,n,i,t[d+14],17,-1502002290),i=E.ff(i,s,o,n,t[d+15],22,1236535329),n=E.gg(n,i,s,o,t[d+1],5,-165796510),o=E.gg(o,n,i,s,t[d+6],9,-1069501632),s=E.gg(s,o,n,i,t[d+11],14,643717713),i=E.gg(i,s,o,n,t[d],20,-373897302),n=E.gg(n,i,s,o,t[d+5],5,-701558691),o=E.gg(o,n,i,s,t[d+10],9,38016083),s=E.gg(s,o,n,i,t[d+15],14,-660478335),i=E.gg(i,s,o,n,t[d+4],20,-405537848),n=E.gg(n,i,s,o,t[d+9],5,568446438),o=E.gg(o,n,i,s,t[d+14],9,-1019803690),s=E.gg(s,o,n,i,t[d+3],14,-187363961),i=E.gg(i,s,o,n,t[d+8],20,1163531501),n=E.gg(n,i,s,o,t[d+13],5,-1444681467),o=E.gg(o,n,i,s,t[d+2],9,-51403784),s=E.gg(s,o,n,i,t[d+7],14,1735328473),i=E.gg(i,s,o,n,t[d+12],20,-1926607734),n=E.hh(n,i,s,o,t[d+5],4,-378558),o=E.hh(o,n,i,s,t[d+8],11,-2022574463),s=E.hh(s,o,n,i,t[d+11],16,1839030562),i=E.hh(i,s,o,n,t[d+14],23,-35309556),n=E.hh(n,i,s,o,t[d+1],4,-1530992060),o=E.hh(o,n,i,s,t[d+4],11,1272893353),s=E.hh(s,o,n,i,t[d+7],16,-155497632),i=E.hh(i,s,o,n,t[d+10],23,-1094730640),n=E.hh(n,i,s,o,t[d+13],4,681279174),o=E.hh(o,n,i,s,t[d],11,-358537222),s=E.hh(s,o,n,i,t[d+3],16,-722521979),i=E.hh(i,s,o,n,t[d+6],23,76029189),n=E.hh(n,i,s,o,t[d+9],4,-640364487),o=E.hh(o,n,i,s,t[d+12],11,-421815835),s=E.hh(s,o,n,i,t[d+15],16,530742520),i=E.hh(i,s,o,n,t[d+2],23,-995338651),n=E.ii(n,i,s,o,t[d],6,-198630844),o=E.ii(o,n,i,s,t[d+7],10,1126891415),s=E.ii(s,o,n,i,t[d+14],15,-1416354905),i=E.ii(i,s,o,n,t[d+5],21,-57434055),n=E.ii(n,i,s,o,t[d+12],6,1700485571),o=E.ii(o,n,i,s,t[d+3],10,-1894986606),s=E.ii(s,o,n,i,t[d+10],15,-1051523),i=E.ii(i,s,o,n,t[d+1],21,-2054922799),n=E.ii(n,i,s,o,t[d+8],6,1873313359),o=E.ii(o,n,i,s,t[d+15],10,-30611744),s=E.ii(s,o,n,i,t[d+6],15,-1560198380),i=E.ii(i,s,o,n,t[d+13],21,1309151649),n=E.ii(n,i,s,o,t[d+4],6,-145523070),o=E.ii(o,n,i,s,t[d+11],10,-1120210379),s=E.ii(s,o,n,i,t[d+2],15,718787259),i=E.ii(i,s,o,n,t[d+9],21,-343485551),n=E.ad(n,a),i=E.ad(i,u),s=E.ad(s,c),o=E.ad(o,l);return E.rh(n)+E.rh(i)+E.rh(s)+E.rh(o)}static rh(e){let t="";for(let n=0;n<=3;n++)t+=E.alphabet.charAt(e>>n*8+4&15)+E.alphabet.charAt(e>>n*8&15);return t}static ad(e,t){let n=(e&65535)+(t&65535);return (e>>16)+(t>>16)+(n>>16)<<16|n&65535}static rl(e,t){return e<<t|e>>>32-t}static cm(e,t,n,i,s,o){return E.ad(E.rl(E.ad(E.ad(t,e),E.ad(i,o)),s),n)}static ff(e,t,n,i,s,o,a){return E.cm(t&n|~t&i,e,t,s,o,a)}static gg(e,t,n,i,s,o,a){return E.cm(t&i|n&~i,e,t,s,o,a)}static hh(e,t,n,i,s,o,a){return E.cm(t^n^i,e,t,s,o,a)}static ii(e,t,n,i,s,o,a){return E.cm(n^(t|~i),e,t,s,o,a)}static sb(e){let t,n=(e.length+8>>6)+1,i=new Array(n*16);for(t=0;t<n*16;t++)i[t]=0;for(t=0;t<e.length;t++)i[t>>2]|=e.charCodeAt(t)<<t%4*8;return i[t>>2]|=128<<t%4*8,i[n*16-2]=e.length*8,i}};E.alphabet="0123456789abcdef";var K=E;function ei(r){if(r===0)return Ee[0];let e="";for(;r>0;)e=Ee[r%62]+e,r=Math.floor(r/62);return e}function ie(r){return r.split("").reverse().reduce((e,t,n)=>e+Ee.indexOf(t)*62**n,0)}function De(r=6){let e="",t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",n=t.length,i=0;for(;i<r;)e+=t.charAt(Math.floor(Math.random()*n)),i+=1;return e}function xr(){return typeof window>"u"||!!window?._runningInNodeJS}function Y(){return !xr()&&typeof document<"u"&&typeof document.createElement=="function"}function Nt(r){let e;try{e=JSON.stringify(r);}catch{throw new f("Invalid data type.",{code:"INVALID_REQUEST"})}if(new Blob([e]).size>Tu)throw new f("Data should not exceed 2MB",{code:"INVALID_REQUEST"})}function zn(r){return r===""||r==="on"||r==="true"}function Yn(r){return r==="false"}function Xn(r,e,t){e.name&&t(r,e.name,e.value);}var Ft=Y(),Cu=typeof SubmitEvent<"u",Du=typeof HTMLFormElement<"u";function M(r,e,t){let n={},i=[];function s(u,c,l){if(e?.ignoreEmpty&&l==="")return;if(e?.nullIfEmpty&&l===""&&(l=null),typeof t=="function"){let p=t(c,l);p!==void 0&&(l=p);}let d=c.split("[").map(p=>{let g=p.replace("]",""),_=Number(g);return !isNaN(_)&&!g.includes(".")?g=_:(g[0]==='"'&&g[g.length-1]==='"'||g[0]==="'"&&g[g.length-1]==="'")&&(g=g.replace(/"/g,"").replace(/'/g,"")),g}),h=u;if(typeof d[0]=="number")throw new f("Form key cannot start with an array index.",{code:"INVALID_REQUEST"});for(let p=0;p<d.length;p++){let g=d[p];p<d.length-1?(h[g]===void 0&&(typeof d[p+1]=="number"?h[g]=[]:h[g]={}),h=h[g]):h[g]===void 0?h[g]=l:Array.isArray(h[g])?h[g].push(l):h[g]=[h[g],l];}}function o(u,c,l){if(l instanceof File)u.push({name:c,file:l});else if(l instanceof FileList&&l&&l.length>0)for(let d=0;d<=l.length-1;d++){let h=l.item(d);h&&u.push({name:c,file:h});}}let a=u=>{u.name&&(u.type==="number"?u.value&&s(n,u.name,Number(u.value)):u.type==="checkbox"||u.type==="radio"?u.checked?u.type==="checkbox"&&u.value===""||zn(u.value)?s(n,u.name,true):Yn(u.value)?s(n,u.name,false):u.value&&s(n,u.name,u.value):u.type==="checkbox"&&(zn(u.value)?s(n,u.name,false):Yn(u.value)&&s(n,u.name,true)):u.type==="file"?u.files&&u.files.length>0&&o(i,u.name,u.files):s(n,u.name,u.value));};if(Ft&&(r instanceof HTMLInputElement||r instanceof HTMLSelectElement||r instanceof HTMLTextAreaElement))return a(r),Nt(n),{data:n,files:i};if(Ft&&r instanceof FormData){for(let u of r.entries()){let c=u[0],l=u[1];if(l instanceof File||l instanceof FileList)o(i,c,l);else if(l instanceof Blob){let d=l;if(d.type==="application/json")try{let h=JSON.parse(d.text());s(n,c,h);}catch{s(n,c,d);}}else s(n,c,l);}return Nt(n),{data:n,files:i}}if(Ft&&Cu&&r instanceof SubmitEvent&&(r=r.target),Ft&&Du&&r instanceof HTMLFormElement){let u=r.querySelectorAll("input"),c=r.querySelectorAll("select"),l=r.querySelectorAll("textarea");for(let d=0;d<c.length;d++)Xn(n,c[d],s);for(let d=0;d<l.length;d++)Xn(n,l[d],s);for(let d=0;d<u.length;d++)a(u[d]);return Nt(n),{data:n,files:i}}return Nt(r),{data:r,files:i}}function et(r){let e={};for(let t in r){let n=r[t];if(!Ru.includes(t))if(Gn[t])e[Gn[t]]=n;else if(t.includes("custom:"))e[t.replace("custom:","")]=n;else if(t==="address"){let i=n;if(i&&typeof i=="object"&&Object.keys(i).length){if(i?.formatted)try{e[t]=JSON.parse(i.formatted);}catch{e[t]=i.formatted;}}else e[t]=i;}else e[t]=n;}for(let t of ["address_public","birthdate_public","email_public","gender_public","phone_number_public","access_group"])t.includes("_public")?e.hasOwnProperty(t.split("_")[0])?e[t]=e.hasOwnProperty(t)?!!Number(e[t]):false:delete e[t]:e[t]=e.hasOwnProperty(t)?Number(e[t]):0;for(let t of ["email","phone_number"])e.hasOwnProperty(t)?e[t+"_verified"]=e[t+"_verified"]===true:delete e[t+"_verified"];return e}function Ur(r){if(r=Vu(r),r.split("-").length===7){let e=r.split("-"),t,n;try{t=Zn[ie(e[1][0])],n=e.slice(2).join("-");}catch{throw new Error("INVALID_PARAMETER: Service ID is invalid: "+r)}if(!t)throw new Error("INVALID_PARAMETER: Service ID is invalid: "+r);return {service:t+e[0]+e[1].slice(1),owner:n}}return {service:r,owner:""}}function Cr(r,e){let t=Zn.indexOf(r.slice(0,4)),n=Iu[t],s=`${r.slice(4,-4)}-${n}${r.slice(-4)}-${e}`;return qu(s)}function ku(r){let e=0n;for(let t of r){let n=Ee.indexOf(t);if(n<0)throw new Error(`INVALID_PARAMETER: Invalid base62 character: ${t}`);e=e*Pr+BigInt(n);}return e}function Nu(r,e=1){if(r<0n)throw new Error("INVALID_PARAMETER: Negative values are not supported.");if(r===0n)return "0".repeat(Math.max(1,e));let t="",n=r;for(;n>0n;){let i=Number(n%Pr);t=Ee[i]+t,n/=Pr;}return t.length<e&&(t="0".repeat(e-t.length)+t),t}function Fu(r){if(r===0n)return Uint8Array.from([0]);let e=[],t=r;for(;t>0n;)e.push(Number(t&0xffn)),t>>=8n;return e.reverse(),Uint8Array.from(e)}function Ou(r){let e=0n;for(let t of r)e=(e<<8n)+BigInt(t);return e}function Lu(r){let e=String(r).replace(/-/g,"");if(!/^[0-9a-fA-F]{32}$/.test(e))throw new Error("INVALID_PARAMETER: Invalid UUID format.");let t=new Uint8Array(16);for(let n=0;n<16;n++)t[n]=parseInt(e.slice(n*2,n*2+2),16);return t}function Mu(r){let e=Array.from(Uu(r),t=>t.toString(16).padStart(2,"0")).join("");return [e.slice(0,8),e.slice(8,12),e.slice(12,16),e.slice(16,20),e.slice(20)].join("-")}function qu(r){let e=String(r);if(e.split("-").length===2)return e;let t=e.match(/^([0-9A-Za-z]+)-([0-9A-Za-z]+)-([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/);if(!t)throw new Error("INVALID_PARAMETER: Input must match <base62>-<base62>-<uuid>.");let[,n,i,s]=t;if(n.length<2)throw new Error("INVALID_PARAMETER: The first part must contain at least 2 characters.");if(i.length>=Ee.length)throw new Error("INVALID_PARAMETER: The middle section is too long to encode.");let o=n.slice(0,2),a=n.slice(2),u=i+o,c=Ee[i.length]+a+u,l=Lu(s),d=Nu(Ou(l));return `${c}-${d}`}function Vu(r){let e=String(r);if(e.split("-").length!==2)return e;let t=e.split("-");if(t.length!==2||!t[0]||!t[1])throw new Error("INVALID_PARAMETER: Corrupt compressed token: "+e);let[n,i]=t,s=Ee.indexOf(n[0]);if(s<0)throw new Error("INVALID_PARAMETER: Corrupt compressed token: "+e);let o=n.slice(1),a=s+2;if(o.length<a)throw new Error("INVALID_PARAMETER: Corrupt compressed token: "+e);let u=o.slice(0,o.length-a),c=o.slice(o.length-a),l=c.slice(s),d=c.slice(0,s),h=l+u;if(!/^[0-9A-Za-z]+$/.test(h)||!/^[0-9A-Za-z]+$/.test(d))throw new Error("INVALID_PARAMETER: Corrupt compressed token: "+e);let p=ku(i),g=Fu(p);if(g.length>16)throw new Error("INVALID_PARAMETER: Corrupt compressed token: "+e);let _=new Uint8Array(16);_.set(g,16-g.length);let w=Mu(_);return `${h}-${d}-${w}`}function tt(r,e,t=[],n=null){let i=["string","number","boolean","object","array","function","null","undefined"];function s(g){return g!==null&&typeof g=="object"&&!Array.isArray(g)}function o(g){return s(g)}function a(g){return Array.isArray(g)}function u(g){return typeof g=="string"&&i.indexOf(g)!==-1}function c(g){return Array.isArray(g)?"array":g===null?"null":typeof g}function l(g){try{return JSON.stringify(g)}catch{return String(g)}}function d(g){if(u(g))return `Type<${g}>`;if(typeof g=="function")return "custom validator";try{return JSON.stringify(g,(_,w)=>typeof w=="function"?"custom validator":w)}catch{return String(g)}}function h(g,_){return _==="array"?Array.isArray(g):_==="object"?s(g):_==="null"?g===null:_==="undefined"?typeof g>"u":typeof g===_}function p(g){return n===null?g:`${n}[${g}]`}if(typeof e>"u")throw new Error('Argument "struct" is required.');if(typeof e=="function")return e(r);if(o(e)){if(!s(r))throw new Error(`Data schema does not match:
207
- `+JSON.stringify(r,null,2));for(let g of Object.keys(e)){let _=p(g);if(Object.prototype.hasOwnProperty.call(r,g))r[g]=tt(r[g],e[g],t,_);else {if(t.indexOf(_)!==-1)throw new Error(`Key "${_}" is required.`);let w=e[g];a(w)&&w.length>1&&typeof w[w.length-1]=="function"&&(r[g]=w[w.length-1]());}}return r}if(a(e)){let g=false;if(e.length===1&&!a(e[0])&&!o(e[0])){let _=e[0];if(!Array.isArray(r))throw new Error(`Type <${c(r)}> is invalid in "${n}". Expected a list.`);for(let w=0;w<r.length;w++){let b=r[w];if(u(_)){if(!h(b,_))throw new Error(`Type <${c(b)}> is invalid in "${n}". Expected a list of Type <${_}>.`)}else if(typeof _=="function")r[w]=_(b);else if(b!==_)throw new Error(`Value ${l(b)} is invalid in "${n}". Expected a list of ${l(_)}.`)}g=true;}else if(Array.isArray(r)&&e.every(w=>!a(w)&&w!=="array")){for(let w=0;w<r.length;w++){let b=false,A="";for(let x of e)try{r[w]=tt(r[w],x,t,n),b=!0;break}catch(I){typeof x=="function"&&(A=I?.message||String(I));}if(!b&&A)throw new Error(A);if(!b){let x=e.map(d).join(", ");throw new Error(`${l(r[w])} is invalid in "${n}". allowed types or values are: ${x}.`)}}g=true;}else {let w="";for(let b of e)try{r=tt(r,b,t,n),g=!0;break}catch(A){typeof b=="function"&&(w=A?.message||String(A));}if(!g&&w)throw new Error(w)}if(!g){let _=e.map(d).join(", ");throw new Error(`${l(r)} is invalid in "${n}". allowed types or values are: ${_}.`)}return r}if(u(e)&&h(r,e)||r===e)return r;throw new Error(`${l(r)} is invalid in "${n}". allowed type or value is: ${d(e)}.`)}function Bu(r,e="User ID"){let t=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;if(r){if(typeof r!="string")throw new f(`${e} should be type: string.`,{code:"INVALID_PARAMETER"});if(!r.match(t))throw new f(`${e} is invalid.`,{code:"INVALID_PARAMETER"})}else throw new f(`${e} is empty.`,{code:"INVALID_PARAMETER"});return r}function $u(r){if(r&&(typeof r!="string"||r.charAt(0)!=="+"||isNaN(Number(r.substring(1)))))throw new f('"phone_number" is invalid. The format should be "+00123456789". Type: string.',{code:"INVALID_PARAMETER"});return r||""}function ju(r){if(r){if(typeof r!="string")throw new f('"birthdate" is invalid. The format should be "yyyy-mm-dd". Type: string.',{code:"INVALID_PARAMETER"});{let e=new RegExp(/([12]\d{3}-(0[1-9]|1[0-2])-(0[1-9]|[12]\d|3[01]))/);if(r.length!==10||r.split("-").length!==3||!e.test(r))throw new f('"birthdate" is invalid. The format should be "yyyy-mm-dd". Type: string.',{code:"INVALID_PARAMETER"})}}return r||""}function Ku(r){if(r){if(typeof r!="string")throw new f('"password" should be type: string.',{code:"INVALID_PARAMETER"});if(r.length<6)throw new f('"password" should be at least 6 characters.',{code:"INVALID_PARAMETER"});if(r.length>60)throw new f('"password" can be up to 60 characters max.',{code:"INVALID_PARAMETER"})}else throw new f('"password" is required.',{code:"INVALID_PARAMETER"});return r}function Hu(r,e="email"){if(r){if(typeof r!="string")throw new f(`"${e}"should be type: string.`,{code:"INVALID_PARAMETER"});if(r.length<5)throw new f(`"${e}" should be at least 5 characters.`,{code:"INVALID_PARAMETER"});if(/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/.test(r)&&(r=r.trim(),r.split("@")[1].split(".").length>=2))return r.toLowerCase()}else throw new f(`"${e}" is required.`,{code:"INVALID_PARAMETER"});throw new f(`"${r}" is an invalid email.`,{code:"INVALID_PARAMETER"})}function Wu(r){let e=typeof window<"u",t=(()=>{let i=e&&window.location.origin||null;return i&&i.slice(-1)==="/"&&(i=i.slice(0,-1)),i})(),n=i=>{if(typeof i=="string"){if(i==="*")return "*";{let s=i.trim();if(s[0]==="/"&&t){if(t.slice(0,5)==="file:")throw new f(`"${i}" is an invalid url. Relative URL does not work on local file system. Use full URL string.`,{code:"INVALID_PARAMETER"});s=t+s;}else if(s[0]==="."&&t){if(t.slice(0,5)==="file:")throw new f(`"${i}" is an invalid url. Relative URL does not work on local file system. Use full URL string.`,{code:"INVALID_PARAMETER"});let a=e?window.location.href.split("?")[0]:"";a.slice(-1)!=="/"&&(a+="/"),s=a+s.slice(1);}let o;try{o=new URL(s);}catch{throw new f(`"${i}" is an invalid url.`,{code:"INVALID_PARAMETER"})}if(o.protocol)return o.href}}throw new f(`"${i}" is an invalid url.`,{code:"INVALID_PARAMETER"})};return Array.isArray(r)?r.map(i=>n(i)):n(r)}function Ju(r,e,t=[],n){let i=M(r,n),s=i.data;e.service="string",e.owner="string";let o={};for(let a in e)if(s&&typeof s=="object"&&!Array.isArray(s)&&s.hasOwnProperty(a))if(typeof s[a]=="function")o[a]=s[a];else try{o[a]=JSON.parse(JSON.stringify(s[a]));}catch{o[a]=s[a];}n?.precall&&n.precall({data:o,files:i?.files||[]});try{return tt(o,e,t)}catch(a){throw new f(a.message,{code:"INVALID_PARAMETER"})}}var m={UserId:Bu,PhoneNumber:$u,Birthdate:ju,Password:Ku,Email:Hu,Url:Wu,Params:Ju};var q=null;function Dr(r){let e={tkid:"ticket_id",cond:"condition",stmp:"timestamp",actn:"action",cnt:"count",ttl:"time_to_live",plch:"placeholder",hash:"hash",desc:"description",pmc:"limit_per_user"},t={};for(let n in r)if(n==="tkid"){let i=r[n].split("#");if(i.length===1){t.ticket_id=i[0];continue}t.ticket_id=i[1],t.consume_id=i[2],t.user_id=i[3];let s=i[2].slice(-4);if(t.is_test=s===":CHK",!r.stmp){let o=i[2].slice(0,-4);/^[0-9]+$/.test(o)?t.timestamp=parseInt(o,10):t.timestamp=ie(i[2].slice(0,-4));}}else e[n]?t[e[n]]=r[n]:t[n]=r[n];return t}async function ri(r){if(!r.ticket_id)throw new f("Ticket ID is required.",{code:"INVALID_PARAMETER"});if(!r.method)throw new f('Method is required. Should be either "GET" or "POST"',{code:"INVALID_PARAMETER"});let e=r.ticket_id;await this.__connection;let t=await T.bind(this)(`https://${this.service.slice(0,4)}.${this.customApiDomain}/auth/consume/${this.service}/${this.owner}/${e}`,r?.data||{},{method:r.method,auth:!!r?.auth});return Dr(t)}async function ni(r,e){await this.__connection;let t=await T.bind(this)("ticket",Object.assign({exec:"list"},r||{}),{auth:true,fetchOptions:e});return t.list=t.list.map(Dr),t}async function ii(r,e){await this.__connection;let t=await T.bind(this)("ticket",Object.assign({exec:"consumed"},r||{}),{auth:true,fetchOptions:e});return t.list=t.list.map(Dr),t}async function si(r){return T.bind(this)("register-ticket",Object.assign({exec:"reg"},r),{auth:true})}async function oi(r){return T.bind(this)("register-ticket",Object.assign({exec:"unreg"},r),{auth:true})}var Gu=3600;async function Je(){if(await this.__connection,this.session){let r=Math.floor(Date.now()/1e3),t=this.session.getIdToken().getExpiration();if(t<r+Gu){this.log("request:requesting new token",null);try{await G.bind(this)().getSession({refreshToken:!0}),this.log("request:received new tokens",{exp:this.session?.idToken?.payload?.exp,currentTime:r,expiresIn:t-r,token:this.session?.accessToken?.jwtToken,refreshToken:this.session?.refreshToken?.token});}catch(n){throw this.log("request:new token error",n),new f("User login is required.",{code:"INVALID_REQUEST"})}}else this.log("request:tokens",{exp:this.session.idToken.payload.exp,currentTime:r,expiresIn:t-r,token:this.session.accessToken.jwtToken,refreshToken:this.session.refreshToken.token});return this.session?.idToken?.jwtToken}else throw this.log("request:no session",null),Ae.bind(this)(),new f("User login is required.",{code:"INVALID_REQUEST"})}function ti(r,e){return new Promise((t,n)=>{e.refreshSession(r.getRefreshToken(),(i,s)=>{this.log("getSession:refreshSessionCallback",{refreshErr:i,refreshedSession:s}),i?(Ae.bind(this)(),n(i)):s.isValid()?t(s):(Ae.bind(this)(),n(new f("Invalid session.",{code:"INVALID_REQUEST"})));});})}function G(){if(!this.userPool)throw new f("User pool is missing",{code:"INVALID_REQUEST"});let r=()=>{let s=q.getSignInUserSession().getIdToken().payload||null,o=et(s);return this.log("normalized user attribute",o),this.__user=o,o},e=async s=>new Promise((o,a)=>{this.log("getSession:option",s);let{refreshToken:u=false,skipUserUpdateEventTrigger:c=false}=s||{};if(u&&c&&(c=false),q=this.userPool.getCurrentUser(),!q){this.log("getSession:cognitoUser",q),Ae.bind(this)(),a(null);return}let l=d=>{let h=d.getIdToken().payload;if(this.log("getSession:respond:sessionAttribute",h),h["custom:service"]!==this.service)throw this.log("getSession:respond","invalid service, signing out"),Ae.bind(this)(),new f("Invalid session.",{code:"INVALID_REQUEST"});return this.session=d,r(),c||this._runOnUserUpdateListeners(this.user),this.session};q.getSession((d,h)=>{if(this.log("getSession:getSessionCallback",{err:d,session:h}),!h){Ae.bind(this)(),a(new f("Current session does not exist.",{code:"INVALID_REQUEST"}));return}if(d){ti.bind(this)(h,q).then(b=>o(l(b))).catch(a);return}let p=Math.floor(Date.now()/1e3),g=h.getIdToken(),_=g.getExpiration(),w=_<p;if(this.log("getSession:currentTime",p),this.log("getSession:idTokenExp",_),this.log("getSession:isExpired",w),this.log("getSession:existingBearerToken",this.bearerToken),this.bearerToken=g.getJwtToken(),w||u||!h.isValid())ti.bind(this)(h,q).then(b=>o(l(b))).catch(a);else try{o(l(h));}catch(b){a(b);}});}),t=(s,o)=>{let a=o||s.includes(this.service+"-")?s:this.service+"-"+K.hash(s);return {cognitoUser:new we({Username:a,Pool:this.userPool}),cognitoUsername:a}};return {getSession:e,authenticateUser:(s,o,a=false,u=false)=>new Promise((c,l)=>{this.__request_signup_confirmation=null,this.__disabledAccount=null;let d=t(s,a),h=d.cognitoUsername,p=new Qt({Username:h,Password:o});d.cognitoUser.authenticateUser(p,{newPasswordRequired:(g,_)=>{this.__disabledAccount=null,this.__request_signup_confirmation=h,g["custom:signup_ticket"]==="PASS"||g["custom:signup_ticket"]==="MEMBER"||g["custom:signup_ticket"]==="OIDPASS"?d.cognitoUser.completeNewPasswordChallenge(o,{},{onSuccess:w=>{q=d.cognitoUser,e().then(b=>c(this.user));},onFailure:w=>{l(new f(w.message||"Failed to authenticate user.",{code:w.code}));}}):l(new f("User's signup confirmation is required.",{code:"SIGNUP_CONFIRMATION_NEEDED"}));},onSuccess:g=>e({skipUserUpdateEventTrigger:true}).then(_=>{this.__disabledAccount=null,this._runOnLoginListeners(this.user),this._runOnUserUpdateListeners(this.user),c(this.user);}),onFailure:g=>{let _=[],{parsed:w,code:b}=Ot(g),A=typeof g?.message=="string"?g.message:"";if(b==="NotAuthorizedException"?A.includes("User is disabled.")?(this.__disabledAccount=h,_=["This account is disabled.","USER_IS_DISABLED"]):u?_=["The account already exists.","ACCOUNT_EXISTS"]:_=["Incorrect username or password.","INCORRECT_USERNAME_OR_PASSWORD"]:b==="UserNotFoundException"?_=["Incorrect username or password.","INCORRECT_USERNAME_OR_PASSWORD"]:b==="UserNotConfirmedException"?(this.__request_signup_confirmation=h,_=["User's signup confirmation is required.","SIGNUP_CONFIRMATION_NEEDED"]):(b==="TooManyRequestsException"||b==="LimitExceededException")&&(_=["Too many attempts. Please try again later.","REQUEST_EXCEED"]),w.code==="SIGNUP_CONFIRMATION_NEEDED"&&(this.__request_signup_confirmation=h),_.length){let x=_[1],I=_[0];l(new f(I,{code:x,cause:g}));}else l(w);}});}),createCognitoUser:t,signup:(s,o,a)=>new Promise((u,c)=>{this.userPool.signUp(s,o,a,null,(l,d)=>{if(l){let{parsed:h,code:p}=Ot(l),g=[];p==="UsernameExistsException"?g=["The account already exists.","EXISTS"]:p==="InvalidPasswordException"?g=["Invalid password. Password must be at least 6 characters.","INVALID_PARAMETER"]:p==="InvalidParameterException"?g=[h.message||"Invalid parameter.","INVALID_PARAMETER"]:p==="TooManyRequestsException"||p==="LimitExceededException"?g=["Too many attempts. Please try again later.","REQUEST_EXCEED"]:p==="CodeDeliveryFailureException"?g=["Failed to deliver verification code.","CODE_DELIVERY_FAILURE"]:p==="UserLambdaValidationException"&&(g=[h.message||"Signup validation failed.","INVALID_REQUEST"]),g.length?c(new f(g[0],{code:g[1],cause:l})):c(h);return}u(d);});})}}function Ot(r){let e=typeof r?.code=="string"&&r.code.trim()?r.code.trim():"ERROR",n=((typeof r?.message=="string"?r.message:typeof r=="string"?r:"An error occurred.")||"An error occurred.").trim();n||(n="An error occurred.");let i=n.match(/#([A-Za-z0-9_]+)\s*:\s*([\s\S]+)/),s=i?.[1]?.trim()||e,o=i?.[2]?.trim()||n;return {parsed:new f(o,{code:s,cause:r}),code:e}}async function ai(r){await this.__authConnection;let e=r?.refreshToken||false;if(!e)return this.user;try{return await G.bind(this)().getSession(Object.assign({skipUserUpdateEventTrigger:!e,refreshToken:e},r)),this.user}catch{return null}}async function ui(r){await this.__connection,r=m.Params(r,{token:"string",id:"string",merge:o=>{if(o===void 0)return false;if(typeof o=="string")return [o];if(Array.isArray(o)){for(let a of o)if(typeof a!="string")throw new f('"merge" array items should be type: <string>.',{code:"INVALID_PARAMETER"})}if(typeof o!="boolean"&&!Array.isArray(o))throw new f('"merge" should be type: <boolean | string[]>.',{code:"INVALID_PARAMETER"});return o},template:o=>{if(typeof o!="object"||o===null)throw new f('"template" should be type: <object>.',{code:"INVALID_PARAMETER"});if(o.welcome!==void 0&&(typeof o.welcome!="string"||!o.welcome))throw new f('"template.welcome" should be a non-empty <string> (template message_id).',{code:"INVALID_PARAMETER"});return o}});let e={token:r.token,id:r.id,merge:r.merge};r.template?.welcome&&(e.template_welcome=r.template.welcome);let t=await T.bind(this)("openid-logger",e),n=t.logger.split("#"),i=this.service+"-"+n[0],s=n[1];return {userProfile:await G.bind(this)().authenticateUser(i,s,true,true),openid:t.openid}}function Qu(r){let e=typeof globalThis<"u"?globalThis:void 0;if(e?.Buffer)return e.Buffer.from(r,"base64").toString("utf8");if(typeof atob=="function"){let t=atob(r),n=new Uint8Array(t.length);for(let i=0;i<t.length;i++)n[i]=t.charCodeAt(i);return typeof TextDecoder<"u"?new TextDecoder().decode(n):t}throw new Error("No base64 decoder available in this environment")}function zu(r){let e=r.split(".");if(e.length!==3)throw new Error("Invalid JWT format");let n=e[1].replace(/-/g,"+").replace(/_/g,"/"),i=Qu(n);return JSON.parse(i)}async function ci(r){await this.__authConnection,this.log("loginWithToken:params",r),r=m.Params(r,{idToken:"string",accessToken:"string",refreshToken:"string"},["idToken"]);let e=zu(r.idToken);if(this.log("loginWithToken:idTokenPayload",e),e["custom:service"]!==this.service)throw new f("Token does not belong to this service.",{code:"INVALID_REQUEST"});let t=Math.floor(Date.now()/1e3);if(e.exp&&e.exp<t)throw new f("Token has expired.",{code:"INVALID_REQUEST"});if(this.__user=et(e),this.session=null,r.accessToken&&r.refreshToken)try{if(this.session=new He({IdToken:new je({IdToken:r.idToken}),AccessToken:new $e({AccessToken:r.accessToken}),RefreshToken:new Ke({RefreshToken:r.refreshToken})}),this.log("loginWithToken:session",this.session),this.log("loginWithToken:CognitoUser",we),this.log("loginWithToken:userPool",this.userPool),we&&this.userPool){this.log("loginWithToken:cognito:username",e["cognito:username"]);let n={Username:e["cognito:username"],Pool:this.userPool};this.log("loginWithToken:cognitoUserParams",n),q=new we(n),q.setSignInUserSession(this.session),this.log("loginWithToken:cognitoUserRestored",{cognitoUserType:typeof q,cognitoUserKeys:Object.keys(q||{}),cognitoUser:q});}}catch(n){this.log("loginWithToken:err",n);try{this.log("loginWithToken:err:stringified",JSON.stringify(n));}catch{this.log("loginWithToken:err:stringifyFail",String(n));}try{let i=Object.keys(n||{}),s=Object.getOwnPropertySymbols?Object.getOwnPropertySymbols(n||{}):[],o=Object.getOwnPropertyDescriptors?Object.getOwnPropertyDescriptors(n||{}):{};this.log("loginWithToken:createSessionError:allKeys",{keys:i,symbols:s,descriptors:o});}catch(i){this.log("loginWithToken:createSessionError:allKeysFail",String(i));}}return this._runOnLoginListeners(this.user),this._runOnUserUpdateListeners(this.user),this.user}async function H(){return await this.__connection,this.__user?.service===this.service?this.__user?.owner===this.host:(await rt.bind(this)(),false)}async function Ae(r=false){let e=null;q&&(r?e=new Promise((n,i)=>{q.globalSignOut({onSuccess:s=>{this.log("globalSignOut:success",s),n(s);},onFailure:s=>{this.log("globalSignOut:error",s),i(s);}});}):q.signOut());let t={session:null,__startKeyHistory:{},__cached_requests:{},__user:null};e&&(e=await e);for(let n in t)this[n]=t[n];return this._runOnUserUpdateListeners(null),this._runOnLoginListeners(null),e}async function rt(r){await this.__connection;let{data:e}=M(r);return await Ae.bind(this)(e?.global),"SUCCESS: The user has been logged out."}async function li(){if(!this.__request_signup_confirmation)throw new f("Least one login attempt is required.",{code:"INVALID_REQUEST"});return await T.bind(this)("confirm-signup",{username:this.__request_signup_confirmation})}async function di(r=false){if(typeof r=="string")r=m.Url(r);else if(typeof r!="boolean")throw new f("Argument should be type: <boolean | string>.",{code:"INVALID_REQUEST"});if(!this.__disabledAccount)throw new f("Least one signin attempt of disabled account is required.",{code:"INVALID_REQUEST"});return await T.bind(this)("recover-account",{username:this.__disabledAccount,redirect:r}),"SUCCESS: Recovery e-mail has been sent."}async function kr(r){let e=m.Params(r,{username:"string",email:"string",password:"string"},["password"]);if(await this.__authConnection,e.email)try{m.Email(e.email);}catch{e.username=e.email,delete e.email;}if(!e.username&&!e.email)throw new f('Least one of "username" or "email" is required.',{code:"INVALID_PARAMETER"});return await G.bind(this)().authenticateUser(e.username||e.email,e.password)}async function fi(r,e){await this.__authConnection;let t={username:"string",password:c=>m.Password(c),email:c=>m.Email(c),name:"string",address:c=>{if(!c)return "";if(typeof c=="string")return c;if(typeof c=="object")return JSON.stringify(c)},gender:"string",birthdate:c=>c?m.Birthdate(c):"",phone_number:c=>c?m.PhoneNumber(c):"",email_public:["boolean",()=>false],address_public:["boolean",()=>false],gender_public:["boolean",()=>false],birthdate_public:["boolean",()=>false],phone_number_public:["boolean",()=>false],access_group:"number",misc:"string",picture:c=>c?m.Url(c):"",profile:c=>c?m.Url(c):"",family_name:"string",given_name:"string",middle_name:"string",nickname:"string",website:c=>c?m.Url(c):""},n=m.Params(r||{},t,["email","password"]);await rt.bind(this)(),e=m.Params(e||{},{email_subscription:c=>{if(typeof c!="boolean")throw new f('"option.email_subscription" should be type: <boolean>.',{code:"INVALID_PARAMETER"});if(!e?.signup_confirmation)throw new f('"option.signup_confirmation" is required for email subscription.',{code:"INVALID_PARAMETER"});return c},signup_confirmation:c=>{let l=c;if(typeof c=="string")l=m.Url(c);else if(typeof c=="boolean")l=c;else throw new f('"option.signup_confirmation" should be type: <string | boolean>.',{code:"INVALID_PARAMETER"});if(l&&!n.email)throw new f('"email" is required for signup confirmation.',{code:"INVALID_PARAMETER"});return l},login:c=>{if(typeof c=="boolean"){if(e.signup_confirmation&&c)throw new f('"login" is not allowed when "option.signup_confirmation" is true.',{code:"INVALID_PARAMETER"});return c}throw new f('"option.login" should be type: boolean.',{code:"INVALID_PARAMETER"})},template:c=>{if(typeof c!="object"||c===null)throw new f('"option.template" should be type: <object>.',{code:"INVALID_PARAMETER"});if(c.signup_confirmation!==void 0){if(typeof c.signup_confirmation!="string"||!c.signup_confirmation)throw new f('"option.template.signup_confirmation" should be a non-empty <string> (template message_id).',{code:"INVALID_PARAMETER"});if(!e?.signup_confirmation)throw new f('"option.signup_confirmation" is required when "option.template.signup_confirmation" is set.',{code:"INVALID_PARAMETER"})}if(c.welcome!==void 0&&(typeof c.welcome!="string"||!c.welcome))throw new f('"option.template.welcome" should be a non-empty <string> (template message_id).',{code:"INVALID_PARAMETER"});return c}});let i=e?.login||false;if(n.signup_confirmation=e?.signup_confirmation||false,n.email_subscription=e?.email_subscription||false,n.email_public&&!n.signup_confirmation)throw new f('"option.signup_confirmation" should be true if "email_public" is set to true.',{code:"INVALID_PARAMETER"});n.service=this.service,n.owner=this.owner;let s=G.bind(this)().createCognitoUser(n.username||n.email);for(let c of ["email_public","address_public","gender_public","birthdate_public","phone_number_public"])n[c]=n[c]?"1":"0";n.access_group&&(n.access_group=n.access_group.toString());let o=(await T.bind(this)("signupkey",{username:s.cognitoUsername,signup_confirmation:typeof n.signup_confirmation=="boolean"?JSON.stringify(n.signup_confirmation):n.signup_confirmation,email_subscription:n.email_subscription,template_confirmation:e?.template?.signup_confirmation||"",template_welcome:e?.template?.welcome||""})).split(":"),a=o.slice(1).join(":"),u=[new de({Name:"custom:signup",Value:o[0]}),new de({Name:"locale",Value:a.split("#")[1]}),new de({Name:"custom:signup_ticket",Value:a})];for(let c in t){let l=["email_public","address_public","gender_public","birthdate_public","phone_number_public","misc","service","owner"];n[c]!==""&&(c==="username"||c==="password"||c==="access_group"||(l.includes(c)?u.push(new de({Name:"custom:"+c,Value:n[c]})):u.push(new de({Name:c,Value:n[c]}))));}return await G.bind(this)().signup(s.cognitoUsername,n.password,u),n.signup_confirmation?(q=s.cognitoUser,this.__request_signup_confirmation=s.cognitoUsername,"SUCCESS: The account has been created. User's signup confirmation is required."):i?kr.bind(this)({email:n.username||n.email,password:n.password}):"SUCCESS: The account has been created."}async function hi(){await this.__connection;let r=await T.bind(this)("remove-account",{disable:this.__user.user_id},{auth:true});return await rt.bind(this)(),r}async function gi(r){await this.__connection;let e=m.Params(r,{email:i=>m.Email(i),code:["number","string"],new_password:i=>m.Password(i)},["email","code","new_password"]),t=e.code,n=e.new_password;return typeof t=="number"&&(t=t.toString()),new Promise(async(i,s)=>{G.bind(this)().createCognitoUser(e.email).cognitoUser.confirmPassword(t,n,{onSuccess:a=>{i("SUCCESS: New password has been set.");},onFailure:a=>{s(new f(a?.message||"Failed to reset password.",{code:a?.code||"ERROR",cause:a}));}});})}async function pi(r,e,t){await this.__connection;let n;if(!q)throw new f("The user has to be logged in.",{code:"INVALID_REQUEST"});if(r==="email"||r==="phone_number"){if(!this.__user.hasOwnProperty(r))throw new f(`No ${r==="email"?"e-mail":"phone number"} to verify`,{code:"INVALID_REQUEST"});if(this.__user?.[`${r}_verified`])return `SUCCESS: "${r}" is verified.`;n=(e?m.Params(e,{code:"string"}):{}).code||"";}else return;let i,s=t?.template?.verification;if(s!==void 0){if(typeof s!="string"||!s)throw new f('"template.verification" should be a non-empty <string> (template message_id).',{code:"INVALID_PARAMETER"});i={template_verification:s};}return new Promise((o,a)=>{let u={onSuccess:c=>{n?G.bind(this)().getSession({refreshToken:true}).then(()=>{this.__user&&(this.__user[r+"_verified"]=true),o(`SUCCESS: "${r}" is verified.`);}).catch(l=>{a(l);}):o("SUCCESS: Verification code has been sent.");},onFailure:c=>{a(new f(c.message||"Failed to request verification code.",{code:c?.code}));}};n?q?.verifyAttribute(r,n,u):(u.inputVerificationCode=null,q?.getAttributeVerificationCode(r,u,i));})}function mi(r,e){return pi.bind(this)("phone_number",r,e)}function _i(r,e){return pi.bind(this)("email",r,e)}async function bi(r,e){await this.__connection;let t=m.Params(r,{email:s=>m.Email(s)},["email"]),n,i=e?.template?.verification;if(i!==void 0){if(typeof i!="string"||!i)throw new f('"template.verification" should be a non-empty <string> (template message_id).',{code:"INVALID_PARAMETER"});n={template_verification:i};}return new Promise(async(s,o)=>{G.bind(this)().createCognitoUser(t.email).cognitoUser.forgotPassword({onSuccess:u=>{s("SUCCESS: Verification code has been sent.");},onFailure:u=>{let{parsed:c,code:l}=Ot(u),d={UserNotFoundException:"NOT_EXISTS",InvalidParameterException:"INVALID_PARAMETER",NotAuthorizedException:"INVALID_REQUEST",LimitExceededException:"REQUEST_EXCEED",TooManyRequestsException:"REQUEST_EXCEED",CodeDeliveryFailureException:"CODE_DELIVERY_FAILURE"}[l]||c.code||l||"ERROR";o(new f(c.message,{code:d,cause:u}));}},n);})}async function yi(r){if(await this.__connection,!this.session)throw new f("User login is required.",{code:"INVALID_REQUEST"});let e=m.Params(r,{current_password:"string",new_password:"string"});if(!e?.current_password)throw new f('"current_password" is required to change password.',{code:"INVALID_PARAMETER"});if(!e?.new_password)throw new f('"new_password" is required to change password.',{code:"INVALID_PARAMETER"});return m.Password(e.current_password),m.Password(e.new_password),new Promise((t,n)=>{q.changePassword(e.current_password,e.new_password,(i,s)=>{if(i){if(i?.code==="InvalidParameterException")n(new f("Invalid password parameter.",{code:"INVALID_PARAMETER"}));else if(i?.code==="NotAuthorizedException")n(new f("Incorrect password.",{code:"INVALID_REQUEST"}));else if(i?.code==="TooManyRequestsException"||i?.code==="LimitExceededException")n(new f("Too many attempts. Please try again later.",{code:"REQUEST_EXCEED"}));else {let{parsed:o}=Ot(i);n(o);}return}t("SUCCESS: Password has been changed.");});})}async function wi(r){if(await this.__connection,!this.session)throw new f("User login is required.",{code:"INVALID_REQUEST"});let e=m.Params(r||{},{user_id:i=>m.UserId(i),email:i=>m.Email(i),address:i=>{if(!i)return "";if(typeof i=="string")return i;if(typeof i=="object")return JSON.stringify(i)},name:"string",gender:"string",birthdate:i=>i?m.Birthdate(i):"",phone_number:i=>i?m.PhoneNumber(i):"",email_public:"boolean",phone_number_public:"boolean",address_public:"boolean",gender_public:"boolean",birthdate_public:"boolean",misc:"string",picture:i=>i?m.Url(i):"",profile:i=>i?m.Url(i):"",family_name:"string",given_name:"string",middle_name:"string",nickname:"string",website:i=>i?m.Url(i):""});if(e&&typeof e=="object"&&!Object.keys(e).length)return this.user;e.email&&(e.preferred_username=this.service+"-"+K.hash(e.email));let t=[["email_public","email_verified","User's e-mail should be verified to set"],["phone_number_public","phone_number_verified","User's phone number should be verified to set"]];if(this.__user){for(let i of t)if(e[i[0]]&&!this.__user[i[1]])throw new f(`${i[2]} "${i[0]}" to true.`,{code:"INVALID_REQUEST"})}let n=[];for(let i in e){if(e[i]===this.user[i]){n.push(i);continue}if(["email_public","phone_number_public","address_public","gender_public","birthdate_public","misc"].includes(i)){let o=e[i];typeof o=="boolean"&&(o=o?"1":"0"),e["custom:"+i]=o,n.push(i);}}for(let i of n)delete e[i];if(e.user_id)if(e.user_id===this.user.user_id)delete e.user_id;else return T.bind(this)("admin-edit-profile",{attributes:e},{auth:true});if(e&&typeof e=="object"&&Object.keys(e).length){let i=[];for(let s in e)i.push(new de({Name:s,Value:e[s]}));return await new Promise((s,o)=>{q?.updateAttributes(i,(a,u)=>{a&&o([a?.code||a?.name,a?.message||"Failed to update user settings."]),s(u);});}),await G.bind(this)().getSession({refreshToken:true}),this.user}return this.user}async function Ei(r,e){r=M(r).data,r||(r={searchFor:"timestamp",condition:">",value:0},e||(e={}),e.ascending=false),await this.__connection;let t={user_id:i=>Array.isArray(i)?i.map(s=>m.UserId(s)):m.UserId(i),email:"string",phone_number:"string",locale:i=>{if(typeof i!="string"||typeof i=="string"&&i.length>5)throw new f('Value of "locale" should be a country code.',{code:"INVALID_PARAMETER"});return i},name:"string",address:"string",gender:"string",birthdate:i=>m.Birthdate(i),subscribers:"number",timestamp:"number",access_group:"number",approved:"string"},n=["searchFor","value"];if(r=m.Params(r,{searchFor:["user_id","name","email","phone_number","address","gender","birthdate","locale","subscribers","timestamp","access_group","approved"],condition:[">",">=","=","<","<=","gt","gte","eq","lt","lte",()=>"="],value:i=>{let s=t[r.searchFor];if(typeof s=="function")return s(i);if(typeof i!==s)throw new f(`Value does not match the type of "${r.searchFor}" index.`,{code:"INVALID_PARAMETER"});return i},range:i=>{let s=t[r.searchFor];if(typeof s=="function")return s(i);if(typeof i!==s)throw new f(`Range does not match the type of "${r.searchFor}" index.`,{code:"INVALID_PARAMETER"});return i}},n),r?.condition&&r?.condition!=="="&&r.hasOwnProperty("range"))throw new f("Conditions does not apply on range search.",{code:"INVALID_PARAMETER"});if(r.searchFor==="user_id"&&(r.condition!=="="||r.range))throw new f(`Conditions are not allowed on "${r.searchFor}"`,{code:"INVALID_PARAMETER"});if(typeof r?.value=="string"&&!r?.value)throw new f("Value should not be an empty string.",{code:"INVALID_PARAMETER"});if(typeof r?.searchFor=="string"&&!r?.searchFor)throw new f('"searchFor" should not be an empty string.',{code:"INVALID_PARAMETER"});return T.bind(this)("get-users",r,{auth:true,fetchOptions:e})}async function Ai(r){await this.__connection;let e=await T.bind(this)("last-verified-email",r,{auth:true});return e.includes("SUCCESS")?(await G.bind(this)().getSession({refreshToken:true}),this.user):e}async function Si(r){return await this.__connection,r=m.Params(r,{username:m.Email,redirect:m.Url},["username"]),await T.bind(this)("request-username-change",r,{auth:true})}var Yu="1.2.1",Xu=class{constructor(r){ue(this,"version",Yu);ue(this,"items",[]);ue(this,"nextJobId",1);ue(this,"breakWhenError",false);ue(this,"batchSize",1);ue(this,"onProgress");ue(this,"activeCount",0);ue(this,"currentCycleCompleted",[]);ue(this,"stopProcessing",false);if(this.breakWhenError=!!r?.breakWhenError,this.batchSize=r?.batchSize??1,typeof this.batchSize!="number"||this.batchSize<1)throw new Error("batchSize must be at least 1");if(r?.onProgress)if(typeof r.onProgress=="function")this.onProgress=r.onProgress;else throw new Error("onProgress must be a function")}get batchToProcess(){return Math.ceil(this.items.length/this.batchSize)}add(r){let e=Array.isArray(r)?r:[r],t=[];for(let n of e){if(typeof n!="function")throw new Error("Each job must be a function that returns a Promise");let i=String(this.nextJobId++);this.items.push({id:i,job:n}),t.push(i);}return this.processNext(),t}setBatchSize(r){if(typeof r!="number"||r<1)throw new Error("batchSize must be at least 1");this.batchSize=r;}remove(r){let e=String(r),t=this.items.findIndex(n=>n.id===e);return t===-1?false:(this.items.splice(t,1),true)}processNext(){if(this.stopProcessing||this.items.length===0||this.activeCount>0)return;let r=this.items.splice(0,this.batchSize);this.activeCount=r.length,this.currentCycleCompleted=new Array(r.length),r.forEach((e,t)=>{Promise.resolve().then(()=>e.job()).then(n=>(this.finalizeJob(t,n,false),n)).catch(n=>(this.finalizeJob(t,n,true),n));});}finalizeJob(r,e,t){if(this.currentCycleCompleted[r]=e,this.activeCount-=1,t&&this.breakWhenError&&(this.stopProcessing=true,this.items=[]),this.activeCount!==0)return;let n=this.currentCycleCompleted.slice();this.currentCycleCompleted=[],this.onProgress&&this.onProgress({batchToProcess:this.batchToProcess,itemsToProcess:this.items.length,completed:n}),this.processNext();}terminate(){this.items=[];}},nt=Xu;var Ge=null,Ti=typeof SubmitEvent<"u",Zu=typeof HTMLFormElement<"u",st=Y(),Nr=0;function Ri(r){if(!r)return null;let e=Number(r);if(Number.isFinite(e))return Math.max(0,e*1e3);let t=Date.parse(r);return Number.isNaN(t)?null:Math.max(0,t-Date.now())}function Fr(r,e){return e>0?r/e*100:0}var vi=r=>{let{auth:e,type:t,endpoints:n,stable:i}=r,s=n[0],o=n[1];if(Nr++,t==="admin"){let a=Object.entries(s).filter(([u,c])=>u.includes(e?"_private":"_public")&&u!=="get_users_private"&&u!=="service_public"&&typeof c=="string").map(([,u])=>u);if(!a.length)throw new f("No available admin gateways.",{code:"INVALID_REQUEST"});return a[Nr%a.length]}if(t==="record"){let a=Object.entries(o).filter(([u,c])=>u.includes(e?"record_private":"record_public")&&typeof c=="string").map(([,u])=>u);if(!a.length)throw new f("No available record gateways.",{code:"INVALID_REQUEST"});return i?a[0]:a[Nr%a.length]}throw new f("Invalid gateway type.",{code:"INVALID_REQUEST"})};async function ec(r,e,t){let n=await Promise.all([this.admin_endpoint,this.record_endpoint]),i=n[0],s=n[1],o=r.split("?"),a=o.length>1?"?"+o[1]:"";switch(r=o[0],r){case "get-users":return i.get_users_private+r+a;case "service":return i.service_public+r+a;case "get-newsletters":case "get-public-newsletters":case "subscribe-newsletter":case "subscribe-public-newsletter":case "signupkey":case "admin-newsletter-request":case "admin-signup":case "confirm-signup":case "openid-logger":case "block-account":case "admin-edit-profile":case "remove-account":case "post-secure":case "recover-account":case "mock":case "grant-access":case "last-verified-email":case "ticket":case "register-ticket":case "get-newsletter-subscription":case "request-username-change":case "send-inquiry":case "register-newsletter-group":case "newsletter-group-endpoint":case "invitation-list":case "csr":case "csr-poll":case "csr-cancel":return vi.bind(this)({auth:e,type:"admin",endpoints:n})+r+a;case "post-record":return (e?s.post_private:s.post_public)+r+a;case "get-records":return (e?s.get_private:s.get_public)+r+a;case "del-files":case "del-records":return s.del_private+r+a;case "store-subscription":case "get-vapid-public-key":case "push-notification":case "delete-subscription":case "subscription":case "get-subscription":case "get-table":case "get-tag":case "get-uniqueid":case "get-index":case "get-signed-url":case "extract-file-text":case "grant-private-access":case "request-private-access-key":case "get-ws-group":case "check-schema":case "get-feed":case "castspell":case "dopamine":case "getspell":return vi.bind(this)({auth:e,type:"record",endpoints:n,stable:t})+r+a;default:return m.Url(r)+a}}var it={};function Ii(){Ge&&(Ge.terminate(),Ge=null);}async function T(r,e=null,t,n){this.log("request",{url:r,data:e,options:t,_etc:n||{}}),t=t||{};let{auth:i=false,method:s="post",bypassAwaitConnection:o=false}=t;s=s.toUpperCase();let a=null,u=e?.service||this.service,c=e?.owner||this.owner,l=null,d=await ec.bind(this)(r,!!i,!!t.stableGateway);if(!o&&(a=await this.__connection,!a))throw new f("Invalid connection. The service could have been disabled, or has a restricted CORS.",{code:"INVALID_REQUEST"});let h=t?.tokenHeaders?.idToken===true;(i||h)&&(l=await Je.bind(this)());let p={},{fetchMore:g=false,progress:_}=t?.fetchOptions||{};if(t?.fetchOptions&&Object.keys(t.fetchOptions).length){for(let P of ["limit","startKey","ascending"])if(t.fetchOptions.hasOwnProperty(P)){if(P==="startKey"&&t.fetchOptions[P]===null)continue;p[P]=t.fetchOptions[P];}p=m.Params(p,{limit:P=>{if(typeof P!="number")throw new f("Fetch limit should be a number.",{code:"INVALID_REQUEST"});if(P>1e3)throw new f("Fetch limit should be below 1000.",{code:"INVALID_REQUEST"});return P},startKey:P=>P,ascending:"boolean"});}let w=n?.ignoreService?{}:{service:u,owner:c};Object.assign(w,p),e=M(e).data,e?e&&typeof e=="object"&&(e=Object.assign(w,e)):e=w;let b=`${s}:${i?"auth":"public"}:${r}`,A=(()=>{if(e&&typeof e=="object"&&Object.keys(e).length&&!(st&&e instanceof FormData)){let P=function(k){return typeof k=="object"&&k!==null?Object.keys(k).sort().reduce((N,L)=>(typeof k[L]=="object"&&k[L]!==null?N[L]=P(k[L]):N[L]=k[L],N),{}):k};return K.hash(b+"/"+JSON.stringify(P(e)))}return K.hash(b+"/"+u)})(),{requestKey:x,requestKeyWithStartKey:I}=tc.bind(this)({params:e,url:r,fetchMore:g,hashedParams:A});if(!x||x&&typeof x=="object")return x;if(this.log("requestKey",I),typeof I=="string"&&it[I]instanceof Promise)return this.log("request:returning pending",I),it[I];let D={Accept:"*/*"};if(Object.prototype.hasOwnProperty.call(t,"contentType")&&t.contentType!==void 0){let P=t.contentType===null?"application/x-www-form-urlencoded":t.contentType;P&&(D["Content-Type"]=P);}else D["Content-Type"]="application/json";if(l&&(D.Authorization=l),t?.tokenHeaders){let P=(L,Ne)=>typeof L=="string"?L:L===true?Ne:null,k=P(t.tokenHeaders.accessToken,this.session?.accessToken?.jwtToken||null),N=P(t.tokenHeaders.idToken,this.bearerToken||this.session?.idToken?.jwtToken||l||null);k&&(D["X-Access-Token"]=k),N&&(D["X-Id-Token"]=N);}let Q={public_identifier:this.__public_identifier,service:u,owner:c};D["Content-Meta"]=JSON.stringify(Q),t.revalidate&&(D["Cache-Control"]="no-cache",D.Pragma="no-cache");let O={headers:D};if(t?.responseType&&(O.responseType=t.responseType),s==="GET"){if(e){let P=[];if(st&&e instanceof FormData?P=Array.from(e.entries()).map(([k,N])=>{let L=typeof N=="string"?N:N.name;return encodeURIComponent(k)+"="+encodeURIComponent(L)}):P=Object.keys(e).map(k=>{let N=e[k];return typeof N!="string"&&(N=JSON.stringify(N)),encodeURIComponent(k)+"="+encodeURIComponent(N)}),P.length){let k=d.includes("?")?d.endsWith("?")||d.endsWith("&")?"":"&":"?";d+=k+P.join("&");}}O.body=null;}else if(st&&e instanceof FormData)O.body=e;else if(D["Content-Type"]==="application/x-www-form-urlencoded"&&e&&typeof e=="object"){let P=new URLSearchParams;for(let k of Object.keys(e)){let N=e[k];P.append(k,typeof N=="string"?N:JSON.stringify(N));}O.body=P.toString();}else typeof e=="string"?O.body=e:O.body=e?JSON.stringify(e):null;if(O.method=s,Ge===null){let P={batchSize:this.requestBatchSize,breakWhenError:false,onProgress:k=>{this.onBatchProcess.forEach(N=>N(k));}};Ge=new nt(P);}return this.log("request-opt",O),new Promise((P,k)=>{Ge.add([async()=>{let N=Pi.bind(this)(d,O,_);it[I]=N;try{let L=rc.bind(this)({hashedParam:x,requestKeyWithStartKey:I,url:r,fetched:await N});return delete it[I],this.log("request:end",L),P(L),L}catch(L){throw delete it[I],this.log("request:err",L),k(L),L}}]);})}function tc(r){let{params:e={},url:t,fetchMore:n=false,hashedParams:i}=r||{};if(e.startKey){if(!(typeof e.startKey=="object"&&Object.keys(e.startKey).length)&&e.startKey!=="start"&&e.startKey!=="end")throw new f(`"${e.startKey}" is invalid startKey key.`,{code:"INVALID_PARAMETER"});e.startKey==="start"&&(n=false,delete e.startKey);}if(!n){if(this.__cached_requests?.[t]?.[i]&&delete this.__cached_requests[t][i],this.__startKeyHistory?.[t]?.[i]){if(Array.isArray(this.__startKeyHistory[t][i])&&this.__startKeyHistory[t][i].length)for(let u of this.__startKeyHistory[t][i]){let c=i+K.hash(u);this.__cached_requests?.[t]&&this.__cached_requests?.[t]?.[c]&&delete this.__cached_requests[t][c];}delete this.__startKeyHistory[t][i];}return {requestKeyWithStartKey:i,requestKey:i}}if(!Array.isArray(this.__startKeyHistory?.[t]?.[i]))return {requestKeyWithStartKey:i,requestKey:i};let s=this.__startKeyHistory[t][i],o=s[s.length-1],a=i;if(o){if(o==="end")return {requestKey:{list:[],startKey:"end",endOfList:true,startKeyHistory:s},requestKeyWithStartKey:a};a+=K.hash(o),e.startKey=JSON.parse(o);}return this.__cached_requests?.[t]?.[a]?{requestKey:this.__cached_requests[t][a],requestKeyWithStartKey:a}:{requestKeyWithStartKey:a,requestKey:i}}function Pi(r,e,t){return new Promise((n,i)=>{let s=new XMLHttpRequest;s.open(e.method||"GET",r);for(var o in e.headers||{})s.setRequestHeader(o,e.headers[o]);e.responseType&&(s.responseType=e.responseType),s.onload=()=>{if(s.status<400)if(e.responseType=="json"||e.responseType=="blob")n(s.response);else {let a=s.responseText;try{a=JSON.parse(a);}catch{}n(a);}else if(s.status===429){let a=s.getResponseHeader("Retry-After"),u=Ri(a);u!==null?setTimeout(()=>{Pi(r,e,t).then(n,i);},u):i("Too many requests");}else {let a=s.status,u=["INVALID_CORS","INVALID_REQUEST","SERVICE_DISABLED","INVALID_PARAMETER","ERROR","EXISTS","NOT_EXISTS"],c=e.responseType=="blob"?s.response:s.responseText;try{c=JSON.parse(c);}catch{}if(typeof c=="string"){let l=c.split(":"),d=l.splice(0,1)[0].trim(),h=l.join(":").trim();i(new f(h||c,{code:u.includes(d)?d:"ERROR"}));}else if(typeof c=="object"&&c?.message){let l=c?.code||(a?a.toString():null)||"ERROR",d=c.message,h=c?.cause;typeof d=="string"&&(d=d.trim()),i(new f(d,{cause:h,code:l}));}else i(c);}},s.onerror=()=>i("Network error"),s.onabort=()=>i("Aborted"),s.ontimeout=()=>i("Timeout"),typeof t=="function"&&(s.onprogress=a=>{t({status:"download",progress:Fr(a.loaded,a.total),loaded:a.loaded,total:a.total,abort:()=>s.abort()});},s.upload&&(s.upload.onprogress=a=>{t({status:"upload",progress:Fr(a.loaded,a.total),loaded:a.loaded,total:a.total,abort:()=>s.abort()});})),s.send(e.body);})}function rc(r){let{hashedParam:e,requestKeyWithStartKey:t,url:n,fetched:i}=r;if(!i?.startKey)return i;this.__startKeyHistory.hasOwnProperty(n)||(this.__startKeyHistory[n]={}),this.__startKeyHistory[n].hasOwnProperty(e)||(this.__startKeyHistory[n][e]=[]);let s=i.startKey==="end"?"end":JSON.stringify(i.startKey);return this.__startKeyHistory[n][e].includes(s)||this.__startKeyHistory[n][e].push(s),this.__cached_requests?.[n]||(this.__cached_requests[n]={}),this.__cached_requests[n][t]=i,Object.assign({startKeyHistory:this.__startKeyHistory[n][e]},i)}async function Mt(r,e){await this.__connection;let{record_id:t,service:n=this.service,progress:i}=e;if(!t)throw new f('"record_id" is required.',{code:"INVALID_PARAMETER"});if(Ti&&r instanceof SubmitEvent&&(r=r.target),Zu&&r instanceof HTMLFormElement&&(r=new FormData(r)),!st||!(r instanceof FormData))throw new f('"fileList" should be a FormData or HTMLFormElement.',{code:"INVALID_PARAMETER"});let o={reserved_key:De(),service:n,request:"post"};e?.record_id&&(o.id=e.record_id);let a,u=(p,g,_)=>new Promise((w,b)=>{a=new XMLHttpRequest,a.open("POST",p),a.onload=()=>{let A=a.responseText;try{A=JSON.parse(A);}catch{}if(a.status>=200&&a.status<300)w(A);else if(a.status===429){let x=a.getResponseHeader("Retry-After"),I=Ri(x);I!==null?setTimeout(()=>{u(p,g,_).then(w,b);},I):b("Too many requests");}else b(A);},a.onerror=()=>b("Network error"),a.onabort=()=>b("Aborted"),a.ontimeout=()=>b("Timeout"),a.upload&&typeof _=="function"&&(a.upload.onprogress=_),a.send(g);});function c(p){let g="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";if(p===0)return g[0];let _="";for(;p>0;)_=g[p%62]+_,p=Math.floor(p/62);return _}let l=[],d=[],h=[];for(let[p,g]of r.entries()){if(!(g instanceof File))continue;let _=Object.assign({key:p+"/"+g.name,sizeKey:c(g.size),contentType:g.type||null},o),{fields:w=null,url:b,cdn:A}=await T.bind(this)("get-signed-url",_,{auth:!!this.__user});h.push(A);let x=new FormData;for(let I in w)x.append(I,w[I]);x.append("file",g);try{await u(b,x,typeof i=="function"?I=>i({status:"upload",progress:Fr(I.loaded,I.total),currentFile:g,completed:l,failed:d,loaded:I.loaded,total:I.total,abort:()=>a.abort()}):null),l.push(g);}catch{d.push(g);}}return {completed:l,failed:d,bin_endpoints:h}}var Lt={};function R(r){let{preventMultipleCalls:e=false}=r||{};return function(t,n,i){let s=i.value;i.value=function(...o){let a=o[0],u=true,c=null,l="",d={},h=false;if(Ti&&a instanceof SubmitEvent){a.preventDefault();let b=window.location.href;c=a.target;let A=new URL(c.action);l=A.href;let x=l?l.match(/(?<=\{).*?(?=\})/g):"";if(x)for(let I of x){if(!I)continue;let D=c.querySelector(`[name="${I}"]`);if(D)if(D.type==="file")for(let F=0;F<=D.files.length-1;F++)D.files[F]&&(d[I]||(d[I]=[]),d[I].push(new Promise((Q,O)=>{let P=new FileReader;P.onload=function(){Q(P.result);},P.readAsDataURL(D.files[F]),P.onerror=O;})));else l=l.replace(`{${I}}`,D.value);}c.getAttribute("action")===null?u=false:h=A.href===b;}let p=async b=>{if(l)for(let A in d)d[A].length&&(l=l.replace(`{${A}}`,(await Promise.all(d[A])).join(",")));return c&&u&&(window.sessionStorage.setItem(`${this.service}:${K.hash(l)}`,JSON.stringify(b)),h?window.location.replace(l):window.location.href=l),b},g,_=b=>{throw b instanceof f?b.name=n+"()":b=b instanceof Error?b:new f(b,{name:n+"()"}),b},w=async()=>{try{if(g=s.bind(this)(...o),g instanceof Promise){let b=await g;return p(b)}return p(g)}catch(b){throw _(b)}};if(e){let b=`${n}:${this?.__public_identifier||""}:${this?.service||""}:${this?.owner||""}`;return Lt?.[b]||(Lt[b]=w().finally(()=>{delete Lt[b];})),Lt[b]}return w()};}}async function xi(){await this.__connection;let r=`${this.service}:${K.hash(window.location.href.split("?")[0])}`,e=window.sessionStorage.getItem(r);if(window.sessionStorage.removeItem(r),e!==null){try{e=JSON.parse(e);}catch{}return e}return null}var nc=256,ic=256,sc=256,Ui=256,oc="\u{10FFFF}",ac=/[\u0000-\u001F\u007F]|\u{10FFFF}/u,uc={"/":"%2F","!":"%21","*":"%2A","#":"%23"},cc={"%2F":"/","%21":"!","%2A":"*","%23":"#"};function lc(r){return r.replace(/%/g,"%25").replace(/[\/!*#]/g,t=>uc[t]||t)}function se(r){return typeof r!="string"?r:r.replace(/%(2F|21|2A|23)/gi,t=>{let n=t.toUpperCase();return cc[n]||t}).replace(/%25/gi,"%")}function fe(r,e,t={}){let{allowEmpty:n=false,maxLength:i,blockKeyDelimiters:s=false,disallowLeadingDollar:o=false,onlyAlphanumeric:a=false}=t;if(typeof r!="string")throw new f(`"${e}" should be type: <string>.`,{code:"INVALID_PARAMETER"});if(a&&/[^a-zA-Z0-9]/.test(r))throw new f(`"${e}" should only contain alphanumeric characters.`,{code:"INVALID_PARAMETER"});if(!n&&r.length===0)throw new f(`"${e}" is required.`,{code:"INVALID_PARAMETER"});if(i&&r.length>i)throw new f(`"${e}" should be <= ${i} characters.`,{code:"INVALID_PARAMETER"});if(ac.test(r)||r.includes(oc))throw new f(`"${e}" cannot include control characters or unsupported sentinel characters.`,{code:"INVALID_PARAMETER"});if(s&&(r=lc(r),i&&r.length>i))throw new f(`"${e}" should be <= ${i} characters. "/", "!", "*", "#" and "%" count as 3 characters each.`,{code:"INVALID_PARAMETER"});if(o&&r.startsWith("$"))throw new f(`"${e}" cannot start with "$".`,{code:"INVALID_PARAMETER"});return r}function Qe(r,e="table.name",t={}){return fe(r,e,{allowEmpty:t.allowEmpty===true,maxLength:nc,blockKeyDelimiters:true})}function Vt(r,e="tag",t={}){return fe(r,e,{allowEmpty:t.allowEmpty===true,maxLength:ic,blockKeyDelimiters:true})}function ot(r,e="index.name",t={}){return fe(r,e,{allowEmpty:t.allowEmpty===true,maxLength:sc,blockKeyDelimiters:true,disallowLeadingDollar:true})}function Ci(r,e="index.value"){return fe(r,e,{allowEmpty:true,maxLength:Ui})}function Or(r){return typeof r=="string"&&r.slice(-1)==="."}function Lr(r,e){return fe(r,e,{allowEmpty:true,maxLength:Ui,blockKeyDelimiters:true})}function Di(r){if(!r.record_id&&!r.unique_id)return null;let e={};return r?.service&&(e.service=r.service),r?.owner&&(e.owner=r.owner),r?.record_id?e.record_id=fe(r.record_id,"record_id",{allowEmpty:false,onlyAlphanumeric:true}):r?.unique_id&&(e.unique_id=r.unique_id),e}function Mr(r){if(r===void 0)return 0;if(typeof r=="number"){if(r>99||r<0)throw new f('"table.access_group" value should be within a range of 0 ~ 99.',{code:"INVALID_REQUEST"})}else if(typeof r=="string"){if(r={private:"private",public:0,authorized:1,admin:99}[r],r===void 0)throw new f('"table.access_group" is invalid.',{code:"INVALID_PARAMETER"})}else throw new f('"table.access_group" should be type: <number | string>.',{code:"INVALID_PARAMETER"});if(!this.__user&&r)throw new f("Unsigned users have no access to records with access group.",{code:"INVALID_REQUEST"});return r}var qt=4503599627370496;function Bt(r){if(typeof r=="number"){if(r>qt||r<-qt)throw new f(`Number value should be within range -${qt} ~ +${qt}`,{code:"INVALID_PARAMETER"});return r}if(typeof r=="boolean")return r;if(typeof r=="string")return Ci(r,"index.value");throw new f('"index.value" should be type: <number | boolean | string>.',{code:"INVALID_PARAMETER"})}function ki(r,e){if(!e.index||!("value"in e.index))throw new f('"index.value" is required.',{code:"INVALID_PARAMETER"});if(e.index.name==="$record_id")throw new f(`Cannot do "index.range" on ${e.index.name}`,{code:"INVALID_PARAMETER"});if(typeof e.index.value!=typeof r)throw new f('"index.range" type should match the type of "index.value".',{code:"INVALID_PARAMETER"});return typeof r=="string"?Or(e.index.name)?Lr(r,"index.range"):Ci(r,"index.range"):r}var $t={},dc=10080*60,fc=3600,Ni=2;function hc(r,e){if(!e)return String(Ni);let t=Math.max(60,r-300)*1e3;return Ni+"."+Math.floor(Date.now()/t)}function gc(r){if(!this.user?.user_id)return false;let e=r[6]==="**"?"**":parseInt(r[6]),t=this.user?.access_group??-1;return !(this.user.user_id!==r[3]&&(e==="**"||t<e))}async function pc(r){return typeof r=="string"?r:r&&typeof r.text=="function"?await r.text():await new Promise((e,t)=>{try{let n=new FileReader;n.onload=()=>e(n.result),n.onerror=()=>t(n.error||new Error("Failed to read blob")),n.readAsText(r);}catch(n){t(n);}})}async function ze(r,e,t=false){let n={user_id:"",record_id:"",updated:0,uploaded:0,readonly:false,table:{name:"",access_group:0,subscription:{is_subscription_record:false,upload_to_feed:false,notify_subscribers:false,feed_referencing_records:false,notify_referencing_records:false}},referenced_count:0,source:{referencing_limit:null,prevent_multiple_referencing:false,can_remove_referencing_records:false,only_granted_can_reference:false},ip:"",bin:{}},i=false,s=[];function o(c){let l=c=="**"?"private":parseInt(c);return l=l==0?"public":l==1?"authorized":l==99?"admin":l,l}let a={ip:c=>{let l=c.split("#"),d=l[0];l.length>1&&(n.unique_id=l.slice(1).join("#")),d.slice(-1)==="R"?(n.readonly=true,d=d.slice(0,-1)):n.readonly=false,/^\d{1,3}-\d{1,3}-\d{1,3}-\d{1,3}$/.test(d)&&(d=d.split("-").join("."),i=true),n.ip=d;},rec:c=>{if(!c)return;n.record_id=c;let l=c.substring(0,c.length-9),d=ie(l);n.uploaded=d;},usr:c=>{n.user_id=c;},tbl:c=>{if(c&&!n.table.name){let l=c.split("/");n.table.name=se(l[0]),n.table.access_group=o(l[2]),l?.[3]&&(n.table.subscription.is_subscription_record=true);}},usr_tbl:c=>{let l=c.split("/");n.user_id||(n.user_id=l[0]),n.table.name||(n.table.name=se(l[1]),n.table.access_group=o(l[3]),l?.[4]&&(n.table.subscription.is_subscription_record=true));},idx:c=>{if(!c)return;let l=c.split("!"),d=se(l.splice(0,1)[0]),h=mc("!"+l.join("!"));n.index={name:d,value:h};},ref:c=>{c&&(n.reference=c.split("/")[0]);},tags:c=>{n.tags=Array.isArray(c)?c.map(l=>se(l)):c;},upd:c=>{n.updated=c;},acpt_mrf:c=>{n.source.prevent_multiple_referencing=!c;},ref_limt:c=>{n.source.referencing_limit=c;},rfd:c=>{n.referenced_count=c;},bin:async c=>{let l={},d=n?.reference||null;if(Array.isArray(c)){let h=await Promise.all(c.map(async p=>{try{let g=p.split("/").slice(3).join("/"),_=g.split("/");if(_.length<12)return null;let w=_[_.length-1],b=_[10];if(b==="__data__"&&w==="__json__.json")return {isDataFile:!0,rawUrl:p};let A=_[9],x=_[8],I=o(_[6]),D=p,F=I!=="public"&&gc.call(this,_)?{expires:fc,browserCache:dc}:null;if(I!=="public")try{D=await ke.bind(this)(p,{dataType:"endpoint",_ref:d});}catch(O){console.error("Error getting signed url for private file:",O),D=p;}let Q={access_group:I,filename:w,url:D,path:g,size:ie(A),uploaded:ie(x),getFile:(O,P)=>{let k={dataType:O||"download",progress:P,_ref:d},N=()=>ke.bind(this)(D,Object.assign({},k,{_update:Q}));return F?ke.bind(this)(p,Object.assign({},k,F)).catch(()=>N()):N()}};return {pathKey:b,obj:Q}}catch{return null}}));for(let p of h)if(p&&!p.isDataFile){if(l[p.pathKey]){l[p.pathKey].push(p.obj);continue}l[p.pathKey]=[p.obj];}}n.bin=l;},prv_acs:c=>{for(let l in c)["notify_subscribers","upload_to_feed","feed_referencing_records","notify_referencing_records"].includes(l)?n.table.subscription[l]=c[l]:l==="referencing_index_restrictions"&&Array.isArray(c[l])?n.source[l]=c[l].map(h=>h&&typeof h=="object"&&typeof h.name=="string"?Object.assign({},h,{name:se(h.name)}):h):n.source[l]=c[l];},data:async c=>{if(c==="!D%{}"){n.data={};return}if(c==="!L%[]"){n.data=[];return}if(c&&typeof c=="object"&&!Array.isArray(c)&&typeof c.__json__=="string"&&Object.keys(c).length===1)try{n.data=JSON.parse(c.__json__);return}catch{}if(c&&typeof c=="object"&&!Array.isArray(c)&&typeof c.__data__=="string"&&Object.keys(c).length===1&&c.__data__.endsWith("/__data__/__json__.json")){let l=c.__data__,d=s.find(h=>h.endsWith(l))||null;if(d){if(t){n.data=c;return}try{let h=await ke.bind(this)(d,{dataType:"blob",_ref:n.reference||null}),p=await pc(h);n.data=JSON.parse(p);}catch(h){console.error("Failed to fetch offloaded record data:",h),n.data=null;}return}}n.data=c;}};if(r.record_id)return r;if(Array.isArray(r.bin))for(let c of r.bin)try{if(typeof c!="string")continue;let l=c.split("/").slice(3);l.length>=12&&l[10]==="__data__"&&l[l.length-1]==="__json__.json"&&s.push(c);}catch{}let u=[];for(let c in a)if(r.hasOwnProperty(c)){let l=a[c](r[c]);l instanceof Promise&&u.push(l);}return i&&(n.user_id="anonymous:"+n.user_id),await Promise.all(u),n}function mc(r){let e=r.substring(3);switch(r.substring(0,3)){case "!S%":return e;case "!N%":let n=e.split("."),i=Number(n[0])-4503599627370496;return n.length===1?i:parseFloat(i.toString()+"."+n[1]);case "!B%":return e==="1";case "!L%":case "!D%":try{return JSON.parse(e)}catch{throw new f("Value parse error.",{code:"PARSE_ERROR"})}default:return r}}async function Fi(r){let{endpoints:e}=r;if(typeof e=="string"&&(e=[e]),!Array.isArray(e))throw new f('"endpoints" should be type: array | string.',{code:"INVALID_PARAMETER"});let t=await T.bind(this)("del-files",{endpoints:e,storage:"records"},{auth:true,method:"post"}),n=[];for(let i in t)n.push(ze.bind(this)(t[i]));return Promise.all(n)}async function ke(r,e){if(typeof r!="string")throw new f('"url" should be type: string.',{code:"INVALID_PARAMETER"});let t=r,n=r.split("?"),i=n.shift()||"",s=n.length?"?"+n.join("?"):"",o=m.Url(i);r=o+s;let a=false,u=o.split("/"),l=u[2].split("."),d=null;l.length===3&&l[1]==="skapi"&&(d=l[0],a=true);let h=u.slice(3),p=false;if(!a&&(h[0]==="auth"||h[0]==="publ"))try{m.UserId(h[2]),m.UserId(h[3]),p=h[0]=="auth",a=!0;}catch{throw new f("Invalid file url.",{code:"INVALID_PARAMETER"})}let g=d?null:h[1];if(e=m.Params(e,{expires:["number",()=>0],browserCache:["number",()=>0],refresh:["boolean",()=>false],dataType:["base64","blob","endpoint","text","info",()=>"download"],progress:["function","undefined",null],_ref:[null,"string"],_update:A=>A}),e?.dataType==="info")return {url:r,filename:h[h.length-1],fileKey:h[h.length-2],access_group:h[6]==="**"?"private":h[6]==="01"?"authorized":h[6]==="00"?"public":parseInt(h[6]),uploader:h[3],record_id:h[4]==="records"?h[5]:"N/A",filesize:ie(h[9]),uploaded:ie(h[8])};let _=r.split("/").slice(-1)[0],w=e.expires;if(w){if(!a)throw new f("Expires option can only be used on skapi cdn endpoints.",{code:"INVALID_PARAMETER"});if(w<0)throw new f('"config.expires" should be > 0. (seconds)',{code:"INVALID_PARAMETER"});let A={request:d?"get-host":"get",id:d||h[5],key:t.split("?")[0],expires:w};g&&(A.service=g);let x=e.browserCache,I={auth:true};if(x){if(x<0)throw new f('"config.browserCache" should be > 0. (seconds)',{code:"INVALID_PARAMETER"});I.method="get",I.stableGateway=true,A.browser_cache=x;let D=this.session?.idToken?.payload?.sub||this.user?.user_id;D&&(A.uid=D),A.nocache=hc(w,e.refresh);}r=(await T.bind(this)("get-signed-url",A,I)).url;}else if(p){let A=Math.floor(Date.now()/1e3);if(!this.bearerToken&&(!this.session?.idToken?.payload?.exp||this.session.idToken.payload.exp<A)){this.log("getFile:requesting new token",null);try{await G.bind(this)().getSession({refreshToken:!0}),this.log("getFile:received new tokens",{exp:this.session?.idToken?.payload?.exp,currTime:A,expiresIn:this.session?.idToken?.payload?.exp-A,token:this.session?.accessToken?.jwtToken,refreshToken:this.session?.refreshToken?.token});}catch(F){throw this.log("getFile:new token error",F),new f("User login is required.",{code:"INVALID_REQUEST"})}}let x=this.bearerToken||this.session?.idToken?.jwtToken;if(!x||!this.user?.user_id)throw new f("User login is required.",{code:"INVALID_REQUEST"});r+=`${r.includes("?")?"&":"?"}t=${encodeURIComponent(x)}`;let I=h[6]==="**"?"**":parseInt(h[6]),D=this.user?.access_group??-1;if(this.user.user_id!==h[3]&&(I==="**"||D<I)){let F=h[5];if(this.__private_access_key[F]&&typeof this.__private_access_key[F]=="string")r+=`&p=${encodeURIComponent(this.__private_access_key[F])}`;else if(this.owner!==this.host)try{let Q=await this.requestPrivateRecordAccessKey({record_id:F,reference_id:e?._ref});r+=`&p=${encodeURIComponent(Q)}`;}catch{}}}if(e?.dataType==="endpoint")return e._update&&(e._update.url=r),r;if(e?.dataType==="download"){let A=document.createElement("a");return A.href=r,document.body.appendChild(A),A.setAttribute("download",_),A.target="_blank",A.click(),document.body.removeChild(A),null}return new Promise(async(A,x)=>{try{let I=await T.bind(this)(r,null,{method:"get",contentType:null,responseType:e?.dataType==="text"?"text":"blob",fetchOptions:{progress:e?.progress}},{ignoreService:!0});if(e?.dataType==="base64"){let D=new FileReader;D.onloadend=()=>A(D.result),D.readAsDataURL(I);}else A(I);}catch(I){if(e?.browserCache&&!e?.refresh)try{A(await ke.bind(this)(t,Object.assign({},e,{refresh:!0})));return}catch(D){x(D);return}x(I);}})}function jt(r,e){return `${r||this.service}/${e||this.owner}`}function qr(r,e){let t=this.__my_unique_ids[r];return t?t[e]:void 0}function Oi(r,e,t){this.__my_unique_ids[r]||(this.__my_unique_ids[r]={}),this.__my_unique_ids[r][e]=t;}function _c(r,e){this.__my_unique_ids[r]&&delete this.__my_unique_ids[r][e];}async function Li(r,e=false){r=M(r,{ignoreEmpty:true}).data||{};let t=jt.bind(this)(r?.service,r?.owner),n="",i=Di(r);if(i){if(r=i,n=r.record_id||r.unique_id,typeof n=="string"){typeof this.__private_access_key?.[n]=="string"&&(r.private_key=this.__private_access_key?.[n]||void 0);let s=qr.bind(this)(t,n);s&&(e?_c.bind(this)(t,n):r.record_id=s);}}else {let s=await H.bind(this)(),o=r?.reference,a=false;typeof o=="object"&&Object.keys(o).length&&(o?.record_id||o?.unique_id?(n=o.record_id||o.unique_id,n&&typeof this.__private_access_key?.[n]=="string"&&(r.private_key=this.__private_access_key?.[n]||void 0),r.reference=n):o?.user_id&&(a=o.user_id===this.user?.user_id,r.reference=o.user_id)),typeof r?.table=="string"&&(r.table={name:r.table,access_group:0}),r.index&&r.index.hasOwnProperty("range")&&r.index.hasOwnProperty("condition")&&delete r.index.range;let u=c=>({table:{name:l=>Qe(l,"table.name"),access_group:Mr.bind(this),subscription:l=>m.UserId(l,'User ID in "subscription"')},reference:"string",index:{name:["$updated","$uploaded","$referenced_count","$user_id",l=>ot(l,"index.name")],value:l=>{let d={$updated:"number",$uploaded:"number",$referenced_count:"number",$user_id:m.UserId};if(d.hasOwnProperty(c.index.name)){let h=d[c.index.name];if(typeof h=="function")return h(l);if(h!==typeof l)throw new f(`"index.value" should be type: ${h}.`,{code:"INVALID_PARAMETER"});return l}return typeof l=="string"&&!l?"":typeof l=="string"&&Or(c.index.name)?Lr(l,"index.value"):Bt(l)},condition:["gt","gte","lt","lte",">",">=","<","<=","=","eq"],range:l=>ki(l,c)},tag:l=>{if(l==null)return l;if(typeof l=="string")return Vt(l,"tag");throw new f('"tag" should be type: string.',{code:"INVALID_PARAMETER"})},private_key:"string"});r=m.Params(r||{},u(r),a||s?[]:["table"],{ignoreEmpty:true});}return {query:r,is_reference_fetch:n}}async function Mi(r,e){await this.__connection;let t=await Li.bind(this)(r),n=t.is_reference_fetch,i=await T.bind(this)("get-records",t.query,{fetchOptions:e,auth:!!this.__user,method:this.__user?"post":"get"});n&&i?.reference_private_key&&typeof i.reference_private_key=="string"&&(this.__private_access_key[n]=i.reference_private_key);let s=[];for(let o in i.list)s.push(ze.bind(this)(i.list[o]));return i.list=await Promise.all(s),i}function qi(r){let e="",t=[],n=jt.bind(this)(r?.service,r?.owner),i=m.Params(r||{},{record_id:o=>{let a=typeof o=="string"?qr.bind(this)(n,o):void 0;return a||fe(o,"record_id",{allowEmpty:false})},unique_id:["string",null],readonly:"boolean",table:{name:o=>Qe(o,"table.name"),subscription:[null,{is_subscription_record:"boolean",upload_to_feed:"boolean",notify_subscribers:"boolean",feed_referencing_records:"boolean",notify_referencing_records:"boolean"}],access_group:Mr.bind(this)},source:{referencing_limit:o=>{if(o===null)return null;if(typeof o=="number"){if(0>o)throw new f('"reference_limit" should be >= 0',{code:"INVALID_PARAMETER"});if(o>4503599627370546)throw new f('"reference_limit" should be <= 4503599627370546',{code:"INVALID_PARAMETER"});return o}throw new f('"reference_limit" should be type: <number | null>',{code:"INVALID_PARAMETER"})},prevent_multiple_referencing:"boolean",can_remove_referencing_records:"boolean",only_granted_can_reference:"boolean",allow_granted_to_grant_others:"boolean",referencing_index_restrictions:o=>{if(o===void 0)return;if(!o||Array.isArray(o)&&!o.length)return null;let a={name:c=>ot(c,'"name" in "index_restrictions"'),value:c=>Bt(c),condition:["gt","gte","lt","lte",">",">=","<","<=","=","eq","!=","ne",()=>null],range:c=>{if(c!==null&&typeof o.value!=typeof c)throw new f('Index restriction "range" type should match the type of "value".',{code:"INVALID_PARAMETER"});if(!o.hasOwnProperty("value"))throw new f('Index restriction "value" is required.',{code:"INVALID_PARAMETER"});return c}};Array.isArray(o)||(o=[o]);let u=o.map(c=>m.Params(c,a,["name"]));if(u.length)for(let c of u)c.condition&&c.hasOwnProperty("range")&&delete c.range;return u}},reference:o=>{if(o===null)return {record_id:null};if(o){if(typeof o=="string"){e=o;let a=qr.bind(this)(n,o);return a||o}if(typeof o!="object")throw new f('"reference" should be type: <string | object>.',{code:"INVALID_PARAMETER"});return m.Params(o,{unique_id:"string",record_id:a=>a==null?a:(e=a,typeof this.__private_access_key?.[a]=="string"&&(r.reference_private_key=this.__private_access_key[a]||void 0),fe(a,"reference.record_id",{allowEmpty:false,onlyAlphanumeric:true}))})}},index:[null,{name:o=>ot(o,"index.name"),value:o=>Bt(o)}],tags:o=>{if(o==null)return o;if(typeof o=="string"&&(o=o.split(",").map(a=>a.trim())),!Array.isArray(o))throw new f('"tag" should be type: <string | string[]>.',{code:"INVALID_PARAMETER"});return o.map(a=>Vt(a,"tag"))},remove_bin:o=>{if(!o)return null;let a=[];if(Array.isArray(o))for(let u of o)if(typeof u=="string")a.push(u.split("?")[0]);else if(u.url&&u.size&&u.filename){let l=u.url.split("/").slice(0,3).join("/")+"/"+u.path;a.push(l);}else throw new f('"remove_bin" should be type: <string[] | BinaryFile[] | null>',{code:"INVALID_PARAMETER"});else throw new f('"remove_bin" should be type: <string[] | BinaryFile[] | null>',{code:"INVALID_PARAMETER"});return a},progress:"function",data:o=>o},[],{precall:o=>{let a=o?.data||{};if(!a?.record_id&&!a.table)throw new f('"table.name" is required.',{code:"INVALID_PARAMETER"});typeof a.table=="string"&&(a.table={name:a.table,access_group:0}),o.files&&(t=o.files);}}),s=r.progress||null;if(delete i.progress,!this.__user){let o=!!(i.table?.subscription?.is_subscription_record||i.table?.subscription?.upload_to_feed||i.table?.subscription?.notify_subscribers||i.table?.subscription?.feed_referencing_records||i.table?.subscription?.notify_referencing_records);if(i.record_id)throw new f("Public users cannot update existing records.",{code:"INVALID_REQUEST"});if(i.table.access_group!=="public"&&i.table.access_group!==0)throw new f("Public users can only post records to public tables.",{code:"INVALID_REQUEST"});if(o)throw new f("Public users cannot post subscription records.",{code:"INVALID_REQUEST"});if(i.remove_bin)throw new f("Public users cannot remove files from records.",{code:"INVALID_REQUEST"});if(i.unique_id)throw new f("Public users cannot set unique_id for records.",{code:"INVALID_REQUEST"})}return {config:i,progress:s,is_reference_post:e,files:t}}async function Vi(r){if(await this.__connection,!Array.isArray(r)||!r.length)throw new f('"params" should be a non-empty array.',{code:"INVALID_PARAMETER"});let e=[],t,n,i=null,o={_is_bulk_:r.map((h,p)=>{if(!h||typeof h!="object"||Array.isArray(h))throw new f(`"params[${p}]" should be type: <object>.`,{code:"INVALID_PARAMETER"});let g=qi.bind(this)(h),_=g.config;if(g.is_reference_post&&e.push(g.is_reference_post),typeof _.progress=="function"&&i===null&&(i=_.progress),_.service!==void 0){if(t===void 0)t=_.service;else if(t!==_.service)throw new f('All bulk params should share the same "service" value.',{code:"INVALID_PARAMETER"})}if(_.owner!==void 0){if(n===void 0)n=_.owner;else if(n!==_.owner)throw new f('All bulk params should share the same "owner" value.',{code:"INVALID_PARAMETER"})}return delete _.progress,delete _.service,delete _.owner,_}),service:"",owner:""};t!==void 0&&(o.service=t),n!==void 0&&(o.owner=n);let a={auth:!!this.__user,method:"post"},u={};Object.keys(u).length&&Object.assign(a,{fetchOptions:u});let c=await T.bind(this)("post-record",o,a),l=await Promise.all(c.map(h=>ze.bind(this)(h,"called from postRecord"))),d=jt.bind(this)(t,n);for(let h=0;h<c.length;h++){let p=c[h],g=l[h];if(p&&typeof p=="object"&&p.error&&g&&!g.record_id&&(g.error=p.error),typeof p?.reference_private_key=="string")for(let _ of e)this.__private_access_key[_]=p.reference_private_key;g?.unique_id&&Oi.bind(this)(d,g.unique_id,g.record_id);}return l}async function Bi(r,e,t){if(await this.__connection,!e)throw new f('"config" argument is required.',{code:"INVALID_PARAMETER"});let n=qi.bind(this)(e),i=n.config,s=n.progress,o=n.is_reference_post,a={auth:!!this.__user,method:"post"},u=[],c=M(r);t&&Array.isArray(t)&&t.length&&(u=u.concat(t)),c.files&&Array.isArray(c.files)&&c.files.length&&(u=u.concat(c.files));let l=null;l=Object.assign({data:c.data},i);let d={};typeof s=="function"&&(d.progress=s),Object.keys(d).length&&Object.assign(a,{fetchOptions:d});let h=await T.bind(this)("post-record",l,a);if(Y()&&u.length){let _=new FormData;for(let A of u)_.append(A.name,A.file,A.file.name);let w={record_id:h.rec,progress:s};i.hasOwnProperty("service")&&(w.service=i.service);let{bin_endpoints:b}=await Mt.bind(this)(_,w);h.bin?h.bin.push(...b):h.bin=b;}o&&typeof h?.reference_private_key=="string"&&(this.__private_access_key[o]=h.reference_private_key);let p=!!h&&h.data&&typeof h.data=="object"&&!Array.isArray(h.data)&&typeof h.data.__data__=="string"&&h.data.__data__.endsWith("/__data__/__json__.json"),g=await ze.bind(this)(h,"called from postRecord",true);if(p&&(g.data=c.data),g.unique_id){let _=jt.bind(this)(i?.service,i?.owner);Oi.bind(this)(_,g.unique_id,g.record_id),Y()&&(this.__uniqueIdsPersistTimer!==null&&clearTimeout(this.__uniqueIdsPersistTimer),this.__uniqueIdsPersistTimer=setTimeout(()=>{this.__uniqueIdsPersistTimer=null;try{window.sessionStorage.setItem(`${_}:uniqueids`,JSON.stringify(this.__my_unique_ids[_]||{}));}catch{}},500));}return g}async function $i(r,e){let t=await T.bind(this)("get-table",m.Params(r||{},{table:i=>Qe(i,"table",{allowEmpty:true}),condition:["gt","gte","lt","lte",">",">=","<","<=","=","eq","!=","ne"]}),Object.assign({auth:!!this.__user},{fetchOptions:e})),n={cnt_rec:"number_of_records",tbl:"table",srvc:"service",grp_:"number_of_records_in_access_group_"};if(Array.isArray(t?.list))for(let i of t.list){for(let s in n){if(s==="grp_"){for(let o in i)if(o.startsWith("grp_")){let a=o.substring(4);a==="pv"?a="private":a==="00"?a="public":a==="01"?a="authorized":a==="99"&&(a="admin"),i[`number_of_records_in_access_group_${a}`]=i[o],delete i[o];}}i.hasOwnProperty(s)&&(i[n[s]]=i[s],delete i[s]);}typeof i.table=="string"&&(i.table=se(i.table));}return t}async function ji(r,e){if(!r?.table)throw new f('"table" is required.',{code:"INVALID_PARAMETER"});let t=m.Params(r||{},{table:s=>Qe(s,"table",{allowEmpty:true}),index:s=>ot(s,"index.name"),order:{by:["average_number","total_number","number_count","average_bool","total_bool","bool_count","string_count","index_name","number_of_records"],value:s=>{if(r?.order?.by==="index_name"&&typeof s=="string")return fe(s,"order.value",{allowEmpty:true,maxLength:256,blockKeyDelimiters:true});if(typeof s!="string"&&typeof s!="number"&&typeof s!="boolean")throw new f('"order.value" should be type: <string | number | boolean>.',{code:"INVALID_PARAMETER"});return s},condition:["gt","gte","lt","lte",">",">=","<","<=","=","eq","!=","ne"]}},["table"]);if(t.hasOwnProperty("order")){if(!t.order?.by)throw new f('"order.by" is required.',{code:"INVALID_PARAMETER"});if(t.order.hasOwnProperty("condition")&&!t.order.hasOwnProperty("value"))throw new f('"value" is required for "condition".',{code:"INVALID_PARAMETER"});if(t.hasOwnProperty("index")&&t.index.substring(t.index.length-1)!==".")throw new f('"index" should be a parent index name of the compound index when using "order.by"',{code:"INVALID_PARAMETER"})}let n=await T.bind(this)("get-index",t,Object.assign({auth:!!this.__user},{fetchOptions:e})),i={cnt_bool:"boolean_count",cnt_numb:"number_count",totl_numb:"total_number",totl_bool:"total_bool",avrg_numb:"average_number",avrg_bool:"average_bool",cnt_str:"string_count"};return Array.isArray(n?.list)&&(n.list=n.list.map(s=>{let o=s.idx.split("/"),a={table:se(o[1]),index:se(o[2]),number_of_records:s.cnt_rec};for(let u in i)Object.prototype.hasOwnProperty.call(s,u)&&(a[i[u]]=s[u]);return a})),n}async function Ki(r,e){let t=await T.bind(this)("get-tag",m.Params(r||{},{table:n=>Qe(n,"table",{allowEmpty:true}),tag:n=>Vt(n,"tag",{allowEmpty:true}),condition:["gt","gte","lt","lte",">",">=","<","<=","=","eq","!=","ne"]}),Object.assign({auth:!!this.__user},{fetchOptions:e}));return Array.isArray(t?.list)&&(t.list=t.list.map(n=>{let i=n.tag.split("/");return {table:se(i[1]),tag:se(i[0]),number_of_records:n.cnt_rec}})),t}async function Hi(r,e){let t=await T.bind(this)("get-uniqueid",m.Params(r||{},{unique_id:"string",condition:["gt","gte","lt","lte",">",">=","<","<=","=","eq","!=","ne"]}),Object.assign({auth:!!this.__user},{fetchOptions:e}));if(Array.isArray(t?.list))for(let n in t.list){let i=t.list[n];t.list[n]={unique_id:i.unq,record_id:i.rec};}return t}async function Wi(r,e){await this.__connection;let t=await Li.bind(this)(r,true),n=t.is_reference_fetch,i=await T.bind(this)("del-records",t.query,{auth:true,fetchOptions:e});return n&&typeof i?.reference_private_key=="string"&&(this.__private_access_key[n]=i.reference_private_key),i?.message||i}function Ji(r){return Yi.bind(this)({record_id:r.record_id,user_id:r.user_id,execute:"add"})}function Gi(r){return Yi.bind(this)({record_id:r.record_id,user_id:r.user_id||null,execute:"remove"})}async function Qi(r,e){let t={record_id:r.record_id||void 0,user_id:r.user_id||void 0,execute:"list"};if(!t.record_id&&!t.user_id)throw new f("Either record_id or user_id must be provided.",{code:"INVALID_PARAMETER"});if(t.user_id)if(typeof t.user_id=="string")m.UserId(t.user_id),t.user_id=[t.user_id];else if(Array.isArray(t.user_id))for(let s of t.user_id)m.UserId(s);else throw new f("user_id should be type: <string | string[]>",{code:"INVALID_PARAMETER"});let n=s=>(s.rec_usr?(s.record_id=s.rec_usr.split("/")[0],s.user_id=s.rec_usr.split("/")[1]):s.usr_rec&&(s.user_id=s.usr_rec.split("/")[0],s.record_id=s.usr_rec.split("/")[1]),s),i=await T.bind(this)("grant-private-access",t,{auth:true,fetchOptions:e});return i.list=i.list.map(n),i}function zi(r){let e=r.record_id,t=r.reference_id||void 0;if(!e)throw new f("Record ID is required.",{code:"INVALID_PARAMETER"});if(typeof e!="string")throw new f("Record ID should be type: <string | string[]>",{code:"INVALID_PARAMETER"});if(t&&typeof t!="string")throw new f("Reference ID should be type: <string>",{code:"INVALID_PARAMETER"});if(typeof this.__private_access_key[e]=="string")return Promise.resolve(this.__private_access_key[e]);if($t[e])return $t[e];let n=T.bind(this)("request-private-access-key",{record_id:e,reference_id:t},{auth:true}).then(i=>{let s=typeof i=="string"?i:i?.private_key;if(typeof s!="string")throw new f("Invalid private access key response.",{code:"ERROR"});return this.__private_access_key[e]=s,s}).finally(()=>{delete $t[e];});return $t[e]=n,n}function Yi(r){r.execute;let t=m.Params(r,{record_id:"string",user_id:n=>{if(!n)throw new f("User ID is required.",{code:"INVALID_PARAMETER"});let i=n;if(typeof i=="string"&&(i=[i]),i.length>100)throw new f("Cannot process more than 100 users at once.",{code:"INVALID_REQUEST"});for(let s of i)m.UserId(s,'User ID in "user_id"');return i},execute:["add","remove"]},["execute","record_id","user_id"]);return t.user_id||(t.user_id=null),T.bind(this)("grant-private-access",t,{auth:true})}var U={},j={},oe={},ge={},he={},Kt={},Ht={};function Xi(r,e,t){r[e]||(r[e]=[]),r[e].push(t);}async function Wt(r,e,t){let n=[];if(r[e]){for(let i of r[e])if(i){let s=t(i);s instanceof Promise&&(s=await s),n.push(s);}delete r[e];}return n}async function Br(r,e){if(!this?.session?.accessToken?.jwtToken)throw new f("Access token is required.",{code:"INVALID_PARAMETER"});let t=await this.__socket;async function n(i,s,o){this.log("answerSdpOffer from",s),await U[s].setRemoteDescription(new RTCSessionDescription(i));let a=await U[s].createAnswer();await U[s].setLocalDescription(a),o.send(JSON.stringify({action:"rtc",uid:s,content:{sdpanswer:a},token:this.session.accessToken.jwtToken}));}U?.[e]?r?(await Wt(Ht,e,i=>n.bind(this)(i,e,t)),await n.bind(this)(r,e,t)):await Wt(Ht,e,i=>n.bind(this)(i,e,t)):r&&Xi(Ht,e,r);}async function $r(r,e){if(this.log("receiveIceCandidate",r),U?.[e]&&U[e]?.remoteDescription&&U[e]?.remoteDescription?.type){if(!r)return Wt(Kt,e,t=>U[e].addIceCandidate(t));await Wt(Kt,e,t=>U[e].addIceCandidate(t)),await U[e].addIceCandidate(r);}else Xi(Kt,e,r);}async function ae(r){if(typeof window>"u"||window._runningInNodeJS)throw new f("WebRTC is not supported in Node.js environment.",{code:"NOT_SUPPORTED"});m.Params(r,{cid:s=>{if(typeof s!="string")throw new f('"cid" should be type: <string>.',{code:"INVALID_PARAMETER"});if(s&&s.slice(0,4)!=="cid:")throw new f('"cid" should be a valid connection id.',{code:"INVALID_PARAMETER"});return s},close:"boolean"});let e=await this.__socket,{cid:t,close_all:n=false}=r||{};if(!n&&!t)throw new f('"cid" is required.',{code:"INVALID_PARAMETER"});let i=s=>{if(!s)throw new f('"cid" is required.',{code:"INVALID_PARAMETER"});if(delete Ht[s],delete Kt[s],j[s]&&Object.values(j[s]).forEach(o=>{o.readyState!=="closed"&&o.close();}),delete j[s],U?.[s]){U[s].connectionState!=="closed"&&(U[s].close(),e.send(JSON.stringify({action:"rtc",uid:s,content:{hungup:this.user.user_id},token:this.session.accessToken.jwtToken})));let o={type:"connectionstatechange",target:U[s],timestamp:new Date().toISOString(),state:U[s].connectionState,iceState:U[s].iceConnectionState,signalingState:U[s].signalingState};he[s]&&he[s](o),this.log("closeRTC",o);}delete he[s],delete ge[s],delete oe[s],delete U[s];};if(n)for(let s in U)i(s);else i(t);this.log("Cleaning up media stream..."),this.__mediaStream&&(this.__mediaStream.getTracks().forEach(s=>{s.stop();}),this.__mediaStream=null);}async function Zi(r){if(r instanceof MediaStream)return r;if(!r.video&&!r.audio){let e=new MediaStream,t=document.createElement("canvas");t.width=1,t.height=1;let i=t.captureStream().getVideoTracks()[0];return e.addTrack(i),e}return window.navigator.mediaDevices.getUserMedia(r)}async function es(r,e){if(typeof window>"u"||window._runningInNodeJS)throw new f("WebRTC is not supported in Node.js environment.",{code:"NOT_SUPPORTED"});if(typeof e!="function")throw new f("Callback is required.",{code:"INVALID_PARAMETER"});if(!this?.session?.accessToken?.jwtToken)throw new f("Access token is required.",{code:"INVALID_PARAMETER"});r=m.Params(r,{cid:o=>{if(typeof o!="string")throw new f('"cid" should be type: <string>.',{code:"INVALID_PARAMETER"});if(o&&o.slice(0,4)!=="cid:")throw new f('"cid" should be a valid connection id.',{code:"INVALID_PARAMETER"});return o},ice:["string",()=>"stun:stun.skapi.com:3468"],media:o=>o,channels:["text-chat","file-transfer","video-chat","voice-chat","gaming",{ordered:"boolean",maxPacketLifeTime:"number",maxRetransmits:"number",protocol:"string"},()=>[{ordered:true,maxPacketLifeTime:10,protocol:"default"}]]},["cid"]);let{cid:t,ice:n}=r;if(!(r?.media instanceof MediaStream)&&(r?.media?.video||r?.media?.audio)&&window.location.hostname!=="localhost"&&window.location.protocol!=="https:")throw new f("Media stream is only supported on either localhost or https.",{code:"INVALID_REQUEST"});let i=this.__socket?await this.__socket:this.__socket;if(!i)throw new f("No realtime connection. Execute connectRealtime() before this method.",{code:"INVALID_REQUEST"});if(i.readyState!==1)throw new f("Realtime connection is not ready.",{code:"INVALID_REQUEST"});let s={iceServers:[{urls:n}]};U?.[t]||(U[t]=new RTCPeerConnection(s)),r?.media&&(this.__mediaStream=await Zi(r.media),this.__mediaStream.getTracks().forEach(o=>{U[t].addTrack(o,this.__mediaStream);})),he[t]=e,j[t]||(j[t]={});for(let o=0;o<r.channels.length;o++){let a=r.channels[o];if(typeof a=="string")switch(a){case "text-chat":a={ordered:true,maxRetransmits:10,protocol:"text-chat"};break;case "file-transfer":a={ordered:false,maxPacketLifeTime:3e3,protocol:"file-transfer"};break;case "video-chat":a={ordered:true,maxRetransmits:10,protocol:"video-chat"};break;case "voice-chat":a={ordered:true,maxRetransmits:10,protocol:"voice-chat"};break;case "gaming":a={ordered:false,maxPacketLifeTime:100,protocol:"gaming"};break;default:a={ordered:true,maxRetransmits:10,protocol:"default"};break}let u=a.protocol||"default";if(Object.keys(j[t]).includes(u))throw new f(`Data channel with the protocol "${u}" already exists.`,{code:"INVALID_REQUEST"});let c=U[t].createDataChannel(u,a);j[t][u]=c;}for(let o in j[t]){let a=j[t][o];ns.bind(this)(t,a);}return rs.bind(this)(t,["onnegotiationneeded"]),await Vr.bind(this)(t),{hangup:()=>oe[t]&&oe[t](false),connection:new Promise(o=>{oe[t]=(a=>{if(this.log("receiver picked up the call",t),!a)return ae.bind(this)({cid:t}),null;U[t].onnegotiationneeded=()=>{this.log("onnegotiationneeded",`sending offer to "${t}".`),Vr.bind(this)(t),he[t]&&he[t]({type:"negotiationneeded",target:U[t],timestamp:new Date().toISOString(),signalingState:U[t].signalingState,connectionState:U[t].iceConnectionState,gatheringState:U[t].iceGatheringState});},o({target:U[t],channels:j[t],hangup:()=>ae.bind(this)({cid:t}),media:this.__mediaStream});}).bind(this);})}}function ts(r){return async(e,t)=>{e=e||{},e=M(e).data;let n=r.sender_cid,i=await this.__socket;if(!ge[n])return null;if(typeof t!="function")throw new f("Callback is required.",{code:"INVALID_PARAMETER"});if(!(e?.media instanceof MediaStream)&&(e?.media?.video||e?.media?.audio)&&window.location.hostname!=="localhost"&&window.location.protocol!=="https:")throw new f("Media stream is only supported on either localhost or https.",{code:"INVALID_REQUEST"});let{ice:s="stun:stun.skapi.com:3468"}=e;return U?.[n]||(U[n]=new RTCPeerConnection({iceServers:[{urls:s}]})),e?.media&&(this.__mediaStream=await Zi(e.media),this.__mediaStream.getTracks().forEach(o=>{U[n].addTrack(o,this.__mediaStream);})),delete ge[n],he[n]=t,j[n]||(j[n]={}),U[n].ondatachannel=o=>{this.log("ondatachannel",`received data channel "${o.channel.label}".`);let a=o.channel;j[n][a.label]=a,ns.bind(this)(n,a);},rs.bind(this)(n,["onnegotiationneeded"]),await Br.bind(this)(null,n),await $r.bind(this)(null,n),i.send(JSON.stringify({action:"rtc",uid:n,content:{pickup:this.user.user_id},token:this.session.accessToken.jwtToken})),{target:U[n],channels:j[n],hangup:()=>ae.bind(this)({cid:n}),media:this.__mediaStream}}}async function Vr(r){if(!this?.session?.accessToken?.jwtToken)throw new f("Access token is required.",{code:"INVALID_PARAMETER"});this.log("sendOffer",r);let e=await this.__socket,t=await U[r].createOffer();await U[r].setLocalDescription(t);let n=U[r].localDescription;this.log("rtcSdpOffer to",n),e.send(JSON.stringify({action:"rtc",uid:r,content:{sdpoffer:n},token:this.session.accessToken.jwtToken}));}async function bc(r,e){if(!this?.session?.accessToken?.jwtToken)throw new f("Access token is required.",{code:"INVALID_PARAMETER"});this.log("sendIceCandidate to",e);let t=await this.__socket;if(!r.candidate){this.log("candidate-end","all ice candidates have been sent");return}let n=he[e]||(()=>{}),i=r.candidate;this.log("ice gathering state set to",U[e].iceGatheringState),n({type:"icecandidate",target:U[e],timestamp:new Date().toISOString(),candidate:r.candidate.candidate,sdpMid:r.candidate.sdpMid,sdpMLineIndex:r.candidate.sdpMLineIndex,usernameFragment:r.candidate.usernameFragment,protocol:r.candidate.protocol,gatheringState:U[e].iceGatheringState,connectionState:U[e].iceConnectionState}),t.send(JSON.stringify({action:"rtc",uid:e,content:{candidate:i},token:this.session.accessToken.jwtToken}));}function rs(r,e){let t=new Set(e),n=he[r]||(o=>{}),i=U[r],s={ontrack:o=>{n({type:"track",target:i,timeStamp:o.timeStamp,streams:o.streams,track:o.track});},onicecandidate:o=>{bc.bind(this)(o,r),o.candidate?n({type:"icecandidate",target:i,timestamp:new Date().toISOString(),candidate:o.candidate.candidate,sdpMid:o.candidate.sdpMid,sdpMLineIndex:o.candidate.sdpMLineIndex,usernameFragment:o.candidate.usernameFragment,protocol:o.candidate.protocol,gatheringState:i.iceGatheringState,connectionState:i.iceConnectionState}):n({type:"icecandidateend",target:i,timestamp:new Date().toISOString()});},onicecandidateerror:o=>{n({type:"icecandidateerror",target:i,timestamp:new Date().toISOString(),errorCode:o.errorCode,errorText:o.errorText,url:o.url,hostCandidate:o.hostCandidate,gatheringState:i.iceGatheringState,connectionState:i.iceConnectionState});},oniceconnectionstatechange:()=>{n({type:"iceconnectionstatechange",target:i,timestamp:new Date().toISOString(),state:i.iceConnectionState,gatheringState:i.iceGatheringState,signalingState:i.signalingState});},onicegatheringstatechange:()=>{n({type:"icegatheringstatechange",target:i,timestamp:new Date().toISOString(),state:i.iceGatheringState,connectionState:i.iceConnectionState,signalingState:i.signalingState});},onsignalingstatechange:()=>{n({type:"signalingstatechange",target:i,timestamp:new Date().toISOString(),state:i.signalingState,connectionState:i.iceConnectionState,gatheringState:i.iceGatheringState});},onnegotiationneeded:()=>{Vr.bind(this)(r),n({type:"negotiationneeded",target:i,timestamp:new Date().toISOString(),signalingState:i.signalingState,connectionState:i.iceConnectionState,gatheringState:i.iceGatheringState});},onconnectionstatechange:()=>{n({type:"connectionstatechange",target:i,timestamp:new Date().toISOString(),state:i.connectionState,iceState:i.iceConnectionState,signalingState:i.signalingState});let o=i.connectionState;(o==="disconnected"||o==="failed"||o==="closed")&&ae.bind(this)({cid:r});}};for(let[o,a]of Object.entries(s))t.has(o)||(i[o]=a);}function ns(r,e,t){let n=new Set(t),i=he[r]||(o=>{}),s={onmessage:o=>{let a={type:o.type,target:e,timeStamp:o.timeStamp,data:o.data,lastEventId:o.lastEventId,origin:o.origin,readyState:e.readyState,bufferedAmount:e.bufferedAmount};this.log(`${e.label}: message`,o.data),i(a);},onerror:o=>{let a={type:o.type,target:e,timeStamp:o.timeStamp,error:o.error.message,errorCode:o.error.errorDetail,readyState:e.readyState,label:e.label};this.log(`${e.label}: error`,o.error.message),i(a);},onclose:o=>{let a={type:o.type,target:e,timeStamp:o.timeStamp,readyState:e.readyState,label:e.label,id:e.id};this.log(`${e.label}: closed`,null),i(a),j[r]&&(delete j[r][e.label],Object.keys(j[r]).length===0&&ae.bind(this)({cid:r}));},onbufferedamountlow:o=>{let a={target:e,bufferedAmount:e.bufferedAmount,bufferedAmountLowThreshold:e.bufferedAmountLowThreshold,type:o.type,timeStamp:o.timeStamp};this.log(`${e.label}: bufferedamountlow`,e.bufferedAmount),i(a);},onopen:o=>{this.log("dataChannel",`data channel: "${e.label}" is open and ready to send messages.`);let a={type:o.type,target:e,timeStamp:o.timeStamp,readyState:e.readyState,label:e.label,id:e.id,ordered:e.ordered,maxRetransmits:e.maxRetransmits,protocol:e.protocol};i(a);}};for(let[o,a]of Object.entries(s))n.has(o)||(e[o]=a);}var Re,Te=null,at=true,Ye=0;async function yc(){if(typeof window>"u"||window._runningInNodeJS)throw new f("WebSocket is not supported in Node.js environment.",{code:"NOT_SUPPORTED"});if(await this.getProfile(),!this.session)throw new f("No access.",{code:"INVALID_REQUEST"});let r=await this.record_endpoint;return new WebSocket(r.websocket_private+"?token="+this.session.accessToken.jwtToken)}var jr=null;async function is(){if(typeof window>"u"||window._runningInNodeJS)throw new f("WebSocket is not supported in Node.js environment.",{code:"NOT_SUPPORTED"});at=true;let r=this.__socket?await this.__socket:this.__socket;ae.bind(this)({close_all:true}),Re&&Kr.bind(this)({group:null}),Ye=0,Te&&(Te.terminate(),Te=null);try{r&&r.close();}catch{}return window.removeEventListener("visibilitychange",jr),this.__socket=null,null}async function Jt(r,e=50,t){if(typeof window>"u"||window._runningInNodeJS)throw new f("WebSocket is not supported in Node.js environment.",{code:"NOT_SUPPORTED"});if(typeof r!="function")throw new f("Callback must be a function.",{code:"INVALID_REQUEST"});if(t==="reconnect"){if(this.__socket instanceof Promise){let n=await this.__socket;if(n.readyState!==WebSocket.CLOSED&&n.readyState!==WebSocket.CLOSING)return this.__socket}}else if(at&&(jr=()=>{!document.hidden&&!at&&Jt.bind(this)(r,0,"reconnect");},this.__socket instanceof Promise))return this.__socket;Te&&(Te.terminate(),Te=null),this.__socket=new Promise(async n=>{await Je.bind(this)(),setTimeout(async()=>{let i=await yc.bind(this)();i.onopen=()=>{at=false,Ye=0,t!=="reconnect"&&window.addEventListener("visibilitychange",jr),this.log("realtime onopen","Connected to WebSocket server."),r({type:"success",message:"Connected to WebSocket server."}),Re&&i.send(JSON.stringify({action:"joinRoom",rid:Re,token:this.session.accessToken.jwtToken}));let s=`
206
+ var sc=Object.create;var ze=Object.defineProperty;var ii=Object.getOwnPropertyDescriptor;var oc=Object.getOwnPropertyNames;var ac=Object.getPrototypeOf,cc=Object.prototype.hasOwnProperty;var uc=(t,e,r)=>e in t?ze(t,e,{enumerable:true,configurable:true,writable:true,value:r}):t[e]=r;var yt=(t=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(t,{get:(e,r)=>(typeof require<"u"?require:e)[r]}):t)(function(t){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+t+'" is not supported')});var Qe=(t,e)=>()=>(t&&(e=t(t=0)),e);var ee=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),Bt=(t,e)=>{for(var r in e)ze(t,r,{get:e[r],enumerable:true});},si=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of oc(e))!cc.call(t,i)&&i!==r&&ze(t,i,{get:()=>e[i],enumerable:!(n=ii(e,i))||n.enumerable});return t};var Xe=(t,e,r)=>(r=t!=null?sc(ac(t)):{},si(!t||!t.__esModule?ze(r,"default",{value:t,enumerable:true}):r,t)),oe=t=>si(ze({},"__esModule",{value:true}),t),R=(t,e,r,n)=>{for(var i=ii(e,r),s=t.length-1,o;s>=0;s--)(o=t[s])&&(i=(o(e,r,i))||i);return i&&ze(e,r,i),i};var we=(t,e,r)=>uc(t,typeof e!="symbol"?e+"":e,r);var Fe={};Bt(Fe,{default:()=>dc});var lc,dc,Le=Qe(()=>{lc={},dc=lc;});var ci=ee(Kt=>{Kt.byteLength=gc;Kt.toByteArray=mc;Kt.fromByteArray=bc;var Ee=[],ae=[],hc=typeof Uint8Array<"u"?Uint8Array:Array,Nr="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";for(Ke=0,oi=Nr.length;Ke<oi;++Ke)Ee[Ke]=Nr[Ke],ae[Nr.charCodeAt(Ke)]=Ke;var Ke,oi;ae[45]=62;ae[95]=63;function ai(t){var e=t.length;if(e%4>0)throw new Error("Invalid string. Length must be a multiple of 4");var r=t.indexOf("=");r===-1&&(r=e);var n=r===e?0:4-r%4;return [r,n]}function gc(t){var e=ai(t),r=e[0],n=e[1];return (r+n)*3/4-n}function pc(t,e,r){return (e+r)*3/4-r}function mc(t){var e,r=ai(t),n=r[0],i=r[1],s=new hc(pc(t,n,i)),o=0,a=i>0?n-4:n,c;for(c=0;c<a;c+=4)e=ae[t.charCodeAt(c)]<<18|ae[t.charCodeAt(c+1)]<<12|ae[t.charCodeAt(c+2)]<<6|ae[t.charCodeAt(c+3)],s[o++]=e>>16&255,s[o++]=e>>8&255,s[o++]=e&255;return i===2&&(e=ae[t.charCodeAt(c)]<<2|ae[t.charCodeAt(c+1)]>>4,s[o++]=e&255),i===1&&(e=ae[t.charCodeAt(c)]<<10|ae[t.charCodeAt(c+1)]<<4|ae[t.charCodeAt(c+2)]>>2,s[o++]=e>>8&255,s[o++]=e&255),s}function yc(t){return Ee[t>>18&63]+Ee[t>>12&63]+Ee[t>>6&63]+Ee[t&63]}function _c(t,e,r){for(var n,i=[],s=e;s<r;s+=3)n=(t[s]<<16&16711680)+(t[s+1]<<8&65280)+(t[s+2]&255),i.push(yc(n));return i.join("")}function bc(t){for(var e,r=t.length,n=r%3,i=[],s=16383,o=0,a=r-n;o<a;o+=s)i.push(_c(t,o,o+s>a?a:o+s));return n===1?(e=t[r-1],i.push(Ee[e>>2]+Ee[e<<4&63]+"==")):n===2&&(e=(t[r-2]<<8)+t[r-1],i.push(Ee[e>>10]+Ee[e>>4&63]+Ee[e<<2&63]+"=")),i.join("")}});var ui=ee(Or=>{Or.read=function(t,e,r,n,i){var s,o,a=i*8-n-1,c=(1<<a)-1,u=c>>1,l=-7,d=r?i-1:0,h=r?-1:1,p=t[e+d];for(d+=h,s=p&(1<<-l)-1,p>>=-l,l+=a;l>0;s=s*256+t[e+d],d+=h,l-=8);for(o=s&(1<<-l)-1,s>>=-l,l+=n;l>0;o=o*256+t[e+d],d+=h,l-=8);if(s===0)s=1-u;else {if(s===c)return o?NaN:(p?-1:1)*(1/0);o=o+Math.pow(2,n),s=s-u;}return (p?-1:1)*o*Math.pow(2,s-n)};Or.write=function(t,e,r,n,i,s){var o,a,c,u=s*8-i-1,l=(1<<u)-1,d=l>>1,h=i===23?Math.pow(2,-24)-Math.pow(2,-77):0,p=n?0:s-1,g=n?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=l):(o=Math.floor(Math.log(e)/Math.LN2),e*(c=Math.pow(2,-o))<1&&(o--,c*=2),o+d>=1?e+=h/c:e+=h*Math.pow(2,1-d),e*c>=2&&(o++,c/=2),o+d>=l?(a=0,o=l):o+d>=1?(a=(e*c-1)*Math.pow(2,i),o=o+d):(a=e*Math.pow(2,d-1)*Math.pow(2,i),o=0));i>=8;t[r+p]=a&255,p+=g,a/=256,i-=8);for(o=o<<i|a,u+=i;u>0;t[r+p]=o&255,p+=g,o/=256,u-=8);t[r+p-g]|=m*128;};});var di=ee((Yd,li)=>{var wc={}.toString;li.exports=Array.isArray||function(t){return wc.call(t)=="[object Array]"};});var Yt=ee(et=>{var Fr=ci(),Ze=ui(),gi=di();et.Buffer=w;et.SlowBuffer=Tc;et.INSPECT_MAX_BYTES=50;w.TYPED_ARRAY_SUPPORT=globalThis.TYPED_ARRAY_SUPPORT!==void 0?globalThis.TYPED_ARRAY_SUPPORT:Ec();et.kMaxLength=jt();function Ec(){try{var t=new Uint8Array(1);return t.__proto__={__proto__:Uint8Array.prototype,foo:function(){return 42}},t.foo()===42&&typeof t.subarray=="function"&&t.subarray(1,1).byteLength===0}catch{return false}}function jt(){return w.TYPED_ARRAY_SUPPORT?2147483647:1073741823}function Ce(t,e){if(jt()<e)throw new RangeError("Invalid typed array length");return w.TYPED_ARRAY_SUPPORT?(t=new Uint8Array(e),t.__proto__=w.prototype):(t===null&&(t=new w(e)),t.length=e),t}function w(t,e,r){if(!w.TYPED_ARRAY_SUPPORT&&!(this instanceof w))return new w(t,e,r);if(typeof t=="number"){if(typeof e=="string")throw new Error("If encoding is specified then the first argument must be a string");return Mr(this,t)}return pi(this,t,e,r)}w.poolSize=8192;w._augment=function(t){return t.__proto__=w.prototype,t};function pi(t,e,r,n){if(typeof e=="number")throw new TypeError('"value" argument must not be a number');return typeof ArrayBuffer<"u"&&e instanceof ArrayBuffer?vc(t,e,r,n):typeof e=="string"?Sc(t,e,r):Rc(t,e)}w.from=function(t,e,r){return pi(null,t,e,r)};w.TYPED_ARRAY_SUPPORT&&(w.prototype.__proto__=Uint8Array.prototype,w.__proto__=Uint8Array,typeof Symbol<"u"&&Symbol.species&&w[Symbol.species]===w&&Object.defineProperty(w,Symbol.species,{value:null,configurable:true}));function mi(t){if(typeof t!="number")throw new TypeError('"size" argument must be a number');if(t<0)throw new RangeError('"size" argument must not be negative')}function Ac(t,e,r,n){return mi(e),e<=0?Ce(t,e):r!==void 0?typeof n=="string"?Ce(t,e).fill(r,n):Ce(t,e).fill(r):Ce(t,e)}w.alloc=function(t,e,r){return Ac(null,t,e,r)};function Mr(t,e){if(mi(e),t=Ce(t,e<0?0:Vr(e)|0),!w.TYPED_ARRAY_SUPPORT)for(var r=0;r<e;++r)t[r]=0;return t}w.allocUnsafe=function(t){return Mr(null,t)};w.allocUnsafeSlow=function(t){return Mr(null,t)};function Sc(t,e,r){if((typeof r!="string"||r==="")&&(r="utf8"),!w.isEncoding(r))throw new TypeError('"encoding" must be a valid string encoding');var n=yi(e,r)|0;t=Ce(t,n);var i=t.write(e,r);return i!==n&&(t=t.slice(0,i)),t}function Lr(t,e){var r=e.length<0?0:Vr(e.length)|0;t=Ce(t,r);for(var n=0;n<r;n+=1)t[n]=e[n]&255;return t}function vc(t,e,r,n){if(e.byteLength,r<0||e.byteLength<r)throw new RangeError("'offset' is out of bounds");if(e.byteLength<r+(n||0))throw new RangeError("'length' is out of bounds");return r===void 0&&n===void 0?e=new Uint8Array(e):n===void 0?e=new Uint8Array(e,r):e=new Uint8Array(e,r,n),w.TYPED_ARRAY_SUPPORT?(t=e,t.__proto__=w.prototype):t=Lr(t,e),t}function Rc(t,e){if(w.isBuffer(e)){var r=Vr(e.length)|0;return t=Ce(t,r),t.length===0||e.copy(t,0,0,r),t}if(e){if(typeof ArrayBuffer<"u"&&e.buffer instanceof ArrayBuffer||"length"in e)return typeof e.length!="number"||Hc(e.length)?Ce(t,0):Lr(t,e);if(e.type==="Buffer"&&gi(e.data))return Lr(t,e.data)}throw new TypeError("First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.")}function Vr(t){if(t>=jt())throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+jt().toString(16)+" bytes");return t|0}function Tc(t){return +t!=t&&(t=0),w.alloc(+t)}w.isBuffer=function(e){return !!(e!=null&&e._isBuffer)};w.compare=function(e,r){if(!w.isBuffer(e)||!w.isBuffer(r))throw new TypeError("Arguments must be Buffers");if(e===r)return 0;for(var n=e.length,i=r.length,s=0,o=Math.min(n,i);s<o;++s)if(e[s]!==r[s]){n=e[s],i=r[s];break}return n<i?-1:i<n?1:0};w.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 true;default:return false}};w.concat=function(e,r){if(!gi(e))throw new TypeError('"list" argument must be an Array of Buffers');if(e.length===0)return w.alloc(0);var n;if(r===void 0)for(r=0,n=0;n<e.length;++n)r+=e[n].length;var i=w.allocUnsafe(r),s=0;for(n=0;n<e.length;++n){var o=e[n];if(!w.isBuffer(o))throw new TypeError('"list" argument must be an Array of Buffers');o.copy(i,s),s+=o.length;}return i};function yi(t,e){if(w.isBuffer(t))return t.length;if(typeof ArrayBuffer<"u"&&typeof ArrayBuffer.isView=="function"&&(ArrayBuffer.isView(t)||t instanceof ArrayBuffer))return t.byteLength;typeof t!="string"&&(t=""+t);var r=t.length;if(r===0)return 0;for(var n=false;;)switch(e){case "ascii":case "latin1":case "binary":return r;case "utf8":case "utf-8":case void 0:return Ht(t).length;case "ucs2":case "ucs-2":case "utf16le":case "utf-16le":return r*2;case "hex":return r>>>1;case "base64":return vi(t).length;default:if(n)return Ht(t).length;e=(""+e).toLowerCase(),n=true;}}w.byteLength=yi;function Ic(t,e,r){var n=false;if((e===void 0||e<0)&&(e=0),e>this.length||((r===void 0||r>this.length)&&(r=this.length),r<=0)||(r>>>=0,e>>>=0,r<=e))return "";for(t||(t="utf8");;)switch(t){case "hex":return Lc(this,e,r);case "utf8":case "utf-8":return wi(this,e,r);case "ascii":return Oc(this,e,r);case "latin1":case "binary":return Fc(this,e,r);case "base64":return kc(this,e,r);case "ucs2":case "ucs-2":case "utf16le":case "utf-16le":return Mc(this,e,r);default:if(n)throw new TypeError("Unknown encoding: "+t);t=(t+"").toLowerCase(),n=true;}}w.prototype._isBuffer=true;function je(t,e,r){var n=t[e];t[e]=t[r],t[r]=n;}w.prototype.swap16=function(){var e=this.length;if(e%2!==0)throw new RangeError("Buffer size must be a multiple of 16-bits");for(var r=0;r<e;r+=2)je(this,r,r+1);return this};w.prototype.swap32=function(){var e=this.length;if(e%4!==0)throw new RangeError("Buffer size must be a multiple of 32-bits");for(var r=0;r<e;r+=4)je(this,r,r+3),je(this,r+1,r+2);return this};w.prototype.swap64=function(){var e=this.length;if(e%8!==0)throw new RangeError("Buffer size must be a multiple of 64-bits");for(var r=0;r<e;r+=8)je(this,r,r+7),je(this,r+1,r+6),je(this,r+2,r+5),je(this,r+3,r+4);return this};w.prototype.toString=function(){var e=this.length|0;return e===0?"":arguments.length===0?wi(this,0,e):Ic.apply(this,arguments)};w.prototype.equals=function(e){if(!w.isBuffer(e))throw new TypeError("Argument must be a Buffer");return this===e?true:w.compare(this,e)===0};w.prototype.inspect=function(){var e="",r=et.INSPECT_MAX_BYTES;return this.length>0&&(e=this.toString("hex",0,r).match(/.{2}/g).join(" "),this.length>r&&(e+=" ... ")),"<Buffer "+e+">"};w.prototype.compare=function(e,r,n,i,s){if(!w.isBuffer(e))throw new TypeError("Argument must be a Buffer");if(r===void 0&&(r=0),n===void 0&&(n=e?e.length:0),i===void 0&&(i=0),s===void 0&&(s=this.length),r<0||n>e.length||i<0||s>this.length)throw new RangeError("out of range index");if(i>=s&&r>=n)return 0;if(i>=s)return -1;if(r>=n)return 1;if(r>>>=0,n>>>=0,i>>>=0,s>>>=0,this===e)return 0;for(var o=s-i,a=n-r,c=Math.min(o,a),u=this.slice(i,s),l=e.slice(r,n),d=0;d<c;++d)if(u[d]!==l[d]){o=u[d],a=l[d];break}return o<a?-1:a<o?1:0};function _i(t,e,r,n,i){if(t.length===0)return -1;if(typeof r=="string"?(n=r,r=0):r>2147483647?r=2147483647:r<-2147483648&&(r=-2147483648),r=+r,isNaN(r)&&(r=i?0:t.length-1),r<0&&(r=t.length+r),r>=t.length){if(i)return -1;r=t.length-1;}else if(r<0)if(i)r=0;else return -1;if(typeof e=="string"&&(e=w.from(e,n)),w.isBuffer(e))return e.length===0?-1:fi(t,e,r,n,i);if(typeof e=="number")return e=e&255,w.TYPED_ARRAY_SUPPORT&&typeof Uint8Array.prototype.indexOf=="function"?i?Uint8Array.prototype.indexOf.call(t,e,r):Uint8Array.prototype.lastIndexOf.call(t,e,r):fi(t,[e],r,n,i);throw new TypeError("val must be string, number or Buffer")}function fi(t,e,r,n,i){var s=1,o=t.length,a=e.length;if(n!==void 0&&(n=String(n).toLowerCase(),n==="ucs2"||n==="ucs-2"||n==="utf16le"||n==="utf-16le")){if(t.length<2||e.length<2)return -1;s=2,o/=2,a/=2,r/=2;}function c(p,g){return s===1?p[g]:p.readUInt16BE(g*s)}var u;if(i){var l=-1;for(u=r;u<o;u++)if(c(t,u)===c(e,l===-1?0:u-l)){if(l===-1&&(l=u),u-l+1===a)return l*s}else l!==-1&&(u-=u-l),l=-1;}else for(r+a>o&&(r=o-a),u=r;u>=0;u--){for(var d=true,h=0;h<a;h++)if(c(t,u+h)!==c(e,h)){d=false;break}if(d)return u}return -1}w.prototype.includes=function(e,r,n){return this.indexOf(e,r,n)!==-1};w.prototype.indexOf=function(e,r,n){return _i(this,e,r,n,true)};w.prototype.lastIndexOf=function(e,r,n){return _i(this,e,r,n,false)};function Pc(t,e,r,n){r=Number(r)||0;var i=t.length-r;n?(n=Number(n),n>i&&(n=i)):n=i;var s=e.length;if(s%2!==0)throw new TypeError("Invalid hex string");n>s/2&&(n=s/2);for(var o=0;o<n;++o){var a=parseInt(e.substr(o*2,2),16);if(isNaN(a))return o;t[r+o]=a;}return o}function Uc(t,e,r,n){return Jt(Ht(e,t.length-r),t,r,n)}function bi(t,e,r,n){return Jt(Kc(e),t,r,n)}function xc(t,e,r,n){return bi(t,e,r,n)}function Cc(t,e,r,n){return Jt(vi(e),t,r,n)}function Dc(t,e,r,n){return Jt(jc(e,t.length-r),t,r,n)}w.prototype.write=function(e,r,n,i){if(r===void 0)i="utf8",n=this.length,r=0;else if(n===void 0&&typeof r=="string")i=r,n=this.length,r=0;else if(isFinite(r))r=r|0,isFinite(n)?(n=n|0,i===void 0&&(i="utf8")):(i=n,n=void 0);else throw new Error("Buffer.write(string, encoding, offset[, length]) is no longer supported");var s=this.length-r;if((n===void 0||n>s)&&(n=s),e.length>0&&(n<0||r<0)||r>this.length)throw new RangeError("Attempt to write outside buffer bounds");i||(i="utf8");for(var o=false;;)switch(i){case "hex":return Pc(this,e,r,n);case "utf8":case "utf-8":return Uc(this,e,r,n);case "ascii":return bi(this,e,r,n);case "latin1":case "binary":return xc(this,e,r,n);case "base64":return Cc(this,e,r,n);case "ucs2":case "ucs-2":case "utf16le":case "utf-16le":return Dc(this,e,r,n);default:if(o)throw new TypeError("Unknown encoding: "+i);i=(""+i).toLowerCase(),o=true;}};w.prototype.toJSON=function(){return {type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};function kc(t,e,r){return e===0&&r===t.length?Fr.fromByteArray(t):Fr.fromByteArray(t.slice(e,r))}function wi(t,e,r){r=Math.min(t.length,r);for(var n=[],i=e;i<r;){var s=t[i],o=null,a=s>239?4:s>223?3:s>191?2:1;if(i+a<=r){var c,u,l,d;switch(a){case 1:s<128&&(o=s);break;case 2:c=t[i+1],(c&192)===128&&(d=(s&31)<<6|c&63,d>127&&(o=d));break;case 3:c=t[i+1],u=t[i+2],(c&192)===128&&(u&192)===128&&(d=(s&15)<<12|(c&63)<<6|u&63,d>2047&&(d<55296||d>57343)&&(o=d));break;case 4:c=t[i+1],u=t[i+2],l=t[i+3],(c&192)===128&&(u&192)===128&&(l&192)===128&&(d=(s&15)<<18|(c&63)<<12|(u&63)<<6|l&63,d>65535&&d<1114112&&(o=d));}}o===null?(o=65533,a=1):o>65535&&(o-=65536,n.push(o>>>10&1023|55296),o=56320|o&1023),n.push(o),i+=a;}return Nc(n)}var hi=4096;function Nc(t){var e=t.length;if(e<=hi)return String.fromCharCode.apply(String,t);for(var r="",n=0;n<e;)r+=String.fromCharCode.apply(String,t.slice(n,n+=hi));return r}function Oc(t,e,r){var n="";r=Math.min(t.length,r);for(var i=e;i<r;++i)n+=String.fromCharCode(t[i]&127);return n}function Fc(t,e,r){var n="";r=Math.min(t.length,r);for(var i=e;i<r;++i)n+=String.fromCharCode(t[i]);return n}function Lc(t,e,r){var n=t.length;(!e||e<0)&&(e=0),(!r||r<0||r>n)&&(r=n);for(var i="",s=e;s<r;++s)i+=$c(t[s]);return i}function Mc(t,e,r){for(var n=t.slice(e,r),i="",s=0;s<n.length;s+=2)i+=String.fromCharCode(n[s]+n[s+1]*256);return i}w.prototype.slice=function(e,r){var n=this.length;e=~~e,r=r===void 0?n:~~r,e<0?(e+=n,e<0&&(e=0)):e>n&&(e=n),r<0?(r+=n,r<0&&(r=0)):r>n&&(r=n),r<e&&(r=e);var i;if(w.TYPED_ARRAY_SUPPORT)i=this.subarray(e,r),i.__proto__=w.prototype;else {var s=r-e;i=new w(s,void 0);for(var o=0;o<s;++o)i[o]=this[o+e];}return i};function G(t,e,r){if(t%1!==0||t<0)throw new RangeError("offset is not uint");if(t+e>r)throw new RangeError("Trying to access beyond buffer length")}w.prototype.readUIntLE=function(e,r,n){e=e|0,r=r|0,n||G(e,r,this.length);for(var i=this[e],s=1,o=0;++o<r&&(s*=256);)i+=this[e+o]*s;return i};w.prototype.readUIntBE=function(e,r,n){e=e|0,r=r|0,n||G(e,r,this.length);for(var i=this[e+--r],s=1;r>0&&(s*=256);)i+=this[e+--r]*s;return i};w.prototype.readUInt8=function(e,r){return r||G(e,1,this.length),this[e]};w.prototype.readUInt16LE=function(e,r){return r||G(e,2,this.length),this[e]|this[e+1]<<8};w.prototype.readUInt16BE=function(e,r){return r||G(e,2,this.length),this[e]<<8|this[e+1]};w.prototype.readUInt32LE=function(e,r){return r||G(e,4,this.length),(this[e]|this[e+1]<<8|this[e+2]<<16)+this[e+3]*16777216};w.prototype.readUInt32BE=function(e,r){return r||G(e,4,this.length),this[e]*16777216+(this[e+1]<<16|this[e+2]<<8|this[e+3])};w.prototype.readIntLE=function(e,r,n){e=e|0,r=r|0,n||G(e,r,this.length);for(var i=this[e],s=1,o=0;++o<r&&(s*=256);)i+=this[e+o]*s;return s*=128,i>=s&&(i-=Math.pow(2,8*r)),i};w.prototype.readIntBE=function(e,r,n){e=e|0,r=r|0,n||G(e,r,this.length);for(var i=r,s=1,o=this[e+--i];i>0&&(s*=256);)o+=this[e+--i]*s;return s*=128,o>=s&&(o-=Math.pow(2,8*r)),o};w.prototype.readInt8=function(e,r){return r||G(e,1,this.length),this[e]&128?(255-this[e]+1)*-1:this[e]};w.prototype.readInt16LE=function(e,r){r||G(e,2,this.length);var n=this[e]|this[e+1]<<8;return n&32768?n|4294901760:n};w.prototype.readInt16BE=function(e,r){r||G(e,2,this.length);var n=this[e+1]|this[e]<<8;return n&32768?n|4294901760:n};w.prototype.readInt32LE=function(e,r){return r||G(e,4,this.length),this[e]|this[e+1]<<8|this[e+2]<<16|this[e+3]<<24};w.prototype.readInt32BE=function(e,r){return r||G(e,4,this.length),this[e]<<24|this[e+1]<<16|this[e+2]<<8|this[e+3]};w.prototype.readFloatLE=function(e,r){return r||G(e,4,this.length),Ze.read(this,e,true,23,4)};w.prototype.readFloatBE=function(e,r){return r||G(e,4,this.length),Ze.read(this,e,false,23,4)};w.prototype.readDoubleLE=function(e,r){return r||G(e,8,this.length),Ze.read(this,e,true,52,8)};w.prototype.readDoubleBE=function(e,r){return r||G(e,8,this.length),Ze.read(this,e,false,52,8)};function te(t,e,r,n,i,s){if(!w.isBuffer(t))throw new TypeError('"buffer" argument must be a Buffer instance');if(e>i||e<s)throw new RangeError('"value" argument is out of bounds');if(r+n>t.length)throw new RangeError("Index out of range")}w.prototype.writeUIntLE=function(e,r,n,i){if(e=+e,r=r|0,n=n|0,!i){var s=Math.pow(2,8*n)-1;te(this,e,r,n,s,0);}var o=1,a=0;for(this[r]=e&255;++a<n&&(o*=256);)this[r+a]=e/o&255;return r+n};w.prototype.writeUIntBE=function(e,r,n,i){if(e=+e,r=r|0,n=n|0,!i){var s=Math.pow(2,8*n)-1;te(this,e,r,n,s,0);}var o=n-1,a=1;for(this[r+o]=e&255;--o>=0&&(a*=256);)this[r+o]=e/a&255;return r+n};w.prototype.writeUInt8=function(e,r,n){return e=+e,r=r|0,n||te(this,e,r,1,255,0),w.TYPED_ARRAY_SUPPORT||(e=Math.floor(e)),this[r]=e&255,r+1};function Wt(t,e,r,n){e<0&&(e=65535+e+1);for(var i=0,s=Math.min(t.length-r,2);i<s;++i)t[r+i]=(e&255<<8*(n?i:1-i))>>>(n?i:1-i)*8;}w.prototype.writeUInt16LE=function(e,r,n){return e=+e,r=r|0,n||te(this,e,r,2,65535,0),w.TYPED_ARRAY_SUPPORT?(this[r]=e&255,this[r+1]=e>>>8):Wt(this,e,r,true),r+2};w.prototype.writeUInt16BE=function(e,r,n){return e=+e,r=r|0,n||te(this,e,r,2,65535,0),w.TYPED_ARRAY_SUPPORT?(this[r]=e>>>8,this[r+1]=e&255):Wt(this,e,r,false),r+2};function Gt(t,e,r,n){e<0&&(e=4294967295+e+1);for(var i=0,s=Math.min(t.length-r,4);i<s;++i)t[r+i]=e>>>(n?i:3-i)*8&255;}w.prototype.writeUInt32LE=function(e,r,n){return e=+e,r=r|0,n||te(this,e,r,4,4294967295,0),w.TYPED_ARRAY_SUPPORT?(this[r+3]=e>>>24,this[r+2]=e>>>16,this[r+1]=e>>>8,this[r]=e&255):Gt(this,e,r,true),r+4};w.prototype.writeUInt32BE=function(e,r,n){return e=+e,r=r|0,n||te(this,e,r,4,4294967295,0),w.TYPED_ARRAY_SUPPORT?(this[r]=e>>>24,this[r+1]=e>>>16,this[r+2]=e>>>8,this[r+3]=e&255):Gt(this,e,r,false),r+4};w.prototype.writeIntLE=function(e,r,n,i){if(e=+e,r=r|0,!i){var s=Math.pow(2,8*n-1);te(this,e,r,n,s-1,-s);}var o=0,a=1,c=0;for(this[r]=e&255;++o<n&&(a*=256);)e<0&&c===0&&this[r+o-1]!==0&&(c=1),this[r+o]=(e/a>>0)-c&255;return r+n};w.prototype.writeIntBE=function(e,r,n,i){if(e=+e,r=r|0,!i){var s=Math.pow(2,8*n-1);te(this,e,r,n,s-1,-s);}var o=n-1,a=1,c=0;for(this[r+o]=e&255;--o>=0&&(a*=256);)e<0&&c===0&&this[r+o+1]!==0&&(c=1),this[r+o]=(e/a>>0)-c&255;return r+n};w.prototype.writeInt8=function(e,r,n){return e=+e,r=r|0,n||te(this,e,r,1,127,-128),w.TYPED_ARRAY_SUPPORT||(e=Math.floor(e)),e<0&&(e=255+e+1),this[r]=e&255,r+1};w.prototype.writeInt16LE=function(e,r,n){return e=+e,r=r|0,n||te(this,e,r,2,32767,-32768),w.TYPED_ARRAY_SUPPORT?(this[r]=e&255,this[r+1]=e>>>8):Wt(this,e,r,true),r+2};w.prototype.writeInt16BE=function(e,r,n){return e=+e,r=r|0,n||te(this,e,r,2,32767,-32768),w.TYPED_ARRAY_SUPPORT?(this[r]=e>>>8,this[r+1]=e&255):Wt(this,e,r,false),r+2};w.prototype.writeInt32LE=function(e,r,n){return e=+e,r=r|0,n||te(this,e,r,4,2147483647,-2147483648),w.TYPED_ARRAY_SUPPORT?(this[r]=e&255,this[r+1]=e>>>8,this[r+2]=e>>>16,this[r+3]=e>>>24):Gt(this,e,r,true),r+4};w.prototype.writeInt32BE=function(e,r,n){return e=+e,r=r|0,n||te(this,e,r,4,2147483647,-2147483648),e<0&&(e=4294967295+e+1),w.TYPED_ARRAY_SUPPORT?(this[r]=e>>>24,this[r+1]=e>>>16,this[r+2]=e>>>8,this[r+3]=e&255):Gt(this,e,r,false),r+4};function Ei(t,e,r,n,i,s){if(r+n>t.length)throw new RangeError("Index out of range");if(r<0)throw new RangeError("Index out of range")}function Ai(t,e,r,n,i){return i||Ei(t,e,r,4),Ze.write(t,e,r,n,23,4),r+4}w.prototype.writeFloatLE=function(e,r,n){return Ai(this,e,r,true,n)};w.prototype.writeFloatBE=function(e,r,n){return Ai(this,e,r,false,n)};function Si(t,e,r,n,i){return i||Ei(t,e,r,8),Ze.write(t,e,r,n,52,8),r+8}w.prototype.writeDoubleLE=function(e,r,n){return Si(this,e,r,true,n)};w.prototype.writeDoubleBE=function(e,r,n){return Si(this,e,r,false,n)};w.prototype.copy=function(e,r,n,i){if(n||(n=0),!i&&i!==0&&(i=this.length),r>=e.length&&(r=e.length),r||(r=0),i>0&&i<n&&(i=n),i===n||e.length===0||this.length===0)return 0;if(r<0)throw new RangeError("targetStart out of bounds");if(n<0||n>=this.length)throw new RangeError("sourceStart out of bounds");if(i<0)throw new RangeError("sourceEnd out of bounds");i>this.length&&(i=this.length),e.length-r<i-n&&(i=e.length-r+n);var s=i-n,o;if(this===e&&n<r&&r<i)for(o=s-1;o>=0;--o)e[o+r]=this[o+n];else if(s<1e3||!w.TYPED_ARRAY_SUPPORT)for(o=0;o<s;++o)e[o+r]=this[o+n];else Uint8Array.prototype.set.call(e,this.subarray(n,n+s),r);return s};w.prototype.fill=function(e,r,n,i){if(typeof e=="string"){if(typeof r=="string"?(i=r,r=0,n=this.length):typeof n=="string"&&(i=n,n=this.length),e.length===1){var s=e.charCodeAt(0);s<256&&(e=s);}if(i!==void 0&&typeof i!="string")throw new TypeError("encoding must be a string");if(typeof i=="string"&&!w.isEncoding(i))throw new TypeError("Unknown encoding: "+i)}else typeof e=="number"&&(e=e&255);if(r<0||this.length<r||this.length<n)throw new RangeError("Out of range index");if(n<=r)return this;r=r>>>0,n=n===void 0?this.length:n>>>0,e||(e=0);var o;if(typeof e=="number")for(o=r;o<n;++o)this[o]=e;else {var a=w.isBuffer(e)?e:Ht(new w(e,i).toString()),c=a.length;for(o=0;o<n-r;++o)this[o+r]=a[o%c];}return this};var Vc=/[^+\/0-9A-Za-z-_]/g;function qc(t){if(t=Bc(t).replace(Vc,""),t.length<2)return "";for(;t.length%4!==0;)t=t+"=";return t}function Bc(t){return t.trim?t.trim():t.replace(/^\s+|\s+$/g,"")}function $c(t){return t<16?"0"+t.toString(16):t.toString(16)}function Ht(t,e){e=e||1/0;for(var r,n=t.length,i=null,s=[],o=0;o<n;++o){if(r=t.charCodeAt(o),r>55295&&r<57344){if(!i){if(r>56319){(e-=3)>-1&&s.push(239,191,189);continue}else if(o+1===n){(e-=3)>-1&&s.push(239,191,189);continue}i=r;continue}if(r<56320){(e-=3)>-1&&s.push(239,191,189),i=r;continue}r=(i-55296<<10|r-56320)+65536;}else i&&(e-=3)>-1&&s.push(239,191,189);if(i=null,r<128){if((e-=1)<0)break;s.push(r);}else if(r<2048){if((e-=2)<0)break;s.push(r>>6|192,r&63|128);}else if(r<65536){if((e-=3)<0)break;s.push(r>>12|224,r>>6&63|128,r&63|128);}else if(r<1114112){if((e-=4)<0)break;s.push(r>>18|240,r>>12&63|128,r>>6&63|128,r&63|128);}else throw new Error("Invalid code point")}return s}function Kc(t){for(var e=[],r=0;r<t.length;++r)e.push(t.charCodeAt(r)&255);return e}function jc(t,e){for(var r,n,i,s=[],o=0;o<t.length&&!((e-=2)<0);++o)r=t.charCodeAt(o),n=r>>8,i=r%256,s.push(i),s.push(n);return s}function vi(t){return Fr.toByteArray(qc(t))}function Jt(t,e,r,n){for(var i=0;i<n&&!(i+r>=e.length||i>=t.length);++i)e[i+r]=t[i];return i}function Hc(t){return t!==t}});var Hr={};Bt(Hr,{__assign:()=>Kr,__asyncDelegator:()=>su,__asyncGenerator:()=>iu,__asyncValues:()=>ou,__await:()=>_t,__awaiter:()=>Xc,__classPrivateFieldGet:()=>lu,__classPrivateFieldSet:()=>du,__createBinding:()=>eu,__decorate:()=>Yc,__exportStar:()=>tu,__extends:()=>Gc,__generator:()=>Zc,__importDefault:()=>uu,__importStar:()=>cu,__makeTemplateObject:()=>au,__metadata:()=>Qc,__param:()=>zc,__read:()=>Ri,__rest:()=>Jc,__spread:()=>ru,__spreadArrays:()=>nu,__values:()=>jr});function Gc(t,e){$r(t,e);function r(){this.constructor=t;}t.prototype=e===null?Object.create(e):(r.prototype=e.prototype,new r);}function Jc(t,e){var r={};for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&e.indexOf(n)<0&&(r[n]=t[n]);if(t!=null&&typeof Object.getOwnPropertySymbols=="function")for(var i=0,n=Object.getOwnPropertySymbols(t);i<n.length;i++)e.indexOf(n[i])<0&&Object.prototype.propertyIsEnumerable.call(t,n[i])&&(r[n[i]]=t[n[i]]);return r}function Yc(t,e,r,n){var i=arguments.length,s=i<3?e:n===null?n=Object.getOwnPropertyDescriptor(e,r):n,o;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")s=Reflect.decorate(t,e,r,n);else for(var a=t.length-1;a>=0;a--)(o=t[a])&&(s=(i<3?o(s):i>3?o(e,r,s):o(e,r))||s);return i>3&&s&&Object.defineProperty(e,r,s),s}function zc(t,e){return function(r,n){e(r,n,t);}}function Qc(t,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(t,e)}function Xc(t,e,r,n){function i(s){return s instanceof r?s:new r(function(o){o(s);})}return new(r||(r=Promise))(function(s,o){function a(l){try{u(n.next(l));}catch(d){o(d);}}function c(l){try{u(n.throw(l));}catch(d){o(d);}}function u(l){l.done?s(l.value):i(l.value).then(a,c);}u((n=n.apply(t,e||[])).next());})}function Zc(t,e){var r={label:0,sent:function(){if(s[0]&1)throw s[1];return s[1]},trys:[],ops:[]},n,i,s,o;return o={next:a(0),throw:a(1),return:a(2)},typeof Symbol=="function"&&(o[Symbol.iterator]=function(){return this}),o;function a(u){return function(l){return c([u,l])}}function c(u){if(n)throw new TypeError("Generator is already executing.");for(;r;)try{if(n=1,i&&(s=u[0]&2?i.return:u[0]?i.throw||((s=i.return)&&s.call(i),0):i.next)&&!(s=s.call(i,u[1])).done)return s;switch(i=0,s&&(u=[u[0]&2,s.value]),u[0]){case 0:case 1:s=u;break;case 4:return r.label++,{value:u[1],done:!1};case 5:r.label++,i=u[1],u=[0];continue;case 7:u=r.ops.pop(),r.trys.pop();continue;default:if(s=r.trys,!(s=s.length>0&&s[s.length-1])&&(u[0]===6||u[0]===2)){r=0;continue}if(u[0]===3&&(!s||u[1]>s[0]&&u[1]<s[3])){r.label=u[1];break}if(u[0]===6&&r.label<s[1]){r.label=s[1],s=u;break}if(s&&r.label<s[2]){r.label=s[2],r.ops.push(u);break}s[2]&&r.ops.pop(),r.trys.pop();continue}u=e.call(t,r);}catch(l){u=[6,l],i=0;}finally{n=s=0;}if(u[0]&5)throw u[1];return {value:u[0]?u[1]:void 0,done:true}}}function eu(t,e,r,n){n===void 0&&(n=r),t[n]=e[r];}function tu(t,e){for(var r in t)r!=="default"&&!e.hasOwnProperty(r)&&(e[r]=t[r]);}function jr(t){var e=typeof Symbol=="function"&&Symbol.iterator,r=e&&t[e],n=0;if(r)return r.call(t);if(t&&typeof t.length=="number")return {next:function(){return t&&n>=t.length&&(t=void 0),{value:t&&t[n++],done:!t}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")}function Ri(t,e){var r=typeof Symbol=="function"&&t[Symbol.iterator];if(!r)return t;var n=r.call(t),i,s=[],o;try{for(;(e===void 0||e-- >0)&&!(i=n.next()).done;)s.push(i.value);}catch(a){o={error:a};}finally{try{i&&!i.done&&(r=n.return)&&r.call(n);}finally{if(o)throw o.error}}return s}function ru(){for(var t=[],e=0;e<arguments.length;e++)t=t.concat(Ri(arguments[e]));return t}function nu(){for(var t=0,e=0,r=arguments.length;e<r;e++)t+=arguments[e].length;for(var n=Array(t),i=0,e=0;e<r;e++)for(var s=arguments[e],o=0,a=s.length;o<a;o++,i++)n[i]=s[o];return n}function _t(t){return this instanceof _t?(this.v=t,this):new _t(t)}function iu(t,e,r){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var n=r.apply(t,e||[]),i,s=[];return i={},o("next"),o("throw"),o("return"),i[Symbol.asyncIterator]=function(){return this},i;function o(h){n[h]&&(i[h]=function(p){return new Promise(function(g,m){s.push([h,p,g,m])>1||a(h,p);})});}function a(h,p){try{c(n[h](p));}catch(g){d(s[0][3],g);}}function c(h){h.value instanceof _t?Promise.resolve(h.value.v).then(u,l):d(s[0][2],h);}function u(h){a("next",h);}function l(h){a("throw",h);}function d(h,p){h(p),s.shift(),s.length&&a(s[0][0],s[0][1]);}}function su(t){var e,r;return e={},n("next"),n("throw",function(i){throw i}),n("return"),e[Symbol.iterator]=function(){return this},e;function n(i,s){e[i]=t[i]?function(o){return (r=!r)?{value:_t(t[i](o)),done:i==="return"}:s?s(o):o}:s;}}function ou(t){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var e=t[Symbol.asyncIterator],r;return e?e.call(t):(t=typeof jr=="function"?jr(t):t[Symbol.iterator](),r={},n("next"),n("throw"),n("return"),r[Symbol.asyncIterator]=function(){return this},r);function n(s){r[s]=t[s]&&function(o){return new Promise(function(a,c){o=t[s](o),i(a,c,o.done,o.value);})};}function i(s,o,a,c){Promise.resolve(c).then(function(u){s({value:u,done:a});},o);}}function au(t,e){return Object.defineProperty?Object.defineProperty(t,"raw",{value:e}):t.raw=e,t}function cu(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)Object.hasOwnProperty.call(t,r)&&(e[r]=t[r]);return e.default=t,e}function uu(t){return t&&t.__esModule?t:{default:t}}function lu(t,e){if(!e.has(t))throw new TypeError("attempted to get private field on non-instance");return e.get(t)}function du(t,e,r){if(!e.has(t))throw new TypeError("attempted to set private field on non-instance");return e.set(t,r),r}var $r,Kr,Wr=Qe(()=>{$r=function(t,e){return $r=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(r,n){r.__proto__=n;}||function(r,n){for(var i in n)n.hasOwnProperty(i)&&(r[i]=n[i]);},$r(t,e)};Kr=function(){return Kr=Object.assign||function(e){for(var r,n=1,i=arguments.length;n<i;n++){r=arguments[n];for(var s in r)Object.prototype.hasOwnProperty.call(r,s)&&(e[s]=r[s]);}return e},Kr.apply(this,arguments)};});var Gr=ee(ue=>{Object.defineProperty(ue,"__esModule",{value:true});ue.MAX_HASHABLE_LENGTH=ue.INIT=ue.KEY=ue.DIGEST_LENGTH=ue.BLOCK_SIZE=void 0;ue.BLOCK_SIZE=64;ue.DIGEST_LENGTH=32;ue.KEY=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]);ue.INIT=[1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225];ue.MAX_HASHABLE_LENGTH=Math.pow(2,53)-1;});var Ti=ee(zt=>{Object.defineProperty(zt,"__esModule",{value:true});zt.RawSha256=void 0;var le=Gr(),fu=(function(){function t(){this.state=Int32Array.from(le.INIT),this.temp=new Int32Array(64),this.buffer=new Uint8Array(64),this.bufferLength=0,this.bytesHashed=0,this.finished=false;}return t.prototype.update=function(e){if(this.finished)throw new Error("Attempted to update an already finished hash.");var r=0,n=e.byteLength;if(this.bytesHashed+=n,this.bytesHashed*8>le.MAX_HASHABLE_LENGTH)throw new Error("Cannot hash more than 2^53 - 1 bits");for(;n>0;)this.buffer[this.bufferLength++]=e[r++],n--,this.bufferLength===le.BLOCK_SIZE&&(this.hashBuffer(),this.bufferLength=0);},t.prototype.digest=function(){if(!this.finished){var e=this.bytesHashed*8,r=new DataView(this.buffer.buffer,this.buffer.byteOffset,this.buffer.byteLength),n=this.bufferLength;if(r.setUint8(this.bufferLength++,128),n%le.BLOCK_SIZE>=le.BLOCK_SIZE-8){for(var i=this.bufferLength;i<le.BLOCK_SIZE;i++)r.setUint8(i,0);this.hashBuffer(),this.bufferLength=0;}for(var i=this.bufferLength;i<le.BLOCK_SIZE-8;i++)r.setUint8(i,0);r.setUint32(le.BLOCK_SIZE-8,Math.floor(e/4294967296),true),r.setUint32(le.BLOCK_SIZE-4,e),this.hashBuffer(),this.finished=true;}for(var s=new Uint8Array(le.DIGEST_LENGTH),i=0;i<8;i++)s[i*4]=this.state[i]>>>24&255,s[i*4+1]=this.state[i]>>>16&255,s[i*4+2]=this.state[i]>>>8&255,s[i*4+3]=this.state[i]>>>0&255;return s},t.prototype.hashBuffer=function(){for(var e=this,r=e.buffer,n=e.state,i=n[0],s=n[1],o=n[2],a=n[3],c=n[4],u=n[5],l=n[6],d=n[7],h=0;h<le.BLOCK_SIZE;h++){if(h<16)this.temp[h]=(r[h*4]&255)<<24|(r[h*4+1]&255)<<16|(r[h*4+2]&255)<<8|r[h*4+3]&255;else {var p=this.temp[h-2],g=(p>>>17|p<<15)^(p>>>19|p<<13)^p>>>10;p=this.temp[h-15];var m=(p>>>7|p<<25)^(p>>>18|p<<14)^p>>>3;this.temp[h]=(g+this.temp[h-7]|0)+(m+this.temp[h-16]|0);}var y=(((c>>>6|c<<26)^(c>>>11|c<<21)^(c>>>25|c<<7))+(c&u^~c&l)|0)+(d+(le.KEY[h]+this.temp[h]|0)|0)|0,b=((i>>>2|i<<30)^(i>>>13|i<<19)^(i>>>22|i<<10))+(i&s^i&o^s&o)|0;d=l,l=u,u=c,c=a+y|0,a=o,o=s,s=i,i=y+b|0;}n[0]+=i,n[1]+=s,n[2]+=o,n[3]+=a,n[4]+=c,n[5]+=u,n[6]+=l,n[7]+=d;},t})();zt.RawSha256=fu;});var Ii,Pi,Ui=Qe(()=>{Ii=t=>{let e=[];for(let r=0,n=t.length;r<n;r++){let i=t.charCodeAt(r);if(i<128)e.push(i);else if(i<2048)e.push(i>>6|192,i&63|128);else if(r+1<t.length&&(i&64512)===55296&&(t.charCodeAt(r+1)&64512)===56320){let s=65536+((i&1023)<<10)+(t.charCodeAt(++r)&1023);e.push(s>>18|240,s>>12&63|128,s>>6&63|128,s&63|128);}else e.push(i>>12|224,i>>6&63|128,i&63|128);}return Uint8Array.from(e)},Pi=t=>{let e="";for(let r=0,n=t.length;r<n;r++){let i=t[r];if(i<128)e+=String.fromCharCode(i);else if(192<=i&&i<224){let s=t[++r];e+=String.fromCharCode((i&31)<<6|s&63);}else if(240<=i&&i<365){let o="%"+[i,t[++r],t[++r],t[++r]].map(a=>a.toString(16)).join("%");e+=decodeURIComponent(o);}else e+=String.fromCharCode((i&15)<<12|(t[++r]&63)<<6|t[++r]&63);}return e};});function xi(t){return new TextEncoder().encode(t)}function Ci(t){return new TextDecoder("utf-8").decode(t)}var Di=Qe(()=>{});var ki={};Bt(ki,{fromUtf8:()=>hu,toUtf8:()=>gu});var hu,gu,Ni=Qe(()=>{Ui();Di();hu=t=>typeof TextEncoder=="function"?xi(t):Ii(t),gu=t=>typeof TextDecoder=="function"?Ci(t):Pi(t);});var Oi=ee(Qt=>{Object.defineProperty(Qt,"__esModule",{value:true});Qt.convertToBuffer=void 0;var pu=(Ni(),oe(ki)),mu=typeof Buffer<"u"&&Buffer.from?function(t){return Buffer.from(t,"utf8")}:pu.fromUtf8;function yu(t){return t instanceof Uint8Array?t:typeof t=="string"?mu(t):ArrayBuffer.isView(t)?new Uint8Array(t.buffer,t.byteOffset,t.byteLength/Uint8Array.BYTES_PER_ELEMENT):new Uint8Array(t)}Qt.convertToBuffer=yu;});var Fi=ee(Xt=>{Object.defineProperty(Xt,"__esModule",{value:true});Xt.isEmptyData=void 0;function _u(t){return typeof t=="string"?t.length===0:t.byteLength===0}Xt.isEmptyData=_u;});var Li=ee(Zt=>{Object.defineProperty(Zt,"__esModule",{value:true});Zt.numToUint8=void 0;function bu(t){return new Uint8Array([(t&4278190080)>>24,(t&16711680)>>16,(t&65280)>>8,t&255])}Zt.numToUint8=bu;});var Mi=ee(er=>{Object.defineProperty(er,"__esModule",{value:true});er.uint32ArrayFrom=void 0;function wu(t){if(!Array.from){for(var e=new Uint32Array(t.length),r=0;r<t.length;)e[r]=t[r];return e}return Uint32Array.from(t)}er.uint32ArrayFrom=wu;});var Vi=ee(Ae=>{Object.defineProperty(Ae,"__esModule",{value:true});Ae.uint32ArrayFrom=Ae.numToUint8=Ae.isEmptyData=Ae.convertToBuffer=void 0;var Eu=Oi();Object.defineProperty(Ae,"convertToBuffer",{enumerable:true,get:function(){return Eu.convertToBuffer}});var Au=Fi();Object.defineProperty(Ae,"isEmptyData",{enumerable:true,get:function(){return Au.isEmptyData}});var Su=Li();Object.defineProperty(Ae,"numToUint8",{enumerable:true,get:function(){return Su.numToUint8}});var vu=Mi();Object.defineProperty(Ae,"uint32ArrayFrom",{enumerable:true,get:function(){return vu.uint32ArrayFrom}});});var Bi=ee(rr=>{Object.defineProperty(rr,"__esModule",{value:true});rr.Sha256=void 0;var qi=(Wr(),oe(Hr)),tr=Gr(),Jr=Ti(),Yr=Vi(),Ru=(function(){function t(e){if(this.hash=new Jr.RawSha256,e){this.outer=new Jr.RawSha256;var r=Tu(e),n=new Uint8Array(tr.BLOCK_SIZE);n.set(r);for(var i=0;i<tr.BLOCK_SIZE;i++)r[i]^=54,n[i]^=92;this.hash.update(r),this.outer.update(n);for(var i=0;i<r.byteLength;i++)r[i]=0;}}return t.prototype.update=function(e){if(!((0, Yr.isEmptyData)(e)||this.error))try{this.hash.update((0,Yr.convertToBuffer)(e));}catch(r){this.error=r;}},t.prototype.digestSync=function(){if(this.error)throw this.error;return this.outer?(this.outer.finished||this.outer.update(this.hash.digest()),this.outer.digest()):this.hash.digest()},t.prototype.digest=function(){return (0, qi.__awaiter)(this,void 0,void 0,function(){return (0, qi.__generator)(this,function(e){return [2,this.digestSync()]})})},t})();rr.Sha256=Ru;function Tu(t){var e=(0, Yr.convertToBuffer)(t);if(e.byteLength>tr.BLOCK_SIZE){var r=new Jr.RawSha256;r.update(e),e=r.digest();}var n=new Uint8Array(tr.BLOCK_SIZE);return n.set(e),n}});var Qr=ee(zr=>{Object.defineProperty(zr,"__esModule",{value:true});var Iu=(Wr(),oe(Hr));(0, Iu.__exportStar)(Bi(),zr);});var an={};Bt(an,{default:()=>El});function El(t,e){return e=e||{},new Promise(function(r,n){var i=new XMLHttpRequest,s=[],o=[],a={},c=function(){return {ok:(i.status/100|0)==2,statusText:i.statusText,status:i.status,url:i.responseURL,text:function(){return Promise.resolve(i.responseText)},json:function(){return Promise.resolve(i.responseText).then(JSON.parse)},blob:function(){return Promise.resolve(new Blob([i.response]))},clone:c,headers:{keys:function(){return s},entries:function(){return o},get:function(l){return a[l.toLowerCase()]},has:function(l){return l.toLowerCase()in a}}}};for(var u in i.open(e.method||"get",t,true),i.onload=function(){i.getAllResponseHeaders().replace(/^(.*?):[^\S\n]*([\s\S]*?)$/gm,function(l,d,h){s.push(d=d.toLowerCase()),o.push([d,h]),a[d]=a[d]?a[d]+","+h:h;}),r(c());},i.onerror=n,i.withCredentials=e.credentials=="include",e.headers)i.setRequestHeader(u,e.headers[u]);i.send(e.body||null);})}var cn=Qe(()=>{});var zi=ee((Kf,Yi)=>{Yi.exports=self.fetch||(self.fetch=(cn(),oe(an)).default||(cn(),oe(an)));});var xe=typeof globalThis<"u"?globalThis:void 0,$t=xe?.window;function fc(t){if(Buffer)return Buffer.from(t).toString("base64");let e="",r=new Uint8Array(t),n=32768;for(let i=0;i<r.length;i+=n){let s=r.subarray(i,i+n);e+=String.fromCharCode.apply(null,Array.from(s));}if(typeof btoa=="function")return btoa(e);throw new Error("No base64 encoder available in this environment.")}if($t)$t.global=$t,$t.global._runningInNodeJS=false;else if(xe&&(xe.global=xe,typeof xe.window>"u")){class t{constructor(){this.result=null;this.error=null;this.onload=null;this.onloadend=null;this.onerror=null;}readAsDataURL(n){n.arrayBuffer().then(i=>{let s=fc(i),o=n.type||"application/octet-stream";this.result=`data:${o};base64,${s}`,this.onload&&this.onload({target:this}),this.onloadend&&this.onloadend({target:this});}).catch(i=>{this.error=i,this.onerror&&this.onerror({target:this});});}readAsArrayBuffer(n){n.arrayBuffer().then(i=>{this.result=i,this.onload&&this.onload({target:this}),this.onloadend&&this.onloadend({target:this});}).catch(i=>{this.error=i,this.onerror&&this.onerror({target:this});});}readAsText(n,i="utf-8"){n.text().then(s=>{this.result=s,this.onload&&this.onload({target:this}),this.onloadend&&this.onloadend({target:this});}).catch(s=>{this.error=s,this.onerror&&this.onerror({target:this});});}}xe.FileReader=t;class e{constructor(){this.status=0;this.statusText="";this.readyState=0;this.responseText="";this.response=null;this.responseType="";this.responseURL="";this.timeout=0;this.withCredentials=false;this.onload=null;this.onerror=null;this.onabort=null;this.ontimeout=null;this.onprogress=null;this.onreadystatechange=null;this.upload={onprogress:null};this._method="GET";this._url="";this._headers={};this._aborted=false;}open(n,i){this._method=n,this._url=i,this.readyState=1;}setRequestHeader(n,i){this._headers[n]=i;}getResponseHeader(n){return null}abort(){this._aborted=true,this.onabort&&this.onabort({});}send(n){if(this._aborted)return;let i={method:this._method,headers:this._headers};n&&this._method!=="GET"&&this._method!=="HEAD"&&(i.body=n),fetch(this._url,i).then(async s=>{if(!this._aborted){if(this.status=s.status,this.statusText=s.statusText,this.responseURL=s.url,this.readyState=4,this.responseType==="blob")this.response=await s.blob();else if(this.responseType==="json")try{this.response=await s.json();}catch{this.response=null;}else this.responseType==="arraybuffer"?this.response=await s.arrayBuffer():(this.responseText=await s.text(),this.response=this.responseText);this.onload&&this.onload({});}}).catch(s=>{this._aborted||this.onerror&&this.onerror(s);});}}xe.XMLHttpRequest=e,xe.window={_runningInNodeJS:true,alert:r=>console.error("[Alert]",r),sessionStorage:{getItem:r=>null,setItem:(r,n)=>{},removeItem:r=>{}},localStorage:{getItem:r=>{let n=(Le(),oe(Fe)),i=(Le(),oe(Fe));try{let s=i.resolve(process.cwd(),"states","localStorage",`${r}.skapi`);return n.existsSync(s)?n.readFileSync(s,"utf8"):null}catch{return null}},setItem:(r,n)=>{let i=(Le(),oe(Fe)),s=(Le(),oe(Fe));try{let o=s.resolve(process.cwd(),"states","localStorage");i.existsSync(o)||i.mkdirSync(o,{recursive:!0});let a=s.resolve(o,`${r}.skapi`);i.writeFileSync(a,n,"utf8");}catch{}},removeItem:r=>{let n=(Le(),oe(Fe)),i=(Le(),oe(Fe));try{let s=i.resolve(process.cwd(),"states","localStorage",`${r}.skapi`);n.existsSync(s)&&n.unlinkSync(s);}catch{}}},location:{href:"",origin:"",hostname:"",protocol:"",replace:r=>{}},navigator:{userAgent:`nodejs/${xe?.process?.versions?.node||"unknown"}`,mediaDevices:{getUserMedia:async r=>{throw new Error("getUserMedia is not supported in Node.js environment.")}}},addEventListener:()=>{},removeEventListener:()=>{}};}var kr=(function(){function t(r){var n=r||{},i=n.ValidationData,s=n.Username,o=n.Password,a=n.AuthParameters,c=n.ClientMetadata;this.validationData=i||{},this.authParameters=a||{},this.clientMetadata=c||{},this.username=s,this.password=o;}var e=t.prototype;return e.getUsername=function(){return this.username},e.getPassword=function(){return this.password},e.getValidationData=function(){return this.validationData},e.getAuthParameters=function(){return this.authParameters},e.getClientMetadata=function(){return this.clientMetadata},t})();var De=Xe(Yt());var ce;typeof window<"u"&&window.crypto&&(ce=window.crypto);!ce&&typeof window<"u"&&window.msCrypto&&(ce=window.msCrypto);!ce&&typeof globalThis<"u"&&globalThis.crypto&&(ce=globalThis.crypto);if(!ce&&typeof yt=="function")try{ce=(Le(),oe(Fe));}catch{}function qr(){if(ce){if(typeof ce.getRandomValues=="function")try{return ce.getRandomValues(new Uint32Array(1))[0]}catch{}if(typeof ce.randomBytes=="function")try{return ce.randomBytes(4).readInt32LE()}catch{}}throw new Error("Native crypto module could not be used to get secure random number.")}function Wc(t){for(var e=t.words,r=t.sigBytes,n=[],i=0;i<r;i++){var s=e[i>>>2]>>>24-i%4*8&255;n.push((s>>>4).toString(16)),n.push((s&15).toString(16));}return n.join("")}var Br=(function(){function t(r,n){r=this.words=r||[],n!=null?this.sigBytes=n:this.sigBytes=r.length*4;}var e=t.prototype;return e.random=function(n){for(var i=[],s=0;s<n;s+=4)i.push(qr());return new t(i,n)},e.toString=function(){return Wc(this)},t})();var ir=Xe(Qr());var H=k;function k(t,e){t!=null&&this.fromString(t,e);}function X(){return new k(null)}var Me,Pu=0xdeadbeefcafe,$i=(Pu&16777215)==15715070;function Uu(t,e,r,n,i,s){for(;--s>=0;){var o=e*this[t++]+r[n]+i;i=Math.floor(o/67108864),r[n++]=o&67108863;}return i}function xu(t,e,r,n,i,s){for(var o=e&32767,a=e>>15;--s>=0;){var c=this[t]&32767,u=this[t++]>>15,l=a*c+u*o;c=o*c+((l&32767)<<15)+r[n]+(i&1073741823),i=(c>>>30)+(l>>>15)+a*u+(i>>>30),r[n++]=c&1073741823;}return i}function Cu(t,e,r,n,i,s){for(var o=e&16383,a=e>>14;--s>=0;){var c=this[t]&16383,u=this[t++]>>14,l=a*c+u*o;c=o*c+((l&16383)<<14)+r[n]+i,i=(c>>28)+(l>>14)+a*u,r[n++]=c&268435455;}return i}var Ki=typeof navigator<"u";Ki&&$i&&navigator.appName=="Microsoft Internet Explorer"?(k.prototype.am=xu,Me=30):Ki&&$i&&navigator.appName!="Netscape"?(k.prototype.am=Uu,Me=26):(k.prototype.am=Cu,Me=28);k.prototype.DB=Me;k.prototype.DM=(1<<Me)-1;k.prototype.DV=1<<Me;var Xr=52;k.prototype.FV=Math.pow(2,Xr);k.prototype.F1=Xr-Me;k.prototype.F2=2*Me-Xr;var Du="0123456789abcdefghijklmnopqrstuvwxyz",nr=new Array,tt,de;tt=48;for(de=0;de<=9;++de)nr[tt++]=de;tt=97;for(de=10;de<36;++de)nr[tt++]=de;tt=65;for(de=10;de<36;++de)nr[tt++]=de;function ji(t){return Du.charAt(t)}function ku(t,e){var r=nr[t.charCodeAt(e)];return r??-1}function Nu(t){for(var e=this.t-1;e>=0;--e)t[e]=this[e];t.t=this.t,t.s=this.s;}function Ou(t){this.t=1,this.s=t<0?-1:0,t>0?this[0]=t:t<-1?this[0]=t+this.DV:this.t=0;}function Zr(t){var e=X();return e.fromInt(t),e}function Fu(t,e){var r;if(e==16)r=4;else if(e==8)r=3;else if(e==2)r=1;else if(e==32)r=5;else if(e==4)r=2;else throw new Error("Only radix 2, 4, 8, 16, 32 are supported");this.t=0,this.s=0;for(var n=t.length,i=false,s=0;--n>=0;){var o=ku(t,n);if(o<0){t.charAt(n)=="-"&&(i=true);continue}i=false,s==0?this[this.t++]=o:s+r>this.DB?(this[this.t-1]|=(o&(1<<this.DB-s)-1)<<s,this[this.t++]=o>>this.DB-s):this[this.t-1]|=o<<s,s+=r,s>=this.DB&&(s-=this.DB);}this.clamp(),i&&k.ZERO.subTo(this,this);}function Lu(){for(var t=this.s&this.DM;this.t>0&&this[this.t-1]==t;)--this.t;}function Mu(t){if(this.s<0)return "-"+this.negate().toString(t);var e;if(t==16)e=4;else if(t==8)e=3;else if(t==2)e=1;else if(t==32)e=5;else if(t==4)e=2;else throw new Error("Only radix 2, 4, 8, 16, 32 are supported");var r=(1<<e)-1,n,i=false,s="",o=this.t,a=this.DB-o*this.DB%e;if(o-- >0)for(a<this.DB&&(n=this[o]>>a)>0&&(i=true,s=ji(n));o>=0;)a<e?(n=(this[o]&(1<<a)-1)<<e-a,n|=this[--o]>>(a+=this.DB-e)):(n=this[o]>>(a-=e)&r,a<=0&&(a+=this.DB,--o)),n>0&&(i=true),i&&(s+=ji(n));return i?s:"0"}function Vu(){var t=X();return k.ZERO.subTo(this,t),t}function qu(){return this.s<0?this.negate():this}function Bu(t){var e=this.s-t.s;if(e!=0)return e;var r=this.t;if(e=r-t.t,e!=0)return this.s<0?-e:e;for(;--r>=0;)if((e=this[r]-t[r])!=0)return e;return 0}function en(t){var e=1,r;return (r=t>>>16)!=0&&(t=r,e+=16),(r=t>>8)!=0&&(t=r,e+=8),(r=t>>4)!=0&&(t=r,e+=4),(r=t>>2)!=0&&(t=r,e+=2),(r=t>>1)!=0&&(t=r,e+=1),e}function $u(){return this.t<=0?0:this.DB*(this.t-1)+en(this[this.t-1]^this.s&this.DM)}function Ku(t,e){var r;for(r=this.t-1;r>=0;--r)e[r+t]=this[r];for(r=t-1;r>=0;--r)e[r]=0;e.t=this.t+t,e.s=this.s;}function ju(t,e){for(var r=t;r<this.t;++r)e[r-t]=this[r];e.t=Math.max(this.t-t,0),e.s=this.s;}function Hu(t,e){var r=t%this.DB,n=this.DB-r,i=(1<<n)-1,s=Math.floor(t/this.DB),o=this.s<<r&this.DM,a;for(a=this.t-1;a>=0;--a)e[a+s+1]=this[a]>>n|o,o=(this[a]&i)<<r;for(a=s-1;a>=0;--a)e[a]=0;e[s]=o,e.t=this.t+s+1,e.s=this.s,e.clamp();}function Wu(t,e){e.s=this.s;var r=Math.floor(t/this.DB);if(r>=this.t){e.t=0;return}var n=t%this.DB,i=this.DB-n,s=(1<<n)-1;e[0]=this[r]>>n;for(var o=r+1;o<this.t;++o)e[o-r-1]|=(this[o]&s)<<i,e[o-r]=this[o]>>n;n>0&&(e[this.t-r-1]|=(this.s&s)<<i),e.t=this.t-r,e.clamp();}function Gu(t,e){for(var r=0,n=0,i=Math.min(t.t,this.t);r<i;)n+=this[r]-t[r],e[r++]=n&this.DM,n>>=this.DB;if(t.t<this.t){for(n-=t.s;r<this.t;)n+=this[r],e[r++]=n&this.DM,n>>=this.DB;n+=this.s;}else {for(n+=this.s;r<t.t;)n-=t[r],e[r++]=n&this.DM,n>>=this.DB;n-=t.s;}e.s=n<0?-1:0,n<-1?e[r++]=this.DV+n:n>0&&(e[r++]=n),e.t=r,e.clamp();}function Ju(t,e){var r=this.abs(),n=t.abs(),i=r.t;for(e.t=i+n.t;--i>=0;)e[i]=0;for(i=0;i<n.t;++i)e[i+r.t]=r.am(0,n[i],e,i,0,r.t);e.s=0,e.clamp(),this.s!=t.s&&k.ZERO.subTo(e,e);}function Yu(t){for(var e=this.abs(),r=t.t=2*e.t;--r>=0;)t[r]=0;for(r=0;r<e.t-1;++r){var n=e.am(r,e[r],t,2*r,0,1);(t[r+e.t]+=e.am(r+1,2*e[r],t,2*r+1,n,e.t-r-1))>=e.DV&&(t[r+e.t]-=e.DV,t[r+e.t+1]=1);}t.t>0&&(t[t.t-1]+=e.am(r,e[r],t,2*r,0,1)),t.s=0,t.clamp();}function zu(t,e,r){var n=t.abs();if(!(n.t<=0)){var i=this.abs();if(i.t<n.t){e?.fromInt(0),r!=null&&this.copyTo(r);return}r==null&&(r=X());var s=X(),o=this.s,a=t.s,c=this.DB-en(n[n.t-1]);c>0?(n.lShiftTo(c,s),i.lShiftTo(c,r)):(n.copyTo(s),i.copyTo(r));var u=s.t,l=s[u-1];if(l!=0){var d=l*(1<<this.F1)+(u>1?s[u-2]>>this.F2:0),h=this.FV/d,p=(1<<this.F1)/d,g=1<<this.F2,m=r.t,y=m-u,b=e??X();for(s.dlShiftTo(y,b),r.compareTo(b)>=0&&(r[r.t++]=1,r.subTo(b,r)),k.ONE.dlShiftTo(u,b),b.subTo(s,s);s.t<u;)s[s.t++]=0;for(;--y>=0;){var E=r[--m]==l?this.DM:Math.floor(r[m]*h+(r[m-1]+g)*p);if((r[m]+=s.am(0,E,r,y,0,u))<E)for(s.dlShiftTo(y,b),r.subTo(b,r);r[m]<--E;)r.subTo(b,r);}e!=null&&(r.drShiftTo(u,e),o!=a&&k.ZERO.subTo(e,e)),r.t=u,r.clamp(),c>0&&r.rShiftTo(c,r),o<0&&k.ZERO.subTo(r,r);}}}function Qu(t){var e=X();return this.abs().divRemTo(t,null,e),this.s<0&&e.compareTo(k.ZERO)>0&&t.subTo(e,e),e}function Xu(){if(this.t<1)return 0;var t=this[0];if((t&1)==0)return 0;var e=t&3;return e=e*(2-(t&15)*e)&15,e=e*(2-(t&255)*e)&255,e=e*(2-((t&65535)*e&65535))&65535,e=e*(2-t*e%this.DV)%this.DV,e>0?this.DV-e:-e}function Zu(t){return this.compareTo(t)==0}function el(t,e){for(var r=0,n=0,i=Math.min(t.t,this.t);r<i;)n+=this[r]+t[r],e[r++]=n&this.DM,n>>=this.DB;if(t.t<this.t){for(n+=t.s;r<this.t;)n+=this[r],e[r++]=n&this.DM,n>>=this.DB;n+=this.s;}else {for(n+=this.s;r<t.t;)n+=t[r],e[r++]=n&this.DM,n>>=this.DB;n+=t.s;}e.s=n<0?-1:0,n>0?e[r++]=n:n<-1&&(e[r++]=this.DV+n),e.t=r,e.clamp();}function tl(t){var e=X();return this.addTo(t,e),e}function rl(t){var e=X();return this.subTo(t,e),e}function nl(t){var e=X();return this.multiplyTo(t,e),e}function il(t){var e=X();return this.divRemTo(t,e,null),e}function rt(t){this.m=t,this.mp=t.invDigit(),this.mpl=this.mp&32767,this.mph=this.mp>>15,this.um=(1<<t.DB-15)-1,this.mt2=2*t.t;}function sl(t){var e=X();return t.abs().dlShiftTo(this.m.t,e),e.divRemTo(this.m,null,e),t.s<0&&e.compareTo(k.ZERO)>0&&this.m.subTo(e,e),e}function ol(t){var e=X();return t.copyTo(e),this.reduce(e),e}function al(t){for(;t.t<=this.mt2;)t[t.t++]=0;for(var e=0;e<this.m.t;++e){var r=t[e]&32767,n=r*this.mpl+((r*this.mph+(t[e]>>15)*this.mpl&this.um)<<15)&t.DM;for(r=e+this.m.t,t[r]+=this.m.am(0,n,t,e,0,this.m.t);t[r]>=t.DV;)t[r]-=t.DV,t[++r]++;}t.clamp(),t.drShiftTo(this.m.t,t),t.compareTo(this.m)>=0&&t.subTo(this.m,t);}function cl(t,e){t.squareTo(e),this.reduce(e);}function ul(t,e,r){t.multiplyTo(e,r),this.reduce(r);}rt.prototype.convert=sl;rt.prototype.revert=ol;rt.prototype.reduce=al;rt.prototype.mulTo=ul;rt.prototype.sqrTo=cl;function ll(t,e,r){var n=t.bitLength(),i,s=Zr(1),o=new rt(e);if(n<=0)return s;n<18?i=1:n<48?i=3:n<144?i=4:n<768?i=5:i=6;var a=new Array,c=3,u=i-1,l=(1<<i)-1;if(a[1]=o.convert(this),i>1){var d=X();for(o.sqrTo(a[1],d);c<=l;)a[c]=X(),o.mulTo(d,a[c-2],a[c]),c+=2;}var h=t.t-1,p,g=true,m=X(),y;for(n=en(t[h])-1;h>=0;){for(n>=u?p=t[h]>>n-u&l:(p=(t[h]&(1<<n+1)-1)<<u-n,h>0&&(p|=t[h-1]>>this.DB+n-u)),c=i;(p&1)==0;)p>>=1,--c;if((n-=c)<0&&(n+=this.DB,--h),g)a[p].copyTo(s),g=false;else {for(;c>1;)o.sqrTo(s,m),o.sqrTo(m,s),c-=2;c>0?o.sqrTo(s,m):(y=s,s=m,m=y),o.mulTo(m,a[p],s);}for(;h>=0&&(t[h]&1<<n)==0;)o.sqrTo(s,m),y=s,s=m,m=y,--n<0&&(n=this.DB-1,--h);}var b=o.revert(s);return r(null,b),b}k.prototype.copyTo=Nu;k.prototype.fromInt=Ou;k.prototype.fromString=Fu;k.prototype.clamp=Lu;k.prototype.dlShiftTo=Ku;k.prototype.drShiftTo=ju;k.prototype.lShiftTo=Hu;k.prototype.rShiftTo=Wu;k.prototype.subTo=Gu;k.prototype.multiplyTo=Ju;k.prototype.squareTo=Yu;k.prototype.divRemTo=zu;k.prototype.invDigit=Xu;k.prototype.addTo=el;k.prototype.toString=Mu;k.prototype.negate=Vu;k.prototype.abs=qu;k.prototype.compareTo=Bu;k.prototype.bitLength=$u;k.prototype.mod=Qu;k.prototype.equals=Zu;k.prototype.add=tl;k.prototype.subtract=rl;k.prototype.multiply=nl;k.prototype.divide=il;k.prototype.modPow=ll;k.ZERO=Zr(0);k.ONE=Zr(1);function tn(t){return De.Buffer.from(new Br().random(t).toString(),"hex")}var dl=/^[89a-f]/i,fl="FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E088A67CC74020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7EDEE386BFB5A899FA5AE9F24117C4B1FE649286651ECE45B3DC2007CB8A163BF0598DA48361C55D39A69163FA8FD24CF5F83655D23DCA3AD961C62F356208552BB9ED529077096966D670C354E4ABC9804F1746C08CA18217C32905E462E36CE3BE39E772C180E86039B2783A2EC07A28FB5C55DF06F4C52C9DE2BCBF6955817183995497CEA956AE515D2261898FA051015728E5A8AAAC42DAD33170D04507A33A85521ABDF1CBA64ECFB850458DBEF0A8AEA71575D060C7DB3970F85A6E1E4C7ABF5AE8CDB0933D71E8C94E04A25619DCEE3D2261AD2EE6BF12FFA06D98A0864D87602733EC86A64521F2B18177B200CBBE117577A615D6C770988C0BAD946E208E24FA074E5AB3143DB5BFCE0FD108E4B82D120A93AD2CAFFFFFFFFFFFFFFFF",hl="userAttributes.",Ve=(function(){function t(r){this.N=new H(fl,16),this.g=new H("2",16),this.k=new H(this.hexHash(""+this.padHex(this.N)+this.padHex(this.g)),16),this.smallAValue=this.generateRandomSmallA(),this.getLargeAValue(function(){}),this.infoBits=De.Buffer.from("Caldera Derived Key","utf8"),this.poolName=r;}var e=t.prototype;return e.getSmallAValue=function(){return this.smallAValue},e.getLargeAValue=function(n){var i=this;this.largeAValue?n(null,this.largeAValue):this.calculateA(this.smallAValue,function(s,o){s&&n(s,null),i.largeAValue=o,n(null,i.largeAValue);});},e.generateRandomSmallA=function(){var n=tn(128).toString("hex"),i=new H(n,16);return i},e.generateRandomString=function(){return tn(40).toString("base64")},e.getRandomPassword=function(){return this.randomPassword},e.getSaltDevices=function(){return this.SaltToHashDevices},e.getVerifierDevices=function(){return this.verifierDevices},e.generateHashDevice=function(n,i,s){var o=this;this.randomPassword=this.generateRandomString();var a=""+n+i+":"+this.randomPassword,c=this.hash(a),u=tn(16).toString("hex");this.SaltToHashDevices=this.padHex(new H(u,16)),this.g.modPow(new H(this.hexHash(this.SaltToHashDevices+c),16),this.N,function(l,d){l&&s(l,null),o.verifierDevices=o.padHex(d),s(null,null);});},e.calculateA=function(n,i){var s=this;this.g.modPow(n,this.N,function(o,a){o&&i(o,null),a.mod(s.N).equals(H.ZERO)&&i(new Error("Illegal paramater. A mod N cannot be 0."),null),i(null,a);});},e.calculateU=function(n,i){this.UHexHash=this.hexHash(this.padHex(n)+this.padHex(i));var s=new H(this.UHexHash,16);return s},e.hash=function(n){var i=new ir.Sha256;i.update(n);var s=i.digestSync(),o=De.Buffer.from(s).toString("hex");return new Array(64-o.length).join("0")+o},e.hexHash=function(n){return this.hash(De.Buffer.from(n,"hex"))},e.computehkdf=function(n,i){var s=De.Buffer.concat([this.infoBits,De.Buffer.from("","utf8")]),o=new ir.Sha256(i);o.update(n);var a=o.digestSync(),c=new ir.Sha256(a);c.update(s);var u=c.digestSync(),l=u,d=l.slice(0,16);return d},e.getPasswordAuthenticationKey=function(n,i,s,o,a){var c=this;if(s.mod(this.N).equals(H.ZERO))throw new Error("B cannot be zero.");if(this.UValue=this.calculateU(this.largeAValue,s),this.UValue.equals(H.ZERO))throw new Error("U cannot be zero.");var u=""+this.poolName+n+":"+i,l=this.hash(u),d=new H(this.hexHash(this.padHex(o)+l),16);this.calculateS(d,s,function(h,p){h&&a(h,null);var g=c.computehkdf(De.Buffer.from(c.padHex(p),"hex"),De.Buffer.from(c.padHex(c.UValue),"hex"));a(null,g);});},e.calculateS=function(n,i,s){var o=this;this.g.modPow(n,this.N,function(a,c){a&&s(a,null);var u=i.subtract(o.k.multiply(c));u.modPow(o.smallAValue.add(o.UValue.multiply(n)),o.N,function(l,d){l&&s(l,null),s(null,d.mod(o.N));});});},e.getNewPasswordRequiredChallengeUserAttributePrefix=function(){return hl},e.padHex=function(n){if(!(n instanceof H))throw new Error("Not a BigInteger");var i=n.compareTo(H.ZERO)<0,s=n.abs().toString(16);if(s=s.length%2!==0?"0"+s:s,s=dl.test(s)?"00"+s:s,i){var o=s.split("").map(function(c){var u=~parseInt(c,16)&15;return "0123456789ABCDEF".charAt(u)}).join(""),a=new H(o,16).add(H.ONE);s=a.toString(16),s.toUpperCase().startsWith("FF8")&&(s=s.substring(2));}return s},t})();var Hi=Xe(Yt());var sr=(function(){function t(r){this.jwtToken=r||"",this.payload=this.decodePayload();}var e=t.prototype;return e.getJwtToken=function(){return this.jwtToken},e.getExpiration=function(){return this.payload.exp},e.getIssuedAt=function(){return this.payload.iat},e.decodePayload=function(){var n=this.jwtToken.split(".")[1];try{return JSON.parse(Hi.Buffer.from(n,"base64").toString("utf8"))}catch{return {}}},t})();function gl(t,e){t.prototype=Object.create(e.prototype),t.prototype.constructor=t,rn(t,e);}function rn(t,e){return rn=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(r,n){return r.__proto__=n,r},rn(t,e)}var nt=(function(t){function e(r){var n=r===void 0?{}:r,i=n.AccessToken;return t.call(this,i||"")||this}return gl(e,t),e})(sr);function pl(t,e){t.prototype=Object.create(e.prototype),t.prototype.constructor=t,nn(t,e);}function nn(t,e){return nn=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(r,n){return r.__proto__=n,r},nn(t,e)}var it=(function(t){function e(r){var n=r===void 0?{}:r,i=n.IdToken;return t.call(this,i||"")||this}return pl(e,t),e})(sr);var st=(function(){function t(r){var n=r===void 0?{}:r,i=n.RefreshToken;this.token=i||"";}var e=t.prototype;return e.getToken=function(){return this.token},t})();var J=Xe(Yt()),on=Xe(Qr());var Wi="5.0.4";var ml="aws-amplify/"+Wi,sn={userAgent:ml,isReactNative:typeof navigator<"u"&&navigator.product==="ReactNative"},Gi=function(){return sn.userAgent};var ot=(function(){function t(r){var n=r===void 0?{}:r,i=n.IdToken,s=n.RefreshToken,o=n.AccessToken,a=n.ClockDrift;if(o==null||i==null)throw new Error("Id token and Access Token must be present.");this.idToken=i,this.refreshToken=s,this.accessToken=o,this.clockDrift=a===void 0?this.calculateClockDrift():a;}var e=t.prototype;return e.getIdToken=function(){return this.idToken},e.getRefreshToken=function(){return this.refreshToken},e.getAccessToken=function(){return this.accessToken},e.getClockDrift=function(){return this.clockDrift},e.calculateClockDrift=function(){var n=Math.floor(new Date/1e3),i=Math.min(this.accessToken.getIssuedAt(),this.idToken.getIssuedAt());return n-i},e.isValid=function(){var n=Math.floor(new Date/1e3),i=n-this.clockDrift;return i<this.accessToken.getExpiration()&&i<this.idToken.getExpiration()},t})();var yl=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],_l=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],or=(function(){function t(){}var e=t.prototype;return e.getNowString=function(){var n=new Date,i=_l[n.getUTCDay()],s=yl[n.getUTCMonth()],o=n.getUTCDate(),a=n.getUTCHours();a<10&&(a="0"+a);var c=n.getUTCMinutes();c<10&&(c="0"+c);var u=n.getUTCSeconds();u<10&&(u="0"+u);var l=n.getUTCFullYear(),d=i+" "+s+" "+o+" "+a+":"+c+":"+u+" UTC "+l;return d},t})();var Se=(function(){function t(r){var n=r===void 0?{}:r,i=n.Name,s=n.Value;this.Name=i||"",this.Value=s||"";}var e=t.prototype;return e.getValue=function(){return this.Value},e.setValue=function(n){return this.Value=n,this},e.getName=function(){return this.Name},e.setName=function(n){return this.Name=n,this},e.toString=function(){return JSON.stringify(this)},e.toJSON=function(){return {Name:this.Name,Value:this.Value}},t})();var He={},bl=(function(){function t(){}return t.setItem=function(r,n){return He[r]=n,He[r]},t.getItem=function(r){return Object.prototype.hasOwnProperty.call(He,r)?He[r]:void 0},t.removeItem=function(r){return delete He[r]},t.clear=function(){return He={},He},t})(),ar=(function(){function t(){try{this.storageWindow=window.localStorage,this.storageWindow.setItem("aws.cognito.test-ls",1),this.storageWindow.removeItem("aws.cognito.test-ls");}catch{this.storageWindow=bl;}}var e=t.prototype;return e.getStorage=function(){return this.storageWindow},t})();var wl=typeof navigator<"u",Ji=wl?sn.isReactNative?"react-native":navigator.userAgent:"nodejs",ke=(function(){function t(r){if(r==null||r.Username==null||r.Pool==null)throw new Error("Username and Pool information are required.");this.username=r.Username||"",this.pool=r.Pool,this.Session=null,this.client=r.Pool.client,this.signInUserSession=null,this.authenticationFlowType="USER_SRP_AUTH",this.storage=r.Storage||new ar().getStorage(),this.keyPrefix="CognitoIdentityServiceProvider."+this.pool.getClientId(),this.userDataKey=this.keyPrefix+"."+this.username+".userData";}var e=t.prototype;return e.setSignInUserSession=function(n){this.clearCachedUserData(),this.signInUserSession=n,this.cacheTokens();},e.getSignInUserSession=function(){return this.signInUserSession},e.getUsername=function(){return this.username},e.getAuthenticationFlowType=function(){return this.authenticationFlowType},e.setAuthenticationFlowType=function(n){this.authenticationFlowType=n;},e.initiateAuth=function(n,i){var s=this,o=n.getAuthParameters();o.USERNAME=this.username;var a=Object.keys(n.getValidationData()).length!==0?n.getValidationData():n.getClientMetadata(),c={AuthFlow:"CUSTOM_AUTH",ClientId:this.pool.getClientId(),AuthParameters:o,ClientMetadata:a};this.getUserContextData()&&(c.UserContextData=this.getUserContextData()),this.client.request("InitiateAuth",c,function(u,l){if(u)return i.onFailure(u);var d=l.ChallengeName,h=l.ChallengeParameters;return d==="CUSTOM_CHALLENGE"?(s.Session=l.Session,i.customChallenge(h)):(s.signInUserSession=s.getCognitoUserSession(l.AuthenticationResult),s.cacheTokens(),i.onSuccess(s.signInUserSession))});},e.authenticateUser=function(n,i){return this.authenticationFlowType==="USER_PASSWORD_AUTH"?this.authenticateUserPlainUsernamePassword(n,i):this.authenticationFlowType==="USER_SRP_AUTH"||this.authenticationFlowType==="CUSTOM_AUTH"?this.authenticateUserDefaultAuth(n,i):i.onFailure(new Error("Authentication flow type is invalid."))},e.authenticateUserDefaultAuth=function(n,i){var s=this,o=new Ve(this.pool.getUserPoolName()),a=new or,c,u,l={};this.deviceKey!=null&&(l.DEVICE_KEY=this.deviceKey),l.USERNAME=this.username,o.getLargeAValue(function(d,h){d&&i.onFailure(d),l.SRP_A=h.toString(16),s.authenticationFlowType==="CUSTOM_AUTH"&&(l.CHALLENGE_NAME="SRP_A");var p=Object.keys(n.getValidationData()).length!==0?n.getValidationData():n.getClientMetadata(),g={AuthFlow:s.authenticationFlowType,ClientId:s.pool.getClientId(),AuthParameters:l,ClientMetadata:p};s.getUserContextData(s.username)&&(g.UserContextData=s.getUserContextData(s.username)),s.client.request("InitiateAuth",g,function(m,y){if(m)return i.onFailure(m);var b=y.ChallengeParameters;s.username=b.USER_ID_FOR_SRP,s.userDataKey=s.keyPrefix+"."+s.username+".userData",c=new H(b.SRP_B,16),u=new H(b.SALT,16),s.getCachedDeviceKeyAndPassword(),o.getPasswordAuthenticationKey(s.username,n.getPassword(),c,u,function(E,v){E&&i.onFailure(E);var x=a.getNowString(),P=J.Buffer.concat([J.Buffer.from(s.pool.getUserPoolName(),"utf8"),J.Buffer.from(s.username,"utf8"),J.Buffer.from(b.SECRET_BLOCK,"base64"),J.Buffer.from(x,"utf8")]),N=new on.Sha256(v);N.update(P);var O=N.digestSync(),M=J.Buffer.from(O).toString("base64"),U={};U.USERNAME=s.username,U.PASSWORD_CLAIM_SECRET_BLOCK=b.SECRET_BLOCK,U.TIMESTAMP=x,U.PASSWORD_CLAIM_SIGNATURE=M,s.deviceKey!=null&&(U.DEVICE_KEY=s.deviceKey);var C=function(Ue,ni){return s.client.request("RespondToAuthChallenge",Ue,function(qt,ic){return qt&&qt.code==="ResourceNotFoundException"&&qt.message.toLowerCase().indexOf("device")!==-1?(U.DEVICE_KEY=null,s.deviceKey=null,s.randomPassword=null,s.deviceGroupKey=null,s.clearCachedDeviceKeyAndPassword(),C(Ue,ni)):ni(qt,ic)})},V={ChallengeName:"PASSWORD_VERIFIER",ClientId:s.pool.getClientId(),ChallengeResponses:U,Session:y.Session,ClientMetadata:p};s.getUserContextData()&&(V.UserContextData=s.getUserContextData()),C(V,function(B,Ue){return B?i.onFailure(B):s.authenticateUserInternal(Ue,o,i)});});});});},e.authenticateUserPlainUsernamePassword=function(n,i){var s=this,o={};if(o.USERNAME=this.username,o.PASSWORD=n.getPassword(),!o.PASSWORD){i.onFailure(new Error("PASSWORD parameter is required"));return}var a=new Ve(this.pool.getUserPoolName());this.getCachedDeviceKeyAndPassword(),this.deviceKey!=null&&(o.DEVICE_KEY=this.deviceKey);var c=Object.keys(n.getValidationData()).length!==0?n.getValidationData():n.getClientMetadata(),u={AuthFlow:"USER_PASSWORD_AUTH",ClientId:this.pool.getClientId(),AuthParameters:o,ClientMetadata:c};this.getUserContextData(this.username)&&(u.UserContextData=this.getUserContextData(this.username)),this.client.request("InitiateAuth",u,function(l,d){return l?i.onFailure(l):s.authenticateUserInternal(d,a,i)});},e.authenticateUserInternal=function(n,i,s){var o=this,a=n.ChallengeName,c=n.ChallengeParameters;if(a==="SMS_MFA")return this.Session=n.Session,s.mfaRequired(a,c);if(a==="SELECT_MFA_TYPE")return this.Session=n.Session,s.selectMFAType(a,c);if(a==="MFA_SETUP")return this.Session=n.Session,s.mfaSetup(a,c);if(a==="SOFTWARE_TOKEN_MFA")return this.Session=n.Session,s.totpRequired(a,c);if(a==="CUSTOM_CHALLENGE")return this.Session=n.Session,s.customChallenge(c);if(a==="NEW_PASSWORD_REQUIRED"){this.Session=n.Session;var u=null,l=null,d=[],h=i.getNewPasswordRequiredChallengeUserAttributePrefix();if(c&&(u=JSON.parse(n.ChallengeParameters.userAttributes),l=JSON.parse(n.ChallengeParameters.requiredAttributes)),l)for(var p=0;p<l.length;p++)d[p]=l[p].substr(h.length);return s.newPasswordRequired(u,d)}if(a==="DEVICE_SRP_AUTH"){this.Session=n.Session,this.getDeviceResponse(s);return}this.signInUserSession=this.getCognitoUserSession(n.AuthenticationResult),this.challengeName=a,this.cacheTokens();var g=n.AuthenticationResult.NewDeviceMetadata;if(g==null)return s.onSuccess(this.signInUserSession);i.generateHashDevice(n.AuthenticationResult.NewDeviceMetadata.DeviceGroupKey,n.AuthenticationResult.NewDeviceMetadata.DeviceKey,function(m){if(m)return s.onFailure(m);var y={Salt:J.Buffer.from(i.getSaltDevices(),"hex").toString("base64"),PasswordVerifier:J.Buffer.from(i.getVerifierDevices(),"hex").toString("base64")};o.verifierDevices=y.PasswordVerifier,o.deviceGroupKey=g.DeviceGroupKey,o.randomPassword=i.getRandomPassword(),o.client.request("ConfirmDevice",{DeviceKey:g.DeviceKey,AccessToken:o.signInUserSession.getAccessToken().getJwtToken(),DeviceSecretVerifierConfig:y,DeviceName:Ji},function(b,E){return b?s.onFailure(b):(o.deviceKey=n.AuthenticationResult.NewDeviceMetadata.DeviceKey,o.cacheDeviceKeyAndPassword(),E.UserConfirmationNecessary===true?s.onSuccess(o.signInUserSession,E.UserConfirmationNecessary):s.onSuccess(o.signInUserSession))});});},e.completeNewPasswordChallenge=function(n,i,s,o){var a=this;if(!n)return s.onFailure(new Error("New password is required."));var c=new Ve(this.pool.getUserPoolName()),u=c.getNewPasswordRequiredChallengeUserAttributePrefix(),l={};i&&Object.keys(i).forEach(function(h){l[u+h]=i[h];}),l.NEW_PASSWORD=n,l.USERNAME=this.username;var d={ChallengeName:"NEW_PASSWORD_REQUIRED",ClientId:this.pool.getClientId(),ChallengeResponses:l,Session:this.Session,ClientMetadata:o};this.getUserContextData()&&(d.UserContextData=this.getUserContextData()),this.client.request("RespondToAuthChallenge",d,function(h,p){return h?s.onFailure(h):a.authenticateUserInternal(p,c,s)});},e.getDeviceResponse=function(n,i){var s=this,o=new Ve(this.deviceGroupKey),a=new or,c={};c.USERNAME=this.username,c.DEVICE_KEY=this.deviceKey,o.getLargeAValue(function(u,l){u&&n.onFailure(u),c.SRP_A=l.toString(16);var d={ChallengeName:"DEVICE_SRP_AUTH",ClientId:s.pool.getClientId(),ChallengeResponses:c,ClientMetadata:i,Session:s.Session};s.getUserContextData()&&(d.UserContextData=s.getUserContextData()),s.client.request("RespondToAuthChallenge",d,function(h,p){if(h)return n.onFailure(h);var g=p.ChallengeParameters,m=new H(g.SRP_B,16),y=new H(g.SALT,16);o.getPasswordAuthenticationKey(s.deviceKey,s.randomPassword,m,y,function(b,E){if(b)return n.onFailure(b);var v=a.getNowString(),x=J.Buffer.concat([J.Buffer.from(s.deviceGroupKey,"utf8"),J.Buffer.from(s.deviceKey,"utf8"),J.Buffer.from(g.SECRET_BLOCK,"base64"),J.Buffer.from(v,"utf8")]),P=new on.Sha256(E);P.update(x);var N=P.digestSync(),O=J.Buffer.from(N).toString("base64"),M={};M.USERNAME=s.username,M.PASSWORD_CLAIM_SECRET_BLOCK=g.SECRET_BLOCK,M.TIMESTAMP=v,M.PASSWORD_CLAIM_SIGNATURE=O,M.DEVICE_KEY=s.deviceKey;var U={ChallengeName:"DEVICE_PASSWORD_VERIFIER",ClientId:s.pool.getClientId(),ChallengeResponses:M,Session:p.Session};s.getUserContextData()&&(U.UserContextData=s.getUserContextData()),s.client.request("RespondToAuthChallenge",U,function(C,V){return C?n.onFailure(C):(s.signInUserSession=s.getCognitoUserSession(V.AuthenticationResult),s.cacheTokens(),n.onSuccess(s.signInUserSession))});});});});},e.confirmRegistration=function(n,i,s,o){var a={ClientId:this.pool.getClientId(),ConfirmationCode:n,Username:this.username,ForceAliasCreation:i,ClientMetadata:o};this.getUserContextData()&&(a.UserContextData=this.getUserContextData()),this.client.request("ConfirmSignUp",a,function(c){return c?s(c,null):s(null,"SUCCESS")});},e.sendCustomChallengeAnswer=function(n,i,s){var o=this,a={};a.USERNAME=this.username,a.ANSWER=n;var c=new Ve(this.pool.getUserPoolName());this.getCachedDeviceKeyAndPassword(),this.deviceKey!=null&&(a.DEVICE_KEY=this.deviceKey);var u={ChallengeName:"CUSTOM_CHALLENGE",ChallengeResponses:a,ClientId:this.pool.getClientId(),Session:this.Session,ClientMetadata:s};this.getUserContextData()&&(u.UserContextData=this.getUserContextData()),this.client.request("RespondToAuthChallenge",u,function(l,d){return l?i.onFailure(l):o.authenticateUserInternal(d,c,i)});},e.sendMFACode=function(n,i,s,o){var a=this,c={};c.USERNAME=this.username,c.SMS_MFA_CODE=n;var u=s||"SMS_MFA";u==="SOFTWARE_TOKEN_MFA"&&(c.SOFTWARE_TOKEN_MFA_CODE=n),this.deviceKey!=null&&(c.DEVICE_KEY=this.deviceKey);var l={ChallengeName:u,ChallengeResponses:c,ClientId:this.pool.getClientId(),Session:this.Session,ClientMetadata:o};this.getUserContextData()&&(l.UserContextData=this.getUserContextData()),this.client.request("RespondToAuthChallenge",l,function(d,h){if(d)return i.onFailure(d);var p=h.ChallengeName;if(p==="DEVICE_SRP_AUTH"){a.getDeviceResponse(i);return}if(a.signInUserSession=a.getCognitoUserSession(h.AuthenticationResult),a.cacheTokens(),h.AuthenticationResult.NewDeviceMetadata==null)return i.onSuccess(a.signInUserSession);var g=new Ve(a.pool.getUserPoolName());g.generateHashDevice(h.AuthenticationResult.NewDeviceMetadata.DeviceGroupKey,h.AuthenticationResult.NewDeviceMetadata.DeviceKey,function(m){if(m)return i.onFailure(m);var y={Salt:J.Buffer.from(g.getSaltDevices(),"hex").toString("base64"),PasswordVerifier:J.Buffer.from(g.getVerifierDevices(),"hex").toString("base64")};a.verifierDevices=y.PasswordVerifier,a.deviceGroupKey=h.AuthenticationResult.NewDeviceMetadata.DeviceGroupKey,a.randomPassword=g.getRandomPassword(),a.client.request("ConfirmDevice",{DeviceKey:h.AuthenticationResult.NewDeviceMetadata.DeviceKey,AccessToken:a.signInUserSession.getAccessToken().getJwtToken(),DeviceSecretVerifierConfig:y,DeviceName:Ji},function(b,E){return b?i.onFailure(b):(a.deviceKey=h.AuthenticationResult.NewDeviceMetadata.DeviceKey,a.cacheDeviceKeyAndPassword(),E.UserConfirmationNecessary===true?i.onSuccess(a.signInUserSession,E.UserConfirmationNecessary):i.onSuccess(a.signInUserSession))});});});},e.changePassword=function(n,i,s,o){if(!(this.signInUserSession!=null&&this.signInUserSession.isValid()))return s(new Error("User is not authenticated"),null);this.client.request("ChangePassword",{PreviousPassword:n,ProposedPassword:i,AccessToken:this.signInUserSession.getAccessToken().getJwtToken(),ClientMetadata:o},function(a){return a?s(a,null):s(null,"SUCCESS")});},e.enableMFA=function(n){if(this.signInUserSession==null||!this.signInUserSession.isValid())return n(new Error("User is not authenticated"),null);var i=[],s={DeliveryMedium:"SMS",AttributeName:"phone_number"};i.push(s),this.client.request("SetUserSettings",{MFAOptions:i,AccessToken:this.signInUserSession.getAccessToken().getJwtToken()},function(o){return o?n(o,null):n(null,"SUCCESS")});},e.setUserMfaPreference=function(n,i,s){if(this.signInUserSession==null||!this.signInUserSession.isValid())return s(new Error("User is not authenticated"),null);this.client.request("SetUserMFAPreference",{SMSMfaSettings:n,SoftwareTokenMfaSettings:i,AccessToken:this.signInUserSession.getAccessToken().getJwtToken()},function(o){return o?s(o,null):s(null,"SUCCESS")});},e.disableMFA=function(n){if(this.signInUserSession==null||!this.signInUserSession.isValid())return n(new Error("User is not authenticated"),null);var i=[];this.client.request("SetUserSettings",{MFAOptions:i,AccessToken:this.signInUserSession.getAccessToken().getJwtToken()},function(s){return s?n(s,null):n(null,"SUCCESS")});},e.deleteUser=function(n,i){var s=this;if(this.signInUserSession==null||!this.signInUserSession.isValid())return n(new Error("User is not authenticated"),null);this.client.request("DeleteUser",{AccessToken:this.signInUserSession.getAccessToken().getJwtToken(),ClientMetadata:i},function(o){return o?n(o,null):(s.clearCachedUser(),n(null,"SUCCESS"))});},e.updateAttributes=function(n,i,s){var o=this;if(this.signInUserSession==null||!this.signInUserSession.isValid())return i(new Error("User is not authenticated"),null);this.client.request("UpdateUserAttributes",{AccessToken:this.signInUserSession.getAccessToken().getJwtToken(),UserAttributes:n,ClientMetadata:s},function(a,c){return a?i(a,null):o.getUserData(function(){return i(null,"SUCCESS",c)},{bypassCache:true})});},e.getUserAttributes=function(n){if(!(this.signInUserSession!=null&&this.signInUserSession.isValid()))return n(new Error("User is not authenticated"),null);this.client.request("GetUser",{AccessToken:this.signInUserSession.getAccessToken().getJwtToken()},function(i,s){if(i)return n(i,null);for(var o=[],a=0;a<s.UserAttributes.length;a++){var c={Name:s.UserAttributes[a].Name,Value:s.UserAttributes[a].Value},u=new Se(c);o.push(u);}return n(null,o)});},e.getMFAOptions=function(n){if(!(this.signInUserSession!=null&&this.signInUserSession.isValid()))return n(new Error("User is not authenticated"),null);this.client.request("GetUser",{AccessToken:this.signInUserSession.getAccessToken().getJwtToken()},function(i,s){return i?n(i,null):n(null,s.MFAOptions)});},e.createGetUserRequest=function(){return this.client.promisifyRequest("GetUser",{AccessToken:this.signInUserSession.getAccessToken().getJwtToken()})},e.refreshSessionIfPossible=function(n){var i=this;return n===void 0&&(n={}),new Promise(function(s){var o=i.signInUserSession.getRefreshToken();o&&o.getToken()?i.refreshSession(o,s,n.clientMetadata):s();})},e.getUserData=function(n,i){var s=this;if(!(this.signInUserSession!=null&&this.signInUserSession.isValid()))return this.clearCachedUserData(),n(new Error("User is not authenticated"),null);var o=this.getUserDataFromCache();if(!o){this.fetchUserData().then(function(a){n(null,a);}).catch(n);return}if(this.isFetchUserDataAndTokenRequired(i)){this.fetchUserData().then(function(a){return s.refreshSessionIfPossible(i).then(function(){return a})}).then(function(a){return n(null,a)}).catch(n);return}try{n(null,JSON.parse(o));return}catch(a){this.clearCachedUserData(),n(a,null);return}},e.getUserDataFromCache=function(){var n=this.storage.getItem(this.userDataKey);return n},e.isFetchUserDataAndTokenRequired=function(n){var i=n||{},s=i.bypassCache,o=s===void 0?false:s;return o},e.fetchUserData=function(){var n=this;return this.createGetUserRequest().then(function(i){return n.cacheUserData(i),i})},e.deleteAttributes=function(n,i){var s=this;if(!(this.signInUserSession!=null&&this.signInUserSession.isValid()))return i(new Error("User is not authenticated"),null);this.client.request("DeleteUserAttributes",{UserAttributeNames:n,AccessToken:this.signInUserSession.getAccessToken().getJwtToken()},function(o){return o?i(o,null):s.getUserData(function(){return i(null,"SUCCESS")},{bypassCache:true})});},e.resendConfirmationCode=function(n,i){var s={ClientId:this.pool.getClientId(),Username:this.username,ClientMetadata:i};this.client.request("ResendConfirmationCode",s,function(o,a){return o?n(o,null):n(null,a)});},e.getSession=function(n,i){if(i===void 0&&(i={}),this.username==null)return n(new Error("Username is null. Cannot retrieve a new session"),null);if(this.signInUserSession!=null&&this.signInUserSession.isValid())return n(null,this.signInUserSession);var s="CognitoIdentityServiceProvider."+this.pool.getClientId()+"."+this.username,o=s+".idToken",a=s+".accessToken",c=s+".refreshToken",u=s+".clockDrift";if(this.storage.getItem(o)){var l=new it({IdToken:this.storage.getItem(o)}),d=new nt({AccessToken:this.storage.getItem(a)}),h=new st({RefreshToken:this.storage.getItem(c)}),p=parseInt(this.storage.getItem(u),0)||0,g={IdToken:l,AccessToken:d,RefreshToken:h,ClockDrift:p},m=new ot(g);if(m.isValid())return this.signInUserSession=m,n(null,this.signInUserSession);if(!h.getToken())return n(new Error("Cannot retrieve a new session. Please authenticate."),null);this.refreshSession(h,n,i.clientMetadata);}else n(new Error("Local storage is missing an ID Token, Please authenticate"),null);},e.refreshSession=function(n,i,s){var o=this,a=this.pool.wrapRefreshSessionCallback?this.pool.wrapRefreshSessionCallback(i):i,c={};c.REFRESH_TOKEN=n.getToken();var u="CognitoIdentityServiceProvider."+this.pool.getClientId(),l=u+".LastAuthUser";if(this.storage.getItem(l)){this.username=this.storage.getItem(l);var d=u+"."+this.username+".deviceKey";this.deviceKey=this.storage.getItem(d),c.DEVICE_KEY=this.deviceKey;}var h={ClientId:this.pool.getClientId(),AuthFlow:"REFRESH_TOKEN_AUTH",AuthParameters:c,ClientMetadata:s};this.getUserContextData()&&(h.UserContextData=this.getUserContextData()),this.client.requestWithRetry("InitiateAuth",h,function(p,g){if(p)return p.code==="NotAuthorizedException"&&o.clearCachedUser(),a(p,null);if(g){var m=g.AuthenticationResult;return Object.prototype.hasOwnProperty.call(m,"RefreshToken")||(m.RefreshToken=n.getToken()),o.signInUserSession=o.getCognitoUserSession(m),o.cacheTokens(),a(null,o.signInUserSession)}});},e.cacheTokens=function(){var n="CognitoIdentityServiceProvider."+this.pool.getClientId(),i=n+"."+this.username+".idToken",s=n+"."+this.username+".accessToken",o=n+"."+this.username+".refreshToken",a=n+"."+this.username+".clockDrift",c=n+".LastAuthUser";this.storage.setItem(i,this.signInUserSession.getIdToken().getJwtToken()),this.storage.setItem(s,this.signInUserSession.getAccessToken().getJwtToken()),this.storage.setItem(o,this.signInUserSession.getRefreshToken().getToken()),this.storage.setItem(a,""+this.signInUserSession.getClockDrift()),this.storage.setItem(c,this.username);},e.cacheUserData=function(n){this.storage.setItem(this.userDataKey,JSON.stringify(n));},e.clearCachedUserData=function(){this.storage.removeItem(this.userDataKey);},e.clearCachedUser=function(){this.clearCachedTokens(),this.clearCachedUserData();},e.cacheDeviceKeyAndPassword=function(){var n="CognitoIdentityServiceProvider."+this.pool.getClientId()+"."+this.username,i=n+".deviceKey",s=n+".randomPasswordKey",o=n+".deviceGroupKey";this.storage.setItem(i,this.deviceKey),this.storage.setItem(s,this.randomPassword),this.storage.setItem(o,this.deviceGroupKey);},e.getCachedDeviceKeyAndPassword=function(){var n="CognitoIdentityServiceProvider."+this.pool.getClientId()+"."+this.username,i=n+".deviceKey",s=n+".randomPasswordKey",o=n+".deviceGroupKey";this.storage.getItem(i)&&(this.deviceKey=this.storage.getItem(i),this.randomPassword=this.storage.getItem(s),this.deviceGroupKey=this.storage.getItem(o));},e.clearCachedDeviceKeyAndPassword=function(){var n="CognitoIdentityServiceProvider."+this.pool.getClientId()+"."+this.username,i=n+".deviceKey",s=n+".randomPasswordKey",o=n+".deviceGroupKey";this.storage.removeItem(i),this.storage.removeItem(s),this.storage.removeItem(o);},e.clearCachedTokens=function(){var n="CognitoIdentityServiceProvider."+this.pool.getClientId(),i=n+"."+this.username+".idToken",s=n+"."+this.username+".accessToken",o=n+"."+this.username+".refreshToken",a=n+".LastAuthUser",c=n+"."+this.username+".clockDrift";this.storage.removeItem(i),this.storage.removeItem(s),this.storage.removeItem(o),this.storage.removeItem(a),this.storage.removeItem(c);},e.getCognitoUserSession=function(n){var i=new it(n),s=new nt(n),o=new st(n),a={IdToken:i,AccessToken:s,RefreshToken:o};return new ot(a)},e.forgotPassword=function(n,i){var s={ClientId:this.pool.getClientId(),Username:this.username,ClientMetadata:i};this.getUserContextData()&&(s.UserContextData=this.getUserContextData()),this.client.request("ForgotPassword",s,function(o,a){return o?n.onFailure(o):typeof n.inputVerificationCode=="function"?n.inputVerificationCode(a):n.onSuccess(a)});},e.confirmPassword=function(n,i,s,o){var a={ClientId:this.pool.getClientId(),Username:this.username,ConfirmationCode:n,Password:i,ClientMetadata:o};this.getUserContextData()&&(a.UserContextData=this.getUserContextData()),this.client.request("ConfirmForgotPassword",a,function(c){return c?s.onFailure(c):s.onSuccess("SUCCESS")});},e.getAttributeVerificationCode=function(n,i,s){if(this.signInUserSession==null||!this.signInUserSession.isValid())return i.onFailure(new Error("User is not authenticated"));this.client.request("GetUserAttributeVerificationCode",{AttributeName:n,AccessToken:this.signInUserSession.getAccessToken().getJwtToken(),ClientMetadata:s},function(o,a){return o?i.onFailure(o):typeof i.inputVerificationCode=="function"?i.inputVerificationCode(a):i.onSuccess("SUCCESS")});},e.verifyAttribute=function(n,i,s){if(this.signInUserSession==null||!this.signInUserSession.isValid())return s.onFailure(new Error("User is not authenticated"));this.client.request("VerifyUserAttribute",{AttributeName:n,Code:i,AccessToken:this.signInUserSession.getAccessToken().getJwtToken()},function(o){return o?s.onFailure(o):s.onSuccess("SUCCESS")});},e.getDevice=function(n){if(this.signInUserSession==null||!this.signInUserSession.isValid())return n.onFailure(new Error("User is not authenticated"));this.client.request("GetDevice",{AccessToken:this.signInUserSession.getAccessToken().getJwtToken(),DeviceKey:this.deviceKey},function(i,s){return i?n.onFailure(i):n.onSuccess(s)});},e.forgetSpecificDevice=function(n,i){if(this.signInUserSession==null||!this.signInUserSession.isValid())return i.onFailure(new Error("User is not authenticated"));this.client.request("ForgetDevice",{AccessToken:this.signInUserSession.getAccessToken().getJwtToken(),DeviceKey:n},function(s){return s?i.onFailure(s):i.onSuccess("SUCCESS")});},e.forgetDevice=function(n){var i=this;this.forgetSpecificDevice(this.deviceKey,{onFailure:n.onFailure,onSuccess:function(o){return i.deviceKey=null,i.deviceGroupKey=null,i.randomPassword=null,i.clearCachedDeviceKeyAndPassword(),n.onSuccess(o)}});},e.setDeviceStatusRemembered=function(n){if(this.signInUserSession==null||!this.signInUserSession.isValid())return n.onFailure(new Error("User is not authenticated"));this.client.request("UpdateDeviceStatus",{AccessToken:this.signInUserSession.getAccessToken().getJwtToken(),DeviceKey:this.deviceKey,DeviceRememberedStatus:"remembered"},function(i){return i?n.onFailure(i):n.onSuccess("SUCCESS")});},e.setDeviceStatusNotRemembered=function(n){if(this.signInUserSession==null||!this.signInUserSession.isValid())return n.onFailure(new Error("User is not authenticated"));this.client.request("UpdateDeviceStatus",{AccessToken:this.signInUserSession.getAccessToken().getJwtToken(),DeviceKey:this.deviceKey,DeviceRememberedStatus:"not_remembered"},function(i){return i?n.onFailure(i):n.onSuccess("SUCCESS")});},e.listDevices=function(n,i,s){if(this.signInUserSession==null||!this.signInUserSession.isValid())return s.onFailure(new Error("User is not authenticated"));var o={AccessToken:this.signInUserSession.getAccessToken().getJwtToken(),Limit:n};i&&(o.PaginationToken=i),this.client.request("ListDevices",o,function(a,c){return a?s.onFailure(a):s.onSuccess(c)});},e.globalSignOut=function(n){var i=this;if(this.signInUserSession==null||!this.signInUserSession.isValid())return n.onFailure(new Error("User is not authenticated"));this.client.request("GlobalSignOut",{AccessToken:this.signInUserSession.getAccessToken().getJwtToken()},function(s){return s?n.onFailure(s):(i.clearCachedUser(),n.onSuccess("SUCCESS"))});},e.signOut=function(n){var i=this;if(!n||typeof n!="function"){this.cleanClientData();return}this.getSession(function(s,o){if(s)return n(s);i.revokeTokens(function(a){i.cleanClientData(),n(a);});});},e.revokeTokens=function(n){if(n===void 0&&(n=function(){}),typeof n!="function")throw new Error("Invalid revokeTokenCallback. It should be a function.");if(!this.signInUserSession){var s=new Error("User is not authenticated");return n(s)}if(!this.signInUserSession.getAccessToken()){var o=new Error("No Access token available");return n(o)}var a=this.signInUserSession.getRefreshToken().getToken(),c=this.signInUserSession.getAccessToken();if(this.isSessionRevocable(c)&&a)return this.revokeToken({token:a,callback:n});n();},e.isSessionRevocable=function(n){if(n&&typeof n.decodePayload=="function")try{var i=n.decodePayload(),s=i.origin_jti;return !!s}catch{}return false},e.cleanClientData=function(){this.signInUserSession=null,this.clearCachedUser();},e.revokeToken=function(n){var i=n.token,s=n.callback;this.client.requestWithRetry("RevokeToken",{Token:i,ClientId:this.pool.getClientId()},function(o){if(o)return s(o);s();});},e.sendMFASelectionAnswer=function(n,i){var s=this,o={};o.USERNAME=this.username,o.ANSWER=n;var a={ChallengeName:"SELECT_MFA_TYPE",ChallengeResponses:o,ClientId:this.pool.getClientId(),Session:this.Session};this.getUserContextData()&&(a.UserContextData=this.getUserContextData()),this.client.request("RespondToAuthChallenge",a,function(c,u){if(c)return i.onFailure(c);if(s.Session=u.Session,n==="SMS_MFA")return i.mfaRequired(u.ChallengeName,u.ChallengeParameters);if(n==="SOFTWARE_TOKEN_MFA")return i.totpRequired(u.ChallengeName,u.ChallengeParameters)});},e.getUserContextData=function(){var n=this.pool;return n.getUserContextData(this.username)},e.associateSoftwareToken=function(n){var i=this;this.signInUserSession!=null&&this.signInUserSession.isValid()?this.client.request("AssociateSoftwareToken",{AccessToken:this.signInUserSession.getAccessToken().getJwtToken()},function(s,o){return s?n.onFailure(s):n.associateSecretCode(o.SecretCode)}):this.client.request("AssociateSoftwareToken",{Session:this.Session},function(s,o){return s?n.onFailure(s):(i.Session=o.Session,n.associateSecretCode(o.SecretCode))});},e.verifySoftwareToken=function(n,i,s){var o=this;this.signInUserSession!=null&&this.signInUserSession.isValid()?this.client.request("VerifySoftwareToken",{AccessToken:this.signInUserSession.getAccessToken().getJwtToken(),UserCode:n,FriendlyDeviceName:i},function(a,c){return a?s.onFailure(a):s.onSuccess(c)}):this.client.request("VerifySoftwareToken",{Session:this.Session,UserCode:n,FriendlyDeviceName:i},function(a,c){if(a)return s.onFailure(a);o.Session=c.Session;var u={};u.USERNAME=o.username;var l={ChallengeName:"MFA_SETUP",ClientId:o.pool.getClientId(),ChallengeResponses:u,Session:o.Session};o.getUserContextData()&&(l.UserContextData=o.getUserContextData()),o.client.request("RespondToAuthChallenge",l,function(d,h){return d?s.onFailure(d):(o.signInUserSession=o.getCognitoUserSession(h.AuthenticationResult),o.cacheTokens(),s.onSuccess(o.signInUserSession))});});},t})();Xe(zi());function at(){}at.prototype.userAgent=Gi();var Qi=function(e){var r=at.category?" "+at.category:"",n=at.framework?" framework/"+at.framework:"",i=""+at.prototype.userAgent+r+n;return i};function Al(t,e){t.prototype=Object.create(e.prototype),t.prototype.constructor=t,bt(t,e);}function un(t){var e=typeof Map=="function"?new Map:void 0;return un=function(n){if(n===null||!vl(n))return n;if(typeof n!="function")throw new TypeError("Super expression must either be null or a function");if(e!==void 0){if(e.has(n))return e.get(n);e.set(n,i);}function i(){return Sl(n,arguments,ln(this).constructor)}return i.prototype=Object.create(n.prototype,{constructor:{value:i,enumerable:false,writable:true,configurable:true}}),bt(i,n)},un(t)}function Sl(t,e,r){if(Xi())return Reflect.construct.apply(null,arguments);var n=[null];n.push.apply(n,e);var i=new(t.bind.apply(t,n));return r&&bt(i,r.prototype),i}function Xi(){try{var t=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}));}catch{}return (Xi=function(){return !!t})()}function vl(t){try{return Function.toString.call(t).indexOf("[native code]")!==-1}catch{return typeof t=="function"}}function bt(t,e){return bt=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(r,n){return r.__proto__=n,r},bt(t,e)}function ln(t){return ln=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(e){return e.__proto__||Object.getPrototypeOf(e)},ln(t)}var Rl=(function(t){function e(r,n,i,s){var o;return o=t.call(this,r)||this,o.code=n,o.name=i,o.statusCode=s,o}return Al(e,t),e})(un(Error)),Zi=(function(){function t(r,n,i){this.endpoint=n||"https://cognito-idp."+r+".amazonaws.com/";var s=i||{},o=s.credentials;this.fetchOptions=o?{credentials:o}:{};}var e=t.prototype;return e.promisifyRequest=function(n,i){var s=this;return new Promise(function(o,a){s.request(n,i,function(c,u){c?a(new Rl(c.message,c.code,c.name,c.statusCode)):o(u);});})},e.requestWithRetry=function(n,i,s){var o=this,a=5*1e3;Ul(function(c){return new Promise(function(u,l){o.request(n,c,function(d,h){d?l(d):u(h);});})},[i],a).then(function(c){return s(null,c)}).catch(function(c){return s(c)});},e.request=function(n,i,s){var o={"Content-Type":"application/x-amz-json-1.1","X-Amz-Target":"AWSCognitoIdentityProviderService."+n,"X-Amz-User-Agent":Qi(),"Cache-Control":"no-store"},a=Object.assign({},this.fetchOptions,{headers:o,method:"POST",mode:"cors",body:JSON.stringify(i)}),c;fetch(this.endpoint,a).then(function(l){return c=l,l},function(l){throw l instanceof TypeError?new Error("Network error"):l}).then(function(l){return l.json().catch(function(){return {}})}).then(function(l){if(c.ok)return s(null,l);var d=(l.__type||l.code).split("#").pop(),h=new Error(l.message||l.Message||null);return h.name=d,h.code=d,s(h)}).catch(function(l){if(c&&c.headers&&c.headers.get("x-amzn-errortype"))try{var d=c.headers.get("x-amzn-errortype").split(":")[0],h=new Error(c.status?c.status.toString():null);return h.code=d,h.name=d,h.statusCode=c.status,s(h)}catch{return s(l)}else l instanceof Error&&l.message==="Network error"&&(l.code="NetworkError");return s(l)});},t})();var cr={debug:function(){}};var Tl=function(e){var r="nonRetryable";return e&&e[r]};function es(t,e,r,n){if(n===void 0&&(n=1),typeof t!="function")throw Error("functionToRetry must be a function");return cr.debug(t.name+" attempt #"+n+" with args: "+JSON.stringify(e)),t.apply(void 0,e).catch(function(i){if(cr.debug("error on "+t.name,i),Tl(i))throw cr.debug(t.name+" non retryable error",i),i;var s=r(n,e,i);if(cr.debug(t.name+" retrying in "+s+" ms"),s!==false)return new Promise(function(o){return setTimeout(o,s)}).then(function(){return es(t,e,r,n+1)});throw i})}function Il(t){var e=100,r=100;return function(n){var i=Math.pow(2,n)*e+r*Math.random();return i>t?false:i}}function Ul(t,e,r){return es(t,e,Il(r))}var xl=55,dn=(function(){function t(r,n){var i=r||{},s=i.UserPoolId,o=i.ClientId,a=i.endpoint,c=i.fetchOptions,u=i.AdvancedSecurityDataCollectionFlag;if(!s||!o)throw new Error("Both UserPoolId and ClientId are required.");if(s.length>xl||!/^[\w-]+_[0-9a-zA-Z]+$/.test(s))throw new Error("Invalid UserPoolId format.");var l=s.split("_")[0];this.userPoolId=s,this.clientId=o,this.client=new Zi(l,a,c),this.advancedSecurityDataCollectionFlag=u!==false,this.storage=r.Storage||new ar().getStorage(),n&&(this.wrapRefreshSessionCallback=n);}var e=t.prototype;return e.getUserPoolId=function(){return this.userPoolId},e.getUserPoolName=function(){return this.getUserPoolId().split("_")[1]},e.getClientId=function(){return this.clientId},e.signUp=function(n,i,s,o,a,c){var u=this,l={ClientId:this.clientId,Username:n,Password:i,UserAttributes:s,ValidationData:o,ClientMetadata:c};this.getUserContextData(n)&&(l.UserContextData=this.getUserContextData(n)),this.client.request("SignUp",l,function(d,h){if(d)return a(d,null);var p={Username:n,Pool:u,Storage:u.storage},g={user:new ke(p),userConfirmed:h.UserConfirmed,userSub:h.UserSub,codeDeliveryDetails:h.CodeDeliveryDetails};return a(null,g)});},e.getCurrentUser=function(){var n="CognitoIdentityServiceProvider."+this.clientId+".LastAuthUser",i=this.storage.getItem(n);if(i){var s={Username:i,Pool:this,Storage:this.storage};return new ke(s)}return null},e.getUserContextData=function(n){if(!(typeof AmazonCognitoAdvancedSecurityData>"u")){var i=AmazonCognitoAdvancedSecurityData;if(this.advancedSecurityDataCollectionFlag){var s=i.getData(n,this.userPoolId,this.clientId);if(s){var o={EncodedData:s};return o}}return {}}},t})();function ur(t){for(var e=1;e<arguments.length;e++){var r=arguments[e];for(var n in r)n!=="__proto__"&&(t[n]=r[n]);}return t}var Cl={read:function(t){return t[0]==='"'&&(t=t.slice(1,-1)),t.replace(/(%[\dA-F]{2})+/gi,decodeURIComponent)},write:function(t){return encodeURIComponent(t).replace(/%(2[346BF]|3[AC-F]|40|5[BDE]|60|7[BCD])/g,decodeURIComponent)}};function fn(t,e){function r(i,s,o){if(!(typeof document>"u")){o=ur({},e,o),typeof o.expires=="number"&&(o.expires=new Date(Date.now()+o.expires*864e5)),o.expires&&(o.expires=o.expires.toUTCString()),i=encodeURIComponent(i).replace(/%(2[346B]|5E|60|7C)/g,decodeURIComponent).replace(/[()]/g,escape);var a="";for(var c in o)o[c]&&(a+="; "+c,o[c]!==true&&(a+="="+o[c].split(";")[0]));return document.cookie=i+"="+t.write(s,i)+a}}function n(i){if(!(typeof document>"u"||arguments.length&&!i)){for(var s=document.cookie?document.cookie.split("; "):[],o={},a=0;a<s.length;a++){var c=s[a].split("="),u=c.slice(1).join("=");try{var l=decodeURIComponent(c[0]);if(l in o||(o[l]=t.read(u,l)),i===l)break}catch{}}return i?o[i]:o}}return Object.create({set:r,get:n,remove:function(i,s){r(i,"",ur({},s,{expires:-1}));},withAttributes:function(i){return fn(this.converter,ur({},this.attributes,i))},withConverter:function(i){return fn(ur({},this.converter,i),this.attributes)}},{attributes:{value:Object.freeze(e)},converter:{value:Object.freeze(t)}})}fn(Cl,{path:"/"});var f=class extends Error{constructor(e,r){if(Array.isArray(e)&&e.length<=2){let n=e[1];if(e.length>2)for(let i=2;i<e.length&&typeof e[i]=="string";i++)n+=e[i];super((n||"Something went wrong.").trim()),this.name=r?.name||"SKAPI",this.code=r?.code||e[0]||"ERROR",r?.cause&&(this.cause=r.cause);}else super((e?.message||(typeof e=="string"?e:"Something went wrong.")).trim()),typeof e=="string"?(this.name=r?.name||"SKAPI",this.code=r?.code||"ERROR",r?.cause&&(this.cause=r.cause)):e instanceof Error?(this.cause=e,this.name=e.name,e.hasOwnProperty("code")&&(this.code=e.code)):typeof e=="object"&&e?.code&&e?.message&&(this.name=r?.name||"SKAPI",this.code=r?.code||"ERROR",this.cause=e?.cause);}};var Ne="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",hn=BigInt(Ne.length),kl=2*1024*1024,Nl=["aud","cognito:username","event_id","exp","iat","iss","jti","origin_jti","secret_key","token_use"],ts={auth_time:"log",sub:"user_id"},Ol=["0","1","2","3","4","5","6","7","8","9","a","b","c","d","e","f","g","h","i","j","k","l"],os=["us31","us72","ap51","ap22","ap41","eu71","ap21","us32","us71","af51","ap31","ap43","ap23","ap42","ca01","eu01","eu72","eu51","eu73","eu11","me51","sa31"],rs=typeof TextEncoder<"u"?new TextEncoder:null;function Fl(){if(typeof globalThis<"u")return globalThis.Buffer}function W(t){if(rs)return rs.encode(t);let e=unescape(encodeURIComponent(t)),r=new Uint8Array(e.length);for(let n=0;n<e.length;n++)r[n]=e.charCodeAt(n);return r}function gn(t){if(t instanceof Uint8Array)return t;if(typeof t=="string")return W(t);if(typeof ArrayBuffer<"u"&&t instanceof ArrayBuffer)return new Uint8Array(t);if(typeof ArrayBuffer<"u"&&ArrayBuffer.isView(t))return new Uint8Array(t.buffer,t.byteOffset,t.byteLength);if(Array.isArray(t))return Uint8Array.from(t);let e=Fl();if(e)return new Uint8Array(e.from(t));throw new Error("No byte conversion available in this environment.")}var A=class A{static hash(e){typeof e!="string"&&(console.warn("coercing non-string value to empty string"),e="");let r=A.sb(e),n=1732584193,i=-271733879,s=-1732584194,o=271733878,a,c,u,l;for(let d=0;d<r.length;d+=16)a=n,c=i,u=s,l=o,n=A.ff(n,i,s,o,r[d],7,-680876936),o=A.ff(o,n,i,s,r[d+1],12,-389564586),s=A.ff(s,o,n,i,r[d+2],17,606105819),i=A.ff(i,s,o,n,r[d+3],22,-1044525330),n=A.ff(n,i,s,o,r[d+4],7,-176418897),o=A.ff(o,n,i,s,r[d+5],12,1200080426),s=A.ff(s,o,n,i,r[d+6],17,-1473231341),i=A.ff(i,s,o,n,r[d+7],22,-45705983),n=A.ff(n,i,s,o,r[d+8],7,1770035416),o=A.ff(o,n,i,s,r[d+9],12,-1958414417),s=A.ff(s,o,n,i,r[d+10],17,-42063),i=A.ff(i,s,o,n,r[d+11],22,-1990404162),n=A.ff(n,i,s,o,r[d+12],7,1804603682),o=A.ff(o,n,i,s,r[d+13],12,-40341101),s=A.ff(s,o,n,i,r[d+14],17,-1502002290),i=A.ff(i,s,o,n,r[d+15],22,1236535329),n=A.gg(n,i,s,o,r[d+1],5,-165796510),o=A.gg(o,n,i,s,r[d+6],9,-1069501632),s=A.gg(s,o,n,i,r[d+11],14,643717713),i=A.gg(i,s,o,n,r[d],20,-373897302),n=A.gg(n,i,s,o,r[d+5],5,-701558691),o=A.gg(o,n,i,s,r[d+10],9,38016083),s=A.gg(s,o,n,i,r[d+15],14,-660478335),i=A.gg(i,s,o,n,r[d+4],20,-405537848),n=A.gg(n,i,s,o,r[d+9],5,568446438),o=A.gg(o,n,i,s,r[d+14],9,-1019803690),s=A.gg(s,o,n,i,r[d+3],14,-187363961),i=A.gg(i,s,o,n,r[d+8],20,1163531501),n=A.gg(n,i,s,o,r[d+13],5,-1444681467),o=A.gg(o,n,i,s,r[d+2],9,-51403784),s=A.gg(s,o,n,i,r[d+7],14,1735328473),i=A.gg(i,s,o,n,r[d+12],20,-1926607734),n=A.hh(n,i,s,o,r[d+5],4,-378558),o=A.hh(o,n,i,s,r[d+8],11,-2022574463),s=A.hh(s,o,n,i,r[d+11],16,1839030562),i=A.hh(i,s,o,n,r[d+14],23,-35309556),n=A.hh(n,i,s,o,r[d+1],4,-1530992060),o=A.hh(o,n,i,s,r[d+4],11,1272893353),s=A.hh(s,o,n,i,r[d+7],16,-155497632),i=A.hh(i,s,o,n,r[d+10],23,-1094730640),n=A.hh(n,i,s,o,r[d+13],4,681279174),o=A.hh(o,n,i,s,r[d],11,-358537222),s=A.hh(s,o,n,i,r[d+3],16,-722521979),i=A.hh(i,s,o,n,r[d+6],23,76029189),n=A.hh(n,i,s,o,r[d+9],4,-640364487),o=A.hh(o,n,i,s,r[d+12],11,-421815835),s=A.hh(s,o,n,i,r[d+15],16,530742520),i=A.hh(i,s,o,n,r[d+2],23,-995338651),n=A.ii(n,i,s,o,r[d],6,-198630844),o=A.ii(o,n,i,s,r[d+7],10,1126891415),s=A.ii(s,o,n,i,r[d+14],15,-1416354905),i=A.ii(i,s,o,n,r[d+5],21,-57434055),n=A.ii(n,i,s,o,r[d+12],6,1700485571),o=A.ii(o,n,i,s,r[d+3],10,-1894986606),s=A.ii(s,o,n,i,r[d+10],15,-1051523),i=A.ii(i,s,o,n,r[d+1],21,-2054922799),n=A.ii(n,i,s,o,r[d+8],6,1873313359),o=A.ii(o,n,i,s,r[d+15],10,-30611744),s=A.ii(s,o,n,i,r[d+6],15,-1560198380),i=A.ii(i,s,o,n,r[d+13],21,1309151649),n=A.ii(n,i,s,o,r[d+4],6,-145523070),o=A.ii(o,n,i,s,r[d+11],10,-1120210379),s=A.ii(s,o,n,i,r[d+2],15,718787259),i=A.ii(i,s,o,n,r[d+9],21,-343485551),n=A.ad(n,a),i=A.ad(i,c),s=A.ad(s,u),o=A.ad(o,l);return A.rh(n)+A.rh(i)+A.rh(s)+A.rh(o)}static rh(e){let r="";for(let n=0;n<=3;n++)r+=A.alphabet.charAt(e>>n*8+4&15)+A.alphabet.charAt(e>>n*8&15);return r}static ad(e,r){let n=(e&65535)+(r&65535);return (e>>16)+(r>>16)+(n>>16)<<16|n&65535}static rl(e,r){return e<<r|e>>>32-r}static cm(e,r,n,i,s,o){return A.ad(A.rl(A.ad(A.ad(r,e),A.ad(i,o)),s),n)}static ff(e,r,n,i,s,o,a){return A.cm(r&n|~r&i,e,r,s,o,a)}static gg(e,r,n,i,s,o,a){return A.cm(r&i|n&~i,e,r,s,o,a)}static hh(e,r,n,i,s,o,a){return A.cm(r^n^i,e,r,s,o,a)}static ii(e,r,n,i,s,o,a){return A.cm(n^(r|~i),e,r,s,o,a)}static sb(e){let r,n=(e.length+8>>6)+1,i=new Array(n*16);for(r=0;r<n*16;r++)i[r]=0;for(r=0;r<e.length;r++)i[r>>2]|=e.charCodeAt(r)<<r%4*8;return i[r>>2]|=128<<r%4*8,i[n*16-2]=e.length*8,i}};A.alphabet="0123456789abcdef";var z=A;function as(t){if(t===0)return Ne[0];let e="";for(;t>0;)e=Ne[t%62]+e,t=Math.floor(t/62);return e}function fe(t){return t.split("").reverse().reduce((e,r,n)=>e+Ne.indexOf(r)*62**n,0)}function We(t=6){let e="",r="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",n=r.length,i=0;for(;i<t;)e+=r.charAt(Math.floor(Math.random()*n)),i+=1;return e}function pn(){return typeof window>"u"||!!window?._runningInNodeJS}function re(){return !pn()&&typeof document<"u"&&typeof document.createElement=="function"}function lr(t){let e;try{e=JSON.stringify(t);}catch{throw new f("Invalid data type.",{code:"INVALID_REQUEST"})}if(new Blob([e]).size>kl)throw new f("Data should not exceed 2MB",{code:"INVALID_REQUEST"})}function ns(t){return t===""||t==="on"||t==="true"}function is(t){return t==="false"}function ss(t,e,r){e.name&&r(t,e.name,e.value);}var dr=re(),Ll=typeof SubmitEvent<"u",Ml=typeof HTMLFormElement<"u";function K(t,e,r){let n={},i=[];function s(c,u,l){if(e?.ignoreEmpty&&l==="")return;if(e?.nullIfEmpty&&l===""&&(l=null),typeof r=="function"){let p=r(u,l);p!==void 0&&(l=p);}let d=u.split("[").map(p=>{let g=p.replace("]",""),m=Number(g);return !isNaN(m)&&!g.includes(".")?g=m:(g[0]==='"'&&g[g.length-1]==='"'||g[0]==="'"&&g[g.length-1]==="'")&&(g=g.replace(/"/g,"").replace(/'/g,"")),g}),h=c;if(typeof d[0]=="number")throw new f("Form key cannot start with an array index.",{code:"INVALID_REQUEST"});for(let p=0;p<d.length;p++){let g=d[p];p<d.length-1?(h[g]===void 0&&(typeof d[p+1]=="number"?h[g]=[]:h[g]={}),h=h[g]):h[g]===void 0?h[g]=l:Array.isArray(h[g])?h[g].push(l):h[g]=[h[g],l];}}function o(c,u,l){if(l instanceof File)c.push({name:u,file:l});else if(l instanceof FileList&&l&&l.length>0)for(let d=0;d<=l.length-1;d++){let h=l.item(d);h&&c.push({name:u,file:h});}}let a=c=>{c.name&&(c.type==="number"?c.value&&s(n,c.name,Number(c.value)):c.type==="checkbox"||c.type==="radio"?c.checked?c.type==="checkbox"&&c.value===""||ns(c.value)?s(n,c.name,true):is(c.value)?s(n,c.name,false):c.value&&s(n,c.name,c.value):c.type==="checkbox"&&(ns(c.value)?s(n,c.name,false):is(c.value)&&s(n,c.name,true)):c.type==="file"?c.files&&c.files.length>0&&o(i,c.name,c.files):s(n,c.name,c.value));};if(dr&&(t instanceof HTMLInputElement||t instanceof HTMLSelectElement||t instanceof HTMLTextAreaElement))return a(t),lr(n),{data:n,files:i};if(dr&&t instanceof FormData){for(let c of t.entries()){let u=c[0],l=c[1];if(l instanceof File||l instanceof FileList)o(i,u,l);else if(l instanceof Blob){let d=l;if(d.type==="application/json")try{let h=JSON.parse(d.text());s(n,u,h);}catch{s(n,u,d);}}else s(n,u,l);}return lr(n),{data:n,files:i}}if(dr&&Ll&&t instanceof SubmitEvent&&(t=t.target),dr&&Ml&&t instanceof HTMLFormElement){let c=t.querySelectorAll("input"),u=t.querySelectorAll("select"),l=t.querySelectorAll("textarea");for(let d=0;d<u.length;d++)ss(n,u[d],s);for(let d=0;d<l.length;d++)ss(n,l[d],s);for(let d=0;d<c.length;d++)a(c[d]);return lr(n),{data:n,files:i}}return lr(t),{data:t,files:i}}function wt(t){let e={};for(let r in t){let n=t[r];if(!Nl.includes(r))if(ts[r])e[ts[r]]=n;else if(r.includes("custom:"))e[r.replace("custom:","")]=n;else if(r==="address"){let i=n;if(i&&typeof i=="object"&&Object.keys(i).length){if(i?.formatted)try{e[r]=JSON.parse(i.formatted);}catch{e[r]=i.formatted;}}else e[r]=i;}else e[r]=n;}for(let r of ["address_public","birthdate_public","email_public","gender_public","phone_number_public","access_group"])r.includes("_public")?e.hasOwnProperty(r.split("_")[0])?e[r]=e.hasOwnProperty(r)?!!Number(e[r]):false:delete e[r]:e[r]=e.hasOwnProperty(r)?Number(e[r]):0;for(let r of ["email","phone_number"])e.hasOwnProperty(r)?e[r+"_verified"]=e[r+"_verified"]===true:delete e[r+"_verified"];return e}function mn(t){if(t=Wl(t),t.split("-").length===7){let e=t.split("-"),r,n;try{r=os[fe(e[1][0])],n=e.slice(2).join("-");}catch{throw new Error("INVALID_PARAMETER: Service ID is invalid: "+t)}if(!r)throw new Error("INVALID_PARAMETER: Service ID is invalid: "+t);return {service:r+e[0]+e[1].slice(1),owner:n}}return {service:t,owner:""}}function yn(t,e){let r=os.indexOf(t.slice(0,4)),n=Ol[r],s=`${t.slice(4,-4)}-${n}${t.slice(-4)}-${e}`;return Hl(s)}function Vl(t){let e=0n;for(let r of t){let n=Ne.indexOf(r);if(n<0)throw new Error(`INVALID_PARAMETER: Invalid base62 character: ${r}`);e=e*hn+BigInt(n);}return e}function ql(t,e=1){if(t<0n)throw new Error("INVALID_PARAMETER: Negative values are not supported.");if(t===0n)return "0".repeat(Math.max(1,e));let r="",n=t;for(;n>0n;){let i=Number(n%hn);r=Ne[i]+r,n/=hn;}return r.length<e&&(r="0".repeat(e-r.length)+r),r}function Bl(t){if(t===0n)return Uint8Array.from([0]);let e=[],r=t;for(;r>0n;)e.push(Number(r&0xffn)),r>>=8n;return e.reverse(),Uint8Array.from(e)}function $l(t){let e=0n;for(let r of t)e=(e<<8n)+BigInt(r);return e}function Kl(t){let e=String(t).replace(/-/g,"");if(!/^[0-9a-fA-F]{32}$/.test(e))throw new Error("INVALID_PARAMETER: Invalid UUID format.");let r=new Uint8Array(16);for(let n=0;n<16;n++)r[n]=parseInt(e.slice(n*2,n*2+2),16);return r}function jl(t){let e=Array.from(gn(t),r=>r.toString(16).padStart(2,"0")).join("");return [e.slice(0,8),e.slice(8,12),e.slice(12,16),e.slice(16,20),e.slice(20)].join("-")}function Hl(t){let e=String(t);if(e.split("-").length===2)return e;let r=e.match(/^([0-9A-Za-z]+)-([0-9A-Za-z]+)-([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/);if(!r)throw new Error("INVALID_PARAMETER: Input must match <base62>-<base62>-<uuid>.");let[,n,i,s]=r;if(n.length<2)throw new Error("INVALID_PARAMETER: The first part must contain at least 2 characters.");if(i.length>=Ne.length)throw new Error("INVALID_PARAMETER: The middle section is too long to encode.");let o=n.slice(0,2),a=n.slice(2),c=i+o,u=Ne[i.length]+a+c,l=Kl(s),d=ql($l(l));return `${u}-${d}`}function Wl(t){let e=String(t);if(e.split("-").length!==2)return e;let r=e.split("-");if(r.length!==2||!r[0]||!r[1])throw new Error("INVALID_PARAMETER: Corrupt compressed token: "+e);let[n,i]=r,s=Ne.indexOf(n[0]);if(s<0)throw new Error("INVALID_PARAMETER: Corrupt compressed token: "+e);let o=n.slice(1),a=s+2;if(o.length<a)throw new Error("INVALID_PARAMETER: Corrupt compressed token: "+e);let c=o.slice(0,o.length-a),u=o.slice(o.length-a),l=u.slice(s),d=u.slice(0,s),h=l+c;if(!/^[0-9A-Za-z]+$/.test(h)||!/^[0-9A-Za-z]+$/.test(d))throw new Error("INVALID_PARAMETER: Corrupt compressed token: "+e);let p=Vl(i),g=Bl(p);if(g.length>16)throw new Error("INVALID_PARAMETER: Corrupt compressed token: "+e);let m=new Uint8Array(16);m.set(g,16-g.length);let y=jl(m);return `${h}-${d}-${y}`}function Et(t){if(typeof TextDecoder<"u")return new TextDecoder().decode(t);let e="";for(let r=0;r<t.length;r++)e+=String.fromCharCode(t[r]);return decodeURIComponent(escape(e))}function _n(...t){let e=0;for(let i of t)e+=i.length;let r=new Uint8Array(e),n=0;for(let i of t)r.set(i,n),n+=i.length;return r}function At(t,e,r=[],n=null){let i=["string","number","boolean","object","array","function","null","undefined"];function s(g){return g!==null&&typeof g=="object"&&!Array.isArray(g)}function o(g){return s(g)}function a(g){return Array.isArray(g)}function c(g){return typeof g=="string"&&i.indexOf(g)!==-1}function u(g){return Array.isArray(g)?"array":g===null?"null":typeof g}function l(g){try{return JSON.stringify(g)}catch{return String(g)}}function d(g){if(c(g))return `Type<${g}>`;if(typeof g=="function")return "custom validator";try{return JSON.stringify(g,(m,y)=>typeof y=="function"?"custom validator":y)}catch{return String(g)}}function h(g,m){return m==="array"?Array.isArray(g):m==="object"?s(g):m==="null"?g===null:m==="undefined"?typeof g>"u":typeof g===m}function p(g){return n===null?g:`${n}[${g}]`}if(typeof e>"u")throw new Error('Argument "struct" is required.');if(typeof e=="function")return e(t);if(o(e)){if(!s(t))throw new Error(`Data schema does not match:
207
+ `+JSON.stringify(t,null,2));for(let g of Object.keys(e)){let m=p(g);if(Object.prototype.hasOwnProperty.call(t,g))t[g]=At(t[g],e[g],r,m);else {if(r.indexOf(m)!==-1)throw new Error(`Key "${m}" is required.`);let y=e[g];a(y)&&y.length>1&&typeof y[y.length-1]=="function"&&(t[g]=y[y.length-1]());}}return t}if(a(e)){let g=false;if(e.length===1&&!a(e[0])&&!o(e[0])){let m=e[0];if(!Array.isArray(t))throw new Error(`Type <${u(t)}> is invalid in "${n}". Expected a list.`);for(let y=0;y<t.length;y++){let b=t[y];if(c(m)){if(!h(b,m))throw new Error(`Type <${u(b)}> is invalid in "${n}". Expected a list of Type <${m}>.`)}else if(typeof m=="function")t[y]=m(b);else if(b!==m)throw new Error(`Value ${l(b)} is invalid in "${n}". Expected a list of ${l(m)}.`)}g=true;}else if(Array.isArray(t)&&e.every(y=>!a(y)&&y!=="array")){for(let y=0;y<t.length;y++){let b=false,E="";for(let v of e)try{t[y]=At(t[y],v,r,n),b=!0;break}catch(x){typeof v=="function"&&(E=x?.message||String(x));}if(!b&&E)throw new Error(E);if(!b){let v=e.map(d).join(", ");throw new Error(`${l(t[y])} is invalid in "${n}". allowed types or values are: ${v}.`)}}g=true;}else {let y="";for(let b of e)try{t=At(t,b,r,n),g=!0;break}catch(E){typeof b=="function"&&(y=E?.message||String(E));}if(!g&&y)throw new Error(y)}if(!g){let m=e.map(d).join(", ");throw new Error(`${l(t)} is invalid in "${n}". allowed types or values are: ${m}.`)}return t}if(c(e)&&h(t,e)||t===e)return t;throw new Error(`${l(t)} is invalid in "${n}". allowed type or value is: ${d(e)}.`)}function Gl(t,e="User ID"){let r=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;if(t){if(typeof t!="string")throw new f(`${e} should be type: string.`,{code:"INVALID_PARAMETER"});if(!t.match(r))throw new f(`${e} is invalid.`,{code:"INVALID_PARAMETER"})}else throw new f(`${e} is empty.`,{code:"INVALID_PARAMETER"});return t}function Jl(t){if(t&&(typeof t!="string"||t.charAt(0)!=="+"||isNaN(Number(t.substring(1)))))throw new f('"phone_number" is invalid. The format should be "+00123456789". Type: string.',{code:"INVALID_PARAMETER"});return t||""}function Yl(t){if(t){if(typeof t!="string")throw new f('"birthdate" is invalid. The format should be "yyyy-mm-dd". Type: string.',{code:"INVALID_PARAMETER"});{let e=new RegExp(/([12]\d{3}-(0[1-9]|1[0-2])-(0[1-9]|[12]\d|3[01]))/);if(t.length!==10||t.split("-").length!==3||!e.test(t))throw new f('"birthdate" is invalid. The format should be "yyyy-mm-dd". Type: string.',{code:"INVALID_PARAMETER"})}}return t||""}function zl(t){if(t){if(typeof t!="string")throw new f('"password" should be type: string.',{code:"INVALID_PARAMETER"});if(t.length<6)throw new f('"password" should be at least 6 characters.',{code:"INVALID_PARAMETER"});if(t.length>60)throw new f('"password" can be up to 60 characters max.',{code:"INVALID_PARAMETER"})}else throw new f('"password" is required.',{code:"INVALID_PARAMETER"});return t}function Ql(t,e="email"){if(t){if(typeof t!="string")throw new f(`"${e}"should be type: string.`,{code:"INVALID_PARAMETER"});if(t.length<5)throw new f(`"${e}" should be at least 5 characters.`,{code:"INVALID_PARAMETER"});if(/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/.test(t)&&(t=t.trim(),t.split("@")[1].split(".").length>=2))return t.toLowerCase()}else throw new f(`"${e}" is required.`,{code:"INVALID_PARAMETER"});throw new f(`"${t}" is an invalid email.`,{code:"INVALID_PARAMETER"})}function Xl(t){let e=typeof window<"u",r=(()=>{let i=e&&window.location.origin||null;return i&&i.slice(-1)==="/"&&(i=i.slice(0,-1)),i})(),n=i=>{if(typeof i=="string"){if(i==="*")return "*";{let s=i.trim();if(s[0]==="/"&&r){if(r.slice(0,5)==="file:")throw new f(`"${i}" is an invalid url. Relative URL does not work on local file system. Use full URL string.`,{code:"INVALID_PARAMETER"});s=r+s;}else if(s[0]==="."&&r){if(r.slice(0,5)==="file:")throw new f(`"${i}" is an invalid url. Relative URL does not work on local file system. Use full URL string.`,{code:"INVALID_PARAMETER"});let a=e?window.location.href.split("?")[0]:"";a.slice(-1)!=="/"&&(a+="/"),s=a+s.slice(1);}let o;try{o=new URL(s);}catch{throw new f(`"${i}" is an invalid url.`,{code:"INVALID_PARAMETER"})}if(o.protocol)return o.href}}throw new f(`"${i}" is an invalid url.`,{code:"INVALID_PARAMETER"})};return Array.isArray(t)?t.map(i=>n(i)):n(t)}function Zl(t,e,r=[],n){let i=K(t,n),s=i.data;e.service="string",e.owner="string";let o={};for(let a in e)if(s&&typeof s=="object"&&!Array.isArray(s)&&s.hasOwnProperty(a))if(typeof s[a]=="function")o[a]=s[a];else try{o[a]=JSON.parse(JSON.stringify(s[a]));}catch{o[a]=s[a];}n?.precall&&n.precall({data:o,files:i?.files||[]});try{return At(o,e,r)}catch(a){throw new f(a.message,{code:"INVALID_PARAMETER"})}}var _={UserId:Gl,PhoneNumber:Jl,Birthdate:Yl,Password:zl,Email:Ql,Url:Xl,Params:Zl};var ne="skapi.enc.v1",ls=6e5,St=12,fr=null,ct=null;function ds(){return new f("Encryption requires Web Crypto, which needs a secure context (https, or localhost) in the browser, or Node 18 or newer. A page served over plain http has crypto.getRandomValues but crypto.subtle is undefined.",{code:"NOT_SUPPORTED"})}function fs(){if(ct)return ct;let t=typeof globalThis<"u"?globalThis:void 0;if(t?.crypto?.subtle&&typeof t.crypto.getRandomValues=="function")return ct=t.crypto,ct;try{let e=typeof yt=="function"?yt("crypto"):null;if(e?.webcrypto?.subtle)return ct=e.webcrypto,ct}catch{}throw ds()}function he(){if(fr)return fr;let t=fs();if(!t.subtle)throw ds();return fr=t.subtle,fr}function wn(){try{return he(),!0}catch{return false}}function ie(t){let e=fs(),r=new Uint8Array(t),n=65536;for(let i=0;i<t;i+=n)e.getRandomValues(r.subarray(i,Math.min(i+n,t)));return r}function L(t){let e=gn(t),r;if(typeof Buffer<"u"&&typeof Buffer.from=="function")r=Buffer.from(e).toString("base64");else if(typeof btoa=="function"){let n="";for(let s=0;s<e.length;s+=32768)n+=String.fromCharCode.apply(null,Array.from(e.subarray(s,s+32768)));r=btoa(n);}else throw new f("No base64 encoder available in this environment.",{code:"NOT_SUPPORTED"});return r.replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function $(t){if(typeof t!="string")throw new f("Expected a base64url string.",{code:"INVALID_PARAMETER"});let e=t.replace(/-/g,"+").replace(/_/g,"/"),r=e.length%4;if(r===2)e+="==";else if(r===3)e+="=";else if(r===1)throw new f("Malformed base64url string.",{code:"INVALID_PARAMETER"});if(typeof Buffer<"u"&&typeof Buffer.from=="function"){let n=Buffer.from(e,"base64");return new Uint8Array(n.buffer,n.byteOffset,n.byteLength)}if(typeof atob=="function"){let n=atob(e),i=new Uint8Array(n.length);for(let s=0;s<n.length;s++)i[s]=n.charCodeAt(s);return i}throw new f("No base64 decoder available in this environment.",{code:"NOT_SUPPORTED"})}async function hr(t){let e=await he().digest("SHA-256",t);return new Uint8Array(e)}async function Tt(t,e,r,n){let i=he(),s=await i.importKey("raw",t,"HKDF",false,["deriveBits"]),o=await i.deriveBits({name:"HKDF",hash:"SHA-256",salt:e,info:r},s,n*8);return new Uint8Array(o)}async function lt(t,e,r,n){let i=he(),s=W(t.normalize("NFC")),o=await i.importKey("raw",s,"PBKDF2",false,["deriveBits"]),a=new Uint8Array(await i.deriveBits({name:"PBKDF2",salt:e,iterations:r,hash:"SHA-256"},o,256)),c=await Tt(a,e,n,32);q(a),q(s);let u=await pe(c);return q(c),u}async function pe(t){return he().importKey("raw",t,{name:"AES-GCM"},false,["encrypt","decrypt"])}async function hs(){let t=ie(32),e=await pe(t);return {bytes:t,key:e}}async function ge(t,e,r){let n=ie(St),i=await he().encrypt({name:"AES-GCM",iv:n,additionalData:r,tagLength:128},t,e);return {iv:n,ct:new Uint8Array(i)}}async function me(t,e,r,n){let i=await he().decrypt({name:"AES-GCM",iv:e,additionalData:n,tagLength:128},t,r);return new Uint8Array(i)}var gr={name:"ECDH",namedCurve:"P-256"};async function gs(){let t=he(),e=await t.generateKey(gr,true,["deriveBits"]),r=new Uint8Array(await t.exportKey("raw",e.publicKey)),n=new Uint8Array(await t.exportKey("pkcs8",e.privateKey)),i=await En(n);return {pubRaw:r,pkcs8:n,priv:i}}async function En(t){return he().importKey("pkcs8",t,gr,false,["deriveBits"])}async function ps(t){if(t.length!==65||t[0]!==4)throw new f("Malformed public key: expected a 65 byte uncompressed P-256 point.",{code:"INVALID_PARAMETER"});return he().importKey("raw",t,gr,false,[])}async function An(t){return L(await hr(t))}async function ms(t,e,r,n){let i=he(),s=await ps(t),o=await i.generateKey(gr,true,["deriveBits"]),a=new Uint8Array(await i.deriveBits({name:"ECDH",public:s},o.privateKey,256)),c=await Tt(a,new Uint8Array(32),r,32);q(a);let u=await pe(c);q(c);let{iv:l,ct:d}=await ge(u,e,n);return {epk:new Uint8Array(await i.exportKey("raw",o.publicKey)),iv:l,ct:d}}async function ys(t,e,r,n,i,s){let o=he(),a=await ps(e),c=new Uint8Array(await o.deriveBits({name:"ECDH",public:a},t,256)),u=await Tt(c,new Uint8Array(32),i,32);q(c);let l=await pe(u);return q(u),me(l,r,n,s)}function q(t){t&&t.length&&t.fill(0);}function ed(t,e){if(t.length!==e.length)return false;let r=0;for(let n=0;n<t.length;n++)r|=t[n]^e[n];return r===0}function Sn(t){return W(JSON.stringify(t))}function It(t,e,r){return _n(t,new Uint8Array([0]),W(e),new Uint8Array([0]),W(r))}var Ge="0123456789ABCDEFGHJKMNPQRSTVWXYZ",vt=16,cs=26,us=28;function _s(t){let e=2166136261;for(let r=0;r<t.length;r++)e^=t[r],e=e*16777619>>>0;return e&1023}function bs(t){if(t.length!==vt)throw new f(`A recovery code needs exactly ${vt} bytes.`,{code:"INVALID_PARAMETER"});let e="",r=0,n=0;for(let s=0;s<t.length;s++)for(r=r<<8|t[s],n+=8;n>=5;)n-=5,e+=Ge[r>>n&31];n>0&&(e+=Ge[r<<5-n&31]);let i=_s(t);return e+=Ge[i>>5&31]+Ge[i&31],(e.match(/.{1,4}/g)||[]).join("-")}function ws(t){if(typeof t!="string")throw new f("Recovery code should be a string.",{code:"INVALID_PARAMETER"});let e=t.toUpperCase().replace(/[\s\-_]/g,"").replace(/O/g,"0").replace(/[IL]/g,"1");if(e.length!==us)throw new f(`That does not look like a recovery code: expected ${us} characters, got ${e.length}.`,{code:"ENCRYPTION_BAD_RECOVERY_CODE"});let r=e.slice(0,cs),n=e.slice(cs),i=0,s=0,o=[];for(let u=0;u<r.length;u++){let l=Ge.indexOf(r[u]);if(l<0)throw new f(`That does not look like a recovery code: "${r[u]}" is not a valid character.`,{code:"ENCRYPTION_BAD_RECOVERY_CODE"});i=i<<5|l,s+=5,s>=8&&(s-=8,o.push(i>>s&255));}let a=new Uint8Array(o.slice(0,vt)),c=_s(a);if(n!==Ge[c>>5&31]+Ge[c&31])throw new f("That recovery code has a typo in it: the check characters do not match.",{code:"ENCRYPTION_BAD_RECOVERY_CODE"});return a}async function vn(t,e,r){let n=await Tt(t,e,r,32),i=await pe(n);return q(n),i}var bn=[83,75,69,78,67,70],Es=2,Rt=56,As=16,td=4*1024*1024;function Rn(t){if(!t||t.length<Rt)return false;for(let e=0;e<bn.length;e++)if(t[e]!==bn[e])return false;return true}function Je(t,e,r){t[e]=r>>>24&255,t[e+1]=r>>>16&255,t[e+2]=r>>>8&255,t[e+3]=r&255;}function ut(t,e){return (t[e]<<24>>>0)+(t[e+1]<<16)+(t[e+2]<<8)+t[e+3]}function rd(t,e,r){let n=Math.floor(r/4294967296);Je(t,e,n),Je(t,e+4,r>>>0);}function nd(t,e){return ut(t,e)*4294967296+ut(t,e+4)}async function Ss(t,e,r,n,i,s){let o=W(`${ne}|binfile|${r}|${n}|${i}|${s}`),a=await Tt(t,e,o,32),c=await pe(a);return q(a),c}async function vs(t){return (await hr(_n(W(`${ne}|dekid`),t))).subarray(0,8)}function Rs(t,e,r){return Sn([`${ne}|binchunk`,L(t),e,r])}function id(t,e,r,n,i,s){let o=new Uint8Array(Rt+s.length);return o.set(bn,0),o[6]=Es,o[7]=s.length?1:0,Je(o,8,t),Je(o,12,e),o.set(r,16),rd(o,32,n),o.set(i,40),Je(o,48,s.length),Je(o,52,0),s.length&&o.set(s,Rt),o}async function Ts(t,e,r,n,i=td){let s=ie(As),o=await Ss(t,s,r.service,r.owner,r.recordOwner,r.recordId),a=await vs(t),c=n?W(JSON.stringify(n)):new Uint8Array(0);if(c.length>4096)throw new f("Encrypted file metadata is too large.",{code:"INVALID_PARAMETER"});let u=e.length===0?1:Math.ceil(e.length/i),l=id(i,u,s,e.length,a,c),d=await hr(l),h=[],p=l.length;for(let y=0;y<u;y++){let b=e.subarray(y*i,Math.min((y+1)*i,e.length)),E=await ge(o,b,Rs(d,y,u));h.push(E),p+=4+E.iv.length+E.ct.length;}let g=new Uint8Array(p);g.set(l,0);let m=l.length;for(let y of h)Je(g,m,y.iv.length+y.ct.length),m+=4,g.set(y.iv,m),m+=y.iv.length,g.set(y.ct,m),m+=y.ct.length;return g}function sd(t){if(!Rn(t))throw new f("This file is not an encrypted skapi file.",{code:"INVALID_PARAMETER"});let e=ut(t,48),r=Rt+e;if(t.length<r)throw new f("Encrypted file header is truncated.",{code:"INVALID_REQUEST"});let n=null;return e&&(n=JSON.parse(Et(t.subarray(Rt,r)))),{version:t[6],chunkBytes:ut(t,8),count:ut(t,12),fileId:t.subarray(16,16+As),plainLen:nd(t,32),dekId:t.subarray(40,48),meta:n,headerLen:r}}async function Is(t,e,r){let n=sd(e);if(n.version!==Es)throw new f(`This file was encrypted by a different version of the SDK (container v${n.version}).`,{code:"NOT_SUPPORTED"});if(!n.count||!n.chunkBytes)throw new f("Encrypted file header is malformed.",{code:"INVALID_PARAMETER"});let i=await vs(t);if(!ed(i,n.dekId))throw new f("This file was encrypted under a previous data key for this record, so it can no longer be opened. It was most likely left behind by an interrupted access change.",{code:"ENCRYPTION_FILE_STALE_KEY"});let s=await Ss(t,n.fileId,r.service,r.owner,r.recordOwner,r.recordId),o=await hr(e.subarray(0,n.headerLen)),a=[],c=n.headerLen,u=0;for(let h=0;h<n.count;h++){if(c+4>e.length)throw new f("Encrypted file is truncated.",{code:"INVALID_REQUEST"});let p=ut(e,c);if(c+=4,p<St+16||c+p>e.length)throw new f("Encrypted file is truncated.",{code:"INVALID_REQUEST"});let g=await me(s,e.subarray(c,c+St),e.subarray(c+St,c+p),Rs(o,h,n.count));c+=p,a.push(g),u+=g.length;}let l=new Uint8Array(u),d=0;for(let h of a)l.set(h,d),d+=h.length;return {bytes:l,meta:n.meta}}var od="skapi__keyring",Pt="__skapi_enc__",Us=1,ad="skapi-enc",qe="keys",Tn=new WeakMap;function xs(t){if(!t)return null;if(t===true&&(t={}),typeof t!="object")throw new f('"options.encryption" should be a boolean or an object.',{code:"INVALID_PARAMETER"});let e=typeof t.iterations=="number"?t.iterations:ls;if(e<1e5)throw new f('"encryption.iterations" must be at least 100000.',{code:"INVALID_PARAMETER"});let r=t.trustPolicy==="strict"?"strict":"tofu";return {enabled:true,iterations:e,trustPolicy:r,persistDevice:t.persistDevice!==false,minPasswordLength:typeof t.minPasswordLength=="number"?t.minPasswordLength:0,withheld:t.withheld==="sentinel"?"sentinel":"null",recovery:t.recovery==="none"?"none":"code",table:typeof t.table=="string"&&t.table?t.table:od}}function F(){return Tn.get(this)||null}function Cs(t){if(!t){Tn.delete(this);return}Tn.set(this,{cfg:t,status:"locked",reason:"NO_SESSION_KEY",user_id:"",scope:"",mk:null,ikPriv:null,pubRaw:null,fpr:"",keyringRecordId:"",pins:{},dek:new Map,roll:new Set,ready:null,unlocking:false,pendingRecoveryCode:"",peerPub:new Map,peerInflight:new Map});}function In(){let t=F.call(this);if(t){t.user_id&&Mn.call(this,t).catch(()=>{}),t.ready=null,t.unlocking=false,t.pendingRecoveryCode="";for(let[,e]of t.dek)q(e.bytes);t.dek.clear(),t.roll.clear(),t.peerPub.clear(),t.peerInflight.clear(),t.pins={},t.mk=null,t.ikPriv=null,t.pubRaw=null,t.fpr="",t.keyringRecordId="",t.user_id="",t.status="locked",t.reason="NO_SESSION_KEY";}}function Ds(){let t=F.call(this);return t?{status:t.status,reason:t.status==="unlocked"?void 0:t.reason,user_id:t.user_id||void 0,fingerprint:t.fpr||void 0}:{status:"disabled"}}function ks(t,e){return typeof e=="string"&&e===t.cfg.table}function dt(){return `${this.service}/${this.owner}`}function Pn(t,e,r,n){let[i,s]=t.split("/");return Sn([ne,i,s,e,r,n])}function Ns(t,e,r,n,i){let[s,o]=t.split("/");return W(`${ne}|dekwrap|${s}|${o}|${e}|${r}|${n}|${i}`)}function Un(t){return t.anch==="uid"?t.uid:t.anch==="rid"?t.rid:""}function mr(t){return !!t&&typeof t=="object"&&!Array.isArray(t)&&typeof t[Pt]=="number"&&typeof t.ct=="string"&&typeof t.iv=="string"&&typeof t.own=="string"&&typeof t.anch=="string"&&!!t.k&&typeof t.k=="object"&&!Array.isArray(t.k)}var Os="__skapi_no_access__";function ye(t,e,r){if(t.withheld!=="sentinel")return null;let n={[Os]:true,reason:e};return r&&(n.recipients=r),Object.freeze(n)}function xn(t){return !!t&&typeof t=="object"&&t[Os]===true}async function cd(t,e,r){let n=e?.table,i=typeof n=="string"?n:n?.name;if(n&&(typeof n=="string"||n.access_group!==void 0))return {group:typeof n=="string"?0:Ps(n.access_group),table:i,record:null};if(!r)return {group:n?.access_group!==void 0?Ps(n.access_group):0,table:i,record:null};let s=t.dek.get(r);if(s)return {group:s.access_group,table:i,record:null};let o=await Ut.call(this,r);if(!o)throw new f(`Record "${r}" not found.`,{code:"NOT_EXISTS"});return {group:o.table.access_group,table:o.table.name,record:o}}async function Ut(t){let e=/^[a-zA-Z0-9]+$/.test(t)?{record_id:t}:{unique_id:t};return (await this.getRecords(e,{limit:1}))?.list?.[0]||null}function Ps(t){return t==="private"||t==="**"?"private":t==="public"?0:t==="authorized"?1:t==="admin"?99:typeof t=="number"?t:0}async function Cn(t,e,r){let n=F.call(this);if(!n)return {send:t,plain:t,encrypted:false,omit:false};let i=e?.record_id||"",s=i,o=e?.unique_id||"",{group:a,table:c,record:u}=await cd.call(this,n,e,s);if(a!=="private"){if(s){let C=n.dek.get(s);C&&(q(C.bytes),n.dek.delete(s));}if(!r&&i){let C=u||await Ut.call(this,i);if(C&&C.encrypted){if(C.encrypted.status==="failed")throw new f(`Cannot make record "${i}" non-private: its current contents could not be decrypted (${C.encrypted.reason}), so they cannot be written back in the clear. Unlock encryption, or supply the record's data with the access group change.`,{code:"ENCRYPTION_LOCKED"});return {send:C.data,plain:C.data,encrypted:false,omit:false}}}return {send:t,plain:t,encrypted:false,omit:!r}}if(ks(n,c))return {send:t,plain:t,encrypted:false,omit:false};if(n.ready&&!n.unlocking)try{await n.ready;}catch{}if(!r)return {send:t,plain:t,encrypted:false,omit:true};if(xn.call(this,t))throw new f("This record's data could not be decrypted by this session, so it cannot be written back. Writing it would replace the record with the placeholder.",{code:"ENCRYPTION_CANNOT_REWRITE_WITHHELD"});if(n.status!=="unlocked"||!n.mk)throw new f("Encryption is enabled but locked, so this private record cannot be written. Call unlockEncryption({ password }) first, or the user must log in with their password.",{code:"ENCRYPTION_LOCKED"});if(t&&typeof t=="object"&&!Array.isArray(t)&&Object.prototype.hasOwnProperty.call(t,Pt))throw new f(`"${Pt}" is a reserved key in record data.`,{code:"INVALID_PARAMETER"});if(e?.service&&e.service!==this.service||e?.owner&&e.owner!==this.owner)throw new f("Encrypted records cannot be written to another project. The encryption key is derived per project, so a record written under one service and read under another could never be decrypted. Construct a separate Skapi instance for that project.",{code:"INVALID_REQUEST"});let l=this.user?.user_id;if(!l)throw new f("User login is required to write an encrypted record.",{code:"INVALID_REQUEST"});let d=dt.call(this),h=false;if(i&&n.roll.has(i)){h=true,n.roll.delete(i);let C=n.dek.get(i);n.dek.delete(i),C&&q(C.bytes);}let p=null;if(i&&!h&&(p=n.dek.get(i)||null,!p)){let C=u||await Ut.call(this,i);if(C&&(s=C.record_id||i,p=n.dek.get(s)||null,!o&&C.unique_id&&(o=C.unique_id),!p&&C.encrypted?.status==="failed"))throw new f(`Cannot update encrypted record "${i}": its current contents could not be decrypted (${C.encrypted.reason}), so its existing key wraps cannot be preserved. Updating anyway would revoke everyone it is shared with.`,{code:"ENCRYPTION_LOCKED"})}s===i&&p&&p.rid&&(s=p.rid),!o&&p&&p.anch==="uid"&&p.uid&&(o=p.uid);let g,m,y;if(p)g=p.bytes,m=p.key,y=Object.assign({},p.recipients);else {let C=await hs();g=C.bytes,m=C.key,y={};}let b=o?"uid":s?"rid":"new",E=b==="uid"?o:b==="rid"?s:"",v=Pn(d,l,b,E),x=It(v,l,"mk"),P=await ge(n.mk,g,x);y[l]={t:"mk",iv:L(P.iv),ct:L(P.ct)},p&&(p.anch!==b||Un(p)!==E)&&(y=await ud.call(this,n,g,y,d,l,b,E,v));let N=W(JSON.stringify(t===void 0?null:t)),O=await ge(m,N,v);q(N);let M={[Pt]:Us,enc:"A256GCM",kw:"ECDH-ES+A256GCM",anch:b,uid:o,rid:s,own:l,iv:L(O.iv),ct:L(O.ct),k:y},U=JSON.stringify(M).length;if(U>2*1024*1024)throw new f(`Encrypted record data is too large: once encrypted and base64 encoded it becomes ${U} bytes, over the ${2*1024*1024} byte limit. Encryption costs about 33% plus roughly 230 bytes per additional recipient.`,{code:"ENCRYPTED_DATA_TOO_LARGE"});return s&&n.dek.set(s,{bytes:g,key:m,recipients:y,anch:b,uid:o,rid:s,own:l,access_group:"private"}),{send:M,plain:t,encrypted:true,omit:false,dek:{bytes:g,key:m,recipients:y,anch:b,uid:o,rid:s,own:l,access_group:"private"}}}function Fs(t,e){let r=F.call(this);!r||!e||!t||r.dek.has(t)||r.dek.set(t,Object.assign({},e,{rid:t}));}async function ud(t,e,r,n,i,s,o,a){let c=Object.keys(r).filter(d=>d!==i);if(!c.length)return r;let u=await Vn.call(this,c),l={[i]:r[i]};for(let d of c){let h=u[d];h&&(l[d]=await Ls.call(this,e,h,n,o,i,d,a));}return l}async function Ls(t,e,r,n,i,s,o){let a=Ns(r,n,i,s,e.fpr),c=It(o,s,e.fpr),u=await ms(e.pubRaw,t,a,c);return {t:"ecdh",epk:L(u.epk),iv:L(u.iv),ct:L(u.ct),fpr:e.fpr}}async function Dn(t,e){if(!mr(t))return {value:t};if(e.access_group!=="private")return {value:t};let r=F.call(this);if(!r)return {value:null,flag:{status:"failed",reason:"ENCRYPTION_DISABLED"}};if(ks(r,e.table_name))return {value:t};if(t[Pt]!==Us)return {value:ye(r.cfg,"UNSUPPORTED_VERSION"),flag:{status:"failed",reason:"UNSUPPORTED_VERSION"}};if(r.ready&&!r.unlocking)try{await r.ready;}catch{}if(t.own!==e.user_id)return {value:ye(r.cfg,"BINDING_MISMATCH"),flag:{status:"failed",reason:"BINDING_MISMATCH"}};if(t.uid&&e.unique_id&&t.uid!==e.unique_id)return {value:ye(r.cfg,"BINDING_MISMATCH"),flag:{status:"failed",reason:"BINDING_MISMATCH"}};if(t.rid&&e.record_id&&t.rid!==e.record_id)return {value:ye(r.cfg,"BINDING_MISMATCH"),flag:{status:"failed",reason:"BINDING_MISMATCH"}};let n=this.user?.user_id,i=n?t.k[n]:null;if(!i)return {value:ye(r.cfg,"NOT_A_RECIPIENT",Object.keys(t.k)),flag:{status:"failed",reason:"NOT_A_RECIPIENT",recipients:Object.keys(t.k)}};if(r.status!=="unlocked"||!r.mk)return {value:ye(r.cfg,"NO_SESSION_KEY"),flag:{status:"failed",reason:"NO_SESSION_KEY"}};let s=dt.call(this),o=Un(t),a=Pn(s,t.own,t.anch,o),c;try{if(i.t==="mk")c=await me(r.mk,$(i.iv),$(i.ct),It(a,n,"mk"));else if(i.t==="ecdh"){if(!r.ikPriv)return {value:ye(r.cfg,"NO_SESSION_KEY"),flag:{status:"failed",reason:"NO_SESSION_KEY"}};c=await ys(r.ikPriv,$(i.epk),$(i.iv),$(i.ct),Ns(s,o,t.own,n,i.fpr),It(a,n,i.fpr));}else return {value:ye(r.cfg,"UNSUPPORTED_VERSION"),flag:{status:"failed",reason:"UNSUPPORTED_VERSION"}}}catch{return {value:ye(r.cfg,"BAD_KEY"),flag:{status:"failed",reason:"BAD_KEY"}}}let u,l;try{l=await pe(c),u=await me(l,$(t.iv),$(t.ct),a);}catch{return q(c),{value:ye(r.cfg,"CORRUPT"),flag:{status:"failed",reason:"CORRUPT"}}}let d;try{d=JSON.parse(Et(u));}catch{return q(u),q(c),{value:ye(r.cfg,"CORRUPT"),flag:{status:"failed",reason:"CORRUPT"}}}if(q(u),e.record_id){let h=r.dek.get(e.record_id);h?(h.bytes=c,h.key=l,h.recipients=t.k,h.anch=t.anch,h.uid=t.uid,h.own=t.own,h.access_group="private"):r.dek.set(e.record_id,{bytes:c,key:l,recipients:t.k,anch:t.anch,uid:t.uid,rid:e.record_id,own:t.own,access_group:"private"});}else q(c);return {value:d,flag:{status:"encrypted",recipients:Object.keys(t.k)}}}function xt(t,e){let[r,n]=t.split("/");return W(`${ne}|kek|${r}|${n}|${e}`)}function Ct(t,e,r,n){let[i,s]=t.split("/");return W(`${ne}|mk|${i}|${s}|${e}|PBKDF2-SHA256|${r}|${n}`)}function Ms(t,e){let[r,n]=t.split("/");return W(`${ne}|recovery|${r}|${n}|${e}`)}function Vs(t,e,r){let[n,i]=t.split("/");return W(`${ne}|rk|${n}|${i}|${e}|HKDF-SHA256|${r}`)}function qs(t,e){let[r,n]=t.split("/");return W(`${ne}|self|${r}|${n}|${e}`)}function Bs(t,e){let[r,n]=t.split("/");return W(`${ne}|ik|${r}|${n}|${e}`)}async function yr(t){let r=((await this.getRecords({table:{name:t.cfg.table,access_group:"private"},index:{name:"$user_id",value:this.user.user_id,condition:"="}},{limit:2}))?.list||[]).filter(n=>n.user_id===this.user.user_id);return r.length?(r.sort((n,i)=>n.uploaded-i.uploaded),r[0]):null}async function kn(t,e,r){let n=ie(vt),i=bs(n),s=ie(16),o=L(s),a=await vn(n,s,Ms(t,e)),c=await ge(a,r,Vs(t,e,o));return q(n),{code:i,wrap:{id:L(ie(6)),p:"recovery",kdf:{a:"HKDF-SHA256",s:o},iv:L(c.iv),ct:L(c.ct),created:Date.now()}}}async function ld(t,e,r,n){let i=ws(n),s=(r||[]).filter(o=>o.p==="recovery");s.sort((o,a)=>(a.created||0)-(o.created||0));for(let o of s)try{let a=await vn(i,$(o.kdf.s),Ms(t,e)),c=await me(a,$(o.iv),$(o.ct),Vs(t,e,o.kdf.s));return q(i),c}catch{}return q(i),null}async function dd(t,e,r,n,i){let s=ie(16),o=L(s),a=await lt(n,s,t.cfg.iterations,xt(e,r)),c=await ge(a,i,Ct(e,r,t.cfg.iterations,o));return {id:L(ie(6)),p:"password",kdf:{a:"PBKDF2-SHA256",it:t.cfg.iterations,s:o},iv:L(c.iv),ct:L(c.ct),created:Date.now()}}async function fd(t,e){let r=this.user.user_id,n=t.scope,i=ie(16),s=L(i),o=await lt(e,i,t.cfg.iterations,xt(n,r)),a=ie(32),c=await ge(o,a,Ct(n,r,t.cfg.iterations,s)),u=await pe(a),l=await gs(),d=await ge(u,l.pkcs8,Bs(n,r));q(l.pkcs8);let h=null;t.cfg.recovery==="code"&&(h=await kn(n,r,a));let p=await ge(u,a,qs(n,r));q(a);let g=await An(l.pubRaw),m=Date.now(),y=[{id:L(ie(6)),p:"password",kdf:{a:"PBKDF2-SHA256",it:t.cfg.iterations,s},iv:L(c.iv),ct:L(c.ct),created:m}];h&&y.push(h.wrap);let b={v:1,alg:"ECDH-P-256",user_id:r,wraps:y,ik:{iv:L(d.iv),ct:L(d.ct)},self:{iv:L(p.iv),ct:L(p.ct)},pub:L(l.pubRaw),fpr:g,pins:null,created:m,updated:m};await this.postRecord({v:1,alg:"ECDH-P-256",user_id:r,pub:L(l.pubRaw),fpr:g,created:m},{table:{name:t.cfg.table,access_group:"authorized"},index:{name:"pubkey",value:r}});let E=await this.postRecord(b,{table:{name:t.cfg.table,access_group:"private"}}),v=await yr.call(this,t);if(v&&v.record_id!==E.record_id){await $s.call(this,t,v,e);return}t.mk=u,t.ikPriv=l.priv,t.pubRaw=l.pubRaw,t.fpr=g,t.keyringRecordId=E.record_id,h&&(t.pendingRecoveryCode=h.code),t.user_id=r,t.pins={},t.status="unlocked",t.reason="";}async function $s(t,e,r){let n=this.user.user_id,i=t.scope,s=e.data;if(e.user_id!==n||s&&s.user_id&&s.user_id!==n)throw new f("The encryption keyring does not belong to this user.",{code:"ENCRYPTION_KEYRING_CORRUPT"});let a=(Array.isArray(s?.wraps)?s.wraps:[]).filter(l=>l.p==="password");if(!a.length)throw new f("The keyring has no password wrap.",{code:"ENCRYPTION_KEYRING_CORRUPT"});a.sort((l,d)=>(d.created||0)-(l.created||0));let c=null;for(let l of a)try{let d=$(l.kdf.s),h=await lt(r,d,l.kdf.it,xt(i,n));c=await me(h,$(l.iv),$(l.ct),Ct(i,n,l.kdf.it,l.kdf.s));break}catch{}if(!c)throw new f("Incorrect password: the encryption keyring could not be opened.",{code:"ENCRYPTION_BAD_PASSWORD"});let u=await pe(c);q(c),await Nn.call(this,t,e,u);}async function Nn(t,e,r){let n=this.user.user_id,i=e.data,s=await me(r,$(i.ik.iv),$(i.ik.ct),Bs(t.scope,n)),o=await En(s);q(s);let a={};if(i.pins&&typeof i.pins=="object"&&i.pins.ct)try{let c=await me(r,$(i.pins.iv),$(i.pins.ct),W(`${ne}|pins|${t.scope}|${n}`));a=JSON.parse(Et(c)),q(c);}catch{a={};}t.mk=r,t.ikPriv=o,t.pubRaw=$(i.pub),t.fpr=i.fpr,t.keyringRecordId=e.record_id,t.user_id=n,t.pins=a,t.status="unlocked",t.reason="";}async function _r(t){let e=F.call(this);if(!e||!this.user?.user_id)return;if(!wn()){e.status="locked",e.reason="NO_WEB_CRYPTO";return}if(this.user?.is_openid){e.status="locked",e.reason="OPENID_UNSUPPORTED";return}if(e.cfg.minPasswordLength&&t.length<e.cfg.minPasswordLength){e.status="locked",e.reason="WEAK_PASSWORD";return}e.scope=dt.call(this);let r=await yr.call(this,e);r?await $s.call(this,e,r,t):await fd.call(this,e,t),e.cfg.persistDevice&&await Gs.call(this,e).catch(()=>{});}async function Ks(t){await this.__connection;let e=F.call(this);if(!e)throw new f("Encryption is not enabled for this instance.",{code:"INVALID_REQUEST"});if(!this.user?.user_id)throw new f("User login is required.",{code:"INVALID_REQUEST"});if(!t?.password||typeof t.password!="string")throw new f('"password" is required.',{code:"INVALID_PARAMETER"});if(await _r.call(this,t.password),e.status!=="unlocked")throw new f(`Encryption could not be unlocked: ${e.reason}`,{code:"ENCRYPTION_LOCKED"});return {status:e.status}}async function js(t){let e=F.call(this);return e?(t?.forgetDevice&&await Mn.call(this,e).catch(()=>{}),In.call(this),this.__cached_requests={},{status:e.status}):{status:"disabled"}}async function Hs(t,e){let r=F.call(this);if(!r)return;if(r.status!=="unlocked"||!r.mk)throw new f("Encryption must be unlocked before changing the password, or the encryption keyring would be left wrapped under a password that no longer exists. Call unlockEncryption({ password }) first.",{code:"ENCRYPTION_LOCKED"});let i=(await this.getRecords({record_id:r.keyringRecordId},{limit:1}))?.list?.[0];if(!i)throw new f("The encryption keyring could not be read, so the password change was stopped before it could strand it.",{code:"ENCRYPTION_KEYRING_CORRUPT"});let s=this.user.user_id,o=i.data,a=(o.wraps||[]).filter(m=>m.p==="password");a.sort((m,y)=>(y.created||0)-(m.created||0));let c=null;for(let m of a)try{let y=await lt(t,$(m.kdf.s),m.kdf.it,xt(r.scope,s));c=await me(y,$(m.iv),$(m.ct),Ct(r.scope,s,m.kdf.it,m.kdf.s));break}catch{}if(!c)throw new f("Incorrect current password: the encryption keyring was not re-wrapped.",{code:"ENCRYPTION_BAD_PASSWORD"});let u=ie(16),l=L(u),d=await lt(e,u,r.cfg.iterations,xt(r.scope,s)),h=await ge(d,c,Ct(r.scope,s,r.cfg.iterations,l));q(c);let p=Date.now(),g=(o.wraps||[]).concat([{id:L(ie(6)),p:"password",kdf:{a:"PBKDF2-SHA256",it:r.cfg.iterations,s:l},iv:L(h.iv),ct:L(h.ct),created:p}]);await this.postRecord(Object.assign({},o,{wraps:g,updated:p}),{record_id:r.keyringRecordId});}async function Ws(){let t=F.call(this);if(!t||t.status!=="unlocked"||!t.keyringRecordId)return;let r=(await this.getRecords({record_id:t.keyringRecordId},{limit:1}))?.list?.[0];if(!r)return;let n=r.data,i=(n.wraps||[]).filter(o=>o.p==="password").sort((o,a)=>(a.created||0)-(o.created||0)),s=(n.wraps||[]).filter(o=>o.p!=="password");i.length<=1||await this.postRecord(Object.assign({},n,{wraps:[i[0]].concat(s),updated:Date.now()}),{record_id:t.keyringRecordId});}function On(){return typeof indexedDB<"u"&&!!indexedDB}function Fn(){return new Promise((t,e)=>{let r=indexedDB.open(ad,1);r.onupgradeneeded=()=>{let n=r.result;n.objectStoreNames.contains(qe)||n.createObjectStore(qe);},r.onsuccess=()=>t(r.result),r.onerror=()=>e(r.error);})}function Ln(t){return `${t.scope}#${this.user?.user_id}`}async function Gs(t){if(!On()||!t.mk)return;let e=await Fn();await new Promise((r,n)=>{let i=e.transaction(qe,"readwrite");i.objectStore(qe).put({mk:t.mk,keyringRecordId:t.keyringRecordId,saved:Date.now()},Ln.call(this,t)),i.oncomplete=()=>r(),i.onerror=()=>n(i.error);}),e.close();}async function hd(t){if(!On())return null;let e=await Fn(),r=await new Promise((n,i)=>{let o=e.transaction(qe,"readonly").objectStore(qe).get(Ln.call(this,t));o.onsuccess=()=>n(o.result||null),o.onerror=()=>i(o.error);});return e.close(),r&&r.mk?r:null}async function Mn(t){if(!On())return;let e=await Fn();await new Promise((r,n)=>{let i=e.transaction(qe,"readwrite");i.objectStore(qe).delete(Ln.call(this,t)),i.oncomplete=()=>r(),i.onerror=()=>n(i.error);}),e.close();}function Js(){let t=F.call(this);!t||t.ready||(t.unlocking=true,t.ready=gd.bind(this)().catch(()=>false).then(()=>{t.unlocking=false;}));}async function gd(){let t=F.call(this);if(!t||!this.user?.user_id||!t.cfg.persistDevice||!wn())return false;t.scope=dt.call(this);try{let e=await hd.call(this,t);if(!e)return !1;let r=await yr.call(this,t);return r?(await Nn.call(this,t,r,e.mk),!0):(await Mn.call(this,t).catch(()=>{}),!1)}catch{return t.status="locked",t.reason="NO_SESSION_KEY",false}}async function Vn(t){let e=F.call(this);if(!e)throw new f("Encryption is not enabled for this instance.",{code:"INVALID_REQUEST"});let r={},n=[],i=false;for(let s of t){let o=e.peerPub.get(s);o?r[s]=o:n.push(s);}return await Promise.all(n.map(async s=>{let o=e.peerInflight.get(s);o||(o=(async()=>{let u=((await this.getRecords({table:{name:e.cfg.table,access_group:"authorized"},index:{name:"$user_id",value:s,condition:"="}},{limit:10}))?.list||[]).filter(p=>p.user_id===s&&p.data?.pub);if(!u.length)return null;u.sort((p,g)=>g.uploaded-p.uploaded);let l=$(u[0].data.pub),d=await An(l),h=e.pins[s];if(h&&h!==d)throw new f(`The public key for user "${s}" has changed since it was first seen. This is expected if they reset their account, and is what a key substitution attack also looks like. Verify the new fingerprint out of band, then call pinPeerKey({ user_id, fingerprint }).`,{code:"ENCRYPTION_PEER_KEY_CHANGED"});if(!h){if(e.cfg.trustPolicy==="strict")throw new f(`No pinned key for user "${s}" and trustPolicy is "strict". Pin it first with pinPeerKey().`,{code:"ENCRYPTION_PEER_NOT_PINNED"});e.pins[s]=d,i=true;}return {pubRaw:l,fpr:d}})().finally(()=>e.peerInflight.delete(s)),e.peerInflight.set(s,o));let a=await o;a&&e.peerPub.set(s,a),r[s]=a;})),i&&await Zs.call(this,e).catch(()=>{}),r}async function Ys(t,e){let r=dt.call(this),n=t.dek.get(e);if(n)return {entry:n,scope:r};let i=await Ut.call(this,e);if(!i)throw new f(`Record "${e}" not found.`,{code:"NOT_EXISTS"});if(i.encrypted?.status==="failed"&&i.encrypted.reason==="DATA_UNAVAILABLE")throw new f(`Cannot change sharing on record "${e}": its data could not be read, so whether it is encrypted is unknown. Retry once the record reads normally.`,{code:"ENCRYPTION_DATA_UNAVAILABLE"});if(!i.encrypted)return null;if(i.user_id!==this.user?.user_id)throw new f("Only the record owner can share or revoke an encrypted record, because adding or removing a key wrap means writing the record.",{code:"ENCRYPTION_GRANT_REQUIRES_OWNER"});let s=t.dek.get(i.record_id)||t.dek.get(e);if(!s)throw new f(`Cannot change sharing on record "${e}": its data could not be decrypted`+(i.encrypted.reason?` (${i.encrypted.reason})`:"")+".",{code:"ENCRYPTION_LOCKED"});return {entry:s,scope:r}}async function qn(t,e){let r=F.call(this);if(!r)return;let n=await Ys.call(this,r,t);if(!n)return;let{entry:i,scope:s}=n,o=this.user.user_id;if(i.own!==o)throw new f("Only the record owner can share an encrypted record, because adding a key wrap means writing the record.",{code:"ENCRYPTION_GRANT_REQUIRES_OWNER"});let a=await Vn.call(this,e),c=e.filter(h=>!a[h]);if(c.length)throw new f(`These users have no encryption key yet, so they cannot be given access: ${c.join(", ")}. A user's key is created the first time they log in with encryption enabled.`,{code:"ENCRYPTION_RECIPIENT_HAS_NO_KEY"});let u=Un(i),l=Pn(s,i.own,i.anch,u),d=Object.assign({},i.recipients);for(let h of e)h!==o&&(d[h]=await Ls.call(this,i.bytes,a[h],s,u,i.own,h,l));await pd.call(this,r,t,i,d);}async function zs(t,e){let r=F.call(this);if(!r)return;let n=await Ys.call(this,r,t);if(!n)return;let{entry:i}=n,s=this.user.user_id;if(i.own!==s)throw new f("Only the record owner can revoke access to an encrypted record.",{code:"ENCRYPTION_GRANT_REQUIRES_OWNER"});let o=Object.keys(i.recipients).filter(u=>u===s?true:e?!e.includes(u):false).filter(u=>u!==s),a=await Ut.call(this,t);if(!a)throw new f(`Record "${t}" not found.`,{code:"NOT_EXISTS"});Qs(a,t);let c={};if(o.length){c=await Vn.call(this,o);let u=o.filter(l=>!c[l]);if(u.length)throw new f(`Cannot revoke on record "${t}": these users keep access but their encryption keys could not be read, so re-sharing after the key roll would fail and lock them out: ${u.join(", ")}.`,{code:"ENCRYPTION_RECIPIENT_HAS_NO_KEY"})}r.roll.add(a.record_id||t),await this.postRecord(a.data,{record_id:a.record_id||t,table:{name:a.table.name,access_group:"private"}}),o.length&&await qn.call(this,a.record_id||t,o);}function Qs(t,e){if(t?.encrypted?.status==="failed")throw new f(`Cannot change sharing on record "${e}": its current data could not be read (${t.encrypted.reason}), so re-writing the record would destroy it.`,{code:"ENCRYPTION_DATA_UNAVAILABLE"})}async function pd(t,e,r,n){let s=(await this.getRecords({record_id:e},{limit:1}))?.list?.[0];if(!s)throw new f(`Record "${e}" not found.`,{code:"NOT_EXISTS"});Qs(s,e),r.recipients=n,t.dek.set(e,r),await this.postRecord(s.data,{record_id:e});}async function Xs(t){let e=F.call(this);if(!e||e.status!=="unlocked")throw new f("Encryption is locked.",{code:"ENCRYPTION_LOCKED"});e.pins[t.user_id]=t.fingerprint,e.peerPub.delete(t.user_id),await Zs.call(this,e);}async function Zs(t){if(!t.mk||!t.keyringRecordId)return;let r=(await this.getRecords({record_id:t.keyringRecordId},{limit:1}))?.list?.[0];if(!r)return;let n=await ge(t.mk,W(JSON.stringify(t.pins)),W(`${ne}|pins|${t.scope}|${t.user_id}`));await this.postRecord(Object.assign({},r.data,{pins:{iv:L(n.iv),ct:L(n.ct)},updated:Date.now()}),{record_id:t.keyringRecordId});}function eo(){let t=F.call(this);if(!t||!t.pendingRecoveryCode)return null;let e=t.pendingRecoveryCode;return t.pendingRecoveryCode="",e}async function to(t){await this.__connection;let e=F.call(this);if(!e)throw new f("Encryption is not enabled for this instance.",{code:"INVALID_REQUEST"});if(!this.user?.user_id)throw new f("User login is required. Reset the password and log in first, then use the recovery code.",{code:"INVALID_REQUEST"});if(!t?.code||typeof t.code!="string")throw new f('"code" is required.',{code:"INVALID_PARAMETER"});e.scope=dt.call(this);let r=this.user.user_id,n=await yr.call(this,e);if(!n)throw new f("This account has no encryption keyring, so there is nothing to recover.",{code:"NOT_EXISTS"});let i=await ld(e.scope,r,n.data?.wraps||[],t.code);if(!i)throw new f("That recovery code did not open the keyring. Check it against the copy you saved when encryption was set up.",{code:"ENCRYPTION_BAD_RECOVERY_CODE"});let s=await pe(i);await Nn.call(this,e,n,s);let o=false,a=null,c=(n.data?.wraps||[]).slice();if(t.password&&(c=c.filter(u=>u.p!=="password"),c.push(await dd(e,e.scope,r,t.password,i)),o=true),e.cfg.recovery==="code"){let u=await kn(e.scope,r,i);c=c.filter(l=>l.p!=="recovery"),c.push(u.wrap),a=u.code;}return q(i),await this.postRecord(Object.assign({},n.data,{wraps:c,updated:Date.now()}),{record_id:n.record_id}),e.cfg.persistDevice&&await Gs.call(this,e).catch(()=>{}),{status:e.status,repaired:o,recoveryCode:a}}async function ro(){await this.__connection;let t=F.call(this);if(!t)throw new f("Encryption is not enabled for this instance.",{code:"INVALID_REQUEST"});if(t.status!=="unlocked"||!t.mk)throw new f("Encryption must be unlocked to issue a recovery code. Only someone who can already decrypt can create one.",{code:"ENCRYPTION_LOCKED"});if(t.cfg.recovery!=="code")throw new f('Recovery codes are disabled for this instance ("recovery" is "none").',{code:"INVALID_REQUEST"});let r=(await this.getRecords({record_id:t.keyringRecordId},{limit:1}))?.list?.[0];if(!r)throw new f("The encryption keyring could not be read.",{code:"ENCRYPTION_KEYRING_CORRUPT"});let n=r.data?.self;if(!n||!n.ct)throw new f("This keyring predates recovery-code rotation and cannot issue a new code. Use unlockWithRecoveryCode() with the existing code, which issues a replacement.",{code:"ENCRYPTION_KEYRING_CORRUPT"});let i=await me(t.mk,$(n.iv),$(n.ct),qs(t.scope,t.user_id)),s=await kn(t.scope,t.user_id,i);q(i);let o=(r.data.wraps||[]).filter(a=>a.p!=="recovery").concat([s.wrap]);return await this.postRecord(Object.assign({},r.data,{wraps:o,updated:Date.now()}),{record_id:t.keyringRecordId}),{recoveryCode:s.code}}var pr="__skenc__",no="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";function md(t){if(t===0)return "0";let e="";for(;t>0;)e=no[t%62]+e,t=Math.floor(t/62);return e}function yd(t){let e=0;for(let r of t){let n=no.indexOf(r);if(n<0)return NaN;e=e*62+n;}return e}function br(t){if(typeof t!="string")return null;let e=t.lastIndexOf(pr);if(e<0)return null;let r=yd(t.slice(e+pr.length));return Number.isFinite(r)?{key:t.slice(0,e),plainSize:r}:null}function Bn(t){try{let e=String(t).split("?")[0].split("/").slice(3);if(e.length<12||e[4]!=="records"||e[7]!=="bin")return null;let r=br(e[10]);return r?{recordId:e[5],recordOwner:e[3],filename:e[e.length-1],plainSize:r.plainSize}:null}catch{return null}}function io(t,e){return {service:this.service,owner:this.owner,recordOwner:e,recordId:t}}async function so(t,e,r){let n=F.call(this);if(!n||!t)return {key:e,file:r,encrypted:false};let i=n.dek.get(t);if(!i)return {key:e,file:r,encrypted:false};if(br(e))throw new f(`"${pr}" is reserved in an upload form key.`,{code:"INVALID_PARAMETER"});let s=new Uint8Array(await r.arrayBuffer()),o={n:r.name,t:r.type||"",lm:r.lastModified||0},a=await Ts(i.bytes,s,io.call(this,t,i.own),o);return q(s),{key:`${e}${pr}${md(r.size)}`,file:new File([a],r.name,{type:"application/octet-stream"}),encrypted:true}}async function oo(t,e){let r=F.call(this),n=Bn(t);if(!r||!n)return e;let i=r.dek.get(n.recordId);if(!i)throw new f(`Cannot open this file: the data key for record "${n.recordId}" is not available. Read the record first, and make sure encryption is unlocked.`,{code:"ENCRYPTION_LOCKED"});let s=new Uint8Array(await e.arrayBuffer());if(!Rn(s))throw new f("This file is marked as encrypted but its contents are not an encrypted container.",{code:"ENCRYPTION_FILE_CORRUPT"});let o=await Is(i.bytes,s,io.call(this,n.recordId,n.recordOwner)),a=o.meta&&o.meta.t||"application/octet-stream";return new Blob([o.bytes],{type:a})}var j=null;function $n(t){let e={tkid:"ticket_id",cond:"condition",stmp:"timestamp",actn:"action",cnt:"count",ttl:"time_to_live",plch:"placeholder",hash:"hash",desc:"description",pmc:"limit_per_user"},r={};for(let n in t)if(n==="tkid"){let i=t[n].split("#");if(i.length===1){r.ticket_id=i[0];continue}r.ticket_id=i[1],r.consume_id=i[2],r.user_id=i[3];let s=i[2].slice(-4);if(r.is_test=s===":CHK",!t.stmp){let o=i[2].slice(0,-4);/^[0-9]+$/.test(o)?r.timestamp=parseInt(o,10):r.timestamp=fe(i[2].slice(0,-4));}}else e[n]?r[e[n]]=t[n]:r[n]=t[n];return r}async function co(t){if(!t.ticket_id)throw new f("Ticket ID is required.",{code:"INVALID_PARAMETER"});if(!t.method)throw new f('Method is required. Should be either "GET" or "POST"',{code:"INVALID_PARAMETER"});let e=t.ticket_id;await this.__connection;let r=await I.bind(this)(`https://${this.service.slice(0,4)}.${this.customApiDomain}/auth/consume/${this.service}/${this.owner}/${e}`,t?.data||{},{method:t.method,auth:!!t?.auth});return $n(r)}async function uo(t,e){await this.__connection;let r=await I.bind(this)("ticket",Object.assign({exec:"list"},t||{}),{auth:true,fetchOptions:e});return r.list=r.list.map($n),r}async function lo(t,e){await this.__connection;let r=await I.bind(this)("ticket",Object.assign({exec:"consumed"},t||{}),{auth:true,fetchOptions:e});return r.list=r.list.map($n),r}async function fo(t){return I.bind(this)("register-ticket",Object.assign({exec:"reg"},t),{auth:true})}async function ho(t){return I.bind(this)("register-ticket",Object.assign({exec:"unreg"},t),{auth:true})}var _d=3600;async function ft(){if(await this.__connection,this.session){let t=Math.floor(Date.now()/1e3),r=this.session.getIdToken().getExpiration();if(r<t+_d){this.log("request:requesting new token",null);try{await Z.bind(this)().getSession({refreshToken:!0}),this.log("request:received new tokens",{exp:this.session?.idToken?.payload?.exp,currentTime:t,expiresIn:r-t,token:this.session?.accessToken?.jwtToken,refreshToken:this.session?.refreshToken?.token});}catch(n){throw this.log("request:new token error",n),new f("User login is required.",{code:"INVALID_REQUEST"})}}else this.log("request:tokens",{exp:this.session.idToken.payload.exp,currentTime:t,expiresIn:r-t,token:this.session.accessToken.jwtToken,refreshToken:this.session.refreshToken.token});return this.session?.idToken?.jwtToken}else throw this.log("request:no session",null),Oe.bind(this)(),new f("User login is required.",{code:"INVALID_REQUEST"})}function ao(t,e){return new Promise((r,n)=>{e.refreshSession(t.getRefreshToken(),(i,s)=>{this.log("getSession:refreshSessionCallback",{refreshErr:i,refreshedSession:s}),i?(Oe.bind(this)(),n(i)):s.isValid()?r(s):(Oe.bind(this)(),n(new f("Invalid session.",{code:"INVALID_REQUEST"})));});})}function Z(){if(!this.userPool)throw new f("User pool is missing",{code:"INVALID_REQUEST"});let t=()=>{let s=j.getSignInUserSession().getIdToken().payload||null,o=wt(s);return this.log("normalized user attribute",o),this.__user=o,o},e=async s=>new Promise((o,a)=>{this.log("getSession:option",s);let{refreshToken:c=false,skipUserUpdateEventTrigger:u=false}=s||{};if(c&&u&&(u=false),j=this.userPool.getCurrentUser(),!j){this.log("getSession:cognitoUser",j),Oe.bind(this)(),a(null);return}let l=d=>{let h=d.getIdToken().payload;if(this.log("getSession:respond:sessionAttribute",h),h["custom:service"]!==this.service)throw this.log("getSession:respond","invalid service, signing out"),Oe.bind(this)(),new f("Invalid session.",{code:"INVALID_REQUEST"});return this.session=d,t(),u||this._runOnUserUpdateListeners(this.user),this.session};j.getSession((d,h)=>{if(this.log("getSession:getSessionCallback",{err:d,session:h}),!h){Oe.bind(this)(),a(new f("Current session does not exist.",{code:"INVALID_REQUEST"}));return}if(d){ao.bind(this)(h,j).then(b=>o(l(b))).catch(a);return}let p=Math.floor(Date.now()/1e3),g=h.getIdToken(),m=g.getExpiration(),y=m<p;if(this.log("getSession:currentTime",p),this.log("getSession:idTokenExp",m),this.log("getSession:isExpired",y),this.log("getSession:existingBearerToken",this.bearerToken),this.bearerToken=g.getJwtToken(),y||c||!h.isValid())ao.bind(this)(h,j).then(b=>o(l(b))).catch(a);else try{o(l(h));}catch(b){a(b);}});}),r=(s,o)=>{let a=o||s.includes(this.service+"-")?s:this.service+"-"+z.hash(s);return {cognitoUser:new ke({Username:a,Pool:this.userPool}),cognitoUsername:a}};return {getSession:e,authenticateUser:(s,o,a=false,c=false)=>new Promise((u,l)=>{this.__request_signup_confirmation=null,this.__disabledAccount=null;let d=r(s,a),h=d.cognitoUsername,p=new kr({Username:h,Password:o});d.cognitoUser.authenticateUser(p,{newPasswordRequired:(g,m)=>{this.__disabledAccount=null,this.__request_signup_confirmation=h,g["custom:signup_ticket"]==="PASS"||g["custom:signup_ticket"]==="MEMBER"||g["custom:signup_ticket"]==="OIDPASS"?d.cognitoUser.completeNewPasswordChallenge(o,{},{onSuccess:y=>{j=d.cognitoUser,e().then(async b=>{if(F.call(this))try{await _r.bind(this)(o);}catch(E){this.log("encryption:ensureKeyring:failed",E);}u(this.user);});},onFailure:y=>{l(new f(y.message||"Failed to authenticate user.",{code:y.code}));}}):l(new f("User's signup confirmation is required.",{code:"SIGNUP_CONFIRMATION_NEEDED"}));},onSuccess:g=>e({skipUserUpdateEventTrigger:true}).then(async m=>{if(this.__disabledAccount=null,F.call(this))try{await _r.bind(this)(o);}catch(y){this.log("encryption:ensureKeyring:failed",y);}this._runOnLoginListeners(this.user),this._runOnUserUpdateListeners(this.user),u(this.user);}),onFailure:g=>{let m=[],{parsed:y,code:b}=wr(g),E=typeof g?.message=="string"?g.message:"";if(b==="NotAuthorizedException"?E.includes("User is disabled.")?(this.__disabledAccount=h,m=["This account is disabled.","USER_IS_DISABLED"]):c?m=["The account already exists.","ACCOUNT_EXISTS"]:m=["Incorrect username or password.","INCORRECT_USERNAME_OR_PASSWORD"]:b==="UserNotFoundException"?m=["Incorrect username or password.","INCORRECT_USERNAME_OR_PASSWORD"]:b==="UserNotConfirmedException"?(this.__request_signup_confirmation=h,m=["User's signup confirmation is required.","SIGNUP_CONFIRMATION_NEEDED"]):(b==="TooManyRequestsException"||b==="LimitExceededException")&&(m=["Too many attempts. Please try again later.","REQUEST_EXCEED"]),y.code==="SIGNUP_CONFIRMATION_NEEDED"&&(this.__request_signup_confirmation=h),m.length){let v=m[1],x=m[0];l(new f(x,{code:v,cause:g}));}else l(y);}});}),createCognitoUser:r,signup:(s,o,a)=>new Promise((c,u)=>{this.userPool.signUp(s,o,a,null,(l,d)=>{if(l){let{parsed:h,code:p}=wr(l),g=[];p==="UsernameExistsException"?g=["The account already exists.","EXISTS"]:p==="InvalidPasswordException"?g=["Invalid password. Password must be at least 6 characters.","INVALID_PARAMETER"]:p==="InvalidParameterException"?g=[h.message||"Invalid parameter.","INVALID_PARAMETER"]:p==="TooManyRequestsException"||p==="LimitExceededException"?g=["Too many attempts. Please try again later.","REQUEST_EXCEED"]:p==="CodeDeliveryFailureException"?g=["Failed to deliver verification code.","CODE_DELIVERY_FAILURE"]:p==="UserLambdaValidationException"&&(g=[h.message||"Signup validation failed.","INVALID_REQUEST"]),g.length?u(new f(g[0],{code:g[1],cause:l})):u(h);return}c(d);});})}}function wr(t){let e=typeof t?.code=="string"&&t.code.trim()?t.code.trim():"ERROR",n=((typeof t?.message=="string"?t.message:typeof t=="string"?t:"An error occurred.")||"An error occurred.").trim();n||(n="An error occurred.");let i=n.match(/#([A-Za-z0-9_]+)\s*:\s*([\s\S]+)/),s=i?.[1]?.trim()||e,o=i?.[2]?.trim()||n;return {parsed:new f(o,{code:s,cause:t}),code:e}}async function go(t){await this.__authConnection;let e=t?.refreshToken||false;if(!e)return this.user;try{return await Z.bind(this)().getSession(Object.assign({skipUserUpdateEventTrigger:!e,refreshToken:e},t)),this.user}catch{return null}}async function po(t){await this.__connection,t=_.Params(t,{token:"string",id:"string",merge:o=>{if(o===void 0)return false;if(typeof o=="string")return [o];if(Array.isArray(o)){for(let a of o)if(typeof a!="string")throw new f('"merge" array items should be type: <string>.',{code:"INVALID_PARAMETER"})}if(typeof o!="boolean"&&!Array.isArray(o))throw new f('"merge" should be type: <boolean | string[]>.',{code:"INVALID_PARAMETER"});return o},template:o=>{if(typeof o!="object"||o===null)throw new f('"template" should be type: <object>.',{code:"INVALID_PARAMETER"});if(o.welcome!==void 0&&(typeof o.welcome!="string"||!o.welcome))throw new f('"template.welcome" should be a non-empty <string> (template message_id).',{code:"INVALID_PARAMETER"});return o}});let e={token:t.token,id:t.id,merge:t.merge};t.template?.welcome&&(e.template_welcome=t.template.welcome);let r=await I.bind(this)("openid-logger",e),n=r.logger.split("#"),i=this.service+"-"+n[0],s=n[1];return {userProfile:await Z.bind(this)().authenticateUser(i,s,true,true),openid:r.openid}}function bd(t){let e=typeof globalThis<"u"?globalThis:void 0;if(e?.Buffer)return e.Buffer.from(t,"base64").toString("utf8");if(typeof atob=="function"){let r=atob(t),n=new Uint8Array(r.length);for(let i=0;i<r.length;i++)n[i]=r.charCodeAt(i);return typeof TextDecoder<"u"?new TextDecoder().decode(n):r}throw new Error("No base64 decoder available in this environment")}function wd(t){let e=t.split(".");if(e.length!==3)throw new Error("Invalid JWT format");let n=e[1].replace(/-/g,"+").replace(/_/g,"/"),i=bd(n);return JSON.parse(i)}async function mo(t){await this.__authConnection,this.log("loginWithToken:params",t),t=_.Params(t,{idToken:"string",accessToken:"string",refreshToken:"string"},["idToken"]);let e=wd(t.idToken);if(this.log("loginWithToken:idTokenPayload",e),e["custom:service"]!==this.service)throw new f("Token does not belong to this service.",{code:"INVALID_REQUEST"});let r=Math.floor(Date.now()/1e3);if(e.exp&&e.exp<r)throw new f("Token has expired.",{code:"INVALID_REQUEST"});if(this.__user=wt(e),this.session=null,t.accessToken&&t.refreshToken)try{if(this.session=new ot({IdToken:new it({IdToken:t.idToken}),AccessToken:new nt({AccessToken:t.accessToken}),RefreshToken:new st({RefreshToken:t.refreshToken})}),this.log("loginWithToken:session",this.session),this.log("loginWithToken:CognitoUser",ke),this.log("loginWithToken:userPool",this.userPool),ke&&this.userPool){this.log("loginWithToken:cognito:username",e["cognito:username"]);let n={Username:e["cognito:username"],Pool:this.userPool};this.log("loginWithToken:cognitoUserParams",n),j=new ke(n),j.setSignInUserSession(this.session),this.log("loginWithToken:cognitoUserRestored",{cognitoUserType:typeof j,cognitoUserKeys:Object.keys(j||{}),cognitoUser:j});}}catch(n){this.log("loginWithToken:err",n);try{this.log("loginWithToken:err:stringified",JSON.stringify(n));}catch{this.log("loginWithToken:err:stringifyFail",String(n));}try{let i=Object.keys(n||{}),s=Object.getOwnPropertySymbols?Object.getOwnPropertySymbols(n||{}):[],o=Object.getOwnPropertyDescriptors?Object.getOwnPropertyDescriptors(n||{}):{};this.log("loginWithToken:createSessionError:allKeys",{keys:i,symbols:s,descriptors:o});}catch(i){this.log("loginWithToken:createSessionError:allKeysFail",String(i));}}return this._runOnLoginListeners(this.user),this._runOnUserUpdateListeners(this.user),this.user}async function Q(){return await this.__connection,this.__user?.service===this.service?this.__user?.owner===this.host:(await Dt.bind(this)(),false)}async function Oe(t=false){let e=null;j&&(t?e=new Promise((n,i)=>{j.globalSignOut({onSuccess:s=>{this.log("globalSignOut:success",s),n(s);},onFailure:s=>{this.log("globalSignOut:error",s),i(s);}});}):j.signOut()),In.bind(this)();let r={session:null,__startKeyHistory:{},__cached_requests:{},__user:null};e&&(e=await e);for(let n in r)this[n]=r[n];return this._runOnUserUpdateListeners(null),this._runOnLoginListeners(null),e}async function Dt(t){await this.__connection;let{data:e}=K(t);return await Oe.bind(this)(e?.global),"SUCCESS: The user has been logged out."}async function yo(){if(!this.__request_signup_confirmation)throw new f("Least one login attempt is required.",{code:"INVALID_REQUEST"});return await I.bind(this)("confirm-signup",{username:this.__request_signup_confirmation})}async function _o(t=false){if(typeof t=="string")t=_.Url(t);else if(typeof t!="boolean")throw new f("Argument should be type: <boolean | string>.",{code:"INVALID_REQUEST"});if(!this.__disabledAccount)throw new f("Least one signin attempt of disabled account is required.",{code:"INVALID_REQUEST"});return await I.bind(this)("recover-account",{username:this.__disabledAccount,redirect:t}),"SUCCESS: Recovery e-mail has been sent."}async function Kn(t){let e=_.Params(t,{username:"string",email:"string",password:"string"},["password"]);if(await this.__authConnection,e.email)try{_.Email(e.email);}catch{e.username=e.email,delete e.email;}if(!e.username&&!e.email)throw new f('Least one of "username" or "email" is required.',{code:"INVALID_PARAMETER"});return await Z.bind(this)().authenticateUser(e.username||e.email,e.password)}async function bo(t,e){await this.__authConnection;let r={username:"string",password:u=>_.Password(u),email:u=>_.Email(u),name:"string",address:u=>{if(!u)return "";if(typeof u=="string")return u;if(typeof u=="object")return JSON.stringify(u)},gender:"string",birthdate:u=>u?_.Birthdate(u):"",phone_number:u=>u?_.PhoneNumber(u):"",email_public:["boolean",()=>false],address_public:["boolean",()=>false],gender_public:["boolean",()=>false],birthdate_public:["boolean",()=>false],phone_number_public:["boolean",()=>false],access_group:"number",misc:"string",picture:u=>u?_.Url(u):"",profile:u=>u?_.Url(u):"",family_name:"string",given_name:"string",middle_name:"string",nickname:"string",website:u=>u?_.Url(u):""},n=_.Params(t||{},r,["email","password"]);await Dt.bind(this)(),e=_.Params(e||{},{email_subscription:u=>{if(typeof u!="boolean")throw new f('"option.email_subscription" should be type: <boolean>.',{code:"INVALID_PARAMETER"});if(!e?.signup_confirmation)throw new f('"option.signup_confirmation" is required for email subscription.',{code:"INVALID_PARAMETER"});return u},signup_confirmation:u=>{let l=u;if(typeof u=="string")l=_.Url(u);else if(typeof u=="boolean")l=u;else throw new f('"option.signup_confirmation" should be type: <string | boolean>.',{code:"INVALID_PARAMETER"});if(l&&!n.email)throw new f('"email" is required for signup confirmation.',{code:"INVALID_PARAMETER"});return l},login:u=>{if(typeof u=="boolean"){if(e.signup_confirmation&&u)throw new f('"login" is not allowed when "option.signup_confirmation" is true.',{code:"INVALID_PARAMETER"});return u}throw new f('"option.login" should be type: boolean.',{code:"INVALID_PARAMETER"})},template:u=>{if(typeof u!="object"||u===null)throw new f('"option.template" should be type: <object>.',{code:"INVALID_PARAMETER"});if(u.signup_confirmation!==void 0){if(typeof u.signup_confirmation!="string"||!u.signup_confirmation)throw new f('"option.template.signup_confirmation" should be a non-empty <string> (template message_id).',{code:"INVALID_PARAMETER"});if(!e?.signup_confirmation)throw new f('"option.signup_confirmation" is required when "option.template.signup_confirmation" is set.',{code:"INVALID_PARAMETER"})}if(u.welcome!==void 0&&(typeof u.welcome!="string"||!u.welcome))throw new f('"option.template.welcome" should be a non-empty <string> (template message_id).',{code:"INVALID_PARAMETER"});return u}});let i=e?.login||false;if(n.signup_confirmation=e?.signup_confirmation||false,n.email_subscription=e?.email_subscription||false,n.email_public&&!n.signup_confirmation)throw new f('"option.signup_confirmation" should be true if "email_public" is set to true.',{code:"INVALID_PARAMETER"});n.service=this.service,n.owner=this.owner;let s=Z.bind(this)().createCognitoUser(n.username||n.email);for(let u of ["email_public","address_public","gender_public","birthdate_public","phone_number_public"])n[u]=n[u]?"1":"0";n.access_group&&(n.access_group=n.access_group.toString());let o=(await I.bind(this)("signupkey",{username:s.cognitoUsername,signup_confirmation:typeof n.signup_confirmation=="boolean"?JSON.stringify(n.signup_confirmation):n.signup_confirmation,email_subscription:n.email_subscription,template_confirmation:e?.template?.signup_confirmation||"",template_welcome:e?.template?.welcome||""})).split(":"),a=o.slice(1).join(":"),c=[new Se({Name:"custom:signup",Value:o[0]}),new Se({Name:"locale",Value:a.split("#")[1]}),new Se({Name:"custom:signup_ticket",Value:a})];for(let u in r){let l=["email_public","address_public","gender_public","birthdate_public","phone_number_public","misc","service","owner"];n[u]!==""&&(u==="username"||u==="password"||u==="access_group"||(l.includes(u)?c.push(new Se({Name:"custom:"+u,Value:n[u]})):c.push(new Se({Name:u,Value:n[u]}))));}return await Z.bind(this)().signup(s.cognitoUsername,n.password,c),n.signup_confirmation?(j=s.cognitoUser,this.__request_signup_confirmation=s.cognitoUsername,"SUCCESS: The account has been created. User's signup confirmation is required."):i?Kn.bind(this)({email:n.username||n.email,password:n.password}):"SUCCESS: The account has been created."}async function wo(){await this.__connection;let t=await I.bind(this)("remove-account",{disable:this.__user.user_id},{auth:true});return await Dt.bind(this)(),t}async function Eo(t){await this.__connection;let e=_.Params(t,{email:i=>_.Email(i),code:["number","string"],new_password:i=>_.Password(i)},["email","code","new_password"]),r=e.code,n=e.new_password;return typeof r=="number"&&(r=r.toString()),new Promise(async(i,s)=>{Z.bind(this)().createCognitoUser(e.email).cognitoUser.confirmPassword(r,n,{onSuccess:a=>{i("SUCCESS: New password has been set.");},onFailure:a=>{s(new f(a?.message||"Failed to reset password.",{code:a?.code||"ERROR",cause:a}));}});})}async function Ao(t,e,r){await this.__connection;let n;if(!j)throw new f("The user has to be logged in.",{code:"INVALID_REQUEST"});if(t==="email"||t==="phone_number"){if(!this.__user.hasOwnProperty(t))throw new f(`No ${t==="email"?"e-mail":"phone number"} to verify`,{code:"INVALID_REQUEST"});if(this.__user?.[`${t}_verified`])return `SUCCESS: "${t}" is verified.`;n=(e?_.Params(e,{code:"string"}):{}).code||"";}else return;let i,s=r?.template?.verification;if(s!==void 0){if(typeof s!="string"||!s)throw new f('"template.verification" should be a non-empty <string> (template message_id).',{code:"INVALID_PARAMETER"});i={template_verification:s};}return new Promise((o,a)=>{let c={onSuccess:u=>{n?Z.bind(this)().getSession({refreshToken:true}).then(()=>{this.__user&&(this.__user[t+"_verified"]=true),o(`SUCCESS: "${t}" is verified.`);}).catch(l=>{a(l);}):o("SUCCESS: Verification code has been sent.");},onFailure:u=>{a(new f(u.message||"Failed to request verification code.",{code:u?.code}));}};n?j?.verifyAttribute(t,n,c):(c.inputVerificationCode=null,j?.getAttributeVerificationCode(t,c,i));})}function So(t,e){return Ao.bind(this)("phone_number",t,e)}function vo(t,e){return Ao.bind(this)("email",t,e)}async function Ro(t,e){await this.__connection;let r=_.Params(t,{email:s=>_.Email(s)},["email"]),n,i=e?.template?.verification;if(i!==void 0){if(typeof i!="string"||!i)throw new f('"template.verification" should be a non-empty <string> (template message_id).',{code:"INVALID_PARAMETER"});n={template_verification:i};}return new Promise(async(s,o)=>{Z.bind(this)().createCognitoUser(r.email).cognitoUser.forgotPassword({onSuccess:c=>{s("SUCCESS: Verification code has been sent.");},onFailure:c=>{let{parsed:u,code:l}=wr(c),d={UserNotFoundException:"NOT_EXISTS",InvalidParameterException:"INVALID_PARAMETER",NotAuthorizedException:"INVALID_REQUEST",LimitExceededException:"REQUEST_EXCEED",TooManyRequestsException:"REQUEST_EXCEED",CodeDeliveryFailureException:"CODE_DELIVERY_FAILURE"}[l]||u.code||l||"ERROR";o(new f(u.message,{code:d,cause:c}));}},n);})}async function To(t){if(await this.__connection,!this.session)throw new f("User login is required.",{code:"INVALID_REQUEST"});let e=_.Params(t,{current_password:"string",new_password:"string"});if(!e?.current_password)throw new f('"current_password" is required to change password.',{code:"INVALID_PARAMETER"});if(!e?.new_password)throw new f('"new_password" is required to change password.',{code:"INVALID_PARAMETER"});return _.Password(e.current_password),_.Password(e.new_password),F.call(this)&&await Hs.bind(this)(e.current_password,e.new_password),new Promise((r,n)=>{j.changePassword(e.current_password,e.new_password,(i,s)=>{if(i){if(i?.code==="InvalidParameterException")n(new f("Invalid password parameter.",{code:"INVALID_PARAMETER"}));else if(i?.code==="NotAuthorizedException")n(new f("Incorrect password.",{code:"INVALID_REQUEST"}));else if(i?.code==="TooManyRequestsException"||i?.code==="LimitExceededException")n(new f("Too many attempts. Please try again later.",{code:"REQUEST_EXCEED"}));else {let{parsed:o}=wr(i);n(o);}return}F.call(this)&&Ws.bind(this)().catch(o=>this.log("encryption:prune:failed",o)),r("SUCCESS: Password has been changed.");});})}async function Io(t){if(await this.__connection,!this.session)throw new f("User login is required.",{code:"INVALID_REQUEST"});let e=_.Params(t||{},{user_id:i=>_.UserId(i),email:i=>_.Email(i),address:i=>{if(!i)return "";if(typeof i=="string")return i;if(typeof i=="object")return JSON.stringify(i)},name:"string",gender:"string",birthdate:i=>i?_.Birthdate(i):"",phone_number:i=>i?_.PhoneNumber(i):"",email_public:"boolean",phone_number_public:"boolean",address_public:"boolean",gender_public:"boolean",birthdate_public:"boolean",misc:"string",picture:i=>i?_.Url(i):"",profile:i=>i?_.Url(i):"",family_name:"string",given_name:"string",middle_name:"string",nickname:"string",website:i=>i?_.Url(i):""});if(e&&typeof e=="object"&&!Object.keys(e).length)return this.user;e.email&&(e.preferred_username=this.service+"-"+z.hash(e.email));let r=[["email_public","email_verified","User's e-mail should be verified to set"],["phone_number_public","phone_number_verified","User's phone number should be verified to set"]];if(this.__user){for(let i of r)if(e[i[0]]&&!this.__user[i[1]])throw new f(`${i[2]} "${i[0]}" to true.`,{code:"INVALID_REQUEST"})}let n=[];for(let i in e){if(e[i]===this.user[i]){n.push(i);continue}if(["email_public","phone_number_public","address_public","gender_public","birthdate_public","misc"].includes(i)){let o=e[i];typeof o=="boolean"&&(o=o?"1":"0"),e["custom:"+i]=o,n.push(i);}}for(let i of n)delete e[i];if(e.user_id)if(e.user_id===this.user.user_id)delete e.user_id;else return I.bind(this)("admin-edit-profile",{attributes:e},{auth:true});if(e&&typeof e=="object"&&Object.keys(e).length){let i=[];for(let s in e)i.push(new Se({Name:s,Value:e[s]}));return await new Promise((s,o)=>{j?.updateAttributes(i,(a,c)=>{a&&o([a?.code||a?.name,a?.message||"Failed to update user settings."]),s(c);});}),await Z.bind(this)().getSession({refreshToken:true}),this.user}return this.user}async function Po(t,e){t=K(t).data,t||(t={searchFor:"timestamp",condition:">",value:0},e||(e={}),e.ascending=false),await this.__connection;let r={user_id:i=>Array.isArray(i)?i.map(s=>_.UserId(s)):_.UserId(i),email:"string",phone_number:"string",locale:i=>{if(typeof i!="string"||typeof i=="string"&&i.length>5)throw new f('Value of "locale" should be a country code.',{code:"INVALID_PARAMETER"});return i},name:"string",address:"string",gender:"string",birthdate:i=>_.Birthdate(i),subscribers:"number",timestamp:"number",access_group:"number",approved:"string"},n=["searchFor","value"];if(t=_.Params(t,{searchFor:["user_id","name","email","phone_number","address","gender","birthdate","locale","subscribers","timestamp","access_group","approved"],condition:[">",">=","=","<","<=","gt","gte","eq","lt","lte",()=>"="],value:i=>{let s=r[t.searchFor];if(typeof s=="function")return s(i);if(typeof i!==s)throw new f(`Value does not match the type of "${t.searchFor}" index.`,{code:"INVALID_PARAMETER"});return i},range:i=>{let s=r[t.searchFor];if(typeof s=="function")return s(i);if(typeof i!==s)throw new f(`Range does not match the type of "${t.searchFor}" index.`,{code:"INVALID_PARAMETER"});return i}},n),t?.condition&&t?.condition!=="="&&t.hasOwnProperty("range"))throw new f("Conditions does not apply on range search.",{code:"INVALID_PARAMETER"});if(t.searchFor==="user_id"&&(t.condition!=="="||t.range))throw new f(`Conditions are not allowed on "${t.searchFor}"`,{code:"INVALID_PARAMETER"});if(typeof t?.value=="string"&&!t?.value)throw new f("Value should not be an empty string.",{code:"INVALID_PARAMETER"});if(typeof t?.searchFor=="string"&&!t?.searchFor)throw new f('"searchFor" should not be an empty string.',{code:"INVALID_PARAMETER"});return I.bind(this)("get-users",t,{auth:true,fetchOptions:e})}async function Uo(t){await this.__connection;let e=await I.bind(this)("last-verified-email",t,{auth:true});return e.includes("SUCCESS")?(await Z.bind(this)().getSession({refreshToken:true}),this.user):e}async function xo(t){return await this.__connection,t=_.Params(t,{username:_.Email,redirect:_.Url},["username"]),await I.bind(this)("request-username-change",t,{auth:true})}var Ed="1.2.1",Ad=class{constructor(t){we(this,"version",Ed);we(this,"items",[]);we(this,"nextJobId",1);we(this,"breakWhenError",false);we(this,"batchSize",1);we(this,"onProgress");we(this,"activeCount",0);we(this,"currentCycleCompleted",[]);we(this,"stopProcessing",false);if(this.breakWhenError=!!t?.breakWhenError,this.batchSize=t?.batchSize??1,typeof this.batchSize!="number"||this.batchSize<1)throw new Error("batchSize must be at least 1");if(t?.onProgress)if(typeof t.onProgress=="function")this.onProgress=t.onProgress;else throw new Error("onProgress must be a function")}get batchToProcess(){return Math.ceil(this.items.length/this.batchSize)}add(t){let e=Array.isArray(t)?t:[t],r=[];for(let n of e){if(typeof n!="function")throw new Error("Each job must be a function that returns a Promise");let i=String(this.nextJobId++);this.items.push({id:i,job:n}),r.push(i);}return this.processNext(),r}setBatchSize(t){if(typeof t!="number"||t<1)throw new Error("batchSize must be at least 1");this.batchSize=t;}remove(t){let e=String(t),r=this.items.findIndex(n=>n.id===e);return r===-1?false:(this.items.splice(r,1),true)}processNext(){if(this.stopProcessing||this.items.length===0||this.activeCount>0)return;let t=this.items.splice(0,this.batchSize);this.activeCount=t.length,this.currentCycleCompleted=new Array(t.length),t.forEach((e,r)=>{Promise.resolve().then(()=>e.job()).then(n=>(this.finalizeJob(r,n,false),n)).catch(n=>(this.finalizeJob(r,n,true),n));});}finalizeJob(t,e,r){if(this.currentCycleCompleted[t]=e,this.activeCount-=1,r&&this.breakWhenError&&(this.stopProcessing=true,this.items=[]),this.activeCount!==0)return;let n=this.currentCycleCompleted.slice();this.currentCycleCompleted=[],this.onProgress&&this.onProgress({batchToProcess:this.batchToProcess,itemsToProcess:this.items.length,completed:n}),this.processNext();}terminate(){this.items=[];}},kt=Ad;var ht=null,Do=typeof SubmitEvent<"u",Sd=typeof HTMLFormElement<"u",Ot=re(),jn=0;function ko(t){if(!t)return null;let e=Number(t);if(Number.isFinite(e))return Math.max(0,e*1e3);let r=Date.parse(t);return Number.isNaN(r)?null:Math.max(0,r-Date.now())}function Hn(t,e){return e>0?t/e*100:0}var Co=t=>{let{auth:e,type:r,endpoints:n,stable:i}=t,s=n[0],o=n[1];if(jn++,r==="admin"){let a=Object.entries(s).filter(([c,u])=>c.includes(e?"_private":"_public")&&c!=="get_users_private"&&c!=="service_public"&&typeof u=="string").map(([,c])=>c);if(!a.length)throw new f("No available admin gateways.",{code:"INVALID_REQUEST"});return a[jn%a.length]}if(r==="record"){let a=Object.entries(o).filter(([c,u])=>c.includes(e?"record_private":"record_public")&&typeof u=="string").map(([,c])=>c);if(!a.length)throw new f("No available record gateways.",{code:"INVALID_REQUEST"});return i?a[0]:a[jn%a.length]}throw new f("Invalid gateway type.",{code:"INVALID_REQUEST"})};async function vd(t,e,r){let n=await Promise.all([this.admin_endpoint,this.record_endpoint]),i=n[0],s=n[1],o=t.split("?"),a=o.length>1?"?"+o[1]:"";switch(t=o[0],t){case "get-users":return i.get_users_private+t+a;case "service":return i.service_public+t+a;case "get-newsletters":case "get-public-newsletters":case "subscribe-newsletter":case "subscribe-public-newsletter":case "signupkey":case "admin-newsletter-request":case "admin-signup":case "confirm-signup":case "openid-logger":case "block-account":case "admin-edit-profile":case "remove-account":case "post-secure":case "recover-account":case "mock":case "grant-access":case "last-verified-email":case "ticket":case "register-ticket":case "get-newsletter-subscription":case "request-username-change":case "send-inquiry":case "register-newsletter-group":case "newsletter-group-endpoint":case "invitation-list":case "csr":case "csr-poll":case "csr-cancel":return Co.bind(this)({auth:e,type:"admin",endpoints:n})+t+a;case "post-record":return (e?s.post_private:s.post_public)+t+a;case "get-records":return (e?s.get_private:s.get_public)+t+a;case "del-files":case "del-records":return s.del_private+t+a;case "store-subscription":case "get-vapid-public-key":case "push-notification":case "delete-subscription":case "subscription":case "get-subscription":case "get-table":case "get-tag":case "get-uniqueid":case "get-index":case "get-signed-url":case "extract-file-text":case "grant-private-access":case "request-private-access-key":case "get-ws-group":case "check-schema":case "get-feed":case "castspell":case "dopamine":case "getspell":return Co.bind(this)({auth:e,type:"record",endpoints:n,stable:r})+t+a;default:return _.Url(t)+a}}var Nt={};function No(){ht&&(ht.terminate(),ht=null);}async function I(t,e=null,r,n){this.log("request",{url:t,data:e,options:r,_etc:n||{}}),r=r||{};let{auth:i=false,method:s="post",bypassAwaitConnection:o=false}=r;s=s.toUpperCase();let a=null,c=e?.service||this.service,u=e?.owner||this.owner,l=null,d=await vd.bind(this)(t,!!i,!!r.stableGateway);if(!o&&(a=await this.__connection,!a))throw new f("Invalid connection. The service could have been disabled, or has a restricted CORS.",{code:"INVALID_REQUEST"});let h=r?.tokenHeaders?.idToken===true;(i||h)&&(l=await ft.bind(this)());let p={},{fetchMore:g=false,progress:m}=r?.fetchOptions||{};if(r?.fetchOptions&&Object.keys(r.fetchOptions).length){for(let U of ["limit","startKey","ascending"])if(r.fetchOptions.hasOwnProperty(U)){if(U==="startKey"&&r.fetchOptions[U]===null)continue;p[U]=r.fetchOptions[U];}p=_.Params(p,{limit:U=>{if(typeof U!="number")throw new f("Fetch limit should be a number.",{code:"INVALID_REQUEST"});if(U>1e3)throw new f("Fetch limit should be below 1000.",{code:"INVALID_REQUEST"});return U},startKey:U=>U,ascending:"boolean"});}let y=n?.ignoreService?{}:{service:c,owner:u};Object.assign(y,p),e=K(e).data,e?e&&typeof e=="object"&&(e=Object.assign(y,e)):e=y;let b=`${s}:${i?"auth":"public"}:${t}`,E=(()=>{if(e&&typeof e=="object"&&Object.keys(e).length&&!(Ot&&e instanceof FormData)){let U=function(C){return typeof C=="object"&&C!==null?Object.keys(C).sort().reduce((V,B)=>(typeof C[B]=="object"&&C[B]!==null?V[B]=U(C[B]):V[B]=C[B],V),{}):C};return z.hash(b+"/"+JSON.stringify(U(e)))}return z.hash(b+"/"+c)})(),{requestKey:v,requestKeyWithStartKey:x}=Rd.bind(this)({params:e,url:t,fetchMore:g,hashedParams:E});if(!v||v&&typeof v=="object")return v;if(this.log("requestKey",x),typeof x=="string"&&Nt[x]instanceof Promise)return this.log("request:returning pending",x),Nt[x];let P={Accept:"*/*"};if(Object.prototype.hasOwnProperty.call(r,"contentType")&&r.contentType!==void 0){let U=r.contentType===null?"application/x-www-form-urlencoded":r.contentType;U&&(P["Content-Type"]=U);}else P["Content-Type"]="application/json";if(l&&(P.Authorization=l),r?.tokenHeaders){let U=(B,Ue)=>typeof B=="string"?B:B===true?Ue:null,C=U(r.tokenHeaders.accessToken,this.session?.accessToken?.jwtToken||null),V=U(r.tokenHeaders.idToken,this.bearerToken||this.session?.idToken?.jwtToken||l||null);C&&(P["X-Access-Token"]=C),V&&(P["X-Id-Token"]=V);}let O={public_identifier:this.__public_identifier,service:c,owner:u};P["Content-Meta"]=JSON.stringify(O),r.revalidate&&(P["Cache-Control"]="no-cache",P.Pragma="no-cache");let M={headers:P};if(r?.responseType&&(M.responseType=r.responseType),s==="GET"){if(e){let U=[];if(Ot&&e instanceof FormData?U=Array.from(e.entries()).map(([C,V])=>{let B=typeof V=="string"?V:V.name;return encodeURIComponent(C)+"="+encodeURIComponent(B)}):U=Object.keys(e).map(C=>{let V=e[C];return typeof V!="string"&&(V=JSON.stringify(V)),encodeURIComponent(C)+"="+encodeURIComponent(V)}),U.length){let C=d.includes("?")?d.endsWith("?")||d.endsWith("&")?"":"&":"?";d+=C+U.join("&");}}M.body=null;}else if(Ot&&e instanceof FormData)M.body=e;else if(P["Content-Type"]==="application/x-www-form-urlencoded"&&e&&typeof e=="object"){let U=new URLSearchParams;for(let C of Object.keys(e)){let V=e[C];U.append(C,typeof V=="string"?V:JSON.stringify(V));}M.body=U.toString();}else typeof e=="string"?M.body=e:M.body=e?JSON.stringify(e):null;if(M.method=s,ht===null){let U={batchSize:this.requestBatchSize,breakWhenError:false,onProgress:C=>{this.onBatchProcess.forEach(V=>V(C));}};ht=new kt(U);}return this.log("request-opt",M),new Promise((U,C)=>{ht.add([async()=>{let V=Oo.bind(this)(d,M,m);Nt[x]=V;try{let B=Id.bind(this)({hashedParam:v,requestKeyWithStartKey:x,url:t,fetched:await V});return delete Nt[x],this.log("request:end",B),U(B),B}catch(B){throw delete Nt[x],this.log("request:err",B),C(B),B}}]);})}function Rd(t){let{params:e={},url:r,fetchMore:n=false,hashedParams:i}=t||{};if(e.startKey){if(!(typeof e.startKey=="object"&&Object.keys(e.startKey).length)&&e.startKey!=="start"&&e.startKey!=="end")throw new f(`"${e.startKey}" is invalid startKey key.`,{code:"INVALID_PARAMETER"});e.startKey==="start"&&(n=false,delete e.startKey);}if(!n){if(this.__cached_requests?.[r]?.[i]&&delete this.__cached_requests[r][i],this.__startKeyHistory?.[r]?.[i]){if(Array.isArray(this.__startKeyHistory[r][i])&&this.__startKeyHistory[r][i].length)for(let c of this.__startKeyHistory[r][i]){let u=i+z.hash(c);this.__cached_requests?.[r]&&this.__cached_requests?.[r]?.[u]&&delete this.__cached_requests[r][u];}delete this.__startKeyHistory[r][i];}return {requestKeyWithStartKey:i,requestKey:i}}if(!Array.isArray(this.__startKeyHistory?.[r]?.[i]))return {requestKeyWithStartKey:i,requestKey:i};let s=this.__startKeyHistory[r][i],o=s[s.length-1],a=i;if(o){if(o==="end")return {requestKey:{list:[],startKey:"end",endOfList:true,startKeyHistory:s},requestKeyWithStartKey:a};a+=z.hash(o),e.startKey=JSON.parse(o);}return this.__cached_requests?.[r]?.[a]?{requestKey:this.__cached_requests[r][a],requestKeyWithStartKey:a}:{requestKeyWithStartKey:a,requestKey:i}}function Td(t){let e=r=>r&&typeof r=="object"&&r.encrypted?Object.assign({},r,{data:null}):r;return Array.isArray(t)?t.map(e):t&&typeof t=="object"?Array.isArray(t.list)?Object.assign({},t,{list:t.list.map(e)}):e(t):t}function Oo(t,e,r){return new Promise((n,i)=>{let s=new XMLHttpRequest;s.open(e.method||"GET",t);for(var o in e.headers||{})s.setRequestHeader(o,e.headers[o]);e.responseType&&(s.responseType=e.responseType),s.onload=()=>{if(s.status<400)if(e.responseType=="json"||e.responseType=="blob")n(s.response);else {let a=s.responseText;try{a=JSON.parse(a);}catch{}n(a);}else if(s.status===429){let a=s.getResponseHeader("Retry-After"),c=ko(a);c!==null?setTimeout(()=>{Oo(t,e,r).then(n,i);},c):i("Too many requests");}else {let a=s.status,c=["INVALID_CORS","INVALID_REQUEST","SERVICE_DISABLED","INVALID_PARAMETER","ERROR","EXISTS","NOT_EXISTS"],u=e.responseType=="blob"?s.response:s.responseText;try{u=JSON.parse(u);}catch{}if(typeof u=="string"){let l=u.split(":"),d=l.splice(0,1)[0].trim(),h=l.join(":").trim();i(new f(h||u,{code:c.includes(d)?d:"ERROR"}));}else if(typeof u=="object"&&u?.message){let l=u?.code||(a?a.toString():null)||"ERROR",d=u.message,h=u?.cause;typeof d=="string"&&(d=d.trim()),i(new f(d,{cause:h,code:l}));}else i(u);}},s.onerror=()=>i("Network error"),s.onabort=()=>i("Aborted"),s.ontimeout=()=>i("Timeout"),typeof r=="function"&&(s.onprogress=a=>{r({status:"download",progress:Hn(a.loaded,a.total),loaded:a.loaded,total:a.total,abort:()=>s.abort()});},s.upload&&(s.upload.onprogress=a=>{r({status:"upload",progress:Hn(a.loaded,a.total),loaded:a.loaded,total:a.total,abort:()=>s.abort()});})),s.send(e.body);})}function Id(t){let{hashedParam:e,requestKeyWithStartKey:r,url:n,fetched:i}=t;if(!i?.startKey)return i;this.__startKeyHistory.hasOwnProperty(n)||(this.__startKeyHistory[n]={}),this.__startKeyHistory[n].hasOwnProperty(e)||(this.__startKeyHistory[n][e]=[]);let s=i.startKey==="end"?"end":JSON.stringify(i.startKey);return this.__startKeyHistory[n][e].includes(s)||this.__startKeyHistory[n][e].push(s),this.__cached_requests?.[n]||(this.__cached_requests[n]={}),this.__cached_requests[n][r]=i,Object.assign({startKeyHistory:this.__startKeyHistory[n][e]},i)}async function Ar(t,e){await this.__connection;let{record_id:r,service:n=this.service,progress:i}=e;if(!r)throw new f('"record_id" is required.',{code:"INVALID_PARAMETER"});if(Do&&t instanceof SubmitEvent&&(t=t.target),Sd&&t instanceof HTMLFormElement&&(t=new FormData(t)),!Ot||!(t instanceof FormData))throw new f('"fileList" should be a FormData or HTMLFormElement.',{code:"INVALID_PARAMETER"});let o={reserved_key:We(),service:n,request:"post"};e?.record_id&&(o.id=e.record_id);let a,c=(p,g,m)=>new Promise((y,b)=>{a=new XMLHttpRequest,a.open("POST",p),a.onload=()=>{let E=a.responseText;try{E=JSON.parse(E);}catch{}if(a.status>=200&&a.status<300)y(E);else if(a.status===429){let v=a.getResponseHeader("Retry-After"),x=ko(v);x!==null?setTimeout(()=>{c(p,g,m).then(y,b);},x):b("Too many requests");}else b(E);},a.onerror=()=>b("Network error"),a.onabort=()=>b("Aborted"),a.ontimeout=()=>b("Timeout"),a.upload&&typeof m=="function"&&(a.upload.onprogress=m),a.send(g);});function u(p){let g="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";if(p===0)return g[0];let m="";for(;p>0;)m=g[p%62]+m,p=Math.floor(p/62);return m}let l=[],d=[],h=[];for(let[p,g]of t.entries()){if(!(g instanceof File))continue;let m=await so.bind(this)(r,p,g),y=m.file,b=m.key,E=Object.assign({key:b+"/"+y.name,sizeKey:u(y.size),contentType:y.type||null},o),{fields:v=null,url:x,cdn:P}=await I.bind(this)("get-signed-url",E,{auth:!!this.__user});h.push(P);let N=new FormData;for(let O in v)N.append(O,v[O]);N.append("file",y);try{await c(x,N,typeof i=="function"?O=>i({status:"upload",progress:Hn(O.loaded,O.total),currentFile:g,completed:l,failed:d,loaded:O.loaded,total:O.total,abort:()=>a.abort()}):null),l.push(g);}catch{d.push(g);}}return {completed:l,failed:d,bin_endpoints:h}}var Er={};function T(t){let{preventMultipleCalls:e=false}=t||{};return function(r,n,i){let s=i.value;i.value=function(...o){let a=o[0],c=true,u=null,l="",d={},h=false;if(Do&&a instanceof SubmitEvent){a.preventDefault();let b=window.location.href;u=a.target;let E=new URL(u.action);l=E.href;let v=l?l.match(/(?<=\{).*?(?=\})/g):"";if(v)for(let x of v){if(!x)continue;let P=u.querySelector(`[name="${x}"]`);if(P)if(P.type==="file")for(let N=0;N<=P.files.length-1;N++)P.files[N]&&(d[x]||(d[x]=[]),d[x].push(new Promise((O,M)=>{let U=new FileReader;U.onload=function(){O(U.result);},U.readAsDataURL(P.files[N]),U.onerror=M;})));else l=l.replace(`{${x}}`,P.value);}u.getAttribute("action")===null?c=false:h=E.href===b;}let p=async b=>{if(l)for(let E in d)d[E].length&&(l=l.replace(`{${E}}`,(await Promise.all(d[E])).join(",")));if(u&&c){let E=F.call(this)?Td(b):b;window.sessionStorage.setItem(`${this.service}:${z.hash(l)}`,JSON.stringify(E)),h?window.location.replace(l):window.location.href=l;}return b},g,m=b=>{throw b instanceof f?b.name=n+"()":b=b instanceof Error?b:new f(b,{name:n+"()"}),b},y=async()=>{try{if(g=s.bind(this)(...o),g instanceof Promise){let b=await g;return p(b)}return p(g)}catch(b){throw m(b)}};if(e){let b=`${n}:${this?.__public_identifier||""}:${this?.service||""}:${this?.owner||""}`;return Er?.[b]||(Er[b]=y().finally(()=>{delete Er[b];})),Er[b]}return y()};}}async function Fo(){await this.__connection;let t=`${this.service}:${z.hash(window.location.href.split("?")[0])}`,e=window.sessionStorage.getItem(t);if(window.sessionStorage.removeItem(t),e!==null){try{e=JSON.parse(e);}catch{}return e}return null}var Pd=256,Ud=256,xd=256,Lo=256,Cd="\u{10FFFF}",Dd=/[\u0000-\u001F\u007F]|\u{10FFFF}/u,kd={"/":"%2F","!":"%21","*":"%2A","#":"%23"},Nd={"%2F":"/","%21":"!","%2A":"*","%23":"#"};function Od(t){return t.replace(/%/g,"%25").replace(/[\/!*#]/g,r=>kd[r]||r)}function se(t){return typeof t!="string"?t:t.replace(/%(2F|21|2A|23)/gi,r=>{let n=r.toUpperCase();return Nd[n]||r}).replace(/%25/gi,"%")}function ve(t,e,r={}){let{allowEmpty:n=false,maxLength:i,blockKeyDelimiters:s=false,disallowLeadingDollar:o=false,onlyAlphanumeric:a=false}=r;if(typeof t!="string")throw new f(`"${e}" should be type: <string>.`,{code:"INVALID_PARAMETER"});if(a&&/[^a-zA-Z0-9]/.test(t))throw new f(`"${e}" should only contain alphanumeric characters.`,{code:"INVALID_PARAMETER"});if(!n&&t.length===0)throw new f(`"${e}" is required.`,{code:"INVALID_PARAMETER"});if(i&&t.length>i)throw new f(`"${e}" should be <= ${i} characters.`,{code:"INVALID_PARAMETER"});if(Dd.test(t)||t.includes(Cd))throw new f(`"${e}" cannot include control characters or unsupported sentinel characters.`,{code:"INVALID_PARAMETER"});if(s&&(t=Od(t),i&&t.length>i))throw new f(`"${e}" should be <= ${i} characters. "/", "!", "*", "#" and "%" count as 3 characters each.`,{code:"INVALID_PARAMETER"});if(o&&t.startsWith("$"))throw new f(`"${e}" cannot start with "$".`,{code:"INVALID_PARAMETER"});return t}function gt(t,e="table.name",r={}){return ve(t,e,{allowEmpty:r.allowEmpty===true,maxLength:Pd,blockKeyDelimiters:true})}function vr(t,e="tag",r={}){return ve(t,e,{allowEmpty:r.allowEmpty===true,maxLength:Ud,blockKeyDelimiters:true})}function Ft(t,e="index.name",r={}){return ve(t,e,{allowEmpty:r.allowEmpty===true,maxLength:xd,blockKeyDelimiters:true,disallowLeadingDollar:true})}function Mo(t,e="index.value"){return ve(t,e,{allowEmpty:true,maxLength:Lo})}function Wn(t){return typeof t=="string"&&t.slice(-1)==="."}function Gn(t,e){return ve(t,e,{allowEmpty:true,maxLength:Lo,blockKeyDelimiters:true})}function Vo(t){if(!t.record_id&&!t.unique_id)return null;let e={};return t?.service&&(e.service=t.service),t?.owner&&(e.owner=t.owner),t?.record_id?e.record_id=ve(t.record_id,"record_id",{allowEmpty:false,onlyAlphanumeric:true}):t?.unique_id&&(e.unique_id=t.unique_id),e}function Jn(t){if(t===void 0)return 0;if(typeof t=="number"){if(t>99||t<0)throw new f('"table.access_group" value should be within a range of 0 ~ 99.',{code:"INVALID_REQUEST"})}else if(typeof t=="string"){if(t={private:"private",public:0,authorized:1,admin:99}[t],t===void 0)throw new f('"table.access_group" is invalid.',{code:"INVALID_PARAMETER"})}else throw new f('"table.access_group" should be type: <number | string>.',{code:"INVALID_PARAMETER"});if(!this.__user&&t)throw new f("Unsigned users have no access to records with access group.",{code:"INVALID_REQUEST"});return t}var Sr=4503599627370496;function Rr(t){if(typeof t=="number"){if(t>Sr||t<-Sr)throw new f(`Number value should be within range -${Sr} ~ +${Sr}`,{code:"INVALID_PARAMETER"});return t}if(typeof t=="boolean")return t;if(typeof t=="string")return Mo(t,"index.value");throw new f('"index.value" should be type: <number | boolean | string>.',{code:"INVALID_PARAMETER"})}function qo(t,e){if(!e.index||!("value"in e.index))throw new f('"index.value" is required.',{code:"INVALID_PARAMETER"});if(e.index.name==="$record_id")throw new f(`Cannot do "index.range" on ${e.index.name}`,{code:"INVALID_PARAMETER"});if(typeof e.index.value!=typeof t)throw new f('"index.range" type should match the type of "index.value".',{code:"INVALID_PARAMETER"});return typeof t=="string"?Wn(e.index.name)?Gn(t,"index.range"):Mo(t,"index.range"):t}var Tr={},Fd=10080*60,Ld=3600,Bo=2;function Md(t,e){if(!e)return String(Bo);let r=Math.max(60,t-300)*1e3;return Bo+"."+Math.floor(Date.now()/r)}function Vd(t){if(!this.user?.user_id)return false;let e=t[6]==="**"?"**":parseInt(t[6]),r=this.user?.access_group??-1;return !(this.user.user_id!==t[3]&&(e==="**"||r<e))}function $o(t){if(typeof t=="string"){if(t.startsWith("!J%"))try{return JSON.parse(t.substring(3))}catch{return t}return t==="!D%{}"?{}:t==="!L%[]"?[]:t}if(t&&typeof t=="object"&&!Array.isArray(t)&&typeof t.__json__=="string"&&Object.keys(t).length===1)try{return JSON.parse(t.__json__)}catch{}return t}async function Ko(t){return typeof t=="string"?t:t&&typeof t.text=="function"?await t.text():await new Promise((e,r)=>{try{let n=new FileReader;n.onload=()=>e(n.result),n.onerror=()=>r(n.error||new Error("Failed to read blob")),n.readAsText(t);}catch(n){r(n);}})}async function pt(t,e,r=false,n=false){let i={user_id:"",record_id:"",updated:0,uploaded:0,readonly:false,table:{name:"",access_group:0,subscription:{is_subscription_record:false,upload_to_feed:false,notify_subscribers:false,feed_referencing_records:false,notify_referencing_records:false}},referenced_count:0,source:{referencing_limit:null,prevent_multiple_referencing:false,can_remove_referencing_records:false,only_granted_can_reference:false},ip:"",bin:{}},s=false,o=[];function a(l){let d=l=="**"?"private":parseInt(l);return d=d==0?"public":d==1?"authorized":d==99?"admin":d,d}let c={ip:l=>{let d=l.split("#"),h=d[0];d.length>1&&(i.unique_id=d.slice(1).join("#")),h.slice(-1)==="R"?(i.readonly=true,h=h.slice(0,-1)):i.readonly=false,/^\d{1,3}-\d{1,3}-\d{1,3}-\d{1,3}$/.test(h)&&(h=h.split("-").join("."),s=true),i.ip=h;},rec:l=>{if(!l)return;i.record_id=l;let d=l.substring(0,l.length-9),h=fe(d);i.uploaded=h;},usr:l=>{i.user_id=l;},tbl:l=>{if(l&&!i.table.name){let d=l.split("/");i.table.name=se(d[0]),i.table.access_group=a(d[2]),d?.[3]&&(i.table.subscription.is_subscription_record=true);}},usr_tbl:l=>{let d=l.split("/");i.user_id||(i.user_id=d[0]),i.table.name||(i.table.name=se(d[1]),i.table.access_group=a(d[3]),d?.[4]&&(i.table.subscription.is_subscription_record=true));},idx:l=>{if(!l)return;let d=l.split("!"),h=se(d.splice(0,1)[0]),p=qd("!"+d.join("!"));i.index={name:h,value:p};},ref:l=>{l&&(i.reference=l.split("/")[0]);},tags:l=>{i.tags=Array.isArray(l)?l.map(d=>se(d)):l;},upd:l=>{i.updated=l;},acpt_mrf:l=>{i.source.prevent_multiple_referencing=!l;},ref_limt:l=>{i.source.referencing_limit=l;},rfd:l=>{i.referenced_count=l;},bin:async l=>{let d={},h=i?.reference||null;if(Array.isArray(l)){let p=await Promise.all(l.map(async g=>{try{let m=g.split("/").slice(3).join("/"),y=m.split("/");if(y.length<12)return null;let b=y[y.length-1],E=y[10];if(E==="__data__"&&b==="__json__.json")return {isDataFile:!0,rawUrl:g};let v=br(E),x=y[9],P=y[8],N=a(y[6]),O=g,M=N!=="public"&&Vd.call(this,y)?{expires:Ld,browserCache:Fd}:null;if(N!=="public")try{O=await Ye.bind(this)(g,{dataType:"endpoint",_ref:h});}catch(C){console.error("Error getting signed url for private file:",C),O=g;}let U={access_group:N,filename:b,url:O,path:m,size:v?v.plainSize:fe(x),uploaded:fe(P),getFile:(C,V)=>{let B={dataType:C||"download",progress:V,_ref:h},Ue=()=>Ye.bind(this)(O,Object.assign({},B,{_update:U}));return M?Ye.bind(this)(g,Object.assign({},B,M)).catch(()=>Ue()):Ue()}};return v&&(U.encrypted=!0,U.stored_size=fe(x)),{pathKey:v?v.key:E,obj:U}}catch{return null}}));for(let g of p)if(g&&!g.isDataFile){if(d[g.pathKey]){d[g.pathKey].push(g.obj);continue}d[g.pathKey]=[g.obj];}}i.bin=d;},prv_acs:l=>{for(let d in l)["notify_subscribers","upload_to_feed","feed_referencing_records","notify_referencing_records"].includes(d)?i.table.subscription[d]=l[d]:d==="referencing_index_restrictions"&&Array.isArray(l[d])?i.source[d]=l[d].map(p=>p&&typeof p=="object"&&typeof p.name=="string"?Object.assign({},p,{name:se(p.name)}):p):i.source[d]=l[d];},data:async l=>{let d={access_group:i.table.access_group,table_name:i.table.name,user_id:i.user_id,record_id:i.record_id,unique_id:i.unique_id},h=()=>{F.call(this)&&(i.encrypted={status:"failed",reason:"DATA_UNAVAILABLE"});},p=async m=>{if(n||!F.call(this)&&!mr(m))return m;let y=await Dn.bind(this)(m,d);return y.flag&&(i.encrypted=y.flag),y.value},g=$o(l);if(g!==l){i.data=await p(g);return}if(l&&typeof l=="object"&&!Array.isArray(l)&&typeof l.__data__=="string"&&Object.keys(l).length===1&&l.__data__.endsWith("/__data__/__json__.json")){let m=l.__data__,y=o.find(b=>b.endsWith(m))||null;if(!y&&!r&&h(),y){if(r){i.data=l;return}try{let b=await Ye.bind(this)(y,{dataType:"blob",_ref:i.reference||null}),E=await Ko(b);i.data=await p(JSON.parse(E));}catch(b){console.error("Failed to fetch offloaded record data:",b),i.data=null,h();}return}}i.data=await p(l);}};if(t.record_id)return t;if(Array.isArray(t.bin))for(let l of t.bin)try{if(typeof l!="string")continue;let d=l.split("/").slice(3);d.length>=12&&d[10]==="__data__"&&d[d.length-1]==="__json__.json"&&o.push(l);}catch{}let u=[];for(let l in c)if(t.hasOwnProperty(l)){let d=c[l](t[l]);d instanceof Promise&&u.push(d);}return s&&(i.user_id="anonymous:"+i.user_id),await Promise.all(u),i}function qd(t){let e=t.substring(3);switch(t.substring(0,3)){case "!S%":return e;case "!N%":let n=e.split("."),i=Number(n[0])-4503599627370496;return n.length===1?i:parseFloat(i.toString()+"."+n[1]);case "!B%":return e==="1";case "!L%":case "!D%":try{return JSON.parse(e)}catch{throw new f("Value parse error.",{code:"PARSE_ERROR"})}default:return t}}async function jo(t){let{endpoints:e}=t;if(typeof e=="string"&&(e=[e]),!Array.isArray(e))throw new f('"endpoints" should be type: array | string.',{code:"INVALID_PARAMETER"});let r=await I.bind(this)("del-files",{endpoints:e,storage:"records"},{auth:true,method:"post"}),n=[];for(let i in r)n.push(pt.bind(this)(r[i]));return Promise.all(n)}async function Ye(t,e){if(typeof t!="string")throw new f('"url" should be type: string.',{code:"INVALID_PARAMETER"});let r=t,n=t.split("?"),i=n.shift()||"",s=n.length?"?"+n.join("?"):"",o=_.Url(i);t=o+s;let a=false,c=o.split("/"),l=c[2].split("."),d=null;l.length===3&&l[1]==="skapi"&&(d=l[0],a=true);let h=c.slice(3),p=false;if(!a&&(h[0]==="auth"||h[0]==="publ"))try{_.UserId(h[2]),_.UserId(h[3]),p=h[0]=="auth",a=!0;}catch{throw new f("Invalid file url.",{code:"INVALID_PARAMETER"})}let g=d?null:h[1];if(e=_.Params(e,{expires:["number",()=>0],browserCache:["number",()=>0],refresh:["boolean",()=>false],dataType:["base64","blob","endpoint","text","info",()=>"download"],progress:["function","undefined",null],_ref:[null,"string"],_update:v=>v}),e?.dataType==="info")return {url:t,filename:h[h.length-1],fileKey:h[h.length-2],access_group:h[6]==="**"?"private":h[6]==="01"?"authorized":h[6]==="00"?"public":parseInt(h[6]),uploader:h[3],record_id:h[4]==="records"?h[5]:"N/A",filesize:fe(h[9]),uploaded:fe(h[8])};let m=t.split("/").slice(-1)[0],y=e.expires;if(y){if(!a)throw new f("Expires option can only be used on skapi cdn endpoints.",{code:"INVALID_PARAMETER"});if(y<0)throw new f('"config.expires" should be > 0. (seconds)',{code:"INVALID_PARAMETER"});let v={request:d?"get-host":"get",id:d||h[5],key:r.split("?")[0],expires:y};g&&(v.service=g);let x=e.browserCache,P={auth:true};if(x){if(x<0)throw new f('"config.browserCache" should be > 0. (seconds)',{code:"INVALID_PARAMETER"});P.method="get",P.stableGateway=true,v.browser_cache=x;let N=this.session?.idToken?.payload?.sub||this.user?.user_id;N&&(v.uid=N),v.nocache=Md(y,e.refresh);}t=(await I.bind(this)("get-signed-url",v,P)).url;}else if(p){let v=Math.floor(Date.now()/1e3);if(!this.bearerToken&&(!this.session?.idToken?.payload?.exp||this.session.idToken.payload.exp<v)){this.log("getFile:requesting new token",null);try{await Z.bind(this)().getSession({refreshToken:!0}),this.log("getFile:received new tokens",{exp:this.session?.idToken?.payload?.exp,currTime:v,expiresIn:this.session?.idToken?.payload?.exp-v,token:this.session?.accessToken?.jwtToken,refreshToken:this.session?.refreshToken?.token});}catch(O){throw this.log("getFile:new token error",O),new f("User login is required.",{code:"INVALID_REQUEST"})}}let x=this.bearerToken||this.session?.idToken?.jwtToken;if(!x||!this.user?.user_id)throw new f("User login is required.",{code:"INVALID_REQUEST"});t+=`${t.includes("?")?"&":"?"}t=${encodeURIComponent(x)}`;let P=h[6]==="**"?"**":parseInt(h[6]),N=this.user?.access_group??-1;if(this.user.user_id!==h[3]&&(P==="**"||N<P)){let O=h[5];if(this.__private_access_key[O]&&typeof this.__private_access_key[O]=="string")t+=`&p=${encodeURIComponent(this.__private_access_key[O])}`;else if(this.owner!==this.host)try{let M=await this.requestPrivateRecordAccessKey({record_id:O,reference_id:e?._ref});t+=`&p=${encodeURIComponent(M)}`;}catch{}}}if((F.call(this)?Bn(t):null)&&e?.dataType!=="endpoint"&&e?.dataType!=="info"){let v=await I.bind(this)(t,null,{method:"get",contentType:null,responseType:"blob",fetchOptions:{progress:e?.progress}},{ignoreService:true}),x=await oo.bind(this)(t,v);if(e?.dataType==="blob")return x;if(e?.dataType==="text")return await Ko(x);if(e?.dataType==="base64")return await new Promise((O,M)=>{let U=new FileReader;U.onloadend=()=>O(U.result),U.onerror=()=>M(U.error),U.readAsDataURL(x);});let P=URL.createObjectURL(x),N=document.createElement("a");return N.href=P,document.body.appendChild(N),N.setAttribute("download",m),N.click(),document.body.removeChild(N),setTimeout(()=>URL.revokeObjectURL(P),6e4),null}if(e?.dataType==="endpoint")return e._update&&(e._update.url=t),t;if(e?.dataType==="download"){let v=document.createElement("a");return v.href=t,document.body.appendChild(v),v.setAttribute("download",m),v.target="_blank",v.click(),document.body.removeChild(v),null}return new Promise(async(v,x)=>{try{let P=await I.bind(this)(t,null,{method:"get",contentType:null,responseType:e?.dataType==="text"?"text":"blob",fetchOptions:{progress:e?.progress}},{ignoreService:!0});if(e?.dataType==="base64"){let N=new FileReader;N.onloadend=()=>v(N.result),N.readAsDataURL(P);}else v(P);}catch(P){if(e?.browserCache&&!e?.refresh)try{v(await Ye.bind(this)(r,Object.assign({},e,{refresh:!0})));return}catch(N){x(N);return}x(P);}})}function Ir(t,e){return `${t||this.service}/${e||this.owner}`}function Yn(t,e){let r=this.__my_unique_ids[t];return r?r[e]:void 0}function Ho(t,e,r){this.__my_unique_ids[t]||(this.__my_unique_ids[t]={}),this.__my_unique_ids[t][e]=r;}function Bd(t,e){this.__my_unique_ids[t]&&delete this.__my_unique_ids[t][e];}async function Wo(t,e=false){t=K(t,{ignoreEmpty:true}).data||{};let r=Ir.bind(this)(t?.service,t?.owner),n="",i=Vo(t);if(i){if(t=i,n=t.record_id||t.unique_id,typeof n=="string"){typeof this.__private_access_key?.[n]=="string"&&(t.private_key=this.__private_access_key?.[n]||void 0);let s=Yn.bind(this)(r,n);s&&(e?Bd.bind(this)(r,n):t.record_id=s);}}else {let s=await Q.bind(this)(),o=t?.reference,a=false;typeof o=="object"&&Object.keys(o).length&&(o?.record_id||o?.unique_id?(n=o.record_id||o.unique_id,n&&typeof this.__private_access_key?.[n]=="string"&&(t.private_key=this.__private_access_key?.[n]||void 0),t.reference=n):o?.user_id&&(a=o.user_id===this.user?.user_id,t.reference=o.user_id)),typeof t?.table=="string"&&(t.table={name:t.table,access_group:0}),t.index&&t.index.hasOwnProperty("range")&&t.index.hasOwnProperty("condition")&&delete t.index.range;let c=u=>({table:{name:l=>gt(l,"table.name"),access_group:Jn.bind(this),subscription:l=>_.UserId(l,'User ID in "subscription"')},reference:"string",index:{name:["$updated","$uploaded","$referenced_count","$user_id",l=>Ft(l,"index.name")],value:l=>{let d={$updated:"number",$uploaded:"number",$referenced_count:"number",$user_id:_.UserId};if(d.hasOwnProperty(u.index.name)){let h=d[u.index.name];if(typeof h=="function")return h(l);if(h!==typeof l)throw new f(`"index.value" should be type: ${h}.`,{code:"INVALID_PARAMETER"});return l}return typeof l=="string"&&!l?"":typeof l=="string"&&Wn(u.index.name)?Gn(l,"index.value"):Rr(l)},condition:["gt","gte","lt","lte",">",">=","<","<=","=","eq"],range:l=>qo(l,u)},tag:l=>{if(l==null)return l;if(typeof l=="string")return vr(l,"tag");throw new f('"tag" should be type: string.',{code:"INVALID_PARAMETER"})},private_key:"string"});t=_.Params(t||{},c(t),a||s?[]:["table"],{ignoreEmpty:true});}return {query:t,is_reference_fetch:n}}async function Go(t,e){await this.__connection;let r=await Wo.bind(this)(t),n=r.is_reference_fetch,i=await I.bind(this)("get-records",r.query,{fetchOptions:e,auth:!!this.__user,method:this.__user?"post":"get"});n&&i?.reference_private_key&&typeof i.reference_private_key=="string"&&(this.__private_access_key[n]=i.reference_private_key);let s=[];for(let o in i.list)s.push(pt.bind(this)(i.list[o]));return i.list=await Promise.all(s),i}function Jo(t){let e="",r=[],n=Ir.bind(this)(t?.service,t?.owner),i=_.Params(t||{},{record_id:o=>{let a=typeof o=="string"?Yn.bind(this)(n,o):void 0;return a||ve(o,"record_id",{allowEmpty:false})},unique_id:["string",null],readonly:"boolean",table:{name:o=>gt(o,"table.name"),subscription:[null,{is_subscription_record:"boolean",upload_to_feed:"boolean",notify_subscribers:"boolean",feed_referencing_records:"boolean",notify_referencing_records:"boolean"}],access_group:Jn.bind(this)},source:{referencing_limit:o=>{if(o===null)return null;if(typeof o=="number"){if(0>o)throw new f('"reference_limit" should be >= 0',{code:"INVALID_PARAMETER"});if(o>4503599627370546)throw new f('"reference_limit" should be <= 4503599627370546',{code:"INVALID_PARAMETER"});return o}throw new f('"reference_limit" should be type: <number | null>',{code:"INVALID_PARAMETER"})},prevent_multiple_referencing:"boolean",can_remove_referencing_records:"boolean",only_granted_can_reference:"boolean",allow_granted_to_grant_others:"boolean",referencing_index_restrictions:o=>{if(o===void 0)return;if(!o||Array.isArray(o)&&!o.length)return null;let a={name:u=>Ft(u,'"name" in "index_restrictions"'),value:u=>Rr(u),condition:["gt","gte","lt","lte",">",">=","<","<=","=","eq","!=","ne",()=>null],range:u=>{if(u!==null&&typeof o.value!=typeof u)throw new f('Index restriction "range" type should match the type of "value".',{code:"INVALID_PARAMETER"});if(!o.hasOwnProperty("value"))throw new f('Index restriction "value" is required.',{code:"INVALID_PARAMETER"});return u}};Array.isArray(o)||(o=[o]);let c=o.map(u=>_.Params(u,a,["name"]));if(c.length)for(let u of c)u.condition&&u.hasOwnProperty("range")&&delete u.range;return c}},reference:o=>{if(o===null)return {record_id:null};if(o){if(typeof o=="string"){e=o;let a=Yn.bind(this)(n,o);return a||o}if(typeof o!="object")throw new f('"reference" should be type: <string | object>.',{code:"INVALID_PARAMETER"});return _.Params(o,{unique_id:"string",record_id:a=>a==null?a:(e=a,typeof this.__private_access_key?.[a]=="string"&&(t.reference_private_key=this.__private_access_key[a]||void 0),ve(a,"reference.record_id",{allowEmpty:false,onlyAlphanumeric:true}))})}},index:[null,{name:o=>Ft(o,"index.name"),value:o=>Rr(o)}],tags:o=>{if(o==null)return o;if(typeof o=="string"&&(o=o.split(",").map(a=>a.trim())),!Array.isArray(o))throw new f('"tag" should be type: <string | string[]>.',{code:"INVALID_PARAMETER"});return o.map(a=>vr(a,"tag"))},remove_bin:o=>{if(!o)return null;let a=[];if(Array.isArray(o))for(let c of o)if(typeof c=="string")a.push(c.split("?")[0]);else if(c.url&&c.size&&c.filename){let l=c.url.split("/").slice(0,3).join("/")+"/"+c.path;a.push(l);}else throw new f('"remove_bin" should be type: <string[] | BinaryFile[] | null>',{code:"INVALID_PARAMETER"});else throw new f('"remove_bin" should be type: <string[] | BinaryFile[] | null>',{code:"INVALID_PARAMETER"});return a},progress:"function",data:o=>o},[],{precall:o=>{let a=o?.data||{};if(!a?.record_id&&!a.table)throw new f('"table.name" is required.',{code:"INVALID_PARAMETER"});typeof a.table=="string"&&(a.table={name:a.table,access_group:0}),o.files&&(r=o.files);}}),s=t.progress||null;if(delete i.progress,!this.__user){let o=!!(i.table?.subscription?.is_subscription_record||i.table?.subscription?.upload_to_feed||i.table?.subscription?.notify_subscribers||i.table?.subscription?.feed_referencing_records||i.table?.subscription?.notify_referencing_records);if(i.record_id)throw new f("Public users cannot update existing records.",{code:"INVALID_REQUEST"});if(i.table.access_group!=="public"&&i.table.access_group!==0)throw new f("Public users can only post records to public tables.",{code:"INVALID_REQUEST"});if(o)throw new f("Public users cannot post subscription records.",{code:"INVALID_REQUEST"});if(i.remove_bin)throw new f("Public users cannot remove files from records.",{code:"INVALID_REQUEST"});if(i.unique_id)throw new f("Public users cannot set unique_id for records.",{code:"INVALID_REQUEST"})}return {config:i,progress:s,is_reference_post:e,files:r}}async function Yo(t){if(await this.__connection,!Array.isArray(t)||!t.length)throw new f('"params" should be a non-empty array.',{code:"INVALID_PARAMETER"});let e=[],r,n,i=null,s={},a={_is_bulk_:await Promise.all(t.map(async(p,g)=>{if(!p||typeof p!="object"||Array.isArray(p))throw new f(`"params[${g}]" should be type: <object>.`,{code:"INVALID_PARAMETER"});let m=Jo.bind(this)(p),y=m.config;if(F.call(this)){let b=Object.prototype.hasOwnProperty.call(y,"data"),E=await Cn.bind(this)(y.data,p,b);E.encrypted&&(y.data=E.send,s[g]=E.plain);}if(m.is_reference_post&&e.push(m.is_reference_post),typeof y.progress=="function"&&i===null&&(i=y.progress),y.service!==void 0){if(r===void 0)r=y.service;else if(r!==y.service)throw new f('All bulk params should share the same "service" value.',{code:"INVALID_PARAMETER"})}if(y.owner!==void 0){if(n===void 0)n=y.owner;else if(n!==y.owner)throw new f('All bulk params should share the same "owner" value.',{code:"INVALID_PARAMETER"})}return delete y.progress,delete y.service,delete y.owner,y})),service:"",owner:""};r!==void 0&&(a.service=r),n!==void 0&&(a.owner=n);let c={auth:!!this.__user,method:"post"},u={};Object.keys(u).length&&Object.assign(c,{fetchOptions:u});let l=await I.bind(this)("post-record",a,c),d=await Promise.all(l.map((p,g)=>pt.bind(this)(p,"called from postRecord",false,s.hasOwnProperty(g))));for(let p=0;p<d.length;p++)s.hasOwnProperty(p)&&d[p]&&!d[p].error&&(d[p].data=s[p],d[p].encrypted={status:"encrypted"});let h=Ir.bind(this)(r,n);for(let p=0;p<l.length;p++){let g=l[p],m=d[p];if(g&&typeof g=="object"&&g.error&&m&&!m.record_id&&(m.error=g.error),typeof g?.reference_private_key=="string")for(let y of e)this.__private_access_key[y]=g.reference_private_key;m?.unique_id&&Ho.bind(this)(h,m.unique_id,m.record_id);}return d}async function zo(t,e,r){if(await this.__connection,!e)throw new f('"config" argument is required.',{code:"INVALID_PARAMETER"});let n=Jo.bind(this)(e),i=n.config,s=n.progress,o=n.is_reference_post,a={auth:!!this.__user,method:"post"},c=[],u=K(t);r&&Array.isArray(r)&&r.length&&(c=c.concat(r)),u.files&&Array.isArray(u.files)&&u.files.length&&(c=c.concat(u.files));let l=e?.data!==void 0?e.data:u.data,d=l!==void 0,h=await Cn.bind(this)(l,e,d),p=null;p=Object.assign({},i),delete p.data,h.omit||(p.data=h.send);let g={};typeof s=="function"&&(g.progress=s),Object.keys(g).length&&Object.assign(a,{fetchOptions:g});let m=await I.bind(this)("post-record",p,a);if(h.encrypted&&m?.rec&&Fs.bind(this)(m.rec,h.dek),re()&&c.length){let E=new FormData;for(let P of c)E.append(P.name,P.file,P.file.name);let v={record_id:m.rec,progress:s};i.hasOwnProperty("service")&&(v.service=i.service);let{bin_endpoints:x}=await Ar.bind(this)(E,v);m.bin?m.bin.push(...x):m.bin=x;}o&&typeof m?.reference_private_key=="string"&&(this.__private_access_key[o]=m.reference_private_key);let y=!!m&&m.data&&typeof m.data=="object"&&!Array.isArray(m.data)&&typeof m.data.__data__=="string"&&m.data.__data__.endsWith("/__data__/__json__.json"),b=await pt.bind(this)(m,"called from postRecord",true,h.encrypted);if(y&&(b.data=u.data),h.encrypted&&(b.data=h.plain,b.encrypted={status:"encrypted",recipients:Object.keys(h.send.k||{})}),b.unique_id){let E=Ir.bind(this)(i?.service,i?.owner);Ho.bind(this)(E,b.unique_id,b.record_id),re()&&(this.__uniqueIdsPersistTimer!==null&&clearTimeout(this.__uniqueIdsPersistTimer),this.__uniqueIdsPersistTimer=setTimeout(()=>{this.__uniqueIdsPersistTimer=null;try{window.sessionStorage.setItem(`${E}:uniqueids`,JSON.stringify(this.__my_unique_ids[E]||{}));}catch{}},500));}return b}async function Qo(t,e){let r=await I.bind(this)("get-table",_.Params(t||{},{table:i=>gt(i,"table",{allowEmpty:true}),condition:["gt","gte","lt","lte",">",">=","<","<=","=","eq","!=","ne"]}),Object.assign({auth:!!this.__user},{fetchOptions:e})),n={cnt_rec:"number_of_records",tbl:"table",srvc:"service",grp_:"number_of_records_in_access_group_"};if(Array.isArray(r?.list))for(let i of r.list){for(let s in n){if(s==="grp_"){for(let o in i)if(o.startsWith("grp_")){let a=o.substring(4);a==="pv"?a="private":a==="00"?a="public":a==="01"?a="authorized":a==="99"&&(a="admin"),i[`number_of_records_in_access_group_${a}`]=i[o],delete i[o];}}i.hasOwnProperty(s)&&(i[n[s]]=i[s],delete i[s]);}typeof i.table=="string"&&(i.table=se(i.table));}return r}async function Xo(t,e){if(!t?.table)throw new f('"table" is required.',{code:"INVALID_PARAMETER"});let r=_.Params(t||{},{table:s=>gt(s,"table",{allowEmpty:true}),index:s=>Ft(s,"index.name"),order:{by:["average_number","total_number","number_count","average_bool","total_bool","bool_count","string_count","index_name","number_of_records"],value:s=>{if(t?.order?.by==="index_name"&&typeof s=="string")return ve(s,"order.value",{allowEmpty:true,maxLength:256,blockKeyDelimiters:true});if(typeof s!="string"&&typeof s!="number"&&typeof s!="boolean")throw new f('"order.value" should be type: <string | number | boolean>.',{code:"INVALID_PARAMETER"});return s},condition:["gt","gte","lt","lte",">",">=","<","<=","=","eq","!=","ne"]}},["table"]);if(r.hasOwnProperty("order")){if(!r.order?.by)throw new f('"order.by" is required.',{code:"INVALID_PARAMETER"});if(r.order.hasOwnProperty("condition")&&!r.order.hasOwnProperty("value"))throw new f('"value" is required for "condition".',{code:"INVALID_PARAMETER"});if(r.hasOwnProperty("index")&&r.index.substring(r.index.length-1)!==".")throw new f('"index" should be a parent index name of the compound index when using "order.by"',{code:"INVALID_PARAMETER"})}let n=await I.bind(this)("get-index",r,Object.assign({auth:!!this.__user},{fetchOptions:e})),i={cnt_bool:"boolean_count",cnt_numb:"number_count",totl_numb:"total_number",totl_bool:"total_bool",avrg_numb:"average_number",avrg_bool:"average_bool",cnt_str:"string_count"};return Array.isArray(n?.list)&&(n.list=n.list.map(s=>{let o=s.idx.split("/"),a={table:se(o[1]),index:se(o[2]),number_of_records:s.cnt_rec};for(let c in i)Object.prototype.hasOwnProperty.call(s,c)&&(a[i[c]]=s[c]);return a})),n}async function Zo(t,e){let r=await I.bind(this)("get-tag",_.Params(t||{},{table:n=>gt(n,"table",{allowEmpty:true}),tag:n=>vr(n,"tag",{allowEmpty:true}),condition:["gt","gte","lt","lte",">",">=","<","<=","=","eq","!=","ne"]}),Object.assign({auth:!!this.__user},{fetchOptions:e}));return Array.isArray(r?.list)&&(r.list=r.list.map(n=>{let i=n.tag.split("/");return {table:se(i[1]),tag:se(i[0]),number_of_records:n.cnt_rec}})),r}async function ea(t,e){let r=await I.bind(this)("get-uniqueid",_.Params(t||{},{unique_id:"string",condition:["gt","gte","lt","lte",">",">=","<","<=","=","eq","!=","ne"]}),Object.assign({auth:!!this.__user},{fetchOptions:e}));if(Array.isArray(r?.list))for(let n in r.list){let i=r.list[n];r.list[n]={unique_id:i.unq,record_id:i.rec};}return r}function $d(t){if(!t||typeof t!="object")return null;let e="",r="",n=0;if(typeof t.usr_tbl=="string"){let s=t.usr_tbl.split("/");e=s[0]||"",r=se(s[1]||""),n=s[3];}else if(typeof t.tbl=="string"){let s=t.tbl.split("/");r=se(s[0]||""),n=s[2],e=t.usr||"";}else return null;let i="";if(typeof t.ip=="string"){let s=t.ip.indexOf("#");s>=0&&(i=t.ip.slice(s+1));}return {access_group:n==="**"?"private":parseInt(n),table_name:r,user_id:e,record_id:t.rec||"",unique_id:i}}async function ta(t,e){await this.__connection;let r=await Wo.bind(this)(t,true),n=r.is_reference_fetch,i=await I.bind(this)("del-records",r.query,{auth:true,fetchOptions:e});if(n&&typeof i?.reference_private_key=="string"&&(this.__private_access_key[n]=i.reference_private_key),Array.isArray(i?.list)){for(let s of i.list)if(s&&typeof s=="object"&&"data"in s&&(s.data=$o(s.data),F.call(this)&&mr(s.data))){let o=$d(s);if(o){let a=await Dn.bind(this)(s.data,o);s.data=a.value,a.flag&&(s.encrypted=a.flag);}else s.data=null,s.encrypted={status:"failed",reason:"BINDING_MISMATCH"};}}return i?.message||i}async function ra(t){if(F.call(this)){let e=typeof t.user_id=="string"?[t.user_id]:t.user_id;Array.isArray(e)&&e.length&&await qn.bind(this)(t.record_id,e);}return oa.bind(this)({record_id:t.record_id,user_id:t.user_id,execute:"add"})}async function na(t){let e=await oa.bind(this)({record_id:t.record_id,user_id:t.user_id||null,execute:"remove"});if(F.call(this)){let r=typeof t.user_id=="string"?[t.user_id]:t.user_id;await zs.bind(this)(t.record_id,Array.isArray(r)&&r.length?r:null);}return e}async function ia(t,e){let r={record_id:t.record_id||void 0,user_id:t.user_id||void 0,execute:"list"};if(!r.record_id&&!r.user_id)throw new f("Either record_id or user_id must be provided.",{code:"INVALID_PARAMETER"});if(r.user_id)if(typeof r.user_id=="string")_.UserId(r.user_id),r.user_id=[r.user_id];else if(Array.isArray(r.user_id))for(let s of r.user_id)_.UserId(s);else throw new f("user_id should be type: <string | string[]>",{code:"INVALID_PARAMETER"});let n=s=>(s.rec_usr?(s.record_id=s.rec_usr.split("/")[0],s.user_id=s.rec_usr.split("/")[1]):s.usr_rec&&(s.user_id=s.usr_rec.split("/")[0],s.record_id=s.usr_rec.split("/")[1]),s),i=await I.bind(this)("grant-private-access",r,{auth:true,fetchOptions:e});return i.list=i.list.map(n),i}function sa(t){let e=t.record_id,r=t.reference_id||void 0;if(!e)throw new f("Record ID is required.",{code:"INVALID_PARAMETER"});if(typeof e!="string")throw new f("Record ID should be type: <string | string[]>",{code:"INVALID_PARAMETER"});if(r&&typeof r!="string")throw new f("Reference ID should be type: <string>",{code:"INVALID_PARAMETER"});if(typeof this.__private_access_key[e]=="string")return Promise.resolve(this.__private_access_key[e]);if(Tr[e])return Tr[e];let n=I.bind(this)("request-private-access-key",{record_id:e,reference_id:r},{auth:true}).then(i=>{let s=typeof i=="string"?i:i?.private_key;if(typeof s!="string")throw new f("Invalid private access key response.",{code:"ERROR"});return this.__private_access_key[e]=s,s}).finally(()=>{delete Tr[e];});return Tr[e]=n,n}function oa(t){t.execute;let r=_.Params(t,{record_id:"string",user_id:n=>{if(!n)throw new f("User ID is required.",{code:"INVALID_PARAMETER"});let i=n;if(typeof i=="string"&&(i=[i]),i.length>100)throw new f("Cannot process more than 100 users at once.",{code:"INVALID_REQUEST"});for(let s of i)_.UserId(s,'User ID in "user_id"');return i},execute:["add","remove"]},["execute","record_id","user_id"]);return r.user_id||(r.user_id=null),I.bind(this)("grant-private-access",r,{auth:true})}var D={},Y={},_e={},Te={},Re={},Pr={},Ur={};function aa(t,e,r){t[e]||(t[e]=[]),t[e].push(r);}async function xr(t,e,r){let n=[];if(t[e]){for(let i of t[e])if(i){let s=r(i);s instanceof Promise&&(s=await s),n.push(s);}delete t[e];}return n}async function Qn(t,e){if(!this?.session?.accessToken?.jwtToken)throw new f("Access token is required.",{code:"INVALID_PARAMETER"});let r=await this.__socket;async function n(i,s,o){this.log("answerSdpOffer from",s),await D[s].setRemoteDescription(new RTCSessionDescription(i));let a=await D[s].createAnswer();await D[s].setLocalDescription(a),o.send(JSON.stringify({action:"rtc",uid:s,content:{sdpanswer:a},token:this.session.accessToken.jwtToken}));}D?.[e]?t?(await xr(Ur,e,i=>n.bind(this)(i,e,r)),await n.bind(this)(t,e,r)):await xr(Ur,e,i=>n.bind(this)(i,e,r)):t&&aa(Ur,e,t);}async function Xn(t,e){if(this.log("receiveIceCandidate",t),D?.[e]&&D[e]?.remoteDescription&&D[e]?.remoteDescription?.type){if(!t)return xr(Pr,e,r=>D[e].addIceCandidate(r));await xr(Pr,e,r=>D[e].addIceCandidate(r)),await D[e].addIceCandidate(t);}else aa(Pr,e,t);}async function be(t){if(typeof window>"u"||window._runningInNodeJS)throw new f("WebRTC is not supported in Node.js environment.",{code:"NOT_SUPPORTED"});_.Params(t,{cid:s=>{if(typeof s!="string")throw new f('"cid" should be type: <string>.',{code:"INVALID_PARAMETER"});if(s&&s.slice(0,4)!=="cid:")throw new f('"cid" should be a valid connection id.',{code:"INVALID_PARAMETER"});return s},close:"boolean"});let e=await this.__socket,{cid:r,close_all:n=false}=t||{};if(!n&&!r)throw new f('"cid" is required.',{code:"INVALID_PARAMETER"});let i=s=>{if(!s)throw new f('"cid" is required.',{code:"INVALID_PARAMETER"});if(delete Ur[s],delete Pr[s],Y[s]&&Object.values(Y[s]).forEach(o=>{o.readyState!=="closed"&&o.close();}),delete Y[s],D?.[s]){D[s].connectionState!=="closed"&&(D[s].close(),e.send(JSON.stringify({action:"rtc",uid:s,content:{hungup:this.user.user_id},token:this.session.accessToken.jwtToken})));let o={type:"connectionstatechange",target:D[s],timestamp:new Date().toISOString(),state:D[s].connectionState,iceState:D[s].iceConnectionState,signalingState:D[s].signalingState};Re[s]&&Re[s](o),this.log("closeRTC",o);}delete Re[s],delete Te[s],delete _e[s],delete D[s];};if(n)for(let s in D)i(s);else i(r);this.log("Cleaning up media stream..."),this.__mediaStream&&(this.__mediaStream.getTracks().forEach(s=>{s.stop();}),this.__mediaStream=null);}async function ca(t){if(t instanceof MediaStream)return t;if(!t.video&&!t.audio){let e=new MediaStream,r=document.createElement("canvas");r.width=1,r.height=1;let i=r.captureStream().getVideoTracks()[0];return e.addTrack(i),e}return window.navigator.mediaDevices.getUserMedia(t)}async function ua(t,e){if(typeof window>"u"||window._runningInNodeJS)throw new f("WebRTC is not supported in Node.js environment.",{code:"NOT_SUPPORTED"});if(typeof e!="function")throw new f("Callback is required.",{code:"INVALID_PARAMETER"});if(!this?.session?.accessToken?.jwtToken)throw new f("Access token is required.",{code:"INVALID_PARAMETER"});t=_.Params(t,{cid:o=>{if(typeof o!="string")throw new f('"cid" should be type: <string>.',{code:"INVALID_PARAMETER"});if(o&&o.slice(0,4)!=="cid:")throw new f('"cid" should be a valid connection id.',{code:"INVALID_PARAMETER"});return o},ice:["string",()=>"stun:stun.skapi.com:3468"],media:o=>o,channels:["text-chat","file-transfer","video-chat","voice-chat","gaming",{ordered:"boolean",maxPacketLifeTime:"number",maxRetransmits:"number",protocol:"string"},()=>[{ordered:true,maxPacketLifeTime:10,protocol:"default"}]]},["cid"]);let{cid:r,ice:n}=t;if(!(t?.media instanceof MediaStream)&&(t?.media?.video||t?.media?.audio)&&window.location.hostname!=="localhost"&&window.location.protocol!=="https:")throw new f("Media stream is only supported on either localhost or https.",{code:"INVALID_REQUEST"});let i=this.__socket?await this.__socket:this.__socket;if(!i)throw new f("No realtime connection. Execute connectRealtime() before this method.",{code:"INVALID_REQUEST"});if(i.readyState!==1)throw new f("Realtime connection is not ready.",{code:"INVALID_REQUEST"});let s={iceServers:[{urls:n}]};D?.[r]||(D[r]=new RTCPeerConnection(s)),t?.media&&(this.__mediaStream=await ca(t.media),this.__mediaStream.getTracks().forEach(o=>{D[r].addTrack(o,this.__mediaStream);})),Re[r]=e,Y[r]||(Y[r]={});for(let o=0;o<t.channels.length;o++){let a=t.channels[o];if(typeof a=="string")switch(a){case "text-chat":a={ordered:true,maxRetransmits:10,protocol:"text-chat"};break;case "file-transfer":a={ordered:false,maxPacketLifeTime:3e3,protocol:"file-transfer"};break;case "video-chat":a={ordered:true,maxRetransmits:10,protocol:"video-chat"};break;case "voice-chat":a={ordered:true,maxRetransmits:10,protocol:"voice-chat"};break;case "gaming":a={ordered:false,maxPacketLifeTime:100,protocol:"gaming"};break;default:a={ordered:true,maxRetransmits:10,protocol:"default"};break}let c=a.protocol||"default";if(Object.keys(Y[r]).includes(c))throw new f(`Data channel with the protocol "${c}" already exists.`,{code:"INVALID_REQUEST"});let u=D[r].createDataChannel(c,a);Y[r][c]=u;}for(let o in Y[r]){let a=Y[r][o];fa.bind(this)(r,a);}return da.bind(this)(r,["onnegotiationneeded"]),await zn.bind(this)(r),{hangup:()=>_e[r]&&_e[r](false),connection:new Promise(o=>{_e[r]=(a=>{if(this.log("receiver picked up the call",r),!a)return be.bind(this)({cid:r}),null;D[r].onnegotiationneeded=()=>{this.log("onnegotiationneeded",`sending offer to "${r}".`),zn.bind(this)(r),Re[r]&&Re[r]({type:"negotiationneeded",target:D[r],timestamp:new Date().toISOString(),signalingState:D[r].signalingState,connectionState:D[r].iceConnectionState,gatheringState:D[r].iceGatheringState});},o({target:D[r],channels:Y[r],hangup:()=>be.bind(this)({cid:r}),media:this.__mediaStream});}).bind(this);})}}function la(t){return async(e,r)=>{e=e||{},e=K(e).data;let n=t.sender_cid,i=await this.__socket;if(!Te[n])return null;if(typeof r!="function")throw new f("Callback is required.",{code:"INVALID_PARAMETER"});if(!(e?.media instanceof MediaStream)&&(e?.media?.video||e?.media?.audio)&&window.location.hostname!=="localhost"&&window.location.protocol!=="https:")throw new f("Media stream is only supported on either localhost or https.",{code:"INVALID_REQUEST"});let{ice:s="stun:stun.skapi.com:3468"}=e;return D?.[n]||(D[n]=new RTCPeerConnection({iceServers:[{urls:s}]})),e?.media&&(this.__mediaStream=await ca(e.media),this.__mediaStream.getTracks().forEach(o=>{D[n].addTrack(o,this.__mediaStream);})),delete Te[n],Re[n]=r,Y[n]||(Y[n]={}),D[n].ondatachannel=o=>{this.log("ondatachannel",`received data channel "${o.channel.label}".`);let a=o.channel;Y[n][a.label]=a,fa.bind(this)(n,a);},da.bind(this)(n,["onnegotiationneeded"]),await Qn.bind(this)(null,n),await Xn.bind(this)(null,n),i.send(JSON.stringify({action:"rtc",uid:n,content:{pickup:this.user.user_id},token:this.session.accessToken.jwtToken})),{target:D[n],channels:Y[n],hangup:()=>be.bind(this)({cid:n}),media:this.__mediaStream}}}async function zn(t){if(!this?.session?.accessToken?.jwtToken)throw new f("Access token is required.",{code:"INVALID_PARAMETER"});this.log("sendOffer",t);let e=await this.__socket,r=await D[t].createOffer();await D[t].setLocalDescription(r);let n=D[t].localDescription;this.log("rtcSdpOffer to",n),e.send(JSON.stringify({action:"rtc",uid:t,content:{sdpoffer:n},token:this.session.accessToken.jwtToken}));}async function Kd(t,e){if(!this?.session?.accessToken?.jwtToken)throw new f("Access token is required.",{code:"INVALID_PARAMETER"});this.log("sendIceCandidate to",e);let r=await this.__socket;if(!t.candidate){this.log("candidate-end","all ice candidates have been sent");return}let n=Re[e]||(()=>{}),i=t.candidate;this.log("ice gathering state set to",D[e].iceGatheringState),n({type:"icecandidate",target:D[e],timestamp:new Date().toISOString(),candidate:t.candidate.candidate,sdpMid:t.candidate.sdpMid,sdpMLineIndex:t.candidate.sdpMLineIndex,usernameFragment:t.candidate.usernameFragment,protocol:t.candidate.protocol,gatheringState:D[e].iceGatheringState,connectionState:D[e].iceConnectionState}),r.send(JSON.stringify({action:"rtc",uid:e,content:{candidate:i},token:this.session.accessToken.jwtToken}));}function da(t,e){let r=new Set(e),n=Re[t]||(o=>{}),i=D[t],s={ontrack:o=>{n({type:"track",target:i,timeStamp:o.timeStamp,streams:o.streams,track:o.track});},onicecandidate:o=>{Kd.bind(this)(o,t),o.candidate?n({type:"icecandidate",target:i,timestamp:new Date().toISOString(),candidate:o.candidate.candidate,sdpMid:o.candidate.sdpMid,sdpMLineIndex:o.candidate.sdpMLineIndex,usernameFragment:o.candidate.usernameFragment,protocol:o.candidate.protocol,gatheringState:i.iceGatheringState,connectionState:i.iceConnectionState}):n({type:"icecandidateend",target:i,timestamp:new Date().toISOString()});},onicecandidateerror:o=>{n({type:"icecandidateerror",target:i,timestamp:new Date().toISOString(),errorCode:o.errorCode,errorText:o.errorText,url:o.url,hostCandidate:o.hostCandidate,gatheringState:i.iceGatheringState,connectionState:i.iceConnectionState});},oniceconnectionstatechange:()=>{n({type:"iceconnectionstatechange",target:i,timestamp:new Date().toISOString(),state:i.iceConnectionState,gatheringState:i.iceGatheringState,signalingState:i.signalingState});},onicegatheringstatechange:()=>{n({type:"icegatheringstatechange",target:i,timestamp:new Date().toISOString(),state:i.iceGatheringState,connectionState:i.iceConnectionState,signalingState:i.signalingState});},onsignalingstatechange:()=>{n({type:"signalingstatechange",target:i,timestamp:new Date().toISOString(),state:i.signalingState,connectionState:i.iceConnectionState,gatheringState:i.iceGatheringState});},onnegotiationneeded:()=>{zn.bind(this)(t),n({type:"negotiationneeded",target:i,timestamp:new Date().toISOString(),signalingState:i.signalingState,connectionState:i.iceConnectionState,gatheringState:i.iceGatheringState});},onconnectionstatechange:()=>{n({type:"connectionstatechange",target:i,timestamp:new Date().toISOString(),state:i.connectionState,iceState:i.iceConnectionState,signalingState:i.signalingState});let o=i.connectionState;(o==="disconnected"||o==="failed"||o==="closed")&&be.bind(this)({cid:t});}};for(let[o,a]of Object.entries(s))r.has(o)||(i[o]=a);}function fa(t,e,r){let n=new Set(r),i=Re[t]||(o=>{}),s={onmessage:o=>{let a={type:o.type,target:e,timeStamp:o.timeStamp,data:o.data,lastEventId:o.lastEventId,origin:o.origin,readyState:e.readyState,bufferedAmount:e.bufferedAmount};this.log(`${e.label}: message`,o.data),i(a);},onerror:o=>{let a={type:o.type,target:e,timeStamp:o.timeStamp,error:o.error.message,errorCode:o.error.errorDetail,readyState:e.readyState,label:e.label};this.log(`${e.label}: error`,o.error.message),i(a);},onclose:o=>{let a={type:o.type,target:e,timeStamp:o.timeStamp,readyState:e.readyState,label:e.label,id:e.id};this.log(`${e.label}: closed`,null),i(a),Y[t]&&(delete Y[t][e.label],Object.keys(Y[t]).length===0&&be.bind(this)({cid:t}));},onbufferedamountlow:o=>{let a={target:e,bufferedAmount:e.bufferedAmount,bufferedAmountLowThreshold:e.bufferedAmountLowThreshold,type:o.type,timeStamp:o.timeStamp};this.log(`${e.label}: bufferedamountlow`,e.bufferedAmount),i(a);},onopen:o=>{this.log("dataChannel",`data channel: "${e.label}" is open and ready to send messages.`);let a={type:o.type,target:e,timeStamp:o.timeStamp,readyState:e.readyState,label:e.label,id:e.id,ordered:e.ordered,maxRetransmits:e.maxRetransmits,protocol:e.protocol};i(a);}};for(let[o,a]of Object.entries(s))n.has(o)||(e[o]=a);}var $e,Be=null,Lt=true,mt=0;async function jd(){if(typeof window>"u"||window._runningInNodeJS)throw new f("WebSocket is not supported in Node.js environment.",{code:"NOT_SUPPORTED"});if(await this.getProfile(),!this.session)throw new f("No access.",{code:"INVALID_REQUEST"});let t=await this.record_endpoint;return new WebSocket(t.websocket_private+"?token="+this.session.accessToken.jwtToken)}var Zn=null;async function ha(){if(typeof window>"u"||window._runningInNodeJS)throw new f("WebSocket is not supported in Node.js environment.",{code:"NOT_SUPPORTED"});Lt=true;let t=this.__socket?await this.__socket:this.__socket;be.bind(this)({close_all:true}),$e&&ei.bind(this)({group:null}),mt=0,Be&&(Be.terminate(),Be=null);try{t&&t.close();}catch{}return window.removeEventListener("visibilitychange",Zn),this.__socket=null,null}async function Cr(t,e=50,r){if(typeof window>"u"||window._runningInNodeJS)throw new f("WebSocket is not supported in Node.js environment.",{code:"NOT_SUPPORTED"});if(typeof t!="function")throw new f("Callback must be a function.",{code:"INVALID_REQUEST"});if(r==="reconnect"){if(this.__socket instanceof Promise){let n=await this.__socket;if(n.readyState!==WebSocket.CLOSED&&n.readyState!==WebSocket.CLOSING)return this.__socket}}else if(Lt&&(Zn=()=>{!document.hidden&&!Lt&&Cr.bind(this)(t,0,"reconnect");},this.__socket instanceof Promise))return this.__socket;Be&&(Be.terminate(),Be=null),this.__socket=new Promise(async n=>{await ft.bind(this)(),setTimeout(async()=>{let i=await jd.bind(this)();i.onopen=()=>{Lt=false,mt=0,r!=="reconnect"&&window.addEventListener("visibilitychange",Zn),this.log("realtime onopen","Connected to WebSocket server."),t({type:"success",message:"Connected to WebSocket server."}),$e&&i.send(JSON.stringify({action:"joinRoom",rid:$e,token:this.session.accessToken.jwtToken}));let s=`
208
208
  let interval = 15000; // Set interval time 15 seconds
209
209
 
210
210
  function runInterval() {
@@ -213,9 +213,9 @@ var zs=Object.create;var Fe=Object.defineProperty;var Gr=Object.getOwnPropertyDe
213
213
  }
214
214
 
215
215
  runInterval(); // Start interval
216
- `,o=new Blob([s],{type:"application/javascript"});Te=new Worker(URL.createObjectURL(o)),Te.onmessage=a=>{i.readyState===1&&i.send(JSON.stringify({action:"keepAlive"}));},n(i);},i.onmessage=async s=>{let o="";try{o=JSON.parse(decodeURI(s.data)),this.log("socket onmessage",o);}catch{return}let a;switch(true){case !!o?.["#message"]:a="message";break;case !!o?.["#private"]:a="private";break;case !!o?.["#notice"]:a="notice";break;case !!o?.["#rtc"]:a="rtc";break;case !!o?.["#error"]:a="error";break}if(!a)return;let u={type:a,message:o?.["#rtc"]||o?.["#message"]||o?.["#private"]||o?.["#notice"]||o?.["#error"]||null,sender:o?.["#user_id"]||null,sender_cid:o?.["#scid"]?"cid:"+o["#scid"]:null,sender_rid:o?.["#srid"]||null,code:o?.["#code"]||null};if(a==="notice")r(u);else if(a==="rtc"){if(u.sender!==this.user.user_id){let c=u.message;if(c.hungup){oe[u.sender_cid]&&(oe[u.sender_cid](false),delete oe[u.sender_cid]),ge[u.sender_cid]&&delete ge[u.sender_cid],U?.[u.sender_cid]&&ae.bind(this)({cid:u.sender_cid}),u.type="rtc:closed",r(u);return}if(c.candidate&&$r.bind(this)(c.candidate,u.sender_cid),c.sdpoffer&&(Br.bind(this)(c.sdpoffer,u.sender_cid),ge[u.sender_cid]||(ge[u.sender_cid]=u.sender_cid,delete u.message,u.connectRTC=ts.bind(this)(u),u.type="rtc:incoming",u.hangup=(()=>{U[u.sender_cid]?ae.bind(this)({cid:u.sender_cid}):ge[u.sender_cid]&&(delete ge[u.sender_cid],i.send(JSON.stringify({action:"rtc",uid:u.sender_cid,content:{hungup:this.user.user_id},token:this.session.accessToken.jwtToken})));}).bind(this),r(u))),c.pickup&&oe[u.sender_cid]&&(oe[u.sender_cid](true),delete oe[u.sender_cid]),c.sdpanswer&&U[u.sender_cid])if(U[u.sender_cid].signalingState==="have-local-offer")await U[u.sender_cid].setRemoteDescription(new RTCSessionDescription(c.sdpanswer));else throw new f("Invalid signaling state.",{code:"INVALID_REQUEST"})}}else r(u);},i.onclose=()=>{at?(this.log("realtime onclose","WebSocket connection closed."),r({type:"close",message:"WebSocket connection closed."})):(this.log("realtime onclose","WebSocket unexpected close."),r({type:"error",message:"Skapi: WebSocket unexpected close."}),Ye++,Ye<3?(this.log("realtime onclose","Reconnecting to WebSocket server..."+Ye),r({type:"reconnect",message:"Reconnecting to WebSocket server..."+Ye}),Jt.bind(this)(r,3e3,"reconnect")):(this.log("realtime onclose","Max reconnection attempts reached."),r({type:"error",message:"Skapi: Max reconnection attempts reached."})));},i.onerror=()=>{this.log("realtime onerror","WebSocket connection error."),r({type:"error",message:"Skapi: WebSocket connection error."});};},e);});}async function ss(r,e,t){if(typeof window>"u"||window._runningInNodeJS)throw new f("WebSocket is not supported in Node.js environment.",{code:"NOT_SUPPORTED"});let n=this.__socket?await this.__socket:this.__socket;if(!n)throw new f("No realtime connection. Execute connectRealtime() before this method.",{code:"INVALID_REQUEST"});if(!e)throw new f("No recipient.",{code:"INVALID_REQUEST"});await Je.bind(this)(),r=M(r).data;let i="";if(t&&(t=m.Params(t,{config:{always:"boolean"},title:"string",body:"string"},["title","body"]),i=JSON.stringify({title:t.title,body:t.body}),new Blob([i]).size>3072))throw new f("Notification size exceeds 3kb.",{code:"INVALID_PARAMETER"});if(n.readyState===1){try{m.UserId(e),n.send(JSON.stringify({action:"sendMessage",uid:e,content:r,notification:i,notificationConfig:t?.config||{},token:`IdT:${this.service}:${this.owner}:`+(this.bearerToken||this.session?.idToken?.jwtToken||"null")}));}catch(s){if(this.log("postRealtime:err",{err:s}),Re!==e)throw new f(`User has not joined to the recipient group. Run joinRealtime({ group: "${e}" })`,{code:"INVALID_REQUEST"});n.send(JSON.stringify({action:"broadcast",rid:e,content:r,notification:i,notificationConfig:t?.config||{},token:`IdT:${this.service}:${this.owner}:`+(this.bearerToken||this.session?.idToken?.jwtToken||"null")}));}return {type:"success",message:"Message sent."}}throw new f("Realtime connection is not open. Try reconnecting with connectRealtime().",{code:"INVALID_REQUEST"})}async function Kr(r){if(typeof window>"u"||window._runningInNodeJS)throw new f("WebSocket is not supported in Node.js environment.",{code:"NOT_SUPPORTED"});let e=this.__socket?await this.__socket:this.__socket;if(!e)throw new f("No realtime connection. Execute connectRealtime() before this method.",{code:"INVALID_REQUEST"});await Je.bind(this)(),r=M(r,{nullIfEmpty:true}).data;let{group:t=null}=r;if(!t&&!Re)return {type:"success",message:"Left realtime message group."};if(t!==null&&typeof t!="string")throw new f('"group" must be a string | null.',{code:"INVALID_PARAMETER"});return e.send(JSON.stringify({action:"joinRoom",rid:t,token:this.session.accessToken.jwtToken})),Re=t,{type:"success",message:t?`Joined realtime message group: "${t}".`:"Left realtime message group."}}async function os(r,e){r=m.Params(r,{user_id:n=>m.UserId(n,'User ID in "user_id"'),group:["string",()=>{if(!Re)throw new f('No group has been joined. Otherwise "group" is required.',{code:"INVALID_REQUEST"});return Re}]});let t=await T.bind(this)("get-ws-group",r,{fetchOptions:e,auth:true,method:"post"});return t.list=t.list.map(n=>({user_id:n.uid.split("#")[1],cid:"cid:"+n.cid})),t}async function as(r,e){if(await this.__connection,r||(r={searchFor:"group",value:" ",condition:">"}),r=m.Params(r,{searchFor:["group","number_of_users",()=>"group"],value:["string","number",()=>r?.searchFor&&r?.searchFor==="number_of_users"?0:" "],condition:[">",">=","=","<","<=","!=","gt","gte","eq","lt","lte","ne"],range:["string","number"]}),r.condition||(r.value===" "||!r.value?r.condition=">":r.condition="="),r.range&&r.condition&&delete r.condition,r.searchFor==="number_of_users"&&typeof r.value!="number")throw new f('"value" must be a number.',{code:"INVALID_PARAMETER"});if(r.searchFor==="group"&&typeof r.value!="string")throw new f('"value" must be a string.',{code:"INVALID_PARAMETER"});if(r.hasOwnProperty("range")&&typeof r.range!=typeof r.value)throw new f(`"range" must be a ${typeof r.value}.`,{code:"INVALID_PARAMETER"});let t=await T.bind(this)("get-ws-group",r,{fetchOptions:e,auth:true,method:"post"});return t.list=t.list.map(n=>({group:n.rid.split("#")[1],number_of_users:n.cnt})),t}var us=typeof FormData<"u",cs=typeof HTMLFormElement<"u",ls=typeof SubmitEvent<"u",pe={},ut={},me={};function Hr(r){return Object.freeze({id:r,status:"stopped"})}function ds(r){return !!r&&typeof r=="object"&&r.status==="stopped"}function fs({id:r,auth:e,service:t,owner:n,latency:i=1e3,queue:s,onResponse:o,onError:a}){if(typeof i!="number")throw new f('"latency" should be a number.',{code:"INVALID_PARAMETER"});if(i<0)throw new f('"latency" should be a non-negative number.',{code:"INVALID_PARAMETER"});s&&!pe?.[s]&&(pe[s]=new nt({breakWhenError:false,batchSize:1}));let u={stop:null,aborted:false,queue:s};me[r]=u;let c=()=>{me[r]===u&&delete me[r];},l=()=>new Promise((h,p)=>{let g=false;if(u.aborted){c(),h(Hr(r));return}let _=setInterval(async()=>{try{let w=await T.bind(this)("csr-poll",{id:r,service:t,owner:n},{auth:e});if(w.status==="running"||w.status==="pending"||g)return;g=!0,o&&o(w),clearInterval(_),c(),h(w);}catch(w){if(g)return;g=true,a&&a(w),clearInterval(_),c(),p(w);}},i);u.stop=()=>{g||(g=true,clearInterval(_),c(),h(Hr(r)));};}),d=()=>{let h=me[r];h&&(h.stop?h.stop():(h.aborted=true,delete me[r]));};if(s){let h=new Promise((p,g)=>{let _=false,w=pe[s].add([async()=>{try{let b=await l();return _||(_=!0,p(b)),b}catch(b){throw _||(_=true,g(b)),b}}])[0];ut[r]=w,u.stop=()=>{if(!_){u.aborted=true;try{pe[s]&&pe[s].remove(ut[r]);}catch{}delete ut[r],c(),_=true,p(Hr(r));}};});return Object.assign(h,{stop:d})}else return Object.assign(l(),{stop:d})}function hs(r){let e=0,t=[];if(r?.id){if(r.url&&r.method){let n=r.service||this.service;t.push(`[${r.method.toUpperCase()}]${r.url.toLowerCase()}#${n}:${r.id}`);}t.push(r.id);}else if(r?.queue)for(let n in me)me[n]?.queue===r.queue&&t.push(n);else for(let n in me)t.push(n);for(let n of t){let i=me[n];i&&(i.stop?i.stop():(i.aborted=true,delete me[n]),e+=1);}return e}function gs(r,e){if(!r.queue)throw new f('"queue" is required.',{code:"INVALID_PARAMETER"});let t={service:r.service||this.service,owner:r.owner||this.owner,queue:r.queue+":"};return T.bind(this)("csr-poll",t,{auth:true})}async function ps(r){let e=false;if(typeof r.poll=="number"&&r.poll<0)throw new f('"poll" should be a non-negative number.',{code:"INVALID_PARAMETER"});let t=r?.onResponse,n=r?.onError,i=typeof r.poll=="number"?r.poll:r.poll?1e3:0;delete r.poll,i&&!r.queue&&(r.queue=(this.__user?.user_id||"anonymous")+"-"+De());let s=u=>{for(let c in u)if(typeof u[c]=="string"&&u[c].includes("$CLIENT_SECRET")){e=true;break}};if(r=m.Params(r,{url:u=>{if(!u||typeof u!="string")throw new f('"url" should be type: <string>.',{code:"INVALID_PARAMETER"});return m.Url(u),u.includes("$CLIENT_SECRET")&&(e=true),u},clientSecretName:"string",method:u=>{if(u&&typeof u!="string")throw new f('"method" should be either "GET" or "POST" or "DELETE" or "PUT".',{code:"INVALID_PARAMETER"});let c=u.toLowerCase();if(c!=="get"&&c!=="post"&&c!=="delete"&&c!=="put")throw new f('"method" should be either "GET" or "POST" or "DELETE" or "PUT".',{code:"INVALID_PARAMETER"});return c},headers:u=>{if(u&&typeof u!="object")throw new f('"headers" should be type: <object>.',{code:"INVALID_PARAMETER"});return s(u),u},data:u=>{if(u&&typeof u!="object")throw new f('"data" should be type: <object>.',{code:"INVALID_PARAMETER"});return s(u),u},params:u=>{if(u&&typeof u!="object")throw new f('"params" should be type: <object>.',{code:"INVALID_PARAMETER"});return s(u),u},expires:"number",queue:"string"},["clientSecretName","method","url"]),!e)throw new f(`At least one parameter value should include "$CLIENT_SECRET" in ${r.method.toLowerCase()==="post"?'"data"':'"params"'} or "headers".`,{code:"INVALID_PARAMETER"});await this.__connection;let o=!!this.__user,a=()=>T.bind(this)("csr",r,{auth:o,tokenHeaders:{accessToken:!!o}}).then(u=>{if(u.status==="running"||u.status==="pending"){let c=`[${r.method.toUpperCase()}]${r.url.toLowerCase()}`,l=r.service||this.service,d=r.owner||this.owner,h=`${c}#${l}:${u.id}`;Object.assign(u,{poll:p=>fs.call(this,{id:h,auth:o,service:l,owner:d,latency:p?.latency||1e3,queue:r?.queue,onResponse:t,onError:n})});}return t?t(u):u}).catch(u=>{if(n)return n(u);throw u});if(r?.queue){let u="base:"+r.queue;return pe?.[u]||(pe[u]=new nt({breakWhenError:false,batchSize:1})),new Promise((c,l)=>{pe[u].add([async()=>{try{let d=await a();if(i>0){let h=d.poll({latency:i});return c(h),h}return c(d),d}catch(d){throw l(d),d}}]);})}else return a()}async function ms(r,e){await this.__connection;let t=r.service||this.service,n=r.owner||this.owner;r=m.Params(r,{url:"string",method:["GET","POST","DELETE","PUT"],queue:"string",status:["pending","running","resolved","failed"],compact:"boolean",queue_exact:"boolean",queue_exclude:"string"},["url","method"]);let i=!!this.__user,s=`[${r.method.toUpperCase()}]${r.url.toLowerCase()}#${t}:`,o={id:s,queue:r?.queue,status:r?.status,service:t,owner:n};r?.compact&&(o.compact=true),r?.queue_exact&&(o.queue_exact=true),r?.queue_exclude&&(o.queue_exclude=r.queue_exclude),Object.keys(o).forEach(u=>{o[u]||delete o[u];}),o.queue&&(o.id_prefix=o.id,delete o.id);let a=await T.bind(this)("csr-poll",o,{auth:i,fetchOptions:e});return a.list=a.list.map(u=>{let c={id:u.id,status_code:u.rslv?.status_code||null,response_body:u.rslv?.body||u.rslv?.truncated||null,error:u?.err,created:u?.stmp,updated:u?.utmp,request_body:u?.reqbdy,expires:u?.expt,status:u.stts,queue_name:u?.qid,request_text:u?.reqtxt,response_text:u?.rslvtxt,response_complete_marker:u?.rslvmk!=null?!!u.rslvmk:void 0,compact:u?.cmpct?true:void 0};for(let l in c)c[l]===void 0&&delete c[l];return (c.status==="running"||c.status==="pending")&&(c.poll=l=>fs.call(this,{id:s+c.id,auth:i,service:t,owner:n,latency:l?.latency||1e3,queue:u?.qid,onResponse:l?.onResponse,onError:l?.onError})),c}),a}async function _s(r){await this.__connection,r=m.Params(r,{url:"string",method:["GET","POST","DELETE","PUT"],id:"string",queue:"string"},["url","method","id"]);let e=r?.service||this.service,t=r?.owner||this.owner,n=!!this.__user,i=`[${r.method.toUpperCase()}]${r.url.toLowerCase()}#${e}`,s=r.id,o=`${i}:${s}`,a=r?.queue;return a&&pe?.[a]&&(pe[a].remove(ut[o]),delete ut[o]),T.bind(this)("csr-cancel",{id:o,service:e,owner:t},{auth:n})}async function bs(r){await this.__connection;let e={name:"string",email:t=>(m.Email(t),t),subject:"string",message:"string"};return r=m.Params(r,e,["name","email","subject","message"]),await T.bind(this)("send-inquiry",r),"SUCCESS: Inquiry has been sent."}async function ys(r,e){if(await this.__connection,us&&r instanceof FormData||cs&&r instanceof HTMLFormElement||ls&&r instanceof SubmitEvent){if(!e)throw new f("Url string as a second argument is required when form is passed.",{code:"INVALID_PARAMETER"});let n=M(r);r={url:e,data:n.data,sync:true};}let t={url:n=>m.Url(n),data:n=>n,sync:["boolean",()=>true]};if(Array.isArray(r))for(let n of r)n=m.Params(n,t);else r=m.Params(r,t);return T.bind(this)("post-secure",r,{auth:true})}async function ws(r,e){await this.__connection;let{auth:t=false,method:n="POST",bypassAwaitConnection:i=false,responseType:s,contentType:o,tokenHeaders:a,progress:u}=e||{};if(e=Object.assign({auth:t,method:n,bypassAwaitConnection:i,responseType:s,contentType:o,tokenHeaders:a},{fetchOptions:{progress:u}}),typeof r!="object"&&(o==="application/json"||o===void 0))throw new f('"data" should be type: <object>.',{code:"INVALID_PARAMETER"});return T.bind(this)("mock",r,e)}async function Es(r,e){if(await this.__connection,!e?.url||typeof e.url!="string")throw new f('"url" is required in the second argument.',{code:"INVALID_PARAMETER"});m.Url(e.url);let n=(await this.admin_endpoint)?.forward_request;if(!n)throw new f("forwardRequest is not available on this service region yet.",{code:"NOT_EXISTS"});let i=null,s=null,o=ls&&r instanceof SubmitEvent?r.target:cs&&r instanceof HTMLFormElement?r:null;o?i=new FormData(o):us&&r instanceof FormData?i=r:r!=null&&(i=JSON.stringify(r),s="application/json");let a={public_identifier:this.__public_identifier,service:this.service,owner:this.owner,forward:{url:e.url,method:e.method||"POST",headers:e.headers||{},apiKeyHeader:e.apiKeyHeader,apiKeyScheme:e.apiKeyScheme}},u=JSON.stringify(a).replace(/[\u007f-\uffff]/g,p=>"\\u"+p.charCodeAt(0).toString(16).padStart(4,"0"));if(u.length>4096)throw new f("Destination url and headers are too large for Content-Meta.",{code:"INVALID_PARAMETER"});let c=this.bearerToken||this.session?.idToken?.jwtToken||null;if(!c)throw new f("User login is required.",{code:"INVALID_REQUEST"});let l={"Content-Meta":u,Authorization:c};s&&(l["Content-Type"]=s);let d=await fetch(n,{method:"POST",headers:l,body:i,signal:e.signal});if(e.responseType==="response")return d;if(!d.ok){let p=await d.text();try{p=JSON.parse(p);}catch{}throw new f(p?.message||(typeof p=="string"?p:JSON.stringify(p)),{code:p?.code||"ERROR"})}if(e.onStream&&d.body){let p=d.body.getReader(),g=new TextDecoder,_="";for(;;){let{done:w,value:b}=await p.read();if(w)break;let A=g.decode(b,{stream:true});_+=A;try{e.onStream(A);}catch(x){console.error(x);}}return _}let h=await d.text();if(e.responseType==="text")return h;try{return JSON.parse(h)}catch{return h}}async function As(r,e){await this.__connection,r=m.Params(r||{},{access_group:n=>{if(n==="authorized"&&(n=1),n==="public"&&(n=0),typeof n!="number")throw new f('"access_group" should be type number.',{code:"INVALID_PARAMETER"});if(n<0)throw new f('"access_group" should be zero or a positive number.',{code:"INVALID_PARAMETER"});if(n>this.__user.access_group)throw new f("User has no access.",{code:"INVALID_REQUEST"});return n}});let t=await T.bind(this)("get-feed",r,{auth:true,fetchOptions:e});for(let n in t.list)t.list[n]=await ze.bind(this)(t.list[n]);return t}function ct(r){if(r===this.__user.user_id)throw new f(`"user_id" cannot be the user's own ID.`,{code:"INVALID_PARAMETER"});return m.UserId(r,'"user_id"')}async function Ss(r,e){if(r=M(r,{ignoreEmpty:true}).data,r=m.Params(r,{subscriber:n=>m.UserId(n,'User ID in "subscriber"'),subscription:ct.bind(this),blocked:"boolean"}),!r.subscriber&&!r.subscription)throw new f('At least either "subscriber" or "subscription" should have a value.',{code:"INVALID_PARAMETER"});let t=await T.bind(this)("get-subscription",r,Object.assign({auth:true},{fetchOptions:e}));return t.list=t.list.map((n=>{let i={};if(n.sub){let s=n.sub.split("#");i.subscriber=s[2],i.subscription=s[0];}else i.subscriber=n.subscriber,i.subscription=n.subscription;return i.timestamp=n?.timestamp||n.stmp,i.blocked=n?.blocked||n.grp.substring(0,1)==="N",Object.assign(i,n.opt),i})),t}async function vs(r){await this.__connection,r=m.Params(r,{user_id:ct.bind(this),get_feed:["boolean",()=>false],get_notified:["boolean",()=>false],get_email:n=>{if(n&&!this.__user.email||!this.__user.email_verified)throw new f("User has no verified email address.",{code:"INVALID_REQUEST"});return !!n}},["user_id"]);let e=await T.bind(this)("subscription",{subscribe:r.user_id,option:{get_feed:r.get_feed,get_notified:r.get_notified,get_email:r.get_email||false}},{auth:true}),t={};if(e.sub){let n=e.sub.split("#");t.subscriber=n[2],t.subscription=n[0];}else t.subscriber=e.subscriber,t.subscription=e.subscription;return t.timestamp=e?.timestamp||e.stmp,t.blocked=e?.blocked||e.grp.substring(0,1)==="N",Object.assign(t,e.opt),t}async function Ts(r){await this.__connection;let{user_id:e}=m.Params(r,{user_id:ct.bind(this)},["user_id"]);return await T.bind(this)("subscription",{unsubscribe:e},{auth:true})}async function Rs(r){await this.__connection;let{user_id:e}=m.Params(r,{user_id:ct.bind(this)},["user_id"]);return await T.bind(this)("subscription",{block:e},{auth:true})}async function Is(r){await this.__connection;let{user_id:e}=m.Params(r,{user_id:ct.bind(this)},["user_id"]);return await T.bind(this)("subscription",{unblock:e},{auth:true})}async function Ps(r,e){await this.__connection;let t=await H.bind(this)();r=m.Params(r,{user_id:o=>{if(o!==this.__user.user_id&&!t)throw new f("No access.",{code:"INVALID_REQUEST"});return o},group:o=>{if(o==="public"&&(o=0),o==="authorized"&&(o=1),typeof o!="number")throw new f('"group" should be type number | "public" | "authorized".',{code:"INVALID_PARAMETER"});return o}});let n=await T.bind(this)("get-newsletter-subscription",r,{auth:true,fetchOptions:e||null}),i=n?.list||n,s=[];Array.isArray(i)||(i=[]);for(let o of i){let a=o.subt.split("#"),u=true;a[0].charAt(0)==="@"&&(u=false,a[0]=a[0].substring(1));let c=parseInt(a[0]);s.push({timestamp:o.stmp,group:c,subscribed_email:a[1],active:u});}return n?.list?(n.list=s,n):s}async function xs(r){await this.__connection;let e=m.Params(r||{},{email:t=>Array.isArray(t)&&t.length>0?t.length===1?m.Email(t[0]):t.map(n=>m.Email(n)):m.Email(t),group:["number","public","authorized","admin",t=>{if(typeof t!="string"||t.length>20||!/^[a-zA-Z0-9]+$/.test(t))throw new f('"group" should be an alphanumeric string without spaces and less than 20 characters.',{code:"INVALID_PARAMETER"});return t}],redirect:t=>m.Url(t)},this.__user?["group"]:["email","group"]);return T.bind(this)(`subscribe-${this.__user?"":"public-"}newsletter`,e,{auth:!!this.__user})}async function Us(r){await this.__connection,r=m.Params(r,{group:["number","public","authorized","admin"]},["group"]);let e=Object.assign({action:"unsubscribe"},r);return T.bind(this)("subscribe-newsletter",e,{auth:true})}async function Cs(r,e){let t=await H.bind(this)(),n={message_id:"string",timestamp:"number",read:"number",complaint:"number",subject:"string",bounced:"number"};r||(e=Object.assign({ascending:false},e||{})),r=M(r).data,r=r||{searchFor:"timestamp",value:Date.now(),condition:"<",group:"public"},r=m.Params(r,{searchFor:["message_id","timestamp","subject","complaint","read","bounced"],value:u=>{if(typeof u!==n[r.searchFor])throw new f(`"value" type does not match the type of "${r.searchFor}" index.`,{code:"INVALID_PARAMETER"});if(typeof u=="string"&&!u)throw new f('"value" should not be empty string.',{code:"INVALID_PARAMETER"});return u},range:u=>{if(!r.hasOwnProperty("value")||typeof u!=typeof r.value)throw new f('"range" should match type of "value".',{code:"INVALID_PARAMETER"});return u},condition:[">",">=","=","<","<=","gt","gte","eq","lt","lte",()=>"="],group:u=>{if(u==="public")return 0;if(!this.session)throw new f("User should be logged in.",{code:"INVALID_REQUEST"});if(u==="authorized")return 1;if(typeof u=="number"){if(!t&&u>parseInt(this.user?.access_group||this.session?.idToken?.payload?.access_group))throw new f("User has no access.",{code:"INVALID_REQUEST"});return u}throw new f('"group" should be type: number | "public" | "authorized".',{code:"INVALID_PARAMETER"})}},["searchFor","value","group"]);let i=r.group===0?"get-public-newsletters":"get-newsletters",s=await T.bind(this)(i,r,Object.assign({method:"get",auth:i==="get-public-newsletters"?!!this.__user:true},{fetchOptions:e})),o={message_id:"mid",timestamp:"stmp",complaint:"cmpl",read:"read",subject:"subj",bounced:"bnce",url:"url",delivered:"delv"},a={message_id:"",timestamp:0,complaint:0,read:0,subject:"",bounced:"",url:"",delivered:0};return s.list=s.list.map(u=>{let c={};for(let l in o)c[l]=u[o[l]]||a[l];return c.bounced=String(c.bounced),c}),s}async function Ds(r){let e=m.Params(r,{user_id:n=>m.UserId(n,'"user_id"')},["user_id"]);if(e?.service&&e?.owner?e={service:e?.service,owner:e?.owner,block:e.user_id}:e={block:e.user_id},!await H.bind(this)()){if(!this.__user)throw new f("User needs to login.",{code:"INVALID_REQUEST"});if(this.__user.access_group<90)throw new f("Invalid access.",{code:"INVALID_REQUEST"})}return await T.bind(this)("block-account",e,{auth:true})}async function ks(r){let e=m.Params(r,{user_id:n=>m.UserId(n,'"user_id"')},["user_id"]);if(e?.service&&e?.owner?e={service:e?.service,owner:e?.owner,unblock:e.user_id}:e={unblock:e.user_id},!await H.bind(this)()){if(!this.__user)throw new f("User needs to login.",{code:"INVALID_REQUEST"});if(this.__user.access_group<90)throw new f("Invalid access.",{code:"INVALID_REQUEST"})}return await T.bind(this)("block-account",e,{auth:true})}async function Ns(r){let e=m.Params(r,{user_id:n=>m.UserId(n,'"user_id"')},["user_id"]);if(e?.service&&e?.owner?e={service:e?.service,owner:e?.owner,delete:e.user_id}:e={delete:e.user_id},!await H.bind(this)()){if(!this.__user)throw new f("User needs to login.",{code:"INVALID_REQUEST"});if(this.__user.access_group<90)throw new f("Invalid access.",{code:"INVALID_REQUEST"})}return await T.bind(this)("remove-account",e,{auth:true})}async function Fs(r,e){let t={email:s=>m.Email(s),password:s=>m.Password(s),name:"string",username:"string",gender:"string",address:s=>{if(!s)return "";if(typeof s=="string")return s;if(typeof s=="object")return JSON.stringify(s)},birthdate:s=>m.Birthdate(s),phone_number:s=>m.PhoneNumber(s),picture:s=>{if(s)return m.Url(s)},profile:s=>{if(s)return m.Url(s)},website:s=>{if(s)return m.Url(s)},nickname:"string",misc:"string",email_public:["boolean",()=>false],gender_public:["boolean",()=>false],address_public:["boolean",()=>false],birthdate_public:["boolean",()=>false],phone_number_public:["boolean",()=>false],openid_id:"string",access_group:s=>{try{typeof s=="string"&&(s=s==="admin"?99:parseInt(s));}catch{throw new f('"access_group" is invalid. Should be type <number>.',{code:"INVALID_PARAMETER"})}if(typeof s!="number"||s<1||s>100)throw new f('"access_group" is invalid. Should be type <number> of range 1~99',{code:"INVALID_PARAMETER"});return s}},n=m.Params(r,t,["email"]);if(e=m.Params(e,{confirmation_url:s=>{let o=s;if(typeof s=="string")o=m.Url(s);else throw new f('"options.confirmation_url" should be type: <string>.',{code:"INVALID_PARAMETER"});if(o&&!n.email)throw new f('"email" is required for signup confirmation.',{code:"INVALID_PARAMETER"});return o},email_subscription:s=>{if(typeof s!="boolean")throw new f('"options.email_subscription" should be type: <boolean>.',{code:"INVALID_PARAMETER"});if(!e?.confirmation_url)throw new f('"options.confirmation_url" is required for email subscription.',{code:"INVALID_PARAMETER"});return s},template:s=>{if(typeof s!="object"||!s.url||!s.subject)throw new f('"options.template" should be type: <object> with "url" and "subject".',{code:"INVALID_PARAMETER"});return {url:m.Url(s.url),subject:s.subject}}}),n.signup_confirmation=e?.confirmation_url||true,n.email_subscription=e?.email_subscription||false,n.template=e?.template||{},!await H.bind(this)()){if(!this.__user)throw new f("User needs to login.",{code:"INVALID_REQUEST"});if(this.__user.access_group<90)throw new f("Invalid access.",{code:"INVALID_REQUEST"})}return await T.bind(this)("admin-signup",n,{auth:true})}async function Os(r){let e={email:s=>m.Email(s),password:s=>m.Password(s),openid_id:"string",name:"string",username:"string",gender:"string",address:s=>{if(!s)return "";if(typeof s=="string")return s;if(typeof s=="object")return JSON.stringify(s)},birthdate:s=>m.Birthdate(s),phone_number:s=>m.PhoneNumber(s),picture:s=>s?m.Url(s):"",profile:s=>s?m.Url(s):"",website:s=>s?m.Url(s):"",nickname:"string",misc:"string",email_public:["boolean",()=>false],gender_public:["boolean",()=>false],address_public:["boolean",()=>false],birthdate_public:["boolean",()=>false],phone_number_public:["boolean",()=>false],access_group:s=>{try{typeof s=="string"&&(s=parseInt(s));}catch{throw new f('"access_group" is invalid. Should be type <number>.',{code:"INVALID_PARAMETER"})}if(typeof s!="number"||s<1||s>100)throw new f('"access_group" is invalid. Should be type <number> of range 1~99',{code:"INVALID_PARAMETER"});return s}},t=["email","password"],n=m.Params(r,e,t);if(!await H.bind(this)()){if(!this.__user)throw new f("User needs to login.",{code:"INVALID_REQUEST"});if(this.__user.access_group<90)throw new f("Invalid access.",{code:"INVALID_REQUEST"})}return await T.bind(this)("admin-signup",n,{auth:true})}async function Ls(r){if(r=m.Params(r,{user_id:t=>m.UserId(t,'"user_id"'),access_group:t=>{try{typeof t=="string"&&(t=parseInt(t));}catch{throw new f('"access_group" is invalid. Should be type <number>.',{code:"INVALID_PARAMETER"})}if(typeof t=="number"&&t>0&&t<100)return t;throw new f('"access_group" is invalid. Should be type <number> of range 1~99',{code:"INVALID_PARAMETER"})}},["user_id","access_group"]),!await H.bind(this)()){if(!this.__user)throw new f("User needs to login.",{code:"INVALID_REQUEST"});if(this.__user.access_group<90)throw new f("Invalid access.",{code:"INVALID_REQUEST"})}return await T.bind(this)("grant-access",r,{auth:true})}async function Ms(r,e){if(r=m.Params(r,{email:"string"}),!await H.bind(this)()){if(!this.__user)throw new f("User needs to login.",{code:"INVALID_REQUEST"});if(this.__user.access_group<90)throw new f("Invalid access.",{code:"INVALID_REQUEST"})}let n=await T.bind(this)("invitation-list",Object.assign({mode:"search"},r),{fetchOptions:e,auth:true});return n.list=n.list.map(i=>et(i.user)),n}async function qs(r){if(r=m.Params(r,{email:t=>m.Email(t)},["email"]),!await H.bind(this)()){if(!this.__user)throw new f("User needs to login.",{code:"INVALID_REQUEST"});if(this.__user.access_group<90)throw new f("Invalid access.",{code:"INVALID_REQUEST"})}return await T.bind(this)("invitation-list",Object.assign({mode:"cancel"},r),{auth:true})}async function Vs(r){if(r=m.Params(r,{email:t=>m.Email(t)},["email"]),!await H.bind(this)()){if(!this.__user)throw new f("User needs to login.",{code:"INVALID_REQUEST"});if(this.__user.access_group<90)throw new f("Invalid access.",{code:"INVALID_REQUEST"})}return await T.bind(this)("invitation-list",Object.assign({mode:"resend"},r),{auth:true})}async function Bs(r){let e=m.Params(r,{user_id:o=>m.UserId(o,'"user_id"'),email:o=>m.Email(o),address:o=>{if(!o)return "";if(typeof o=="string")return o;if(typeof o=="object")return JSON.stringify(o)},name:"string",gender:"string",birthdate:o=>o?m.Birthdate(o):"",phone_number:o=>o?m.PhoneNumber(o):"",email_public:"boolean",phone_number_public:"boolean",address_public:"boolean",gender_public:"boolean",birthdate_public:"boolean",misc:"string",picture:o=>o?m.Url(o):"",profile:o=>o?m.Url(o):"",nickname:"string",website:o=>o?m.Url(o):""},["user_id"]),t=e.service,n=e.owner;if(delete e.service,delete e.owner,Object.keys(e).filter(o=>o!=="user_id"&&e[o]!==void 0).length===0)throw new f("At least one attribute to update is required.",{code:"INVALID_PARAMETER"});if(!await H.bind(this)()){if(!this.__user)throw new f("User needs to login.",{code:"INVALID_REQUEST"});if(this.__user.access_group<90)throw new f("Invalid access.",{code:"INVALID_REQUEST"})}e.email&&(e.preferred_username=(t||this.service)+"-"+K.hash(e.email));let s={attributes:e};return t&&n&&(s.service=t,s.owner=n),await T.bind(this)("admin-edit-profile",s,{auth:true})}async function $s(r){if(typeof window>"u"||window._runningInNodeJS)throw new f("Push Notifications are not supported in Node.js environment.",{code:"NOT_SUPPORTED"});if(await this.__connection,!r.endpoint)throw new f("Missing parameter: endpoint",{code:"INVALID_PARAMETER"});if(!r.keys||!r.keys.p256dh||!r.keys.auth)throw new f("Missing parameter: keys.p256dh or keys.auth",{code:"INVALID_PARAMETER"});return await T.bind(this)("store-subscription",{endpoint:r.endpoint,keys:r.keys},{auth:true}),"SUCCESS: Subscribed to receive notifications."}async function js(r){if(typeof window>"u"||window._runningInNodeJS)throw new f("Push Notifications are not supported in Node.js environment.",{code:"NOT_SUPPORTED"});if(await this.__connection,!r.endpoint)throw new f("Missing parameter: endpoint",{code:"INVALID_PARAMETER"});if(!r.keys||!r.keys.p256dh||!r.keys.auth)throw new f("Missing parameter: keys.p256dh or keys.auth",{code:"INVALID_PARAMETER"});return await T.bind(this)("delete-subscription",{endpoint:r.endpoint,keys:r.keys},{auth:true}),"SUCCESS: Unsubscribed from notifications."}async function Ks(){if(typeof window>"u"||window._runningInNodeJS)throw new f("Push Notifications are not supported in Node.js environment.",{code:"NOT_SUPPORTED"});return await this.__connection,{VAPIDPublicKey:await T.bind(this)("get-vapid-public-key",null,{auth:true})}}async function Hs(r,e){if(typeof window>"u"||window._runningInNodeJS)throw new f("Push Notifications are not supported in Node.js environment.",{code:"NOT_SUPPORTED"});await this.__connection;let{title:t,body:n}=M(r||{},{nullIfEmpty:true}).data;if(!t)throw new f("Missing parameter: message title",{code:"INVALID_PARAMETER"});if(!n)throw new f("Missing parameter: message body",{code:"INVALID_PARAMETER"});let i={title:t,body:n};return e?(typeof e=="string"&&(e=[e]),i.user_ids=e):i.user_ids="all_users",await T.bind(this)("push-notification",i,{auth:true}),"SUCCESS: Notification sent."}async function Ws(r){await this.__connection,r=m.Params(r,{spell:"string",name:"string",magic:t=>t},["spell","name"]);await T.bind(this)("castspell",r);return `The spell "${r.spell}" has been cast.`}async function Js(r){return await this.__connection,r=m.Params(r||{},{search:["spell","name",()=>"spell"],value:"string"}),await T.bind(this)("getspell",r)}async function Gs(r){await this.__connection,r=m.Params(r,{message:"string",name:"string"},["message","name"]);let e=await T.bind(this)("dopamine",r,{auth:true}),t=e?.previous_message?.message,n=e?.previous_message?.name;if(Y())t&&n&&window.alert(`${n} said: ${t}`),window.location.href=e.video;else return t&&n?`${n} said: ${t}
216
+ `,o=new Blob([s],{type:"application/javascript"});Be=new Worker(URL.createObjectURL(o)),Be.onmessage=a=>{i.readyState===1&&i.send(JSON.stringify({action:"keepAlive"}));},n(i);},i.onmessage=async s=>{let o="";try{o=JSON.parse(decodeURI(s.data)),this.log("socket onmessage",o);}catch{return}let a;switch(true){case !!o?.["#message"]:a="message";break;case !!o?.["#private"]:a="private";break;case !!o?.["#notice"]:a="notice";break;case !!o?.["#rtc"]:a="rtc";break;case !!o?.["#error"]:a="error";break}if(!a)return;let c={type:a,message:o?.["#rtc"]||o?.["#message"]||o?.["#private"]||o?.["#notice"]||o?.["#error"]||null,sender:o?.["#user_id"]||null,sender_cid:o?.["#scid"]?"cid:"+o["#scid"]:null,sender_rid:o?.["#srid"]||null,code:o?.["#code"]||null};if(a==="notice")t(c);else if(a==="rtc"){if(c.sender!==this.user.user_id){let u=c.message;if(u.hungup){_e[c.sender_cid]&&(_e[c.sender_cid](false),delete _e[c.sender_cid]),Te[c.sender_cid]&&delete Te[c.sender_cid],D?.[c.sender_cid]&&be.bind(this)({cid:c.sender_cid}),c.type="rtc:closed",t(c);return}if(u.candidate&&Xn.bind(this)(u.candidate,c.sender_cid),u.sdpoffer&&(Qn.bind(this)(u.sdpoffer,c.sender_cid),Te[c.sender_cid]||(Te[c.sender_cid]=c.sender_cid,delete c.message,c.connectRTC=la.bind(this)(c),c.type="rtc:incoming",c.hangup=(()=>{D[c.sender_cid]?be.bind(this)({cid:c.sender_cid}):Te[c.sender_cid]&&(delete Te[c.sender_cid],i.send(JSON.stringify({action:"rtc",uid:c.sender_cid,content:{hungup:this.user.user_id},token:this.session.accessToken.jwtToken})));}).bind(this),t(c))),u.pickup&&_e[c.sender_cid]&&(_e[c.sender_cid](true),delete _e[c.sender_cid]),u.sdpanswer&&D[c.sender_cid])if(D[c.sender_cid].signalingState==="have-local-offer")await D[c.sender_cid].setRemoteDescription(new RTCSessionDescription(u.sdpanswer));else throw new f("Invalid signaling state.",{code:"INVALID_REQUEST"})}}else t(c);},i.onclose=()=>{Lt?(this.log("realtime onclose","WebSocket connection closed."),t({type:"close",message:"WebSocket connection closed."})):(this.log("realtime onclose","WebSocket unexpected close."),t({type:"error",message:"Skapi: WebSocket unexpected close."}),mt++,mt<3?(this.log("realtime onclose","Reconnecting to WebSocket server..."+mt),t({type:"reconnect",message:"Reconnecting to WebSocket server..."+mt}),Cr.bind(this)(t,3e3,"reconnect")):(this.log("realtime onclose","Max reconnection attempts reached."),t({type:"error",message:"Skapi: Max reconnection attempts reached."})));},i.onerror=()=>{this.log("realtime onerror","WebSocket connection error."),t({type:"error",message:"Skapi: WebSocket connection error."});};},e);});}async function ga(t,e,r){if(typeof window>"u"||window._runningInNodeJS)throw new f("WebSocket is not supported in Node.js environment.",{code:"NOT_SUPPORTED"});let n=this.__socket?await this.__socket:this.__socket;if(!n)throw new f("No realtime connection. Execute connectRealtime() before this method.",{code:"INVALID_REQUEST"});if(!e)throw new f("No recipient.",{code:"INVALID_REQUEST"});await ft.bind(this)(),t=K(t).data;let i="";if(r&&(r=_.Params(r,{config:{always:"boolean"},title:"string",body:"string"},["title","body"]),i=JSON.stringify({title:r.title,body:r.body}),new Blob([i]).size>3072))throw new f("Notification size exceeds 3kb.",{code:"INVALID_PARAMETER"});if(n.readyState===1){try{_.UserId(e),n.send(JSON.stringify({action:"sendMessage",uid:e,content:t,notification:i,notificationConfig:r?.config||{},token:`IdT:${this.service}:${this.owner}:`+(this.bearerToken||this.session?.idToken?.jwtToken||"null")}));}catch(s){if(this.log("postRealtime:err",{err:s}),$e!==e)throw new f(`User has not joined to the recipient group. Run joinRealtime({ group: "${e}" })`,{code:"INVALID_REQUEST"});n.send(JSON.stringify({action:"broadcast",rid:e,content:t,notification:i,notificationConfig:r?.config||{},token:`IdT:${this.service}:${this.owner}:`+(this.bearerToken||this.session?.idToken?.jwtToken||"null")}));}return {type:"success",message:"Message sent."}}throw new f("Realtime connection is not open. Try reconnecting with connectRealtime().",{code:"INVALID_REQUEST"})}async function ei(t){if(typeof window>"u"||window._runningInNodeJS)throw new f("WebSocket is not supported in Node.js environment.",{code:"NOT_SUPPORTED"});let e=this.__socket?await this.__socket:this.__socket;if(!e)throw new f("No realtime connection. Execute connectRealtime() before this method.",{code:"INVALID_REQUEST"});await ft.bind(this)(),t=K(t,{nullIfEmpty:true}).data;let{group:r=null}=t;if(!r&&!$e)return {type:"success",message:"Left realtime message group."};if(r!==null&&typeof r!="string")throw new f('"group" must be a string | null.',{code:"INVALID_PARAMETER"});return e.send(JSON.stringify({action:"joinRoom",rid:r,token:this.session.accessToken.jwtToken})),$e=r,{type:"success",message:r?`Joined realtime message group: "${r}".`:"Left realtime message group."}}async function pa(t,e){t=_.Params(t,{user_id:n=>_.UserId(n,'User ID in "user_id"'),group:["string",()=>{if(!$e)throw new f('No group has been joined. Otherwise "group" is required.',{code:"INVALID_REQUEST"});return $e}]});let r=await I.bind(this)("get-ws-group",t,{fetchOptions:e,auth:true,method:"post"});return r.list=r.list.map(n=>({user_id:n.uid.split("#")[1],cid:"cid:"+n.cid})),r}async function ma(t,e){if(await this.__connection,t||(t={searchFor:"group",value:" ",condition:">"}),t=_.Params(t,{searchFor:["group","number_of_users",()=>"group"],value:["string","number",()=>t?.searchFor&&t?.searchFor==="number_of_users"?0:" "],condition:[">",">=","=","<","<=","!=","gt","gte","eq","lt","lte","ne"],range:["string","number"]}),t.condition||(t.value===" "||!t.value?t.condition=">":t.condition="="),t.range&&t.condition&&delete t.condition,t.searchFor==="number_of_users"&&typeof t.value!="number")throw new f('"value" must be a number.',{code:"INVALID_PARAMETER"});if(t.searchFor==="group"&&typeof t.value!="string")throw new f('"value" must be a string.',{code:"INVALID_PARAMETER"});if(t.hasOwnProperty("range")&&typeof t.range!=typeof t.value)throw new f(`"range" must be a ${typeof t.value}.`,{code:"INVALID_PARAMETER"});let r=await I.bind(this)("get-ws-group",t,{fetchOptions:e,auth:true,method:"post"});return r.list=r.list.map(n=>({group:n.rid.split("#")[1],number_of_users:n.cnt})),r}var ya=typeof FormData<"u",_a=typeof HTMLFormElement<"u",ba=typeof SubmitEvent<"u",Ie={},Mt={},Pe={};function ti(t){return Object.freeze({id:t,status:"stopped"})}function wa(t){return !!t&&typeof t=="object"&&t.status==="stopped"}function Ea({id:t,auth:e,service:r,owner:n,latency:i=1e3,queue:s,onResponse:o,onError:a}){if(typeof i!="number")throw new f('"latency" should be a number.',{code:"INVALID_PARAMETER"});if(i<0)throw new f('"latency" should be a non-negative number.',{code:"INVALID_PARAMETER"});s&&!Ie?.[s]&&(Ie[s]=new kt({breakWhenError:false,batchSize:1}));let c={stop:null,aborted:false,queue:s};Pe[t]=c;let u=()=>{Pe[t]===c&&delete Pe[t];},l=()=>new Promise((h,p)=>{let g=false;if(c.aborted){u(),h(ti(t));return}let m=setInterval(async()=>{try{let y=await I.bind(this)("csr-poll",{id:t,service:r,owner:n},{auth:e});if(y.status==="running"||y.status==="pending"||g)return;g=!0,o&&o(y),clearInterval(m),u(),h(y);}catch(y){if(g)return;g=true,a&&a(y),clearInterval(m),u(),p(y);}},i);c.stop=()=>{g||(g=true,clearInterval(m),u(),h(ti(t)));};}),d=()=>{let h=Pe[t];h&&(h.stop?h.stop():(h.aborted=true,delete Pe[t]));};if(s){let h=new Promise((p,g)=>{let m=false,y=Ie[s].add([async()=>{try{let b=await l();return m||(m=!0,p(b)),b}catch(b){throw m||(m=true,g(b)),b}}])[0];Mt[t]=y,c.stop=()=>{if(!m){c.aborted=true;try{Ie[s]&&Ie[s].remove(Mt[t]);}catch{}delete Mt[t],u(),m=true,p(ti(t));}};});return Object.assign(h,{stop:d})}else return Object.assign(l(),{stop:d})}function Aa(t){let e=0,r=[];if(t?.id){if(t.url&&t.method){let n=t.service||this.service;r.push(`[${t.method.toUpperCase()}]${t.url.toLowerCase()}#${n}:${t.id}`);}r.push(t.id);}else if(t?.queue)for(let n in Pe)Pe[n]?.queue===t.queue&&r.push(n);else for(let n in Pe)r.push(n);for(let n of r){let i=Pe[n];i&&(i.stop?i.stop():(i.aborted=true,delete Pe[n]),e+=1);}return e}function Sa(t,e){if(!t.queue)throw new f('"queue" is required.',{code:"INVALID_PARAMETER"});let r={service:t.service||this.service,owner:t.owner||this.owner,queue:t.queue+":"};return I.bind(this)("csr-poll",r,{auth:true})}async function va(t){let e=false;if(typeof t.poll=="number"&&t.poll<0)throw new f('"poll" should be a non-negative number.',{code:"INVALID_PARAMETER"});let r=t?.onResponse,n=t?.onError,i=typeof t.poll=="number"?t.poll:t.poll?1e3:0;delete t.poll,i&&!t.queue&&(t.queue=(this.__user?.user_id||"anonymous")+"-"+We());let s=c=>{for(let u in c)if(typeof c[u]=="string"&&c[u].includes("$CLIENT_SECRET")){e=true;break}};if(t=_.Params(t,{url:c=>{if(!c||typeof c!="string")throw new f('"url" should be type: <string>.',{code:"INVALID_PARAMETER"});return _.Url(c),c.includes("$CLIENT_SECRET")&&(e=true),c},clientSecretName:"string",method:c=>{if(c&&typeof c!="string")throw new f('"method" should be either "GET" or "POST" or "DELETE" or "PUT".',{code:"INVALID_PARAMETER"});let u=c.toLowerCase();if(u!=="get"&&u!=="post"&&u!=="delete"&&u!=="put")throw new f('"method" should be either "GET" or "POST" or "DELETE" or "PUT".',{code:"INVALID_PARAMETER"});return u},headers:c=>{if(c&&typeof c!="object")throw new f('"headers" should be type: <object>.',{code:"INVALID_PARAMETER"});return s(c),c},data:c=>{if(c&&typeof c!="object")throw new f('"data" should be type: <object>.',{code:"INVALID_PARAMETER"});return s(c),c},params:c=>{if(c&&typeof c!="object")throw new f('"params" should be type: <object>.',{code:"INVALID_PARAMETER"});return s(c),c},expires:"number",queue:"string"},["clientSecretName","method","url"]),!e)throw new f(`At least one parameter value should include "$CLIENT_SECRET" in ${t.method.toLowerCase()==="post"?'"data"':'"params"'} or "headers".`,{code:"INVALID_PARAMETER"});await this.__connection;let o=!!this.__user,a=()=>I.bind(this)("csr",t,{auth:o,tokenHeaders:{accessToken:!!o}}).then(c=>{if(c.status==="running"||c.status==="pending"){let u=`[${t.method.toUpperCase()}]${t.url.toLowerCase()}`,l=t.service||this.service,d=t.owner||this.owner,h=`${u}#${l}:${c.id}`;Object.assign(c,{poll:p=>Ea.call(this,{id:h,auth:o,service:l,owner:d,latency:p?.latency||1e3,queue:t?.queue,onResponse:r,onError:n})});}return r?r(c):c}).catch(c=>{if(n)return n(c);throw c});if(t?.queue){let c="base:"+t.queue;return Ie?.[c]||(Ie[c]=new kt({breakWhenError:false,batchSize:1})),new Promise((u,l)=>{Ie[c].add([async()=>{try{let d=await a();if(i>0){let h=d.poll({latency:i});return u(h),h}return u(d),d}catch(d){throw l(d),d}}]);})}else return a()}async function Ra(t,e){await this.__connection;let r=t.service||this.service,n=t.owner||this.owner;t=_.Params(t,{url:"string",method:["GET","POST","DELETE","PUT"],queue:"string",status:["pending","running","resolved","failed"],compact:"boolean",queue_exact:"boolean",queue_exclude:"string"},["url","method"]);let i=!!this.__user,s=`[${t.method.toUpperCase()}]${t.url.toLowerCase()}#${r}:`,o={id:s,queue:t?.queue,status:t?.status,service:r,owner:n};t?.compact&&(o.compact=true),t?.queue_exact&&(o.queue_exact=true),t?.queue_exclude&&(o.queue_exclude=t.queue_exclude),Object.keys(o).forEach(c=>{o[c]||delete o[c];}),o.queue&&(o.id_prefix=o.id,delete o.id);let a=await I.bind(this)("csr-poll",o,{auth:i,fetchOptions:e});return a.list=a.list.map(c=>{let u={id:c.id,status_code:c.rslv?.status_code||null,response_body:c.rslv?.body||c.rslv?.truncated||null,error:c?.err,created:c?.stmp,updated:c?.utmp,request_body:c?.reqbdy,expires:c?.expt,status:c.stts,queue_name:c?.qid,request_text:c?.reqtxt,response_text:c?.rslvtxt,response_complete_marker:c?.rslvmk!=null?!!c.rslvmk:void 0,compact:c?.cmpct?true:void 0};for(let l in u)u[l]===void 0&&delete u[l];return (u.status==="running"||u.status==="pending")&&(u.poll=l=>Ea.call(this,{id:s+u.id,auth:i,service:r,owner:n,latency:l?.latency||1e3,queue:c?.qid,onResponse:l?.onResponse,onError:l?.onError})),u}),a}async function Ta(t){await this.__connection,t=_.Params(t,{url:"string",method:["GET","POST","DELETE","PUT"],id:"string",queue:"string"},["url","method","id"]);let e=t?.service||this.service,r=t?.owner||this.owner,n=!!this.__user,i=`[${t.method.toUpperCase()}]${t.url.toLowerCase()}#${e}`,s=t.id,o=`${i}:${s}`,a=t?.queue;return a&&Ie?.[a]&&(Ie[a].remove(Mt[o]),delete Mt[o]),I.bind(this)("csr-cancel",{id:o,service:e,owner:r},{auth:n})}async function Ia(t){await this.__connection;let e={name:"string",email:r=>(_.Email(r),r),subject:"string",message:"string"};return t=_.Params(t,e,["name","email","subject","message"]),await I.bind(this)("send-inquiry",t),"SUCCESS: Inquiry has been sent."}async function Pa(t,e){if(await this.__connection,ya&&t instanceof FormData||_a&&t instanceof HTMLFormElement||ba&&t instanceof SubmitEvent){if(!e)throw new f("Url string as a second argument is required when form is passed.",{code:"INVALID_PARAMETER"});let n=K(t);t={url:e,data:n.data,sync:true};}let r={url:n=>_.Url(n),data:n=>n,sync:["boolean",()=>true]};if(Array.isArray(t))for(let n of t)n=_.Params(n,r);else t=_.Params(t,r);return I.bind(this)("post-secure",t,{auth:true})}async function Ua(t,e){await this.__connection;let{auth:r=false,method:n="POST",bypassAwaitConnection:i=false,responseType:s,contentType:o,tokenHeaders:a,progress:c}=e||{};if(e=Object.assign({auth:r,method:n,bypassAwaitConnection:i,responseType:s,contentType:o,tokenHeaders:a},{fetchOptions:{progress:c}}),typeof t!="object"&&(o==="application/json"||o===void 0))throw new f('"data" should be type: <object>.',{code:"INVALID_PARAMETER"});return I.bind(this)("mock",t,e)}async function xa(t,e){if(await this.__connection,!e?.url||typeof e.url!="string")throw new f('"url" is required in the second argument.',{code:"INVALID_PARAMETER"});_.Url(e.url);let n=(await this.admin_endpoint)?.forward_request;if(!n)throw new f("forwardRequest is not available on this service region yet.",{code:"NOT_EXISTS"});let i=null,s=null,o=ba&&t instanceof SubmitEvent?t.target:_a&&t instanceof HTMLFormElement?t:null;o?i=new FormData(o):ya&&t instanceof FormData?i=t:t!=null&&(i=JSON.stringify(t),s="application/json");let a={public_identifier:this.__public_identifier,service:this.service,owner:this.owner,forward:{url:e.url,method:e.method||"POST",headers:e.headers||{},apiKeyHeader:e.apiKeyHeader,apiKeyScheme:e.apiKeyScheme}},c=JSON.stringify(a).replace(/[\u007f-\uffff]/g,p=>"\\u"+p.charCodeAt(0).toString(16).padStart(4,"0"));if(c.length>4096)throw new f("Destination url and headers are too large for Content-Meta.",{code:"INVALID_PARAMETER"});let u=this.bearerToken||this.session?.idToken?.jwtToken||null;if(!u)throw new f("User login is required.",{code:"INVALID_REQUEST"});let l={"Content-Meta":c,Authorization:u};s&&(l["Content-Type"]=s);let d=await fetch(n,{method:"POST",headers:l,body:i,signal:e.signal});if(e.responseType==="response")return d;if(!d.ok){let p=await d.text();try{p=JSON.parse(p);}catch{}throw new f(p?.message||(typeof p=="string"?p:JSON.stringify(p)),{code:p?.code||"ERROR"})}if(e.onStream&&d.body){let p=d.body.getReader(),g=new TextDecoder,m="";for(;;){let{done:y,value:b}=await p.read();if(y)break;let E=g.decode(b,{stream:true});m+=E;try{e.onStream(E);}catch(v){console.error(v);}}return m}let h=await d.text();if(e.responseType==="text")return h;try{return JSON.parse(h)}catch{return h}}async function Ca(t,e){await this.__connection,t=_.Params(t||{},{access_group:n=>{if(n==="authorized"&&(n=1),n==="public"&&(n=0),typeof n!="number")throw new f('"access_group" should be type number.',{code:"INVALID_PARAMETER"});if(n<0)throw new f('"access_group" should be zero or a positive number.',{code:"INVALID_PARAMETER"});if(n>this.__user.access_group)throw new f("User has no access.",{code:"INVALID_REQUEST"});return n}});let r=await I.bind(this)("get-feed",t,{auth:true,fetchOptions:e});for(let n in r.list)r.list[n]=await pt.bind(this)(r.list[n]);return r}function Vt(t){if(t===this.__user.user_id)throw new f(`"user_id" cannot be the user's own ID.`,{code:"INVALID_PARAMETER"});return _.UserId(t,'"user_id"')}async function Da(t,e){if(t=K(t,{ignoreEmpty:true}).data,t=_.Params(t,{subscriber:n=>_.UserId(n,'User ID in "subscriber"'),subscription:Vt.bind(this),blocked:"boolean"}),!t.subscriber&&!t.subscription)throw new f('At least either "subscriber" or "subscription" should have a value.',{code:"INVALID_PARAMETER"});let r=await I.bind(this)("get-subscription",t,Object.assign({auth:true},{fetchOptions:e}));return r.list=r.list.map((n=>{let i={};if(n.sub){let s=n.sub.split("#");i.subscriber=s[2],i.subscription=s[0];}else i.subscriber=n.subscriber,i.subscription=n.subscription;return i.timestamp=n?.timestamp||n.stmp,i.blocked=n?.blocked||n.grp.substring(0,1)==="N",Object.assign(i,n.opt),i})),r}async function ka(t){await this.__connection,t=_.Params(t,{user_id:Vt.bind(this),get_feed:["boolean",()=>false],get_notified:["boolean",()=>false],get_email:n=>{if(n&&!this.__user.email||!this.__user.email_verified)throw new f("User has no verified email address.",{code:"INVALID_REQUEST"});return !!n}},["user_id"]);let e=await I.bind(this)("subscription",{subscribe:t.user_id,option:{get_feed:t.get_feed,get_notified:t.get_notified,get_email:t.get_email||false}},{auth:true}),r={};if(e.sub){let n=e.sub.split("#");r.subscriber=n[2],r.subscription=n[0];}else r.subscriber=e.subscriber,r.subscription=e.subscription;return r.timestamp=e?.timestamp||e.stmp,r.blocked=e?.blocked||e.grp.substring(0,1)==="N",Object.assign(r,e.opt),r}async function Na(t){await this.__connection;let{user_id:e}=_.Params(t,{user_id:Vt.bind(this)},["user_id"]);return await I.bind(this)("subscription",{unsubscribe:e},{auth:true})}async function Oa(t){await this.__connection;let{user_id:e}=_.Params(t,{user_id:Vt.bind(this)},["user_id"]);return await I.bind(this)("subscription",{block:e},{auth:true})}async function Fa(t){await this.__connection;let{user_id:e}=_.Params(t,{user_id:Vt.bind(this)},["user_id"]);return await I.bind(this)("subscription",{unblock:e},{auth:true})}async function La(t,e){await this.__connection;let r=await Q.bind(this)();t=_.Params(t,{user_id:o=>{if(o!==this.__user.user_id&&!r)throw new f("No access.",{code:"INVALID_REQUEST"});return o},group:o=>{if(o==="public"&&(o=0),o==="authorized"&&(o=1),typeof o!="number")throw new f('"group" should be type number | "public" | "authorized".',{code:"INVALID_PARAMETER"});return o}});let n=await I.bind(this)("get-newsletter-subscription",t,{auth:true,fetchOptions:e||null}),i=n?.list||n,s=[];Array.isArray(i)||(i=[]);for(let o of i){let a=o.subt.split("#"),c=true;a[0].charAt(0)==="@"&&(c=false,a[0]=a[0].substring(1));let u=parseInt(a[0]);s.push({timestamp:o.stmp,group:u,subscribed_email:a[1],active:c});}return n?.list?(n.list=s,n):s}async function Ma(t){await this.__connection;let e=_.Params(t||{},{email:r=>Array.isArray(r)&&r.length>0?r.length===1?_.Email(r[0]):r.map(n=>_.Email(n)):_.Email(r),group:["number","public","authorized","admin",r=>{if(typeof r!="string"||r.length>20||!/^[a-zA-Z0-9]+$/.test(r))throw new f('"group" should be an alphanumeric string without spaces and less than 20 characters.',{code:"INVALID_PARAMETER"});return r}],redirect:r=>_.Url(r)},this.__user?["group"]:["email","group"]);return I.bind(this)(`subscribe-${this.__user?"":"public-"}newsletter`,e,{auth:!!this.__user})}async function Va(t){await this.__connection,t=_.Params(t,{group:["number","public","authorized","admin"]},["group"]);let e=Object.assign({action:"unsubscribe"},t);return I.bind(this)("subscribe-newsletter",e,{auth:true})}async function qa(t,e){let r=await Q.bind(this)(),n={message_id:"string",timestamp:"number",read:"number",complaint:"number",subject:"string",bounced:"number"};t||(e=Object.assign({ascending:false},e||{})),t=K(t).data,t=t||{searchFor:"timestamp",value:Date.now(),condition:"<",group:"public"},t=_.Params(t,{searchFor:["message_id","timestamp","subject","complaint","read","bounced"],value:c=>{if(typeof c!==n[t.searchFor])throw new f(`"value" type does not match the type of "${t.searchFor}" index.`,{code:"INVALID_PARAMETER"});if(typeof c=="string"&&!c)throw new f('"value" should not be empty string.',{code:"INVALID_PARAMETER"});return c},range:c=>{if(!t.hasOwnProperty("value")||typeof c!=typeof t.value)throw new f('"range" should match type of "value".',{code:"INVALID_PARAMETER"});return c},condition:[">",">=","=","<","<=","gt","gte","eq","lt","lte",()=>"="],group:c=>{if(c==="public")return 0;if(!this.session)throw new f("User should be logged in.",{code:"INVALID_REQUEST"});if(c==="authorized")return 1;if(typeof c=="number"){if(!r&&c>parseInt(this.user?.access_group||this.session?.idToken?.payload?.access_group))throw new f("User has no access.",{code:"INVALID_REQUEST"});return c}throw new f('"group" should be type: number | "public" | "authorized".',{code:"INVALID_PARAMETER"})}},["searchFor","value","group"]);let i=t.group===0?"get-public-newsletters":"get-newsletters",s=await I.bind(this)(i,t,Object.assign({method:"get",auth:i==="get-public-newsletters"?!!this.__user:true},{fetchOptions:e})),o={message_id:"mid",timestamp:"stmp",complaint:"cmpl",read:"read",subject:"subj",bounced:"bnce",url:"url",delivered:"delv"},a={message_id:"",timestamp:0,complaint:0,read:0,subject:"",bounced:"",url:"",delivered:0};return s.list=s.list.map(c=>{let u={};for(let l in o)u[l]=c[o[l]]||a[l];return u.bounced=String(u.bounced),u}),s}async function Ba(t){let e=_.Params(t,{user_id:n=>_.UserId(n,'"user_id"')},["user_id"]);if(e?.service&&e?.owner?e={service:e?.service,owner:e?.owner,block:e.user_id}:e={block:e.user_id},!await Q.bind(this)()){if(!this.__user)throw new f("User needs to login.",{code:"INVALID_REQUEST"});if(this.__user.access_group<90)throw new f("Invalid access.",{code:"INVALID_REQUEST"})}return await I.bind(this)("block-account",e,{auth:true})}async function $a(t){let e=_.Params(t,{user_id:n=>_.UserId(n,'"user_id"')},["user_id"]);if(e?.service&&e?.owner?e={service:e?.service,owner:e?.owner,unblock:e.user_id}:e={unblock:e.user_id},!await Q.bind(this)()){if(!this.__user)throw new f("User needs to login.",{code:"INVALID_REQUEST"});if(this.__user.access_group<90)throw new f("Invalid access.",{code:"INVALID_REQUEST"})}return await I.bind(this)("block-account",e,{auth:true})}async function Ka(t){let e=_.Params(t,{user_id:n=>_.UserId(n,'"user_id"')},["user_id"]);if(e?.service&&e?.owner?e={service:e?.service,owner:e?.owner,delete:e.user_id}:e={delete:e.user_id},!await Q.bind(this)()){if(!this.__user)throw new f("User needs to login.",{code:"INVALID_REQUEST"});if(this.__user.access_group<90)throw new f("Invalid access.",{code:"INVALID_REQUEST"})}return await I.bind(this)("remove-account",e,{auth:true})}async function ja(t,e){let r={email:s=>_.Email(s),password:s=>_.Password(s),name:"string",username:"string",gender:"string",address:s=>{if(!s)return "";if(typeof s=="string")return s;if(typeof s=="object")return JSON.stringify(s)},birthdate:s=>_.Birthdate(s),phone_number:s=>_.PhoneNumber(s),picture:s=>{if(s)return _.Url(s)},profile:s=>{if(s)return _.Url(s)},website:s=>{if(s)return _.Url(s)},nickname:"string",misc:"string",email_public:["boolean",()=>false],gender_public:["boolean",()=>false],address_public:["boolean",()=>false],birthdate_public:["boolean",()=>false],phone_number_public:["boolean",()=>false],openid_id:"string",access_group:s=>{try{typeof s=="string"&&(s=s==="admin"?99:parseInt(s));}catch{throw new f('"access_group" is invalid. Should be type <number>.',{code:"INVALID_PARAMETER"})}if(typeof s!="number"||s<1||s>100)throw new f('"access_group" is invalid. Should be type <number> of range 1~99',{code:"INVALID_PARAMETER"});return s}},n=_.Params(t,r,["email"]);if(e=_.Params(e,{confirmation_url:s=>{let o=s;if(typeof s=="string")o=_.Url(s);else throw new f('"options.confirmation_url" should be type: <string>.',{code:"INVALID_PARAMETER"});if(o&&!n.email)throw new f('"email" is required for signup confirmation.',{code:"INVALID_PARAMETER"});return o},email_subscription:s=>{if(typeof s!="boolean")throw new f('"options.email_subscription" should be type: <boolean>.',{code:"INVALID_PARAMETER"});if(!e?.confirmation_url)throw new f('"options.confirmation_url" is required for email subscription.',{code:"INVALID_PARAMETER"});return s},template:s=>{if(typeof s!="object"||!s.url||!s.subject)throw new f('"options.template" should be type: <object> with "url" and "subject".',{code:"INVALID_PARAMETER"});return {url:_.Url(s.url),subject:s.subject}}}),n.signup_confirmation=e?.confirmation_url||true,n.email_subscription=e?.email_subscription||false,n.template=e?.template||{},!await Q.bind(this)()){if(!this.__user)throw new f("User needs to login.",{code:"INVALID_REQUEST"});if(this.__user.access_group<90)throw new f("Invalid access.",{code:"INVALID_REQUEST"})}return await I.bind(this)("admin-signup",n,{auth:true})}async function Ha(t){let e={email:s=>_.Email(s),password:s=>_.Password(s),openid_id:"string",name:"string",username:"string",gender:"string",address:s=>{if(!s)return "";if(typeof s=="string")return s;if(typeof s=="object")return JSON.stringify(s)},birthdate:s=>_.Birthdate(s),phone_number:s=>_.PhoneNumber(s),picture:s=>s?_.Url(s):"",profile:s=>s?_.Url(s):"",website:s=>s?_.Url(s):"",nickname:"string",misc:"string",email_public:["boolean",()=>false],gender_public:["boolean",()=>false],address_public:["boolean",()=>false],birthdate_public:["boolean",()=>false],phone_number_public:["boolean",()=>false],access_group:s=>{try{typeof s=="string"&&(s=parseInt(s));}catch{throw new f('"access_group" is invalid. Should be type <number>.',{code:"INVALID_PARAMETER"})}if(typeof s!="number"||s<1||s>100)throw new f('"access_group" is invalid. Should be type <number> of range 1~99',{code:"INVALID_PARAMETER"});return s}},r=["email","password"],n=_.Params(t,e,r);if(!await Q.bind(this)()){if(!this.__user)throw new f("User needs to login.",{code:"INVALID_REQUEST"});if(this.__user.access_group<90)throw new f("Invalid access.",{code:"INVALID_REQUEST"})}return await I.bind(this)("admin-signup",n,{auth:true})}async function Wa(t){if(t=_.Params(t,{user_id:r=>_.UserId(r,'"user_id"'),access_group:r=>{try{typeof r=="string"&&(r=parseInt(r));}catch{throw new f('"access_group" is invalid. Should be type <number>.',{code:"INVALID_PARAMETER"})}if(typeof r=="number"&&r>0&&r<100)return r;throw new f('"access_group" is invalid. Should be type <number> of range 1~99',{code:"INVALID_PARAMETER"})}},["user_id","access_group"]),!await Q.bind(this)()){if(!this.__user)throw new f("User needs to login.",{code:"INVALID_REQUEST"});if(this.__user.access_group<90)throw new f("Invalid access.",{code:"INVALID_REQUEST"})}return await I.bind(this)("grant-access",t,{auth:true})}async function Ga(t,e){if(t=_.Params(t,{email:"string"}),!await Q.bind(this)()){if(!this.__user)throw new f("User needs to login.",{code:"INVALID_REQUEST"});if(this.__user.access_group<90)throw new f("Invalid access.",{code:"INVALID_REQUEST"})}let n=await I.bind(this)("invitation-list",Object.assign({mode:"search"},t),{fetchOptions:e,auth:true});return n.list=n.list.map(i=>wt(i.user)),n}async function Ja(t){if(t=_.Params(t,{email:r=>_.Email(r)},["email"]),!await Q.bind(this)()){if(!this.__user)throw new f("User needs to login.",{code:"INVALID_REQUEST"});if(this.__user.access_group<90)throw new f("Invalid access.",{code:"INVALID_REQUEST"})}return await I.bind(this)("invitation-list",Object.assign({mode:"cancel"},t),{auth:true})}async function Ya(t){if(t=_.Params(t,{email:r=>_.Email(r)},["email"]),!await Q.bind(this)()){if(!this.__user)throw new f("User needs to login.",{code:"INVALID_REQUEST"});if(this.__user.access_group<90)throw new f("Invalid access.",{code:"INVALID_REQUEST"})}return await I.bind(this)("invitation-list",Object.assign({mode:"resend"},t),{auth:true})}async function za(t){let e=_.Params(t,{user_id:o=>_.UserId(o,'"user_id"'),email:o=>_.Email(o),address:o=>{if(!o)return "";if(typeof o=="string")return o;if(typeof o=="object")return JSON.stringify(o)},name:"string",gender:"string",birthdate:o=>o?_.Birthdate(o):"",phone_number:o=>o?_.PhoneNumber(o):"",email_public:"boolean",phone_number_public:"boolean",address_public:"boolean",gender_public:"boolean",birthdate_public:"boolean",misc:"string",picture:o=>o?_.Url(o):"",profile:o=>o?_.Url(o):"",nickname:"string",website:o=>o?_.Url(o):""},["user_id"]),r=e.service,n=e.owner;if(delete e.service,delete e.owner,Object.keys(e).filter(o=>o!=="user_id"&&e[o]!==void 0).length===0)throw new f("At least one attribute to update is required.",{code:"INVALID_PARAMETER"});if(!await Q.bind(this)()){if(!this.__user)throw new f("User needs to login.",{code:"INVALID_REQUEST"});if(this.__user.access_group<90)throw new f("Invalid access.",{code:"INVALID_REQUEST"})}e.email&&(e.preferred_username=(r||this.service)+"-"+z.hash(e.email));let s={attributes:e};return r&&n&&(s.service=r,s.owner=n),await I.bind(this)("admin-edit-profile",s,{auth:true})}async function Qa(t){if(typeof window>"u"||window._runningInNodeJS)throw new f("Push Notifications are not supported in Node.js environment.",{code:"NOT_SUPPORTED"});if(await this.__connection,!t.endpoint)throw new f("Missing parameter: endpoint",{code:"INVALID_PARAMETER"});if(!t.keys||!t.keys.p256dh||!t.keys.auth)throw new f("Missing parameter: keys.p256dh or keys.auth",{code:"INVALID_PARAMETER"});return await I.bind(this)("store-subscription",{endpoint:t.endpoint,keys:t.keys},{auth:true}),"SUCCESS: Subscribed to receive notifications."}async function Xa(t){if(typeof window>"u"||window._runningInNodeJS)throw new f("Push Notifications are not supported in Node.js environment.",{code:"NOT_SUPPORTED"});if(await this.__connection,!t.endpoint)throw new f("Missing parameter: endpoint",{code:"INVALID_PARAMETER"});if(!t.keys||!t.keys.p256dh||!t.keys.auth)throw new f("Missing parameter: keys.p256dh or keys.auth",{code:"INVALID_PARAMETER"});return await I.bind(this)("delete-subscription",{endpoint:t.endpoint,keys:t.keys},{auth:true}),"SUCCESS: Unsubscribed from notifications."}async function Za(){if(typeof window>"u"||window._runningInNodeJS)throw new f("Push Notifications are not supported in Node.js environment.",{code:"NOT_SUPPORTED"});return await this.__connection,{VAPIDPublicKey:await I.bind(this)("get-vapid-public-key",null,{auth:true})}}async function ec(t,e){if(typeof window>"u"||window._runningInNodeJS)throw new f("Push Notifications are not supported in Node.js environment.",{code:"NOT_SUPPORTED"});await this.__connection;let{title:r,body:n}=K(t||{},{nullIfEmpty:true}).data;if(!r)throw new f("Missing parameter: message title",{code:"INVALID_PARAMETER"});if(!n)throw new f("Missing parameter: message body",{code:"INVALID_PARAMETER"});let i={title:r,body:n};return e?(typeof e=="string"&&(e=[e]),i.user_ids=e):i.user_ids="all_users",await I.bind(this)("push-notification",i,{auth:true}),"SUCCESS: Notification sent."}async function tc(t){await this.__connection,t=_.Params(t,{spell:"string",name:"string",magic:r=>r},["spell","name"]);await I.bind(this)("castspell",t);return `The spell "${t.spell}" has been cast.`}async function rc(t){return await this.__connection,t=_.Params(t||{},{search:["spell","name",()=>"spell"],value:"string"}),await I.bind(this)("getspell",t)}async function nc(t){await this.__connection,t=_.Params(t,{message:"string",name:"string"},["message","name"]);let e=await I.bind(this)("dopamine",t,{auth:true}),r=e?.previous_message?.message,n=e?.previous_message?.name;if(re())r&&n&&window.alert(`${n} said: ${r}`),window.location.href=e.video;else return r&&n?`${n} said: ${r}
217
217
  Watch the video here: ${e.video}`:`Your message has been uploaded for future generations to receive.
218
- Watch the video here: ${e.video}`}var S=class{constructor(e,t,n,i){this.__version="2.0.0-rc.6";this.project_id="";this.session=null;this.connection=null;this.__my_unique_ids={};this.__uniqueIdsPersistTimer=null;this.userPool=null;this.__socket=null;this.__mediaStream=null;this.host="skapi";this.hostDomain="skapi.com";this.target_cdn="d3e9syvbtso631";this.customApiDomain="skapi.dev";this.requestBatchSize=30;this.__disabledAccount=null;this.__cached_requests={};this.__startKeyHistory={};this.__request_signup_confirmation=null;this.__private_access_key={};this.__class_properties_has_been_cached=false;this.__user=null;this._userProfileListeners=[];this._onLoginListeners=[];this._onBatchProcessListeners=[];this.validate={userId(e){try{return m.UserId(e),!0}catch{return false}},url(e){try{return m.Url(e),!0}catch{return false}},phoneNumber(e){try{return m.PhoneNumber(e),!0}catch{return false}},birthdate(e){try{return m.Birthdate(e),!0}catch{return false}},email(e){try{return m.Email(e),!0}catch{return false}},params(e,t,n){return m.Params(e,t,n)}};this.util={MD5:K,generateRandom:De,toBase62:ei,fromBase62:ie,decodeProjectId:Ur,formatServiceId:Cr,extractFormData:M,terminatePendingRequests:Ii,request:(e,t,n)=>T.bind(this)(e,t,n,{ignoreService:true})};this.__network_logs=false;this.__endpoint_version="v2";this.__public_identifier="";this.bearerToken="";this.registerTicket=si.bind(this);this.unregisterTicket=oi.bind(this);if(!e||typeof e!="string")throw this._alert("Service ID is required."),new f("Service ID is required.",{code:"INVALID_PARAMETER"});let s=e.trim().toLowerCase().replace(/^<|>$/g,"").replace(/[\s_\-.]+/g,"");if(s==="serviceid"||s==="projectid")throw this._alert(`Replace "${e}" with your actual Project ID.`),new f("Project ID is required.",{code:"INVALID_PARAMETER"});let o=e.split("-").length;if(o===2||o===7)try{let b=Ur(e);n&&typeof n=="object"&&(i=n),t&&typeof t=="object"&&(n=t),t=b.owner,e=b.service;}catch{throw this._alert("Service ID is invalid."),new f("Service ID is invalid.",{code:"INVALID_PARAMETER"})}if(!t||typeof t!="string")throw this._alert("Owner ID is invalid."),new f("Owner ID is invalid.",{code:"INVALID_PARAMETER"});if(t!==this.host)try{m.UserId(t,'"owner"');}catch{throw this._alert("Owner ID is invalid."),new f("Owner ID is invalid.",{code:"INVALID_PARAMETER"})}this.service=e,this.owner=t;try{this.project_id=Cr(e,t);}catch{this.project_id="";}let c=true,l=false;if(n&&(typeof n.refetchServiceInfo=="boolean"&&(l=n.refetchServiceInfo),typeof n.autoLogin=="boolean"&&(c=n.autoLogin),typeof n.requestBatchSize=="number")){if(n.requestBatchSize<1)throw new f('"requestBatchSize" must be greater than 0.',{code:"INVALID_PARAMETER"});this.requestBatchSize=n.requestBatchSize;}n?.eventListener&&typeof n.eventListener=="object"&&(n.eventListener?.onLogin&&typeof n.eventListener.onLogin=="function"&&(this.onLogin=n.eventListener.onLogin),n.eventListener?.onUserUpdate&&typeof n.eventListener.onUserUpdate=="function"&&(this.onUserUpdate=n.eventListener.onUserUpdate),n.eventListener?.onBatchProcess&&typeof n.eventListener.onBatchProcess=="function"&&(this.onBatchProcess=n.eventListener.onBatchProcess)),this.target_cdn=i?.target_cdn||this.target_cdn,this.hostDomain=i?.hostDomain||this.hostDomain,this.customApiDomain=i?.customApiDomain||this.customApiDomain,this.__network_logs=!!i?.network_logs;let d=`https://${this.target_cdn}.cloudfront.net`,h=e.substring(0,4);this.admin_endpoint=fetch(`${d}/${h}/admin-${this.__endpoint_version}.json`).then(b=>b.blob()).then(b=>new Promise((A,x)=>{let I=new FileReader;I.onloadend=()=>A(I.result),I.onerror=x,I.readAsDataURL(b);})).then(b=>{try{return typeof b=="string"?JSON.parse(atob(b.split(",")[1])):null}catch{throw new f("Service does not exist. Create your service from skapi.com",{code:"NOT_EXISTS"})}}),this.record_endpoint=fetch(`${d}/${h}/record-${this.__endpoint_version}.json`).then(b=>b.blob()).then(b=>new Promise((A,x)=>{let I=new FileReader;I.onloadend=()=>A(I.result),I.onerror=x,I.readAsDataURL(b);})).then(b=>{try{return typeof b=="string"?JSON.parse(atob(b.split(",")[1])):null}catch{throw new f("Service does not exist. Create your service from skapi.com",{code:"NOT_EXISTS"})}});let p=Y();if(p&&!window.sessionStorage)throw this._alert("This browser is not supported."),new Error("This browser is not supported.");let g=p?JSON.parse(window.sessionStorage.getItem(`${e}#${t}`)||"null"):null;if(this.log("constructor:restore",g),g?.connection){for(let b in g)this[b]=g[b];g.__public_identifier||(this.__public_identifier=`${this.service}:${this.owner}:${De(16)}`);}this.__authConnection=(async()=>{let b=await this.admin_endpoint,A={UserPoolId:b.userpool_id,ClientId:b.userpool_client};xr()&&(A.Storage=window.localStorage),this.userPool=new Rr(A);try{this.user||await G.bind(this)().getSession({skipUserUpdateEventTrigger:!0}),this.user&&(!g?.connection&&!c?Ae.bind(this)():(this._runOnLoginListeners(this.user),this._runOnUserUpdateListeners(this.user)));}catch{}})();let _=`${this.service}/${this.owner}`,w=p?window.sessionStorage.getItem(`${_}:uniqueids`):null;if(w)try{let b=JSON.parse(w);this.__my_unique_ids=b&&typeof b=="object"&&!Array.isArray(b)?{[_]:b}:{};}catch{this.__my_unique_ids={};}this.__connection=(async()=>{let b=null;await this.record_endpoint,g?.connection||(b=this._updateConnection({refresh:l}));let A=()=>{if(this.__class_properties_has_been_cached)return;let x=()=>{let I={},D=["__startKeyHistory","__disabledAccount","__cached_requests","__request_signup_confirmation","__public_identifier","connection"];if(this.connection){for(let F of D)I[F]=this[F];if(p){let F=`${e}#${t}`;try{window.sessionStorage.setItem(F,JSON.stringify(I));}catch{try{let O=Object.assign({},I,{__cached_requests:{},__startKeyHistory:{}});window.sessionStorage.setItem(F,JSON.stringify(O));}catch{try{window.sessionStorage.removeItem(F);}catch{}}}}this.__class_properties_has_been_cached=true;}};return b instanceof Promise?b.then(()=>x()):x()};return p&&(window.addEventListener("beforeunload",()=>{this.closeRealtime(),A();}),window.addEventListener("visibilitychange",()=>{A();})),await b,await this.__authConnection,this.connection})(),this.__connection.then(b=>{((b?.group||0)<3||this.__network_logs)&&this.version();});}get user(){return this.__user&&Object.keys(this.__user).length?JSON.parse(JSON.stringify(this.__user)):null}set user(e){}get onLogin(){return this._onLoginListeners}set onLogin(e){typeof e=="function"&&this._onLoginListeners.push(e);}get onUserUpdate(){return this._userProfileListeners}set onUserUpdate(e){typeof e=="function"&&this._userProfileListeners.push(e);}_runOnUserUpdateListeners(e){for(let t of this._userProfileListeners)typeof t=="function"&&t(e);}_runOnLoginListeners(e){for(let t of this._onLoginListeners)typeof t=="function"&&t(e);}get onBatchProcess(){return this._onBatchProcessListeners}set onBatchProcess(e){typeof e=="function"&&this._onBatchProcessListeners.push(e);}_alert(e){Y()&&typeof window.alert=="function"&&window.alert(e);}async getConnectionInfo(e){e?.refresh&&(this.__connection instanceof Promise&&await this.__connection,this.__connection=this._updateConnection({refresh:true}));let n=await this.__connection,i=n?.user_agent||(Y()&&typeof window.navigator?.userAgent=="string"?window.navigator.userAgent:`skapi-node/${globalThis?.process?.versions?.node||"unknown"}`);return {project_id:this.project_id,user_ip:n.ip,user_agent:i,user_location:n.locale,service_name:n.service_name,version:this.__version,service_description:n?.service_description||"",ai_agent:n?.ai_agent||"",conf:n?.opt}}async _updateConnection(e){let t=e?.refresh||false;try{this.connection=await T.bind(this)("service",{service:this.service,owner:this.owner,refresh:t},{bypassAwaitConnection:!0,method:"get"});}catch(n){throw this.log("connection fail",n),this._alert("Service is not available: "+(n.message||n.toString())),this.connection=null,n}return this.connection}async version(){if(await this.__connection,Y()){let t=`Built with:
218
+ Watch the video here: ${e.video}`}var S=class{constructor(e,r,n,i){this.__version="2.0.0-rc.7";this.project_id="";this.session=null;this.connection=null;this.__my_unique_ids={};this.__uniqueIdsPersistTimer=null;this.userPool=null;this.__socket=null;this.__mediaStream=null;this.host="skapi";this.hostDomain="skapi.com";this.target_cdn="d3e9syvbtso631";this.customApiDomain="skapi.dev";this.requestBatchSize=30;this.__disabledAccount=null;this.__cached_requests={};this.__startKeyHistory={};this.__request_signup_confirmation=null;this.__private_access_key={};this.__class_properties_has_been_cached=false;this.__user=null;this._userProfileListeners=[];this._onLoginListeners=[];this._onBatchProcessListeners=[];this.validate={userId(e){try{return _.UserId(e),!0}catch{return false}},url(e){try{return _.Url(e),!0}catch{return false}},phoneNumber(e){try{return _.PhoneNumber(e),!0}catch{return false}},birthdate(e){try{return _.Birthdate(e),!0}catch{return false}},email(e){try{return _.Email(e),!0}catch{return false}},params(e,r,n){return _.Params(e,r,n)}};this.util={MD5:z,generateRandom:We,toBase62:as,fromBase62:fe,decodeProjectId:mn,formatServiceId:yn,extractFormData:K,terminatePendingRequests:No,request:(e,r,n)=>I.bind(this)(e,r,n,{ignoreService:true})};this.__network_logs=false;this.__endpoint_version="v2";this.__public_identifier="";this.bearerToken="";this.registerTicket=fo.bind(this);this.unregisterTicket=ho.bind(this);if(!e||typeof e!="string")throw this._alert("Service ID is required."),new f("Service ID is required.",{code:"INVALID_PARAMETER"});let s=e.trim().toLowerCase().replace(/^<|>$/g,"").replace(/[\s_\-.]+/g,"");if(s==="serviceid"||s==="projectid")throw this._alert(`Replace "${e}" with your actual Project ID.`),new f("Project ID is required.",{code:"INVALID_PARAMETER"});let o=e.split("-").length;if(o===2||o===7)try{let E=mn(e);n&&typeof n=="object"&&(i=n),r&&typeof r=="object"&&(n=r),r=E.owner,e=E.service;}catch{throw this._alert("Service ID is invalid."),new f("Service ID is invalid.",{code:"INVALID_PARAMETER"})}if(!r||typeof r!="string")throw this._alert("Owner ID is invalid."),new f("Owner ID is invalid.",{code:"INVALID_PARAMETER"});if(r!==this.host)try{_.UserId(r,'"owner"');}catch{throw this._alert("Owner ID is invalid."),new f("Owner ID is invalid.",{code:"INVALID_PARAMETER"})}this.service=e,this.owner=r;try{this.project_id=yn(e,r);}catch{this.project_id="";}let u=true,l=false,d=null;if(n&&(typeof n.refetchServiceInfo=="boolean"&&(l=n.refetchServiceInfo),typeof n.autoLogin=="boolean"&&(u=n.autoLogin),n.encryption&&(d=xs(n.encryption)),typeof n.requestBatchSize=="number")){if(n.requestBatchSize<1)throw new f('"requestBatchSize" must be greater than 0.',{code:"INVALID_PARAMETER"});this.requestBatchSize=n.requestBatchSize;}n?.eventListener&&typeof n.eventListener=="object"&&(n.eventListener?.onLogin&&typeof n.eventListener.onLogin=="function"&&(this.onLogin=n.eventListener.onLogin),n.eventListener?.onUserUpdate&&typeof n.eventListener.onUserUpdate=="function"&&(this.onUserUpdate=n.eventListener.onUserUpdate),n.eventListener?.onBatchProcess&&typeof n.eventListener.onBatchProcess=="function"&&(this.onBatchProcess=n.eventListener.onBatchProcess)),this.target_cdn=i?.target_cdn||this.target_cdn,this.hostDomain=i?.hostDomain||this.hostDomain,this.customApiDomain=i?.customApiDomain||this.customApiDomain,this.__network_logs=!!i?.network_logs;let h=`https://${this.target_cdn}.cloudfront.net`,p=e.substring(0,4);this.admin_endpoint=fetch(`${h}/${p}/admin-${this.__endpoint_version}.json`).then(E=>E.blob()).then(E=>new Promise((v,x)=>{let P=new FileReader;P.onloadend=()=>v(P.result),P.onerror=x,P.readAsDataURL(E);})).then(E=>{try{return typeof E=="string"?JSON.parse(atob(E.split(",")[1])):null}catch{throw new f("Service does not exist. Create your service from skapi.com",{code:"NOT_EXISTS"})}}),this.record_endpoint=fetch(`${h}/${p}/record-${this.__endpoint_version}.json`).then(E=>E.blob()).then(E=>new Promise((v,x)=>{let P=new FileReader;P.onloadend=()=>v(P.result),P.onerror=x,P.readAsDataURL(E);})).then(E=>{try{return typeof E=="string"?JSON.parse(atob(E.split(",")[1])):null}catch{throw new f("Service does not exist. Create your service from skapi.com",{code:"NOT_EXISTS"})}});let g=re();if(g&&!window.sessionStorage)throw this._alert("This browser is not supported."),new Error("This browser is not supported.");let m=g?JSON.parse(window.sessionStorage.getItem(`${e}#${r}`)||"null"):null;if(this.log("constructor:restore",m),m?.connection){for(let E in m)this[E]=m[E];m.__public_identifier||(this.__public_identifier=`${this.service}:${this.owner}:${We(16)}`);}Cs.bind(this)(d),this.__authConnection=(async()=>{let E=await this.admin_endpoint,v={UserPoolId:E.userpool_id,ClientId:E.userpool_client};pn()&&(v.Storage=window.localStorage),this.userPool=new dn(v);try{this.user||await Z.bind(this)().getSession({skipUserUpdateEventTrigger:!0}),this.user&&(!m?.connection&&!u?Oe.bind(this)():(d&&Js.bind(this)(),this._runOnLoginListeners(this.user),this._runOnUserUpdateListeners(this.user)));}catch{}})();let y=`${this.service}/${this.owner}`,b=g?window.sessionStorage.getItem(`${y}:uniqueids`):null;if(b)try{let E=JSON.parse(b);this.__my_unique_ids=E&&typeof E=="object"&&!Array.isArray(E)?{[y]:E}:{};}catch{this.__my_unique_ids={};}this.__connection=(async()=>{let E=null;await this.record_endpoint,m?.connection||(E=this._updateConnection({refresh:l}));let v=()=>{if(this.__class_properties_has_been_cached)return;let x=()=>{let P={},N=["__startKeyHistory","__disabledAccount","__cached_requests","__request_signup_confirmation","__public_identifier","connection"];if(this.connection){for(let O of N)P[O]=this[O];if(d&&(P.__cached_requests={},P.__startKeyHistory={}),g){let O=`${e}#${r}`;try{window.sessionStorage.setItem(O,JSON.stringify(P));}catch{try{let U=Object.assign({},P,{__cached_requests:{},__startKeyHistory:{}});window.sessionStorage.setItem(O,JSON.stringify(U));}catch{try{window.sessionStorage.removeItem(O);}catch{}}}}this.__class_properties_has_been_cached=true;}};return E instanceof Promise?E.then(()=>x()):x()};return g&&(window.addEventListener("beforeunload",()=>{this.closeRealtime(),v();}),window.addEventListener("visibilitychange",()=>{v();})),await E,await this.__authConnection,this.connection})(),this.__connection.then(E=>{((E?.group||0)<3||this.__network_logs)&&this.version();});}get user(){return this.__user&&Object.keys(this.__user).length?JSON.parse(JSON.stringify(this.__user)):null}set user(e){}get onLogin(){return this._onLoginListeners}set onLogin(e){typeof e=="function"&&this._onLoginListeners.push(e);}get onUserUpdate(){return this._userProfileListeners}set onUserUpdate(e){typeof e=="function"&&this._userProfileListeners.push(e);}_runOnUserUpdateListeners(e){for(let r of this._userProfileListeners)typeof r=="function"&&r(e);}_runOnLoginListeners(e){for(let r of this._onLoginListeners)typeof r=="function"&&r(e);}get onBatchProcess(){return this._onBatchProcessListeners}set onBatchProcess(e){typeof e=="function"&&this._onBatchProcessListeners.push(e);}_alert(e){re()&&typeof window.alert=="function"&&window.alert(e);}async getConnectionInfo(e){e?.refresh&&(this.__connection instanceof Promise&&await this.__connection,this.__connection=this._updateConnection({refresh:true}));let n=await this.__connection,i=n?.user_agent||(re()&&typeof window.navigator?.userAgent=="string"?window.navigator.userAgent:`skapi-node/${globalThis?.process?.versions?.node||"unknown"}`);return {project_id:this.project_id,user_ip:n.ip,user_agent:i,user_location:n.locale,service_name:n.service_name,version:this.__version,service_description:n?.service_description||"",ai_agent:n?.ai_agent||"",conf:n?.opt}}async _updateConnection(e){let r=e?.refresh||false;try{this.connection=await I.bind(this)("service",{service:this.service,owner:this.owner,refresh:r},{bypassAwaitConnection:!0,method:"get"});}catch(n){throw this.log("connection fail",n),this._alert("Service is not available: "+(n.message||n.toString())),this.connection=null,n}return this.connection}async version(){if(await this.__connection,re()){let r=`Built with:
219
219
  %c\r
220
220
  $$\\ $$\\ \r
221
221
  $$ | \\__|\r
@@ -230,7 +230,7 @@ $$$$$$$ |$$ | \\$$\\\\$$$$$$$ |$$$$$$$ |$$ |\r
230
230
  \\__| \r
231
231
  Version: ${this.__version}
232
232
 
233
- Full Documentation: https://docs.skapi.com/skapi.md`;console.log(t,"font-family: monospace; color:blue;"),this.connection.group===1&&console.log("%cSKAPI: THE SERVICE IS IN TRIAL MODE.","font-family: monospace; color:red;");}return this.__version}log(e,t){if(this.__network_logs){if(t!==null&&typeof t=="object")try{Y()?t=JSON.parse(JSON.stringify(t)):t=JSON.stringify(t,null,2);}catch{t=String(t);}else typeof t=="string"&&t.length>100&&(t=t.substring(0,100)+"...");console.log(`%c${e}:`,"color: blue;",t);}}getFeed(e,t){return As.bind(this)(e,t)}closeRTC(e){return ae.bind(this)(e)}connectRTC(e,t){return es.bind(this)(e,t)}connectRealtime(e){return Jt.bind(this)(e)}spellcast(e){return Ws.bind(this)(e)}getspell(e){return Js.bind(this)(e)}dopamine(e){return Gs.bind(this)(e)}getUniqueId(e,t){return Hi.bind(this)(e,t)}resendInvitation(e){return Vs.bind(this)(e)}cancelInvitation(e){return qs.bind(this)(e)}getInvitations(e,t){return Ms.bind(this)(e,t)}openIdLogin(e){return ui.bind(this)(e)}loginWithToken(e){return ci.bind(this)(e)}clientSecretRequest(e){return ps.bind(this)(e)}clientSecretRequestHistory(e,t){return ms.bind(this)(e,t)}cancelClientSecretRequest(e){return _s.bind(this)(e)}stopClientSecretPolling(e){return hs.bind(this)(e||{})}isPollStopped(e){return ds(e)}clientSecretRequestQueueCount(e){return gs.bind(this)(e)}consumeTicket(e){return ri.bind(this)(e)}getConsumedTickets(e,t){return ii.bind(this)(e,t)}getTickets(e,t){return ni.bind(this)(e,t)}closeRealtime(){return is.bind(this)()}getRealtimeUsers(e,t){return os.bind(this)(e,t)}sendInquiry(e){return bs.bind(this)(e)}blockAccount(e){return Ds.bind(this)(e)}unblockAccount(e){return ks.bind(this)(e)}deleteAccount(e){return Ns.bind(this)(e)}inviteUser(e,t){return Fs.bind(this)(e,t)}createAccount(e){return Os.bind(this)(e)}grantAccess(e){return Ls.bind(this)(e)}updateUserAttributes(e){return Bs.bind(this)(e)}getRealtimeGroups(e,t){return as.bind(this)(e,t)}postRealtime(e,t,n){return ss.bind(this)(e,t,n)}joinRealtime(e){return Kr.bind(this)(e)}getProfile(e){return ai.bind(this)(e)}getFile(e,t){return ke.bind(this)(e,t)}secureRequest(e,t){return ys.bind(this)(e,t)}forwardRequest(e,t){return Es.bind(this)(e,t)}getFormResponse(){return xi.bind(this)()}getRecords(e,t){return Mi.bind(this)(e,t)}getTables(e,t){return $i.bind(this)(e,t)}getIndexes(e,t){return ji.bind(this)(e,t)}getTags(e,t){return Ki.bind(this)(e,t)}deleteRecords(e,t){return Wi.bind(this)(e,t)}resendSignupConfirmation(){return li.bind(this)()}recoverAccount(e=false){return di.bind(this)(e)}getUsers(e,t){return Ei.bind(this)(e,t)}disableAccount(){return hi.bind(this)()}lastVerifiedEmail(e){return Ai.bind(this)(e)}unsubscribeNewsletter(e){return Us.bind(this)(e)}subscribeNotification(e,t){return $s.bind(this)({endpoint:e,keys:t})}unsubscribeNotification(e,t){return js.bind(this)({endpoint:e,keys:t})}vapidPublicKey(){return Ks.bind(this)()}pushNotification(e,t){return Hs.bind(this)(e,t)}getNewsletters(e,t){return Cs.bind(this)(e,t)}getNewsletterSubscription(e,t){return Ps.bind(this)(e,t)}requestUsernameChange(e){return Si.bind(this)(e)}grantPrivateRecordAccess(e){return Ji.bind(this)(e)}removePrivateRecordAccess(e){return Gi.bind(this)(e)}listPrivateRecordAccess(e,t){return Qi.bind(this)(e,t)}requestPrivateRecordAccessKey(e){return zi.bind(this)(e)}deleteFiles(e){return Fi.bind(this)(e)}uploadFiles(e,t){return Mt.bind(this)(e,t)}mock(e,t){return ws.bind(this)(e,t)}login(e){return kr.bind(this)(e)}logout(e){return rt.bind(this)(e)}signup(e,t){return fi.bind(this)(e,t)}resetPassword(e){return gi.bind(this)(e)}verifyEmail(e,t){return _i.bind(this)(e,t)}verifyPhoneNumber(e,t){return mi.bind(this)(e,t)}forgotPassword(e,t){return bi.bind(this)(e,t)}changePassword(e){return yi.bind(this)(e)}updateProfile(e){return wi.bind(this)(e)}postRecord(e,t,n){return Bi.bind(this)(e,t,n)}getSubscriptions(e,t){return Ss.bind(this)(e,t)}subscribe(e){return vs.bind(this)(e)}unsubscribe(e){return Ts.bind(this)(e)}blockSubscriber(e){return Rs.bind(this)(e)}unblockSubscriber(e){return Is.bind(this)(e)}subscribeNewsletter(e){return xs.bind(this)(e)}bulkPostRecords(e){return Vi.bind(this)(e)}};v([R()],S.prototype,"getFeed"),v([R()],S.prototype,"closeRTC"),v([R()],S.prototype,"connectRTC"),v([R()],S.prototype,"spellcast"),v([R()],S.prototype,"getspell"),v([R()],S.prototype,"dopamine"),v([R()],S.prototype,"getUniqueId"),v([R()],S.prototype,"resendInvitation"),v([R()],S.prototype,"cancelInvitation"),v([R()],S.prototype,"getInvitations"),v([R()],S.prototype,"openIdLogin"),v([R()],S.prototype,"loginWithToken"),v([R()],S.prototype,"clientSecretRequest"),v([R()],S.prototype,"clientSecretRequestHistory"),v([R()],S.prototype,"cancelClientSecretRequest"),v([R()],S.prototype,"consumeTicket"),v([R()],S.prototype,"getConsumedTickets"),v([R()],S.prototype,"getTickets"),v([R()],S.prototype,"getRealtimeUsers"),v([R()],S.prototype,"sendInquiry"),v([R()],S.prototype,"blockAccount"),v([R()],S.prototype,"unblockAccount"),v([R()],S.prototype,"deleteAccount"),v([R()],S.prototype,"inviteUser"),v([R()],S.prototype,"createAccount"),v([R()],S.prototype,"grantAccess"),v([R()],S.prototype,"updateUserAttributes"),v([R()],S.prototype,"getRealtimeGroups"),v([R()],S.prototype,"postRealtime"),v([R()],S.prototype,"joinRealtime"),v([R()],S.prototype,"getProfile"),v([R()],S.prototype,"getFile"),v([R()],S.prototype,"secureRequest"),v([R()],S.prototype,"forwardRequest"),v([R()],S.prototype,"getFormResponse"),v([R()],S.prototype,"getRecords"),v([R()],S.prototype,"getTables"),v([R()],S.prototype,"getIndexes"),v([R()],S.prototype,"getTags"),v([R()],S.prototype,"deleteRecords"),v([R()],S.prototype,"resendSignupConfirmation"),v([R()],S.prototype,"recoverAccount"),v([R()],S.prototype,"getUsers"),v([R()],S.prototype,"disableAccount"),v([R()],S.prototype,"lastVerifiedEmail"),v([R()],S.prototype,"unsubscribeNewsletter"),v([R()],S.prototype,"subscribeNotification"),v([R()],S.prototype,"unsubscribeNotification"),v([R()],S.prototype,"vapidPublicKey"),v([R()],S.prototype,"pushNotification"),v([R()],S.prototype,"getNewsletters"),v([R()],S.prototype,"getNewsletterSubscription"),v([R()],S.prototype,"requestUsernameChange"),v([R()],S.prototype,"grantPrivateRecordAccess"),v([R()],S.prototype,"removePrivateRecordAccess"),v([R()],S.prototype,"listPrivateRecordAccess"),v([R()],S.prototype,"requestPrivateRecordAccessKey"),v([R()],S.prototype,"deleteFiles"),v([R()],S.prototype,"uploadFiles"),v([R()],S.prototype,"mock"),v([R({preventMultipleCalls:true})],S.prototype,"login"),v([R()],S.prototype,"logout"),v([R({preventMultipleCalls:true})],S.prototype,"signup"),v([R({preventMultipleCalls:true})],S.prototype,"resetPassword"),v([R({preventMultipleCalls:true})],S.prototype,"verifyEmail"),v([R({preventMultipleCalls:true})],S.prototype,"verifyPhoneNumber"),v([R({preventMultipleCalls:true})],S.prototype,"forgotPassword"),v([R({preventMultipleCalls:true})],S.prototype,"changePassword"),v([R({preventMultipleCalls:true})],S.prototype,"updateProfile"),v([R()],S.prototype,"postRecord"),v([R()],S.prototype,"getSubscriptions"),v([R()],S.prototype,"subscribe"),v([R()],S.prototype,"unsubscribe"),v([R()],S.prototype,"blockSubscriber"),v([R()],S.prototype,"unblockSubscriber"),v([R()],S.prototype,"subscribeNewsletter");var Wr={};var Gt=typeof globalThis<"u"?globalThis:void 0;Gt&&(Gt.Skapi=S,Gt.SkapiError=f,Gt.SkapiTypes=Wr);/*! Bundled license information:
233
+ Full Documentation: https://docs.skapi.com/skapi.md`;console.log(r,"font-family: monospace; color:blue;"),this.connection.group===1&&console.log("%cSKAPI: THE SERVICE IS IN TRIAL MODE.","font-family: monospace; color:red;");}return this.__version}log(e,r){if(this.__network_logs){if(r!==null&&typeof r=="object")try{re()?r=JSON.parse(JSON.stringify(r)):r=JSON.stringify(r,null,2);}catch{r=String(r);}else typeof r=="string"&&r.length>100&&(r=r.substring(0,100)+"...");console.log(`%c${e}:`,"color: blue;",r);}}getFeed(e,r){return Ca.bind(this)(e,r)}closeRTC(e){return be.bind(this)(e)}connectRTC(e,r){return ua.bind(this)(e,r)}connectRealtime(e){return Cr.bind(this)(e)}spellcast(e){return tc.bind(this)(e)}getspell(e){return rc.bind(this)(e)}dopamine(e){return nc.bind(this)(e)}getUniqueId(e,r){return ea.bind(this)(e,r)}resendInvitation(e){return Ya.bind(this)(e)}cancelInvitation(e){return Ja.bind(this)(e)}getInvitations(e,r){return Ga.bind(this)(e,r)}openIdLogin(e){return po.bind(this)(e)}loginWithToken(e){return mo.bind(this)(e)}clientSecretRequest(e){return va.bind(this)(e)}clientSecretRequestHistory(e,r){return Ra.bind(this)(e,r)}cancelClientSecretRequest(e){return Ta.bind(this)(e)}stopClientSecretPolling(e){return Aa.bind(this)(e||{})}isPollStopped(e){return wa(e)}clientSecretRequestQueueCount(e){return Sa.bind(this)(e)}consumeTicket(e){return co.bind(this)(e)}getConsumedTickets(e,r){return lo.bind(this)(e,r)}getTickets(e,r){return uo.bind(this)(e,r)}closeRealtime(){return ha.bind(this)()}getRealtimeUsers(e,r){return pa.bind(this)(e,r)}sendInquiry(e){return Ia.bind(this)(e)}blockAccount(e){return Ba.bind(this)(e)}unblockAccount(e){return $a.bind(this)(e)}deleteAccount(e){return Ka.bind(this)(e)}inviteUser(e,r){return ja.bind(this)(e,r)}createAccount(e){return Ha.bind(this)(e)}grantAccess(e){return Wa.bind(this)(e)}updateUserAttributes(e){return za.bind(this)(e)}getRealtimeGroups(e,r){return ma.bind(this)(e,r)}postRealtime(e,r,n){return ga.bind(this)(e,r,n)}joinRealtime(e){return ei.bind(this)(e)}getProfile(e){return go.bind(this)(e)}getFile(e,r){return Ye.bind(this)(e,r)}secureRequest(e,r){return Pa.bind(this)(e,r)}forwardRequest(e,r){return xa.bind(this)(e,r)}getFormResponse(){return Fo.bind(this)()}getRecords(e,r){return Go.bind(this)(e,r)}getTables(e,r){return Qo.bind(this)(e,r)}getIndexes(e,r){return Xo.bind(this)(e,r)}getTags(e,r){return Zo.bind(this)(e,r)}deleteRecords(e,r){return ta.bind(this)(e,r)}resendSignupConfirmation(){return yo.bind(this)()}recoverAccount(e=false){return _o.bind(this)(e)}getUsers(e,r){return Po.bind(this)(e,r)}disableAccount(){return wo.bind(this)()}lastVerifiedEmail(e){return Uo.bind(this)(e)}unsubscribeNewsletter(e){return Va.bind(this)(e)}subscribeNotification(e,r){return Qa.bind(this)({endpoint:e,keys:r})}unsubscribeNotification(e,r){return Xa.bind(this)({endpoint:e,keys:r})}vapidPublicKey(){return Za.bind(this)()}pushNotification(e,r){return ec.bind(this)(e,r)}getNewsletters(e,r){return qa.bind(this)(e,r)}getNewsletterSubscription(e,r){return La.bind(this)(e,r)}requestUsernameChange(e){return xo.bind(this)(e)}getEncryptionStatus(){return Ds.bind(this)()}isWithheld(e){return xn.call(this,e)}unlockEncryption(e){return Ks.bind(this)(e)}lockEncryption(e){return js.bind(this)(e)}takeRecoveryCode(){return eo.bind(this)()}unlockWithRecoveryCode(e){return to.bind(this)(e)}regenerateRecoveryCode(){return ro.bind(this)()}pinPeerKey(e){return Xs.bind(this)(e)}grantPrivateRecordAccess(e){return ra.bind(this)(e)}removePrivateRecordAccess(e){return na.bind(this)(e)}listPrivateRecordAccess(e,r){return ia.bind(this)(e,r)}requestPrivateRecordAccessKey(e){return sa.bind(this)(e)}deleteFiles(e){return jo.bind(this)(e)}uploadFiles(e,r){return Ar.bind(this)(e,r)}mock(e,r){return Ua.bind(this)(e,r)}login(e){return Kn.bind(this)(e)}logout(e){return Dt.bind(this)(e)}signup(e,r){return bo.bind(this)(e,r)}resetPassword(e){return Eo.bind(this)(e)}verifyEmail(e,r){return vo.bind(this)(e,r)}verifyPhoneNumber(e,r){return So.bind(this)(e,r)}forgotPassword(e,r){return Ro.bind(this)(e,r)}changePassword(e){return To.bind(this)(e)}updateProfile(e){return Io.bind(this)(e)}postRecord(e,r,n){return zo.bind(this)(e,r,n)}getSubscriptions(e,r){return Da.bind(this)(e,r)}subscribe(e){return ka.bind(this)(e)}unsubscribe(e){return Na.bind(this)(e)}blockSubscriber(e){return Oa.bind(this)(e)}unblockSubscriber(e){return Fa.bind(this)(e)}subscribeNewsletter(e){return Ma.bind(this)(e)}bulkPostRecords(e){return Yo.bind(this)(e)}};R([T()],S.prototype,"getFeed"),R([T()],S.prototype,"closeRTC"),R([T()],S.prototype,"connectRTC"),R([T()],S.prototype,"spellcast"),R([T()],S.prototype,"getspell"),R([T()],S.prototype,"dopamine"),R([T()],S.prototype,"getUniqueId"),R([T()],S.prototype,"resendInvitation"),R([T()],S.prototype,"cancelInvitation"),R([T()],S.prototype,"getInvitations"),R([T()],S.prototype,"openIdLogin"),R([T()],S.prototype,"loginWithToken"),R([T()],S.prototype,"clientSecretRequest"),R([T()],S.prototype,"clientSecretRequestHistory"),R([T()],S.prototype,"cancelClientSecretRequest"),R([T()],S.prototype,"consumeTicket"),R([T()],S.prototype,"getConsumedTickets"),R([T()],S.prototype,"getTickets"),R([T()],S.prototype,"getRealtimeUsers"),R([T()],S.prototype,"sendInquiry"),R([T()],S.prototype,"blockAccount"),R([T()],S.prototype,"unblockAccount"),R([T()],S.prototype,"deleteAccount"),R([T()],S.prototype,"inviteUser"),R([T()],S.prototype,"createAccount"),R([T()],S.prototype,"grantAccess"),R([T()],S.prototype,"updateUserAttributes"),R([T()],S.prototype,"getRealtimeGroups"),R([T()],S.prototype,"postRealtime"),R([T()],S.prototype,"joinRealtime"),R([T()],S.prototype,"getProfile"),R([T()],S.prototype,"getFile"),R([T()],S.prototype,"secureRequest"),R([T()],S.prototype,"forwardRequest"),R([T()],S.prototype,"getFormResponse"),R([T()],S.prototype,"getRecords"),R([T()],S.prototype,"getTables"),R([T()],S.prototype,"getIndexes"),R([T()],S.prototype,"getTags"),R([T()],S.prototype,"deleteRecords"),R([T()],S.prototype,"resendSignupConfirmation"),R([T()],S.prototype,"recoverAccount"),R([T()],S.prototype,"getUsers"),R([T()],S.prototype,"disableAccount"),R([T()],S.prototype,"lastVerifiedEmail"),R([T()],S.prototype,"unsubscribeNewsletter"),R([T()],S.prototype,"subscribeNotification"),R([T()],S.prototype,"unsubscribeNotification"),R([T()],S.prototype,"vapidPublicKey"),R([T()],S.prototype,"pushNotification"),R([T()],S.prototype,"getNewsletters"),R([T()],S.prototype,"getNewsletterSubscription"),R([T()],S.prototype,"requestUsernameChange"),R([T()],S.prototype,"unlockEncryption"),R([T()],S.prototype,"unlockWithRecoveryCode"),R([T()],S.prototype,"grantPrivateRecordAccess"),R([T()],S.prototype,"removePrivateRecordAccess"),R([T()],S.prototype,"listPrivateRecordAccess"),R([T()],S.prototype,"requestPrivateRecordAccessKey"),R([T()],S.prototype,"deleteFiles"),R([T()],S.prototype,"uploadFiles"),R([T()],S.prototype,"mock"),R([T({preventMultipleCalls:true})],S.prototype,"login"),R([T()],S.prototype,"logout"),R([T({preventMultipleCalls:true})],S.prototype,"signup"),R([T({preventMultipleCalls:true})],S.prototype,"resetPassword"),R([T({preventMultipleCalls:true})],S.prototype,"verifyEmail"),R([T({preventMultipleCalls:true})],S.prototype,"verifyPhoneNumber"),R([T({preventMultipleCalls:true})],S.prototype,"forgotPassword"),R([T({preventMultipleCalls:true})],S.prototype,"changePassword"),R([T({preventMultipleCalls:true})],S.prototype,"updateProfile"),R([T()],S.prototype,"postRecord"),R([T()],S.prototype,"getSubscriptions"),R([T()],S.prototype,"subscribe"),R([T()],S.prototype,"unsubscribe"),R([T()],S.prototype,"blockSubscriber"),R([T()],S.prototype,"unblockSubscriber"),R([T()],S.prototype,"subscribeNewsletter");var ri={};var Dr=typeof globalThis<"u"?globalThis:void 0;Dr&&(Dr.Skapi=S,Dr.SkapiError=f,Dr.SkapiTypes=ri);/*! Bundled license information:
234
234
 
235
235
  ieee754/index.js:
236
236
  (*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh <https://feross.org/opensource> *)
@@ -280,5 +280,5 @@ amazon-cognito-identity-js/es/index.js:
280
280
 
281
281
  js-cookie/dist/js.cookie.mjs:
282
282
  (*! js-cookie v3.0.8 | MIT *)
283
- */export{S as Skapi,f as SkapiError,Wr as Types};//# sourceMappingURL=skapi.browser.mjs.map
283
+ */export{S as Skapi,f as SkapiError,ri as Types};//# sourceMappingURL=skapi.browser.mjs.map
284
284
  //# sourceMappingURL=skapi.browser.mjs.map