skapi-js 2.0.0-rc.2 → 2.0.0-rc.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/skapi.browser.mjs +6 -6
- package/dist/skapi.browser.mjs.map +1 -1
- package/dist/skapi.cjs +6 -6
- package/dist/skapi.cjs.map +1 -1
- package/dist/skapi.d.mts +29 -0
- package/dist/skapi.d.ts +29 -0
- package/dist/skapi.js +6 -6
- package/dist/skapi.js.map +1 -1
- package/dist/skapi.mjs +6 -6
- package/dist/skapi.mjs.map +1 -1
- package/package.json +2 -2
package/dist/skapi.cjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
'use strict';var amazonCognitoIdentityJs=require('amazon-cognito-identity-js'),
|
|
1
|
+
'use strict';var amazonCognitoIdentityJs=require('amazon-cognito-identity-js'),Ir=require('cocochex'),mn=require('qpass');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var Ir__default=/*#__PURE__*/_interopDefault(Ir);var mn__default=/*#__PURE__*/_interopDefault(mn);/**
|
|
2
2
|
* @license
|
|
3
3
|
Apache License
|
|
4
4
|
Version 2.0, January 2004
|
|
@@ -203,7 +203,7 @@
|
|
|
203
203
|
limitations under the License.
|
|
204
204
|
|
|
205
205
|
*/
|
|
206
|
-
var tr=Object.defineProperty;var nr=Object.getOwnPropertyDescriptor;var oe=(t=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(t,{get:(e,n)=>(typeof require<"u"?require:e)[n]}):t)(function(t){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+t+'" is not supported')});var R=(t,e,n,r)=>{for(var i=nr(e,n),s=t.length-1,o;s>=0;s--)(o=t[s])&&(i=(o(e,n,i))||i);return i&&tr(e,n,i),i};var Y=typeof globalThis<"u"?globalThis:void 0,Ee=Y?.window;function rr(t){if(Buffer)return Buffer.from(t).toString("base64");let e="",n=new Uint8Array(t),r=32768;for(let i=0;i<n.length;i+=r){let s=n.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(Ee)Ee.global=Ee,Ee.global._runningInNodeJS=false;else if(Y&&(Y.global=Y,typeof Y.window>"u")){class t{constructor(){this.result=null;this.error=null;this.onload=null;this.onloadend=null;this.onerror=null;}readAsDataURL(r){r.arrayBuffer().then(i=>{let s=rr(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});});}}Y.FileReader=t;class e{constructor(){this.status=0;this.statusText="";this.readyState=0;this.responseText="";this.response=null;this.responseType="";this.responseURL="";this.timeout=0;this.withCredentials=false;this.onload=null;this.onerror=null;this.onabort=null;this.ontimeout=null;this.onprogress=null;this.onreadystatechange=null;this.upload={onprogress:null};this._method="GET";this._url="";this._headers={};this._aborted=false;}open(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);});}}Y.XMLHttpRequest=e,Y.window={_runningInNodeJS:true,alert:n=>console.error("[Alert]",n),sessionStorage:{getItem:n=>null,setItem:(n,r)=>{},removeItem:n=>{}},localStorage:{getItem:n=>{let r=oe("fs"),i=oe("path");try{let s=i.resolve(process.cwd(),"states","localStorage",`${n}.skapi`);return r.existsSync(s)?r.readFileSync(s,"utf8"):null}catch{return null}},setItem:(n,r)=>{let i=oe("fs"),s=oe("path");try{let o=s.resolve(process.cwd(),"states","localStorage");i.existsSync(o)||i.mkdirSync(o,{recursive:!0});let l=s.resolve(o,`${n}.skapi`);i.writeFileSync(l,r,"utf8");}catch{}},removeItem:n=>{let r=oe("fs"),i=oe("path");try{let s=i.resolve(process.cwd(),"states","localStorage",`${n}.skapi`);r.existsSync(s)&&r.unlinkSync(s);}catch{}}},location:{href:"",origin:"",hostname:"",protocol:"",replace:n=>{}},navigator:{userAgent:`nodejs/${Y?.process?.versions?.node||"unknown"}`,mediaDevices:{getUserMedia:async n=>{throw new Error("getUserMedia is not supported in Node.js environment.")}}},addEventListener:()=>{},removeEventListener:()=>{}};}var a=class extends Error{constructor(e,n){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=n?.name||"SKAPI",this.code=n?.code||e[0]||"ERROR",n?.cause&&(this.cause=n.cause);}else super((e?.message||(typeof e=="string"?e:"Something went wrong.")).trim()),typeof e=="string"?(this.name=n?.name||"SKAPI",this.code=n?.code||"ERROR",n?.cause&&(this.cause=n.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=n?.name||"SKAPI",this.code=n?.code||"ERROR",this.cause=e?.cause);}};var ee="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",Me=BigInt(ee.length),ir=2*1024*1024,sr=["aud","cognito:username","event_id","exp","iat","iss","jti","origin_jti","secret_key","token_use"],tt={auth_time:"log",sub:"user_id"},or=["0","1","2","3","4","5","6","7","8","9","a","b","c","d","e","f","g","h","i","j","k","l"],ot=["us31","us72","ap51","ap22","ap41","eu71","ap21","us32","us71","af51","ap31","ap43","ap23","ap42","ca01","eu01","eu72","eu51","eu73","eu11","me51","sa31"],nt=typeof TextEncoder<"u"?new TextEncoder:null;function ar(){if(typeof globalThis<"u")return globalThis.Buffer}function cr(t){if(nt)return nt.encode(t);let e=unescape(encodeURIComponent(t)),n=new Uint8Array(e.length);for(let r=0;r<e.length;r++)n[r]=e.charCodeAt(r);return n}function lr(t){if(t instanceof Uint8Array)return t;if(typeof t=="string")return cr(t);if(typeof ArrayBuffer<"u"&&t instanceof ArrayBuffer)return new Uint8Array(t);if(typeof ArrayBuffer<"u"&&ArrayBuffer.isView(t))return new Uint8Array(t.buffer,t.byteOffset,t.byteLength);if(Array.isArray(t))return Uint8Array.from(t);let e=ar();if(e)return new Uint8Array(e.from(t));throw new Error("No byte conversion available in this environment.")}var b=class b{static hash(e){typeof e!="string"&&(console.warn("coercing non-string value to empty string"),e="");let n=b.sb(e),r=1732584193,i=-271733879,s=-1732584194,o=271733878,l,u,c,d;for(let g=0;g<n.length;g+=16)l=r,u=i,c=s,d=o,r=b.ff(r,i,s,o,n[g],7,-680876936),o=b.ff(o,r,i,s,n[g+1],12,-389564586),s=b.ff(s,o,r,i,n[g+2],17,606105819),i=b.ff(i,s,o,r,n[g+3],22,-1044525330),r=b.ff(r,i,s,o,n[g+4],7,-176418897),o=b.ff(o,r,i,s,n[g+5],12,1200080426),s=b.ff(s,o,r,i,n[g+6],17,-1473231341),i=b.ff(i,s,o,r,n[g+7],22,-45705983),r=b.ff(r,i,s,o,n[g+8],7,1770035416),o=b.ff(o,r,i,s,n[g+9],12,-1958414417),s=b.ff(s,o,r,i,n[g+10],17,-42063),i=b.ff(i,s,o,r,n[g+11],22,-1990404162),r=b.ff(r,i,s,o,n[g+12],7,1804603682),o=b.ff(o,r,i,s,n[g+13],12,-40341101),s=b.ff(s,o,r,i,n[g+14],17,-1502002290),i=b.ff(i,s,o,r,n[g+15],22,1236535329),r=b.gg(r,i,s,o,n[g+1],5,-165796510),o=b.gg(o,r,i,s,n[g+6],9,-1069501632),s=b.gg(s,o,r,i,n[g+11],14,643717713),i=b.gg(i,s,o,r,n[g],20,-373897302),r=b.gg(r,i,s,o,n[g+5],5,-701558691),o=b.gg(o,r,i,s,n[g+10],9,38016083),s=b.gg(s,o,r,i,n[g+15],14,-660478335),i=b.gg(i,s,o,r,n[g+4],20,-405537848),r=b.gg(r,i,s,o,n[g+9],5,568446438),o=b.gg(o,r,i,s,n[g+14],9,-1019803690),s=b.gg(s,o,r,i,n[g+3],14,-187363961),i=b.gg(i,s,o,r,n[g+8],20,1163531501),r=b.gg(r,i,s,o,n[g+13],5,-1444681467),o=b.gg(o,r,i,s,n[g+2],9,-51403784),s=b.gg(s,o,r,i,n[g+7],14,1735328473),i=b.gg(i,s,o,r,n[g+12],20,-1926607734),r=b.hh(r,i,s,o,n[g+5],4,-378558),o=b.hh(o,r,i,s,n[g+8],11,-2022574463),s=b.hh(s,o,r,i,n[g+11],16,1839030562),i=b.hh(i,s,o,r,n[g+14],23,-35309556),r=b.hh(r,i,s,o,n[g+1],4,-1530992060),o=b.hh(o,r,i,s,n[g+4],11,1272893353),s=b.hh(s,o,r,i,n[g+7],16,-155497632),i=b.hh(i,s,o,r,n[g+10],23,-1094730640),r=b.hh(r,i,s,o,n[g+13],4,681279174),o=b.hh(o,r,i,s,n[g],11,-358537222),s=b.hh(s,o,r,i,n[g+3],16,-722521979),i=b.hh(i,s,o,r,n[g+6],23,76029189),r=b.hh(r,i,s,o,n[g+9],4,-640364487),o=b.hh(o,r,i,s,n[g+12],11,-421815835),s=b.hh(s,o,r,i,n[g+15],16,530742520),i=b.hh(i,s,o,r,n[g+2],23,-995338651),r=b.ii(r,i,s,o,n[g],6,-198630844),o=b.ii(o,r,i,s,n[g+7],10,1126891415),s=b.ii(s,o,r,i,n[g+14],15,-1416354905),i=b.ii(i,s,o,r,n[g+5],21,-57434055),r=b.ii(r,i,s,o,n[g+12],6,1700485571),o=b.ii(o,r,i,s,n[g+3],10,-1894986606),s=b.ii(s,o,r,i,n[g+10],15,-1051523),i=b.ii(i,s,o,r,n[g+1],21,-2054922799),r=b.ii(r,i,s,o,n[g+8],6,1873313359),o=b.ii(o,r,i,s,n[g+15],10,-30611744),s=b.ii(s,o,r,i,n[g+6],15,-1560198380),i=b.ii(i,s,o,r,n[g+13],21,1309151649),r=b.ii(r,i,s,o,n[g+4],6,-145523070),o=b.ii(o,r,i,s,n[g+11],10,-1120210379),s=b.ii(s,o,r,i,n[g+2],15,718787259),i=b.ii(i,s,o,r,n[g+9],21,-343485551),r=b.ad(r,l),i=b.ad(i,u),s=b.ad(s,c),o=b.ad(o,d);return b.rh(r)+b.rh(i)+b.rh(s)+b.rh(o)}static rh(e){let n="";for(let r=0;r<=3;r++)n+=b.alphabet.charAt(e>>r*8+4&15)+b.alphabet.charAt(e>>r*8&15);return n}static ad(e,n){let r=(e&65535)+(n&65535);return (e>>16)+(n>>16)+(r>>16)<<16|r&65535}static rl(e,n){return e<<n|e>>>32-n}static cm(e,n,r,i,s,o){return b.ad(b.rl(b.ad(b.ad(n,e),b.ad(i,o)),s),r)}static ff(e,n,r,i,s,o,l){return b.cm(n&r|~n&i,e,n,s,o,l)}static gg(e,n,r,i,s,o,l){return b.cm(n&i|r&~i,e,n,s,o,l)}static hh(e,n,r,i,s,o,l){return b.cm(n^r^i,e,n,s,o,l)}static ii(e,n,r,i,s,o,l){return b.cm(r^(n|~i),e,n,s,o,l)}static sb(e){let n,r=(e.length+8>>6)+1,i=new Array(r*16);for(n=0;n<r*16;n++)i[n]=0;for(n=0;n<e.length;n++)i[n>>2]|=e.charCodeAt(n)<<n%4*8;return i[n>>2]|=128<<n%4*8,i[r*16-2]=e.length*8,i}};b.alphabet="0123456789abcdef";var q=b;function at(t){if(t===0)return ee[0];let e="";for(;t>0;)e=ee[t%62]+e,t=Math.floor(t/62);return e}function B(t){return t.split("").reverse().reduce((e,n,r)=>e+ee.indexOf(n)*62**r,0)}function ie(t=6){let e="",n="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",r=n.length,i=0;for(;i<t;)e+=n.charAt(Math.floor(Math.random()*r)),i+=1;return e}function Fe(){return typeof window>"u"||!!window?._runningInNodeJS}function j(){return !Fe()&&typeof document<"u"&&typeof document.createElement=="function"}function Re(t){let e;try{e=JSON.stringify(t);}catch{throw new a("Invalid data type.",{code:"INVALID_REQUEST"})}if(new Blob([e]).size>ir)throw new a("Data should not exceed 2MB",{code:"INVALID_REQUEST"})}function rt(t){return t===""||t==="on"||t==="true"}function it(t){return t==="false"}function st(t,e,n){e.name&&n(t,e.name,e.value);}var Ae=j(),ur=typeof SubmitEvent<"u",dr=typeof HTMLFormElement<"u";function U(t,e,n){let r={},i=[];function s(u,c,d){if(e?.ignoreEmpty&&d==="")return;if(e?.nullIfEmpty&&d===""&&(d=null),typeof n=="function"){let _=n(c,d);_!==void 0&&(d=_);}let g=c.split("[").map(_=>{let p=_.replace("]",""),y=Number(p);return !isNaN(y)&&!p.includes(".")?p=y:(p[0]==='"'&&p[p.length-1]==='"'||p[0]==="'"&&p[p.length-1]==="'")&&(p=p.replace(/"/g,"").replace(/'/g,"")),p}),h=u;if(typeof g[0]=="number")throw new a("Form key cannot start with an array index.",{code:"INVALID_REQUEST"});for(let _=0;_<g.length;_++){let p=g[_];_<g.length-1?(h[p]===void 0&&(typeof g[_+1]=="number"?h[p]=[]:h[p]={}),h=h[p]):h[p]===void 0?h[p]=d:Array.isArray(h[p])?h[p].push(d):h[p]=[h[p],d];}}function o(u,c,d){if(d instanceof File)u.push({name:c,file:d});else if(d instanceof FileList&&d&&d.length>0)for(let g=0;g<=d.length-1;g++){let h=d.item(g);h&&u.push({name:c,file:h});}}let l=u=>{u.name&&(u.type==="number"?u.value&&s(r,u.name,Number(u.value)):u.type==="checkbox"||u.type==="radio"?u.checked?u.type==="checkbox"&&u.value===""||rt(u.value)?s(r,u.name,true):it(u.value)?s(r,u.name,false):u.value&&s(r,u.name,u.value):u.type==="checkbox"&&(rt(u.value)?s(r,u.name,false):it(u.value)&&s(r,u.name,true)):u.type==="file"?u.files&&u.files.length>0&&o(i,u.name,u.files):s(r,u.name,u.value));};if(Ae&&(t instanceof HTMLInputElement||t instanceof HTMLSelectElement||t instanceof HTMLTextAreaElement))return l(t),Re(r),{data:r,files:i};if(Ae&&t instanceof FormData){for(let u of t.entries()){let c=u[0],d=u[1];if(d instanceof File||d instanceof FileList)o(i,c,d);else if(d instanceof Blob){let g=d;if(g.type==="application/json")try{let h=JSON.parse(g.text());s(r,c,h);}catch{s(r,c,g);}}else s(r,c,d);}return Re(r),{data:r,files:i}}if(Ae&&ur&&t instanceof SubmitEvent&&(t=t.target),Ae&&dr&&t instanceof HTMLFormElement){let u=t.querySelectorAll("input"),c=t.querySelectorAll("select"),d=t.querySelectorAll("textarea");for(let g=0;g<c.length;g++)st(r,c[g],s);for(let g=0;g<d.length;g++)st(r,d[g],s);for(let g=0;g<u.length;g++)l(u[g]);return Re(r),{data:r,files:i}}return Re(t),{data:t,files:i}}function fe(t){let e={};for(let n in t){let r=t[n];if(!sr.includes(n))if(tt[n])e[tt[n]]=r;else if(n.includes("custom:"))e[n.replace("custom:","")]=r;else if(n==="address"){let i=r;if(i&&typeof i=="object"&&Object.keys(i).length){if(i?.formatted)try{e[n]=JSON.parse(i.formatted);}catch{e[n]=i.formatted;}}else e[n]=i;}else e[n]=r;}for(let n of ["address_public","birthdate_public","email_public","gender_public","phone_number_public","access_group"])n.includes("_public")?e.hasOwnProperty(n.split("_")[0])?e[n]=e.hasOwnProperty(n)?!!Number(e[n]):false:delete e[n]:e[n]=e.hasOwnProperty(n)?Number(e[n]):0;for(let n of ["email","phone_number"])e.hasOwnProperty(n)?e[n+"_verified"]=e[n+"_verified"]===true:delete e[n+"_verified"];return e}function qe(t){if(t=yr(t),t.split("-").length===7){let e=t.split("-"),n,r;try{n=ot[B(e[1][0])],r=e.slice(2).join("-");}catch{throw new Error("INVALID_PARAMETER: Service ID is invalid: "+t)}if(!n)throw new Error("INVALID_PARAMETER: Service ID is invalid: "+t);return {service:n+e[0]+e[1].slice(1),owner:r}}return {service:t,owner:""}}function Ve(t,e){let n=ot.indexOf(t.slice(0,4)),r=or[n],s=`${t.slice(4,-4)}-${r}${t.slice(-4)}-${e}`;return br(s)}function gr(t){let e=0n;for(let n of t){let r=ee.indexOf(n);if(r<0)throw new Error(`INVALID_PARAMETER: Invalid base62 character: ${n}`);e=e*Me+BigInt(r);}return e}function fr(t,e=1){if(t<0n)throw new Error("INVALID_PARAMETER: Negative values are not supported.");if(t===0n)return "0".repeat(Math.max(1,e));let n="",r=t;for(;r>0n;){let i=Number(r%Me);n=ee[i]+n,r/=Me;}return n.length<e&&(n="0".repeat(e-n.length)+n),n}function hr(t){if(t===0n)return Uint8Array.from([0]);let e=[],n=t;for(;n>0n;)e.push(Number(n&0xffn)),n>>=8n;return e.reverse(),Uint8Array.from(e)}function pr(t){let e=0n;for(let n of t)e=(e<<8n)+BigInt(n);return e}function mr(t){let e=String(t).replace(/-/g,"");if(!/^[0-9a-fA-F]{32}$/.test(e))throw new Error("INVALID_PARAMETER: Invalid UUID format.");let n=new Uint8Array(16);for(let r=0;r<16;r++)n[r]=parseInt(e.slice(r*2,r*2+2),16);return n}function _r(t){let e=Array.from(lr(t),n=>n.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 br(t){let e=String(t);if(e.split("-").length===2)return e;let n=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(!n)throw new Error("INVALID_PARAMETER: Input must match <base62>-<base62>-<uuid>.");let[,r,i,s]=n;if(r.length<2)throw new Error("INVALID_PARAMETER: The first part must contain at least 2 characters.");if(i.length>=ee.length)throw new Error("INVALID_PARAMETER: The middle section is too long to encode.");let o=r.slice(0,2),l=r.slice(2),u=i+o,c=ee[i.length]+l+u,d=mr(s),g=fr(pr(d));return `${c}-${g}`}function yr(t){let e=String(t);if(e.split("-").length!==2)return e;let n=e.split("-");if(n.length!==2||!n[0]||!n[1])throw new Error("INVALID_PARAMETER: Corrupt compressed token: "+e);let[r,i]=n,s=ee.indexOf(r[0]);if(s<0)throw new Error("INVALID_PARAMETER: Corrupt compressed token: "+e);let o=r.slice(1),l=s+2;if(o.length<l)throw new Error("INVALID_PARAMETER: Corrupt compressed token: "+e);let u=o.slice(0,o.length-l),c=o.slice(o.length-l),d=c.slice(s),g=c.slice(0,s),h=d+u;if(!/^[0-9A-Za-z]+$/.test(h)||!/^[0-9A-Za-z]+$/.test(g))throw new Error("INVALID_PARAMETER: Corrupt compressed token: "+e);let _=gr(i),p=hr(_);if(p.length>16)throw new Error("INVALID_PARAMETER: Corrupt compressed token: "+e);let y=new Uint8Array(16);y.set(p,16-p.length);let P=_r(y);return `${h}-${g}-${P}`}function Er(t,e="User ID"){let n=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;if(t){if(typeof t!="string")throw new a(`${e} should be type: string.`,{code:"INVALID_PARAMETER"});if(!t.match(n))throw new a(`${e} is invalid.`,{code:"INVALID_PARAMETER"})}else throw new a(`${e} is empty.`,{code:"INVALID_PARAMETER"});return t}function Rr(t){if(t&&(typeof t!="string"||t.charAt(0)!=="+"||isNaN(Number(t.substring(1)))))throw new a('"phone_number" is invalid. The format should be "+00123456789". Type: string.',{code:"INVALID_PARAMETER"});return t||""}function Ar(t){if(t){if(typeof t!="string")throw new a('"birthdate" is invalid. The format should be "yyyy-mm-dd". Type: string.',{code:"INVALID_PARAMETER"});{let e=new RegExp(/([12]\d{3}-(0[1-9]|1[0-2])-(0[1-9]|[12]\d|3[01]))/);if(t.length!==10||t.split("-").length!==3||!e.test(t))throw new a('"birthdate" is invalid. The format should be "yyyy-mm-dd". Type: string.',{code:"INVALID_PARAMETER"})}}return t||""}function Ir(t){if(t){if(typeof t!="string")throw new a('"password" should be type: string.',{code:"INVALID_PARAMETER"});if(t.length<6)throw new a('"password" should be at least 6 characters.',{code:"INVALID_PARAMETER"});if(t.length>60)throw new a('"password" can be up to 60 characters max.',{code:"INVALID_PARAMETER"})}else throw new a('"password" is required.',{code:"INVALID_PARAMETER"});return t}function Tr(t,e="email"){if(t){if(typeof t!="string")throw new a(`"${e}"should be type: string.`,{code:"INVALID_PARAMETER"});if(t.length<5)throw new a(`"${e}" should be at least 5 characters.`,{code:"INVALID_PARAMETER"});if(/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/.test(t)&&(t=t.trim(),t.split("@")[1].split(".").length>=2))return t.toLowerCase()}else throw new a(`"${e}" is required.`,{code:"INVALID_PARAMETER"});throw new a(`"${t}" is an invalid email.`,{code:"INVALID_PARAMETER"})}function Pr(t){let e=typeof window<"u",n=(()=>{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]==="/"&&n){if(n.slice(0,5)==="file:")throw new a(`"${i}" is an invalid url. Relative URL does not work on local file system. Use full URL string.`,{code:"INVALID_PARAMETER"});s=n+s;}else if(s[0]==="."&&n){if(n.slice(0,5)==="file:")throw new a(`"${i}" is an invalid url. Relative URL does not work on local file system. Use full URL string.`,{code:"INVALID_PARAMETER"});let l=e?window.location.href.split("?")[0]:"";l.slice(-1)!=="/"&&(l+="/"),s=l+s.slice(1);}let o;try{o=new URL(s);}catch{throw new a(`"${i}" is an invalid url.`,{code:"INVALID_PARAMETER"})}if(o.protocol)return o.href}}throw new a(`"${i}" is an invalid url.`,{code:"INVALID_PARAMETER"})};return Array.isArray(t)?t.map(i=>r(i)):r(t)}function Sr(t,e,n=[],r){let i=U(t,r),s=i.data;e.service="string",e.owner="string";let o={};for(let l in e)if(s&&typeof s=="object"&&!Array.isArray(s)&&s.hasOwnProperty(l))if(typeof s[l]=="function")o[l]=s[l];else try{o[l]=JSON.parse(JSON.stringify(s[l]));}catch{o[l]=s[l];}r?.precall&&r.precall({data:o,files:i?.files||[]});try{return wr__default.default(o,e,n)}catch(l){throw new a(l.message,{code:"INVALID_PARAMETER"})}}var f={UserId:Er,PhoneNumber:Rr,Birthdate:Ar,Password:Ir,Email:Tr,Url:Pr,Params:Sr};var L=null;function $e(t){let e={tkid:"ticket_id",cond:"condition",stmp:"timestamp",actn:"action",cnt:"count",ttl:"time_to_live",plch:"placeholder",hash:"hash",desc:"description",pmc:"limit_per_user"},n={};for(let r in t)if(r==="tkid"){let i=t[r].split("#");if(i.length===1){n.ticket_id=i[0];continue}n.ticket_id=i[1],n.consume_id=i[2],n.user_id=i[3];let s=i[2].slice(-4);if(n.is_test=s===":CHK",!t.stmp){let o=i[2].slice(0,-4);/^[0-9]+$/.test(o)?n.timestamp=parseInt(o,10):n.timestamp=B(i[2].slice(0,-4));}}else e[r]?n[e[r]]=t[r]:n[r]=t[r];return n}async function lt(t){if(!t.ticket_id)throw new a("Ticket ID is required.",{code:"INVALID_PARAMETER"});if(!t.method)throw new a('Method is required. Should be either "GET" or "POST"',{code:"INVALID_PARAMETER"});let e=t.ticket_id;await this.__connection;let n=await E.bind(this)(`https://${this.service.slice(0,4)}.${this.customApiDomain}/auth/consume/${this.service}/${this.owner}/${e}`,t?.data||{},{method:t.method,auth:!!t?.auth});return $e(n)}async function ut(t,e){await this.__connection;let n=await E.bind(this)("ticket",Object.assign({exec:"list"},t||{}),{auth:true,fetchOptions:e});return n.list=n.list.map($e),n}async function dt(t,e){await this.__connection;let n=await E.bind(this)("ticket",Object.assign({exec:"consumed"},t||{}),{auth:true,fetchOptions:e});return n.list=n.list.map($e),n}async function gt(t){return E.bind(this)("register-ticket",Object.assign({exec:"reg"},t),{auth:true})}async function ft(t){return E.bind(this)("register-ticket",Object.assign({exec:"unreg"},t),{auth:true})}var Ur=3600;async function ce(){if(await this.__connection,this.session){let t=Math.floor(Date.now()/1e3),n=this.session.getIdToken().getExpiration();if(n<t+Ur){this.log("request:requesting new token",null);try{await $.bind(this)().getSession({refreshToken:!0}),this.log("request:received new tokens",{exp:this.session?.idToken?.payload?.exp,currentTime:t,expiresIn:n-t,token:this.session?.accessToken?.jwtToken,refreshToken:this.session?.refreshToken?.token});}catch(r){throw this.log("request:new token error",r),new a("User login is required.",{code:"INVALID_REQUEST"})}}else this.log("request:tokens",{exp:this.session.idToken.payload.exp,currentTime:t,expiresIn:n-t,token:this.session.accessToken.jwtToken,refreshToken:this.session.refreshToken.token});return this.session?.idToken?.jwtToken}else throw this.log("request:no session",null),te.bind(this)(),new a("User login is required.",{code:"INVALID_REQUEST"})}function ct(t,e){return new Promise((n,r)=>{e.refreshSession(t.getRefreshToken(),(i,s)=>{this.log("getSession:refreshSessionCallback",{refreshErr:i,refreshedSession:s}),i?(te.bind(this)(),r(i)):s.isValid()?n(s):(te.bind(this)(),r(new a("Invalid session.",{code:"INVALID_REQUEST"})));});})}function $(){if(!this.userPool)throw new a("User pool is missing",{code:"INVALID_REQUEST"});let t=()=>{let s=L.getSignInUserSession().getIdToken().payload||null,o=fe(s);return this.log("normalized user attribute",o),this.__user=o,o},e=async s=>new Promise((o,l)=>{this.log("getSession:option",s);let{refreshToken:u=false,skipUserUpdateEventTrigger:c=false}=s||{};if(u&&c&&(c=false),L=this.userPool.getCurrentUser(),!L){this.log("getSession:cognitoUser",L),te.bind(this)(),l(null);return}let d=g=>{let h=g.getIdToken().payload;if(this.log("getSession:respond:sessionAttribute",h),h["custom:service"]!==this.service)throw this.log("getSession:respond","invalid service, signing out"),te.bind(this)(),new a("Invalid session.",{code:"INVALID_REQUEST"});return this.session=g,t(),c||this._runOnUserUpdateListeners(this.user),this.session};L.getSession((g,h)=>{if(this.log("getSession:getSessionCallback",{err:g,session:h}),!h){te.bind(this)(),l(new a("Current session does not exist.",{code:"INVALID_REQUEST"}));return}if(g){ct.bind(this)(h,L).then(m=>o(d(m))).catch(l);return}let _=Math.floor(Date.now()/1e3),p=h.getIdToken(),y=p.getExpiration(),P=y<_;if(this.log("getSession:currentTime",_),this.log("getSession:idTokenExp",y),this.log("getSession:isExpired",P),this.log("getSession:existingBearerToken",this.bearerToken),this.bearerToken=p.getJwtToken(),P||u||!h.isValid())ct.bind(this)(h,L).then(m=>o(d(m))).catch(l);else try{o(d(h));}catch(m){l(m);}});}),n=(s,o)=>{let l=o||s.includes(this.service+"-")?s:this.service+"-"+q.hash(s);return {cognitoUser:new amazonCognitoIdentityJs.CognitoUser({Username:l,Pool:this.userPool}),cognitoUsername:l}};return {getSession:e,authenticateUser:(s,o,l=false,u=false)=>new Promise((c,d)=>{this.__request_signup_confirmation=null,this.__disabledAccount=null;let g=n(s,l),h=g.cognitoUsername,_=new amazonCognitoIdentityJs.AuthenticationDetails({Username:h,Password:o});g.cognitoUser.authenticateUser(_,{newPasswordRequired:(p,y)=>{this.__disabledAccount=null,this.__request_signup_confirmation=h,p["custom:signup_ticket"]==="PASS"||p["custom:signup_ticket"]==="MEMBER"||p["custom:signup_ticket"]==="OIDPASS"?g.cognitoUser.completeNewPasswordChallenge(o,{},{onSuccess:P=>{L=g.cognitoUser,e().then(m=>c(this.user));},onFailure:P=>{d(new a(P.message||"Failed to authenticate user.",{code:P.code}));}}):d(new a("User's signup confirmation is required.",{code:"SIGNUP_CONFIRMATION_NEEDED"}));},onSuccess:p=>e({skipUserUpdateEventTrigger:true}).then(y=>{this.__disabledAccount=null,this._runOnLoginListeners(this.user),this._runOnUserUpdateListeners(this.user),c(this.user);}),onFailure:p=>{let y=[],{parsed:P,code:m}=Te(p),T=typeof p?.message=="string"?p.message:"";if(m==="NotAuthorizedException"?T.includes("User is disabled.")?(this.__disabledAccount=h,y=["This account is disabled.","USER_IS_DISABLED"]):u?y=["The account already exists.","ACCOUNT_EXISTS"]:y=["Incorrect username or password.","INCORRECT_USERNAME_OR_PASSWORD"]:m==="UserNotFoundException"?y=["Incorrect username or password.","INCORRECT_USERNAME_OR_PASSWORD"]:m==="UserNotConfirmedException"?(this.__request_signup_confirmation=h,y=["User's signup confirmation is required.","SIGNUP_CONFIRMATION_NEEDED"]):(m==="TooManyRequestsException"||m==="LimitExceededException")&&(y=["Too many attempts. Please try again later.","REQUEST_EXCEED"]),P.code==="SIGNUP_CONFIRMATION_NEEDED"&&(this.__request_signup_confirmation=h),y.length){let x=y[1],I=y[0];d(new a(I,{code:x,cause:p}));}else d(P);}});}),createCognitoUser:n,signup:(s,o,l)=>new Promise((u,c)=>{this.userPool.signUp(s,o,l,null,(d,g)=>{if(d){let{parsed:h,code:_}=Te(d),p=[];_==="UsernameExistsException"?p=["The account already exists.","EXISTS"]:_==="InvalidPasswordException"?p=["Invalid password. Password must be at least 6 characters.","INVALID_PARAMETER"]:_==="InvalidParameterException"?p=[h.message||"Invalid parameter.","INVALID_PARAMETER"]:_==="TooManyRequestsException"||_==="LimitExceededException"?p=["Too many attempts. Please try again later.","REQUEST_EXCEED"]:_==="CodeDeliveryFailureException"?p=["Failed to deliver verification code.","CODE_DELIVERY_FAILURE"]:_==="UserLambdaValidationException"&&(p=[h.message||"Signup validation failed.","INVALID_REQUEST"]),p.length?c(new a(p[0],{code:p[1],cause:d})):c(h);return}u(g);});})}}function Te(t){let e=typeof t?.code=="string"&&t.code.trim()?t.code.trim():"ERROR",r=((typeof t?.message=="string"?t.message:typeof t=="string"?t:"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 a(o,{code:s,cause:t}),code:e}}async function ht(t){await this.__authConnection;let e=t?.refreshToken||false;if(!e)return this.user;try{return await $.bind(this)().getSession(Object.assign({skipUserUpdateEventTrigger:!e,refreshToken:e},t)),this.user}catch{return null}}async function pt(t){await this.__connection,t=f.Params(t,{token:"string",id:"string",merge:o=>{if(o===void 0)return false;if(typeof o=="string")return [o];if(Array.isArray(o)){for(let l of o)if(typeof l!="string")throw new a('"merge" array items should be type: <string>.',{code:"INVALID_PARAMETER"})}if(typeof o!="boolean"&&!Array.isArray(o))throw new a('"merge" should be type: <boolean | string[]>.',{code:"INVALID_PARAMETER"});return o},template:o=>{if(typeof o!="object"||o===null)throw new a('"template" should be type: <object>.',{code:"INVALID_PARAMETER"});if(o.welcome!==void 0&&(typeof o.welcome!="string"||!o.welcome))throw new a('"template.welcome" should be a non-empty <string> (template message_id).',{code:"INVALID_PARAMETER"});return o}});let e={token:t.token,id:t.id,merge:t.merge};t.template?.welcome&&(e.template_welcome=t.template.welcome);let n=await E.bind(this)("openid-logger",e),r=n.logger.split("#"),i=this.service+"-"+r[0],s=r[1];return {userProfile:await $.bind(this)().authenticateUser(i,s,true,true),openid:n.openid}}function Cr(t){let e=typeof globalThis<"u"?globalThis:void 0;if(e?.Buffer)return e.Buffer.from(t,"base64").toString("utf8");if(typeof atob=="function"){let n=atob(t),r=new Uint8Array(n.length);for(let i=0;i<n.length;i++)r[i]=n.charCodeAt(i);return typeof TextDecoder<"u"?new TextDecoder().decode(r):n}throw new Error("No base64 decoder available in this environment")}function Lr(t){let e=t.split(".");if(e.length!==3)throw new Error("Invalid JWT format");let r=e[1].replace(/-/g,"+").replace(/_/g,"/"),i=Cr(r);return JSON.parse(i)}async function mt(t){await this.__authConnection,this.log("loginWithToken:params",t),t=f.Params(t,{idToken:"string",accessToken:"string",refreshToken:"string"},["idToken"]);let e=Lr(t.idToken);if(this.log("loginWithToken:idTokenPayload",e),e["custom:service"]!==this.service)throw new a("Token does not belong to this service.",{code:"INVALID_REQUEST"});let n=Math.floor(Date.now()/1e3);if(e.exp&&e.exp<n)throw new a("Token has expired.",{code:"INVALID_REQUEST"});if(this.__user=fe(e),this.session=null,t.accessToken&&t.refreshToken)try{if(this.session=new amazonCognitoIdentityJs.CognitoUserSession({IdToken:new amazonCognitoIdentityJs.CognitoIdToken({IdToken:t.idToken}),AccessToken:new amazonCognitoIdentityJs.CognitoAccessToken({AccessToken:t.accessToken}),RefreshToken:new amazonCognitoIdentityJs.CognitoRefreshToken({RefreshToken:t.refreshToken})}),this.log("loginWithToken:session",this.session),this.log("loginWithToken:CognitoUser",amazonCognitoIdentityJs.CognitoUser),this.log("loginWithToken:userPool",this.userPool),amazonCognitoIdentityJs.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),L=new amazonCognitoIdentityJs.CognitoUser(r),L.setSignInUserSession(this.session),this.log("loginWithToken:cognitoUserRestored",{cognitoUserType:typeof L,cognitoUserKeys:Object.keys(L||{}),cognitoUser:L});}}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 V(){return await this.__connection,this.__user?.service===this.service?this.__user?.owner===this.host:(await he.bind(this)(),false)}async function te(t=false){let e=null;L&&(t?e=new Promise((r,i)=>{L.globalSignOut({onSuccess:s=>{this.log("globalSignOut:success",s),r(s);},onFailure:s=>{this.log("globalSignOut:error",s),i(s);}});}):L.signOut());let n={session:null,__startKeyHistory:{},__cached_requests:{},__user:null};e&&(e=await e);for(let r in n)this[r]=n[r];return this._runOnUserUpdateListeners(null),this._runOnLoginListeners(null),e}async function he(t){await this.__connection;let{data:e}=U(t);return await te.bind(this)(e?.global),"SUCCESS: The user has been logged out."}async function _t(){if(!this.__request_signup_confirmation)throw new a("Least one login attempt is required.",{code:"INVALID_REQUEST"});return await E.bind(this)("confirm-signup",{username:this.__request_signup_confirmation})}async function bt(t=false){if(typeof t=="string")t=f.Url(t);else if(typeof t!="boolean")throw new a("Argument should be type: <boolean | string>.",{code:"INVALID_REQUEST"});if(!this.__disabledAccount)throw new a("Least one signin attempt of disabled account is required.",{code:"INVALID_REQUEST"});return await E.bind(this)("recover-account",{username:this.__disabledAccount,redirect:t}),"SUCCESS: Recovery e-mail has been sent."}async function je(t){let e=f.Params(t,{username:"string",email:"string",password:"string"},["password"]);if(await this.__authConnection,e.email)try{f.Email(e.email);}catch{e.username=e.email,delete e.email;}if(!e.username&&!e.email)throw new a('Least one of "username" or "email" is required.',{code:"INVALID_PARAMETER"});return await $.bind(this)().authenticateUser(e.username||e.email,e.password)}async function yt(t,e){await this.__authConnection;let n={username:"string",password:c=>f.Password(c),email:c=>f.Email(c),name:"string",address:c=>{if(!c)return "";if(typeof c=="string")return c;if(typeof c=="object")return JSON.stringify(c)},gender:"string",birthdate:c=>c?f.Birthdate(c):"",phone_number:c=>c?f.PhoneNumber(c):"",email_public:["boolean",()=>false],address_public:["boolean",()=>false],gender_public:["boolean",()=>false],birthdate_public:["boolean",()=>false],phone_number_public:["boolean",()=>false],access_group:"number",misc:"string",picture:c=>c?f.Url(c):"",profile:c=>c?f.Url(c):"",family_name:"string",given_name:"string",middle_name:"string",nickname:"string",website:c=>c?f.Url(c):""},r=f.Params(t||{},n,["email","password"]);await he.bind(this)(),e=f.Params(e||{},{email_subscription:c=>{if(typeof c!="boolean")throw new a('"option.email_subscription" should be type: <boolean>.',{code:"INVALID_PARAMETER"});if(!e?.signup_confirmation)throw new a('"option.signup_confirmation" is required for email subscription.',{code:"INVALID_PARAMETER"});return c},signup_confirmation:c=>{let d=c;if(typeof c=="string")d=f.Url(c);else if(typeof c=="boolean")d=c;else throw new a('"option.signup_confirmation" should be type: <string | boolean>.',{code:"INVALID_PARAMETER"});if(d&&!r.email)throw new a('"email" is required for signup confirmation.',{code:"INVALID_PARAMETER"});return d},login:c=>{if(typeof c=="boolean"){if(e.signup_confirmation&&c)throw new a('"login" is not allowed when "option.signup_confirmation" is true.',{code:"INVALID_PARAMETER"});return c}throw new a('"option.login" should be type: boolean.',{code:"INVALID_PARAMETER"})},template:c=>{if(typeof c!="object"||c===null)throw new a('"option.template" should be type: <object>.',{code:"INVALID_PARAMETER"});if(c.signup_confirmation!==void 0){if(typeof c.signup_confirmation!="string"||!c.signup_confirmation)throw new a('"option.template.signup_confirmation" should be a non-empty <string> (template message_id).',{code:"INVALID_PARAMETER"});if(!e?.signup_confirmation)throw new a('"option.signup_confirmation" is required when "option.template.signup_confirmation" is set.',{code:"INVALID_PARAMETER"})}if(c.welcome!==void 0&&(typeof c.welcome!="string"||!c.welcome))throw new a('"option.template.welcome" should be a non-empty <string> (template message_id).',{code:"INVALID_PARAMETER"});return c}});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 a('"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=$.bind(this)().createCognitoUser(r.username||r.email);for(let c of ["email_public","address_public","gender_public","birthdate_public","phone_number_public"])r[c]=r[c]?"1":"0";r.access_group&&(r.access_group=r.access_group.toString());let o=(await E.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,template_confirmation:e?.template?.signup_confirmation||"",template_welcome:e?.template?.welcome||""})).split(":"),l=o.slice(1).join(":"),u=[new amazonCognitoIdentityJs.CognitoUserAttribute({Name:"custom:signup",Value:o[0]}),new amazonCognitoIdentityJs.CognitoUserAttribute({Name:"locale",Value:l.split("#")[1]}),new amazonCognitoIdentityJs.CognitoUserAttribute({Name:"custom:signup_ticket",Value:l})];for(let c in n){let d=["email_public","address_public","gender_public","birthdate_public","phone_number_public","misc","service","owner"];r[c]!==""&&(c==="username"||c==="password"||c==="access_group"||(d.includes(c)?u.push(new amazonCognitoIdentityJs.CognitoUserAttribute({Name:"custom:"+c,Value:r[c]})):u.push(new amazonCognitoIdentityJs.CognitoUserAttribute({Name:c,Value:r[c]}))));}return await $.bind(this)().signup(s.cognitoUsername,r.password,u),r.signup_confirmation?(L=s.cognitoUser,this.__request_signup_confirmation=s.cognitoUsername,"SUCCESS: The account has been created. User's signup confirmation is required."):i?je.bind(this)({email:r.username||r.email,password:r.password}):"SUCCESS: The account has been created."}async function wt(){await this.__connection;let t=await E.bind(this)("remove-account",{disable:this.__user.user_id},{auth:true});return await he.bind(this)(),t}async function Et(t){await this.__connection;let e=f.Params(t,{email:i=>f.Email(i),code:["number","string"],new_password:i=>f.Password(i)},["email","code","new_password"]),n=e.code,r=e.new_password;return typeof n=="number"&&(n=n.toString()),new Promise(async(i,s)=>{$.bind(this)().createCognitoUser(e.email).cognitoUser.confirmPassword(n,r,{onSuccess:l=>{i("SUCCESS: New password has been set.");},onFailure:l=>{s(new a(l?.message||"Failed to reset password.",{code:l?.code||"ERROR",cause:l}));}});})}async function Rt(t,e,n){await this.__connection;let r;if(!L)throw new a("The user has to be logged in.",{code:"INVALID_REQUEST"});if(t==="email"||t==="phone_number"){if(!this.__user.hasOwnProperty(t))throw new a(`No ${t==="email"?"e-mail":"phone number"} to verify`,{code:"INVALID_REQUEST"});if(this.__user?.[`${t}_verified`])return `SUCCESS: "${t}" is verified.`;r=(e?f.Params(e,{code:"string"}):{}).code||"";}else return;let i,s=n?.template?.verification;if(s!==void 0){if(typeof s!="string"||!s)throw new a('"template.verification" should be a non-empty <string> (template message_id).',{code:"INVALID_PARAMETER"});i={template_verification:s};}return new Promise((o,l)=>{let u={onSuccess:c=>{r?$.bind(this)().getSession({refreshToken:true}).then(()=>{this.__user&&(this.__user[t+"_verified"]=true),o(`SUCCESS: "${t}" is verified.`);}).catch(d=>{l(d);}):o("SUCCESS: Verification code has been sent.");},onFailure:c=>{l(new a(c.message||"Failed to request verification code.",{code:c?.code}));}};r?L?.verifyAttribute(t,r,u):(u.inputVerificationCode=null,L?.getAttributeVerificationCode(t,u,i));})}function At(t,e){return Rt.bind(this)("phone_number",t,e)}function It(t,e){return Rt.bind(this)("email",t,e)}async function Tt(t,e){await this.__connection;let n=f.Params(t,{email:s=>f.Email(s)},["email"]),r,i=e?.template?.verification;if(i!==void 0){if(typeof i!="string"||!i)throw new a('"template.verification" should be a non-empty <string> (template message_id).',{code:"INVALID_PARAMETER"});r={template_verification:i};}return new Promise(async(s,o)=>{$.bind(this)().createCognitoUser(n.email).cognitoUser.forgotPassword({onSuccess:u=>{s("SUCCESS: Verification code has been sent.");},onFailure:u=>{let{parsed:c,code:d}=Te(u),g={UserNotFoundException:"NOT_EXISTS",InvalidParameterException:"INVALID_PARAMETER",NotAuthorizedException:"INVALID_REQUEST",LimitExceededException:"REQUEST_EXCEED",TooManyRequestsException:"REQUEST_EXCEED",CodeDeliveryFailureException:"CODE_DELIVERY_FAILURE"}[d]||c.code||d||"ERROR";o(new a(c.message,{code:g,cause:u}));}},r);})}async function Pt(t){if(await this.__connection,!this.session)throw new a("User login is required.",{code:"INVALID_REQUEST"});let e=f.Params(t,{current_password:"string",new_password:"string"});if(!e?.current_password)throw new a('"current_password" is required to change password.',{code:"INVALID_PARAMETER"});if(!e?.new_password)throw new a('"new_password" is required to change password.',{code:"INVALID_PARAMETER"});return f.Password(e.current_password),f.Password(e.new_password),new Promise((n,r)=>{L.changePassword(e.current_password,e.new_password,(i,s)=>{if(i){if(i?.code==="InvalidParameterException")r(new a("Invalid password parameter.",{code:"INVALID_PARAMETER"}));else if(i?.code==="NotAuthorizedException")r(new a("Incorrect password.",{code:"INVALID_REQUEST"}));else if(i?.code==="TooManyRequestsException"||i?.code==="LimitExceededException")r(new a("Too many attempts. Please try again later.",{code:"REQUEST_EXCEED"}));else {let{parsed:o}=Te(i);r(o);}return}n("SUCCESS: Password has been changed.");});})}async function St(t){if(await this.__connection,!this.session)throw new a("User login is required.",{code:"INVALID_REQUEST"});let e=f.Params(t||{},{user_id:i=>f.UserId(i),email:i=>f.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?f.Birthdate(i):"",phone_number:i=>i?f.PhoneNumber(i):"",email_public:"boolean",phone_number_public:"boolean",address_public:"boolean",gender_public:"boolean",birthdate_public:"boolean",misc:"string",picture:i=>i?f.Url(i):"",profile:i=>i?f.Url(i):"",family_name:"string",given_name:"string",middle_name:"string",nickname:"string",website:i=>i?f.Url(i):""});if(e&&typeof e=="object"&&!Object.keys(e).length)return this.user;e.email&&(e.preferred_username=this.service+"-"+q.hash(e.email));let n=[["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 n)if(e[i[0]]&&!this.__user[i[1]])throw new a(`${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 E.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 amazonCognitoIdentityJs.CognitoUserAttribute({Name:s,Value:e[s]}));return await new Promise((s,o)=>{L?.updateAttributes(i,(l,u)=>{l&&o([l?.code||l?.name,l?.message||"Failed to update user settings."]),s(u);});}),await $.bind(this)().getSession({refreshToken:true}),this.user}return this.user}async function kt(t,e){t=U(t).data,t||(t={searchFor:"timestamp",condition:">",value:0},e||(e={}),e.ascending=false),await this.__connection;let n={user_id:i=>Array.isArray(i)?i.map(s=>f.UserId(s)):f.UserId(i),email:"string",phone_number:"string",locale:i=>{if(typeof i!="string"||typeof i=="string"&&i.length>5)throw new a('Value of "locale" should be a country code.',{code:"INVALID_PARAMETER"});return i},name:"string",address:"string",gender:"string",birthdate:i=>f.Birthdate(i),subscribers:"number",timestamp:"number",access_group:"number",approved:"string"},r=["searchFor","value"];if(t=f.Params(t,{searchFor:["user_id","name","email","phone_number","address","gender","birthdate","locale","subscribers","timestamp","access_group","approved"],condition:[">",">=","=","<","<=","gt","gte","eq","lt","lte",()=>"="],value:i=>{let s=n[t.searchFor];if(typeof s=="function")return s(i);if(typeof i!==s)throw new a(`Value does not match the type of "${t.searchFor}" index.`,{code:"INVALID_PARAMETER"});return i},range:i=>{let s=n[t.searchFor];if(typeof s=="function")return s(i);if(typeof i!==s)throw new a(`Range does not match the type of "${t.searchFor}" index.`,{code:"INVALID_PARAMETER"});return i}},r),t?.condition&&t?.condition!=="="&&t.hasOwnProperty("range"))throw new a("Conditions does not apply on range search.",{code:"INVALID_PARAMETER"});if(t.searchFor==="user_id"&&(t.condition!=="="||t.range))throw new a(`Conditions are not allowed on "${t.searchFor}"`,{code:"INVALID_PARAMETER"});if(typeof t?.value=="string"&&!t?.value)throw new a("Value should not be an empty string.",{code:"INVALID_PARAMETER"});if(typeof t?.searchFor=="string"&&!t?.searchFor)throw new a('"searchFor" should not be an empty string.',{code:"INVALID_PARAMETER"});return E.bind(this)("get-users",t,{auth:true,fetchOptions:e})}async function xt(t){await this.__connection;let e=await E.bind(this)("last-verified-email",t,{auth:true});return e.includes("SUCCESS")?(await $.bind(this)().getSession({refreshToken:true}),this.user):e}async function vt(t){return await this.__connection,t=f.Params(t,{username:f.Email,redirect:f.Url},["username"]),await E.bind(this)("request-username-change",t,{auth:true})}var le=null,Nt=typeof SubmitEvent<"u",Mr=typeof HTMLFormElement<"u",me=j(),Be=0;function Ut(t){if(!t)return null;let e=Number(t);if(Number.isFinite(e))return Math.max(0,e*1e3);let n=Date.parse(t);return Number.isNaN(n)?null:Math.max(0,n-Date.now())}function Ke(t,e){return e>0?t/e*100:0}var Dt=t=>{let{auth:e,type:n,endpoints:r,stable:i}=t,s=r[0],o=r[1];if(Be++,n==="admin"){let l=Object.entries(s).filter(([u,c])=>u.includes(e?"_private":"_public")&&u!=="get_users_private"&&u!=="service_public"&&typeof c=="string").map(([,u])=>u);if(!l.length)throw new a("No available admin gateways.",{code:"INVALID_REQUEST"});return l[Be%l.length]}if(n==="record"){let l=Object.entries(o).filter(([u,c])=>u.includes(e?"record_private":"record_public")&&typeof c=="string").map(([,u])=>u);if(!l.length)throw new a("No available record gateways.",{code:"INVALID_REQUEST"});return i?l[0]:l[Be%l.length]}throw new a("Invalid gateway type.",{code:"INVALID_REQUEST"})};async function Fr(t,e,n){let r=await Promise.all([this.admin_endpoint,this.record_endpoint]),i=r[0],s=r[1],o=t.split("?"),l=o.length>1?"?"+o[1]:"";switch(t=o[0],t){case "get-users":return i.get_users_private+t+l;case "service":return i.service_public+t+l;case "get-newsletters":case "get-public-newsletters":case "subscribe-newsletter":case "subscribe-public-newsletter":case "signupkey":case "admin-newsletter-request":case "admin-signup":case "confirm-signup":case "openid-logger":case "block-account":case "admin-edit-profile":case "remove-account":case "post-secure":case "recover-account":case "mock":case "grant-access":case "last-verified-email":case "ticket":case "register-ticket":case "get-newsletter-subscription":case "request-username-change":case "send-inquiry":case "register-newsletter-group":case "newsletter-group-endpoint":case "invitation-list":case "csr":case "csr-poll":case "csr-cancel":return Dt.bind(this)({auth:e,type:"admin",endpoints:r})+t+l;case "post-record":return (e?s.post_private:s.post_public)+t+l;case "get-records":return (e?s.get_private:s.get_public)+t+l;case "del-files":case "del-records":return s.del_private+t+l;case "store-subscription":case "get-vapid-public-key":case "push-notification":case "delete-subscription":case "subscription":case "get-subscription":case "get-table":case "get-tag":case "get-uniqueid":case "get-index":case "get-signed-url":case "extract-file-text":case "grant-private-access":case "request-private-access-key":case "get-ws-group":case "check-schema":case "get-feed":case "castspell":case "dopamine":case "getspell":return Dt.bind(this)({auth:e,type:"record",endpoints:r,stable:n})+t+l;default:return f.Url(t)+l}}var pe={};function Ct(){le&&(le.terminate(),le=null);}async function E(t,e=null,n,r){this.log("request",{url:t,data:e,options:n,_etc:r||{}}),n=n||{};let{auth:i=false,method:s="post",bypassAwaitConnection:o=false}=n;s=s.toUpperCase();let l=null,u=e?.service||this.service,c=e?.owner||this.owner,d=null,g=await Fr.bind(this)(t,!!i,!!n.stableGateway);if(!o&&(l=await this.__connection,!l))throw new a("Invalid connection. The service could have been disabled, or has a restricted CORS.",{code:"INVALID_REQUEST"});let h=n?.tokenHeaders?.idToken===true;(i||h)&&(d=await ce.bind(this)());let _={},{fetchMore:p=false,progress:y}=n?.fetchOptions||{};if(n?.fetchOptions&&Object.keys(n.fetchOptions).length){for(let k of ["limit","startKey","ascending"])if(n.fetchOptions.hasOwnProperty(k)){if(k==="startKey"&&n.fetchOptions[k]===null)continue;_[k]=n.fetchOptions[k];}_=f.Params(_,{limit:k=>{if(typeof k!="number")throw new a("Fetch limit should be a number.",{code:"INVALID_REQUEST"});if(k>1e3)throw new a("Fetch limit should be below 1000.",{code:"INVALID_REQUEST"});return k},startKey:k=>k,ascending:"boolean"});}let P=r?.ignoreService?{}:{service:u,owner:c};Object.assign(P,_),e=U(e).data,e?e&&typeof e=="object"&&(e=Object.assign(P,e)):e=P;let m=`${s}:${i?"auth":"public"}:${t}`,T=(()=>{if(e&&typeof e=="object"&&Object.keys(e).length&&!(me&&e instanceof FormData)){let k=function(D){return typeof D=="object"&&D!==null?Object.keys(D).sort().reduce((N,O)=>(typeof D[O]=="object"&&D[O]!==null?N[O]=k(D[O]):N[O]=D[O],N),{}):D};return q.hash(m+"/"+JSON.stringify(k(e)))}return q.hash(m+"/"+u)})(),{requestKey:x,requestKeyWithStartKey:I}=qr.bind(this)({params:e,url:t,fetchMore:p,hashedParams:T});if(!x||x&&typeof x=="object")return x;if(this.log("requestKey",I),typeof I=="string"&&pe[I]instanceof Promise)return this.log("request:returning pending",I),pe[I];let v={Accept:"*/*"};if(Object.prototype.hasOwnProperty.call(n,"contentType")&&n.contentType!==void 0){let k=n.contentType===null?"application/x-www-form-urlencoded":n.contentType;k&&(v["Content-Type"]=k);}else v["Content-Type"]="application/json";if(d&&(v.Authorization=d),n?.tokenHeaders){let k=(O,er)=>typeof O=="string"?O:O===true?er:null,D=k(n.tokenHeaders.accessToken,this.session?.accessToken?.jwtToken||null),N=k(n.tokenHeaders.idToken,this.bearerToken||this.session?.idToken?.jwtToken||d||null);D&&(v["X-Access-Token"]=D),N&&(v["X-Id-Token"]=N);}let W={public_identifier:this.__public_identifier,service:u,owner:c};v["Content-Meta"]=JSON.stringify(W),n.revalidate&&(v["Cache-Control"]="no-cache",v.Pragma="no-cache");let M={headers:v};if(n?.responseType&&(M.responseType=n.responseType),s==="GET"){if(e){let k=[];if(me&&e instanceof FormData?k=Array.from(e.entries()).map(([D,N])=>{let O=typeof N=="string"?N:N.name;return encodeURIComponent(D)+"="+encodeURIComponent(O)}):k=Object.keys(e).map(D=>{let N=e[D];return typeof N!="string"&&(N=JSON.stringify(N)),encodeURIComponent(D)+"="+encodeURIComponent(N)}),k.length){let D=g.includes("?")?g.endsWith("?")||g.endsWith("&")?"":"&":"?";g+=D+k.join("&");}}M.body=null;}else if(me&&e instanceof FormData)M.body=e;else if(v["Content-Type"]==="application/x-www-form-urlencoded"&&e&&typeof e=="object"){let k=new URLSearchParams;for(let D of Object.keys(e)){let N=e[D];k.append(D,typeof N=="string"?N:JSON.stringify(N));}M.body=k.toString();}else typeof e=="string"?M.body=e:M.body=e?JSON.stringify(e):null;if(M.method=s,le===null){let k={batchSize:this.requestBatchSize,breakWhenError:false,onProgress:D=>{this.onBatchProcess.forEach(N=>N(D));}};le=new mn__default.default(k);}return this.log("request-opt",M),new Promise((k,D)=>{le.add([async()=>{let N=Lt.bind(this)(g,M,y);pe[I]=N;try{let O=Vr.bind(this)({hashedParam:x,requestKeyWithStartKey:I,url:t,fetched:await N});return delete pe[I],this.log("request:end",O),k(O),O}catch(O){throw delete pe[I],this.log("request:err",O),D(O),O}}]);})}function qr(t){let{params:e={},url:n,fetchMore:r=false,hashedParams:i}=t||{};if(e.startKey){if(!(typeof e.startKey=="object"&&Object.keys(e.startKey).length)&&e.startKey!=="start"&&e.startKey!=="end")throw new a(`"${e.startKey}" is invalid startKey key.`,{code:"INVALID_PARAMETER"});e.startKey==="start"&&(r=false,delete e.startKey);}if(!r){if(this.__cached_requests?.[n]?.[i]&&delete this.__cached_requests[n][i],this.__startKeyHistory?.[n]?.[i]){if(Array.isArray(this.__startKeyHistory[n][i])&&this.__startKeyHistory[n][i].length)for(let u of this.__startKeyHistory[n][i]){let c=i+q.hash(u);this.__cached_requests?.[n]&&this.__cached_requests?.[n]?.[c]&&delete this.__cached_requests[n][c];}delete this.__startKeyHistory[n][i];}return {requestKeyWithStartKey:i,requestKey:i}}if(!Array.isArray(this.__startKeyHistory?.[n]?.[i]))return {requestKeyWithStartKey:i,requestKey:i};let s=this.__startKeyHistory[n][i],o=s[s.length-1],l=i;if(o){if(o==="end")return {requestKey:{list:[],startKey:"end",endOfList:true,startKeyHistory:s},requestKeyWithStartKey:l};l+=q.hash(o),e.startKey=JSON.parse(o);}return this.__cached_requests?.[n]?.[l]?{requestKey:this.__cached_requests[n][l],requestKeyWithStartKey:l}:{requestKeyWithStartKey:l,requestKey:i}}function Lt(t,e,n){return new Promise((r,i)=>{let s=new XMLHttpRequest;s.open(e.method||"GET",t);for(var o in e.headers||{})s.setRequestHeader(o,e.headers[o]);e.responseType&&(s.responseType=e.responseType),s.onload=()=>{if(s.status<400)if(e.responseType=="json"||e.responseType=="blob")r(s.response);else {let l=s.responseText;try{l=JSON.parse(l);}catch{}r(l);}else if(s.status===429){let l=s.getResponseHeader("Retry-After"),u=Ut(l);u!==null?setTimeout(()=>{Lt(t,e,n).then(r,i);},u):i("Too many requests");}else {let l=s.status,u=["INVALID_CORS","INVALID_REQUEST","SERVICE_DISABLED","INVALID_PARAMETER","ERROR","EXISTS","NOT_EXISTS"],c=e.responseType=="blob"?s.response:s.responseText;try{c=JSON.parse(c);}catch{}if(typeof c=="string"){let d=c.split(":"),g=d.splice(0,1)[0].trim(),h=d.join(":").trim();i(new a(h||c,{code:u.includes(g)?g:"ERROR"}));}else if(typeof c=="object"&&c?.message){let d=c?.code||(l?l.toString():null)||"ERROR",g=c.message,h=c?.cause;typeof g=="string"&&(g=g.trim()),i(new a(g,{cause:h,code:d}));}else i(c);}},s.onerror=()=>i("Network error"),s.onabort=()=>i("Aborted"),s.ontimeout=()=>i("Timeout"),typeof n=="function"&&(s.onprogress=l=>{n({status:"download",progress:Ke(l.loaded,l.total),loaded:l.loaded,total:l.total,abort:()=>s.abort()});},s.upload&&(s.upload.onprogress=l=>{n({status:"upload",progress:Ke(l.loaded,l.total),loaded:l.loaded,total:l.total,abort:()=>s.abort()});})),s.send(e.body);})}function Vr(t){let{hashedParam:e,requestKeyWithStartKey:n,url:r,fetched:i}=t;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][n]=i,Object.assign({startKeyHistory:this.__startKeyHistory[r][e]},i)}async function Se(t,e){await this.__connection;let{record_id:n,service:r=this.service,progress:i}=e;if(!n)throw new a('"record_id" is required.',{code:"INVALID_PARAMETER"});if(Nt&&t instanceof SubmitEvent&&(t=t.target),Mr&&t instanceof HTMLFormElement&&(t=new FormData(t)),!me||!(t instanceof FormData))throw new a('"fileList" should be a FormData or HTMLFormElement.',{code:"INVALID_PARAMETER"});let o={reserved_key:ie(),service:r,request:"post"};e?.record_id&&(o.id=e.record_id);let l,u=(_,p,y)=>new Promise((P,m)=>{l=new XMLHttpRequest,l.open("POST",_),l.onload=()=>{let T=l.responseText;try{T=JSON.parse(T);}catch{}if(l.status>=200&&l.status<300)P(T);else if(l.status===429){let x=l.getResponseHeader("Retry-After"),I=Ut(x);I!==null?setTimeout(()=>{u(_,p,y).then(P,m);},I):m("Too many requests");}else m(T);},l.onerror=()=>m("Network error"),l.onabort=()=>m("Aborted"),l.ontimeout=()=>m("Timeout"),l.upload&&typeof y=="function"&&(l.upload.onprogress=y),l.send(p);});function c(_){let p="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";if(_===0)return p[0];let y="";for(;_>0;)y=p[_%62]+y,_=Math.floor(_/62);return y}let d=[],g=[],h=[];for(let[_,p]of t.entries()){if(!(p instanceof File))continue;let y=Object.assign({key:_+"/"+p.name,sizeKey:c(p.size),contentType:p.type||null},o),{fields:P=null,url:m,cdn:T}=await E.bind(this)("get-signed-url",y,{auth:!!this.__user});h.push(T);let x=new FormData;for(let I in P)x.append(I,P[I]);x.append("file",p);try{await u(m,x,typeof i=="function"?I=>i({status:"upload",progress:Ke(I.loaded,I.total),currentFile:p,completed:d,failed:g,loaded:I.loaded,total:I.total,abort:()=>l.abort()}):null),d.push(p);}catch{g.push(p);}}return {completed:d,failed:g,bin_endpoints:h}}var Pe={};function A(t){let{preventMultipleCalls:e=false}=t||{};return function(n,r,i){let s=i.value;i.value=function(...o){let l=o[0],u=true,c=null,d="",g={},h=false;if(Nt&&l instanceof SubmitEvent){l.preventDefault();let m=window.location.href;c=l.target;let T=new URL(c.action);d=T.href;let x=d?d.match(/(?<=\{).*?(?=\})/g):"";if(x)for(let I of x){if(!I)continue;let v=c.querySelector(`[name="${I}"]`);if(v)if(v.type==="file")for(let C=0;C<=v.files.length-1;C++)v.files[C]&&(g[I]||(g[I]=[]),g[I].push(new Promise((W,M)=>{let k=new FileReader;k.onload=function(){W(k.result);},k.readAsDataURL(v.files[C]),k.onerror=M;})));else d=d.replace(`{${I}}`,v.value);}c.getAttribute("action")===null?u=false:h=T.href===m;}let _=async m=>{if(d)for(let T in g)g[T].length&&(d=d.replace(`{${T}}`,(await Promise.all(g[T])).join(",")));return c&&u&&(window.sessionStorage.setItem(`${this.service}:${q.hash(d)}`,JSON.stringify(m)),h?window.location.replace(d):window.location.href=d),m},p,y=m=>{throw m instanceof a?m.name=r+"()":m=m instanceof Error?m:new a(m,{name:r+"()"}),m},P=async()=>{try{if(p=s.bind(this)(...o),p instanceof Promise){let m=await p;return _(m)}return _(p)}catch(m){throw y(m)}};if(e){let m=`${r}:${this?.__public_identifier||""}:${this?.service||""}:${this?.owner||""}`;return Pe?.[m]||(Pe[m]=P().finally(()=>{delete Pe[m];})),Pe[m]}return P()};}}async function Ot(){await this.__connection;let t=`${this.service}:${q.hash(window.location.href.split("?")[0])}`,e=window.sessionStorage.getItem(t);if(window.sessionStorage.removeItem(t),e!==null){try{e=JSON.parse(e);}catch{}return e}return null}var $r=256,jr=256,Br=256,Mt=256,Kr="\u{10FFFF}",Qr=/[\u0000-\u001F\u007F]|\u{10FFFF}/u,Hr={"/":"%2F","!":"%21","*":"%2A","#":"%23"},Wr={"%2F":"/","%21":"!","%2A":"*","%23":"#"};function zr(t){return t.replace(/%/g,"%25").replace(/[\/!*#]/g,n=>Hr[n]||n)}function K(t){return typeof t!="string"?t:t.replace(/%(2F|21|2A|23)/gi,n=>{let r=n.toUpperCase();return Wr[r]||n}).replace(/%25/gi,"%")}function z(t,e,n={}){let{allowEmpty:r=false,maxLength:i,blockKeyDelimiters:s=false,disallowLeadingDollar:o=false,onlyAlphanumeric:l=false}=n;if(typeof t!="string")throw new a(`"${e}" should be type: <string>.`,{code:"INVALID_PARAMETER"});if(l&&/[^a-zA-Z0-9]/.test(t))throw new a(`"${e}" should only contain alphanumeric characters.`,{code:"INVALID_PARAMETER"});if(!r&&t.length===0)throw new a(`"${e}" is required.`,{code:"INVALID_PARAMETER"});if(i&&t.length>i)throw new a(`"${e}" should be <= ${i} characters.`,{code:"INVALID_PARAMETER"});if(Qr.test(t)||t.includes(Kr))throw new a(`"${e}" cannot include control characters or unsupported sentinel characters.`,{code:"INVALID_PARAMETER"});if(s&&(t=zr(t),i&&t.length>i))throw new a(`"${e}" should be <= ${i} characters. "/", "!", "*", "#" and "%" count as 3 characters each.`,{code:"INVALID_PARAMETER"});if(o&&t.startsWith("$"))throw new a(`"${e}" cannot start with "$".`,{code:"INVALID_PARAMETER"});return t}function ue(t,e="table.name",n={}){return z(t,e,{allowEmpty:n.allowEmpty===true,maxLength:$r,blockKeyDelimiters:true})}function xe(t,e="tag",n={}){return z(t,e,{allowEmpty:n.allowEmpty===true,maxLength:jr,blockKeyDelimiters:true})}function _e(t,e="index.name",n={}){return z(t,e,{allowEmpty:n.allowEmpty===true,maxLength:Br,blockKeyDelimiters:true,disallowLeadingDollar:true})}function Ft(t,e="index.value"){return z(t,e,{allowEmpty:true,maxLength:Mt})}function Qe(t){return typeof t=="string"&&t.slice(-1)==="."}function He(t,e){return z(t,e,{allowEmpty:true,maxLength:Mt,blockKeyDelimiters:true})}function qt(t){if(!t.record_id&&!t.unique_id)return null;let e={};return t?.service&&(e.service=t.service),t?.owner&&(e.owner=t.owner),t?.record_id?e.record_id=z(t.record_id,"record_id",{allowEmpty:false,onlyAlphanumeric:true}):t?.unique_id&&(e.unique_id=t.unique_id),e}function We(t){if(t===void 0)return 0;if(typeof t=="number"){if(t>99||t<0)throw new a('"table.access_group" value should be within a range of 0 ~ 99.',{code:"INVALID_REQUEST"})}else if(typeof t=="string"){if(t={private:"private",public:0,authorized:1,admin:99}[t],t===void 0)throw new a('"table.access_group" is invalid.',{code:"INVALID_PARAMETER"})}else throw new a('"table.access_group" should be type: <number | string>.',{code:"INVALID_PARAMETER"});if(!this.__user&&t)throw new a("Unsigned users have no access to records with access group.",{code:"INVALID_REQUEST"});return t}var ke=4503599627370496;function ve(t){if(typeof t=="number"){if(t>ke||t<-ke)throw new a(`Number value should be within range -${ke} ~ +${ke}`,{code:"INVALID_PARAMETER"});return t}if(typeof t=="boolean")return t;if(typeof t=="string")return Ft(t,"index.value");throw new a('"index.value" should be type: <number | boolean | string>.',{code:"INVALID_PARAMETER"})}function Vt(t,e){if(!e.index||!("value"in e.index))throw new a('"index.value" is required.',{code:"INVALID_PARAMETER"});if(e.index.name==="$record_id")throw new a(`Cannot do "index.range" on ${e.index.name}`,{code:"INVALID_PARAMETER"});if(typeof e.index.value!=typeof t)throw new a('"index.range" type should match the type of "index.value".',{code:"INVALID_PARAMETER"});return typeof t=="string"?Qe(e.index.name)?He(t,"index.range"):Ft(t,"index.range"):t}var De={},Jr=10080*60,Gr=3600,$t=2;function Xr(t,e){if(!e)return String($t);let n=Math.max(60,t-300)*1e3;return $t+"."+Math.floor(Date.now()/n)}function Zr(t){if(!this.user?.user_id)return false;let e=t[6]==="**"?"**":parseInt(t[6]),n=this.user?.access_group??-1;return !(this.user.user_id!==t[3]&&(e==="**"||n<e))}async function Yr(t){return typeof t=="string"?t:t&&typeof t.text=="function"?await t.text():await new Promise((e,n)=>{try{let r=new FileReader;r.onload=()=>e(r.result),r.onerror=()=>n(r.error||new Error("Failed to read blob")),r.readAsText(t);}catch(r){n(r);}})}async function de(t,e,n=false){let r={user_id:"",record_id:"",updated:0,uploaded:0,readonly:false,table:{name:"",access_group:0,subscription:{is_subscription_record:false,upload_to_feed:false,notify_subscribers:false,feed_referencing_records:false,notify_referencing_records:false}},referenced_count:0,source:{referencing_limit:null,prevent_multiple_referencing:false,can_remove_referencing_records:false,only_granted_can_reference:false},ip:"",bin:{}},i=false,s=[];function o(c){let d=c=="**"?"private":parseInt(c);return d=d==0?"public":d==1?"authorized":d==99?"admin":d,d}let l={ip:c=>{let d=c.split("#"),g=d[0];d.length>1&&(r.unique_id=d.slice(1).join("#")),g.slice(-1)==="R"?(r.readonly=true,g=g.slice(0,-1)):r.readonly=false,/^\d{1,3}-\d{1,3}-\d{1,3}-\d{1,3}$/.test(g)&&(g=g.split("-").join("."),i=true),r.ip=g;},rec:c=>{if(!c)return;r.record_id=c;let d=c.substring(0,c.length-9),g=B(d);r.uploaded=g;},usr:c=>{r.user_id=c;},tbl:c=>{if(c&&!r.table.name){let d=c.split("/");r.table.name=K(d[0]),r.table.access_group=o(d[2]),d?.[3]&&(r.table.subscription.is_subscription_record=true);}},usr_tbl:c=>{let d=c.split("/");r.user_id||(r.user_id=d[0]),r.table.name||(r.table.name=K(d[1]),r.table.access_group=o(d[3]),d?.[4]&&(r.table.subscription.is_subscription_record=true));},idx:c=>{if(!c)return;let d=c.split("!"),g=K(d.splice(0,1)[0]),h=ei("!"+d.join("!"));r.index={name:g,value:h};},ref:c=>{c&&(r.reference=c.split("/")[0]);},tags:c=>{r.tags=Array.isArray(c)?c.map(d=>K(d)):c;},upd:c=>{r.updated=c;},acpt_mrf:c=>{r.source.prevent_multiple_referencing=!c;},ref_limt:c=>{r.source.referencing_limit=c;},rfd:c=>{r.referenced_count=c;},bin:async c=>{let d={},g=r?.reference||null;if(Array.isArray(c)){let h=await Promise.all(c.map(async _=>{try{let p=_.split("/").slice(3).join("/"),y=p.split("/");if(y.length<12)return null;let P=y[y.length-1],m=y[10];if(m==="__data__"&&P==="__json__.json")return {isDataFile:!0,rawUrl:_};let T=y[9],x=y[8],I=o(y[6]),v=_,C=I!=="public"&&Zr.call(this,y)?{expires:Gr,browserCache:Jr}:null;if(I!=="public")try{v=await se.bind(this)(_,{dataType:"endpoint",_ref:g});}catch(M){console.error("Error getting signed url for private file:",M),v=_;}let W={access_group:I,filename:P,url:v,path:p,size:B(T),uploaded:B(x),getFile:(M,k)=>{let D={dataType:M||"download",progress:k,_ref:g},N=()=>se.bind(this)(v,Object.assign({},D,{_update:W}));return C?se.bind(this)(_,Object.assign({},D,C)).catch(()=>N()):N()}};return {pathKey:m,obj:W}}catch{return null}}));for(let _ of h)if(_&&!_.isDataFile){if(d[_.pathKey]){d[_.pathKey].push(_.obj);continue}d[_.pathKey]=[_.obj];}}r.bin=d;},prv_acs:c=>{for(let d in c)["notify_subscribers","upload_to_feed","feed_referencing_records","notify_referencing_records"].includes(d)?r.table.subscription[d]=c[d]:d==="referencing_index_restrictions"&&Array.isArray(c[d])?r.source[d]=c[d].map(h=>h&&typeof h=="object"&&typeof h.name=="string"?Object.assign({},h,{name:K(h.name)}):h):r.source[d]=c[d];},data:async c=>{if(c==="!D%{}"){r.data={};return}if(c==="!L%[]"){r.data=[];return}if(c&&typeof c=="object"&&!Array.isArray(c)&&typeof c.__data__=="string"&&Object.keys(c).length===1&&c.__data__.endsWith("/__data__/__json__.json")){let d=c.__data__,g=s.find(h=>h.endsWith(d))||null;if(g){if(n){r.data=c;return}try{let h=await se.bind(this)(g,{dataType:"blob",_ref:r.reference||null}),_=await Yr(h);r.data=JSON.parse(_);}catch(h){console.error("Failed to fetch offloaded record data:",h),r.data=null;}return}}r.data=c;}};if(t.record_id)return t;if(Array.isArray(t.bin))for(let c of t.bin)try{if(typeof c!="string")continue;let d=c.split("/").slice(3);d.length>=12&&d[10]==="__data__"&&d[d.length-1]==="__json__.json"&&s.push(c);}catch{}let u=[];for(let c in l)if(t.hasOwnProperty(c)){let d=l[c](t[c]);d instanceof Promise&&u.push(d);}return i&&(r.user_id="anonymous:"+r.user_id),await Promise.all(u),r}function ei(t){let e=t.substring(3);switch(t.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 a("Value parse error.",{code:"PARSE_ERROR"})}default:return t}}async function jt(t){let{endpoints:e}=t;if(typeof e=="string"&&(e=[e]),!Array.isArray(e))throw new a('"endpoints" should be type: array | string.',{code:"INVALID_PARAMETER"});let n=await E.bind(this)("del-files",{endpoints:e,storage:"records"},{auth:true,method:"post"}),r=[];for(let i in n)r.push(de.bind(this)(n[i]));return Promise.all(r)}async function se(t,e){if(typeof t!="string")throw new a('"url" should be type: string.',{code:"INVALID_PARAMETER"});let n=t,r=t.split("?"),i=r.shift()||"",s=r.length?"?"+r.join("?"):"",o=f.Url(i);t=o+s;let l=false,u=o.split("/"),d=u[2].split("."),g=null;d.length===3&&d[1]==="skapi"&&(g=d[0],l=true);let h=u.slice(3),_=false;if(!l&&(h[0]==="auth"||h[0]==="publ"))try{f.UserId(h[2]),f.UserId(h[3]),_=h[0]=="auth",l=!0;}catch{throw new a("Invalid file url.",{code:"INVALID_PARAMETER"})}let p=g?null:h[1];if(e=f.Params(e,{expires:["number",()=>0],browserCache:["number",()=>0],refresh:["boolean",()=>false],dataType:["base64","blob","endpoint","text","info",()=>"download"],progress:["function","undefined",null],_ref:[null,"string"],_update:T=>T}),e?.dataType==="info")return {url:t,filename:h[h.length-1],fileKey:h[h.length-2],access_group:h[6]==="**"?"private":h[6]==="01"?"authorized":h[6]==="00"?"public":parseInt(h[6]),uploader:h[3],record_id:h[4]==="records"?h[5]:"N/A",filesize:B(h[9]),uploaded:B(h[8])};let y=t.split("/").slice(-1)[0],P=e.expires;if(P){if(!l)throw new a("Expires option can only be used on skapi cdn endpoints.",{code:"INVALID_PARAMETER"});if(P<0)throw new a('"config.expires" should be > 0. (seconds)',{code:"INVALID_PARAMETER"});let T={request:g?"get-host":"get",id:g||h[5],key:n.split("?")[0],expires:P};p&&(T.service=p);let x=e.browserCache,I={auth:true};if(x){if(x<0)throw new a('"config.browserCache" should be > 0. (seconds)',{code:"INVALID_PARAMETER"});I.method="get",I.stableGateway=true,T.browser_cache=x;let v=this.session?.idToken?.payload?.sub||this.user?.user_id;v&&(T.uid=v),T.nocache=Xr(P,e.refresh);}t=(await E.bind(this)("get-signed-url",T,I)).url;}else if(_){let T=Math.floor(Date.now()/1e3);if(!this.bearerToken&&(!this.session?.idToken?.payload?.exp||this.session.idToken.payload.exp<T)){this.log("getFile:requesting new token",null);try{await $.bind(this)().getSession({refreshToken:!0}),this.log("getFile:received new tokens",{exp:this.session?.idToken?.payload?.exp,currTime:T,expiresIn:this.session?.idToken?.payload?.exp-T,token:this.session?.accessToken?.jwtToken,refreshToken:this.session?.refreshToken?.token});}catch(C){throw this.log("getFile:new token error",C),new a("User login is required.",{code:"INVALID_REQUEST"})}}let x=this.bearerToken||this.session?.idToken?.jwtToken;if(!x||!this.user?.user_id)throw new a("User login is required.",{code:"INVALID_REQUEST"});t+=`${t.includes("?")?"&":"?"}t=${encodeURIComponent(x)}`;let I=h[6]==="**"?"**":parseInt(h[6]),v=this.user?.access_group??-1;if(this.user.user_id!==h[3]&&(I==="**"||v<I)){let C=h[5];if(this.__private_access_key[C]&&typeof this.__private_access_key[C]=="string")t+=`&p=${encodeURIComponent(this.__private_access_key[C])}`;else if(this.owner!==this.host)try{let W=await this.requestPrivateRecordAccessKey({record_id:C,reference_id:e?._ref});t+=`&p=${encodeURIComponent(W)}`;}catch{}}}if(e?.dataType==="endpoint")return e._update&&(e._update.url=t),t;if(e?.dataType==="download"){let T=document.createElement("a");return T.href=t,document.body.appendChild(T),T.setAttribute("download",y),T.target="_blank",T.click(),document.body.removeChild(T),null}return new Promise(async(T,x)=>{try{let I=await E.bind(this)(t,null,{method:"get",contentType:null,responseType:e?.dataType==="text"?"text":"blob",fetchOptions:{progress:e?.progress}},{ignoreService:!0});if(e?.dataType==="base64"){let v=new FileReader;v.onloadend=()=>T(v.result),v.readAsDataURL(I);}else T(I);}catch(I){if(e?.browserCache&&!e?.refresh)try{T(await se.bind(this)(n,Object.assign({},e,{refresh:!0})));return}catch(v){x(v);return}x(I);}})}function Ne(t,e){return `${t||this.service}/${e||this.owner}`}function ze(t,e){let n=this.__my_unique_ids[t];return n?n[e]:void 0}function Bt(t,e,n){this.__my_unique_ids[t]||(this.__my_unique_ids[t]={}),this.__my_unique_ids[t][e]=n;}function ti(t,e){this.__my_unique_ids[t]&&delete this.__my_unique_ids[t][e];}async function Kt(t,e=false){t=U(t,{ignoreEmpty:true}).data||{};let n=Ne.bind(this)(t?.service,t?.owner),r="",i=qt(t);if(i){if(t=i,r=t.record_id||t.unique_id,typeof r=="string"){typeof this.__private_access_key?.[r]=="string"&&(t.private_key=this.__private_access_key?.[r]||void 0);let s=ze.bind(this)(n,r);s&&(e?ti.bind(this)(n,r):t.record_id=s);}}else {let s=await V.bind(this)(),o=t?.reference,l=false;typeof o=="object"&&Object.keys(o).length&&(o?.record_id||o?.unique_id?(r=o.record_id||o.unique_id,r&&typeof this.__private_access_key?.[r]=="string"&&(t.private_key=this.__private_access_key?.[r]||void 0),t.reference=r):o?.user_id&&(l=o.user_id===this.user?.user_id,t.reference=o.user_id)),typeof t?.table=="string"&&(t.table={name:t.table,access_group:0}),t.index&&t.index.hasOwnProperty("range")&&t.index.hasOwnProperty("condition")&&delete t.index.range;let u=c=>({table:{name:d=>ue(d,"table.name"),access_group:We.bind(this),subscription:d=>f.UserId(d,'User ID in "subscription"')},reference:"string",index:{name:["$updated","$uploaded","$referenced_count","$user_id",d=>_e(d,"index.name")],value:d=>{let g={$updated:"number",$uploaded:"number",$referenced_count:"number",$user_id:f.UserId};if(g.hasOwnProperty(c.index.name)){let h=g[c.index.name];if(typeof h=="function")return h(d);if(h!==typeof d)throw new a(`"index.value" should be type: ${h}.`,{code:"INVALID_PARAMETER"});return d}return typeof d=="string"&&!d?"":typeof d=="string"&&Qe(c.index.name)?He(d,"index.value"):ve(d)},condition:["gt","gte","lt","lte",">",">=","<","<=","=","eq"],range:d=>Vt(d,c)},tag:d=>{if(d==null)return d;if(typeof d=="string")return xe(d,"tag");throw new a('"tag" should be type: string.',{code:"INVALID_PARAMETER"})},private_key:"string"});t=f.Params(t||{},u(t),l||s?[]:["table"],{ignoreEmpty:true});}return {query:t,is_reference_fetch:r}}async function Qt(t,e){await this.__connection;let n=await Kt.bind(this)(t),r=n.is_reference_fetch,i=await E.bind(this)("get-records",n.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(de.bind(this)(i.list[o]));return i.list=await Promise.all(s),i}function Ht(t){let e="",n=[],r=Ne.bind(this)(t?.service,t?.owner),i=f.Params(t||{},{record_id:o=>{let l=typeof o=="string"?ze.bind(this)(r,o):void 0;return l||z(o,"record_id",{allowEmpty:false})},unique_id:["string",null],readonly:"boolean",table:{name:o=>ue(o,"table.name"),subscription:[null,{is_subscription_record:"boolean",upload_to_feed:"boolean",notify_subscribers:"boolean",feed_referencing_records:"boolean",notify_referencing_records:"boolean"}],access_group:We.bind(this)},source:{referencing_limit:o=>{if(o===null)return null;if(typeof o=="number"){if(0>o)throw new a('"reference_limit" should be >= 0',{code:"INVALID_PARAMETER"});if(o>4503599627370546)throw new a('"reference_limit" should be <= 4503599627370546',{code:"INVALID_PARAMETER"});return o}throw new a('"reference_limit" should be type: <number | null>',{code:"INVALID_PARAMETER"})},prevent_multiple_referencing:"boolean",can_remove_referencing_records:"boolean",only_granted_can_reference:"boolean",allow_granted_to_grant_others:"boolean",referencing_index_restrictions:o=>{if(o===void 0)return;if(!o||Array.isArray(o)&&!o.length)return null;let l={name:c=>_e(c,'"name" in "index_restrictions"'),value:c=>ve(c),condition:["gt","gte","lt","lte",">",">=","<","<=","=","eq","!=","ne",()=>null],range:c=>{if(c!==null&&typeof o.value!=typeof c)throw new a('Index restriction "range" type should match the type of "value".',{code:"INVALID_PARAMETER"});if(!o.hasOwnProperty("value"))throw new a('Index restriction "value" is required.',{code:"INVALID_PARAMETER"});return c}};Array.isArray(o)||(o=[o]);let u=o.map(c=>f.Params(c,l,["name"]));if(u.length)for(let c of u)c.condition&&c.hasOwnProperty("range")&&delete c.range;return u}},reference:o=>{if(o===null)return {record_id:null};if(o){if(typeof o=="string"){e=o;let l=ze.bind(this)(r,o);return l||o}if(typeof o!="object")throw new a('"reference" should be type: <string | object>.',{code:"INVALID_PARAMETER"});return f.Params(o,{unique_id:"string",record_id:l=>l==null?l:(e=l,typeof this.__private_access_key?.[l]=="string"&&(t.reference_private_key=this.__private_access_key[l]||void 0),z(l,"reference.record_id",{allowEmpty:false,onlyAlphanumeric:true}))})}},index:[null,{name:o=>_e(o,"index.name"),value:o=>ve(o)}],tags:o=>{if(o==null)return o;if(typeof o=="string"&&(o=o.split(",").map(l=>l.trim())),!Array.isArray(o))throw new a('"tag" should be type: <string | string[]>.',{code:"INVALID_PARAMETER"});return o.map(l=>xe(l,"tag"))},remove_bin:o=>{if(!o)return null;let l=[];if(Array.isArray(o))for(let u of o)if(typeof u=="string")l.push(u.split("?")[0]);else if(u.url&&u.size&&u.filename){let d=u.url.split("/").slice(0,3).join("/")+"/"+u.path;l.push(d);}else throw new a('"remove_bin" should be type: <string[] | BinaryFile[] | null>',{code:"INVALID_PARAMETER"});else throw new a('"remove_bin" should be type: <string[] | BinaryFile[] | null>',{code:"INVALID_PARAMETER"});return l},progress:"function",data:o=>o},[],{precall:o=>{let l=o?.data||{};if(!l?.record_id&&!l.table)throw new a('"table.name" is required.',{code:"INVALID_PARAMETER"});typeof l.table=="string"&&(l.table={name:l.table,access_group:0}),o.files&&(n=o.files);}}),s=t.progress||null;if(delete i.progress,!this.__user){let o=!!(i.table?.subscription?.is_subscription_record||i.table?.subscription?.upload_to_feed||i.table?.subscription?.notify_subscribers||i.table?.subscription?.feed_referencing_records||i.table?.subscription?.notify_referencing_records);if(i.record_id)throw new a("Public users cannot update existing records.",{code:"INVALID_REQUEST"});if(i.table.access_group!=="public"&&i.table.access_group!==0)throw new a("Public users can only post records to public tables.",{code:"INVALID_REQUEST"});if(o)throw new a("Public users cannot post subscription records.",{code:"INVALID_REQUEST"});if(i.remove_bin)throw new a("Public users cannot remove files from records.",{code:"INVALID_REQUEST"});if(i.unique_id)throw new a("Public users cannot set unique_id for records.",{code:"INVALID_REQUEST"})}return {config:i,progress:s,is_reference_post:e,files:n}}async function Wt(t){if(await this.__connection,!Array.isArray(t)||!t.length)throw new a('"params" should be a non-empty array.',{code:"INVALID_PARAMETER"});let e=[],n,r,i=null,o={_is_bulk_:t.map((h,_)=>{if(!h||typeof h!="object"||Array.isArray(h))throw new a(`"params[${_}]" should be type: <object>.`,{code:"INVALID_PARAMETER"});let p=Ht.bind(this)(h),y=p.config;if(p.is_reference_post&&e.push(p.is_reference_post),typeof y.progress=="function"&&i===null&&(i=y.progress),y.service!==void 0){if(n===void 0)n=y.service;else if(n!==y.service)throw new a('All bulk params should share the same "service" value.',{code:"INVALID_PARAMETER"})}if(y.owner!==void 0){if(r===void 0)r=y.owner;else if(r!==y.owner)throw new a('All bulk params should share the same "owner" value.',{code:"INVALID_PARAMETER"})}return delete y.progress,delete y.service,delete y.owner,y}),service:"",owner:""};n!==void 0&&(o.service=n),r!==void 0&&(o.owner=r);let l={auth:!!this.__user,method:"post"},u={};Object.keys(u).length&&Object.assign(l,{fetchOptions:u});let c=await E.bind(this)("post-record",o,l),d=await Promise.all(c.map(h=>de.bind(this)(h,"called from postRecord"))),g=Ne.bind(this)(n,r);for(let h=0;h<c.length;h++){let _=c[h],p=d[h];if(_&&typeof _=="object"&&_.error&&p&&!p.record_id&&(p.error=_.error),typeof _?.reference_private_key=="string")for(let y of e)this.__private_access_key[y]=_.reference_private_key;p?.unique_id&&Bt.bind(this)(g,p.unique_id,p.record_id);}return d}async function zt(t,e,n){if(await this.__connection,!e)throw new a('"config" argument is required.',{code:"INVALID_PARAMETER"});let r=Ht.bind(this)(e),i=r.config,s=r.progress,o=r.is_reference_post,l={auth:!!this.__user,method:"post"},u=[],c=U(t);n&&Array.isArray(n)&&n.length&&(u=u.concat(n)),c.files&&Array.isArray(c.files)&&c.files.length&&(u=u.concat(c.files));let d=null;d=Object.assign({data:c.data},i);let g={};typeof s=="function"&&(g.progress=s),Object.keys(g).length&&Object.assign(l,{fetchOptions:g});let h=await E.bind(this)("post-record",d,l);if(j()&&u.length){let y=new FormData;for(let T of u)y.append(T.name,T.file,T.file.name);let P={record_id:h.rec,progress:s};i.hasOwnProperty("service")&&(P.service=i.service);let{bin_endpoints:m}=await Se.bind(this)(y,P);h.bin?h.bin.push(...m):h.bin=m;}o&&typeof h?.reference_private_key=="string"&&(this.__private_access_key[o]=h.reference_private_key);let _=!!h&&h.data&&typeof h.data=="object"&&!Array.isArray(h.data)&&typeof h.data.__data__=="string"&&h.data.__data__.endsWith("/__data__/__json__.json"),p=await de.bind(this)(h,"called from postRecord",true);if(_&&(p.data=c.data),p.unique_id){let y=Ne.bind(this)(i?.service,i?.owner);Bt.bind(this)(y,p.unique_id,p.record_id),j()&&(this.__uniqueIdsPersistTimer!==null&&clearTimeout(this.__uniqueIdsPersistTimer),this.__uniqueIdsPersistTimer=setTimeout(()=>{this.__uniqueIdsPersistTimer=null;try{window.sessionStorage.setItem(`${y}:uniqueids`,JSON.stringify(this.__my_unique_ids[y]||{}));}catch{}},500));}return p}async function Jt(t,e){let n=await E.bind(this)("get-table",f.Params(t||{},{table:i=>ue(i,"table",{allowEmpty:true}),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(n?.list))for(let i of n.list){for(let s in r){if(s==="grp_"){for(let o in i)if(o.startsWith("grp_")){let l=o.substring(4);l==="pv"?l="private":l==="00"?l="public":l==="01"?l="authorized":l==="99"&&(l="admin"),i[`number_of_records_in_access_group_${l}`]=i[o],delete i[o];}}i.hasOwnProperty(s)&&(i[r[s]]=i[s],delete i[s]);}typeof i.table=="string"&&(i.table=K(i.table));}return n}async function Gt(t,e){if(!t?.table)throw new a('"table" is required.',{code:"INVALID_PARAMETER"});let n=f.Params(t||{},{table:s=>ue(s,"table",{allowEmpty:true}),index:s=>_e(s,"index.name"),order:{by:["average_number","total_number","number_count","average_bool","total_bool","bool_count","string_count","index_name","number_of_records"],value:s=>{if(t?.order?.by==="index_name"&&typeof s=="string")return z(s,"order.value",{allowEmpty:true,maxLength:256,blockKeyDelimiters:true});if(typeof s!="string"&&typeof s!="number"&&typeof s!="boolean")throw new a('"order.value" should be type: <string | number | boolean>.',{code:"INVALID_PARAMETER"});return s},condition:["gt","gte","lt","lte",">",">=","<","<=","=","eq","!=","ne"]}},["table"]);if(n.hasOwnProperty("order")){if(!n.order?.by)throw new a('"order.by" is required.',{code:"INVALID_PARAMETER"});if(n.order.hasOwnProperty("condition")&&!n.order.hasOwnProperty("value"))throw new a('"value" is required for "condition".',{code:"INVALID_PARAMETER"});if(n.hasOwnProperty("index")&&n.index.substring(n.index.length-1)!==".")throw new a('"index" should be a parent index name of the compound index when using "order.by"',{code:"INVALID_PARAMETER"})}let r=await E.bind(this)("get-index",n,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("/"),l={table:K(o[1]),index:K(o[2]),number_of_records:s.cnt_rec};for(let u in i)Object.prototype.hasOwnProperty.call(s,u)&&(l[i[u]]=s[u]);return l})),r}async function Xt(t,e){let n=await E.bind(this)("get-tag",f.Params(t||{},{table:r=>ue(r,"table",{allowEmpty:true}),tag:r=>xe(r,"tag",{allowEmpty:true}),condition:["gt","gte","lt","lte",">",">=","<","<=","=","eq","!=","ne"]}),Object.assign({auth:!!this.__user},{fetchOptions:e}));return Array.isArray(n?.list)&&(n.list=n.list.map(r=>{let i=r.tag.split("/");return {table:K(i[1]),tag:K(i[0]),number_of_records:r.cnt_rec}})),n}async function Zt(t,e){let n=await E.bind(this)("get-uniqueid",f.Params(t||{},{unique_id:"string",condition:["gt","gte","lt","lte",">",">=","<","<=","=","eq","!=","ne"]}),Object.assign({auth:!!this.__user},{fetchOptions:e}));if(Array.isArray(n?.list))for(let r in n.list){let i=n.list[r];n.list[r]={unique_id:i.unq,record_id:i.rec};}return n}async function Yt(t,e){await this.__connection;let n=await Kt.bind(this)(t,true),r=n.is_reference_fetch,i=await E.bind(this)("del-records",n.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 en(t){return sn.bind(this)({record_id:t.record_id,user_id:t.user_id,execute:"add"})}function tn(t){return sn.bind(this)({record_id:t.record_id,user_id:t.user_id||null,execute:"remove"})}async function nn(t,e){let n={record_id:t.record_id||void 0,user_id:t.user_id||void 0,execute:"list"};if(!n.record_id&&!n.user_id)throw new a("Either record_id or user_id must be provided.",{code:"INVALID_PARAMETER"});if(n.user_id)if(typeof n.user_id=="string")f.UserId(n.user_id),n.user_id=[n.user_id];else if(Array.isArray(n.user_id))for(let s of n.user_id)f.UserId(s);else throw new a("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 E.bind(this)("grant-private-access",n,{auth:true,fetchOptions:e});return i.list=i.list.map(r),i}function rn(t){let e=t.record_id,n=t.reference_id||void 0;if(!e)throw new a("Record ID is required.",{code:"INVALID_PARAMETER"});if(typeof e!="string")throw new a("Record ID should be type: <string | string[]>",{code:"INVALID_PARAMETER"});if(n&&typeof n!="string")throw new a("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(De[e])return De[e];let r=E.bind(this)("request-private-access-key",{record_id:e,reference_id:n},{auth:true}).then(i=>{let s=typeof i=="string"?i:i?.private_key;if(typeof s!="string")throw new a("Invalid private access key response.",{code:"ERROR"});return this.__private_access_key[e]=s,s}).finally(()=>{delete De[e];});return De[e]=r,r}function sn(t){t.execute;let n=f.Params(t,{record_id:"string",user_id:r=>{if(!r)throw new a("User ID is required.",{code:"INVALID_PARAMETER"});let i=r;if(typeof i=="string"&&(i=[i]),i.length>100)throw new a("Cannot process more than 100 users at once.",{code:"INVALID_REQUEST"});for(let s of i)f.UserId(s,'User ID in "user_id"');return i},execute:["add","remove"]},["execute","record_id","user_id"]);return n.user_id||(n.user_id=null),E.bind(this)("grant-private-access",n,{auth:true})}var S={},F={},Q={},G={},J={},Ue={},Ce={};function on(t,e,n){t[e]||(t[e]=[]),t[e].push(n);}async function Le(t,e,n){let r=[];if(t[e]){for(let i of t[e])if(i){let s=n(i);s instanceof Promise&&(s=await s),r.push(s);}delete t[e];}return r}async function Ge(t,e){if(!this?.session?.accessToken?.jwtToken)throw new a("Access token is required.",{code:"INVALID_PARAMETER"});let n=await this.__socket;async function r(i,s,o){this.log("answerSdpOffer from",s),await S[s].setRemoteDescription(new RTCSessionDescription(i));let l=await S[s].createAnswer();await S[s].setLocalDescription(l),o.send(JSON.stringify({action:"rtc",uid:s,content:{sdpanswer:l},token:this.session.accessToken.jwtToken}));}S?.[e]?t?(await Le(Ce,e,i=>r.bind(this)(i,e,n)),await r.bind(this)(t,e,n)):await Le(Ce,e,i=>r.bind(this)(i,e,n)):t&&on(Ce,e,t);}async function Xe(t,e){if(this.log("receiveIceCandidate",t),S?.[e]&&S[e]?.remoteDescription&&S[e]?.remoteDescription?.type){if(!t)return Le(Ue,e,n=>S[e].addIceCandidate(n));await Le(Ue,e,n=>S[e].addIceCandidate(n)),await S[e].addIceCandidate(t);}else on(Ue,e,t);}async function H(t){if(typeof window>"u"||window._runningInNodeJS)throw new a("WebRTC is not supported in Node.js environment.",{code:"NOT_SUPPORTED"});f.Params(t,{cid:s=>{if(typeof s!="string")throw new a('"cid" should be type: <string>.',{code:"INVALID_PARAMETER"});if(s&&s.slice(0,4)!=="cid:")throw new a('"cid" should be a valid connection id.',{code:"INVALID_PARAMETER"});return s},close:"boolean"});let e=await this.__socket,{cid:n,close_all:r=false}=t||{};if(!r&&!n)throw new a('"cid" is required.',{code:"INVALID_PARAMETER"});let i=s=>{if(!s)throw new a('"cid" is required.',{code:"INVALID_PARAMETER"});if(delete Ce[s],delete Ue[s],F[s]&&Object.values(F[s]).forEach(o=>{o.readyState!=="closed"&&o.close();}),delete F[s],S?.[s]){S[s].connectionState!=="closed"&&(S[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:S[s],timestamp:new Date().toISOString(),state:S[s].connectionState,iceState:S[s].iceConnectionState,signalingState:S[s].signalingState};J[s]&&J[s](o),this.log("closeRTC",o);}delete J[s],delete G[s],delete Q[s],delete S[s];};if(r)for(let s in S)i(s);else i(n);this.log("Cleaning up media stream..."),this.__mediaStream&&(this.__mediaStream.getTracks().forEach(s=>{s.stop();}),this.__mediaStream=null);}async function an(t){if(t instanceof MediaStream)return t;if(!t.video&&!t.audio){let e=new MediaStream,n=document.createElement("canvas");n.width=1,n.height=1;let i=n.captureStream().getVideoTracks()[0];return e.addTrack(i),e}return window.navigator.mediaDevices.getUserMedia(t)}async function cn(t,e){if(typeof window>"u"||window._runningInNodeJS)throw new a("WebRTC is not supported in Node.js environment.",{code:"NOT_SUPPORTED"});if(typeof e!="function")throw new a("Callback is required.",{code:"INVALID_PARAMETER"});if(!this?.session?.accessToken?.jwtToken)throw new a("Access token is required.",{code:"INVALID_PARAMETER"});t=f.Params(t,{cid:o=>{if(typeof o!="string")throw new a('"cid" should be type: <string>.',{code:"INVALID_PARAMETER"});if(o&&o.slice(0,4)!=="cid:")throw new a('"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:n,ice:r}=t;if(!(t?.media instanceof MediaStream)&&(t?.media?.video||t?.media?.audio)&&window.location.hostname!=="localhost"&&window.location.protocol!=="https:")throw new a("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 a("No realtime connection. Execute connectRealtime() before this method.",{code:"INVALID_REQUEST"});if(i.readyState!==1)throw new a("Realtime connection is not ready.",{code:"INVALID_REQUEST"});let s={iceServers:[{urls:r}]};S?.[n]||(S[n]=new RTCPeerConnection(s)),t?.media&&(this.__mediaStream=await an(t.media),this.__mediaStream.getTracks().forEach(o=>{S[n].addTrack(o,this.__mediaStream);})),J[n]=e,F[n]||(F[n]={});for(let o=0;o<t.channels.length;o++){let l=t.channels[o];if(typeof l=="string")switch(l){case "text-chat":l={ordered:true,maxRetransmits:10,protocol:"text-chat"};break;case "file-transfer":l={ordered:false,maxPacketLifeTime:3e3,protocol:"file-transfer"};break;case "video-chat":l={ordered:true,maxRetransmits:10,protocol:"video-chat"};break;case "voice-chat":l={ordered:true,maxRetransmits:10,protocol:"voice-chat"};break;case "gaming":l={ordered:false,maxPacketLifeTime:100,protocol:"gaming"};break;default:l={ordered:true,maxRetransmits:10,protocol:"default"};break}let u=l.protocol||"default";if(Object.keys(F[n]).includes(u))throw new a(`Data channel with the protocol "${u}" already exists.`,{code:"INVALID_REQUEST"});let c=S[n].createDataChannel(u,l);F[n][u]=c;}for(let o in F[n]){let l=F[n][o];dn.bind(this)(n,l);}return un.bind(this)(n,["onnegotiationneeded"]),await Je.bind(this)(n),{hangup:()=>Q[n]&&Q[n](false),connection:new Promise(o=>{Q[n]=(l=>{if(this.log("receiver picked up the call",n),!l)return H.bind(this)({cid:n}),null;S[n].onnegotiationneeded=()=>{this.log("onnegotiationneeded",`sending offer to "${n}".`),Je.bind(this)(n),J[n]&&J[n]({type:"negotiationneeded",target:S[n],timestamp:new Date().toISOString(),signalingState:S[n].signalingState,connectionState:S[n].iceConnectionState,gatheringState:S[n].iceGatheringState});},o({target:S[n],channels:F[n],hangup:()=>H.bind(this)({cid:n}),media:this.__mediaStream});}).bind(this);})}}function ln(t){return async(e,n)=>{e=e||{},e=U(e).data;let r=t.sender_cid,i=await this.__socket;if(!G[r])return null;if(typeof n!="function")throw new a("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 a("Media stream is only supported on either localhost or https.",{code:"INVALID_REQUEST"});let{ice:s="stun:stun.skapi.com:3468"}=e;return S?.[r]||(S[r]=new RTCPeerConnection({iceServers:[{urls:s}]})),e?.media&&(this.__mediaStream=await an(e.media),this.__mediaStream.getTracks().forEach(o=>{S[r].addTrack(o,this.__mediaStream);})),delete G[r],J[r]=n,F[r]||(F[r]={}),S[r].ondatachannel=o=>{this.log("ondatachannel",`received data channel "${o.channel.label}".`);let l=o.channel;F[r][l.label]=l,dn.bind(this)(r,l);},un.bind(this)(r,["onnegotiationneeded"]),await Ge.bind(this)(null,r),await Xe.bind(this)(null,r),i.send(JSON.stringify({action:"rtc",uid:r,content:{pickup:this.user.user_id},token:this.session.accessToken.jwtToken})),{target:S[r],channels:F[r],hangup:()=>H.bind(this)({cid:r}),media:this.__mediaStream}}}async function Je(t){if(!this?.session?.accessToken?.jwtToken)throw new a("Access token is required.",{code:"INVALID_PARAMETER"});this.log("sendOffer",t);let e=await this.__socket,n=await S[t].createOffer();await S[t].setLocalDescription(n);let r=S[t].localDescription;this.log("rtcSdpOffer to",r),e.send(JSON.stringify({action:"rtc",uid:t,content:{sdpoffer:r},token:this.session.accessToken.jwtToken}));}async function ni(t,e){if(!this?.session?.accessToken?.jwtToken)throw new a("Access token is required.",{code:"INVALID_PARAMETER"});this.log("sendIceCandidate to",e);let n=await this.__socket;if(!t.candidate){this.log("candidate-end","all ice candidates have been sent");return}let r=J[e]||(()=>{}),i=t.candidate;this.log("ice gathering state set to",S[e].iceGatheringState),r({type:"icecandidate",target:S[e],timestamp:new Date().toISOString(),candidate:t.candidate.candidate,sdpMid:t.candidate.sdpMid,sdpMLineIndex:t.candidate.sdpMLineIndex,usernameFragment:t.candidate.usernameFragment,protocol:t.candidate.protocol,gatheringState:S[e].iceGatheringState,connectionState:S[e].iceConnectionState}),n.send(JSON.stringify({action:"rtc",uid:e,content:{candidate:i},token:this.session.accessToken.jwtToken}));}function un(t,e){let n=new Set(e),r=J[t]||(o=>{}),i=S[t],s={ontrack:o=>{r({type:"track",target:i,timeStamp:o.timeStamp,streams:o.streams,track:o.track});},onicecandidate:o=>{ni.bind(this)(o,t),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:()=>{Je.bind(this)(t),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")&&H.bind(this)({cid:t});}};for(let[o,l]of Object.entries(s))n.has(o)||(i[o]=l);}function dn(t,e,n){let r=new Set(n),i=J[t]||(o=>{}),s={onmessage:o=>{let l={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(l);},onerror:o=>{let l={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(l);},onclose:o=>{let l={type:o.type,target:e,timeStamp:o.timeStamp,readyState:e.readyState,label:e.label,id:e.id};this.log(`${e.label}: closed`,null),i(l),F[t]&&(delete F[t][e.label],Object.keys(F[t]).length===0&&H.bind(this)({cid:t}));},onbufferedamountlow:o=>{let l={target:e,bufferedAmount:e.bufferedAmount,bufferedAmountLowThreshold:e.bufferedAmountLowThreshold,type:o.type,timeStamp:o.timeStamp};this.log(`${e.label}: bufferedamountlow`,e.bufferedAmount),i(l);},onopen:o=>{this.log("dataChannel",`data channel: "${e.label}" is open and ready to send messages.`);let l={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(l);}};for(let[o,l]of Object.entries(s))r.has(o)||(e[o]=l);}var re,ne=null,be=true,ge=0;async function ri(){if(typeof window>"u"||window._runningInNodeJS)throw new a("WebSocket is not supported in Node.js environment.",{code:"NOT_SUPPORTED"});if(await this.getProfile(),!this.session)throw new a("No access.",{code:"INVALID_REQUEST"});let t=await this.record_endpoint;return new WebSocket(t.websocket_private+"?token="+this.session.accessToken.jwtToken)}var Ze=null;async function gn(){if(typeof window>"u"||window._runningInNodeJS)throw new a("WebSocket is not supported in Node.js environment.",{code:"NOT_SUPPORTED"});be=true;let t=this.__socket?await this.__socket:this.__socket;H.bind(this)({close_all:true}),re&&Ye.bind(this)({group:null}),ge=0,ne&&(ne.terminate(),ne=null);try{t&&t.close();}catch{}return window.removeEventListener("visibilitychange",Ze),this.__socket=null,null}async function Oe(t,e=50,n){if(typeof window>"u"||window._runningInNodeJS)throw new a("WebSocket is not supported in Node.js environment.",{code:"NOT_SUPPORTED"});if(typeof t!="function")throw new a("Callback must be a function.",{code:"INVALID_REQUEST"});if(n==="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(be&&(Ze=()=>{!document.hidden&&!be&&Oe.bind(this)(t,0,"reconnect");},this.__socket instanceof Promise))return this.__socket;ne&&(ne.terminate(),ne=null),this.__socket=new Promise(async r=>{await ce.bind(this)(),setTimeout(async()=>{let i=await ri.bind(this)();i.onopen=()=>{be=false,ge=0,n!=="reconnect"&&window.addEventListener("visibilitychange",Ze),this.log("realtime onopen","Connected to WebSocket server."),t({type:"success",message:"Connected to WebSocket server."}),re&&i.send(JSON.stringify({action:"joinRoom",rid:re,token:this.session.accessToken.jwtToken}));let s=`
|
|
206
|
+
var sr=Object.defineProperty;var or=Object.getOwnPropertyDescriptor;var oe=(t=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(t,{get:(e,n)=>(typeof require<"u"?require:e)[n]}):t)(function(t){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+t+'" is not supported')});var E=(t,e,n,r)=>{for(var i=or(e,n),s=t.length-1,o;s>=0;s--)(o=t[s])&&(i=(o(e,n,i))||i);return i&&sr(e,n,i),i};var Y=typeof globalThis<"u"?globalThis:void 0,Ee=Y?.window;function ar(t){if(Buffer)return Buffer.from(t).toString("base64");let e="",n=new Uint8Array(t),r=32768;for(let i=0;i<n.length;i+=r){let s=n.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(Ee)Ee.global=Ee,Ee.global._runningInNodeJS=false;else if(Y&&(Y.global=Y,typeof Y.window>"u")){class t{constructor(){this.result=null;this.error=null;this.onload=null;this.onloadend=null;this.onerror=null;}readAsDataURL(r){r.arrayBuffer().then(i=>{let s=ar(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});});}}Y.FileReader=t;class e{constructor(){this.status=0;this.statusText="";this.readyState=0;this.responseText="";this.response=null;this.responseType="";this.responseURL="";this.timeout=0;this.withCredentials=false;this.onload=null;this.onerror=null;this.onabort=null;this.ontimeout=null;this.onprogress=null;this.onreadystatechange=null;this.upload={onprogress:null};this._method="GET";this._url="";this._headers={};this._aborted=false;}open(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);});}}Y.XMLHttpRequest=e,Y.window={_runningInNodeJS:true,alert:n=>console.error("[Alert]",n),sessionStorage:{getItem:n=>null,setItem:(n,r)=>{},removeItem:n=>{}},localStorage:{getItem:n=>{let r=oe("fs"),i=oe("path");try{let s=i.resolve(process.cwd(),"states","localStorage",`${n}.skapi`);return r.existsSync(s)?r.readFileSync(s,"utf8"):null}catch{return null}},setItem:(n,r)=>{let i=oe("fs"),s=oe("path");try{let o=s.resolve(process.cwd(),"states","localStorage");i.existsSync(o)||i.mkdirSync(o,{recursive:!0});let l=s.resolve(o,`${n}.skapi`);i.writeFileSync(l,r,"utf8");}catch{}},removeItem:n=>{let r=oe("fs"),i=oe("path");try{let s=i.resolve(process.cwd(),"states","localStorage",`${n}.skapi`);r.existsSync(s)&&r.unlinkSync(s);}catch{}}},location:{href:"",origin:"",hostname:"",protocol:"",replace:n=>{}},navigator:{userAgent:`nodejs/${Y?.process?.versions?.node||"unknown"}`,mediaDevices:{getUserMedia:async n=>{throw new Error("getUserMedia is not supported in Node.js environment.")}}},addEventListener:()=>{},removeEventListener:()=>{}};}var a=class extends Error{constructor(e,n){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=n?.name||"SKAPI",this.code=n?.code||e[0]||"ERROR",n?.cause&&(this.cause=n.cause);}else super((e?.message||(typeof e=="string"?e:"Something went wrong.")).trim()),typeof e=="string"?(this.name=n?.name||"SKAPI",this.code=n?.code||"ERROR",n?.cause&&(this.cause=n.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=n?.name||"SKAPI",this.code=n?.code||"ERROR",this.cause=e?.cause);}};var ee="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",Me=BigInt(ee.length),cr=2*1024*1024,lr=["aud","cognito:username","event_id","exp","iat","iss","jti","origin_jti","secret_key","token_use"],tt={auth_time:"log",sub:"user_id"},ur=["0","1","2","3","4","5","6","7","8","9","a","b","c","d","e","f","g","h","i","j","k","l"],ot=["us31","us72","ap51","ap22","ap41","eu71","ap21","us32","us71","af51","ap31","ap43","ap23","ap42","ca01","eu01","eu72","eu51","eu73","eu11","me51","sa31"],nt=typeof TextEncoder<"u"?new TextEncoder:null;function dr(){if(typeof globalThis<"u")return globalThis.Buffer}function gr(t){if(nt)return nt.encode(t);let e=unescape(encodeURIComponent(t)),n=new Uint8Array(e.length);for(let r=0;r<e.length;r++)n[r]=e.charCodeAt(r);return n}function fr(t){if(t instanceof Uint8Array)return t;if(typeof t=="string")return gr(t);if(typeof ArrayBuffer<"u"&&t instanceof ArrayBuffer)return new Uint8Array(t);if(typeof ArrayBuffer<"u"&&ArrayBuffer.isView(t))return new Uint8Array(t.buffer,t.byteOffset,t.byteLength);if(Array.isArray(t))return Uint8Array.from(t);let e=dr();if(e)return new Uint8Array(e.from(t));throw new Error("No byte conversion available in this environment.")}var b=class b{static hash(e){typeof e!="string"&&(console.warn("coercing non-string value to empty string"),e="");let n=b.sb(e),r=1732584193,i=-271733879,s=-1732584194,o=271733878,l,u,c,d;for(let g=0;g<n.length;g+=16)l=r,u=i,c=s,d=o,r=b.ff(r,i,s,o,n[g],7,-680876936),o=b.ff(o,r,i,s,n[g+1],12,-389564586),s=b.ff(s,o,r,i,n[g+2],17,606105819),i=b.ff(i,s,o,r,n[g+3],22,-1044525330),r=b.ff(r,i,s,o,n[g+4],7,-176418897),o=b.ff(o,r,i,s,n[g+5],12,1200080426),s=b.ff(s,o,r,i,n[g+6],17,-1473231341),i=b.ff(i,s,o,r,n[g+7],22,-45705983),r=b.ff(r,i,s,o,n[g+8],7,1770035416),o=b.ff(o,r,i,s,n[g+9],12,-1958414417),s=b.ff(s,o,r,i,n[g+10],17,-42063),i=b.ff(i,s,o,r,n[g+11],22,-1990404162),r=b.ff(r,i,s,o,n[g+12],7,1804603682),o=b.ff(o,r,i,s,n[g+13],12,-40341101),s=b.ff(s,o,r,i,n[g+14],17,-1502002290),i=b.ff(i,s,o,r,n[g+15],22,1236535329),r=b.gg(r,i,s,o,n[g+1],5,-165796510),o=b.gg(o,r,i,s,n[g+6],9,-1069501632),s=b.gg(s,o,r,i,n[g+11],14,643717713),i=b.gg(i,s,o,r,n[g],20,-373897302),r=b.gg(r,i,s,o,n[g+5],5,-701558691),o=b.gg(o,r,i,s,n[g+10],9,38016083),s=b.gg(s,o,r,i,n[g+15],14,-660478335),i=b.gg(i,s,o,r,n[g+4],20,-405537848),r=b.gg(r,i,s,o,n[g+9],5,568446438),o=b.gg(o,r,i,s,n[g+14],9,-1019803690),s=b.gg(s,o,r,i,n[g+3],14,-187363961),i=b.gg(i,s,o,r,n[g+8],20,1163531501),r=b.gg(r,i,s,o,n[g+13],5,-1444681467),o=b.gg(o,r,i,s,n[g+2],9,-51403784),s=b.gg(s,o,r,i,n[g+7],14,1735328473),i=b.gg(i,s,o,r,n[g+12],20,-1926607734),r=b.hh(r,i,s,o,n[g+5],4,-378558),o=b.hh(o,r,i,s,n[g+8],11,-2022574463),s=b.hh(s,o,r,i,n[g+11],16,1839030562),i=b.hh(i,s,o,r,n[g+14],23,-35309556),r=b.hh(r,i,s,o,n[g+1],4,-1530992060),o=b.hh(o,r,i,s,n[g+4],11,1272893353),s=b.hh(s,o,r,i,n[g+7],16,-155497632),i=b.hh(i,s,o,r,n[g+10],23,-1094730640),r=b.hh(r,i,s,o,n[g+13],4,681279174),o=b.hh(o,r,i,s,n[g],11,-358537222),s=b.hh(s,o,r,i,n[g+3],16,-722521979),i=b.hh(i,s,o,r,n[g+6],23,76029189),r=b.hh(r,i,s,o,n[g+9],4,-640364487),o=b.hh(o,r,i,s,n[g+12],11,-421815835),s=b.hh(s,o,r,i,n[g+15],16,530742520),i=b.hh(i,s,o,r,n[g+2],23,-995338651),r=b.ii(r,i,s,o,n[g],6,-198630844),o=b.ii(o,r,i,s,n[g+7],10,1126891415),s=b.ii(s,o,r,i,n[g+14],15,-1416354905),i=b.ii(i,s,o,r,n[g+5],21,-57434055),r=b.ii(r,i,s,o,n[g+12],6,1700485571),o=b.ii(o,r,i,s,n[g+3],10,-1894986606),s=b.ii(s,o,r,i,n[g+10],15,-1051523),i=b.ii(i,s,o,r,n[g+1],21,-2054922799),r=b.ii(r,i,s,o,n[g+8],6,1873313359),o=b.ii(o,r,i,s,n[g+15],10,-30611744),s=b.ii(s,o,r,i,n[g+6],15,-1560198380),i=b.ii(i,s,o,r,n[g+13],21,1309151649),r=b.ii(r,i,s,o,n[g+4],6,-145523070),o=b.ii(o,r,i,s,n[g+11],10,-1120210379),s=b.ii(s,o,r,i,n[g+2],15,718787259),i=b.ii(i,s,o,r,n[g+9],21,-343485551),r=b.ad(r,l),i=b.ad(i,u),s=b.ad(s,c),o=b.ad(o,d);return b.rh(r)+b.rh(i)+b.rh(s)+b.rh(o)}static rh(e){let n="";for(let r=0;r<=3;r++)n+=b.alphabet.charAt(e>>r*8+4&15)+b.alphabet.charAt(e>>r*8&15);return n}static ad(e,n){let r=(e&65535)+(n&65535);return (e>>16)+(n>>16)+(r>>16)<<16|r&65535}static rl(e,n){return e<<n|e>>>32-n}static cm(e,n,r,i,s,o){return b.ad(b.rl(b.ad(b.ad(n,e),b.ad(i,o)),s),r)}static ff(e,n,r,i,s,o,l){return b.cm(n&r|~n&i,e,n,s,o,l)}static gg(e,n,r,i,s,o,l){return b.cm(n&i|r&~i,e,n,s,o,l)}static hh(e,n,r,i,s,o,l){return b.cm(n^r^i,e,n,s,o,l)}static ii(e,n,r,i,s,o,l){return b.cm(r^(n|~i),e,n,s,o,l)}static sb(e){let n,r=(e.length+8>>6)+1,i=new Array(r*16);for(n=0;n<r*16;n++)i[n]=0;for(n=0;n<e.length;n++)i[n>>2]|=e.charCodeAt(n)<<n%4*8;return i[n>>2]|=128<<n%4*8,i[r*16-2]=e.length*8,i}};b.alphabet="0123456789abcdef";var F=b;function at(t){if(t===0)return ee[0];let e="";for(;t>0;)e=ee[t%62]+e,t=Math.floor(t/62);return e}function B(t){return t.split("").reverse().reduce((e,n,r)=>e+ee.indexOf(n)*62**r,0)}function ie(t=6){let e="",n="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",r=n.length,i=0;for(;i<t;)e+=n.charAt(Math.floor(Math.random()*r)),i+=1;return e}function qe(){return typeof window>"u"||!!window?._runningInNodeJS}function j(){return !qe()&&typeof document<"u"&&typeof document.createElement=="function"}function Re(t){let e;try{e=JSON.stringify(t);}catch{throw new a("Invalid data type.",{code:"INVALID_REQUEST"})}if(new Blob([e]).size>cr)throw new a("Data should not exceed 2MB",{code:"INVALID_REQUEST"})}function rt(t){return t===""||t==="on"||t==="true"}function it(t){return t==="false"}function st(t,e,n){e.name&&n(t,e.name,e.value);}var Ae=j(),hr=typeof SubmitEvent<"u",pr=typeof HTMLFormElement<"u";function U(t,e,n){let r={},i=[];function s(u,c,d){if(e?.ignoreEmpty&&d==="")return;if(e?.nullIfEmpty&&d===""&&(d=null),typeof n=="function"){let _=n(c,d);_!==void 0&&(d=_);}let g=c.split("[").map(_=>{let p=_.replace("]",""),y=Number(p);return !isNaN(y)&&!p.includes(".")?p=y:(p[0]==='"'&&p[p.length-1]==='"'||p[0]==="'"&&p[p.length-1]==="'")&&(p=p.replace(/"/g,"").replace(/'/g,"")),p}),h=u;if(typeof g[0]=="number")throw new a("Form key cannot start with an array index.",{code:"INVALID_REQUEST"});for(let _=0;_<g.length;_++){let p=g[_];_<g.length-1?(h[p]===void 0&&(typeof g[_+1]=="number"?h[p]=[]:h[p]={}),h=h[p]):h[p]===void 0?h[p]=d:Array.isArray(h[p])?h[p].push(d):h[p]=[h[p],d];}}function o(u,c,d){if(d instanceof File)u.push({name:c,file:d});else if(d instanceof FileList&&d&&d.length>0)for(let g=0;g<=d.length-1;g++){let h=d.item(g);h&&u.push({name:c,file:h});}}let l=u=>{u.name&&(u.type==="number"?u.value&&s(r,u.name,Number(u.value)):u.type==="checkbox"||u.type==="radio"?u.checked?u.type==="checkbox"&&u.value===""||rt(u.value)?s(r,u.name,true):it(u.value)?s(r,u.name,false):u.value&&s(r,u.name,u.value):u.type==="checkbox"&&(rt(u.value)?s(r,u.name,false):it(u.value)&&s(r,u.name,true)):u.type==="file"?u.files&&u.files.length>0&&o(i,u.name,u.files):s(r,u.name,u.value));};if(Ae&&(t instanceof HTMLInputElement||t instanceof HTMLSelectElement||t instanceof HTMLTextAreaElement))return l(t),Re(r),{data:r,files:i};if(Ae&&t instanceof FormData){for(let u of t.entries()){let c=u[0],d=u[1];if(d instanceof File||d instanceof FileList)o(i,c,d);else if(d instanceof Blob){let g=d;if(g.type==="application/json")try{let h=JSON.parse(g.text());s(r,c,h);}catch{s(r,c,g);}}else s(r,c,d);}return Re(r),{data:r,files:i}}if(Ae&&hr&&t instanceof SubmitEvent&&(t=t.target),Ae&&pr&&t instanceof HTMLFormElement){let u=t.querySelectorAll("input"),c=t.querySelectorAll("select"),d=t.querySelectorAll("textarea");for(let g=0;g<c.length;g++)st(r,c[g],s);for(let g=0;g<d.length;g++)st(r,d[g],s);for(let g=0;g<u.length;g++)l(u[g]);return Re(r),{data:r,files:i}}return Re(t),{data:t,files:i}}function fe(t){let e={};for(let n in t){let r=t[n];if(!lr.includes(n))if(tt[n])e[tt[n]]=r;else if(n.includes("custom:"))e[n.replace("custom:","")]=r;else if(n==="address"){let i=r;if(i&&typeof i=="object"&&Object.keys(i).length){if(i?.formatted)try{e[n]=JSON.parse(i.formatted);}catch{e[n]=i.formatted;}}else e[n]=i;}else e[n]=r;}for(let n of ["address_public","birthdate_public","email_public","gender_public","phone_number_public","access_group"])n.includes("_public")?e.hasOwnProperty(n.split("_")[0])?e[n]=e.hasOwnProperty(n)?!!Number(e[n]):false:delete e[n]:e[n]=e.hasOwnProperty(n)?Number(e[n]):0;for(let n of ["email","phone_number"])e.hasOwnProperty(n)?e[n+"_verified"]=e[n+"_verified"]===true:delete e[n+"_verified"];return e}function Fe(t){if(t=Ar(t),t.split("-").length===7){let e=t.split("-"),n,r;try{n=ot[B(e[1][0])],r=e.slice(2).join("-");}catch{throw new Error("INVALID_PARAMETER: Service ID is invalid: "+t)}if(!n)throw new Error("INVALID_PARAMETER: Service ID is invalid: "+t);return {service:n+e[0]+e[1].slice(1),owner:r}}return {service:t,owner:""}}function Ve(t,e){let n=ot.indexOf(t.slice(0,4)),r=ur[n],s=`${t.slice(4,-4)}-${r}${t.slice(-4)}-${e}`;return Rr(s)}function mr(t){let e=0n;for(let n of t){let r=ee.indexOf(n);if(r<0)throw new Error(`INVALID_PARAMETER: Invalid base62 character: ${n}`);e=e*Me+BigInt(r);}return e}function _r(t,e=1){if(t<0n)throw new Error("INVALID_PARAMETER: Negative values are not supported.");if(t===0n)return "0".repeat(Math.max(1,e));let n="",r=t;for(;r>0n;){let i=Number(r%Me);n=ee[i]+n,r/=Me;}return n.length<e&&(n="0".repeat(e-n.length)+n),n}function br(t){if(t===0n)return Uint8Array.from([0]);let e=[],n=t;for(;n>0n;)e.push(Number(n&0xffn)),n>>=8n;return e.reverse(),Uint8Array.from(e)}function yr(t){let e=0n;for(let n of t)e=(e<<8n)+BigInt(n);return e}function wr(t){let e=String(t).replace(/-/g,"");if(!/^[0-9a-fA-F]{32}$/.test(e))throw new Error("INVALID_PARAMETER: Invalid UUID format.");let n=new Uint8Array(16);for(let r=0;r<16;r++)n[r]=parseInt(e.slice(r*2,r*2+2),16);return n}function Er(t){let e=Array.from(fr(t),n=>n.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 Rr(t){let e=String(t);if(e.split("-").length===2)return e;let n=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(!n)throw new Error("INVALID_PARAMETER: Input must match <base62>-<base62>-<uuid>.");let[,r,i,s]=n;if(r.length<2)throw new Error("INVALID_PARAMETER: The first part must contain at least 2 characters.");if(i.length>=ee.length)throw new Error("INVALID_PARAMETER: The middle section is too long to encode.");let o=r.slice(0,2),l=r.slice(2),u=i+o,c=ee[i.length]+l+u,d=wr(s),g=_r(yr(d));return `${c}-${g}`}function Ar(t){let e=String(t);if(e.split("-").length!==2)return e;let n=e.split("-");if(n.length!==2||!n[0]||!n[1])throw new Error("INVALID_PARAMETER: Corrupt compressed token: "+e);let[r,i]=n,s=ee.indexOf(r[0]);if(s<0)throw new Error("INVALID_PARAMETER: Corrupt compressed token: "+e);let o=r.slice(1),l=s+2;if(o.length<l)throw new Error("INVALID_PARAMETER: Corrupt compressed token: "+e);let u=o.slice(0,o.length-l),c=o.slice(o.length-l),d=c.slice(s),g=c.slice(0,s),h=d+u;if(!/^[0-9A-Za-z]+$/.test(h)||!/^[0-9A-Za-z]+$/.test(g))throw new Error("INVALID_PARAMETER: Corrupt compressed token: "+e);let _=mr(i),p=br(_);if(p.length>16)throw new Error("INVALID_PARAMETER: Corrupt compressed token: "+e);let y=new Uint8Array(16);y.set(p,16-p.length);let P=Er(y);return `${h}-${g}-${P}`}function Tr(t,e="User ID"){let n=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;if(t){if(typeof t!="string")throw new a(`${e} should be type: string.`,{code:"INVALID_PARAMETER"});if(!t.match(n))throw new a(`${e} is invalid.`,{code:"INVALID_PARAMETER"})}else throw new a(`${e} is empty.`,{code:"INVALID_PARAMETER"});return t}function Pr(t){if(t&&(typeof t!="string"||t.charAt(0)!=="+"||isNaN(Number(t.substring(1)))))throw new a('"phone_number" is invalid. The format should be "+00123456789". Type: string.',{code:"INVALID_PARAMETER"});return t||""}function Sr(t){if(t){if(typeof t!="string")throw new a('"birthdate" is invalid. The format should be "yyyy-mm-dd". Type: string.',{code:"INVALID_PARAMETER"});{let e=new RegExp(/([12]\d{3}-(0[1-9]|1[0-2])-(0[1-9]|[12]\d|3[01]))/);if(t.length!==10||t.split("-").length!==3||!e.test(t))throw new a('"birthdate" is invalid. The format should be "yyyy-mm-dd". Type: string.',{code:"INVALID_PARAMETER"})}}return t||""}function kr(t){if(t){if(typeof t!="string")throw new a('"password" should be type: string.',{code:"INVALID_PARAMETER"});if(t.length<6)throw new a('"password" should be at least 6 characters.',{code:"INVALID_PARAMETER"});if(t.length>60)throw new a('"password" can be up to 60 characters max.',{code:"INVALID_PARAMETER"})}else throw new a('"password" is required.',{code:"INVALID_PARAMETER"});return t}function xr(t,e="email"){if(t){if(typeof t!="string")throw new a(`"${e}"should be type: string.`,{code:"INVALID_PARAMETER"});if(t.length<5)throw new a(`"${e}" should be at least 5 characters.`,{code:"INVALID_PARAMETER"});if(/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/.test(t)&&(t=t.trim(),t.split("@")[1].split(".").length>=2))return t.toLowerCase()}else throw new a(`"${e}" is required.`,{code:"INVALID_PARAMETER"});throw new a(`"${t}" is an invalid email.`,{code:"INVALID_PARAMETER"})}function vr(t){let e=typeof window<"u",n=(()=>{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]==="/"&&n){if(n.slice(0,5)==="file:")throw new a(`"${i}" is an invalid url. Relative URL does not work on local file system. Use full URL string.`,{code:"INVALID_PARAMETER"});s=n+s;}else if(s[0]==="."&&n){if(n.slice(0,5)==="file:")throw new a(`"${i}" is an invalid url. Relative URL does not work on local file system. Use full URL string.`,{code:"INVALID_PARAMETER"});let l=e?window.location.href.split("?")[0]:"";l.slice(-1)!=="/"&&(l+="/"),s=l+s.slice(1);}let o;try{o=new URL(s);}catch{throw new a(`"${i}" is an invalid url.`,{code:"INVALID_PARAMETER"})}if(o.protocol)return o.href}}throw new a(`"${i}" is an invalid url.`,{code:"INVALID_PARAMETER"})};return Array.isArray(t)?t.map(i=>r(i)):r(t)}function Dr(t,e,n=[],r){let i=U(t,r),s=i.data;e.service="string",e.owner="string";let o={};for(let l in e)if(s&&typeof s=="object"&&!Array.isArray(s)&&s.hasOwnProperty(l))if(typeof s[l]=="function")o[l]=s[l];else try{o[l]=JSON.parse(JSON.stringify(s[l]));}catch{o[l]=s[l];}r?.precall&&r.precall({data:o,files:i?.files||[]});try{return Ir__default.default(o,e,n)}catch(l){throw new a(l.message,{code:"INVALID_PARAMETER"})}}var f={UserId:Tr,PhoneNumber:Pr,Birthdate:Sr,Password:kr,Email:xr,Url:vr,Params:Dr};var L=null;function $e(t){let e={tkid:"ticket_id",cond:"condition",stmp:"timestamp",actn:"action",cnt:"count",ttl:"time_to_live",plch:"placeholder",hash:"hash",desc:"description",pmc:"limit_per_user"},n={};for(let r in t)if(r==="tkid"){let i=t[r].split("#");if(i.length===1){n.ticket_id=i[0];continue}n.ticket_id=i[1],n.consume_id=i[2],n.user_id=i[3];let s=i[2].slice(-4);if(n.is_test=s===":CHK",!t.stmp){let o=i[2].slice(0,-4);/^[0-9]+$/.test(o)?n.timestamp=parseInt(o,10):n.timestamp=B(i[2].slice(0,-4));}}else e[r]?n[e[r]]=t[r]:n[r]=t[r];return n}async function lt(t){if(!t.ticket_id)throw new a("Ticket ID is required.",{code:"INVALID_PARAMETER"});if(!t.method)throw new a('Method is required. Should be either "GET" or "POST"',{code:"INVALID_PARAMETER"});let e=t.ticket_id;await this.__connection;let n=await R.bind(this)(`https://${this.service.slice(0,4)}.${this.customApiDomain}/auth/consume/${this.service}/${this.owner}/${e}`,t?.data||{},{method:t.method,auth:!!t?.auth});return $e(n)}async function ut(t,e){await this.__connection;let n=await R.bind(this)("ticket",Object.assign({exec:"list"},t||{}),{auth:true,fetchOptions:e});return n.list=n.list.map($e),n}async function dt(t,e){await this.__connection;let n=await R.bind(this)("ticket",Object.assign({exec:"consumed"},t||{}),{auth:true,fetchOptions:e});return n.list=n.list.map($e),n}async function gt(t){return R.bind(this)("register-ticket",Object.assign({exec:"reg"},t),{auth:true})}async function ft(t){return R.bind(this)("register-ticket",Object.assign({exec:"unreg"},t),{auth:true})}var Mr=3600;async function ce(){if(await this.__connection,this.session){let t=Math.floor(Date.now()/1e3),n=this.session.getIdToken().getExpiration();if(n<t+Mr){this.log("request:requesting new token",null);try{await $.bind(this)().getSession({refreshToken:!0}),this.log("request:received new tokens",{exp:this.session?.idToken?.payload?.exp,currentTime:t,expiresIn:n-t,token:this.session?.accessToken?.jwtToken,refreshToken:this.session?.refreshToken?.token});}catch(r){throw this.log("request:new token error",r),new a("User login is required.",{code:"INVALID_REQUEST"})}}else this.log("request:tokens",{exp:this.session.idToken.payload.exp,currentTime:t,expiresIn:n-t,token:this.session.accessToken.jwtToken,refreshToken:this.session.refreshToken.token});return this.session?.idToken?.jwtToken}else throw this.log("request:no session",null),te.bind(this)(),new a("User login is required.",{code:"INVALID_REQUEST"})}function ct(t,e){return new Promise((n,r)=>{e.refreshSession(t.getRefreshToken(),(i,s)=>{this.log("getSession:refreshSessionCallback",{refreshErr:i,refreshedSession:s}),i?(te.bind(this)(),r(i)):s.isValid()?n(s):(te.bind(this)(),r(new a("Invalid session.",{code:"INVALID_REQUEST"})));});})}function $(){if(!this.userPool)throw new a("User pool is missing",{code:"INVALID_REQUEST"});let t=()=>{let s=L.getSignInUserSession().getIdToken().payload||null,o=fe(s);return this.log("normalized user attribute",o),this.__user=o,o},e=async s=>new Promise((o,l)=>{this.log("getSession:option",s);let{refreshToken:u=false,skipUserUpdateEventTrigger:c=false}=s||{};if(u&&c&&(c=false),L=this.userPool.getCurrentUser(),!L){this.log("getSession:cognitoUser",L),te.bind(this)(),l(null);return}let d=g=>{let h=g.getIdToken().payload;if(this.log("getSession:respond:sessionAttribute",h),h["custom:service"]!==this.service)throw this.log("getSession:respond","invalid service, signing out"),te.bind(this)(),new a("Invalid session.",{code:"INVALID_REQUEST"});return this.session=g,t(),c||this._runOnUserUpdateListeners(this.user),this.session};L.getSession((g,h)=>{if(this.log("getSession:getSessionCallback",{err:g,session:h}),!h){te.bind(this)(),l(new a("Current session does not exist.",{code:"INVALID_REQUEST"}));return}if(g){ct.bind(this)(h,L).then(m=>o(d(m))).catch(l);return}let _=Math.floor(Date.now()/1e3),p=h.getIdToken(),y=p.getExpiration(),P=y<_;if(this.log("getSession:currentTime",_),this.log("getSession:idTokenExp",y),this.log("getSession:isExpired",P),this.log("getSession:existingBearerToken",this.bearerToken),this.bearerToken=p.getJwtToken(),P||u||!h.isValid())ct.bind(this)(h,L).then(m=>o(d(m))).catch(l);else try{o(d(h));}catch(m){l(m);}});}),n=(s,o)=>{let l=o||s.includes(this.service+"-")?s:this.service+"-"+F.hash(s);return {cognitoUser:new amazonCognitoIdentityJs.CognitoUser({Username:l,Pool:this.userPool}),cognitoUsername:l}};return {getSession:e,authenticateUser:(s,o,l=false,u=false)=>new Promise((c,d)=>{this.__request_signup_confirmation=null,this.__disabledAccount=null;let g=n(s,l),h=g.cognitoUsername,_=new amazonCognitoIdentityJs.AuthenticationDetails({Username:h,Password:o});g.cognitoUser.authenticateUser(_,{newPasswordRequired:(p,y)=>{this.__disabledAccount=null,this.__request_signup_confirmation=h,p["custom:signup_ticket"]==="PASS"||p["custom:signup_ticket"]==="MEMBER"||p["custom:signup_ticket"]==="OIDPASS"?g.cognitoUser.completeNewPasswordChallenge(o,{},{onSuccess:P=>{L=g.cognitoUser,e().then(m=>c(this.user));},onFailure:P=>{d(new a(P.message||"Failed to authenticate user.",{code:P.code}));}}):d(new a("User's signup confirmation is required.",{code:"SIGNUP_CONFIRMATION_NEEDED"}));},onSuccess:p=>e({skipUserUpdateEventTrigger:true}).then(y=>{this.__disabledAccount=null,this._runOnLoginListeners(this.user),this._runOnUserUpdateListeners(this.user),c(this.user);}),onFailure:p=>{let y=[],{parsed:P,code:m}=Te(p),I=typeof p?.message=="string"?p.message:"";if(m==="NotAuthorizedException"?I.includes("User is disabled.")?(this.__disabledAccount=h,y=["This account is disabled.","USER_IS_DISABLED"]):u?y=["The account already exists.","ACCOUNT_EXISTS"]:y=["Incorrect username or password.","INCORRECT_USERNAME_OR_PASSWORD"]:m==="UserNotFoundException"?y=["Incorrect username or password.","INCORRECT_USERNAME_OR_PASSWORD"]:m==="UserNotConfirmedException"?(this.__request_signup_confirmation=h,y=["User's signup confirmation is required.","SIGNUP_CONFIRMATION_NEEDED"]):(m==="TooManyRequestsException"||m==="LimitExceededException")&&(y=["Too many attempts. Please try again later.","REQUEST_EXCEED"]),P.code==="SIGNUP_CONFIRMATION_NEEDED"&&(this.__request_signup_confirmation=h),y.length){let x=y[1],T=y[0];d(new a(T,{code:x,cause:p}));}else d(P);}});}),createCognitoUser:n,signup:(s,o,l)=>new Promise((u,c)=>{this.userPool.signUp(s,o,l,null,(d,g)=>{if(d){let{parsed:h,code:_}=Te(d),p=[];_==="UsernameExistsException"?p=["The account already exists.","EXISTS"]:_==="InvalidPasswordException"?p=["Invalid password. Password must be at least 6 characters.","INVALID_PARAMETER"]:_==="InvalidParameterException"?p=[h.message||"Invalid parameter.","INVALID_PARAMETER"]:_==="TooManyRequestsException"||_==="LimitExceededException"?p=["Too many attempts. Please try again later.","REQUEST_EXCEED"]:_==="CodeDeliveryFailureException"?p=["Failed to deliver verification code.","CODE_DELIVERY_FAILURE"]:_==="UserLambdaValidationException"&&(p=[h.message||"Signup validation failed.","INVALID_REQUEST"]),p.length?c(new a(p[0],{code:p[1],cause:d})):c(h);return}u(g);});})}}function Te(t){let e=typeof t?.code=="string"&&t.code.trim()?t.code.trim():"ERROR",r=((typeof t?.message=="string"?t.message:typeof t=="string"?t:"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 a(o,{code:s,cause:t}),code:e}}async function ht(t){await this.__authConnection;let e=t?.refreshToken||false;if(!e)return this.user;try{return await $.bind(this)().getSession(Object.assign({skipUserUpdateEventTrigger:!e,refreshToken:e},t)),this.user}catch{return null}}async function pt(t){await this.__connection,t=f.Params(t,{token:"string",id:"string",merge:o=>{if(o===void 0)return false;if(typeof o=="string")return [o];if(Array.isArray(o)){for(let l of o)if(typeof l!="string")throw new a('"merge" array items should be type: <string>.',{code:"INVALID_PARAMETER"})}if(typeof o!="boolean"&&!Array.isArray(o))throw new a('"merge" should be type: <boolean | string[]>.',{code:"INVALID_PARAMETER"});return o},template:o=>{if(typeof o!="object"||o===null)throw new a('"template" should be type: <object>.',{code:"INVALID_PARAMETER"});if(o.welcome!==void 0&&(typeof o.welcome!="string"||!o.welcome))throw new a('"template.welcome" should be a non-empty <string> (template message_id).',{code:"INVALID_PARAMETER"});return o}});let e={token:t.token,id:t.id,merge:t.merge};t.template?.welcome&&(e.template_welcome=t.template.welcome);let n=await R.bind(this)("openid-logger",e),r=n.logger.split("#"),i=this.service+"-"+r[0],s=r[1];return {userProfile:await $.bind(this)().authenticateUser(i,s,true,true),openid:n.openid}}function qr(t){let e=typeof globalThis<"u"?globalThis:void 0;if(e?.Buffer)return e.Buffer.from(t,"base64").toString("utf8");if(typeof atob=="function"){let n=atob(t),r=new Uint8Array(n.length);for(let i=0;i<n.length;i++)r[i]=n.charCodeAt(i);return typeof TextDecoder<"u"?new TextDecoder().decode(r):n}throw new Error("No base64 decoder available in this environment")}function Fr(t){let e=t.split(".");if(e.length!==3)throw new Error("Invalid JWT format");let r=e[1].replace(/-/g,"+").replace(/_/g,"/"),i=qr(r);return JSON.parse(i)}async function mt(t){await this.__authConnection,this.log("loginWithToken:params",t),t=f.Params(t,{idToken:"string",accessToken:"string",refreshToken:"string"},["idToken"]);let e=Fr(t.idToken);if(this.log("loginWithToken:idTokenPayload",e),e["custom:service"]!==this.service)throw new a("Token does not belong to this service.",{code:"INVALID_REQUEST"});let n=Math.floor(Date.now()/1e3);if(e.exp&&e.exp<n)throw new a("Token has expired.",{code:"INVALID_REQUEST"});if(this.__user=fe(e),this.session=null,t.accessToken&&t.refreshToken)try{if(this.session=new amazonCognitoIdentityJs.CognitoUserSession({IdToken:new amazonCognitoIdentityJs.CognitoIdToken({IdToken:t.idToken}),AccessToken:new amazonCognitoIdentityJs.CognitoAccessToken({AccessToken:t.accessToken}),RefreshToken:new amazonCognitoIdentityJs.CognitoRefreshToken({RefreshToken:t.refreshToken})}),this.log("loginWithToken:session",this.session),this.log("loginWithToken:CognitoUser",amazonCognitoIdentityJs.CognitoUser),this.log("loginWithToken:userPool",this.userPool),amazonCognitoIdentityJs.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),L=new amazonCognitoIdentityJs.CognitoUser(r),L.setSignInUserSession(this.session),this.log("loginWithToken:cognitoUserRestored",{cognitoUserType:typeof L,cognitoUserKeys:Object.keys(L||{}),cognitoUser:L});}}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 V(){return await this.__connection,this.__user?.service===this.service?this.__user?.owner===this.host:(await he.bind(this)(),false)}async function te(t=false){let e=null;L&&(t?e=new Promise((r,i)=>{L.globalSignOut({onSuccess:s=>{this.log("globalSignOut:success",s),r(s);},onFailure:s=>{this.log("globalSignOut:error",s),i(s);}});}):L.signOut());let n={session:null,__startKeyHistory:{},__cached_requests:{},__user:null};e&&(e=await e);for(let r in n)this[r]=n[r];return this._runOnUserUpdateListeners(null),this._runOnLoginListeners(null),e}async function he(t){await this.__connection;let{data:e}=U(t);return await te.bind(this)(e?.global),"SUCCESS: The user has been logged out."}async function _t(){if(!this.__request_signup_confirmation)throw new a("Least one login attempt is required.",{code:"INVALID_REQUEST"});return await R.bind(this)("confirm-signup",{username:this.__request_signup_confirmation})}async function bt(t=false){if(typeof t=="string")t=f.Url(t);else if(typeof t!="boolean")throw new a("Argument should be type: <boolean | string>.",{code:"INVALID_REQUEST"});if(!this.__disabledAccount)throw new a("Least one signin attempt of disabled account is required.",{code:"INVALID_REQUEST"});return await R.bind(this)("recover-account",{username:this.__disabledAccount,redirect:t}),"SUCCESS: Recovery e-mail has been sent."}async function je(t){let e=f.Params(t,{username:"string",email:"string",password:"string"},["password"]);if(await this.__authConnection,e.email)try{f.Email(e.email);}catch{e.username=e.email,delete e.email;}if(!e.username&&!e.email)throw new a('Least one of "username" or "email" is required.',{code:"INVALID_PARAMETER"});return await $.bind(this)().authenticateUser(e.username||e.email,e.password)}async function yt(t,e){await this.__authConnection;let n={username:"string",password:c=>f.Password(c),email:c=>f.Email(c),name:"string",address:c=>{if(!c)return "";if(typeof c=="string")return c;if(typeof c=="object")return JSON.stringify(c)},gender:"string",birthdate:c=>c?f.Birthdate(c):"",phone_number:c=>c?f.PhoneNumber(c):"",email_public:["boolean",()=>false],address_public:["boolean",()=>false],gender_public:["boolean",()=>false],birthdate_public:["boolean",()=>false],phone_number_public:["boolean",()=>false],access_group:"number",misc:"string",picture:c=>c?f.Url(c):"",profile:c=>c?f.Url(c):"",family_name:"string",given_name:"string",middle_name:"string",nickname:"string",website:c=>c?f.Url(c):""},r=f.Params(t||{},n,["email","password"]);await he.bind(this)(),e=f.Params(e||{},{email_subscription:c=>{if(typeof c!="boolean")throw new a('"option.email_subscription" should be type: <boolean>.',{code:"INVALID_PARAMETER"});if(!e?.signup_confirmation)throw new a('"option.signup_confirmation" is required for email subscription.',{code:"INVALID_PARAMETER"});return c},signup_confirmation:c=>{let d=c;if(typeof c=="string")d=f.Url(c);else if(typeof c=="boolean")d=c;else throw new a('"option.signup_confirmation" should be type: <string | boolean>.',{code:"INVALID_PARAMETER"});if(d&&!r.email)throw new a('"email" is required for signup confirmation.',{code:"INVALID_PARAMETER"});return d},login:c=>{if(typeof c=="boolean"){if(e.signup_confirmation&&c)throw new a('"login" is not allowed when "option.signup_confirmation" is true.',{code:"INVALID_PARAMETER"});return c}throw new a('"option.login" should be type: boolean.',{code:"INVALID_PARAMETER"})},template:c=>{if(typeof c!="object"||c===null)throw new a('"option.template" should be type: <object>.',{code:"INVALID_PARAMETER"});if(c.signup_confirmation!==void 0){if(typeof c.signup_confirmation!="string"||!c.signup_confirmation)throw new a('"option.template.signup_confirmation" should be a non-empty <string> (template message_id).',{code:"INVALID_PARAMETER"});if(!e?.signup_confirmation)throw new a('"option.signup_confirmation" is required when "option.template.signup_confirmation" is set.',{code:"INVALID_PARAMETER"})}if(c.welcome!==void 0&&(typeof c.welcome!="string"||!c.welcome))throw new a('"option.template.welcome" should be a non-empty <string> (template message_id).',{code:"INVALID_PARAMETER"});return c}});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 a('"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=$.bind(this)().createCognitoUser(r.username||r.email);for(let c of ["email_public","address_public","gender_public","birthdate_public","phone_number_public"])r[c]=r[c]?"1":"0";r.access_group&&(r.access_group=r.access_group.toString());let o=(await R.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,template_confirmation:e?.template?.signup_confirmation||"",template_welcome:e?.template?.welcome||""})).split(":"),l=o.slice(1).join(":"),u=[new amazonCognitoIdentityJs.CognitoUserAttribute({Name:"custom:signup",Value:o[0]}),new amazonCognitoIdentityJs.CognitoUserAttribute({Name:"locale",Value:l.split("#")[1]}),new amazonCognitoIdentityJs.CognitoUserAttribute({Name:"custom:signup_ticket",Value:l})];for(let c in n){let d=["email_public","address_public","gender_public","birthdate_public","phone_number_public","misc","service","owner"];r[c]!==""&&(c==="username"||c==="password"||c==="access_group"||(d.includes(c)?u.push(new amazonCognitoIdentityJs.CognitoUserAttribute({Name:"custom:"+c,Value:r[c]})):u.push(new amazonCognitoIdentityJs.CognitoUserAttribute({Name:c,Value:r[c]}))));}return await $.bind(this)().signup(s.cognitoUsername,r.password,u),r.signup_confirmation?(L=s.cognitoUser,this.__request_signup_confirmation=s.cognitoUsername,"SUCCESS: The account has been created. User's signup confirmation is required."):i?je.bind(this)({email:r.username||r.email,password:r.password}):"SUCCESS: The account has been created."}async function wt(){await this.__connection;let t=await R.bind(this)("remove-account",{disable:this.__user.user_id},{auth:true});return await he.bind(this)(),t}async function Et(t){await this.__connection;let e=f.Params(t,{email:i=>f.Email(i),code:["number","string"],new_password:i=>f.Password(i)},["email","code","new_password"]),n=e.code,r=e.new_password;return typeof n=="number"&&(n=n.toString()),new Promise(async(i,s)=>{$.bind(this)().createCognitoUser(e.email).cognitoUser.confirmPassword(n,r,{onSuccess:l=>{i("SUCCESS: New password has been set.");},onFailure:l=>{s(new a(l?.message||"Failed to reset password.",{code:l?.code||"ERROR",cause:l}));}});})}async function Rt(t,e,n){await this.__connection;let r;if(!L)throw new a("The user has to be logged in.",{code:"INVALID_REQUEST"});if(t==="email"||t==="phone_number"){if(!this.__user.hasOwnProperty(t))throw new a(`No ${t==="email"?"e-mail":"phone number"} to verify`,{code:"INVALID_REQUEST"});if(this.__user?.[`${t}_verified`])return `SUCCESS: "${t}" is verified.`;r=(e?f.Params(e,{code:"string"}):{}).code||"";}else return;let i,s=n?.template?.verification;if(s!==void 0){if(typeof s!="string"||!s)throw new a('"template.verification" should be a non-empty <string> (template message_id).',{code:"INVALID_PARAMETER"});i={template_verification:s};}return new Promise((o,l)=>{let u={onSuccess:c=>{r?$.bind(this)().getSession({refreshToken:true}).then(()=>{this.__user&&(this.__user[t+"_verified"]=true),o(`SUCCESS: "${t}" is verified.`);}).catch(d=>{l(d);}):o("SUCCESS: Verification code has been sent.");},onFailure:c=>{l(new a(c.message||"Failed to request verification code.",{code:c?.code}));}};r?L?.verifyAttribute(t,r,u):(u.inputVerificationCode=null,L?.getAttributeVerificationCode(t,u,i));})}function At(t,e){return Rt.bind(this)("phone_number",t,e)}function It(t,e){return Rt.bind(this)("email",t,e)}async function Tt(t,e){await this.__connection;let n=f.Params(t,{email:s=>f.Email(s)},["email"]),r,i=e?.template?.verification;if(i!==void 0){if(typeof i!="string"||!i)throw new a('"template.verification" should be a non-empty <string> (template message_id).',{code:"INVALID_PARAMETER"});r={template_verification:i};}return new Promise(async(s,o)=>{$.bind(this)().createCognitoUser(n.email).cognitoUser.forgotPassword({onSuccess:u=>{s("SUCCESS: Verification code has been sent.");},onFailure:u=>{let{parsed:c,code:d}=Te(u),g={UserNotFoundException:"NOT_EXISTS",InvalidParameterException:"INVALID_PARAMETER",NotAuthorizedException:"INVALID_REQUEST",LimitExceededException:"REQUEST_EXCEED",TooManyRequestsException:"REQUEST_EXCEED",CodeDeliveryFailureException:"CODE_DELIVERY_FAILURE"}[d]||c.code||d||"ERROR";o(new a(c.message,{code:g,cause:u}));}},r);})}async function Pt(t){if(await this.__connection,!this.session)throw new a("User login is required.",{code:"INVALID_REQUEST"});let e=f.Params(t,{current_password:"string",new_password:"string"});if(!e?.current_password)throw new a('"current_password" is required to change password.',{code:"INVALID_PARAMETER"});if(!e?.new_password)throw new a('"new_password" is required to change password.',{code:"INVALID_PARAMETER"});return f.Password(e.current_password),f.Password(e.new_password),new Promise((n,r)=>{L.changePassword(e.current_password,e.new_password,(i,s)=>{if(i){if(i?.code==="InvalidParameterException")r(new a("Invalid password parameter.",{code:"INVALID_PARAMETER"}));else if(i?.code==="NotAuthorizedException")r(new a("Incorrect password.",{code:"INVALID_REQUEST"}));else if(i?.code==="TooManyRequestsException"||i?.code==="LimitExceededException")r(new a("Too many attempts. Please try again later.",{code:"REQUEST_EXCEED"}));else {let{parsed:o}=Te(i);r(o);}return}n("SUCCESS: Password has been changed.");});})}async function St(t){if(await this.__connection,!this.session)throw new a("User login is required.",{code:"INVALID_REQUEST"});let e=f.Params(t||{},{user_id:i=>f.UserId(i),email:i=>f.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?f.Birthdate(i):"",phone_number:i=>i?f.PhoneNumber(i):"",email_public:"boolean",phone_number_public:"boolean",address_public:"boolean",gender_public:"boolean",birthdate_public:"boolean",misc:"string",picture:i=>i?f.Url(i):"",profile:i=>i?f.Url(i):"",family_name:"string",given_name:"string",middle_name:"string",nickname:"string",website:i=>i?f.Url(i):""});if(e&&typeof e=="object"&&!Object.keys(e).length)return this.user;e.email&&(e.preferred_username=this.service+"-"+F.hash(e.email));let n=[["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 n)if(e[i[0]]&&!this.__user[i[1]])throw new a(`${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 R.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 amazonCognitoIdentityJs.CognitoUserAttribute({Name:s,Value:e[s]}));return await new Promise((s,o)=>{L?.updateAttributes(i,(l,u)=>{l&&o([l?.code||l?.name,l?.message||"Failed to update user settings."]),s(u);});}),await $.bind(this)().getSession({refreshToken:true}),this.user}return this.user}async function kt(t,e){t=U(t).data,t||(t={searchFor:"timestamp",condition:">",value:0},e||(e={}),e.ascending=false),await this.__connection;let n={user_id:i=>Array.isArray(i)?i.map(s=>f.UserId(s)):f.UserId(i),email:"string",phone_number:"string",locale:i=>{if(typeof i!="string"||typeof i=="string"&&i.length>5)throw new a('Value of "locale" should be a country code.',{code:"INVALID_PARAMETER"});return i},name:"string",address:"string",gender:"string",birthdate:i=>f.Birthdate(i),subscribers:"number",timestamp:"number",access_group:"number",approved:"string"},r=["searchFor","value"];if(t=f.Params(t,{searchFor:["user_id","name","email","phone_number","address","gender","birthdate","locale","subscribers","timestamp","access_group","approved"],condition:[">",">=","=","<","<=","gt","gte","eq","lt","lte",()=>"="],value:i=>{let s=n[t.searchFor];if(typeof s=="function")return s(i);if(typeof i!==s)throw new a(`Value does not match the type of "${t.searchFor}" index.`,{code:"INVALID_PARAMETER"});return i},range:i=>{let s=n[t.searchFor];if(typeof s=="function")return s(i);if(typeof i!==s)throw new a(`Range does not match the type of "${t.searchFor}" index.`,{code:"INVALID_PARAMETER"});return i}},r),t?.condition&&t?.condition!=="="&&t.hasOwnProperty("range"))throw new a("Conditions does not apply on range search.",{code:"INVALID_PARAMETER"});if(t.searchFor==="user_id"&&(t.condition!=="="||t.range))throw new a(`Conditions are not allowed on "${t.searchFor}"`,{code:"INVALID_PARAMETER"});if(typeof t?.value=="string"&&!t?.value)throw new a("Value should not be an empty string.",{code:"INVALID_PARAMETER"});if(typeof t?.searchFor=="string"&&!t?.searchFor)throw new a('"searchFor" should not be an empty string.',{code:"INVALID_PARAMETER"});return R.bind(this)("get-users",t,{auth:true,fetchOptions:e})}async function xt(t){await this.__connection;let e=await R.bind(this)("last-verified-email",t,{auth:true});return e.includes("SUCCESS")?(await $.bind(this)().getSession({refreshToken:true}),this.user):e}async function vt(t){return await this.__connection,t=f.Params(t,{username:f.Email,redirect:f.Url},["username"]),await R.bind(this)("request-username-change",t,{auth:true})}var le=null,Nt=typeof SubmitEvent<"u",$r=typeof HTMLFormElement<"u",me=j(),Be=0;function Ut(t){if(!t)return null;let e=Number(t);if(Number.isFinite(e))return Math.max(0,e*1e3);let n=Date.parse(t);return Number.isNaN(n)?null:Math.max(0,n-Date.now())}function Ke(t,e){return e>0?t/e*100:0}var Dt=t=>{let{auth:e,type:n,endpoints:r,stable:i}=t,s=r[0],o=r[1];if(Be++,n==="admin"){let l=Object.entries(s).filter(([u,c])=>u.includes(e?"_private":"_public")&&u!=="get_users_private"&&u!=="service_public"&&typeof c=="string").map(([,u])=>u);if(!l.length)throw new a("No available admin gateways.",{code:"INVALID_REQUEST"});return l[Be%l.length]}if(n==="record"){let l=Object.entries(o).filter(([u,c])=>u.includes(e?"record_private":"record_public")&&typeof c=="string").map(([,u])=>u);if(!l.length)throw new a("No available record gateways.",{code:"INVALID_REQUEST"});return i?l[0]:l[Be%l.length]}throw new a("Invalid gateway type.",{code:"INVALID_REQUEST"})};async function jr(t,e,n){let r=await Promise.all([this.admin_endpoint,this.record_endpoint]),i=r[0],s=r[1],o=t.split("?"),l=o.length>1?"?"+o[1]:"";switch(t=o[0],t){case "get-users":return i.get_users_private+t+l;case "service":return i.service_public+t+l;case "get-newsletters":case "get-public-newsletters":case "subscribe-newsletter":case "subscribe-public-newsletter":case "signupkey":case "admin-newsletter-request":case "admin-signup":case "confirm-signup":case "openid-logger":case "block-account":case "admin-edit-profile":case "remove-account":case "post-secure":case "recover-account":case "mock":case "grant-access":case "last-verified-email":case "ticket":case "register-ticket":case "get-newsletter-subscription":case "request-username-change":case "send-inquiry":case "register-newsletter-group":case "newsletter-group-endpoint":case "invitation-list":case "csr":case "csr-poll":case "csr-cancel":return Dt.bind(this)({auth:e,type:"admin",endpoints:r})+t+l;case "post-record":return (e?s.post_private:s.post_public)+t+l;case "get-records":return (e?s.get_private:s.get_public)+t+l;case "del-files":case "del-records":return s.del_private+t+l;case "store-subscription":case "get-vapid-public-key":case "push-notification":case "delete-subscription":case "subscription":case "get-subscription":case "get-table":case "get-tag":case "get-uniqueid":case "get-index":case "get-signed-url":case "extract-file-text":case "grant-private-access":case "request-private-access-key":case "get-ws-group":case "check-schema":case "get-feed":case "castspell":case "dopamine":case "getspell":return Dt.bind(this)({auth:e,type:"record",endpoints:r,stable:n})+t+l;default:return f.Url(t)+l}}var pe={};function Ct(){le&&(le.terminate(),le=null);}async function R(t,e=null,n,r){this.log("request",{url:t,data:e,options:n,_etc:r||{}}),n=n||{};let{auth:i=false,method:s="post",bypassAwaitConnection:o=false}=n;s=s.toUpperCase();let l=null,u=e?.service||this.service,c=e?.owner||this.owner,d=null,g=await jr.bind(this)(t,!!i,!!n.stableGateway);if(!o&&(l=await this.__connection,!l))throw new a("Invalid connection. The service could have been disabled, or has a restricted CORS.",{code:"INVALID_REQUEST"});let h=n?.tokenHeaders?.idToken===true;(i||h)&&(d=await ce.bind(this)());let _={},{fetchMore:p=false,progress:y}=n?.fetchOptions||{};if(n?.fetchOptions&&Object.keys(n.fetchOptions).length){for(let k of ["limit","startKey","ascending"])if(n.fetchOptions.hasOwnProperty(k)){if(k==="startKey"&&n.fetchOptions[k]===null)continue;_[k]=n.fetchOptions[k];}_=f.Params(_,{limit:k=>{if(typeof k!="number")throw new a("Fetch limit should be a number.",{code:"INVALID_REQUEST"});if(k>1e3)throw new a("Fetch limit should be below 1000.",{code:"INVALID_REQUEST"});return k},startKey:k=>k,ascending:"boolean"});}let P=r?.ignoreService?{}:{service:u,owner:c};Object.assign(P,_),e=U(e).data,e?e&&typeof e=="object"&&(e=Object.assign(P,e)):e=P;let m=`${s}:${i?"auth":"public"}:${t}`,I=(()=>{if(e&&typeof e=="object"&&Object.keys(e).length&&!(me&&e instanceof FormData)){let k=function(D){return typeof D=="object"&&D!==null?Object.keys(D).sort().reduce((N,O)=>(typeof D[O]=="object"&&D[O]!==null?N[O]=k(D[O]):N[O]=D[O],N),{}):D};return F.hash(m+"/"+JSON.stringify(k(e)))}return F.hash(m+"/"+u)})(),{requestKey:x,requestKeyWithStartKey:T}=Br.bind(this)({params:e,url:t,fetchMore:p,hashedParams:I});if(!x||x&&typeof x=="object")return x;if(this.log("requestKey",T),typeof T=="string"&&pe[T]instanceof Promise)return this.log("request:returning pending",T),pe[T];let v={Accept:"*/*"};if(Object.prototype.hasOwnProperty.call(n,"contentType")&&n.contentType!==void 0){let k=n.contentType===null?"application/x-www-form-urlencoded":n.contentType;k&&(v["Content-Type"]=k);}else v["Content-Type"]="application/json";if(d&&(v.Authorization=d),n?.tokenHeaders){let k=(O,ir)=>typeof O=="string"?O:O===true?ir:null,D=k(n.tokenHeaders.accessToken,this.session?.accessToken?.jwtToken||null),N=k(n.tokenHeaders.idToken,this.bearerToken||this.session?.idToken?.jwtToken||d||null);D&&(v["X-Access-Token"]=D),N&&(v["X-Id-Token"]=N);}let W={public_identifier:this.__public_identifier,service:u,owner:c};v["Content-Meta"]=JSON.stringify(W),n.revalidate&&(v["Cache-Control"]="no-cache",v.Pragma="no-cache");let M={headers:v};if(n?.responseType&&(M.responseType=n.responseType),s==="GET"){if(e){let k=[];if(me&&e instanceof FormData?k=Array.from(e.entries()).map(([D,N])=>{let O=typeof N=="string"?N:N.name;return encodeURIComponent(D)+"="+encodeURIComponent(O)}):k=Object.keys(e).map(D=>{let N=e[D];return typeof N!="string"&&(N=JSON.stringify(N)),encodeURIComponent(D)+"="+encodeURIComponent(N)}),k.length){let D=g.includes("?")?g.endsWith("?")||g.endsWith("&")?"":"&":"?";g+=D+k.join("&");}}M.body=null;}else if(me&&e instanceof FormData)M.body=e;else if(v["Content-Type"]==="application/x-www-form-urlencoded"&&e&&typeof e=="object"){let k=new URLSearchParams;for(let D of Object.keys(e)){let N=e[D];k.append(D,typeof N=="string"?N:JSON.stringify(N));}M.body=k.toString();}else typeof e=="string"?M.body=e:M.body=e?JSON.stringify(e):null;if(M.method=s,le===null){let k={batchSize:this.requestBatchSize,breakWhenError:false,onProgress:D=>{this.onBatchProcess.forEach(N=>N(D));}};le=new mn__default.default(k);}return this.log("request-opt",M),new Promise((k,D)=>{le.add([async()=>{let N=Lt.bind(this)(g,M,y);pe[T]=N;try{let O=Kr.bind(this)({hashedParam:x,requestKeyWithStartKey:T,url:t,fetched:await N});return delete pe[T],this.log("request:end",O),k(O),O}catch(O){throw delete pe[T],this.log("request:err",O),D(O),O}}]);})}function Br(t){let{params:e={},url:n,fetchMore:r=false,hashedParams:i}=t||{};if(e.startKey){if(!(typeof e.startKey=="object"&&Object.keys(e.startKey).length)&&e.startKey!=="start"&&e.startKey!=="end")throw new a(`"${e.startKey}" is invalid startKey key.`,{code:"INVALID_PARAMETER"});e.startKey==="start"&&(r=false,delete e.startKey);}if(!r){if(this.__cached_requests?.[n]?.[i]&&delete this.__cached_requests[n][i],this.__startKeyHistory?.[n]?.[i]){if(Array.isArray(this.__startKeyHistory[n][i])&&this.__startKeyHistory[n][i].length)for(let u of this.__startKeyHistory[n][i]){let c=i+F.hash(u);this.__cached_requests?.[n]&&this.__cached_requests?.[n]?.[c]&&delete this.__cached_requests[n][c];}delete this.__startKeyHistory[n][i];}return {requestKeyWithStartKey:i,requestKey:i}}if(!Array.isArray(this.__startKeyHistory?.[n]?.[i]))return {requestKeyWithStartKey:i,requestKey:i};let s=this.__startKeyHistory[n][i],o=s[s.length-1],l=i;if(o){if(o==="end")return {requestKey:{list:[],startKey:"end",endOfList:true,startKeyHistory:s},requestKeyWithStartKey:l};l+=F.hash(o),e.startKey=JSON.parse(o);}return this.__cached_requests?.[n]?.[l]?{requestKey:this.__cached_requests[n][l],requestKeyWithStartKey:l}:{requestKeyWithStartKey:l,requestKey:i}}function Lt(t,e,n){return new Promise((r,i)=>{let s=new XMLHttpRequest;s.open(e.method||"GET",t);for(var o in e.headers||{})s.setRequestHeader(o,e.headers[o]);e.responseType&&(s.responseType=e.responseType),s.onload=()=>{if(s.status<400)if(e.responseType=="json"||e.responseType=="blob")r(s.response);else {let l=s.responseText;try{l=JSON.parse(l);}catch{}r(l);}else if(s.status===429){let l=s.getResponseHeader("Retry-After"),u=Ut(l);u!==null?setTimeout(()=>{Lt(t,e,n).then(r,i);},u):i("Too many requests");}else {let l=s.status,u=["INVALID_CORS","INVALID_REQUEST","SERVICE_DISABLED","INVALID_PARAMETER","ERROR","EXISTS","NOT_EXISTS"],c=e.responseType=="blob"?s.response:s.responseText;try{c=JSON.parse(c);}catch{}if(typeof c=="string"){let d=c.split(":"),g=d.splice(0,1)[0].trim(),h=d.join(":").trim();i(new a(h||c,{code:u.includes(g)?g:"ERROR"}));}else if(typeof c=="object"&&c?.message){let d=c?.code||(l?l.toString():null)||"ERROR",g=c.message,h=c?.cause;typeof g=="string"&&(g=g.trim()),i(new a(g,{cause:h,code:d}));}else i(c);}},s.onerror=()=>i("Network error"),s.onabort=()=>i("Aborted"),s.ontimeout=()=>i("Timeout"),typeof n=="function"&&(s.onprogress=l=>{n({status:"download",progress:Ke(l.loaded,l.total),loaded:l.loaded,total:l.total,abort:()=>s.abort()});},s.upload&&(s.upload.onprogress=l=>{n({status:"upload",progress:Ke(l.loaded,l.total),loaded:l.loaded,total:l.total,abort:()=>s.abort()});})),s.send(e.body);})}function Kr(t){let{hashedParam:e,requestKeyWithStartKey:n,url:r,fetched:i}=t;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][n]=i,Object.assign({startKeyHistory:this.__startKeyHistory[r][e]},i)}async function Se(t,e){await this.__connection;let{record_id:n,service:r=this.service,progress:i}=e;if(!n)throw new a('"record_id" is required.',{code:"INVALID_PARAMETER"});if(Nt&&t instanceof SubmitEvent&&(t=t.target),$r&&t instanceof HTMLFormElement&&(t=new FormData(t)),!me||!(t instanceof FormData))throw new a('"fileList" should be a FormData or HTMLFormElement.',{code:"INVALID_PARAMETER"});let o={reserved_key:ie(),service:r,request:"post"};e?.record_id&&(o.id=e.record_id);let l,u=(_,p,y)=>new Promise((P,m)=>{l=new XMLHttpRequest,l.open("POST",_),l.onload=()=>{let I=l.responseText;try{I=JSON.parse(I);}catch{}if(l.status>=200&&l.status<300)P(I);else if(l.status===429){let x=l.getResponseHeader("Retry-After"),T=Ut(x);T!==null?setTimeout(()=>{u(_,p,y).then(P,m);},T):m("Too many requests");}else m(I);},l.onerror=()=>m("Network error"),l.onabort=()=>m("Aborted"),l.ontimeout=()=>m("Timeout"),l.upload&&typeof y=="function"&&(l.upload.onprogress=y),l.send(p);});function c(_){let p="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";if(_===0)return p[0];let y="";for(;_>0;)y=p[_%62]+y,_=Math.floor(_/62);return y}let d=[],g=[],h=[];for(let[_,p]of t.entries()){if(!(p instanceof File))continue;let y=Object.assign({key:_+"/"+p.name,sizeKey:c(p.size),contentType:p.type||null},o),{fields:P=null,url:m,cdn:I}=await R.bind(this)("get-signed-url",y,{auth:!!this.__user});h.push(I);let x=new FormData;for(let T in P)x.append(T,P[T]);x.append("file",p);try{await u(m,x,typeof i=="function"?T=>i({status:"upload",progress:Ke(T.loaded,T.total),currentFile:p,completed:d,failed:g,loaded:T.loaded,total:T.total,abort:()=>l.abort()}):null),d.push(p);}catch{g.push(p);}}return {completed:d,failed:g,bin_endpoints:h}}var Pe={};function A(t){let{preventMultipleCalls:e=false}=t||{};return function(n,r,i){let s=i.value;i.value=function(...o){let l=o[0],u=true,c=null,d="",g={},h=false;if(Nt&&l instanceof SubmitEvent){l.preventDefault();let m=window.location.href;c=l.target;let I=new URL(c.action);d=I.href;let x=d?d.match(/(?<=\{).*?(?=\})/g):"";if(x)for(let T of x){if(!T)continue;let v=c.querySelector(`[name="${T}"]`);if(v)if(v.type==="file")for(let C=0;C<=v.files.length-1;C++)v.files[C]&&(g[T]||(g[T]=[]),g[T].push(new Promise((W,M)=>{let k=new FileReader;k.onload=function(){W(k.result);},k.readAsDataURL(v.files[C]),k.onerror=M;})));else d=d.replace(`{${T}}`,v.value);}c.getAttribute("action")===null?u=false:h=I.href===m;}let _=async m=>{if(d)for(let I in g)g[I].length&&(d=d.replace(`{${I}}`,(await Promise.all(g[I])).join(",")));return c&&u&&(window.sessionStorage.setItem(`${this.service}:${F.hash(d)}`,JSON.stringify(m)),h?window.location.replace(d):window.location.href=d),m},p,y=m=>{throw m instanceof a?m.name=r+"()":m=m instanceof Error?m:new a(m,{name:r+"()"}),m},P=async()=>{try{if(p=s.bind(this)(...o),p instanceof Promise){let m=await p;return _(m)}return _(p)}catch(m){throw y(m)}};if(e){let m=`${r}:${this?.__public_identifier||""}:${this?.service||""}:${this?.owner||""}`;return Pe?.[m]||(Pe[m]=P().finally(()=>{delete Pe[m];})),Pe[m]}return P()};}}async function Ot(){await this.__connection;let t=`${this.service}:${F.hash(window.location.href.split("?")[0])}`,e=window.sessionStorage.getItem(t);if(window.sessionStorage.removeItem(t),e!==null){try{e=JSON.parse(e);}catch{}return e}return null}var Qr=256,Hr=256,Wr=256,Mt=256,Jr="\u{10FFFF}",zr=/[\u0000-\u001F\u007F]|\u{10FFFF}/u,Gr={"/":"%2F","!":"%21","*":"%2A","#":"%23"},Xr={"%2F":"/","%21":"!","%2A":"*","%23":"#"};function Zr(t){return t.replace(/%/g,"%25").replace(/[\/!*#]/g,n=>Gr[n]||n)}function K(t){return typeof t!="string"?t:t.replace(/%(2F|21|2A|23)/gi,n=>{let r=n.toUpperCase();return Xr[r]||n}).replace(/%25/gi,"%")}function J(t,e,n={}){let{allowEmpty:r=false,maxLength:i,blockKeyDelimiters:s=false,disallowLeadingDollar:o=false,onlyAlphanumeric:l=false}=n;if(typeof t!="string")throw new a(`"${e}" should be type: <string>.`,{code:"INVALID_PARAMETER"});if(l&&/[^a-zA-Z0-9]/.test(t))throw new a(`"${e}" should only contain alphanumeric characters.`,{code:"INVALID_PARAMETER"});if(!r&&t.length===0)throw new a(`"${e}" is required.`,{code:"INVALID_PARAMETER"});if(i&&t.length>i)throw new a(`"${e}" should be <= ${i} characters.`,{code:"INVALID_PARAMETER"});if(zr.test(t)||t.includes(Jr))throw new a(`"${e}" cannot include control characters or unsupported sentinel characters.`,{code:"INVALID_PARAMETER"});if(s&&(t=Zr(t),i&&t.length>i))throw new a(`"${e}" should be <= ${i} characters. "/", "!", "*", "#" and "%" count as 3 characters each.`,{code:"INVALID_PARAMETER"});if(o&&t.startsWith("$"))throw new a(`"${e}" cannot start with "$".`,{code:"INVALID_PARAMETER"});return t}function ue(t,e="table.name",n={}){return J(t,e,{allowEmpty:n.allowEmpty===true,maxLength:Qr,blockKeyDelimiters:true})}function xe(t,e="tag",n={}){return J(t,e,{allowEmpty:n.allowEmpty===true,maxLength:Hr,blockKeyDelimiters:true})}function _e(t,e="index.name",n={}){return J(t,e,{allowEmpty:n.allowEmpty===true,maxLength:Wr,blockKeyDelimiters:true,disallowLeadingDollar:true})}function qt(t,e="index.value"){return J(t,e,{allowEmpty:true,maxLength:Mt})}function Qe(t){return typeof t=="string"&&t.slice(-1)==="."}function He(t,e){return J(t,e,{allowEmpty:true,maxLength:Mt,blockKeyDelimiters:true})}function Ft(t){if(!t.record_id&&!t.unique_id)return null;let e={};return t?.service&&(e.service=t.service),t?.owner&&(e.owner=t.owner),t?.record_id?e.record_id=J(t.record_id,"record_id",{allowEmpty:false,onlyAlphanumeric:true}):t?.unique_id&&(e.unique_id=t.unique_id),e}function We(t){if(t===void 0)return 0;if(typeof t=="number"){if(t>99||t<0)throw new a('"table.access_group" value should be within a range of 0 ~ 99.',{code:"INVALID_REQUEST"})}else if(typeof t=="string"){if(t={private:"private",public:0,authorized:1,admin:99}[t],t===void 0)throw new a('"table.access_group" is invalid.',{code:"INVALID_PARAMETER"})}else throw new a('"table.access_group" should be type: <number | string>.',{code:"INVALID_PARAMETER"});if(!this.__user&&t)throw new a("Unsigned users have no access to records with access group.",{code:"INVALID_REQUEST"});return t}var ke=4503599627370496;function ve(t){if(typeof t=="number"){if(t>ke||t<-ke)throw new a(`Number value should be within range -${ke} ~ +${ke}`,{code:"INVALID_PARAMETER"});return t}if(typeof t=="boolean")return t;if(typeof t=="string")return qt(t,"index.value");throw new a('"index.value" should be type: <number | boolean | string>.',{code:"INVALID_PARAMETER"})}function Vt(t,e){if(!e.index||!("value"in e.index))throw new a('"index.value" is required.',{code:"INVALID_PARAMETER"});if(e.index.name==="$record_id")throw new a(`Cannot do "index.range" on ${e.index.name}`,{code:"INVALID_PARAMETER"});if(typeof e.index.value!=typeof t)throw new a('"index.range" type should match the type of "index.value".',{code:"INVALID_PARAMETER"});return typeof t=="string"?Qe(e.index.name)?He(t,"index.range"):qt(t,"index.range"):t}var De={},Yr=10080*60,ei=3600,$t=2;function ti(t,e){if(!e)return String($t);let n=Math.max(60,t-300)*1e3;return $t+"."+Math.floor(Date.now()/n)}function ni(t){if(!this.user?.user_id)return false;let e=t[6]==="**"?"**":parseInt(t[6]),n=this.user?.access_group??-1;return !(this.user.user_id!==t[3]&&(e==="**"||n<e))}async function ri(t){return typeof t=="string"?t:t&&typeof t.text=="function"?await t.text():await new Promise((e,n)=>{try{let r=new FileReader;r.onload=()=>e(r.result),r.onerror=()=>n(r.error||new Error("Failed to read blob")),r.readAsText(t);}catch(r){n(r);}})}async function de(t,e,n=false){let r={user_id:"",record_id:"",updated:0,uploaded:0,readonly:false,table:{name:"",access_group:0,subscription:{is_subscription_record:false,upload_to_feed:false,notify_subscribers:false,feed_referencing_records:false,notify_referencing_records:false}},referenced_count:0,source:{referencing_limit:null,prevent_multiple_referencing:false,can_remove_referencing_records:false,only_granted_can_reference:false},ip:"",bin:{}},i=false,s=[];function o(c){let d=c=="**"?"private":parseInt(c);return d=d==0?"public":d==1?"authorized":d==99?"admin":d,d}let l={ip:c=>{let d=c.split("#"),g=d[0];d.length>1&&(r.unique_id=d.slice(1).join("#")),g.slice(-1)==="R"?(r.readonly=true,g=g.slice(0,-1)):r.readonly=false,/^\d{1,3}-\d{1,3}-\d{1,3}-\d{1,3}$/.test(g)&&(g=g.split("-").join("."),i=true),r.ip=g;},rec:c=>{if(!c)return;r.record_id=c;let d=c.substring(0,c.length-9),g=B(d);r.uploaded=g;},usr:c=>{r.user_id=c;},tbl:c=>{if(c&&!r.table.name){let d=c.split("/");r.table.name=K(d[0]),r.table.access_group=o(d[2]),d?.[3]&&(r.table.subscription.is_subscription_record=true);}},usr_tbl:c=>{let d=c.split("/");r.user_id||(r.user_id=d[0]),r.table.name||(r.table.name=K(d[1]),r.table.access_group=o(d[3]),d?.[4]&&(r.table.subscription.is_subscription_record=true));},idx:c=>{if(!c)return;let d=c.split("!"),g=K(d.splice(0,1)[0]),h=ii("!"+d.join("!"));r.index={name:g,value:h};},ref:c=>{c&&(r.reference=c.split("/")[0]);},tags:c=>{r.tags=Array.isArray(c)?c.map(d=>K(d)):c;},upd:c=>{r.updated=c;},acpt_mrf:c=>{r.source.prevent_multiple_referencing=!c;},ref_limt:c=>{r.source.referencing_limit=c;},rfd:c=>{r.referenced_count=c;},bin:async c=>{let d={},g=r?.reference||null;if(Array.isArray(c)){let h=await Promise.all(c.map(async _=>{try{let p=_.split("/").slice(3).join("/"),y=p.split("/");if(y.length<12)return null;let P=y[y.length-1],m=y[10];if(m==="__data__"&&P==="__json__.json")return {isDataFile:!0,rawUrl:_};let I=y[9],x=y[8],T=o(y[6]),v=_,C=T!=="public"&&ni.call(this,y)?{expires:ei,browserCache:Yr}:null;if(T!=="public")try{v=await se.bind(this)(_,{dataType:"endpoint",_ref:g});}catch(M){console.error("Error getting signed url for private file:",M),v=_;}let W={access_group:T,filename:P,url:v,path:p,size:B(I),uploaded:B(x),getFile:(M,k)=>{let D={dataType:M||"download",progress:k,_ref:g},N=()=>se.bind(this)(v,Object.assign({},D,{_update:W}));return C?se.bind(this)(_,Object.assign({},D,C)).catch(()=>N()):N()}};return {pathKey:m,obj:W}}catch{return null}}));for(let _ of h)if(_&&!_.isDataFile){if(d[_.pathKey]){d[_.pathKey].push(_.obj);continue}d[_.pathKey]=[_.obj];}}r.bin=d;},prv_acs:c=>{for(let d in c)["notify_subscribers","upload_to_feed","feed_referencing_records","notify_referencing_records"].includes(d)?r.table.subscription[d]=c[d]:d==="referencing_index_restrictions"&&Array.isArray(c[d])?r.source[d]=c[d].map(h=>h&&typeof h=="object"&&typeof h.name=="string"?Object.assign({},h,{name:K(h.name)}):h):r.source[d]=c[d];},data:async c=>{if(c==="!D%{}"){r.data={};return}if(c==="!L%[]"){r.data=[];return}if(c&&typeof c=="object"&&!Array.isArray(c)&&typeof c.__data__=="string"&&Object.keys(c).length===1&&c.__data__.endsWith("/__data__/__json__.json")){let d=c.__data__,g=s.find(h=>h.endsWith(d))||null;if(g){if(n){r.data=c;return}try{let h=await se.bind(this)(g,{dataType:"blob",_ref:r.reference||null}),_=await ri(h);r.data=JSON.parse(_);}catch(h){console.error("Failed to fetch offloaded record data:",h),r.data=null;}return}}r.data=c;}};if(t.record_id)return t;if(Array.isArray(t.bin))for(let c of t.bin)try{if(typeof c!="string")continue;let d=c.split("/").slice(3);d.length>=12&&d[10]==="__data__"&&d[d.length-1]==="__json__.json"&&s.push(c);}catch{}let u=[];for(let c in l)if(t.hasOwnProperty(c)){let d=l[c](t[c]);d instanceof Promise&&u.push(d);}return i&&(r.user_id="anonymous:"+r.user_id),await Promise.all(u),r}function ii(t){let e=t.substring(3);switch(t.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 a("Value parse error.",{code:"PARSE_ERROR"})}default:return t}}async function jt(t){let{endpoints:e}=t;if(typeof e=="string"&&(e=[e]),!Array.isArray(e))throw new a('"endpoints" should be type: array | string.',{code:"INVALID_PARAMETER"});let n=await R.bind(this)("del-files",{endpoints:e,storage:"records"},{auth:true,method:"post"}),r=[];for(let i in n)r.push(de.bind(this)(n[i]));return Promise.all(r)}async function se(t,e){if(typeof t!="string")throw new a('"url" should be type: string.',{code:"INVALID_PARAMETER"});let n=t,r=t.split("?"),i=r.shift()||"",s=r.length?"?"+r.join("?"):"",o=f.Url(i);t=o+s;let l=false,u=o.split("/"),d=u[2].split("."),g=null;d.length===3&&d[1]==="skapi"&&(g=d[0],l=true);let h=u.slice(3),_=false;if(!l&&(h[0]==="auth"||h[0]==="publ"))try{f.UserId(h[2]),f.UserId(h[3]),_=h[0]=="auth",l=!0;}catch{throw new a("Invalid file url.",{code:"INVALID_PARAMETER"})}let p=g?null:h[1];if(e=f.Params(e,{expires:["number",()=>0],browserCache:["number",()=>0],refresh:["boolean",()=>false],dataType:["base64","blob","endpoint","text","info",()=>"download"],progress:["function","undefined",null],_ref:[null,"string"],_update:I=>I}),e?.dataType==="info")return {url:t,filename:h[h.length-1],fileKey:h[h.length-2],access_group:h[6]==="**"?"private":h[6]==="01"?"authorized":h[6]==="00"?"public":parseInt(h[6]),uploader:h[3],record_id:h[4]==="records"?h[5]:"N/A",filesize:B(h[9]),uploaded:B(h[8])};let y=t.split("/").slice(-1)[0],P=e.expires;if(P){if(!l)throw new a("Expires option can only be used on skapi cdn endpoints.",{code:"INVALID_PARAMETER"});if(P<0)throw new a('"config.expires" should be > 0. (seconds)',{code:"INVALID_PARAMETER"});let I={request:g?"get-host":"get",id:g||h[5],key:n.split("?")[0],expires:P};p&&(I.service=p);let x=e.browserCache,T={auth:true};if(x){if(x<0)throw new a('"config.browserCache" should be > 0. (seconds)',{code:"INVALID_PARAMETER"});T.method="get",T.stableGateway=true,I.browser_cache=x;let v=this.session?.idToken?.payload?.sub||this.user?.user_id;v&&(I.uid=v),I.nocache=ti(P,e.refresh);}t=(await R.bind(this)("get-signed-url",I,T)).url;}else if(_){let I=Math.floor(Date.now()/1e3);if(!this.bearerToken&&(!this.session?.idToken?.payload?.exp||this.session.idToken.payload.exp<I)){this.log("getFile:requesting new token",null);try{await $.bind(this)().getSession({refreshToken:!0}),this.log("getFile:received new tokens",{exp:this.session?.idToken?.payload?.exp,currTime:I,expiresIn:this.session?.idToken?.payload?.exp-I,token:this.session?.accessToken?.jwtToken,refreshToken:this.session?.refreshToken?.token});}catch(C){throw this.log("getFile:new token error",C),new a("User login is required.",{code:"INVALID_REQUEST"})}}let x=this.bearerToken||this.session?.idToken?.jwtToken;if(!x||!this.user?.user_id)throw new a("User login is required.",{code:"INVALID_REQUEST"});t+=`${t.includes("?")?"&":"?"}t=${encodeURIComponent(x)}`;let T=h[6]==="**"?"**":parseInt(h[6]),v=this.user?.access_group??-1;if(this.user.user_id!==h[3]&&(T==="**"||v<T)){let C=h[5];if(this.__private_access_key[C]&&typeof this.__private_access_key[C]=="string")t+=`&p=${encodeURIComponent(this.__private_access_key[C])}`;else if(this.owner!==this.host)try{let W=await this.requestPrivateRecordAccessKey({record_id:C,reference_id:e?._ref});t+=`&p=${encodeURIComponent(W)}`;}catch{}}}if(e?.dataType==="endpoint")return e._update&&(e._update.url=t),t;if(e?.dataType==="download"){let I=document.createElement("a");return I.href=t,document.body.appendChild(I),I.setAttribute("download",y),I.target="_blank",I.click(),document.body.removeChild(I),null}return new Promise(async(I,x)=>{try{let T=await R.bind(this)(t,null,{method:"get",contentType:null,responseType:e?.dataType==="text"?"text":"blob",fetchOptions:{progress:e?.progress}},{ignoreService:!0});if(e?.dataType==="base64"){let v=new FileReader;v.onloadend=()=>I(v.result),v.readAsDataURL(T);}else I(T);}catch(T){if(e?.browserCache&&!e?.refresh)try{I(await se.bind(this)(n,Object.assign({},e,{refresh:!0})));return}catch(v){x(v);return}x(T);}})}function Ne(t,e){return `${t||this.service}/${e||this.owner}`}function Je(t,e){let n=this.__my_unique_ids[t];return n?n[e]:void 0}function Bt(t,e,n){this.__my_unique_ids[t]||(this.__my_unique_ids[t]={}),this.__my_unique_ids[t][e]=n;}function si(t,e){this.__my_unique_ids[t]&&delete this.__my_unique_ids[t][e];}async function Kt(t,e=false){t=U(t,{ignoreEmpty:true}).data||{};let n=Ne.bind(this)(t?.service,t?.owner),r="",i=Ft(t);if(i){if(t=i,r=t.record_id||t.unique_id,typeof r=="string"){typeof this.__private_access_key?.[r]=="string"&&(t.private_key=this.__private_access_key?.[r]||void 0);let s=Je.bind(this)(n,r);s&&(e?si.bind(this)(n,r):t.record_id=s);}}else {let s=await V.bind(this)(),o=t?.reference,l=false;typeof o=="object"&&Object.keys(o).length&&(o?.record_id||o?.unique_id?(r=o.record_id||o.unique_id,r&&typeof this.__private_access_key?.[r]=="string"&&(t.private_key=this.__private_access_key?.[r]||void 0),t.reference=r):o?.user_id&&(l=o.user_id===this.user?.user_id,t.reference=o.user_id)),typeof t?.table=="string"&&(t.table={name:t.table,access_group:0}),t.index&&t.index.hasOwnProperty("range")&&t.index.hasOwnProperty("condition")&&delete t.index.range;let u=c=>({table:{name:d=>ue(d,"table.name"),access_group:We.bind(this),subscription:d=>f.UserId(d,'User ID in "subscription"')},reference:"string",index:{name:["$updated","$uploaded","$referenced_count","$user_id",d=>_e(d,"index.name")],value:d=>{let g={$updated:"number",$uploaded:"number",$referenced_count:"number",$user_id:f.UserId};if(g.hasOwnProperty(c.index.name)){let h=g[c.index.name];if(typeof h=="function")return h(d);if(h!==typeof d)throw new a(`"index.value" should be type: ${h}.`,{code:"INVALID_PARAMETER"});return d}return typeof d=="string"&&!d?"":typeof d=="string"&&Qe(c.index.name)?He(d,"index.value"):ve(d)},condition:["gt","gte","lt","lte",">",">=","<","<=","=","eq"],range:d=>Vt(d,c)},tag:d=>{if(d==null)return d;if(typeof d=="string")return xe(d,"tag");throw new a('"tag" should be type: string.',{code:"INVALID_PARAMETER"})},private_key:"string"});t=f.Params(t||{},u(t),l||s?[]:["table"],{ignoreEmpty:true});}return {query:t,is_reference_fetch:r}}async function Qt(t,e){await this.__connection;let n=await Kt.bind(this)(t),r=n.is_reference_fetch,i=await R.bind(this)("get-records",n.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(de.bind(this)(i.list[o]));return i.list=await Promise.all(s),i}function Ht(t){let e="",n=[],r=Ne.bind(this)(t?.service,t?.owner),i=f.Params(t||{},{record_id:o=>{let l=typeof o=="string"?Je.bind(this)(r,o):void 0;return l||J(o,"record_id",{allowEmpty:false})},unique_id:["string",null],readonly:"boolean",table:{name:o=>ue(o,"table.name"),subscription:[null,{is_subscription_record:"boolean",upload_to_feed:"boolean",notify_subscribers:"boolean",feed_referencing_records:"boolean",notify_referencing_records:"boolean"}],access_group:We.bind(this)},source:{referencing_limit:o=>{if(o===null)return null;if(typeof o=="number"){if(0>o)throw new a('"reference_limit" should be >= 0',{code:"INVALID_PARAMETER"});if(o>4503599627370546)throw new a('"reference_limit" should be <= 4503599627370546',{code:"INVALID_PARAMETER"});return o}throw new a('"reference_limit" should be type: <number | null>',{code:"INVALID_PARAMETER"})},prevent_multiple_referencing:"boolean",can_remove_referencing_records:"boolean",only_granted_can_reference:"boolean",allow_granted_to_grant_others:"boolean",referencing_index_restrictions:o=>{if(o===void 0)return;if(!o||Array.isArray(o)&&!o.length)return null;let l={name:c=>_e(c,'"name" in "index_restrictions"'),value:c=>ve(c),condition:["gt","gte","lt","lte",">",">=","<","<=","=","eq","!=","ne",()=>null],range:c=>{if(c!==null&&typeof o.value!=typeof c)throw new a('Index restriction "range" type should match the type of "value".',{code:"INVALID_PARAMETER"});if(!o.hasOwnProperty("value"))throw new a('Index restriction "value" is required.',{code:"INVALID_PARAMETER"});return c}};Array.isArray(o)||(o=[o]);let u=o.map(c=>f.Params(c,l,["name"]));if(u.length)for(let c of u)c.condition&&c.hasOwnProperty("range")&&delete c.range;return u}},reference:o=>{if(o===null)return {record_id:null};if(o){if(typeof o=="string"){e=o;let l=Je.bind(this)(r,o);return l||o}if(typeof o!="object")throw new a('"reference" should be type: <string | object>.',{code:"INVALID_PARAMETER"});return f.Params(o,{unique_id:"string",record_id:l=>l==null?l:(e=l,typeof this.__private_access_key?.[l]=="string"&&(t.reference_private_key=this.__private_access_key[l]||void 0),J(l,"reference.record_id",{allowEmpty:false,onlyAlphanumeric:true}))})}},index:[null,{name:o=>_e(o,"index.name"),value:o=>ve(o)}],tags:o=>{if(o==null)return o;if(typeof o=="string"&&(o=o.split(",").map(l=>l.trim())),!Array.isArray(o))throw new a('"tag" should be type: <string | string[]>.',{code:"INVALID_PARAMETER"});return o.map(l=>xe(l,"tag"))},remove_bin:o=>{if(!o)return null;let l=[];if(Array.isArray(o))for(let u of o)if(typeof u=="string")l.push(u.split("?")[0]);else if(u.url&&u.size&&u.filename){let d=u.url.split("/").slice(0,3).join("/")+"/"+u.path;l.push(d);}else throw new a('"remove_bin" should be type: <string[] | BinaryFile[] | null>',{code:"INVALID_PARAMETER"});else throw new a('"remove_bin" should be type: <string[] | BinaryFile[] | null>',{code:"INVALID_PARAMETER"});return l},progress:"function",data:o=>o},[],{precall:o=>{let l=o?.data||{};if(!l?.record_id&&!l.table)throw new a('"table.name" is required.',{code:"INVALID_PARAMETER"});typeof l.table=="string"&&(l.table={name:l.table,access_group:0}),o.files&&(n=o.files);}}),s=t.progress||null;if(delete i.progress,!this.__user){let o=!!(i.table?.subscription?.is_subscription_record||i.table?.subscription?.upload_to_feed||i.table?.subscription?.notify_subscribers||i.table?.subscription?.feed_referencing_records||i.table?.subscription?.notify_referencing_records);if(i.record_id)throw new a("Public users cannot update existing records.",{code:"INVALID_REQUEST"});if(i.table.access_group!=="public"&&i.table.access_group!==0)throw new a("Public users can only post records to public tables.",{code:"INVALID_REQUEST"});if(o)throw new a("Public users cannot post subscription records.",{code:"INVALID_REQUEST"});if(i.remove_bin)throw new a("Public users cannot remove files from records.",{code:"INVALID_REQUEST"});if(i.unique_id)throw new a("Public users cannot set unique_id for records.",{code:"INVALID_REQUEST"})}return {config:i,progress:s,is_reference_post:e,files:n}}async function Wt(t){if(await this.__connection,!Array.isArray(t)||!t.length)throw new a('"params" should be a non-empty array.',{code:"INVALID_PARAMETER"});let e=[],n,r,i=null,o={_is_bulk_:t.map((h,_)=>{if(!h||typeof h!="object"||Array.isArray(h))throw new a(`"params[${_}]" should be type: <object>.`,{code:"INVALID_PARAMETER"});let p=Ht.bind(this)(h),y=p.config;if(p.is_reference_post&&e.push(p.is_reference_post),typeof y.progress=="function"&&i===null&&(i=y.progress),y.service!==void 0){if(n===void 0)n=y.service;else if(n!==y.service)throw new a('All bulk params should share the same "service" value.',{code:"INVALID_PARAMETER"})}if(y.owner!==void 0){if(r===void 0)r=y.owner;else if(r!==y.owner)throw new a('All bulk params should share the same "owner" value.',{code:"INVALID_PARAMETER"})}return delete y.progress,delete y.service,delete y.owner,y}),service:"",owner:""};n!==void 0&&(o.service=n),r!==void 0&&(o.owner=r);let l={auth:!!this.__user,method:"post"},u={};Object.keys(u).length&&Object.assign(l,{fetchOptions:u});let c=await R.bind(this)("post-record",o,l),d=await Promise.all(c.map(h=>de.bind(this)(h,"called from postRecord"))),g=Ne.bind(this)(n,r);for(let h=0;h<c.length;h++){let _=c[h],p=d[h];if(_&&typeof _=="object"&&_.error&&p&&!p.record_id&&(p.error=_.error),typeof _?.reference_private_key=="string")for(let y of e)this.__private_access_key[y]=_.reference_private_key;p?.unique_id&&Bt.bind(this)(g,p.unique_id,p.record_id);}return d}async function Jt(t,e,n){if(await this.__connection,!e)throw new a('"config" argument is required.',{code:"INVALID_PARAMETER"});let r=Ht.bind(this)(e),i=r.config,s=r.progress,o=r.is_reference_post,l={auth:!!this.__user,method:"post"},u=[],c=U(t);n&&Array.isArray(n)&&n.length&&(u=u.concat(n)),c.files&&Array.isArray(c.files)&&c.files.length&&(u=u.concat(c.files));let d=null;d=Object.assign({data:c.data},i);let g={};typeof s=="function"&&(g.progress=s),Object.keys(g).length&&Object.assign(l,{fetchOptions:g});let h=await R.bind(this)("post-record",d,l);if(j()&&u.length){let y=new FormData;for(let I of u)y.append(I.name,I.file,I.file.name);let P={record_id:h.rec,progress:s};i.hasOwnProperty("service")&&(P.service=i.service);let{bin_endpoints:m}=await Se.bind(this)(y,P);h.bin?h.bin.push(...m):h.bin=m;}o&&typeof h?.reference_private_key=="string"&&(this.__private_access_key[o]=h.reference_private_key);let _=!!h&&h.data&&typeof h.data=="object"&&!Array.isArray(h.data)&&typeof h.data.__data__=="string"&&h.data.__data__.endsWith("/__data__/__json__.json"),p=await de.bind(this)(h,"called from postRecord",true);if(_&&(p.data=c.data),p.unique_id){let y=Ne.bind(this)(i?.service,i?.owner);Bt.bind(this)(y,p.unique_id,p.record_id),j()&&(this.__uniqueIdsPersistTimer!==null&&clearTimeout(this.__uniqueIdsPersistTimer),this.__uniqueIdsPersistTimer=setTimeout(()=>{this.__uniqueIdsPersistTimer=null;try{window.sessionStorage.setItem(`${y}:uniqueids`,JSON.stringify(this.__my_unique_ids[y]||{}));}catch{}},500));}return p}async function zt(t,e){let n=await R.bind(this)("get-table",f.Params(t||{},{table:i=>ue(i,"table",{allowEmpty:true}),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(n?.list))for(let i of n.list){for(let s in r){if(s==="grp_"){for(let o in i)if(o.startsWith("grp_")){let l=o.substring(4);l==="pv"?l="private":l==="00"?l="public":l==="01"?l="authorized":l==="99"&&(l="admin"),i[`number_of_records_in_access_group_${l}`]=i[o],delete i[o];}}i.hasOwnProperty(s)&&(i[r[s]]=i[s],delete i[s]);}typeof i.table=="string"&&(i.table=K(i.table));}return n}async function Gt(t,e){if(!t?.table)throw new a('"table" is required.',{code:"INVALID_PARAMETER"});let n=f.Params(t||{},{table:s=>ue(s,"table",{allowEmpty:true}),index:s=>_e(s,"index.name"),order:{by:["average_number","total_number","number_count","average_bool","total_bool","bool_count","string_count","index_name","number_of_records"],value:s=>{if(t?.order?.by==="index_name"&&typeof s=="string")return J(s,"order.value",{allowEmpty:true,maxLength:256,blockKeyDelimiters:true});if(typeof s!="string"&&typeof s!="number"&&typeof s!="boolean")throw new a('"order.value" should be type: <string | number | boolean>.',{code:"INVALID_PARAMETER"});return s},condition:["gt","gte","lt","lte",">",">=","<","<=","=","eq","!=","ne"]}},["table"]);if(n.hasOwnProperty("order")){if(!n.order?.by)throw new a('"order.by" is required.',{code:"INVALID_PARAMETER"});if(n.order.hasOwnProperty("condition")&&!n.order.hasOwnProperty("value"))throw new a('"value" is required for "condition".',{code:"INVALID_PARAMETER"});if(n.hasOwnProperty("index")&&n.index.substring(n.index.length-1)!==".")throw new a('"index" should be a parent index name of the compound index when using "order.by"',{code:"INVALID_PARAMETER"})}let r=await R.bind(this)("get-index",n,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("/"),l={table:K(o[1]),index:K(o[2]),number_of_records:s.cnt_rec};for(let u in i)Object.prototype.hasOwnProperty.call(s,u)&&(l[i[u]]=s[u]);return l})),r}async function Xt(t,e){let n=await R.bind(this)("get-tag",f.Params(t||{},{table:r=>ue(r,"table",{allowEmpty:true}),tag:r=>xe(r,"tag",{allowEmpty:true}),condition:["gt","gte","lt","lte",">",">=","<","<=","=","eq","!=","ne"]}),Object.assign({auth:!!this.__user},{fetchOptions:e}));return Array.isArray(n?.list)&&(n.list=n.list.map(r=>{let i=r.tag.split("/");return {table:K(i[1]),tag:K(i[0]),number_of_records:r.cnt_rec}})),n}async function Zt(t,e){let n=await R.bind(this)("get-uniqueid",f.Params(t||{},{unique_id:"string",condition:["gt","gte","lt","lte",">",">=","<","<=","=","eq","!=","ne"]}),Object.assign({auth:!!this.__user},{fetchOptions:e}));if(Array.isArray(n?.list))for(let r in n.list){let i=n.list[r];n.list[r]={unique_id:i.unq,record_id:i.rec};}return n}async function Yt(t,e){await this.__connection;let n=await Kt.bind(this)(t,true),r=n.is_reference_fetch,i=await R.bind(this)("del-records",n.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 en(t){return sn.bind(this)({record_id:t.record_id,user_id:t.user_id,execute:"add"})}function tn(t){return sn.bind(this)({record_id:t.record_id,user_id:t.user_id||null,execute:"remove"})}async function nn(t,e){let n={record_id:t.record_id||void 0,user_id:t.user_id||void 0,execute:"list"};if(!n.record_id&&!n.user_id)throw new a("Either record_id or user_id must be provided.",{code:"INVALID_PARAMETER"});if(n.user_id)if(typeof n.user_id=="string")f.UserId(n.user_id),n.user_id=[n.user_id];else if(Array.isArray(n.user_id))for(let s of n.user_id)f.UserId(s);else throw new a("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 R.bind(this)("grant-private-access",n,{auth:true,fetchOptions:e});return i.list=i.list.map(r),i}function rn(t){let e=t.record_id,n=t.reference_id||void 0;if(!e)throw new a("Record ID is required.",{code:"INVALID_PARAMETER"});if(typeof e!="string")throw new a("Record ID should be type: <string | string[]>",{code:"INVALID_PARAMETER"});if(n&&typeof n!="string")throw new a("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(De[e])return De[e];let r=R.bind(this)("request-private-access-key",{record_id:e,reference_id:n},{auth:true}).then(i=>{let s=typeof i=="string"?i:i?.private_key;if(typeof s!="string")throw new a("Invalid private access key response.",{code:"ERROR"});return this.__private_access_key[e]=s,s}).finally(()=>{delete De[e];});return De[e]=r,r}function sn(t){t.execute;let n=f.Params(t,{record_id:"string",user_id:r=>{if(!r)throw new a("User ID is required.",{code:"INVALID_PARAMETER"});let i=r;if(typeof i=="string"&&(i=[i]),i.length>100)throw new a("Cannot process more than 100 users at once.",{code:"INVALID_REQUEST"});for(let s of i)f.UserId(s,'User ID in "user_id"');return i},execute:["add","remove"]},["execute","record_id","user_id"]);return n.user_id||(n.user_id=null),R.bind(this)("grant-private-access",n,{auth:true})}var S={},q={},Q={},G={},z={},Ue={},Ce={};function on(t,e,n){t[e]||(t[e]=[]),t[e].push(n);}async function Le(t,e,n){let r=[];if(t[e]){for(let i of t[e])if(i){let s=n(i);s instanceof Promise&&(s=await s),r.push(s);}delete t[e];}return r}async function Ge(t,e){if(!this?.session?.accessToken?.jwtToken)throw new a("Access token is required.",{code:"INVALID_PARAMETER"});let n=await this.__socket;async function r(i,s,o){this.log("answerSdpOffer from",s),await S[s].setRemoteDescription(new RTCSessionDescription(i));let l=await S[s].createAnswer();await S[s].setLocalDescription(l),o.send(JSON.stringify({action:"rtc",uid:s,content:{sdpanswer:l},token:this.session.accessToken.jwtToken}));}S?.[e]?t?(await Le(Ce,e,i=>r.bind(this)(i,e,n)),await r.bind(this)(t,e,n)):await Le(Ce,e,i=>r.bind(this)(i,e,n)):t&&on(Ce,e,t);}async function Xe(t,e){if(this.log("receiveIceCandidate",t),S?.[e]&&S[e]?.remoteDescription&&S[e]?.remoteDescription?.type){if(!t)return Le(Ue,e,n=>S[e].addIceCandidate(n));await Le(Ue,e,n=>S[e].addIceCandidate(n)),await S[e].addIceCandidate(t);}else on(Ue,e,t);}async function H(t){if(typeof window>"u"||window._runningInNodeJS)throw new a("WebRTC is not supported in Node.js environment.",{code:"NOT_SUPPORTED"});f.Params(t,{cid:s=>{if(typeof s!="string")throw new a('"cid" should be type: <string>.',{code:"INVALID_PARAMETER"});if(s&&s.slice(0,4)!=="cid:")throw new a('"cid" should be a valid connection id.',{code:"INVALID_PARAMETER"});return s},close:"boolean"});let e=await this.__socket,{cid:n,close_all:r=false}=t||{};if(!r&&!n)throw new a('"cid" is required.',{code:"INVALID_PARAMETER"});let i=s=>{if(!s)throw new a('"cid" is required.',{code:"INVALID_PARAMETER"});if(delete Ce[s],delete Ue[s],q[s]&&Object.values(q[s]).forEach(o=>{o.readyState!=="closed"&&o.close();}),delete q[s],S?.[s]){S[s].connectionState!=="closed"&&(S[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:S[s],timestamp:new Date().toISOString(),state:S[s].connectionState,iceState:S[s].iceConnectionState,signalingState:S[s].signalingState};z[s]&&z[s](o),this.log("closeRTC",o);}delete z[s],delete G[s],delete Q[s],delete S[s];};if(r)for(let s in S)i(s);else i(n);this.log("Cleaning up media stream..."),this.__mediaStream&&(this.__mediaStream.getTracks().forEach(s=>{s.stop();}),this.__mediaStream=null);}async function an(t){if(t instanceof MediaStream)return t;if(!t.video&&!t.audio){let e=new MediaStream,n=document.createElement("canvas");n.width=1,n.height=1;let i=n.captureStream().getVideoTracks()[0];return e.addTrack(i),e}return window.navigator.mediaDevices.getUserMedia(t)}async function cn(t,e){if(typeof window>"u"||window._runningInNodeJS)throw new a("WebRTC is not supported in Node.js environment.",{code:"NOT_SUPPORTED"});if(typeof e!="function")throw new a("Callback is required.",{code:"INVALID_PARAMETER"});if(!this?.session?.accessToken?.jwtToken)throw new a("Access token is required.",{code:"INVALID_PARAMETER"});t=f.Params(t,{cid:o=>{if(typeof o!="string")throw new a('"cid" should be type: <string>.',{code:"INVALID_PARAMETER"});if(o&&o.slice(0,4)!=="cid:")throw new a('"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:n,ice:r}=t;if(!(t?.media instanceof MediaStream)&&(t?.media?.video||t?.media?.audio)&&window.location.hostname!=="localhost"&&window.location.protocol!=="https:")throw new a("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 a("No realtime connection. Execute connectRealtime() before this method.",{code:"INVALID_REQUEST"});if(i.readyState!==1)throw new a("Realtime connection is not ready.",{code:"INVALID_REQUEST"});let s={iceServers:[{urls:r}]};S?.[n]||(S[n]=new RTCPeerConnection(s)),t?.media&&(this.__mediaStream=await an(t.media),this.__mediaStream.getTracks().forEach(o=>{S[n].addTrack(o,this.__mediaStream);})),z[n]=e,q[n]||(q[n]={});for(let o=0;o<t.channels.length;o++){let l=t.channels[o];if(typeof l=="string")switch(l){case "text-chat":l={ordered:true,maxRetransmits:10,protocol:"text-chat"};break;case "file-transfer":l={ordered:false,maxPacketLifeTime:3e3,protocol:"file-transfer"};break;case "video-chat":l={ordered:true,maxRetransmits:10,protocol:"video-chat"};break;case "voice-chat":l={ordered:true,maxRetransmits:10,protocol:"voice-chat"};break;case "gaming":l={ordered:false,maxPacketLifeTime:100,protocol:"gaming"};break;default:l={ordered:true,maxRetransmits:10,protocol:"default"};break}let u=l.protocol||"default";if(Object.keys(q[n]).includes(u))throw new a(`Data channel with the protocol "${u}" already exists.`,{code:"INVALID_REQUEST"});let c=S[n].createDataChannel(u,l);q[n][u]=c;}for(let o in q[n]){let l=q[n][o];dn.bind(this)(n,l);}return un.bind(this)(n,["onnegotiationneeded"]),await ze.bind(this)(n),{hangup:()=>Q[n]&&Q[n](false),connection:new Promise(o=>{Q[n]=(l=>{if(this.log("receiver picked up the call",n),!l)return H.bind(this)({cid:n}),null;S[n].onnegotiationneeded=()=>{this.log("onnegotiationneeded",`sending offer to "${n}".`),ze.bind(this)(n),z[n]&&z[n]({type:"negotiationneeded",target:S[n],timestamp:new Date().toISOString(),signalingState:S[n].signalingState,connectionState:S[n].iceConnectionState,gatheringState:S[n].iceGatheringState});},o({target:S[n],channels:q[n],hangup:()=>H.bind(this)({cid:n}),media:this.__mediaStream});}).bind(this);})}}function ln(t){return async(e,n)=>{e=e||{},e=U(e).data;let r=t.sender_cid,i=await this.__socket;if(!G[r])return null;if(typeof n!="function")throw new a("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 a("Media stream is only supported on either localhost or https.",{code:"INVALID_REQUEST"});let{ice:s="stun:stun.skapi.com:3468"}=e;return S?.[r]||(S[r]=new RTCPeerConnection({iceServers:[{urls:s}]})),e?.media&&(this.__mediaStream=await an(e.media),this.__mediaStream.getTracks().forEach(o=>{S[r].addTrack(o,this.__mediaStream);})),delete G[r],z[r]=n,q[r]||(q[r]={}),S[r].ondatachannel=o=>{this.log("ondatachannel",`received data channel "${o.channel.label}".`);let l=o.channel;q[r][l.label]=l,dn.bind(this)(r,l);},un.bind(this)(r,["onnegotiationneeded"]),await Ge.bind(this)(null,r),await Xe.bind(this)(null,r),i.send(JSON.stringify({action:"rtc",uid:r,content:{pickup:this.user.user_id},token:this.session.accessToken.jwtToken})),{target:S[r],channels:q[r],hangup:()=>H.bind(this)({cid:r}),media:this.__mediaStream}}}async function ze(t){if(!this?.session?.accessToken?.jwtToken)throw new a("Access token is required.",{code:"INVALID_PARAMETER"});this.log("sendOffer",t);let e=await this.__socket,n=await S[t].createOffer();await S[t].setLocalDescription(n);let r=S[t].localDescription;this.log("rtcSdpOffer to",r),e.send(JSON.stringify({action:"rtc",uid:t,content:{sdpoffer:r},token:this.session.accessToken.jwtToken}));}async function oi(t,e){if(!this?.session?.accessToken?.jwtToken)throw new a("Access token is required.",{code:"INVALID_PARAMETER"});this.log("sendIceCandidate to",e);let n=await this.__socket;if(!t.candidate){this.log("candidate-end","all ice candidates have been sent");return}let r=z[e]||(()=>{}),i=t.candidate;this.log("ice gathering state set to",S[e].iceGatheringState),r({type:"icecandidate",target:S[e],timestamp:new Date().toISOString(),candidate:t.candidate.candidate,sdpMid:t.candidate.sdpMid,sdpMLineIndex:t.candidate.sdpMLineIndex,usernameFragment:t.candidate.usernameFragment,protocol:t.candidate.protocol,gatheringState:S[e].iceGatheringState,connectionState:S[e].iceConnectionState}),n.send(JSON.stringify({action:"rtc",uid:e,content:{candidate:i},token:this.session.accessToken.jwtToken}));}function un(t,e){let n=new Set(e),r=z[t]||(o=>{}),i=S[t],s={ontrack:o=>{r({type:"track",target:i,timeStamp:o.timeStamp,streams:o.streams,track:o.track});},onicecandidate:o=>{oi.bind(this)(o,t),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:()=>{ze.bind(this)(t),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")&&H.bind(this)({cid:t});}};for(let[o,l]of Object.entries(s))n.has(o)||(i[o]=l);}function dn(t,e,n){let r=new Set(n),i=z[t]||(o=>{}),s={onmessage:o=>{let l={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(l);},onerror:o=>{let l={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(l);},onclose:o=>{let l={type:o.type,target:e,timeStamp:o.timeStamp,readyState:e.readyState,label:e.label,id:e.id};this.log(`${e.label}: closed`,null),i(l),q[t]&&(delete q[t][e.label],Object.keys(q[t]).length===0&&H.bind(this)({cid:t}));},onbufferedamountlow:o=>{let l={target:e,bufferedAmount:e.bufferedAmount,bufferedAmountLowThreshold:e.bufferedAmountLowThreshold,type:o.type,timeStamp:o.timeStamp};this.log(`${e.label}: bufferedamountlow`,e.bufferedAmount),i(l);},onopen:o=>{this.log("dataChannel",`data channel: "${e.label}" is open and ready to send messages.`);let l={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(l);}};for(let[o,l]of Object.entries(s))r.has(o)||(e[o]=l);}var re,ne=null,be=true,ge=0;async function ai(){if(typeof window>"u"||window._runningInNodeJS)throw new a("WebSocket is not supported in Node.js environment.",{code:"NOT_SUPPORTED"});if(await this.getProfile(),!this.session)throw new a("No access.",{code:"INVALID_REQUEST"});let t=await this.record_endpoint;return new WebSocket(t.websocket_private+"?token="+this.session.accessToken.jwtToken)}var Ze=null;async function gn(){if(typeof window>"u"||window._runningInNodeJS)throw new a("WebSocket is not supported in Node.js environment.",{code:"NOT_SUPPORTED"});be=true;let t=this.__socket?await this.__socket:this.__socket;H.bind(this)({close_all:true}),re&&Ye.bind(this)({group:null}),ge=0,ne&&(ne.terminate(),ne=null);try{t&&t.close();}catch{}return window.removeEventListener("visibilitychange",Ze),this.__socket=null,null}async function Oe(t,e=50,n){if(typeof window>"u"||window._runningInNodeJS)throw new a("WebSocket is not supported in Node.js environment.",{code:"NOT_SUPPORTED"});if(typeof t!="function")throw new a("Callback must be a function.",{code:"INVALID_REQUEST"});if(n==="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(be&&(Ze=()=>{!document.hidden&&!be&&Oe.bind(this)(t,0,"reconnect");},this.__socket instanceof Promise))return this.__socket;ne&&(ne.terminate(),ne=null),this.__socket=new Promise(async r=>{await ce.bind(this)(),setTimeout(async()=>{let i=await ai.bind(this)();i.onopen=()=>{be=false,ge=0,n!=="reconnect"&&window.addEventListener("visibilitychange",Ze),this.log("realtime onopen","Connected to WebSocket server."),t({type:"success",message:"Connected to WebSocket server."}),re&&i.send(JSON.stringify({action:"joinRoom",rid:re,token:this.session.accessToken.jwtToken}));let s=`
|
|
207
207
|
let interval = 15000; // Set interval time 15 seconds
|
|
208
208
|
|
|
209
209
|
function runInterval() {
|
|
@@ -212,9 +212,9 @@ var tr=Object.defineProperty;var nr=Object.getOwnPropertyDescriptor;var oe=(t=>t
|
|
|
212
212
|
}
|
|
213
213
|
|
|
214
214
|
runInterval(); // Start interval
|
|
215
|
-
`,o=new Blob([s],{type:"application/javascript"});ne=new Worker(URL.createObjectURL(o)),ne.onmessage=l=>{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 l;switch(true){case !!o?.["#message"]:l="message";break;case !!o?.["#private"]:l="private";break;case !!o?.["#notice"]:l="notice";break;case !!o?.["#rtc"]:l="rtc";break;case !!o?.["#error"]:l="error";break}if(!l)return;let u={type:l,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(l==="notice")t(u);else if(l==="rtc"){if(u.sender!==this.user.user_id){let c=u.message;if(c.hungup){Q[u.sender_cid]&&(Q[u.sender_cid](false),delete Q[u.sender_cid]),G[u.sender_cid]&&delete G[u.sender_cid],S?.[u.sender_cid]&&H.bind(this)({cid:u.sender_cid}),u.type="rtc:closed",t(u);return}if(c.candidate&&Xe.bind(this)(c.candidate,u.sender_cid),c.sdpoffer&&(Ge.bind(this)(c.sdpoffer,u.sender_cid),G[u.sender_cid]||(G[u.sender_cid]=u.sender_cid,delete u.message,u.connectRTC=ln.bind(this)(u),u.type="rtc:incoming",u.hangup=(()=>{S[u.sender_cid]?H.bind(this)({cid:u.sender_cid}):G[u.sender_cid]&&(delete G[u.sender_cid],i.send(JSON.stringify({action:"rtc",uid:u.sender_cid,content:{hungup:this.user.user_id},token:this.session.accessToken.jwtToken})));}).bind(this),t(u))),c.pickup&&Q[u.sender_cid]&&(Q[u.sender_cid](true),delete Q[u.sender_cid]),c.sdpanswer&&S[u.sender_cid])if(S[u.sender_cid].signalingState==="have-local-offer")await S[u.sender_cid].setRemoteDescription(new RTCSessionDescription(c.sdpanswer));else throw new a("Invalid signaling state.",{code:"INVALID_REQUEST"})}}else t(u);},i.onclose=()=>{be?(this.log("realtime onclose","WebSocket connection closed."),t({type:"close",message:"WebSocket connection closed."})):(this.log("realtime onclose","WebSocket unexpected close."),t({type:"error",message:"Skapi: WebSocket unexpected close."}),ge++,ge<3?(this.log("realtime onclose","Reconnecting to WebSocket server..."+ge),t({type:"reconnect",message:"Reconnecting to WebSocket server..."+ge}),Oe.bind(this)(t,3e3,"reconnect")):(this.log("realtime onclose","Max reconnection attempts reached."),t({type:"error",message:"Skapi: Max reconnection attempts reached."})));},i.onerror=()=>{this.log("realtime onerror","WebSocket connection error."),t({type:"error",message:"Skapi: WebSocket connection error."});};},e);});}async function fn(t,e,n){if(typeof window>"u"||window._runningInNodeJS)throw new a("WebSocket is not supported in Node.js environment.",{code:"NOT_SUPPORTED"});let r=this.__socket?await this.__socket:this.__socket;if(!r)throw new a("No realtime connection. Execute connectRealtime() before this method.",{code:"INVALID_REQUEST"});if(!e)throw new a("No recipient.",{code:"INVALID_REQUEST"});await ce.bind(this)(),t=U(t).data;let i="";if(n&&(n=f.Params(n,{config:{always:"boolean"},title:"string",body:"string"},["title","body"]),i=JSON.stringify({title:n.title,body:n.body}),new Blob([i]).size>3072))throw new a("Notification size exceeds 3kb.",{code:"INVALID_PARAMETER"});if(r.readyState===1){try{f.UserId(e),r.send(JSON.stringify({action:"sendMessage",uid:e,content:t,notification:i,notificationConfig:n?.config||{},token:`IdT:${this.service}:${this.owner}:`+(this.bearerToken||this.session?.idToken?.jwtToken||"null")}));}catch(s){if(this.log("postRealtime:err",{err:s}),re!==e)throw new a(`User has not joined to the recipient group. Run joinRealtime({ group: "${e}" })`,{code:"INVALID_REQUEST"});r.send(JSON.stringify({action:"broadcast",rid:e,content:t,notification:i,notificationConfig:n?.config||{},token:`IdT:${this.service}:${this.owner}:`+(this.bearerToken||this.session?.idToken?.jwtToken||"null")}));}return {type:"success",message:"Message sent."}}throw new a("Realtime connection is not open. Try reconnecting with connectRealtime().",{code:"INVALID_REQUEST"})}async function Ye(t){if(typeof window>"u"||window._runningInNodeJS)throw new a("WebSocket is not supported in Node.js environment.",{code:"NOT_SUPPORTED"});let e=this.__socket?await this.__socket:this.__socket;if(!e)throw new a("No realtime connection. Execute connectRealtime() before this method.",{code:"INVALID_REQUEST"});await ce.bind(this)(),t=U(t,{nullIfEmpty:true}).data;let{group:n=null}=t;if(!n&&!re)return {type:"success",message:"Left realtime message group."};if(n!==null&&typeof n!="string")throw new a('"group" must be a string | null.',{code:"INVALID_PARAMETER"});return e.send(JSON.stringify({action:"joinRoom",rid:n,token:this.session.accessToken.jwtToken})),re=n,{type:"success",message:n?`Joined realtime message group: "${n}".`:"Left realtime message group."}}async function hn(t,e){t=f.Params(t,{user_id:r=>f.UserId(r,'User ID in "user_id"'),group:["string",()=>{if(!re)throw new a('No group has been joined. Otherwise "group" is required.',{code:"INVALID_REQUEST"});return re}]});let n=await E.bind(this)("get-ws-group",t,{fetchOptions:e,auth:true,method:"post"});return n.list=n.list.map(r=>({user_id:r.uid.split("#")[1],cid:"cid:"+r.cid})),n}async function pn(t,e){if(await this.__connection,t||(t={searchFor:"group",value:" ",condition:">"}),t=f.Params(t,{searchFor:["group","number_of_users",()=>"group"],value:["string","number",()=>t?.searchFor&&t?.searchFor==="number_of_users"?0:" "],condition:[">",">=","=","<","<=","!=","gt","gte","eq","lt","lte","ne"],range:["string","number"]}),t.condition||(t.value===" "||!t.value?t.condition=">":t.condition="="),t.range&&t.condition&&delete t.condition,t.searchFor==="number_of_users"&&typeof t.value!="number")throw new a('"value" must be a number.',{code:"INVALID_PARAMETER"});if(t.searchFor==="group"&&typeof t.value!="string")throw new a('"value" must be a string.',{code:"INVALID_PARAMETER"});if(t.hasOwnProperty("range")&&typeof t.range!=typeof t.value)throw new a(`"range" must be a ${typeof t.value}.`,{code:"INVALID_PARAMETER"});let n=await E.bind(this)("get-ws-group",t,{fetchOptions:e,auth:true,method:"post"});return n.list=n.list.map(r=>({group:r.rid.split("#")[1],number_of_users:r.cnt})),n}var ii=typeof FormData<"u",si=typeof HTMLFormElement<"u",oi=typeof SubmitEvent<"u",X={},ye={},Z={};function et(t){return Object.freeze({id:t,status:"stopped"})}function _n(t){return !!t&&typeof t=="object"&&t.status==="stopped"}function bn({id:t,auth:e,service:n,owner:r,latency:i=1e3,queue:s,onResponse:o,onError:l}){if(typeof i!="number")throw new a('"latency" should be a number.',{code:"INVALID_PARAMETER"});if(i<0)throw new a('"latency" should be a non-negative number.',{code:"INVALID_PARAMETER"});s&&!X?.[s]&&(X[s]=new mn__default.default({breakWhenError:false,batchSize:1}));let u={stop:null,aborted:false,queue:s};Z[t]=u;let c=()=>{Z[t]===u&&delete Z[t];},d=()=>new Promise((h,_)=>{let p=false;if(u.aborted){c(),h(et(t));return}let y=setInterval(async()=>{try{let P=await E.bind(this)("csr-poll",{id:t,service:n,owner:r},{auth:e});if(P.status==="running"||P.status==="pending"||p)return;p=!0,o&&o(P),clearInterval(y),c(),h(P);}catch(P){if(p)return;p=true,l&&l(P),clearInterval(y),c(),_(P);}},i);u.stop=()=>{p||(p=true,clearInterval(y),c(),h(et(t)));};}),g=()=>{let h=Z[t];h&&(h.stop?h.stop():(h.aborted=true,delete Z[t]));};if(s){let h=new Promise((_,p)=>{let y=false,P=X[s].add([async()=>{try{let m=await d();return y||(y=!0,_(m)),m}catch(m){throw y||(y=true,p(m)),m}}])[0];ye[t]=P,u.stop=()=>{if(!y){u.aborted=true;try{X[s]&&X[s].remove(ye[t]);}catch{}delete ye[t],c(),y=true,_(et(t));}};});return Object.assign(h,{stop:g})}else return Object.assign(d(),{stop:g})}function yn(t){let e=0,n=[];if(t?.id){if(t.url&&t.method){let r=t.service||this.service;n.push(`[${t.method.toUpperCase()}]${t.url.toLowerCase()}#${r}:${t.id}`);}n.push(t.id);}else if(t?.queue)for(let r in Z)Z[r]?.queue===t.queue&&n.push(r);else for(let r in Z)n.push(r);for(let r of n){let i=Z[r];i&&(i.stop?i.stop():(i.aborted=true,delete Z[r]),e+=1);}return e}function wn(t,e){if(!t.queue)throw new a('"queue" is required.',{code:"INVALID_PARAMETER"});let n={service:t.service||this.service,owner:t.owner||this.owner,queue:t.queue+":"};return E.bind(this)("csr-poll",n,{auth:true})}async function En(t){let e=false;if(typeof t.poll=="number"&&t.poll<0)throw new a('"poll" should be a non-negative number.',{code:"INVALID_PARAMETER"});let n=t?.onResponse,r=t?.onError,i=typeof t.poll=="number"?t.poll:t.poll?1e3:0;delete t.poll,i&&!t.queue&&(t.queue=(this.__user?.user_id||"anonymous")+"-"+ie());let s=u=>{for(let c in u)if(typeof u[c]=="string"&&u[c].includes("$CLIENT_SECRET")){e=true;break}};if(t=f.Params(t,{url:u=>{if(!u||typeof u!="string")throw new a('"url" should be type: <string>.',{code:"INVALID_PARAMETER"});return f.Url(u),u.includes("$CLIENT_SECRET")&&(e=true),u},clientSecretName:"string",method:u=>{if(u&&typeof u!="string")throw new a('"method" should be either "GET" or "POST" or "DELETE" or "PUT".',{code:"INVALID_PARAMETER"});let c=u.toLowerCase();if(c!=="get"&&c!=="post"&&c!=="delete"&&c!=="put")throw new a('"method" should be either "GET" or "POST" or "DELETE" or "PUT".',{code:"INVALID_PARAMETER"});return c},headers:u=>{if(u&&typeof u!="object")throw new a('"headers" should be type: <object>.',{code:"INVALID_PARAMETER"});return s(u),u},data:u=>{if(u&&typeof u!="object")throw new a('"data" should be type: <object>.',{code:"INVALID_PARAMETER"});return s(u),u},params:u=>{if(u&&typeof u!="object")throw new a('"params" should be type: <object>.',{code:"INVALID_PARAMETER"});return s(u),u},expires:"number",queue:"string"},["clientSecretName","method","url"]),!e)throw new a(`At least one parameter value should include "$CLIENT_SECRET" in ${t.method.toLowerCase()==="post"?'"data"':'"params"'} or "headers".`,{code:"INVALID_PARAMETER"});await this.__connection;let o=!!this.__user,l=()=>E.bind(this)("csr",t,{auth:o,tokenHeaders:{accessToken:!!o}}).then(u=>{if(u.status==="running"||u.status==="pending"){let c=`[${t.method.toUpperCase()}]${t.url.toLowerCase()}`,d=t.service||this.service,g=t.owner||this.owner,h=`${c}#${d}:${u.id}`;Object.assign(u,{poll:_=>bn.call(this,{id:h,auth:o,service:d,owner:g,latency:_?.latency||1e3,queue:t?.queue,onResponse:n,onError:r})});}return n?n(u):u}).catch(u=>{if(r)return r(u);throw u});if(t?.queue){let u="base:"+t.queue;return X?.[u]||(X[u]=new mn__default.default({breakWhenError:false,batchSize:1})),new Promise((c,d)=>{X[u].add([async()=>{try{let g=await l();if(i>0){let h=g.poll({latency:i});return c(h),h}return c(g),g}catch(g){throw d(g),g}}]);})}else return l()}async function Rn(t,e){await this.__connection;let n=t.service||this.service,r=t.owner||this.owner;t=f.Params(t,{url:"string",method:["GET","POST","DELETE","PUT"],queue:"string",status:["pending","running","resolved","failed"],compact:"boolean",queue_exact:"boolean",queue_exclude:"string"},["url","method"]);let i=!!this.__user,s=`[${t.method.toUpperCase()}]${t.url.toLowerCase()}#${n}:`,o={id:s,queue:t?.queue,status:t?.status,service:n,owner:r};t?.compact&&(o.compact=true),t?.queue_exact&&(o.queue_exact=true),t?.queue_exclude&&(o.queue_exclude=t.queue_exclude),Object.keys(o).forEach(u=>{o[u]||delete o[u];}),o.queue&&(o.id_prefix=o.id,delete o.id);let l=await E.bind(this)("csr-poll",o,{auth:i,fetchOptions:e});return l.list=l.list.map(u=>{let c={id:u.id,status_code:u.rslv?.status_code||null,response_body:u.rslv?.body||u.rslv?.truncated||null,error:u?.err,created:u?.stmp,updated:u?.utmp,request_body:u?.reqbdy,expires:u?.expt,status:u.stts,queue_name:u?.qid,request_text:u?.reqtxt,response_text:u?.rslvtxt,response_complete_marker:u?.rslvmk!=null?!!u.rslvmk:void 0,compact:u?.cmpct?true:void 0};for(let d in c)c[d]===void 0&&delete c[d];return (c.status==="running"||c.status==="pending")&&(c.poll=d=>bn.call(this,{id:s+c.id,auth:i,service:n,owner:r,latency:d?.latency||1e3,queue:u?.qid,onResponse:d?.onResponse,onError:d?.onError})),c}),l}async function An(t){await this.__connection,t=f.Params(t,{url:"string",method:["GET","POST","DELETE","PUT"],id:"string",queue:"string"},["url","method","id"]);let e=t?.service||this.service,n=t?.owner||this.owner,r=!!this.__user,i=`[${t.method.toUpperCase()}]${t.url.toLowerCase()}#${e}`,s=t.id,o=`${i}:${s}`,l=t?.queue;return l&&X?.[l]&&(X[l].remove(ye[o]),delete ye[o]),E.bind(this)("csr-cancel",{id:o,service:e,owner:n},{auth:r})}async function In(t){await this.__connection;let e={name:"string",email:n=>(f.Email(n),n),subject:"string",message:"string"};return t=f.Params(t,e,["name","email","subject","message"]),await E.bind(this)("send-inquiry",t),"SUCCESS: Inquiry has been sent."}async function Tn(t,e){if(await this.__connection,ii&&t instanceof FormData||si&&t instanceof HTMLFormElement||oi&&t instanceof SubmitEvent){if(!e)throw new a("Url string as a second argument is required when form is passed.",{code:"INVALID_PARAMETER"});let r=U(t);t={url:e,data:r.data,sync:true};}let n={url:r=>f.Url(r),data:r=>r,sync:["boolean",()=>true]};if(Array.isArray(t))for(let r of t)r=f.Params(r,n);else t=f.Params(t,n);return E.bind(this)("post-secure",t,{auth:true})}async function Pn(t,e){await this.__connection;let{auth:n=false,method:r="POST",bypassAwaitConnection:i=false,responseType:s,contentType:o,tokenHeaders:l,progress:u}=e||{};if(e=Object.assign({auth:n,method:r,bypassAwaitConnection:i,responseType:s,contentType:o,tokenHeaders:l},{fetchOptions:{progress:u}}),typeof t!="object"&&(o==="application/json"||o===void 0))throw new a('"data" should be type: <object>.',{code:"INVALID_PARAMETER"});return E.bind(this)("mock",t,e)}async function Sn(t,e){await this.__connection,t=f.Params(t||{},{access_group:r=>{if(r==="authorized"&&(r=1),r==="public"&&(r=0),typeof r!="number")throw new a('"access_group" should be type number.',{code:"INVALID_PARAMETER"});if(r<0)throw new a('"access_group" should be zero or a positive number.',{code:"INVALID_PARAMETER"});if(r>this.__user.access_group)throw new a("User has no access.",{code:"INVALID_REQUEST"});return r}});let n=await E.bind(this)("get-feed",t,{auth:true,fetchOptions:e});for(let r in n.list)n.list[r]=await de.bind(this)(n.list[r]);return n}function we(t){if(t===this.__user.user_id)throw new a(`"user_id" cannot be the user's own ID.`,{code:"INVALID_PARAMETER"});return f.UserId(t,'"user_id"')}async function kn(t,e){if(t=U(t,{ignoreEmpty:true}).data,t=f.Params(t,{subscriber:r=>f.UserId(r,'User ID in "subscriber"'),subscription:we.bind(this),blocked:"boolean"}),!t.subscriber&&!t.subscription)throw new a('At least either "subscriber" or "subscription" should have a value.',{code:"INVALID_PARAMETER"});let n=await E.bind(this)("get-subscription",t,Object.assign({auth:true},{fetchOptions:e}));return n.list=n.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})),n}async function xn(t){await this.__connection,t=f.Params(t,{user_id:we.bind(this),get_feed:["boolean",()=>false],get_notified:["boolean",()=>false],get_email:r=>{if(r&&!this.__user.email||!this.__user.email_verified)throw new a("User has no verified email address.",{code:"INVALID_REQUEST"});return !!r}},["user_id"]);let e=await E.bind(this)("subscription",{subscribe:t.user_id,option:{get_feed:t.get_feed,get_notified:t.get_notified,get_email:t.get_email||false}},{auth:true}),n={};if(e.sub){let r=e.sub.split("#");n.subscriber=r[2],n.subscription=r[0];}else n.subscriber=e.subscriber,n.subscription=e.subscription;return n.timestamp=e?.timestamp||e.stmp,n.blocked=e?.blocked||e.grp.substring(0,1)==="N",Object.assign(n,e.opt),n}async function vn(t){await this.__connection;let{user_id:e}=f.Params(t,{user_id:we.bind(this)},["user_id"]);return await E.bind(this)("subscription",{unsubscribe:e},{auth:true})}async function Dn(t){await this.__connection;let{user_id:e}=f.Params(t,{user_id:we.bind(this)},["user_id"]);return await E.bind(this)("subscription",{block:e},{auth:true})}async function Nn(t){await this.__connection;let{user_id:e}=f.Params(t,{user_id:we.bind(this)},["user_id"]);return await E.bind(this)("subscription",{unblock:e},{auth:true})}async function Un(t,e){await this.__connection;let n=await V.bind(this)();t=f.Params(t,{user_id:o=>{if(o!==this.__user.user_id&&!n)throw new a("No access.",{code:"INVALID_REQUEST"});return o},group:o=>{if(o==="public"&&(o=0),o==="authorized"&&(o=1),typeof o!="number")throw new a('"group" should be type number | "public" | "authorized".',{code:"INVALID_PARAMETER"});return o}});let r=await E.bind(this)("get-newsletter-subscription",t,{auth:true,fetchOptions:e||null}),i=r?.list||r,s=[];Array.isArray(i)||(i=[]);for(let o of i){let l=o.subt.split("#"),u=true;l[0].charAt(0)==="@"&&(u=false,l[0]=l[0].substring(1));let c=parseInt(l[0]);s.push({timestamp:o.stmp,group:c,subscribed_email:l[1],active:u});}return r?.list?(r.list=s,r):s}async function Cn(t){await this.__connection;let e=f.Params(t||{},{email:n=>Array.isArray(n)&&n.length>0?n.length===1?f.Email(n[0]):n.map(r=>f.Email(r)):f.Email(n),group:["number","public","authorized","admin",n=>{if(typeof n!="string"||n.length>20||!/^[a-zA-Z0-9]+$/.test(n))throw new a('"group" should be an alphanumeric string without spaces and less than 20 characters.',{code:"INVALID_PARAMETER"});return n}],redirect:n=>f.Url(n)},this.__user?["group"]:["email","group"]);return E.bind(this)(`subscribe-${this.__user?"":"public-"}newsletter`,e,{auth:!!this.__user})}async function Ln(t){await this.__connection,t=f.Params(t,{group:["number","public","authorized","admin"]},["group"]);let e=Object.assign({action:"unsubscribe"},t);return E.bind(this)("subscribe-newsletter",e,{auth:true})}async function On(t,e){let n=await V.bind(this)(),r={message_id:"string",timestamp:"number",read:"number",complaint:"number",subject:"string",bounced:"number"};t||(e=Object.assign({ascending:false},e||{})),t=U(t).data,t=t||{searchFor:"timestamp",value:Date.now(),condition:"<",group:"public"},t=f.Params(t,{searchFor:["message_id","timestamp","subject","complaint","read","bounced"],value:u=>{if(typeof u!==r[t.searchFor])throw new a(`"value" type does not match the type of "${t.searchFor}" index.`,{code:"INVALID_PARAMETER"});if(typeof u=="string"&&!u)throw new a('"value" should not be empty string.',{code:"INVALID_PARAMETER"});return u},range:u=>{if(!t.hasOwnProperty("value")||typeof u!=typeof t.value)throw new a('"range" should match type of "value".',{code:"INVALID_PARAMETER"});return u},condition:[">",">=","=","<","<=","gt","gte","eq","lt","lte",()=>"="],group:u=>{if(u==="public")return 0;if(!this.session)throw new a("User should be logged in.",{code:"INVALID_REQUEST"});if(u==="authorized")return 1;if(typeof u=="number"){if(!n&&u>parseInt(this.user?.access_group||this.session?.idToken?.payload?.access_group))throw new a("User has no access.",{code:"INVALID_REQUEST"});return u}throw new a('"group" should be type: number | "public" | "authorized".',{code:"INVALID_PARAMETER"})}},["searchFor","value","group"]);let i=t.group===0?"get-public-newsletters":"get-newsletters",s=await E.bind(this)(i,t,Object.assign({method:"get",auth:i==="get-public-newsletters"?!!this.__user:true},{fetchOptions:e})),o={message_id:"mid",timestamp:"stmp",complaint:"cmpl",read:"read",subject:"subj",bounced:"bnce",url:"url",delivered:"delv"},l={message_id:"",timestamp:0,complaint:0,read:0,subject:"",bounced:"",url:"",delivered:0};return s.list=s.list.map(u=>{let c={};for(let d in o)c[d]=u[o[d]]||l[d];return c.bounced=String(c.bounced),c}),s}async function Mn(t){let e=f.Params(t,{user_id:r=>f.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 V.bind(this)()){if(!this.__user)throw new a("User needs to login.",{code:"INVALID_REQUEST"});if(this.__user.access_group<90)throw new a("Invalid access.",{code:"INVALID_REQUEST"})}return await E.bind(this)("block-account",e,{auth:true})}async function Fn(t){let e=f.Params(t,{user_id:r=>f.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 V.bind(this)()){if(!this.__user)throw new a("User needs to login.",{code:"INVALID_REQUEST"});if(this.__user.access_group<90)throw new a("Invalid access.",{code:"INVALID_REQUEST"})}return await E.bind(this)("block-account",e,{auth:true})}async function qn(t){let e=f.Params(t,{user_id:r=>f.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 V.bind(this)()){if(!this.__user)throw new a("User needs to login.",{code:"INVALID_REQUEST"});if(this.__user.access_group<90)throw new a("Invalid access.",{code:"INVALID_REQUEST"})}return await E.bind(this)("remove-account",e,{auth:true})}async function Vn(t,e){let n={email:s=>f.Email(s),password:s=>f.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=>f.Birthdate(s),phone_number:s=>f.PhoneNumber(s),picture:s=>{if(s)return f.Url(s)},profile:s=>{if(s)return f.Url(s)},website:s=>{if(s)return f.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 a('"access_group" is invalid. Should be type <number>.',{code:"INVALID_PARAMETER"})}if(typeof s!="number"||s<1||s>100)throw new a('"access_group" is invalid. Should be type <number> of range 1~99',{code:"INVALID_PARAMETER"});return s}},r=f.Params(t,n,["email"]);if(e=f.Params(e,{confirmation_url:s=>{let o=s;if(typeof s=="string")o=f.Url(s);else throw new a('"options.confirmation_url" should be type: <string>.',{code:"INVALID_PARAMETER"});if(o&&!r.email)throw new a('"email" is required for signup confirmation.',{code:"INVALID_PARAMETER"});return o},email_subscription:s=>{if(typeof s!="boolean")throw new a('"options.email_subscription" should be type: <boolean>.',{code:"INVALID_PARAMETER"});if(!e?.confirmation_url)throw new a('"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 a('"options.template" should be type: <object> with "url" and "subject".',{code:"INVALID_PARAMETER"});return {url:f.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 V.bind(this)()){if(!this.__user)throw new a("User needs to login.",{code:"INVALID_REQUEST"});if(this.__user.access_group<90)throw new a("Invalid access.",{code:"INVALID_REQUEST"})}return await E.bind(this)("admin-signup",r,{auth:true})}async function $n(t){let e={email:s=>f.Email(s),password:s=>f.Password(s),openid_id:"string",name:"string",username:"string",gender:"string",address:s=>{if(!s)return "";if(typeof s=="string")return s;if(typeof s=="object")return JSON.stringify(s)},birthdate:s=>f.Birthdate(s),phone_number:s=>f.PhoneNumber(s),picture:s=>s?f.Url(s):"",profile:s=>s?f.Url(s):"",website:s=>s?f.Url(s):"",nickname:"string",misc:"string",email_public:["boolean",()=>false],gender_public:["boolean",()=>false],address_public:["boolean",()=>false],birthdate_public:["boolean",()=>false],phone_number_public:["boolean",()=>false],access_group:s=>{try{typeof s=="string"&&(s=parseInt(s));}catch{throw new a('"access_group" is invalid. Should be type <number>.',{code:"INVALID_PARAMETER"})}if(typeof s!="number"||s<1||s>100)throw new a('"access_group" is invalid. Should be type <number> of range 1~99',{code:"INVALID_PARAMETER"});return s}},n=["email","password"],r=f.Params(t,e,n);if(!await V.bind(this)()){if(!this.__user)throw new a("User needs to login.",{code:"INVALID_REQUEST"});if(this.__user.access_group<90)throw new a("Invalid access.",{code:"INVALID_REQUEST"})}return await E.bind(this)("admin-signup",r,{auth:true})}async function jn(t){if(t=f.Params(t,{user_id:n=>f.UserId(n,'"user_id"'),access_group:n=>{try{typeof n=="string"&&(n=parseInt(n));}catch{throw new a('"access_group" is invalid. Should be type <number>.',{code:"INVALID_PARAMETER"})}if(typeof n=="number"&&n>0&&n<100)return n;throw new a('"access_group" is invalid. Should be type <number> of range 1~99',{code:"INVALID_PARAMETER"})}},["user_id","access_group"]),!await V.bind(this)()){if(!this.__user)throw new a("User needs to login.",{code:"INVALID_REQUEST"});if(this.__user.access_group<90)throw new a("Invalid access.",{code:"INVALID_REQUEST"})}return await E.bind(this)("grant-access",t,{auth:true})}async function Bn(t,e){if(t=f.Params(t,{email:"string"}),!await V.bind(this)()){if(!this.__user)throw new a("User needs to login.",{code:"INVALID_REQUEST"});if(this.__user.access_group<90)throw new a("Invalid access.",{code:"INVALID_REQUEST"})}let r=await E.bind(this)("invitation-list",Object.assign({mode:"search"},t),{fetchOptions:e,auth:true});return r.list=r.list.map(i=>fe(i.user)),r}async function Kn(t){if(t=f.Params(t,{email:n=>f.Email(n)},["email"]),!await V.bind(this)()){if(!this.__user)throw new a("User needs to login.",{code:"INVALID_REQUEST"});if(this.__user.access_group<90)throw new a("Invalid access.",{code:"INVALID_REQUEST"})}return await E.bind(this)("invitation-list",Object.assign({mode:"cancel"},t),{auth:true})}async function Qn(t){if(t=f.Params(t,{email:n=>f.Email(n)},["email"]),!await V.bind(this)()){if(!this.__user)throw new a("User needs to login.",{code:"INVALID_REQUEST"});if(this.__user.access_group<90)throw new a("Invalid access.",{code:"INVALID_REQUEST"})}return await E.bind(this)("invitation-list",Object.assign({mode:"resend"},t),{auth:true})}async function Hn(t){let e=f.Params(t,{user_id:o=>f.UserId(o,'"user_id"'),email:o=>f.Email(o),address:o=>{if(!o)return "";if(typeof o=="string")return o;if(typeof o=="object")return JSON.stringify(o)},name:"string",gender:"string",birthdate:o=>o?f.Birthdate(o):"",phone_number:o=>o?f.PhoneNumber(o):"",email_public:"boolean",phone_number_public:"boolean",address_public:"boolean",gender_public:"boolean",birthdate_public:"boolean",misc:"string",picture:o=>o?f.Url(o):"",profile:o=>o?f.Url(o):"",nickname:"string",website:o=>o?f.Url(o):""},["user_id"]),n=e.service,r=e.owner;if(delete e.service,delete e.owner,Object.keys(e).filter(o=>o!=="user_id"&&e[o]!==void 0).length===0)throw new a("At least one attribute to update is required.",{code:"INVALID_PARAMETER"});if(!await V.bind(this)()){if(!this.__user)throw new a("User needs to login.",{code:"INVALID_REQUEST"});if(this.__user.access_group<90)throw new a("Invalid access.",{code:"INVALID_REQUEST"})}e.email&&(e.preferred_username=(n||this.service)+"-"+q.hash(e.email));let s={attributes:e};return n&&r&&(s.service=n,s.owner=r),await E.bind(this)("admin-edit-profile",s,{auth:true})}async function Wn(t){if(typeof window>"u"||window._runningInNodeJS)throw new a("Push Notifications are not supported in Node.js environment.",{code:"NOT_SUPPORTED"});if(await this.__connection,!t.endpoint)throw new a("Missing parameter: endpoint",{code:"INVALID_PARAMETER"});if(!t.keys||!t.keys.p256dh||!t.keys.auth)throw new a("Missing parameter: keys.p256dh or keys.auth",{code:"INVALID_PARAMETER"});return await E.bind(this)("store-subscription",{endpoint:t.endpoint,keys:t.keys},{auth:true}),"SUCCESS: Subscribed to receive notifications."}async function zn(t){if(typeof window>"u"||window._runningInNodeJS)throw new a("Push Notifications are not supported in Node.js environment.",{code:"NOT_SUPPORTED"});if(await this.__connection,!t.endpoint)throw new a("Missing parameter: endpoint",{code:"INVALID_PARAMETER"});if(!t.keys||!t.keys.p256dh||!t.keys.auth)throw new a("Missing parameter: keys.p256dh or keys.auth",{code:"INVALID_PARAMETER"});return await E.bind(this)("delete-subscription",{endpoint:t.endpoint,keys:t.keys},{auth:true}),"SUCCESS: Unsubscribed from notifications."}async function Jn(){if(typeof window>"u"||window._runningInNodeJS)throw new a("Push Notifications are not supported in Node.js environment.",{code:"NOT_SUPPORTED"});return await this.__connection,{VAPIDPublicKey:await E.bind(this)("get-vapid-public-key",null,{auth:true})}}async function Gn(t,e){if(typeof window>"u"||window._runningInNodeJS)throw new a("Push Notifications are not supported in Node.js environment.",{code:"NOT_SUPPORTED"});await this.__connection;let{title:n,body:r}=U(t||{},{nullIfEmpty:true}).data;if(!n)throw new a("Missing parameter: message title",{code:"INVALID_PARAMETER"});if(!r)throw new a("Missing parameter: message body",{code:"INVALID_PARAMETER"});let i={title:n,body:r};return e?(typeof e=="string"&&(e=[e]),i.user_ids=e):i.user_ids="all_users",await E.bind(this)("push-notification",i,{auth:true}),"SUCCESS: Notification sent."}async function Xn(t){await this.__connection,t=f.Params(t,{spell:"string",name:"string",magic:n=>n},["spell","name"]);await E.bind(this)("castspell",t);return `The spell "${t.spell}" has been cast.`}async function Zn(t){return await this.__connection,t=f.Params(t||{},{search:["spell","name",()=>"spell"],value:"string"}),await E.bind(this)("getspell",t)}async function Yn(t){await this.__connection,t=f.Params(t,{message:"string",name:"string"},["message","name"]);let e=await E.bind(this)("dopamine",t,{auth:true}),n=e?.previous_message?.message,r=e?.previous_message?.name;if(j())n&&r&&window.alert(`${r} said: ${n}`),window.location.href=e.video;else return n&&r?`${r} said: ${n}
|
|
215
|
+
`,o=new Blob([s],{type:"application/javascript"});ne=new Worker(URL.createObjectURL(o)),ne.onmessage=l=>{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 l;switch(true){case !!o?.["#message"]:l="message";break;case !!o?.["#private"]:l="private";break;case !!o?.["#notice"]:l="notice";break;case !!o?.["#rtc"]:l="rtc";break;case !!o?.["#error"]:l="error";break}if(!l)return;let u={type:l,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(l==="notice")t(u);else if(l==="rtc"){if(u.sender!==this.user.user_id){let c=u.message;if(c.hungup){Q[u.sender_cid]&&(Q[u.sender_cid](false),delete Q[u.sender_cid]),G[u.sender_cid]&&delete G[u.sender_cid],S?.[u.sender_cid]&&H.bind(this)({cid:u.sender_cid}),u.type="rtc:closed",t(u);return}if(c.candidate&&Xe.bind(this)(c.candidate,u.sender_cid),c.sdpoffer&&(Ge.bind(this)(c.sdpoffer,u.sender_cid),G[u.sender_cid]||(G[u.sender_cid]=u.sender_cid,delete u.message,u.connectRTC=ln.bind(this)(u),u.type="rtc:incoming",u.hangup=(()=>{S[u.sender_cid]?H.bind(this)({cid:u.sender_cid}):G[u.sender_cid]&&(delete G[u.sender_cid],i.send(JSON.stringify({action:"rtc",uid:u.sender_cid,content:{hungup:this.user.user_id},token:this.session.accessToken.jwtToken})));}).bind(this),t(u))),c.pickup&&Q[u.sender_cid]&&(Q[u.sender_cid](true),delete Q[u.sender_cid]),c.sdpanswer&&S[u.sender_cid])if(S[u.sender_cid].signalingState==="have-local-offer")await S[u.sender_cid].setRemoteDescription(new RTCSessionDescription(c.sdpanswer));else throw new a("Invalid signaling state.",{code:"INVALID_REQUEST"})}}else t(u);},i.onclose=()=>{be?(this.log("realtime onclose","WebSocket connection closed."),t({type:"close",message:"WebSocket connection closed."})):(this.log("realtime onclose","WebSocket unexpected close."),t({type:"error",message:"Skapi: WebSocket unexpected close."}),ge++,ge<3?(this.log("realtime onclose","Reconnecting to WebSocket server..."+ge),t({type:"reconnect",message:"Reconnecting to WebSocket server..."+ge}),Oe.bind(this)(t,3e3,"reconnect")):(this.log("realtime onclose","Max reconnection attempts reached."),t({type:"error",message:"Skapi: Max reconnection attempts reached."})));},i.onerror=()=>{this.log("realtime onerror","WebSocket connection error."),t({type:"error",message:"Skapi: WebSocket connection error."});};},e);});}async function fn(t,e,n){if(typeof window>"u"||window._runningInNodeJS)throw new a("WebSocket is not supported in Node.js environment.",{code:"NOT_SUPPORTED"});let r=this.__socket?await this.__socket:this.__socket;if(!r)throw new a("No realtime connection. Execute connectRealtime() before this method.",{code:"INVALID_REQUEST"});if(!e)throw new a("No recipient.",{code:"INVALID_REQUEST"});await ce.bind(this)(),t=U(t).data;let i="";if(n&&(n=f.Params(n,{config:{always:"boolean"},title:"string",body:"string"},["title","body"]),i=JSON.stringify({title:n.title,body:n.body}),new Blob([i]).size>3072))throw new a("Notification size exceeds 3kb.",{code:"INVALID_PARAMETER"});if(r.readyState===1){try{f.UserId(e),r.send(JSON.stringify({action:"sendMessage",uid:e,content:t,notification:i,notificationConfig:n?.config||{},token:`IdT:${this.service}:${this.owner}:`+(this.bearerToken||this.session?.idToken?.jwtToken||"null")}));}catch(s){if(this.log("postRealtime:err",{err:s}),re!==e)throw new a(`User has not joined to the recipient group. Run joinRealtime({ group: "${e}" })`,{code:"INVALID_REQUEST"});r.send(JSON.stringify({action:"broadcast",rid:e,content:t,notification:i,notificationConfig:n?.config||{},token:`IdT:${this.service}:${this.owner}:`+(this.bearerToken||this.session?.idToken?.jwtToken||"null")}));}return {type:"success",message:"Message sent."}}throw new a("Realtime connection is not open. Try reconnecting with connectRealtime().",{code:"INVALID_REQUEST"})}async function Ye(t){if(typeof window>"u"||window._runningInNodeJS)throw new a("WebSocket is not supported in Node.js environment.",{code:"NOT_SUPPORTED"});let e=this.__socket?await this.__socket:this.__socket;if(!e)throw new a("No realtime connection. Execute connectRealtime() before this method.",{code:"INVALID_REQUEST"});await ce.bind(this)(),t=U(t,{nullIfEmpty:true}).data;let{group:n=null}=t;if(!n&&!re)return {type:"success",message:"Left realtime message group."};if(n!==null&&typeof n!="string")throw new a('"group" must be a string | null.',{code:"INVALID_PARAMETER"});return e.send(JSON.stringify({action:"joinRoom",rid:n,token:this.session.accessToken.jwtToken})),re=n,{type:"success",message:n?`Joined realtime message group: "${n}".`:"Left realtime message group."}}async function hn(t,e){t=f.Params(t,{user_id:r=>f.UserId(r,'User ID in "user_id"'),group:["string",()=>{if(!re)throw new a('No group has been joined. Otherwise "group" is required.',{code:"INVALID_REQUEST"});return re}]});let n=await R.bind(this)("get-ws-group",t,{fetchOptions:e,auth:true,method:"post"});return n.list=n.list.map(r=>({user_id:r.uid.split("#")[1],cid:"cid:"+r.cid})),n}async function pn(t,e){if(await this.__connection,t||(t={searchFor:"group",value:" ",condition:">"}),t=f.Params(t,{searchFor:["group","number_of_users",()=>"group"],value:["string","number",()=>t?.searchFor&&t?.searchFor==="number_of_users"?0:" "],condition:[">",">=","=","<","<=","!=","gt","gte","eq","lt","lte","ne"],range:["string","number"]}),t.condition||(t.value===" "||!t.value?t.condition=">":t.condition="="),t.range&&t.condition&&delete t.condition,t.searchFor==="number_of_users"&&typeof t.value!="number")throw new a('"value" must be a number.',{code:"INVALID_PARAMETER"});if(t.searchFor==="group"&&typeof t.value!="string")throw new a('"value" must be a string.',{code:"INVALID_PARAMETER"});if(t.hasOwnProperty("range")&&typeof t.range!=typeof t.value)throw new a(`"range" must be a ${typeof t.value}.`,{code:"INVALID_PARAMETER"});let n=await R.bind(this)("get-ws-group",t,{fetchOptions:e,auth:true,method:"post"});return n.list=n.list.map(r=>({group:r.rid.split("#")[1],number_of_users:r.cnt})),n}var _n=typeof FormData<"u",bn=typeof HTMLFormElement<"u",yn=typeof SubmitEvent<"u",X={},ye={},Z={};function et(t){return Object.freeze({id:t,status:"stopped"})}function wn(t){return !!t&&typeof t=="object"&&t.status==="stopped"}function En({id:t,auth:e,service:n,owner:r,latency:i=1e3,queue:s,onResponse:o,onError:l}){if(typeof i!="number")throw new a('"latency" should be a number.',{code:"INVALID_PARAMETER"});if(i<0)throw new a('"latency" should be a non-negative number.',{code:"INVALID_PARAMETER"});s&&!X?.[s]&&(X[s]=new mn__default.default({breakWhenError:false,batchSize:1}));let u={stop:null,aborted:false,queue:s};Z[t]=u;let c=()=>{Z[t]===u&&delete Z[t];},d=()=>new Promise((h,_)=>{let p=false;if(u.aborted){c(),h(et(t));return}let y=setInterval(async()=>{try{let P=await R.bind(this)("csr-poll",{id:t,service:n,owner:r},{auth:e});if(P.status==="running"||P.status==="pending"||p)return;p=!0,o&&o(P),clearInterval(y),c(),h(P);}catch(P){if(p)return;p=true,l&&l(P),clearInterval(y),c(),_(P);}},i);u.stop=()=>{p||(p=true,clearInterval(y),c(),h(et(t)));};}),g=()=>{let h=Z[t];h&&(h.stop?h.stop():(h.aborted=true,delete Z[t]));};if(s){let h=new Promise((_,p)=>{let y=false,P=X[s].add([async()=>{try{let m=await d();return y||(y=!0,_(m)),m}catch(m){throw y||(y=true,p(m)),m}}])[0];ye[t]=P,u.stop=()=>{if(!y){u.aborted=true;try{X[s]&&X[s].remove(ye[t]);}catch{}delete ye[t],c(),y=true,_(et(t));}};});return Object.assign(h,{stop:g})}else return Object.assign(d(),{stop:g})}function Rn(t){let e=0,n=[];if(t?.id){if(t.url&&t.method){let r=t.service||this.service;n.push(`[${t.method.toUpperCase()}]${t.url.toLowerCase()}#${r}:${t.id}`);}n.push(t.id);}else if(t?.queue)for(let r in Z)Z[r]?.queue===t.queue&&n.push(r);else for(let r in Z)n.push(r);for(let r of n){let i=Z[r];i&&(i.stop?i.stop():(i.aborted=true,delete Z[r]),e+=1);}return e}function An(t,e){if(!t.queue)throw new a('"queue" is required.',{code:"INVALID_PARAMETER"});let n={service:t.service||this.service,owner:t.owner||this.owner,queue:t.queue+":"};return R.bind(this)("csr-poll",n,{auth:true})}async function In(t){let e=false;if(typeof t.poll=="number"&&t.poll<0)throw new a('"poll" should be a non-negative number.',{code:"INVALID_PARAMETER"});let n=t?.onResponse,r=t?.onError,i=typeof t.poll=="number"?t.poll:t.poll?1e3:0;delete t.poll,i&&!t.queue&&(t.queue=(this.__user?.user_id||"anonymous")+"-"+ie());let s=u=>{for(let c in u)if(typeof u[c]=="string"&&u[c].includes("$CLIENT_SECRET")){e=true;break}};if(t=f.Params(t,{url:u=>{if(!u||typeof u!="string")throw new a('"url" should be type: <string>.',{code:"INVALID_PARAMETER"});return f.Url(u),u.includes("$CLIENT_SECRET")&&(e=true),u},clientSecretName:"string",method:u=>{if(u&&typeof u!="string")throw new a('"method" should be either "GET" or "POST" or "DELETE" or "PUT".',{code:"INVALID_PARAMETER"});let c=u.toLowerCase();if(c!=="get"&&c!=="post"&&c!=="delete"&&c!=="put")throw new a('"method" should be either "GET" or "POST" or "DELETE" or "PUT".',{code:"INVALID_PARAMETER"});return c},headers:u=>{if(u&&typeof u!="object")throw new a('"headers" should be type: <object>.',{code:"INVALID_PARAMETER"});return s(u),u},data:u=>{if(u&&typeof u!="object")throw new a('"data" should be type: <object>.',{code:"INVALID_PARAMETER"});return s(u),u},params:u=>{if(u&&typeof u!="object")throw new a('"params" should be type: <object>.',{code:"INVALID_PARAMETER"});return s(u),u},expires:"number",queue:"string"},["clientSecretName","method","url"]),!e)throw new a(`At least one parameter value should include "$CLIENT_SECRET" in ${t.method.toLowerCase()==="post"?'"data"':'"params"'} or "headers".`,{code:"INVALID_PARAMETER"});await this.__connection;let o=!!this.__user,l=()=>R.bind(this)("csr",t,{auth:o,tokenHeaders:{accessToken:!!o}}).then(u=>{if(u.status==="running"||u.status==="pending"){let c=`[${t.method.toUpperCase()}]${t.url.toLowerCase()}`,d=t.service||this.service,g=t.owner||this.owner,h=`${c}#${d}:${u.id}`;Object.assign(u,{poll:_=>En.call(this,{id:h,auth:o,service:d,owner:g,latency:_?.latency||1e3,queue:t?.queue,onResponse:n,onError:r})});}return n?n(u):u}).catch(u=>{if(r)return r(u);throw u});if(t?.queue){let u="base:"+t.queue;return X?.[u]||(X[u]=new mn__default.default({breakWhenError:false,batchSize:1})),new Promise((c,d)=>{X[u].add([async()=>{try{let g=await l();if(i>0){let h=g.poll({latency:i});return c(h),h}return c(g),g}catch(g){throw d(g),g}}]);})}else return l()}async function Tn(t,e){await this.__connection;let n=t.service||this.service,r=t.owner||this.owner;t=f.Params(t,{url:"string",method:["GET","POST","DELETE","PUT"],queue:"string",status:["pending","running","resolved","failed"],compact:"boolean",queue_exact:"boolean",queue_exclude:"string"},["url","method"]);let i=!!this.__user,s=`[${t.method.toUpperCase()}]${t.url.toLowerCase()}#${n}:`,o={id:s,queue:t?.queue,status:t?.status,service:n,owner:r};t?.compact&&(o.compact=true),t?.queue_exact&&(o.queue_exact=true),t?.queue_exclude&&(o.queue_exclude=t.queue_exclude),Object.keys(o).forEach(u=>{o[u]||delete o[u];}),o.queue&&(o.id_prefix=o.id,delete o.id);let l=await R.bind(this)("csr-poll",o,{auth:i,fetchOptions:e});return l.list=l.list.map(u=>{let c={id:u.id,status_code:u.rslv?.status_code||null,response_body:u.rslv?.body||u.rslv?.truncated||null,error:u?.err,created:u?.stmp,updated:u?.utmp,request_body:u?.reqbdy,expires:u?.expt,status:u.stts,queue_name:u?.qid,request_text:u?.reqtxt,response_text:u?.rslvtxt,response_complete_marker:u?.rslvmk!=null?!!u.rslvmk:void 0,compact:u?.cmpct?true:void 0};for(let d in c)c[d]===void 0&&delete c[d];return (c.status==="running"||c.status==="pending")&&(c.poll=d=>En.call(this,{id:s+c.id,auth:i,service:n,owner:r,latency:d?.latency||1e3,queue:u?.qid,onResponse:d?.onResponse,onError:d?.onError})),c}),l}async function Pn(t){await this.__connection,t=f.Params(t,{url:"string",method:["GET","POST","DELETE","PUT"],id:"string",queue:"string"},["url","method","id"]);let e=t?.service||this.service,n=t?.owner||this.owner,r=!!this.__user,i=`[${t.method.toUpperCase()}]${t.url.toLowerCase()}#${e}`,s=t.id,o=`${i}:${s}`,l=t?.queue;return l&&X?.[l]&&(X[l].remove(ye[o]),delete ye[o]),R.bind(this)("csr-cancel",{id:o,service:e,owner:n},{auth:r})}async function Sn(t){await this.__connection;let e={name:"string",email:n=>(f.Email(n),n),subject:"string",message:"string"};return t=f.Params(t,e,["name","email","subject","message"]),await R.bind(this)("send-inquiry",t),"SUCCESS: Inquiry has been sent."}async function kn(t,e){if(await this.__connection,_n&&t instanceof FormData||bn&&t instanceof HTMLFormElement||yn&&t instanceof SubmitEvent){if(!e)throw new a("Url string as a second argument is required when form is passed.",{code:"INVALID_PARAMETER"});let r=U(t);t={url:e,data:r.data,sync:true};}let n={url:r=>f.Url(r),data:r=>r,sync:["boolean",()=>true]};if(Array.isArray(t))for(let r of t)r=f.Params(r,n);else t=f.Params(t,n);return R.bind(this)("post-secure",t,{auth:true})}async function xn(t,e){await this.__connection;let{auth:n=false,method:r="POST",bypassAwaitConnection:i=false,responseType:s,contentType:o,tokenHeaders:l,progress:u}=e||{};if(e=Object.assign({auth:n,method:r,bypassAwaitConnection:i,responseType:s,contentType:o,tokenHeaders:l},{fetchOptions:{progress:u}}),typeof t!="object"&&(o==="application/json"||o===void 0))throw new a('"data" should be type: <object>.',{code:"INVALID_PARAMETER"});return R.bind(this)("mock",t,e)}async function vn(t,e){if(await this.__connection,!e?.url||typeof e.url!="string")throw new a('"url" is required in the second argument.',{code:"INVALID_PARAMETER"});f.Url(e.url);let r=(await this.admin_endpoint)?.forward_request;if(!r)throw new a("forwardRequest is not available on this service region yet.",{code:"NOT_EXISTS"});let i=null,s=null,o=yn&&t instanceof SubmitEvent?t.target:bn&&t instanceof HTMLFormElement?t:null;o?i=new FormData(o):_n&&t instanceof FormData?i=t:t!=null&&(i=JSON.stringify(t),s="application/json");let l={public_identifier:this.__public_identifier,service:this.service,owner:this.owner,forward:{url:e.url,method:e.method||"POST",headers:e.headers||{},apiKeyHeader:e.apiKeyHeader,apiKeyScheme:e.apiKeyScheme}},u=JSON.stringify(l);if(u.length>4096)throw new a("Destination url and headers are too large for Content-Meta.",{code:"INVALID_PARAMETER"});let c=this.bearerToken||this.session?.idToken?.jwtToken||null;if(!c)throw new a("User login is required.",{code:"INVALID_REQUEST"});let d={"Content-Meta":u,Authorization:c};s&&(d["Content-Type"]=s);let g=await fetch(r,{method:"POST",headers:d,body:i,signal:e.signal});if(e.responseType==="response")return g;if(!g.ok){let _=await g.text();try{_=JSON.parse(_);}catch{}throw new a(_?.message||(typeof _=="string"?_:JSON.stringify(_)),{code:_?.code||"ERROR"})}if(e.onStream&&g.body){let _=g.body.getReader(),p=new TextDecoder,y="";for(;;){let{done:P,value:m}=await _.read();if(P)break;let I=p.decode(m,{stream:true});y+=I;try{e.onStream(I);}catch(x){console.error(x);}}return y}let h=await g.text();if(e.responseType==="text")return h;try{return JSON.parse(h)}catch{return h}}async function Dn(t,e){await this.__connection,t=f.Params(t||{},{access_group:r=>{if(r==="authorized"&&(r=1),r==="public"&&(r=0),typeof r!="number")throw new a('"access_group" should be type number.',{code:"INVALID_PARAMETER"});if(r<0)throw new a('"access_group" should be zero or a positive number.',{code:"INVALID_PARAMETER"});if(r>this.__user.access_group)throw new a("User has no access.",{code:"INVALID_REQUEST"});return r}});let n=await R.bind(this)("get-feed",t,{auth:true,fetchOptions:e});for(let r in n.list)n.list[r]=await de.bind(this)(n.list[r]);return n}function we(t){if(t===this.__user.user_id)throw new a(`"user_id" cannot be the user's own ID.`,{code:"INVALID_PARAMETER"});return f.UserId(t,'"user_id"')}async function Nn(t,e){if(t=U(t,{ignoreEmpty:true}).data,t=f.Params(t,{subscriber:r=>f.UserId(r,'User ID in "subscriber"'),subscription:we.bind(this),blocked:"boolean"}),!t.subscriber&&!t.subscription)throw new a('At least either "subscriber" or "subscription" should have a value.',{code:"INVALID_PARAMETER"});let n=await R.bind(this)("get-subscription",t,Object.assign({auth:true},{fetchOptions:e}));return n.list=n.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})),n}async function Un(t){await this.__connection,t=f.Params(t,{user_id:we.bind(this),get_feed:["boolean",()=>false],get_notified:["boolean",()=>false],get_email:r=>{if(r&&!this.__user.email||!this.__user.email_verified)throw new a("User has no verified email address.",{code:"INVALID_REQUEST"});return !!r}},["user_id"]);let e=await R.bind(this)("subscription",{subscribe:t.user_id,option:{get_feed:t.get_feed,get_notified:t.get_notified,get_email:t.get_email||false}},{auth:true}),n={};if(e.sub){let r=e.sub.split("#");n.subscriber=r[2],n.subscription=r[0];}else n.subscriber=e.subscriber,n.subscription=e.subscription;return n.timestamp=e?.timestamp||e.stmp,n.blocked=e?.blocked||e.grp.substring(0,1)==="N",Object.assign(n,e.opt),n}async function Cn(t){await this.__connection;let{user_id:e}=f.Params(t,{user_id:we.bind(this)},["user_id"]);return await R.bind(this)("subscription",{unsubscribe:e},{auth:true})}async function Ln(t){await this.__connection;let{user_id:e}=f.Params(t,{user_id:we.bind(this)},["user_id"]);return await R.bind(this)("subscription",{block:e},{auth:true})}async function On(t){await this.__connection;let{user_id:e}=f.Params(t,{user_id:we.bind(this)},["user_id"]);return await R.bind(this)("subscription",{unblock:e},{auth:true})}async function Mn(t,e){await this.__connection;let n=await V.bind(this)();t=f.Params(t,{user_id:o=>{if(o!==this.__user.user_id&&!n)throw new a("No access.",{code:"INVALID_REQUEST"});return o},group:o=>{if(o==="public"&&(o=0),o==="authorized"&&(o=1),typeof o!="number")throw new a('"group" should be type number | "public" | "authorized".',{code:"INVALID_PARAMETER"});return o}});let r=await R.bind(this)("get-newsletter-subscription",t,{auth:true,fetchOptions:e||null}),i=r?.list||r,s=[];Array.isArray(i)||(i=[]);for(let o of i){let l=o.subt.split("#"),u=true;l[0].charAt(0)==="@"&&(u=false,l[0]=l[0].substring(1));let c=parseInt(l[0]);s.push({timestamp:o.stmp,group:c,subscribed_email:l[1],active:u});}return r?.list?(r.list=s,r):s}async function qn(t){await this.__connection;let e=f.Params(t||{},{email:n=>Array.isArray(n)&&n.length>0?n.length===1?f.Email(n[0]):n.map(r=>f.Email(r)):f.Email(n),group:["number","public","authorized","admin",n=>{if(typeof n!="string"||n.length>20||!/^[a-zA-Z0-9]+$/.test(n))throw new a('"group" should be an alphanumeric string without spaces and less than 20 characters.',{code:"INVALID_PARAMETER"});return n}],redirect:n=>f.Url(n)},this.__user?["group"]:["email","group"]);return R.bind(this)(`subscribe-${this.__user?"":"public-"}newsletter`,e,{auth:!!this.__user})}async function Fn(t){await this.__connection,t=f.Params(t,{group:["number","public","authorized","admin"]},["group"]);let e=Object.assign({action:"unsubscribe"},t);return R.bind(this)("subscribe-newsletter",e,{auth:true})}async function Vn(t,e){let n=await V.bind(this)(),r={message_id:"string",timestamp:"number",read:"number",complaint:"number",subject:"string",bounced:"number"};t||(e=Object.assign({ascending:false},e||{})),t=U(t).data,t=t||{searchFor:"timestamp",value:Date.now(),condition:"<",group:"public"},t=f.Params(t,{searchFor:["message_id","timestamp","subject","complaint","read","bounced"],value:u=>{if(typeof u!==r[t.searchFor])throw new a(`"value" type does not match the type of "${t.searchFor}" index.`,{code:"INVALID_PARAMETER"});if(typeof u=="string"&&!u)throw new a('"value" should not be empty string.',{code:"INVALID_PARAMETER"});return u},range:u=>{if(!t.hasOwnProperty("value")||typeof u!=typeof t.value)throw new a('"range" should match type of "value".',{code:"INVALID_PARAMETER"});return u},condition:[">",">=","=","<","<=","gt","gte","eq","lt","lte",()=>"="],group:u=>{if(u==="public")return 0;if(!this.session)throw new a("User should be logged in.",{code:"INVALID_REQUEST"});if(u==="authorized")return 1;if(typeof u=="number"){if(!n&&u>parseInt(this.user?.access_group||this.session?.idToken?.payload?.access_group))throw new a("User has no access.",{code:"INVALID_REQUEST"});return u}throw new a('"group" should be type: number | "public" | "authorized".',{code:"INVALID_PARAMETER"})}},["searchFor","value","group"]);let i=t.group===0?"get-public-newsletters":"get-newsletters",s=await R.bind(this)(i,t,Object.assign({method:"get",auth:i==="get-public-newsletters"?!!this.__user:true},{fetchOptions:e})),o={message_id:"mid",timestamp:"stmp",complaint:"cmpl",read:"read",subject:"subj",bounced:"bnce",url:"url",delivered:"delv"},l={message_id:"",timestamp:0,complaint:0,read:0,subject:"",bounced:"",url:"",delivered:0};return s.list=s.list.map(u=>{let c={};for(let d in o)c[d]=u[o[d]]||l[d];return c.bounced=String(c.bounced),c}),s}async function $n(t){let e=f.Params(t,{user_id:r=>f.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 V.bind(this)()){if(!this.__user)throw new a("User needs to login.",{code:"INVALID_REQUEST"});if(this.__user.access_group<90)throw new a("Invalid access.",{code:"INVALID_REQUEST"})}return await R.bind(this)("block-account",e,{auth:true})}async function jn(t){let e=f.Params(t,{user_id:r=>f.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 V.bind(this)()){if(!this.__user)throw new a("User needs to login.",{code:"INVALID_REQUEST"});if(this.__user.access_group<90)throw new a("Invalid access.",{code:"INVALID_REQUEST"})}return await R.bind(this)("block-account",e,{auth:true})}async function Bn(t){let e=f.Params(t,{user_id:r=>f.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 V.bind(this)()){if(!this.__user)throw new a("User needs to login.",{code:"INVALID_REQUEST"});if(this.__user.access_group<90)throw new a("Invalid access.",{code:"INVALID_REQUEST"})}return await R.bind(this)("remove-account",e,{auth:true})}async function Kn(t,e){let n={email:s=>f.Email(s),password:s=>f.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=>f.Birthdate(s),phone_number:s=>f.PhoneNumber(s),picture:s=>{if(s)return f.Url(s)},profile:s=>{if(s)return f.Url(s)},website:s=>{if(s)return f.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 a('"access_group" is invalid. Should be type <number>.',{code:"INVALID_PARAMETER"})}if(typeof s!="number"||s<1||s>100)throw new a('"access_group" is invalid. Should be type <number> of range 1~99',{code:"INVALID_PARAMETER"});return s}},r=f.Params(t,n,["email"]);if(e=f.Params(e,{confirmation_url:s=>{let o=s;if(typeof s=="string")o=f.Url(s);else throw new a('"options.confirmation_url" should be type: <string>.',{code:"INVALID_PARAMETER"});if(o&&!r.email)throw new a('"email" is required for signup confirmation.',{code:"INVALID_PARAMETER"});return o},email_subscription:s=>{if(typeof s!="boolean")throw new a('"options.email_subscription" should be type: <boolean>.',{code:"INVALID_PARAMETER"});if(!e?.confirmation_url)throw new a('"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 a('"options.template" should be type: <object> with "url" and "subject".',{code:"INVALID_PARAMETER"});return {url:f.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 V.bind(this)()){if(!this.__user)throw new a("User needs to login.",{code:"INVALID_REQUEST"});if(this.__user.access_group<90)throw new a("Invalid access.",{code:"INVALID_REQUEST"})}return await R.bind(this)("admin-signup",r,{auth:true})}async function Qn(t){let e={email:s=>f.Email(s),password:s=>f.Password(s),openid_id:"string",name:"string",username:"string",gender:"string",address:s=>{if(!s)return "";if(typeof s=="string")return s;if(typeof s=="object")return JSON.stringify(s)},birthdate:s=>f.Birthdate(s),phone_number:s=>f.PhoneNumber(s),picture:s=>s?f.Url(s):"",profile:s=>s?f.Url(s):"",website:s=>s?f.Url(s):"",nickname:"string",misc:"string",email_public:["boolean",()=>false],gender_public:["boolean",()=>false],address_public:["boolean",()=>false],birthdate_public:["boolean",()=>false],phone_number_public:["boolean",()=>false],access_group:s=>{try{typeof s=="string"&&(s=parseInt(s));}catch{throw new a('"access_group" is invalid. Should be type <number>.',{code:"INVALID_PARAMETER"})}if(typeof s!="number"||s<1||s>100)throw new a('"access_group" is invalid. Should be type <number> of range 1~99',{code:"INVALID_PARAMETER"});return s}},n=["email","password"],r=f.Params(t,e,n);if(!await V.bind(this)()){if(!this.__user)throw new a("User needs to login.",{code:"INVALID_REQUEST"});if(this.__user.access_group<90)throw new a("Invalid access.",{code:"INVALID_REQUEST"})}return await R.bind(this)("admin-signup",r,{auth:true})}async function Hn(t){if(t=f.Params(t,{user_id:n=>f.UserId(n,'"user_id"'),access_group:n=>{try{typeof n=="string"&&(n=parseInt(n));}catch{throw new a('"access_group" is invalid. Should be type <number>.',{code:"INVALID_PARAMETER"})}if(typeof n=="number"&&n>0&&n<100)return n;throw new a('"access_group" is invalid. Should be type <number> of range 1~99',{code:"INVALID_PARAMETER"})}},["user_id","access_group"]),!await V.bind(this)()){if(!this.__user)throw new a("User needs to login.",{code:"INVALID_REQUEST"});if(this.__user.access_group<90)throw new a("Invalid access.",{code:"INVALID_REQUEST"})}return await R.bind(this)("grant-access",t,{auth:true})}async function Wn(t,e){if(t=f.Params(t,{email:"string"}),!await V.bind(this)()){if(!this.__user)throw new a("User needs to login.",{code:"INVALID_REQUEST"});if(this.__user.access_group<90)throw new a("Invalid access.",{code:"INVALID_REQUEST"})}let r=await R.bind(this)("invitation-list",Object.assign({mode:"search"},t),{fetchOptions:e,auth:true});return r.list=r.list.map(i=>fe(i.user)),r}async function Jn(t){if(t=f.Params(t,{email:n=>f.Email(n)},["email"]),!await V.bind(this)()){if(!this.__user)throw new a("User needs to login.",{code:"INVALID_REQUEST"});if(this.__user.access_group<90)throw new a("Invalid access.",{code:"INVALID_REQUEST"})}return await R.bind(this)("invitation-list",Object.assign({mode:"cancel"},t),{auth:true})}async function zn(t){if(t=f.Params(t,{email:n=>f.Email(n)},["email"]),!await V.bind(this)()){if(!this.__user)throw new a("User needs to login.",{code:"INVALID_REQUEST"});if(this.__user.access_group<90)throw new a("Invalid access.",{code:"INVALID_REQUEST"})}return await R.bind(this)("invitation-list",Object.assign({mode:"resend"},t),{auth:true})}async function Gn(t){let e=f.Params(t,{user_id:o=>f.UserId(o,'"user_id"'),email:o=>f.Email(o),address:o=>{if(!o)return "";if(typeof o=="string")return o;if(typeof o=="object")return JSON.stringify(o)},name:"string",gender:"string",birthdate:o=>o?f.Birthdate(o):"",phone_number:o=>o?f.PhoneNumber(o):"",email_public:"boolean",phone_number_public:"boolean",address_public:"boolean",gender_public:"boolean",birthdate_public:"boolean",misc:"string",picture:o=>o?f.Url(o):"",profile:o=>o?f.Url(o):"",nickname:"string",website:o=>o?f.Url(o):""},["user_id"]),n=e.service,r=e.owner;if(delete e.service,delete e.owner,Object.keys(e).filter(o=>o!=="user_id"&&e[o]!==void 0).length===0)throw new a("At least one attribute to update is required.",{code:"INVALID_PARAMETER"});if(!await V.bind(this)()){if(!this.__user)throw new a("User needs to login.",{code:"INVALID_REQUEST"});if(this.__user.access_group<90)throw new a("Invalid access.",{code:"INVALID_REQUEST"})}e.email&&(e.preferred_username=(n||this.service)+"-"+F.hash(e.email));let s={attributes:e};return n&&r&&(s.service=n,s.owner=r),await R.bind(this)("admin-edit-profile",s,{auth:true})}async function Xn(t){if(typeof window>"u"||window._runningInNodeJS)throw new a("Push Notifications are not supported in Node.js environment.",{code:"NOT_SUPPORTED"});if(await this.__connection,!t.endpoint)throw new a("Missing parameter: endpoint",{code:"INVALID_PARAMETER"});if(!t.keys||!t.keys.p256dh||!t.keys.auth)throw new a("Missing parameter: keys.p256dh or keys.auth",{code:"INVALID_PARAMETER"});return await R.bind(this)("store-subscription",{endpoint:t.endpoint,keys:t.keys},{auth:true}),"SUCCESS: Subscribed to receive notifications."}async function Zn(t){if(typeof window>"u"||window._runningInNodeJS)throw new a("Push Notifications are not supported in Node.js environment.",{code:"NOT_SUPPORTED"});if(await this.__connection,!t.endpoint)throw new a("Missing parameter: endpoint",{code:"INVALID_PARAMETER"});if(!t.keys||!t.keys.p256dh||!t.keys.auth)throw new a("Missing parameter: keys.p256dh or keys.auth",{code:"INVALID_PARAMETER"});return await R.bind(this)("delete-subscription",{endpoint:t.endpoint,keys:t.keys},{auth:true}),"SUCCESS: Unsubscribed from notifications."}async function Yn(){if(typeof window>"u"||window._runningInNodeJS)throw new a("Push Notifications are not supported in Node.js environment.",{code:"NOT_SUPPORTED"});return await this.__connection,{VAPIDPublicKey:await R.bind(this)("get-vapid-public-key",null,{auth:true})}}async function er(t,e){if(typeof window>"u"||window._runningInNodeJS)throw new a("Push Notifications are not supported in Node.js environment.",{code:"NOT_SUPPORTED"});await this.__connection;let{title:n,body:r}=U(t||{},{nullIfEmpty:true}).data;if(!n)throw new a("Missing parameter: message title",{code:"INVALID_PARAMETER"});if(!r)throw new a("Missing parameter: message body",{code:"INVALID_PARAMETER"});let i={title:n,body:r};return e?(typeof e=="string"&&(e=[e]),i.user_ids=e):i.user_ids="all_users",await R.bind(this)("push-notification",i,{auth:true}),"SUCCESS: Notification sent."}async function tr(t){await this.__connection,t=f.Params(t,{spell:"string",name:"string",magic:n=>n},["spell","name"]);await R.bind(this)("castspell",t);return `The spell "${t.spell}" has been cast.`}async function nr(t){return await this.__connection,t=f.Params(t||{},{search:["spell","name",()=>"spell"],value:"string"}),await R.bind(this)("getspell",t)}async function rr(t){await this.__connection,t=f.Params(t,{message:"string",name:"string"},["message","name"]);let e=await R.bind(this)("dopamine",t,{auth:true}),n=e?.previous_message?.message,r=e?.previous_message?.name;if(j())n&&r&&window.alert(`${r} said: ${n}`),window.location.href=e.video;else return n&&r?`${r} said: ${n}
|
|
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 w=class{constructor(e,n,r,i){this.__version="2.0.0-rc.
|
|
217
|
+
Watch the video here: ${e.video}`}var w=class{constructor(e,n,r,i){this.__version="2.0.0-rc.4";this.project_id="";this.session=null;this.connection=null;this.__my_unique_ids={};this.__uniqueIdsPersistTimer=null;this.userPool=null;this.__socket=null;this.__mediaStream=null;this.host="skapi";this.hostDomain="skapi.com";this.target_cdn="d3e9syvbtso631";this.customApiDomain="skapi.dev";this.requestBatchSize=30;this.__disabledAccount=null;this.__cached_requests={};this.__startKeyHistory={};this.__request_signup_confirmation=null;this.__private_access_key={};this.__class_properties_has_been_cached=false;this.__user=null;this._userProfileListeners=[];this._onLoginListeners=[];this._onBatchProcessListeners=[];this.validate={userId(e){try{return f.UserId(e),!0}catch{return false}},url(e){try{return f.Url(e),!0}catch{return false}},phoneNumber(e){try{return f.PhoneNumber(e),!0}catch{return false}},birthdate(e){try{return f.Birthdate(e),!0}catch{return false}},email(e){try{return f.Email(e),!0}catch{return false}},params(e,n,r){return f.Params(e,n,r)}};this.util={MD5:F,generateRandom:ie,toBase62:at,fromBase62:B,decodeProjectId:Fe,formatServiceId:Ve,extractFormData:U,terminatePendingRequests:Ct,request:(e,n,r)=>R.bind(this)(e,n,r,{ignoreService:true})};this.__network_logs=false;this.__endpoint_version="v2";this.__public_identifier="";this.bearerToken="";this.registerTicket=gt.bind(this);this.unregisterTicket=ft.bind(this);if(!e||typeof e!="string")throw this._alert("Service ID is required."),new a("Service ID is required.",{code:"INVALID_PARAMETER"});let s=e.trim().toLowerCase().replace(/^<|>$/g,"").replace(/[\s_\-.]+/g,"");if(s==="serviceid"||s==="projectid")throw this._alert(`Replace "${e}" with your actual Project ID.`),new a("Project ID is required.",{code:"INVALID_PARAMETER"});let o=e.split("-").length;if(o===2||o===7)try{let m=Fe(e);r&&typeof r=="object"&&(i=r),n&&typeof n=="object"&&(r=n),n=m.owner,e=m.service;}catch{throw this._alert("Service ID is invalid."),new a("Service ID is invalid.",{code:"INVALID_PARAMETER"})}if(!n||typeof n!="string")throw this._alert("Owner ID is invalid."),new a("Owner ID is invalid.",{code:"INVALID_PARAMETER"});if(n!==this.host)try{f.UserId(n,'"owner"');}catch{throw this._alert("Owner ID is invalid."),new a("Owner ID is invalid.",{code:"INVALID_PARAMETER"})}this.service=e,this.owner=n;try{this.project_id=Ve(e,n);}catch{this.project_id="";}let c=true,d=false;if(r&&(typeof r.refetchServiceInfo=="boolean"&&(d=r.refetchServiceInfo),typeof r.autoLogin=="boolean"&&(c=r.autoLogin),typeof r.requestBatchSize=="number")){if(r.requestBatchSize<1)throw new a('"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 g=`https://${this.target_cdn}.cloudfront.net`,h=e.substring(0,4);this.admin_endpoint=fetch(`${g}/${h}/admin-${this.__endpoint_version}.json`).then(m=>m.blob()).then(m=>new Promise((I,x)=>{let T=new FileReader;T.onloadend=()=>I(T.result),T.onerror=x,T.readAsDataURL(m);})).then(m=>{try{return typeof m=="string"?JSON.parse(atob(m.split(",")[1])):null}catch{throw new a("Service does not exist. Create your service from skapi.com",{code:"NOT_EXISTS"})}}),this.record_endpoint=fetch(`${g}/${h}/record-${this.__endpoint_version}.json`).then(m=>m.blob()).then(m=>new Promise((I,x)=>{let T=new FileReader;T.onloadend=()=>I(T.result),T.onerror=x,T.readAsDataURL(m);})).then(m=>{try{return typeof m=="string"?JSON.parse(atob(m.split(",")[1])):null}catch{throw new a("Service does not exist. Create your service from skapi.com",{code:"NOT_EXISTS"})}});let _=j();if(_&&!window.sessionStorage)throw this._alert("This browser is not supported."),new Error("This browser is not supported.");let p=_?JSON.parse(window.sessionStorage.getItem(`${e}#${n}`)||"null"):null;if(this.log("constructor:restore",p),p?.connection){for(let m in p)this[m]=p[m];p.__public_identifier||(this.__public_identifier=`${this.service}:${this.owner}:${ie(16)}`);}this.__authConnection=(async()=>{let m=await this.admin_endpoint,I={UserPoolId:m.userpool_id,ClientId:m.userpool_client};qe()&&(I.Storage=window.localStorage),this.userPool=new amazonCognitoIdentityJs.CognitoUserPool(I);try{this.user||await $.bind(this)().getSession({skipUserUpdateEventTrigger:!0}),this.user&&(!p?.connection&&!c?te.bind(this)():(this._runOnLoginListeners(this.user),this._runOnUserUpdateListeners(this.user)));}catch{}})();let y=`${this.service}/${this.owner}`,P=_?window.sessionStorage.getItem(`${y}:uniqueids`):null;if(P)try{let m=JSON.parse(P);this.__my_unique_ids=m&&typeof m=="object"&&!Array.isArray(m)?{[y]:m}:{};}catch{this.__my_unique_ids={};}this.__connection=(async()=>{let m=null;await this.record_endpoint,p?.connection||(m=this._updateConnection({refresh:d}));let I=()=>{if(this.__class_properties_has_been_cached)return;let x=()=>{let T={},v=["__startKeyHistory","__disabledAccount","__cached_requests","__request_signup_confirmation","__public_identifier","connection"];if(this.connection){for(let C of v)T[C]=this[C];if(_){let C=`${e}#${n}`;try{window.sessionStorage.setItem(C,JSON.stringify(T));}catch{try{let M=Object.assign({},T,{__cached_requests:{},__startKeyHistory:{}});window.sessionStorage.setItem(C,JSON.stringify(M));}catch{try{window.sessionStorage.removeItem(C);}catch{}}}}this.__class_properties_has_been_cached=true;}};return m instanceof Promise?m.then(()=>x()):x()};return _&&(window.addEventListener("beforeunload",()=>{this.closeRealtime(),I();}),window.addEventListener("visibilitychange",()=>{I();})),await m,await this.__authConnection,this.connection})(),this.__connection.then(m=>{((m?.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 n of this._userProfileListeners)typeof n=="function"&&n(e);}_runOnLoginListeners(e){for(let n of this._onLoginListeners)typeof n=="function"&&n(e);}get onBatchProcess(){return this._onBatchProcessListeners}set onBatchProcess(e){typeof e=="function"&&this._onBatchProcessListeners.push(e);}_alert(e){j()&&typeof window.alert=="function"&&window.alert(e);}async getConnectionInfo(e){e?.refresh&&(this.__connection instanceof Promise&&await this.__connection,this.__connection=this._updateConnection({refresh:true}));let r=await this.__connection,i=r?.user_agent||(j()&&typeof window.navigator?.userAgent=="string"?window.navigator.userAgent:`skapi-node/${globalThis?.process?.versions?.node||"unknown"}`);return {project_id:this.project_id,user_ip:r.ip,user_agent:i,user_location:r.locale,service_name:r.service_name,version:this.__version,service_description:r?.service_description||"",ai_agent:r?.ai_agent||"",conf:r?.opt}}async _updateConnection(e){let n=e?.refresh||false;try{this.connection=await R.bind(this)("service",{service:this.service,owner:this.owner,refresh:n},{bypassAwaitConnection:!0,method:"get"});}catch(r){throw this.log("connection fail",r),this._alert("Service is not available: "+(r.message||r.toString())),this.connection=null,r}return this.connection}async version(){if(await this.__connection,j()){let n=`Built with:
|
|
218
218
|
%c\r
|
|
219
219
|
$$\\ $$\\ \r
|
|
220
220
|
$$ | \\__|\r
|
|
@@ -229,6 +229,6 @@ $$$$$$$ |$$ | \\$$\\\\$$$$$$$ |$$$$$$$ |$$ |\r
|
|
|
229
229
|
\\__| \r
|
|
230
230
|
Version: ${this.__version}
|
|
231
231
|
|
|
232
|
-
Full Documentation: https://docs.skapi.com/skapi.md`;console.log(n,"font-family: monospace; color:blue;"),this.connection.group===1&&console.log("%cSKAPI: THE SERVICE IS IN TRIAL MODE.","font-family: monospace; color:red;");}return this.__version}log(e,n){if(this.__network_logs){if(n!==null&&typeof n=="object")try{j()?n=JSON.parse(JSON.stringify(n)):n=JSON.stringify(n,null,2);}catch{n=String(n);}else typeof n=="string"&&n.length>100&&(n=n.substring(0,100)+"...");console.log(`%c${e}:`,"color: blue;",n);}}getFeed(e,n){return
|
|
233
|
-
exports.Skapi=w;exports.SkapiError=a;exports.Types=
|
|
232
|
+
Full Documentation: https://docs.skapi.com/skapi.md`;console.log(n,"font-family: monospace; color:blue;"),this.connection.group===1&&console.log("%cSKAPI: THE SERVICE IS IN TRIAL MODE.","font-family: monospace; color:red;");}return this.__version}log(e,n){if(this.__network_logs){if(n!==null&&typeof n=="object")try{j()?n=JSON.parse(JSON.stringify(n)):n=JSON.stringify(n,null,2);}catch{n=String(n);}else typeof n=="string"&&n.length>100&&(n=n.substring(0,100)+"...");console.log(`%c${e}:`,"color: blue;",n);}}getFeed(e,n){return Dn.bind(this)(e,n)}closeRTC(e){return H.bind(this)(e)}connectRTC(e,n){return cn.bind(this)(e,n)}connectRealtime(e){return Oe.bind(this)(e)}spellcast(e){return tr.bind(this)(e)}getspell(e){return nr.bind(this)(e)}dopamine(e){return rr.bind(this)(e)}getUniqueId(e,n){return Zt.bind(this)(e,n)}resendInvitation(e){return zn.bind(this)(e)}cancelInvitation(e){return Jn.bind(this)(e)}getInvitations(e,n){return Wn.bind(this)(e,n)}openIdLogin(e){return pt.bind(this)(e)}loginWithToken(e){return mt.bind(this)(e)}clientSecretRequest(e){return In.bind(this)(e)}clientSecretRequestHistory(e,n){return Tn.bind(this)(e,n)}cancelClientSecretRequest(e){return Pn.bind(this)(e)}stopClientSecretPolling(e){return Rn.bind(this)(e||{})}isPollStopped(e){return wn(e)}clientSecretRequestQueueCount(e){return An.bind(this)(e)}consumeTicket(e){return lt.bind(this)(e)}getConsumedTickets(e,n){return dt.bind(this)(e,n)}getTickets(e,n){return ut.bind(this)(e,n)}closeRealtime(){return gn.bind(this)()}getRealtimeUsers(e,n){return hn.bind(this)(e,n)}sendInquiry(e){return Sn.bind(this)(e)}blockAccount(e){return $n.bind(this)(e)}unblockAccount(e){return jn.bind(this)(e)}deleteAccount(e){return Bn.bind(this)(e)}inviteUser(e,n){return Kn.bind(this)(e,n)}createAccount(e){return Qn.bind(this)(e)}grantAccess(e){return Hn.bind(this)(e)}updateUserAttributes(e){return Gn.bind(this)(e)}getRealtimeGroups(e,n){return pn.bind(this)(e,n)}postRealtime(e,n,r){return fn.bind(this)(e,n,r)}joinRealtime(e){return Ye.bind(this)(e)}getProfile(e){return ht.bind(this)(e)}getFile(e,n){return se.bind(this)(e,n)}secureRequest(e,n){return kn.bind(this)(e,n)}forwardRequest(e,n){return vn.bind(this)(e,n)}getFormResponse(){return Ot.bind(this)()}getRecords(e,n){return Qt.bind(this)(e,n)}getTables(e,n){return zt.bind(this)(e,n)}getIndexes(e,n){return Gt.bind(this)(e,n)}getTags(e,n){return Xt.bind(this)(e,n)}deleteRecords(e,n){return Yt.bind(this)(e,n)}resendSignupConfirmation(){return _t.bind(this)()}recoverAccount(e=false){return bt.bind(this)(e)}getUsers(e,n){return kt.bind(this)(e,n)}disableAccount(){return wt.bind(this)()}lastVerifiedEmail(e){return xt.bind(this)(e)}unsubscribeNewsletter(e){return Fn.bind(this)(e)}subscribeNotification(e,n){return Xn.bind(this)({endpoint:e,keys:n})}unsubscribeNotification(e,n){return Zn.bind(this)({endpoint:e,keys:n})}vapidPublicKey(){return Yn.bind(this)()}pushNotification(e,n){return er.bind(this)(e,n)}getNewsletters(e,n){return Vn.bind(this)(e,n)}getNewsletterSubscription(e,n){return Mn.bind(this)(e,n)}requestUsernameChange(e){return vt.bind(this)(e)}grantPrivateRecordAccess(e){return en.bind(this)(e)}removePrivateRecordAccess(e){return tn.bind(this)(e)}listPrivateRecordAccess(e,n){return nn.bind(this)(e,n)}requestPrivateRecordAccessKey(e){return rn.bind(this)(e)}deleteFiles(e){return jt.bind(this)(e)}uploadFiles(e,n){return Se.bind(this)(e,n)}mock(e,n){return xn.bind(this)(e,n)}login(e){return je.bind(this)(e)}logout(e){return he.bind(this)(e)}signup(e,n){return yt.bind(this)(e,n)}resetPassword(e){return Et.bind(this)(e)}verifyEmail(e,n){return It.bind(this)(e,n)}verifyPhoneNumber(e,n){return At.bind(this)(e,n)}forgotPassword(e,n){return Tt.bind(this)(e,n)}changePassword(e){return Pt.bind(this)(e)}updateProfile(e){return St.bind(this)(e)}postRecord(e,n,r){return Jt.bind(this)(e,n,r)}getSubscriptions(e,n){return Nn.bind(this)(e,n)}subscribe(e){return Un.bind(this)(e)}unsubscribe(e){return Cn.bind(this)(e)}blockSubscriber(e){return Ln.bind(this)(e)}unblockSubscriber(e){return On.bind(this)(e)}subscribeNewsletter(e){return qn.bind(this)(e)}bulkPostRecords(e){return Wt.bind(this)(e)}};E([A()],w.prototype,"getFeed"),E([A()],w.prototype,"closeRTC"),E([A()],w.prototype,"connectRTC"),E([A()],w.prototype,"spellcast"),E([A()],w.prototype,"getspell"),E([A()],w.prototype,"dopamine"),E([A()],w.prototype,"getUniqueId"),E([A()],w.prototype,"resendInvitation"),E([A()],w.prototype,"cancelInvitation"),E([A()],w.prototype,"getInvitations"),E([A()],w.prototype,"openIdLogin"),E([A()],w.prototype,"loginWithToken"),E([A()],w.prototype,"clientSecretRequest"),E([A()],w.prototype,"clientSecretRequestHistory"),E([A()],w.prototype,"cancelClientSecretRequest"),E([A()],w.prototype,"consumeTicket"),E([A()],w.prototype,"getConsumedTickets"),E([A()],w.prototype,"getTickets"),E([A()],w.prototype,"getRealtimeUsers"),E([A()],w.prototype,"sendInquiry"),E([A()],w.prototype,"blockAccount"),E([A()],w.prototype,"unblockAccount"),E([A()],w.prototype,"deleteAccount"),E([A()],w.prototype,"inviteUser"),E([A()],w.prototype,"createAccount"),E([A()],w.prototype,"grantAccess"),E([A()],w.prototype,"updateUserAttributes"),E([A()],w.prototype,"getRealtimeGroups"),E([A()],w.prototype,"postRealtime"),E([A()],w.prototype,"joinRealtime"),E([A()],w.prototype,"getProfile"),E([A()],w.prototype,"getFile"),E([A()],w.prototype,"secureRequest"),E([A()],w.prototype,"forwardRequest"),E([A()],w.prototype,"getFormResponse"),E([A()],w.prototype,"getRecords"),E([A()],w.prototype,"getTables"),E([A()],w.prototype,"getIndexes"),E([A()],w.prototype,"getTags"),E([A()],w.prototype,"deleteRecords"),E([A()],w.prototype,"resendSignupConfirmation"),E([A()],w.prototype,"recoverAccount"),E([A()],w.prototype,"getUsers"),E([A()],w.prototype,"disableAccount"),E([A()],w.prototype,"lastVerifiedEmail"),E([A()],w.prototype,"unsubscribeNewsletter"),E([A()],w.prototype,"subscribeNotification"),E([A()],w.prototype,"unsubscribeNotification"),E([A()],w.prototype,"vapidPublicKey"),E([A()],w.prototype,"pushNotification"),E([A()],w.prototype,"getNewsletters"),E([A()],w.prototype,"getNewsletterSubscription"),E([A()],w.prototype,"requestUsernameChange"),E([A()],w.prototype,"grantPrivateRecordAccess"),E([A()],w.prototype,"removePrivateRecordAccess"),E([A()],w.prototype,"listPrivateRecordAccess"),E([A()],w.prototype,"requestPrivateRecordAccessKey"),E([A()],w.prototype,"deleteFiles"),E([A()],w.prototype,"uploadFiles"),E([A()],w.prototype,"mock"),E([A({preventMultipleCalls:true})],w.prototype,"login"),E([A()],w.prototype,"logout"),E([A({preventMultipleCalls:true})],w.prototype,"signup"),E([A({preventMultipleCalls:true})],w.prototype,"resetPassword"),E([A({preventMultipleCalls:true})],w.prototype,"verifyEmail"),E([A({preventMultipleCalls:true})],w.prototype,"verifyPhoneNumber"),E([A({preventMultipleCalls:true})],w.prototype,"forgotPassword"),E([A({preventMultipleCalls:true})],w.prototype,"changePassword"),E([A({preventMultipleCalls:true})],w.prototype,"updateProfile"),E([A()],w.prototype,"postRecord"),E([A()],w.prototype,"getSubscriptions"),E([A()],w.prototype,"subscribe"),E([A()],w.prototype,"unsubscribe"),E([A()],w.prototype,"blockSubscriber"),E([A()],w.prototype,"unblockSubscriber"),E([A()],w.prototype,"subscribeNewsletter");var li={};
|
|
233
|
+
exports.Skapi=w;exports.SkapiError=a;exports.Types=li;//# sourceMappingURL=skapi.cjs.map
|
|
234
234
|
//# sourceMappingURL=skapi.cjs.map
|