skapi-js 2.0.5 → 2.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/skapi.browser.mjs +6 -6
- package/dist/skapi.browser.mjs.map +1 -1
- package/dist/skapi.cjs +6 -6
- package/dist/skapi.cjs.map +1 -1
- package/dist/skapi.d.mts +793 -55
- package/dist/skapi.d.ts +793 -55
- package/dist/skapi.js +6 -6
- package/dist/skapi.js.map +1 -1
- package/dist/skapi.mjs +6 -6
- package/dist/skapi.mjs.map +1 -1
- package/package.json +2 -2
package/dist/skapi.browser.mjs
CHANGED
|
@@ -203,8 +203,8 @@
|
|
|
203
203
|
limitations under the License.
|
|
204
204
|
|
|
205
205
|
*/
|
|
206
|
-
var Fc=Object.create;var et=Object.defineProperty;var bi=Object.getOwnPropertyDescriptor;var Lc=Object.getOwnPropertyNames;var Mc=Object.getPrototypeOf,qc=Object.prototype.hasOwnProperty;var Vc=(t,e,r)=>e in t?et(t,e,{enumerable:true,configurable:true,writable:true,value:r}):t[e]=r;var Ve=(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 tt=(t,e)=>()=>(t&&(e=t(t=0)),e);var se=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),Qt=(t,e)=>{for(var r in e)et(t,r,{get:e[r],enumerable:true});},wi=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of Lc(e))!qc.call(t,i)&&i!==r&&et(t,i,{get:()=>e[i],enumerable:!(n=bi(e,i))||n.enumerable});return t};var rt=(t,e,r)=>(r=t!=null?Fc(Mc(t)):{},wi(!t||!t.__esModule?et(r,"default",{value:t,enumerable:true}):r,t)),nt=t=>wi(et({},"__esModule",{value:true}),t),I=(t,e,r,n)=>{for(var i=bi(e,r),s=t.length-1,o;s>=0;s--)(o=t[s])&&(i=(o(e,r,i))||i);return i&&et(e,r,i),i};var Re=(t,e,r)=>Vc(t,typeof e!="symbol"?e+"":e,r);var vi=se(Zt=>{Zt.byteLength=Kc;Zt.toByteArray=Hc;Zt.fromByteArray=Jc;var Te=[],fe=[],$c=typeof Uint8Array<"u"?Uint8Array:Array,Jr="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";for(We=0,Ai=Jr.length;We<Ai;++We)Te[We]=Jr[We],fe[Jr.charCodeAt(We)]=We;var We,Ai;fe[45]=62;fe[95]=63;function Si(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 Kc(t){var e=Si(t),r=e[0],n=e[1];return (r+n)*3/4-n}function jc(t,e,r){return (e+r)*3/4-r}function Hc(t){var e,r=Si(t),n=r[0],i=r[1],s=new $c(jc(t,n,i)),o=0,a=i>0?n-4:n,l;for(l=0;l<a;l+=4)e=fe[t.charCodeAt(l)]<<18|fe[t.charCodeAt(l+1)]<<12|fe[t.charCodeAt(l+2)]<<6|fe[t.charCodeAt(l+3)],s[o++]=e>>16&255,s[o++]=e>>8&255,s[o++]=e&255;return i===2&&(e=fe[t.charCodeAt(l)]<<2|fe[t.charCodeAt(l+1)]>>4,s[o++]=e&255),i===1&&(e=fe[t.charCodeAt(l)]<<10|fe[t.charCodeAt(l+1)]<<4|fe[t.charCodeAt(l+2)]>>2,s[o++]=e>>8&255,s[o++]=e&255),s}function Wc(t){return Te[t>>18&63]+Te[t>>12&63]+Te[t>>6&63]+Te[t&63]}function Gc(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(Wc(n));return i.join("")}function Jc(t){for(var e,r=t.length,n=r%3,i=[],s=16383,o=0,a=r-n;o<a;o+=s)i.push(Gc(t,o,o+s>a?a:o+s));return n===1?(e=t[r-1],i.push(Te[e>>2]+Te[e<<4&63]+"==")):n===2&&(e=(t[r-2]<<8)+t[r-1],i.push(Te[e>>10]+Te[e>>4&63]+Te[e<<2&63]+"=")),i.join("")}});var Ri=se(Yr=>{Yr.read=function(t,e,r,n,i){var s,o,a=i*8-n-1,l=(1<<a)-1,c=l>>1,u=-7,f=r?i-1:0,d=r?-1:1,p=t[e+f];for(f+=d,s=p&(1<<-u)-1,p>>=-u,u+=a;u>0;s=s*256+t[e+f],f+=d,u-=8);for(o=s&(1<<-u)-1,s>>=-u,u+=n;u>0;o=o*256+t[e+f],f+=d,u-=8);if(s===0)s=1-c;else {if(s===l)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)};Yr.write=function(t,e,r,n,i,s){var o,a,l,c=s*8-i-1,u=(1<<c)-1,f=u>>1,d=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=u):(o=Math.floor(Math.log(e)/Math.LN2),e*(l=Math.pow(2,-o))<1&&(o--,l*=2),o+f>=1?e+=d/l:e+=d*Math.pow(2,1-f),e*l>=2&&(o++,l/=2),o+f>=u?(a=0,o=u):o+f>=1?(a=(e*l-1)*Math.pow(2,i),o=o+f):(a=e*Math.pow(2,f-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,c+=i;c>0;t[r+p]=o&255,p+=g,o/=256,c-=8);t[r+p-g]|=m*128;};});var Ii=se((jf,Ti)=>{var Yc={}.toString;Ti.exports=Array.isArray||function(t){return Yc.call(t)=="[object Array]"};});var sr=se(st=>{var zr=vi(),it=Ri(),xi=Ii();st.Buffer=E;st.SlowBuffer=tl;st.INSPECT_MAX_BYTES=50;E.TYPED_ARRAY_SUPPORT=globalThis.TYPED_ARRAY_SUPPORT!==void 0?globalThis.TYPED_ARRAY_SUPPORT:zc();st.kMaxLength=er();function zc(){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 er(){return E.TYPED_ARRAY_SUPPORT?2147483647:1073741823}function Ne(t,e){if(er()<e)throw new RangeError("Invalid typed array length");return E.TYPED_ARRAY_SUPPORT?(t=new Uint8Array(e),t.__proto__=E.prototype):(t===null&&(t=new E(e)),t.length=e),t}function E(t,e,r){if(!E.TYPED_ARRAY_SUPPORT&&!(this instanceof E))return new E(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 Xr(this,t)}return Ci(this,t,e,r)}E.poolSize=8192;E._augment=function(t){return t.__proto__=E.prototype,t};function Ci(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?Zc(t,e,r,n):typeof e=="string"?Xc(t,e,r):el(t,e)}E.from=function(t,e,r){return Ci(null,t,e,r)};E.TYPED_ARRAY_SUPPORT&&(E.prototype.__proto__=Uint8Array.prototype,E.__proto__=Uint8Array,typeof Symbol<"u"&&Symbol.species&&E[Symbol.species]===E&&Object.defineProperty(E,Symbol.species,{value:null,configurable:true}));function ki(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 Qc(t,e,r,n){return ki(e),e<=0?Ne(t,e):r!==void 0?typeof n=="string"?Ne(t,e).fill(r,n):Ne(t,e).fill(r):Ne(t,e)}E.alloc=function(t,e,r){return Qc(null,t,e,r)};function Xr(t,e){if(ki(e),t=Ne(t,e<0?0:Zr(e)|0),!E.TYPED_ARRAY_SUPPORT)for(var r=0;r<e;++r)t[r]=0;return t}E.allocUnsafe=function(t){return Xr(null,t)};E.allocUnsafeSlow=function(t){return Xr(null,t)};function Xc(t,e,r){if((typeof r!="string"||r==="")&&(r="utf8"),!E.isEncoding(r))throw new TypeError('"encoding" must be a valid string encoding');var n=Di(e,r)|0;t=Ne(t,n);var i=t.write(e,r);return i!==n&&(t=t.slice(0,i)),t}function Qr(t,e){var r=e.length<0?0:Zr(e.length)|0;t=Ne(t,r);for(var n=0;n<r;n+=1)t[n]=e[n]&255;return t}function Zc(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),E.TYPED_ARRAY_SUPPORT?(t=e,t.__proto__=E.prototype):t=Qr(t,e),t}function el(t,e){if(E.isBuffer(e)){var r=Zr(e.length)|0;return t=Ne(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"||wl(e.length)?Ne(t,0):Qr(t,e);if(e.type==="Buffer"&&xi(e.data))return Qr(t,e.data)}throw new TypeError("First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.")}function Zr(t){if(t>=er())throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+er().toString(16)+" bytes");return t|0}function tl(t){return +t!=t&&(t=0),E.alloc(+t)}E.isBuffer=function(e){return !!(e!=null&&e._isBuffer)};E.compare=function(e,r){if(!E.isBuffer(e)||!E.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};E.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}};E.concat=function(e,r){if(!xi(e))throw new TypeError('"list" argument must be an Array of Buffers');if(e.length===0)return E.alloc(0);var n;if(r===void 0)for(r=0,n=0;n<e.length;++n)r+=e[n].length;var i=E.allocUnsafe(r),s=0;for(n=0;n<e.length;++n){var o=e[n];if(!E.isBuffer(o))throw new TypeError('"list" argument must be an Array of Buffers');o.copy(i,s),s+=o.length;}return i};function Di(t,e){if(E.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 tr(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 tr(t).length;e=(""+e).toLowerCase(),n=true;}}E.byteLength=Di;function rl(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 fl(this,e,r);case "utf8":case "utf-8":return Fi(this,e,r);case "ascii":return ul(this,e,r);case "latin1":case "binary":return dl(this,e,r);case "base64":return cl(this,e,r);case "ucs2":case "ucs-2":case "utf16le":case "utf-16le":return hl(this,e,r);default:if(n)throw new TypeError("Unknown encoding: "+t);t=(t+"").toLowerCase(),n=true;}}E.prototype._isBuffer=true;function Ge(t,e,r){var n=t[e];t[e]=t[r],t[r]=n;}E.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)Ge(this,r,r+1);return this};E.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)Ge(this,r,r+3),Ge(this,r+1,r+2);return this};E.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)Ge(this,r,r+7),Ge(this,r+1,r+6),Ge(this,r+2,r+5),Ge(this,r+3,r+4);return this};E.prototype.toString=function(){var e=this.length|0;return e===0?"":arguments.length===0?Fi(this,0,e):rl.apply(this,arguments)};E.prototype.equals=function(e){if(!E.isBuffer(e))throw new TypeError("Argument must be a Buffer");return this===e?true:E.compare(this,e)===0};E.prototype.inspect=function(){var e="",r=st.INSPECT_MAX_BYTES;return this.length>0&&(e=this.toString("hex",0,r).match(/.{2}/g).join(" "),this.length>r&&(e+=" ... ")),"<Buffer "+e+">"};E.prototype.compare=function(e,r,n,i,s){if(!E.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,l=Math.min(o,a),c=this.slice(i,s),u=e.slice(r,n),f=0;f<l;++f)if(c[f]!==u[f]){o=c[f],a=u[f];break}return o<a?-1:a<o?1:0};function Ni(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=E.from(e,n)),E.isBuffer(e))return e.length===0?-1:Pi(t,e,r,n,i);if(typeof e=="number")return e=e&255,E.TYPED_ARRAY_SUPPORT&&typeof Uint8Array.prototype.indexOf=="function"?i?Uint8Array.prototype.indexOf.call(t,e,r):Uint8Array.prototype.lastIndexOf.call(t,e,r):Pi(t,[e],r,n,i);throw new TypeError("val must be string, number or Buffer")}function Pi(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 l(p,g){return s===1?p[g]:p.readUInt16BE(g*s)}var c;if(i){var u=-1;for(c=r;c<o;c++)if(l(t,c)===l(e,u===-1?0:c-u)){if(u===-1&&(u=c),c-u+1===a)return u*s}else u!==-1&&(c-=c-u),u=-1;}else for(r+a>o&&(r=o-a),c=r;c>=0;c--){for(var f=true,d=0;d<a;d++)if(l(t,c+d)!==l(e,d)){f=false;break}if(f)return c}return -1}E.prototype.includes=function(e,r,n){return this.indexOf(e,r,n)!==-1};E.prototype.indexOf=function(e,r,n){return Ni(this,e,r,n,true)};E.prototype.lastIndexOf=function(e,r,n){return Ni(this,e,r,n,false)};function nl(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 il(t,e,r,n){return ir(tr(e,t.length-r),t,r,n)}function Oi(t,e,r,n){return ir(_l(e),t,r,n)}function sl(t,e,r,n){return Oi(t,e,r,n)}function ol(t,e,r,n){return ir(Vi(e),t,r,n)}function al(t,e,r,n){return ir(bl(e,t.length-r),t,r,n)}E.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 nl(this,e,r,n);case "utf8":case "utf-8":return il(this,e,r,n);case "ascii":return Oi(this,e,r,n);case "latin1":case "binary":return sl(this,e,r,n);case "base64":return ol(this,e,r,n);case "ucs2":case "ucs-2":case "utf16le":case "utf-16le":return al(this,e,r,n);default:if(o)throw new TypeError("Unknown encoding: "+i);i=(""+i).toLowerCase(),o=true;}};E.prototype.toJSON=function(){return {type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};function cl(t,e,r){return e===0&&r===t.length?zr.fromByteArray(t):zr.fromByteArray(t.slice(e,r))}function Fi(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 l,c,u,f;switch(a){case 1:s<128&&(o=s);break;case 2:l=t[i+1],(l&192)===128&&(f=(s&31)<<6|l&63,f>127&&(o=f));break;case 3:l=t[i+1],c=t[i+2],(l&192)===128&&(c&192)===128&&(f=(s&15)<<12|(l&63)<<6|c&63,f>2047&&(f<55296||f>57343)&&(o=f));break;case 4:l=t[i+1],c=t[i+2],u=t[i+3],(l&192)===128&&(c&192)===128&&(u&192)===128&&(f=(s&15)<<18|(l&63)<<12|(c&63)<<6|u&63,f>65535&&f<1114112&&(o=f));}}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 ll(n)}var Ui=4096;function ll(t){var e=t.length;if(e<=Ui)return String.fromCharCode.apply(String,t);for(var r="",n=0;n<e;)r+=String.fromCharCode.apply(String,t.slice(n,n+=Ui));return r}function ul(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 dl(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 fl(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+=yl(t[s]);return i}function hl(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}E.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(E.TYPED_ARRAY_SUPPORT)i=this.subarray(e,r),i.__proto__=E.prototype;else {var s=r-e;i=new E(s,void 0);for(var o=0;o<s;++o)i[o]=this[o+e];}return i};function J(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")}E.prototype.readUIntLE=function(e,r,n){e=e|0,r=r|0,n||J(e,r,this.length);for(var i=this[e],s=1,o=0;++o<r&&(s*=256);)i+=this[e+o]*s;return i};E.prototype.readUIntBE=function(e,r,n){e=e|0,r=r|0,n||J(e,r,this.length);for(var i=this[e+--r],s=1;r>0&&(s*=256);)i+=this[e+--r]*s;return i};E.prototype.readUInt8=function(e,r){return r||J(e,1,this.length),this[e]};E.prototype.readUInt16LE=function(e,r){return r||J(e,2,this.length),this[e]|this[e+1]<<8};E.prototype.readUInt16BE=function(e,r){return r||J(e,2,this.length),this[e]<<8|this[e+1]};E.prototype.readUInt32LE=function(e,r){return r||J(e,4,this.length),(this[e]|this[e+1]<<8|this[e+2]<<16)+this[e+3]*16777216};E.prototype.readUInt32BE=function(e,r){return r||J(e,4,this.length),this[e]*16777216+(this[e+1]<<16|this[e+2]<<8|this[e+3])};E.prototype.readIntLE=function(e,r,n){e=e|0,r=r|0,n||J(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};E.prototype.readIntBE=function(e,r,n){e=e|0,r=r|0,n||J(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};E.prototype.readInt8=function(e,r){return r||J(e,1,this.length),this[e]&128?(255-this[e]+1)*-1:this[e]};E.prototype.readInt16LE=function(e,r){r||J(e,2,this.length);var n=this[e]|this[e+1]<<8;return n&32768?n|4294901760:n};E.prototype.readInt16BE=function(e,r){r||J(e,2,this.length);var n=this[e+1]|this[e]<<8;return n&32768?n|4294901760:n};E.prototype.readInt32LE=function(e,r){return r||J(e,4,this.length),this[e]|this[e+1]<<8|this[e+2]<<16|this[e+3]<<24};E.prototype.readInt32BE=function(e,r){return r||J(e,4,this.length),this[e]<<24|this[e+1]<<16|this[e+2]<<8|this[e+3]};E.prototype.readFloatLE=function(e,r){return r||J(e,4,this.length),it.read(this,e,true,23,4)};E.prototype.readFloatBE=function(e,r){return r||J(e,4,this.length),it.read(this,e,false,23,4)};E.prototype.readDoubleLE=function(e,r){return r||J(e,8,this.length),it.read(this,e,true,52,8)};E.prototype.readDoubleBE=function(e,r){return r||J(e,8,this.length),it.read(this,e,false,52,8)};function oe(t,e,r,n,i,s){if(!E.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")}E.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;oe(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};E.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;oe(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};E.prototype.writeUInt8=function(e,r,n){return e=+e,r=r|0,n||oe(this,e,r,1,255,0),E.TYPED_ARRAY_SUPPORT||(e=Math.floor(e)),this[r]=e&255,r+1};function rr(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;}E.prototype.writeUInt16LE=function(e,r,n){return e=+e,r=r|0,n||oe(this,e,r,2,65535,0),E.TYPED_ARRAY_SUPPORT?(this[r]=e&255,this[r+1]=e>>>8):rr(this,e,r,true),r+2};E.prototype.writeUInt16BE=function(e,r,n){return e=+e,r=r|0,n||oe(this,e,r,2,65535,0),E.TYPED_ARRAY_SUPPORT?(this[r]=e>>>8,this[r+1]=e&255):rr(this,e,r,false),r+2};function nr(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;}E.prototype.writeUInt32LE=function(e,r,n){return e=+e,r=r|0,n||oe(this,e,r,4,4294967295,0),E.TYPED_ARRAY_SUPPORT?(this[r+3]=e>>>24,this[r+2]=e>>>16,this[r+1]=e>>>8,this[r]=e&255):nr(this,e,r,true),r+4};E.prototype.writeUInt32BE=function(e,r,n){return e=+e,r=r|0,n||oe(this,e,r,4,4294967295,0),E.TYPED_ARRAY_SUPPORT?(this[r]=e>>>24,this[r+1]=e>>>16,this[r+2]=e>>>8,this[r+3]=e&255):nr(this,e,r,false),r+4};E.prototype.writeIntLE=function(e,r,n,i){if(e=+e,r=r|0,!i){var s=Math.pow(2,8*n-1);oe(this,e,r,n,s-1,-s);}var o=0,a=1,l=0;for(this[r]=e&255;++o<n&&(a*=256);)e<0&&l===0&&this[r+o-1]!==0&&(l=1),this[r+o]=(e/a>>0)-l&255;return r+n};E.prototype.writeIntBE=function(e,r,n,i){if(e=+e,r=r|0,!i){var s=Math.pow(2,8*n-1);oe(this,e,r,n,s-1,-s);}var o=n-1,a=1,l=0;for(this[r+o]=e&255;--o>=0&&(a*=256);)e<0&&l===0&&this[r+o+1]!==0&&(l=1),this[r+o]=(e/a>>0)-l&255;return r+n};E.prototype.writeInt8=function(e,r,n){return e=+e,r=r|0,n||oe(this,e,r,1,127,-128),E.TYPED_ARRAY_SUPPORT||(e=Math.floor(e)),e<0&&(e=255+e+1),this[r]=e&255,r+1};E.prototype.writeInt16LE=function(e,r,n){return e=+e,r=r|0,n||oe(this,e,r,2,32767,-32768),E.TYPED_ARRAY_SUPPORT?(this[r]=e&255,this[r+1]=e>>>8):rr(this,e,r,true),r+2};E.prototype.writeInt16BE=function(e,r,n){return e=+e,r=r|0,n||oe(this,e,r,2,32767,-32768),E.TYPED_ARRAY_SUPPORT?(this[r]=e>>>8,this[r+1]=e&255):rr(this,e,r,false),r+2};E.prototype.writeInt32LE=function(e,r,n){return e=+e,r=r|0,n||oe(this,e,r,4,2147483647,-2147483648),E.TYPED_ARRAY_SUPPORT?(this[r]=e&255,this[r+1]=e>>>8,this[r+2]=e>>>16,this[r+3]=e>>>24):nr(this,e,r,true),r+4};E.prototype.writeInt32BE=function(e,r,n){return e=+e,r=r|0,n||oe(this,e,r,4,2147483647,-2147483648),e<0&&(e=4294967295+e+1),E.TYPED_ARRAY_SUPPORT?(this[r]=e>>>24,this[r+1]=e>>>16,this[r+2]=e>>>8,this[r+3]=e&255):nr(this,e,r,false),r+4};function Li(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 Mi(t,e,r,n,i){return i||Li(t,e,r,4),it.write(t,e,r,n,23,4),r+4}E.prototype.writeFloatLE=function(e,r,n){return Mi(this,e,r,true,n)};E.prototype.writeFloatBE=function(e,r,n){return Mi(this,e,r,false,n)};function qi(t,e,r,n,i){return i||Li(t,e,r,8),it.write(t,e,r,n,52,8),r+8}E.prototype.writeDoubleLE=function(e,r,n){return qi(this,e,r,true,n)};E.prototype.writeDoubleBE=function(e,r,n){return qi(this,e,r,false,n)};E.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||!E.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};E.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"&&!E.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=E.isBuffer(e)?e:tr(new E(e,i).toString()),l=a.length;for(o=0;o<n-r;++o)this[o+r]=a[o%l];}return this};var pl=/[^+\/0-9A-Za-z-_]/g;function gl(t){if(t=ml(t).replace(pl,""),t.length<2)return "";for(;t.length%4!==0;)t=t+"=";return t}function ml(t){return t.trim?t.trim():t.replace(/^\s+|\s+$/g,"")}function yl(t){return t<16?"0"+t.toString(16):t.toString(16)}function tr(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 _l(t){for(var e=[],r=0;r<t.length;++r)e.push(t.charCodeAt(r)&255);return e}function bl(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 zr.toByteArray(gl(t))}function ir(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 wl(t){return t!==t}});var Bi={};Qt(Bi,{default:()=>Al});var El,Al,$i=tt(()=>{El={},Al=El;});var on={};Qt(on,{__assign:()=>nn,__asyncDelegator:()=>Fl,__asyncGenerator:()=>Ol,__asyncValues:()=>Ll,__await:()=>vt,__awaiter:()=>Ul,__classPrivateFieldGet:()=>Bl,__classPrivateFieldSet:()=>$l,__createBinding:()=>Cl,__decorate:()=>Tl,__exportStar:()=>kl,__extends:()=>vl,__generator:()=>xl,__importDefault:()=>Vl,__importStar:()=>ql,__makeTemplateObject:()=>Ml,__metadata:()=>Pl,__param:()=>Il,__read:()=>Ki,__rest:()=>Rl,__spread:()=>Dl,__spreadArrays:()=>Nl,__values:()=>sn});function vl(t,e){rn(t,e);function r(){this.constructor=t;}t.prototype=e===null?Object.create(e):(r.prototype=e.prototype,new r);}function Rl(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 Tl(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 Il(t,e){return function(r,n){e(r,n,t);}}function Pl(t,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(t,e)}function Ul(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(u){try{c(n.next(u));}catch(f){o(f);}}function l(u){try{c(n.throw(u));}catch(f){o(f);}}function c(u){u.done?s(u.value):i(u.value).then(a,l);}c((n=n.apply(t,e||[])).next());})}function xl(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(c){return function(u){return l([c,u])}}function l(c){if(n)throw new TypeError("Generator is already executing.");for(;r;)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 r.label++,{value:c[1],done:!1};case 5:r.label++,i=c[1],c=[0];continue;case 7:c=r.ops.pop(),r.trys.pop();continue;default:if(s=r.trys,!(s=s.length>0&&s[s.length-1])&&(c[0]===6||c[0]===2)){r=0;continue}if(c[0]===3&&(!s||c[1]>s[0]&&c[1]<s[3])){r.label=c[1];break}if(c[0]===6&&r.label<s[1]){r.label=s[1],s=c;break}if(s&&r.label<s[2]){r.label=s[2],r.ops.push(c);break}s[2]&&r.ops.pop(),r.trys.pop();continue}c=e.call(t,r);}catch(u){c=[6,u],i=0;}finally{n=s=0;}if(c[0]&5)throw c[1];return {value:c[0]?c[1]:void 0,done:true}}}function Cl(t,e,r,n){n===void 0&&(n=r),t[n]=e[r];}function kl(t,e){for(var r in t)r!=="default"&&!e.hasOwnProperty(r)&&(e[r]=t[r]);}function sn(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 Ki(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 Dl(){for(var t=[],e=0;e<arguments.length;e++)t=t.concat(Ki(arguments[e]));return t}function Nl(){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 vt(t){return this instanceof vt?(this.v=t,this):new vt(t)}function Ol(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(d){n[d]&&(i[d]=function(p){return new Promise(function(g,m){s.push([d,p,g,m])>1||a(d,p);})});}function a(d,p){try{l(n[d](p));}catch(g){f(s[0][3],g);}}function l(d){d.value instanceof vt?Promise.resolve(d.value.v).then(c,u):f(s[0][2],d);}function c(d){a("next",d);}function u(d){a("throw",d);}function f(d,p){d(p),s.shift(),s.length&&a(s[0][0],s[0][1]);}}function Fl(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:vt(t[i](o)),done:i==="return"}:s?s(o):o}:s;}}function Ll(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 sn=="function"?sn(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,l){o=t[s](o),i(a,l,o.done,o.value);})};}function i(s,o,a,l){Promise.resolve(l).then(function(c){s({value:c,done:a});},o);}}function Ml(t,e){return Object.defineProperty?Object.defineProperty(t,"raw",{value:e}):t.raw=e,t}function ql(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 Vl(t){return t&&t.__esModule?t:{default:t}}function Bl(t,e){if(!e.has(t))throw new TypeError("attempted to get private field on non-instance");return e.get(t)}function $l(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 rn,nn,an=tt(()=>{rn=function(t,e){return rn=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]);},rn(t,e)};nn=function(){return nn=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},nn.apply(this,arguments)};});var cn=se(pe=>{Object.defineProperty(pe,"__esModule",{value:true});pe.MAX_HASHABLE_LENGTH=pe.INIT=pe.KEY=pe.DIGEST_LENGTH=pe.BLOCK_SIZE=void 0;pe.BLOCK_SIZE=64;pe.DIGEST_LENGTH=32;pe.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]);pe.INIT=[1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225];pe.MAX_HASHABLE_LENGTH=Math.pow(2,53)-1;});var ji=se(or=>{Object.defineProperty(or,"__esModule",{value:true});or.RawSha256=void 0;var ge=cn(),Kl=(function(){function t(){this.state=Int32Array.from(ge.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>ge.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===ge.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%ge.BLOCK_SIZE>=ge.BLOCK_SIZE-8){for(var i=this.bufferLength;i<ge.BLOCK_SIZE;i++)r.setUint8(i,0);this.hashBuffer(),this.bufferLength=0;}for(var i=this.bufferLength;i<ge.BLOCK_SIZE-8;i++)r.setUint8(i,0);r.setUint32(ge.BLOCK_SIZE-8,Math.floor(e/4294967296),true),r.setUint32(ge.BLOCK_SIZE-4,e),this.hashBuffer(),this.finished=true;}for(var s=new Uint8Array(ge.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],l=n[4],c=n[5],u=n[6],f=n[7],d=0;d<ge.BLOCK_SIZE;d++){if(d<16)this.temp[d]=(r[d*4]&255)<<24|(r[d*4+1]&255)<<16|(r[d*4+2]&255)<<8|r[d*4+3]&255;else {var p=this.temp[d-2],g=(p>>>17|p<<15)^(p>>>19|p<<13)^p>>>10;p=this.temp[d-15];var m=(p>>>7|p<<25)^(p>>>18|p<<14)^p>>>3;this.temp[d]=(g+this.temp[d-7]|0)+(m+this.temp[d-16]|0);}var y=(((l>>>6|l<<26)^(l>>>11|l<<21)^(l>>>25|l<<7))+(l&c^~l&u)|0)+(f+(ge.KEY[d]+this.temp[d]|0)|0)|0,w=((i>>>2|i<<30)^(i>>>13|i<<19)^(i>>>22|i<<10))+(i&s^i&o^s&o)|0;f=u,u=c,c=l,l=a+y|0,a=o,o=s,s=i,i=y+w|0;}n[0]+=i,n[1]+=s,n[2]+=o,n[3]+=a,n[4]+=l,n[5]+=c,n[6]+=u,n[7]+=f;},t})();or.RawSha256=Kl;});var Hi,Wi,Gi=tt(()=>{Hi=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)},Wi=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 Ji(t){return new TextEncoder().encode(t)}function Yi(t){return new TextDecoder("utf-8").decode(t)}var zi=tt(()=>{});var Qi={};Qt(Qi,{fromUtf8:()=>jl,toUtf8:()=>Hl});var jl,Hl,Xi=tt(()=>{Gi();zi();jl=t=>typeof TextEncoder=="function"?Ji(t):Hi(t),Hl=t=>typeof TextDecoder=="function"?Yi(t):Wi(t);});var Zi=se(ar=>{Object.defineProperty(ar,"__esModule",{value:true});ar.convertToBuffer=void 0;var Wl=(Xi(),nt(Qi)),Gl=typeof Buffer<"u"&&Buffer.from?function(t){return Buffer.from(t,"utf8")}:Wl.fromUtf8;function Jl(t){return t instanceof Uint8Array?t:typeof t=="string"?Gl(t):ArrayBuffer.isView(t)?new Uint8Array(t.buffer,t.byteOffset,t.byteLength/Uint8Array.BYTES_PER_ELEMENT):new Uint8Array(t)}ar.convertToBuffer=Jl;});var es=se(cr=>{Object.defineProperty(cr,"__esModule",{value:true});cr.isEmptyData=void 0;function Yl(t){return typeof t=="string"?t.length===0:t.byteLength===0}cr.isEmptyData=Yl;});var ts=se(lr=>{Object.defineProperty(lr,"__esModule",{value:true});lr.numToUint8=void 0;function zl(t){return new Uint8Array([(t&4278190080)>>24,(t&16711680)>>16,(t&65280)>>8,t&255])}lr.numToUint8=zl;});var rs=se(ur=>{Object.defineProperty(ur,"__esModule",{value:true});ur.uint32ArrayFrom=void 0;function Ql(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)}ur.uint32ArrayFrom=Ql;});var ns=se(Ie=>{Object.defineProperty(Ie,"__esModule",{value:true});Ie.uint32ArrayFrom=Ie.numToUint8=Ie.isEmptyData=Ie.convertToBuffer=void 0;var Xl=Zi();Object.defineProperty(Ie,"convertToBuffer",{enumerable:true,get:function(){return Xl.convertToBuffer}});var Zl=es();Object.defineProperty(Ie,"isEmptyData",{enumerable:true,get:function(){return Zl.isEmptyData}});var eu=ts();Object.defineProperty(Ie,"numToUint8",{enumerable:true,get:function(){return eu.numToUint8}});var tu=rs();Object.defineProperty(Ie,"uint32ArrayFrom",{enumerable:true,get:function(){return tu.uint32ArrayFrom}});});var ss=se(fr=>{Object.defineProperty(fr,"__esModule",{value:true});fr.Sha256=void 0;var is=(an(),nt(on)),dr=cn(),ln=ji(),un=ns(),ru=(function(){function t(e){if(this.hash=new ln.RawSha256,e){this.outer=new ln.RawSha256;var r=nu(e),n=new Uint8Array(dr.BLOCK_SIZE);n.set(r);for(var i=0;i<dr.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, un.isEmptyData)(e)||this.error))try{this.hash.update((0,un.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, is.__awaiter)(this,void 0,void 0,function(){return (0, is.__generator)(this,function(e){return [2,this.digestSync()]})})},t})();fr.Sha256=ru;function nu(t){var e=(0, un.convertToBuffer)(t);if(e.byteLength>dr.BLOCK_SIZE){var r=new ln.RawSha256;r.update(e),e=r.digest();}var n=new Uint8Array(dr.BLOCK_SIZE);return n.set(e),n}});var fn=se(dn=>{Object.defineProperty(dn,"__esModule",{value:true});var iu=(an(),nt(on));(0, iu.__exportStar)(ss(),dn);});var En={};Qt(En,{default:()=>Xu});function Xu(t,e){return e=e||{},new Promise(function(r,n){var i=new XMLHttpRequest,s=[],o=[],a={},l=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:l,headers:{keys:function(){return s},entries:function(){return o},get:function(u){return a[u.toLowerCase()]},has:function(u){return u.toLowerCase()in a}}}};for(var c in i.open(e.method||"get",t,true),i.onload=function(){i.getAllResponseHeaders().replace(/^(.*?):[^\S\n]*([\s\S]*?)$/gm,function(u,f,d){s.push(f=f.toLowerCase()),o.push([f,d]),a[f]=a[f]?a[f]+","+d:d;}),r(l());},i.onerror=n,i.withCredentials=e.credentials=="include",e.headers)i.setRequestHeader(c,e.headers[c]);i.send(e.body||null);})}var An=tt(()=>{});var ps=se((Lh,hs)=>{hs.exports=self.fetch||(self.fetch=(An(),nt(En)).default||(An(),nt(En)));});function Ei(t){let r=(typeof globalThis<"u"?globalThis:void 0)?.process;if(r&&typeof r.getBuiltinModule=="function")try{return r.getBuiltinModule(t)}catch{}try{if(typeof Ve=="function")return Ve(t)}catch{}return null}var Kr,jr,Hr=()=>Kr!==void 0?Kr:Kr=Ei("fs"),Wr=()=>jr!==void 0?jr:jr=Ei("path"),De=typeof globalThis<"u"?globalThis:void 0,Xt=De?.window;function Bc(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(Xt)Xt.global=Xt,Xt.global._runningInNodeJS=false;else if(De&&(De.global=De,typeof De.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=Bc(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});});}}De.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);});}}De.XMLHttpRequest=e,De.window={_runningInNodeJS:true,alert:r=>console.error("[Alert]",r),sessionStorage:{getItem:r=>null,setItem:(r,n)=>{},removeItem:r=>{}},localStorage:{getItem:r=>{let n=Hr(),i=Wr();if(!n||!i)return null;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=Hr(),s=Wr();if(!(!i||!s))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=Hr(),i=Wr();if(!(!n||!i))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/${De?.process?.versions?.node||"unknown"}`,mediaDevices:{getUserMedia:async r=>{throw new Error("getUserMedia is not supported in Node.js environment.")}}},addEventListener:()=>{},removeEventListener:()=>{}};}var Gr=(function(){function t(r){var n=r||{},i=n.ValidationData,s=n.Username,o=n.Password,a=n.AuthParameters,l=n.ClientMetadata;this.validationData=i||{},this.authParameters=a||{},this.clientMetadata=l||{},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 Oe=rt(sr());var he;typeof window<"u"&&window.crypto&&(he=window.crypto);!he&&typeof window<"u"&&window.msCrypto&&(he=window.msCrypto);!he&&typeof globalThis<"u"&&globalThis.crypto&&(he=globalThis.crypto);if(!he&&typeof Ve=="function")try{he=($i(),nt(Bi));}catch{}function en(){if(he){if(typeof he.getRandomValues=="function")try{return he.getRandomValues(new Uint32Array(1))[0]}catch{}if(typeof he.randomBytes=="function")try{return he.randomBytes(4).readInt32LE()}catch{}}throw new Error("Native crypto module could not be used to get secure random number.")}function Sl(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 tn=(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(en());return new t(i,n)},e.toString=function(){return Sl(this)},t})();var pr=rt(fn());var W=N;function N(t,e){t!=null&&this.fromString(t,e);}function re(){return new N(null)}var Be,su=0xdeadbeefcafe,os=(su&16777215)==15715070;function ou(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 au(t,e,r,n,i,s){for(var o=e&32767,a=e>>15;--s>=0;){var l=this[t]&32767,c=this[t++]>>15,u=a*l+c*o;l=o*l+((u&32767)<<15)+r[n]+(i&1073741823),i=(l>>>30)+(u>>>15)+a*c+(i>>>30),r[n++]=l&1073741823;}return i}function cu(t,e,r,n,i,s){for(var o=e&16383,a=e>>14;--s>=0;){var l=this[t]&16383,c=this[t++]>>14,u=a*l+c*o;l=o*l+((u&16383)<<14)+r[n]+i,i=(l>>28)+(u>>14)+a*c,r[n++]=l&268435455;}return i}var as=typeof navigator<"u";as&&os&&navigator.appName=="Microsoft Internet Explorer"?(N.prototype.am=au,Be=30):as&&os&&navigator.appName!="Netscape"?(N.prototype.am=ou,Be=26):(N.prototype.am=cu,Be=28);N.prototype.DB=Be;N.prototype.DM=(1<<Be)-1;N.prototype.DV=1<<Be;var hn=52;N.prototype.FV=Math.pow(2,hn);N.prototype.F1=hn-Be;N.prototype.F2=2*Be-hn;var lu="0123456789abcdefghijklmnopqrstuvwxyz",hr=new Array,ot,me;ot=48;for(me=0;me<=9;++me)hr[ot++]=me;ot=97;for(me=10;me<36;++me)hr[ot++]=me;ot=65;for(me=10;me<36;++me)hr[ot++]=me;function cs(t){return lu.charAt(t)}function uu(t,e){var r=hr[t.charCodeAt(e)];return r??-1}function du(t){for(var e=this.t-1;e>=0;--e)t[e]=this[e];t.t=this.t,t.s=this.s;}function fu(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 pn(t){var e=re();return e.fromInt(t),e}function hu(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=uu(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&&N.ZERO.subTo(this,this);}function pu(){for(var t=this.s&this.DM;this.t>0&&this[this.t-1]==t;)--this.t;}function gu(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=cs(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+=cs(n));return i?s:"0"}function mu(){var t=re();return N.ZERO.subTo(this,t),t}function yu(){return this.s<0?this.negate():this}function _u(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 gn(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 bu(){return this.t<=0?0:this.DB*(this.t-1)+gn(this[this.t-1]^this.s&this.DM)}function wu(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 Eu(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 Au(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 Su(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 vu(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 Ru(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&&N.ZERO.subTo(e,e);}function Tu(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 Iu(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=re());var s=re(),o=this.s,a=t.s,l=this.DB-gn(n[n.t-1]);l>0?(n.lShiftTo(l,s),i.lShiftTo(l,r)):(n.copyTo(s),i.copyTo(r));var c=s.t,u=s[c-1];if(u!=0){var f=u*(1<<this.F1)+(c>1?s[c-2]>>this.F2:0),d=this.FV/f,p=(1<<this.F1)/f,g=1<<this.F2,m=r.t,y=m-c,w=e??re();for(s.dlShiftTo(y,w),r.compareTo(w)>=0&&(r[r.t++]=1,r.subTo(w,r)),N.ONE.dlShiftTo(c,w),w.subTo(s,s);s.t<c;)s[s.t++]=0;for(;--y>=0;){var _=r[--m]==u?this.DM:Math.floor(r[m]*d+(r[m-1]+g)*p);if((r[m]+=s.am(0,_,r,y,0,c))<_)for(s.dlShiftTo(y,w),r.subTo(w,r);r[m]<--_;)r.subTo(w,r);}e!=null&&(r.drShiftTo(c,e),o!=a&&N.ZERO.subTo(e,e)),r.t=c,r.clamp(),l>0&&r.rShiftTo(l,r),o<0&&N.ZERO.subTo(r,r);}}}function Pu(t){var e=re();return this.abs().divRemTo(t,null,e),this.s<0&&e.compareTo(N.ZERO)>0&&t.subTo(e,e),e}function Uu(){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 xu(t){return this.compareTo(t)==0}function Cu(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 ku(t){var e=re();return this.addTo(t,e),e}function Du(t){var e=re();return this.subTo(t,e),e}function Nu(t){var e=re();return this.multiplyTo(t,e),e}function Ou(t){var e=re();return this.divRemTo(t,e,null),e}function at(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 Fu(t){var e=re();return t.abs().dlShiftTo(this.m.t,e),e.divRemTo(this.m,null,e),t.s<0&&e.compareTo(N.ZERO)>0&&this.m.subTo(e,e),e}function Lu(t){var e=re();return t.copyTo(e),this.reduce(e),e}function Mu(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 qu(t,e){t.squareTo(e),this.reduce(e);}function Vu(t,e,r){t.multiplyTo(e,r),this.reduce(r);}at.prototype.convert=Fu;at.prototype.revert=Lu;at.prototype.reduce=Mu;at.prototype.mulTo=Vu;at.prototype.sqrTo=qu;function Bu(t,e,r){var n=t.bitLength(),i,s=pn(1),o=new at(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,l=3,c=i-1,u=(1<<i)-1;if(a[1]=o.convert(this),i>1){var f=re();for(o.sqrTo(a[1],f);l<=u;)a[l]=re(),o.mulTo(f,a[l-2],a[l]),l+=2;}var d=t.t-1,p,g=true,m=re(),y;for(n=gn(t[d])-1;d>=0;){for(n>=c?p=t[d]>>n-c&u:(p=(t[d]&(1<<n+1)-1)<<c-n,d>0&&(p|=t[d-1]>>this.DB+n-c)),l=i;(p&1)==0;)p>>=1,--l;if((n-=l)<0&&(n+=this.DB,--d),g)a[p].copyTo(s),g=false;else {for(;l>1;)o.sqrTo(s,m),o.sqrTo(m,s),l-=2;l>0?o.sqrTo(s,m):(y=s,s=m,m=y),o.mulTo(m,a[p],s);}for(;d>=0&&(t[d]&1<<n)==0;)o.sqrTo(s,m),y=s,s=m,m=y,--n<0&&(n=this.DB-1,--d);}var w=o.revert(s);return r(null,w),w}N.prototype.copyTo=du;N.prototype.fromInt=fu;N.prototype.fromString=hu;N.prototype.clamp=pu;N.prototype.dlShiftTo=wu;N.prototype.drShiftTo=Eu;N.prototype.lShiftTo=Au;N.prototype.rShiftTo=Su;N.prototype.subTo=vu;N.prototype.multiplyTo=Ru;N.prototype.squareTo=Tu;N.prototype.divRemTo=Iu;N.prototype.invDigit=Uu;N.prototype.addTo=Cu;N.prototype.toString=gu;N.prototype.negate=mu;N.prototype.abs=yu;N.prototype.compareTo=_u;N.prototype.bitLength=bu;N.prototype.mod=Pu;N.prototype.equals=xu;N.prototype.add=ku;N.prototype.subtract=Du;N.prototype.multiply=Nu;N.prototype.divide=Ou;N.prototype.modPow=Bu;N.ZERO=pn(0);N.ONE=pn(1);function mn(t){return Oe.Buffer.from(new tn().random(t).toString(),"hex")}var $u=/^[89a-f]/i,Ku="FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E088A67CC74020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7EDEE386BFB5A899FA5AE9F24117C4B1FE649286651ECE45B3DC2007CB8A163BF0598DA48361C55D39A69163FA8FD24CF5F83655D23DCA3AD961C62F356208552BB9ED529077096966D670C354E4ABC9804F1746C08CA18217C32905E462E36CE3BE39E772C180E86039B2783A2EC07A28FB5C55DF06F4C52C9DE2BCBF6955817183995497CEA956AE515D2261898FA051015728E5A8AAAC42DAD33170D04507A33A85521ABDF1CBA64ECFB850458DBEF0A8AEA71575D060C7DB3970F85A6E1E4C7ABF5AE8CDB0933D71E8C94E04A25619DCEE3D2261AD2EE6BF12FFA06D98A0864D87602733EC86A64521F2B18177B200CBBE117577A615D6C770988C0BAD946E208E24FA074E5AB3143DB5BFCE0FD108E4B82D120A93AD2CAFFFFFFFFFFFFFFFF",ju="userAttributes.",$e=(function(){function t(r){this.N=new W(Ku,16),this.g=new W("2",16),this.k=new W(this.hexHash(""+this.padHex(this.N)+this.padHex(this.g)),16),this.smallAValue=this.generateRandomSmallA(),this.getLargeAValue(function(){}),this.infoBits=Oe.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=mn(128).toString("hex"),i=new W(n,16);return i},e.generateRandomString=function(){return mn(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,l=this.hash(a),c=mn(16).toString("hex");this.SaltToHashDevices=this.padHex(new W(c,16)),this.g.modPow(new W(this.hexHash(this.SaltToHashDevices+l),16),this.N,function(u,f){u&&s(u,null),o.verifierDevices=o.padHex(f),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(W.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 W(this.UHexHash,16);return s},e.hash=function(n){var i=new pr.Sha256;i.update(n);var s=i.digestSync(),o=Oe.Buffer.from(s).toString("hex");return new Array(64-o.length).join("0")+o},e.hexHash=function(n){return this.hash(Oe.Buffer.from(n,"hex"))},e.computehkdf=function(n,i){var s=Oe.Buffer.concat([this.infoBits,Oe.Buffer.from("","utf8")]),o=new pr.Sha256(i);o.update(n);var a=o.digestSync(),l=new pr.Sha256(a);l.update(s);var c=l.digestSync(),u=c,f=u.slice(0,16);return f},e.getPasswordAuthenticationKey=function(n,i,s,o,a){var l=this;if(s.mod(this.N).equals(W.ZERO))throw new Error("B cannot be zero.");if(this.UValue=this.calculateU(this.largeAValue,s),this.UValue.equals(W.ZERO))throw new Error("U cannot be zero.");var c=""+this.poolName+n+":"+i,u=this.hash(c),f=new W(this.hexHash(this.padHex(o)+u),16);this.calculateS(f,s,function(d,p){d&&a(d,null);var g=l.computehkdf(Oe.Buffer.from(l.padHex(p),"hex"),Oe.Buffer.from(l.padHex(l.UValue),"hex"));a(null,g);});},e.calculateS=function(n,i,s){var o=this;this.g.modPow(n,this.N,function(a,l){a&&s(a,null);var c=i.subtract(o.k.multiply(l));c.modPow(o.smallAValue.add(o.UValue.multiply(n)),o.N,function(u,f){u&&s(u,null),s(null,f.mod(o.N));});});},e.getNewPasswordRequiredChallengeUserAttributePrefix=function(){return ju},e.padHex=function(n){if(!(n instanceof W))throw new Error("Not a BigInteger");var i=n.compareTo(W.ZERO)<0,s=n.abs().toString(16);if(s=s.length%2!==0?"0"+s:s,s=$u.test(s)?"00"+s:s,i){var o=s.split("").map(function(l){var c=~parseInt(l,16)&15;return "0123456789ABCDEF".charAt(c)}).join(""),a=new W(o,16).add(W.ONE);s=a.toString(16),s.toUpperCase().startsWith("FF8")&&(s=s.substring(2));}return s},t})();var ls=rt(sr());var gr=(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(ls.Buffer.from(n,"base64").toString("utf8"))}catch{return {}}},t})();function Hu(t,e){t.prototype=Object.create(e.prototype),t.prototype.constructor=t,yn(t,e);}function yn(t,e){return yn=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(r,n){return r.__proto__=n,r},yn(t,e)}var ct=(function(t){function e(r){var n=r===void 0?{}:r,i=n.AccessToken;return t.call(this,i||"")||this}return Hu(e,t),e})(gr);function Wu(t,e){t.prototype=Object.create(e.prototype),t.prototype.constructor=t,_n(t,e);}function _n(t,e){return _n=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(r,n){return r.__proto__=n,r},_n(t,e)}var lt=(function(t){function e(r){var n=r===void 0?{}:r,i=n.IdToken;return t.call(this,i||"")||this}return Wu(e,t),e})(gr);var ut=(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 Y=rt(sr()),wn=rt(fn());var us="5.0.4";var Gu="aws-amplify/"+us,bn={userAgent:Gu,isReactNative:typeof navigator<"u"&&navigator.product==="ReactNative"},ds=function(){return bn.userAgent};var dt=(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 Ju=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],Yu=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],mr=(function(){function t(){}var e=t.prototype;return e.getNowString=function(){var n=new Date,i=Yu[n.getUTCDay()],s=Ju[n.getUTCMonth()],o=n.getUTCDate(),a=n.getUTCHours();a<10&&(a="0"+a);var l=n.getUTCMinutes();l<10&&(l="0"+l);var c=n.getUTCSeconds();c<10&&(c="0"+c);var u=n.getUTCFullYear(),f=i+" "+s+" "+o+" "+a+":"+l+":"+c+" UTC "+u;return f},t})();var Pe=(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 Je={},zu=(function(){function t(){}return t.setItem=function(r,n){return Je[r]=n,Je[r]},t.getItem=function(r){return Object.prototype.hasOwnProperty.call(Je,r)?Je[r]:void 0},t.removeItem=function(r){return delete Je[r]},t.clear=function(){return Je={},Je},t})(),yr=(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=zu;}}var e=t.prototype;return e.getStorage=function(){return this.storageWindow},t})();var Qu=typeof navigator<"u",fs=Qu?bn.isReactNative?"react-native":navigator.userAgent:"nodejs",Fe=(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 yr().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(),l={AuthFlow:"CUSTOM_AUTH",ClientId:this.pool.getClientId(),AuthParameters:o,ClientMetadata:a};this.getUserContextData()&&(l.UserContextData=this.getUserContextData()),this.client.request("InitiateAuth",l,function(c,u){if(c)return i.onFailure(c);var f=u.ChallengeName,d=u.ChallengeParameters;return f==="CUSTOM_CHALLENGE"?(s.Session=u.Session,i.customChallenge(d)):(s.signInUserSession=s.getCognitoUserSession(u.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 $e(this.pool.getUserPoolName()),a=new mr,l,c,u={};this.deviceKey!=null&&(u.DEVICE_KEY=this.deviceKey),u.USERNAME=this.username,o.getLargeAValue(function(f,d){f&&i.onFailure(f),u.SRP_A=d.toString(16),s.authenticationFlowType==="CUSTOM_AUTH"&&(u.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:u,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 w=y.ChallengeParameters;s.username=w.USER_ID_FOR_SRP,s.userDataKey=s.keyPrefix+"."+s.username+".userData",l=new W(w.SRP_B,16),c=new W(w.SALT,16),s.getCachedDeviceKeyAndPassword(),o.getPasswordAuthenticationKey(s.username,n.getPassword(),l,c,function(_,A){_&&i.onFailure(_);var U=a.getNowString(),S=Y.Buffer.concat([Y.Buffer.from(s.pool.getUserPoolName(),"utf8"),Y.Buffer.from(s.username,"utf8"),Y.Buffer.from(w.SECRET_BLOCK,"base64"),Y.Buffer.from(U,"utf8")]),F=new wn.Sha256(A);F.update(S);var O=F.digestSync(),k=Y.Buffer.from(O).toString("base64"),x={};x.USERNAME=s.username,x.PASSWORD_CLAIM_SECRET_BLOCK=w.SECRET_BLOCK,x.TIMESTAMP=U,x.PASSWORD_CLAIM_SIGNATURE=k,s.deviceKey!=null&&(x.DEVICE_KEY=s.deviceKey);var C=function(ee,ie){return s.client.request("RespondToAuthChallenge",ee,function(M,Q){return M&&M.code==="ResourceNotFoundException"&&M.message.toLowerCase().indexOf("device")!==-1?(x.DEVICE_KEY=null,s.deviceKey=null,s.randomPassword=null,s.deviceGroupKey=null,s.clearCachedDeviceKeyAndPassword(),C(ee,ie)):ie(M,Q)})},L={ChallengeName:"PASSWORD_VERIFIER",ClientId:s.pool.getClientId(),ChallengeResponses:x,Session:y.Session,ClientMetadata:p};s.getUserContextData()&&(L.UserContextData=s.getUserContextData()),C(L,function(B,ee){return B?i.onFailure(B):s.authenticateUserInternal(ee,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 $e(this.pool.getUserPoolName());this.getCachedDeviceKeyAndPassword(),this.deviceKey!=null&&(o.DEVICE_KEY=this.deviceKey);var l=Object.keys(n.getValidationData()).length!==0?n.getValidationData():n.getClientMetadata(),c={AuthFlow:"USER_PASSWORD_AUTH",ClientId:this.pool.getClientId(),AuthParameters:o,ClientMetadata:l};this.getUserContextData(this.username)&&(c.UserContextData=this.getUserContextData(this.username)),this.client.request("InitiateAuth",c,function(u,f){return u?i.onFailure(u):s.authenticateUserInternal(f,a,i)});},e.authenticateUserInternal=function(n,i,s){var o=this,a=n.ChallengeName,l=n.ChallengeParameters;if(a==="SMS_MFA")return this.Session=n.Session,s.mfaRequired(a,l);if(a==="SELECT_MFA_TYPE")return this.Session=n.Session,s.selectMFAType(a,l);if(a==="MFA_SETUP")return this.Session=n.Session,s.mfaSetup(a,l);if(a==="SOFTWARE_TOKEN_MFA")return this.Session=n.Session,s.totpRequired(a,l);if(a==="CUSTOM_CHALLENGE")return this.Session=n.Session,s.customChallenge(l);if(a==="NEW_PASSWORD_REQUIRED"){this.Session=n.Session;var c=null,u=null,f=[],d=i.getNewPasswordRequiredChallengeUserAttributePrefix();if(l&&(c=JSON.parse(n.ChallengeParameters.userAttributes),u=JSON.parse(n.ChallengeParameters.requiredAttributes)),u)for(var p=0;p<u.length;p++)f[p]=u[p].substr(d.length);return s.newPasswordRequired(c,f)}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:Y.Buffer.from(i.getSaltDevices(),"hex").toString("base64"),PasswordVerifier:Y.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:fs},function(w,_){return w?s.onFailure(w):(o.deviceKey=n.AuthenticationResult.NewDeviceMetadata.DeviceKey,o.cacheDeviceKeyAndPassword(),_.UserConfirmationNecessary===true?s.onSuccess(o.signInUserSession,_.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 l=new $e(this.pool.getUserPoolName()),c=l.getNewPasswordRequiredChallengeUserAttributePrefix(),u={};i&&Object.keys(i).forEach(function(d){u[c+d]=i[d];}),u.NEW_PASSWORD=n,u.USERNAME=this.username;var f={ChallengeName:"NEW_PASSWORD_REQUIRED",ClientId:this.pool.getClientId(),ChallengeResponses:u,Session:this.Session,ClientMetadata:o};this.getUserContextData()&&(f.UserContextData=this.getUserContextData()),this.client.request("RespondToAuthChallenge",f,function(d,p){return d?s.onFailure(d):a.authenticateUserInternal(p,l,s)});},e.getDeviceResponse=function(n,i){var s=this,o=new $e(this.deviceGroupKey),a=new mr,l={};l.USERNAME=this.username,l.DEVICE_KEY=this.deviceKey,o.getLargeAValue(function(c,u){c&&n.onFailure(c),l.SRP_A=u.toString(16);var f={ChallengeName:"DEVICE_SRP_AUTH",ClientId:s.pool.getClientId(),ChallengeResponses:l,ClientMetadata:i,Session:s.Session};s.getUserContextData()&&(f.UserContextData=s.getUserContextData()),s.client.request("RespondToAuthChallenge",f,function(d,p){if(d)return n.onFailure(d);var g=p.ChallengeParameters,m=new W(g.SRP_B,16),y=new W(g.SALT,16);o.getPasswordAuthenticationKey(s.deviceKey,s.randomPassword,m,y,function(w,_){if(w)return n.onFailure(w);var A=a.getNowString(),U=Y.Buffer.concat([Y.Buffer.from(s.deviceGroupKey,"utf8"),Y.Buffer.from(s.deviceKey,"utf8"),Y.Buffer.from(g.SECRET_BLOCK,"base64"),Y.Buffer.from(A,"utf8")]),S=new wn.Sha256(_);S.update(U);var F=S.digestSync(),O=Y.Buffer.from(F).toString("base64"),k={};k.USERNAME=s.username,k.PASSWORD_CLAIM_SECRET_BLOCK=g.SECRET_BLOCK,k.TIMESTAMP=A,k.PASSWORD_CLAIM_SIGNATURE=O,k.DEVICE_KEY=s.deviceKey;var x={ChallengeName:"DEVICE_PASSWORD_VERIFIER",ClientId:s.pool.getClientId(),ChallengeResponses:k,Session:p.Session};s.getUserContextData()&&(x.UserContextData=s.getUserContextData()),s.client.request("RespondToAuthChallenge",x,function(C,L){return C?n.onFailure(C):(s.signInUserSession=s.getCognitoUserSession(L.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(l){return l?s(l,null):s(null,"SUCCESS")});},e.sendCustomChallengeAnswer=function(n,i,s){var o=this,a={};a.USERNAME=this.username,a.ANSWER=n;var l=new $e(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(u,f){return u?i.onFailure(u):o.authenticateUserInternal(f,l,i)});},e.sendMFACode=function(n,i,s,o){var a=this,l={};l.USERNAME=this.username,l.SMS_MFA_CODE=n;var c=s||"SMS_MFA";c==="SOFTWARE_TOKEN_MFA"&&(l.SOFTWARE_TOKEN_MFA_CODE=n),this.deviceKey!=null&&(l.DEVICE_KEY=this.deviceKey);var u={ChallengeName:c,ChallengeResponses:l,ClientId:this.pool.getClientId(),Session:this.Session,ClientMetadata:o};this.getUserContextData()&&(u.UserContextData=this.getUserContextData()),this.client.request("RespondToAuthChallenge",u,function(f,d){if(f)return i.onFailure(f);var p=d.ChallengeName;if(p==="DEVICE_SRP_AUTH"){a.getDeviceResponse(i);return}if(a.signInUserSession=a.getCognitoUserSession(d.AuthenticationResult),a.cacheTokens(),d.AuthenticationResult.NewDeviceMetadata==null)return i.onSuccess(a.signInUserSession);var g=new $e(a.pool.getUserPoolName());g.generateHashDevice(d.AuthenticationResult.NewDeviceMetadata.DeviceGroupKey,d.AuthenticationResult.NewDeviceMetadata.DeviceKey,function(m){if(m)return i.onFailure(m);var y={Salt:Y.Buffer.from(g.getSaltDevices(),"hex").toString("base64"),PasswordVerifier:Y.Buffer.from(g.getVerifierDevices(),"hex").toString("base64")};a.verifierDevices=y.PasswordVerifier,a.deviceGroupKey=d.AuthenticationResult.NewDeviceMetadata.DeviceGroupKey,a.randomPassword=g.getRandomPassword(),a.client.request("ConfirmDevice",{DeviceKey:d.AuthenticationResult.NewDeviceMetadata.DeviceKey,AccessToken:a.signInUserSession.getAccessToken().getJwtToken(),DeviceSecretVerifierConfig:y,DeviceName:fs},function(w,_){return w?i.onFailure(w):(a.deviceKey=d.AuthenticationResult.NewDeviceMetadata.DeviceKey,a.cacheDeviceKeyAndPassword(),_.UserConfirmationNecessary===true?i.onSuccess(a.signInUserSession,_.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,l){return a?i(a,null):o.getUserData(function(){return i(null,"SUCCESS",l)},{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 l={Name:s.UserAttributes[a].Name,Value:s.UserAttributes[a].Value},c=new Pe(l);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",l=s+".refreshToken",c=s+".clockDrift";if(this.storage.getItem(o)){var u=new lt({IdToken:this.storage.getItem(o)}),f=new ct({AccessToken:this.storage.getItem(a)}),d=new ut({RefreshToken:this.storage.getItem(l)}),p=parseInt(this.storage.getItem(c),0)||0,g={IdToken:u,AccessToken:f,RefreshToken:d,ClockDrift:p},m=new dt(g);if(m.isValid())return this.signInUserSession=m,n(null,this.signInUserSession);if(!d.getToken())return n(new Error("Cannot retrieve a new session. Please authenticate."),null);this.refreshSession(d,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,l={};l.REFRESH_TOKEN=n.getToken();var c="CognitoIdentityServiceProvider."+this.pool.getClientId(),u=c+".LastAuthUser";if(this.storage.getItem(u)){this.username=this.storage.getItem(u);var f=c+"."+this.username+".deviceKey";this.deviceKey=this.storage.getItem(f),l.DEVICE_KEY=this.deviceKey;}var d={ClientId:this.pool.getClientId(),AuthFlow:"REFRESH_TOKEN_AUTH",AuthParameters:l,ClientMetadata:s};this.getUserContextData()&&(d.UserContextData=this.getUserContextData()),this.client.requestWithRetry("InitiateAuth",d,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",l=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(l,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",l=n+"."+this.username+".clockDrift";this.storage.removeItem(i),this.storage.removeItem(s),this.storage.removeItem(o),this.storage.removeItem(a),this.storage.removeItem(l);},e.getCognitoUserSession=function(n){var i=new lt(n),s=new ct(n),o=new ut(n),a={IdToken:i,AccessToken:s,RefreshToken:o};return new dt(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(l){return l?s.onFailure(l):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,l){return a?s.onFailure(a):s.onSuccess(l)});},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(),l=this.signInUserSession.getAccessToken();if(this.isSessionRevocable(l)&&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(l,c){if(l)return i.onFailure(l);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,l){return a?s.onFailure(a):s.onSuccess(l)}):this.client.request("VerifySoftwareToken",{Session:this.Session,UserCode:n,FriendlyDeviceName:i},function(a,l){if(a)return s.onFailure(a);o.Session=l.Session;var c={};c.USERNAME=o.username;var u={ChallengeName:"MFA_SETUP",ClientId:o.pool.getClientId(),ChallengeResponses:c,Session:o.Session};o.getUserContextData()&&(u.UserContextData=o.getUserContextData()),o.client.request("RespondToAuthChallenge",u,function(f,d){return f?s.onFailure(f):(o.signInUserSession=o.getCognitoUserSession(d.AuthenticationResult),o.cacheTokens(),s.onSuccess(o.signInUserSession))});});},t})();rt(ps());function ft(){}ft.prototype.userAgent=ds();var gs=function(e){var r=ft.category?" "+ft.category:"",n=ft.framework?" framework/"+ft.framework:"",i=""+ft.prototype.userAgent+r+n;return i};function Zu(t,e){t.prototype=Object.create(e.prototype),t.prototype.constructor=t,Rt(t,e);}function Sn(t){var e=typeof Map=="function"?new Map:void 0;return Sn=function(n){if(n===null||!td(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 ed(n,arguments,vn(this).constructor)}return i.prototype=Object.create(n.prototype,{constructor:{value:i,enumerable:false,writable:true,configurable:true}}),Rt(i,n)},Sn(t)}function ed(t,e,r){if(ms())return Reflect.construct.apply(null,arguments);var n=[null];n.push.apply(n,e);var i=new(t.bind.apply(t,n));return r&&Rt(i,r.prototype),i}function ms(){try{var t=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}));}catch{}return (ms=function(){return !!t})()}function td(t){try{return Function.toString.call(t).indexOf("[native code]")!==-1}catch{return typeof t=="function"}}function Rt(t,e){return Rt=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(r,n){return r.__proto__=n,r},Rt(t,e)}function vn(t){return vn=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(e){return e.__proto__||Object.getPrototypeOf(e)},vn(t)}var rd=(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 Zu(e,t),e})(Sn(Error)),ys=(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(l,c){l?a(new rd(l.message,l.code,l.name,l.statusCode)):o(c);});})},e.requestWithRetry=function(n,i,s){var o=this,a=5*1e3;od(function(l){return new Promise(function(c,u){o.request(n,l,function(f,d){f?u(f):c(d);});})},[i],a).then(function(l){return s(null,l)}).catch(function(l){return s(l)});},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":gs(),"Cache-Control":"no-store"},a=Object.assign({},this.fetchOptions,{headers:o,method:"POST",mode:"cors",body:JSON.stringify(i)}),l;fetch(this.endpoint,a).then(function(u){return l=u,u},function(u){throw u instanceof TypeError?new Error("Network error"):u}).then(function(u){return u.json().catch(function(){return {}})}).then(function(u){if(l.ok)return s(null,u);var f=(u.__type||u.code).split("#").pop(),d=new Error(u.message||u.Message||null);return d.name=f,d.code=f,s(d)}).catch(function(u){if(l&&l.headers&&l.headers.get("x-amzn-errortype"))try{var f=l.headers.get("x-amzn-errortype").split(":")[0],d=new Error(l.status?l.status.toString():null);return d.code=f,d.name=f,d.statusCode=l.status,s(d)}catch{return s(u)}else u instanceof Error&&u.message==="Network error"&&(u.code="NetworkError");return s(u)});},t})();var _r={debug:function(){}};var nd=function(e){var r="nonRetryable";return e&&e[r]};function _s(t,e,r,n){if(n===void 0&&(n=1),typeof t!="function")throw Error("functionToRetry must be a function");return _r.debug(t.name+" attempt #"+n+" with args: "+JSON.stringify(e)),t.apply(void 0,e).catch(function(i){if(_r.debug("error on "+t.name,i),nd(i))throw _r.debug(t.name+" non retryable error",i),i;var s=r(n,e,i);if(_r.debug(t.name+" retrying in "+s+" ms"),s!==false)return new Promise(function(o){return setTimeout(o,s)}).then(function(){return _s(t,e,r,n+1)});throw i})}function id(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 od(t,e,r){return _s(t,e,id(r))}var ad=55,Rn=(function(){function t(r,n){var i=r||{},s=i.UserPoolId,o=i.ClientId,a=i.endpoint,l=i.fetchOptions,c=i.AdvancedSecurityDataCollectionFlag;if(!s||!o)throw new Error("Both UserPoolId and ClientId are required.");if(s.length>ad||!/^[\w-]+_[0-9a-zA-Z]+$/.test(s))throw new Error("Invalid UserPoolId format.");var u=s.split("_")[0];this.userPoolId=s,this.clientId=o,this.client=new ys(u,a,l),this.advancedSecurityDataCollectionFlag=c!==false,this.storage=r.Storage||new yr().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,l){var c=this,u={ClientId:this.clientId,Username:n,Password:i,UserAttributes:s,ValidationData:o,ClientMetadata:l};this.getUserContextData(n)&&(u.UserContextData=this.getUserContextData(n)),this.client.request("SignUp",u,function(f,d){if(f)return a(f,null);var p={Username:n,Pool:c,Storage:c.storage},g={user:new Fe(p),userConfirmed:d.UserConfirmed,userSub:d.UserSub,codeDeliveryDetails:d.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 Fe(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 br(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 cd={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 Tn(t,e){function r(i,s,o){if(!(typeof document>"u")){o=br({},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 l in o)o[l]&&(a+="; "+l,o[l]!==true&&(a+="="+o[l].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 l=s[a].split("="),c=l.slice(1).join("=");try{var u=decodeURIComponent(l[0]);if(u in o||(o[u]=t.read(c,u)),i===u)break}catch{}}return i?o[i]:o}}return Object.create({set:r,get:n,remove:function(i,s){r(i,"",br({},s,{expires:-1}));},withAttributes:function(i){return Tn(this.converter,br({},this.attributes,i))},withConverter:function(i){return Tn(br({},this.converter,i),this.attributes)}},{attributes:{value:Object.freeze(e)},converter:{value:Object.freeze(t)}})}Tn(cd,{path:"/"});var h=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 Le="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",In=BigInt(Le.length),ud=2*1024*1024,dd=["aud","cognito:username","event_id","exp","iat","iss","jti","origin_jti","secret_key","token_use"],bs={auth_time:"log",sub:"user_id"},vs=["0","1","2","3","4","5","6","7","8","9","a","b","c","d","e","f","g","h","i","j","k","l"],Rs=["us31","us72","ap51","ap22","ap41","eu71","ap21","us32","us71","af51","ap31","ap43","ap23","ap42","ca01","eu01","eu72","eu51","eu73","eu11","me51","sa31"],ws=typeof TextEncoder<"u"?new TextEncoder:null;function fd(){if(typeof globalThis<"u")return globalThis.Buffer}function G(t){if(ws)return ws.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 Pn(t){if(t instanceof Uint8Array)return t;if(typeof t=="string")return G(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=fd();if(e)return new Uint8Array(e.from(t));throw new Error("No byte conversion available in this environment.")}var v=class v{static hash(e){typeof e!="string"&&(console.warn("coercing non-string value to empty string"),e="");let r=v.sb(e),n=1732584193,i=-271733879,s=-1732584194,o=271733878,a,l,c,u;for(let f=0;f<r.length;f+=16)a=n,l=i,c=s,u=o,n=v.ff(n,i,s,o,r[f],7,-680876936),o=v.ff(o,n,i,s,r[f+1],12,-389564586),s=v.ff(s,o,n,i,r[f+2],17,606105819),i=v.ff(i,s,o,n,r[f+3],22,-1044525330),n=v.ff(n,i,s,o,r[f+4],7,-176418897),o=v.ff(o,n,i,s,r[f+5],12,1200080426),s=v.ff(s,o,n,i,r[f+6],17,-1473231341),i=v.ff(i,s,o,n,r[f+7],22,-45705983),n=v.ff(n,i,s,o,r[f+8],7,1770035416),o=v.ff(o,n,i,s,r[f+9],12,-1958414417),s=v.ff(s,o,n,i,r[f+10],17,-42063),i=v.ff(i,s,o,n,r[f+11],22,-1990404162),n=v.ff(n,i,s,o,r[f+12],7,1804603682),o=v.ff(o,n,i,s,r[f+13],12,-40341101),s=v.ff(s,o,n,i,r[f+14],17,-1502002290),i=v.ff(i,s,o,n,r[f+15],22,1236535329),n=v.gg(n,i,s,o,r[f+1],5,-165796510),o=v.gg(o,n,i,s,r[f+6],9,-1069501632),s=v.gg(s,o,n,i,r[f+11],14,643717713),i=v.gg(i,s,o,n,r[f],20,-373897302),n=v.gg(n,i,s,o,r[f+5],5,-701558691),o=v.gg(o,n,i,s,r[f+10],9,38016083),s=v.gg(s,o,n,i,r[f+15],14,-660478335),i=v.gg(i,s,o,n,r[f+4],20,-405537848),n=v.gg(n,i,s,o,r[f+9],5,568446438),o=v.gg(o,n,i,s,r[f+14],9,-1019803690),s=v.gg(s,o,n,i,r[f+3],14,-187363961),i=v.gg(i,s,o,n,r[f+8],20,1163531501),n=v.gg(n,i,s,o,r[f+13],5,-1444681467),o=v.gg(o,n,i,s,r[f+2],9,-51403784),s=v.gg(s,o,n,i,r[f+7],14,1735328473),i=v.gg(i,s,o,n,r[f+12],20,-1926607734),n=v.hh(n,i,s,o,r[f+5],4,-378558),o=v.hh(o,n,i,s,r[f+8],11,-2022574463),s=v.hh(s,o,n,i,r[f+11],16,1839030562),i=v.hh(i,s,o,n,r[f+14],23,-35309556),n=v.hh(n,i,s,o,r[f+1],4,-1530992060),o=v.hh(o,n,i,s,r[f+4],11,1272893353),s=v.hh(s,o,n,i,r[f+7],16,-155497632),i=v.hh(i,s,o,n,r[f+10],23,-1094730640),n=v.hh(n,i,s,o,r[f+13],4,681279174),o=v.hh(o,n,i,s,r[f],11,-358537222),s=v.hh(s,o,n,i,r[f+3],16,-722521979),i=v.hh(i,s,o,n,r[f+6],23,76029189),n=v.hh(n,i,s,o,r[f+9],4,-640364487),o=v.hh(o,n,i,s,r[f+12],11,-421815835),s=v.hh(s,o,n,i,r[f+15],16,530742520),i=v.hh(i,s,o,n,r[f+2],23,-995338651),n=v.ii(n,i,s,o,r[f],6,-198630844),o=v.ii(o,n,i,s,r[f+7],10,1126891415),s=v.ii(s,o,n,i,r[f+14],15,-1416354905),i=v.ii(i,s,o,n,r[f+5],21,-57434055),n=v.ii(n,i,s,o,r[f+12],6,1700485571),o=v.ii(o,n,i,s,r[f+3],10,-1894986606),s=v.ii(s,o,n,i,r[f+10],15,-1051523),i=v.ii(i,s,o,n,r[f+1],21,-2054922799),n=v.ii(n,i,s,o,r[f+8],6,1873313359),o=v.ii(o,n,i,s,r[f+15],10,-30611744),s=v.ii(s,o,n,i,r[f+6],15,-1560198380),i=v.ii(i,s,o,n,r[f+13],21,1309151649),n=v.ii(n,i,s,o,r[f+4],6,-145523070),o=v.ii(o,n,i,s,r[f+11],10,-1120210379),s=v.ii(s,o,n,i,r[f+2],15,718787259),i=v.ii(i,s,o,n,r[f+9],21,-343485551),n=v.ad(n,a),i=v.ad(i,l),s=v.ad(s,c),o=v.ad(o,u);return v.rh(n)+v.rh(i)+v.rh(s)+v.rh(o)}static rh(e){let r="";for(let n=0;n<=3;n++)r+=v.alphabet.charAt(e>>n*8+4&15)+v.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 v.ad(v.rl(v.ad(v.ad(r,e),v.ad(i,o)),s),n)}static ff(e,r,n,i,s,o,a){return v.cm(r&n|~r&i,e,r,s,o,a)}static gg(e,r,n,i,s,o,a){return v.cm(r&i|n&~i,e,r,s,o,a)}static hh(e,r,n,i,s,o,a){return v.cm(r^n^i,e,r,s,o,a)}static ii(e,r,n,i,s,o,a){return v.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}};v.alphabet="0123456789abcdef";var X=v;function Ts(t){if(t===0)return Le[0];let e="";for(;t>0;)e=Le[t%62]+e,t=Math.floor(t/62);return e}function be(t){return t.split("").reverse().reduce((e,r,n)=>e+Le.indexOf(r)*62**n,0)}function Ye(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 Un(){return typeof window>"u"||!!window?._runningInNodeJS}function ae(){return !Un()&&typeof document<"u"&&typeof document.createElement=="function"}function wr(t){let e;try{e=JSON.stringify(t);}catch{throw new h("Invalid data type.",{code:"INVALID_REQUEST"})}if(new Blob([e]).size>ud)throw new h("Data should not exceed 2MB",{code:"INVALID_REQUEST"})}function Es(t){return t===""||t==="on"||t==="true"}function As(t){return t==="false"}function Ss(t,e,r){e.name&&r(t,e.name,e.value);}var Er=ae(),hd=typeof SubmitEvent<"u",pd=typeof HTMLFormElement<"u";function j(t,e,r){let n={},i=[];function s(l,c,u){if(e?.ignoreEmpty&&u==="")return;if(e?.nullIfEmpty&&u===""&&(u=null),typeof r=="function"){let p=r(c,u);p!==void 0&&(u=p);}let f=c.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}),d=l;if(typeof f[0]=="number")throw new h("Form key cannot start with an array index.",{code:"INVALID_REQUEST"});for(let p=0;p<f.length;p++){let g=f[p];p<f.length-1?(d[g]===void 0&&(typeof f[p+1]=="number"?d[g]=[]:d[g]={}),d=d[g]):d[g]===void 0?d[g]=u:Array.isArray(d[g])?d[g].push(u):d[g]=[d[g],u];}}function o(l,c,u){if(u instanceof File)l.push({name:c,file:u});else if(u instanceof FileList&&u&&u.length>0)for(let f=0;f<=u.length-1;f++){let d=u.item(f);d&&l.push({name:c,file:d});}}let a=l=>{l.name&&(l.type==="number"?l.value&&s(n,l.name,Number(l.value)):l.type==="checkbox"||l.type==="radio"?l.checked?l.type==="checkbox"&&l.value===""||Es(l.value)?s(n,l.name,true):As(l.value)?s(n,l.name,false):l.value&&s(n,l.name,l.value):l.type==="checkbox"&&(Es(l.value)?s(n,l.name,false):As(l.value)&&s(n,l.name,true)):l.type==="file"?l.files&&l.files.length>0&&o(i,l.name,l.files):s(n,l.name,l.value));};if(Er&&(t instanceof HTMLInputElement||t instanceof HTMLSelectElement||t instanceof HTMLTextAreaElement))return a(t),wr(n),{data:n,files:i};if(Er&&t instanceof FormData){for(let l of t.entries()){let c=l[0],u=l[1];if(u instanceof File||u instanceof FileList)o(i,c,u);else if(u instanceof Blob){let f=u;if(f.type==="application/json")try{let d=JSON.parse(f.text());s(n,c,d);}catch{s(n,c,f);}}else s(n,c,u);}return wr(n),{data:n,files:i}}if(Er&&hd&&t instanceof SubmitEvent&&(t=t.target),Er&&pd&&t instanceof HTMLFormElement){let l=t.querySelectorAll("input"),c=t.querySelectorAll("select"),u=t.querySelectorAll("textarea");for(let f=0;f<c.length;f++)Ss(n,c[f],s);for(let f=0;f<u.length;f++)Ss(n,u[f],s);for(let f=0;f<l.length;f++)a(l[f]);return wr(n),{data:n,files:i}}return wr(t),{data:t,files:i}}function Tt(t){let e={};for(let r in t){let n=t[r];if(!dd.includes(r))if(bs[r])e[bs[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 xn(t){if(t=Ad(t),t.split("-").length===7){let e=t.split("-"),r,n;try{r=Rs[vs.indexOf(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 Cn(t,e){let r=Rs.indexOf(t.slice(0,4)),n=vs[r],s=`${t.slice(4,-4)}-${n}${t.slice(-4)}-${e}`;return Ed(s)}function gd(t){let e=0n;for(let r of t){let n=Le.indexOf(r);if(n<0)throw new Error(`INVALID_PARAMETER: Invalid base62 character: ${r}`);e=e*In+BigInt(n);}return e}function md(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%In);r=Le[i]+r,n/=In;}return r.length<e&&(r="0".repeat(e-r.length)+r),r}function yd(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 _d(t){let e=0n;for(let r of t)e=(e<<8n)+BigInt(r);return e}function bd(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 wd(t){let e=Array.from(Pn(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 Ed(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>=Le.length)throw new Error("INVALID_PARAMETER: The middle section is too long to encode.");let o=n.slice(0,2),a=n.slice(2),l=i+o,c=Le[i.length]+a+l,u=bd(s),f=md(_d(u));return `${c}-${f}`}function Ad(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=Le.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 l=o.slice(0,o.length-a),c=o.slice(o.length-a),u=c.slice(s),f=c.slice(0,s),d=u+l;if(!/^[0-9A-Za-z]+$/.test(d)||!/^[0-9A-Za-z]+$/.test(f))throw new Error("INVALID_PARAMETER: Corrupt compressed token: "+e);let p=gd(i),g=yd(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=wd(m);return `${d}-${f}-${y}`}function It(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 kn(...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 Pt(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 l(g){return typeof g=="string"&&i.indexOf(g)!==-1}function c(g){return Array.isArray(g)?"array":g===null?"null":typeof g}function u(g){try{return JSON.stringify(g)}catch{return String(g)}}function f(g){if(l(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 d(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]=Pt(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 <${c(t)}> is invalid in "${n}". Expected a list.`);for(let y=0;y<t.length;y++){let w=t[y];if(l(m)){if(!d(w,m))throw new Error(`Type <${c(w)}> is invalid in "${n}". Expected a list of Type <${m}>.`)}else if(typeof m=="function")t[y]=m(w);else if(w!==m)throw new Error(`Value ${u(w)} is invalid in "${n}". Expected a list of ${u(m)}.`)}g=true;}else if(Array.isArray(t)&&e.every(y=>!a(y)&&y!=="array")){for(let y=0;y<t.length;y++){let w=false,_="";for(let A of e)try{t[y]=Pt(t[y],A,r,n),w=!0;break}catch(U){typeof A=="function"&&(_=U?.message||String(U));}if(!w&&_)throw new Error(_);if(!w){let A=e.map(f).join(", ");throw new Error(`${u(t[y])} is invalid in "${n}". allowed types or values are: ${A}.`)}}g=true;}else {let y="";for(let w of e)try{t=Pt(t,w,r,n),g=!0;break}catch(_){typeof w=="function"&&(y=_?.message||String(_));}if(!g&&y)throw new Error(y)}if(!g){let m=e.map(f).join(", ");throw new Error(`${u(t)} is invalid in "${n}". allowed types or values are: ${m}.`)}return t}if(l(e)&&d(t,e)||t===e)return t;throw new Error(`${u(t)} is invalid in "${n}". allowed type or value is: ${f(e)}.`)}function Sd(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 h(`${e} should be type: string.`,{code:"INVALID_PARAMETER"});if(!t.match(r))throw new h(`${e} is invalid.`,{code:"INVALID_PARAMETER"})}else throw new h(`${e} is empty.`,{code:"INVALID_PARAMETER"});return t}function vd(t){if(t&&(typeof t!="string"||t.charAt(0)!=="+"||isNaN(Number(t.substring(1)))))throw new h('"phone_number" is invalid. The format should be "+00123456789". Type: string.',{code:"INVALID_PARAMETER"});return t||""}function Rd(t){if(t){if(typeof t!="string")throw new h('"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 h('"birthdate" is invalid. The format should be "yyyy-mm-dd". Type: string.',{code:"INVALID_PARAMETER"})}}return t||""}function Td(t){if(t){if(typeof t!="string")throw new h('"password" should be type: string.',{code:"INVALID_PARAMETER"});if(t.length<6)throw new h('"password" should be at least 6 characters.',{code:"INVALID_PARAMETER"});if(t.length>60)throw new h('"password" can be up to 60 characters max.',{code:"INVALID_PARAMETER"})}else throw new h('"password" is required.',{code:"INVALID_PARAMETER"});return t}function Id(t,e="email"){if(t){if(typeof t!="string")throw new h(`"${e}"should be type: string.`,{code:"INVALID_PARAMETER"});if(t.length<5)throw new h(`"${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 h(`"${e}" is required.`,{code:"INVALID_PARAMETER"});throw new h(`"${t}" is an invalid email.`,{code:"INVALID_PARAMETER"})}function Pd(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 h(`"${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 h(`"${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 h(`"${i}" is an invalid url.`,{code:"INVALID_PARAMETER"})}if(o.protocol)return o.href}}throw new h(`"${i}" is an invalid url.`,{code:"INVALID_PARAMETER"})};return Array.isArray(t)?t.map(i=>n(i)):n(t)}var Ud=/^[a-z0-9]{2,20}$/,xd=/[a-z]/,Cd=/^[0-9]+e[0-9]+$/,kd=["tp","admin","public","authorized","newsletter","forward","all","true","false","null"];function Dd(t,e){if(t==null){if(e?.allowNull)return null;throw new h('"group" is required.',{code:"INVALID_PARAMETER"})}if(!e?.nameOnly){if(t==="public")return 0;if(t==="authorized")return 1;if(typeof t=="number"){if(!Number.isInteger(t)||t<0||t>99)throw new h('"group" should be an integer between 0 and 99.',{code:"INVALID_PARAMETER"});return t}}if(typeof t!="string"||!Ud.test(t)||!xd.test(t)||Cd.test(t)||kd.includes(t))throw new h("Newsletter group name must be 2-20 lowercase alphanumeric characters, contain a letter, and not be a reserved name.",{code:"INVALID_PARAMETER"});return t}function Nd(t,e,r=[],n){let i=j(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 Pt(o,e,r)}catch(a){throw new h(a.message,{code:"INVALID_PARAMETER"})}}var b={UserId:Sd,PhoneNumber:vd,Birthdate:Rd,Password:Td,Email:Id,Url:Pd,newsletterGroup:Dd,Params:Nd};var ce="skapi.enc.v1",Us=6e5,Ut=12,Ar=null,ht=null;function xs(){return new h("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 Cs(){if(ht)return ht;let t=typeof globalThis<"u"?globalThis:void 0;if(t?.crypto?.subtle&&typeof t.crypto.getRandomValues=="function")return ht=t.crypto,ht;try{let e=typeof globalThis<"u"?globalThis:void 0,r=null;if(e?.process&&typeof e.process.getBuiltinModule=="function"&&(r=e.process.getBuiltinModule("crypto")),!r&&typeof Ve=="function"&&(r=Ve("crypto")),r?.webcrypto?.subtle)return ht=r.webcrypto,ht}catch{}throw xs()}function ye(){if(Ar)return Ar;let t=Cs();if(!t.subtle)throw xs();return Ar=t.subtle,Ar}function Nn(){try{return ye(),!0}catch{return false}}function le(t){let e=Cs(),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 $(t){let e=Pn(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 h("No base64 encoder available in this environment.",{code:"NOT_SUPPORTED"});return r.replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function K(t){if(typeof t!="string")throw new h("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 h("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 h("No base64 decoder available in this environment.",{code:"NOT_SUPPORTED"})}async function Sr(t){let e=await ye().digest("SHA-256",t);return new Uint8Array(e)}async function kt(t,e,r,n){let i=ye(),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 gt(t,e,r,n){let i=ye(),s=G(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)),l=await kt(a,e,n,32);V(a),V(s);let c=await we(l);return V(l),c}async function we(t){return ye().importKey("raw",t,{name:"AES-GCM"},false,["encrypt","decrypt"])}async function ks(){let t=le(32),e=await we(t);return {bytes:t,key:e}}async function _e(t,e,r){let n=le(Ut),i=await ye().encrypt({name:"AES-GCM",iv:n,additionalData:r,tagLength:128},t,e);return {iv:n,ct:new Uint8Array(i)}}async function Ee(t,e,r,n){let i=await ye().decrypt({name:"AES-GCM",iv:e,additionalData:n,tagLength:128},t,r);return new Uint8Array(i)}var vr={name:"ECDH",namedCurve:"P-256"};async function Ds(){let t=ye(),e=await t.generateKey(vr,true,["deriveBits"]),r=new Uint8Array(await t.exportKey("raw",e.publicKey)),n=new Uint8Array(await t.exportKey("pkcs8",e.privateKey)),i=await On(n);return {pubRaw:r,pkcs8:n,priv:i}}async function On(t){return ye().importKey("pkcs8",t,vr,false,["deriveBits"])}async function Ns(t){if(t.length!==65||t[0]!==4)throw new h("Malformed public key: expected a 65 byte uncompressed P-256 point.",{code:"INVALID_PARAMETER"});return ye().importKey("raw",t,vr,false,[])}async function Fn(t){return $(await Sr(t))}async function Os(t,e,r,n){let i=ye(),s=await Ns(t),o=await i.generateKey(vr,true,["deriveBits"]),a=new Uint8Array(await i.deriveBits({name:"ECDH",public:s},o.privateKey,256)),l=await kt(a,new Uint8Array(32),r,32);V(a);let c=await we(l);V(l);let{iv:u,ct:f}=await _e(c,e,n);return {epk:new Uint8Array(await i.exportKey("raw",o.publicKey)),iv:u,ct:f}}async function Fs(t,e,r,n,i,s){let o=ye(),a=await Ns(e),l=new Uint8Array(await o.deriveBits({name:"ECDH",public:a},t,256)),c=await kt(l,new Uint8Array(32),i,32);V(l);let u=await we(c);return V(c),Ee(u,r,n,s)}function V(t){t&&t.length&&t.fill(0);}function Od(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 Ln(t){return G(JSON.stringify(t))}function Dt(t,e,r){return kn(t,new Uint8Array([0]),G(e),new Uint8Array([0]),G(r))}var ze="0123456789ABCDEFGHJKMNPQRSTVWXYZ",xt=16,Is=26,Ps=28;function Ls(t){let e=2166136261;for(let r=0;r<t.length;r++)e^=t[r],e=e*16777619>>>0;return e&1023}function Ms(t){if(t.length!==xt)throw new h(`A recovery code needs exactly ${xt} 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+=ze[r>>n&31];n>0&&(e+=ze[r<<5-n&31]);let i=Ls(t);return e+=ze[i>>5&31]+ze[i&31],(e.match(/.{1,4}/g)||[]).join("-")}function qs(t){if(typeof t!="string")throw new h("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!==Ps)throw new h(`That does not look like a recovery code: expected ${Ps} characters, got ${e.length}.`,{code:"ENCRYPTION_BAD_RECOVERY_CODE"});let r=e.slice(0,Is),n=e.slice(Is),i=0,s=0,o=[];for(let c=0;c<r.length;c++){let u=ze.indexOf(r[c]);if(u<0)throw new h(`That does not look like a recovery code: "${r[c]}" is not a valid character.`,{code:"ENCRYPTION_BAD_RECOVERY_CODE"});i=i<<5|u,s+=5,s>=8&&(s-=8,o.push(i>>s&255));}let a=new Uint8Array(o.slice(0,xt)),l=Ls(a);if(n!==ze[l>>5&31]+ze[l&31])throw new h("That recovery code has a typo in it: the check characters do not match.",{code:"ENCRYPTION_BAD_RECOVERY_CODE"});return a}async function Mn(t,e,r){let n=await kt(t,e,r,32),i=await we(n);return V(n),i}var Dn=[83,75,69,78,67,70],Vs=2,Ct=56,Bs=16,Fd=4*1024*1024;function qn(t){if(!t||t.length<Ct)return false;for(let e=0;e<Dn.length;e++)if(t[e]!==Dn[e])return false;return true}function Qe(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 pt(t,e){return (t[e]<<24>>>0)+(t[e+1]<<16)+(t[e+2]<<8)+t[e+3]}function Ld(t,e,r){let n=Math.floor(r/4294967296);Qe(t,e,n),Qe(t,e+4,r>>>0);}function Md(t,e){return pt(t,e)*4294967296+pt(t,e+4)}async function $s(t,e,r,n,i,s){let o=G(`${ce}|binfile|${r}|${n}|${i}|${s}`),a=await kt(t,e,o,32),l=await we(a);return V(a),l}async function Ks(t){return (await Sr(kn(G(`${ce}|dekid`),t))).subarray(0,8)}function js(t,e,r){return Ln([`${ce}|binchunk`,$(t),e,r])}function qd(t,e,r,n,i,s){let o=new Uint8Array(Ct+s.length);return o.set(Dn,0),o[6]=Vs,o[7]=s.length?1:0,Qe(o,8,t),Qe(o,12,e),o.set(r,16),Ld(o,32,n),o.set(i,40),Qe(o,48,s.length),Qe(o,52,0),s.length&&o.set(s,Ct),o}async function Hs(t,e,r,n,i=Fd){let s=le(Bs),o=await $s(t,s,r.service,r.owner,r.recordOwner,r.recordId),a=await Ks(t),l=n?G(JSON.stringify(n)):new Uint8Array(0);if(l.length>4096)throw new h("Encrypted file metadata is too large.",{code:"INVALID_PARAMETER"});let c=e.length===0?1:Math.ceil(e.length/i),u=qd(i,c,s,e.length,a,l),f=await Sr(u),d=[],p=u.length;for(let y=0;y<c;y++){let w=e.subarray(y*i,Math.min((y+1)*i,e.length)),_=await _e(o,w,js(f,y,c));d.push(_),p+=4+_.iv.length+_.ct.length;}let g=new Uint8Array(p);g.set(u,0);let m=u.length;for(let y of d)Qe(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 Vd(t){if(!qn(t))throw new h("This file is not an encrypted skapi file.",{code:"INVALID_PARAMETER"});let e=pt(t,48),r=Ct+e;if(t.length<r)throw new h("Encrypted file header is truncated.",{code:"INVALID_REQUEST"});let n=null;return e&&(n=JSON.parse(It(t.subarray(Ct,r)))),{version:t[6],chunkBytes:pt(t,8),count:pt(t,12),fileId:t.subarray(16,16+Bs),plainLen:Md(t,32),dekId:t.subarray(40,48),meta:n,headerLen:r}}async function Ws(t,e,r){let n=Vd(e);if(n.version!==Vs)throw new h(`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 h("Encrypted file header is malformed.",{code:"INVALID_PARAMETER"});let i=await Ks(t);if(!Od(i,n.dekId))throw new h("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 $s(t,n.fileId,r.service,r.owner,r.recordOwner,r.recordId),o=await Sr(e.subarray(0,n.headerLen)),a=[],l=n.headerLen,c=0;for(let d=0;d<n.count;d++){if(l+4>e.length)throw new h("Encrypted file is truncated.",{code:"INVALID_REQUEST"});let p=pt(e,l);if(l+=4,p<Ut+16||l+p>e.length)throw new h("Encrypted file is truncated.",{code:"INVALID_REQUEST"});let g=await Ee(s,e.subarray(l,l+Ut),e.subarray(l+Ut,l+p),js(o,d,n.count));l+=p,a.push(g),c+=g.length;}let u=new Uint8Array(c),f=0;for(let d of a)u.set(d,f),f+=d.length;return {bytes:u,meta:n.meta}}var Bd="__skapi__keyring",Nt="__skapi_enc__",Js=1,$d="skapi-enc",je="keys",Bn=new WeakMap;function Ys(t){if(!t)return null;if(t===true&&(t={}),typeof t!="object")throw new h('"options.encryption" should be a boolean or an object.',{code:"INVALID_PARAMETER"});let e=typeof t.iterations=="number"?t.iterations:Us;if(e<1e5)throw new h('"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:Bd}}function q(){return Bn.get(this)||null}function zs(t){if(!t){Bn.delete(this);return}Bn.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,passthrough:new Map,rawRead:false,ready:null,unlocking:false,pendingRecoveryCode:"",peerPub:new Map,peerInflight:new Map});}function $n(){let t=q.call(this);if(t){t.user_id&&Zn.call(this,t).catch(()=>{}),t.ready=null,t.unlocking=false,t.pendingRecoveryCode="";for(let[,e]of t.dek)V(e.bytes);t.dek.clear(),t.roll.clear(),t.passthrough.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 Qs(){let t=q.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 Xs(t,e){return typeof e=="string"&&e===t.cfg.table}function mt(){return `${this.service}/${this.owner}`}function Kn(t,e,r,n){let[i,s]=t.split("/");return Ln([ce,i,s,e,r,n])}function Zs(t,e,r,n,i){let[s,o]=t.split("/");return G(`${ce}|dekwrap|${s}|${o}|${e}|${r}|${n}|${i}`)}function jn(t){return t.anch==="uid"?t.uid:t.anch==="rid"?t.rid:""}function Tr(t){return !!t&&typeof t=="object"&&!Array.isArray(t)&&typeof t[Nt]=="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 eo="__skapi_no_access__";function ue(t,e,r){if(t.withheld!=="sentinel")return null;let n={[eo]:true,reason:e};return r&&(n.recipients=r),Object.freeze(n)}function Hn(t){return !!t&&typeof t=="object"&&t[eo]===true}var Kd=256*1024,Lt="__skenc_ct__",to="payload.bin",jd=`/${Lt}/${to}`;function Wn(t,e){return t===Lt&&e===to}async function Hd(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:Gs(n.access_group),table:i,record:null};if(!r)return {group:n?.access_group!==void 0?Gs(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 Ke.call(this,r);if(!o)throw new h(`Record "${r}" not found.`,{code:"NOT_EXISTS"});return {group:o.table.access_group,table:o.table.name,record:o}}function Wd(t){return this.getFile(t,{dataType:"blob"})}async function Ke(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 Gs(t){return t==="private"||t==="*"||t==="**"?"private":t==="public"?0:t==="authorized"?1:t==="admin"?99:typeof t=="number"?t:0}function Vn(t,e,r){let n=this.user?.user_id;if(!(!t||!t.user_id||!n||t.user_id===n))throw new h(`Record "${e}" belongs to another user (${t.user_id}), so ${r} would either seal it under the wrong key or strand its contents. Encryption only operates on records you own, no matter what access level you hold.`,{code:"ENCRYPTION_NOT_RECORD_OWNER"})}async function Gn(t,e,r){let n=q.call(this);if(!n)return {send:t,plain:t,encrypted:false,omit:false};let i=e?.record_id||"",s=i,o=e?.unique_id||"";if(i&&n.passthrough.has(i)){let M=n.passthrough.get(i);return n.passthrough.delete(i),{send:M,plain:t,encrypted:true,omit:false}}let{group:a,table:l,record:c}=await Hd.call(this,n,e,s);if(a!=="private"){let M=true;if(!r&&i){let te=c||await Ke.call(this,i);if(te&&te.encrypted){if(Vn.call(this,te,i,"making it non-private"),te.encrypted.status==="failed")throw new h(`Cannot make record "${i}" non-private: its current contents could not be decrypted (${te.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"});let St=!!te.bin&&Object.keys(te.bin).some(zt=>(te.bin[zt]||[]).some(_i=>_i&&_i.encrypted));if(!St&&s){let zt=n.dek.get(s);zt&&(V(zt.bytes),n.dek.delete(s));}return {send:te.data,plain:te.data,encrypted:false,omit:false,files:St?"decrypt":void 0}}}let Q=c;i&&!Q&&(Q=await Ke.call(this,i).catch(()=>null)),Q&&Q.encrypted&&Vn.call(this,Q,i,"making it non-private");let Yt=!!Q&&!!Q.bin&&Object.keys(Q.bin).some(te=>(Q.bin[te]||[]).some(St=>St&&St.encrypted));if(Yt&&(M=false),M&&s){let te=n.dek.get(s);te&&(V(te.bytes),n.dek.delete(s));}return {send:t,plain:t,encrypted:false,omit:!r,files:Yt?"decrypt":void 0}}if(Xs(n,l))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(Hn.call(this,t))throw new h("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 h("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,Nt))throw new h(`"${Nt}" 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 h("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 u=this.user?.user_id;if(!u)throw new h("User login is required to write an encrypted record.",{code:"INVALID_REQUEST"});let f=mt.call(this),d=false;if(i&&n.roll.has(i)){d=true,n.roll.delete(i);let M=n.dek.get(i);n.dek.delete(i),M&&V(M.bytes);}let p=c;i&&!p&&!n.dek.has(i)&&(p=await Ke.call(this,i).catch(()=>null)),p&&Vn.call(this,p,i,"making it private");let g=!!p&&!p.encrypted&&!!p.bin&&Object.keys(p.bin).some(M=>(p.bin[M]||[]).some(Q=>Q&&!Q.encrypted)),m=null;if(i&&!d&&(m=n.dek.get(i)||null,!m)){let M=p||c||await Ke.call(this,i);if(M&&(s=M.record_id||i,m=n.dek.get(s)||null,!o&&M.unique_id&&(o=M.unique_id),!m&&M.encrypted?.status==="failed"))throw new h(`Cannot update encrypted record "${i}": its current contents could not be decrypted (${M.encrypted.reason}), so its existing key wraps cannot be preserved. Updating anyway would revoke everyone it is shared with.`,{code:"ENCRYPTION_LOCKED"})}s===i&&m&&m.rid&&(s=m.rid),!o&&m&&m.anch==="uid"&&m.uid&&(o=m.uid);let y,w,_;if(m){if(m.own&&m.own!==u)throw new h(`Record "${i}" belongs to another user (${m.own}). Encryption only operates on records you own.`,{code:"ENCRYPTION_NOT_RECORD_OWNER"});y=m.bytes,w=m.key,_=Object.assign({},m.recipients);}else {let M=await ks();y=M.bytes,w=M.key,_={};}let A=o?"uid":s?"rid":"new",U=A==="uid"?o:A==="rid"?s:"",S=Kn(f,u,A,U),F=Dt(S,u,"mk"),O=await _e(n.mk,y,F);_[u]={t:"mk",iv:$(O.iv),ct:$(O.ct)},m&&(m.anch!==A||jn(m)!==U)&&(_=await Gd.call(this,n,y,_,f,u,A,U,S));let k=G(JSON.stringify(t===void 0?null:t)),x=await _e(w,k,S);V(k);let C={[Nt]:Js,enc:"A256GCM",kw:"ECDH-ES+A256GCM",anch:A,uid:o,rid:s,own:u,iv:$(x.iv),ct:$(x.ct),k:_},L,B,ee=C.ct;s&&ee.length>Kd&&(L=K(ee),C.ct="",C.ct_ref=jd,m&&m.ctRef&&(B=m.ctRef));let ie=JSON.stringify(C).length;if(ie>2*1024*1024)throw new h(`Encrypted record data is too large: once encrypted and base64 encoded it becomes ${ie} 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:y,key:w,recipients:_,anch:A,uid:o,rid:s,own:u,access_group:"private"}),{send:C,plain:t,encrypted:true,omit:false,spill:L,retireCt:B,dek:{bytes:y,key:w,recipients:_,anch:A,uid:o,rid:s,own:u,access_group:"private"},files:g?"encrypt":void 0}}function ro(t,e){let r=q.call(this);!r||!e||!t||r.dek.has(t)||r.dek.set(t,Object.assign({},e,{rid:t}));}async function Gd(t,e,r,n,i,s,o,a){let l=Object.keys(r).filter(f=>f!==i);if(!l.length)return r;let c=await ei.call(this,l),u={[i]:r[i]};for(let f of l){let d=c[f];d&&(u[f]=await no.call(this,e,d,n,o,i,f,a));}return u}async function no(t,e,r,n,i,s,o){let a=Zs(r,n,i,s,e.fpr),l=Dt(o,s,e.fpr),c=await Os(e.pubRaw,t,a,l);return {t:"ecdh",epk:$(c.epk),iv:$(c.iv),ct:$(c.ct),fpr:e.fpr}}async function io(t,e){if(!Tr(t))return {value:t};if(e.access_group!=="private")return {value:t};let r=q.call(this);if(!r)return {value:null,flag:{status:"failed",reason:"ENCRYPTION_DISABLED"}};if(r.rawRead)return {value:t};if(Xs(r,e.table_name))return {value:t};if(t[Nt]!==Js)return {value:ue(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:ue(r.cfg,"BINDING_MISMATCH"),flag:{status:"failed",reason:"BINDING_MISMATCH"}};if(t.uid&&e.unique_id&&t.uid!==e.unique_id)return {value:ue(r.cfg,"BINDING_MISMATCH"),flag:{status:"failed",reason:"BINDING_MISMATCH"}};if(t.rid&&e.record_id&&t.rid!==e.record_id)return {value:ue(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:ue(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:ue(r.cfg,"NO_SESSION_KEY"),flag:{status:"failed",reason:"NO_SESSION_KEY"}};let s=mt.call(this),o=jn(t),a=Kn(s,t.own,t.anch,o),l;try{if(i.t==="mk")l=await Ee(r.mk,K(i.iv),K(i.ct),Dt(a,n,"mk"));else if(i.t==="ecdh"){if(!r.ikPriv)return {value:ue(r.cfg,"NO_SESSION_KEY"),flag:{status:"failed",reason:"NO_SESSION_KEY"}};l=await Fs(r.ikPriv,K(i.epk),K(i.iv),K(i.ct),Zs(s,o,t.own,n,i.fpr),Dt(a,n,i.fpr));}else return {value:ue(r.cfg,"UNSUPPORTED_VERSION"),flag:{status:"failed",reason:"UNSUPPORTED_VERSION"}}}catch{return {value:ue(r.cfg,"BAD_KEY"),flag:{status:"failed",reason:"BAD_KEY"}}}let c;try{if(t.ct_ref){if(!e.ctUrl)return V(l),{value:ue(r.cfg,"DATA_UNAVAILABLE"),flag:{status:"failed",reason:"DATA_UNAVAILABLE"}};let p=await Wd.call(this,e.ctUrl);c=new Uint8Array(await p.arrayBuffer());}else c=K(t.ct);}catch{return V(l),{value:ue(r.cfg,"DATA_UNAVAILABLE"),flag:{status:"failed",reason:"DATA_UNAVAILABLE"}}}let u,f;try{f=await we(l),u=await Ee(f,K(t.iv),c,a);}catch{return V(l),{value:ue(r.cfg,"CORRUPT"),flag:{status:"failed",reason:"CORRUPT"}}}let d;try{d=JSON.parse(It(u));}catch{return V(u),V(l),{value:ue(r.cfg,"CORRUPT"),flag:{status:"failed",reason:"CORRUPT"}}}if(V(u),e.record_id){let p=r.dek.get(e.record_id);p?(p.bytes=l,p.key=f,p.recipients=t.k,p.anch=t.anch,p.uid=t.uid,p.own=t.own,p.access_group="private",p.ctRef=t.ct_ref||""):r.dek.set(e.record_id,{bytes:l,key:f,recipients:t.k,anch:t.anch,uid:t.uid,rid:e.record_id,own:t.own,access_group:"private",ctRef:t.ct_ref||""});}else V(l);return {value:d,flag:{status:"encrypted",recipients:Object.keys(t.k)}}}function Ot(t,e){let[r,n]=t.split("/");return G(`${ce}|kek|${r}|${n}|${e}`)}function Ft(t,e,r,n){let[i,s]=t.split("/");return G(`${ce}|mk|${i}|${s}|${e}|PBKDF2-SHA256|${r}|${n}`)}function so(t,e){let[r,n]=t.split("/");return G(`${ce}|recovery|${r}|${n}|${e}`)}function oo(t,e,r){let[n,i]=t.split("/");return G(`${ce}|rk|${n}|${i}|${e}|HKDF-SHA256|${r}`)}function ao(t,e){let[r,n]=t.split("/");return G(`${ce}|self|${r}|${n}|${e}`)}function co(t,e){let[r,n]=t.split("/");return G(`${ce}|ik|${r}|${n}|${e}`)}async function Ir(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 Jn(t,e,r){let n=le(xt),i=Ms(n),s=le(16),o=$(s),a=await Mn(n,s,so(t,e)),l=await _e(a,r,oo(t,e,o));return V(n),{code:i,wrap:{id:$(le(6)),p:"recovery",kdf:{a:"HKDF-SHA256",s:o},iv:$(l.iv),ct:$(l.ct),created:Date.now()}}}async function Jd(t,e,r,n){let i=qs(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 Mn(i,K(o.kdf.s),so(t,e)),l=await Ee(a,K(o.iv),K(o.ct),oo(t,e,o.kdf.s));return V(i),l}catch{}return V(i),null}async function Yd(t,e,r,n,i){let s=le(16),o=$(s),a=await gt(n,s,t.cfg.iterations,Ot(e,r)),l=await _e(a,i,Ft(e,r,t.cfg.iterations,o));return {id:$(le(6)),p:"password",kdf:{a:"PBKDF2-SHA256",it:t.cfg.iterations,s:o},iv:$(l.iv),ct:$(l.ct),created:Date.now()}}async function zd(t,e){let r=this.user.user_id,n=t.scope,i=le(16),s=$(i),o=await gt(e,i,t.cfg.iterations,Ot(n,r)),a=le(32),l=await _e(o,a,Ft(n,r,t.cfg.iterations,s)),c=await we(a),u=await Ds(),f=await _e(c,u.pkcs8,co(n,r));V(u.pkcs8);let d=null;t.cfg.recovery==="code"&&(d=await Jn(n,r,a));let p=await _e(c,a,ao(n,r));V(a);let g=await Fn(u.pubRaw),m=Date.now(),y=[{id:$(le(6)),p:"password",kdf:{a:"PBKDF2-SHA256",it:t.cfg.iterations,s},iv:$(l.iv),ct:$(l.ct),created:m}];d&&y.push(d.wrap);let w={v:1,alg:"ECDH-P-256",user_id:r,wraps:y,ik:{iv:$(f.iv),ct:$(f.ct)},self:{iv:$(p.iv),ct:$(p.ct)},pub:$(u.pubRaw),fpr:g,pins:null,created:m,updated:m};await this.postRecord({v:1,alg:"ECDH-P-256",user_id:r,pub:$(u.pubRaw),fpr:g,created:m},{table:{name:t.cfg.table,access_group:"authorized"},index:{name:"pubkey",value:r}});let _=await this.postRecord(w,{table:{name:t.cfg.table,access_group:"private"}}),A=await Ir.call(this,t);if(A&&A.record_id!==_.record_id){await lo.call(this,t,A,e);return}t.mk=c,t.ikPriv=u.priv,t.pubRaw=u.pubRaw,t.fpr=g,t.keyringRecordId=_.record_id,d&&(t.pendingRecoveryCode=d.code),t.user_id=r,t.pins={},t.status="unlocked",t.reason="";}async function lo(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 h("The encryption keyring does not belong to this user.",{code:"ENCRYPTION_KEYRING_CORRUPT"});let a=(Array.isArray(s?.wraps)?s.wraps:[]).filter(u=>u.p==="password");if(!a.length)throw new h("The keyring has no password wrap.",{code:"ENCRYPTION_KEYRING_CORRUPT"});a.sort((u,f)=>(f.created||0)-(u.created||0));let l=null;for(let u of a)try{let f=K(u.kdf.s),d=await gt(r,f,u.kdf.it,Ot(i,n));l=await Ee(d,K(u.iv),K(u.ct),Ft(i,n,u.kdf.it,u.kdf.s));break}catch{}if(!l)throw new h("Incorrect password: the encryption keyring could not be opened.",{code:"ENCRYPTION_BAD_PASSWORD"});let c=await we(l);V(l),await Yn.call(this,t,e,c);}async function Yn(t,e,r){let n=this.user.user_id,i=e.data,s=await Ee(r,K(i.ik.iv),K(i.ik.ct),co(t.scope,n)),o=await On(s);V(s);let a={};if(i.pins&&typeof i.pins=="object"&&i.pins.ct)try{let l=await Ee(r,K(i.pins.iv),K(i.pins.ct),G(`${ce}|pins|${t.scope}|${n}`));a=JSON.parse(It(l)),V(l);}catch{a={};}t.mk=r,t.ikPriv=o,t.pubRaw=K(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 Pr(t){let e=q.call(this);if(!e||!this.user?.user_id)return;if(!Nn()){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=mt.call(this);let r=await Ir.call(this,e);r?await lo.call(this,e,r,t):await zd.call(this,e,t),e.cfg.persistDevice&&await go.call(this,e).catch(()=>{});}async function uo(t){await this.__connection;let e=q.call(this);if(!e)throw new h("Encryption is not enabled for this instance.",{code:"INVALID_REQUEST"});if(!this.user?.user_id)throw new h("User login is required.",{code:"INVALID_REQUEST"});if(!t?.password||typeof t.password!="string")throw new h('"password" is required.',{code:"INVALID_PARAMETER"});if(await Pr.call(this,t.password),e.status!=="unlocked")throw new h(`Encryption could not be unlocked: ${e.reason}`,{code:"ENCRYPTION_LOCKED"});return {status:e.status}}async function fo(t){let e=q.call(this);return e?(t?.forgetDevice&&await Zn.call(this,e).catch(()=>{}),$n.call(this),this.__cached_requests={},{status:e.status}):{status:"disabled"}}async function ho(t,e){let r=q.call(this);if(!r)return;if(r.status!=="unlocked"||!r.mk)throw new h("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 h("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 l=null;for(let m of a)try{let y=await gt(t,K(m.kdf.s),m.kdf.it,Ot(r.scope,s));l=await Ee(y,K(m.iv),K(m.ct),Ft(r.scope,s,m.kdf.it,m.kdf.s));break}catch{}if(!l)throw new h("Incorrect current password: the encryption keyring was not re-wrapped.",{code:"ENCRYPTION_BAD_PASSWORD"});let c=le(16),u=$(c),f=await gt(e,c,r.cfg.iterations,Ot(r.scope,s)),d=await _e(f,l,Ft(r.scope,s,r.cfg.iterations,u));V(l);let p=Date.now(),g=(o.wraps||[]).concat([{id:$(le(6)),p:"password",kdf:{a:"PBKDF2-SHA256",it:r.cfg.iterations,s:u},iv:$(d.iv),ct:$(d.ct),created:p}]);await this.postRecord(Object.assign({},o,{wraps:g,updated:p}),{record_id:r.keyringRecordId});}async function po(){let t=q.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 zn(){return typeof indexedDB<"u"&&!!indexedDB}function Qn(){return new Promise((t,e)=>{let r=indexedDB.open($d,1);r.onupgradeneeded=()=>{let n=r.result;n.objectStoreNames.contains(je)||n.createObjectStore(je);},r.onsuccess=()=>t(r.result),r.onerror=()=>e(r.error);})}function Xn(t){return `${t.scope}#${this.user?.user_id}`}async function go(t){if(!zn()||!t.mk)return;let e=await Qn();await new Promise((r,n)=>{let i=e.transaction(je,"readwrite");i.objectStore(je).put({mk:t.mk,keyringRecordId:t.keyringRecordId,saved:Date.now()},Xn.call(this,t)),i.oncomplete=()=>r(),i.onerror=()=>n(i.error);}),e.close();}async function Qd(t){if(!zn())return null;let e=await Qn(),r=await new Promise((n,i)=>{let o=e.transaction(je,"readonly").objectStore(je).get(Xn.call(this,t));o.onsuccess=()=>n(o.result||null),o.onerror=()=>i(o.error);});return e.close(),r&&r.mk?r:null}async function Zn(t){if(!zn())return;let e=await Qn();await new Promise((r,n)=>{let i=e.transaction(je,"readwrite");i.objectStore(je).delete(Xn.call(this,t)),i.oncomplete=()=>r(),i.onerror=()=>n(i.error);}),e.close();}function mo(){let t=q.call(this);!t||t.ready||(t.unlocking=true,t.ready=Xd.bind(this)().catch(()=>false).then(()=>{t.unlocking=false;}));}async function Xd(){let t=q.call(this);if(!t||!this.user?.user_id||!t.cfg.persistDevice||!Nn())return false;t.scope=mt.call(this);try{let e=await Qd.call(this,t);if(!e)return !1;let r=await Ir.call(this,t);return r?(await Yn.call(this,t,r,e.mk),!0):(await Zn.call(this,t).catch(()=>{}),!1)}catch{return t.status="locked",t.reason="NO_SESSION_KEY",false}}async function ei(t){let e=q.call(this);if(!e)throw new h("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 c=((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(!c.length)return null;c.sort((p,g)=>g.uploaded-p.uploaded);let u=K(c[0].data.pub),f=await Fn(u),d=e.pins[s];if(d&&d!==f)throw new h(`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(!d){if(e.cfg.trustPolicy==="strict")throw new h(`No pinned key for user "${s}" and trustPolicy is "strict". Pin it first with pinPeerKey().`,{code:"ENCRYPTION_PEER_NOT_PINNED"});e.pins[s]=f,i=true;}return {pubRaw:u,fpr:f}})().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 wo.call(this,e).catch(()=>{}),r}async function yo(t,e){let r=mt.call(this),n=t.dek.get(e);if(n)return {entry:n,scope:r};let i=await Ke.call(this,e);if(!i)throw new h(`Record "${e}" not found.`,{code:"NOT_EXISTS"});if(i.encrypted?.status==="failed"&&i.encrypted.reason==="DATA_UNAVAILABLE")throw new h(`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 h("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 h(`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 ti(t,e){let r=q.call(this);if(!r)return;let n=await yo.call(this,r,t);if(!n)return;let{entry:i,scope:s}=n,o=this.user.user_id;if(i.own!==o)throw new h("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 ei.call(this,e),l=e.filter(d=>!a[d]);if(l.length)throw new h(`These users have no encryption key yet, so they cannot be given access: ${l.join(", ")}. A user's key is created the first time they log in with encryption enabled.`,{code:"ENCRYPTION_RECIPIENT_HAS_NO_KEY"});let c=jn(i),u=Kn(s,i.own,i.anch,c),f=Object.assign({},i.recipients);for(let d of e)d!==o&&(f[d]=await no.call(this,i.bytes,a[d],s,c,i.own,d,u));await ef.call(this,r,t,i,f);}async function _o(t,e){let r=q.call(this);if(!r)return;let n=await yo.call(this,r,t);if(!n)return;let{entry:i}=n,s=this.user.user_id;if(i.own!==s)throw new h("Only the record owner can revoke access to an encrypted record.",{code:"ENCRYPTION_GRANT_REQUIRES_OWNER"});let o=Object.keys(i.recipients).filter(c=>c===s?true:e?!e.includes(c):false).filter(c=>c!==s),a=await Ke.call(this,t);if(!a)throw new h(`Record "${t}" not found.`,{code:"NOT_EXISTS"});Zd(a,t);let l={};if(o.length){l=await ei.call(this,o);let c=o.filter(u=>!l[u]);if(c.length)throw new h(`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: ${c.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 ti.call(this,a.record_id||t,o);}function Zd(t,e){if(t?.encrypted?.status==="failed")throw new h(`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 ef(t,e,r,n){let i=await tf.call(this,e);if(!i)throw new h(`Cannot change sharing on record "${e}": its stored envelope could not be read.`,{code:"ENCRYPTION_DATA_UNAVAILABLE"});r.recipients=n,t.dek.set(e,r);let s=Object.assign({},i,{k:n});t.passthrough.set(e,s),await this.postRecord(void 0,{record_id:e});}async function tf(t){let e=q.call(this);if(!e)return null;e.rawRead=true;let r;try{r=(await this.getRecords({record_id:t},{limit:1}))?.list?.[0];}finally{e.rawRead=false;}return r&&Tr(r.data)?r.data:null}async function bo(t){let e=q.call(this);if(!e||e.status!=="unlocked")throw new h("Encryption is locked.",{code:"ENCRYPTION_LOCKED"});e.pins[t.user_id]=t.fingerprint,e.peerPub.delete(t.user_id),await wo.call(this,e);}async function wo(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 _e(t.mk,G(JSON.stringify(t.pins)),G(`${ce}|pins|${t.scope}|${t.user_id}`));await this.postRecord(Object.assign({},r.data,{pins:{iv:$(n.iv),ct:$(n.ct)},updated:Date.now()}),{record_id:t.keyringRecordId});}function Eo(){let t=q.call(this);if(!t||!t.pendingRecoveryCode)return null;let e=t.pendingRecoveryCode;return t.pendingRecoveryCode="",e}async function Ao(t){await this.__connection;let e=q.call(this);if(!e)throw new h("Encryption is not enabled for this instance.",{code:"INVALID_REQUEST"});if(!this.user?.user_id)throw new h("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 h('"code" is required.',{code:"INVALID_PARAMETER"});e.scope=mt.call(this);let r=this.user.user_id,n=await Ir.call(this,e);if(!n)throw new h("This account has no encryption keyring, so there is nothing to recover.",{code:"NOT_EXISTS"});let i=await Jd(e.scope,r,n.data?.wraps||[],t.code);if(!i)throw new h("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 we(i);await Yn.call(this,e,n,s);let o=false,a=null,l=(n.data?.wraps||[]).slice();if(t.password&&(l=l.filter(c=>c.p!=="password"),l.push(await Yd(e,e.scope,r,t.password,i)),o=true),e.cfg.recovery==="code"){let c=await Jn(e.scope,r,i);l=l.filter(u=>u.p!=="recovery"),l.push(c.wrap),a=c.code;}return V(i),await this.postRecord(Object.assign({},n.data,{wraps:l,updated:Date.now()}),{record_id:n.record_id}),e.cfg.persistDevice&&await go.call(this,e).catch(()=>{}),{status:e.status,repaired:o,recoveryCode:a}}async function So(){await this.__connection;let t=q.call(this);if(!t)throw new h("Encryption is not enabled for this instance.",{code:"INVALID_REQUEST"});if(t.status!=="unlocked"||!t.mk)throw new h("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 h('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 h("The encryption keyring could not be read.",{code:"ENCRYPTION_KEYRING_CORRUPT"});let n=r.data?.self;if(!n||!n.ct)throw new h("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 Ee(t.mk,K(n.iv),K(n.ct),ao(t.scope,t.user_id)),s=await Jn(t.scope,t.user_id,i);V(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 Rr="__skenc__",vo="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";function rf(t){if(t===0)return "0";let e="";for(;t>0;)e=vo[t%62]+e,t=Math.floor(t/62);return e}function nf(t){let e=0;for(let r of t){let n=vo.indexOf(r);if(n<0)return NaN;e=e*62+n;}return e}function Ur(t){if(typeof t!="string")return null;let e=t.lastIndexOf(Rr);if(e<0)return null;let r=nf(t.slice(e+Rr.length));return Number.isFinite(r)?{key:t.slice(0,e),plainSize:r}:null}function ri(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=Ur(e[10]);return r?{recordId:e[5],recordOwner:e[3],filename:e[e.length-1],plainSize:r.plainSize}:null}catch{return null}}function Ro(t,e){return {service:this.service,owner:this.owner,recordOwner:e,recordId:t}}async function To(t,e,r){let n=q.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(Ur(e))throw new h(`"${Rr}" is reserved in an upload form key.`,{code:"INVALID_PARAMETER"});if(e===Lt)return {key:e,file:r,encrypted:false};let s=new Uint8Array(await r.arrayBuffer()),o={n:r.name,t:r.type||"",lm:r.lastModified||0},a=await Hs(i.bytes,s,Ro.call(this,t,i.own),o);return V(s),{key:`${e}${Rr}${rf(r.size)}`,file:new File([a],r.name,{type:"application/octet-stream"}),encrypted:true}}async function Io(t,e){let r=q.call(this),n=ri(t);if(!r||!n)return e;let i=r.dek.get(n.recordId);if(!i)throw new h(`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(!qn(s))throw new h("This file is marked as encrypted but its contents are not an encrypted container.",{code:"ENCRYPTION_FILE_CORRUPT"});let o=await Ws(i.bytes,s,Ro.call(this,n.recordId,n.recordOwner)),a=o.meta&&o.meta.t||"application/octet-stream";return new Blob([o.bytes],{type:a})}function sf(t){let e=[];for(let r in t?.bin||{})for(let n of t.bin[r]||[])n&&n.encrypted&&e.push({formKey:r,url:n.url,filename:n.filename});return e}function of(t){let e=[];for(let r in t?.bin||{})for(let n of t.bin[r]||[])n&&!n.encrypted&&e.push({formKey:r,url:n.url,filename:n.filename});return e}async function ni(t,e,r){let n=q.call(this);if(!n)return [];let i=await Ke.call(this,t);if(!i)return [];let s=e==="decrypt"?sf(i):of(i);if(!s.length)return [];let o=[],a=new FormData,l=false;for(let c of s){let u=i.bin[c.formKey].find(d=>d.url===c.url);if(!u||typeof u.getFile!="function")continue;let f=await u.getFile("blob");f&&(a.append(c.formKey,new File([f],c.filename,{type:f.type||"application/octet-stream"})),o.push(c.url),l=true);}if(!l)return [];if(e==="decrypt"){let c=n.dek.get(t);c&&(V(c.bytes),n.dek.delete(t));}return await this.uploadFiles(a,{record_id:t,progress:r}),o}var H=null;function ii(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=be(i[2].slice(0,-4));}}else e[n]?r[e[n]]=t[n]:r[n]=t[n];return r}async function Uo(t){if(!t.ticket_id)throw new h("Ticket ID is required.",{code:"INVALID_PARAMETER"});if(!t.method)throw new h('Method is required. Should be either "GET" or "POST"',{code:"INVALID_PARAMETER"});let e=t.ticket_id;await this.__connection;let r=await T.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 ii(r)}async function xo(t,e){await this.__connection;let r=await T.bind(this)("ticket",Object.assign({exec:"list"},t||{}),{auth:true,fetchOptions:e});return r.list=r.list.map(ii),r}async function Co(t,e){await this.__connection;let r=await T.bind(this)("ticket",Object.assign({exec:"consumed"},t||{}),{auth:true,fetchOptions:e});return r.list=r.list.map(ii),r}async function ko(t){return T.bind(this)("register-ticket",Object.assign({exec:"reg"},t),{auth:true})}async function Do(t){return T.bind(this)("register-ticket",Object.assign({exec:"unreg"},t),{auth:true})}var af=3600;async function yt(){if(await this.__connection,this.session){let t=Math.floor(Date.now()/1e3),r=this.session.getIdToken().getExpiration();if(r<t+af){this.log("request:requesting new token",null);try{await ne.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 h("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),Me.bind(this)(),new h("User login is required.",{code:"INVALID_REQUEST"})}function Po(t,e){return new Promise((r,n)=>{e.refreshSession(t.getRefreshToken(),(i,s)=>{this.log("getSession:refreshSessionCallback",{refreshErr:i,refreshedSession:s}),i?(Me.bind(this)(),n(i)):s.isValid()?r(s):(Me.bind(this)(),n(new h("Invalid session.",{code:"INVALID_REQUEST"})));});})}function ne(){if(!this.userPool)throw new h("User pool is missing",{code:"INVALID_REQUEST"});let t=()=>{let s=H.getSignInUserSession().getIdToken().payload||null,o=Tt(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:l=false,skipUserUpdateEventTrigger:c=false}=s||{};if(l&&c&&(c=false),H=this.userPool.getCurrentUser(),!H){this.log("getSession:cognitoUser",H),Me.bind(this)(),a(null);return}let u=f=>{let d=f.getIdToken().payload;if(this.log("getSession:respond:sessionAttribute",d),d["custom:service"]!==this.service)throw this.log("getSession:respond","invalid service, signing out"),Me.bind(this)(),new h("Invalid session.",{code:"INVALID_REQUEST"});return this.session=f,t(),c||this._runOnUserUpdateListeners(this.user),this.session};H.getSession((f,d)=>{if(this.log("getSession:getSessionCallback",{err:f,session:d}),!d){Me.bind(this)(),a(new h("Current session does not exist.",{code:"INVALID_REQUEST"}));return}if(f){Po.bind(this)(d,H).then(w=>o(u(w))).catch(a);return}let p=Math.floor(Date.now()/1e3),g=d.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||l||!d.isValid())Po.bind(this)(d,H).then(w=>o(u(w))).catch(a);else try{o(u(d));}catch(w){a(w);}});}),r=(s,o)=>{let a=o||s.includes(this.service+"-")?s:this.service+"-"+X.hash(s);return {cognitoUser:new Fe({Username:a,Pool:this.userPool}),cognitoUsername:a}};return {getSession:e,authenticateUser:(s,o,a=false,l=false)=>new Promise((c,u)=>{this.__request_signup_confirmation=null,this.__disabledAccount=null;let f=r(s,a),d=f.cognitoUsername,p=new Gr({Username:d,Password:o});f.cognitoUser.authenticateUser(p,{newPasswordRequired:(g,m)=>{this.__disabledAccount=null,this.__request_signup_confirmation=d,g["custom:signup_ticket"]==="PASS"||g["custom:signup_ticket"]==="MEMBER"||g["custom:signup_ticket"]==="OIDPASS"?f.cognitoUser.completeNewPasswordChallenge(o,{},{onSuccess:y=>{H=f.cognitoUser,e().then(async w=>{if(q.call(this))try{await Pr.bind(this)(o);}catch(_){this.log("encryption:ensureKeyring:failed",_);}c(this.user);});},onFailure:y=>{u(new h(y.message||"Failed to authenticate user.",{code:y.code}));}}):u(new h("User's signup confirmation is required.",{code:"SIGNUP_CONFIRMATION_NEEDED"}));},onSuccess:g=>e({skipUserUpdateEventTrigger:true}).then(async m=>{if(this.__disabledAccount=null,q.call(this))try{await Pr.bind(this)(o);}catch(y){this.log("encryption:ensureKeyring:failed",y);}this._runOnLoginListeners(this.user),this._runOnUserUpdateListeners(this.user),c(this.user);}),onFailure:g=>{let m=[],{parsed:y,code:w}=xr(g),_=typeof g?.message=="string"?g.message:"";if(w==="NotAuthorizedException"?_.includes("User is disabled.")?(this.__disabledAccount=d,m=["This account is disabled.","USER_IS_DISABLED"]):l?m=["The account already exists.","ACCOUNT_EXISTS"]:m=["Incorrect username or password.","INCORRECT_USERNAME_OR_PASSWORD"]:w==="UserNotFoundException"?m=["Incorrect username or password.","INCORRECT_USERNAME_OR_PASSWORD"]:w==="UserNotConfirmedException"?(this.__request_signup_confirmation=d,m=["User's signup confirmation is required.","SIGNUP_CONFIRMATION_NEEDED"]):(w==="TooManyRequestsException"||w==="LimitExceededException")&&(m=["Too many attempts. Please try again later.","REQUEST_EXCEED"]),y.code==="SIGNUP_CONFIRMATION_NEEDED"&&(this.__request_signup_confirmation=d),m.length){let A=m[1],U=m[0];u(new h(U,{code:A,cause:g}));}else u(y);}});}),createCognitoUser:r,signup:(s,o,a)=>new Promise((l,c)=>{this.userPool.signUp(s,o,a,null,(u,f)=>{if(u){let{parsed:d,code:p}=xr(u),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=[d.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=[d.message||"Signup validation failed.","INVALID_REQUEST"]),g.length?c(new h(g[0],{code:g[1],cause:u})):c(d);return}l(f);});})}}function xr(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 h(o,{code:s,cause:t}),code:e}}async function No(t){await this.__authConnection;let e=t?.refreshToken||false;if(!e)return this.user;try{return await ne.bind(this)().getSession(Object.assign({skipUserUpdateEventTrigger:!e,refreshToken:e},t)),this.user}catch{return null}}async function Oo(t){await this.__connection,t=b.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 h('"merge" array items should be type: <string>.',{code:"INVALID_PARAMETER"})}if(typeof o!="boolean"&&!Array.isArray(o))throw new h('"merge" should be type: <boolean | string[]>.',{code:"INVALID_PARAMETER"});return o},template:o=>{if(typeof o!="object"||o===null)throw new h('"template" should be type: <object>.',{code:"INVALID_PARAMETER"});if(o.welcome!==void 0&&(typeof o.welcome!="string"||!o.welcome))throw new h('"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 T.bind(this)("openid-logger",e),n=r.logger.split("#"),i=this.service+"-"+n[0],s=n[1];return {userProfile:await ne.bind(this)().authenticateUser(i,s,true,true),openid:r.openid}}function cf(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 lf(t){let e=t.split(".");if(e.length!==3)throw new Error("Invalid JWT format");let n=e[1].replace(/-/g,"+").replace(/_/g,"/"),i=cf(n);return JSON.parse(i)}async function Fo(t){await this.__authConnection,this.log("loginWithToken:params",t),t=b.Params(t,{idToken:"string",accessToken:"string",refreshToken:"string"},["idToken"]);let e=lf(t.idToken);if(this.log("loginWithToken:idTokenPayload",e),e["custom:service"]!==this.service)throw new h("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 h("Token has expired.",{code:"INVALID_REQUEST"});if(this.__user=Tt(e),this.session=null,t.accessToken&&t.refreshToken)try{if(this.session=new dt({IdToken:new lt({IdToken:t.idToken}),AccessToken:new ct({AccessToken:t.accessToken}),RefreshToken:new ut({RefreshToken:t.refreshToken})}),this.log("loginWithToken:session",this.session),this.log("loginWithToken:CognitoUser",Fe),this.log("loginWithToken:userPool",this.userPool),Fe&&this.userPool){this.log("loginWithToken:cognito:username",e["cognito:username"]);let n={Username:e["cognito:username"],Pool:this.userPool};this.log("loginWithToken:cognitoUserParams",n),H=new Fe(n),H.setSignInUserSession(this.session),this.log("loginWithToken:cognitoUserRestored",{cognitoUserType:typeof H,cognitoUserKeys:Object.keys(H||{}),cognitoUser:H});}}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 Z(){return await this.__connection,this.__user?.service===this.service?this.__user?.owner===this.host:(await Mt.bind(this)(),false)}async function Me(t=false){let e=null;H&&(t?e=new Promise((n,i)=>{H.globalSignOut({onSuccess:s=>{this.log("globalSignOut:success",s),n(s);},onFailure:s=>{this.log("globalSignOut:error",s),i(s);}});}):H.signOut()),$n.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 Mt(t){await this.__connection;let{data:e}=j(t);return await Me.bind(this)(e?.global),"SUCCESS: The user has been logged out."}async function Lo(){if(!this.__request_signup_confirmation)throw new h("Least one login attempt is required.",{code:"INVALID_REQUEST"});return await T.bind(this)("confirm-signup",{username:this.__request_signup_confirmation})}async function Mo(t=false){if(typeof t=="string")t=b.Url(t);else if(typeof t!="boolean")throw new h("Argument should be type: <boolean | string>.",{code:"INVALID_REQUEST"});if(!this.__disabledAccount)throw new h("Least one signin attempt of disabled account is required.",{code:"INVALID_REQUEST"});return await T.bind(this)("recover-account",{username:this.__disabledAccount,redirect:t}),"SUCCESS: Recovery e-mail has been sent."}async function si(t){let e=b.Params(t,{username:"string",email:"string",password:"string"},["password"]);if(await this.__authConnection,e.email)try{b.Email(e.email);}catch{e.username=e.email,delete e.email;}if(!e.username&&!e.email)throw new h('Least one of "username" or "email" is required.',{code:"INVALID_PARAMETER"});return await ne.bind(this)().authenticateUser(e.username||e.email,e.password)}async function qo(t,e){await this.__authConnection;let r={username:"string",password:c=>b.Password(c),email:c=>b.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?b.Birthdate(c):"",phone_number:c=>c?b.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?b.Url(c):"",profile:c=>c?b.Url(c):"",family_name:"string",given_name:"string",middle_name:"string",nickname:"string",website:c=>c?b.Url(c):""},n=b.Params(t||{},r,["email","password"]);await Mt.bind(this)(),e=b.Params(e||{},{email_subscription:c=>{if(typeof c!="boolean")throw new h('"option.email_subscription" should be type: <boolean>.',{code:"INVALID_PARAMETER"});if(!e?.signup_confirmation)throw new h('"option.signup_confirmation" is required for email subscription.',{code:"INVALID_PARAMETER"});return c},signup_confirmation:c=>{let u=c;if(typeof c=="string")u=b.Url(c);else if(typeof c=="boolean")u=c;else throw new h('"option.signup_confirmation" should be type: <string | boolean>.',{code:"INVALID_PARAMETER"});if(u&&!n.email)throw new h('"email" is required for signup confirmation.',{code:"INVALID_PARAMETER"});return u},login:c=>{if(typeof c=="boolean"){if(e.signup_confirmation&&c)throw new h('"login" is not allowed when "option.signup_confirmation" is true.',{code:"INVALID_PARAMETER"});return c}throw new h('"option.login" should be type: boolean.',{code:"INVALID_PARAMETER"})},template:c=>{if(typeof c!="object"||c===null)throw new h('"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 h('"option.template.signup_confirmation" should be a non-empty <string> (template message_id).',{code:"INVALID_PARAMETER"});if(!e?.signup_confirmation)throw new h('"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 h('"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 h('"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=ne.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(":"),l=[new Pe({Name:"custom:signup",Value:o[0]}),new Pe({Name:"locale",Value:a.split("#")[1]}),new Pe({Name:"custom:signup_ticket",Value:a})];for(let c in r){let u=["email_public","address_public","gender_public","birthdate_public","phone_number_public","misc","service","owner"];n[c]!==""&&(c==="username"||c==="password"||c==="access_group"||(u.includes(c)?l.push(new Pe({Name:"custom:"+c,Value:n[c]})):l.push(new Pe({Name:c,Value:n[c]}))));}return await ne.bind(this)().signup(s.cognitoUsername,n.password,l),n.signup_confirmation?(H=s.cognitoUser,this.__request_signup_confirmation=s.cognitoUsername,"SUCCESS: The account has been created. User's signup confirmation is required."):i?si.bind(this)({email:n.username||n.email,password:n.password}):"SUCCESS: The account has been created."}async function Vo(){await this.__connection;let t=await T.bind(this)("remove-account",{disable:this.__user.user_id},{auth:true});return await Mt.bind(this)(),t}async function Bo(t){await this.__connection;let e=b.Params(t,{email:i=>b.Email(i),code:["number","string"],new_password:i=>b.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)=>{ne.bind(this)().createCognitoUser(e.email).cognitoUser.confirmPassword(r,n,{onSuccess:a=>{i("SUCCESS: New password has been set.");},onFailure:a=>{s(new h(a?.message||"Failed to reset password.",{code:a?.code||"ERROR",cause:a}));}});})}async function $o(t,e,r){await this.__connection;let n;if(!H)throw new h("The user has to be logged in.",{code:"INVALID_REQUEST"});if(t==="email"||t==="phone_number"){if(!this.__user.hasOwnProperty(t))throw new h(`No ${t==="email"?"e-mail":"phone number"} to verify`,{code:"INVALID_REQUEST"});if(this.__user?.[`${t}_verified`])return `SUCCESS: "${t}" is verified.`;n=(e?b.Params(e,{code:"string"}):{}).code||"";}else return;let i,s=r?.template?.verification;if(s!==void 0){if(typeof s!="string"||!s)throw new h('"template.verification" should be a non-empty <string> (template message_id).',{code:"INVALID_PARAMETER"});i={template_verification:s};}return new Promise((o,a)=>{let l={onSuccess:c=>{n?ne.bind(this)().getSession({refreshToken:true}).then(()=>{this.__user&&(this.__user[t+"_verified"]=true),o(`SUCCESS: "${t}" is verified.`);}).catch(u=>{a(u);}):o("SUCCESS: Verification code has been sent.");},onFailure:c=>{a(new h(c.message||"Failed to request verification code.",{code:c?.code}));}};n?H?.verifyAttribute(t,n,l):(l.inputVerificationCode=null,H?.getAttributeVerificationCode(t,l,i));})}function Ko(t,e){return $o.bind(this)("phone_number",t,e)}function jo(t,e){return $o.bind(this)("email",t,e)}async function Ho(t,e){await this.__connection;let r=b.Params(t,{email:s=>b.Email(s)},["email"]),n,i=e?.template?.verification;if(i!==void 0){if(typeof i!="string"||!i)throw new h('"template.verification" should be a non-empty <string> (template message_id).',{code:"INVALID_PARAMETER"});n={template_verification:i};}return new Promise(async(s,o)=>{ne.bind(this)().createCognitoUser(r.email).cognitoUser.forgotPassword({onSuccess:l=>{s("SUCCESS: Verification code has been sent.");},onFailure:l=>{let{parsed:c,code:u}=xr(l),f={UserNotFoundException:"NOT_EXISTS",InvalidParameterException:"INVALID_PARAMETER",NotAuthorizedException:"INVALID_REQUEST",LimitExceededException:"REQUEST_EXCEED",TooManyRequestsException:"REQUEST_EXCEED",CodeDeliveryFailureException:"CODE_DELIVERY_FAILURE"}[u]||c.code||u||"ERROR";o(new h(c.message,{code:f,cause:l}));}},n);})}async function Wo(t){if(await this.__connection,!this.session)throw new h("User login is required.",{code:"INVALID_REQUEST"});let e=b.Params(t,{current_password:"string",new_password:"string"});if(!e?.current_password)throw new h('"current_password" is required to change password.',{code:"INVALID_PARAMETER"});if(!e?.new_password)throw new h('"new_password" is required to change password.',{code:"INVALID_PARAMETER"});return b.Password(e.current_password),b.Password(e.new_password),q.call(this)&&await ho.bind(this)(e.current_password,e.new_password),new Promise((r,n)=>{H.changePassword(e.current_password,e.new_password,(i,s)=>{if(i){if(i?.code==="InvalidParameterException")n(new h("Invalid password parameter.",{code:"INVALID_PARAMETER"}));else if(i?.code==="NotAuthorizedException")n(new h("Incorrect password.",{code:"INVALID_REQUEST"}));else if(i?.code==="TooManyRequestsException"||i?.code==="LimitExceededException")n(new h("Too many attempts. Please try again later.",{code:"REQUEST_EXCEED"}));else {let{parsed:o}=xr(i);n(o);}return}q.call(this)&&po.bind(this)().catch(o=>this.log("encryption:prune:failed",o)),r("SUCCESS: Password has been changed.");});})}async function Go(t){if(await this.__connection,!this.session)throw new h("User login is required.",{code:"INVALID_REQUEST"});let e=b.Params(t||{},{user_id:i=>b.UserId(i),email:i=>b.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?b.Birthdate(i):"",phone_number:i=>i?b.PhoneNumber(i):"",email_public:"boolean",phone_number_public:"boolean",address_public:"boolean",gender_public:"boolean",birthdate_public:"boolean",misc:"string",picture:i=>i?b.Url(i):"",profile:i=>i?b.Url(i):"",family_name:"string",given_name:"string",middle_name:"string",nickname:"string",website:i=>i?b.Url(i):""});if(e&&typeof e=="object"&&!Object.keys(e).length)return this.user;e.email&&(e.preferred_username=this.service+"-"+X.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 h(`${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 Pe({Name:s,Value:e[s]}));return await new Promise((s,o)=>{H?.updateAttributes(i,(a,l)=>{a&&o([a?.code||a?.name,a?.message||"Failed to update user settings."]),s(l);});}),await ne.bind(this)().getSession({refreshToken:true}),this.user}return this.user}async function Jo(t,e){t=j(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=>b.UserId(s)):b.UserId(i),email:"string",phone_number:"string",locale:i=>{if(typeof i!="string"||typeof i=="string"&&i.length>5)throw new h('Value of "locale" should be a country code.',{code:"INVALID_PARAMETER"});return i},name:"string",address:"string",gender:"string",birthdate:i=>b.Birthdate(i),subscribers:"number",timestamp:"number",access_group:"number",approved:"string"},n=["searchFor","value"];if(t=b.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 h(`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 h(`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 h("Conditions does not apply on range search.",{code:"INVALID_PARAMETER"});if(t.searchFor==="user_id"&&(t.condition!=="="||t.range))throw new h(`Conditions are not allowed on "${t.searchFor}"`,{code:"INVALID_PARAMETER"});if(typeof t?.value=="string"&&!t?.value)throw new h("Value should not be an empty string.",{code:"INVALID_PARAMETER"});if(typeof t?.searchFor=="string"&&!t?.searchFor)throw new h('"searchFor" should not be an empty string.',{code:"INVALID_PARAMETER"});return T.bind(this)("get-users",t,{auth:true,fetchOptions:e})}async function Yo(t){await this.__connection;let e=await T.bind(this)("last-verified-email",t,{auth:true});return e.includes("SUCCESS")?(await ne.bind(this)().getSession({refreshToken:true}),this.user):e}async function zo(t){return await this.__connection,t=b.Params(t,{username:b.Email,redirect:b.Url},["username"]),await T.bind(this)("request-username-change",t,{auth:true})}var uf="1.2.1",df=class{constructor(t){Re(this,"version",uf);Re(this,"items",[]);Re(this,"nextJobId",1);Re(this,"breakWhenError",false);Re(this,"batchSize",1);Re(this,"onProgress");Re(this,"activeCount",0);Re(this,"currentCycleCompleted",[]);Re(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=[];}},qt=df;var _t=null,Xo=typeof SubmitEvent<"u",ff=typeof HTMLFormElement<"u",Bt=ae(),oi=0;function Zo(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 ai(t,e){return e>0?t/e*100:0}var Qo=t=>{let{auth:e,type:r,endpoints:n,stable:i}=t,s=n[0],o=n[1];if(oi++,r==="admin"){let a=Object.entries(s).filter(([l,c])=>l.includes(e?"_private":"_public")&&l!=="get_users_private"&&l!=="service_public"&&typeof c=="string").map(([,l])=>l);if(!a.length)throw new h("No available admin gateways.",{code:"INVALID_REQUEST"});return a[oi%a.length]}if(r==="record"){let a=Object.entries(o).filter(([l,c])=>l.includes(e?"record_private":"record_public")&&typeof c=="string").map(([,l])=>l);if(!a.length)throw new h("No available record gateways.",{code:"INVALID_REQUEST"});return i?a[0]:a[oi%a.length]}throw new h("Invalid gateway type.",{code:"INVALID_REQUEST"})};async function hf(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 "delete-newsletter-group":case "newsletter-group-endpoint":case "invitation-list":case "csr":case "csr-poll":case "csr-cancel":case "csr-finalize":return Qo.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 "grid-query":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 Qo.bind(this)({auth:e,type:"record",endpoints:n,stable:r})+t+a;default:return b.Url(t)+a}}var Vt={};function ea(){_t&&(_t.terminate(),_t=null);}async function T(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,l=e?.service||this.service,c=e?.owner||this.owner,u=null,f=await hf.bind(this)(t,!!i,!!r.stableGateway);if(!o&&(a=await this.__connection,!a))throw new h("Invalid connection. The service could have been disabled, or has a restricted CORS.",{code:"INVALID_REQUEST"});let d=r?.tokenHeaders?.idToken===true;(i||d)&&(u=await yt.bind(this)());let p={},{fetchMore:g=false,progress:m}=r?.fetchOptions||{};if(r?.fetchOptions&&Object.keys(r.fetchOptions).length){for(let x of ["limit","startKey","ascending"])if(r.fetchOptions.hasOwnProperty(x)){if(x==="startKey"&&r.fetchOptions[x]===null)continue;p[x]=r.fetchOptions[x];}p=b.Params(p,{limit:x=>{if(typeof x!="number")throw new h("Fetch limit should be a number.",{code:"INVALID_REQUEST"});if(x>1e3)throw new h("Fetch limit should be below 1000.",{code:"INVALID_REQUEST"});return x},startKey:x=>x,ascending:"boolean"});}let y=n?.ignoreService?{}:{service:l,owner:c};Object.assign(y,p),e=j(e).data,e?e&&typeof e=="object"&&(e=Object.assign(y,e)):e=y;let w=`${s}:${i?"auth":"public"}:${t}`,_=(()=>{if(e&&typeof e=="object"&&Object.keys(e).length&&!(Bt&&e instanceof FormData)){let x=function(C){return typeof C=="object"&&C!==null?Object.keys(C).sort().reduce((L,B)=>(typeof C[B]=="object"&&C[B]!==null?L[B]=x(C[B]):L[B]=C[B],L),{}):C};return X.hash(w+"/"+JSON.stringify(x(e)))}return X.hash(w+"/"+l)})(),{requestKey:A,requestKeyWithStartKey:U}=pf.bind(this)({params:e,url:t,fetchMore:g,hashedParams:_});if(!A||A&&typeof A=="object")return A;if(this.log("requestKey",U),typeof U=="string"&&Vt[U]instanceof Promise)return this.log("request:returning pending",U),Vt[U];let S={Accept:"*/*"};if(Object.prototype.hasOwnProperty.call(r,"contentType")&&r.contentType!==void 0){let x=r.contentType===null?"application/x-www-form-urlencoded":r.contentType;x&&(S["Content-Type"]=x);}else S["Content-Type"]="application/json";if(u&&(S.Authorization=u),r?.tokenHeaders){let x=(B,ee)=>typeof B=="string"?B:B===true?ee:null,C=x(r.tokenHeaders.accessToken,this.session?.accessToken?.jwtToken||null),L=x(r.tokenHeaders.idToken,this.bearerToken||this.session?.idToken?.jwtToken||u||null);C&&(S["X-Access-Token"]=C),L&&(S["X-Id-Token"]=L);}let O={public_identifier:this.__public_identifier,service:l,owner:c};S["Content-Meta"]=JSON.stringify(O),r.revalidate&&(S["Cache-Control"]="no-cache",S.Pragma="no-cache");let k={headers:S};if(r?.responseType&&(k.responseType=r.responseType),s==="GET"){if(e){let x=[];if(Bt&&e instanceof FormData?x=Array.from(e.entries()).map(([C,L])=>{let B=typeof L=="string"?L:L.name;return encodeURIComponent(C)+"="+encodeURIComponent(B)}):x=Object.keys(e).map(C=>{let L=e[C];return typeof L!="string"&&(L=JSON.stringify(L)),encodeURIComponent(C)+"="+encodeURIComponent(L)}),x.length){let C=f.includes("?")?f.endsWith("?")||f.endsWith("&")?"":"&":"?";f+=C+x.join("&");}}k.body=null;}else if(Bt&&e instanceof FormData)k.body=e;else if(S["Content-Type"]==="application/x-www-form-urlencoded"&&e&&typeof e=="object"){let x=new URLSearchParams;for(let C of Object.keys(e)){let L=e[C];x.append(C,typeof L=="string"?L:JSON.stringify(L));}k.body=x.toString();}else typeof e=="string"?k.body=e:k.body=e?JSON.stringify(e):null;if(k.method=s,_t===null){let x={batchSize:this.requestBatchSize,breakWhenError:false,onProgress:C=>{this.onBatchProcess.forEach(L=>L(C));}};_t=new qt(x);}return this.log("request-opt",k),new Promise((x,C)=>{_t.add([async()=>{let L=ta.bind(this)(f,k,m);Vt[U]=L;try{let B=mf.bind(this)({hashedParam:A,requestKeyWithStartKey:U,url:t,fetched:await L});return delete Vt[U],this.log("request:end",B),x(B),B}catch(B){throw delete Vt[U],this.log("request:err",B),C(B),B}}]);})}function pf(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 h(`"${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 l of this.__startKeyHistory[r][i]){let c=i+X.hash(l);this.__cached_requests?.[r]&&this.__cached_requests?.[r]?.[c]&&delete this.__cached_requests[r][c];}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+=X.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 gf(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 ta(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"),l=Zo(a);l!==null?setTimeout(()=>{ta(t,e,r).then(n,i);},l):i("Too many requests");}else {let a=s.status,l=["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 u=c.split(":"),f=u.splice(0,1)[0].trim(),d=u.join(":").trim();i(new h(d||c,{code:l.includes(f)?f:"ERROR"}));}else if(typeof c=="object"&&c?.message){let u=c?.code||(a?a.toString():null)||"ERROR",f=c.message,d=c?.cause;typeof f=="string"&&(f=f.trim()),i(new h(f,{cause:d,code:u}));}else i(c);}},s.onerror=()=>i("Network error"),s.onabort=()=>i("Aborted"),s.ontimeout=()=>i("Timeout"),typeof r=="function"&&(s.onprogress=a=>{r({status:"download",progress:ai(a.loaded,a.total),loaded:a.loaded,total:a.total,abort:()=>s.abort()});},s.upload&&(s.upload.onprogress=a=>{r({status:"upload",progress:ai(a.loaded,a.total),loaded:a.loaded,total:a.total,abort:()=>s.abort()});})),s.send(e.body);})}function mf(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 $t(t,e){await this.__connection;let{record_id:r,service:n=this.service,progress:i}=e;if(!r)throw new h('"record_id" is required.',{code:"INVALID_PARAMETER"});if(Xo&&t instanceof SubmitEvent&&(t=t.target),ff&&t instanceof HTMLFormElement&&(t=new FormData(t)),!Bt||!(t instanceof FormData))throw new h('"fileList" should be a FormData or HTMLFormElement.',{code:"INVALID_PARAMETER"});let o={reserved_key:Ye(),service:n,request:"post"};e?.record_id&&(o.id=e.record_id);let a,l=(p,g,m)=>new Promise((y,w)=>{a=new XMLHttpRequest,a.open("POST",p),a.onload=()=>{let _=a.responseText;try{_=JSON.parse(_);}catch{}if(a.status>=200&&a.status<300)y(_);else if(a.status===429){let A=a.getResponseHeader("Retry-After"),U=Zo(A);U!==null?setTimeout(()=>{l(p,g,m).then(y,w);},U):w("Too many requests");}else w(_);},a.onerror=()=>w("Network error"),a.onabort=()=>w("Aborted"),a.ontimeout=()=>w("Timeout"),a.upload&&typeof m=="function"&&(a.upload.onprogress=m),a.send(g);});function c(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 u=[],f=[],d=[];for(let[p,g]of t.entries()){if(!(g instanceof File))continue;let m=await To.bind(this)(r,p,g),y=m.file,w=m.key,_=Object.assign({key:w+"/"+y.name,sizeKey:c(y.size),contentType:y.type||null},o),{fields:A=null,url:U,cdn:S}=await T.bind(this)("get-signed-url",_,{auth:!!this.__user});d.push(S);let F=new FormData;for(let O in A)F.append(O,A[O]);F.append("file",y);try{await l(U,F,typeof i=="function"?O=>i({status:"upload",progress:ai(O.loaded,O.total),currentFile:g,completed:u,failed:f,loaded:O.loaded,total:O.total,abort:()=>a.abort()}):null),u.push(g);}catch{f.push(g);}}return {completed:u,failed:f,bin_endpoints:d}}var Cr={};function P(t){let{preventMultipleCalls:e=false}=t||{};return function(r,n,i){let s=i.value;i.value=function(...o){let a=o[0],l=true,c=null,u="",f={},d=false;if(Xo&&a instanceof SubmitEvent){a.preventDefault();let w=window.location.href;c=a.target;let _=new URL(c.action);u=_.href;let A=u?u.match(/(?<=\{).*?(?=\})/g):"";if(A)for(let U of A){if(!U)continue;let S=c.querySelector(`[name="${U}"]`);if(S)if(S.type==="file")for(let F=0;F<=S.files.length-1;F++)S.files[F]&&(f[U]||(f[U]=[]),f[U].push(new Promise((O,k)=>{let x=new FileReader;x.onload=function(){O(x.result);},x.readAsDataURL(S.files[F]),x.onerror=k;})));else u=u.replace(`{${U}}`,S.value);}c.getAttribute("action")===null?l=false:d=_.href===w;}let p=async w=>{if(u)for(let _ in f)f[_].length&&(u=u.replace(`{${_}}`,(await Promise.all(f[_])).join(",")));if(c&&l){let _=q.call(this)?gf(w):w;window.sessionStorage.setItem(`${this.service}:${X.hash(u)}`,JSON.stringify(_)),d?window.location.replace(u):window.location.href=u;}return w},g,m=w=>{throw w instanceof h?w.name=n+"()":w=w instanceof Error?w:new h(w,{name:n+"()"}),w},y=async()=>{try{if(g=s.bind(this)(...o),g instanceof Promise){let w=await g;return p(w)}return p(g)}catch(w){throw m(w)}};if(e){let w=`${n}:${this?.__public_identifier||""}:${this?.service||""}:${this?.owner||""}`;return Cr?.[w]||(Cr[w]=y().finally(()=>{delete Cr[w];})),Cr[w]}return y()};}}async function ra(){await this.__connection;let t=`${this.service}:${X.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 yf=256,_f=256,bf=256,na=256,wf="\u{10FFFF}",Ef=/[\u0000-\u001F\u007F]|\u{10FFFF}/u,Af={"/":"%2F","!":"%21","*":"%2A","#":"%23"},Sf={"%2F":"/","%21":"!","%2A":"*","%23":"#"};function vf(t){return t.replace(/%/g,"%25").replace(/[\/!*#]/g,r=>Af[r]||r)}function Ae(t){return typeof t!="string"?t:t.replace(/%(2F|21|2A|23)/gi,r=>{let n=r.toUpperCase();return Sf[n]||r}).replace(/%25/gi,"%")}function Ue(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 h(`"${e}" should be type: <string>.`,{code:"INVALID_PARAMETER"});if(a&&/[^a-zA-Z0-9]/.test(t))throw new h(`"${e}" should only contain alphanumeric characters.`,{code:"INVALID_PARAMETER"});if(!n&&t.length===0)throw new h(`"${e}" is required.`,{code:"INVALID_PARAMETER"});if(i&&t.length>i)throw new h(`"${e}" should be <= ${i} characters.`,{code:"INVALID_PARAMETER"});if(Ef.test(t)||t.includes(wf))throw new h(`"${e}" cannot include control characters or unsupported sentinel characters.`,{code:"INVALID_PARAMETER"});if(s&&(t=vf(t),i&&t.length>i))throw new h(`"${e}" should be <= ${i} characters. "/", "!", "*", "#" and "%" count as 3 characters each.`,{code:"INVALID_PARAMETER"});if(o&&t.startsWith("$"))throw new h(`"${e}" cannot start with "$".`,{code:"INVALID_PARAMETER"});return t}function bt(t,e="table.name",r={}){return Ue(t,e,{allowEmpty:r.allowEmpty===true,maxLength:yf,blockKeyDelimiters:true})}function Dr(t,e="tag",r={}){return Ue(t,e,{allowEmpty:r.allowEmpty===true,maxLength:_f,blockKeyDelimiters:true})}function Kt(t,e="index.name",r={}){return Ue(t,e,{allowEmpty:r.allowEmpty===true,maxLength:bf,blockKeyDelimiters:true,disallowLeadingDollar:true})}function ia(t,e="index.value"){return Ue(t,e,{allowEmpty:true,maxLength:na})}function ci(t){return typeof t=="string"&&t.slice(-1)==="."}function li(t,e){return Ue(t,e,{allowEmpty:true,maxLength:na,blockKeyDelimiters:true})}function sa(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=Ue(t.record_id,"record_id",{allowEmpty:false,onlyAlphanumeric:true}):t?.unique_id&&(e.unique_id=t.unique_id),e}function ui(t){if(t===void 0)return 0;if(typeof t=="number"){if(t>99||t<0)throw new h('"table.access_group" value should be within a range of 0 ~ 99.',{code:"INVALID_REQUEST"})}else if(typeof t=="string"){if(t={"*":"private",private:"private",public:0,authorized:1,admin:99}[t],t===void 0)throw new h('"table.access_group" is invalid.',{code:"INVALID_PARAMETER"})}else throw new h('"table.access_group" should be type: <number | string>.',{code:"INVALID_PARAMETER"});if(!this.__user&&t)throw new h("Unsigned users have no access to records with access group.",{code:"INVALID_REQUEST"});return t}var kr=4503599627370496;function Nr(t){if(typeof t=="number"){if(t>kr||t<-kr)throw new h(`Number value should be within range -${kr} ~ +${kr}`,{code:"INVALID_PARAMETER"});return t}if(typeof t=="boolean")return t;if(typeof t=="string")return ia(t,"index.value");throw new h('"index.value" should be type: <number | boolean | string>.',{code:"INVALID_PARAMETER"})}function oa(t,e){if(!e.index||!("value"in e.index))throw new h('"index.value" is required.',{code:"INVALID_PARAMETER"});if(e.index.name==="$record_id")throw new h(`Cannot do "index.range" on ${e.index.name}`,{code:"INVALID_PARAMETER"});if(typeof e.index.value!=typeof t)throw new h('"index.range" type should match the type of "index.value".',{code:"INVALID_PARAMETER"});return typeof t=="string"?ci(e.index.name)?li(t,"index.range"):ia(t,"index.range"):t}var Or={},Rf=10080*60,Tf=3600,aa=2;function If(t,e){if(!e)return String(aa);let r=Math.max(60,t-300)*1e3;return "g"+aa+"w"+Math.floor(Date.now()/r)}function Pf(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 Uf(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 ca(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 Ze(t,e,r=false,n=false,i=false){let s={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:{}},o=false,a=[],l=null;function c(d){let p=d=="**"?"private":parseInt(d);return p=p==0?"public":p==1?"authorized":p==99?"admin":p,p}let u={ip:d=>{let p=d.split("#"),g=p[0];p.length>1&&(s.unique_id=p.slice(1).join("#")),g.slice(-1)==="R"?(s.readonly=true,g=g.slice(0,-1)):s.readonly=false,/^\d{1,3}-\d{1,3}-\d{1,3}-\d{1,3}$/.test(g)&&(g=g.split("-").join("."),o=true),s.ip=g;},rec:d=>{if(!d)return;s.record_id=d;let p=d.substring(0,d.length-9),g=be(p);s.uploaded=g;},usr:d=>{s.user_id=d;},tbl:d=>{if(d&&!s.table.name){let p=d.split("/");s.table.name=Ae(p[0]),s.table.access_group=c(p[2]),p?.[3]&&(s.table.subscription.is_subscription_record=true);}},usr_tbl:d=>{let p=d.split("/");s.user_id||(s.user_id=p[0]),s.table.name||(s.table.name=Ae(p[1]),s.table.access_group=c(p[3]),p?.[4]&&(s.table.subscription.is_subscription_record=true));},idx:d=>{if(!d)return;let p=d.split("!"),g=Ae(p.splice(0,1)[0]),m=xf("!"+p.join("!"));s.index={name:g,value:m};},ref:d=>{d&&(s.reference=d.split("/")[0]);},tags:d=>{s.tags=Array.isArray(d)?d.map(p=>Ae(p)):d;},upd:d=>{s.updated=d;},acpt_mrf:d=>{s.source.prevent_multiple_referencing=!d;},ref_limt:d=>{s.source.referencing_limit=d;},rfd:d=>{s.referenced_count=d;},bin:async d=>{let p={},g=s?.reference||null;if(Array.isArray(d)){let m=await Promise.all(d.map(async y=>{try{let w=y.split("/").slice(3).join("/"),_=w.split("/");if(_.length<12)return null;let A=_[_.length-1],U=_[10];if(U==="__data__"&&A==="__json__.json")return {isDataFile:!0,rawUrl:y};if(Wn(U,A))return {isDataFile:!0,rawUrl:y};let S=Ur(U),F=_[9],O=_[8],k=c(_[6]),x=y,C=k!=="public"&&Pf.call(this,_)?{expires:Tf,browserCache:Rf}:null;if(k!=="public"&&!i)try{x=await Xe.bind(this)(y,{dataType:"endpoint",_ref:g});}catch(B){console.error("Error getting signed url for private file:",B),x=y;}let L={access_group:k,filename:A,url:x,path:w,size:S?S.plainSize:be(F),uploaded:be(O),getFile:(B,ee)=>{let ie={dataType:B||"download",progress:ee,_ref:g},M=()=>Xe.bind(this)(x,Object.assign({},ie,{_update:L}));return C?Xe.bind(this)(y,Object.assign({},ie,C)).catch(()=>M()):M()}};return S&&(L.encrypted=!0,L.stored_size=be(F)),{pathKey:S?S.key:U,obj:L}}catch{return null}}));for(let y of m)if(y&&!y.isDataFile){if(p[y.pathKey]){p[y.pathKey].push(y.obj);continue}p[y.pathKey]=[y.obj];}}s.bin=p;},prv_acs:d=>{for(let p in d)["notify_subscribers","upload_to_feed","feed_referencing_records","notify_referencing_records"].includes(p)?s.table.subscription[p]=d[p]:p==="referencing_index_restrictions"&&Array.isArray(d[p])?s.source[p]=d[p].map(m=>m&&typeof m=="object"&&typeof m.name=="string"?Object.assign({},m,{name:Ae(m.name)}):m):s.source[p]=d[p];},data:async d=>{let p={access_group:s.table.access_group,table_name:s.table.name,user_id:s.user_id,record_id:s.record_id,unique_id:s.unique_id,ctUrl:l},g=()=>{q.call(this)&&(s.encrypted={status:"failed",reason:"DATA_UNAVAILABLE"});},m=async w=>{if(n||!q.call(this)&&!Tr(w))return w;let _=await io.bind(this)(w,p);return _.flag&&(s.encrypted=_.flag),_.value},y=Uf(d);if(y!==d){s.data=await m(y);return}if(d&&typeof d=="object"&&!Array.isArray(d)&&typeof d.__data__=="string"&&Object.keys(d).length===1&&d.__data__.endsWith("/__data__/__json__.json")){let w=d.__data__,_=a.find(A=>A.endsWith(w))||null;if(!_&&!r&&g(),_){if(r){s.data=d;return}try{let A=await Xe.bind(this)(_,{dataType:"blob",_ref:s.reference||null}),U=await ca(A);s.data=await m(JSON.parse(U));}catch(A){console.error("Failed to fetch offloaded record data:",A),s.data=null,g();}return}}s.data=await m(d);}};if(t.record_id)return t;if(Array.isArray(t.bin))for(let d of t.bin)try{if(typeof d!="string")continue;let p=d.split("/").slice(3);p.length>=12&&p[10]==="__data__"&&p[p.length-1]==="__json__.json"&&a.push(d),p.length>=12&&Wn(p[10],p[p.length-1])&&(l=d);}catch{}let f=[];for(let d in u)if(t.hasOwnProperty(d)){let p=u[d](t[d]);p instanceof Promise&&f.push(p);}return o&&(s.user_id="anonymous:"+s.user_id),await Promise.all(f),s}function xf(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 h("Value parse error.",{code:"PARSE_ERROR"})}default:return t}}async function la(t){let{endpoints:e}=t;if(typeof e=="string"&&(e=[e]),!Array.isArray(e))throw new h('"endpoints" should be type: array | string.',{code:"INVALID_PARAMETER"});let r=await T.bind(this)("del-files",{endpoints:e,storage:"records"},{auth:true,method:"post"}),n=[];for(let i in r)n.push(Ze.bind(this)(r[i]));return Promise.all(n)}async function Xe(t,e){if(typeof t!="string")throw new h('"url" should be type: string.',{code:"INVALID_PARAMETER"});let r=t,n=t.split("?"),i=n.shift()||"",s=n.length?"?"+n.join("?"):"",o=b.Url(i);t=o+s;let a=false,l=o.split("/"),u=l[2].split("."),f=null;u.length===3&&u[1]==="skapi"&&(f=u[0],a=true);let d=l.slice(3),p=false;if(!a&&(d[0]==="auth"||d[0]==="publ"))try{b.UserId(d[2]),b.UserId(d[3]),p=d[0]=="auth",a=!0;}catch{throw new h("Invalid file url.",{code:"INVALID_PARAMETER"})}let g=f?null:d[1];if(e=b.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:t,filename:d[d.length-1],fileKey:d[d.length-2],access_group:d[6]==="**"?"private":d[6]==="01"?"authorized":d[6]==="00"?"public":parseInt(d[6]),uploader:d[3],record_id:d[4]==="records"?d[5]:"N/A",filesize:be(d[9]),uploaded:be(d[8])};let m=t.split("/").slice(-1)[0],y=e.expires;if(y){if(!a)throw new h("Expires option can only be used on skapi cdn endpoints.",{code:"INVALID_PARAMETER"});if(y<0)throw new h('"config.expires" should be > 0. (seconds)',{code:"INVALID_PARAMETER"});let A={request:f?"get-host":"get",id:f||d[5],key:r.split("?")[0],expires:y};g&&(A.service=g);let U=e.browserCache,S={auth:true};if(U){if(U<0)throw new h('"config.browserCache" should be > 0. (seconds)',{code:"INVALID_PARAMETER"});S.method="get",S.stableGateway=true,A.browser_cache=U;let F=this.session?.idToken?.payload?.sub||this.user?.user_id;F&&(A.uid=F),A.nocache=If(y,e.refresh);}t=(await T.bind(this)("get-signed-url",A,S)).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 ne.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(O){throw this.log("getFile:new token error",O),new h("User login is required.",{code:"INVALID_REQUEST"})}}let U=this.bearerToken||this.session?.idToken?.jwtToken;if(!U||!this.user?.user_id)throw new h("User login is required.",{code:"INVALID_REQUEST"});t+=`${t.includes("?")?"&":"?"}t=${encodeURIComponent(U)}`;let S=d[6]==="**"?"**":parseInt(d[6]),F=this.user?.access_group??-1;if(this.user.user_id!==d[3]&&(S==="**"||F<S)){let O=d[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 k=await this.requestPrivateRecordAccessKey({record_id:O,reference_id:e?._ref});t+=`&p=${encodeURIComponent(k)}`;}catch{}}}if((q.call(this)?ri(t):null)&&e?.dataType!=="endpoint"&&e?.dataType!=="info"){let A=await T.bind(this)(t,null,{method:"get",contentType:null,responseType:"blob",fetchOptions:{progress:e?.progress}},{ignoreService:true}),U=await Io.bind(this)(t,A);if(e?.dataType==="blob")return U;if(e?.dataType==="text")return await ca(U);if(e?.dataType==="base64")return await new Promise((O,k)=>{let x=new FileReader;x.onloadend=()=>O(x.result),x.onerror=()=>k(x.error),x.readAsDataURL(U);});let S=URL.createObjectURL(U),F=document.createElement("a");return F.href=S,document.body.appendChild(F),F.setAttribute("download",m),F.click(),document.body.removeChild(F),setTimeout(()=>URL.revokeObjectURL(S),6e4),null}if(e?.dataType==="endpoint")return e._update&&(e._update.url=t),t;if(e?.dataType==="download"){let A=document.createElement("a");return A.href=t,document.body.appendChild(A),A.setAttribute("download",m),A.target="_blank",A.click(),document.body.removeChild(A),null}return new Promise(async(A,U)=>{try{let S=await T.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 F=new FileReader;F.onloadend=()=>A(F.result),F.readAsDataURL(S);}else A(S);}catch(S){if(e?.browserCache&&!e?.refresh)try{A(await Xe.bind(this)(r,Object.assign({},e,{refresh:!0})));return}catch(F){U(F);return}U(S);}})}function Fr(t,e){return `${t||this.service}/${e||this.owner}`}function di(t,e){let r=this.__my_unique_ids[t];return r?r[e]:void 0}function ua(t,e,r){this.__my_unique_ids[t]||(this.__my_unique_ids[t]={}),this.__my_unique_ids[t][e]=r;}function Cf(t,e){this.__my_unique_ids[t]&&delete this.__my_unique_ids[t][e];}function da(t,e){return !e||e.table===void 0?t:Object.assign({},t,{table:e.table})}async function jt(t){if(await this.__connection,!this.__user&&this.connection?.opt?.require_login===true)throw new h(`This project requires users to sign in before reading its database, so "${t}" is not available to a signed-out visitor.`,{code:"REQUIRE_LOGIN"})}async function fa(t,e=false){t=j(t,{ignoreEmpty:true}).data||{};let r=Fr.bind(this)(t?.service,t?.owner),n="",i=sa(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=di.bind(this)(r,n);s&&(e?Cf.bind(this)(r,n):t.record_id=s);}}else {let s=await Z.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 l=c=>({table:{name:u=>bt(u,"table.name"),access_group:ui.bind(this),subscription:u=>b.UserId(u,'User ID in "subscription"')},reference:"string",index:{name:["$updated","$uploaded","$referenced_count","$user_id",u=>Kt(u,"index.name")],value:u=>{let f={$updated:"number",$uploaded:"number",$referenced_count:"number",$user_id:b.UserId};if(f.hasOwnProperty(c.index.name)){let d=f[c.index.name];if(typeof d=="function")return d(u);if(d!==typeof u)throw new h(`"index.value" should be type: ${d}.`,{code:"INVALID_PARAMETER"});return u}return typeof u=="string"&&!u?"":typeof u=="string"&&ci(c.index.name)?li(u,"index.value"):Nr(u)},condition:["gt","gte","lt","lte",">",">=","<","<=","=","eq"],range:u=>oa(u,c)},tag:u=>{if(u==null)return u;if(typeof u=="string")return Dr(u,"tag");throw new h('"tag" should be type: string.',{code:"INVALID_PARAMETER"})},private_key:"string"});t=b.Params(t||{},l(t),a||s?[]:["table"],{ignoreEmpty:true});}return {query:t,is_reference_fetch:n}}async function ha(t,e){await this.__connection,await jt.call(this,"getRecords");let r=await fa.bind(this)(t),n=r.is_reference_fetch,i=await T.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(Ze.bind(this)(i.list[o]));return i.list=await Promise.all(s),i}function pa(t){let e="",r=[],n=Fr.bind(this)(t?.service,t?.owner),i=b.Params(t||{},{record_id:o=>{let a=typeof o=="string"?di.bind(this)(n,o):void 0;return a||Ue(o,"record_id",{allowEmpty:false})},unique_id:["string",null],readonly:"boolean",table:{name:o=>bt(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:ui.bind(this)},source:{referencing_limit:o=>{if(o===null)return null;if(typeof o=="number"){if(0>o)throw new h('"reference_limit" should be >= 0',{code:"INVALID_PARAMETER"});if(o>4503599627370546)throw new h('"reference_limit" should be <= 4503599627370546',{code:"INVALID_PARAMETER"});return o}throw new h('"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=>Kt(c,'"name" in "index_restrictions"'),value:c=>Nr(c),condition:["gt","gte","lt","lte",">",">=","<","<=","=","eq","!=","ne",()=>null],range:c=>{if(c!==null&&typeof o.value!=typeof c)throw new h('Index restriction "range" type should match the type of "value".',{code:"INVALID_PARAMETER"});if(!o.hasOwnProperty("value"))throw new h('Index restriction "value" is required.',{code:"INVALID_PARAMETER"});return c}};Array.isArray(o)||(o=[o]);let l=o.map(c=>b.Params(c,a,["name"]));if(l.length)for(let c of l)c.condition&&c.hasOwnProperty("range")&&delete c.range;return l}},reference:o=>{if(o===null)return {record_id:null};if(o){if(typeof o=="string"){e=o;let a=di.bind(this)(n,o);return a||o}if(typeof o!="object")throw new h('"reference" should be type: <string | object>.',{code:"INVALID_PARAMETER"});return b.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),Ue(a,"reference.record_id",{allowEmpty:false,onlyAlphanumeric:true}))})}},index:[null,{name:o=>Kt(o,"index.name"),value:o=>Nr(o)}],tags:o=>{if(o==null)return o;if(typeof o=="string"&&(o=o.split(",").map(a=>a.trim())),!Array.isArray(o))throw new h('"tag" should be type: <string | string[]>.',{code:"INVALID_PARAMETER"});return o.map(a=>Dr(a,"tag"))},remove_bin:o=>{if(!o)return null;let a=[];if(Array.isArray(o))for(let l of o)if(typeof l=="string")a.push(l.split("?")[0]);else if(l.url&&l.size&&l.filename){let u=l.url.split("/").slice(0,3).join("/")+"/"+l.path;a.push(u);}else throw new h('"remove_bin" should be type: <string[] | BinaryFile[] | null>',{code:"INVALID_PARAMETER"});else throw new h('"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 h('"table.name" is required.',{code:"INVALID_PARAMETER"});typeof a.table=="string"&&(a.table={name:a.table},a?.record_id||(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 h("Public users cannot update existing records.",{code:"INVALID_REQUEST"});if(i.table.access_group!=="public"&&i.table.access_group!==0)throw new h("Public users can only post records to public tables.",{code:"INVALID_REQUEST"});if(o)throw new h("Public users cannot post subscription records.",{code:"INVALID_REQUEST"});if(i.remove_bin)throw new h("Public users cannot remove files from records.",{code:"INVALID_REQUEST"});if(i.unique_id)throw new h("Public users cannot set unique_id for records.",{code:"INVALID_REQUEST"})}return {config:i,progress:s,is_reference_post:e,files:r}}async function ga(t){if(await this.__connection,!Array.isArray(t)||!t.length)throw new h('"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 h(`"params[${g}]" should be type: <object>.`,{code:"INVALID_PARAMETER"});let m=pa.bind(this)(p),y=m.config;if(q.call(this)){let w=Object.prototype.hasOwnProperty.call(y,"data"),_=await Gn.bind(this)(y.data,da(p,y),w);_.encrypted&&(y.data=_.send,s[g]=_.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 h('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 h('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 l={auth:!!this.__user,method:"post"},c={};Object.keys(c).length&&Object.assign(l,{fetchOptions:c});let u=await T.bind(this)("post-record",a,l),f=await Promise.all(u.map((p,g)=>Ze.bind(this)(p,"called from postRecord",false,s.hasOwnProperty(g))));for(let p=0;p<f.length;p++)s.hasOwnProperty(p)&&f[p]&&!f[p].error&&(f[p].data=s[p],f[p].encrypted={status:"encrypted"});let d=Fr.bind(this)(r,n);for(let p=0;p<u.length;p++){let g=u[p],m=f[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&&ua.bind(this)(d,m.unique_id,m.record_id);}return f}async function fi(t,e,r){if(await this.__connection,!e)throw new h('"config" argument is required.',{code:"INVALID_PARAMETER"});let n=pa.bind(this)(e),i=n.config,s=n.progress,o=n.is_reference_post,a={auth:!!this.__user,method:"post"},l=[],c=j(t);r&&Array.isArray(r)&&r.length&&(l=l.concat(r)),c.files&&Array.isArray(c.files)&&c.files.length&&(l=l.concat(c.files));let u=e?.data!==void 0?e.data:c.data,f=u!==void 0,d=await Gn.bind(this)(u,da(e,i),f),p=null;p=Object.assign({},i),delete p.data,d.omit||(p.data=d.send);let g={};if(typeof s=="function"&&(g.progress=s),Object.keys(g).length&&Object.assign(a,{fetchOptions:g}),d.files==="decrypt"&&e?.record_id){let _=await ni.bind(this)(e.record_id,"decrypt",s);if(_.length){let A=p.remove_bin;p.remove_bin=Array.isArray(A)?A.concat(_):_;}}if(d.spill&&e?.record_id){let _=new FormData;if(_.append(Lt,new File([d.spill],"payload.bin",{type:"application/octet-stream"})),await $t.bind(this)(_,{record_id:e.record_id}),d.retireCt){let A=p.remove_bin,U=[d.retireCt];p.remove_bin=Array.isArray(A)?A.concat(U):U;}}let m=await T.bind(this)("post-record",p,a);if(d.encrypted&&m?.rec&&ro.bind(this)(m.rec,d.dek),d.files==="encrypt"&&m?.rec)try{let _=await ni.bind(this)(m.rec,"encrypt",s);_.length&&await fi.bind(this)(void 0,{record_id:m.rec,remove_bin:_});}catch(_){console.error("Failed to encrypt existing attachments after making the record private:",_);}if(ae()&&l.length){let _=new FormData;for(let S of l)_.append(S.name,S.file,S.file.name);let A={record_id:m.rec,progress:s};i.hasOwnProperty("service")&&(A.service=i.service);let{bin_endpoints:U}=await $t.bind(this)(_,A);m.bin?m.bin.push(...U):m.bin=U;}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"),w=await Ze.bind(this)(m,"called from postRecord",true,d.encrypted);if(y&&(w.data=c.data),d.encrypted&&(w.data=d.plain,w.encrypted={status:"encrypted",recipients:Object.keys(d.send.k||{})}),w.unique_id){let _=Fr.bind(this)(i?.service,i?.owner);ua.bind(this)(_,w.unique_id,w.record_id),ae()&&(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 w}async function ma(t,e){await jt.call(this,"getTables");let r=await T.bind(this)("get-table",b.Params(t||{},{table:i=>bt(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=Ae(i.table));}return r}async function ya(t,e){if(await jt.call(this,"getIndexes"),!t?.table)throw new h('"table" is required.',{code:"INVALID_PARAMETER"});let r=b.Params(t||{},{table:s=>bt(s,"table",{allowEmpty:true}),index:s=>Kt(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 Ue(s,"order.value",{allowEmpty:true,maxLength:256,blockKeyDelimiters:true});if(typeof s!="string"&&typeof s!="number"&&typeof s!="boolean")throw new h('"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 h('"order.by" is required.',{code:"INVALID_PARAMETER"});if(r.order.hasOwnProperty("condition")&&!r.order.hasOwnProperty("value"))throw new h('"value" is required for "condition".',{code:"INVALID_PARAMETER"});if(r.hasOwnProperty("index")&&r.index.substring(r.index.length-1)!==".")throw new h('"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",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:Ae(o[1]),index:Ae(o[2]),number_of_records:s.cnt_rec};for(let l in i)Object.prototype.hasOwnProperty.call(s,l)&&(a[i[l]]=s[l]);return a})),n}async function _a(t,e){await jt.call(this,"getTags");let r=await T.bind(this)("get-tag",b.Params(t||{},{table:n=>bt(n,"table",{allowEmpty:true}),tag:n=>Dr(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:Ae(i[1]),tag:Ae(i[0]),number_of_records:n.cnt_rec}})),r}async function ba(t,e){await jt.call(this,"getUniqueId");let r=await T.bind(this)("get-uniqueid",b.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}async function wa(t,e){await this.__connection;let r=await fa.bind(this)(t,true),n=r.is_reference_fetch,i=await T.bind(this)("del-records",r.query,{auth:true,fetchOptions:e});return n&&typeof i?.reference_private_key=="string"&&(this.__private_access_key[n]=i.reference_private_key),Array.isArray(i?.list)&&(i.list=await Promise.all(i.list.map(async s=>{if(!s||typeof s!="object")return s;try{return await Ze.bind(this)(s,"called from deleteRecords",!0,!1,!0)}catch{return s}}))),i?.message||i}async function Ea(t){if(q.call(this)){let e=typeof t.user_id=="string"?[t.user_id]:t.user_id;Array.isArray(e)&&e.length&&await ti.bind(this)(t.record_id,e);}return Ra.bind(this)({record_id:t.record_id,user_id:t.user_id,execute:"add"})}async function Aa(t){let e=await Ra.bind(this)({record_id:t.record_id,user_id:t.user_id||null,execute:"remove"});if(q.call(this)){let r=typeof t.user_id=="string"?[t.user_id]:t.user_id;await _o.bind(this)(t.record_id,Array.isArray(r)&&r.length?r:null);}return e}async function Sa(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 h("Either record_id or user_id must be provided.",{code:"INVALID_PARAMETER"});if(r.user_id)if(typeof r.user_id=="string")b.UserId(r.user_id),r.user_id=[r.user_id];else if(Array.isArray(r.user_id))for(let s of r.user_id)b.UserId(s);else throw new h("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",r,{auth:true,fetchOptions:e});return i.list=i.list.map(n),i}function va(t){let e=t.record_id,r=t.reference_id||void 0;if(!e)throw new h("Record ID is required.",{code:"INVALID_PARAMETER"});if(typeof e!="string")throw new h("Record ID should be type: <string | string[]>",{code:"INVALID_PARAMETER"});if(r&&typeof r!="string")throw new h("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(Or[e])return Or[e];let n=T.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 h("Invalid private access key response.",{code:"ERROR"});return this.__private_access_key[e]=s,s}).finally(()=>{delete Or[e];});return Or[e]=n,n}function Ra(t){t.execute;let r=b.Params(t,{record_id:"string",user_id:n=>{if(!n)throw new h("User ID is required.",{code:"INVALID_PARAMETER"});let i=n;if(typeof i=="string"&&(i=[i]),i.length>100)throw new h("Cannot process more than 100 users at once.",{code:"INVALID_REQUEST"});for(let s of i)b.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),T.bind(this)("grant-private-access",r,{auth:true})}var D={},z={},Se={},Ce={},xe={},Lr={},Mr={};function Ta(t,e,r){t[e]||(t[e]=[]),t[e].push(r);}async function qr(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 pi(t,e){if(!this?.session?.accessToken?.jwtToken)throw new h("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 qr(Mr,e,i=>n.bind(this)(i,e,r)),await n.bind(this)(t,e,r)):await qr(Mr,e,i=>n.bind(this)(i,e,r)):t&&Ta(Mr,e,t);}async function gi(t,e){if(this.log("receiveIceCandidate",t),D?.[e]&&D[e]?.remoteDescription&&D[e]?.remoteDescription?.type){if(!t)return qr(Lr,e,r=>D[e].addIceCandidate(r));await qr(Lr,e,r=>D[e].addIceCandidate(r)),await D[e].addIceCandidate(t);}else Ta(Lr,e,t);}async function ve(t){if(typeof window>"u"||window._runningInNodeJS)throw new h("WebRTC is not supported in Node.js environment.",{code:"NOT_SUPPORTED"});b.Params(t,{cid:s=>{if(typeof s!="string")throw new h('"cid" should be type: <string>.',{code:"INVALID_PARAMETER"});if(s&&s.slice(0,4)!=="cid:")throw new h('"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 h('"cid" is required.',{code:"INVALID_PARAMETER"});let i=s=>{if(!s)throw new h('"cid" is required.',{code:"INVALID_PARAMETER"});if(delete Mr[s],delete Lr[s],z[s]&&Object.values(z[s]).forEach(o=>{o.readyState!=="closed"&&o.close();}),delete z[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};xe[s]&&xe[s](o),this.log("closeRTC",o);}delete xe[s],delete Ce[s],delete Se[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 Ia(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 Pa(t,e){if(typeof window>"u"||window._runningInNodeJS)throw new h("WebRTC is not supported in Node.js environment.",{code:"NOT_SUPPORTED"});if(typeof e!="function")throw new h("Callback is required.",{code:"INVALID_PARAMETER"});if(!this?.session?.accessToken?.jwtToken)throw new h("Access token is required.",{code:"INVALID_PARAMETER"});t=b.Params(t,{cid:o=>{if(typeof o!="string")throw new h('"cid" should be type: <string>.',{code:"INVALID_PARAMETER"});if(o&&o.slice(0,4)!=="cid:")throw new h('"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 h("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 h("No realtime connection. Execute connectRealtime() before this method.",{code:"INVALID_REQUEST"});if(i.readyState!==1)throw new h("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 Ia(t.media),this.__mediaStream.getTracks().forEach(o=>{D[r].addTrack(o,this.__mediaStream);})),xe[r]=e,z[r]||(z[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 l=a.protocol||"default";if(Object.keys(z[r]).includes(l))throw new h(`Data channel with the protocol "${l}" already exists.`,{code:"INVALID_REQUEST"});let c=D[r].createDataChannel(l,a);z[r][l]=c;}for(let o in z[r]){let a=z[r][o];Ca.bind(this)(r,a);}return xa.bind(this)(r,["onnegotiationneeded"]),await hi.bind(this)(r),{hangup:()=>Se[r]&&Se[r](false),connection:new Promise(o=>{Se[r]=(a=>{if(this.log("receiver picked up the call",r),!a)return ve.bind(this)({cid:r}),null;D[r].onnegotiationneeded=()=>{this.log("onnegotiationneeded",`sending offer to "${r}".`),hi.bind(this)(r),xe[r]&&xe[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:z[r],hangup:()=>ve.bind(this)({cid:r}),media:this.__mediaStream});}).bind(this);})}}function Ua(t){return async(e,r)=>{e=e||{},e=j(e).data;let n=t.sender_cid,i=await this.__socket;if(!Ce[n])return null;if(typeof r!="function")throw new h("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 h("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 Ia(e.media),this.__mediaStream.getTracks().forEach(o=>{D[n].addTrack(o,this.__mediaStream);})),delete Ce[n],xe[n]=r,z[n]||(z[n]={}),D[n].ondatachannel=o=>{this.log("ondatachannel",`received data channel "${o.channel.label}".`);let a=o.channel;z[n][a.label]=a,Ca.bind(this)(n,a);},xa.bind(this)(n,["onnegotiationneeded"]),await pi.bind(this)(null,n),await gi.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:z[n],hangup:()=>ve.bind(this)({cid:n}),media:this.__mediaStream}}}async function hi(t){if(!this?.session?.accessToken?.jwtToken)throw new h("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 kf(t,e){if(!this?.session?.accessToken?.jwtToken)throw new h("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=xe[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 xa(t,e){let r=new Set(e),n=xe[t]||(o=>{}),i=D[t],s={ontrack:o=>{n({type:"track",target:i,timeStamp:o.timeStamp,streams:o.streams,track:o.track});},onicecandidate:o=>{kf.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:()=>{hi.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")&&ve.bind(this)({cid:t});}};for(let[o,a]of Object.entries(s))r.has(o)||(i[o]=a);}function Ca(t,e,r){let n=new Set(r),i=xe[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),z[t]&&(delete z[t][e.label],Object.keys(z[t]).length===0&&ve.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 qe;function ka(){return qe}var He=null,Ht=true,wt=0;async function Df(){if(typeof window>"u"||window._runningInNodeJS)throw new h("WebSocket is not supported in Node.js environment.",{code:"NOT_SUPPORTED"});if(await this.getProfile(),!this.session)throw new h("No access.",{code:"INVALID_REQUEST"});let t=await this.record_endpoint;return new WebSocket(t.websocket_private+"?token="+this.session.accessToken.jwtToken)}var mi=null;async function Vr(){if(typeof window>"u"||window._runningInNodeJS)throw new h("WebSocket is not supported in Node.js environment.",{code:"NOT_SUPPORTED"});Ht=true;let t=this.__socket?await this.__socket:this.__socket;ve.bind(this)({close_all:true}),qe&&At.bind(this)({group:null}),wt=0,He&&(He.terminate(),He=null);try{t&&t.close();}catch{}return window.removeEventListener("visibilitychange",mi),this.__socket=null,null}async function Et(t,e=50,r){if(typeof window>"u"||window._runningInNodeJS)throw new h("WebSocket is not supported in Node.js environment.",{code:"NOT_SUPPORTED"});if(typeof t!="function")throw new h("Callback must be a function.",{code:"INVALID_REQUEST"});if(r==="reconnect"){if(this.__socket instanceof Promise){let i=await this.__socket;if(i.readyState!==WebSocket.CLOSED&&i.readyState!==WebSocket.CLOSING)return this.__socket}}else if(Ht&&(mi=()=>{!document.hidden&&!Ht&&Et.bind(this)(t,0,"reconnect");},this.__socket instanceof Promise))return this.__socket;He&&(He.terminate(),He=null);let n={value:null};return this.__socket=new Promise(async(i,s)=>{let o=a=>{this.__socket===n.value&&(this.__socket=null),s(a);};try{await yt.bind(this)();}catch(a){o(a);return}setTimeout(async()=>{try{let a=await Df.bind(this)();a.onopen=()=>{Ht=!1,wt=0,r!=="reconnect"&&window.addEventListener("visibilitychange",mi),this.log("realtime onopen","Connected to WebSocket server."),t({type:"success",message:"Connected to WebSocket server."}),qe&&a.send(JSON.stringify({action:"joinRoom",rid:qe,token:this.session.accessToken.jwtToken}));let l=`
|
|
206
|
+
var Qc=Object.create;var et=Object.defineProperty;var Ui=Object.getOwnPropertyDescriptor;var Xc=Object.getOwnPropertyNames;var Zc=Object.getPrototypeOf,el=Object.prototype.hasOwnProperty;var tl=(t,e,r)=>e in t?et(t,e,{enumerable:true,configurable:true,writable:true,value:r}):t[e]=r;var Be=(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 tt=(t,e)=>()=>(t&&(e=t(t=0)),e);var ie=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),Xt=(t,e)=>{for(var r in e)et(t,r,{get:e[r],enumerable:true});},ki=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of Xc(e))!el.call(t,i)&&i!==r&&et(t,i,{get:()=>e[i],enumerable:!(n=Ui(e,i))||n.enumerable});return t};var rt=(t,e,r)=>(r=t!=null?Qc(Zc(t)):{},ki(!t||!t.__esModule?et(r,"default",{value:t,enumerable:true}):r,t)),nt=t=>ki(et({},"__esModule",{value:true}),t),I=(t,e,r,n)=>{for(var i=Ui(e,r),s=t.length-1,o;s>=0;s--)(o=t[s])&&(i=(o(e,r,i))||i);return i&&et(e,r,i),i};var ve=(t,e,r)=>tl(t,typeof e!="symbol"?e+"":e,r);var Fi=ie(er=>{er.byteLength=il;er.toByteArray=ol;er.fromByteArray=ll;var Te=[],fe=[],nl=typeof Uint8Array<"u"?Uint8Array:Array,Zr="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";for(We=0,Ni=Zr.length;We<Ni;++We)Te[We]=Zr[We],fe[Zr.charCodeAt(We)]=We;var We,Ni;fe[45]=62;fe[95]=63;function Oi(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 il(t){var e=Oi(t),r=e[0],n=e[1];return (r+n)*3/4-n}function sl(t,e,r){return (e+r)*3/4-r}function ol(t){var e,r=Oi(t),n=r[0],i=r[1],s=new nl(sl(t,n,i)),o=0,a=i>0?n-4:n,c;for(c=0;c<a;c+=4)e=fe[t.charCodeAt(c)]<<18|fe[t.charCodeAt(c+1)]<<12|fe[t.charCodeAt(c+2)]<<6|fe[t.charCodeAt(c+3)],s[o++]=e>>16&255,s[o++]=e>>8&255,s[o++]=e&255;return i===2&&(e=fe[t.charCodeAt(c)]<<2|fe[t.charCodeAt(c+1)]>>4,s[o++]=e&255),i===1&&(e=fe[t.charCodeAt(c)]<<10|fe[t.charCodeAt(c+1)]<<4|fe[t.charCodeAt(c+2)]>>2,s[o++]=e>>8&255,s[o++]=e&255),s}function al(t){return Te[t>>18&63]+Te[t>>12&63]+Te[t>>6&63]+Te[t&63]}function cl(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(al(n));return i.join("")}function ll(t){for(var e,r=t.length,n=r%3,i=[],s=16383,o=0,a=r-n;o<a;o+=s)i.push(cl(t,o,o+s>a?a:o+s));return n===1?(e=t[r-1],i.push(Te[e>>2]+Te[e<<4&63]+"==")):n===2&&(e=(t[r-2]<<8)+t[r-1],i.push(Te[e>>10]+Te[e>>4&63]+Te[e<<2&63]+"=")),i.join("")}});var Li=ie(en=>{en.read=function(t,e,r,n,i){var s,o,a=i*8-n-1,c=(1<<a)-1,l=c>>1,d=-7,h=r?i-1:0,u=r?-1:1,p=t[e+h];for(h+=u,s=p&(1<<-d)-1,p>>=-d,d+=a;d>0;s=s*256+t[e+h],h+=u,d-=8);for(o=s&(1<<-d)-1,s>>=-d,d+=n;d>0;o=o*256+t[e+h],h+=u,d-=8);if(s===0)s=1-l;else {if(s===c)return o?NaN:(p?-1:1)*(1/0);o=o+Math.pow(2,n),s=s-l;}return (p?-1:1)*o*Math.pow(2,s-n)};en.write=function(t,e,r,n,i,s){var o,a,c,l=s*8-i-1,d=(1<<l)-1,h=d>>1,u=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=d):(o=Math.floor(Math.log(e)/Math.LN2),e*(c=Math.pow(2,-o))<1&&(o--,c*=2),o+h>=1?e+=u/c:e+=u*Math.pow(2,1-h),e*c>=2&&(o++,c/=2),o+h>=d?(a=0,o=d):o+h>=1?(a=(e*c-1)*Math.pow(2,i),o=o+h):(a=e*Math.pow(2,h-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,l+=i;l>0;t[r+p]=o&255,p+=g,o/=256,l-=8);t[r+p-g]|=m*128;};});var qi=ie((ph,Mi)=>{var ul={}.toString;Mi.exports=Array.isArray||function(t){return ul.call(t)=="[object Array]"};});var or=ie(st=>{var tn=Fi(),it=Li(),$i=qi();st.Buffer=A;st.SlowBuffer=ml;st.INSPECT_MAX_BYTES=50;A.TYPED_ARRAY_SUPPORT=globalThis.TYPED_ARRAY_SUPPORT!==void 0?globalThis.TYPED_ARRAY_SUPPORT:dl();st.kMaxLength=tr();function dl(){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 tr(){return A.TYPED_ARRAY_SUPPORT?2147483647:1073741823}function Ne(t,e){if(tr()<e)throw new RangeError("Invalid typed array length");return A.TYPED_ARRAY_SUPPORT?(t=new Uint8Array(e),t.__proto__=A.prototype):(t===null&&(t=new A(e)),t.length=e),t}function A(t,e,r){if(!A.TYPED_ARRAY_SUPPORT&&!(this instanceof A))return new A(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 nn(this,t)}return ji(this,t,e,r)}A.poolSize=8192;A._augment=function(t){return t.__proto__=A.prototype,t};function ji(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?pl(t,e,r,n):typeof e=="string"?hl(t,e,r):gl(t,e)}A.from=function(t,e,r){return ji(null,t,e,r)};A.TYPED_ARRAY_SUPPORT&&(A.prototype.__proto__=Uint8Array.prototype,A.__proto__=Uint8Array,typeof Symbol<"u"&&Symbol.species&&A[Symbol.species]===A&&Object.defineProperty(A,Symbol.species,{value:null,configurable:true}));function Ki(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 fl(t,e,r,n){return Ki(e),e<=0?Ne(t,e):r!==void 0?typeof n=="string"?Ne(t,e).fill(r,n):Ne(t,e).fill(r):Ne(t,e)}A.alloc=function(t,e,r){return fl(null,t,e,r)};function nn(t,e){if(Ki(e),t=Ne(t,e<0?0:sn(e)|0),!A.TYPED_ARRAY_SUPPORT)for(var r=0;r<e;++r)t[r]=0;return t}A.allocUnsafe=function(t){return nn(null,t)};A.allocUnsafeSlow=function(t){return nn(null,t)};function hl(t,e,r){if((typeof r!="string"||r==="")&&(r="utf8"),!A.isEncoding(r))throw new TypeError('"encoding" must be a valid string encoding');var n=Hi(e,r)|0;t=Ne(t,n);var i=t.write(e,r);return i!==n&&(t=t.slice(0,i)),t}function rn(t,e){var r=e.length<0?0:sn(e.length)|0;t=Ne(t,r);for(var n=0;n<r;n+=1)t[n]=e[n]&255;return t}function pl(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),A.TYPED_ARRAY_SUPPORT?(t=e,t.__proto__=A.prototype):t=rn(t,e),t}function gl(t,e){if(A.isBuffer(e)){var r=sn(e.length)|0;return t=Ne(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"||Ol(e.length)?Ne(t,0):rn(t,e);if(e.type==="Buffer"&&$i(e.data))return rn(t,e.data)}throw new TypeError("First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.")}function sn(t){if(t>=tr())throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+tr().toString(16)+" bytes");return t|0}function ml(t){return +t!=t&&(t=0),A.alloc(+t)}A.isBuffer=function(e){return !!(e!=null&&e._isBuffer)};A.compare=function(e,r){if(!A.isBuffer(e)||!A.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};A.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}};A.concat=function(e,r){if(!$i(e))throw new TypeError('"list" argument must be an Array of Buffers');if(e.length===0)return A.alloc(0);var n;if(r===void 0)for(r=0,n=0;n<e.length;++n)r+=e[n].length;var i=A.allocUnsafe(r),s=0;for(n=0;n<e.length;++n){var o=e[n];if(!A.isBuffer(o))throw new TypeError('"list" argument must be an Array of Buffers');o.copy(i,s),s+=o.length;}return i};function Hi(t,e){if(A.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 rr(t).length;case "ucs2":case "ucs-2":case "utf16le":case "utf-16le":return r*2;case "hex":return r>>>1;case "base64":return Xi(t).length;default:if(n)return rr(t).length;e=(""+e).toLowerCase(),n=true;}}A.byteLength=Hi;function yl(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 Il(this,e,r);case "utf8":case "utf-8":return zi(this,e,r);case "ascii":return vl(this,e,r);case "latin1":case "binary":return Tl(this,e,r);case "base64":return Sl(this,e,r);case "ucs2":case "ucs-2":case "utf16le":case "utf-16le":return Pl(this,e,r);default:if(n)throw new TypeError("Unknown encoding: "+t);t=(t+"").toLowerCase(),n=true;}}A.prototype._isBuffer=true;function ze(t,e,r){var n=t[e];t[e]=t[r],t[r]=n;}A.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)ze(this,r,r+1);return this};A.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)ze(this,r,r+3),ze(this,r+1,r+2);return this};A.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)ze(this,r,r+7),ze(this,r+1,r+6),ze(this,r+2,r+5),ze(this,r+3,r+4);return this};A.prototype.toString=function(){var e=this.length|0;return e===0?"":arguments.length===0?zi(this,0,e):yl.apply(this,arguments)};A.prototype.equals=function(e){if(!A.isBuffer(e))throw new TypeError("Argument must be a Buffer");return this===e?true:A.compare(this,e)===0};A.prototype.inspect=function(){var e="",r=st.INSPECT_MAX_BYTES;return this.length>0&&(e=this.toString("hex",0,r).match(/.{2}/g).join(" "),this.length>r&&(e+=" ... ")),"<Buffer "+e+">"};A.prototype.compare=function(e,r,n,i,s){if(!A.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),l=this.slice(i,s),d=e.slice(r,n),h=0;h<c;++h)if(l[h]!==d[h]){o=l[h],a=d[h];break}return o<a?-1:a<o?1:0};function Gi(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=A.from(e,n)),A.isBuffer(e))return e.length===0?-1:Vi(t,e,r,n,i);if(typeof e=="number")return e=e&255,A.TYPED_ARRAY_SUPPORT&&typeof Uint8Array.prototype.indexOf=="function"?i?Uint8Array.prototype.indexOf.call(t,e,r):Uint8Array.prototype.lastIndexOf.call(t,e,r):Vi(t,[e],r,n,i);throw new TypeError("val must be string, number or Buffer")}function Vi(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 l;if(i){var d=-1;for(l=r;l<o;l++)if(c(t,l)===c(e,d===-1?0:l-d)){if(d===-1&&(d=l),l-d+1===a)return d*s}else d!==-1&&(l-=l-d),d=-1;}else for(r+a>o&&(r=o-a),l=r;l>=0;l--){for(var h=true,u=0;u<a;u++)if(c(t,l+u)!==c(e,u)){h=false;break}if(h)return l}return -1}A.prototype.includes=function(e,r,n){return this.indexOf(e,r,n)!==-1};A.prototype.indexOf=function(e,r,n){return Gi(this,e,r,n,true)};A.prototype.lastIndexOf=function(e,r,n){return Gi(this,e,r,n,false)};function bl(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 _l(t,e,r,n){return sr(rr(e,t.length-r),t,r,n)}function Wi(t,e,r,n){return sr(Dl(e),t,r,n)}function wl(t,e,r,n){return Wi(t,e,r,n)}function El(t,e,r,n){return sr(Xi(e),t,r,n)}function Al(t,e,r,n){return sr(Nl(e,t.length-r),t,r,n)}A.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 bl(this,e,r,n);case "utf8":case "utf-8":return _l(this,e,r,n);case "ascii":return Wi(this,e,r,n);case "latin1":case "binary":return wl(this,e,r,n);case "base64":return El(this,e,r,n);case "ucs2":case "ucs-2":case "utf16le":case "utf-16le":return Al(this,e,r,n);default:if(o)throw new TypeError("Unknown encoding: "+i);i=(""+i).toLowerCase(),o=true;}};A.prototype.toJSON=function(){return {type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};function Sl(t,e,r){return e===0&&r===t.length?tn.fromByteArray(t):tn.fromByteArray(t.slice(e,r))}function zi(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,l,d,h;switch(a){case 1:s<128&&(o=s);break;case 2:c=t[i+1],(c&192)===128&&(h=(s&31)<<6|c&63,h>127&&(o=h));break;case 3:c=t[i+1],l=t[i+2],(c&192)===128&&(l&192)===128&&(h=(s&15)<<12|(c&63)<<6|l&63,h>2047&&(h<55296||h>57343)&&(o=h));break;case 4:c=t[i+1],l=t[i+2],d=t[i+3],(c&192)===128&&(l&192)===128&&(d&192)===128&&(h=(s&15)<<18|(c&63)<<12|(l&63)<<6|d&63,h>65535&&h<1114112&&(o=h));}}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 Rl(n)}var Bi=4096;function Rl(t){var e=t.length;if(e<=Bi)return String.fromCharCode.apply(String,t);for(var r="",n=0;n<e;)r+=String.fromCharCode.apply(String,t.slice(n,n+=Bi));return r}function vl(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 Tl(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 Il(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+=kl(t[s]);return i}function Pl(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}A.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(A.TYPED_ARRAY_SUPPORT)i=this.subarray(e,r),i.__proto__=A.prototype;else {var s=r-e;i=new A(s,void 0);for(var o=0;o<s;++o)i[o]=this[o+e];}return i};function z(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")}A.prototype.readUIntLE=function(e,r,n){e=e|0,r=r|0,n||z(e,r,this.length);for(var i=this[e],s=1,o=0;++o<r&&(s*=256);)i+=this[e+o]*s;return i};A.prototype.readUIntBE=function(e,r,n){e=e|0,r=r|0,n||z(e,r,this.length);for(var i=this[e+--r],s=1;r>0&&(s*=256);)i+=this[e+--r]*s;return i};A.prototype.readUInt8=function(e,r){return r||z(e,1,this.length),this[e]};A.prototype.readUInt16LE=function(e,r){return r||z(e,2,this.length),this[e]|this[e+1]<<8};A.prototype.readUInt16BE=function(e,r){return r||z(e,2,this.length),this[e]<<8|this[e+1]};A.prototype.readUInt32LE=function(e,r){return r||z(e,4,this.length),(this[e]|this[e+1]<<8|this[e+2]<<16)+this[e+3]*16777216};A.prototype.readUInt32BE=function(e,r){return r||z(e,4,this.length),this[e]*16777216+(this[e+1]<<16|this[e+2]<<8|this[e+3])};A.prototype.readIntLE=function(e,r,n){e=e|0,r=r|0,n||z(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};A.prototype.readIntBE=function(e,r,n){e=e|0,r=r|0,n||z(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};A.prototype.readInt8=function(e,r){return r||z(e,1,this.length),this[e]&128?(255-this[e]+1)*-1:this[e]};A.prototype.readInt16LE=function(e,r){r||z(e,2,this.length);var n=this[e]|this[e+1]<<8;return n&32768?n|4294901760:n};A.prototype.readInt16BE=function(e,r){r||z(e,2,this.length);var n=this[e+1]|this[e]<<8;return n&32768?n|4294901760:n};A.prototype.readInt32LE=function(e,r){return r||z(e,4,this.length),this[e]|this[e+1]<<8|this[e+2]<<16|this[e+3]<<24};A.prototype.readInt32BE=function(e,r){return r||z(e,4,this.length),this[e]<<24|this[e+1]<<16|this[e+2]<<8|this[e+3]};A.prototype.readFloatLE=function(e,r){return r||z(e,4,this.length),it.read(this,e,true,23,4)};A.prototype.readFloatBE=function(e,r){return r||z(e,4,this.length),it.read(this,e,false,23,4)};A.prototype.readDoubleLE=function(e,r){return r||z(e,8,this.length),it.read(this,e,true,52,8)};A.prototype.readDoubleBE=function(e,r){return r||z(e,8,this.length),it.read(this,e,false,52,8)};function se(t,e,r,n,i,s){if(!A.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")}A.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;se(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};A.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;se(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};A.prototype.writeUInt8=function(e,r,n){return e=+e,r=r|0,n||se(this,e,r,1,255,0),A.TYPED_ARRAY_SUPPORT||(e=Math.floor(e)),this[r]=e&255,r+1};function nr(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;}A.prototype.writeUInt16LE=function(e,r,n){return e=+e,r=r|0,n||se(this,e,r,2,65535,0),A.TYPED_ARRAY_SUPPORT?(this[r]=e&255,this[r+1]=e>>>8):nr(this,e,r,true),r+2};A.prototype.writeUInt16BE=function(e,r,n){return e=+e,r=r|0,n||se(this,e,r,2,65535,0),A.TYPED_ARRAY_SUPPORT?(this[r]=e>>>8,this[r+1]=e&255):nr(this,e,r,false),r+2};function ir(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;}A.prototype.writeUInt32LE=function(e,r,n){return e=+e,r=r|0,n||se(this,e,r,4,4294967295,0),A.TYPED_ARRAY_SUPPORT?(this[r+3]=e>>>24,this[r+2]=e>>>16,this[r+1]=e>>>8,this[r]=e&255):ir(this,e,r,true),r+4};A.prototype.writeUInt32BE=function(e,r,n){return e=+e,r=r|0,n||se(this,e,r,4,4294967295,0),A.TYPED_ARRAY_SUPPORT?(this[r]=e>>>24,this[r+1]=e>>>16,this[r+2]=e>>>8,this[r+3]=e&255):ir(this,e,r,false),r+4};A.prototype.writeIntLE=function(e,r,n,i){if(e=+e,r=r|0,!i){var s=Math.pow(2,8*n-1);se(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};A.prototype.writeIntBE=function(e,r,n,i){if(e=+e,r=r|0,!i){var s=Math.pow(2,8*n-1);se(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};A.prototype.writeInt8=function(e,r,n){return e=+e,r=r|0,n||se(this,e,r,1,127,-128),A.TYPED_ARRAY_SUPPORT||(e=Math.floor(e)),e<0&&(e=255+e+1),this[r]=e&255,r+1};A.prototype.writeInt16LE=function(e,r,n){return e=+e,r=r|0,n||se(this,e,r,2,32767,-32768),A.TYPED_ARRAY_SUPPORT?(this[r]=e&255,this[r+1]=e>>>8):nr(this,e,r,true),r+2};A.prototype.writeInt16BE=function(e,r,n){return e=+e,r=r|0,n||se(this,e,r,2,32767,-32768),A.TYPED_ARRAY_SUPPORT?(this[r]=e>>>8,this[r+1]=e&255):nr(this,e,r,false),r+2};A.prototype.writeInt32LE=function(e,r,n){return e=+e,r=r|0,n||se(this,e,r,4,2147483647,-2147483648),A.TYPED_ARRAY_SUPPORT?(this[r]=e&255,this[r+1]=e>>>8,this[r+2]=e>>>16,this[r+3]=e>>>24):ir(this,e,r,true),r+4};A.prototype.writeInt32BE=function(e,r,n){return e=+e,r=r|0,n||se(this,e,r,4,2147483647,-2147483648),e<0&&(e=4294967295+e+1),A.TYPED_ARRAY_SUPPORT?(this[r]=e>>>24,this[r+1]=e>>>16,this[r+2]=e>>>8,this[r+3]=e&255):ir(this,e,r,false),r+4};function Ji(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 Yi(t,e,r,n,i){return i||Ji(t,e,r,4),it.write(t,e,r,n,23,4),r+4}A.prototype.writeFloatLE=function(e,r,n){return Yi(this,e,r,true,n)};A.prototype.writeFloatBE=function(e,r,n){return Yi(this,e,r,false,n)};function Qi(t,e,r,n,i){return i||Ji(t,e,r,8),it.write(t,e,r,n,52,8),r+8}A.prototype.writeDoubleLE=function(e,r,n){return Qi(this,e,r,true,n)};A.prototype.writeDoubleBE=function(e,r,n){return Qi(this,e,r,false,n)};A.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||!A.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};A.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"&&!A.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=A.isBuffer(e)?e:rr(new A(e,i).toString()),c=a.length;for(o=0;o<n-r;++o)this[o+r]=a[o%c];}return this};var Cl=/[^+\/0-9A-Za-z-_]/g;function xl(t){if(t=Ul(t).replace(Cl,""),t.length<2)return "";for(;t.length%4!==0;)t=t+"=";return t}function Ul(t){return t.trim?t.trim():t.replace(/^\s+|\s+$/g,"")}function kl(t){return t<16?"0"+t.toString(16):t.toString(16)}function rr(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 Dl(t){for(var e=[],r=0;r<t.length;++r)e.push(t.charCodeAt(r)&255);return e}function Nl(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 Xi(t){return tn.toByteArray(xl(t))}function sr(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 Ol(t){return t!==t}});var Zi={};Xt(Zi,{default:()=>Ll});var Fl,Ll,es=tt(()=>{Fl={},Ll=Fl;});var dn={};Xt(dn,{__assign:()=>ln,__asyncDelegator:()=>Ql,__asyncGenerator:()=>Yl,__asyncValues:()=>Xl,__await:()=>vt,__awaiter:()=>Kl,__classPrivateFieldGet:()=>ru,__classPrivateFieldSet:()=>nu,__createBinding:()=>Gl,__decorate:()=>Bl,__exportStar:()=>Wl,__extends:()=>ql,__generator:()=>Hl,__importDefault:()=>tu,__importStar:()=>eu,__makeTemplateObject:()=>Zl,__metadata:()=>jl,__param:()=>$l,__read:()=>ts,__rest:()=>Vl,__spread:()=>zl,__spreadArrays:()=>Jl,__values:()=>un});function ql(t,e){cn(t,e);function r(){this.constructor=t;}t.prototype=e===null?Object.create(e):(r.prototype=e.prototype,new r);}function Vl(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 Bl(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 $l(t,e){return function(r,n){e(r,n,t);}}function jl(t,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(t,e)}function Kl(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(d){try{l(n.next(d));}catch(h){o(h);}}function c(d){try{l(n.throw(d));}catch(h){o(h);}}function l(d){d.done?s(d.value):i(d.value).then(a,c);}l((n=n.apply(t,e||[])).next());})}function Hl(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(l){return function(d){return c([l,d])}}function c(l){if(n)throw new TypeError("Generator is already executing.");for(;r;)try{if(n=1,i&&(s=l[0]&2?i.return:l[0]?i.throw||((s=i.return)&&s.call(i),0):i.next)&&!(s=s.call(i,l[1])).done)return s;switch(i=0,s&&(l=[l[0]&2,s.value]),l[0]){case 0:case 1:s=l;break;case 4:return r.label++,{value:l[1],done:!1};case 5:r.label++,i=l[1],l=[0];continue;case 7:l=r.ops.pop(),r.trys.pop();continue;default:if(s=r.trys,!(s=s.length>0&&s[s.length-1])&&(l[0]===6||l[0]===2)){r=0;continue}if(l[0]===3&&(!s||l[1]>s[0]&&l[1]<s[3])){r.label=l[1];break}if(l[0]===6&&r.label<s[1]){r.label=s[1],s=l;break}if(s&&r.label<s[2]){r.label=s[2],r.ops.push(l);break}s[2]&&r.ops.pop(),r.trys.pop();continue}l=e.call(t,r);}catch(d){l=[6,d],i=0;}finally{n=s=0;}if(l[0]&5)throw l[1];return {value:l[0]?l[1]:void 0,done:true}}}function Gl(t,e,r,n){n===void 0&&(n=r),t[n]=e[r];}function Wl(t,e){for(var r in t)r!=="default"&&!e.hasOwnProperty(r)&&(e[r]=t[r]);}function un(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 ts(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 zl(){for(var t=[],e=0;e<arguments.length;e++)t=t.concat(ts(arguments[e]));return t}function Jl(){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 vt(t){return this instanceof vt?(this.v=t,this):new vt(t)}function Yl(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(u){n[u]&&(i[u]=function(p){return new Promise(function(g,m){s.push([u,p,g,m])>1||a(u,p);})});}function a(u,p){try{c(n[u](p));}catch(g){h(s[0][3],g);}}function c(u){u.value instanceof vt?Promise.resolve(u.value.v).then(l,d):h(s[0][2],u);}function l(u){a("next",u);}function d(u){a("throw",u);}function h(u,p){u(p),s.shift(),s.length&&a(s[0][0],s[0][1]);}}function Ql(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:vt(t[i](o)),done:i==="return"}:s?s(o):o}:s;}}function Xl(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 un=="function"?un(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(l){s({value:l,done:a});},o);}}function Zl(t,e){return Object.defineProperty?Object.defineProperty(t,"raw",{value:e}):t.raw=e,t}function eu(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 tu(t){return t&&t.__esModule?t:{default:t}}function ru(t,e){if(!e.has(t))throw new TypeError("attempted to get private field on non-instance");return e.get(t)}function nu(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 cn,ln,fn=tt(()=>{cn=function(t,e){return cn=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]);},cn(t,e)};ln=function(){return ln=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},ln.apply(this,arguments)};});var hn=ie(pe=>{Object.defineProperty(pe,"__esModule",{value:true});pe.MAX_HASHABLE_LENGTH=pe.INIT=pe.KEY=pe.DIGEST_LENGTH=pe.BLOCK_SIZE=void 0;pe.BLOCK_SIZE=64;pe.DIGEST_LENGTH=32;pe.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]);pe.INIT=[1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225];pe.MAX_HASHABLE_LENGTH=Math.pow(2,53)-1;});var rs=ie(ar=>{Object.defineProperty(ar,"__esModule",{value:true});ar.RawSha256=void 0;var ge=hn(),iu=(function(){function t(){this.state=Int32Array.from(ge.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>ge.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===ge.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%ge.BLOCK_SIZE>=ge.BLOCK_SIZE-8){for(var i=this.bufferLength;i<ge.BLOCK_SIZE;i++)r.setUint8(i,0);this.hashBuffer(),this.bufferLength=0;}for(var i=this.bufferLength;i<ge.BLOCK_SIZE-8;i++)r.setUint8(i,0);r.setUint32(ge.BLOCK_SIZE-8,Math.floor(e/4294967296),true),r.setUint32(ge.BLOCK_SIZE-4,e),this.hashBuffer(),this.finished=true;}for(var s=new Uint8Array(ge.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],l=n[5],d=n[6],h=n[7],u=0;u<ge.BLOCK_SIZE;u++){if(u<16)this.temp[u]=(r[u*4]&255)<<24|(r[u*4+1]&255)<<16|(r[u*4+2]&255)<<8|r[u*4+3]&255;else {var p=this.temp[u-2],g=(p>>>17|p<<15)^(p>>>19|p<<13)^p>>>10;p=this.temp[u-15];var m=(p>>>7|p<<25)^(p>>>18|p<<14)^p>>>3;this.temp[u]=(g+this.temp[u-7]|0)+(m+this.temp[u-16]|0);}var y=(((c>>>6|c<<26)^(c>>>11|c<<21)^(c>>>25|c<<7))+(c&l^~c&d)|0)+(h+(ge.KEY[u]+this.temp[u]|0)|0)|0,b=((i>>>2|i<<30)^(i>>>13|i<<19)^(i>>>22|i<<10))+(i&s^i&o^s&o)|0;h=d,d=l,l=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]+=l,n[6]+=d,n[7]+=h;},t})();ar.RawSha256=iu;});var ns,is,ss=tt(()=>{ns=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)},is=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 os(t){return new TextEncoder().encode(t)}function as(t){return new TextDecoder("utf-8").decode(t)}var cs=tt(()=>{});var ls={};Xt(ls,{fromUtf8:()=>su,toUtf8:()=>ou});var su,ou,us=tt(()=>{ss();cs();su=t=>typeof TextEncoder=="function"?os(t):ns(t),ou=t=>typeof TextDecoder=="function"?as(t):is(t);});var ds=ie(cr=>{Object.defineProperty(cr,"__esModule",{value:true});cr.convertToBuffer=void 0;var au=(us(),nt(ls)),cu=typeof Buffer<"u"&&Buffer.from?function(t){return Buffer.from(t,"utf8")}:au.fromUtf8;function lu(t){return t instanceof Uint8Array?t:typeof t=="string"?cu(t):ArrayBuffer.isView(t)?new Uint8Array(t.buffer,t.byteOffset,t.byteLength/Uint8Array.BYTES_PER_ELEMENT):new Uint8Array(t)}cr.convertToBuffer=lu;});var fs=ie(lr=>{Object.defineProperty(lr,"__esModule",{value:true});lr.isEmptyData=void 0;function uu(t){return typeof t=="string"?t.length===0:t.byteLength===0}lr.isEmptyData=uu;});var hs=ie(ur=>{Object.defineProperty(ur,"__esModule",{value:true});ur.numToUint8=void 0;function du(t){return new Uint8Array([(t&4278190080)>>24,(t&16711680)>>16,(t&65280)>>8,t&255])}ur.numToUint8=du;});var ps=ie(dr=>{Object.defineProperty(dr,"__esModule",{value:true});dr.uint32ArrayFrom=void 0;function fu(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)}dr.uint32ArrayFrom=fu;});var gs=ie(Ie=>{Object.defineProperty(Ie,"__esModule",{value:true});Ie.uint32ArrayFrom=Ie.numToUint8=Ie.isEmptyData=Ie.convertToBuffer=void 0;var hu=ds();Object.defineProperty(Ie,"convertToBuffer",{enumerable:true,get:function(){return hu.convertToBuffer}});var pu=fs();Object.defineProperty(Ie,"isEmptyData",{enumerable:true,get:function(){return pu.isEmptyData}});var gu=hs();Object.defineProperty(Ie,"numToUint8",{enumerable:true,get:function(){return gu.numToUint8}});var mu=ps();Object.defineProperty(Ie,"uint32ArrayFrom",{enumerable:true,get:function(){return mu.uint32ArrayFrom}});});var ys=ie(hr=>{Object.defineProperty(hr,"__esModule",{value:true});hr.Sha256=void 0;var ms=(fn(),nt(dn)),fr=hn(),pn=rs(),gn=gs(),yu=(function(){function t(e){if(this.hash=new pn.RawSha256,e){this.outer=new pn.RawSha256;var r=bu(e),n=new Uint8Array(fr.BLOCK_SIZE);n.set(r);for(var i=0;i<fr.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, gn.isEmptyData)(e)||this.error))try{this.hash.update((0,gn.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, ms.__awaiter)(this,void 0,void 0,function(){return (0, ms.__generator)(this,function(e){return [2,this.digestSync()]})})},t})();hr.Sha256=yu;function bu(t){var e=(0, gn.convertToBuffer)(t);if(e.byteLength>fr.BLOCK_SIZE){var r=new pn.RawSha256;r.update(e),e=r.digest();}var n=new Uint8Array(fr.BLOCK_SIZE);return n.set(e),n}});var yn=ie(mn=>{Object.defineProperty(mn,"__esModule",{value:true});var _u=(fn(),nt(dn));(0, _u.__exportStar)(ys(),mn);});var Tn={};Xt(Tn,{default:()=>hd});function hd(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(d){return a[d.toLowerCase()]},has:function(d){return d.toLowerCase()in a}}}};for(var l in i.open(e.method||"get",t,true),i.onload=function(){i.getAllResponseHeaders().replace(/^(.*?):[^\S\n]*([\s\S]*?)$/gm,function(d,h,u){s.push(h=h.toLowerCase()),o.push([h,u]),a[h]=a[h]?a[h]+","+u:u;}),r(c());},i.onerror=n,i.withCredentials=e.credentials=="include",e.headers)i.setRequestHeader(l,e.headers[l]);i.send(e.body||null);})}var In=tt(()=>{});var Ts=ie((ap,vs)=>{vs.exports=self.fetch||(self.fetch=(In(),nt(Tn)).default||(In(),nt(Tn)));});function Di(t){let r=(typeof globalThis<"u"?globalThis:void 0)?.process;if(r&&typeof r.getBuiltinModule=="function")try{return r.getBuiltinModule(t)}catch{}try{if(typeof Be=="function")return Be(t)}catch{}return null}var zr,Jr,Yr=()=>zr!==void 0?zr:zr=Di("fs"),Qr=()=>Jr!==void 0?Jr:Jr=Di("path"),De=typeof globalThis<"u"?globalThis:void 0,Zt=De?.window;function rl(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(Zt)Zt.global=Zt,Zt.global._runningInNodeJS=false;else if(De&&(De.global=De,typeof De.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=rl(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});});}}De.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);});}}De.XMLHttpRequest=e,De.window={_runningInNodeJS:true,alert:r=>console.error("[Alert]",r),sessionStorage:{getItem:r=>null,setItem:(r,n)=>{},removeItem:r=>{}},localStorage:{getItem:r=>{let n=Yr(),i=Qr();if(!n||!i)return null;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=Yr(),s=Qr();if(!(!i||!s))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=Yr(),i=Qr();if(!(!n||!i))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/${De?.process?.versions?.node||"unknown"}`,mediaDevices:{getUserMedia:async r=>{throw new Error("getUserMedia is not supported in Node.js environment.")}}},addEventListener:()=>{},removeEventListener:()=>{}};}var Xr=(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 Oe=rt(or());var he;typeof window<"u"&&window.crypto&&(he=window.crypto);!he&&typeof window<"u"&&window.msCrypto&&(he=window.msCrypto);!he&&typeof globalThis<"u"&&globalThis.crypto&&(he=globalThis.crypto);if(!he&&typeof Be=="function")try{he=(es(),nt(Zi));}catch{}function on(){if(he){if(typeof he.getRandomValues=="function")try{return he.getRandomValues(new Uint32Array(1))[0]}catch{}if(typeof he.randomBytes=="function")try{return he.randomBytes(4).readInt32LE()}catch{}}throw new Error("Native crypto module could not be used to get secure random number.")}function Ml(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 an=(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(on());return new t(i,n)},e.toString=function(){return Ml(this)},t})();var gr=rt(yn());var G=F;function F(t,e){t!=null&&this.fromString(t,e);}function re(){return new F(null)}var $e,wu=0xdeadbeefcafe,bs=(wu&16777215)==15715070;function Eu(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 Au(t,e,r,n,i,s){for(var o=e&32767,a=e>>15;--s>=0;){var c=this[t]&32767,l=this[t++]>>15,d=a*c+l*o;c=o*c+((d&32767)<<15)+r[n]+(i&1073741823),i=(c>>>30)+(d>>>15)+a*l+(i>>>30),r[n++]=c&1073741823;}return i}function Su(t,e,r,n,i,s){for(var o=e&16383,a=e>>14;--s>=0;){var c=this[t]&16383,l=this[t++]>>14,d=a*c+l*o;c=o*c+((d&16383)<<14)+r[n]+i,i=(c>>28)+(d>>14)+a*l,r[n++]=c&268435455;}return i}var _s=typeof navigator<"u";_s&&bs&&navigator.appName=="Microsoft Internet Explorer"?(F.prototype.am=Au,$e=30):_s&&bs&&navigator.appName!="Netscape"?(F.prototype.am=Eu,$e=26):(F.prototype.am=Su,$e=28);F.prototype.DB=$e;F.prototype.DM=(1<<$e)-1;F.prototype.DV=1<<$e;var bn=52;F.prototype.FV=Math.pow(2,bn);F.prototype.F1=bn-$e;F.prototype.F2=2*$e-bn;var Ru="0123456789abcdefghijklmnopqrstuvwxyz",pr=new Array,ot,me;ot=48;for(me=0;me<=9;++me)pr[ot++]=me;ot=97;for(me=10;me<36;++me)pr[ot++]=me;ot=65;for(me=10;me<36;++me)pr[ot++]=me;function ws(t){return Ru.charAt(t)}function vu(t,e){var r=pr[t.charCodeAt(e)];return r??-1}function Tu(t){for(var e=this.t-1;e>=0;--e)t[e]=this[e];t.t=this.t,t.s=this.s;}function Iu(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 _n(t){var e=re();return e.fromInt(t),e}function Pu(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=vu(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&&F.ZERO.subTo(this,this);}function Cu(){for(var t=this.s&this.DM;this.t>0&&this[this.t-1]==t;)--this.t;}function xu(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=ws(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+=ws(n));return i?s:"0"}function Uu(){var t=re();return F.ZERO.subTo(this,t),t}function ku(){return this.s<0?this.negate():this}function Du(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 wn(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 Nu(){return this.t<=0?0:this.DB*(this.t-1)+wn(this[this.t-1]^this.s&this.DM)}function Ou(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 Fu(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 Lu(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 Mu(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 qu(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 Vu(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&&F.ZERO.subTo(e,e);}function Bu(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 $u(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=re());var s=re(),o=this.s,a=t.s,c=this.DB-wn(n[n.t-1]);c>0?(n.lShiftTo(c,s),i.lShiftTo(c,r)):(n.copyTo(s),i.copyTo(r));var l=s.t,d=s[l-1];if(d!=0){var h=d*(1<<this.F1)+(l>1?s[l-2]>>this.F2:0),u=this.FV/h,p=(1<<this.F1)/h,g=1<<this.F2,m=r.t,y=m-l,b=e??re();for(s.dlShiftTo(y,b),r.compareTo(b)>=0&&(r[r.t++]=1,r.subTo(b,r)),F.ONE.dlShiftTo(l,b),b.subTo(s,s);s.t<l;)s[s.t++]=0;for(;--y>=0;){var w=r[--m]==d?this.DM:Math.floor(r[m]*u+(r[m-1]+g)*p);if((r[m]+=s.am(0,w,r,y,0,l))<w)for(s.dlShiftTo(y,b),r.subTo(b,r);r[m]<--w;)r.subTo(b,r);}e!=null&&(r.drShiftTo(l,e),o!=a&&F.ZERO.subTo(e,e)),r.t=l,r.clamp(),c>0&&r.rShiftTo(c,r),o<0&&F.ZERO.subTo(r,r);}}}function ju(t){var e=re();return this.abs().divRemTo(t,null,e),this.s<0&&e.compareTo(F.ZERO)>0&&t.subTo(e,e),e}function Ku(){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 Hu(t){return this.compareTo(t)==0}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>0?e[r++]=n:n<-1&&(e[r++]=this.DV+n),e.t=r,e.clamp();}function Wu(t){var e=re();return this.addTo(t,e),e}function zu(t){var e=re();return this.subTo(t,e),e}function Ju(t){var e=re();return this.multiplyTo(t,e),e}function Yu(t){var e=re();return this.divRemTo(t,e,null),e}function at(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 Qu(t){var e=re();return t.abs().dlShiftTo(this.m.t,e),e.divRemTo(this.m,null,e),t.s<0&&e.compareTo(F.ZERO)>0&&this.m.subTo(e,e),e}function Xu(t){var e=re();return t.copyTo(e),this.reduce(e),e}function Zu(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 ed(t,e){t.squareTo(e),this.reduce(e);}function td(t,e,r){t.multiplyTo(e,r),this.reduce(r);}at.prototype.convert=Qu;at.prototype.revert=Xu;at.prototype.reduce=Zu;at.prototype.mulTo=td;at.prototype.sqrTo=ed;function rd(t,e,r){var n=t.bitLength(),i,s=_n(1),o=new at(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,l=i-1,d=(1<<i)-1;if(a[1]=o.convert(this),i>1){var h=re();for(o.sqrTo(a[1],h);c<=d;)a[c]=re(),o.mulTo(h,a[c-2],a[c]),c+=2;}var u=t.t-1,p,g=true,m=re(),y;for(n=wn(t[u])-1;u>=0;){for(n>=l?p=t[u]>>n-l&d:(p=(t[u]&(1<<n+1)-1)<<l-n,u>0&&(p|=t[u-1]>>this.DB+n-l)),c=i;(p&1)==0;)p>>=1,--c;if((n-=c)<0&&(n+=this.DB,--u),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(;u>=0&&(t[u]&1<<n)==0;)o.sqrTo(s,m),y=s,s=m,m=y,--n<0&&(n=this.DB-1,--u);}var b=o.revert(s);return r(null,b),b}F.prototype.copyTo=Tu;F.prototype.fromInt=Iu;F.prototype.fromString=Pu;F.prototype.clamp=Cu;F.prototype.dlShiftTo=Ou;F.prototype.drShiftTo=Fu;F.prototype.lShiftTo=Lu;F.prototype.rShiftTo=Mu;F.prototype.subTo=qu;F.prototype.multiplyTo=Vu;F.prototype.squareTo=Bu;F.prototype.divRemTo=$u;F.prototype.invDigit=Ku;F.prototype.addTo=Gu;F.prototype.toString=xu;F.prototype.negate=Uu;F.prototype.abs=ku;F.prototype.compareTo=Du;F.prototype.bitLength=Nu;F.prototype.mod=ju;F.prototype.equals=Hu;F.prototype.add=Wu;F.prototype.subtract=zu;F.prototype.multiply=Ju;F.prototype.divide=Yu;F.prototype.modPow=rd;F.ZERO=_n(0);F.ONE=_n(1);function En(t){return Oe.Buffer.from(new an().random(t).toString(),"hex")}var nd=/^[89a-f]/i,id="FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E088A67CC74020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7EDEE386BFB5A899FA5AE9F24117C4B1FE649286651ECE45B3DC2007CB8A163BF0598DA48361C55D39A69163FA8FD24CF5F83655D23DCA3AD961C62F356208552BB9ED529077096966D670C354E4ABC9804F1746C08CA18217C32905E462E36CE3BE39E772C180E86039B2783A2EC07A28FB5C55DF06F4C52C9DE2BCBF6955817183995497CEA956AE515D2261898FA051015728E5A8AAAC42DAD33170D04507A33A85521ABDF1CBA64ECFB850458DBEF0A8AEA71575D060C7DB3970F85A6E1E4C7ABF5AE8CDB0933D71E8C94E04A25619DCEE3D2261AD2EE6BF12FFA06D98A0864D87602733EC86A64521F2B18177B200CBBE117577A615D6C770988C0BAD946E208E24FA074E5AB3143DB5BFCE0FD108E4B82D120A93AD2CAFFFFFFFFFFFFFFFF",sd="userAttributes.",je=(function(){function t(r){this.N=new G(id,16),this.g=new G("2",16),this.k=new G(this.hexHash(""+this.padHex(this.N)+this.padHex(this.g)),16),this.smallAValue=this.generateRandomSmallA(),this.getLargeAValue(function(){}),this.infoBits=Oe.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=En(128).toString("hex"),i=new G(n,16);return i},e.generateRandomString=function(){return En(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),l=En(16).toString("hex");this.SaltToHashDevices=this.padHex(new G(l,16)),this.g.modPow(new G(this.hexHash(this.SaltToHashDevices+c),16),this.N,function(d,h){d&&s(d,null),o.verifierDevices=o.padHex(h),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(G.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 G(this.UHexHash,16);return s},e.hash=function(n){var i=new gr.Sha256;i.update(n);var s=i.digestSync(),o=Oe.Buffer.from(s).toString("hex");return new Array(64-o.length).join("0")+o},e.hexHash=function(n){return this.hash(Oe.Buffer.from(n,"hex"))},e.computehkdf=function(n,i){var s=Oe.Buffer.concat([this.infoBits,Oe.Buffer.from("","utf8")]),o=new gr.Sha256(i);o.update(n);var a=o.digestSync(),c=new gr.Sha256(a);c.update(s);var l=c.digestSync(),d=l,h=d.slice(0,16);return h},e.getPasswordAuthenticationKey=function(n,i,s,o,a){var c=this;if(s.mod(this.N).equals(G.ZERO))throw new Error("B cannot be zero.");if(this.UValue=this.calculateU(this.largeAValue,s),this.UValue.equals(G.ZERO))throw new Error("U cannot be zero.");var l=""+this.poolName+n+":"+i,d=this.hash(l),h=new G(this.hexHash(this.padHex(o)+d),16);this.calculateS(h,s,function(u,p){u&&a(u,null);var g=c.computehkdf(Oe.Buffer.from(c.padHex(p),"hex"),Oe.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 l=i.subtract(o.k.multiply(c));l.modPow(o.smallAValue.add(o.UValue.multiply(n)),o.N,function(d,h){d&&s(d,null),s(null,h.mod(o.N));});});},e.getNewPasswordRequiredChallengeUserAttributePrefix=function(){return sd},e.padHex=function(n){if(!(n instanceof G))throw new Error("Not a BigInteger");var i=n.compareTo(G.ZERO)<0,s=n.abs().toString(16);if(s=s.length%2!==0?"0"+s:s,s=nd.test(s)?"00"+s:s,i){var o=s.split("").map(function(c){var l=~parseInt(c,16)&15;return "0123456789ABCDEF".charAt(l)}).join(""),a=new G(o,16).add(G.ONE);s=a.toString(16),s.toUpperCase().startsWith("FF8")&&(s=s.substring(2));}return s},t})();var Es=rt(or());var mr=(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(Es.Buffer.from(n,"base64").toString("utf8"))}catch{return {}}},t})();function od(t,e){t.prototype=Object.create(e.prototype),t.prototype.constructor=t,An(t,e);}function An(t,e){return An=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(r,n){return r.__proto__=n,r},An(t,e)}var ct=(function(t){function e(r){var n=r===void 0?{}:r,i=n.AccessToken;return t.call(this,i||"")||this}return od(e,t),e})(mr);function ad(t,e){t.prototype=Object.create(e.prototype),t.prototype.constructor=t,Sn(t,e);}function Sn(t,e){return Sn=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(r,n){return r.__proto__=n,r},Sn(t,e)}var lt=(function(t){function e(r){var n=r===void 0?{}:r,i=n.IdToken;return t.call(this,i||"")||this}return ad(e,t),e})(mr);var ut=(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=rt(or()),vn=rt(yn());var As="5.0.4";var cd="aws-amplify/"+As,Rn={userAgent:cd,isReactNative:typeof navigator<"u"&&navigator.product==="ReactNative"},Ss=function(){return Rn.userAgent};var dt=(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 ld=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],ud=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],yr=(function(){function t(){}var e=t.prototype;return e.getNowString=function(){var n=new Date,i=ud[n.getUTCDay()],s=ld[n.getUTCMonth()],o=n.getUTCDate(),a=n.getUTCHours();a<10&&(a="0"+a);var c=n.getUTCMinutes();c<10&&(c="0"+c);var l=n.getUTCSeconds();l<10&&(l="0"+l);var d=n.getUTCFullYear(),h=i+" "+s+" "+o+" "+a+":"+c+":"+l+" UTC "+d;return h},t})();var Pe=(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 Je={},dd=(function(){function t(){}return t.setItem=function(r,n){return Je[r]=n,Je[r]},t.getItem=function(r){return Object.prototype.hasOwnProperty.call(Je,r)?Je[r]:void 0},t.removeItem=function(r){return delete Je[r]},t.clear=function(){return Je={},Je},t})(),br=(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=dd;}}var e=t.prototype;return e.getStorage=function(){return this.storageWindow},t})();var fd=typeof navigator<"u",Rs=fd?Rn.isReactNative?"react-native":navigator.userAgent:"nodejs",Fe=(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 br().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(l,d){if(l)return i.onFailure(l);var h=d.ChallengeName,u=d.ChallengeParameters;return h==="CUSTOM_CHALLENGE"?(s.Session=d.Session,i.customChallenge(u)):(s.signInUserSession=s.getCognitoUserSession(d.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 je(this.pool.getUserPoolName()),a=new yr,c,l,d={};this.deviceKey!=null&&(d.DEVICE_KEY=this.deviceKey),d.USERNAME=this.username,o.getLargeAValue(function(h,u){h&&i.onFailure(h),d.SRP_A=u.toString(16),s.authenticationFlowType==="CUSTOM_AUTH"&&(d.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:d,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 G(b.SRP_B,16),l=new G(b.SALT,16),s.getCachedDeviceKeyAndPassword(),o.getPasswordAuthenticationKey(s.username,n.getPassword(),c,l,function(w,E){w&&i.onFailure(w);var R=a.getNowString(),S=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(R,"utf8")]),U=new vn.Sha256(E);U.update(S);var k=U.digestSync(),N=J.Buffer.from(k).toString("base64"),x={};x.USERNAME=s.username,x.PASSWORD_CLAIM_SECRET_BLOCK=b.SECRET_BLOCK,x.TIMESTAMP=R,x.PASSWORD_CLAIM_SIGNATURE=N,s.deviceKey!=null&&(x.DEVICE_KEY=s.deviceKey);var D=function(ee,ne){return s.client.request("RespondToAuthChallenge",ee,function(M,Q){return M&&M.code==="ResourceNotFoundException"&&M.message.toLowerCase().indexOf("device")!==-1?(x.DEVICE_KEY=null,s.deviceKey=null,s.randomPassword=null,s.deviceGroupKey=null,s.clearCachedDeviceKeyAndPassword(),D(ee,ne)):ne(M,Q)})},L={ChallengeName:"PASSWORD_VERIFIER",ClientId:s.pool.getClientId(),ChallengeResponses:x,Session:y.Session,ClientMetadata:p};s.getUserContextData()&&(L.UserContextData=s.getUserContextData()),D(L,function(B,ee){return B?i.onFailure(B):s.authenticateUserInternal(ee,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 je(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(),l={AuthFlow:"USER_PASSWORD_AUTH",ClientId:this.pool.getClientId(),AuthParameters:o,ClientMetadata:c};this.getUserContextData(this.username)&&(l.UserContextData=this.getUserContextData(this.username)),this.client.request("InitiateAuth",l,function(d,h){return d?i.onFailure(d):s.authenticateUserInternal(h,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 l=null,d=null,h=[],u=i.getNewPasswordRequiredChallengeUserAttributePrefix();if(c&&(l=JSON.parse(n.ChallengeParameters.userAttributes),d=JSON.parse(n.ChallengeParameters.requiredAttributes)),d)for(var p=0;p<d.length;p++)h[p]=d[p].substr(u.length);return s.newPasswordRequired(l,h)}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:Rs},function(b,w){return b?s.onFailure(b):(o.deviceKey=n.AuthenticationResult.NewDeviceMetadata.DeviceKey,o.cacheDeviceKeyAndPassword(),w.UserConfirmationNecessary===true?s.onSuccess(o.signInUserSession,w.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 je(this.pool.getUserPoolName()),l=c.getNewPasswordRequiredChallengeUserAttributePrefix(),d={};i&&Object.keys(i).forEach(function(u){d[l+u]=i[u];}),d.NEW_PASSWORD=n,d.USERNAME=this.username;var h={ChallengeName:"NEW_PASSWORD_REQUIRED",ClientId:this.pool.getClientId(),ChallengeResponses:d,Session:this.Session,ClientMetadata:o};this.getUserContextData()&&(h.UserContextData=this.getUserContextData()),this.client.request("RespondToAuthChallenge",h,function(u,p){return u?s.onFailure(u):a.authenticateUserInternal(p,c,s)});},e.getDeviceResponse=function(n,i){var s=this,o=new je(this.deviceGroupKey),a=new yr,c={};c.USERNAME=this.username,c.DEVICE_KEY=this.deviceKey,o.getLargeAValue(function(l,d){l&&n.onFailure(l),c.SRP_A=d.toString(16);var h={ChallengeName:"DEVICE_SRP_AUTH",ClientId:s.pool.getClientId(),ChallengeResponses:c,ClientMetadata:i,Session:s.Session};s.getUserContextData()&&(h.UserContextData=s.getUserContextData()),s.client.request("RespondToAuthChallenge",h,function(u,p){if(u)return n.onFailure(u);var g=p.ChallengeParameters,m=new G(g.SRP_B,16),y=new G(g.SALT,16);o.getPasswordAuthenticationKey(s.deviceKey,s.randomPassword,m,y,function(b,w){if(b)return n.onFailure(b);var E=a.getNowString(),R=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(E,"utf8")]),S=new vn.Sha256(w);S.update(R);var U=S.digestSync(),k=J.Buffer.from(U).toString("base64"),N={};N.USERNAME=s.username,N.PASSWORD_CLAIM_SECRET_BLOCK=g.SECRET_BLOCK,N.TIMESTAMP=E,N.PASSWORD_CLAIM_SIGNATURE=k,N.DEVICE_KEY=s.deviceKey;var x={ChallengeName:"DEVICE_PASSWORD_VERIFIER",ClientId:s.pool.getClientId(),ChallengeResponses:N,Session:p.Session};s.getUserContextData()&&(x.UserContextData=s.getUserContextData()),s.client.request("RespondToAuthChallenge",x,function(D,L){return D?n.onFailure(D):(s.signInUserSession=s.getCognitoUserSession(L.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 je(this.pool.getUserPoolName());this.getCachedDeviceKeyAndPassword(),this.deviceKey!=null&&(a.DEVICE_KEY=this.deviceKey);var l={ChallengeName:"CUSTOM_CHALLENGE",ChallengeResponses:a,ClientId:this.pool.getClientId(),Session:this.Session,ClientMetadata:s};this.getUserContextData()&&(l.UserContextData=this.getUserContextData()),this.client.request("RespondToAuthChallenge",l,function(d,h){return d?i.onFailure(d):o.authenticateUserInternal(h,c,i)});},e.sendMFACode=function(n,i,s,o){var a=this,c={};c.USERNAME=this.username,c.SMS_MFA_CODE=n;var l=s||"SMS_MFA";l==="SOFTWARE_TOKEN_MFA"&&(c.SOFTWARE_TOKEN_MFA_CODE=n),this.deviceKey!=null&&(c.DEVICE_KEY=this.deviceKey);var d={ChallengeName:l,ChallengeResponses:c,ClientId:this.pool.getClientId(),Session:this.Session,ClientMetadata:o};this.getUserContextData()&&(d.UserContextData=this.getUserContextData()),this.client.request("RespondToAuthChallenge",d,function(h,u){if(h)return i.onFailure(h);var p=u.ChallengeName;if(p==="DEVICE_SRP_AUTH"){a.getDeviceResponse(i);return}if(a.signInUserSession=a.getCognitoUserSession(u.AuthenticationResult),a.cacheTokens(),u.AuthenticationResult.NewDeviceMetadata==null)return i.onSuccess(a.signInUserSession);var g=new je(a.pool.getUserPoolName());g.generateHashDevice(u.AuthenticationResult.NewDeviceMetadata.DeviceGroupKey,u.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=u.AuthenticationResult.NewDeviceMetadata.DeviceGroupKey,a.randomPassword=g.getRandomPassword(),a.client.request("ConfirmDevice",{DeviceKey:u.AuthenticationResult.NewDeviceMetadata.DeviceKey,AccessToken:a.signInUserSession.getAccessToken().getJwtToken(),DeviceSecretVerifierConfig:y,DeviceName:Rs},function(b,w){return b?i.onFailure(b):(a.deviceKey=u.AuthenticationResult.NewDeviceMetadata.DeviceKey,a.cacheDeviceKeyAndPassword(),w.UserConfirmationNecessary===true?i.onSuccess(a.signInUserSession,w.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},l=new Pe(c);o.push(l);}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",l=s+".clockDrift";if(this.storage.getItem(o)){var d=new lt({IdToken:this.storage.getItem(o)}),h=new ct({AccessToken:this.storage.getItem(a)}),u=new ut({RefreshToken:this.storage.getItem(c)}),p=parseInt(this.storage.getItem(l),0)||0,g={IdToken:d,AccessToken:h,RefreshToken:u,ClockDrift:p},m=new dt(g);if(m.isValid())return this.signInUserSession=m,n(null,this.signInUserSession);if(!u.getToken())return n(new Error("Cannot retrieve a new session. Please authenticate."),null);this.refreshSession(u,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 l="CognitoIdentityServiceProvider."+this.pool.getClientId(),d=l+".LastAuthUser";if(this.storage.getItem(d)){this.username=this.storage.getItem(d);var h=l+"."+this.username+".deviceKey";this.deviceKey=this.storage.getItem(h),c.DEVICE_KEY=this.deviceKey;}var u={ClientId:this.pool.getClientId(),AuthFlow:"REFRESH_TOKEN_AUTH",AuthParameters:c,ClientMetadata:s};this.getUserContextData()&&(u.UserContextData=this.getUserContextData()),this.client.requestWithRetry("InitiateAuth",u,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 lt(n),s=new ct(n),o=new ut(n),a={IdToken:i,AccessToken:s,RefreshToken:o};return new dt(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,l){if(c)return i.onFailure(c);if(s.Session=l.Session,n==="SMS_MFA")return i.mfaRequired(l.ChallengeName,l.ChallengeParameters);if(n==="SOFTWARE_TOKEN_MFA")return i.totpRequired(l.ChallengeName,l.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 l={};l.USERNAME=o.username;var d={ChallengeName:"MFA_SETUP",ClientId:o.pool.getClientId(),ChallengeResponses:l,Session:o.Session};o.getUserContextData()&&(d.UserContextData=o.getUserContextData()),o.client.request("RespondToAuthChallenge",d,function(h,u){return h?s.onFailure(h):(o.signInUserSession=o.getCognitoUserSession(u.AuthenticationResult),o.cacheTokens(),s.onSuccess(o.signInUserSession))});});},t})();rt(Ts());function ft(){}ft.prototype.userAgent=Ss();var Is=function(e){var r=ft.category?" "+ft.category:"",n=ft.framework?" framework/"+ft.framework:"",i=""+ft.prototype.userAgent+r+n;return i};function pd(t,e){t.prototype=Object.create(e.prototype),t.prototype.constructor=t,Tt(t,e);}function Pn(t){var e=typeof Map=="function"?new Map:void 0;return Pn=function(n){if(n===null||!md(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 gd(n,arguments,Cn(this).constructor)}return i.prototype=Object.create(n.prototype,{constructor:{value:i,enumerable:false,writable:true,configurable:true}}),Tt(i,n)},Pn(t)}function gd(t,e,r){if(Ps())return Reflect.construct.apply(null,arguments);var n=[null];n.push.apply(n,e);var i=new(t.bind.apply(t,n));return r&&Tt(i,r.prototype),i}function Ps(){try{var t=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}));}catch{}return (Ps=function(){return !!t})()}function md(t){try{return Function.toString.call(t).indexOf("[native code]")!==-1}catch{return typeof t=="function"}}function Tt(t,e){return Tt=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(r,n){return r.__proto__=n,r},Tt(t,e)}function Cn(t){return Cn=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(e){return e.__proto__||Object.getPrototypeOf(e)},Cn(t)}var yd=(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 pd(e,t),e})(Pn(Error)),Cs=(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,l){c?a(new yd(c.message,c.code,c.name,c.statusCode)):o(l);});})},e.requestWithRetry=function(n,i,s){var o=this,a=5*1e3;Ed(function(c){return new Promise(function(l,d){o.request(n,c,function(h,u){h?d(h):l(u);});})},[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":Is(),"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(d){return c=d,d},function(d){throw d instanceof TypeError?new Error("Network error"):d}).then(function(d){return d.json().catch(function(){return {}})}).then(function(d){if(c.ok)return s(null,d);var h=(d.__type||d.code).split("#").pop(),u=new Error(d.message||d.Message||null);return u.name=h,u.code=h,s(u)}).catch(function(d){if(c&&c.headers&&c.headers.get("x-amzn-errortype"))try{var h=c.headers.get("x-amzn-errortype").split(":")[0],u=new Error(c.status?c.status.toString():null);return u.code=h,u.name=h,u.statusCode=c.status,s(u)}catch{return s(d)}else d instanceof Error&&d.message==="Network error"&&(d.code="NetworkError");return s(d)});},t})();var _r={debug:function(){}};var bd=function(e){var r="nonRetryable";return e&&e[r]};function xs(t,e,r,n){if(n===void 0&&(n=1),typeof t!="function")throw Error("functionToRetry must be a function");return _r.debug(t.name+" attempt #"+n+" with args: "+JSON.stringify(e)),t.apply(void 0,e).catch(function(i){if(_r.debug("error on "+t.name,i),bd(i))throw _r.debug(t.name+" non retryable error",i),i;var s=r(n,e,i);if(_r.debug(t.name+" retrying in "+s+" ms"),s!==false)return new Promise(function(o){return setTimeout(o,s)}).then(function(){return xs(t,e,r,n+1)});throw i})}function _d(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 Ed(t,e,r){return xs(t,e,_d(r))}var Ad=55,xn=(function(){function t(r,n){var i=r||{},s=i.UserPoolId,o=i.ClientId,a=i.endpoint,c=i.fetchOptions,l=i.AdvancedSecurityDataCollectionFlag;if(!s||!o)throw new Error("Both UserPoolId and ClientId are required.");if(s.length>Ad||!/^[\w-]+_[0-9a-zA-Z]+$/.test(s))throw new Error("Invalid UserPoolId format.");var d=s.split("_")[0];this.userPoolId=s,this.clientId=o,this.client=new Cs(d,a,c),this.advancedSecurityDataCollectionFlag=l!==false,this.storage=r.Storage||new br().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 l=this,d={ClientId:this.clientId,Username:n,Password:i,UserAttributes:s,ValidationData:o,ClientMetadata:c};this.getUserContextData(n)&&(d.UserContextData=this.getUserContextData(n)),this.client.request("SignUp",d,function(h,u){if(h)return a(h,null);var p={Username:n,Pool:l,Storage:l.storage},g={user:new Fe(p),userConfirmed:u.UserConfirmed,userSub:u.UserSub,codeDeliveryDetails:u.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 Fe(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 wr(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 Sd={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 Un(t,e){function r(i,s,o){if(!(typeof document>"u")){o=wr({},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("="),l=c.slice(1).join("=");try{var d=decodeURIComponent(c[0]);if(d in o||(o[d]=t.read(l,d)),i===d)break}catch{}}return i?o[i]:o}}return Object.create({set:r,get:n,remove:function(i,s){r(i,"",wr({},s,{expires:-1}));},withAttributes:function(i){return Un(this.converter,wr({},this.attributes,i))},withConverter:function(i){return Un(wr({},this.converter,i),this.attributes)}},{attributes:{value:Object.freeze(e)},converter:{value:Object.freeze(t)}})}Un(Sd,{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 Le="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",kn=BigInt(Le.length),vd=2*1024*1024,Td=["aud","cognito:username","event_id","exp","iat","iss","jti","origin_jti","secret_key","token_use"],Us={auth_time:"log",sub:"user_id"},Fs=["0","1","2","3","4","5","6","7","8","9","a","b","c","d","e","f","g","h","i","j","k","l"],Ls=["us31","us72","ap51","ap22","ap41","eu71","ap21","us32","us71","af51","ap31","ap43","ap23","ap42","ca01","eu01","eu72","eu51","eu73","eu11","me51","sa31"],ks=typeof TextEncoder<"u"?new TextEncoder:null;function Id(){if(typeof globalThis<"u")return globalThis.Buffer}function W(t){if(ks)return ks.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 Dn(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=Id();if(e)return new Uint8Array(e.from(t));throw new Error("No byte conversion available in this environment.")}var T=class T{static hash(e){typeof e!="string"&&(console.warn("coercing non-string value to empty string"),e="");let r=T.sb(e),n=1732584193,i=-271733879,s=-1732584194,o=271733878,a,c,l,d;for(let h=0;h<r.length;h+=16)a=n,c=i,l=s,d=o,n=T.ff(n,i,s,o,r[h],7,-680876936),o=T.ff(o,n,i,s,r[h+1],12,-389564586),s=T.ff(s,o,n,i,r[h+2],17,606105819),i=T.ff(i,s,o,n,r[h+3],22,-1044525330),n=T.ff(n,i,s,o,r[h+4],7,-176418897),o=T.ff(o,n,i,s,r[h+5],12,1200080426),s=T.ff(s,o,n,i,r[h+6],17,-1473231341),i=T.ff(i,s,o,n,r[h+7],22,-45705983),n=T.ff(n,i,s,o,r[h+8],7,1770035416),o=T.ff(o,n,i,s,r[h+9],12,-1958414417),s=T.ff(s,o,n,i,r[h+10],17,-42063),i=T.ff(i,s,o,n,r[h+11],22,-1990404162),n=T.ff(n,i,s,o,r[h+12],7,1804603682),o=T.ff(o,n,i,s,r[h+13],12,-40341101),s=T.ff(s,o,n,i,r[h+14],17,-1502002290),i=T.ff(i,s,o,n,r[h+15],22,1236535329),n=T.gg(n,i,s,o,r[h+1],5,-165796510),o=T.gg(o,n,i,s,r[h+6],9,-1069501632),s=T.gg(s,o,n,i,r[h+11],14,643717713),i=T.gg(i,s,o,n,r[h],20,-373897302),n=T.gg(n,i,s,o,r[h+5],5,-701558691),o=T.gg(o,n,i,s,r[h+10],9,38016083),s=T.gg(s,o,n,i,r[h+15],14,-660478335),i=T.gg(i,s,o,n,r[h+4],20,-405537848),n=T.gg(n,i,s,o,r[h+9],5,568446438),o=T.gg(o,n,i,s,r[h+14],9,-1019803690),s=T.gg(s,o,n,i,r[h+3],14,-187363961),i=T.gg(i,s,o,n,r[h+8],20,1163531501),n=T.gg(n,i,s,o,r[h+13],5,-1444681467),o=T.gg(o,n,i,s,r[h+2],9,-51403784),s=T.gg(s,o,n,i,r[h+7],14,1735328473),i=T.gg(i,s,o,n,r[h+12],20,-1926607734),n=T.hh(n,i,s,o,r[h+5],4,-378558),o=T.hh(o,n,i,s,r[h+8],11,-2022574463),s=T.hh(s,o,n,i,r[h+11],16,1839030562),i=T.hh(i,s,o,n,r[h+14],23,-35309556),n=T.hh(n,i,s,o,r[h+1],4,-1530992060),o=T.hh(o,n,i,s,r[h+4],11,1272893353),s=T.hh(s,o,n,i,r[h+7],16,-155497632),i=T.hh(i,s,o,n,r[h+10],23,-1094730640),n=T.hh(n,i,s,o,r[h+13],4,681279174),o=T.hh(o,n,i,s,r[h],11,-358537222),s=T.hh(s,o,n,i,r[h+3],16,-722521979),i=T.hh(i,s,o,n,r[h+6],23,76029189),n=T.hh(n,i,s,o,r[h+9],4,-640364487),o=T.hh(o,n,i,s,r[h+12],11,-421815835),s=T.hh(s,o,n,i,r[h+15],16,530742520),i=T.hh(i,s,o,n,r[h+2],23,-995338651),n=T.ii(n,i,s,o,r[h],6,-198630844),o=T.ii(o,n,i,s,r[h+7],10,1126891415),s=T.ii(s,o,n,i,r[h+14],15,-1416354905),i=T.ii(i,s,o,n,r[h+5],21,-57434055),n=T.ii(n,i,s,o,r[h+12],6,1700485571),o=T.ii(o,n,i,s,r[h+3],10,-1894986606),s=T.ii(s,o,n,i,r[h+10],15,-1051523),i=T.ii(i,s,o,n,r[h+1],21,-2054922799),n=T.ii(n,i,s,o,r[h+8],6,1873313359),o=T.ii(o,n,i,s,r[h+15],10,-30611744),s=T.ii(s,o,n,i,r[h+6],15,-1560198380),i=T.ii(i,s,o,n,r[h+13],21,1309151649),n=T.ii(n,i,s,o,r[h+4],6,-145523070),o=T.ii(o,n,i,s,r[h+11],10,-1120210379),s=T.ii(s,o,n,i,r[h+2],15,718787259),i=T.ii(i,s,o,n,r[h+9],21,-343485551),n=T.ad(n,a),i=T.ad(i,c),s=T.ad(s,l),o=T.ad(o,d);return T.rh(n)+T.rh(i)+T.rh(s)+T.rh(o)}static rh(e){let r="";for(let n=0;n<=3;n++)r+=T.alphabet.charAt(e>>n*8+4&15)+T.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 T.ad(T.rl(T.ad(T.ad(r,e),T.ad(i,o)),s),n)}static ff(e,r,n,i,s,o,a){return T.cm(r&n|~r&i,e,r,s,o,a)}static gg(e,r,n,i,s,o,a){return T.cm(r&i|n&~i,e,r,s,o,a)}static hh(e,r,n,i,s,o,a){return T.cm(r^n^i,e,r,s,o,a)}static ii(e,r,n,i,s,o,a){return T.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}};T.alphabet="0123456789abcdef";var le=T;function Ms(t){if(t===0)return Le[0];let e="";for(;t>0;)e=Le[t%62]+e,t=Math.floor(t/62);return e}function _e(t){return t.split("").reverse().reduce((e,r,n)=>e+Le.indexOf(r)*62**n,0)}function Ye(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 Nn(){return typeof window>"u"||!!window?._runningInNodeJS}function oe(){return !Nn()&&typeof document<"u"&&typeof document.createElement=="function"}function Er(t){let e;try{e=JSON.stringify(t);}catch{throw new f("Invalid data type.",{code:"INVALID_REQUEST"})}if(new Blob([e]).size>vd)throw new f("Data should not exceed 2MB",{code:"INVALID_REQUEST"})}function Ds(t){return t===""||t==="on"||t==="true"}function Ns(t){return t==="false"}function Os(t,e,r){e.name&&r(t,e.name,e.value);}var Ar=oe(),Pd=typeof SubmitEvent<"u",Cd=typeof HTMLFormElement<"u";function K(t,e,r){let n={},i=[];function s(c,l,d){if(e?.ignoreEmpty&&d==="")return;if(e?.nullIfEmpty&&d===""&&(d=null),typeof r=="function"){let p=r(l,d);p!==void 0&&(d=p);}let h=l.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}),u=c;if(typeof h[0]=="number")throw new f("Form key cannot start with an array index.",{code:"INVALID_REQUEST"});for(let p=0;p<h.length;p++){let g=h[p];p<h.length-1?(u[g]===void 0&&(typeof h[p+1]=="number"?u[g]=[]:u[g]={}),u=u[g]):u[g]===void 0?u[g]=d:Array.isArray(u[g])?u[g].push(d):u[g]=[u[g],d];}}function o(c,l,d){if(d instanceof File)c.push({name:l,file:d});else if(d instanceof FileList&&d&&d.length>0)for(let h=0;h<=d.length-1;h++){let u=d.item(h);u&&c.push({name:l,file:u});}}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===""||Ds(c.value)?s(n,c.name,true):Ns(c.value)?s(n,c.name,false):c.value&&s(n,c.name,c.value):c.type==="checkbox"&&(Ds(c.value)?s(n,c.name,false):Ns(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(Ar&&(t instanceof HTMLInputElement||t instanceof HTMLSelectElement||t instanceof HTMLTextAreaElement))return a(t),Er(n),{data:n,files:i};if(Ar&&t instanceof FormData){for(let c of t.entries()){let l=c[0],d=c[1];if(d instanceof File||d instanceof FileList)o(i,l,d);else if(d instanceof Blob){let h=d;if(h.type==="application/json")try{let u=JSON.parse(h.text());s(n,l,u);}catch{s(n,l,h);}}else s(n,l,d);}return Er(n),{data:n,files:i}}if(Ar&&Pd&&t instanceof SubmitEvent&&(t=t.target),Ar&&Cd&&t instanceof HTMLFormElement){let c=t.querySelectorAll("input"),l=t.querySelectorAll("select"),d=t.querySelectorAll("textarea");for(let h=0;h<l.length;h++)Os(n,l[h],s);for(let h=0;h<d.length;h++)Os(n,d[h],s);for(let h=0;h<c.length;h++)a(c[h]);return Er(n),{data:n,files:i}}return Er(t),{data:t,files:i}}function It(t){let e={};for(let r in t){let n=t[r];if(!Td.includes(r))if(Us[r])e[Us[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 On(t){if(t=Ld(t),t.split("-").length===7){let e=t.split("-"),r,n;try{r=Ls[Fs.indexOf(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 Fn(t,e){let r=Ls.indexOf(t.slice(0,4)),n=Fs[r],s=`${t.slice(4,-4)}-${n}${t.slice(-4)}-${e}`;return Fd(s)}function xd(t){let e=0n;for(let r of t){let n=Le.indexOf(r);if(n<0)throw new Error(`INVALID_PARAMETER: Invalid base62 character: ${r}`);e=e*kn+BigInt(n);}return e}function Ud(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%kn);r=Le[i]+r,n/=kn;}return r.length<e&&(r="0".repeat(e-r.length)+r),r}function kd(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 Dd(t){let e=0n;for(let r of t)e=(e<<8n)+BigInt(r);return e}function Nd(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 Od(t){let e=Array.from(Dn(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 Fd(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>=Le.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,l=Le[i.length]+a+c,d=Nd(s),h=Ud(Dd(d));return `${l}-${h}`}function Ld(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=Le.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),l=o.slice(o.length-a),d=l.slice(s),h=l.slice(0,s),u=d+c;if(!/^[0-9A-Za-z]+$/.test(u)||!/^[0-9A-Za-z]+$/.test(h))throw new Error("INVALID_PARAMETER: Corrupt compressed token: "+e);let p=xd(i),g=kd(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=Od(m);return `${u}-${h}-${y}`}function Pt(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 Ln(...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 Ct(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 l(g){return Array.isArray(g)?"array":g===null?"null":typeof g}function d(g){try{return JSON.stringify(g)}catch{return String(g)}}function h(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 u(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]=Ct(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 <${l(t)}> is invalid in "${n}". Expected a list.`);for(let y=0;y<t.length;y++){let b=t[y];if(c(m)){if(!u(b,m))throw new Error(`Type <${l(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 ${d(b)} is invalid in "${n}". Expected a list of ${d(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,w="";for(let E of e)try{t[y]=Ct(t[y],E,r,n),b=!0;break}catch(R){typeof E=="function"&&(w=R?.message||String(R));}if(!b&&w)throw new Error(w);if(!b){let E=e.map(h).join(", ");throw new Error(`${d(t[y])} is invalid in "${n}". allowed types or values are: ${E}.`)}}g=true;}else {let y="";for(let b of e)try{t=Ct(t,b,r,n),g=!0;break}catch(w){typeof b=="function"&&(y=w?.message||String(w));}if(!g&&y)throw new Error(y)}if(!g){let m=e.map(h).join(", ");throw new Error(`${d(t)} is invalid in "${n}". allowed types or values are: ${m}.`)}return t}if(c(e)&&u(t,e)||t===e)return t;throw new Error(`${d(t)} is invalid in "${n}". allowed type or value is: ${h(e)}.`)}function Md(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 qd(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 Vd(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 Bd(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 $d(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 jd(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)}var Kd=/^[a-z0-9]{2,20}$/,Hd=/[a-z]/,Gd=/^[0-9]+e[0-9]+$/,Wd=["tp","admin","public","authorized","newsletter","forward","all","true","false","null"];function zd(t,e){if(t==null){if(e?.allowNull)return null;throw new f('"group" is required.',{code:"INVALID_PARAMETER"})}if(!e?.nameOnly){if(t==="public")return 0;if(t==="authorized")return 1;if(typeof t=="number"){if(!Number.isInteger(t)||t<0||t>99)throw new f('"group" should be an integer between 0 and 99.',{code:"INVALID_PARAMETER"});return t}}if(typeof t!="string"||!Kd.test(t)||!Hd.test(t)||Gd.test(t)||Wd.includes(t))throw new f("Newsletter group name must be 2-20 lowercase alphanumeric characters, contain a letter, and not be a reserved name.",{code:"INVALID_PARAMETER"});return t}function Jd(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 Ct(o,e,r)}catch(a){throw new f(a.message,{code:"INVALID_PARAMETER"})}}var _={UserId:Md,PhoneNumber:qd,Birthdate:Vd,Password:Bd,Email:$d,Url:jd,newsletterGroup:zd,Params:Jd};var ae="skapi.enc.v1",Bs=6e5,xt=12,Sr=null,ht=null;function $s(){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 js(){if(ht)return ht;let t=typeof globalThis<"u"?globalThis:void 0;if(t?.crypto?.subtle&&typeof t.crypto.getRandomValues=="function")return ht=t.crypto,ht;try{let e=typeof globalThis<"u"?globalThis:void 0,r=null;if(e?.process&&typeof e.process.getBuiltinModule=="function"&&(r=e.process.getBuiltinModule("crypto")),!r&&typeof Be=="function"&&(r=Be("crypto")),r?.webcrypto?.subtle)return ht=r.webcrypto,ht}catch{}throw $s()}function ye(){if(Sr)return Sr;let t=js();if(!t.subtle)throw $s();return Sr=t.subtle,Sr}function qn(){try{return ye(),!0}catch{return false}}function ce(t){let e=js(),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 $(t){let e=Dn(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 j(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 Rr(t){let e=await ye().digest("SHA-256",t);return new Uint8Array(e)}async function Dt(t,e,r,n){let i=ye(),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 gt(t,e,r,n){let i=ye(),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 Dt(a,e,n,32);V(a),V(s);let l=await we(c);return V(c),l}async function we(t){return ye().importKey("raw",t,{name:"AES-GCM"},false,["encrypt","decrypt"])}async function Ks(){let t=ce(32),e=await we(t);return {bytes:t,key:e}}async function be(t,e,r){let n=ce(xt),i=await ye().encrypt({name:"AES-GCM",iv:n,additionalData:r,tagLength:128},t,e);return {iv:n,ct:new Uint8Array(i)}}async function Ee(t,e,r,n){let i=await ye().decrypt({name:"AES-GCM",iv:e,additionalData:n,tagLength:128},t,r);return new Uint8Array(i)}var vr={name:"ECDH",namedCurve:"P-256"};async function Hs(){let t=ye(),e=await t.generateKey(vr,true,["deriveBits"]),r=new Uint8Array(await t.exportKey("raw",e.publicKey)),n=new Uint8Array(await t.exportKey("pkcs8",e.privateKey)),i=await Vn(n);return {pubRaw:r,pkcs8:n,priv:i}}async function Vn(t){return ye().importKey("pkcs8",t,vr,false,["deriveBits"])}async function Gs(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 ye().importKey("raw",t,vr,false,[])}async function Bn(t){return $(await Rr(t))}async function Ws(t,e,r,n){let i=ye(),s=await Gs(t),o=await i.generateKey(vr,true,["deriveBits"]),a=new Uint8Array(await i.deriveBits({name:"ECDH",public:s},o.privateKey,256)),c=await Dt(a,new Uint8Array(32),r,32);V(a);let l=await we(c);V(c);let{iv:d,ct:h}=await be(l,e,n);return {epk:new Uint8Array(await i.exportKey("raw",o.publicKey)),iv:d,ct:h}}async function zs(t,e,r,n,i,s){let o=ye(),a=await Gs(e),c=new Uint8Array(await o.deriveBits({name:"ECDH",public:a},t,256)),l=await Dt(c,new Uint8Array(32),i,32);V(c);let d=await we(l);return V(l),Ee(d,r,n,s)}function V(t){t&&t.length&&t.fill(0);}function Yd(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 $n(t){return W(JSON.stringify(t))}function Nt(t,e,r){return Ln(t,new Uint8Array([0]),W(e),new Uint8Array([0]),W(r))}var Qe="0123456789ABCDEFGHJKMNPQRSTVWXYZ",Ut=16,qs=26,Vs=28;function Js(t){let e=2166136261;for(let r=0;r<t.length;r++)e^=t[r],e=e*16777619>>>0;return e&1023}function Ys(t){if(t.length!==Ut)throw new f(`A recovery code needs exactly ${Ut} 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+=Qe[r>>n&31];n>0&&(e+=Qe[r<<5-n&31]);let i=Js(t);return e+=Qe[i>>5&31]+Qe[i&31],(e.match(/.{1,4}/g)||[]).join("-")}function Qs(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!==Vs)throw new f(`That does not look like a recovery code: expected ${Vs} characters, got ${e.length}.`,{code:"ENCRYPTION_BAD_RECOVERY_CODE"});let r=e.slice(0,qs),n=e.slice(qs),i=0,s=0,o=[];for(let l=0;l<r.length;l++){let d=Qe.indexOf(r[l]);if(d<0)throw new f(`That does not look like a recovery code: "${r[l]}" is not a valid character.`,{code:"ENCRYPTION_BAD_RECOVERY_CODE"});i=i<<5|d,s+=5,s>=8&&(s-=8,o.push(i>>s&255));}let a=new Uint8Array(o.slice(0,Ut)),c=Js(a);if(n!==Qe[c>>5&31]+Qe[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 jn(t,e,r){let n=await Dt(t,e,r,32),i=await we(n);return V(n),i}var Mn=[83,75,69,78,67,70],Xs=2,kt=56,Zs=16,Qd=4*1024*1024;function Kn(t){if(!t||t.length<kt)return false;for(let e=0;e<Mn.length;e++)if(t[e]!==Mn[e])return false;return true}function Xe(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 pt(t,e){return (t[e]<<24>>>0)+(t[e+1]<<16)+(t[e+2]<<8)+t[e+3]}function Xd(t,e,r){let n=Math.floor(r/4294967296);Xe(t,e,n),Xe(t,e+4,r>>>0);}function Zd(t,e){return pt(t,e)*4294967296+pt(t,e+4)}async function eo(t,e,r,n,i,s){let o=W(`${ae}|binfile|${r}|${n}|${i}|${s}`),a=await Dt(t,e,o,32),c=await we(a);return V(a),c}async function to(t){return (await Rr(Ln(W(`${ae}|dekid`),t))).subarray(0,8)}function ro(t,e,r){return $n([`${ae}|binchunk`,$(t),e,r])}function ef(t,e,r,n,i,s){let o=new Uint8Array(kt+s.length);return o.set(Mn,0),o[6]=Xs,o[7]=s.length?1:0,Xe(o,8,t),Xe(o,12,e),o.set(r,16),Xd(o,32,n),o.set(i,40),Xe(o,48,s.length),Xe(o,52,0),s.length&&o.set(s,kt),o}async function no(t,e,r,n,i=Qd){let s=ce(Zs),o=await eo(t,s,r.service,r.owner,r.recordOwner,r.recordId),a=await to(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 l=e.length===0?1:Math.ceil(e.length/i),d=ef(i,l,s,e.length,a,c),h=await Rr(d),u=[],p=d.length;for(let y=0;y<l;y++){let b=e.subarray(y*i,Math.min((y+1)*i,e.length)),w=await be(o,b,ro(h,y,l));u.push(w),p+=4+w.iv.length+w.ct.length;}let g=new Uint8Array(p);g.set(d,0);let m=d.length;for(let y of u)Xe(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 tf(t){if(!Kn(t))throw new f("This file is not an encrypted skapi file.",{code:"INVALID_PARAMETER"});let e=pt(t,48),r=kt+e;if(t.length<r)throw new f("Encrypted file header is truncated.",{code:"INVALID_REQUEST"});let n=null;return e&&(n=JSON.parse(Pt(t.subarray(kt,r)))),{version:t[6],chunkBytes:pt(t,8),count:pt(t,12),fileId:t.subarray(16,16+Zs),plainLen:Zd(t,32),dekId:t.subarray(40,48),meta:n,headerLen:r}}async function io(t,e,r){let n=tf(e);if(n.version!==Xs)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 to(t);if(!Yd(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 eo(t,n.fileId,r.service,r.owner,r.recordOwner,r.recordId),o=await Rr(e.subarray(0,n.headerLen)),a=[],c=n.headerLen,l=0;for(let u=0;u<n.count;u++){if(c+4>e.length)throw new f("Encrypted file is truncated.",{code:"INVALID_REQUEST"});let p=pt(e,c);if(c+=4,p<xt+16||c+p>e.length)throw new f("Encrypted file is truncated.",{code:"INVALID_REQUEST"});let g=await Ee(s,e.subarray(c,c+xt),e.subarray(c+xt,c+p),ro(o,u,n.count));c+=p,a.push(g),l+=g.length;}let d=new Uint8Array(l),h=0;for(let u of a)d.set(u,h),h+=u.length;return {bytes:d,meta:n.meta}}var rf="__skapi__keyring",Ot="__skapi_enc__",oo=1,nf="skapi-enc",He="keys",Gn=new WeakMap;function ao(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:Bs;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:rf}}function q(){return Gn.get(this)||null}function co(t){if(!t){Gn.delete(this);return}Gn.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,passthrough:new Map,rawRead:false,ready:null,unlocking:false,pendingRecoveryCode:"",peerPub:new Map,peerInflight:new Map});}function Wn(){let t=q.call(this);if(t){t.user_id&&ii.call(this,t).catch(()=>{}),t.ready=null,t.unlocking=false,t.pendingRecoveryCode="";for(let[,e]of t.dek)V(e.bytes);t.dek.clear(),t.roll.clear(),t.passthrough.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 lo(){let t=q.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 uo(t,e){return typeof e=="string"&&e===t.cfg.table}function mt(){return `${this.service}/${this.owner}`}function zn(t,e,r,n){let[i,s]=t.split("/");return $n([ae,i,s,e,r,n])}function fo(t,e,r,n,i){let[s,o]=t.split("/");return W(`${ae}|dekwrap|${s}|${o}|${e}|${r}|${n}|${i}`)}function Jn(t){return t.anch==="uid"?t.uid:t.anch==="rid"?t.rid:""}function Ir(t){return !!t&&typeof t=="object"&&!Array.isArray(t)&&typeof t[Ot]=="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 ho="__skapi_no_access__";function ue(t,e,r){if(t.withheld!=="sentinel")return null;let n={[ho]:true,reason:e};return r&&(n.recipients=r),Object.freeze(n)}function Yn(t){return !!t&&typeof t=="object"&&t[ho]===true}var sf=256*1024,Mt="__skenc_ct__",po="payload.bin",of=`/${Mt}/${po}`;function Qn(t,e){return t===Mt&&e===po}async function af(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:so(n.access_group),table:i,record:null};if(!r)return {group:n?.access_group!==void 0?so(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 Ke.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}}function cf(t){return this.getFile(t,{dataType:"blob"})}async function Ke(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 so(t){return t==="private"||t==="*"||t==="**"?"private":t==="public"?0:t==="authorized"?1:t==="admin"?99:typeof t=="number"?t:0}function Hn(t,e,r){let n=this.user?.user_id;if(!(!t||!t.user_id||!n||t.user_id===n))throw new f(`Record "${e}" belongs to another user (${t.user_id}), so ${r} would either seal it under the wrong key or strand its contents. Encryption only operates on records you own, no matter what access level you hold.`,{code:"ENCRYPTION_NOT_RECORD_OWNER"})}async function Xn(t,e,r){let n=q.call(this);if(!n)return {send:t,plain:t,encrypted:false,omit:false};let i=e?.record_id||"",s=i,o=e?.unique_id||"";if(i&&n.passthrough.has(i)){let M=n.passthrough.get(i);return n.passthrough.delete(i),{send:M,plain:t,encrypted:true,omit:false}}let{group:a,table:c,record:l}=await af.call(this,n,e,s);if(a!=="private"){let M=true;if(!r&&i){let te=l||await Ke.call(this,i);if(te&&te.encrypted){if(Hn.call(this,te,i,"making it non-private"),te.encrypted.status==="failed")throw new f(`Cannot make record "${i}" non-private: its current contents could not be decrypted (${te.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"});let Rt=!!te.bin&&Object.keys(te.bin).some(Qt=>(te.bin[Qt]||[]).some(xi=>xi&&xi.encrypted));if(!Rt&&s){let Qt=n.dek.get(s);Qt&&(V(Qt.bytes),n.dek.delete(s));}return {send:te.data,plain:te.data,encrypted:false,omit:false,files:Rt?"decrypt":void 0}}}let Q=l;i&&!Q&&(Q=await Ke.call(this,i).catch(()=>null)),Q&&Q.encrypted&&Hn.call(this,Q,i,"making it non-private");let Yt=!!Q&&!!Q.bin&&Object.keys(Q.bin).some(te=>(Q.bin[te]||[]).some(Rt=>Rt&&Rt.encrypted));if(Yt&&(M=false),M&&s){let te=n.dek.get(s);te&&(V(te.bytes),n.dek.delete(s));}return {send:t,plain:t,encrypted:false,omit:!r,files:Yt?"decrypt":void 0}}if(uo(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(Yn.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,Ot))throw new f(`"${Ot}" 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 d=this.user?.user_id;if(!d)throw new f("User login is required to write an encrypted record.",{code:"INVALID_REQUEST"});let h=mt.call(this),u=false;if(i&&n.roll.has(i)){u=true,n.roll.delete(i);let M=n.dek.get(i);n.dek.delete(i),M&&V(M.bytes);}let p=l;i&&!p&&!n.dek.has(i)&&(p=await Ke.call(this,i).catch(()=>null)),p&&Hn.call(this,p,i,"making it private");let g=!!p&&!p.encrypted&&!!p.bin&&Object.keys(p.bin).some(M=>(p.bin[M]||[]).some(Q=>Q&&!Q.encrypted)),m=null;if(i&&!u&&(m=n.dek.get(i)||null,!m)){let M=p||l||await Ke.call(this,i);if(M&&(s=M.record_id||i,m=n.dek.get(s)||null,!o&&M.unique_id&&(o=M.unique_id),!m&&M.encrypted?.status==="failed"))throw new f(`Cannot update encrypted record "${i}": its current contents could not be decrypted (${M.encrypted.reason}), so its existing key wraps cannot be preserved. Updating anyway would revoke everyone it is shared with.`,{code:"ENCRYPTION_LOCKED"})}s===i&&m&&m.rid&&(s=m.rid),!o&&m&&m.anch==="uid"&&m.uid&&(o=m.uid);let y,b,w;if(m){if(m.own&&m.own!==d)throw new f(`Record "${i}" belongs to another user (${m.own}). Encryption only operates on records you own.`,{code:"ENCRYPTION_NOT_RECORD_OWNER"});y=m.bytes,b=m.key,w=Object.assign({},m.recipients);}else {let M=await Ks();y=M.bytes,b=M.key,w={};}let E=o?"uid":s?"rid":"new",R=E==="uid"?o:E==="rid"?s:"",S=zn(h,d,E,R),U=Nt(S,d,"mk"),k=await be(n.mk,y,U);w[d]={t:"mk",iv:$(k.iv),ct:$(k.ct)},m&&(m.anch!==E||Jn(m)!==R)&&(w=await lf.call(this,n,y,w,h,d,E,R,S));let N=W(JSON.stringify(t===void 0?null:t)),x=await be(b,N,S);V(N);let D={[Ot]:oo,enc:"A256GCM",kw:"ECDH-ES+A256GCM",anch:E,uid:o,rid:s,own:d,iv:$(x.iv),ct:$(x.ct),k:w},L,B,ee=D.ct;s&&ee.length>sf&&(L=j(ee),D.ct="",D.ct_ref=of,m&&m.ctRef&&(B=m.ctRef));let ne=JSON.stringify(D).length;if(ne>2*1024*1024)throw new f(`Encrypted record data is too large: once encrypted and base64 encoded it becomes ${ne} 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:y,key:b,recipients:w,anch:E,uid:o,rid:s,own:d,access_group:"private"}),{send:D,plain:t,encrypted:true,omit:false,spill:L,retireCt:B,dek:{bytes:y,key:b,recipients:w,anch:E,uid:o,rid:s,own:d,access_group:"private"},files:g?"encrypt":void 0}}function go(t,e){let r=q.call(this);!r||!e||!t||r.dek.has(t)||r.dek.set(t,Object.assign({},e,{rid:t}));}async function lf(t,e,r,n,i,s,o,a){let c=Object.keys(r).filter(h=>h!==i);if(!c.length)return r;let l=await si.call(this,c),d={[i]:r[i]};for(let h of c){let u=l[h];u&&(d[h]=await mo.call(this,e,u,n,o,i,h,a));}return d}async function mo(t,e,r,n,i,s,o){let a=fo(r,n,i,s,e.fpr),c=Nt(o,s,e.fpr),l=await Ws(e.pubRaw,t,a,c);return {t:"ecdh",epk:$(l.epk),iv:$(l.iv),ct:$(l.ct),fpr:e.fpr}}async function yo(t,e){if(!Ir(t))return {value:t};if(e.access_group!=="private")return {value:t};let r=q.call(this);if(!r)return {value:null,flag:{status:"failed",reason:"ENCRYPTION_DISABLED"}};if(r.rawRead)return {value:t};if(uo(r,e.table_name))return {value:t};if(t[Ot]!==oo)return {value:ue(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:ue(r.cfg,"BINDING_MISMATCH"),flag:{status:"failed",reason:"BINDING_MISMATCH"}};if(t.uid&&e.unique_id&&t.uid!==e.unique_id)return {value:ue(r.cfg,"BINDING_MISMATCH"),flag:{status:"failed",reason:"BINDING_MISMATCH"}};if(t.rid&&e.record_id&&t.rid!==e.record_id)return {value:ue(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:ue(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:ue(r.cfg,"NO_SESSION_KEY"),flag:{status:"failed",reason:"NO_SESSION_KEY"}};let s=mt.call(this),o=Jn(t),a=zn(s,t.own,t.anch,o),c;try{if(i.t==="mk")c=await Ee(r.mk,j(i.iv),j(i.ct),Nt(a,n,"mk"));else if(i.t==="ecdh"){if(!r.ikPriv)return {value:ue(r.cfg,"NO_SESSION_KEY"),flag:{status:"failed",reason:"NO_SESSION_KEY"}};c=await zs(r.ikPriv,j(i.epk),j(i.iv),j(i.ct),fo(s,o,t.own,n,i.fpr),Nt(a,n,i.fpr));}else return {value:ue(r.cfg,"UNSUPPORTED_VERSION"),flag:{status:"failed",reason:"UNSUPPORTED_VERSION"}}}catch{return {value:ue(r.cfg,"BAD_KEY"),flag:{status:"failed",reason:"BAD_KEY"}}}let l;try{if(t.ct_ref){if(!e.ctUrl)return V(c),{value:ue(r.cfg,"DATA_UNAVAILABLE"),flag:{status:"failed",reason:"DATA_UNAVAILABLE"}};let p=await cf.call(this,e.ctUrl);l=new Uint8Array(await p.arrayBuffer());}else l=j(t.ct);}catch{return V(c),{value:ue(r.cfg,"DATA_UNAVAILABLE"),flag:{status:"failed",reason:"DATA_UNAVAILABLE"}}}let d,h;try{h=await we(c),d=await Ee(h,j(t.iv),l,a);}catch{return V(c),{value:ue(r.cfg,"CORRUPT"),flag:{status:"failed",reason:"CORRUPT"}}}let u;try{u=JSON.parse(Pt(d));}catch{return V(d),V(c),{value:ue(r.cfg,"CORRUPT"),flag:{status:"failed",reason:"CORRUPT"}}}if(V(d),e.record_id){let p=r.dek.get(e.record_id);p?(p.bytes=c,p.key=h,p.recipients=t.k,p.anch=t.anch,p.uid=t.uid,p.own=t.own,p.access_group="private",p.ctRef=t.ct_ref||""):r.dek.set(e.record_id,{bytes:c,key:h,recipients:t.k,anch:t.anch,uid:t.uid,rid:e.record_id,own:t.own,access_group:"private",ctRef:t.ct_ref||""});}else V(c);return {value:u,flag:{status:"encrypted",recipients:Object.keys(t.k)}}}function Ft(t,e){let[r,n]=t.split("/");return W(`${ae}|kek|${r}|${n}|${e}`)}function Lt(t,e,r,n){let[i,s]=t.split("/");return W(`${ae}|mk|${i}|${s}|${e}|PBKDF2-SHA256|${r}|${n}`)}function bo(t,e){let[r,n]=t.split("/");return W(`${ae}|recovery|${r}|${n}|${e}`)}function _o(t,e,r){let[n,i]=t.split("/");return W(`${ae}|rk|${n}|${i}|${e}|HKDF-SHA256|${r}`)}function wo(t,e){let[r,n]=t.split("/");return W(`${ae}|self|${r}|${n}|${e}`)}function Eo(t,e){let[r,n]=t.split("/");return W(`${ae}|ik|${r}|${n}|${e}`)}async function Pr(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 Zn(t,e,r){let n=ce(Ut),i=Ys(n),s=ce(16),o=$(s),a=await jn(n,s,bo(t,e)),c=await be(a,r,_o(t,e,o));return V(n),{code:i,wrap:{id:$(ce(6)),p:"recovery",kdf:{a:"HKDF-SHA256",s:o},iv:$(c.iv),ct:$(c.ct),created:Date.now()}}}async function uf(t,e,r,n){let i=Qs(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 jn(i,j(o.kdf.s),bo(t,e)),c=await Ee(a,j(o.iv),j(o.ct),_o(t,e,o.kdf.s));return V(i),c}catch{}return V(i),null}async function df(t,e,r,n,i){let s=ce(16),o=$(s),a=await gt(n,s,t.cfg.iterations,Ft(e,r)),c=await be(a,i,Lt(e,r,t.cfg.iterations,o));return {id:$(ce(6)),p:"password",kdf:{a:"PBKDF2-SHA256",it:t.cfg.iterations,s:o},iv:$(c.iv),ct:$(c.ct),created:Date.now()}}async function ff(t,e){let r=this.user.user_id,n=t.scope,i=ce(16),s=$(i),o=await gt(e,i,t.cfg.iterations,Ft(n,r)),a=ce(32),c=await be(o,a,Lt(n,r,t.cfg.iterations,s)),l=await we(a),d=await Hs(),h=await be(l,d.pkcs8,Eo(n,r));V(d.pkcs8);let u=null;t.cfg.recovery==="code"&&(u=await Zn(n,r,a));let p=await be(l,a,wo(n,r));V(a);let g=await Bn(d.pubRaw),m=Date.now(),y=[{id:$(ce(6)),p:"password",kdf:{a:"PBKDF2-SHA256",it:t.cfg.iterations,s},iv:$(c.iv),ct:$(c.ct),created:m}];u&&y.push(u.wrap);let b={v:1,alg:"ECDH-P-256",user_id:r,wraps:y,ik:{iv:$(h.iv),ct:$(h.ct)},self:{iv:$(p.iv),ct:$(p.ct)},pub:$(d.pubRaw),fpr:g,pins:null,created:m,updated:m};await this.postRecord({v:1,alg:"ECDH-P-256",user_id:r,pub:$(d.pubRaw),fpr:g,created:m},{table:{name:t.cfg.table,access_group:"authorized"},index:{name:"pubkey",value:r}});let w=await this.postRecord(b,{table:{name:t.cfg.table,access_group:"private"}}),E=await Pr.call(this,t);if(E&&E.record_id!==w.record_id){await Ao.call(this,t,E,e);return}t.mk=l,t.ikPriv=d.priv,t.pubRaw=d.pubRaw,t.fpr=g,t.keyringRecordId=w.record_id,u&&(t.pendingRecoveryCode=u.code),t.user_id=r,t.pins={},t.status="unlocked",t.reason="";}async function Ao(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(d=>d.p==="password");if(!a.length)throw new f("The keyring has no password wrap.",{code:"ENCRYPTION_KEYRING_CORRUPT"});a.sort((d,h)=>(h.created||0)-(d.created||0));let c=null;for(let d of a)try{let h=j(d.kdf.s),u=await gt(r,h,d.kdf.it,Ft(i,n));c=await Ee(u,j(d.iv),j(d.ct),Lt(i,n,d.kdf.it,d.kdf.s));break}catch{}if(!c)throw new f("Incorrect password: the encryption keyring could not be opened.",{code:"ENCRYPTION_BAD_PASSWORD"});let l=await we(c);V(c),await ei.call(this,t,e,l);}async function ei(t,e,r){let n=this.user.user_id,i=e.data,s=await Ee(r,j(i.ik.iv),j(i.ik.ct),Eo(t.scope,n)),o=await Vn(s);V(s);let a={};if(i.pins&&typeof i.pins=="object"&&i.pins.ct)try{let c=await Ee(r,j(i.pins.iv),j(i.pins.ct),W(`${ae}|pins|${t.scope}|${n}`));a=JSON.parse(Pt(c)),V(c);}catch{a={};}t.mk=r,t.ikPriv=o,t.pubRaw=j(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 Cr(t){let e=q.call(this);if(!e||!this.user?.user_id)return;if(!qn()){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=mt.call(this);let r=await Pr.call(this,e);r?await Ao.call(this,e,r,t):await ff.call(this,e,t),e.cfg.persistDevice&&await Io.call(this,e).catch(()=>{});}async function So(t){await this.__connection;let e=q.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 Cr.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 Ro(t){let e=q.call(this);return e?(t?.forgetDevice&&await ii.call(this,e).catch(()=>{}),Wn.call(this),this.__cached_requests={},{status:e.status}):{status:"disabled"}}async function vo(t,e){let r=q.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 gt(t,j(m.kdf.s),m.kdf.it,Ft(r.scope,s));c=await Ee(y,j(m.iv),j(m.ct),Lt(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 l=ce(16),d=$(l),h=await gt(e,l,r.cfg.iterations,Ft(r.scope,s)),u=await be(h,c,Lt(r.scope,s,r.cfg.iterations,d));V(c);let p=Date.now(),g=(o.wraps||[]).concat([{id:$(ce(6)),p:"password",kdf:{a:"PBKDF2-SHA256",it:r.cfg.iterations,s:d},iv:$(u.iv),ct:$(u.ct),created:p}]);await this.postRecord(Object.assign({},o,{wraps:g,updated:p}),{record_id:r.keyringRecordId});}async function To(){let t=q.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 ti(){return typeof indexedDB<"u"&&!!indexedDB}function ri(){return new Promise((t,e)=>{let r=indexedDB.open(nf,1);r.onupgradeneeded=()=>{let n=r.result;n.objectStoreNames.contains(He)||n.createObjectStore(He);},r.onsuccess=()=>t(r.result),r.onerror=()=>e(r.error);})}function ni(t){return `${t.scope}#${this.user?.user_id}`}async function Io(t){if(!ti()||!t.mk)return;let e=await ri();await new Promise((r,n)=>{let i=e.transaction(He,"readwrite");i.objectStore(He).put({mk:t.mk,keyringRecordId:t.keyringRecordId,saved:Date.now()},ni.call(this,t)),i.oncomplete=()=>r(),i.onerror=()=>n(i.error);}),e.close();}async function hf(t){if(!ti())return null;let e=await ri(),r=await new Promise((n,i)=>{let o=e.transaction(He,"readonly").objectStore(He).get(ni.call(this,t));o.onsuccess=()=>n(o.result||null),o.onerror=()=>i(o.error);});return e.close(),r&&r.mk?r:null}async function ii(t){if(!ti())return;let e=await ri();await new Promise((r,n)=>{let i=e.transaction(He,"readwrite");i.objectStore(He).delete(ni.call(this,t)),i.oncomplete=()=>r(),i.onerror=()=>n(i.error);}),e.close();}function Po(){let t=q.call(this);!t||t.ready||(t.unlocking=true,t.ready=pf.bind(this)().catch(()=>false).then(()=>{t.unlocking=false;}));}async function pf(){let t=q.call(this);if(!t||!this.user?.user_id||!t.cfg.persistDevice||!qn())return false;t.scope=mt.call(this);try{let e=await hf.call(this,t);if(!e)return !1;let r=await Pr.call(this,t);return r?(await ei.call(this,t,r,e.mk),!0):(await ii.call(this,t).catch(()=>{}),!1)}catch{return t.status="locked",t.reason="NO_SESSION_KEY",false}}async function si(t){let e=q.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 l=((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(!l.length)return null;l.sort((p,g)=>g.uploaded-p.uploaded);let d=j(l[0].data.pub),h=await Bn(d),u=e.pins[s];if(u&&u!==h)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(!u){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]=h,i=true;}return {pubRaw:d,fpr:h}})().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 ko.call(this,e).catch(()=>{}),r}async function Co(t,e){let r=mt.call(this),n=t.dek.get(e);if(n)return {entry:n,scope:r};let i=await Ke.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 oi(t,e){let r=q.call(this);if(!r)return;let n=await Co.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 si.call(this,e),c=e.filter(u=>!a[u]);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 l=Jn(i),d=zn(s,i.own,i.anch,l),h=Object.assign({},i.recipients);for(let u of e)u!==o&&(h[u]=await mo.call(this,i.bytes,a[u],s,l,i.own,u,d));await mf.call(this,r,t,i,h);}async function xo(t,e){let r=q.call(this);if(!r)return;let n=await Co.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(l=>l===s?true:e?!e.includes(l):false).filter(l=>l!==s),a=await Ke.call(this,t);if(!a)throw new f(`Record "${t}" not found.`,{code:"NOT_EXISTS"});gf(a,t);let c={};if(o.length){c=await si.call(this,o);let l=o.filter(d=>!c[d]);if(l.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: ${l.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 oi.call(this,a.record_id||t,o);}function gf(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 mf(t,e,r,n){let i=await yf.call(this,e);if(!i)throw new f(`Cannot change sharing on record "${e}": its stored envelope could not be read.`,{code:"ENCRYPTION_DATA_UNAVAILABLE"});r.recipients=n,t.dek.set(e,r);let s=Object.assign({},i,{k:n});t.passthrough.set(e,s),await this.postRecord(void 0,{record_id:e});}async function yf(t){let e=q.call(this);if(!e)return null;e.rawRead=true;let r;try{r=(await this.getRecords({record_id:t},{limit:1}))?.list?.[0];}finally{e.rawRead=false;}return r&&Ir(r.data)?r.data:null}async function Uo(t){let e=q.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 ko.call(this,e);}async function ko(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 be(t.mk,W(JSON.stringify(t.pins)),W(`${ae}|pins|${t.scope}|${t.user_id}`));await this.postRecord(Object.assign({},r.data,{pins:{iv:$(n.iv),ct:$(n.ct)},updated:Date.now()}),{record_id:t.keyringRecordId});}function Do(){let t=q.call(this);if(!t||!t.pendingRecoveryCode)return null;let e=t.pendingRecoveryCode;return t.pendingRecoveryCode="",e}async function No(t){await this.__connection;let e=q.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=mt.call(this);let r=this.user.user_id,n=await Pr.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 uf(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 we(i);await ei.call(this,e,n,s);let o=false,a=null,c=(n.data?.wraps||[]).slice();if(t.password&&(c=c.filter(l=>l.p!=="password"),c.push(await df(e,e.scope,r,t.password,i)),o=true),e.cfg.recovery==="code"){let l=await Zn(e.scope,r,i);c=c.filter(d=>d.p!=="recovery"),c.push(l.wrap),a=l.code;}return V(i),await this.postRecord(Object.assign({},n.data,{wraps:c,updated:Date.now()}),{record_id:n.record_id}),e.cfg.persistDevice&&await Io.call(this,e).catch(()=>{}),{status:e.status,repaired:o,recoveryCode:a}}async function Oo(){await this.__connection;let t=q.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 Ee(t.mk,j(n.iv),j(n.ct),wo(t.scope,t.user_id)),s=await Zn(t.scope,t.user_id,i);V(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 Tr="__skenc__",Fo="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";function bf(t){if(t===0)return "0";let e="";for(;t>0;)e=Fo[t%62]+e,t=Math.floor(t/62);return e}function _f(t){let e=0;for(let r of t){let n=Fo.indexOf(r);if(n<0)return NaN;e=e*62+n;}return e}function xr(t){if(typeof t!="string")return null;let e=t.lastIndexOf(Tr);if(e<0)return null;let r=_f(t.slice(e+Tr.length));return Number.isFinite(r)?{key:t.slice(0,e),plainSize:r}:null}function ai(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=xr(e[10]);return r?{recordId:e[5],recordOwner:e[3],filename:e[e.length-1],plainSize:r.plainSize}:null}catch{return null}}function Lo(t,e){return {service:this.service,owner:this.owner,recordOwner:e,recordId:t}}async function Mo(t,e,r){let n=q.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(xr(e))throw new f(`"${Tr}" is reserved in an upload form key.`,{code:"INVALID_PARAMETER"});if(e===Mt)return {key:e,file:r,encrypted:false};let s=new Uint8Array(await r.arrayBuffer()),o={n:r.name,t:r.type||"",lm:r.lastModified||0},a=await no(i.bytes,s,Lo.call(this,t,i.own),o);return V(s),{key:`${e}${Tr}${bf(r.size)}`,file:new File([a],r.name,{type:"application/octet-stream"}),encrypted:true}}async function qo(t,e){let r=q.call(this),n=ai(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(!Kn(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 io(i.bytes,s,Lo.call(this,n.recordId,n.recordOwner)),a=o.meta&&o.meta.t||"application/octet-stream";return new Blob([o.bytes],{type:a})}function wf(t){let e=[];for(let r in t?.bin||{})for(let n of t.bin[r]||[])n&&n.encrypted&&e.push({formKey:r,url:n.url,filename:n.filename});return e}function Ef(t){let e=[];for(let r in t?.bin||{})for(let n of t.bin[r]||[])n&&!n.encrypted&&e.push({formKey:r,url:n.url,filename:n.filename});return e}async function ci(t,e,r){let n=q.call(this);if(!n)return [];let i=await Ke.call(this,t);if(!i)return [];let s=e==="decrypt"?wf(i):Ef(i);if(!s.length)return [];let o=[],a=new FormData,c=false;for(let l of s){let d=i.bin[l.formKey].find(u=>u.url===l.url);if(!d||typeof d.getFile!="function")continue;let h=await d.getFile("blob");h&&(a.append(l.formKey,new File([h],l.filename,{type:h.type||"application/octet-stream"})),o.push(l.url),c=true);}if(!c)return [];if(e==="decrypt"){let l=n.dek.get(t);l&&(V(l.bytes),n.dek.delete(t));}return await this.uploadFiles(a,{record_id:t,progress:r}),o}var H=null;function kr(t){let e={tkid:"ticket_id",cond:"condition",stmp:"timestamp",upd:"updated",acts:"actions",actn:"action",cnt:"count",ttl:"time_to_live",plch:"placeholder",hash:"hash",desc:"description",pmc:"limit_per_user",fail:"failed"},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.slice(3).join("#");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=_e(i[2].slice(0,-4));}}else e[n]?r[e[n]]=t[n]:r[n]=t[n];return r}async function Bo(t){if(!t?.ticket_id)throw new f("Ticket ID is required.",{code:"INVALID_PARAMETER"});if(!/^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$/.test(t.ticket_id))throw new f('Invalid "ticket_id". Use letters, digits, "_" and "-" (up to 64 chars, starting with a letter or digit).',{code:"INVALID_PARAMETER"});if(!t.method)throw new f('Method is required. Should be either "GET" or "POST"',{code:"INVALID_PARAMETER"});let e=String(t.method).toUpperCase();if(e!=="GET"&&e!=="POST")throw new f('Method should be either "GET" or "POST".',{code:"INVALID_PARAMETER"});let r=!!t.auth;if(r&&e==="GET")throw new f("Signed-in consumption is POST only.",{code:"INVALID_PARAMETER"});await this.__connection;let n=r?"tpa":e==="GET"?"tg":"tp",i=`https://${this.service.slice(0,4)}.${this.customApiDomain}/${n}/${this.service}/${t.ticket_id}`,s=await C.bind(this)(i,t.data||{},{method:e,auth:r},{ignoreService:true});if(s&&typeof s=="object"&&s.stage)throw new f(s.message,{code:s.code,cause:s});return !s||typeof s!="object"?s:kr(s)}async function $o(t,e){await this.__connection;let r=await C.bind(this)("ticket",Object.assign({exec:"list"},t||{}),{auth:true,fetchOptions:e});return r.list=r.list.map(kr),r}async function jo(t,e){await this.__connection;let r=await C.bind(this)("ticket",Object.assign({exec:"consumed"},t||{}),{auth:true,fetchOptions:e});return r.list=r.list.map(kr),r}async function Ko(t){let e=await C.bind(this)("register-ticket",Object.assign({exec:"reg"},t),{auth:true});return e&&typeof e=="object"&&e.ticket&&(e.ticket=kr(e.ticket)),e}async function Ho(t){return C.bind(this)("register-ticket",Object.assign({exec:"unreg"},t),{auth:true})}var Af=3600;async function yt(){if(await this.__connection,this.session){let t=Math.floor(Date.now()/1e3),r=this.session.getIdToken().getExpiration();if(r<t+Af){this.log("request:requesting new token",null);try{await X.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),Me.bind(this)(),new f("User login is required.",{code:"INVALID_REQUEST"})}function Vo(t,e){return new Promise((r,n)=>{e.refreshSession(t.getRefreshToken(),(i,s)=>{this.log("getSession:refreshSessionCallback",{refreshErr:i,refreshedSession:s}),i?(Me.bind(this)(),n(i)):s.isValid()?r(s):(Me.bind(this)(),n(new f("Invalid session.",{code:"INVALID_REQUEST"})));});})}function X(){if(!this.userPool)throw new f("User pool is missing",{code:"INVALID_REQUEST"});let t=()=>{let s=H.getSignInUserSession().getIdToken().payload||null,o=It(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:l=false}=s||{};if(c&&l&&(l=false),H=this.userPool.getCurrentUser(),!H){this.log("getSession:cognitoUser",H),Me.bind(this)(),a(null);return}let d=h=>{let u=h.getIdToken().payload;if(this.log("getSession:respond:sessionAttribute",u),u["custom:service"]!==this.service)throw this.log("getSession:respond","invalid service, signing out"),Me.bind(this)(),new f("Invalid session.",{code:"INVALID_REQUEST"});return this.session=h,t(),l||this._runOnUserUpdateListeners(this.user),this.session};H.getSession((h,u)=>{if(this.log("getSession:getSessionCallback",{err:h,session:u}),!u){Me.bind(this)(),a(new f("Current session does not exist.",{code:"INVALID_REQUEST"}));return}if(h){Vo.bind(this)(u,H).then(b=>o(d(b))).catch(a);return}let p=Math.floor(Date.now()/1e3),g=u.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||!u.isValid())Vo.bind(this)(u,H).then(b=>o(d(b))).catch(a);else try{o(d(u));}catch(b){a(b);}});}),r=(s,o)=>{let a=o||s.includes(this.service+"-")?s:this.service+"-"+le.hash(s);return {cognitoUser:new Fe({Username:a,Pool:this.userPool}),cognitoUsername:a}};return {getSession:e,authenticateUser:(s,o,a=false,c=false)=>new Promise((l,d)=>{this.__request_signup_confirmation=null,this.__disabledAccount=null;let h=r(s,a),u=h.cognitoUsername,p=new Xr({Username:u,Password:o});h.cognitoUser.authenticateUser(p,{newPasswordRequired:(g,m)=>{this.__disabledAccount=null,this.__request_signup_confirmation=u,g["custom:signup_ticket"]==="PASS"||g["custom:signup_ticket"]==="MEMBER"||g["custom:signup_ticket"]==="OIDPASS"?h.cognitoUser.completeNewPasswordChallenge(o,{},{onSuccess:y=>{H=h.cognitoUser,e().then(async b=>{if(q.call(this))try{await Cr.bind(this)(o);}catch(w){this.log("encryption:ensureKeyring:failed",w);}l(this.user);});},onFailure:y=>{d(new f(y.message||"Failed to authenticate user.",{code:y.code}));}}):d(new f("User's signup confirmation is required.",{code:"SIGNUP_CONFIRMATION_NEEDED"}));},onSuccess:g=>e({skipUserUpdateEventTrigger:true}).then(async m=>{if(this.__disabledAccount=null,q.call(this))try{await Cr.bind(this)(o);}catch(y){this.log("encryption:ensureKeyring:failed",y);}this._runOnLoginListeners(this.user),this._runOnUserUpdateListeners(this.user),l(this.user);}),onFailure:g=>{let m=[],{parsed:y,code:b}=Ur(g),w=typeof g?.message=="string"?g.message:"";if(b==="NotAuthorizedException"?w.includes("User is disabled.")?(this.__disabledAccount=u,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=u,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=u),m.length){let E=m[1],R=m[0];d(new f(R,{code:E,cause:g}));}else d(y);}});}),createCognitoUser:r,signup:(s,o,a)=>new Promise((c,l)=>{this.userPool.signUp(s,o,a,null,(d,h)=>{if(d){let{parsed:u,code:p}=Ur(d),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=[u.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=[u.message||"Signup validation failed.",u.code==="EXISTS"?"EXISTS":"INVALID_REQUEST"]),g.length?l(new f(g[0],{code:g[1],cause:d})):l(u);return}c(h);});})}}function Ur(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 X.bind(this)().getSession(Object.assign({skipUserUpdateEventTrigger:!e,refreshToken:e},t)),this.user}catch{return null}}async function Wo(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 C.bind(this)("openid-logger",e),n=r.logger.split("#"),i=this.service+"-"+n[0],s=n[1];return {userProfile:await X.bind(this)().authenticateUser(i,s,true,true),openid:r.openid}}function Sf(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 Rf(t){let e=t.split(".");if(e.length!==3)throw new Error("Invalid JWT format");let n=e[1].replace(/-/g,"+").replace(/_/g,"/"),i=Sf(n);return JSON.parse(i)}async function zo(t){await this.__authConnection,this.log("loginWithToken:params",t),t=_.Params(t,{idToken:"string",accessToken:"string",refreshToken:"string"},["idToken"]);let e=Rf(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=It(e),this.session=null,t.accessToken&&t.refreshToken)try{if(this.session=new dt({IdToken:new lt({IdToken:t.idToken}),AccessToken:new ct({AccessToken:t.accessToken}),RefreshToken:new ut({RefreshToken:t.refreshToken})}),this.log("loginWithToken:session",this.session),this.log("loginWithToken:CognitoUser",Fe),this.log("loginWithToken:userPool",this.userPool),Fe&&this.userPool){this.log("loginWithToken:cognito:username",e["cognito:username"]);let n={Username:e["cognito:username"],Pool:this.userPool};this.log("loginWithToken:cognitoUserParams",n),H=new Fe(n),H.setSignInUserSession(this.session),this.log("loginWithToken:cognitoUserRestored",{cognitoUserType:typeof H,cognitoUserKeys:Object.keys(H||{}),cognitoUser:H});}}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 Z(){return await this.__connection,this.__user?.service===this.service?this.__user?.owner===this.host:(await qt.bind(this)(),false)}async function Me(t=false){let e=null;H&&(t?e=new Promise((n,i)=>{H.globalSignOut({onSuccess:s=>{this.log("globalSignOut:success",s),n(s);},onFailure:s=>{this.log("globalSignOut:error",s),i(s);}});}):H.signOut()),Wn.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 qt(t){await this.__connection;let{data:e}=K(t);return await Me.bind(this)(e?.global),"SUCCESS: The user has been logged out."}async function Jo(){if(!this.__request_signup_confirmation)throw new f("Least one login attempt is required.",{code:"INVALID_REQUEST"});return await C.bind(this)("confirm-signup",{username:this.__request_signup_confirmation})}async function Yo(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 C.bind(this)("recover-account",{username:this.__disabledAccount,redirect:t}),"SUCCESS: Recovery e-mail has been sent."}async function li(t){let e=_.Params(t,{username:"string",email:"string",password:"string"},["password"]);await this.__authConnection;let r=null;if(e.email)try{r=_.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"});let n=e.username||e.email;try{return await X.bind(this)().authenticateUser(n,e.password)}catch(i){if((i?.code==="UserNotFoundException"||i?.code==="NotAuthorizedException")&&r&&r!==n)return await X.bind(this)().authenticateUser(r,e.password);throw i}}async function Qo(t,e){await this.__authConnection;let r={username:"string",password:l=>_.Password(l),email:l=>_.Email(l),name:"string",address:l=>{if(!l)return "";if(typeof l=="string")return l;if(typeof l=="object")return JSON.stringify(l)},gender:"string",birthdate:l=>l?_.Birthdate(l):"",phone_number:l=>l?_.PhoneNumber(l):"",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:l=>l?_.Url(l):"",profile:l=>l?_.Url(l):"",family_name:"string",given_name:"string",middle_name:"string",nickname:"string",website:l=>l?_.Url(l):""},n=_.Params(t||{},r,["email","password"]);await qt.bind(this)(),e=_.Params(e||{},{email_subscription:l=>{if(typeof l!="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 l},signup_confirmation:l=>{let d=l;if(typeof l=="string")d=_.Url(l);else if(typeof l=="boolean")d=l;else throw new f('"option.signup_confirmation" should be type: <string | boolean>.',{code:"INVALID_PARAMETER"});if(d&&!n.email)throw new f('"email" is required for signup confirmation.',{code:"INVALID_PARAMETER"});return d},login:l=>{if(typeof l=="boolean"){if(e.signup_confirmation&&l)throw new f('"login" is not allowed when "option.signup_confirmation" is true.',{code:"INVALID_PARAMETER"});return l}throw new f('"option.login" should be type: boolean.',{code:"INVALID_PARAMETER"})},template:l=>{if(typeof l!="object"||l===null)throw new f('"option.template" should be type: <object>.',{code:"INVALID_PARAMETER"});if(l.signup_confirmation!==void 0){if(typeof l.signup_confirmation!="string"||!l.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(l.welcome!==void 0&&(typeof l.welcome!="string"||!l.welcome))throw new f('"option.template.welcome" should be a non-empty <string> (template message_id).',{code:"INVALID_PARAMETER"});return l}});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=X.bind(this)().createCognitoUser(n.username||n.email);for(let l of ["email_public","address_public","gender_public","birthdate_public","phone_number_public"])n[l]=n[l]?"1":"0";n.access_group&&(n.access_group=n.access_group.toString());let o=(await C.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 Pe({Name:"custom:signup",Value:o[0]}),new Pe({Name:"locale",Value:a.split("#")[1]}),new Pe({Name:"custom:signup_ticket",Value:a})];for(let l in r){let d=["email_public","address_public","gender_public","birthdate_public","phone_number_public","misc","service","owner"];n[l]!==""&&(l==="username"||l==="password"||l==="access_group"||(d.includes(l)?c.push(new Pe({Name:"custom:"+l,Value:n[l]})):c.push(new Pe({Name:l,Value:n[l]}))));}return await X.bind(this)().signup(s.cognitoUsername,n.password,c),n.signup_confirmation?(H=s.cognitoUser,this.__request_signup_confirmation=s.cognitoUsername,"SUCCESS: The account has been created. User's signup confirmation is required."):i?li.bind(this)({email:n.username||n.email,password:n.password}):"SUCCESS: The account has been created."}async function Xo(){await this.__connection;let t=await C.bind(this)("remove-account",{disable:this.__user.user_id},{auth:true});return await qt.bind(this)(),t}async function Zo(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)=>{X.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 ea(t,e,r){await this.__connection;let n;if(!H)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:l=>{n?X.bind(this)().getSession({refreshToken:true}).then(()=>{this.__user&&(this.__user[t+"_verified"]=true),o(`SUCCESS: "${t}" is verified.`);}).catch(d=>{a(d);}):o("SUCCESS: Verification code has been sent.");},onFailure:l=>{a(new f(l.message||"Failed to request verification code.",{code:l?.code}));}};n?H?.verifyAttribute(t,n,c):(c.inputVerificationCode=null,H?.getAttributeVerificationCode(t,c,i));})}function ta(t,e){return ea.bind(this)("phone_number",t,e)}function ra(t,e){return ea.bind(this)("email",t,e)}async function na(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)=>{X.bind(this)().createCognitoUser(r.email).cognitoUser.forgotPassword({onSuccess:c=>{s("SUCCESS: Verification code has been sent.");},onFailure:c=>{let{parsed:l,code:d}=Ur(c),h={UserNotFoundException:"NOT_EXISTS",InvalidParameterException:"INVALID_PARAMETER",NotAuthorizedException:"INVALID_REQUEST",LimitExceededException:"REQUEST_EXCEED",TooManyRequestsException:"REQUEST_EXCEED",CodeDeliveryFailureException:"CODE_DELIVERY_FAILURE"}[d]||l.code||d||"ERROR";o(new f(l.message,{code:h,cause:c}));}},n);})}async function ia(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),q.call(this)&&await vo.bind(this)(e.current_password,e.new_password),new Promise((r,n)=>{H.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}=Ur(i);n(o);}return}q.call(this)&&To.bind(this)().catch(o=>this.log("encryption:prune:failed",o)),r("SUCCESS: Password has been changed.");});})}async function sa(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;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 C.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 Pe({Name:s,Value:e[s]}));return await new Promise((s,o)=>{H?.updateAttributes(i,(a,c)=>{a&&o([a?.code||a?.name,a?.message||"Failed to update user settings."]),s(c);});}),await X.bind(this)().getSession({refreshToken:true}),this.user}return this.user}async function oa(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 C.bind(this)("get-users",t,{auth:true,fetchOptions:e})}async function aa(t){await this.__connection;let e=await C.bind(this)("last-verified-email",t,{auth:true});return e.includes("SUCCESS")?(await X.bind(this)().getSession({refreshToken:true}),this.user):e}var vf="1.2.1",Tf=class{constructor(t){ve(this,"version",vf);ve(this,"items",[]);ve(this,"nextJobId",1);ve(this,"breakWhenError",false);ve(this,"batchSize",1);ve(this,"onProgress");ve(this,"activeCount",0);ve(this,"currentCycleCompleted",[]);ve(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=[];}},Vt=Tf;var bt=null,la=typeof SubmitEvent<"u",If=typeof HTMLFormElement<"u",$t=oe(),ui=0;function ua(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 di(t,e){return e>0?t/e*100:0}var ca=t=>{let{auth:e,type:r,endpoints:n,stable:i}=t,s=n[0],o=n[1];if(ui++,r==="admin"){let a=Object.entries(s).filter(([c,l])=>c.includes(e?"_private":"_public")&&c!=="get_users_private"&&c!=="service_public"&&typeof l=="string").map(([,c])=>c);if(!a.length)throw new f("No available admin gateways.",{code:"INVALID_REQUEST"});return a[ui%a.length]}if(r==="record"){let a=Object.entries(o).filter(([c,l])=>c.includes(e?"record_private":"record_public")&&typeof l=="string").map(([,c])=>c);if(!a.length)throw new f("No available record gateways.",{code:"INVALID_REQUEST"});return i?a[0]:a[ui%a.length]}throw new f("Invalid gateway type.",{code:"INVALID_REQUEST"})};async function Pf(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 "send-inquiry":case "register-newsletter-group":case "delete-newsletter-group":case "newsletter-group-endpoint":case "invitation-list":case "csr":case "csr-poll":case "csr-cancel":case "csr-finalize":return ca.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 "grid-query":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 ca.bind(this)({auth:e,type:"record",endpoints:n,stable:r})+t+a;default:return _.Url(t)+a}}var Bt={};function da(){bt&&(bt.terminate(),bt=null);}async function C(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,l=e?.owner||this.owner,d=null,h=await Pf.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 u=r?.tokenHeaders?.idToken===true;(i||u)&&(d=await yt.bind(this)());let p={},{fetchMore:g=false,progress:m}=r?.fetchOptions||{};if(r?.fetchOptions&&Object.keys(r.fetchOptions).length){for(let x of ["limit","startKey","ascending"])if(r.fetchOptions.hasOwnProperty(x)){if(x==="startKey"&&r.fetchOptions[x]===null)continue;p[x]=r.fetchOptions[x];}p=_.Params(p,{limit:x=>{if(typeof x!="number")throw new f("Fetch limit should be a number.",{code:"INVALID_REQUEST"});if(x>1e3)throw new f("Fetch limit should be below 1000.",{code:"INVALID_REQUEST"});return x},startKey:x=>x,ascending:"boolean"});}let y=n?.ignoreService?{}:{service:c,owner:l};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}`,w=(()=>{if(e&&typeof e=="object"&&Object.keys(e).length&&!($t&&e instanceof FormData)){let x=function(D){return typeof D=="object"&&D!==null?Object.keys(D).sort().reduce((L,B)=>(typeof D[B]=="object"&&D[B]!==null?L[B]=x(D[B]):L[B]=D[B],L),{}):D};return le.hash(b+"/"+JSON.stringify(x(e)))}return le.hash(b+"/"+c)})(),{requestKey:E,requestKeyWithStartKey:R}=Cf.bind(this)({params:e,url:t,fetchMore:g,hashedParams:w});if(!E||E&&typeof E=="object")return E;if(this.log("requestKey",R),typeof R=="string"&&Bt[R]instanceof Promise)return this.log("request:returning pending",R),Bt[R];let S={Accept:"*/*"};if(Object.prototype.hasOwnProperty.call(r,"contentType")&&r.contentType!==void 0){let x=r.contentType===null?"application/x-www-form-urlencoded":r.contentType;x&&(S["Content-Type"]=x);}else S["Content-Type"]="application/json";if(d&&(S.Authorization=d),r?.tokenHeaders){let x=(B,ee)=>typeof B=="string"?B:B===true?ee:null,D=x(r.tokenHeaders.accessToken,this.session?.accessToken?.jwtToken||null),L=x(r.tokenHeaders.idToken,this.bearerToken||this.session?.idToken?.jwtToken||d||null);D&&(S["X-Access-Token"]=D),L&&(S["X-Id-Token"]=L);}let k={public_identifier:this.__public_identifier,service:c,owner:l,resolves_offloaded_data:true};S["Content-Meta"]=JSON.stringify(k),r.revalidate&&(S["Cache-Control"]="no-cache",S.Pragma="no-cache");let N={headers:S};if(r?.responseType&&(N.responseType=r.responseType),s==="GET"){if(e){let x=[];if($t&&e instanceof FormData?x=Array.from(e.entries()).map(([D,L])=>{let B=typeof L=="string"?L:L.name;return encodeURIComponent(D)+"="+encodeURIComponent(B)}):x=Object.keys(e).map(D=>{let L=e[D];return typeof L!="string"&&(L=JSON.stringify(L)),encodeURIComponent(D)+"="+encodeURIComponent(L)}),x.length){let D=h.includes("?")?h.endsWith("?")||h.endsWith("&")?"":"&":"?";h+=D+x.join("&");}}N.body=null;}else if($t&&e instanceof FormData)N.body=e;else if(S["Content-Type"]==="application/x-www-form-urlencoded"&&e&&typeof e=="object"){let x=new URLSearchParams;for(let D of Object.keys(e)){let L=e[D];x.append(D,typeof L=="string"?L:JSON.stringify(L));}N.body=x.toString();}else typeof e=="string"?N.body=e:N.body=e?JSON.stringify(e):null;if(N.method=s,bt===null){let x={batchSize:this.requestBatchSize,breakWhenError:false,onProgress:D=>{this.onBatchProcess.forEach(L=>L(D));}};bt=new Vt(x);}return this.log("request-opt",N),new Promise((x,D)=>{bt.add([async()=>{let L=fa.bind(this)(h,N,m);Bt[R]=L;try{let B=Uf.bind(this)({hashedParam:E,requestKeyWithStartKey:R,url:t,fetched:await L});return delete Bt[R],this.log("request:end",B),x(B),B}catch(B){throw delete Bt[R],this.log("request:err",B),D(B),B}}]);})}function Cf(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 l=i+le.hash(c);this.__cached_requests?.[r]&&this.__cached_requests?.[r]?.[l]&&delete this.__cached_requests[r][l];}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+=le.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 xf(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 fa(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=ua(a);c!==null?setTimeout(()=>{fa(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"],l=e.responseType=="blob"?s.response:s.responseText;try{l=JSON.parse(l);}catch{}if(typeof l=="string"){let d=l.split(":"),h=d.splice(0,1)[0].trim(),u=d.join(":").trim();i(new f(u||l,{code:c.includes(h)?h:"ERROR"}));}else if(typeof l=="object"&&(l?.message||l?.stage||l?.code)){let d=l?.code||(a?a.toString():null)||"ERROR",h=l.message,u=l?.cause;u===void 0&&l.stage&&(u=l),typeof h=="string"&&(h=h.trim()),h||(h=String(d)),i(new f(h,{cause:u,code:d}));}else i(l);}},s.onerror=()=>i("Network error"),s.onabort=()=>i("Aborted"),s.ontimeout=()=>i("Timeout"),typeof r=="function"&&(s.onprogress=a=>{r({status:"download",progress:di(a.loaded,a.total),loaded:a.loaded,total:a.total,abort:()=>s.abort()});},s.upload&&(s.upload.onprogress=a=>{r({status:"upload",progress:di(a.loaded,a.total),loaded:a.loaded,total:a.total,abort:()=>s.abort()});})),s.send(e.body);})}function Uf(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 jt(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(la&&t instanceof SubmitEvent&&(t=t.target),If&&t instanceof HTMLFormElement&&(t=new FormData(t)),!$t||!(t instanceof FormData))throw new f('"fileList" should be a FormData or HTMLFormElement.',{code:"INVALID_PARAMETER"});let o={reserved_key:Ye(),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 w=a.responseText;try{w=JSON.parse(w);}catch{}if(a.status>=200&&a.status<300)y(w);else if(a.status===429){let E=a.getResponseHeader("Retry-After"),R=ua(E);R!==null?setTimeout(()=>{c(p,g,m).then(y,b);},R):b("Too many requests");}else b(w);},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 l(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 d=[],h=[],u=[];for(let[p,g]of t.entries()){if(!(g instanceof File))continue;let m=await Mo.bind(this)(r,p,g),y=m.file,b=m.key,w=Object.assign({key:b+"/"+y.name,sizeKey:l(y.size),contentType:y.type||null},o),{fields:E=null,url:R,cdn:S}=await C.bind(this)("get-signed-url",w,{auth:!!this.__user});u.push(S);let U=new FormData;for(let k in E)U.append(k,E[k]);U.append("file",y);try{await c(R,U,typeof i=="function"?k=>i({status:"upload",progress:di(k.loaded,k.total),currentFile:g,completed:d,failed:h,loaded:k.loaded,total:k.total,abort:()=>a.abort()}):null),d.push(g);}catch{h.push(g);}}return {completed:d,failed:h,bin_endpoints:u}}var Dr={};function P(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,l=null,d="",h={},u=false;if(la&&a instanceof SubmitEvent){a.preventDefault();let b=window.location.href;l=a.target;let w=new URL(l.action);d=w.href;let E=d?d.match(/(?<=\{).*?(?=\})/g):"";if(E)for(let R of E){if(!R)continue;let S=l.querySelector(`[name="${R}"]`);if(S)if(S.type==="file")for(let U=0;U<=S.files.length-1;U++)S.files[U]&&(h[R]||(h[R]=[]),h[R].push(new Promise((k,N)=>{let x=new FileReader;x.onload=function(){k(x.result);},x.readAsDataURL(S.files[U]),x.onerror=N;})));else d=d.replace(`{${R}}`,S.value);}l.getAttribute("action")===null?c=false:u=w.href===b;}let p=async b=>{if(d)for(let w in h)h[w].length&&(d=d.replace(`{${w}}`,(await Promise.all(h[w])).join(",")));if(l&&c){let w=q.call(this)?xf(b):b;window.sessionStorage.setItem(`${this.service}:${le.hash(d)}`,JSON.stringify(w)),u?window.location.replace(d):window.location.href=d;}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 Dr?.[b]||(Dr[b]=y().finally(()=>{delete Dr[b];})),Dr[b]}return y()};}}async function ha(){await this.__connection;let t=`${this.service}:${le.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 kf=256,Df=256,Nf=256,pa=256,Of="\u{10FFFF}",Ff=/[\u0000-\u001F\u007F]|\u{10FFFF}/u,Lf={"/":"%2F","!":"%21","*":"%2A","#":"%23"},Mf={"%2F":"/","%21":"!","%2A":"*","%23":"#"};function qf(t){return t.replace(/%/g,"%25").replace(/[\/!*#]/g,r=>Lf[r]||r)}function Ae(t){return typeof t!="string"?t:t.replace(/%(2F|21|2A|23)/gi,r=>{let n=r.toUpperCase();return Mf[n]||r}).replace(/%25/gi,"%")}function Ce(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(Ff.test(t)||t.includes(Of))throw new f(`"${e}" cannot include control characters or unsupported sentinel characters.`,{code:"INVALID_PARAMETER"});if(s&&(t=qf(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 _t(t,e="table.name",r={}){return Ce(t,e,{allowEmpty:r.allowEmpty===true,maxLength:kf,blockKeyDelimiters:true})}function Or(t,e="tag",r={}){return Ce(t,e,{allowEmpty:r.allowEmpty===true,maxLength:Df,blockKeyDelimiters:true})}function Kt(t,e="index.name",r={}){return Ce(t,e,{allowEmpty:r.allowEmpty===true,maxLength:Nf,blockKeyDelimiters:true,disallowLeadingDollar:true})}function ga(t,e="index.value"){return Ce(t,e,{allowEmpty:true,maxLength:pa})}function fi(t){return typeof t=="string"&&t.slice(-1)==="."}function hi(t,e){return Ce(t,e,{allowEmpty:true,maxLength:pa,blockKeyDelimiters:true})}function ma(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=Ce(t.record_id,"record_id",{allowEmpty:false,onlyAlphanumeric:true}):t?.unique_id&&(e.unique_id=t.unique_id),e}function pi(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:"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 Nr=4503599627370496;function Fr(t){if(typeof t=="number"){if(t>Nr||t<-Nr)throw new f(`Number value should be within range -${Nr} ~ +${Nr}`,{code:"INVALID_PARAMETER"});return t}if(typeof t=="boolean")return t;if(typeof t=="string")return ga(t,"index.value");throw new f('"index.value" should be type: <number | boolean | string>.',{code:"INVALID_PARAMETER"})}function ya(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"?fi(e.index.name)?hi(t,"index.range"):ga(t,"index.range"):t}var Lr={},Vf=10080*60,Bf=3600,ba=2;function $f(t,e){if(!e)return String(ba);let r=Math.max(60,t-300)*1e3;return "g"+ba+"w"+Math.floor(Date.now()/r)}function jf(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 Kf(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 Mr(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);}})}function mi(t){return !!t&&typeof t=="object"&&!Array.isArray(t)&&typeof t.__data__=="string"&&Object.keys(t).length===1&&t.__data__.endsWith("/__data__/__json__.json")}var wt=new Map,Hf=1024,Gf=/^[0-9A-Za-z]+\/[0-9A-Za-z]+\/__data__\/__json__\.json$/,wa=/^[0-9A-Za-z_-]+$/,Wf=/^(\d{2}|\*\*)$/;function Ea(t){if(typeof t!="string")return null;let e=t.split("?")[0].split("/");if(e.length<15||e[0]!=="https:"||e[1]!==""||!e[2])return null;let r=e.slice(3);return r[0]!=="publ"&&r[0]!=="auth"||r[4]!=="records"||r[7]!=="bin"||!wa.test(r[1])?null:{origin:e.slice(0,3).join("/"),service:r[1]}}function zf(t){let e=Ea(t);!e||wt.get(e.service)===e.origin||(wt.size>=Hf&&!wt.has(e.service)&&wt.clear(),wt.set(e.service,e.origin));}function _a(t,e){if(typeof e!="string"||!Gf.test(e))return null;let r=typeof t.usr_tbl=="string"?t.usr_tbl.split("/"):null,n=typeof t.tbl=="string"?t.tbl.split("/"):null,i=null,s=null;if(typeof t.srvc=="string"){let d=t.srvc.split("!")[0].split("/");d.length===2&&(i=d[0],s=d[1]);}i||(i=r?.[2]||n?.[1]||null,i&&i===this.service&&(s=this.owner));let o=typeof t.usr=="string"&&t.usr?t.usr:r?.[0]||null,a=r?.[3]||n?.[2]||null,c=t.rec;for(let d of [i,s,o,c])if(typeof d!="string"||!wa.test(d))return null;if(typeof a!="string"||!Wf.test(a))return null;let l=null;if(Array.isArray(t.bin))for(let d of t.bin){let h=Ea(d);if(h&&h.service===i){l=h.origin;break}}return l=l||wt.get(i)||null,l?`${l}/${a==="00"?"publ":"auth"}/${i}/${s}/${o}/records/${c}/${a}/bin/${e}`:null}async function Ze(t,e,r=false,n=false,i=false){let s={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:{}},o=false,a=[],c=null;function l(u){let p=u=="**"?"private":parseInt(u);return p=p==0?"public":p==1?"authorized":p==99?"admin":p,p}let d={ip:u=>{let p=u.split("#"),g=p[0];p.length>1&&(s.unique_id=p.slice(1).join("#")),g.slice(-1)==="R"?(s.readonly=true,g=g.slice(0,-1)):s.readonly=false,/^\d{1,3}-\d{1,3}-\d{1,3}-\d{1,3}$/.test(g)&&(g=g.split("-").join("."),o=true),s.ip=g;},rec:u=>{if(!u)return;s.record_id=u;let p=u.substring(0,u.length-9),g=_e(p);s.uploaded=g;},usr:u=>{s.user_id=u;},tbl:u=>{if(u&&!s.table.name){let p=u.split("/");s.table.name=Ae(p[0]),s.table.access_group=l(p[2]),p?.[3]&&(s.table.subscription.is_subscription_record=true);}},usr_tbl:u=>{let p=u.split("/");s.user_id||(s.user_id=p[0]),s.table.name||(s.table.name=Ae(p[1]),s.table.access_group=l(p[3]),p?.[4]&&(s.table.subscription.is_subscription_record=true));},idx:u=>{if(!u)return;let p=u.split("!"),g=Ae(p.splice(0,1)[0]),m=Jf("!"+p.join("!"));s.index={name:g,value:m};},ref:u=>{u&&(s.reference=u.split("/")[0]);},tags:u=>{s.tags=Array.isArray(u)?u.map(p=>Ae(p)):u;},upd:u=>{s.updated=u;},acpt_mrf:u=>{s.source.prevent_multiple_referencing=!u;},ref_limt:u=>{s.source.referencing_limit=u;},rfd:u=>{s.referenced_count=u;},bin:async u=>{let p={},g=s?.reference||null;if(Array.isArray(u)){let m=await Promise.all(u.map(async y=>{try{let b=y.split("/").slice(3).join("/"),w=b.split("/");if(w.length<12)return null;let E=w[w.length-1],R=w[10];if(R==="__data__"&&E==="__json__.json")return {isDataFile:!0,rawUrl:y};if(Qn(R,E))return {isDataFile:!0,rawUrl:y};let S=xr(R),U=w[9],k=w[8],N=l(w[6]),x=y,D=N!=="public"&&jf.call(this,w)?{expires:Bf,browserCache:Vf}:null;if(N!=="public"&&!i)try{x=await qe.bind(this)(y,{dataType:"endpoint",_ref:g});}catch(B){console.error("Error getting signed url for private file:",B),x=y;}let L={access_group:N,filename:E,url:x,path:b,size:S?S.plainSize:_e(U),uploaded:_e(k),getFile:(B,ee)=>{let ne={dataType:B||"download",progress:ee,_ref:g},M=()=>qe.bind(this)(x,Object.assign({},ne,{_update:L}));return D?qe.bind(this)(y,Object.assign({},ne,D)).catch(()=>M()):M()}};return S&&(L.encrypted=!0,L.stored_size=_e(U)),{pathKey:S?S.key:R,obj:L}}catch{return null}}));for(let y of m)if(y&&!y.isDataFile){if(p[y.pathKey]){p[y.pathKey].push(y.obj);continue}p[y.pathKey]=[y.obj];}}s.bin=p;},prv_acs:u=>{for(let p in u)["notify_subscribers","upload_to_feed","feed_referencing_records","notify_referencing_records"].includes(p)?s.table.subscription[p]=u[p]:p==="referencing_index_restrictions"&&Array.isArray(u[p])?s.source[p]=u[p].map(m=>m&&typeof m=="object"&&typeof m.name=="string"?Object.assign({},m,{name:Ae(m.name)}):m):s.source[p]=u[p];},data:async u=>{let p={access_group:s.table.access_group,table_name:s.table.name,user_id:s.user_id,record_id:s.record_id,unique_id:s.unique_id,ctUrl:c},g=()=>{q.call(this)&&(s.encrypted={status:"failed",reason:"DATA_UNAVAILABLE"});},m=async b=>{if(n||!q.call(this)&&!Ir(b))return b;let w=await yo.bind(this)(b,p);return w.flag&&(s.encrypted=w.flag),w.value},y=Kf(u);if(y!==u){s.data=await m(y);return}if(mi(u)){let b=u.__data__,w=a.find(E=>E.endsWith(b))||null;if(!w&&!r){await Promise.resolve();let E=_a.call(this,t,b),R=false,S;if(E)try{let U=await qe.bind(this)(E,{dataType:"blob",_ref:s.reference||null});S=JSON.parse(await Mr(U)),R=!0;}catch{}if(R){s.data=await m(S);return}g();}if(w){if(r){s.data=u;return}try{let E=await qe.bind(this)(w,{dataType:"blob",_ref:s.reference||null}),R=await Mr(E);s.data=await m(JSON.parse(R));}catch(E){let R=_a.call(this,t,b),S=false,U;if(R&&R!==w)try{let k=await qe.bind(this)(R,{dataType:"blob",_ref:s.reference||null});U=JSON.parse(await Mr(k)),S=!0;}catch{}if(S){s.data=await m(U);return}console.error("Failed to fetch offloaded record data:",E),s.data=null,g();}return}}s.data=await m(u);}};if(t.record_id)return t;if(Array.isArray(t.bin))for(let u of t.bin)try{if(typeof u!="string")continue;zf(u);let p=u.split("/").slice(3);p.length>=12&&p[10]==="__data__"&&p[p.length-1]==="__json__.json"&&a.push(u),p.length>=12&&Qn(p[10],p[p.length-1])&&(c=u);}catch{}let h=[];for(let u in d)if(t.hasOwnProperty(u)){let p=d[u](t[u]);p instanceof Promise&&h.push(p);}return o&&(s.user_id="anonymous:"+s.user_id),await Promise.all(h),s}function Jf(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 Aa(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 C.bind(this)("del-files",{endpoints:e,storage:"records"},{auth:true,method:"post"}),n=[];for(let i in r)n.push(Ze.bind(this)(r[i]));return Promise.all(n)}async function qe(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("/"),d=c[2].split("."),h=null;d.length===3&&d[1]==="skapi"&&(h=d[0],a=true);let u=c.slice(3),p=false;if(!a&&(u[0]==="auth"||u[0]==="publ"))try{_.UserId(u[2]),_.UserId(u[3]),p=u[0]=="auth",a=!0;}catch{throw new f("Invalid file url.",{code:"INVALID_PARAMETER"})}let g=h?null:u[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:E=>E}),e?.dataType==="info")return {url:t,filename:u[u.length-1],fileKey:u[u.length-2],access_group:u[6]==="**"?"private":u[6]==="01"?"authorized":u[6]==="00"?"public":parseInt(u[6]),uploader:u[3],record_id:u[4]==="records"?u[5]:"N/A",filesize:_e(u[9]),uploaded:_e(u[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 E={request:h?"get-host":"get",id:h||u[5],key:r.split("?")[0],expires:y};g&&(E.service=g);let R=e.browserCache,S={auth:true};if(R){if(R<0)throw new f('"config.browserCache" should be > 0. (seconds)',{code:"INVALID_PARAMETER"});S.method="get",S.stableGateway=true,E.browser_cache=R;let U=this.session?.idToken?.payload?.sub||this.user?.user_id;U&&(E.uid=U),E.nocache=$f(y,e.refresh);}t=(await C.bind(this)("get-signed-url",E,S)).url;}else if(p){let E=Math.floor(Date.now()/1e3);if(!this.bearerToken&&(!this.session?.idToken?.payload?.exp||this.session.idToken.payload.exp<E)){this.log("getFile:requesting new token",null);try{await X.bind(this)().getSession({refreshToken:!0}),this.log("getFile:received new tokens",{exp:this.session?.idToken?.payload?.exp,currTime:E,expiresIn:this.session?.idToken?.payload?.exp-E,token:this.session?.accessToken?.jwtToken,refreshToken:this.session?.refreshToken?.token});}catch(k){throw this.log("getFile:new token error",k),new f("User login is required.",{code:"INVALID_REQUEST"})}}let R=this.bearerToken||this.session?.idToken?.jwtToken;if(!R||!this.user?.user_id)throw new f("User login is required.",{code:"INVALID_REQUEST"});t+=`${t.includes("?")?"&":"?"}t=${encodeURIComponent(R)}`;let S=u[6]==="**"?"**":parseInt(u[6]),U=this.user?.access_group??-1;if(this.user.user_id!==u[3]&&(S==="**"||U<S)){let k=u[5];if(this.__private_access_key[k]&&typeof this.__private_access_key[k]=="string")t+=`&p=${encodeURIComponent(this.__private_access_key[k])}`;else if(this.owner!==this.host)try{let N=await this.requestPrivateRecordAccessKey({record_id:k,reference_id:e?._ref});t+=`&p=${encodeURIComponent(N)}`;}catch{}}}if((q.call(this)?ai(t):null)&&e?.dataType!=="endpoint"&&e?.dataType!=="info"){let E=await C.bind(this)(t,null,{method:"get",contentType:null,responseType:"blob",fetchOptions:{progress:e?.progress}},{ignoreService:true}),R=await qo.bind(this)(t,E);if(e?.dataType==="blob")return R;if(e?.dataType==="text")return await Mr(R);if(e?.dataType==="base64")return await new Promise((k,N)=>{let x=new FileReader;x.onloadend=()=>k(x.result),x.onerror=()=>N(x.error),x.readAsDataURL(R);});let S=URL.createObjectURL(R),U=document.createElement("a");return U.href=S,document.body.appendChild(U),U.setAttribute("download",m),U.click(),document.body.removeChild(U),setTimeout(()=>URL.revokeObjectURL(S),6e4),null}if(e?.dataType==="endpoint")return e._update&&(e._update.url=t),t;if(e?.dataType==="download"){let E=document.createElement("a");return E.href=t,document.body.appendChild(E),E.setAttribute("download",m),E.target="_blank",E.click(),document.body.removeChild(E),null}return new Promise(async(E,R)=>{try{let S=await C.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 U=new FileReader;U.onloadend=()=>E(U.result),U.readAsDataURL(S);}else E(S);}catch(S){if(e?.browserCache&&!e?.refresh)try{E(await qe.bind(this)(r,Object.assign({},e,{refresh:!0})));return}catch(U){R(U);return}R(S);}})}function qr(t,e){return `${t||this.service}/${e||this.owner}`}function gi(t,e){let r=this.__my_unique_ids[t];return r?r[e]:void 0}function Sa(t,e,r){this.__my_unique_ids[t]||(this.__my_unique_ids[t]={}),this.__my_unique_ids[t][e]=r;}function Yf(t,e){this.__my_unique_ids[t]&&delete this.__my_unique_ids[t][e];}function Ra(t,e){return !e||e.table===void 0?t:Object.assign({},t,{table:e.table})}async function Ht(t){if(await this.__connection,!this.__user&&this.connection?.opt?.require_login===true)throw new f(`This project requires users to sign in before reading its database, so "${t}" is not available to a signed-out visitor.`,{code:"REQUIRE_LOGIN"})}async function va(t,e=false){t=K(t,{ignoreEmpty:true}).data||{};let r=qr.bind(this)(t?.service,t?.owner),n="",i=ma(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=gi.bind(this)(r,n);s&&(e?Yf.bind(this)(r,n):t.record_id=s);}}else {let s=await Z.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=l=>({table:{name:d=>_t(d,"table.name"),access_group:pi.bind(this),subscription:d=>_.UserId(d,'User ID in "subscription"')},reference:"string",index:{name:["$updated","$uploaded","$referenced_count","$user_id",d=>Kt(d,"index.name")],value:d=>{let h={$updated:"number",$uploaded:"number",$referenced_count:"number",$user_id:_.UserId};if(h.hasOwnProperty(l.index.name)){let u=h[l.index.name];if(typeof u=="function")return u(d);if(u!==typeof d)throw new f(`"index.value" should be type: ${u}.`,{code:"INVALID_PARAMETER"});return d}return typeof d=="string"&&!d?"":typeof d=="string"&&fi(l.index.name)?hi(d,"index.value"):Fr(d)},condition:["gt","gte","lt","lte",">",">=","<","<=","=","eq"],range:d=>ya(d,l)},tag:d=>{if(d==null)return d;if(typeof d=="string")return Or(d,"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 Ta(t,e){await this.__connection,await Ht.call(this,"getRecords");let r=await va.bind(this)(t),n=r.is_reference_fetch,i=await C.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(Ze.bind(this)(i.list[o]));return i.list=await Promise.all(s),i}function Ia(t){let e="",r=[],n=qr.bind(this)(t?.service,t?.owner),i=_.Params(t||{},{record_id:o=>{let a=typeof o=="string"?gi.bind(this)(n,o):void 0;return a||Ce(o,"record_id",{allowEmpty:false})},unique_id:["string",null],readonly:"boolean",table:{name:o=>_t(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:pi.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:l=>Kt(l,'"name" in "index_restrictions"'),value:l=>Fr(l),condition:["gt","gte","lt","lte",">",">=","<","<=","=","eq","!=","ne",()=>null],range:l=>{if(l!==null&&typeof o.value!=typeof l)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 l}};Array.isArray(o)||(o=[o]);let c=o.map(l=>_.Params(l,a,["name"]));if(c.length)for(let l of c)l.condition&&l.hasOwnProperty("range")&&delete l.range;return c}},reference:o=>{if(o===null)return {record_id:null};if(o){if(typeof o=="string"){e=o;let a=gi.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),Ce(a,"reference.record_id",{allowEmpty:false,onlyAlphanumeric:true}))})}},index:[null,{name:o=>Kt(o,"index.name"),value:o=>Fr(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=>Or(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 d=c.url.split("/").slice(0,3).join("/")+"/"+c.path;a.push(d);}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},a?.record_id||(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 Pa(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={},o={},c={_is_bulk_:await Promise.all(t.map(async(g,m)=>{if(!g||typeof g!="object"||Array.isArray(g))throw new f(`"params[${m}]" should be type: <object>.`,{code:"INVALID_PARAMETER"});o[m]={has:g.data!==void 0,value:g.data};let y=Ia.bind(this)(g),b=y.config;if(q.call(this)){let w=Object.prototype.hasOwnProperty.call(b,"data"),E=await Xn.bind(this)(b.data,Ra(g,b),w);E.encrypted&&(b.data=E.send,s[m]=E.plain);}if(y.is_reference_post&&e.push(y.is_reference_post),typeof b.progress=="function"&&i===null&&(i=b.progress),b.service!==void 0){if(r===void 0)r=b.service;else if(r!==b.service)throw new f('All bulk params should share the same "service" value.',{code:"INVALID_PARAMETER"})}if(b.owner!==void 0){if(n===void 0)n=b.owner;else if(n!==b.owner)throw new f('All bulk params should share the same "owner" value.',{code:"INVALID_PARAMETER"})}return delete b.progress,delete b.service,delete b.owner,b})),service:"",owner:""};r!==void 0&&(c.service=r),n!==void 0&&(c.owner=n);let l={auth:!!this.__user,method:"post"},d={};Object.keys(d).length&&Object.assign(l,{fetchOptions:d});let h=await C.bind(this)("post-record",c,l),u=await Promise.all(h.map((g,m)=>Ze.bind(this)(g,"called from postRecord",o[m]?.has===true,s.hasOwnProperty(m))));for(let g=0;g<u.length;g++)s.hasOwnProperty(g)&&u[g]&&!u[g].error?(u[g].data=s[g],u[g].encrypted={status:"encrypted"}):o[g]?.has&&u[g]&&!h[g]?.error&&mi(h[g]?.data)&&(u[g].data=o[g].value);let p=qr.bind(this)(r,n);for(let g=0;g<h.length;g++){let m=h[g],y=u[g];if(m&&typeof m=="object"&&m.error&&y&&!y.record_id&&(y.error=m.error),typeof m?.reference_private_key=="string")for(let b of e)this.__private_access_key[b]=m.reference_private_key;y?.unique_id&&Sa.bind(this)(p,y.unique_id,y.record_id);}return u}async function yi(t,e,r){if(await this.__connection,!e)throw new f('"config" argument is required.',{code:"INVALID_PARAMETER"});let n=Ia.bind(this)(e),i=n.config,s=n.progress,o=n.is_reference_post,a={auth:!!this.__user,method:"post"},c=[],l=K(t);r&&Array.isArray(r)&&r.length&&(c=c.concat(r)),l.files&&Array.isArray(l.files)&&l.files.length&&(c=c.concat(l.files));let d=e?.data!==void 0?e.data:l.data,h=d!==void 0,u=await Xn.bind(this)(d,Ra(e,i),h),p=null;p=Object.assign({},i),delete p.data,u.omit||(p.data=u.send);let g={};if(typeof s=="function"&&(g.progress=s),Object.keys(g).length&&Object.assign(a,{fetchOptions:g}),u.files==="decrypt"&&e?.record_id){let E=await ci.bind(this)(e.record_id,"decrypt",s);if(E.length){let R=p.remove_bin;p.remove_bin=Array.isArray(R)?R.concat(E):E;}}if(u.spill&&e?.record_id){let E=new FormData;if(E.append(Mt,new File([u.spill],"payload.bin",{type:"application/octet-stream"})),await jt.bind(this)(E,{record_id:e.record_id}),u.retireCt){let R=p.remove_bin,S=[u.retireCt];p.remove_bin=Array.isArray(R)?R.concat(S):S;}}let m=await C.bind(this)("post-record",p,a);if(u.encrypted&&m?.rec&&go.bind(this)(m.rec,u.dek),u.files==="encrypt"&&m?.rec)try{let E=await ci.bind(this)(m.rec,"encrypt",s);E.length&&await yi.bind(this)(void 0,{record_id:m.rec,remove_bin:E});}catch(E){console.error("Failed to encrypt existing attachments after making the record private:",E);}if(oe()&&c.length){let E=new FormData;for(let U of c)E.append(U.name,U.file,U.file.name);let R={record_id:m.rec,progress:s};i.hasOwnProperty("service")&&(R.service=i.service);let{bin_endpoints:S}=await jt.bind(this)(E,R);m.bin?m.bin.push(...S):m.bin=S;}o&&typeof m?.reference_private_key=="string"&&(this.__private_access_key[o]=m.reference_private_key);let y=!!m&&mi(m.data),b=!u.omit&&u.send!==void 0,w=await Ze.bind(this)(m,"called from postRecord",b,u.encrypted);if(y&&b&&!u.encrypted&&(w.data=u.plain),u.encrypted&&(w.data=u.plain,w.encrypted={status:"encrypted",recipients:Object.keys(u.send.k||{})}),w.unique_id){let E=qr.bind(this)(i?.service,i?.owner);Sa.bind(this)(E,w.unique_id,w.record_id),oe()&&(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 w}async function Ca(t,e){await Ht.call(this,"getTables");let r=await C.bind(this)("get-table",_.Params(t||{},{table:i=>_t(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=Ae(i.table));}return r}async function xa(t,e){if(await Ht.call(this,"getIndexes"),!t?.table)throw new f('"table" is required.',{code:"INVALID_PARAMETER"});let r=_.Params(t||{},{table:s=>_t(s,"table",{allowEmpty:true}),index:s=>Kt(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 Ce(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 C.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:Ae(o[1]),index:Ae(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 Ua(t,e){await Ht.call(this,"getTags");let r=await C.bind(this)("get-tag",_.Params(t||{},{table:n=>_t(n,"table",{allowEmpty:true}),tag:n=>Or(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:Ae(i[1]),tag:Ae(i[0]),number_of_records:n.cnt_rec}})),r}async function ka(t,e){await Ht.call(this,"getUniqueId");let r=await C.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}async function Da(t,e){await this.__connection;let r=await va.bind(this)(t,true),n=r.is_reference_fetch,i=await C.bind(this)("del-records",r.query,{auth:true,fetchOptions:e});return n&&typeof i?.reference_private_key=="string"&&(this.__private_access_key[n]=i.reference_private_key),Array.isArray(i?.list)&&(i.list=await Promise.all(i.list.map(async s=>{if(!s||typeof s!="object")return s;try{return await Ze.bind(this)(s,"called from deleteRecords",!0,!1,!0)}catch{return s}}))),i?.message||i}async function Na(t){if(q.call(this)){let e=typeof t.user_id=="string"?[t.user_id]:t.user_id;Array.isArray(e)&&e.length&&await oi.bind(this)(t.record_id,e);}return Ma.bind(this)({record_id:t.record_id,user_id:t.user_id,execute:"add"})}async function Oa(t){let e=await Ma.bind(this)({record_id:t.record_id,user_id:t.user_id||null,execute:"remove"});if(q.call(this)){let r=typeof t.user_id=="string"?[t.user_id]:t.user_id;await xo.bind(this)(t.record_id,Array.isArray(r)&&r.length?r:null);}return e}async function Fa(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 C.bind(this)("grant-private-access",r,{auth:true,fetchOptions:e});return i.list=i.list.map(n),i}function La(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(Lr[e])return Lr[e];let n=C.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 Lr[e];});return Lr[e]=n,n}function Ma(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),C.bind(this)("grant-private-access",r,{auth:true})}var O={},Y={},Se={},Ue={},xe={},Vr={},Br={};function qa(t,e,r){t[e]||(t[e]=[]),t[e].push(r);}async function $r(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 _i(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 O[s].setRemoteDescription(new RTCSessionDescription(i));let a=await O[s].createAnswer();await O[s].setLocalDescription(a),o.send(JSON.stringify({action:"rtc",uid:s,content:{sdpanswer:a},token:this.session.accessToken.jwtToken}));}O?.[e]?t?(await $r(Br,e,i=>n.bind(this)(i,e,r)),await n.bind(this)(t,e,r)):await $r(Br,e,i=>n.bind(this)(i,e,r)):t&&qa(Br,e,t);}async function wi(t,e){if(this.log("receiveIceCandidate",t),O?.[e]&&O[e]?.remoteDescription&&O[e]?.remoteDescription?.type){if(!t)return $r(Vr,e,r=>O[e].addIceCandidate(r));await $r(Vr,e,r=>O[e].addIceCandidate(r)),await O[e].addIceCandidate(t);}else qa(Vr,e,t);}async function Re(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 Br[s],delete Vr[s],Y[s]&&Object.values(Y[s]).forEach(o=>{o.readyState!=="closed"&&o.close();}),delete Y[s],O?.[s]){O[s].connectionState!=="closed"&&(O[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:O[s],timestamp:new Date().toISOString(),state:O[s].connectionState,iceState:O[s].iceConnectionState,signalingState:O[s].signalingState};xe[s]&&xe[s](o),this.log("closeRTC",o);}delete xe[s],delete Ue[s],delete Se[s],delete O[s];};if(n)for(let s in O)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 Va(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 Ba(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}]};O?.[r]||(O[r]=new RTCPeerConnection(s)),t?.media&&(this.__mediaStream=await Va(t.media),this.__mediaStream.getTracks().forEach(o=>{O[r].addTrack(o,this.__mediaStream);})),xe[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 l=O[r].createDataChannel(c,a);Y[r][c]=l;}for(let o in Y[r]){let a=Y[r][o];Ka.bind(this)(r,a);}return ja.bind(this)(r,["onnegotiationneeded"]),await bi.bind(this)(r),{hangup:()=>Se[r]&&Se[r](false),connection:new Promise(o=>{Se[r]=(a=>{if(this.log("receiver picked up the call",r),!a)return Re.bind(this)({cid:r}),null;O[r].onnegotiationneeded=()=>{this.log("onnegotiationneeded",`sending offer to "${r}".`),bi.bind(this)(r),xe[r]&&xe[r]({type:"negotiationneeded",target:O[r],timestamp:new Date().toISOString(),signalingState:O[r].signalingState,connectionState:O[r].iceConnectionState,gatheringState:O[r].iceGatheringState});},o({target:O[r],channels:Y[r],hangup:()=>Re.bind(this)({cid:r}),media:this.__mediaStream});}).bind(this);})}}function $a(t){return async(e,r)=>{e=e||{},e=K(e).data;let n=t.sender_cid,i=await this.__socket;if(!Ue[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 O?.[n]||(O[n]=new RTCPeerConnection({iceServers:[{urls:s}]})),e?.media&&(this.__mediaStream=await Va(e.media),this.__mediaStream.getTracks().forEach(o=>{O[n].addTrack(o,this.__mediaStream);})),delete Ue[n],xe[n]=r,Y[n]||(Y[n]={}),O[n].ondatachannel=o=>{this.log("ondatachannel",`received data channel "${o.channel.label}".`);let a=o.channel;Y[n][a.label]=a,Ka.bind(this)(n,a);},ja.bind(this)(n,["onnegotiationneeded"]),await _i.bind(this)(null,n),await wi.bind(this)(null,n),i.send(JSON.stringify({action:"rtc",uid:n,content:{pickup:this.user.user_id},token:this.session.accessToken.jwtToken})),{target:O[n],channels:Y[n],hangup:()=>Re.bind(this)({cid:n}),media:this.__mediaStream}}}async function bi(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 O[t].createOffer();await O[t].setLocalDescription(r);let n=O[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 Qf(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=xe[e]||(()=>{}),i=t.candidate;this.log("ice gathering state set to",O[e].iceGatheringState),n({type:"icecandidate",target:O[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:O[e].iceGatheringState,connectionState:O[e].iceConnectionState}),r.send(JSON.stringify({action:"rtc",uid:e,content:{candidate:i},token:this.session.accessToken.jwtToken}));}function ja(t,e){let r=new Set(e),n=xe[t]||(o=>{}),i=O[t],s={ontrack:o=>{n({type:"track",target:i,timeStamp:o.timeStamp,streams:o.streams,track:o.track});},onicecandidate:o=>{Qf.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:()=>{bi.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")&&Re.bind(this)({cid:t});}};for(let[o,a]of Object.entries(s))r.has(o)||(i[o]=a);}function Ka(t,e,r){let n=new Set(r),i=xe[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&&Re.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 Ve;function Ha(){return Ve}var Ge=null,Gt=true,Et=0;async function Xf(){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 Ei=null;async function jr(){if(typeof window>"u"||window._runningInNodeJS)throw new f("WebSocket is not supported in Node.js environment.",{code:"NOT_SUPPORTED"});Gt=true;let t=this.__socket?await this.__socket:this.__socket;Re.bind(this)({close_all:true}),Ve&&St.bind(this)({group:null}),Et=0,Ge&&(Ge.terminate(),Ge=null);try{t&&t.close();}catch{}return window.removeEventListener("visibilitychange",Ei),this.__socket=null,null}async function At(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 i=await this.__socket;if(i.readyState!==WebSocket.CLOSED&&i.readyState!==WebSocket.CLOSING)return this.__socket}}else if(Gt&&(Ei=()=>{!document.hidden&&!Gt&&At.bind(this)(t,0,"reconnect");},this.__socket instanceof Promise))return this.__socket;Ge&&(Ge.terminate(),Ge=null);let n={value:null};return this.__socket=new Promise(async(i,s)=>{let o=a=>{this.__socket===n.value&&(this.__socket=null),s(a);};try{await yt.bind(this)();}catch(a){o(a);return}setTimeout(async()=>{try{let a=await Xf.bind(this)();a.onopen=()=>{Gt=!1,Et=0,r!=="reconnect"&&window.addEventListener("visibilitychange",Ei),this.log("realtime onopen","Connected to WebSocket server."),t({type:"success",message:"Connected to WebSocket server."}),Ve&&a.send(JSON.stringify({action:"joinRoom",rid:Ve,token:this.session.accessToken.jwtToken}));let c=`
|
|
208
208
|
let interval = 15000; // Set interval time 15 seconds
|
|
209
209
|
|
|
210
210
|
function runInterval() {
|
|
@@ -213,9 +213,9 @@ var Fc=Object.create;var et=Object.defineProperty;var bi=Object.getOwnPropertyDe
|
|
|
213
213
|
}
|
|
214
214
|
|
|
215
215
|
runInterval(); // Start interval
|
|
216
|
-
`,c=new Blob([l],{type:"application/javascript"});He=new Worker(URL.createObjectURL(c)),He.onmessage=u=>{a.readyState===1&&a.send(JSON.stringify({action:"keepAlive"}));},i(a);},a.onmessage=async l=>{let c="";try{c=JSON.parse(decodeURI(l.data)),this.log("socket onmessage",c);}catch{return}let u;switch(!0){case !!c?.["#message"]:u="message";break;case !!c?.["#private"]:u="private";break;case !!c?.["#notice"]:u="notice";break;case !!c?.["#rtc"]:u="rtc";break;case !!c?.["#error"]:u="error";break}if(!u)return;let f={type:u,message:c?.["#rtc"]||c?.["#message"]||c?.["#private"]||c?.["#notice"]||c?.["#error"]||null,sender:c?.["#user_id"]||null,sender_cid:c?.["#scid"]?"cid:"+c["#scid"]:null,sender_rid:c?.["#srid"]||null,code:c?.["#code"]||null};if(u==="notice")t(f);else if(u==="rtc"){if(f.sender!==this.user.user_id){let d=f.message;if(d.hungup){Se[f.sender_cid]&&(Se[f.sender_cid](!1),delete Se[f.sender_cid]),Ce[f.sender_cid]&&delete Ce[f.sender_cid],D?.[f.sender_cid]&&ve.bind(this)({cid:f.sender_cid}),f.type="rtc:closed",t(f);return}if(d.candidate&&gi.bind(this)(d.candidate,f.sender_cid),d.sdpoffer&&(pi.bind(this)(d.sdpoffer,f.sender_cid),Ce[f.sender_cid]||(Ce[f.sender_cid]=f.sender_cid,delete f.message,f.connectRTC=Ua.bind(this)(f),f.type="rtc:incoming",f.hangup=(()=>{D[f.sender_cid]?ve.bind(this)({cid:f.sender_cid}):Ce[f.sender_cid]&&(delete Ce[f.sender_cid],a.send(JSON.stringify({action:"rtc",uid:f.sender_cid,content:{hungup:this.user.user_id},token:this.session.accessToken.jwtToken})));}).bind(this),t(f))),d.pickup&&Se[f.sender_cid]&&(Se[f.sender_cid](!0),delete Se[f.sender_cid]),d.sdpanswer&&D[f.sender_cid])if(D[f.sender_cid].signalingState==="have-local-offer")await D[f.sender_cid].setRemoteDescription(new RTCSessionDescription(d.sdpanswer));else throw new h("Invalid signaling state.",{code:"INVALID_REQUEST"})}}else t(f);},a.onclose=()=>{Ht?(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."}),wt++,wt<3?(this.log("realtime onclose","Reconnecting to WebSocket server..."+wt),t({type:"reconnect",message:"Reconnecting to WebSocket server..."+wt}),Et.bind(this)(t,3e3,"reconnect")):(this.log("realtime onclose","Max reconnection attempts reached."),t({type:"error",message:"Skapi: Max reconnection attempts reached."})));},a.onerror=()=>{this.log("realtime onerror","WebSocket connection error."),t({type:"error",message:"Skapi: WebSocket connection error."});};}catch(a){o(a);}},e);}),n.value=this.__socket,this.__socket}async function Da(t,e,r){if(typeof window>"u"||window._runningInNodeJS)throw new h("WebSocket is not supported in Node.js environment.",{code:"NOT_SUPPORTED"});let n=this.__socket?await this.__socket:this.__socket;if(!n)throw new h("No realtime connection. Execute connectRealtime() before this method.",{code:"INVALID_REQUEST"});if(!e)throw new h("No recipient.",{code:"INVALID_REQUEST"});await yt.bind(this)(),t=j(t).data;let i="";if(r&&(r=b.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 h("Notification size exceeds 3kb.",{code:"INVALID_PARAMETER"});if(n.readyState===1){try{b.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}),qe!==e)throw new h(`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 h("Realtime connection is not open. Try reconnecting with connectRealtime().",{code:"INVALID_REQUEST"})}async function At(t){if(typeof window>"u"||window._runningInNodeJS)throw new h("WebSocket is not supported in Node.js environment.",{code:"NOT_SUPPORTED"});let e=this.__socket?await this.__socket:this.__socket;if(!e)throw new h("No realtime connection. Execute connectRealtime() before this method.",{code:"INVALID_REQUEST"});await yt.bind(this)(),t=j(t,{nullIfEmpty:true}).data;let{group:r=null}=t;if(!r&&!qe)return {type:"success",message:"Left realtime message group."};if(r!==null&&typeof r!="string")throw new h('"group" must be a string | null.',{code:"INVALID_PARAMETER"});return e.readyState===1&&e.send(JSON.stringify({action:"joinRoom",rid:r,token:this.session.accessToken.jwtToken})),qe=r,{type:"success",message:r?`Joined realtime message group: "${r}".`:"Left realtime message group."}}async function Na(t,e){t=b.Params(t,{user_id:n=>b.UserId(n,'User ID in "user_id"'),group:["string",()=>{if(!qe)throw new h('No group has been joined. Otherwise "group" is required.',{code:"INVALID_REQUEST"});return qe}]});let r=await T.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 Oa(t,e){if(await this.__connection,t||(t={searchFor:"group",value:" ",condition:">"}),t=b.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 h('"value" must be a number.',{code:"INVALID_PARAMETER"});if(t.searchFor==="group"&&typeof t.value!="string")throw new h('"value" must be a string.',{code:"INVALID_PARAMETER"});if(t.hasOwnProperty("range")&&typeof t.range!=typeof t.value)throw new h(`"range" must be a ${typeof t.value}.`,{code:"INVALID_PARAMETER"});let r=await T.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 Fa=typeof FormData<"u",La=typeof HTMLFormElement<"u",Ma=typeof SubmitEvent<"u",ke={},Wt={},de={};function Gt(t){return Object.freeze({id:t,status:"stopped"})}function qa(t){return !!t&&typeof t=="object"&&t.status==="stopped"}var Va=3;function Ba(t,e,r){let n=false,i=Array.isArray(t?.chunks)?t.chunks.slice():[];i.sort((s,o)=>(s?.seq||0)-(o?.seq||0));for(let s of i)if(!(!s||typeof s.seq!="number"||s.seq<=e.seq)&&(e.seq=s.seq,n=true,r&&typeof s.txt=="string"&&s.txt!==""))try{r(s.txt,s.seq,"poll");}catch(o){console.error(o);}return typeof t?.last_seq=="number"&&t.last_seq>e.seq&&(e.seq=t.last_seq,n=true),n}var Nf=2e3,$a=5e3,Of=2e3,Ff=5,Lf=1500,Br=null;function Ka(t,e,r){let n=new Map,i=false,s=false,o=0,a={socket:0,poll:0},l=(d,p,g)=>{if(t.seq=d,!(!e||typeof p!="string"||p===""))try{e(p,d,g);}catch(m){console.error(m);}},c=()=>{for(let d of Array.from(n.keys()))d<=t.seq&&n.delete(d);for(;;){let d=t.seq+1;if(!n.has(d))break;let p=n.get(d);n.delete(d),l(d,p.txt,p.via);}};return {cursor:t,open:()=>{i||s||(i=true,c());},fromPoll:d=>{if(s)return false;let p=t.seq,g=t.seq,m=Array.isArray(d?.chunks)?d.chunks:[];for(let w of m){if(!w||typeof w.seq!="number"||w.seq<=t.seq)continue;let _=!n.has(w.seq);_&&(a.poll++,r&&a.poll===1&&r("poll",w.seq)),n.set(w.seq,{txt:typeof w.txt=="string"?w.txt:"",via:_?"poll":n.get(w.seq).via}),w.seq>g&&(g=w.seq);}typeof d?.last_seq=="number"&&d.last_seq>g&&(g=d.last_seq);let y=Array.from(n.keys()).sort((w,_)=>w-_);for(let w of y){if(w<=t.seq){n.delete(w);continue}if(w>g)break;let _=n.get(w);n.delete(w),l(w,_.txt,_.via);}return g>t.seq&&(t.seq=g),c(),t.seq>p},fromSocket:(d,p)=>{s||typeof d!="number"||!Number.isFinite(d)||(o=Date.now(),!(d<=t.seq)&&(!n.has(d)&&n.size>=Of||(n.has(d)||(a.socket++,r&&a.socket===1&&r("socket",d)),n.set(d,{txt:typeof p=="string"?p:"",via:n.has(d)?n.get(d).via:"socket"}),i&&c())));},warm:()=>o!==0&&Date.now()-o<Nf,stats:()=>({socket:a.socket,poll:a.poll}),close:()=>{s=true,n.clear();}}}function ja(t){if(!this||!this.__network_logs)return {onTransport:void 0,done:()=>{}};let e=Date.now(),r=false;return {onTransport:(n,i)=>{console.log(`%cSKAPI: stream chunk arrived over ${n==="socket"?"WEBSOCKET":"POLL"}`,`color: ${n==="socket"?"green":"orange"};`,{id:t,first_seq:i,after_ms:Date.now()-e});},done:n=>{if(r||!n)return;r=true;let i=n.stats();console.log("%cSKAPI: stream transport","color: blue;",{id:t,over_websocket:i.socket,over_poll:i.poll,took_ms:Date.now()-e});}}}function Ha(t,e){let r={stop:()=>{}};if(typeof window>"u"||window._runningInNodeJS||Br)return r;let n={stopped:false,socket:null,opened:null,joined:false,attempts:0,unavailable:false};Br=n;let i=c=>{if(n.stopped)return;let u=c?.data;if(typeof u!="string")return;let f=null;try{f=JSON.parse(u);}catch{try{f=JSON.parse(decodeURI(u));}catch{return}}let d=f?.["#message"];if(d==null)return;if(typeof d=="string")try{d=JSON.parse(d);}catch{return}if(typeof d!="object")return;let p=f?.["#srid"];if(typeof p=="string"&&p!==t)return;let g=d.seq;typeof g=="string"&&g!==""&&(g=Number(g)),e.fromSocket(g,d.txt);},s=()=>{if(n.socket){try{n.socket.removeEventListener("message",i);}catch{}try{n.socket.removeEventListener("close",a);}catch{}n.socket=null;}},o=async()=>{let c=n.opened,u=n.joined;if(n.opened=null,n.joined=false,s(),!(!u&&!c))try{let f=this.__socket?await this.__socket:null;if(c&&f===c){await Vr.bind(this)();return}u&&f&&ka()===room&&await At.bind(this)({group:null});}catch{}},a=()=>{n.stopped||(s(),!n.unavailable&&(n.attempts>=Ff||(n.attempts+=1,setTimeout(()=>{n.stopped||l();},Lf))));},l=async()=>{try{let c=this.__socket?await this.__socket:null;if(n.stopped){o();return}if(!c){if(!this.session){n.unavailable=!0,o();return}if(await Et.bind(this)(()=>{},0),c=this.__socket?await this.__socket:null,n.stopped){o();return}c&&!n.opened&&(n.opened=c);}if(!c||c.readyState!==1)return;if(c.addEventListener("message",i),c.addEventListener("close",a),n.socket=c,!n.joined&&(await At.bind(this)({group:t}),n.joined=!0,n.stopped)){o();return}}catch{}};return l(),{stop:()=>{n.stopped||(n.stopped=true,Br===n&&(Br=null),o());}}}function Wa(t){return t?.status==="running"||t?.status==="pending"}function Mf(t){return !!t&&typeof t=="object"&&!Array.isArray(t)&&typeof t.status=="string"&&typeof t.id=="string"&&"in_queue"in t}function Ga(t,e,r,n){if(!t||typeof t!="string")throw new h('"requestId" should be type: <string>.',{code:"INVALID_PARAMETER"});if(t.includes("#"))return t;if(!e||typeof e!="string"||!r||typeof r!="string")throw new h('"url" and "method" are required to address a request by its short id.',{code:"INVALID_PARAMETER"});return b.Url(e),`[${r.toUpperCase()}]${e.toLowerCase()}#${n}:${t}`}function Ja({id:t,auth:e,service:r,owner:n,latency:i=1e3,queue:s,seedExecuted:o,onResponse:a,onError:l,onStream:c,realtimeGroup:u}){if(typeof i!="number")throw new h('"latency" should be a number.',{code:"INVALID_PARAMETER"});if(i<0)throw new h('"latency" should be a non-negative number.',{code:"INVALID_PARAMETER"});s&&!ke?.[s]&&(ke[s]=new qt({breakWhenError:false,batchSize:1}));let f={stop:null,aborted:false,queue:s};de[t]=f;let d=null,p=()=>{de[t]===f&&delete de[t];},g=()=>new Promise((y,w)=>{let _=false;if(f.aborted){p(),y(Gt(t));return}let A={seq:0},U=ja.call(this,t),S=c&&u?Ka(A,c,U.onTransport):null,F=S?Ha.call(this,u,S):null,O=()=>{U.done(S),F&&F.stop(),S&&S.close();};d=O;let k=0,x=false,C=0,L=typeof o=="number"&&o>0?o:void 0,B=async()=>{if(!(_||x)&&!(S&&S.warm()&&Date.now()-k<$a)){x=true;try{for(;;){let ie={id:t,service:r,owner:n};c&&(ie.since=A.seq),k=Date.now();let M=await T.bind(this)("csr-poll",ie,{auth:e});if(_)return;let Q=S?S.fromPoll(M):c?Ba(M,A,c):!1;S&&S.open();let Yt=Wa(M);if(typeof M?.executed=="number"&&M.executed>0&&(L=M.executed),M?.more&&Q){C=0;continue}if(Yt){C=0;return}if(C=M?.more?C+1:0,M?.more&&C<Va)return;_=!0,a&&a(M,L!==void 0?{executed:L}:void 0),clearInterval(ee),O(),p(),y(M);return}}catch(ie){if(_)return;_=true,l&&l(ie),clearInterval(ee),O(),p(),w(ie);}finally{x=false;}}},ee=setInterval(B,i);S&&B(),f.stop=()=>{_||(_=true,clearInterval(ee),O(),p(),y(Gt(t)));};}),m=()=>{let y=de[t];y&&(y.stop?y.stop():(y.aborted=true,delete de[t]));};if(s){let y=new Promise((w,_)=>{let A=false,U=ke[s].add([async()=>{try{let S=await g();return A||(A=!0,w(S)),S}catch(S){throw A||(A=true,_(S)),S}}])[0];Wt[t]=U,f.stop=()=>{if(!A){f.aborted=true,d&&d();try{ke[s]&&ke[s].remove(Wt[t]);}catch{}delete Wt[t],p(),A=true,w(Gt(t));}};});return Object.assign(y,{stop:m})}else return Object.assign(g(),{stop:m})}function Ya(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 de)de[n]?.queue===t.queue&&r.push(n);else for(let n in de)r.push(n);for(let n of r){let i=de[n];i&&(i.stop?i.stop():(i.aborted=true,delete de[n]),e+=1);}return e}function za(t,e){if(!t.queue)throw new h('"queue" is required.',{code:"INVALID_PARAMETER"});let r={service:t.service||this.service,owner:t.owner||this.owner,queue:t.queue+":"};return T.bind(this)("csr-poll",r,{auth:true})}async function Qa(t){let e=false;if(typeof t.poll=="number"&&t.poll<0)throw new h('"poll" should be a non-negative number.',{code:"INVALID_PARAMETER"});let r=t?.onResponse,n=t?.onError,i=t?.onStream,s=typeof t.poll=="number"?t.poll:t.poll?1e3:0;delete t.poll,(s||t.stream)&&!t.queue&&(t.queue=(this.__user?.user_id||"anonymous")+"-"+Ye());let o=c=>{for(let u in c)if(typeof c[u]=="string"&&c[u].includes("$CLIENT_SECRET")){e=true;break}};if(t=b.Params(t,{url:c=>{if(!c||typeof c!="string")throw new h('"url" should be type: <string>.',{code:"INVALID_PARAMETER"});return b.Url(c),c.includes("$CLIENT_SECRET")&&(e=true),c},clientSecretName:"string",method:c=>{if(c&&typeof c!="string")throw new h('"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 h('"method" should be either "GET" or "POST" or "DELETE" or "PUT".',{code:"INVALID_PARAMETER"});return u},stream:c=>{if(c!=null&&typeof c!="boolean")throw new h('"stream" should be type: <boolean>.',{code:"INVALID_PARAMETER"});return !!c},realtime:c=>{if(c!=null&&typeof c!="boolean")throw new h('"realtime" should be type: <boolean>.',{code:"INVALID_PARAMETER"});return !!c},headers:c=>{if(c&&typeof c!="object")throw new h('"headers" should be type: <object>.',{code:"INVALID_PARAMETER"});return o(c),c},data:c=>{if(c&&typeof c!="object")throw new h('"data" should be type: <object>.',{code:"INVALID_PARAMETER"});return o(c),c},params:c=>{if(c&&typeof c!="object")throw new h('"params" should be type: <object>.',{code:"INVALID_PARAMETER"});return o(c),c},expires:"number",queue:"string"},["clientSecretName","method","url"]),t.realtime&&!t.stream)throw new h('"realtime" requires "stream": true.',{code:"INVALID_PARAMETER"});if(!e)throw new h(`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 a=!!this.__user,l=()=>T.bind(this)("csr",t,{auth:a,tokenHeaders:{accessToken:!!a}}).then(c=>{if(c.status==="running"||c.status==="pending"){let u=`[${t.method.toUpperCase()}]${t.url.toLowerCase()}`,f=t.service||this.service,d=t.owner||this.owner,p=`${u}#${f}:${c.id}`;Object.assign(c,{poll:g=>Ja.call(this,{id:p,auth:a,service:f,owner:d,latency:g?.latency||1e3,queue:t?.queue,onResponse:r,onError:n,onStream:g?.onStream||i,realtimeGroup:c?.realtime_group})});}return r?r(c):c}).catch(c=>{if(n)return n(c);throw c});if(t?.queue){let c="base:"+t.queue;return ke?.[c]||(ke[c]=new qt({breakWhenError:false,batchSize:1})),new Promise((u,f)=>{ke[c].add([async()=>{try{let d=await l();if(s>0){let p=d.poll({latency:s});return u(p),p}return u(d),d}catch(d){throw f(d),d}}]);})}else return l()}async function Xa(t,e){await this.__connection;let r=t.service||this.service,n=t.owner||this.owner;t=b.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(l=>{o[l]||delete o[l];}),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(l=>{let c={id:l.id,status_code:l.rslv?.status_code||null,response_body:l.rslv?.body||l.rslv?.truncated||null,error:l?.err,created:l?.stmp,updated:l?.utmp,executed:typeof l?.att=="number"?l.att*1e3:void 0,request_body:l?.reqbdy,expires:l?.expt,status:l.stts,queue_name:l?.qid,request_text:l?.reqtxt,response_text:l?.rslvtxt,response_complete_marker:l?.rslvmk!=null?!!l.rslvmk:void 0,compact:l?.cmpct?true:void 0};for(let u in c)c[u]===void 0&&delete c[u];return (c.status==="running"||c.status==="pending")&&(c.poll=u=>Ja.call(this,{id:s+c.id,auth:i,service:r,owner:n,latency:u?.latency||1e3,queue:l?.qid,seedExecuted:c.executed,onResponse:u?.onResponse,onError:u?.onError,onStream:u?.onStream})),c}),a}async function Za(t){await this.__connection,t=b.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&&ke?.[a]&&(ke[a].remove(Wt[o]),delete Wt[o]),T.bind(this)("csr-cancel",{id:o,service:e,owner:r},{auth:n})}function ec(t,e){let r=typeof e?.poll=="number"?e.poll:1e3;if(!Number.isFinite(r)||r<0)throw new h('"poll" should be a non-negative number.',{code:"INVALID_PARAMETER"});if(!t||typeof t!="string")throw new h('"requestId" should be type: <string>.',{code:"INVALID_PARAMETER"});if(e?.since!==void 0&&typeof e.since!="number")throw new h('"since" should be a number.',{code:"INVALID_PARAMETER"});if(e?.realtimeGroup!==void 0&&e.realtimeGroup!==null&&typeof e.realtimeGroup!="string")throw new h('"realtimeGroup" should be type: <string>.',{code:"INVALID_PARAMETER"});let n=typeof e?.since=="number"&&e.since>0?e.since:0,i=e?.onStream,s=e?.onResponse,o=e?.onError,a={stopped:false,fullId:t,resolve:null},l=null,c={stop:null,aborted:false},u=()=>{de[a.fullId]===c&&delete de[a.fullId];},f=()=>{a.stopped||(a.stopped=true,l&&l(),u(),a.resolve&&a.resolve(Gt(a.fullId)));};c.stop=f;let d=new Promise(async(p,g)=>{a.resolve=p;try{await this.__connection;let m=!!this.__user,y=e?.service||this.service,w=e?.owner||this.owner;if(a.fullId=Ga(t,e?.url,e?.method,y),a.stopped){p(Gt(a.fullId));return}de[a.fullId]=c;let _={seq:n},A=0,U=ja.call(this,a.fullId),S=i&&e?.realtimeGroup?Ka(_,i,U.onTransport):null,F=S?Ha.call(this,e.realtimeGroup,S):null,O=()=>{U.done(S),F&&F.stop(),S&&S.close();};for(l=O;;){let k=await T.bind(this)("csr-poll",{id:a.fullId,service:y,owner:w,since:_.seq},{auth:m});if(a.stopped)return;if(!Mf(k)){O(),u(),s&&s(k),p(k);return}let x=S?S.fromPoll(k):Ba(k,_,i);S&&S.open();let C=Wa(k);if(k.more&&x){A=0;continue}if(A=k.more?A+1:0,!C&&(!k.more||A>=Va)){O(),u(),s&&s(k),p(k);return}if(await new Promise(L=>setTimeout(L,S&&S.warm()?Math.max(r,$a):r)),a.stopped)return}}catch(m){if(a.stopped)return;l&&l(),u(),o&&o(m),g(m);}});return Object.assign(d,{stop:f})}async function tc(t,e,r){await this.__connection;let n=r?.service||this.service,i=r?.owner||this.owner,s=!!this.__user,o=Ga(t,r?.url,r?.method,n);return T.bind(this)("csr-finalize",{id:o,data:e,service:n,owner:i},{auth:s})}async function rc(t){await this.__connection;let e={name:"string",email:r=>(b.Email(r),r),subject:"string",message:"string"};return t=b.Params(t,e,["name","email","subject","message"]),await T.bind(this)("send-inquiry",t),"SUCCESS: Inquiry has been sent."}async function nc(t,e){if(await this.__connection,Fa&&t instanceof FormData||La&&t instanceof HTMLFormElement||Ma&&t instanceof SubmitEvent){if(!e)throw new h("Url string as a second argument is required when form is passed.",{code:"INVALID_PARAMETER"});let n=j(t);t={url:e,data:n.data,sync:true};}let r={url:n=>b.Url(n),data:n=>n,sync:["boolean",()=>true]};if(Array.isArray(t))for(let n of t)n=b.Params(n,r);else t=b.Params(t,r);return T.bind(this)("post-secure",t,{auth:true})}async function ic(t,e){await this.__connection;let{auth:r=false,method:n="POST",bypassAwaitConnection:i=false,responseType:s,contentType:o,tokenHeaders:a,progress:l}=e||{};if(e=Object.assign({auth:r,method:n,bypassAwaitConnection:i,responseType:s,contentType:o,tokenHeaders:a},{fetchOptions:{progress:l}}),typeof t!="object"&&(o==="application/json"||o===void 0))throw new h('"data" should be type: <object>.',{code:"INVALID_PARAMETER"});return T.bind(this)("mock",t,e)}async function sc(t,e){if(await this.__connection,!e?.url||typeof e.url!="string")throw new h('"url" is required in the second argument.',{code:"INVALID_PARAMETER"});b.Url(e.url);let n=(await this.admin_endpoint)?.forward_request;if(!n)throw new h("forwardRequest is not available on this service region yet.",{code:"NOT_EXISTS"});let i=null,s=null,o=Ma&&t instanceof SubmitEvent?t.target:La&&t instanceof HTMLFormElement?t:null;o?i=new FormData(o):Fa&&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}},l=JSON.stringify(a).replace(/[\u007f-\uffff]/g,p=>"\\u"+p.charCodeAt(0).toString(16).padStart(4,"0"));if(l.length>4096)throw new h("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 h("User login is required.",{code:"INVALID_REQUEST"});let u={"Content-Meta":l,Authorization:c};s&&(u["Content-Type"]=s);let f=await fetch(n,{method:"POST",headers:u,body:i,signal:e.signal});if(e.responseType==="response")return f;if(!f.ok){let p=await f.text();try{p=JSON.parse(p);}catch{}throw new h(p?.message||(typeof p=="string"?p:JSON.stringify(p)),{code:p?.code||"ERROR"})}if(e.onStream&&f.body){let p=f.body.getReader(),g=new TextDecoder,m="";for(;;){let{done:y,value:w}=await p.read();if(y)break;let _=g.decode(w,{stream:true});m+=_;try{e.onStream(_);}catch(A){console.error(A);}}return m}let d=await f.text();if(e.responseType==="text")return d;try{return JSON.parse(d)}catch{return d}}async function oc(t,e){await this.__connection,t=b.Params(t||{},{access_group:n=>{if(n==="authorized"&&(n=1),n==="public"&&(n=0),typeof n!="number")throw new h('"access_group" should be type number.',{code:"INVALID_PARAMETER"});if(n<0)throw new h('"access_group" should be zero or a positive number.',{code:"INVALID_PARAMETER"});if(n>this.__user.access_group)throw new h("User has no access.",{code:"INVALID_REQUEST"});return n}});let r=await T.bind(this)("get-feed",t,{auth:true,fetchOptions:e});for(let n in r.list)r.list[n]=await Ze.bind(this)(r.list[n]);return r}function Jt(t){if(t===this.__user.user_id)throw new h(`"user_id" cannot be the user's own ID.`,{code:"INVALID_PARAMETER"});return b.UserId(t,'"user_id"')}async function ac(t,e){if(t=j(t,{ignoreEmpty:true}).data,t=b.Params(t,{subscriber:n=>b.UserId(n,'User ID in "subscriber"'),subscription:Jt.bind(this),blocked:"boolean"}),!t.subscriber&&!t.subscription)throw new h('At least either "subscriber" or "subscription" should have a value.',{code:"INVALID_PARAMETER"});let r=await T.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 cc(t){await this.__connection,t=b.Params(t,{user_id:Jt.bind(this),get_feed:["boolean",()=>false],get_notified:["boolean",()=>false],get_email:n=>{if(n&&!this.__user.email||!this.__user.email_verified)throw new h("User has no verified email address.",{code:"INVALID_REQUEST"});return !!n}},["user_id"]);let e=await T.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 lc(t){await this.__connection;let{user_id:e}=b.Params(t,{user_id:Jt.bind(this)},["user_id"]);return await T.bind(this)("subscription",{unsubscribe:e},{auth:true})}async function uc(t){await this.__connection;let{user_id:e}=b.Params(t,{user_id:Jt.bind(this)},["user_id"]);return await T.bind(this)("subscription",{block:e},{auth:true})}async function dc(t){await this.__connection;let{user_id:e}=b.Params(t,{user_id:Jt.bind(this)},["user_id"]);return await T.bind(this)("subscription",{unblock:e},{auth:true})}async function fc(t,e){await this.__connection;let r=await Z.bind(this)();t=b.Params(t||{},{user_id:o=>{if(o!==this.__user.user_id&&!r)throw new h("No access.",{code:"INVALID_REQUEST"});return o},group:o=>b.newsletterGroup(o,{allowNull:true})});let n=await T.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("#"),l=true;a[0].charAt(0)==="@"&&(l=false,a[0]=a[0].substring(1));let c=/^\d+$/.test(a[0])?parseInt(a[0]):a[0];s.push({timestamp:o.stmp,group:c,subscribed_email:a[1],active:l});}return n?.list?(n.list=s,n):s}async function hc(t){await this.__connection;let e=b.Params(t||{},{email:r=>Array.isArray(r)&&r.length>0?r.length===1?b.Email(r[0]):r.map(n=>b.Email(n)):b.Email(r),group:r=>b.newsletterGroup(r),redirect:r=>b.Url(r)},this.__user?["group"]:["email","group"]);return T.bind(this)(`subscribe-${this.__user?"":"public-"}newsletter`,e,{auth:!!this.__user})}async function pc(t){await this.__connection;let e=b.Params(t||{},{group:r=>b.newsletterGroup(r,{nameOnly:true}),restriction:r=>{if(typeof r!="number"||!Number.isInteger(r)||r<0||r>99)throw new h('"restriction" should be a number between 0 and 99.',{code:"INVALID_PARAMETER"});return r},name:r=>{if(typeof r!="string"||r.length>60)throw new h('"name" should be a string of 60 characters or less.',{code:"INVALID_PARAMETER"});return r}},["group"]);return T.bind(this)("register-newsletter-group",e,{auth:true})}async function gc(t){await this.__connection;let e=b.Params(t||{},{group:r=>b.newsletterGroup(r,{nameOnly:true})},["group"]);return T.bind(this)("delete-newsletter-group",e,{auth:true})}async function mc(){return await this.__connection,T.bind(this)("newsletter-group-endpoint",null,{auth:true})}async function yc(t){await this.__connection,t=b.Params(t,{group:r=>b.newsletterGroup(r,{allowNull:true})},["group"]);let e=Object.assign({action:"unsubscribe"},t);return T.bind(this)("subscribe-newsletter",e,{auth:true})}async function _c(t,e){let r=await Z.bind(this)(),n={message_id:"string",timestamp:"number",read:"number",complaint:"number",subject:"string",bounced:"number"};t||(e=Object.assign({ascending:false},e||{})),t=j(t).data,t=t||{searchFor:"timestamp",value:Date.now(),condition:"<",group:"public"},t=b.Params(t,{searchFor:["message_id","timestamp","subject","complaint","read","bounced"],value:l=>{if(typeof l!==n[t.searchFor])throw new h(`"value" type does not match the type of "${t.searchFor}" index.`,{code:"INVALID_PARAMETER"});if(typeof l=="string"&&!l)throw new h('"value" should not be empty string.',{code:"INVALID_PARAMETER"});return l},range:l=>{if(!t.hasOwnProperty("value")||typeof l!=typeof t.value)throw new h('"range" should match type of "value".',{code:"INVALID_PARAMETER"});return l},condition:[">",">=","=","<","<=","gt","gte","eq","lt","lte",()=>"="],group:l=>{let c=b.newsletterGroup(l);if(c===0)return 0;if(typeof c=="string")return c;if(!this.session)throw new h("User should be logged in.",{code:"INVALID_REQUEST"});if(l==="authorized")return 1;if(!r&&c>parseInt(this.user?.access_group||this.session?.idToken?.payload?.access_group))throw new h("User has no access.",{code:"INVALID_REQUEST"});return c}},["searchFor","value","group"]);let i=t.group===0||typeof t.group=="string"&&!this.__user?"get-public-newsletters":"get-newsletters",s=await T.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",group:"grp"},a={message_id:"",timestamp:0,complaint:0,read:0,subject:"",bounced:"",url:"",delivered:0,group:t.group};return s.list=s.list.map(l=>{let c={};for(let u in o)c[u]=l[o[u]]||a[u];return c.bounced=String(c.bounced),c}),s}async function bc(t){let e=b.Params(t,{user_id:n=>b.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 Z.bind(this)()){if(!this.__user)throw new h("User needs to login.",{code:"INVALID_REQUEST"});if(this.__user.access_group<90)throw new h("Invalid access.",{code:"INVALID_REQUEST"})}return await T.bind(this)("block-account",e,{auth:true})}async function wc(t){let e=b.Params(t,{user_id:n=>b.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 Z.bind(this)()){if(!this.__user)throw new h("User needs to login.",{code:"INVALID_REQUEST"});if(this.__user.access_group<90)throw new h("Invalid access.",{code:"INVALID_REQUEST"})}return await T.bind(this)("block-account",e,{auth:true})}async function Ec(t){let e=b.Params(t,{user_id:n=>b.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 Z.bind(this)()){if(!this.__user)throw new h("User needs to login.",{code:"INVALID_REQUEST"});if(this.__user.access_group<90)throw new h("Invalid access.",{code:"INVALID_REQUEST"})}return await T.bind(this)("remove-account",e,{auth:true})}async function Ac(t,e){let r={email:s=>b.Email(s),password:s=>b.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=>b.Birthdate(s),phone_number:s=>b.PhoneNumber(s),picture:s=>{if(s)return b.Url(s)},profile:s=>{if(s)return b.Url(s)},website:s=>{if(s)return b.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 h('"access_group" is invalid. Should be type <number>.',{code:"INVALID_PARAMETER"})}if(typeof s!="number"||s<1||s>100)throw new h('"access_group" is invalid. Should be type <number> of range 1~99',{code:"INVALID_PARAMETER"});return s}},n=b.Params(t,r,["email"]);if(e=b.Params(e,{confirmation_url:s=>{let o=s;if(typeof s=="string")o=b.Url(s);else throw new h('"options.confirmation_url" should be type: <string>.',{code:"INVALID_PARAMETER"});if(o&&!n.email)throw new h('"email" is required for signup confirmation.',{code:"INVALID_PARAMETER"});return o},email_subscription:s=>{if(typeof s!="boolean")throw new h('"options.email_subscription" should be type: <boolean>.',{code:"INVALID_PARAMETER"});if(!e?.confirmation_url)throw new h('"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 h('"options.template" should be type: <object> with "url" and "subject".',{code:"INVALID_PARAMETER"});return {url:b.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 Z.bind(this)()){if(!this.__user)throw new h("User needs to login.",{code:"INVALID_REQUEST"});if(this.__user.access_group<90)throw new h("Invalid access.",{code:"INVALID_REQUEST"})}return await T.bind(this)("admin-signup",n,{auth:true})}async function Sc(t){let e={email:s=>b.Email(s),password:s=>b.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=>b.Birthdate(s),phone_number:s=>b.PhoneNumber(s),picture:s=>s?b.Url(s):"",profile:s=>s?b.Url(s):"",website:s=>s?b.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 h('"access_group" is invalid. Should be type <number>.',{code:"INVALID_PARAMETER"})}if(typeof s!="number"||s<1||s>100)throw new h('"access_group" is invalid. Should be type <number> of range 1~99',{code:"INVALID_PARAMETER"});return s}},r=["email","password"],n=b.Params(t,e,r);if(!await Z.bind(this)()){if(!this.__user)throw new h("User needs to login.",{code:"INVALID_REQUEST"});if(this.__user.access_group<90)throw new h("Invalid access.",{code:"INVALID_REQUEST"})}return await T.bind(this)("admin-signup",n,{auth:true})}async function vc(t){if(t=b.Params(t,{user_id:r=>b.UserId(r,'"user_id"'),access_group:r=>{try{typeof r=="string"&&(r=parseInt(r));}catch{throw new h('"access_group" is invalid. Should be type <number>.',{code:"INVALID_PARAMETER"})}if(typeof r=="number"&&r>0&&r<100)return r;throw new h('"access_group" is invalid. Should be type <number> of range 1~99',{code:"INVALID_PARAMETER"})}},["user_id","access_group"]),!await Z.bind(this)()){if(!this.__user)throw new h("User needs to login.",{code:"INVALID_REQUEST"});if(this.__user.access_group<90)throw new h("Invalid access.",{code:"INVALID_REQUEST"})}return await T.bind(this)("grant-access",t,{auth:true})}async function Rc(t,e){if(t=b.Params(t,{email:"string"}),!await Z.bind(this)()){if(!this.__user)throw new h("User needs to login.",{code:"INVALID_REQUEST"});if(this.__user.access_group<90)throw new h("Invalid access.",{code:"INVALID_REQUEST"})}let n=await T.bind(this)("invitation-list",Object.assign({mode:"search"},t),{fetchOptions:e,auth:true});return n.list=n.list.map(i=>Tt(i.user)),n}async function Tc(t){if(t=b.Params(t,{email:r=>b.Email(r)},["email"]),!await Z.bind(this)()){if(!this.__user)throw new h("User needs to login.",{code:"INVALID_REQUEST"});if(this.__user.access_group<90)throw new h("Invalid access.",{code:"INVALID_REQUEST"})}return await T.bind(this)("invitation-list",Object.assign({mode:"cancel"},t),{auth:true})}async function Ic(t){if(t=b.Params(t,{email:r=>b.Email(r)},["email"]),!await Z.bind(this)()){if(!this.__user)throw new h("User needs to login.",{code:"INVALID_REQUEST"});if(this.__user.access_group<90)throw new h("Invalid access.",{code:"INVALID_REQUEST"})}return await T.bind(this)("invitation-list",Object.assign({mode:"resend"},t),{auth:true})}async function Pc(t){let e=b.Params(t,{user_id:o=>b.UserId(o,'"user_id"'),email:o=>b.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?b.Birthdate(o):"",phone_number:o=>o?b.PhoneNumber(o):"",email_public:"boolean",phone_number_public:"boolean",address_public:"boolean",gender_public:"boolean",birthdate_public:"boolean",misc:"string",picture:o=>o?b.Url(o):"",profile:o=>o?b.Url(o):"",nickname:"string",website:o=>o?b.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 h("At least one attribute to update is required.",{code:"INVALID_PARAMETER"});if(!await Z.bind(this)()){if(!this.__user)throw new h("User needs to login.",{code:"INVALID_REQUEST"});if(this.__user.access_group<90)throw new h("Invalid access.",{code:"INVALID_REQUEST"})}e.email&&(e.preferred_username=(r||this.service)+"-"+X.hash(e.email));let s={attributes:e};return r&&n&&(s.service=r,s.owner=n),await T.bind(this)("admin-edit-profile",s,{auth:true})}async function Uc(t){if(typeof window>"u"||window._runningInNodeJS)throw new h("Push Notifications are not supported in Node.js environment.",{code:"NOT_SUPPORTED"});if(await this.__connection,!t.endpoint)throw new h("Missing parameter: endpoint",{code:"INVALID_PARAMETER"});if(!t.keys||!t.keys.p256dh||!t.keys.auth)throw new h("Missing parameter: keys.p256dh or keys.auth",{code:"INVALID_PARAMETER"});return await T.bind(this)("store-subscription",{endpoint:t.endpoint,keys:t.keys},{auth:true}),"SUCCESS: Subscribed to receive notifications."}async function xc(t){if(typeof window>"u"||window._runningInNodeJS)throw new h("Push Notifications are not supported in Node.js environment.",{code:"NOT_SUPPORTED"});if(await this.__connection,!t.endpoint)throw new h("Missing parameter: endpoint",{code:"INVALID_PARAMETER"});if(!t.keys||!t.keys.p256dh||!t.keys.auth)throw new h("Missing parameter: keys.p256dh or keys.auth",{code:"INVALID_PARAMETER"});return await T.bind(this)("delete-subscription",{endpoint:t.endpoint,keys:t.keys},{auth:true}),"SUCCESS: Unsubscribed from notifications."}async function Cc(){if(typeof window>"u"||window._runningInNodeJS)throw new h("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 kc(t,e){if(typeof window>"u"||window._runningInNodeJS)throw new h("Push Notifications are not supported in Node.js environment.",{code:"NOT_SUPPORTED"});await this.__connection;let{title:r,body:n}=j(t||{},{nullIfEmpty:true}).data;if(!r)throw new h("Missing parameter: message title",{code:"INVALID_PARAMETER"});if(!n)throw new h("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 T.bind(this)("push-notification",i,{auth:true}),"SUCCESS: Notification sent."}async function Dc(t){await this.__connection,t=b.Params(t,{spell:"string",name:"string",magic:r=>r},["spell","name"]);await T.bind(this)("castspell",t);return `The spell "${t.spell}" has been cast.`}async function Nc(t){return await this.__connection,t=b.Params(t||{},{search:["spell","name",()=>"spell"],value:"string"}),await T.bind(this)("getspell",t)}async function Oc(t){await this.__connection,t=b.Params(t,{message:"string",name:"string"},["message","name"]);let e=await T.bind(this)("dopamine",t,{auth:true}),r=e?.previous_message?.message,n=e?.previous_message?.name;if(ae())r&&n&&window.alert(`${n} said: ${r}`),window.location.href=e.video;else return r&&n?`${n} said: ${r}
|
|
216
|
+
`,l=new Blob([c],{type:"application/javascript"});Ge=new Worker(URL.createObjectURL(l)),Ge.onmessage=d=>{a.readyState===1&&a.send(JSON.stringify({action:"keepAlive"}));},i(a);},a.onmessage=async c=>{let l="";try{l=JSON.parse(decodeURI(c.data)),this.log("socket onmessage",l);}catch{return}let d;switch(!0){case !!l?.["#message"]:d="message";break;case !!l?.["#private"]:d="private";break;case !!l?.["#notice"]:d="notice";break;case !!l?.["#rtc"]:d="rtc";break;case !!l?.["#error"]:d="error";break}if(!d)return;let h={type:d,message:l?.["#rtc"]||l?.["#message"]||l?.["#private"]||l?.["#notice"]||l?.["#error"]||null,sender:l?.["#user_id"]||null,sender_cid:l?.["#scid"]?"cid:"+l["#scid"]:null,sender_rid:l?.["#srid"]||null,code:l?.["#code"]||null};if(d==="notice")t(h);else if(d==="rtc"){if(h.sender!==this.user.user_id){let u=h.message;if(u.hungup){Se[h.sender_cid]&&(Se[h.sender_cid](!1),delete Se[h.sender_cid]),Ue[h.sender_cid]&&delete Ue[h.sender_cid],O?.[h.sender_cid]&&Re.bind(this)({cid:h.sender_cid}),h.type="rtc:closed",t(h);return}if(u.candidate&&wi.bind(this)(u.candidate,h.sender_cid),u.sdpoffer&&(_i.bind(this)(u.sdpoffer,h.sender_cid),Ue[h.sender_cid]||(Ue[h.sender_cid]=h.sender_cid,delete h.message,h.connectRTC=$a.bind(this)(h),h.type="rtc:incoming",h.hangup=(()=>{O[h.sender_cid]?Re.bind(this)({cid:h.sender_cid}):Ue[h.sender_cid]&&(delete Ue[h.sender_cid],a.send(JSON.stringify({action:"rtc",uid:h.sender_cid,content:{hungup:this.user.user_id},token:this.session.accessToken.jwtToken})));}).bind(this),t(h))),u.pickup&&Se[h.sender_cid]&&(Se[h.sender_cid](!0),delete Se[h.sender_cid]),u.sdpanswer&&O[h.sender_cid])if(O[h.sender_cid].signalingState==="have-local-offer")await O[h.sender_cid].setRemoteDescription(new RTCSessionDescription(u.sdpanswer));else throw new f("Invalid signaling state.",{code:"INVALID_REQUEST"})}}else t(h);},a.onclose=()=>{Gt?(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."}),Et++,Et<3?(this.log("realtime onclose","Reconnecting to WebSocket server..."+Et),t({type:"reconnect",message:"Reconnecting to WebSocket server..."+Et}),At.bind(this)(t,3e3,"reconnect")):(this.log("realtime onclose","Max reconnection attempts reached."),t({type:"error",message:"Skapi: Max reconnection attempts reached."})));},a.onerror=()=>{this.log("realtime onerror","WebSocket connection error."),t({type:"error",message:"Skapi: WebSocket connection error."});};}catch(a){o(a);}},e);}),n.value=this.__socket,this.__socket}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 yt.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}),Ve!==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 St(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 yt.bind(this)(),t=K(t,{nullIfEmpty:true}).data;let{group:r=null}=t;if(!r&&!Ve)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.readyState===1&&e.send(JSON.stringify({action:"joinRoom",rid:r,token:this.session.accessToken.jwtToken})),Ve=r,{type:"success",message:r?`Joined realtime message group: "${r}".`:"Left realtime message group."}}async function Wa(t,e){t=_.Params(t,{user_id:n=>_.UserId(n,'User ID in "user_id"'),group:["string",()=>{if(!Ve)throw new f('No group has been joined. Otherwise "group" is required.',{code:"INVALID_REQUEST"});return Ve}]});let r=await C.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 za(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 C.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 Zf=typeof FormData<"u",Ya=typeof HTMLFormElement<"u",Qa=typeof SubmitEvent<"u",ke={},Wt={},de={};function zt(t){return Object.freeze({id:t,status:"stopped"})}function Si(t){return !!t&&typeof t=="object"&&t.status==="stopped"}var Xa=3;function Za(t,e,r){let n=false,i=Array.isArray(t?.chunks)?t.chunks.slice():[];i.sort((s,o)=>(s?.seq||0)-(o?.seq||0));for(let s of i)if(!(!s||typeof s.seq!="number"||s.seq<=e.seq)&&(e.seq=s.seq,n=true,r&&typeof s.txt=="string"&&s.txt!==""))try{r(s.txt,s.seq,"poll");}catch(o){console.error(o);}return typeof t?.last_seq=="number"&&t.last_seq>e.seq&&(e.seq=t.last_seq,n=true),n}var eh=2e3,ec=5e3,th=2e3,rh=5,nh=1500,Kr=null;function tc(t,e,r){let n=new Map,i=false,s=false,o=0,a={socket:0,poll:0},c=(u,p,g)=>{if(t.seq=u,!(!e||typeof p!="string"||p===""))try{e(p,u,g);}catch(m){console.error(m);}},l=()=>{for(let u of Array.from(n.keys()))u<=t.seq&&n.delete(u);for(;;){let u=t.seq+1;if(!n.has(u))break;let p=n.get(u);n.delete(u),c(u,p.txt,p.via);}};return {cursor:t,open:()=>{i||s||(i=true,l());},fromPoll:u=>{if(s)return false;let p=t.seq,g=t.seq,m=Array.isArray(u?.chunks)?u.chunks:[];for(let b of m){if(!b||typeof b.seq!="number"||b.seq<=t.seq)continue;let w=!n.has(b.seq);w&&(a.poll++,r&&a.poll===1&&r("poll",b.seq)),n.set(b.seq,{txt:typeof b.txt=="string"?b.txt:"",via:w?"poll":n.get(b.seq).via}),b.seq>g&&(g=b.seq);}typeof u?.last_seq=="number"&&u.last_seq>g&&(g=u.last_seq);let y=Array.from(n.keys()).sort((b,w)=>b-w);for(let b of y){if(b<=t.seq){n.delete(b);continue}if(b>g)break;let w=n.get(b);n.delete(b),c(b,w.txt,w.via);}return g>t.seq&&(t.seq=g),l(),t.seq>p},fromSocket:(u,p)=>{s||typeof u!="number"||!Number.isFinite(u)||(o=Date.now(),!(u<=t.seq)&&(!n.has(u)&&n.size>=th||(n.has(u)||(a.socket++,r&&a.socket===1&&r("socket",u)),n.set(u,{txt:typeof p=="string"?p:"",via:n.has(u)?n.get(u).via:"socket"}),i&&l())));},warm:()=>o!==0&&Date.now()-o<eh,stats:()=>({socket:a.socket,poll:a.poll}),close:()=>{s=true,n.clear();}}}function rc(t){if(!this||!this.__network_logs)return {onTransport:void 0,done:()=>{}};let e=Date.now(),r=false;return {onTransport:(n,i)=>{console.log(`%cSKAPI: stream chunk arrived over ${n==="socket"?"WEBSOCKET":"POLL"}`,`color: ${n==="socket"?"green":"orange"};`,{id:t,first_seq:i,after_ms:Date.now()-e});},done:n=>{if(r||!n)return;r=true;let i=n.stats();console.log("%cSKAPI: stream transport","color: blue;",{id:t,over_websocket:i.socket,over_poll:i.poll,took_ms:Date.now()-e});}}}function nc(t,e){let r={stop:()=>{}};if(typeof window>"u"||window._runningInNodeJS||Kr)return r;let n={stopped:false,socket:null,opened:null,joined:false,attempts:0,unavailable:false};Kr=n;let i=l=>{if(n.stopped)return;let d=l?.data;if(typeof d!="string")return;let h=null;try{h=JSON.parse(d);}catch{try{h=JSON.parse(decodeURI(d));}catch{return}}let u=h?.["#message"];if(u==null)return;if(typeof u=="string")try{u=JSON.parse(u);}catch{return}if(typeof u!="object")return;let p=h?.["#srid"];if(typeof p=="string"&&p!==t)return;let g=u.seq;typeof g=="string"&&g!==""&&(g=Number(g)),e.fromSocket(g,u.txt);},s=()=>{if(n.socket){try{n.socket.removeEventListener("message",i);}catch{}try{n.socket.removeEventListener("close",a);}catch{}n.socket=null;}},o=async()=>{let l=n.opened,d=n.joined;if(n.opened=null,n.joined=false,s(),!(!d&&!l))try{let h=this.__socket?await this.__socket:null;if(l&&h===l){await jr.bind(this)();return}d&&h&&Ha()===room&&await St.bind(this)({group:null});}catch{}},a=()=>{n.stopped||(s(),!n.unavailable&&(n.attempts>=rh||(n.attempts+=1,setTimeout(()=>{n.stopped||c();},nh))));},c=async()=>{try{let l=this.__socket?await this.__socket:null;if(n.stopped){o();return}if(!l){if(!this.session){n.unavailable=!0,o();return}if(await At.bind(this)(()=>{},0),l=this.__socket?await this.__socket:null,n.stopped){o();return}l&&!n.opened&&(n.opened=l);}if(!l||l.readyState!==1)return;if(l.addEventListener("message",i),l.addEventListener("close",a),n.socket=l,!n.joined&&(await St.bind(this)({group:t}),n.joined=!0,n.stopped)){o();return}}catch{}};return c(),{stop:()=>{n.stopped||(n.stopped=true,Kr===n&&(Kr=null),o());}}}function ic(t){return t?.status==="running"||t?.status==="pending"}function sc(t){return !!t&&typeof t=="object"&&!Array.isArray(t)&&typeof t.status=="string"&&typeof t.id=="string"&&"in_queue"in t}function oc(t,e,r,n){if(!t||typeof t!="string")throw new f('"requestId" should be type: <string>.',{code:"INVALID_PARAMETER"});if(t.includes("#"))return t;if(!e||typeof e!="string"||!r||typeof r!="string")throw new f('"url" and "method" are required to address a request by its short id.',{code:"INVALID_PARAMETER"});return _.Url(e),`[${r.toUpperCase()}]${e.toLowerCase()}#${n}:${t}`}function ac({id:t,auth:e,service:r,owner:n,latency:i=1e3,queue:s,seedExecuted:o,onResponse:a,onError:c,onStream:l,realtimeGroup:d}){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&&!ke?.[s]&&(ke[s]=new Vt({breakWhenError:false,batchSize:1}));let h={stop:null,aborted:false,queue:s};de[t]=h;let u=null,p=()=>{de[t]===h&&delete de[t];},g=()=>new Promise((y,b)=>{let w=false;if(h.aborted){p(),y(zt(t));return}let E={seq:0},R=rc.call(this,t),S=l&&d?tc(E,l,R.onTransport):null,U=S?nc.call(this,d,S):null,k=()=>{R.done(S),U&&U.stop(),S&&S.close();};u=k;let N=0,x=false,D=0,L=typeof o=="number"&&o>0?o:void 0,B=async()=>{if(!(w||x)&&!(S&&S.warm()&&Date.now()-N<ec)){x=true;try{for(;;){let ne={id:t,service:r,owner:n};l&&(ne.since=E.seq),N=Date.now();let M=await C.bind(this)("csr-poll",ne,{auth:e});if(w)return;let Q=S?S.fromPoll(M):l?Za(M,E,l):!1;S&&S.open();let Yt=ic(M);if(typeof M?.executed=="number"&&M.executed>0&&(L=M.executed),M?.more&&Q){D=0;continue}if(Yt){D=0;return}if(D=M?.more?D+1:0,M?.more&&D<Xa)return;w=!0,a&&a(M,L!==void 0?{executed:L}:void 0),clearInterval(ee),k(),p(),y(M);return}}catch(ne){if(w)return;w=true,c&&c(ne),clearInterval(ee),k(),p(),b(ne);}finally{x=false;}}},ee=setInterval(B,i);S&&B(),h.stop=()=>{w||(w=true,clearInterval(ee),k(),p(),y(zt(t)));};}),m=()=>{let y=de[t];y&&(y.stop?y.stop():(y.aborted=true,delete de[t]));};if(s){let y=new Promise((b,w)=>{let E=false,R=ke[s].add([async()=>{try{let S=await g();return E||(E=!0,b(S)),S}catch(S){throw E||(E=true,w(S)),S}}])[0];Wt[t]=R,h.stop=()=>{if(!E){h.aborted=true,u&&u();try{ke[s]&&ke[s].remove(Wt[t]);}catch{}delete Wt[t],p(),E=true,b(zt(t));}};});return Object.assign(y,{stop:m})}else return Object.assign(g(),{stop:m})}function Gr(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 de)de[n]?.queue===t.queue&&r.push(n);else for(let n in de)r.push(n);for(let n of r){let i=de[n];i&&(i.stop?i.stop():(i.aborted=true,delete de[n]),e+=1);}return e}function Ri(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 C.bind(this)("csr-poll",r,{auth:true})}function ih(t){if(typeof Buffer<"u"&&typeof Buffer.from=="function")return Buffer.from(t).toString("base64");if(typeof btoa=="function"){let e="";for(let n=0;n<t.length;n+=32768)e+=String.fromCharCode.apply(null,Array.from(t.subarray(n,n+32768)));return btoa(e)}throw new f("No base64 encoder available in this environment.",{code:"NOT_SUPPORTED"})}var Ja=2*1024*1024-64*1024;function Hr(t){return typeof File<"u"&&t instanceof File||typeof Blob<"u"&&t instanceof Blob}function Ai(t){if(Array.isArray(t)){let e=[];for(let r of t)Hr(r)||e.push(Ai(r));return e}if(t&&typeof t=="object"&&!Hr(t)){let e=Object.getPrototypeOf(t);if(e!==Object.prototype&&e!==null)return t;let r={};for(let n in t)Hr(t[n])||(r[n]=Ai(t[n]));return r}return t}function sh(t){if(t==null)return null;let e=K(t)?.data;return !e||typeof e!="object"||Array.isArray(e)?null:Ai(e)}function cc(t,e,r){if(r!==void 0){if(Array.isArray(r)){for(let n of r)cc(t,e,n);return}if(Hr(r)){t.append(e,r);return}if(r===null){t.append(e,"");return}if(typeof r=="object"){t.append(e,JSON.stringify(r));return}t.append(e,String(r));}}async function oh(t){if(t==null)throw new f('"multipart": true needs a form body in the first argument.',{code:"INVALID_PARAMETER"});if(typeof FormData>"u"||typeof Response>"u")throw new f('"multipart": true is not available in this environment.',{code:"NOT_SUPPORTED"});let e;if(Qa&&t instanceof SubmitEvent)e=new FormData(t.target);else if(Ya&&t instanceof HTMLFormElement)e=new FormData(t);else if(t instanceof FormData)e=t;else if(typeof t=="object"&&!Array.isArray(t)){e=new FormData;for(let s in t)cc(e,s,t[s]);}else throw new f('"form" should be a submit event, a form element, FormData, or an object.',{code:"INVALID_PARAMETER"});let r=new Response(e),n=r.headers.get("content-type"),i=ih(new Uint8Array(await r.arrayBuffer()));if(i.length>Ja)throw new f(`Multipart body is too large: ${i.length} bytes once base64 encoded, and the limit is ${Ja}. Upload the file first and send its url instead.`,{code:"INVALID_PARAMETER"});return {body_b64:i,body_content_type:n}}function ah(t){if(t!=null){if(typeof t=="boolean")return t;if(typeof t=="object"&&!Array.isArray(t))return {user:!!t.user,service:!!t.service};throw new f('"skapiHeaders" should be type: <boolean> or { user?: boolean; service?: boolean }.',{code:"INVALID_PARAMETER"})}}function ch(t){if(!(!t||typeof t!="object")){for(let e in t)if(typeof e=="string"&&e.toLowerCase().indexOf("x-skapi-")===0)throw new f(`"headers" cannot set "${e}": the "x-skapi-" prefix is reserved. Use "skapiHeaders" to tell the destination who the caller is.`,{code:"INVALID_PARAMETER"})}}async function lc(t,e){let r=false,n=!!(t?.secretName||t?.clientSecretName),i=e?.signal;if(i?.aborted)throw new f('"signal" was already aborted.',{code:"INVALID_REQUEST"});if(typeof t.poll=="number"&&t.poll<0)throw new f('"poll" should be a non-negative number.',{code:"INVALID_PARAMETER"});let s=t?.onResponse,o=t?.onError,a=t?.onStream,c=typeof t.poll=="number"?t.poll:t.poll?1e3:0;delete t.poll,(c||t.stream)&&!t.queue&&(t.queue=(this.__user?.user_id||"anonymous")+"-"+Ye());let l=u=>{for(let p in u)if(typeof u[p]=="string"&&u[p].includes("$CLIENT_SECRET")){r=true;break}};if(t=_.Params(t,{url:u=>{if(!u||typeof u!="string")throw new f('"url" should be type: <string>.',{code:"INVALID_PARAMETER"});return _.Url(u),u.includes("$CLIENT_SECRET")&&(r=true),u},secretName:"string",clientSecretName:"string",method:u=>{if(u&&typeof u!="string")throw new f('"method" should be one of "GET", "POST", "PUT", "PATCH", "DELETE" or "HEAD".',{code:"INVALID_PARAMETER"});let p=u.toLowerCase();if(p!=="get"&&p!=="post"&&p!=="delete"&&p!=="put"&&p!=="patch"&&p!=="head")throw new f('"method" should be one of "GET", "POST", "PUT", "PATCH", "DELETE" or "HEAD".',{code:"INVALID_PARAMETER"});return p},stream:u=>{if(u!=null&&typeof u!="boolean")throw new f('"stream" should be type: <boolean>.',{code:"INVALID_PARAMETER"});return !!u},realtime:u=>{if(u!=null&&typeof u!="boolean")throw new f('"realtime" should be type: <boolean>.',{code:"INVALID_PARAMETER"});return !!u},headers:u=>{if(u&&typeof u!="object")throw new f('"headers" should be type: <object>.',{code:"INVALID_PARAMETER"});return ch(u),l(u),u},skapiHeaders:u=>ah(u),data:u=>{if(u&&typeof u!="object")throw new f('"data" should be type: <object>.',{code:"INVALID_PARAMETER"});return l(u),u},params:u=>{if(u&&typeof u!="object")throw new f('"params" should be type: <object>.',{code:"INVALID_PARAMETER"});return l(u),u},body_b64:"string",body_content_type:"string",expires:"number",queue:"string"},e?.requireSecretName?["clientSecretName","method","url"]:["method","url"]),t.realtime&&!t.stream)throw new f('"realtime" requires "stream": true.',{code:"INVALID_PARAMETER"});if(t.body_b64&&t.data)throw new f('"data" cannot be sent with "multipart": true.',{code:"INVALID_PARAMETER"});if(n&&!r){let u=t.method==="get"||t.method==="delete"||t.method==="head"?'"params"':'"data"';throw new f(`At least one parameter value should include "$CLIENT_SECRET" in ${u} or "headers".`,{code:"INVALID_PARAMETER"})}await this.__connection;let d=!!this.__user,h=()=>C.bind(this)("csr",t,{auth:d,tokenHeaders:{accessToken:!!d}}).then(u=>{if(u.status==="running"||u.status==="pending"){let p=`[${t.method.toUpperCase()}]${t.url.toLowerCase()}`,g=t.service||this.service,m=t.owner||this.owner,y=`${p}#${g}:${u.id}`;if(i){let b=()=>{Gr.call(this,{id:y});};i.aborted?b():i.addEventListener("abort",b,{once:true});}Object.assign(u,{poll:b=>ac.call(this,{id:y,auth:d,service:g,owner:m,latency:b?.latency||1e3,queue:t?.queue,onResponse:s,onError:o,onStream:b?.onStream||a,realtimeGroup:u?.realtime_group})});}return s?s(u):u}).catch(u=>{if(o)return o(u);throw u});if(t?.queue){let u="base:"+t.queue;return ke?.[u]||(ke[u]=new Vt({breakWhenError:false,batchSize:1})),new Promise((p,g)=>{ke[u].add([async()=>{try{let m=await h();if(c>0){let y=m.poll({latency:c});return i&&(i.aborted?y.stop():i.addEventListener("abort",()=>y.stop(),{once:!0})),p(y),y}return p(m),m}catch(m){throw g(m),m}}]);})}else return h()}async function uc(t,e){if(!e||typeof e!="object")throw new f('"options" is required in the second argument.',{code:"INVALID_PARAMETER"});if(e.apiKeyHeader!==void 0||e.apiKeyScheme!==void 0)throw new f('"apiKeyHeader" and "apiKeyScheme" are no longer supported. Store the key as a client secret, name it with "secretName", and put "$CLIENT_SECRET" where the key goes.',{code:"INVALID_PARAMETER"});if(e.multipart!==void 0&&e.multipart!==null&&typeof e.multipart!="boolean")throw new f('"multipart" should be type: <boolean>.',{code:"INVALID_PARAMETER"});let r=e.responseType;if(r!=null){if(r==="response")throw new f(`"responseType": "response" is not available here. The request is relayed from the server and what comes back is the stored answer, not a live Response; the destination's status code is the "status_code" of the row forwardRequestHistory lists.`,{code:"INVALID_PARAMETER"});if(r!=="json"&&r!=="text")throw new f('"responseType" should be either "json" or "text".',{code:"INVALID_PARAMETER"})}let n=e.method||"POST",i=typeof n=="string"?n.toLowerCase():"",s=i==="get"||i==="delete"||i==="head"?"params":"data",o={url:e.url,method:n};if(e.secretName!==void 0&&(o.secretName=e.secretName),e.headers!==void 0&&(o.headers=e.headers),e.data!==void 0&&(o.data=e.data),e.params!==void 0&&(o.params=e.params),e.skapiHeaders!==void 0&&(o.skapiHeaders=e.skapiHeaders),e.service!==void 0&&(o.service=e.service),e.owner!==void 0&&(o.owner=e.owner),e.queue!==void 0&&(o.queue=e.queue),e.expires!==void 0&&(o.expires=e.expires),e.stream!==void 0&&(o.stream=e.stream),e.realtime!==void 0&&(o.realtime=e.realtime),e.poll!==void 0&&(o.poll=e.poll),e.onStream!==void 0&&(o.onStream=e.onStream),e.onResponse!==void 0&&(o.onResponse=e.onResponse),e.onError!==void 0&&(o.onError=e.onError),e.multipart){if(e.data!==void 0&&e.data!==null)throw new f('"data" cannot be sent with "multipart": true. The form itself is the body.',{code:"INVALID_PARAMETER"});let c=await oh(t);o.body_b64=c.body_b64,o.body_content_type=c.body_content_type;}else {let c=sh(t);c&&Object.keys(c).length&&(o[s]=Object.assign({},c,o[s]||{}));}let a=lc.call(this,o,{signal:e.signal});return r?a.then(c=>{if(sc(c)||Si(c))return c;if(r==="text")return typeof c=="string"?c:JSON.stringify(c);if(typeof c=="string")try{return JSON.parse(c)}catch{return c}return c}):a}async function dc(t){return lc.call(this,t,{requireSecretName:true})}async function vi(t,e){await this.__connection;let r=t.service||this.service,n=t.owner||this.owner;t=_.Params(t,{url:"string",method:["GET","POST","PUT","PATCH","DELETE","HEAD"],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 C.bind(this)("csr-poll",o,{auth:i,fetchOptions:e});return a.list=a.list.map(c=>{let l={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,executed:typeof c?.att=="number"?c.att*1e3:void 0,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 d in l)l[d]===void 0&&delete l[d];return (l.status==="running"||l.status==="pending")&&(l.poll=d=>ac.call(this,{id:s+l.id,auth:i,service:r,owner:n,latency:d?.latency||1e3,queue:c?.qid,seedExecuted:l.executed,onResponse:d?.onResponse,onError:d?.onError,onStream:d?.onStream})),l}),a}async function Ti(t){await this.__connection,t=_.Params(t,{url:"string",method:["GET","POST","PUT","PATCH","DELETE","HEAD"],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&&ke?.[a]&&(ke[a].remove(Wt[o]),delete Wt[o]),C.bind(this)("csr-cancel",{id:o,service:e,owner:r},{auth:n})}function Ii(t,e){let r=typeof e?.poll=="number"?e.poll:1e3;if(!Number.isFinite(r)||r<0)throw new f('"poll" should be a non-negative number.',{code:"INVALID_PARAMETER"});if(!t||typeof t!="string")throw new f('"requestId" should be type: <string>.',{code:"INVALID_PARAMETER"});if(e?.since!==void 0&&typeof e.since!="number")throw new f('"since" should be a number.',{code:"INVALID_PARAMETER"});if(e?.realtimeGroup!==void 0&&e.realtimeGroup!==null&&typeof e.realtimeGroup!="string")throw new f('"realtimeGroup" should be type: <string>.',{code:"INVALID_PARAMETER"});let n=typeof e?.since=="number"&&e.since>0?e.since:0,i=e?.onStream,s=e?.onResponse,o=e?.onError,a={stopped:false,fullId:t,resolve:null},c=null,l={stop:null,aborted:false},d=()=>{de[a.fullId]===l&&delete de[a.fullId];},h=()=>{a.stopped||(a.stopped=true,c&&c(),d(),a.resolve&&a.resolve(zt(a.fullId)));};l.stop=h;let u=new Promise(async(p,g)=>{a.resolve=p;try{await this.__connection;let m=!!this.__user,y=e?.service||this.service,b=e?.owner||this.owner;if(a.fullId=oc(t,e?.url,e?.method,y),a.stopped){p(zt(a.fullId));return}de[a.fullId]=l;let w={seq:n},E=0,R=rc.call(this,a.fullId),S=i&&e?.realtimeGroup?tc(w,i,R.onTransport):null,U=S?nc.call(this,e.realtimeGroup,S):null,k=()=>{R.done(S),U&&U.stop(),S&&S.close();};for(c=k;;){let N=await C.bind(this)("csr-poll",{id:a.fullId,service:y,owner:b,since:w.seq},{auth:m});if(a.stopped)return;if(!sc(N)){k(),d(),s&&s(N),p(N);return}let x=S?S.fromPoll(N):Za(N,w,i);S&&S.open();let D=ic(N);if(N.more&&x){E=0;continue}if(E=N.more?E+1:0,!D&&(!N.more||E>=Xa)){k(),d(),s&&s(N),p(N);return}if(await new Promise(L=>setTimeout(L,S&&S.warm()?Math.max(r,ec):r)),a.stopped)return}}catch(m){if(a.stopped)return;c&&c(),d(),o&&o(m),g(m);}});return Object.assign(u,{stop:h})}async function Pi(t,e,r){await this.__connection;let n=r?.service||this.service,i=r?.owner||this.owner,s=!!this.__user,o=oc(t,r?.url,r?.method,n);return C.bind(this)("csr-finalize",{id:o,data:e,service:n,owner:i},{auth:s})}var fc=Ii,hc=Pi,pc=vi,gc=Ti,mc=Gr,yc=Ri;async function bc(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 C.bind(this)("send-inquiry",t),"SUCCESS: Inquiry has been sent."}async function _c(t,e){if(await this.__connection,Zf&&t instanceof FormData||Ya&&t instanceof HTMLFormElement||Qa&&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 C.bind(this)("post-secure",t,{auth:true})}async function wc(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 C.bind(this)("mock",t,e)}async function Ec(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 C.bind(this)("get-feed",t,{auth:true,fetchOptions:e});return Array.isArray(r?.list)&&(r.list=await Promise.all(r.list.map(n=>Ze.bind(this)(n)))),r}function Jt(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 Ac(t,e){if(t=K(t,{ignoreEmpty:true}).data,t=_.Params(t,{subscriber:n=>_.UserId(n,'User ID in "subscriber"'),subscription:Jt.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 C.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 Sc(t){await this.__connection,t=_.Params(t,{user_id:Jt.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 C.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 Rc(t){await this.__connection;let{user_id:e}=_.Params(t,{user_id:Jt.bind(this)},["user_id"]);return await C.bind(this)("subscription",{unsubscribe:e},{auth:true})}async function vc(t){await this.__connection;let{user_id:e}=_.Params(t,{user_id:Jt.bind(this)},["user_id"]);return await C.bind(this)("subscription",{block:e},{auth:true})}async function Tc(t){await this.__connection;let{user_id:e}=_.Params(t,{user_id:Jt.bind(this)},["user_id"]);return await C.bind(this)("subscription",{unblock:e},{auth:true})}async function Ic(t,e){await this.__connection;let r=await Z.bind(this)();if(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=>_.newsletterGroup(o,{allowNull:true}),email:o=>{if(typeof o!="string"||!o.trim())throw new f('"email" should be a non-empty string.',{code:"INVALID_PARAMETER"});if(o.trim().length>255)throw new f('"email" should be at most 255 characters.',{code:"INVALID_PARAMETER"});return o.trim().toLowerCase()}}),t.email!==void 0){if(t.user_id!==void 0&&t.user_id!==null)throw new f('"email" cannot be used with "user_id".',{code:"INVALID_PARAMETER"});if(t.group===void 0||t.group===null)throw new f('"group" is required to search by "email".',{code:"INVALID_PARAMETER"})}let n=await C.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 l=/^\d+$/.test(a[0])?parseInt(a[0]):a[0],d={timestamp:o.stmp,group:l,subscribed_email:a[1],active:c};typeof o.email_token=="string"&&o.email_token&&(d.subscriber_token=o.email_token),s.push(d);}return n?.list?(n.list=s,n):s}async function Pc(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:r=>_.newsletterGroup(r),redirect:r=>_.Url(r)},this.__user?["group"]:["email","group"]);return C.bind(this)(`subscribe-${this.__user?"":"public-"}newsletter`,e,{auth:!!this.__user})}async function Cc(t){await this.__connection;let e=_.Params(t||{},{group:r=>_.newsletterGroup(r,{nameOnly:true}),restriction:r=>{if(typeof r!="number"||!Number.isInteger(r)||r<0||r>99)throw new f('"restriction" should be a number between 0 and 99.',{code:"INVALID_PARAMETER"});return r},name:r=>{if(typeof r!="string"||r.length>60)throw new f('"name" should be a string of 60 characters or less.',{code:"INVALID_PARAMETER"});return r}},["group"]);return C.bind(this)("register-newsletter-group",e,{auth:true})}async function xc(t){await this.__connection;let e=_.Params(t||{},{group:r=>_.newsletterGroup(r,{nameOnly:true})},["group"]);return C.bind(this)("delete-newsletter-group",e,{auth:true})}async function Uc(){return await this.__connection,C.bind(this)("newsletter-group-endpoint",null,{auth:true})}async function kc(t){await this.__connection,t=_.Params(t,{group:r=>_.newsletterGroup(r,{allowNull:true})},["group"]);let e=Object.assign({action:"unsubscribe"},t);return C.bind(this)("subscribe-newsletter",e,{auth:true})}async function Dc(t,e){let r=await Z.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=>{let l=_.newsletterGroup(c);if(l===0)return 0;if(typeof l=="string")return l;if(!this.session)throw new f("User should be logged in.",{code:"INVALID_REQUEST"});if(c==="authorized")return 1;if(!r&&l>parseInt(this.user?.access_group||this.session?.idToken?.payload?.access_group))throw new f("User has no access.",{code:"INVALID_REQUEST"});return l}},["searchFor","value","group"]);let i=t.group===0||typeof t.group=="string"&&!this.__user?"get-public-newsletters":"get-newsletters",s=await C.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",group:"grp"},a={message_id:"",timestamp:0,complaint:0,read:0,subject:"",bounced:"",url:"",delivered:0,group:t.group};return s.list=s.list.map(c=>{let l={};for(let d in o)l[d]=c[o[d]]||a[d];return l.bounced=String(l.bounced),l}),s}async function Nc(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 Z.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 C.bind(this)("block-account",e,{auth:true})}async function Oc(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 Z.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 C.bind(this)("block-account",e,{auth:true})}async function Fc(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 Z.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 C.bind(this)("remove-account",e,{auth:true})}async function Lc(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 Z.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 C.bind(this)("admin-signup",n,{auth:true})}async function Mc(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 Z.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 C.bind(this)("admin-signup",n,{auth:true})}async function qc(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 Z.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 C.bind(this)("grant-access",t,{auth:true})}async function Vc(t,e){if(t=_.Params(t,{email:"string"}),!await Z.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 C.bind(this)("invitation-list",Object.assign({mode:"search"},t),{fetchOptions:e,auth:true});return n.list=n.list.map(i=>It(i.user)),n}async function Bc(t){if(t=_.Params(t,{email:r=>_.Email(r)},["email"]),!await Z.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 C.bind(this)("invitation-list",Object.assign({mode:"cancel"},t),{auth:true})}async function $c(t){if(t=_.Params(t,{email:r=>_.Email(r)},["email"]),!await Z.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 C.bind(this)("invitation-list",Object.assign({mode:"resend"},t),{auth:true})}async function jc(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,await this.__connection,this.__user?.user_id&&e.user_id===this.__user.user_id)throw new f("Cannot modify attributes of the current user.",{code:"INVALID_REQUEST"});if(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 Z.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 s={attributes:e};return r&&n&&(s.service=r,s.owner=n),await C.bind(this)("admin-edit-profile",s,{auth:true})}async function Kc(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 C.bind(this)("store-subscription",{endpoint:t.endpoint,keys:t.keys},{auth:true}),"SUCCESS: Subscribed to receive notifications."}async function Hc(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 C.bind(this)("delete-subscription",{endpoint:t.endpoint,keys:t.keys},{auth:true}),"SUCCESS: Unsubscribed from notifications."}async function Gc(){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 C.bind(this)("get-vapid-public-key",null,{auth:true})}}async function Wc(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 C.bind(this)("push-notification",i,{auth:true}),"SUCCESS: Notification sent."}async function zc(t){await this.__connection,t=_.Params(t,{spell:"string",name:"string",magic:r=>r},["spell","name"]);await C.bind(this)("castspell",t);return `The spell "${t.spell}" has been cast.`}async function Jc(t){return await this.__connection,t=_.Params(t||{},{search:["spell","name",()=>"spell"],value:"string"}),await C.bind(this)("getspell",t)}async function Yc(t){await this.__connection,t=_.Params(t,{message:"string",name:"string"},["message","name"]);let e=await C.bind(this)("dopamine",t,{auth:true}),r=e?.previous_message?.message,n=e?.previous_message?.name;if(oe())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
|
|
218
|
+
Watch the video here: ${e.video}`}var v=class{constructor(e,r,n,i){this.__version="2.1.0";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:le,generateRandom:Ye,toBase62:Ms,fromBase62:_e,decodeProjectId:On,formatServiceId:Fn,extractFormData:K,terminatePendingRequests:da,request:(e,r,n)=>C.bind(this)(e,r,n,{ignoreService:true})};this.__network_logs=false;this.__endpoint_version="v2";this.__public_identifier="";this.bearerToken="";this.registerTicket=Ko.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 w=On(e);n&&typeof n=="object"&&(i=n),r&&typeof r=="object"&&(n=r),r=w.owner,e=w.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=Fn(e,r);}catch{this.project_id="";}let l=true,d=false,h=null;if(n&&(typeof n.refetchServiceInfo=="boolean"&&(d=n.refetchServiceInfo),typeof n.autoLogin=="boolean"&&(l=n.autoLogin),n.encryption&&(h=ao(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 u=`https://${this.target_cdn}.cloudfront.net`,p=e.substring(0,4);this.admin_endpoint=fetch(`${u}/${p}/admin-${this.__endpoint_version}.json`).then(w=>w.blob()).then(w=>new Promise((E,R)=>{let S=new FileReader;S.onloadend=()=>E(S.result),S.onerror=R,S.readAsDataURL(w);})).then(w=>{try{return typeof w=="string"?JSON.parse(atob(w.split(",")[1])):null}catch{throw new f("Service does not exist. Create your service from skapi.com",{code:"NOT_EXISTS"})}}),this.record_endpoint=fetch(`${u}/${p}/record-${this.__endpoint_version}.json`).then(w=>w.blob()).then(w=>new Promise((E,R)=>{let S=new FileReader;S.onloadend=()=>E(S.result),S.onerror=R,S.readAsDataURL(w);})).then(w=>{try{return typeof w=="string"?JSON.parse(atob(w.split(",")[1])):null}catch{throw new f("Service does not exist. Create your service from skapi.com",{code:"NOT_EXISTS"})}});let g=oe();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 w in m)this[w]=m[w];m.__public_identifier||(this.__public_identifier=`${this.service}:${this.owner}:${Ye(16)}`);}co.bind(this)(h),this.__authConnection=(async()=>{let w=await this.admin_endpoint,E={UserPoolId:w.userpool_id,ClientId:w.userpool_client};Nn()&&(E.Storage=window.localStorage),this.userPool=new xn(E);try{this.user||await X.bind(this)().getSession({skipUserUpdateEventTrigger:!0}),this.user&&(!m?.connection&&!l?Me.bind(this)():(h&&Po.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 w=JSON.parse(b);this.__my_unique_ids=w&&typeof w=="object"&&!Array.isArray(w)?{[y]:w}:{};}catch{this.__my_unique_ids={};}this.__connection=(async()=>{let w=null;await this.record_endpoint,m?.connection||(w=this._updateConnection({refresh:d}));let E=()=>{if(this.__class_properties_has_been_cached)return;let R=()=>{let S={},U=["__startKeyHistory","__disabledAccount","__cached_requests","__request_signup_confirmation","__public_identifier","connection"];if(this.connection){for(let k of U)S[k]=this[k];if(h&&(S.__cached_requests={},S.__startKeyHistory={}),g){let k=`${e}#${r}`;try{window.sessionStorage.setItem(k,JSON.stringify(S));}catch{try{let x=Object.assign({},S,{__cached_requests:{},__startKeyHistory:{}});window.sessionStorage.setItem(k,JSON.stringify(x));}catch{try{window.sessionStorage.removeItem(k);}catch{}}}}this.__class_properties_has_been_cached=true;}};return w instanceof Promise?w.then(()=>R()):R()};return g&&(window.addEventListener("beforeunload",()=>{this.closeRealtime(),E();}),window.addEventListener("visibilitychange",()=>{E();})),await w,await this.__authConnection,this.connection})(),this.__connection.then(w=>{((w?.group||0)<3||this.__network_logs)&&this.version();}).catch(()=>{});}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){oe()&&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||(oe()&&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 C.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,oe()){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(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{
|
|
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{oe()?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 Ec.bind(this)(e,r)}closeRTC(e){return Re.bind(this)(e)}connectRTC(e,r){return Ba.bind(this)(e,r)}connectRealtime(e){return At.bind(this)(e)}spellcast(e){return zc.bind(this)(e)}getspell(e){return Jc.bind(this)(e)}dopamine(e){return Yc.bind(this)(e)}getUniqueId(e,r){return ka.bind(this)(e,r)}resendInvitation(e){return $c.bind(this)(e)}cancelInvitation(e){return Bc.bind(this)(e)}getInvitations(e,r){return Vc.bind(this)(e,r)}openIdLogin(e){return Wo.bind(this)(e)}loginWithToken(e){return zo.bind(this)(e)}registerNewsletterGroup(e){return Cc.bind(this)(e)}deleteNewsletterGroup(e){return xc.bind(this)(e)}clientSecretRequest(e){return dc.bind(this)(e)}clientSecretRequestHistory(e,r){return vi.bind(this)(e,r)}clientSecretRequestStream(e,r){return Ii.bind(this)(e,r)}clientSecretRequestFinalize(e,r,n){return Pi.bind(this)(e,r,n)}cancelClientSecretRequest(e){return Ti.bind(this)(e)}stopClientSecretPolling(e){return Gr.bind(this)(e||{})}isPollStopped(e){return Si(e)}clientSecretRequestQueueCount(e){return Ri.bind(this)(e)}forwardRequestHistory(e,r){return pc.bind(this)(e,r)}forwardRequestStream(e,r){return fc.bind(this)(e,r)}forwardRequestFinalize(e,r,n){return hc.bind(this)(e,r,n)}cancelForwardRequest(e){return gc.bind(this)(e)}stopForwardRequestPolling(e){return mc.bind(this)(e||{})}forwardRequestQueueCount(e){return yc.bind(this)(e)}consumeTicket(e){return Bo.bind(this)(e)}getConsumedTickets(e,r){return jo.bind(this)(e,r)}getTickets(e,r){return $o.bind(this)(e,r)}closeRealtime(){return jr.bind(this)()}getRealtimeUsers(e,r){return Wa.bind(this)(e,r)}sendInquiry(e){return bc.bind(this)(e)}blockAccount(e){return Nc.bind(this)(e)}unblockAccount(e){return Oc.bind(this)(e)}deleteAccount(e){return Fc.bind(this)(e)}inviteUser(e,r){return Lc.bind(this)(e,r)}createAccount(e){return Mc.bind(this)(e)}grantAccess(e){return qc.bind(this)(e)}updateUserAttributes(e){return jc.bind(this)(e)}getRealtimeGroups(e,r){return za.bind(this)(e,r)}newsletterGroupEndpoint(){return Uc.bind(this)()}postRealtime(e,r,n){return Ga.bind(this)(e,r,n)}joinRealtime(e){return St.bind(this)(e)}getProfile(e){return Go.bind(this)(e)}getFile(e,r){return qe.bind(this)(e,r)}secureRequest(e,r){return _c.bind(this)(e,r)}forwardRequest(e,r){return uc.bind(this)(e,r)}getFormResponse(){return ha.bind(this)()}getRecords(e,r){return Ta.bind(this)(e,r)}getTables(e,r){return Ca.bind(this)(e,r)}getIndexes(e,r){return xa.bind(this)(e,r)}getTags(e,r){return Ua.bind(this)(e,r)}deleteRecords(e,r){return Da.bind(this)(e,r)}resendSignupConfirmation(){return Jo.bind(this)()}recoverAccount(e=false){return Yo.bind(this)(e)}getUsers(e,r){return oa.bind(this)(e,r)}disableAccount(){return Xo.bind(this)()}lastVerifiedEmail(e){return aa.bind(this)(e)}unsubscribeNewsletter(e){return kc.bind(this)(e)}subscribeNotification(e,r){return Kc.bind(this)({endpoint:e,keys:r})}unsubscribeNotification(e,r){return Hc.bind(this)({endpoint:e,keys:r})}vapidPublicKey(){return Gc.bind(this)()}pushNotification(e,r){return Wc.bind(this)(e,r)}getNewsletters(e,r){return Dc.bind(this)(e,r)}getNewsletterSubscription(e,r){return Ic.bind(this)(e,r)}getEncryptionStatus(){return lo.bind(this)()}isWithheld(e){return Yn.call(this,e)}unlockEncryption(e){return So.bind(this)(e)}lockEncryption(e){return Ro.bind(this)(e)}takeRecoveryCode(){return Do.bind(this)()}unlockWithRecoveryCode(e){return No.bind(this)(e)}regenerateRecoveryCode(){return Oo.bind(this)()}pinPeerKey(e){return Uo.bind(this)(e)}grantPrivateRecordAccess(e){return Na.bind(this)(e)}removePrivateRecordAccess(e){return Oa.bind(this)(e)}listPrivateRecordAccess(e,r){return Fa.bind(this)(e,r)}requestPrivateRecordAccessKey(e){return La.bind(this)(e)}deleteFiles(e){return Aa.bind(this)(e)}uploadFiles(e,r){return jt.bind(this)(e,r)}mock(e,r){return wc.bind(this)(e,r)}login(e){return li.bind(this)(e)}logout(e){return qt.bind(this)(e)}signup(e,r){return Qo.bind(this)(e,r)}resetPassword(e){return Zo.bind(this)(e)}verifyEmail(e,r){return ra.bind(this)(e,r)}verifyPhoneNumber(e,r){return ta.bind(this)(e,r)}forgotPassword(e,r){return na.bind(this)(e,r)}changePassword(e){return ia.bind(this)(e)}updateProfile(e){return sa.bind(this)(e)}postRecord(e,r,n){return yi.bind(this)(e,r,n)}getSubscriptions(e,r){return Ac.bind(this)(e,r)}subscribe(e){return Sc.bind(this)(e)}unsubscribe(e){return Rc.bind(this)(e)}blockSubscriber(e){return vc.bind(this)(e)}unblockSubscriber(e){return Tc.bind(this)(e)}subscribeNewsletter(e){return Pc.bind(this)(e)}bulkPostRecords(e){return Pa.bind(this)(e)}};I([P()],v.prototype,"getFeed"),I([P()],v.prototype,"closeRTC"),I([P()],v.prototype,"connectRTC"),I([P()],v.prototype,"spellcast"),I([P()],v.prototype,"getspell"),I([P()],v.prototype,"dopamine"),I([P()],v.prototype,"getUniqueId"),I([P()],v.prototype,"resendInvitation"),I([P()],v.prototype,"cancelInvitation"),I([P()],v.prototype,"getInvitations"),I([P()],v.prototype,"openIdLogin"),I([P()],v.prototype,"loginWithToken"),I([P()],v.prototype,"registerNewsletterGroup"),I([P()],v.prototype,"deleteNewsletterGroup"),I([P()],v.prototype,"clientSecretRequest"),I([P()],v.prototype,"clientSecretRequestHistory"),I([P()],v.prototype,"cancelClientSecretRequest"),I([P()],v.prototype,"forwardRequestHistory"),I([P()],v.prototype,"cancelForwardRequest"),I([P()],v.prototype,"consumeTicket"),I([P()],v.prototype,"getConsumedTickets"),I([P()],v.prototype,"getTickets"),I([P()],v.prototype,"getRealtimeUsers"),I([P()],v.prototype,"sendInquiry"),I([P()],v.prototype,"blockAccount"),I([P()],v.prototype,"unblockAccount"),I([P()],v.prototype,"deleteAccount"),I([P()],v.prototype,"inviteUser"),I([P()],v.prototype,"createAccount"),I([P()],v.prototype,"grantAccess"),I([P()],v.prototype,"updateUserAttributes"),I([P()],v.prototype,"getRealtimeGroups"),I([P()],v.prototype,"newsletterGroupEndpoint"),I([P()],v.prototype,"postRealtime"),I([P()],v.prototype,"joinRealtime"),I([P()],v.prototype,"getProfile"),I([P()],v.prototype,"getFile"),I([P()],v.prototype,"secureRequest"),I([P()],v.prototype,"forwardRequest"),I([P()],v.prototype,"getFormResponse"),I([P()],v.prototype,"getRecords"),I([P()],v.prototype,"getTables"),I([P()],v.prototype,"getIndexes"),I([P()],v.prototype,"getTags"),I([P()],v.prototype,"deleteRecords"),I([P()],v.prototype,"resendSignupConfirmation"),I([P()],v.prototype,"recoverAccount"),I([P()],v.prototype,"getUsers"),I([P()],v.prototype,"disableAccount"),I([P()],v.prototype,"lastVerifiedEmail"),I([P()],v.prototype,"unsubscribeNewsletter"),I([P()],v.prototype,"subscribeNotification"),I([P()],v.prototype,"unsubscribeNotification"),I([P()],v.prototype,"vapidPublicKey"),I([P()],v.prototype,"pushNotification"),I([P()],v.prototype,"getNewsletters"),I([P()],v.prototype,"getNewsletterSubscription"),I([P()],v.prototype,"unlockEncryption"),I([P()],v.prototype,"unlockWithRecoveryCode"),I([P()],v.prototype,"grantPrivateRecordAccess"),I([P()],v.prototype,"removePrivateRecordAccess"),I([P()],v.prototype,"listPrivateRecordAccess"),I([P()],v.prototype,"requestPrivateRecordAccessKey"),I([P()],v.prototype,"deleteFiles"),I([P()],v.prototype,"uploadFiles"),I([P()],v.prototype,"mock"),I([P({preventMultipleCalls:true})],v.prototype,"login"),I([P()],v.prototype,"logout"),I([P({preventMultipleCalls:true})],v.prototype,"signup"),I([P({preventMultipleCalls:true})],v.prototype,"resetPassword"),I([P({preventMultipleCalls:true})],v.prototype,"verifyEmail"),I([P({preventMultipleCalls:true})],v.prototype,"verifyPhoneNumber"),I([P({preventMultipleCalls:true})],v.prototype,"forgotPassword"),I([P({preventMultipleCalls:true})],v.prototype,"changePassword"),I([P({preventMultipleCalls:true})],v.prototype,"updateProfile"),I([P()],v.prototype,"postRecord"),I([P()],v.prototype,"getSubscriptions"),I([P()],v.prototype,"subscribe"),I([P()],v.prototype,"unsubscribe"),I([P()],v.prototype,"blockSubscriber"),I([P()],v.prototype,"unblockSubscriber"),I([P()],v.prototype,"subscribeNewsletter");var Ci={};var Wr=typeof globalThis<"u"?globalThis:void 0;Wr&&(Wr.Skapi=v,Wr.SkapiError=f,Wr.SkapiTypes=Ci);/*! 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{
|
|
283
|
+
*/export{v as Skapi,f as SkapiError,Ci as Types};//# sourceMappingURL=skapi.browser.mjs.map
|
|
284
284
|
//# sourceMappingURL=skapi.browser.mjs.map
|