skapi-js 1.5.2 → 1.5.3
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 +2 -2
- package/dist/skapi.browser.mjs.map +1 -1
- package/dist/skapi.cjs +2 -2
- package/dist/skapi.cjs.map +1 -1
- package/dist/skapi.js +2 -2
- package/dist/skapi.js.map +1 -1
- package/dist/skapi.mjs +2 -2
- package/dist/skapi.mjs.map +1 -1
- package/package.json +1 -1
package/dist/skapi.mjs
CHANGED
|
@@ -203,7 +203,7 @@ import {CognitoUserPool,AuthenticationDetails,CognitoUserSession,CognitoRefreshT
|
|
|
203
203
|
limitations under the License.
|
|
204
204
|
|
|
205
205
|
*/
|
|
206
|
-
var Fn=Object.defineProperty;var Mn=Object.getOwnPropertyDescriptor;var ee=(n=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(n,{get:(e,t)=>(typeof require<"u"?require:e)[t]}):n)(function(n){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+n+'" is not supported')});var y=(n,e,t,r)=>{for(var i=Mn(e,t),s=n.length-1,o;s>=0;s--)(o=n[s])&&(i=(o(e,t,i))||i);return i&&Fn(e,t,i),i};var z=typeof globalThis<"u"?globalThis:void 0,he=z?.window;function Vn(n){if(Buffer)return Buffer.from(n).toString("base64");let e="",t=new Uint8Array(n),r=32768;for(let i=0;i<t.length;i+=r){let s=t.subarray(i,i+r);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(he)he.global=he,he.global._runningInNodeJS=false;else if(z&&(z.global=z,typeof z.window>"u")){class n{constructor(){this.result=null;this.error=null;this.onload=null;this.onloadend=null;this.onerror=null;}readAsDataURL(r){r.arrayBuffer().then(i=>{let s=Vn(i),o=r.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(r){r.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(r,i="utf-8"){r.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});});}}z.FileReader=n;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(r,i){this._method=r,this._url=i,this.readyState=1;}setRequestHeader(r,i){this._headers[r]=i;}getResponseHeader(r){return null}abort(){this._aborted=true,this.onabort&&this.onabort({});}send(r){if(this._aborted)return;let i={method:this._method,headers:this._headers};r&&this._method!=="GET"&&this._method!=="HEAD"&&(i.body=r),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);});}}z.XMLHttpRequest=e,z.window={_runningInNodeJS:true,alert:t=>console.error("[Alert]",t),sessionStorage:{getItem:t=>null,setItem:(t,r)=>{},removeItem:t=>{}},localStorage:{getItem:t=>{let r=ee("fs"),i=ee("path");try{let s=i.resolve(process.cwd(),"states","localStorage",`${t}.skapi`);return r.existsSync(s)?r.readFileSync(s,"utf8"):null}catch{return null}},setItem:(t,r)=>{let i=ee("fs"),s=ee("path");try{let o=s.resolve(process.cwd(),"states","localStorage");i.existsSync(o)||i.mkdirSync(o,{recursive:!0});let a=s.resolve(o,`${t}.skapi`);i.writeFileSync(a,r,"utf8");}catch{}},removeItem:t=>{let r=ee("fs"),i=ee("path");try{let s=i.resolve(process.cwd(),"states","localStorage",`${t}.skapi`);r.existsSync(s)&&r.unlinkSync(s);}catch{}}},location:{href:"",origin:"",hostname:"",protocol:"",replace:t=>{}},navigator:{userAgent:`nodejs/${z?.process?.versions?.node||"unknown"}`,mediaDevices:{getUserMedia:async t=>{throw new Error("getUserMedia is not supported in Node.js environment.")}}},addEventListener:()=>{},removeEventListener:()=>{}};}var c=class extends Error{constructor(e,t){if(Array.isArray(e)&&e.length<=2){let r=e[1];if(e.length>2)for(let i=2;i<e.length&&typeof e[i]=="string";i++)r+=e[i];super((r||"Something went wrong.").trim()),this.name=t?.name||"SKAPI",this.code=t?.code||e[0]||"ERROR",t?.cause&&(this.cause=t.cause);}else super((e?.message||(typeof e=="string"?e:"Something went wrong.")).trim()),typeof e=="string"?(this.name=t?.name||"SKAPI",this.code=t?.code||"ERROR",t?.cause&&(this.cause=t.cause)):e instanceof Error?(this.cause=e,this.name=e.name,e.hasOwnProperty("code")&&(this.code=e.code)):typeof e=="object"&&e?.code&&e?.message&&(this.name=t?.name||"SKAPI",this.code=t?.code||"ERROR",this.cause=e?.cause);}};var J="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",ve=BigInt(J.length),$n=2*1024*1024,qn=["aud","cognito:username","event_id","exp","iat","iss","jti","origin_jti","secret_key","token_use"],Qe={auth_time:"log",sub:"user_id"},jn=["0","1","2","3","4","5","6","7","8","9","a","b","c","d","e","f","g","h","i","j","k","l"],Ge=["us31","us72","ap51","ap22","ap41","eu71","ap21","us32","us71","af51","ap31","ap43","ap23","ap42","ca01","eu01","eu72","eu51","eu73","eu11","me51","sa31"],He=typeof TextEncoder<"u"?new TextEncoder:null;function Bn(){if(typeof globalThis<"u")return globalThis.Buffer}function Kn(n){if(He)return He.encode(n);let e=unescape(encodeURIComponent(n)),t=new Uint8Array(e.length);for(let r=0;r<e.length;r++)t[r]=e.charCodeAt(r);return t}function Qn(n){if(n instanceof Uint8Array)return n;if(typeof n=="string")return Kn(n);if(typeof ArrayBuffer<"u"&&n instanceof ArrayBuffer)return new Uint8Array(n);if(typeof ArrayBuffer<"u"&&ArrayBuffer.isView(n))return new Uint8Array(n.buffer,n.byteOffset,n.byteLength);if(Array.isArray(n))return Uint8Array.from(n);let e=Bn();if(e)return new Uint8Array(e.from(n));throw new Error("No byte conversion available in this environment.")}var p=class p{static hash(e){typeof e!="string"&&(console.warn("coercing non-string value to empty string"),e="");let t=p.sb(e),r=1732584193,i=-271733879,s=-1732584194,o=271733878,a,l,d,h;for(let u=0;u<t.length;u+=16)a=r,l=i,d=s,h=o,r=p.ff(r,i,s,o,t[u],7,-680876936),o=p.ff(o,r,i,s,t[u+1],12,-389564586),s=p.ff(s,o,r,i,t[u+2],17,606105819),i=p.ff(i,s,o,r,t[u+3],22,-1044525330),r=p.ff(r,i,s,o,t[u+4],7,-176418897),o=p.ff(o,r,i,s,t[u+5],12,1200080426),s=p.ff(s,o,r,i,t[u+6],17,-1473231341),i=p.ff(i,s,o,r,t[u+7],22,-45705983),r=p.ff(r,i,s,o,t[u+8],7,1770035416),o=p.ff(o,r,i,s,t[u+9],12,-1958414417),s=p.ff(s,o,r,i,t[u+10],17,-42063),i=p.ff(i,s,o,r,t[u+11],22,-1990404162),r=p.ff(r,i,s,o,t[u+12],7,1804603682),o=p.ff(o,r,i,s,t[u+13],12,-40341101),s=p.ff(s,o,r,i,t[u+14],17,-1502002290),i=p.ff(i,s,o,r,t[u+15],22,1236535329),r=p.gg(r,i,s,o,t[u+1],5,-165796510),o=p.gg(o,r,i,s,t[u+6],9,-1069501632),s=p.gg(s,o,r,i,t[u+11],14,643717713),i=p.gg(i,s,o,r,t[u],20,-373897302),r=p.gg(r,i,s,o,t[u+5],5,-701558691),o=p.gg(o,r,i,s,t[u+10],9,38016083),s=p.gg(s,o,r,i,t[u+15],14,-660478335),i=p.gg(i,s,o,r,t[u+4],20,-405537848),r=p.gg(r,i,s,o,t[u+9],5,568446438),o=p.gg(o,r,i,s,t[u+14],9,-1019803690),s=p.gg(s,o,r,i,t[u+3],14,-187363961),i=p.gg(i,s,o,r,t[u+8],20,1163531501),r=p.gg(r,i,s,o,t[u+13],5,-1444681467),o=p.gg(o,r,i,s,t[u+2],9,-51403784),s=p.gg(s,o,r,i,t[u+7],14,1735328473),i=p.gg(i,s,o,r,t[u+12],20,-1926607734),r=p.hh(r,i,s,o,t[u+5],4,-378558),o=p.hh(o,r,i,s,t[u+8],11,-2022574463),s=p.hh(s,o,r,i,t[u+11],16,1839030562),i=p.hh(i,s,o,r,t[u+14],23,-35309556),r=p.hh(r,i,s,o,t[u+1],4,-1530992060),o=p.hh(o,r,i,s,t[u+4],11,1272893353),s=p.hh(s,o,r,i,t[u+7],16,-155497632),i=p.hh(i,s,o,r,t[u+10],23,-1094730640),r=p.hh(r,i,s,o,t[u+13],4,681279174),o=p.hh(o,r,i,s,t[u],11,-358537222),s=p.hh(s,o,r,i,t[u+3],16,-722521979),i=p.hh(i,s,o,r,t[u+6],23,76029189),r=p.hh(r,i,s,o,t[u+9],4,-640364487),o=p.hh(o,r,i,s,t[u+12],11,-421815835),s=p.hh(s,o,r,i,t[u+15],16,530742520),i=p.hh(i,s,o,r,t[u+2],23,-995338651),r=p.ii(r,i,s,o,t[u],6,-198630844),o=p.ii(o,r,i,s,t[u+7],10,1126891415),s=p.ii(s,o,r,i,t[u+14],15,-1416354905),i=p.ii(i,s,o,r,t[u+5],21,-57434055),r=p.ii(r,i,s,o,t[u+12],6,1700485571),o=p.ii(o,r,i,s,t[u+3],10,-1894986606),s=p.ii(s,o,r,i,t[u+10],15,-1051523),i=p.ii(i,s,o,r,t[u+1],21,-2054922799),r=p.ii(r,i,s,o,t[u+8],6,1873313359),o=p.ii(o,r,i,s,t[u+15],10,-30611744),s=p.ii(s,o,r,i,t[u+6],15,-1560198380),i=p.ii(i,s,o,r,t[u+13],21,1309151649),r=p.ii(r,i,s,o,t[u+4],6,-145523070),o=p.ii(o,r,i,s,t[u+11],10,-1120210379),s=p.ii(s,o,r,i,t[u+2],15,718787259),i=p.ii(i,s,o,r,t[u+9],21,-343485551),r=p.ad(r,a),i=p.ad(i,l),s=p.ad(s,d),o=p.ad(o,h);return p.rh(r)+p.rh(i)+p.rh(s)+p.rh(o)}static rh(e){let t="";for(let r=0;r<=3;r++)t+=p.alphabet.charAt(e>>r*8+4&15)+p.alphabet.charAt(e>>r*8&15);return t}static ad(e,t){let r=(e&65535)+(t&65535);return (e>>16)+(t>>16)+(r>>16)<<16|r&65535}static rl(e,t){return e<<t|e>>>32-t}static cm(e,t,r,i,s,o){return p.ad(p.rl(p.ad(p.ad(t,e),p.ad(i,o)),s),r)}static ff(e,t,r,i,s,o,a){return p.cm(t&r|~t&i,e,t,s,o,a)}static gg(e,t,r,i,s,o,a){return p.cm(t&i|r&~i,e,t,s,o,a)}static hh(e,t,r,i,s,o,a){return p.cm(t^r^i,e,t,s,o,a)}static ii(e,t,r,i,s,o,a){return p.cm(r^(t|~i),e,t,s,o,a)}static sb(e){let t,r=(e.length+8>>6)+1,i=new Array(r*16);for(t=0;t<r*16;t++)i[t]=0;for(t=0;t<e.length;t++)i[t>>2]|=e.charCodeAt(t)<<t%4*8;return i[t>>2]|=128<<t%4*8,i[r*16-2]=e.length*8,i}};p.alphabet="0123456789abcdef";var V=p;function Xe(n){if(n===0)return J[0];let e="";for(;n>0;)e=J[n%62]+e,n=Math.floor(n/62);return e}function j(n){return n.split("").reverse().reduce((e,t,r)=>e+J.indexOf(t)*62**r,0)}function oe(n=6){let e="",t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",r=t.length,i=0;for(;i<n;)e+=t.charAt(Math.floor(Math.random()*r)),i+=1;return e}function De(){return typeof window>"u"||!!window?._runningInNodeJS}function $(){return !De()&&typeof document<"u"&&typeof document.createElement=="function"}function pe(n){let e;try{e=JSON.stringify(n);}catch{throw new c("Invalid data type.",{code:"INVALID_REQUEST"})}if(new Blob([e]).size>$n)throw new c("Data should not exceed 2MB",{code:"INVALID_REQUEST"})}function We(n){return n===""||n==="on"||n==="true"}function ze(n){return n==="false"}function Je(n,e,t){e.name&&t(n,e.name,e.value);}var me=$(),Hn=typeof SubmitEvent<"u",Wn=typeof HTMLFormElement<"u";function N(n,e,t){let r={},i=[];function s(l,d,h){if(e?.ignoreEmpty&&h==="")return;if(e?.nullIfEmpty&&h===""&&(h=null),typeof t=="function"){let R=t(d,h);R!==void 0&&(h=R);}let u=d.split("[").map(R=>{let f=R.replace("]",""),A=Number(f);return !isNaN(A)&&!f.includes(".")?f=A:(f[0]==='"'&&f[f.length-1]==='"'||f[0]==="'"&&f[f.length-1]==="'")&&(f=f.replace(/"/g,"").replace(/'/g,"")),f}),m=l;if(typeof u[0]=="number")throw new c("Form key cannot start with an array index.",{code:"INVALID_REQUEST"});for(let R=0;R<u.length;R++){let f=u[R];R<u.length-1?(m[f]===void 0&&(typeof u[R+1]=="number"?m[f]=[]:m[f]={}),m=m[f]):m[f]===void 0?m[f]=h:Array.isArray(m[f])?m[f].push(h):m[f]=[m[f],h];}}function o(l,d,h){if(h instanceof File)l.push({name:d,file:h});else if(h instanceof FileList&&h&&h.length>0)for(let u=0;u<=h.length-1;u++){let m=h.item(u);m&&l.push({name:d,file:m});}}let a=l=>{l.name&&(l.type==="number"?l.value&&s(r,l.name,Number(l.value)):l.type==="checkbox"||l.type==="radio"?l.checked?l.type==="checkbox"&&l.value===""||We(l.value)?s(r,l.name,true):ze(l.value)?s(r,l.name,false):l.value&&s(r,l.name,l.value):l.type==="checkbox"&&(We(l.value)?s(r,l.name,false):ze(l.value)&&s(r,l.name,true)):l.type==="file"?l.files&&l.files.length>0&&o(i,l.name,l.files):s(r,l.name,l.value));};if(me&&(n instanceof HTMLInputElement||n instanceof HTMLSelectElement||n instanceof HTMLTextAreaElement))return a(n),pe(r),{data:r,files:i};if(me&&n instanceof FormData){for(let l of n.entries()){let d=l[0],h=l[1];if(h instanceof File||h instanceof FileList)o(i,d,h);else if(h instanceof Blob){let u=h;if(u.type==="application/json")try{let m=JSON.parse(u.text());s(r,d,m);}catch{s(r,d,u);}}else s(r,d,h);}return pe(r),{data:r,files:i}}if(me&&Hn&&n instanceof SubmitEvent&&(n=n.target),me&&Wn&&n instanceof HTMLFormElement){let l=n.querySelectorAll("input"),d=n.querySelectorAll("select"),h=n.querySelectorAll("textarea");for(let u=0;u<d.length;u++)Je(r,d[u],s);for(let u=0;u<h.length;u++)Je(r,h[u],s);for(let u=0;u<l.length;u++)a(l[u]);return pe(r),{data:r,files:i}}return pe(n),{data:n,files:i}}function ae(n){let e={};for(let t in n){let r=n[t];if(!qn.includes(t))if(Qe[t])e[Qe[t]]=r;else if(t.includes("custom:"))e[t.replace("custom:","")]=r;else if(t==="address"){let i=r;if(i&&typeof i=="object"&&Object.keys(i).length){if(i?.formatted)try{e[t]=JSON.parse(i.formatted);}catch{e[t]=i.formatted;}}else e[t]=i;}else e[t]=r;}for(let t of ["address_public","birthdate_public","email_public","gender_public","phone_number_public","access_group"])t.includes("_public")?e.hasOwnProperty(t.split("_")[0])?e[t]=e.hasOwnProperty(t)?!!Number(e[t]):false:delete e[t]:e[t]=e.hasOwnProperty(t)?Number(e[t]):0;for(let t of ["email","phone_number"])e.hasOwnProperty(t)?e[t+"_verified"]=e[t+"_verified"]===true:delete e[t+"_verified"];return e}function Ue(n){if(n=tr(n),n.split("-").length===7){let e=n.split("-"),t,r;try{t=Ge[j(e[1][0])],r=e.slice(2).join("-");}catch{throw new Error("INVALID_PARAMETER: Service ID is invalid.")}if(!t)throw new Error("INVALID_PARAMETER: Service ID is invalid.");return {service:t+e[0]+e[1].slice(1),owner:r}}return {service:n,owner:""}}function Ze(n,e){let t=Ge.indexOf(n.slice(0,4)),r=jn[t],s=`${n.slice(4,-4)}-${r}${n.slice(-4)}-${e}`;return er(s)}function zn(n){let e=0n;for(let t of n){let r=J.indexOf(t);if(r<0)throw new Error(`INVALID_PARAMETER: Invalid base62 character: ${t}`);e=e*ve+BigInt(r);}return e}function Jn(n,e=1){if(n<0n)throw new Error("INVALID_PARAMETER: Negative values are not supported.");if(n===0n)return "0".repeat(Math.max(1,e));let t="",r=n;for(;r>0n;){let i=Number(r%ve);t=J[i]+t,r/=ve;}return t.length<e&&(t="0".repeat(e-t.length)+t),t}function Gn(n){if(n===0n)return Uint8Array.from([0]);let e=[],t=n;for(;t>0n;)e.push(Number(t&0xffn)),t>>=8n;return e.reverse(),Uint8Array.from(e)}function Xn(n){let e=0n;for(let t of n)e=(e<<8n)+BigInt(t);return e}function Zn(n){let e=String(n).replace(/-/g,"");if(!/^[0-9a-fA-F]{32}$/.test(e))throw new Error("INVALID_PARAMETER: Invalid UUID format.");let t=new Uint8Array(16);for(let r=0;r<16;r++)t[r]=parseInt(e.slice(r*2,r*2+2),16);return t}function Yn(n){let e=Array.from(Qn(n),t=>t.toString(16).padStart(2,"0")).join("");return [e.slice(0,8),e.slice(8,12),e.slice(12,16),e.slice(16,20),e.slice(20)].join("-")}function er(n){let e=String(n);if(e.split("-").length===2)return e;let t=e.match(/^([0-9A-Za-z]+)-([0-9A-Za-z]+)-([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/);if(!t)throw new Error("INVALID_PARAMETER: Input must match <base62>-<base62>-<uuid>.");let[,r,i,s]=t;if(r.length<2)throw new Error("INVALID_PARAMETER: The first part must contain at least 2 characters.");if(i.length>=J.length)throw new Error("INVALID_PARAMETER: The middle section is too long to encode.");let o=r.slice(0,2),a=r.slice(2),l=i+o,d=J[i.length]+a+l,h=Zn(s),u=Jn(Xn(h));return `${d}-${u}`}function tr(n){let e=String(n);if(e.split("-").length!==2)return e;let t=e.split("-");if(t.length!==2||!t[0]||!t[1])throw new Error("INVALID_PARAMETER: Corrupt compressed token.");let[r,i]=t,s=J.indexOf(r[0]);if(s<0)throw new Error("INVALID_PARAMETER: Corrupt compressed token.");let o=r.slice(1),a=s+2;if(o.length<a)throw new Error("INVALID_PARAMETER: Corrupt compressed token.");let l=o.slice(0,o.length-a),d=o.slice(o.length-a),h=d.slice(s),u=d.slice(0,s),m=h+l;if(!/^[0-9A-Za-z]+$/.test(m)||!/^[0-9A-Za-z]+$/.test(u))throw new Error("INVALID_PARAMETER: Corrupt compressed token.");let R=zn(i),f=Gn(R);if(f.length>16)throw new Error("INVALID_PARAMETER: Corrupt compressed token.");let A=new Uint8Array(16);A.set(f,16-f.length);let P=Yn(A);return `${m}-${u}-${P}`}function rr(n,e="User ID"){let t=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;if(n){if(typeof n!="string")throw new c(`${e} should be type: string.`,{code:"INVALID_PARAMETER"});if(!n.match(t))throw new c(`${e} is invalid.`,{code:"INVALID_PARAMETER"})}else throw new c(`${e} is empty.`,{code:"INVALID_PARAMETER"});return n}function ir(n){if(n&&(typeof n!="string"||n.charAt(0)!=="+"||isNaN(Number(n.substring(1)))))throw new c('"phone_number" is invalid. The format should be "+00123456789". Type: string.',{code:"INVALID_PARAMETER"});return n||""}function sr(n){if(n){if(typeof n!="string")throw new c('"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(n.length!==10||n.split("-").length!==3||!e.test(n))throw new c('"birthdate" is invalid. The format should be "yyyy-mm-dd". Type: string.',{code:"INVALID_PARAMETER"})}}return n||""}function or(n){if(n){if(typeof n!="string")throw new c('"password" should be type: string.',{code:"INVALID_PARAMETER"});if(n.length<6)throw new c('"password" should be at least 6 characters.',{code:"INVALID_PARAMETER"});if(n.length>60)throw new c('"password" can be up to 60 characters max.',{code:"INVALID_PARAMETER"})}else throw new c('"password" is required.',{code:"INVALID_PARAMETER"});return n}function ar(n,e="email"){if(n){if(typeof n!="string")throw new c(`"${e}"should be type: string.`,{code:"INVALID_PARAMETER"});if(n.length<5)throw new c(`"${e}" should be at least 5 characters.`,{code:"INVALID_PARAMETER"});if(/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/.test(n)&&(n=n.trim(),n.split("@")[1].split(".").length>=2))return n.toLowerCase()}else throw new c(`"${e}" is required.`,{code:"INVALID_PARAMETER"});throw new c(`"${n}" is an invalid email.`,{code:"INVALID_PARAMETER"})}function cr(n){let e=typeof window<"u",t=(()=>{let i=e&&window.location.origin||null;return i&&i.slice(-1)==="/"&&(i=i.slice(0,-1)),i})(),r=i=>{if(typeof i=="string"){if(i==="*")return "*";{let s=i.trim();if(s[0]==="/"&&t){if(t.slice(0,5)==="file:")throw new c(`"${i}" is an invalid url. Relative URL does not work on local file system. Use full URL string.`,{code:"INVALID_PARAMETER"});s=t+s;}else if(s[0]==="."&&t){if(t.slice(0,5)==="file:")throw new c(`"${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 c(`"${i}" is an invalid url.`,{code:"INVALID_PARAMETER"})}if(o.protocol)return o.href}}throw new c(`"${i}" is an invalid url.`,{code:"INVALID_PARAMETER"})};return Array.isArray(n)?n.map(i=>r(i)):r(n)}function lr(n,e,t=[],r){let i=N(n,r),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];}r?.precall&&r.precall({data:o,files:i?.files||[]});try{return nr(o,e,t)}catch(a){throw new c(a.message,{code:"INVALID_PARAMETER"})}}var g={UserId:rr,PhoneNumber:ir,Birthdate:sr,Password:or,Email:ar,Url:cr,Params:lr};var C=null;function Ne(n){let e={tkid:"ticket_id",cond:"condition",stmp:"timestamp",actn:"action",cnt:"count",ttl:"time_to_live",plch:"placeholder",hash:"hash",desc:"description",pmc:"limit_per_user"},t={};for(let r in n)if(r==="tkid"){let i=n[r].split("#");if(i.length===1){t.ticket_id=i[0];continue}t.ticket_id=i[1],t.consume_id=i[2],t.user_id=i[3];let s=i[2].slice(-4);if(t.is_test=s===":CHK",!n.stmp){let o=i[2].slice(0,-4);/^[0-9]+$/.test(o)?t.timestamp=parseInt(o,10):t.timestamp=j(i[2].slice(0,-4));}}else e[r]?t[e[r]]=n[r]:t[r]=n[r];return t}async function et(n){if(!n.ticket_id)throw new c("Ticket ID is required.",{code:"INVALID_PARAMETER"});if(!n.method)throw new c('Method is required. Should be either "GET" or "POST"',{code:"INVALID_PARAMETER"});let e=n.ticket_id;await this.__connection;let t=await w.bind(this)(`https://${this.service.slice(0,4)}.${this.customApiDomain}/auth/consume/${this.service}/${this.owner}/${e}`,n?.data||{},{method:n.method,auth:!!n?.auth});return Ne(t)}async function tt(n,e){await this.__connection;let t=await w.bind(this)("ticket",Object.assign({exec:"list"},n||{}),{auth:true,fetchOptions:e});return t.list=t.list.map(Ne),t}async function nt(n,e){await this.__connection;let t=await w.bind(this)("ticket",Object.assign({exec:"consumed"},n||{}),{auth:true,fetchOptions:e});return t.list=t.list.map(Ne),t}async function rt(n){return w.bind(this)("register-ticket",Object.assign({exec:"reg"},n),{auth:true})}async function it(n){return w.bind(this)("register-ticket",Object.assign({exec:"unreg"},n),{auth:true})}async function ne(){if(await this.__connection,this.session){let n=Math.floor(Date.now()/1e3),t=this.session.getIdToken().getExpiration();if(t<n){this.log("request:requesting new token",null);try{await F.bind(this)().getSession({refreshToken:!0}),this.log("request:received new tokens",{exp:this.session?.idToken?.payload?.exp,currentTime:n,expiresIn:t-n,token:this.session?.accessToken?.jwtToken,refreshToken:this.session?.refreshToken?.token});}catch(r){throw this.log("request:new token error",r),new c("User login is required.",{code:"INVALID_REQUEST"})}}else this.log("request:tokens",{exp:this.session.idToken.payload.exp,currentTime:n,expiresIn:t-n,token:this.session.accessToken.jwtToken,refreshToken:this.session.refreshToken.token});return this.session?.idToken?.jwtToken}else throw this.log("request:no session",null),G.bind(this)(),new c("User login is required.",{code:"INVALID_REQUEST"})}function Ye(n,e){return new Promise((t,r)=>{e.refreshSession(n.getRefreshToken(),(i,s)=>{this.log("getSession:refreshSessionCallback",{refreshErr:i,refreshedSession:s}),i?(G.bind(this)(),r(i)):s.isValid()?t(s):(G.bind(this)(),r(new c("Invalid session.",{code:"INVALID_REQUEST"})));});})}function F(){if(!this.userPool)throw new c("User pool is missing",{code:"INVALID_REQUEST"});let n=()=>{let s=C.getSignInUserSession().getIdToken().payload||null,o=ae(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:d=false}=s||{};if(l&&d&&(d=false),C=this.userPool.getCurrentUser(),!C){this.log("getSession:cognitoUser",C),G.bind(this)(),a(null);return}let h=u=>{let m=u.getIdToken().payload;if(this.log("getSession:respond:sessionAttribute",m),m["custom:service"]!==this.service)throw this.log("getSession:respond","invalid service, signing out"),G.bind(this)(),new c("Invalid session.",{code:"INVALID_REQUEST"});return this.session=u,n(),d||this._runOnUserUpdateListeners(this.user),this.session};C.getSession((u,m)=>{if(this.log("getSession:getSessionCallback",{err:u,session:m}),!m){G.bind(this)(),a(new c("Current session does not exist.",{code:"INVALID_REQUEST"}));return}if(u){Ye.bind(this)(m,C).then(_=>o(h(_))).catch(a);return}let R=Math.floor(Date.now()/1e3),f=m.getIdToken(),A=f.getExpiration(),P=A<R;if(this.log("getSession:currentTime",R),this.log("getSession:idTokenExp",A),this.log("getSession:isExpired",P),this.log("getSession:existingBearerToken",this.bearerToken),this.bearerToken=f.getJwtToken(),P||l||!m.isValid())Ye.bind(this)(m,C).then(_=>o(h(_))).catch(a);else try{o(h(m));}catch(_){a(_);}});}),t=(s,o)=>{let a=o||s.includes(this.service+"-")?s:this.service+"-"+V.hash(s);return {cognitoUser:new CognitoUser({Username:a,Pool:this.userPool}),cognitoUsername:a}};return {getSession:e,authenticateUser:(s,o,a=false,l=false)=>new Promise((d,h)=>{this.__request_signup_confirmation=null,this.__disabledAccount=null;let u=t(s,a),m=u.cognitoUsername,R=new AuthenticationDetails({Username:m,Password:o});u.cognitoUser.authenticateUser(R,{newPasswordRequired:(f,A)=>{this.__disabledAccount=null,this.__request_signup_confirmation=m,f["custom:signup_ticket"]==="PASS"||f["custom:signup_ticket"]==="MEMBER"||f["custom:signup_ticket"]==="OIDPASS"?u.cognitoUser.completeNewPasswordChallenge(o,{},{onSuccess:P=>{C=u.cognitoUser,e().then(_=>d(this.user));},onFailure:P=>{h(new c(P.message||"Failed to authenticate user.",{code:P.code}));}}):h(new c("User's signup confirmation is required.",{code:"SIGNUP_CONFIRMATION_NEEDED"}));},onSuccess:f=>e({skipUserUpdateEventTrigger:true}).then(A=>{this.__disabledAccount=null,this._runOnLoginListeners(this.user),this._runOnUserUpdateListeners(this.user),d(this.user);}),onFailure:f=>{let A=[],{parsed:P,code:_}=be(f),x=typeof f?.message=="string"?f.message:"";if(_==="NotAuthorizedException"?x.includes("User is disabled.")?(this.__disabledAccount=m,A=["This account is disabled.","USER_IS_DISABLED"]):l?A=["The account already exists.","ACCOUNT_EXISTS"]:A=["Incorrect username or password.","INCORRECT_USERNAME_OR_PASSWORD"]:_==="UserNotFoundException"?A=["Incorrect username or password.","INCORRECT_USERNAME_OR_PASSWORD"]:_==="UserNotConfirmedException"?(this.__request_signup_confirmation=m,A=["User's signup confirmation is required.","SIGNUP_CONFIRMATION_NEEDED"]):(_==="TooManyRequestsException"||_==="LimitExceededException")&&(A=["Too many attempts. Please try again later.","REQUEST_EXCEED"]),P.code==="SIGNUP_CONFIRMATION_NEEDED"&&(this.__request_signup_confirmation=m),A.length){let k=A[1],T=A[0];h(new c(T,{code:k,cause:f}));}else h(P);}});}),createCognitoUser:t,signup:(s,o,a)=>new Promise((l,d)=>{this.userPool.signUp(s,o,a,null,(h,u)=>{if(h){let{parsed:m,code:R}=be(h),f=[];R==="UsernameExistsException"?f=["The account already exists.","EXISTS"]:R==="InvalidPasswordException"?f=["Invalid password. Password must be at least 6 characters.","INVALID_PARAMETER"]:R==="InvalidParameterException"?f=[m.message||"Invalid parameter.","INVALID_PARAMETER"]:R==="TooManyRequestsException"||R==="LimitExceededException"?f=["Too many attempts. Please try again later.","REQUEST_EXCEED"]:R==="CodeDeliveryFailureException"?f=["Failed to deliver verification code.","CODE_DELIVERY_FAILURE"]:R==="UserLambdaValidationException"&&(f=[m.message||"Signup validation failed.","INVALID_REQUEST"]),f.length?d(new c(f[0],{code:f[1],cause:h})):d(m);return}l(u);});})}}function be(n){let e=typeof n?.code=="string"&&n.code.trim()?n.code.trim():"ERROR",r=((typeof n?.message=="string"?n.message:typeof n=="string"?n:"An error occurred.")||"An error occurred.").trim();r||(r="An error occurred.");let i=r.match(/#([A-Za-z0-9_]+)\s*:\s*([\s\S]+)/),s=i?.[1]?.trim()||e,o=i?.[2]?.trim()||r;return {parsed:new c(o,{code:s,cause:n}),code:e}}async function st(n){await this.__authConnection;let e=n?.refreshToken||false;if(!e)return this.user;try{return await F.bind(this)().getSession(Object.assign({skipUserUpdateEventTrigger:!e,refreshToken:e},n)),this.user}catch{return null}}async function ot(n){await this.__connection,n=g.Params(n,{token:"string",id:"string",merge:s=>{if(s===void 0)return false;if(typeof s=="string")return [s];if(Array.isArray(s)){for(let o of s)if(typeof o!="string")throw new c('"merge" array items should be type: <string>.',{code:"INVALID_PARAMETER"})}if(typeof s!="boolean"&&!Array.isArray(s))throw new c('"merge" should be type: <boolean | string[]>.',{code:"INVALID_PARAMETER"});return s}});let e=await w.bind(this)("openid-logger",n),t=e.logger.split("#"),r=this.service+"-"+t[0],i=t[1];return {userProfile:await F.bind(this)().authenticateUser(r,i,true,true),openid:e.openid}}function pr(n){let e=typeof globalThis<"u"?globalThis:void 0;if(e?.Buffer)return e.Buffer.from(n,"base64").toString("utf8");if(typeof atob=="function"){let t=atob(n),r=new Uint8Array(t.length);for(let i=0;i<t.length;i++)r[i]=t.charCodeAt(i);return typeof TextDecoder<"u"?new TextDecoder().decode(r):t}throw new Error("No base64 decoder available in this environment")}function mr(n){let e=n.split(".");if(e.length!==3)throw new Error("Invalid JWT format");let r=e[1].replace(/-/g,"+").replace(/_/g,"/"),i=pr(r);return JSON.parse(i)}async function at(n){await this.__authConnection,this.log("loginWithToken:params",n),n=g.Params(n,{idToken:"string",accessToken:"string",refreshToken:"string"},["idToken"]);let e=mr(n.idToken);if(this.log("loginWithToken:idTokenPayload",e),e["custom:service"]!==this.service)throw new c("Token does not belong to this service.",{code:"INVALID_REQUEST"});let t=Math.floor(Date.now()/1e3);if(e.exp&&e.exp<t)throw new c("Token has expired.",{code:"INVALID_REQUEST"});if(this.__user=ae(e),this.session=null,n.accessToken&&n.refreshToken)try{if(this.session=new CognitoUserSession({IdToken:new CognitoIdToken({IdToken:n.idToken}),AccessToken:new CognitoAccessToken({AccessToken:n.accessToken}),RefreshToken:new CognitoRefreshToken({RefreshToken:n.refreshToken})}),this.log("loginWithToken:session",this.session),this.log("loginWithToken:CognitoUser",CognitoUser),this.log("loginWithToken:userPool",this.userPool),CognitoUser&&this.userPool){this.log("loginWithToken:cognito:username",e["cognito:username"]);let r={Username:e["cognito:username"],Pool:this.userPool};this.log("loginWithToken:cognitoUserParams",r),C=new CognitoUser(r),C.setSignInUserSession(this.session),this.log("loginWithToken:cognitoUserRestored",{cognitoUserType:typeof C,cognitoUserKeys:Object.keys(C||{}),cognitoUser:C});}}catch(r){this.log("loginWithToken:err",r);try{this.log("loginWithToken:err:stringified",JSON.stringify(r));}catch{this.log("loginWithToken:err:stringifyFail",String(r));}try{let i=Object.keys(r||{}),s=Object.getOwnPropertySymbols?Object.getOwnPropertySymbols(r||{}):[],o=Object.getOwnPropertyDescriptors?Object.getOwnPropertyDescriptors(r||{}):{};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 M(){return await this.__connection,this.__user?.service===this.service?this.__user?.owner===this.host:(await ce.bind(this)(),false)}async function G(n=false){let e=null;C&&(n?e=new Promise((r,i)=>{C.globalSignOut({onSuccess:s=>{this.log("globalSignOut:success",s),r(s);},onFailure:s=>{this.log("globalSignOut:error",s),i(s);}});}):C.signOut());let t={session:null,__startKeyHistory:{},__cached_requests:{},__user:null};e&&(e=await e);for(let r in t)this[r]=t[r];return this._runOnUserUpdateListeners(null),this._runOnLoginListeners(null),e}async function ce(n){await this.__connection;let{data:e}=N(n);return await G.bind(this)(e?.global),"SUCCESS: The user has been logged out."}async function ct(){if(!this.__request_signup_confirmation)throw new c("Least one login attempt is required.",{code:"INVALID_REQUEST"});return await w.bind(this)("confirm-signup",{username:this.__request_signup_confirmation})}async function lt(n=false){if(typeof n=="string")n=g.Url(n);else if(typeof n!="boolean")throw new c("Argument should be type: <boolean | string>.",{code:"INVALID_REQUEST"});if(!this.__disabledAccount)throw new c("Least one signin attempt of disabled account is required.",{code:"INVALID_REQUEST"});return await w.bind(this)("recover-account",{username:this.__disabledAccount,redirect:n}),"SUCCESS: Recovery e-mail has been sent."}async function Ce(n){let e=g.Params(n,{username:"string",email:"string",password:"string"},["password"]);if(await this.__authConnection,e.email)try{g.Email(e.email);}catch{e.username=e.email,delete e.email;}if(!e.username&&!e.email)throw new c('Least one of "username" or "email" is required.',{code:"INVALID_PARAMETER"});return await F.bind(this)().authenticateUser(e.username||e.email,e.password)}async function ut(n,e){await this.__authConnection;let t={username:"string",password:d=>g.Password(d),email:d=>g.Email(d),name:"string",address:d=>{if(!d)return "";if(typeof d=="string")return d;if(typeof d=="object")return JSON.stringify(d)},gender:"string",birthdate:d=>d?g.Birthdate(d):"",phone_number:d=>d?g.PhoneNumber(d):"",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:d=>d?g.Url(d):"",profile:d=>d?g.Url(d):"",family_name:"string",given_name:"string",middle_name:"string",nickname:"string",website:d=>d?g.Url(d):""},r=g.Params(n||{},t,["email","password"]);await ce.bind(this)(),e=g.Params(e||{},{email_subscription:d=>{if(typeof d!="boolean")throw new c('"option.email_subscription" should be type: <boolean>.',{code:"INVALID_PARAMETER"});if(!e?.signup_confirmation)throw new c('"option.signup_confirmation" is required for email subscription.',{code:"INVALID_PARAMETER"});return d},signup_confirmation:d=>{let h=d;if(typeof d=="string")h=g.Url(d);else if(typeof d=="boolean")h=d;else throw new c('"option.signup_confirmation" should be type: <string | boolean>.',{code:"INVALID_PARAMETER"});if(h&&!r.email)throw new c('"email" is required for signup confirmation.',{code:"INVALID_PARAMETER"});return h},login:d=>{if(typeof d=="boolean"){if(e.signup_confirmation&&d)throw new c('"login" is not allowed when "option.signup_confirmation" is true.',{code:"INVALID_PARAMETER"});return d}throw new c('"option.login" should be type: boolean.',{code:"INVALID_PARAMETER"})}});let i=e?.login||false;if(r.signup_confirmation=e?.signup_confirmation||false,r.email_subscription=e?.email_subscription||false,r.email_public&&!r.signup_confirmation)throw new c('"option.signup_confirmation" should be true if "email_public" is set to true.',{code:"INVALID_PARAMETER"});r.service=this.service,r.owner=this.owner;let s=F.bind(this)().createCognitoUser(r.username||r.email);for(let d of ["email_public","address_public","gender_public","birthdate_public","phone_number_public"])r[d]=r[d]?"1":"0";r.access_group&&(r.access_group=r.access_group.toString());let o=(await w.bind(this)("signupkey",{username:s.cognitoUsername,signup_confirmation:typeof r.signup_confirmation=="boolean"?JSON.stringify(r.signup_confirmation):r.signup_confirmation,email_subscription:r.email_subscription})).split(":"),a=o.slice(1).join(":"),l=[new CognitoUserAttribute({Name:"custom:signup",Value:o[0]}),new CognitoUserAttribute({Name:"locale",Value:a.split("#")[1]}),new CognitoUserAttribute({Name:"custom:signup_ticket",Value:a})];for(let d in t){let h=["email_public","address_public","gender_public","birthdate_public","phone_number_public","misc","service","owner"];r[d]!==""&&(d==="username"||d==="password"||d==="access_group"||(h.includes(d)?l.push(new CognitoUserAttribute({Name:"custom:"+d,Value:r[d]})):l.push(new CognitoUserAttribute({Name:d,Value:r[d]}))));}return await F.bind(this)().signup(s.cognitoUsername,r.password,l),r.signup_confirmation?(C=s.cognitoUser,this.__request_signup_confirmation=s.cognitoUsername,"SUCCESS: The account has been created. User's signup confirmation is required."):i?Ce.bind(this)({email:r.username||r.email,password:r.password}):"SUCCESS: The account has been created."}async function dt(){await this.__connection;let n=await w.bind(this)("remove-account",{disable:this.__user.user_id},{auth:true});return await ce.bind(this)(),n}async function gt(n){await this.__connection;let e=g.Params(n,{email:i=>g.Email(i),code:["number","string"],new_password:i=>g.Password(i)},["email","code","new_password"]),t=e.code,r=e.new_password;return typeof t=="number"&&(t=t.toString()),new Promise(async(i,s)=>{F.bind(this)().createCognitoUser(e.email).cognitoUser.confirmPassword(t,r,{onSuccess:a=>{i("SUCCESS: New password has been set.");},onFailure:a=>{s(new c(a?.message||"Failed to reset password.",{code:a?.code||"ERROR",cause:a}));}});})}async function ft(n,e){await this.__connection;let t;if(!C)throw new c("The user has to be logged in.",{code:"INVALID_REQUEST"});if(n==="email"||n==="phone_number"){if(!this.__user.hasOwnProperty(n))throw new c(`No ${n==="email"?"e-mail":"phone number"} to verify`,{code:"INVALID_REQUEST"});if(this.__user?.[`${n}_verified`])return `SUCCESS: "${n}" is verified.`;t=(e?g.Params(e,{code:"string"}):{}).code||"";}else return;return new Promise((r,i)=>{let s={onSuccess:o=>{t?F.bind(this)().getSession({refreshToken:true}).then(()=>{this.__user&&(this.__user[n+"_verified"]=true),r(`SUCCESS: "${n}" is verified.`);}).catch(a=>{i(a);}):r("SUCCESS: Verification code has been sent.");},onFailure:o=>{i(new c(o.message||"Failed to request verification code.",{code:o?.code}));}};t?C?.verifyAttribute(n,t,s):(s.inputVerificationCode=null,C?.getAttributeVerificationCode(n,s));})}function ht(n){return ft.bind(this)("phone_number",n)}function pt(n){return ft.bind(this)("email",n)}async function mt(n){await this.__connection;let e=g.Params(n,{email:t=>g.Email(t)},["email"]);return new Promise(async(t,r)=>{F.bind(this)().createCognitoUser(e.email).cognitoUser.forgotPassword({onSuccess:s=>{t("SUCCESS: Verification code has been sent.");},onFailure:s=>{let{parsed:o,code:a}=be(s),l={UserNotFoundException:"NOT_EXISTS",InvalidParameterException:"INVALID_PARAMETER",NotAuthorizedException:"INVALID_REQUEST",LimitExceededException:"REQUEST_EXCEED",TooManyRequestsException:"REQUEST_EXCEED",CodeDeliveryFailureException:"CODE_DELIVERY_FAILURE"}[a]||o.code||a||"ERROR";r(new c(o.message,{code:l,cause:s}));}});})}async function _t(n){if(await this.__connection,!this.session)throw new c("User login is required.",{code:"INVALID_REQUEST"});let e=g.Params(n,{current_password:"string",new_password:"string"});if(!e?.current_password)throw new c('"current_password" is required to change password.',{code:"INVALID_PARAMETER"});if(!e?.new_password)throw new c('"new_password" is required to change password.',{code:"INVALID_PARAMETER"});return g.Password(e.current_password),g.Password(e.new_password),new Promise((t,r)=>{C.changePassword(e.current_password,e.new_password,(i,s)=>{if(i){if(i?.code==="InvalidParameterException")r(new c("Invalid password parameter.",{code:"INVALID_PARAMETER"}));else if(i?.code==="NotAuthorizedException")r(new c("Incorrect password.",{code:"INVALID_REQUEST"}));else if(i?.code==="TooManyRequestsException"||i?.code==="LimitExceededException")r(new c("Too many attempts. Please try again later.",{code:"REQUEST_EXCEED"}));else {let{parsed:o}=be(i);r(o);}return}t("SUCCESS: Password has been changed.");});})}async function bt(n){if(await this.__connection,!this.session)throw new c("User login is required.",{code:"INVALID_REQUEST"});let e=g.Params(n||{},{user_id:i=>g.UserId(i),email:i=>g.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?g.Birthdate(i):"",phone_number:i=>i?g.PhoneNumber(i):"",email_public:"boolean",phone_number_public:"boolean",address_public:"boolean",gender_public:"boolean",birthdate_public:"boolean",misc:"string",picture:i=>i?g.Url(i):"",profile:i=>i?g.Url(i):"",family_name:"string",given_name:"string",middle_name:"string",nickname:"string",website:i=>i?g.Url(i):""});if(e&&typeof e=="object"&&!Object.keys(e).length)return this.user;e.email&&(e.preferred_username=this.service+"-"+V.hash(e.email));let t=[["email_public","email_verified","User's e-mail should be verified to set"],["phone_number_public","phone_number_verified","User's phone number should be verified to set"]];if(this.__user){for(let i of t)if(e[i[0]]&&!this.__user[i[1]])throw new c(`${i[2]} "${i[0]}" to true.`,{code:"INVALID_REQUEST"})}let r=[];for(let i in e){if(e[i]===this.user[i]){r.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,r.push(i);}}for(let i of r)delete e[i];if(e.user_id)if(e.user_id===this.user.user_id)delete e.user_id;else return w.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 CognitoUserAttribute({Name:s,Value:e[s]}));return await new Promise((s,o)=>{C?.updateAttributes(i,(a,l)=>{a&&o([a?.code||a?.name,a?.message||"Failed to update user settings."]),s(l);});}),await F.bind(this)().getSession({refreshToken:true}),this.user}return this.user}async function yt(n,e){n=N(n).data,n||(n={searchFor:"timestamp",condition:">",value:0},e||(e={}),e.ascending=false),await this.__connection;let t={user_id:i=>Array.isArray(i)?i.map(s=>g.UserId(s)):g.UserId(i),email:"string",phone_number:"string",locale:i=>{if(typeof i!="string"||typeof i=="string"&&i.length>5)throw new c('Value of "locale" should be a country code.',{code:"INVALID_PARAMETER"});return i},name:"string",address:"string",gender:"string",birthdate:i=>g.Birthdate(i),subscribers:"number",timestamp:"number",access_group:"number",approved:"string"},r=["searchFor","value"];if(n=g.Params(n,{searchFor:["user_id","name","email","phone_number","address","gender","birthdate","locale","subscribers","timestamp","access_group","approved"],condition:[">",">=","=","<","<=","gt","gte","eq","lt","lte",()=>"="],value:i=>{let s=t[n.searchFor];if(typeof s=="function")return s(i);if(typeof i!==s)throw new c(`Value does not match the type of "${n.searchFor}" index.`,{code:"INVALID_PARAMETER"});return i},range:i=>{let s=t[n.searchFor];if(typeof s=="function")return s(i);if(typeof i!==s)throw new c(`Range does not match the type of "${n.searchFor}" index.`,{code:"INVALID_PARAMETER"});return i}},r),n?.condition&&n?.condition!=="="&&n.hasOwnProperty("range"))throw new c("Conditions does not apply on range search.",{code:"INVALID_PARAMETER"});if(n.searchFor==="user_id"&&(n.condition!=="="||n.range))throw new c(`Conditions are not allowed on "${n.searchFor}"`,{code:"INVALID_PARAMETER"});if(typeof n?.value=="string"&&!n?.value)throw new c("Value should not be an empty string.",{code:"INVALID_PARAMETER"});if(typeof n?.searchFor=="string"&&!n?.searchFor)throw new c('"searchFor" should not be an empty string.',{code:"INVALID_PARAMETER"});return w.bind(this)("get-users",n,{auth:true,fetchOptions:e})}async function wt(n){await this.__connection;let e=await w.bind(this)("last-verified-email",n,{auth:true});return e.includes("SUCCESS")?(await F.bind(this)().getSession({refreshToken:true}),this.user):e}async function Et(n){return await this.__connection,n=g.Params(n,{username:g.Email,redirect:g.Url},["username"]),await w.bind(this)("request-username-change",n,{auth:true})}var re=null,At=typeof SubmitEvent<"u",br=typeof HTMLFormElement<"u",ue=$(),Le=0;function It(n){if(!n)return null;let e=Number(n);if(Number.isFinite(e))return Math.max(0,e*1e3);let t=Date.parse(n);return Number.isNaN(t)?null:Math.max(0,t-Date.now())}function Oe(n,e){return e>0?n/e*100:0}var Rt=n=>{let{auth:e,type:t,endpoints:r}=n,i=r[0],s=r[1];if(Le++,t==="admin"){let o=Object.entries(i).filter(([a,l])=>a.includes(e?"_private":"_public")&&a!=="get_users_private"&&a!=="service_public"&&typeof l=="string").map(([,a])=>a);if(!o.length)throw new c("No available admin gateways.",{code:"INVALID_REQUEST"});return o[Le%o.length]}if(t==="record"){let o=Object.entries(s).filter(([a,l])=>a.includes(e?"record_private":"record_public")&&typeof l=="string").map(([,a])=>a);if(!o.length)throw new c("No available record gateways.",{code:"INVALID_REQUEST"});return o[Le%o.length]}throw new c("Invalid gateway type.",{code:"INVALID_REQUEST"})};async function yr(n,e){let t=await Promise.all([this.admin_endpoint,this.record_endpoint]),r=t[0],i=t[1],s=n.split("?"),o=s.length>1?"?"+s[1]:"";switch(n=s[0],n){case "get-users":return r.get_users_private+n+o;case "service":return r.service_public+n+o;case "get-newsletters":case "get-public-newsletters":case "subscribe-newsletter":case "subscribe-public-newsletter":case "signupkey":case "admin-newsletter-request":case "admin-signup":case "confirm-signup":case "openid-logger":case "block-account":case "admin-edit-profile":case "remove-account":case "post-secure":case "recover-account":case "mock":case "grant-access":case "last-verified-email":case "ticket":case "register-ticket":case "get-newsletter-subscription":case "request-username-change":case "send-inquiry":case "register-newsletter-group":case "newsletter-group-endpoint":case "invitation-list":case "csr":case "csr-poll":return Rt.bind(this)({auth:e,type:"admin",endpoints:t})+n+o;case "post-record":return (e?i.post_private:i.post_public)+n+o;case "get-records":return (e?i.get_private:i.get_public)+n+o;case "del-files":case "del-records":return i.del_private+n+o;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 "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 Rt.bind(this)({auth:e,type:"record",endpoints:t})+n+o;default:return g.Url(n)+o}}var le={};function Tt(){re&&(re.terminate(),re=null);}async function w(n,e=null,t,r){this.log("request",{url:n,data:e,options:t,_etc:r||{}}),t=t||{};let{auth:i=false,method:s="post",bypassAwaitConnection:o=false}=t;s=s.toUpperCase();let a=null,l=e?.service||this.service,d=e?.owner||this.owner,h=null,u=await yr.bind(this)(n,!!i);if(!o&&(a=await this.__connection,!a))throw new c("Invalid connection. The service could have been disabled, or has a restricted CORS.",{code:"INVALID_REQUEST"});let m=t?.tokenHeaders?.idToken===true;(i||m)&&(h=await ne.bind(this)());let R={},{fetchMore:f=false,progress:A}=t?.fetchOptions||{};if(t?.fetchOptions&&Object.keys(t.fetchOptions).length){for(let S of ["limit","startKey","ascending"])if(t.fetchOptions.hasOwnProperty(S)){if(S==="startKey"&&t.fetchOptions[S]===null)continue;R[S]=t.fetchOptions[S];}R=g.Params(R,{limit:S=>{if(typeof S!="number")throw new c("Fetch limit should be a number.",{code:"INVALID_REQUEST"});if(S>1e3)throw new c("Fetch limit should be below 1000.",{code:"INVALID_REQUEST"});return S},startKey:S=>S,ascending:"boolean"});}let P=r?.ignoreService?{}:{service:l,owner:d};Object.assign(P,R),e=N(e).data,e?e&&typeof e=="object"&&(e=Object.assign(P,e)):e=P;let _=`${s}:${i?"auth":"public"}:${n}`,x=(()=>{if(e&&typeof e=="object"&&Object.keys(e).length&&!(ue&&e instanceof FormData)){let S=function(D){return typeof D=="object"&&D!==null?Object.keys(D).sort().reduce((U,L)=>(typeof D[L]=="object"&&D[L]!==null?U[L]=S(D[L]):U[L]=D[L],U),{}):D};return V.hash(_+"/"+JSON.stringify(S(e)))}return V.hash(_+"/"+l)})(),{requestKey:k,requestKeyWithStartKey:T}=wr.bind(this)({params:e,url:n,fetchMore:f,hashedParams:x});if(!k||k&&typeof k=="object")return k;if(this.log("requestKey",T),typeof T=="string"&&le[T]instanceof Promise)return this.log("request:returning pending",T),le[T];let v={Accept:"*/*"};if(Object.prototype.hasOwnProperty.call(t,"contentType")&&t.contentType!==void 0){let S=t.contentType===null?"application/x-www-form-urlencoded":t.contentType;S&&(v["Content-Type"]=S);}else v["Content-Type"]="application/json";if(h&&(v.Authorization=h),t?.tokenHeaders){let S=(L,On)=>typeof L=="string"?L:L===true?On:null,D=S(t.tokenHeaders.accessToken,this.session?.accessToken?.jwtToken||null),U=S(t.tokenHeaders.idToken,this.bearerToken||this.session?.idToken?.jwtToken||h||null);D&&(v["X-Access-Token"]=D),U&&(v["X-Id-Token"]=U);}let xe={public_identifier:this.__public_identifier,service:l,owner:d};v["Content-Meta"]=JSON.stringify(xe);let q={headers:v};if(t?.responseType&&(q.responseType=t.responseType),s==="GET"){if(e){let S=[];if(ue&&e instanceof FormData?S=Array.from(e.entries()).map(([D,U])=>{let L=typeof U=="string"?U:U.name;return encodeURIComponent(D)+"="+encodeURIComponent(L)}):S=Object.keys(e).map(D=>{let U=e[D];return typeof U!="string"&&(U=JSON.stringify(U)),encodeURIComponent(D)+"="+encodeURIComponent(U)}),S.length){let D=u.includes("?")?u.endsWith("?")||u.endsWith("&")?"":"&":"?";u+=D+S.join("&");}}q.body=null;}else if(ue&&e instanceof FormData)q.body=e;else if(v["Content-Type"]==="application/x-www-form-urlencoded"&&e&&typeof e=="object"){let S=new URLSearchParams;for(let D of Object.keys(e)){let U=e[D];S.append(D,typeof U=="string"?U:JSON.stringify(U));}q.body=S.toString();}else typeof e=="string"?q.body=e:q.body=e?JSON.stringify(e):null;if(q.method=s,re===null){let S={batchSize:this.requestBatchSize,breakWhenError:false,onProgress:D=>{this.onBatchProcess.forEach(U=>U(D));}};re=new _r(S);}return this.log("request-opt",q),new Promise((S,D)=>{re.add([async()=>{let U=Pt.bind(this)(u,q,A);le[T]=U;try{let L=Er.bind(this)({hashedParam:k,requestKeyWithStartKey:T,url:n,fetched:await U});return delete le[T],this.log("request:end",L),S(L),L}catch(L){throw delete le[T],this.log("request:err",L),D(L),L}}]);})}function wr(n){let{params:e={},url:t,fetchMore:r=false,hashedParams:i}=n||{};if(e.startKey){if(!(typeof e.startKey=="object"&&Object.keys(e.startKey).length)&&e.startKey!=="start"&&e.startKey!=="end")throw new c(`"${e.startKey}" is invalid startKey key.`,{code:"INVALID_PARAMETER"});e.startKey==="start"&&(r=false,delete e.startKey);}if(!r){if(this.__cached_requests?.[t]?.[i]&&delete this.__cached_requests[t][i],this.__startKeyHistory?.[t]?.[i]){if(Array.isArray(this.__startKeyHistory[t][i])&&this.__startKeyHistory[t][i].length)for(let l of this.__startKeyHistory[t][i]){let d=i+V.hash(l);this.__cached_requests?.[t]&&this.__cached_requests?.[t]?.[d]&&delete this.__cached_requests[t][d];}delete this.__startKeyHistory[t][i];}return {requestKeyWithStartKey:i,requestKey:i}}if(!Array.isArray(this.__startKeyHistory?.[t]?.[i]))return {requestKeyWithStartKey:i,requestKey:i};let s=this.__startKeyHistory[t][i],o=s[s.length-1],a=i;if(o){if(o==="end")return {requestKey:{list:[],startKey:"end",endOfList:true,startKeyHistory:s},requestKeyWithStartKey:a};a+=V.hash(o),e.startKey=JSON.parse(o);}return this.__cached_requests?.[t]?.[a]?{requestKey:this.__cached_requests[t][a],requestKeyWithStartKey:a}:{requestKeyWithStartKey:a,requestKey:i}}function Pt(n,e,t){return new Promise((r,i)=>{let s=new XMLHttpRequest;s.open(e.method||"GET",n);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")r(s.response);else {let a=s.responseText;try{a=JSON.parse(a);}catch{}r(a);}else if(s.status===429){let a=s.getResponseHeader("Retry-After"),l=It(a);l!==null?setTimeout(()=>{Pt(n,e,t).then(r,i);},l):i("Too many requests");}else {let a=s.status,l=["INVALID_CORS","INVALID_REQUEST","SERVICE_DISABLED","INVALID_PARAMETER","ERROR","EXISTS","NOT_EXISTS"],d=e.responseType=="blob"?s.response:s.responseText;try{d=JSON.parse(d);}catch{}if(typeof d=="string"){let h=d.split(":"),u=h.splice(0,1)[0].trim(),m=h.join(":").trim();i(new c(m||d,{code:l.includes(u)?u:"ERROR"}));}else if(typeof d=="object"&&d?.message){let h=d?.code||(a?a.toString():null)||"ERROR",u=d.message,m=d?.cause;typeof u=="string"&&(u=u.trim()),i(new c(u,{cause:m,code:h}));}else i(d);}},s.onerror=()=>i("Network error"),s.onabort=()=>i("Aborted"),s.ontimeout=()=>i("Timeout"),typeof t=="function"&&(s.onprogress=a=>{t({status:"download",progress:Oe(a.loaded,a.total),loaded:a.loaded,total:a.total,abort:()=>s.abort()});},s.upload&&(s.upload.onprogress=a=>{t({status:"upload",progress:Oe(a.loaded,a.total),loaded:a.loaded,total:a.total,abort:()=>s.abort()});})),s.send(e.body);})}function Er(n){let{hashedParam:e,requestKeyWithStartKey:t,url:r,fetched:i}=n;if(!i?.startKey)return i;this.__startKeyHistory.hasOwnProperty(r)||(this.__startKeyHistory[r]={}),this.__startKeyHistory[r].hasOwnProperty(e)||(this.__startKeyHistory[r][e]=[]);let s=i.startKey==="end"?"end":JSON.stringify(i.startKey);return this.__startKeyHistory[r][e].includes(s)||this.__startKeyHistory[r][e].push(s),this.__cached_requests?.[r]||(this.__cached_requests[r]={}),this.__cached_requests[r][t]=i,Object.assign({startKeyHistory:this.__startKeyHistory[r][e]},i)}async function we(n,e){await this.__connection;let{record_id:t,service:r=this.service,progress:i}=e;if(!t)throw new c('"record_id" is required.',{code:"INVALID_PARAMETER"});if(At&&n instanceof SubmitEvent&&(n=n.target),br&&n instanceof HTMLFormElement&&(n=new FormData(n)),!ue||!(n instanceof FormData))throw new c('"fileList" should be a FormData or HTMLFormElement.',{code:"INVALID_PARAMETER"});let o={reserved_key:oe(),service:r,request:"post"};e?.record_id&&(o.id=e.record_id);let a,l=(R,f,A)=>new Promise((P,_)=>{a=new XMLHttpRequest,a.open("POST",R),a.onload=()=>{let x=a.responseText;try{x=JSON.parse(x);}catch{}if(a.status>=200&&a.status<300)P(x);else if(a.status===429){let k=a.getResponseHeader("Retry-After"),T=It(k);T!==null?setTimeout(()=>{l(R,f,A).then(P,_);},T):_("Too many requests");}else _(x);},a.onerror=()=>_("Network error"),a.onabort=()=>_("Aborted"),a.ontimeout=()=>_("Timeout"),a.upload&&typeof A=="function"&&(a.upload.onprogress=A),a.send(f);});function d(R){let f="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";if(R===0)return f[0];let A="";for(;R>0;)A=f[R%62]+A,R=Math.floor(R/62);return A}let h=[],u=[],m=[];for(let[R,f]of n.entries()){if(!(f instanceof File))continue;let A=Object.assign({key:R+"/"+f.name,sizeKey:d(f.size),contentType:f.type||null},o),{fields:P=null,url:_,cdn:x}=await w.bind(this)("get-signed-url",A,{auth:!!this.__user});m.push(x);let k=new FormData;for(let T in P)k.append(T,P[T]);k.append("file",f);try{await l(_,k,typeof i=="function"?T=>i({status:"upload",progress:Oe(T.loaded,T.total),currentFile:f,completed:h,failed:u,loaded:T.loaded,total:T.total,abort:()=>a.abort()}):null),h.push(f);}catch{u.push(f);}}return {completed:h,failed:u,bin_endpoints:m}}var ye={};function E(n){let{preventMultipleCalls:e=false}=n||{};return function(t,r,i){let s=i.value;i.value=function(...o){let a=o[0],l=true,d=null,h="",u={},m=false;if(At&&a instanceof SubmitEvent){a.preventDefault();let _=window.location.href;d=a.target;let x=new URL(d.action);h=x.href;let k=h?h.match(/(?<=\{).*?(?=\})/g):"";if(k)for(let T of k){if(!T)continue;let v=d.querySelector(`[name="${T}"]`);if(v)if(v.type==="file")for(let Q=0;Q<=v.files.length-1;Q++)v.files[Q]&&(u[T]||(u[T]=[]),u[T].push(new Promise((xe,q)=>{let S=new FileReader;S.onload=function(){xe(S.result);},S.readAsDataURL(v.files[Q]),S.onerror=q;})));else h=h.replace(`{${T}}`,v.value);}d.getAttribute("action")===null?l=false:m=x.href===_;}let R=async _=>{if(h)for(let x in u)u[x].length&&(h=h.replace(`{${x}}`,(await Promise.all(u[x])).join(",")));return d&&l&&(window.sessionStorage.setItem(`${this.service}:${V.hash(h)}`,JSON.stringify(_)),m?window.location.replace(h):window.location.href=h),_},f,A=_=>{throw _ instanceof c?_.name=r+"()":_=_ instanceof Error?_:new c(_,{name:r+"()"}),_},P=async()=>{try{if(f=s.bind(this)(...o),f instanceof Promise){let _=await f;return R(_)}return R(f)}catch(_){throw A(_)}};if(e){let _=`${r}:${this?.__public_identifier||""}:${this?.service||""}:${this?.owner||""}`;return ye?.[_]||(ye[_]=P().finally(()=>{delete ye[_];})),ye[_]}return P()};}}async function St(){await this.__connection;let n=`${this.service}:${V.hash(window.location.href.split("?")[0])}`,e=window.sessionStorage.getItem(n);if(window.sessionStorage.removeItem(n),e!==null){try{e=JSON.parse(e);}catch{}return e}return null}var Rr=128,Ar=64,Ir=128,Tr=256,Pr="\u{10FFFF}",Sr=/[\u0000-\u001F\u007F]|\u{10FFFF}/u,kr=/[\/!*#]/;function X(n,e,t={}){let{allowEmpty:r=false,maxLength:i,blockKeyDelimiters:s=false,disallowLeadingDollar:o=false,onlyAlphanumeric:a=false}=t;if(typeof n!="string")throw new c(`"${e}" should be type: <string>.`,{code:"INVALID_PARAMETER"});if(a&&/[^a-zA-Z0-9]/.test(n))throw new c(`"${e}" should only contain alphanumeric characters.`,{code:"INVALID_PARAMETER"});if(!r&&n.length===0)throw new c(`"${e}" is required.`,{code:"INVALID_PARAMETER"});if(i&&n.length>i)throw new c(`"${e}" should be <= ${i} characters.`,{code:"INVALID_PARAMETER"});if(Sr.test(n)||n.includes(Pr))throw new c(`"${e}" cannot include control characters or unsupported sentinel characters.`,{code:"INVALID_PARAMETER"});if(s&&kr.test(n))throw new c(`"${e}" cannot include reserved delimiters: / ! * #`,{code:"INVALID_PARAMETER"});if(o&&n.startsWith("$"))throw new c(`"${e}" cannot start with "$".`,{code:"INVALID_PARAMETER"});return n}function Fe(n,e="table.name"){return X(n,e,{allowEmpty:false,maxLength:Rr,blockKeyDelimiters:true})}function Me(n,e="tag"){return X(n,e,{allowEmpty:false,maxLength:Ar,blockKeyDelimiters:true})}function de(n,e="index.name"){return X(n,e,{allowEmpty:false,maxLength:Ir,blockKeyDelimiters:true,disallowLeadingDollar:true})}function kt(n,e="index.value"){return X(n,e,{allowEmpty:true,maxLength:Tr})}function xt(n){if(!n.record_id&&!n.unique_id)return null;let e={};return n?.service&&(e.service=n.service),n?.owner&&(e.owner=n.owner),n?.record_id?e.record_id=X(n.record_id,"record_id",{allowEmpty:false,onlyAlphanumeric:true}):n?.unique_id&&(e.unique_id=n.unique_id),e}function Ve(n){if(n===void 0)return 0;if(typeof n=="number"){if(n>99||n<0)throw new c('"table.access_group" value should be within a range of 0 ~ 99.',{code:"INVALID_REQUEST"})}else if(typeof n=="string"){if(n={private:"private",public:0,authorized:1,admin:99}[n],n===void 0)throw new c('"table.access_group" is invalid.',{code:"INVALID_PARAMETER"})}else throw new c('"table.access_group" should be type: <number | string>.',{code:"INVALID_PARAMETER"});if(!this.__user&&n)throw new c("Unsigned users have no access to records with access group.",{code:"INVALID_REQUEST"});return n}var Ee=4503599627370496;function Re(n){if(typeof n=="number"){if(n>Ee||n<-Ee)throw new c(`Number value should be within range -${Ee} ~ +${Ee}`,{code:"INVALID_PARAMETER"});return n}if(typeof n=="boolean")return n;if(typeof n=="string")return kt(n,"index.value");throw new c('"index.value" should be type: <number | boolean | string>.',{code:"INVALID_PARAMETER"})}function vt(n,e){if(!e.index||!("value"in e.index))throw new c('"index.value" is required.',{code:"INVALID_PARAMETER"});if(e.index.name==="$record_id")throw new c(`Cannot do "index.range" on ${e.index.name}`,{code:"INVALID_PARAMETER"});if(typeof e.index.value!=typeof n)throw new c('"index.range" type should match the type of "index.value".',{code:"INVALID_PARAMETER"});return typeof n=="string"?kt(n,"index.range"):n}var Ae={};async function ie(n,e){let t={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:{}},r=false;function i(o){let a=o=="**"?"private":parseInt(o);return a=a==0?"public":a==1?"authorized":a==99?"admin":a,a}let s={ip:o=>{let a=o.split("#"),l=a[0];a.length>1&&(t.unique_id=a[1]),l.slice(-1)==="R"?(t.readonly=true,l=l.slice(0,-1)):t.readonly=false,/^\d{1,3}-\d{1,3}-\d{1,3}-\d{1,3}$/.test(l)&&(l=l.split("-").join("."),r=true),t.ip=l;},rec:o=>{if(!o)return;t.record_id=o;let a=o.substring(0,o.length-9),l=j(a);t.uploaded=l;},usr:o=>{t.user_id=o;},tbl:o=>{if(o&&!t.table.name){let a=o.split("/");t.table.name=a[0],t.table.access_group=i(a[2]),a?.[3]&&(t.table.subscription.is_subscription_record=true);}},usr_tbl:o=>{let a=o.split("/");t.user_id||(t.user_id=a[0]),t.table.name||(t.table.name=a[1],t.table.access_group=i(a[3]),a?.[4]&&(t.table.subscription.is_subscription_record=true));},idx:o=>{if(!o)return;let a=o.split("!"),l=a.splice(0,1)[0],d=xr("!"+a.join("!"));t.index={name:l,value:d};},ref:o=>{o&&(t.reference=o.split("/")[0]);},tags:o=>{t.tags=o;},upd:o=>{t.updated=o;},acpt_mrf:o=>{t.source.prevent_multiple_referencing=!o;},ref_limt:o=>{t.source.referencing_limit=o;},rfd:o=>{t.referenced_count=o;},bin:async o=>{let a={},l=t?.reference||null;if(Array.isArray(o)){let d=await Promise.all(o.map(async h=>{try{let u=h.split("/").slice(3).join("/"),m=u.split("/");if(m.length<12)return null;let R=decodeURIComponent(m[m.length-1]),f=decodeURIComponent(m[10]),A=m[9],P=m[8],_=i(m[6]),x=h;if(_!=="public")try{x=await Ie.bind(this)(h,{dataType:"endpoint",_ref:l});}catch(T){console.error("Error getting signed url for private file:",T),x=h;}let k={access_group:_,filename:R,url:x,path:u,size:j(A),uploaded:j(P),getFile:(T,v)=>{let Q={dataType:T||"download",progress:v,_ref:l,_update:k};return Ie.bind(this)(x,Q)}};return {pathKey:f,obj:k}}catch{return null}}));for(let h of d)if(h){if(a[h.pathKey]){a[h.pathKey].push(h.obj);continue}a[h.pathKey]=[h.obj];}}t.bin=a;},prv_acs:o=>{for(let a in o)["notify_subscribers","upload_to_feed","feed_referencing_records","notify_referencing_records"].includes(a)?t.table.subscription[a]=o[a]:t.source[a]=o[a];},data:o=>{let a=o;o==="!D%{}"?a={}:o==="!L%[]"&&(a=[]),t.data=a;}};if(n.record_id)return n;for(let o in s)if(n.hasOwnProperty(o)){let a=s[o](n[o]);a instanceof Promise&&await a;}return r&&(t.user_id="anonymous:"+t.user_id),t}function xr(n){let e=n.substring(3);switch(n.substring(0,3)){case "!S%":return e;case "!N%":let r=e.split("."),i=Number(r[0])-4503599627370496;return r.length===1?i:parseFloat(i.toString()+"."+r[1]);case "!B%":return e==="1";case "!L%":case "!D%":try{return JSON.parse(e)}catch{throw new c("Value parse error.",{code:"PARSE_ERROR"})}default:return n}}async function Dt(n){let{endpoints:e}=n;if(typeof e=="string"&&(e=[e]),!Array.isArray(e))throw new c('"endpoints" should be type: array | string.',{code:"INVALID_PARAMETER"});let t=await w.bind(this)("del-files",{endpoints:e,storage:"records"},{auth:true,method:"post"}),r=[];for(let i in t)r.push(ie.bind(this)(t[i]));return Promise.all(r)}async function Ie(n,e){if(typeof n!="string")throw new c('"url" should be type: string.',{code:"INVALID_PARAMETER"});let t=n.split("?"),r=t.shift()||"",i=t.length?"?"+t.join("?"):"",s=g.Url(r);n=s+i;let o=false,a=s.split("/"),d=a[2].split("."),h=null;d.length===3&&d[1]==="skapi"&&(h=d[0],o=true);let u=a.slice(3),m=false;if(!o&&(u[0]==="auth"||u[0]==="publ"))try{g.UserId(u[2]),g.UserId(u[3]),m=u[0]=="auth",o=!0;}catch{throw new c("Invalid file url.",{code:"INVALID_PARAMETER"})}let R=h?null:u[1];if(e=g.Params(e,{expires:["number",()=>0],dataType:["base64","blob","endpoint","text","info",()=>"download"],progress:"function",_ref:[null,"string"],_update:_=>_}),e?.dataType==="info")return {url:n,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:j(u[9]),uploaded:j(u[8])};let f=n.split("/").slice(-1)[0],A=e.expires;if(A){if(!o)throw new c("Expires option can only be used on skapi cdn endpoints.",{code:"INVALID_PARAMETER"});if(A<0)throw new c('"config.expires" should be > 0. (seconds)',{code:"INVALID_PARAMETER"});let _={request:h?"get-host":"get",id:h||u[5],key:n,expires:A};R&&(_.service=R),n=(await w.bind(this)("get-signed-url",_,{auth:true})).url;}else if(m){let _=Math.floor(Date.now()/1e3);if(!this.bearerToken&&(!this.session?.idToken?.payload?.exp||this.session.idToken.payload.exp<_)){this.log("getFile:requesting new token",null);try{await F.bind(this)().getSession({refreshToken:!0}),this.log("getFile:received new tokens",{exp:this.session?.idToken?.payload?.exp,currTime:_,expiresIn:this.session?.idToken?.payload?.exp-_,token:this.session?.accessToken?.jwtToken,refreshToken:this.session?.refreshToken?.token});}catch(v){throw this.log("getFile:new token error",v),new c("User login is required.",{code:"INVALID_REQUEST"})}}let x=this.bearerToken||this.session?.idToken?.jwtToken;if(!x||!this.user?.user_id)throw new c("User login is required.",{code:"INVALID_REQUEST"});n+=`${n.includes("?")?"&":"?"}t=${encodeURIComponent(x)}`;let k=u[6]==="**"?"**":parseInt(u[6]),T=this.user?.access_group??-1;if(this.user.user_id!==u[3]&&(k==="**"||T<k)){let v=u[5];if(this.__private_access_key[v]&&typeof this.__private_access_key[v]=="string")n+=`&p=${encodeURIComponent(this.__private_access_key[v])}`;else if(this.owner!==this.host)try{let Q=await this.requestPrivateRecordAccessKey({record_id:v,reference_id:e?._ref});n+=`&p=${encodeURIComponent(Q)}`;}catch{}}}if(e?.dataType==="endpoint")return e._update&&(e._update.url=n),n;if(e?.dataType==="download"){let _=document.createElement("a");return _.href=n,document.body.appendChild(_),_.setAttribute("download",f),_.target="_blank",_.click(),document.body.removeChild(_),null}return new Promise(async(_,x)=>{try{let k=await w.bind(this)(n,null,{method:"get",contentType:null,responseType:e?.dataType==="text"?"text":"blob",fetchOptions:{progress:e?.progress}},{ignoreService:!0});if(e?.dataType==="base64"){let T=new FileReader;T.onloadend=()=>_(T.result),T.readAsDataURL(k);}else _(k);}catch(k){x(k);}})}async function Ut(n,e=false){n=N(n,{ignoreEmpty:true}).data||{};let t="",r=xt(n);if(r)n=r,t=n.record_id||n.unique_id,typeof t=="string"&&(typeof this.__private_access_key?.[t]=="string"&&(n.private_key=this.__private_access_key?.[t]||void 0),this.__my_unique_ids[t]&&(e?delete this.__my_unique_ids[t]:n.record_id=this.__my_unique_ids[t]));else {let i=await M.bind(this)(),s=n?.reference,o=false;typeof s=="object"&&Object.keys(s).length&&(s?.record_id||s?.unique_id?(t=s.record_id||s.unique_id,t&&typeof this.__private_access_key?.[t]=="string"&&(n.private_key=this.__private_access_key?.[t]||void 0),n.reference=t):s?.user_id&&(o=s.user_id===this.user?.user_id,n.reference=s.user_id)),typeof n?.table=="string"&&(n.table={name:n.table,access_group:0}),n.index&&n.index.hasOwnProperty("range")&&n.index.hasOwnProperty("condition")&&delete n.index.range;let a=l=>({table:{name:d=>Fe(d,"table.name"),access_group:Ve.bind(this),subscription:d=>g.UserId(d,'User ID in "subscription"')},reference:"string",index:{name:["$updated","$uploaded","$referenced_count","$user_id",d=>de(d,"index.name")],value:d=>{let h={$updated:"number",$uploaded:"number",$referenced_count:"number",$user_id:g.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 c(`"index.value" should be type: ${u}.`,{code:"INVALID_PARAMETER"});return d}return typeof d=="string"&&!d?"":Re(d)},condition:["gt","gte","lt","lte",">",">=","<","<=","=","eq"],range:d=>vt(d,l)},tag:d=>{if(d==null)return d;if(typeof d=="string")return Me(d,"tag");throw new c('"tag" should be type: string.',{code:"INVALID_PARAMETER"})},private_key:"string"});n=g.Params(n||{},a(n),o||i?[]:["table"],{ignoreEmpty:true});}return {query:n,is_reference_fetch:t}}async function Nt(n,e){await this.__connection;let t=await Ut.bind(this)(n),r=t.is_reference_fetch,i=await w.bind(this)("get-records",t.query,{fetchOptions:e,auth:!!this.__user,method:this.__user?"post":"get"});r&&i?.reference_private_key&&typeof i.reference_private_key=="string"&&(this.__private_access_key[r]=i.reference_private_key);let s=[];for(let o in i.list)s.push(ie.bind(this)(i.list[o]));return i.list=await Promise.all(s),i}function Ct(n){let e="",t=[],r=g.Params(n||{},{record_id:s=>X(s,"record_id",{allowEmpty:false,onlyAlphanumeric:true}),unique_id:["string",null],readonly:"boolean",table:{name:s=>Fe(s,"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:Ve.bind(this)},source:{referencing_limit:s=>{if(s===null)return null;if(typeof s=="number"){if(0>s)throw new c('"reference_limit" should be >= 0',{code:"INVALID_PARAMETER"});if(s>4503599627370546)throw new c('"reference_limit" should be <= 4503599627370546',{code:"INVALID_PARAMETER"});return s}throw new c('"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:s=>{if(s===void 0)return;if(!s||Array.isArray(s)&&!s.length)return null;let o={name:l=>de(l,'"name" in "index_restrictions"'),value:l=>Re(l),condition:["gt","gte","lt","lte",">",">=","<","<=","=","eq","!=","ne",()=>null],range:l=>{if(l!==null&&typeof s.value!=typeof l)throw new c('Index restriction "range" type should match the type of "value".',{code:"INVALID_PARAMETER"});if(!s.hasOwnProperty("value"))throw new c('Index restriction "value" is required.',{code:"INVALID_PARAMETER"});return l}};Array.isArray(s)||(s=[s]);let a=s.map(l=>g.Params(l,o,["name"]));if(a.length)for(let l of a)l.condition&&l.hasOwnProperty("range")&&delete l.range;return a}},reference:s=>{if(s===null)return {record_id:null};if(s){if(typeof s=="string")return e=s,this.__my_unique_ids[s]?this.__my_unique_ids[s]:s;if(typeof s!="object")throw new c('"reference" should be type: <string | object>.',{code:"INVALID_PARAMETER"});return g.Params(s,{unique_id:"string",record_id:o=>o==null?o:(e=o,typeof this.__private_access_key?.[o]=="string"&&(n.reference_private_key=this.__private_access_key[o]||void 0),X(o,"reference.record_id",{allowEmpty:false,onlyAlphanumeric:true}))})}},index:[null,{name:s=>de(s,"index.name"),value:s=>Re(s)}],tags:s=>{if(s==null)return s;if(typeof s=="string"&&(s=s.split(",").map(o=>o.trim())),!Array.isArray(s))throw new c('"tag" should be type: <string | string[]>.',{code:"INVALID_PARAMETER"});return s.map(o=>Me(o,"tag"))},remove_bin:s=>{if(!s)return null;let o=[];if(Array.isArray(s))for(let a of s)if(typeof a=="string")o.push(decodeURIComponent(a.split("?")[0]));else if(a.url&&a.size&&a.filename){let d=a.url.split("/").slice(0,3).join("/")+"/"+a.path;o.push(d);}else throw new c('"remove_bin" should be type: <string[] | BinaryFile[] | null>',{code:"INVALID_PARAMETER"});else throw new c('"remove_bin" should be type: <string[] | BinaryFile[] | null>',{code:"INVALID_PARAMETER"});return o},progress:"function",data:s=>s},[],{precall:s=>{let o=s?.data||{};if(!o?.record_id&&!o.table)throw new c('"table.name" is required.',{code:"INVALID_PARAMETER"});typeof o.table=="string"&&(o.table={name:o.table,access_group:0}),s.files&&(t=s.files);}}),i=n.progress||null;if(delete r.progress,!this.__user){let s=!!(r.table?.subscription?.is_subscription_record||r.table?.subscription?.upload_to_feed||r.table?.subscription?.notify_subscribers||r.table?.subscription?.feed_referencing_records||r.table?.subscription?.notify_referencing_records);if(r.record_id)throw new c("Public users cannot update existing records.",{code:"INVALID_REQUEST"});if(r.table.access_group!=="public"&&r.table.access_group!==0)throw new c("Public users can only post records to public tables.",{code:"INVALID_REQUEST"});if(s)throw new c("Public users cannot post subscription records.",{code:"INVALID_REQUEST"});if(r.remove_bin)throw new c("Public users cannot remove files from records.",{code:"INVALID_REQUEST"});if(r.unique_id)throw new c("Public users cannot set unique_id for records.",{code:"INVALID_REQUEST"})}return {config:r,progress:i,is_reference_post:e,files:t}}async function Lt(n){if(await this.__connection,!Array.isArray(n)||!n.length)throw new c('"params" should be a non-empty array.',{code:"INVALID_PARAMETER"});let e=[],t,r,i=null,o={_is_bulk_:n.map((u,m)=>{if(!u||typeof u!="object"||Array.isArray(u))throw new c(`"params[${m}]" should be type: <object>.`,{code:"INVALID_PARAMETER"});let R=Ct.bind(this)(u),f=R.config;if(R.is_reference_post&&e.push(R.is_reference_post),typeof f.progress=="function"&&i===null&&(i=f.progress),f.service!==void 0){if(t===void 0)t=f.service;else if(t!==f.service)throw new c('All bulk params should share the same "service" value.',{code:"INVALID_PARAMETER"})}if(f.owner!==void 0){if(r===void 0)r=f.owner;else if(r!==f.owner)throw new c('All bulk params should share the same "owner" value.',{code:"INVALID_PARAMETER"})}return delete f.progress,delete f.service,delete f.owner,f}),service:"",owner:""};t!==void 0&&(o.service=t),r!==void 0&&(o.owner=r);let a={auth:!!this.__user,method:"post"},l={};Object.keys(l).length&&Object.assign(a,{fetchOptions:l});let d=await w.bind(this)("post-record",o,a),h=await Promise.all(d.map(u=>ie.bind(this)(u,"called from postRecord")));for(let u=0;u<d.length;u++){let m=d[u],R=h[u];if(typeof m?.reference_private_key=="string")for(let f of e)this.__private_access_key[f]=m.reference_private_key;R?.unique_id&&(this.__my_unique_ids[R.unique_id]=R.record_id);}return h}async function Ot(n,e,t){if(await this.__connection,!e)throw new c('"config" argument is required.',{code:"INVALID_PARAMETER"});let r=Ct.bind(this)(e),i=r.config,s=r.progress,o=r.is_reference_post,a={auth:!!this.__user,method:"post"},l=[],d=N(n);t&&Array.isArray(t)&&t.length&&(l=l.concat(t)),d.files&&Array.isArray(d.files)&&d.files.length&&(l=l.concat(d.files));let h=null;h=Object.assign({data:d.data},i);let u={};typeof s=="function"&&(u.progress=s),Object.keys(u).length&&Object.assign(a,{fetchOptions:u});let m=await w.bind(this)("post-record",h,a);if($()&&l.length){let f=new FormData;for(let _ of l)f.append(_.name,_.file,_.file.name);let A={record_id:m.rec,progress:s};i.hasOwnProperty("service")&&(A.service=i.service);let{bin_endpoints:P}=await we.bind(this)(f,A);m.bin?m.bin.push(...P):m.bin=P;}o&&typeof m?.reference_private_key=="string"&&(this.__private_access_key[o]=m.reference_private_key);let R=await ie.bind(this)(m,"called from postRecord");return R.unique_id&&(this.__my_unique_ids[R.unique_id]=R.record_id,$()&&window.sessionStorage.setItem(`${this.service}:uniqueids`,JSON.stringify(this.__my_unique_ids))),R}async function Ft(n,e){let t=await w.bind(this)("get-table",g.Params(n||{},{table:"string",condition:["gt","gte","lt","lte",">",">=","<","<=","=","eq","!=","ne"]}),Object.assign({auth:!!this.__user},{fetchOptions:e})),r={cnt_rec:"number_of_records",tbl:"table",srvc:"service",grp_:"number_of_records_in_access_group_"};if(Array.isArray(t?.list))for(let i of t.list)for(let s in r){if(s==="grp_"){for(let o in i)if(o.startsWith("grp_")){let a=o.substring(4);a==="**"?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[r[s]]=i[s],delete i[s]);}return t}async function Mt(n,e){if(!n?.table)throw new c('"table" is required.',{code:"INVALID_PARAMETER"});let t=g.Params(n||{},{table:"string",index:s=>de(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:["string","number","boolean"],condition:["gt","gte","lt","lte",">",">=","<","<=","=","eq","!=","ne"]}},["table"]);if(t.hasOwnProperty("order")){if(!t.order?.by)throw new c('"order.by" is required.',{code:"INVALID_PARAMETER"});if(t.order.hasOwnProperty("condition")&&!t.order.hasOwnProperty("value"))throw new c('"value" is required for "condition".',{code:"INVALID_PARAMETER"});if(t.hasOwnProperty("index")&&t.index.substring(t.index.length-1)!==".")throw new c('"index" should be a parent index name of the compound index when using "order.by"',{code:"INVALID_PARAMETER"})}let r=await w.bind(this)("get-index",t,Object.assign({auth:!!this.__user},{fetchOptions:e})),i={cnt_bool:"boolean_count",cnt_numb:"number_count",totl_numb:"total_number",totl_bool:"total_bool",avrg_numb:"average_number",avrg_bool:"average_bool",cnt_str:"string_count"};return Array.isArray(r?.list)&&(r.list=r.list.map(s=>{let o=s.idx.split("/"),a={table:o[1],index: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})),r}async function Vt(n,e){let t=await w.bind(this)("get-tag",g.Params(n||{},{table:"string",tag:"string",condition:["gt","gte","lt","lte",">",">=","<","<=","=","eq","!=","ne"]}),Object.assign({auth:!!this.__user},{fetchOptions:e}));return Array.isArray(t?.list)&&(t.list=t.list.map(r=>{let i=r.tag.split("/");return {table:i[1],tag:i[0],number_of_records:r.cnt_rec}})),t}async function $t(n,e){let t=await w.bind(this)("get-uniqueid",g.Params(n||{},{unique_id:"string",condition:["gt","gte","lt","lte",">",">=","<","<=","=","eq","!=","ne"]}),Object.assign({auth:!!this.__user},{fetchOptions:e}));if(Array.isArray(t?.list))for(let r in t.list){let i=t.list[r];t.list[r]={unique_id:i.unq,record_id:i.rec};}return t}async function qt(n,e){await this.__connection;let t=await Ut.bind(this)(n,true),r=t.is_reference_fetch,i=await w.bind(this)("del-records",t.query,{auth:true,fetchOptions:e});return r&&typeof i?.reference_private_key=="string"&&(this.__private_access_key[r]=i.reference_private_key),i?.message||i}function jt(n){return Ht.bind(this)({record_id:n.record_id,user_id:n.user_id,execute:"add"})}function Bt(n){return Ht.bind(this)({record_id:n.record_id,user_id:n.user_id||null,execute:"remove"})}async function Kt(n,e){let t={record_id:n.record_id||void 0,user_id:n.user_id||void 0,execute:"list"};if(!t.record_id&&!t.user_id)throw new c("Either record_id or user_id must be provided.",{code:"INVALID_PARAMETER"});if(t.user_id)if(typeof t.user_id=="string")g.UserId(t.user_id),t.user_id=[t.user_id];else if(Array.isArray(t.user_id))for(let s of t.user_id)g.UserId(s);else throw new c("user_id should be type: <string | string[]>",{code:"INVALID_PARAMETER"});let r=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 w.bind(this)("grant-private-access",t,{auth:true,fetchOptions:e});return i.list=i.list.map(r),i}function Qt(n){let e=n.record_id,t=n.reference_id||void 0;if(!e)throw new c("Record ID is required.",{code:"INVALID_PARAMETER"});if(typeof e!="string")throw new c("Record ID should be type: <string | string[]>",{code:"INVALID_PARAMETER"});if(t&&typeof t!="string")throw new c("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(Ae[e])return Ae[e];let r=w.bind(this)("request-private-access-key",{record_id:e,reference_id:t},{auth:true}).then(i=>{let s=typeof i=="string"?i:i?.private_key;if(typeof s!="string")throw new c("Invalid private access key response.",{code:"ERROR"});return this.__private_access_key[e]=s,s}).finally(()=>{delete Ae[e];});return Ae[e]=r,r}function Ht(n){n.execute;let t=g.Params(n,{record_id:"string",user_id:r=>{if(!r)throw new c("User ID is required.",{code:"INVALID_PARAMETER"});let i=r;if(typeof i=="string"&&(i=[i]),i.length>100)throw new c("Cannot process more than 100 users at once.",{code:"INVALID_REQUEST"});for(let s of i)g.UserId(s,'User ID in "user_id"');return i},execute:["add","remove"]},["execute","record_id","user_id"]);return t.user_id||(t.user_id=null),w.bind(this)("grant-private-access",t,{auth:true})}var I={},O={},B={},W={},H={},Te={},Pe={};function Wt(n,e,t){n[e]||(n[e]=[]),n[e].push(t);}async function Se(n,e,t){let r=[];if(n[e]){for(let i of n[e])if(i){let s=t(i);s instanceof Promise&&(s=await s),r.push(s);}delete n[e];}return r}async function qe(n,e){if(!this?.session?.accessToken?.jwtToken)throw new c("Access token is required.",{code:"INVALID_PARAMETER"});let t=await this.__socket;async function r(i,s,o){this.log("answerSdpOffer from",s),await I[s].setRemoteDescription(new RTCSessionDescription(i));let a=await I[s].createAnswer();await I[s].setLocalDescription(a),o.send(JSON.stringify({action:"rtc",uid:s,content:{sdpanswer:a},token:this.session.accessToken.jwtToken}));}I?.[e]?n?(await Se(Pe,e,i=>r.bind(this)(i,e,t)),await r.bind(this)(n,e,t)):await Se(Pe,e,i=>r.bind(this)(i,e,t)):n&&Wt(Pe,e,n);}async function je(n,e){if(this.log("receiveIceCandidate",n),I?.[e]&&I[e]?.remoteDescription&&I[e]?.remoteDescription?.type){if(!n)return Se(Te,e,t=>I[e].addIceCandidate(t));await Se(Te,e,t=>I[e].addIceCandidate(t)),await I[e].addIceCandidate(n);}else Wt(Te,e,n);}async function K(n){if(typeof window>"u"||window._runningInNodeJS)throw new c("WebRTC is not supported in Node.js environment.",{code:"NOT_SUPPORTED"});g.Params(n,{cid:s=>{if(typeof s!="string")throw new c('"cid" should be type: <string>.',{code:"INVALID_PARAMETER"});if(s&&s.slice(0,4)!=="cid:")throw new c('"cid" should be a valid connection id.',{code:"INVALID_PARAMETER"});return s},close:"boolean"});let e=await this.__socket,{cid:t,close_all:r=false}=n||{};if(!r&&!t)throw new c('"cid" is required.',{code:"INVALID_PARAMETER"});let i=s=>{if(!s)throw new c('"cid" is required.',{code:"INVALID_PARAMETER"});if(delete Pe[s],delete Te[s],O[s]&&Object.values(O[s]).forEach(o=>{o.readyState!=="closed"&&o.close();}),delete O[s],I?.[s]){I[s].connectionState!=="closed"&&(I[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:I[s],timestamp:new Date().toISOString(),state:I[s].connectionState,iceState:I[s].iceConnectionState,signalingState:I[s].signalingState};H[s]&&H[s](o),this.log("closeRTC",o);}delete H[s],delete W[s],delete B[s],delete I[s];};if(r)for(let s in I)i(s);else i(t);this.log("Cleaning up media stream..."),this.__mediaStream&&(this.__mediaStream.getTracks().forEach(s=>{s.stop();}),this.__mediaStream=null);}async function zt(n){if(n instanceof MediaStream)return n;if(!n.video&&!n.audio){let e=new MediaStream,t=document.createElement("canvas");t.width=1,t.height=1;let i=t.captureStream().getVideoTracks()[0];return e.addTrack(i),e}return window.navigator.mediaDevices.getUserMedia(n)}async function Jt(n,e){if(typeof window>"u"||window._runningInNodeJS)throw new c("WebRTC is not supported in Node.js environment.",{code:"NOT_SUPPORTED"});if(typeof e!="function")throw new c("Callback is required.",{code:"INVALID_PARAMETER"});if(!this?.session?.accessToken?.jwtToken)throw new c("Access token is required.",{code:"INVALID_PARAMETER"});n=g.Params(n,{cid:o=>{if(typeof o!="string")throw new c('"cid" should be type: <string>.',{code:"INVALID_PARAMETER"});if(o&&o.slice(0,4)!=="cid:")throw new c('"cid" should be a valid connection id.',{code:"INVALID_PARAMETER"});return o},ice:["string",()=>"stun:stun.skapi.com:3468"],media:o=>o,channels:["text-chat","file-transfer","video-chat","voice-chat","gaming",{ordered:"boolean",maxPacketLifeTime:"number",maxRetransmits:"number",protocol:"string"},()=>[{ordered:true,maxPacketLifeTime:10,protocol:"default"}]]},["cid"]);let{cid:t,ice:r}=n;if(!(n?.media instanceof MediaStream)&&(n?.media?.video||n?.media?.audio)&&window.location.hostname!=="localhost"&&window.location.protocol!=="https:")throw new c("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 c("No realtime connection. Execute connectRealtime() before this method.",{code:"INVALID_REQUEST"});if(i.readyState!==1)throw new c("Realtime connection is not ready.",{code:"INVALID_REQUEST"});let s={iceServers:[{urls:r}]};I?.[t]||(I[t]=new RTCPeerConnection(s)),n?.media&&(this.__mediaStream=await zt(n.media),this.__mediaStream.getTracks().forEach(o=>{I[t].addTrack(o,this.__mediaStream);})),H[t]=e,O[t]||(O[t]={});for(let o=0;o<n.channels.length;o++){let a=n.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(O[t]).includes(l))throw new c(`Data channel with the protocol "${l}" already exists.`,{code:"INVALID_REQUEST"});let d=I[t].createDataChannel(l,a);O[t][l]=d;}for(let o in O[t]){let a=O[t][o];Zt.bind(this)(t,a);}return Xt.bind(this)(t,["onnegotiationneeded"]),await $e.bind(this)(t),{hangup:()=>B[t]&&B[t](false),connection:new Promise(o=>{B[t]=(a=>{if(this.log("receiver picked up the call",t),!a)return K.bind(this)({cid:t}),null;I[t].onnegotiationneeded=()=>{this.log("onnegotiationneeded",`sending offer to "${t}".`),$e.bind(this)(t),H[t]&&H[t]({type:"negotiationneeded",target:I[t],timestamp:new Date().toISOString(),signalingState:I[t].signalingState,connectionState:I[t].iceConnectionState,gatheringState:I[t].iceGatheringState});},o({target:I[t],channels:O[t],hangup:()=>K.bind(this)({cid:t}),media:this.__mediaStream});}).bind(this);})}}function Gt(n){return async(e,t)=>{e=e||{},e=N(e).data;let r=n.sender_cid,i=await this.__socket;if(!W[r])return null;if(typeof t!="function")throw new c("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 c("Media stream is only supported on either localhost or https.",{code:"INVALID_REQUEST"});let{ice:s="stun:stun.skapi.com:3468"}=e;return I?.[r]||(I[r]=new RTCPeerConnection({iceServers:[{urls:s}]})),e?.media&&(this.__mediaStream=await zt(e.media),this.__mediaStream.getTracks().forEach(o=>{I[r].addTrack(o,this.__mediaStream);})),delete W[r],H[r]=t,O[r]||(O[r]={}),I[r].ondatachannel=o=>{this.log("ondatachannel",`received data channel "${o.channel.label}".`);let a=o.channel;O[r][a.label]=a,Zt.bind(this)(r,a);},Xt.bind(this)(r,["onnegotiationneeded"]),await qe.bind(this)(null,r),await je.bind(this)(null,r),i.send(JSON.stringify({action:"rtc",uid:r,content:{pickup:this.user.user_id},token:this.session.accessToken.jwtToken})),{target:I[r],channels:O[r],hangup:()=>K.bind(this)({cid:r}),media:this.__mediaStream}}}async function $e(n){if(!this?.session?.accessToken?.jwtToken)throw new c("Access token is required.",{code:"INVALID_PARAMETER"});this.log("sendOffer",n);let e=await this.__socket,t=await I[n].createOffer();await I[n].setLocalDescription(t);let r=I[n].localDescription;this.log("rtcSdpOffer to",r),e.send(JSON.stringify({action:"rtc",uid:n,content:{sdpoffer:r},token:this.session.accessToken.jwtToken}));}async function vr(n,e){if(!this?.session?.accessToken?.jwtToken)throw new c("Access token is required.",{code:"INVALID_PARAMETER"});this.log("sendIceCandidate to",e);let t=await this.__socket;if(!n.candidate){this.log("candidate-end","all ice candidates have been sent");return}let r=H[e]||(()=>{}),i=n.candidate;this.log("ice gathering state set to",I[e].iceGatheringState),r({type:"icecandidate",target:I[e],timestamp:new Date().toISOString(),candidate:n.candidate.candidate,sdpMid:n.candidate.sdpMid,sdpMLineIndex:n.candidate.sdpMLineIndex,usernameFragment:n.candidate.usernameFragment,protocol:n.candidate.protocol,gatheringState:I[e].iceGatheringState,connectionState:I[e].iceConnectionState}),t.send(JSON.stringify({action:"rtc",uid:e,content:{candidate:i},token:this.session.accessToken.jwtToken}));}function Xt(n,e){let t=new Set(e),r=H[n]||(o=>{}),i=I[n],s={ontrack:o=>{r({type:"track",target:i,timeStamp:o.timeStamp,streams:o.streams,track:o.track});},onicecandidate:o=>{vr.bind(this)(o,n),o.candidate?r({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}):r({type:"icecandidateend",target:i,timestamp:new Date().toISOString()});},onicecandidateerror:o=>{r({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:()=>{r({type:"iceconnectionstatechange",target:i,timestamp:new Date().toISOString(),state:i.iceConnectionState,gatheringState:i.iceGatheringState,signalingState:i.signalingState});},onicegatheringstatechange:()=>{r({type:"icegatheringstatechange",target:i,timestamp:new Date().toISOString(),state:i.iceGatheringState,connectionState:i.iceConnectionState,signalingState:i.signalingState});},onsignalingstatechange:()=>{r({type:"signalingstatechange",target:i,timestamp:new Date().toISOString(),state:i.signalingState,connectionState:i.iceConnectionState,gatheringState:i.iceGatheringState});},onnegotiationneeded:()=>{$e.bind(this)(n),r({type:"negotiationneeded",target:i,timestamp:new Date().toISOString(),signalingState:i.signalingState,connectionState:i.iceConnectionState,gatheringState:i.iceGatheringState});},onconnectionstatechange:()=>{r({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")&&K.bind(this)({cid:n});}};for(let[o,a]of Object.entries(s))t.has(o)||(i[o]=a);}function Zt(n,e,t){let r=new Set(t),i=H[n]||(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),O[n]&&(delete O[n][e.label],Object.keys(O[n]).length===0&&K.bind(this)({cid:n}));},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))r.has(o)||(e[o]=a);}var Y,Z=null,ge=true,se=0;async function Dr(){if(typeof window>"u"||window._runningInNodeJS)throw new c("WebSocket is not supported in Node.js environment.",{code:"NOT_SUPPORTED"});if(await this.getProfile(),!this.session)throw new c("No access.",{code:"INVALID_REQUEST"});let n=await this.record_endpoint;return new WebSocket(n.websocket_private+"?token="+this.session.accessToken.jwtToken)}var Be=null;async function Yt(){if(typeof window>"u"||window._runningInNodeJS)throw new c("WebSocket is not supported in Node.js environment.",{code:"NOT_SUPPORTED"});ge=true;let n=this.__socket?await this.__socket:this.__socket;K.bind(this)({close_all:true}),Y&&Ke.bind(this)({group:null}),se=0,Z&&(Z.terminate(),Z=null);try{n&&n.close();}catch{}return window.removeEventListener("visibilitychange",Be),this.__socket=null,null}async function ke(n,e=50,t){if(typeof window>"u"||window._runningInNodeJS)throw new c("WebSocket is not supported in Node.js environment.",{code:"NOT_SUPPORTED"});if(typeof n!="function")throw new c("Callback must be a function.",{code:"INVALID_REQUEST"});if(t==="reconnect"){if(this.__socket instanceof Promise){let r=await this.__socket;if(r.readyState!==WebSocket.CLOSED&&r.readyState!==WebSocket.CLOSING)return this.__socket}}else if(ge&&(Be=()=>{!document.hidden&&!ge&&ke.bind(this)(n,0,"reconnect");},this.__socket instanceof Promise))return this.__socket;Z&&(Z.terminate(),Z=null),this.__socket=new Promise(async r=>{await ne.bind(this)(),setTimeout(async()=>{let i=await Dr.bind(this)();i.onopen=()=>{ge=false,se=0,t!=="reconnect"&&window.addEventListener("visibilitychange",Be),this.log("realtime onopen","Connected to WebSocket server."),n({type:"success",message:"Connected to WebSocket server."}),Y&&i.send(JSON.stringify({action:"joinRoom",rid:Y,token:this.session.accessToken.jwtToken}));let s=`
|
|
206
|
+
var Fn=Object.defineProperty;var Mn=Object.getOwnPropertyDescriptor;var ee=(n=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(n,{get:(e,t)=>(typeof require<"u"?require:e)[t]}):n)(function(n){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+n+'" is not supported')});var y=(n,e,t,r)=>{for(var i=Mn(e,t),s=n.length-1,o;s>=0;s--)(o=n[s])&&(i=(o(e,t,i))||i);return i&&Fn(e,t,i),i};var z=typeof globalThis<"u"?globalThis:void 0,he=z?.window;function Vn(n){if(Buffer)return Buffer.from(n).toString("base64");let e="",t=new Uint8Array(n),r=32768;for(let i=0;i<t.length;i+=r){let s=t.subarray(i,i+r);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(he)he.global=he,he.global._runningInNodeJS=false;else if(z&&(z.global=z,typeof z.window>"u")){class n{constructor(){this.result=null;this.error=null;this.onload=null;this.onloadend=null;this.onerror=null;}readAsDataURL(r){r.arrayBuffer().then(i=>{let s=Vn(i),o=r.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(r){r.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(r,i="utf-8"){r.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});});}}z.FileReader=n;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(r,i){this._method=r,this._url=i,this.readyState=1;}setRequestHeader(r,i){this._headers[r]=i;}getResponseHeader(r){return null}abort(){this._aborted=true,this.onabort&&this.onabort({});}send(r){if(this._aborted)return;let i={method:this._method,headers:this._headers};r&&this._method!=="GET"&&this._method!=="HEAD"&&(i.body=r),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);});}}z.XMLHttpRequest=e,z.window={_runningInNodeJS:true,alert:t=>console.error("[Alert]",t),sessionStorage:{getItem:t=>null,setItem:(t,r)=>{},removeItem:t=>{}},localStorage:{getItem:t=>{let r=ee("fs"),i=ee("path");try{let s=i.resolve(process.cwd(),"states","localStorage",`${t}.skapi`);return r.existsSync(s)?r.readFileSync(s,"utf8"):null}catch{return null}},setItem:(t,r)=>{let i=ee("fs"),s=ee("path");try{let o=s.resolve(process.cwd(),"states","localStorage");i.existsSync(o)||i.mkdirSync(o,{recursive:!0});let a=s.resolve(o,`${t}.skapi`);i.writeFileSync(a,r,"utf8");}catch{}},removeItem:t=>{let r=ee("fs"),i=ee("path");try{let s=i.resolve(process.cwd(),"states","localStorage",`${t}.skapi`);r.existsSync(s)&&r.unlinkSync(s);}catch{}}},location:{href:"",origin:"",hostname:"",protocol:"",replace:t=>{}},navigator:{userAgent:`nodejs/${z?.process?.versions?.node||"unknown"}`,mediaDevices:{getUserMedia:async t=>{throw new Error("getUserMedia is not supported in Node.js environment.")}}},addEventListener:()=>{},removeEventListener:()=>{}};}var c=class extends Error{constructor(e,t){if(Array.isArray(e)&&e.length<=2){let r=e[1];if(e.length>2)for(let i=2;i<e.length&&typeof e[i]=="string";i++)r+=e[i];super((r||"Something went wrong.").trim()),this.name=t?.name||"SKAPI",this.code=t?.code||e[0]||"ERROR",t?.cause&&(this.cause=t.cause);}else super((e?.message||(typeof e=="string"?e:"Something went wrong.")).trim()),typeof e=="string"?(this.name=t?.name||"SKAPI",this.code=t?.code||"ERROR",t?.cause&&(this.cause=t.cause)):e instanceof Error?(this.cause=e,this.name=e.name,e.hasOwnProperty("code")&&(this.code=e.code)):typeof e=="object"&&e?.code&&e?.message&&(this.name=t?.name||"SKAPI",this.code=t?.code||"ERROR",this.cause=e?.cause);}};var J="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",ve=BigInt(J.length),$n=2*1024*1024,qn=["aud","cognito:username","event_id","exp","iat","iss","jti","origin_jti","secret_key","token_use"],Qe={auth_time:"log",sub:"user_id"},jn=["0","1","2","3","4","5","6","7","8","9","a","b","c","d","e","f","g","h","i","j","k","l"],Ge=["us31","us72","ap51","ap22","ap41","eu71","ap21","us32","us71","af51","ap31","ap43","ap23","ap42","ca01","eu01","eu72","eu51","eu73","eu11","me51","sa31"],He=typeof TextEncoder<"u"?new TextEncoder:null;function Bn(){if(typeof globalThis<"u")return globalThis.Buffer}function Kn(n){if(He)return He.encode(n);let e=unescape(encodeURIComponent(n)),t=new Uint8Array(e.length);for(let r=0;r<e.length;r++)t[r]=e.charCodeAt(r);return t}function Qn(n){if(n instanceof Uint8Array)return n;if(typeof n=="string")return Kn(n);if(typeof ArrayBuffer<"u"&&n instanceof ArrayBuffer)return new Uint8Array(n);if(typeof ArrayBuffer<"u"&&ArrayBuffer.isView(n))return new Uint8Array(n.buffer,n.byteOffset,n.byteLength);if(Array.isArray(n))return Uint8Array.from(n);let e=Bn();if(e)return new Uint8Array(e.from(n));throw new Error("No byte conversion available in this environment.")}var p=class p{static hash(e){typeof e!="string"&&(console.warn("coercing non-string value to empty string"),e="");let t=p.sb(e),r=1732584193,i=-271733879,s=-1732584194,o=271733878,a,l,d,h;for(let u=0;u<t.length;u+=16)a=r,l=i,d=s,h=o,r=p.ff(r,i,s,o,t[u],7,-680876936),o=p.ff(o,r,i,s,t[u+1],12,-389564586),s=p.ff(s,o,r,i,t[u+2],17,606105819),i=p.ff(i,s,o,r,t[u+3],22,-1044525330),r=p.ff(r,i,s,o,t[u+4],7,-176418897),o=p.ff(o,r,i,s,t[u+5],12,1200080426),s=p.ff(s,o,r,i,t[u+6],17,-1473231341),i=p.ff(i,s,o,r,t[u+7],22,-45705983),r=p.ff(r,i,s,o,t[u+8],7,1770035416),o=p.ff(o,r,i,s,t[u+9],12,-1958414417),s=p.ff(s,o,r,i,t[u+10],17,-42063),i=p.ff(i,s,o,r,t[u+11],22,-1990404162),r=p.ff(r,i,s,o,t[u+12],7,1804603682),o=p.ff(o,r,i,s,t[u+13],12,-40341101),s=p.ff(s,o,r,i,t[u+14],17,-1502002290),i=p.ff(i,s,o,r,t[u+15],22,1236535329),r=p.gg(r,i,s,o,t[u+1],5,-165796510),o=p.gg(o,r,i,s,t[u+6],9,-1069501632),s=p.gg(s,o,r,i,t[u+11],14,643717713),i=p.gg(i,s,o,r,t[u],20,-373897302),r=p.gg(r,i,s,o,t[u+5],5,-701558691),o=p.gg(o,r,i,s,t[u+10],9,38016083),s=p.gg(s,o,r,i,t[u+15],14,-660478335),i=p.gg(i,s,o,r,t[u+4],20,-405537848),r=p.gg(r,i,s,o,t[u+9],5,568446438),o=p.gg(o,r,i,s,t[u+14],9,-1019803690),s=p.gg(s,o,r,i,t[u+3],14,-187363961),i=p.gg(i,s,o,r,t[u+8],20,1163531501),r=p.gg(r,i,s,o,t[u+13],5,-1444681467),o=p.gg(o,r,i,s,t[u+2],9,-51403784),s=p.gg(s,o,r,i,t[u+7],14,1735328473),i=p.gg(i,s,o,r,t[u+12],20,-1926607734),r=p.hh(r,i,s,o,t[u+5],4,-378558),o=p.hh(o,r,i,s,t[u+8],11,-2022574463),s=p.hh(s,o,r,i,t[u+11],16,1839030562),i=p.hh(i,s,o,r,t[u+14],23,-35309556),r=p.hh(r,i,s,o,t[u+1],4,-1530992060),o=p.hh(o,r,i,s,t[u+4],11,1272893353),s=p.hh(s,o,r,i,t[u+7],16,-155497632),i=p.hh(i,s,o,r,t[u+10],23,-1094730640),r=p.hh(r,i,s,o,t[u+13],4,681279174),o=p.hh(o,r,i,s,t[u],11,-358537222),s=p.hh(s,o,r,i,t[u+3],16,-722521979),i=p.hh(i,s,o,r,t[u+6],23,76029189),r=p.hh(r,i,s,o,t[u+9],4,-640364487),o=p.hh(o,r,i,s,t[u+12],11,-421815835),s=p.hh(s,o,r,i,t[u+15],16,530742520),i=p.hh(i,s,o,r,t[u+2],23,-995338651),r=p.ii(r,i,s,o,t[u],6,-198630844),o=p.ii(o,r,i,s,t[u+7],10,1126891415),s=p.ii(s,o,r,i,t[u+14],15,-1416354905),i=p.ii(i,s,o,r,t[u+5],21,-57434055),r=p.ii(r,i,s,o,t[u+12],6,1700485571),o=p.ii(o,r,i,s,t[u+3],10,-1894986606),s=p.ii(s,o,r,i,t[u+10],15,-1051523),i=p.ii(i,s,o,r,t[u+1],21,-2054922799),r=p.ii(r,i,s,o,t[u+8],6,1873313359),o=p.ii(o,r,i,s,t[u+15],10,-30611744),s=p.ii(s,o,r,i,t[u+6],15,-1560198380),i=p.ii(i,s,o,r,t[u+13],21,1309151649),r=p.ii(r,i,s,o,t[u+4],6,-145523070),o=p.ii(o,r,i,s,t[u+11],10,-1120210379),s=p.ii(s,o,r,i,t[u+2],15,718787259),i=p.ii(i,s,o,r,t[u+9],21,-343485551),r=p.ad(r,a),i=p.ad(i,l),s=p.ad(s,d),o=p.ad(o,h);return p.rh(r)+p.rh(i)+p.rh(s)+p.rh(o)}static rh(e){let t="";for(let r=0;r<=3;r++)t+=p.alphabet.charAt(e>>r*8+4&15)+p.alphabet.charAt(e>>r*8&15);return t}static ad(e,t){let r=(e&65535)+(t&65535);return (e>>16)+(t>>16)+(r>>16)<<16|r&65535}static rl(e,t){return e<<t|e>>>32-t}static cm(e,t,r,i,s,o){return p.ad(p.rl(p.ad(p.ad(t,e),p.ad(i,o)),s),r)}static ff(e,t,r,i,s,o,a){return p.cm(t&r|~t&i,e,t,s,o,a)}static gg(e,t,r,i,s,o,a){return p.cm(t&i|r&~i,e,t,s,o,a)}static hh(e,t,r,i,s,o,a){return p.cm(t^r^i,e,t,s,o,a)}static ii(e,t,r,i,s,o,a){return p.cm(r^(t|~i),e,t,s,o,a)}static sb(e){let t,r=(e.length+8>>6)+1,i=new Array(r*16);for(t=0;t<r*16;t++)i[t]=0;for(t=0;t<e.length;t++)i[t>>2]|=e.charCodeAt(t)<<t%4*8;return i[t>>2]|=128<<t%4*8,i[r*16-2]=e.length*8,i}};p.alphabet="0123456789abcdef";var V=p;function Xe(n){if(n===0)return J[0];let e="";for(;n>0;)e=J[n%62]+e,n=Math.floor(n/62);return e}function j(n){return n.split("").reverse().reduce((e,t,r)=>e+J.indexOf(t)*62**r,0)}function oe(n=6){let e="",t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",r=t.length,i=0;for(;i<n;)e+=t.charAt(Math.floor(Math.random()*r)),i+=1;return e}function De(){return typeof window>"u"||!!window?._runningInNodeJS}function $(){return !De()&&typeof document<"u"&&typeof document.createElement=="function"}function pe(n){let e;try{e=JSON.stringify(n);}catch{throw new c("Invalid data type.",{code:"INVALID_REQUEST"})}if(new Blob([e]).size>$n)throw new c("Data should not exceed 2MB",{code:"INVALID_REQUEST"})}function We(n){return n===""||n==="on"||n==="true"}function ze(n){return n==="false"}function Je(n,e,t){e.name&&t(n,e.name,e.value);}var me=$(),Hn=typeof SubmitEvent<"u",Wn=typeof HTMLFormElement<"u";function N(n,e,t){let r={},i=[];function s(l,d,h){if(e?.ignoreEmpty&&h==="")return;if(e?.nullIfEmpty&&h===""&&(h=null),typeof t=="function"){let R=t(d,h);R!==void 0&&(h=R);}let u=d.split("[").map(R=>{let f=R.replace("]",""),A=Number(f);return !isNaN(A)&&!f.includes(".")?f=A:(f[0]==='"'&&f[f.length-1]==='"'||f[0]==="'"&&f[f.length-1]==="'")&&(f=f.replace(/"/g,"").replace(/'/g,"")),f}),m=l;if(typeof u[0]=="number")throw new c("Form key cannot start with an array index.",{code:"INVALID_REQUEST"});for(let R=0;R<u.length;R++){let f=u[R];R<u.length-1?(m[f]===void 0&&(typeof u[R+1]=="number"?m[f]=[]:m[f]={}),m=m[f]):m[f]===void 0?m[f]=h:Array.isArray(m[f])?m[f].push(h):m[f]=[m[f],h];}}function o(l,d,h){if(h instanceof File)l.push({name:d,file:h});else if(h instanceof FileList&&h&&h.length>0)for(let u=0;u<=h.length-1;u++){let m=h.item(u);m&&l.push({name:d,file:m});}}let a=l=>{l.name&&(l.type==="number"?l.value&&s(r,l.name,Number(l.value)):l.type==="checkbox"||l.type==="radio"?l.checked?l.type==="checkbox"&&l.value===""||We(l.value)?s(r,l.name,true):ze(l.value)?s(r,l.name,false):l.value&&s(r,l.name,l.value):l.type==="checkbox"&&(We(l.value)?s(r,l.name,false):ze(l.value)&&s(r,l.name,true)):l.type==="file"?l.files&&l.files.length>0&&o(i,l.name,l.files):s(r,l.name,l.value));};if(me&&(n instanceof HTMLInputElement||n instanceof HTMLSelectElement||n instanceof HTMLTextAreaElement))return a(n),pe(r),{data:r,files:i};if(me&&n instanceof FormData){for(let l of n.entries()){let d=l[0],h=l[1];if(h instanceof File||h instanceof FileList)o(i,d,h);else if(h instanceof Blob){let u=h;if(u.type==="application/json")try{let m=JSON.parse(u.text());s(r,d,m);}catch{s(r,d,u);}}else s(r,d,h);}return pe(r),{data:r,files:i}}if(me&&Hn&&n instanceof SubmitEvent&&(n=n.target),me&&Wn&&n instanceof HTMLFormElement){let l=n.querySelectorAll("input"),d=n.querySelectorAll("select"),h=n.querySelectorAll("textarea");for(let u=0;u<d.length;u++)Je(r,d[u],s);for(let u=0;u<h.length;u++)Je(r,h[u],s);for(let u=0;u<l.length;u++)a(l[u]);return pe(r),{data:r,files:i}}return pe(n),{data:n,files:i}}function ae(n){let e={};for(let t in n){let r=n[t];if(!qn.includes(t))if(Qe[t])e[Qe[t]]=r;else if(t.includes("custom:"))e[t.replace("custom:","")]=r;else if(t==="address"){let i=r;if(i&&typeof i=="object"&&Object.keys(i).length){if(i?.formatted)try{e[t]=JSON.parse(i.formatted);}catch{e[t]=i.formatted;}}else e[t]=i;}else e[t]=r;}for(let t of ["address_public","birthdate_public","email_public","gender_public","phone_number_public","access_group"])t.includes("_public")?e.hasOwnProperty(t.split("_")[0])?e[t]=e.hasOwnProperty(t)?!!Number(e[t]):false:delete e[t]:e[t]=e.hasOwnProperty(t)?Number(e[t]):0;for(let t of ["email","phone_number"])e.hasOwnProperty(t)?e[t+"_verified"]=e[t+"_verified"]===true:delete e[t+"_verified"];return e}function Ue(n){if(n=tr(n),n.split("-").length===7){let e=n.split("-"),t,r;try{t=Ge[j(e[1][0])],r=e.slice(2).join("-");}catch{throw new Error("INVALID_PARAMETER: Service ID is invalid.")}if(!t)throw new Error("INVALID_PARAMETER: Service ID is invalid.");return {service:t+e[0]+e[1].slice(1),owner:r}}return {service:n,owner:""}}function Ze(n,e){let t=Ge.indexOf(n.slice(0,4)),r=jn[t],s=`${n.slice(4,-4)}-${r}${n.slice(-4)}-${e}`;return er(s)}function zn(n){let e=0n;for(let t of n){let r=J.indexOf(t);if(r<0)throw new Error(`INVALID_PARAMETER: Invalid base62 character: ${t}`);e=e*ve+BigInt(r);}return e}function Jn(n,e=1){if(n<0n)throw new Error("INVALID_PARAMETER: Negative values are not supported.");if(n===0n)return "0".repeat(Math.max(1,e));let t="",r=n;for(;r>0n;){let i=Number(r%ve);t=J[i]+t,r/=ve;}return t.length<e&&(t="0".repeat(e-t.length)+t),t}function Gn(n){if(n===0n)return Uint8Array.from([0]);let e=[],t=n;for(;t>0n;)e.push(Number(t&0xffn)),t>>=8n;return e.reverse(),Uint8Array.from(e)}function Xn(n){let e=0n;for(let t of n)e=(e<<8n)+BigInt(t);return e}function Zn(n){let e=String(n).replace(/-/g,"");if(!/^[0-9a-fA-F]{32}$/.test(e))throw new Error("INVALID_PARAMETER: Invalid UUID format.");let t=new Uint8Array(16);for(let r=0;r<16;r++)t[r]=parseInt(e.slice(r*2,r*2+2),16);return t}function Yn(n){let e=Array.from(Qn(n),t=>t.toString(16).padStart(2,"0")).join("");return [e.slice(0,8),e.slice(8,12),e.slice(12,16),e.slice(16,20),e.slice(20)].join("-")}function er(n){let e=String(n);if(e.split("-").length===2)return e;let t=e.match(/^([0-9A-Za-z]+)-([0-9A-Za-z]+)-([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/);if(!t)throw new Error("INVALID_PARAMETER: Input must match <base62>-<base62>-<uuid>.");let[,r,i,s]=t;if(r.length<2)throw new Error("INVALID_PARAMETER: The first part must contain at least 2 characters.");if(i.length>=J.length)throw new Error("INVALID_PARAMETER: The middle section is too long to encode.");let o=r.slice(0,2),a=r.slice(2),l=i+o,d=J[i.length]+a+l,h=Zn(s),u=Jn(Xn(h));return `${d}-${u}`}function tr(n){let e=String(n);if(e.split("-").length!==2)return e;let t=e.split("-");if(t.length!==2||!t[0]||!t[1])throw new Error("INVALID_PARAMETER: Corrupt compressed token.");let[r,i]=t,s=J.indexOf(r[0]);if(s<0)throw new Error("INVALID_PARAMETER: Corrupt compressed token.");let o=r.slice(1),a=s+2;if(o.length<a)throw new Error("INVALID_PARAMETER: Corrupt compressed token.");let l=o.slice(0,o.length-a),d=o.slice(o.length-a),h=d.slice(s),u=d.slice(0,s),m=h+l;if(!/^[0-9A-Za-z]+$/.test(m)||!/^[0-9A-Za-z]+$/.test(u))throw new Error("INVALID_PARAMETER: Corrupt compressed token.");let R=zn(i),f=Gn(R);if(f.length>16)throw new Error("INVALID_PARAMETER: Corrupt compressed token.");let A=new Uint8Array(16);A.set(f,16-f.length);let P=Yn(A);return `${m}-${u}-${P}`}function rr(n,e="User ID"){let t=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;if(n){if(typeof n!="string")throw new c(`${e} should be type: string.`,{code:"INVALID_PARAMETER"});if(!n.match(t))throw new c(`${e} is invalid.`,{code:"INVALID_PARAMETER"})}else throw new c(`${e} is empty.`,{code:"INVALID_PARAMETER"});return n}function ir(n){if(n&&(typeof n!="string"||n.charAt(0)!=="+"||isNaN(Number(n.substring(1)))))throw new c('"phone_number" is invalid. The format should be "+00123456789". Type: string.',{code:"INVALID_PARAMETER"});return n||""}function sr(n){if(n){if(typeof n!="string")throw new c('"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(n.length!==10||n.split("-").length!==3||!e.test(n))throw new c('"birthdate" is invalid. The format should be "yyyy-mm-dd". Type: string.',{code:"INVALID_PARAMETER"})}}return n||""}function or(n){if(n){if(typeof n!="string")throw new c('"password" should be type: string.',{code:"INVALID_PARAMETER"});if(n.length<6)throw new c('"password" should be at least 6 characters.',{code:"INVALID_PARAMETER"});if(n.length>60)throw new c('"password" can be up to 60 characters max.',{code:"INVALID_PARAMETER"})}else throw new c('"password" is required.',{code:"INVALID_PARAMETER"});return n}function ar(n,e="email"){if(n){if(typeof n!="string")throw new c(`"${e}"should be type: string.`,{code:"INVALID_PARAMETER"});if(n.length<5)throw new c(`"${e}" should be at least 5 characters.`,{code:"INVALID_PARAMETER"});if(/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/.test(n)&&(n=n.trim(),n.split("@")[1].split(".").length>=2))return n.toLowerCase()}else throw new c(`"${e}" is required.`,{code:"INVALID_PARAMETER"});throw new c(`"${n}" is an invalid email.`,{code:"INVALID_PARAMETER"})}function cr(n){let e=typeof window<"u",t=(()=>{let i=e&&window.location.origin||null;return i&&i.slice(-1)==="/"&&(i=i.slice(0,-1)),i})(),r=i=>{if(typeof i=="string"){if(i==="*")return "*";{let s=i.trim();if(s[0]==="/"&&t){if(t.slice(0,5)==="file:")throw new c(`"${i}" is an invalid url. Relative URL does not work on local file system. Use full URL string.`,{code:"INVALID_PARAMETER"});s=t+s;}else if(s[0]==="."&&t){if(t.slice(0,5)==="file:")throw new c(`"${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 c(`"${i}" is an invalid url.`,{code:"INVALID_PARAMETER"})}if(o.protocol)return o.href}}throw new c(`"${i}" is an invalid url.`,{code:"INVALID_PARAMETER"})};return Array.isArray(n)?n.map(i=>r(i)):r(n)}function lr(n,e,t=[],r){let i=N(n,r),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];}r?.precall&&r.precall({data:o,files:i?.files||[]});try{return nr(o,e,t)}catch(a){throw new c(a.message,{code:"INVALID_PARAMETER"})}}var g={UserId:rr,PhoneNumber:ir,Birthdate:sr,Password:or,Email:ar,Url:cr,Params:lr};var C=null;function Ne(n){let e={tkid:"ticket_id",cond:"condition",stmp:"timestamp",actn:"action",cnt:"count",ttl:"time_to_live",plch:"placeholder",hash:"hash",desc:"description",pmc:"limit_per_user"},t={};for(let r in n)if(r==="tkid"){let i=n[r].split("#");if(i.length===1){t.ticket_id=i[0];continue}t.ticket_id=i[1],t.consume_id=i[2],t.user_id=i[3];let s=i[2].slice(-4);if(t.is_test=s===":CHK",!n.stmp){let o=i[2].slice(0,-4);/^[0-9]+$/.test(o)?t.timestamp=parseInt(o,10):t.timestamp=j(i[2].slice(0,-4));}}else e[r]?t[e[r]]=n[r]:t[r]=n[r];return t}async function et(n){if(!n.ticket_id)throw new c("Ticket ID is required.",{code:"INVALID_PARAMETER"});if(!n.method)throw new c('Method is required. Should be either "GET" or "POST"',{code:"INVALID_PARAMETER"});let e=n.ticket_id;await this.__connection;let t=await w.bind(this)(`https://${this.service.slice(0,4)}.${this.customApiDomain}/auth/consume/${this.service}/${this.owner}/${e}`,n?.data||{},{method:n.method,auth:!!n?.auth});return Ne(t)}async function tt(n,e){await this.__connection;let t=await w.bind(this)("ticket",Object.assign({exec:"list"},n||{}),{auth:true,fetchOptions:e});return t.list=t.list.map(Ne),t}async function nt(n,e){await this.__connection;let t=await w.bind(this)("ticket",Object.assign({exec:"consumed"},n||{}),{auth:true,fetchOptions:e});return t.list=t.list.map(Ne),t}async function rt(n){return w.bind(this)("register-ticket",Object.assign({exec:"reg"},n),{auth:true})}async function it(n){return w.bind(this)("register-ticket",Object.assign({exec:"unreg"},n),{auth:true})}async function ne(){if(await this.__connection,this.session){let n=Math.floor(Date.now()/1e3),t=this.session.getIdToken().getExpiration();if(t<n){this.log("request:requesting new token",null);try{await F.bind(this)().getSession({refreshToken:!0}),this.log("request:received new tokens",{exp:this.session?.idToken?.payload?.exp,currentTime:n,expiresIn:t-n,token:this.session?.accessToken?.jwtToken,refreshToken:this.session?.refreshToken?.token});}catch(r){throw this.log("request:new token error",r),new c("User login is required.",{code:"INVALID_REQUEST"})}}else this.log("request:tokens",{exp:this.session.idToken.payload.exp,currentTime:n,expiresIn:t-n,token:this.session.accessToken.jwtToken,refreshToken:this.session.refreshToken.token});return this.session?.idToken?.jwtToken}else throw this.log("request:no session",null),G.bind(this)(),new c("User login is required.",{code:"INVALID_REQUEST"})}function Ye(n,e){return new Promise((t,r)=>{e.refreshSession(n.getRefreshToken(),(i,s)=>{this.log("getSession:refreshSessionCallback",{refreshErr:i,refreshedSession:s}),i?(G.bind(this)(),r(i)):s.isValid()?t(s):(G.bind(this)(),r(new c("Invalid session.",{code:"INVALID_REQUEST"})));});})}function F(){if(!this.userPool)throw new c("User pool is missing",{code:"INVALID_REQUEST"});let n=()=>{let s=C.getSignInUserSession().getIdToken().payload||null,o=ae(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:d=false}=s||{};if(l&&d&&(d=false),C=this.userPool.getCurrentUser(),!C){this.log("getSession:cognitoUser",C),G.bind(this)(),a(null);return}let h=u=>{let m=u.getIdToken().payload;if(this.log("getSession:respond:sessionAttribute",m),m["custom:service"]!==this.service)throw this.log("getSession:respond","invalid service, signing out"),G.bind(this)(),new c("Invalid session.",{code:"INVALID_REQUEST"});return this.session=u,n(),d||this._runOnUserUpdateListeners(this.user),this.session};C.getSession((u,m)=>{if(this.log("getSession:getSessionCallback",{err:u,session:m}),!m){G.bind(this)(),a(new c("Current session does not exist.",{code:"INVALID_REQUEST"}));return}if(u){Ye.bind(this)(m,C).then(_=>o(h(_))).catch(a);return}let R=Math.floor(Date.now()/1e3),f=m.getIdToken(),A=f.getExpiration(),P=A<R;if(this.log("getSession:currentTime",R),this.log("getSession:idTokenExp",A),this.log("getSession:isExpired",P),this.log("getSession:existingBearerToken",this.bearerToken),this.bearerToken=f.getJwtToken(),P||l||!m.isValid())Ye.bind(this)(m,C).then(_=>o(h(_))).catch(a);else try{o(h(m));}catch(_){a(_);}});}),t=(s,o)=>{let a=o||s.includes(this.service+"-")?s:this.service+"-"+V.hash(s);return {cognitoUser:new CognitoUser({Username:a,Pool:this.userPool}),cognitoUsername:a}};return {getSession:e,authenticateUser:(s,o,a=false,l=false)=>new Promise((d,h)=>{this.__request_signup_confirmation=null,this.__disabledAccount=null;let u=t(s,a),m=u.cognitoUsername,R=new AuthenticationDetails({Username:m,Password:o});u.cognitoUser.authenticateUser(R,{newPasswordRequired:(f,A)=>{this.__disabledAccount=null,this.__request_signup_confirmation=m,f["custom:signup_ticket"]==="PASS"||f["custom:signup_ticket"]==="MEMBER"||f["custom:signup_ticket"]==="OIDPASS"?u.cognitoUser.completeNewPasswordChallenge(o,{},{onSuccess:P=>{C=u.cognitoUser,e().then(_=>d(this.user));},onFailure:P=>{h(new c(P.message||"Failed to authenticate user.",{code:P.code}));}}):h(new c("User's signup confirmation is required.",{code:"SIGNUP_CONFIRMATION_NEEDED"}));},onSuccess:f=>e({skipUserUpdateEventTrigger:true}).then(A=>{this.__disabledAccount=null,this._runOnLoginListeners(this.user),this._runOnUserUpdateListeners(this.user),d(this.user);}),onFailure:f=>{let A=[],{parsed:P,code:_}=be(f),x=typeof f?.message=="string"?f.message:"";if(_==="NotAuthorizedException"?x.includes("User is disabled.")?(this.__disabledAccount=m,A=["This account is disabled.","USER_IS_DISABLED"]):l?A=["The account already exists.","ACCOUNT_EXISTS"]:A=["Incorrect username or password.","INCORRECT_USERNAME_OR_PASSWORD"]:_==="UserNotFoundException"?A=["Incorrect username or password.","INCORRECT_USERNAME_OR_PASSWORD"]:_==="UserNotConfirmedException"?(this.__request_signup_confirmation=m,A=["User's signup confirmation is required.","SIGNUP_CONFIRMATION_NEEDED"]):(_==="TooManyRequestsException"||_==="LimitExceededException")&&(A=["Too many attempts. Please try again later.","REQUEST_EXCEED"]),P.code==="SIGNUP_CONFIRMATION_NEEDED"&&(this.__request_signup_confirmation=m),A.length){let k=A[1],T=A[0];h(new c(T,{code:k,cause:f}));}else h(P);}});}),createCognitoUser:t,signup:(s,o,a)=>new Promise((l,d)=>{this.userPool.signUp(s,o,a,null,(h,u)=>{if(h){let{parsed:m,code:R}=be(h),f=[];R==="UsernameExistsException"?f=["The account already exists.","EXISTS"]:R==="InvalidPasswordException"?f=["Invalid password. Password must be at least 6 characters.","INVALID_PARAMETER"]:R==="InvalidParameterException"?f=[m.message||"Invalid parameter.","INVALID_PARAMETER"]:R==="TooManyRequestsException"||R==="LimitExceededException"?f=["Too many attempts. Please try again later.","REQUEST_EXCEED"]:R==="CodeDeliveryFailureException"?f=["Failed to deliver verification code.","CODE_DELIVERY_FAILURE"]:R==="UserLambdaValidationException"&&(f=[m.message||"Signup validation failed.","INVALID_REQUEST"]),f.length?d(new c(f[0],{code:f[1],cause:h})):d(m);return}l(u);});})}}function be(n){let e=typeof n?.code=="string"&&n.code.trim()?n.code.trim():"ERROR",r=((typeof n?.message=="string"?n.message:typeof n=="string"?n:"An error occurred.")||"An error occurred.").trim();r||(r="An error occurred.");let i=r.match(/#([A-Za-z0-9_]+)\s*:\s*([\s\S]+)/),s=i?.[1]?.trim()||e,o=i?.[2]?.trim()||r;return {parsed:new c(o,{code:s,cause:n}),code:e}}async function st(n){await this.__authConnection;let e=n?.refreshToken||false;if(!e)return this.user;try{return await F.bind(this)().getSession(Object.assign({skipUserUpdateEventTrigger:!e,refreshToken:e},n)),this.user}catch{return null}}async function ot(n){await this.__connection,n=g.Params(n,{token:"string",id:"string",merge:s=>{if(s===void 0)return false;if(typeof s=="string")return [s];if(Array.isArray(s)){for(let o of s)if(typeof o!="string")throw new c('"merge" array items should be type: <string>.',{code:"INVALID_PARAMETER"})}if(typeof s!="boolean"&&!Array.isArray(s))throw new c('"merge" should be type: <boolean | string[]>.',{code:"INVALID_PARAMETER"});return s}});let e=await w.bind(this)("openid-logger",n),t=e.logger.split("#"),r=this.service+"-"+t[0],i=t[1];return {userProfile:await F.bind(this)().authenticateUser(r,i,true,true),openid:e.openid}}function pr(n){let e=typeof globalThis<"u"?globalThis:void 0;if(e?.Buffer)return e.Buffer.from(n,"base64").toString("utf8");if(typeof atob=="function"){let t=atob(n),r=new Uint8Array(t.length);for(let i=0;i<t.length;i++)r[i]=t.charCodeAt(i);return typeof TextDecoder<"u"?new TextDecoder().decode(r):t}throw new Error("No base64 decoder available in this environment")}function mr(n){let e=n.split(".");if(e.length!==3)throw new Error("Invalid JWT format");let r=e[1].replace(/-/g,"+").replace(/_/g,"/"),i=pr(r);return JSON.parse(i)}async function at(n){await this.__authConnection,this.log("loginWithToken:params",n),n=g.Params(n,{idToken:"string",accessToken:"string",refreshToken:"string"},["idToken"]);let e=mr(n.idToken);if(this.log("loginWithToken:idTokenPayload",e),e["custom:service"]!==this.service)throw new c("Token does not belong to this service.",{code:"INVALID_REQUEST"});let t=Math.floor(Date.now()/1e3);if(e.exp&&e.exp<t)throw new c("Token has expired.",{code:"INVALID_REQUEST"});if(this.__user=ae(e),this.session=null,n.accessToken&&n.refreshToken)try{if(this.session=new CognitoUserSession({IdToken:new CognitoIdToken({IdToken:n.idToken}),AccessToken:new CognitoAccessToken({AccessToken:n.accessToken}),RefreshToken:new CognitoRefreshToken({RefreshToken:n.refreshToken})}),this.log("loginWithToken:session",this.session),this.log("loginWithToken:CognitoUser",CognitoUser),this.log("loginWithToken:userPool",this.userPool),CognitoUser&&this.userPool){this.log("loginWithToken:cognito:username",e["cognito:username"]);let r={Username:e["cognito:username"],Pool:this.userPool};this.log("loginWithToken:cognitoUserParams",r),C=new CognitoUser(r),C.setSignInUserSession(this.session),this.log("loginWithToken:cognitoUserRestored",{cognitoUserType:typeof C,cognitoUserKeys:Object.keys(C||{}),cognitoUser:C});}}catch(r){this.log("loginWithToken:err",r);try{this.log("loginWithToken:err:stringified",JSON.stringify(r));}catch{this.log("loginWithToken:err:stringifyFail",String(r));}try{let i=Object.keys(r||{}),s=Object.getOwnPropertySymbols?Object.getOwnPropertySymbols(r||{}):[],o=Object.getOwnPropertyDescriptors?Object.getOwnPropertyDescriptors(r||{}):{};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 M(){return await this.__connection,this.__user?.service===this.service?this.__user?.owner===this.host:(await ce.bind(this)(),false)}async function G(n=false){let e=null;C&&(n?e=new Promise((r,i)=>{C.globalSignOut({onSuccess:s=>{this.log("globalSignOut:success",s),r(s);},onFailure:s=>{this.log("globalSignOut:error",s),i(s);}});}):C.signOut());let t={session:null,__startKeyHistory:{},__cached_requests:{},__user:null};e&&(e=await e);for(let r in t)this[r]=t[r];return this._runOnUserUpdateListeners(null),this._runOnLoginListeners(null),e}async function ce(n){await this.__connection;let{data:e}=N(n);return await G.bind(this)(e?.global),"SUCCESS: The user has been logged out."}async function ct(){if(!this.__request_signup_confirmation)throw new c("Least one login attempt is required.",{code:"INVALID_REQUEST"});return await w.bind(this)("confirm-signup",{username:this.__request_signup_confirmation})}async function lt(n=false){if(typeof n=="string")n=g.Url(n);else if(typeof n!="boolean")throw new c("Argument should be type: <boolean | string>.",{code:"INVALID_REQUEST"});if(!this.__disabledAccount)throw new c("Least one signin attempt of disabled account is required.",{code:"INVALID_REQUEST"});return await w.bind(this)("recover-account",{username:this.__disabledAccount,redirect:n}),"SUCCESS: Recovery e-mail has been sent."}async function Ce(n){let e=g.Params(n,{username:"string",email:"string",password:"string"},["password"]);if(await this.__authConnection,e.email)try{g.Email(e.email);}catch{e.username=e.email,delete e.email;}if(!e.username&&!e.email)throw new c('Least one of "username" or "email" is required.',{code:"INVALID_PARAMETER"});return await F.bind(this)().authenticateUser(e.username||e.email,e.password)}async function ut(n,e){await this.__authConnection;let t={username:"string",password:d=>g.Password(d),email:d=>g.Email(d),name:"string",address:d=>{if(!d)return "";if(typeof d=="string")return d;if(typeof d=="object")return JSON.stringify(d)},gender:"string",birthdate:d=>d?g.Birthdate(d):"",phone_number:d=>d?g.PhoneNumber(d):"",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:d=>d?g.Url(d):"",profile:d=>d?g.Url(d):"",family_name:"string",given_name:"string",middle_name:"string",nickname:"string",website:d=>d?g.Url(d):""},r=g.Params(n||{},t,["email","password"]);await ce.bind(this)(),e=g.Params(e||{},{email_subscription:d=>{if(typeof d!="boolean")throw new c('"option.email_subscription" should be type: <boolean>.',{code:"INVALID_PARAMETER"});if(!e?.signup_confirmation)throw new c('"option.signup_confirmation" is required for email subscription.',{code:"INVALID_PARAMETER"});return d},signup_confirmation:d=>{let h=d;if(typeof d=="string")h=g.Url(d);else if(typeof d=="boolean")h=d;else throw new c('"option.signup_confirmation" should be type: <string | boolean>.',{code:"INVALID_PARAMETER"});if(h&&!r.email)throw new c('"email" is required for signup confirmation.',{code:"INVALID_PARAMETER"});return h},login:d=>{if(typeof d=="boolean"){if(e.signup_confirmation&&d)throw new c('"login" is not allowed when "option.signup_confirmation" is true.',{code:"INVALID_PARAMETER"});return d}throw new c('"option.login" should be type: boolean.',{code:"INVALID_PARAMETER"})}});let i=e?.login||false;if(r.signup_confirmation=e?.signup_confirmation||false,r.email_subscription=e?.email_subscription||false,r.email_public&&!r.signup_confirmation)throw new c('"option.signup_confirmation" should be true if "email_public" is set to true.',{code:"INVALID_PARAMETER"});r.service=this.service,r.owner=this.owner;let s=F.bind(this)().createCognitoUser(r.username||r.email);for(let d of ["email_public","address_public","gender_public","birthdate_public","phone_number_public"])r[d]=r[d]?"1":"0";r.access_group&&(r.access_group=r.access_group.toString());let o=(await w.bind(this)("signupkey",{username:s.cognitoUsername,signup_confirmation:typeof r.signup_confirmation=="boolean"?JSON.stringify(r.signup_confirmation):r.signup_confirmation,email_subscription:r.email_subscription})).split(":"),a=o.slice(1).join(":"),l=[new CognitoUserAttribute({Name:"custom:signup",Value:o[0]}),new CognitoUserAttribute({Name:"locale",Value:a.split("#")[1]}),new CognitoUserAttribute({Name:"custom:signup_ticket",Value:a})];for(let d in t){let h=["email_public","address_public","gender_public","birthdate_public","phone_number_public","misc","service","owner"];r[d]!==""&&(d==="username"||d==="password"||d==="access_group"||(h.includes(d)?l.push(new CognitoUserAttribute({Name:"custom:"+d,Value:r[d]})):l.push(new CognitoUserAttribute({Name:d,Value:r[d]}))));}return await F.bind(this)().signup(s.cognitoUsername,r.password,l),r.signup_confirmation?(C=s.cognitoUser,this.__request_signup_confirmation=s.cognitoUsername,"SUCCESS: The account has been created. User's signup confirmation is required."):i?Ce.bind(this)({email:r.username||r.email,password:r.password}):"SUCCESS: The account has been created."}async function dt(){await this.__connection;let n=await w.bind(this)("remove-account",{disable:this.__user.user_id},{auth:true});return await ce.bind(this)(),n}async function gt(n){await this.__connection;let e=g.Params(n,{email:i=>g.Email(i),code:["number","string"],new_password:i=>g.Password(i)},["email","code","new_password"]),t=e.code,r=e.new_password;return typeof t=="number"&&(t=t.toString()),new Promise(async(i,s)=>{F.bind(this)().createCognitoUser(e.email).cognitoUser.confirmPassword(t,r,{onSuccess:a=>{i("SUCCESS: New password has been set.");},onFailure:a=>{s(new c(a?.message||"Failed to reset password.",{code:a?.code||"ERROR",cause:a}));}});})}async function ft(n,e){await this.__connection;let t;if(!C)throw new c("The user has to be logged in.",{code:"INVALID_REQUEST"});if(n==="email"||n==="phone_number"){if(!this.__user.hasOwnProperty(n))throw new c(`No ${n==="email"?"e-mail":"phone number"} to verify`,{code:"INVALID_REQUEST"});if(this.__user?.[`${n}_verified`])return `SUCCESS: "${n}" is verified.`;t=(e?g.Params(e,{code:"string"}):{}).code||"";}else return;return new Promise((r,i)=>{let s={onSuccess:o=>{t?F.bind(this)().getSession({refreshToken:true}).then(()=>{this.__user&&(this.__user[n+"_verified"]=true),r(`SUCCESS: "${n}" is verified.`);}).catch(a=>{i(a);}):r("SUCCESS: Verification code has been sent.");},onFailure:o=>{i(new c(o.message||"Failed to request verification code.",{code:o?.code}));}};t?C?.verifyAttribute(n,t,s):(s.inputVerificationCode=null,C?.getAttributeVerificationCode(n,s));})}function ht(n){return ft.bind(this)("phone_number",n)}function pt(n){return ft.bind(this)("email",n)}async function mt(n){await this.__connection;let e=g.Params(n,{email:t=>g.Email(t)},["email"]);return new Promise(async(t,r)=>{F.bind(this)().createCognitoUser(e.email).cognitoUser.forgotPassword({onSuccess:s=>{t("SUCCESS: Verification code has been sent.");},onFailure:s=>{let{parsed:o,code:a}=be(s),l={UserNotFoundException:"NOT_EXISTS",InvalidParameterException:"INVALID_PARAMETER",NotAuthorizedException:"INVALID_REQUEST",LimitExceededException:"REQUEST_EXCEED",TooManyRequestsException:"REQUEST_EXCEED",CodeDeliveryFailureException:"CODE_DELIVERY_FAILURE"}[a]||o.code||a||"ERROR";r(new c(o.message,{code:l,cause:s}));}});})}async function _t(n){if(await this.__connection,!this.session)throw new c("User login is required.",{code:"INVALID_REQUEST"});let e=g.Params(n,{current_password:"string",new_password:"string"});if(!e?.current_password)throw new c('"current_password" is required to change password.',{code:"INVALID_PARAMETER"});if(!e?.new_password)throw new c('"new_password" is required to change password.',{code:"INVALID_PARAMETER"});return g.Password(e.current_password),g.Password(e.new_password),new Promise((t,r)=>{C.changePassword(e.current_password,e.new_password,(i,s)=>{if(i){if(i?.code==="InvalidParameterException")r(new c("Invalid password parameter.",{code:"INVALID_PARAMETER"}));else if(i?.code==="NotAuthorizedException")r(new c("Incorrect password.",{code:"INVALID_REQUEST"}));else if(i?.code==="TooManyRequestsException"||i?.code==="LimitExceededException")r(new c("Too many attempts. Please try again later.",{code:"REQUEST_EXCEED"}));else {let{parsed:o}=be(i);r(o);}return}t("SUCCESS: Password has been changed.");});})}async function bt(n){if(await this.__connection,!this.session)throw new c("User login is required.",{code:"INVALID_REQUEST"});let e=g.Params(n||{},{user_id:i=>g.UserId(i),email:i=>g.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?g.Birthdate(i):"",phone_number:i=>i?g.PhoneNumber(i):"",email_public:"boolean",phone_number_public:"boolean",address_public:"boolean",gender_public:"boolean",birthdate_public:"boolean",misc:"string",picture:i=>i?g.Url(i):"",profile:i=>i?g.Url(i):"",family_name:"string",given_name:"string",middle_name:"string",nickname:"string",website:i=>i?g.Url(i):""});if(e&&typeof e=="object"&&!Object.keys(e).length)return this.user;e.email&&(e.preferred_username=this.service+"-"+V.hash(e.email));let t=[["email_public","email_verified","User's e-mail should be verified to set"],["phone_number_public","phone_number_verified","User's phone number should be verified to set"]];if(this.__user){for(let i of t)if(e[i[0]]&&!this.__user[i[1]])throw new c(`${i[2]} "${i[0]}" to true.`,{code:"INVALID_REQUEST"})}let r=[];for(let i in e){if(e[i]===this.user[i]){r.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,r.push(i);}}for(let i of r)delete e[i];if(e.user_id)if(e.user_id===this.user.user_id)delete e.user_id;else return w.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 CognitoUserAttribute({Name:s,Value:e[s]}));return await new Promise((s,o)=>{C?.updateAttributes(i,(a,l)=>{a&&o([a?.code||a?.name,a?.message||"Failed to update user settings."]),s(l);});}),await F.bind(this)().getSession({refreshToken:true}),this.user}return this.user}async function yt(n,e){n=N(n).data,n||(n={searchFor:"timestamp",condition:">",value:0},e||(e={}),e.ascending=false),await this.__connection;let t={user_id:i=>Array.isArray(i)?i.map(s=>g.UserId(s)):g.UserId(i),email:"string",phone_number:"string",locale:i=>{if(typeof i!="string"||typeof i=="string"&&i.length>5)throw new c('Value of "locale" should be a country code.',{code:"INVALID_PARAMETER"});return i},name:"string",address:"string",gender:"string",birthdate:i=>g.Birthdate(i),subscribers:"number",timestamp:"number",access_group:"number",approved:"string"},r=["searchFor","value"];if(n=g.Params(n,{searchFor:["user_id","name","email","phone_number","address","gender","birthdate","locale","subscribers","timestamp","access_group","approved"],condition:[">",">=","=","<","<=","gt","gte","eq","lt","lte",()=>"="],value:i=>{let s=t[n.searchFor];if(typeof s=="function")return s(i);if(typeof i!==s)throw new c(`Value does not match the type of "${n.searchFor}" index.`,{code:"INVALID_PARAMETER"});return i},range:i=>{let s=t[n.searchFor];if(typeof s=="function")return s(i);if(typeof i!==s)throw new c(`Range does not match the type of "${n.searchFor}" index.`,{code:"INVALID_PARAMETER"});return i}},r),n?.condition&&n?.condition!=="="&&n.hasOwnProperty("range"))throw new c("Conditions does not apply on range search.",{code:"INVALID_PARAMETER"});if(n.searchFor==="user_id"&&(n.condition!=="="||n.range))throw new c(`Conditions are not allowed on "${n.searchFor}"`,{code:"INVALID_PARAMETER"});if(typeof n?.value=="string"&&!n?.value)throw new c("Value should not be an empty string.",{code:"INVALID_PARAMETER"});if(typeof n?.searchFor=="string"&&!n?.searchFor)throw new c('"searchFor" should not be an empty string.',{code:"INVALID_PARAMETER"});return w.bind(this)("get-users",n,{auth:true,fetchOptions:e})}async function wt(n){await this.__connection;let e=await w.bind(this)("last-verified-email",n,{auth:true});return e.includes("SUCCESS")?(await F.bind(this)().getSession({refreshToken:true}),this.user):e}async function Et(n){return await this.__connection,n=g.Params(n,{username:g.Email,redirect:g.Url},["username"]),await w.bind(this)("request-username-change",n,{auth:true})}var re=null,At=typeof SubmitEvent<"u",br=typeof HTMLFormElement<"u",ue=$(),Le=0;function It(n){if(!n)return null;let e=Number(n);if(Number.isFinite(e))return Math.max(0,e*1e3);let t=Date.parse(n);return Number.isNaN(t)?null:Math.max(0,t-Date.now())}function Oe(n,e){return e>0?n/e*100:0}var Rt=n=>{let{auth:e,type:t,endpoints:r}=n,i=r[0],s=r[1];if(Le++,t==="admin"){let o=Object.entries(i).filter(([a,l])=>a.includes(e?"_private":"_public")&&a!=="get_users_private"&&a!=="service_public"&&typeof l=="string").map(([,a])=>a);if(!o.length)throw new c("No available admin gateways.",{code:"INVALID_REQUEST"});return o[Le%o.length]}if(t==="record"){let o=Object.entries(s).filter(([a,l])=>a.includes(e?"record_private":"record_public")&&typeof l=="string").map(([,a])=>a);if(!o.length)throw new c("No available record gateways.",{code:"INVALID_REQUEST"});return o[Le%o.length]}throw new c("Invalid gateway type.",{code:"INVALID_REQUEST"})};async function yr(n,e){let t=await Promise.all([this.admin_endpoint,this.record_endpoint]),r=t[0],i=t[1],s=n.split("?"),o=s.length>1?"?"+s[1]:"";switch(n=s[0],n){case "get-users":return r.get_users_private+n+o;case "service":return r.service_public+n+o;case "get-newsletters":case "get-public-newsletters":case "subscribe-newsletter":case "subscribe-public-newsletter":case "signupkey":case "admin-newsletter-request":case "admin-signup":case "confirm-signup":case "openid-logger":case "block-account":case "admin-edit-profile":case "remove-account":case "post-secure":case "recover-account":case "mock":case "grant-access":case "last-verified-email":case "ticket":case "register-ticket":case "get-newsletter-subscription":case "request-username-change":case "send-inquiry":case "register-newsletter-group":case "newsletter-group-endpoint":case "invitation-list":case "csr":case "csr-poll":return Rt.bind(this)({auth:e,type:"admin",endpoints:t})+n+o;case "post-record":return (e?i.post_private:i.post_public)+n+o;case "get-records":return (e?i.get_private:i.get_public)+n+o;case "del-files":case "del-records":return i.del_private+n+o;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 "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 Rt.bind(this)({auth:e,type:"record",endpoints:t})+n+o;default:return g.Url(n)+o}}var le={};function Tt(){re&&(re.terminate(),re=null);}async function w(n,e=null,t,r){this.log("request",{url:n,data:e,options:t,_etc:r||{}}),t=t||{};let{auth:i=false,method:s="post",bypassAwaitConnection:o=false}=t;s=s.toUpperCase();let a=null,l=e?.service||this.service,d=e?.owner||this.owner,h=null,u=await yr.bind(this)(n,!!i);if(!o&&(a=await this.__connection,!a))throw new c("Invalid connection. The service could have been disabled, or has a restricted CORS.",{code:"INVALID_REQUEST"});let m=t?.tokenHeaders?.idToken===true;(i||m)&&(h=await ne.bind(this)());let R={},{fetchMore:f=false,progress:A}=t?.fetchOptions||{};if(t?.fetchOptions&&Object.keys(t.fetchOptions).length){for(let S of ["limit","startKey","ascending"])if(t.fetchOptions.hasOwnProperty(S)){if(S==="startKey"&&t.fetchOptions[S]===null)continue;R[S]=t.fetchOptions[S];}R=g.Params(R,{limit:S=>{if(typeof S!="number")throw new c("Fetch limit should be a number.",{code:"INVALID_REQUEST"});if(S>1e3)throw new c("Fetch limit should be below 1000.",{code:"INVALID_REQUEST"});return S},startKey:S=>S,ascending:"boolean"});}let P=r?.ignoreService?{}:{service:l,owner:d};Object.assign(P,R),e=N(e).data,e?e&&typeof e=="object"&&(e=Object.assign(P,e)):e=P;let _=`${s}:${i?"auth":"public"}:${n}`,x=(()=>{if(e&&typeof e=="object"&&Object.keys(e).length&&!(ue&&e instanceof FormData)){let S=function(D){return typeof D=="object"&&D!==null?Object.keys(D).sort().reduce((U,L)=>(typeof D[L]=="object"&&D[L]!==null?U[L]=S(D[L]):U[L]=D[L],U),{}):D};return V.hash(_+"/"+JSON.stringify(S(e)))}return V.hash(_+"/"+l)})(),{requestKey:k,requestKeyWithStartKey:T}=wr.bind(this)({params:e,url:n,fetchMore:f,hashedParams:x});if(!k||k&&typeof k=="object")return k;if(this.log("requestKey",T),typeof T=="string"&&le[T]instanceof Promise)return this.log("request:returning pending",T),le[T];let v={Accept:"*/*"};if(Object.prototype.hasOwnProperty.call(t,"contentType")&&t.contentType!==void 0){let S=t.contentType===null?"application/x-www-form-urlencoded":t.contentType;S&&(v["Content-Type"]=S);}else v["Content-Type"]="application/json";if(h&&(v.Authorization=h),t?.tokenHeaders){let S=(L,On)=>typeof L=="string"?L:L===true?On:null,D=S(t.tokenHeaders.accessToken,this.session?.accessToken?.jwtToken||null),U=S(t.tokenHeaders.idToken,this.bearerToken||this.session?.idToken?.jwtToken||h||null);D&&(v["X-Access-Token"]=D),U&&(v["X-Id-Token"]=U);}let xe={public_identifier:this.__public_identifier,service:l,owner:d};v["Content-Meta"]=JSON.stringify(xe);let q={headers:v};if(t?.responseType&&(q.responseType=t.responseType),s==="GET"){if(e){let S=[];if(ue&&e instanceof FormData?S=Array.from(e.entries()).map(([D,U])=>{let L=typeof U=="string"?U:U.name;return encodeURIComponent(D)+"="+encodeURIComponent(L)}):S=Object.keys(e).map(D=>{let U=e[D];return typeof U!="string"&&(U=JSON.stringify(U)),encodeURIComponent(D)+"="+encodeURIComponent(U)}),S.length){let D=u.includes("?")?u.endsWith("?")||u.endsWith("&")?"":"&":"?";u+=D+S.join("&");}}q.body=null;}else if(ue&&e instanceof FormData)q.body=e;else if(v["Content-Type"]==="application/x-www-form-urlencoded"&&e&&typeof e=="object"){let S=new URLSearchParams;for(let D of Object.keys(e)){let U=e[D];S.append(D,typeof U=="string"?U:JSON.stringify(U));}q.body=S.toString();}else typeof e=="string"?q.body=e:q.body=e?JSON.stringify(e):null;if(q.method=s,re===null){let S={batchSize:this.requestBatchSize,breakWhenError:false,onProgress:D=>{this.onBatchProcess.forEach(U=>U(D));}};re=new _r(S);}return this.log("request-opt",q),new Promise((S,D)=>{re.add([async()=>{let U=Pt.bind(this)(u,q,A);le[T]=U;try{let L=Er.bind(this)({hashedParam:k,requestKeyWithStartKey:T,url:n,fetched:await U});return delete le[T],this.log("request:end",L),S(L),L}catch(L){throw delete le[T],this.log("request:err",L),D(L),L}}]);})}function wr(n){let{params:e={},url:t,fetchMore:r=false,hashedParams:i}=n||{};if(e.startKey){if(!(typeof e.startKey=="object"&&Object.keys(e.startKey).length)&&e.startKey!=="start"&&e.startKey!=="end")throw new c(`"${e.startKey}" is invalid startKey key.`,{code:"INVALID_PARAMETER"});e.startKey==="start"&&(r=false,delete e.startKey);}if(!r){if(this.__cached_requests?.[t]?.[i]&&delete this.__cached_requests[t][i],this.__startKeyHistory?.[t]?.[i]){if(Array.isArray(this.__startKeyHistory[t][i])&&this.__startKeyHistory[t][i].length)for(let l of this.__startKeyHistory[t][i]){let d=i+V.hash(l);this.__cached_requests?.[t]&&this.__cached_requests?.[t]?.[d]&&delete this.__cached_requests[t][d];}delete this.__startKeyHistory[t][i];}return {requestKeyWithStartKey:i,requestKey:i}}if(!Array.isArray(this.__startKeyHistory?.[t]?.[i]))return {requestKeyWithStartKey:i,requestKey:i};let s=this.__startKeyHistory[t][i],o=s[s.length-1],a=i;if(o){if(o==="end")return {requestKey:{list:[],startKey:"end",endOfList:true,startKeyHistory:s},requestKeyWithStartKey:a};a+=V.hash(o),e.startKey=JSON.parse(o);}return this.__cached_requests?.[t]?.[a]?{requestKey:this.__cached_requests[t][a],requestKeyWithStartKey:a}:{requestKeyWithStartKey:a,requestKey:i}}function Pt(n,e,t){return new Promise((r,i)=>{let s=new XMLHttpRequest;s.open(e.method||"GET",n);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")r(s.response);else {let a=s.responseText;try{a=JSON.parse(a);}catch{}r(a);}else if(s.status===429){let a=s.getResponseHeader("Retry-After"),l=It(a);l!==null?setTimeout(()=>{Pt(n,e,t).then(r,i);},l):i("Too many requests");}else {let a=s.status,l=["INVALID_CORS","INVALID_REQUEST","SERVICE_DISABLED","INVALID_PARAMETER","ERROR","EXISTS","NOT_EXISTS"],d=e.responseType=="blob"?s.response:s.responseText;try{d=JSON.parse(d);}catch{}if(typeof d=="string"){let h=d.split(":"),u=h.splice(0,1)[0].trim(),m=h.join(":").trim();i(new c(m||d,{code:l.includes(u)?u:"ERROR"}));}else if(typeof d=="object"&&d?.message){let h=d?.code||(a?a.toString():null)||"ERROR",u=d.message,m=d?.cause;typeof u=="string"&&(u=u.trim()),i(new c(u,{cause:m,code:h}));}else i(d);}},s.onerror=()=>i("Network error"),s.onabort=()=>i("Aborted"),s.ontimeout=()=>i("Timeout"),typeof t=="function"&&(s.onprogress=a=>{t({status:"download",progress:Oe(a.loaded,a.total),loaded:a.loaded,total:a.total,abort:()=>s.abort()});},s.upload&&(s.upload.onprogress=a=>{t({status:"upload",progress:Oe(a.loaded,a.total),loaded:a.loaded,total:a.total,abort:()=>s.abort()});})),s.send(e.body);})}function Er(n){let{hashedParam:e,requestKeyWithStartKey:t,url:r,fetched:i}=n;if(!i?.startKey)return i;this.__startKeyHistory.hasOwnProperty(r)||(this.__startKeyHistory[r]={}),this.__startKeyHistory[r].hasOwnProperty(e)||(this.__startKeyHistory[r][e]=[]);let s=i.startKey==="end"?"end":JSON.stringify(i.startKey);return this.__startKeyHistory[r][e].includes(s)||this.__startKeyHistory[r][e].push(s),this.__cached_requests?.[r]||(this.__cached_requests[r]={}),this.__cached_requests[r][t]=i,Object.assign({startKeyHistory:this.__startKeyHistory[r][e]},i)}async function we(n,e){await this.__connection;let{record_id:t,service:r=this.service,progress:i}=e;if(!t)throw new c('"record_id" is required.',{code:"INVALID_PARAMETER"});if(At&&n instanceof SubmitEvent&&(n=n.target),br&&n instanceof HTMLFormElement&&(n=new FormData(n)),!ue||!(n instanceof FormData))throw new c('"fileList" should be a FormData or HTMLFormElement.',{code:"INVALID_PARAMETER"});let o={reserved_key:oe(),service:r,request:"post"};e?.record_id&&(o.id=e.record_id);let a,l=(R,f,A)=>new Promise((P,_)=>{a=new XMLHttpRequest,a.open("POST",R),a.onload=()=>{let x=a.responseText;try{x=JSON.parse(x);}catch{}if(a.status>=200&&a.status<300)P(x);else if(a.status===429){let k=a.getResponseHeader("Retry-After"),T=It(k);T!==null?setTimeout(()=>{l(R,f,A).then(P,_);},T):_("Too many requests");}else _(x);},a.onerror=()=>_("Network error"),a.onabort=()=>_("Aborted"),a.ontimeout=()=>_("Timeout"),a.upload&&typeof A=="function"&&(a.upload.onprogress=A),a.send(f);});function d(R){let f="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";if(R===0)return f[0];let A="";for(;R>0;)A=f[R%62]+A,R=Math.floor(R/62);return A}let h=[],u=[],m=[];for(let[R,f]of n.entries()){if(!(f instanceof File))continue;let A=Object.assign({key:R+"/"+f.name,sizeKey:d(f.size),contentType:f.type||null},o),{fields:P=null,url:_,cdn:x}=await w.bind(this)("get-signed-url",A,{auth:!!this.__user});m.push(x);let k=new FormData;for(let T in P)k.append(T,P[T]);k.append("file",f);try{await l(_,k,typeof i=="function"?T=>i({status:"upload",progress:Oe(T.loaded,T.total),currentFile:f,completed:h,failed:u,loaded:T.loaded,total:T.total,abort:()=>a.abort()}):null),h.push(f);}catch{u.push(f);}}return {completed:h,failed:u,bin_endpoints:m}}var ye={};function E(n){let{preventMultipleCalls:e=false}=n||{};return function(t,r,i){let s=i.value;i.value=function(...o){let a=o[0],l=true,d=null,h="",u={},m=false;if(At&&a instanceof SubmitEvent){a.preventDefault();let _=window.location.href;d=a.target;let x=new URL(d.action);h=x.href;let k=h?h.match(/(?<=\{).*?(?=\})/g):"";if(k)for(let T of k){if(!T)continue;let v=d.querySelector(`[name="${T}"]`);if(v)if(v.type==="file")for(let Q=0;Q<=v.files.length-1;Q++)v.files[Q]&&(u[T]||(u[T]=[]),u[T].push(new Promise((xe,q)=>{let S=new FileReader;S.onload=function(){xe(S.result);},S.readAsDataURL(v.files[Q]),S.onerror=q;})));else h=h.replace(`{${T}}`,v.value);}d.getAttribute("action")===null?l=false:m=x.href===_;}let R=async _=>{if(h)for(let x in u)u[x].length&&(h=h.replace(`{${x}}`,(await Promise.all(u[x])).join(",")));return d&&l&&(window.sessionStorage.setItem(`${this.service}:${V.hash(h)}`,JSON.stringify(_)),m?window.location.replace(h):window.location.href=h),_},f,A=_=>{throw _ instanceof c?_.name=r+"()":_=_ instanceof Error?_:new c(_,{name:r+"()"}),_},P=async()=>{try{if(f=s.bind(this)(...o),f instanceof Promise){let _=await f;return R(_)}return R(f)}catch(_){throw A(_)}};if(e){let _=`${r}:${this?.__public_identifier||""}:${this?.service||""}:${this?.owner||""}`;return ye?.[_]||(ye[_]=P().finally(()=>{delete ye[_];})),ye[_]}return P()};}}async function St(){await this.__connection;let n=`${this.service}:${V.hash(window.location.href.split("?")[0])}`,e=window.sessionStorage.getItem(n);if(window.sessionStorage.removeItem(n),e!==null){try{e=JSON.parse(e);}catch{}return e}return null}var Rr=128,Ar=64,Ir=128,Tr=256,Pr="\u{10FFFF}",Sr=/[\u0000-\u001F\u007F]|\u{10FFFF}/u,kr=/[\/!*#]/;function X(n,e,t={}){let{allowEmpty:r=false,maxLength:i,blockKeyDelimiters:s=false,disallowLeadingDollar:o=false,onlyAlphanumeric:a=false}=t;if(typeof n!="string")throw new c(`"${e}" should be type: <string>.`,{code:"INVALID_PARAMETER"});if(a&&/[^a-zA-Z0-9]/.test(n))throw new c(`"${e}" should only contain alphanumeric characters.`,{code:"INVALID_PARAMETER"});if(!r&&n.length===0)throw new c(`"${e}" is required.`,{code:"INVALID_PARAMETER"});if(i&&n.length>i)throw new c(`"${e}" should be <= ${i} characters.`,{code:"INVALID_PARAMETER"});if(Sr.test(n)||n.includes(Pr))throw new c(`"${e}" cannot include control characters or unsupported sentinel characters.`,{code:"INVALID_PARAMETER"});if(s&&kr.test(n))throw new c(`"${e}" cannot include reserved delimiters: / ! * #`,{code:"INVALID_PARAMETER"});if(o&&n.startsWith("$"))throw new c(`"${e}" cannot start with "$".`,{code:"INVALID_PARAMETER"});return n}function Fe(n,e="table.name"){return X(n,e,{allowEmpty:false,maxLength:Rr,blockKeyDelimiters:true})}function Me(n,e="tag"){return X(n,e,{allowEmpty:false,maxLength:Ar,blockKeyDelimiters:true})}function de(n,e="index.name"){return X(n,e,{allowEmpty:false,maxLength:Ir,blockKeyDelimiters:true,disallowLeadingDollar:true})}function kt(n,e="index.value"){return X(n,e,{allowEmpty:true,maxLength:Tr})}function xt(n){if(!n.record_id&&!n.unique_id)return null;let e={};return n?.service&&(e.service=n.service),n?.owner&&(e.owner=n.owner),n?.record_id?e.record_id=X(n.record_id,"record_id",{allowEmpty:false,onlyAlphanumeric:true}):n?.unique_id&&(e.unique_id=n.unique_id),e}function Ve(n){if(n===void 0)return 0;if(typeof n=="number"){if(n>99||n<0)throw new c('"table.access_group" value should be within a range of 0 ~ 99.',{code:"INVALID_REQUEST"})}else if(typeof n=="string"){if(n={private:"private",public:0,authorized:1,admin:99}[n],n===void 0)throw new c('"table.access_group" is invalid.',{code:"INVALID_PARAMETER"})}else throw new c('"table.access_group" should be type: <number | string>.',{code:"INVALID_PARAMETER"});if(!this.__user&&n)throw new c("Unsigned users have no access to records with access group.",{code:"INVALID_REQUEST"});return n}var Ee=4503599627370496;function Re(n){if(typeof n=="number"){if(n>Ee||n<-Ee)throw new c(`Number value should be within range -${Ee} ~ +${Ee}`,{code:"INVALID_PARAMETER"});return n}if(typeof n=="boolean")return n;if(typeof n=="string")return kt(n,"index.value");throw new c('"index.value" should be type: <number | boolean | string>.',{code:"INVALID_PARAMETER"})}function vt(n,e){if(!e.index||!("value"in e.index))throw new c('"index.value" is required.',{code:"INVALID_PARAMETER"});if(e.index.name==="$record_id")throw new c(`Cannot do "index.range" on ${e.index.name}`,{code:"INVALID_PARAMETER"});if(typeof e.index.value!=typeof n)throw new c('"index.range" type should match the type of "index.value".',{code:"INVALID_PARAMETER"});return typeof n=="string"?kt(n,"index.range"):n}var Ae={};async function ie(n,e){let t={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:{}},r=false;function i(o){let a=o=="**"?"private":parseInt(o);return a=a==0?"public":a==1?"authorized":a==99?"admin":a,a}let s={ip:o=>{let a=o.split("#"),l=a[0];a.length>1&&(t.unique_id=a[1]),l.slice(-1)==="R"?(t.readonly=true,l=l.slice(0,-1)):t.readonly=false,/^\d{1,3}-\d{1,3}-\d{1,3}-\d{1,3}$/.test(l)&&(l=l.split("-").join("."),r=true),t.ip=l;},rec:o=>{if(!o)return;t.record_id=o;let a=o.substring(0,o.length-9),l=j(a);t.uploaded=l;},usr:o=>{t.user_id=o;},tbl:o=>{if(o&&!t.table.name){let a=o.split("/");t.table.name=a[0],t.table.access_group=i(a[2]),a?.[3]&&(t.table.subscription.is_subscription_record=true);}},usr_tbl:o=>{let a=o.split("/");t.user_id||(t.user_id=a[0]),t.table.name||(t.table.name=a[1],t.table.access_group=i(a[3]),a?.[4]&&(t.table.subscription.is_subscription_record=true));},idx:o=>{if(!o)return;let a=o.split("!"),l=a.splice(0,1)[0],d=xr("!"+a.join("!"));t.index={name:l,value:d};},ref:o=>{o&&(t.reference=o.split("/")[0]);},tags:o=>{t.tags=o;},upd:o=>{t.updated=o;},acpt_mrf:o=>{t.source.prevent_multiple_referencing=!o;},ref_limt:o=>{t.source.referencing_limit=o;},rfd:o=>{t.referenced_count=o;},bin:async o=>{let a={},l=t?.reference||null;if(Array.isArray(o)){let d=await Promise.all(o.map(async h=>{try{let u=h.split("/").slice(3).join("/"),m=u.split("/");if(m.length<12)return null;let R=decodeURIComponent(m[m.length-1]),f=decodeURIComponent(m[10]),A=m[9],P=m[8],_=i(m[6]),x=h;if(_!=="public")try{x=await Ie.bind(this)(h,{dataType:"endpoint",_ref:l});}catch(T){console.error("Error getting signed url for private file:",T),x=h;}let k={access_group:_,filename:R,url:x,path:u,size:j(A),uploaded:j(P),getFile:(T,v)=>{let Q={dataType:T||"download",progress:v,_ref:l,_update:k};return Ie.bind(this)(x,Q)}};return {pathKey:f,obj:k}}catch{return null}}));for(let h of d)if(h){if(a[h.pathKey]){a[h.pathKey].push(h.obj);continue}a[h.pathKey]=[h.obj];}}t.bin=a;},prv_acs:o=>{for(let a in o)["notify_subscribers","upload_to_feed","feed_referencing_records","notify_referencing_records"].includes(a)?t.table.subscription[a]=o[a]:t.source[a]=o[a];},data:o=>{let a=o;o==="!D%{}"?a={}:o==="!L%[]"&&(a=[]),t.data=a;}};if(n.record_id)return n;for(let o in s)if(n.hasOwnProperty(o)){let a=s[o](n[o]);a instanceof Promise&&await a;}return r&&(t.user_id="anonymous:"+t.user_id),t}function xr(n){let e=n.substring(3);switch(n.substring(0,3)){case "!S%":return e;case "!N%":let r=e.split("."),i=Number(r[0])-4503599627370496;return r.length===1?i:parseFloat(i.toString()+"."+r[1]);case "!B%":return e==="1";case "!L%":case "!D%":try{return JSON.parse(e)}catch{throw new c("Value parse error.",{code:"PARSE_ERROR"})}default:return n}}async function Dt(n){let{endpoints:e}=n;if(typeof e=="string"&&(e=[e]),!Array.isArray(e))throw new c('"endpoints" should be type: array | string.',{code:"INVALID_PARAMETER"});let t=await w.bind(this)("del-files",{endpoints:e,storage:"records"},{auth:true,method:"post"}),r=[];for(let i in t)r.push(ie.bind(this)(t[i]));return Promise.all(r)}async function Ie(n,e){if(typeof n!="string")throw new c('"url" should be type: string.',{code:"INVALID_PARAMETER"});let t=n.split("?"),r=t.shift()||"",i=t.length?"?"+t.join("?"):"",s=g.Url(r);n=s+i;let o=false,a=s.split("/"),d=a[2].split("."),h=null;d.length===3&&d[1]==="skapi"&&(h=d[0],o=true);let u=a.slice(3),m=false;if(!o&&(u[0]==="auth"||u[0]==="publ"))try{g.UserId(u[2]),g.UserId(u[3]),m=u[0]=="auth",o=!0;}catch{throw new c("Invalid file url.",{code:"INVALID_PARAMETER"})}let R=h?null:u[1];if(e=g.Params(e,{expires:["number",()=>0],dataType:["base64","blob","endpoint","text","info",()=>"download"],progress:"function",_ref:[null,"string"],_update:_=>_}),e?.dataType==="info")return {url:n,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:j(u[9]),uploaded:j(u[8])};let f=n.split("/").slice(-1)[0],A=e.expires;if(A){if(!o)throw new c("Expires option can only be used on skapi cdn endpoints.",{code:"INVALID_PARAMETER"});if(A<0)throw new c('"config.expires" should be > 0. (seconds)',{code:"INVALID_PARAMETER"});let _={request:h?"get-host":"get",id:h||u[5],key:n,expires:A};R&&(_.service=R),n=(await w.bind(this)("get-signed-url",_,{auth:true})).url;}else if(m){let _=Math.floor(Date.now()/1e3);if(!this.bearerToken&&(!this.session?.idToken?.payload?.exp||this.session.idToken.payload.exp<_)){this.log("getFile:requesting new token",null);try{await F.bind(this)().getSession({refreshToken:!0}),this.log("getFile:received new tokens",{exp:this.session?.idToken?.payload?.exp,currTime:_,expiresIn:this.session?.idToken?.payload?.exp-_,token:this.session?.accessToken?.jwtToken,refreshToken:this.session?.refreshToken?.token});}catch(v){throw this.log("getFile:new token error",v),new c("User login is required.",{code:"INVALID_REQUEST"})}}let x=this.bearerToken||this.session?.idToken?.jwtToken;if(!x||!this.user?.user_id)throw new c("User login is required.",{code:"INVALID_REQUEST"});n+=`${n.includes("?")?"&":"?"}t=${encodeURIComponent(x)}`;let k=u[6]==="**"?"**":parseInt(u[6]),T=this.user?.access_group??-1;if(this.user.user_id!==u[3]&&(k==="**"||T<k)){let v=u[5];if(this.__private_access_key[v]&&typeof this.__private_access_key[v]=="string")n+=`&p=${encodeURIComponent(this.__private_access_key[v])}`;else if(this.owner!==this.host)try{let Q=await this.requestPrivateRecordAccessKey({record_id:v,reference_id:e?._ref});n+=`&p=${encodeURIComponent(Q)}`;}catch{}}}if(e?.dataType==="endpoint")return e._update&&(e._update.url=n),n;if(e?.dataType==="download"){let _=document.createElement("a");return _.href=n,document.body.appendChild(_),_.setAttribute("download",f),_.target="_blank",_.click(),document.body.removeChild(_),null}return new Promise(async(_,x)=>{try{let k=await w.bind(this)(n,null,{method:"get",contentType:null,responseType:e?.dataType==="text"?"text":"blob",fetchOptions:{progress:e?.progress}},{ignoreService:!0});if(e?.dataType==="base64"){let T=new FileReader;T.onloadend=()=>_(T.result),T.readAsDataURL(k);}else _(k);}catch(k){x(k);}})}async function Ut(n,e=false){n=N(n,{ignoreEmpty:true}).data||{};let t="",r=xt(n);if(r)n=r,t=n.record_id||n.unique_id,typeof t=="string"&&(typeof this.__private_access_key?.[t]=="string"&&(n.private_key=this.__private_access_key?.[t]||void 0),this.__my_unique_ids[t]&&(e?delete this.__my_unique_ids[t]:n.record_id=this.__my_unique_ids[t]));else {let i=await M.bind(this)(),s=n?.reference,o=false;typeof s=="object"&&Object.keys(s).length&&(s?.record_id||s?.unique_id?(t=s.record_id||s.unique_id,t&&typeof this.__private_access_key?.[t]=="string"&&(n.private_key=this.__private_access_key?.[t]||void 0),n.reference=t):s?.user_id&&(o=s.user_id===this.user?.user_id,n.reference=s.user_id)),typeof n?.table=="string"&&(n.table={name:n.table,access_group:0}),n.index&&n.index.hasOwnProperty("range")&&n.index.hasOwnProperty("condition")&&delete n.index.range;let a=l=>({table:{name:d=>Fe(d,"table.name"),access_group:Ve.bind(this),subscription:d=>g.UserId(d,'User ID in "subscription"')},reference:"string",index:{name:["$updated","$uploaded","$referenced_count","$user_id",d=>de(d,"index.name")],value:d=>{let h={$updated:"number",$uploaded:"number",$referenced_count:"number",$user_id:g.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 c(`"index.value" should be type: ${u}.`,{code:"INVALID_PARAMETER"});return d}return typeof d=="string"&&!d?"":Re(d)},condition:["gt","gte","lt","lte",">",">=","<","<=","=","eq"],range:d=>vt(d,l)},tag:d=>{if(d==null)return d;if(typeof d=="string")return Me(d,"tag");throw new c('"tag" should be type: string.',{code:"INVALID_PARAMETER"})},private_key:"string"});n=g.Params(n||{},a(n),o||i?[]:["table"],{ignoreEmpty:true});}return {query:n,is_reference_fetch:t}}async function Nt(n,e){await this.__connection;let t=await Ut.bind(this)(n),r=t.is_reference_fetch,i=await w.bind(this)("get-records",t.query,{fetchOptions:e,auth:!!this.__user,method:this.__user?"post":"get"});r&&i?.reference_private_key&&typeof i.reference_private_key=="string"&&(this.__private_access_key[r]=i.reference_private_key);let s=[];for(let o in i.list)s.push(ie.bind(this)(i.list[o]));return i.list=await Promise.all(s),i}function Ct(n){let e="",t=[],r=g.Params(n||{},{record_id:s=>X(s,"record_id",{allowEmpty:false,onlyAlphanumeric:true}),unique_id:["string",null],readonly:"boolean",table:{name:s=>Fe(s,"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:Ve.bind(this)},source:{referencing_limit:s=>{if(s===null)return null;if(typeof s=="number"){if(0>s)throw new c('"reference_limit" should be >= 0',{code:"INVALID_PARAMETER"});if(s>4503599627370546)throw new c('"reference_limit" should be <= 4503599627370546',{code:"INVALID_PARAMETER"});return s}throw new c('"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:s=>{if(s===void 0)return;if(!s||Array.isArray(s)&&!s.length)return null;let o={name:l=>de(l,'"name" in "index_restrictions"'),value:l=>Re(l),condition:["gt","gte","lt","lte",">",">=","<","<=","=","eq","!=","ne",()=>null],range:l=>{if(l!==null&&typeof s.value!=typeof l)throw new c('Index restriction "range" type should match the type of "value".',{code:"INVALID_PARAMETER"});if(!s.hasOwnProperty("value"))throw new c('Index restriction "value" is required.',{code:"INVALID_PARAMETER"});return l}};Array.isArray(s)||(s=[s]);let a=s.map(l=>g.Params(l,o,["name"]));if(a.length)for(let l of a)l.condition&&l.hasOwnProperty("range")&&delete l.range;return a}},reference:s=>{if(s===null)return {record_id:null};if(s){if(typeof s=="string")return e=s,this.__my_unique_ids[s]?this.__my_unique_ids[s]:s;if(typeof s!="object")throw new c('"reference" should be type: <string | object>.',{code:"INVALID_PARAMETER"});return g.Params(s,{unique_id:"string",record_id:o=>o==null?o:(e=o,typeof this.__private_access_key?.[o]=="string"&&(n.reference_private_key=this.__private_access_key[o]||void 0),X(o,"reference.record_id",{allowEmpty:false,onlyAlphanumeric:true}))})}},index:[null,{name:s=>de(s,"index.name"),value:s=>Re(s)}],tags:s=>{if(s==null)return s;if(typeof s=="string"&&(s=s.split(",").map(o=>o.trim())),!Array.isArray(s))throw new c('"tag" should be type: <string | string[]>.',{code:"INVALID_PARAMETER"});return s.map(o=>Me(o,"tag"))},remove_bin:s=>{if(!s)return null;let o=[];if(Array.isArray(s))for(let a of s)if(typeof a=="string")o.push(decodeURIComponent(a.split("?")[0]));else if(a.url&&a.size&&a.filename){let d=a.url.split("/").slice(0,3).join("/")+"/"+a.path;o.push(d);}else throw new c('"remove_bin" should be type: <string[] | BinaryFile[] | null>',{code:"INVALID_PARAMETER"});else throw new c('"remove_bin" should be type: <string[] | BinaryFile[] | null>',{code:"INVALID_PARAMETER"});return o},progress:"function",data:s=>s},[],{precall:s=>{let o=s?.data||{};if(!o?.record_id&&!o.table)throw new c('"table.name" is required.',{code:"INVALID_PARAMETER"});typeof o.table=="string"&&(o.table={name:o.table,access_group:0}),s.files&&(t=s.files);}}),i=n.progress||null;if(delete r.progress,!this.__user){let s=!!(r.table?.subscription?.is_subscription_record||r.table?.subscription?.upload_to_feed||r.table?.subscription?.notify_subscribers||r.table?.subscription?.feed_referencing_records||r.table?.subscription?.notify_referencing_records);if(r.record_id)throw new c("Public users cannot update existing records.",{code:"INVALID_REQUEST"});if(r.table.access_group!=="public"&&r.table.access_group!==0)throw new c("Public users can only post records to public tables.",{code:"INVALID_REQUEST"});if(s)throw new c("Public users cannot post subscription records.",{code:"INVALID_REQUEST"});if(r.remove_bin)throw new c("Public users cannot remove files from records.",{code:"INVALID_REQUEST"});if(r.unique_id)throw new c("Public users cannot set unique_id for records.",{code:"INVALID_REQUEST"})}return {config:r,progress:i,is_reference_post:e,files:t}}async function Lt(n){if(await this.__connection,!Array.isArray(n)||!n.length)throw new c('"params" should be a non-empty array.',{code:"INVALID_PARAMETER"});let e=[],t,r,i=null,o={_is_bulk_:n.map((u,m)=>{if(!u||typeof u!="object"||Array.isArray(u))throw new c(`"params[${m}]" should be type: <object>.`,{code:"INVALID_PARAMETER"});let R=Ct.bind(this)(u),f=R.config;if(R.is_reference_post&&e.push(R.is_reference_post),typeof f.progress=="function"&&i===null&&(i=f.progress),f.service!==void 0){if(t===void 0)t=f.service;else if(t!==f.service)throw new c('All bulk params should share the same "service" value.',{code:"INVALID_PARAMETER"})}if(f.owner!==void 0){if(r===void 0)r=f.owner;else if(r!==f.owner)throw new c('All bulk params should share the same "owner" value.',{code:"INVALID_PARAMETER"})}return delete f.progress,delete f.service,delete f.owner,f}),service:"",owner:""};t!==void 0&&(o.service=t),r!==void 0&&(o.owner=r);let a={auth:!!this.__user,method:"post"},l={};Object.keys(l).length&&Object.assign(a,{fetchOptions:l});let d=await w.bind(this)("post-record",o,a),h=await Promise.all(d.map(u=>ie.bind(this)(u,"called from postRecord")));for(let u=0;u<d.length;u++){let m=d[u],R=h[u];if(typeof m?.reference_private_key=="string")for(let f of e)this.__private_access_key[f]=m.reference_private_key;R?.unique_id&&(this.__my_unique_ids[R.unique_id]=R.record_id);}return h}async function Ot(n,e,t){if(await this.__connection,!e)throw new c('"config" argument is required.',{code:"INVALID_PARAMETER"});let r=Ct.bind(this)(e),i=r.config,s=r.progress,o=r.is_reference_post,a={auth:!!this.__user,method:"post"},l=[],d=N(n);t&&Array.isArray(t)&&t.length&&(l=l.concat(t)),d.files&&Array.isArray(d.files)&&d.files.length&&(l=l.concat(d.files));let h=null;h=Object.assign({data:d.data},i);let u={};typeof s=="function"&&(u.progress=s),Object.keys(u).length&&Object.assign(a,{fetchOptions:u});let m=await w.bind(this)("post-record",h,a);if($()&&l.length){let f=new FormData;for(let _ of l)f.append(_.name,_.file,_.file.name);let A={record_id:m.rec,progress:s};i.hasOwnProperty("service")&&(A.service=i.service);let{bin_endpoints:P}=await we.bind(this)(f,A);m.bin?m.bin.push(...P):m.bin=P;}o&&typeof m?.reference_private_key=="string"&&(this.__private_access_key[o]=m.reference_private_key);let R=await ie.bind(this)(m,"called from postRecord");return R.unique_id&&(this.__my_unique_ids[R.unique_id]=R.record_id,$()&&window.sessionStorage.setItem(`${this.service}:uniqueids`,JSON.stringify(this.__my_unique_ids))),R}async function Ft(n,e){let t=await w.bind(this)("get-table",g.Params(n||{},{table:"string",condition:["gt","gte","lt","lte",">",">=","<","<=","=","eq","!=","ne"]}),Object.assign({auth:!!this.__user},{fetchOptions:e})),r={cnt_rec:"number_of_records",tbl:"table",srvc:"service",grp_:"number_of_records_in_access_group_"};if(Array.isArray(t?.list))for(let i of t.list)for(let s in r){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[r[s]]=i[s],delete i[s]);}return t}async function Mt(n,e){if(!n?.table)throw new c('"table" is required.',{code:"INVALID_PARAMETER"});let t=g.Params(n||{},{table:"string",index:s=>de(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:["string","number","boolean"],condition:["gt","gte","lt","lte",">",">=","<","<=","=","eq","!=","ne"]}},["table"]);if(t.hasOwnProperty("order")){if(!t.order?.by)throw new c('"order.by" is required.',{code:"INVALID_PARAMETER"});if(t.order.hasOwnProperty("condition")&&!t.order.hasOwnProperty("value"))throw new c('"value" is required for "condition".',{code:"INVALID_PARAMETER"});if(t.hasOwnProperty("index")&&t.index.substring(t.index.length-1)!==".")throw new c('"index" should be a parent index name of the compound index when using "order.by"',{code:"INVALID_PARAMETER"})}let r=await w.bind(this)("get-index",t,Object.assign({auth:!!this.__user},{fetchOptions:e})),i={cnt_bool:"boolean_count",cnt_numb:"number_count",totl_numb:"total_number",totl_bool:"total_bool",avrg_numb:"average_number",avrg_bool:"average_bool",cnt_str:"string_count"};return Array.isArray(r?.list)&&(r.list=r.list.map(s=>{let o=s.idx.split("/"),a={table:o[1],index: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})),r}async function Vt(n,e){let t=await w.bind(this)("get-tag",g.Params(n||{},{table:"string",tag:"string",condition:["gt","gte","lt","lte",">",">=","<","<=","=","eq","!=","ne"]}),Object.assign({auth:!!this.__user},{fetchOptions:e}));return Array.isArray(t?.list)&&(t.list=t.list.map(r=>{let i=r.tag.split("/");return {table:i[1],tag:i[0],number_of_records:r.cnt_rec}})),t}async function $t(n,e){let t=await w.bind(this)("get-uniqueid",g.Params(n||{},{unique_id:"string",condition:["gt","gte","lt","lte",">",">=","<","<=","=","eq","!=","ne"]}),Object.assign({auth:!!this.__user},{fetchOptions:e}));if(Array.isArray(t?.list))for(let r in t.list){let i=t.list[r];t.list[r]={unique_id:i.unq,record_id:i.rec};}return t}async function qt(n,e){await this.__connection;let t=await Ut.bind(this)(n,true),r=t.is_reference_fetch,i=await w.bind(this)("del-records",t.query,{auth:true,fetchOptions:e});return r&&typeof i?.reference_private_key=="string"&&(this.__private_access_key[r]=i.reference_private_key),i?.message||i}function jt(n){return Ht.bind(this)({record_id:n.record_id,user_id:n.user_id,execute:"add"})}function Bt(n){return Ht.bind(this)({record_id:n.record_id,user_id:n.user_id||null,execute:"remove"})}async function Kt(n,e){let t={record_id:n.record_id||void 0,user_id:n.user_id||void 0,execute:"list"};if(!t.record_id&&!t.user_id)throw new c("Either record_id or user_id must be provided.",{code:"INVALID_PARAMETER"});if(t.user_id)if(typeof t.user_id=="string")g.UserId(t.user_id),t.user_id=[t.user_id];else if(Array.isArray(t.user_id))for(let s of t.user_id)g.UserId(s);else throw new c("user_id should be type: <string | string[]>",{code:"INVALID_PARAMETER"});let r=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 w.bind(this)("grant-private-access",t,{auth:true,fetchOptions:e});return i.list=i.list.map(r),i}function Qt(n){let e=n.record_id,t=n.reference_id||void 0;if(!e)throw new c("Record ID is required.",{code:"INVALID_PARAMETER"});if(typeof e!="string")throw new c("Record ID should be type: <string | string[]>",{code:"INVALID_PARAMETER"});if(t&&typeof t!="string")throw new c("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(Ae[e])return Ae[e];let r=w.bind(this)("request-private-access-key",{record_id:e,reference_id:t},{auth:true}).then(i=>{let s=typeof i=="string"?i:i?.private_key;if(typeof s!="string")throw new c("Invalid private access key response.",{code:"ERROR"});return this.__private_access_key[e]=s,s}).finally(()=>{delete Ae[e];});return Ae[e]=r,r}function Ht(n){n.execute;let t=g.Params(n,{record_id:"string",user_id:r=>{if(!r)throw new c("User ID is required.",{code:"INVALID_PARAMETER"});let i=r;if(typeof i=="string"&&(i=[i]),i.length>100)throw new c("Cannot process more than 100 users at once.",{code:"INVALID_REQUEST"});for(let s of i)g.UserId(s,'User ID in "user_id"');return i},execute:["add","remove"]},["execute","record_id","user_id"]);return t.user_id||(t.user_id=null),w.bind(this)("grant-private-access",t,{auth:true})}var I={},O={},B={},W={},H={},Te={},Pe={};function Wt(n,e,t){n[e]||(n[e]=[]),n[e].push(t);}async function Se(n,e,t){let r=[];if(n[e]){for(let i of n[e])if(i){let s=t(i);s instanceof Promise&&(s=await s),r.push(s);}delete n[e];}return r}async function qe(n,e){if(!this?.session?.accessToken?.jwtToken)throw new c("Access token is required.",{code:"INVALID_PARAMETER"});let t=await this.__socket;async function r(i,s,o){this.log("answerSdpOffer from",s),await I[s].setRemoteDescription(new RTCSessionDescription(i));let a=await I[s].createAnswer();await I[s].setLocalDescription(a),o.send(JSON.stringify({action:"rtc",uid:s,content:{sdpanswer:a},token:this.session.accessToken.jwtToken}));}I?.[e]?n?(await Se(Pe,e,i=>r.bind(this)(i,e,t)),await r.bind(this)(n,e,t)):await Se(Pe,e,i=>r.bind(this)(i,e,t)):n&&Wt(Pe,e,n);}async function je(n,e){if(this.log("receiveIceCandidate",n),I?.[e]&&I[e]?.remoteDescription&&I[e]?.remoteDescription?.type){if(!n)return Se(Te,e,t=>I[e].addIceCandidate(t));await Se(Te,e,t=>I[e].addIceCandidate(t)),await I[e].addIceCandidate(n);}else Wt(Te,e,n);}async function K(n){if(typeof window>"u"||window._runningInNodeJS)throw new c("WebRTC is not supported in Node.js environment.",{code:"NOT_SUPPORTED"});g.Params(n,{cid:s=>{if(typeof s!="string")throw new c('"cid" should be type: <string>.',{code:"INVALID_PARAMETER"});if(s&&s.slice(0,4)!=="cid:")throw new c('"cid" should be a valid connection id.',{code:"INVALID_PARAMETER"});return s},close:"boolean"});let e=await this.__socket,{cid:t,close_all:r=false}=n||{};if(!r&&!t)throw new c('"cid" is required.',{code:"INVALID_PARAMETER"});let i=s=>{if(!s)throw new c('"cid" is required.',{code:"INVALID_PARAMETER"});if(delete Pe[s],delete Te[s],O[s]&&Object.values(O[s]).forEach(o=>{o.readyState!=="closed"&&o.close();}),delete O[s],I?.[s]){I[s].connectionState!=="closed"&&(I[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:I[s],timestamp:new Date().toISOString(),state:I[s].connectionState,iceState:I[s].iceConnectionState,signalingState:I[s].signalingState};H[s]&&H[s](o),this.log("closeRTC",o);}delete H[s],delete W[s],delete B[s],delete I[s];};if(r)for(let s in I)i(s);else i(t);this.log("Cleaning up media stream..."),this.__mediaStream&&(this.__mediaStream.getTracks().forEach(s=>{s.stop();}),this.__mediaStream=null);}async function zt(n){if(n instanceof MediaStream)return n;if(!n.video&&!n.audio){let e=new MediaStream,t=document.createElement("canvas");t.width=1,t.height=1;let i=t.captureStream().getVideoTracks()[0];return e.addTrack(i),e}return window.navigator.mediaDevices.getUserMedia(n)}async function Jt(n,e){if(typeof window>"u"||window._runningInNodeJS)throw new c("WebRTC is not supported in Node.js environment.",{code:"NOT_SUPPORTED"});if(typeof e!="function")throw new c("Callback is required.",{code:"INVALID_PARAMETER"});if(!this?.session?.accessToken?.jwtToken)throw new c("Access token is required.",{code:"INVALID_PARAMETER"});n=g.Params(n,{cid:o=>{if(typeof o!="string")throw new c('"cid" should be type: <string>.',{code:"INVALID_PARAMETER"});if(o&&o.slice(0,4)!=="cid:")throw new c('"cid" should be a valid connection id.',{code:"INVALID_PARAMETER"});return o},ice:["string",()=>"stun:stun.skapi.com:3468"],media:o=>o,channels:["text-chat","file-transfer","video-chat","voice-chat","gaming",{ordered:"boolean",maxPacketLifeTime:"number",maxRetransmits:"number",protocol:"string"},()=>[{ordered:true,maxPacketLifeTime:10,protocol:"default"}]]},["cid"]);let{cid:t,ice:r}=n;if(!(n?.media instanceof MediaStream)&&(n?.media?.video||n?.media?.audio)&&window.location.hostname!=="localhost"&&window.location.protocol!=="https:")throw new c("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 c("No realtime connection. Execute connectRealtime() before this method.",{code:"INVALID_REQUEST"});if(i.readyState!==1)throw new c("Realtime connection is not ready.",{code:"INVALID_REQUEST"});let s={iceServers:[{urls:r}]};I?.[t]||(I[t]=new RTCPeerConnection(s)),n?.media&&(this.__mediaStream=await zt(n.media),this.__mediaStream.getTracks().forEach(o=>{I[t].addTrack(o,this.__mediaStream);})),H[t]=e,O[t]||(O[t]={});for(let o=0;o<n.channels.length;o++){let a=n.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(O[t]).includes(l))throw new c(`Data channel with the protocol "${l}" already exists.`,{code:"INVALID_REQUEST"});let d=I[t].createDataChannel(l,a);O[t][l]=d;}for(let o in O[t]){let a=O[t][o];Zt.bind(this)(t,a);}return Xt.bind(this)(t,["onnegotiationneeded"]),await $e.bind(this)(t),{hangup:()=>B[t]&&B[t](false),connection:new Promise(o=>{B[t]=(a=>{if(this.log("receiver picked up the call",t),!a)return K.bind(this)({cid:t}),null;I[t].onnegotiationneeded=()=>{this.log("onnegotiationneeded",`sending offer to "${t}".`),$e.bind(this)(t),H[t]&&H[t]({type:"negotiationneeded",target:I[t],timestamp:new Date().toISOString(),signalingState:I[t].signalingState,connectionState:I[t].iceConnectionState,gatheringState:I[t].iceGatheringState});},o({target:I[t],channels:O[t],hangup:()=>K.bind(this)({cid:t}),media:this.__mediaStream});}).bind(this);})}}function Gt(n){return async(e,t)=>{e=e||{},e=N(e).data;let r=n.sender_cid,i=await this.__socket;if(!W[r])return null;if(typeof t!="function")throw new c("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 c("Media stream is only supported on either localhost or https.",{code:"INVALID_REQUEST"});let{ice:s="stun:stun.skapi.com:3468"}=e;return I?.[r]||(I[r]=new RTCPeerConnection({iceServers:[{urls:s}]})),e?.media&&(this.__mediaStream=await zt(e.media),this.__mediaStream.getTracks().forEach(o=>{I[r].addTrack(o,this.__mediaStream);})),delete W[r],H[r]=t,O[r]||(O[r]={}),I[r].ondatachannel=o=>{this.log("ondatachannel",`received data channel "${o.channel.label}".`);let a=o.channel;O[r][a.label]=a,Zt.bind(this)(r,a);},Xt.bind(this)(r,["onnegotiationneeded"]),await qe.bind(this)(null,r),await je.bind(this)(null,r),i.send(JSON.stringify({action:"rtc",uid:r,content:{pickup:this.user.user_id},token:this.session.accessToken.jwtToken})),{target:I[r],channels:O[r],hangup:()=>K.bind(this)({cid:r}),media:this.__mediaStream}}}async function $e(n){if(!this?.session?.accessToken?.jwtToken)throw new c("Access token is required.",{code:"INVALID_PARAMETER"});this.log("sendOffer",n);let e=await this.__socket,t=await I[n].createOffer();await I[n].setLocalDescription(t);let r=I[n].localDescription;this.log("rtcSdpOffer to",r),e.send(JSON.stringify({action:"rtc",uid:n,content:{sdpoffer:r},token:this.session.accessToken.jwtToken}));}async function vr(n,e){if(!this?.session?.accessToken?.jwtToken)throw new c("Access token is required.",{code:"INVALID_PARAMETER"});this.log("sendIceCandidate to",e);let t=await this.__socket;if(!n.candidate){this.log("candidate-end","all ice candidates have been sent");return}let r=H[e]||(()=>{}),i=n.candidate;this.log("ice gathering state set to",I[e].iceGatheringState),r({type:"icecandidate",target:I[e],timestamp:new Date().toISOString(),candidate:n.candidate.candidate,sdpMid:n.candidate.sdpMid,sdpMLineIndex:n.candidate.sdpMLineIndex,usernameFragment:n.candidate.usernameFragment,protocol:n.candidate.protocol,gatheringState:I[e].iceGatheringState,connectionState:I[e].iceConnectionState}),t.send(JSON.stringify({action:"rtc",uid:e,content:{candidate:i},token:this.session.accessToken.jwtToken}));}function Xt(n,e){let t=new Set(e),r=H[n]||(o=>{}),i=I[n],s={ontrack:o=>{r({type:"track",target:i,timeStamp:o.timeStamp,streams:o.streams,track:o.track});},onicecandidate:o=>{vr.bind(this)(o,n),o.candidate?r({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}):r({type:"icecandidateend",target:i,timestamp:new Date().toISOString()});},onicecandidateerror:o=>{r({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:()=>{r({type:"iceconnectionstatechange",target:i,timestamp:new Date().toISOString(),state:i.iceConnectionState,gatheringState:i.iceGatheringState,signalingState:i.signalingState});},onicegatheringstatechange:()=>{r({type:"icegatheringstatechange",target:i,timestamp:new Date().toISOString(),state:i.iceGatheringState,connectionState:i.iceConnectionState,signalingState:i.signalingState});},onsignalingstatechange:()=>{r({type:"signalingstatechange",target:i,timestamp:new Date().toISOString(),state:i.signalingState,connectionState:i.iceConnectionState,gatheringState:i.iceGatheringState});},onnegotiationneeded:()=>{$e.bind(this)(n),r({type:"negotiationneeded",target:i,timestamp:new Date().toISOString(),signalingState:i.signalingState,connectionState:i.iceConnectionState,gatheringState:i.iceGatheringState});},onconnectionstatechange:()=>{r({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")&&K.bind(this)({cid:n});}};for(let[o,a]of Object.entries(s))t.has(o)||(i[o]=a);}function Zt(n,e,t){let r=new Set(t),i=H[n]||(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),O[n]&&(delete O[n][e.label],Object.keys(O[n]).length===0&&K.bind(this)({cid:n}));},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))r.has(o)||(e[o]=a);}var Y,Z=null,ge=true,se=0;async function Dr(){if(typeof window>"u"||window._runningInNodeJS)throw new c("WebSocket is not supported in Node.js environment.",{code:"NOT_SUPPORTED"});if(await this.getProfile(),!this.session)throw new c("No access.",{code:"INVALID_REQUEST"});let n=await this.record_endpoint;return new WebSocket(n.websocket_private+"?token="+this.session.accessToken.jwtToken)}var Be=null;async function Yt(){if(typeof window>"u"||window._runningInNodeJS)throw new c("WebSocket is not supported in Node.js environment.",{code:"NOT_SUPPORTED"});ge=true;let n=this.__socket?await this.__socket:this.__socket;K.bind(this)({close_all:true}),Y&&Ke.bind(this)({group:null}),se=0,Z&&(Z.terminate(),Z=null);try{n&&n.close();}catch{}return window.removeEventListener("visibilitychange",Be),this.__socket=null,null}async function ke(n,e=50,t){if(typeof window>"u"||window._runningInNodeJS)throw new c("WebSocket is not supported in Node.js environment.",{code:"NOT_SUPPORTED"});if(typeof n!="function")throw new c("Callback must be a function.",{code:"INVALID_REQUEST"});if(t==="reconnect"){if(this.__socket instanceof Promise){let r=await this.__socket;if(r.readyState!==WebSocket.CLOSED&&r.readyState!==WebSocket.CLOSING)return this.__socket}}else if(ge&&(Be=()=>{!document.hidden&&!ge&&ke.bind(this)(n,0,"reconnect");},this.__socket instanceof Promise))return this.__socket;Z&&(Z.terminate(),Z=null),this.__socket=new Promise(async r=>{await ne.bind(this)(),setTimeout(async()=>{let i=await Dr.bind(this)();i.onopen=()=>{ge=false,se=0,t!=="reconnect"&&window.addEventListener("visibilitychange",Be),this.log("realtime onopen","Connected to WebSocket server."),n({type:"success",message:"Connected to WebSocket server."}),Y&&i.send(JSON.stringify({action:"joinRoom",rid:Y,token:this.session.accessToken.jwtToken}));let s=`
|
|
207
207
|
let interval = 15000; // Set interval time 15 seconds
|
|
208
208
|
|
|
209
209
|
function runInterval() {
|
|
@@ -214,7 +214,7 @@ var Fn=Object.defineProperty;var Mn=Object.getOwnPropertyDescriptor;var ee=(n=>t
|
|
|
214
214
|
runInterval(); // Start interval
|
|
215
215
|
`,o=new Blob([s],{type:"application/javascript"});Z=new Worker(URL.createObjectURL(o)),Z.onmessage=a=>{i.readyState===1&&i.send(JSON.stringify({action:"keepAlive"}));},r(i);},i.onmessage=async s=>{let o="";try{o=JSON.parse(decodeURI(s.data)),this.log("socket onmessage",o);}catch{return}let a;switch(true){case !!o?.["#message"]:a="message";break;case !!o?.["#private"]:a="private";break;case !!o?.["#notice"]:a="notice";break;case !!o?.["#rtc"]:a="rtc";break;case !!o?.["#error"]:a="error";break}if(!a)return;let l={type:a,message:o?.["#rtc"]||o?.["#message"]||o?.["#private"]||o?.["#notice"]||o?.["#error"]||null,sender:o?.["#user_id"]||null,sender_cid:o?.["#scid"]?"cid:"+o["#scid"]:null,sender_rid:o?.["#srid"]||null,code:o?.["#code"]||null};if(a==="notice")n(l);else if(a==="rtc"){if(l.sender!==this.user.user_id){let d=l.message;if(d.hungup){B[l.sender_cid]&&(B[l.sender_cid](false),delete B[l.sender_cid]),W[l.sender_cid]&&delete W[l.sender_cid],I?.[l.sender_cid]&&K.bind(this)({cid:l.sender_cid}),l.type="rtc:closed",n(l);return}if(d.candidate&&je.bind(this)(d.candidate,l.sender_cid),d.sdpoffer&&(qe.bind(this)(d.sdpoffer,l.sender_cid),W[l.sender_cid]||(W[l.sender_cid]=l.sender_cid,delete l.message,l.connectRTC=Gt.bind(this)(l),l.type="rtc:incoming",l.hangup=(()=>{I[l.sender_cid]?K.bind(this)({cid:l.sender_cid}):W[l.sender_cid]&&(delete W[l.sender_cid],i.send(JSON.stringify({action:"rtc",uid:l.sender_cid,content:{hungup:this.user.user_id},token:this.session.accessToken.jwtToken})));}).bind(this),n(l))),d.pickup&&B[l.sender_cid]&&(B[l.sender_cid](true),delete B[l.sender_cid]),d.sdpanswer&&I[l.sender_cid])if(I[l.sender_cid].signalingState==="have-local-offer")await I[l.sender_cid].setRemoteDescription(new RTCSessionDescription(d.sdpanswer));else throw new c("Invalid signaling state.",{code:"INVALID_REQUEST"})}}else n(l);},i.onclose=()=>{ge?(this.log("realtime onclose","WebSocket connection closed."),n({type:"close",message:"WebSocket connection closed."})):(this.log("realtime onclose","WebSocket unexpected close."),n({type:"error",message:"Skapi: WebSocket unexpected close."}),se++,se<3?(this.log("realtime onclose","Reconnecting to WebSocket server..."+se),n({type:"reconnect",message:"Reconnecting to WebSocket server..."+se}),ke.bind(this)(n,3e3,"reconnect")):(this.log("realtime onclose","Max reconnection attempts reached."),n({type:"error",message:"Skapi: Max reconnection attempts reached."})));},i.onerror=()=>{this.log("realtime onerror","WebSocket connection error."),n({type:"error",message:"Skapi: WebSocket connection error."});};},e);});}async function en(n,e,t){if(typeof window>"u"||window._runningInNodeJS)throw new c("WebSocket is not supported in Node.js environment.",{code:"NOT_SUPPORTED"});let r=this.__socket?await this.__socket:this.__socket;if(!r)throw new c("No realtime connection. Execute connectRealtime() before this method.",{code:"INVALID_REQUEST"});if(!e)throw new c("No recipient.",{code:"INVALID_REQUEST"});await ne.bind(this)(),n=N(n).data;let i="";if(t&&(t=g.Params(t,{config:{always:"boolean"},title:"string",body:"string"},["title","body"]),i=JSON.stringify({title:t.title,body:t.body}),new Blob([i]).size>3072))throw new c("Notification size exceeds 3kb.",{code:"INVALID_PARAMETER"});if(r.readyState===1){try{g.UserId(e),r.send(JSON.stringify({action:"sendMessage",uid:e,content:n,notification:i,notificationConfig:t?.config||{},token:`IdT:${this.service}:${this.owner}:`+(this.bearerToken||this.session?.idToken?.jwtToken||"null")}));}catch(s){if(this.log("postRealtime:err",{err:s}),Y!==e)throw new c(`User has not joined to the recipient group. Run joinRealtime({ group: "${e}" })`,{code:"INVALID_REQUEST"});r.send(JSON.stringify({action:"broadcast",rid:e,content:n,notification:i,notificationConfig:t?.config||{},token:`IdT:${this.service}:${this.owner}:`+(this.bearerToken||this.session?.idToken?.jwtToken||"null")}));}return {type:"success",message:"Message sent."}}throw new c("Realtime connection is not open. Try reconnecting with connectRealtime().",{code:"INVALID_REQUEST"})}async function Ke(n){if(typeof window>"u"||window._runningInNodeJS)throw new c("WebSocket is not supported in Node.js environment.",{code:"NOT_SUPPORTED"});let e=this.__socket?await this.__socket:this.__socket;if(!e)throw new c("No realtime connection. Execute connectRealtime() before this method.",{code:"INVALID_REQUEST"});await ne.bind(this)(),n=N(n,{nullIfEmpty:true}).data;let{group:t=null}=n;if(!t&&!Y)return {type:"success",message:"Left realtime message group."};if(t!==null&&typeof t!="string")throw new c('"group" must be a string | null.',{code:"INVALID_PARAMETER"});return e.send(JSON.stringify({action:"joinRoom",rid:t,token:this.session.accessToken.jwtToken})),Y=t,{type:"success",message:t?`Joined realtime message group: "${t}".`:"Left realtime message group."}}async function tn(n,e){n=g.Params(n,{user_id:r=>g.UserId(r,'User ID in "user_id"'),group:["string",()=>{if(!Y)throw new c('No group has been joined. Otherwise "group" is required.',{code:"INVALID_REQUEST"});return Y}]});let t=await w.bind(this)("get-ws-group",n,{fetchOptions:e,auth:true,method:"post"});return t.list=t.list.map(r=>({user_id:r.uid.split("#")[1],cid:"cid:"+r.cid})),t}async function nn(n,e){if(await this.__connection,n||(n={searchFor:"group",value:" ",condition:">"}),n=g.Params(n,{searchFor:["group","number_of_users",()=>"group"],value:["string","number",()=>n?.searchFor&&n?.searchFor==="number_of_users"?0:" "],condition:[">",">=","=","<","<=","!=","gt","gte","eq","lt","lte","ne"],range:["string","number"]}),n.condition||(n.value===" "||!n.value?n.condition=">":n.condition="="),n.range&&n.condition&&delete n.condition,n.searchFor==="number_of_users"&&typeof n.value!="number")throw new c('"value" must be a number.',{code:"INVALID_PARAMETER"});if(n.searchFor==="group"&&typeof n.value!="string")throw new c('"value" must be a string.',{code:"INVALID_PARAMETER"});if(n.hasOwnProperty("range")&&typeof n.range!=typeof n.value)throw new c(`"range" must be a ${typeof n.value}.`,{code:"INVALID_PARAMETER"});let t=await w.bind(this)("get-ws-group",n,{fetchOptions:e,auth:true,method:"post"});return t.list=t.list.map(r=>({group:r.rid.split("#")[1],number_of_users:r.cnt})),t}var Ur=typeof FormData<"u",Nr=typeof HTMLFormElement<"u",Cr=typeof SubmitEvent<"u";function rn({id:n,auth:e,service:t,owner:r,latency:i=1e3}){return new Promise((s,o)=>{let a=setInterval(async()=>{try{let l=await w.bind(this)("csr-poll",{id:n,service:t,owner:r},{auth:e});if(l.status==="pending")return;clearInterval(a),s(l);}catch(l){clearInterval(a),o(l);}},i);})}async function sn(n){let e=false,t=typeof n.poll=="number"?n.poll:0;n.poll=!!n.poll;let r=s=>{for(let o in s)if(typeof s[o]=="string"&&s[o].includes("$CLIENT_SECRET")){e=true;break}};if(n=g.Params(n,{url:s=>{if(!s||typeof s!="string")throw new c('"url" should be type: <string>.',{code:"INVALID_PARAMETER"});return g.Url(s),s.includes("$CLIENT_SECRET")&&(e=true),s},clientSecretName:"string",method:s=>{if(s&&typeof s!="string")throw new c('"method" should be either "GET" or "POST" or "DELETE" or "PUT".',{code:"INVALID_PARAMETER"});let o=s.toLowerCase();if(o!=="get"&&o!=="post"&&o!=="delete"&&o!=="put")throw new c('"method" should be either "GET" or "POST" or "DELETE" or "PUT".',{code:"INVALID_PARAMETER"});return o},headers:s=>{if(s&&typeof s!="object")throw new c('"headers" should be type: <object>.',{code:"INVALID_PARAMETER"});return r(s),s},data:s=>{if(s&&typeof s!="object")throw new c('"data" should be type: <object>.',{code:"INVALID_PARAMETER"});return r(s),s},params:s=>{if(s&&typeof s!="object")throw new c('"params" should be type: <object>.',{code:"INVALID_PARAMETER"});return r(s),s},poll:"boolean",expires:"number"},["clientSecretName","method","url"]),!e)throw new c(`At least one parameter value should include "$CLIENT_SECRET" in ${n.method.toLowerCase()==="post"?'"data"':'"params"'} or "headers".`,{code:"INVALID_PARAMETER"});await this.__connection;let i=!!this.__user;return w.bind(this)("csr",n,{auth:i,tokenHeaders:{accessToken:!!i}}).then(s=>{if(t&&s.id&&s.status==="pending"){let a=`[${n.method.toUpperCase()}]${n.url.toLowerCase()}`+":"+s.id;return rn.call(this,{id:a,auth:i,service:n.service,owner:n.owner,latency:t})}else return s})}async function on(n,e){await this.__connection;let t=!!n.poll,r=typeof n.poll=="number"?n.poll:1e3;n=g.Params(n,{url:"string",method:["GET","POST","DELETE","PUT"]},["url","method"]);let i=!!this.__user,s=`[${n.method.toUpperCase()}]${n.url.toLowerCase()}:`,o=await w.bind(this)("csr-poll",{id:s,service:n.service,owner:n.owner},{auth:i,fetchOptions:e}),a=[];return o.list=o.list.map(l=>{let d={id:l.id,status_code:l.rslv?.status_code||null,response_body:l.rslv?.body||l.rslv?.truncated||null,error:l.err,updated:l.utmp,request_body:l.reqbdy,expires:l.stts!=="pending"?l.expt:null,status:l.stts||null};return t&&d.status==="pending"&&typeof d.id=="string"&&a.push(d.id),d}),t&&(o.pending=a.map(l=>rn.call(this,{id:s+l,auth:i,service:n.service,owner:n.owner,latency:r}).then(d=>({...d})).catch(d=>({error:d,id:l})))),o}async function an(n){await this.__connection;let e={name:"string",email:t=>(g.Email(t),t),subject:"string",message:"string"};return n=g.Params(n,e,["name","email","subject","message"]),await w.bind(this)("send-inquiry",n),"SUCCESS: Inquiry has been sent."}async function cn(n,e){if(await this.__connection,Ur&&n instanceof FormData||Nr&&n instanceof HTMLFormElement||Cr&&n instanceof SubmitEvent){if(!e)throw new c("Url string as a second argument is required when form is passed.",{code:"INVALID_PARAMETER"});let r=N(n);n={url:e,data:r.data,sync:true};}let t={url:r=>g.Url(r),data:r=>r,sync:["boolean",()=>true]};if(Array.isArray(n))for(let r of n)r=g.Params(r,t);else n=g.Params(n,t);return w.bind(this)("post-secure",n,{auth:true})}async function ln(n,e){await this.__connection;let{auth:t=false,method:r="POST",bypassAwaitConnection:i=false,responseType:s,contentType:o,tokenHeaders:a,progress:l}=e||{};if(e=Object.assign({auth:t,method:r,bypassAwaitConnection:i,responseType:s,contentType:o,tokenHeaders:a},{fetchOptions:{progress:l}}),typeof n!="object"&&(o==="application/json"||o===void 0))throw new c('"data" should be type: <object>.',{code:"INVALID_PARAMETER"});return w.bind(this)("mock",n,e)}async function un(n,e){await this.__connection,n=g.Params(n||{},{access_group:r=>{if(r==="authorized"&&(r=1),r==="public"&&(r=0),typeof r!="number")throw new c('"access_group" should be type number.',{code:"INVALID_PARAMETER"});if(r<0)throw new c('"access_group" should be zero or a positive number.',{code:"INVALID_PARAMETER"});if(r>this.__user.access_group)throw new c("User has no access.",{code:"INVALID_REQUEST"});return r}});let t=await w.bind(this)("get-feed",n,{auth:true,fetchOptions:e});for(let r in t.list)t.list[r]=await ie.bind(this)(t.list[r]);return t}function fe(n){if(n===this.__user.user_id)throw new c(`"user_id" cannot be the user's own ID.`,{code:"INVALID_PARAMETER"});return g.UserId(n,'"user_id"')}async function dn(n,e){if(n=N(n,{ignoreEmpty:true}).data,n=g.Params(n,{subscriber:r=>g.UserId(r,'User ID in "subscriber"'),subscription:fe.bind(this),blocked:"boolean"}),!n.subscriber&&!n.subscription)throw new c('At least either "subscriber" or "subscription" should have a value.',{code:"INVALID_PARAMETER"});let t=await w.bind(this)("get-subscription",n,Object.assign({auth:true},{fetchOptions:e}));return t.list=t.list.map((r=>{let i={};if(r.sub){let s=r.sub.split("#");i.subscriber=s[2],i.subscription=s[0];}else i.subscriber=r.subscriber,i.subscription=r.subscription;return i.timestamp=r?.timestamp||r.stmp,i.blocked=r?.blocked||r.grp.substring(0,1)==="N",Object.assign(i,r.opt),i})),t}async function gn(n){await this.__connection,n=g.Params(n,{user_id:fe.bind(this),get_feed:["boolean",()=>false],get_notified:["boolean",()=>false],get_email:r=>{if(r&&!this.__user.email||!this.__user.email_verified)throw new c("User has no verified email address.",{code:"INVALID_REQUEST"});return !!r}},["user_id"]);let e=await w.bind(this)("subscription",{subscribe:n.user_id,option:{get_feed:n.get_feed,get_notified:n.get_notified,get_email:n.get_email||false}},{auth:true}),t={};if(e.sub){let r=e.sub.split("#");t.subscriber=r[2],t.subscription=r[0];}else t.subscriber=e.subscriber,t.subscription=e.subscription;return t.timestamp=e?.timestamp||e.stmp,t.blocked=e?.blocked||e.grp.substring(0,1)==="N",Object.assign(t,e.opt),t}async function fn(n){await this.__connection;let{user_id:e}=g.Params(n,{user_id:fe.bind(this)},["user_id"]);return await w.bind(this)("subscription",{unsubscribe:e},{auth:true})}async function hn(n){await this.__connection;let{user_id:e}=g.Params(n,{user_id:fe.bind(this)},["user_id"]);return await w.bind(this)("subscription",{block:e},{auth:true})}async function pn(n){await this.__connection;let{user_id:e}=g.Params(n,{user_id:fe.bind(this)},["user_id"]);return await w.bind(this)("subscription",{unblock:e},{auth:true})}async function mn(n,e){await this.__connection;let t=await M.bind(this)();n=g.Params(n,{user_id:o=>{if(o!==this.__user.user_id&&!t)throw new c("No access.",{code:"INVALID_REQUEST"});return o},group:o=>{if(o==="public"&&(o=0),o==="authorized"&&(o=1),typeof o!="number")throw new c('"group" should be type number | "public" | "authorized".',{code:"INVALID_PARAMETER"});return o}});let r=await w.bind(this)("get-newsletter-subscription",n,{auth:true,fetchOptions:e||null}),i=r?.list||r,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 d=parseInt(a[0]);s.push({timestamp:o.stmp,group:d,subscribed_email:a[1],active:l});}return r?.list?(r.list=s,r):s}async function _n(n){await this.__connection;let e=g.Params(n||{},{email:t=>Array.isArray(t)&&t.length>0?t.length===1?g.Email(t[0]):t.map(r=>g.Email(r)):g.Email(t),group:["number","public","authorized","admin",t=>{if(typeof t!="string"||t.length>20||!/^[a-zA-Z0-9]+$/.test(t))throw new c('"group" should be an alphanumeric string without spaces and less than 20 characters.',{code:"INVALID_PARAMETER"});return t}],redirect:t=>g.Url(t)},this.__user?["group"]:["email","group"]);return w.bind(this)(`subscribe-${this.__user?"":"public-"}newsletter`,e,{auth:!!this.__user})}async function bn(n){await this.__connection,n=g.Params(n,{group:["number","public","authorized","admin"]},["group"]);let e=Object.assign({action:"unsubscribe"},n);return w.bind(this)("subscribe-newsletter",e,{auth:true})}async function yn(n,e){let t=await M.bind(this)(),r={message_id:"string",timestamp:"number",read:"number",complaint:"number",subject:"string",bounced:"number"};n||(e=Object.assign({ascending:false},e||{})),n=N(n).data,n=n||{searchFor:"timestamp",value:Date.now(),condition:"<",group:"public"},n=g.Params(n,{searchFor:["message_id","timestamp","subject","complaint","read","bounced"],value:l=>{if(typeof l!==r[n.searchFor])throw new c(`"value" type does not match the type of "${n.searchFor}" index.`,{code:"INVALID_PARAMETER"});if(typeof l=="string"&&!l)throw new c('"value" should not be empty string.',{code:"INVALID_PARAMETER"});return l},range:l=>{if(!n.hasOwnProperty("value")||typeof l!=typeof n.value)throw new c('"range" should match type of "value".',{code:"INVALID_PARAMETER"});return l},condition:[">",">=","=","<","<=","gt","gte","eq","lt","lte",()=>"="],group:l=>{if(l==="public")return 0;if(!this.session)throw new c("User should be logged in.",{code:"INVALID_REQUEST"});if(l==="authorized")return 1;if(typeof l=="number"){if(!t&&l>parseInt(this.user?.access_group||this.session?.idToken?.payload?.access_group))throw new c("User has no access.",{code:"INVALID_REQUEST"});return l}throw new c('"group" should be type: number | "public" | "authorized".',{code:"INVALID_PARAMETER"})}},["searchFor","value","group"]);let i=n.group===0?"get-public-newsletters":"get-newsletters",s=await w.bind(this)(i,n,Object.assign({method:"get",auth:i==="get-public-newsletters"?!!this.__user:true},{fetchOptions:e})),o={message_id:"mid",timestamp:"stmp",complaint:"cmpl",read:"read",subject:"subj",bounced:"bnce",url:"url",delivered:"delv"},a={message_id:"",timestamp:0,complaint:0,read:0,subject:"",bounced:"",url:"",delivered:0};return s.list=s.list.map(l=>{let d={};for(let h in o)d[h]=l[o[h]]||a[h];return d.bounced=String(d.bounced),d}),s}async function wn(n){let e=g.Params(n,{user_id:r=>g.UserId(r,'"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 M.bind(this)()){if(!this.__user)throw new c("User needs to login.",{code:"INVALID_REQUEST"});if(this.__user.access_group<90)throw new c("Invalid access.",{code:"INVALID_REQUEST"})}return await w.bind(this)("block-account",e,{auth:true})}async function En(n){let e=g.Params(n,{user_id:r=>g.UserId(r,'"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 M.bind(this)()){if(!this.__user)throw new c("User needs to login.",{code:"INVALID_REQUEST"});if(this.__user.access_group<90)throw new c("Invalid access.",{code:"INVALID_REQUEST"})}return await w.bind(this)("block-account",e,{auth:true})}async function Rn(n){let e=g.Params(n,{user_id:r=>g.UserId(r,'"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 M.bind(this)()){if(!this.__user)throw new c("User needs to login.",{code:"INVALID_REQUEST"});if(this.__user.access_group<90)throw new c("Invalid access.",{code:"INVALID_REQUEST"})}return await w.bind(this)("remove-account",e,{auth:true})}async function An(n,e){let t={email:s=>g.Email(s),password:s=>g.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=>g.Birthdate(s),phone_number:s=>g.PhoneNumber(s),picture:s=>{if(s)return g.Url(s)},profile:s=>{if(s)return g.Url(s)},website:s=>{if(s)return g.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 c('"access_group" is invalid. Should be type <number>.',{code:"INVALID_PARAMETER"})}if(typeof s!="number"||s<1||s>100)throw new c('"access_group" is invalid. Should be type <number> of range 1~99',{code:"INVALID_PARAMETER"});return s}},r=g.Params(n,t,["email"]);if(e=g.Params(e,{confirmation_url:s=>{let o=s;if(typeof s=="string")o=g.Url(s);else throw new c('"options.confirmation_url" should be type: <string>.',{code:"INVALID_PARAMETER"});if(o&&!r.email)throw new c('"email" is required for signup confirmation.',{code:"INVALID_PARAMETER"});return o},email_subscription:s=>{if(typeof s!="boolean")throw new c('"options.email_subscription" should be type: <boolean>.',{code:"INVALID_PARAMETER"});if(!e?.confirmation_url)throw new c('"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 c('"options.template" should be type: <object> with "url" and "subject".',{code:"INVALID_PARAMETER"});return {url:g.Url(s.url),subject:s.subject}}}),r.signup_confirmation=e?.confirmation_url||true,r.email_subscription=e?.email_subscription||false,r.template=e?.template||{},!await M.bind(this)()){if(!this.__user)throw new c("User needs to login.",{code:"INVALID_REQUEST"});if(this.__user.access_group<90)throw new c("Invalid access.",{code:"INVALID_REQUEST"})}return await w.bind(this)("admin-signup",r,{auth:true})}async function In(n){let e={email:i=>g.Email(i),password:i=>g.Password(i),openid_id:"string",name:"string",username:"string",gender:"string",address:i=>{if(!i)return "";if(typeof i=="string")return i;if(typeof i=="object")return JSON.stringify(i)},birthdate:i=>g.Birthdate(i),phone_number:i=>g.PhoneNumber(i),picture:i=>i?g.Url(i):"",profile:i=>i?g.Url(i):"",website:i=>i?g.Url(i):"",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:i=>{try{typeof i=="string"&&(i=parseInt(i));}catch{throw new c('"access_group" is invalid. Should be type <number>.',{code:"INVALID_PARAMETER"})}if(typeof i!="number"||i<1||i>100)throw new c('"access_group" is invalid. Should be type <number> of range 1~99',{code:"INVALID_PARAMETER"});return i}},t=g.Params(n,e,["email","password"]);if(!await M.bind(this)()){if(!this.__user)throw new c("User needs to login.",{code:"INVALID_REQUEST"});if(this.__user.access_group<90)throw new c("Invalid access.",{code:"INVALID_REQUEST"})}return await w.bind(this)("admin-signup",t,{auth:true})}async function Tn(n){if(n=g.Params(n,{user_id:t=>g.UserId(t,'"user_id"'),access_group:t=>{try{typeof t=="string"&&(t=parseInt(t));}catch{throw new c('"access_group" is invalid. Should be type <number>.',{code:"INVALID_PARAMETER"})}if(typeof t=="number"&&t>0&&t<100)return t;throw new c('"access_group" is invalid. Should be type <number> of range 1~99',{code:"INVALID_PARAMETER"})}},["user_id","access_group"]),!await M.bind(this)()){if(!this.__user)throw new c("User needs to login.",{code:"INVALID_REQUEST"});if(this.__user.access_group<90)throw new c("Invalid access.",{code:"INVALID_REQUEST"})}return await w.bind(this)("grant-access",n,{auth:true})}async function Pn(n,e){if(n=g.Params(n,{email:"string"}),!await M.bind(this)()){if(!this.__user)throw new c("User needs to login.",{code:"INVALID_REQUEST"});if(this.__user.access_group<90)throw new c("Invalid access.",{code:"INVALID_REQUEST"})}let r=await w.bind(this)("invitation-list",Object.assign({mode:"search"},n),{fetchOptions:e,auth:true});return r.list=r.list.map(i=>ae(i.user)),r}async function Sn(n){if(n=g.Params(n,{email:t=>g.Email(t)},["email"]),!await M.bind(this)()){if(!this.__user)throw new c("User needs to login.",{code:"INVALID_REQUEST"});if(this.__user.access_group<90)throw new c("Invalid access.",{code:"INVALID_REQUEST"})}return await w.bind(this)("invitation-list",Object.assign({mode:"cancel"},n),{auth:true})}async function kn(n){if(n=g.Params(n,{email:t=>g.Email(t)},["email"]),!await M.bind(this)()){if(!this.__user)throw new c("User needs to login.",{code:"INVALID_REQUEST"});if(this.__user.access_group<90)throw new c("Invalid access.",{code:"INVALID_REQUEST"})}return await w.bind(this)("invitation-list",Object.assign({mode:"resend"},n),{auth:true})}async function xn(n){if(typeof window>"u"||window._runningInNodeJS)throw new c("Push Notifications are not supported in Node.js environment.",{code:"NOT_SUPPORTED"});if(await this.__connection,!n.endpoint)throw new c("Missing parameter: endpoint",{code:"INVALID_PARAMETER"});if(!n.keys||!n.keys.p256dh||!n.keys.auth)throw new c("Missing parameter: keys.p256dh or keys.auth",{code:"INVALID_PARAMETER"});return await w.bind(this)("store-subscription",{endpoint:n.endpoint,keys:n.keys},{auth:true}),"SUCCESS: Subscribed to receive notifications."}async function vn(n){if(typeof window>"u"||window._runningInNodeJS)throw new c("Push Notifications are not supported in Node.js environment.",{code:"NOT_SUPPORTED"});if(await this.__connection,!n.endpoint)throw new c("Missing parameter: endpoint",{code:"INVALID_PARAMETER"});if(!n.keys||!n.keys.p256dh||!n.keys.auth)throw new c("Missing parameter: keys.p256dh or keys.auth",{code:"INVALID_PARAMETER"});return await w.bind(this)("delete-subscription",{endpoint:n.endpoint,keys:n.keys},{auth:true}),"SUCCESS: Unsubscribed from notifications."}async function Dn(){if(typeof window>"u"||window._runningInNodeJS)throw new c("Push Notifications are not supported in Node.js environment.",{code:"NOT_SUPPORTED"});return await this.__connection,{VAPIDPublicKey:await w.bind(this)("get-vapid-public-key",null,{auth:true})}}async function Un(n,e){if(typeof window>"u"||window._runningInNodeJS)throw new c("Push Notifications are not supported in Node.js environment.",{code:"NOT_SUPPORTED"});await this.__connection;let{title:t,body:r}=N(n||{},{nullIfEmpty:true}).data;if(!t)throw new c("Missing parameter: message title",{code:"INVALID_PARAMETER"});if(!r)throw new c("Missing parameter: message body",{code:"INVALID_PARAMETER"});let i={title:t,body:r};return e?(typeof e=="string"&&(e=[e]),i.user_ids=e):i.user_ids="all_users",await w.bind(this)("push-notification",i,{auth:true}),"SUCCESS: Notification sent."}async function Nn(n){await this.__connection,n=g.Params(n,{spell:"string",name:"string",magic:t=>t},["spell","name"]);await w.bind(this)("castspell",n);return `The spell "${n.spell}" has been cast.`}async function Cn(n){return await this.__connection,n=g.Params(n||{},{search:["spell","name",()=>"spell"],value:"string"}),await w.bind(this)("getspell",n)}async function Ln(n){await this.__connection,n=g.Params(n,{message:"string",name:"string"},["message","name"]);let e=await w.bind(this)("dopamine",n,{auth:true}),t=e?.previous_message?.message,r=e?.previous_message?.name;if($())t&&r&&window.alert(`${r} said: ${t}`),window.location.href=e.video;else return t&&r?`${r} said: ${t}
|
|
216
216
|
Watch the video here: ${e.video}`:`Your message has been uploaded for future generations to receive.
|
|
217
|
-
Watch the video here: ${e.video}`}var b=class{constructor(e,t,r,i){this.__version="1.5.
|
|
217
|
+
Watch the video here: ${e.video}`}var b=class{constructor(e,t,r,i){this.__version="1.5.3";this.session=null;this.connection=null;this.__my_unique_ids={};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 g.UserId(e),!0}catch{return false}},url(e){try{return g.Url(e),!0}catch{return false}},phoneNumber(e){try{return g.PhoneNumber(e),!0}catch{return false}},birthdate(e){try{return g.Birthdate(e),!0}catch{return false}},email(e){try{return g.Email(e),!0}catch{return false}},params(e,t,r){return g.Params(e,t,r)}};this.util={MD5:V,generateRandom:oe,toBase62:Xe,fromBase62:j,decodeServiceId:Ue,formatServiceId:Ze,extractFormData:N,terminatePendingRequests:Tt,request:(e,t,r)=>w.bind(this)(e,t,r,{ignoreService:true})};this.__network_logs=false;this.__endpoint_version="v1";this.__public_identifier="";this.bearerToken="";this.registerTicket=rt.bind(this);this.unregisterTicket=it.bind(this);if(!e||typeof e!="string")throw this._alert("Service ID is required."),new c("Service ID is required.",{code:"INVALID_PARAMETER"});let s=e.split("-").length;if(s===2||s===7)try{let f=Ue(e);r&&typeof r=="object"&&(i=r),t&&typeof t=="object"&&(r=t),t=f.owner,e=f.service;}catch{throw this._alert("Service ID is invalid."),new c("Service ID is invalid.",{code:"INVALID_PARAMETER"})}if(!t||typeof t!="string")throw this._alert("Owner ID is invalid."),new c("Owner ID is invalid.",{code:"INVALID_PARAMETER"});if(e.toLowerCase()==="service_id")throw this._alert('Replace "service_id" with your actual Service ID.'),new c("Service ID is required.",{code:"INVALID_PARAMETER"});if(t!==this.host)try{g.UserId(t,'"owner"');}catch{throw this._alert("Owner ID is invalid."),new c("Owner ID is invalid.",{code:"INVALID_PARAMETER"})}this.service=e,this.owner=t;let l=true;if(r&&(typeof r.autoLogin=="boolean"&&(l=r.autoLogin),typeof r.requestBatchSize=="number")){if(r.requestBatchSize<1)throw new c('"requestBatchSize" must be greater than 0.',{code:"INVALID_PARAMETER"});this.requestBatchSize=r.requestBatchSize;}r?.eventListener&&typeof r.eventListener=="object"&&(r.eventListener?.onLogin&&typeof r.eventListener.onLogin=="function"&&(this.onLogin=r.eventListener.onLogin),r.eventListener?.onUserUpdate&&typeof r.eventListener.onUserUpdate=="function"&&(this.onUserUpdate=r.eventListener.onUserUpdate),r.eventListener?.onBatchProcess&&typeof r.eventListener.onBatchProcess=="function"&&(this.onBatchProcess=r.eventListener.onBatchProcess)),this.target_cdn=i?.target_cdn||this.target_cdn,this.hostDomain=i?.hostDomain||this.hostDomain,this.customApiDomain=i?.customApiDomain||this.customApiDomain,this.__network_logs=!!i?.network_logs;let d=`https://${this.target_cdn}.cloudfront.net`,h=e.substring(0,4);this.admin_endpoint=fetch(`${d}/${h}/admin-${this.__endpoint_version}.json`).then(f=>f.blob()).then(f=>new Promise((A,P)=>{let _=new FileReader;_.onloadend=()=>A(_.result),_.onerror=P,_.readAsDataURL(f);})).then(f=>{try{return typeof f=="string"?JSON.parse(atob(f.split(",")[1])):null}catch{throw new c("Service does not exist. Create your service from skapi.com",{code:"NOT_EXISTS"})}}),this.record_endpoint=fetch(`${d}/${h}/record-${this.__endpoint_version}.json`).then(f=>f.blob()).then(f=>new Promise((A,P)=>{let _=new FileReader;_.onloadend=()=>A(_.result),_.onerror=P,_.readAsDataURL(f);})).then(f=>{try{return typeof f=="string"?JSON.parse(atob(f.split(",")[1])):null}catch{throw new c("Service does not exist. Create your service from skapi.com",{code:"NOT_EXISTS"})}});let u=$();if(u&&!window.sessionStorage)throw this._alert("This browser is not supported."),new Error("This browser is not supported.");let m=u?JSON.parse(window.sessionStorage.getItem(`${e}#${t}`)||"null"):null;if(this.log("constructor:restore",m),m?.connection){for(let f in m)this[f]=m[f];m.__public_identifier||(this.__public_identifier=`${this.service}:${this.owner}:${oe(16)}`);}this.__authConnection=(async()=>{let f=await this.admin_endpoint,A={UserPoolId:f.userpool_id,ClientId:f.userpool_client};De()&&(A.Storage=window.localStorage),this.userPool=new CognitoUserPool(A);try{this.user||await F.bind(this)().getSession({skipUserUpdateEventTrigger:!0}),this.user&&(!m?.connection&&!l?G.bind(this)():(this._runOnLoginListeners(this.user),this._runOnUserUpdateListeners(this.user)));}catch{}})();let R=u?window.sessionStorage.getItem(`${this.service}:uniqueids`):null;if(R)try{this.__my_unique_ids=JSON.parse(R);}catch{this.__my_unique_ids={};}this.__connection=(async()=>{let f=null;await this.record_endpoint,m?.connection||(f=this._updateConnection());let A=()=>{if(this.__class_properties_has_been_cached)return;let P=()=>{let _={},x=["__startKeyHistory","__disabledAccount","__cached_requests","__request_signup_confirmation","__public_identifier","connection"];if(this.connection){for(let k of x)_[k]=this[k];u&&window.sessionStorage.setItem(`${e}#${t}`,JSON.stringify(_)),this.__class_properties_has_been_cached=true;}};return f instanceof Promise?f.then(()=>P()):P()};return u&&(window.addEventListener("beforeunload",()=>{this.closeRealtime(),A();}),window.addEventListener("visibilitychange",()=>{A();})),await f,await this.__authConnection,this.connection})(),this.__connection.then(f=>{((f?.group||0)<3||this.__network_logs)&&this.version();});}get user(){return this.__user&&Object.keys(this.__user).length?JSON.parse(JSON.stringify(this.__user)):null}set user(e){}get onLogin(){return this._onLoginListeners}set onLogin(e){typeof e=="function"&&this._onLoginListeners.push(e);}get onUserUpdate(){return this._userProfileListeners}set onUserUpdate(e){typeof e=="function"&&this._userProfileListeners.push(e);}_runOnUserUpdateListeners(e){for(let t of this._userProfileListeners)typeof t=="function"&&t(e);}_runOnLoginListeners(e){for(let t of this._onLoginListeners)typeof t=="function"&&t(e);}get onBatchProcess(){return this._onBatchProcessListeners}set onBatchProcess(e){typeof e=="function"&&this._onBatchProcessListeners.push(e);}_alert(e){$()&&typeof window.alert=="function"&&window.alert(e);}async getConnectionInfo(){let e=await this.__connection,t=e?.user_agent||($()&&typeof window.navigator?.userAgent=="string"?window.navigator.userAgent:`skapi-node/${globalThis?.process?.versions?.node||"unknown"}`);return {user_ip:e.ip,user_agent:t,user_location:e.locale,service_name:e.service_name,version:this.__version}}async _updateConnection(){try{this.connection=await w.bind(this)("service",{service:this.service,owner:this.owner},{bypassAwaitConnection:!0,method:"get"});}catch(e){throw this.log("connection fail",e),this._alert("Service is not available: "+(e.message||e.toString())),this.connection=null,e}return this.connection}async version(){if(await this.__connection,$()){let t=`Built with:
|
|
218
218
|
%c\r
|
|
219
219
|
$$\\ $$\\ \r
|
|
220
220
|
$$ | \\__|\r
|