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

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.cjs CHANGED
@@ -1,4 +1,4 @@
1
- 'use strict';var amazonCognitoIdentityJs=require('amazon-cognito-identity-js'),Ns=require('cocochex'),Ti=require('qpass');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var Ns__default=/*#__PURE__*/_interopDefault(Ns);var Ti__default=/*#__PURE__*/_interopDefault(Ti);/**
1
+ 'use strict';var amazonCognitoIdentityJs=require('amazon-cognito-identity-js'),Qs=require('cocochex'),ji=require('qpass');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var Qs__default=/*#__PURE__*/_interopDefault(Qs);var ji__default=/*#__PURE__*/_interopDefault(ji);/**
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 ps=Object.defineProperty;var hs=Object.getOwnPropertyDescriptor;var de=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(t,r)=>(typeof require<"u"?require:t)[r]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')});var R=(e,t,r,n)=>{for(var i=hs(t,r),s=e.length-1,o;s>=0;s--)(o=e[s])&&(i=(o(t,r,i))||i);return i&&ps(t,r,i),i};var fe=typeof globalThis<"u"?globalThis:void 0,Ye=fe?.window;function ms(e){if(Buffer)return Buffer.from(e).toString("base64");let t="",r=new Uint8Array(e),n=32768;for(let i=0;i<r.length;i+=n){let s=r.subarray(i,i+n);t+=String.fromCharCode.apply(null,Array.from(s));}if(typeof btoa=="function")return btoa(t);throw new Error("No base64 encoder available in this environment.")}if(Ye)Ye.global=Ye,Ye.global._runningInNodeJS=false;else if(fe&&(fe.global=fe,typeof fe.window>"u")){class e{constructor(){this.result=null;this.error=null;this.onload=null;this.onloadend=null;this.onerror=null;}readAsDataURL(n){n.arrayBuffer().then(i=>{let s=ms(i),o=n.type||"application/octet-stream";this.result=`data:${o};base64,${s}`,this.onload&&this.onload({target:this}),this.onloadend&&this.onloadend({target:this});}).catch(i=>{this.error=i,this.onerror&&this.onerror({target:this});});}readAsArrayBuffer(n){n.arrayBuffer().then(i=>{this.result=i,this.onload&&this.onload({target:this}),this.onloadend&&this.onloadend({target:this});}).catch(i=>{this.error=i,this.onerror&&this.onerror({target:this});});}readAsText(n,i="utf-8"){n.text().then(s=>{this.result=s,this.onload&&this.onload({target:this}),this.onloadend&&this.onloadend({target:this});}).catch(s=>{this.error=s,this.onerror&&this.onerror({target:this});});}}fe.FileReader=e;class t{constructor(){this.status=0;this.statusText="";this.readyState=0;this.responseText="";this.response=null;this.responseType="";this.responseURL="";this.timeout=0;this.withCredentials=false;this.onload=null;this.onerror=null;this.onabort=null;this.ontimeout=null;this.onprogress=null;this.onreadystatechange=null;this.upload={onprogress:null};this._method="GET";this._url="";this._headers={};this._aborted=false;}open(n,i){this._method=n,this._url=i,this.readyState=1;}setRequestHeader(n,i){this._headers[n]=i;}getResponseHeader(n){return null}abort(){this._aborted=true,this.onabort&&this.onabort({});}send(n){if(this._aborted)return;let i={method:this._method,headers:this._headers};n&&this._method!=="GET"&&this._method!=="HEAD"&&(i.body=n),fetch(this._url,i).then(async s=>{if(!this._aborted){if(this.status=s.status,this.statusText=s.statusText,this.responseURL=s.url,this.readyState=4,this.responseType==="blob")this.response=await s.blob();else if(this.responseType==="json")try{this.response=await s.json();}catch{this.response=null;}else this.responseType==="arraybuffer"?this.response=await s.arrayBuffer():(this.responseText=await s.text(),this.response=this.responseText);this.onload&&this.onload({});}}).catch(s=>{this._aborted||this.onerror&&this.onerror(s);});}}fe.XMLHttpRequest=t,fe.window={_runningInNodeJS:true,alert:r=>console.error("[Alert]",r),sessionStorage:{getItem:r=>null,setItem:(r,n)=>{},removeItem:r=>{}},localStorage:{getItem:r=>{let n=de("fs"),i=de("path");try{let s=i.resolve(process.cwd(),"states","localStorage",`${r}.skapi`);return n.existsSync(s)?n.readFileSync(s,"utf8"):null}catch{return null}},setItem:(r,n)=>{let i=de("fs"),s=de("path");try{let o=s.resolve(process.cwd(),"states","localStorage");i.existsSync(o)||i.mkdirSync(o,{recursive:!0});let a=s.resolve(o,`${r}.skapi`);i.writeFileSync(a,n,"utf8");}catch{}},removeItem:r=>{let n=de("fs"),i=de("path");try{let s=i.resolve(process.cwd(),"states","localStorage",`${r}.skapi`);n.existsSync(s)&&n.unlinkSync(s);}catch{}}},location:{href:"",origin:"",hostname:"",protocol:"",replace:r=>{}},navigator:{userAgent:`nodejs/${fe?.process?.versions?.node||"unknown"}`,mediaDevices:{getUserMedia:async r=>{throw new Error("getUserMedia is not supported in Node.js environment.")}}},addEventListener:()=>{},removeEventListener:()=>{}};}var c=class extends Error{constructor(t,r){if(Array.isArray(t)&&t.length<=2){let n=t[1];if(t.length>2)for(let i=2;i<t.length&&typeof t[i]=="string";i++)n+=t[i];super((n||"Something went wrong.").trim()),this.name=r?.name||"SKAPI",this.code=r?.code||t[0]||"ERROR",r?.cause&&(this.cause=r.cause);}else super((t?.message||(typeof t=="string"?t:"Something went wrong.")).trim()),typeof t=="string"?(this.name=r?.name||"SKAPI",this.code=r?.code||"ERROR",r?.cause&&(this.cause=r.cause)):t instanceof Error?(this.cause=t,this.name=t.name,t.hasOwnProperty("code")&&(this.code=t.code)):typeof t=="object"&&t?.code&&t?.message&&(this.name=r?.name||"SKAPI",this.code=r?.code||"ERROR",this.cause=t?.cause);}};var ge="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",Et=BigInt(ge.length),ys=2*1024*1024,bs=["aud","cognito:username","event_id","exp","iat","iss","jti","origin_jti","secret_key","token_use"],ur={auth_time:"log",sub:"user_id"},_s=["0","1","2","3","4","5","6","7","8","9","a","b","c","d","e","f","g","h","i","j","k","l"],hr=["us31","us72","ap51","ap22","ap41","eu71","ap21","us32","us71","af51","ap31","ap43","ap23","ap42","ca01","eu01","eu72","eu51","eu73","eu11","me51","sa31"],dr=typeof TextEncoder<"u"?new TextEncoder:null;function ws(){if(typeof globalThis<"u")return globalThis.Buffer}function B(e){if(dr)return dr.encode(e);let t=unescape(encodeURIComponent(e)),r=new Uint8Array(t.length);for(let n=0;n<t.length;n++)r[n]=t.charCodeAt(n);return r}function At(e){if(e instanceof Uint8Array)return e;if(typeof e=="string")return B(e);if(typeof ArrayBuffer<"u"&&e instanceof ArrayBuffer)return new Uint8Array(e);if(typeof ArrayBuffer<"u"&&ArrayBuffer.isView(e))return new Uint8Array(e.buffer,e.byteOffset,e.byteLength);if(Array.isArray(e))return Uint8Array.from(e);let t=ws();if(t)return new Uint8Array(t.from(e));throw new Error("No byte conversion available in this environment.")}var E=class E{static hash(t){typeof t!="string"&&(console.warn("coercing non-string value to empty string"),t="");let r=E.sb(t),n=1732584193,i=-271733879,s=-1732584194,o=271733878,a,l,u,d;for(let f=0;f<r.length;f+=16)a=n,l=i,u=s,d=o,n=E.ff(n,i,s,o,r[f],7,-680876936),o=E.ff(o,n,i,s,r[f+1],12,-389564586),s=E.ff(s,o,n,i,r[f+2],17,606105819),i=E.ff(i,s,o,n,r[f+3],22,-1044525330),n=E.ff(n,i,s,o,r[f+4],7,-176418897),o=E.ff(o,n,i,s,r[f+5],12,1200080426),s=E.ff(s,o,n,i,r[f+6],17,-1473231341),i=E.ff(i,s,o,n,r[f+7],22,-45705983),n=E.ff(n,i,s,o,r[f+8],7,1770035416),o=E.ff(o,n,i,s,r[f+9],12,-1958414417),s=E.ff(s,o,n,i,r[f+10],17,-42063),i=E.ff(i,s,o,n,r[f+11],22,-1990404162),n=E.ff(n,i,s,o,r[f+12],7,1804603682),o=E.ff(o,n,i,s,r[f+13],12,-40341101),s=E.ff(s,o,n,i,r[f+14],17,-1502002290),i=E.ff(i,s,o,n,r[f+15],22,1236535329),n=E.gg(n,i,s,o,r[f+1],5,-165796510),o=E.gg(o,n,i,s,r[f+6],9,-1069501632),s=E.gg(s,o,n,i,r[f+11],14,643717713),i=E.gg(i,s,o,n,r[f],20,-373897302),n=E.gg(n,i,s,o,r[f+5],5,-701558691),o=E.gg(o,n,i,s,r[f+10],9,38016083),s=E.gg(s,o,n,i,r[f+15],14,-660478335),i=E.gg(i,s,o,n,r[f+4],20,-405537848),n=E.gg(n,i,s,o,r[f+9],5,568446438),o=E.gg(o,n,i,s,r[f+14],9,-1019803690),s=E.gg(s,o,n,i,r[f+3],14,-187363961),i=E.gg(i,s,o,n,r[f+8],20,1163531501),n=E.gg(n,i,s,o,r[f+13],5,-1444681467),o=E.gg(o,n,i,s,r[f+2],9,-51403784),s=E.gg(s,o,n,i,r[f+7],14,1735328473),i=E.gg(i,s,o,n,r[f+12],20,-1926607734),n=E.hh(n,i,s,o,r[f+5],4,-378558),o=E.hh(o,n,i,s,r[f+8],11,-2022574463),s=E.hh(s,o,n,i,r[f+11],16,1839030562),i=E.hh(i,s,o,n,r[f+14],23,-35309556),n=E.hh(n,i,s,o,r[f+1],4,-1530992060),o=E.hh(o,n,i,s,r[f+4],11,1272893353),s=E.hh(s,o,n,i,r[f+7],16,-155497632),i=E.hh(i,s,o,n,r[f+10],23,-1094730640),n=E.hh(n,i,s,o,r[f+13],4,681279174),o=E.hh(o,n,i,s,r[f],11,-358537222),s=E.hh(s,o,n,i,r[f+3],16,-722521979),i=E.hh(i,s,o,n,r[f+6],23,76029189),n=E.hh(n,i,s,o,r[f+9],4,-640364487),o=E.hh(o,n,i,s,r[f+12],11,-421815835),s=E.hh(s,o,n,i,r[f+15],16,530742520),i=E.hh(i,s,o,n,r[f+2],23,-995338651),n=E.ii(n,i,s,o,r[f],6,-198630844),o=E.ii(o,n,i,s,r[f+7],10,1126891415),s=E.ii(s,o,n,i,r[f+14],15,-1416354905),i=E.ii(i,s,o,n,r[f+5],21,-57434055),n=E.ii(n,i,s,o,r[f+12],6,1700485571),o=E.ii(o,n,i,s,r[f+3],10,-1894986606),s=E.ii(s,o,n,i,r[f+10],15,-1051523),i=E.ii(i,s,o,n,r[f+1],21,-2054922799),n=E.ii(n,i,s,o,r[f+8],6,1873313359),o=E.ii(o,n,i,s,r[f+15],10,-30611744),s=E.ii(s,o,n,i,r[f+6],15,-1560198380),i=E.ii(i,s,o,n,r[f+13],21,1309151649),n=E.ii(n,i,s,o,r[f+4],6,-145523070),o=E.ii(o,n,i,s,r[f+11],10,-1120210379),s=E.ii(s,o,n,i,r[f+2],15,718787259),i=E.ii(i,s,o,n,r[f+9],21,-343485551),n=E.ad(n,a),i=E.ad(i,l),s=E.ad(s,u),o=E.ad(o,d);return E.rh(n)+E.rh(i)+E.rh(s)+E.rh(o)}static rh(t){let r="";for(let n=0;n<=3;n++)r+=E.alphabet.charAt(t>>n*8+4&15)+E.alphabet.charAt(t>>n*8&15);return r}static ad(t,r){let n=(t&65535)+(r&65535);return (t>>16)+(r>>16)+(n>>16)<<16|n&65535}static rl(t,r){return t<<r|t>>>32-r}static cm(t,r,n,i,s,o){return E.ad(E.rl(E.ad(E.ad(r,t),E.ad(i,o)),s),n)}static ff(t,r,n,i,s,o,a){return E.cm(r&n|~r&i,t,r,s,o,a)}static gg(t,r,n,i,s,o,a){return E.cm(r&i|n&~i,t,r,s,o,a)}static hh(t,r,n,i,s,o,a){return E.cm(r^n^i,t,r,s,o,a)}static ii(t,r,n,i,s,o,a){return E.cm(n^(r|~i),t,r,s,o,a)}static sb(t){let r,n=(t.length+8>>6)+1,i=new Array(n*16);for(r=0;r<n*16;r++)i[r]=0;for(r=0;r<t.length;r++)i[r>>2]|=t.charCodeAt(r)<<r%4*8;return i[r>>2]|=128<<r%4*8,i[n*16-2]=t.length*8,i}};E.alphabet="0123456789abcdef";var H=E;function mr(e){if(e===0)return ge[0];let t="";for(;e>0;)t=ge[e%62]+t,e=Math.floor(e/62);return t}function X(e){return e.split("").reverse().reduce((t,r,n)=>t+ge.indexOf(r)*62**n,0)}function be(e=6){let t="",r="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",n=r.length,i=0;for(;i<e;)t+=r.charAt(Math.floor(Math.random()*n)),i+=1;return t}function Rt(){return typeof window>"u"||!!window?._runningInNodeJS}function G(){return !Rt()&&typeof document<"u"&&typeof document.createElement=="function"}function Xe(e){let t;try{t=JSON.stringify(e);}catch{throw new c("Invalid data type.",{code:"INVALID_REQUEST"})}if(new Blob([t]).size>ys)throw new c("Data should not exceed 2MB",{code:"INVALID_REQUEST"})}function fr(e){return e===""||e==="on"||e==="true"}function gr(e){return e==="false"}function pr(e,t,r){t.name&&r(e,t.name,t.value);}var Ze=G(),Es=typeof SubmitEvent<"u",As=typeof HTMLFormElement<"u";function V(e,t,r){let n={},i=[];function s(l,u,d){if(t?.ignoreEmpty&&d==="")return;if(t?.nullIfEmpty&&d===""&&(d=null),typeof r=="function"){let h=r(u,d);h!==void 0&&(d=h);}let f=u.split("[").map(h=>{let m=h.replace("]",""),y=Number(m);return !isNaN(y)&&!m.includes(".")?m=y:(m[0]==='"'&&m[m.length-1]==='"'||m[0]==="'"&&m[m.length-1]==="'")&&(m=m.replace(/"/g,"").replace(/'/g,"")),m}),g=l;if(typeof f[0]=="number")throw new c("Form key cannot start with an array index.",{code:"INVALID_REQUEST"});for(let h=0;h<f.length;h++){let m=f[h];h<f.length-1?(g[m]===void 0&&(typeof f[h+1]=="number"?g[m]=[]:g[m]={}),g=g[m]):g[m]===void 0?g[m]=d:Array.isArray(g[m])?g[m].push(d):g[m]=[g[m],d];}}function o(l,u,d){if(d instanceof File)l.push({name:u,file:d});else if(d instanceof FileList&&d&&d.length>0)for(let f=0;f<=d.length-1;f++){let g=d.item(f);g&&l.push({name:u,file:g});}}let a=l=>{l.name&&(l.type==="number"?l.value&&s(n,l.name,Number(l.value)):l.type==="checkbox"||l.type==="radio"?l.checked?l.type==="checkbox"&&l.value===""||fr(l.value)?s(n,l.name,true):gr(l.value)?s(n,l.name,false):l.value&&s(n,l.name,l.value):l.type==="checkbox"&&(fr(l.value)?s(n,l.name,false):gr(l.value)&&s(n,l.name,true)):l.type==="file"?l.files&&l.files.length>0&&o(i,l.name,l.files):s(n,l.name,l.value));};if(Ze&&(e instanceof HTMLInputElement||e instanceof HTMLSelectElement||e instanceof HTMLTextAreaElement))return a(e),Xe(n),{data:n,files:i};if(Ze&&e instanceof FormData){for(let l of e.entries()){let u=l[0],d=l[1];if(d instanceof File||d instanceof FileList)o(i,u,d);else if(d instanceof Blob){let f=d;if(f.type==="application/json")try{let g=JSON.parse(f.text());s(n,u,g);}catch{s(n,u,f);}}else s(n,u,d);}return Xe(n),{data:n,files:i}}if(Ze&&Es&&e instanceof SubmitEvent&&(e=e.target),Ze&&As&&e instanceof HTMLFormElement){let l=e.querySelectorAll("input"),u=e.querySelectorAll("select"),d=e.querySelectorAll("textarea");for(let f=0;f<u.length;f++)pr(n,u[f],s);for(let f=0;f<d.length;f++)pr(n,d[f],s);for(let f=0;f<l.length;f++)a(l[f]);return Xe(n),{data:n,files:i}}return Xe(e),{data:e,files:i}}function xe(e){let t={};for(let r in e){let n=e[r];if(!bs.includes(r))if(ur[r])t[ur[r]]=n;else if(r.includes("custom:"))t[r.replace("custom:","")]=n;else if(r==="address"){let i=n;if(i&&typeof i=="object"&&Object.keys(i).length){if(i?.formatted)try{t[r]=JSON.parse(i.formatted);}catch{t[r]=i.formatted;}}else t[r]=i;}else t[r]=n;}for(let r of ["address_public","birthdate_public","email_public","gender_public","phone_number_public","access_group"])r.includes("_public")?t.hasOwnProperty(r.split("_")[0])?t[r]=t.hasOwnProperty(r)?!!Number(t[r]):false:delete t[r]:t[r]=t.hasOwnProperty(r)?Number(t[r]):0;for(let r of ["email","phone_number"])t.hasOwnProperty(r)?t[r+"_verified"]=t[r+"_verified"]===true:delete t[r+"_verified"];return t}function It(e){if(e=Us(e),e.split("-").length===7){let t=e.split("-"),r,n;try{r=hr[X(t[1][0])],n=t.slice(2).join("-");}catch{throw new Error("INVALID_PARAMETER: Service ID is invalid: "+e)}if(!r)throw new Error("INVALID_PARAMETER: Service ID is invalid: "+e);return {service:r+t[0]+t[1].slice(1),owner:n}}return {service:e,owner:""}}function Pt(e,t){let r=hr.indexOf(e.slice(0,4)),n=_s[r],s=`${e.slice(4,-4)}-${n}${e.slice(-4)}-${t}`;return vs(s)}function Rs(e){let t=0n;for(let r of e){let n=ge.indexOf(r);if(n<0)throw new Error(`INVALID_PARAMETER: Invalid base62 character: ${r}`);t=t*Et+BigInt(n);}return t}function Is(e,t=1){if(e<0n)throw new Error("INVALID_PARAMETER: Negative values are not supported.");if(e===0n)return "0".repeat(Math.max(1,t));let r="",n=e;for(;n>0n;){let i=Number(n%Et);r=ge[i]+r,n/=Et;}return r.length<t&&(r="0".repeat(t-r.length)+r),r}function Ps(e){if(e===0n)return Uint8Array.from([0]);let t=[],r=e;for(;r>0n;)t.push(Number(r&0xffn)),r>>=8n;return t.reverse(),Uint8Array.from(t)}function Ts(e){let t=0n;for(let r of e)t=(t<<8n)+BigInt(r);return t}function Ss(e){let t=String(e).replace(/-/g,"");if(!/^[0-9a-fA-F]{32}$/.test(t))throw new Error("INVALID_PARAMETER: Invalid UUID format.");let r=new Uint8Array(16);for(let n=0;n<16;n++)r[n]=parseInt(t.slice(n*2,n*2+2),16);return r}function ks(e){let t=Array.from(At(e),r=>r.toString(16).padStart(2,"0")).join("");return [t.slice(0,8),t.slice(8,12),t.slice(12,16),t.slice(16,20),t.slice(20)].join("-")}function vs(e){let t=String(e);if(t.split("-").length===2)return t;let r=t.match(/^([0-9A-Za-z]+)-([0-9A-Za-z]+)-([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/);if(!r)throw new Error("INVALID_PARAMETER: Input must match <base62>-<base62>-<uuid>.");let[,n,i,s]=r;if(n.length<2)throw new Error("INVALID_PARAMETER: The first part must contain at least 2 characters.");if(i.length>=ge.length)throw new Error("INVALID_PARAMETER: The middle section is too long to encode.");let o=n.slice(0,2),a=n.slice(2),l=i+o,u=ge[i.length]+a+l,d=Ss(s),f=Is(Ts(d));return `${u}-${f}`}function Us(e){let t=String(e);if(t.split("-").length!==2)return t;let r=t.split("-");if(r.length!==2||!r[0]||!r[1])throw new Error("INVALID_PARAMETER: Corrupt compressed token: "+t);let[n,i]=r,s=ge.indexOf(n[0]);if(s<0)throw new Error("INVALID_PARAMETER: Corrupt compressed token: "+t);let o=n.slice(1),a=s+2;if(o.length<a)throw new Error("INVALID_PARAMETER: Corrupt compressed token: "+t);let l=o.slice(0,o.length-a),u=o.slice(o.length-a),d=u.slice(s),f=u.slice(0,s),g=d+l;if(!/^[0-9A-Za-z]+$/.test(g)||!/^[0-9A-Za-z]+$/.test(f))throw new Error("INVALID_PARAMETER: Corrupt compressed token: "+t);let h=Rs(i),m=Ps(h);if(m.length>16)throw new Error("INVALID_PARAMETER: Corrupt compressed token: "+t);let y=new Uint8Array(16);y.set(m,16-m.length);let b=ks(y);return `${g}-${f}-${b}`}function De(e){if(typeof TextDecoder<"u")return new TextDecoder().decode(e);let t="";for(let r=0;r<e.length;r++)t+=String.fromCharCode(e[r]);return decodeURIComponent(escape(t))}function Tt(...e){let t=0;for(let i of e)t+=i.length;let r=new Uint8Array(t),n=0;for(let i of e)r.set(i,n),n+=i.length;return r}function xs(e,t="User ID"){let r=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;if(e){if(typeof e!="string")throw new c(`${t} should be type: string.`,{code:"INVALID_PARAMETER"});if(!e.match(r))throw new c(`${t} is invalid.`,{code:"INVALID_PARAMETER"})}else throw new c(`${t} is empty.`,{code:"INVALID_PARAMETER"});return e}function Ds(e){if(e&&(typeof e!="string"||e.charAt(0)!=="+"||isNaN(Number(e.substring(1)))))throw new c('"phone_number" is invalid. The format should be "+00123456789". Type: string.',{code:"INVALID_PARAMETER"});return e||""}function Cs(e){if(e){if(typeof e!="string")throw new c('"birthdate" is invalid. The format should be "yyyy-mm-dd". Type: string.',{code:"INVALID_PARAMETER"});{let t=new RegExp(/([12]\d{3}-(0[1-9]|1[0-2])-(0[1-9]|[12]\d|3[01]))/);if(e.length!==10||e.split("-").length!==3||!t.test(e))throw new c('"birthdate" is invalid. The format should be "yyyy-mm-dd". Type: string.',{code:"INVALID_PARAMETER"})}}return e||""}function Os(e){if(e){if(typeof e!="string")throw new c('"password" should be type: string.',{code:"INVALID_PARAMETER"});if(e.length<6)throw new c('"password" should be at least 6 characters.',{code:"INVALID_PARAMETER"});if(e.length>60)throw new c('"password" can be up to 60 characters max.',{code:"INVALID_PARAMETER"})}else throw new c('"password" is required.',{code:"INVALID_PARAMETER"});return e}function Ls(e,t="email"){if(e){if(typeof e!="string")throw new c(`"${t}"should be type: string.`,{code:"INVALID_PARAMETER"});if(e.length<5)throw new c(`"${t}" should be at least 5 characters.`,{code:"INVALID_PARAMETER"});if(/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/.test(e)&&(e=e.trim(),e.split("@")[1].split(".").length>=2))return e.toLowerCase()}else throw new c(`"${t}" is required.`,{code:"INVALID_PARAMETER"});throw new c(`"${e}" is an invalid email.`,{code:"INVALID_PARAMETER"})}function Ms(e){let t=typeof window<"u",r=(()=>{let i=t&&window.location.origin||null;return i&&i.slice(-1)==="/"&&(i=i.slice(0,-1)),i})(),n=i=>{if(typeof i=="string"){if(i==="*")return "*";{let s=i.trim();if(s[0]==="/"&&r){if(r.slice(0,5)==="file:")throw new c(`"${i}" is an invalid url. Relative URL does not work on local file system. Use full URL string.`,{code:"INVALID_PARAMETER"});s=r+s;}else if(s[0]==="."&&r){if(r.slice(0,5)==="file:")throw new c(`"${i}" is an invalid url. Relative URL does not work on local file system. Use full URL string.`,{code:"INVALID_PARAMETER"});let a=t?window.location.href.split("?")[0]:"";a.slice(-1)!=="/"&&(a+="/"),s=a+s.slice(1);}let o;try{o=new URL(s);}catch{throw new c(`"${i}" is an invalid url.`,{code:"INVALID_PARAMETER"})}if(o.protocol)return o.href}}throw new c(`"${i}" is an invalid url.`,{code:"INVALID_PARAMETER"})};return Array.isArray(e)?e.map(i=>n(i)):n(e)}function Fs(e,t,r=[],n){let i=V(e,n),s=i.data;t.service="string",t.owner="string";let o={};for(let a in t)if(s&&typeof s=="object"&&!Array.isArray(s)&&s.hasOwnProperty(a))if(typeof s[a]=="function")o[a]=s[a];else try{o[a]=JSON.parse(JSON.stringify(s[a]));}catch{o[a]=s[a];}n?.precall&&n.precall({data:o,files:i?.files||[]});try{return Ns__default.default(o,t,r)}catch(a){throw new c(a.message,{code:"INVALID_PARAMETER"})}}var p={UserId:xs,PhoneNumber:Ds,Birthdate:Cs,Password:Os,Email:Ls,Url:Ms,Params:Fs};var z="skapi.enc.v1",_r=6e5,Ce=12,et=null,Ae=null;function wr(){return new c("Encryption requires Web Crypto, which needs a secure context (https, or localhost) in the browser, or Node 18 or newer. A page served over plain http has crypto.getRandomValues but crypto.subtle is undefined.",{code:"NOT_SUPPORTED"})}function Er(){if(Ae)return Ae;let e=typeof globalThis<"u"?globalThis:void 0;if(e?.crypto?.subtle&&typeof e.crypto.getRandomValues=="function")return Ae=e.crypto,Ae;try{let t=typeof de=="function"?de("crypto"):null;if(t?.webcrypto?.subtle)return Ae=t.webcrypto,Ae}catch{}throw wr()}function Z(){if(et)return et;let e=Er();if(!e.subtle)throw wr();return et=e.subtle,et}function kt(){try{return Z(),!0}catch{return false}}function J(e){let t=Er(),r=new Uint8Array(e),n=65536;for(let i=0;i<e;i+=n)t.getRandomValues(r.subarray(i,Math.min(i+n,e)));return r}function O(e){let t=At(e),r;if(typeof Buffer<"u"&&typeof Buffer.from=="function")r=Buffer.from(t).toString("base64");else if(typeof btoa=="function"){let n="";for(let s=0;s<t.length;s+=32768)n+=String.fromCharCode.apply(null,Array.from(t.subarray(s,s+32768)));r=btoa(n);}else throw new c("No base64 encoder available in this environment.",{code:"NOT_SUPPORTED"});return r.replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function F(e){if(typeof e!="string")throw new c("Expected a base64url string.",{code:"INVALID_PARAMETER"});let t=e.replace(/-/g,"+").replace(/_/g,"/"),r=t.length%4;if(r===2)t+="==";else if(r===3)t+="=";else if(r===1)throw new c("Malformed base64url string.",{code:"INVALID_PARAMETER"});if(typeof Buffer<"u"&&typeof Buffer.from=="function"){let n=Buffer.from(t,"base64");return new Uint8Array(n.buffer,n.byteOffset,n.byteLength)}if(typeof atob=="function"){let n=atob(t),i=new Uint8Array(n.length);for(let s=0;s<n.length;s++)i[s]=n.charCodeAt(s);return i}throw new c("No base64 decoder available in this environment.",{code:"NOT_SUPPORTED"})}async function tt(e){let t=await Z().digest("SHA-256",e);return new Uint8Array(t)}async function Me(e,t,r,n){let i=Z(),s=await i.importKey("raw",e,"HKDF",false,["deriveBits"]),o=await i.deriveBits({name:"HKDF",hash:"SHA-256",salt:t,info:r},s,n*8);return new Uint8Array(o)}async function Ie(e,t,r,n){let i=Z(),s=B(e.normalize("NFC")),o=await i.importKey("raw",s,"PBKDF2",false,["deriveBits"]),a=new Uint8Array(await i.deriveBits({name:"PBKDF2",salt:t,iterations:r,hash:"SHA-256"},o,256)),l=await Me(a,t,n,32);L(a),L(s);let u=await te(l);return L(l),u}async function te(e){return Z().importKey("raw",e,{name:"AES-GCM"},false,["encrypt","decrypt"])}async function Ar(){let e=J(32),t=await te(e);return {bytes:e,key:t}}async function ee(e,t,r){let n=J(Ce),i=await Z().encrypt({name:"AES-GCM",iv:n,additionalData:r,tagLength:128},e,t);return {iv:n,ct:new Uint8Array(i)}}async function re(e,t,r,n){let i=await Z().decrypt({name:"AES-GCM",iv:t,additionalData:n,tagLength:128},e,r);return new Uint8Array(i)}var rt={name:"ECDH",namedCurve:"P-256"};async function Rr(){let e=Z(),t=await e.generateKey(rt,true,["deriveBits"]),r=new Uint8Array(await e.exportKey("raw",t.publicKey)),n=new Uint8Array(await e.exportKey("pkcs8",t.privateKey)),i=await vt(n);return {pubRaw:r,pkcs8:n,priv:i}}async function vt(e){return Z().importKey("pkcs8",e,rt,false,["deriveBits"])}async function Ir(e){if(e.length!==65||e[0]!==4)throw new c("Malformed public key: expected a 65 byte uncompressed P-256 point.",{code:"INVALID_PARAMETER"});return Z().importKey("raw",e,rt,false,[])}async function Ut(e){return O(await tt(e))}async function Pr(e,t,r,n){let i=Z(),s=await Ir(e),o=await i.generateKey(rt,true,["deriveBits"]),a=new Uint8Array(await i.deriveBits({name:"ECDH",public:s},o.privateKey,256)),l=await Me(a,new Uint8Array(32),r,32);L(a);let u=await te(l);L(l);let{iv:d,ct:f}=await ee(u,t,n);return {epk:new Uint8Array(await i.exportKey("raw",o.publicKey)),iv:d,ct:f}}async function Tr(e,t,r,n,i,s){let o=Z(),a=await Ir(t),l=new Uint8Array(await o.deriveBits({name:"ECDH",public:a},e,256)),u=await Me(l,new Uint8Array(32),i,32);L(l);let d=await te(u);return L(u),re(d,r,n,s)}function L(e){e&&e.length&&e.fill(0);}function Vs(e,t){if(e.length!==t.length)return false;let r=0;for(let n=0;n<e.length;n++)r|=e[n]^t[n];return r===0}function Nt(e){return B(JSON.stringify(e))}function Fe(e,t,r){return Tt(e,new Uint8Array([0]),B(t),new Uint8Array([0]),B(r))}var _e="0123456789ABCDEFGHJKMNPQRSTVWXYZ",Oe=16,yr=26,br=28;function Sr(e){let t=2166136261;for(let r=0;r<e.length;r++)t^=e[r],t=t*16777619>>>0;return t&1023}function kr(e){if(e.length!==Oe)throw new c(`A recovery code needs exactly ${Oe} bytes.`,{code:"INVALID_PARAMETER"});let t="",r=0,n=0;for(let s=0;s<e.length;s++)for(r=r<<8|e[s],n+=8;n>=5;)n-=5,t+=_e[r>>n&31];n>0&&(t+=_e[r<<5-n&31]);let i=Sr(e);return t+=_e[i>>5&31]+_e[i&31],(t.match(/.{1,4}/g)||[]).join("-")}function vr(e){if(typeof e!="string")throw new c("Recovery code should be a string.",{code:"INVALID_PARAMETER"});let t=e.toUpperCase().replace(/[\s\-_]/g,"").replace(/O/g,"0").replace(/[IL]/g,"1");if(t.length!==br)throw new c(`That does not look like a recovery code: expected ${br} characters, got ${t.length}.`,{code:"ENCRYPTION_BAD_RECOVERY_CODE"});let r=t.slice(0,yr),n=t.slice(yr),i=0,s=0,o=[];for(let u=0;u<r.length;u++){let d=_e.indexOf(r[u]);if(d<0)throw new c(`That does not look like a recovery code: "${r[u]}" is not a valid character.`,{code:"ENCRYPTION_BAD_RECOVERY_CODE"});i=i<<5|d,s+=5,s>=8&&(s-=8,o.push(i>>s&255));}let a=new Uint8Array(o.slice(0,Oe)),l=Sr(a);if(n!==_e[l>>5&31]+_e[l&31])throw new c("That recovery code has a typo in it: the check characters do not match.",{code:"ENCRYPTION_BAD_RECOVERY_CODE"});return a}async function xt(e,t,r){let n=await Me(e,t,r,32),i=await te(n);return L(n),i}var St=[83,75,69,78,67,70],Ur=2,Le=56,Nr=16,$s=4*1024*1024;function Dt(e){if(!e||e.length<Le)return false;for(let t=0;t<St.length;t++)if(e[t]!==St[t])return false;return true}function we(e,t,r){e[t]=r>>>24&255,e[t+1]=r>>>16&255,e[t+2]=r>>>8&255,e[t+3]=r&255;}function Re(e,t){return (e[t]<<24>>>0)+(e[t+1]<<16)+(e[t+2]<<8)+e[t+3]}function qs(e,t,r){let n=Math.floor(r/4294967296);we(e,t,n),we(e,t+4,r>>>0);}function js(e,t){return Re(e,t)*4294967296+Re(e,t+4)}async function xr(e,t,r,n,i,s){let o=B(`${z}|binfile|${r}|${n}|${i}|${s}`),a=await Me(e,t,o,32),l=await te(a);return L(a),l}async function Dr(e){return (await tt(Tt(B(`${z}|dekid`),e))).subarray(0,8)}function Cr(e,t,r){return Nt([`${z}|binchunk`,O(e),t,r])}function Bs(e,t,r,n,i,s){let o=new Uint8Array(Le+s.length);return o.set(St,0),o[6]=Ur,o[7]=s.length?1:0,we(o,8,e),we(o,12,t),o.set(r,16),qs(o,32,n),o.set(i,40),we(o,48,s.length),we(o,52,0),s.length&&o.set(s,Le),o}async function Or(e,t,r,n,i=$s){let s=J(Nr),o=await xr(e,s,r.service,r.owner,r.recordOwner,r.recordId),a=await Dr(e),l=n?B(JSON.stringify(n)):new Uint8Array(0);if(l.length>4096)throw new c("Encrypted file metadata is too large.",{code:"INVALID_PARAMETER"});let u=t.length===0?1:Math.ceil(t.length/i),d=Bs(i,u,s,t.length,a,l),f=await tt(d),g=[],h=d.length;for(let b=0;b<u;b++){let _=t.subarray(b*i,Math.min((b+1)*i,t.length)),w=await ee(o,_,Cr(f,b,u));g.push(w),h+=4+w.iv.length+w.ct.length;}let m=new Uint8Array(h);m.set(d,0);let y=d.length;for(let b of g)we(m,y,b.iv.length+b.ct.length),y+=4,m.set(b.iv,y),y+=b.iv.length,m.set(b.ct,y),y+=b.ct.length;return m}function Ks(e){if(!Dt(e))throw new c("This file is not an encrypted skapi file.",{code:"INVALID_PARAMETER"});let t=Re(e,48),r=Le+t;if(e.length<r)throw new c("Encrypted file header is truncated.",{code:"INVALID_REQUEST"});let n=null;return t&&(n=JSON.parse(De(e.subarray(Le,r)))),{version:e[6],chunkBytes:Re(e,8),count:Re(e,12),fileId:e.subarray(16,16+Nr),plainLen:js(e,32),dekId:e.subarray(40,48),meta:n,headerLen:r}}async function Lr(e,t,r){let n=Ks(t);if(n.version!==Ur)throw new c(`This file was encrypted by a different version of the SDK (container v${n.version}).`,{code:"NOT_SUPPORTED"});if(!n.count||!n.chunkBytes)throw new c("Encrypted file header is malformed.",{code:"INVALID_PARAMETER"});let i=await Dr(e);if(!Vs(i,n.dekId))throw new c("This file was encrypted under a previous data key for this record, so it can no longer be opened. It was most likely left behind by an interrupted access change.",{code:"ENCRYPTION_FILE_STALE_KEY"});let s=await xr(e,n.fileId,r.service,r.owner,r.recordOwner,r.recordId),o=await tt(t.subarray(0,n.headerLen)),a=[],l=n.headerLen,u=0;for(let g=0;g<n.count;g++){if(l+4>t.length)throw new c("Encrypted file is truncated.",{code:"INVALID_REQUEST"});let h=Re(t,l);if(l+=4,h<Ce+16||l+h>t.length)throw new c("Encrypted file is truncated.",{code:"INVALID_REQUEST"});let m=await re(s,t.subarray(l,l+Ce),t.subarray(l+Ce,l+h),Cr(o,g,n.count));l+=h,a.push(m),u+=m.length;}let d=new Uint8Array(u),f=0;for(let g of a)d.set(g,f),f+=g.length;return {bytes:d,meta:n.meta}}var Hs="skapi__keyring",Ve="__skapi_enc__",Fr=1,Ws="skapi-enc",he="keys",Ct=new WeakMap;function Vr(e){if(!e)return null;if(e===true&&(e={}),typeof e!="object")throw new c('"options.encryption" should be a boolean or an object.',{code:"INVALID_PARAMETER"});let t=typeof e.iterations=="number"?e.iterations:_r;if(t<1e5)throw new c('"encryption.iterations" must be at least 100000.',{code:"INVALID_PARAMETER"});let r=e.trustPolicy==="strict"?"strict":"tofu";return {enabled:true,iterations:t,trustPolicy:r,persistDevice:e.persistDevice!==false,minPasswordLength:typeof e.minPasswordLength=="number"?e.minPasswordLength:0,withheld:e.withheld==="sentinel"?"sentinel":"null",recovery:e.recovery==="none"?"none":"code",table:typeof e.table=="string"&&e.table?e.table:Hs}}function D(){return Ct.get(this)||null}function $r(e){if(!e){Ct.delete(this);return}Ct.set(this,{cfg:e,status:"locked",reason:"NO_SESSION_KEY",user_id:"",scope:"",mk:null,ikPriv:null,pubRaw:null,fpr:"",keyringRecordId:"",pins:{},dek:new Map,roll:new Set,ready:null,unlocking:false,pendingRecoveryCode:"",peerPub:new Map,peerInflight:new Map});}function Ot(){let e=D.call(this);if(e){e.user_id&&Wt.call(this,e).catch(()=>{}),e.ready=null,e.unlocking=false,e.pendingRecoveryCode="";for(let[,t]of e.dek)L(t.bytes);e.dek.clear(),e.roll.clear(),e.peerPub.clear(),e.peerInflight.clear(),e.pins={},e.mk=null,e.ikPriv=null,e.pubRaw=null,e.fpr="",e.keyringRecordId="",e.user_id="",e.status="locked",e.reason="NO_SESSION_KEY";}}function qr(){let e=D.call(this);return e?{status:e.status,reason:e.status==="unlocked"?void 0:e.reason,user_id:e.user_id||void 0,fingerprint:e.fpr||void 0}:{status:"disabled"}}function jr(e,t){return typeof t=="string"&&t===e.cfg.table}function Pe(){return `${this.service}/${this.owner}`}function Lt(e,t,r,n){let[i,s]=e.split("/");return Nt([z,i,s,t,r,n])}function Br(e,t,r,n,i){let[s,o]=e.split("/");return B(`${z}|dekwrap|${s}|${o}|${t}|${r}|${n}|${i}`)}function Mt(e){return e.anch==="uid"?e.uid:e.anch==="rid"?e.rid:""}function it(e){return !!e&&typeof e=="object"&&!Array.isArray(e)&&typeof e[Ve]=="number"&&typeof e.ct=="string"&&typeof e.iv=="string"&&typeof e.own=="string"&&typeof e.anch=="string"&&!!e.k&&typeof e.k=="object"&&!Array.isArray(e.k)}var Kr="__skapi_no_access__";function ne(e,t,r){if(e.withheld!=="sentinel")return null;let n={[Kr]:true,reason:t};return r&&(n.recipients=r),Object.freeze(n)}function Ft(e){return !!e&&typeof e=="object"&&e[Kr]===true}async function Qs(e,t,r){let n=t?.table,i=typeof n=="string"?n:n?.name;if(n&&(typeof n=="string"||n.access_group!==void 0))return {group:typeof n=="string"?0:Mr(n.access_group),table:i,record:null};if(!r)return {group:n?.access_group!==void 0?Mr(n.access_group):0,table:i,record:null};let s=e.dek.get(r);if(s)return {group:s.access_group,table:i,record:null};let o=await $e.call(this,r);if(!o)throw new c(`Record "${r}" not found.`,{code:"NOT_EXISTS"});return {group:o.table.access_group,table:o.table.name,record:o}}async function $e(e){let t=/^[a-zA-Z0-9]+$/.test(e)?{record_id:e}:{unique_id:e};return (await this.getRecords(t,{limit:1}))?.list?.[0]||null}function Mr(e){return e==="private"||e==="**"?"private":e==="public"?0:e==="authorized"?1:e==="admin"?99:typeof e=="number"?e:0}async function Vt(e,t,r){let n=D.call(this);if(!n)return {send:e,plain:e,encrypted:false,omit:false};let i=t?.record_id||"",s=i,o=t?.unique_id||"",{group:a,table:l,record:u}=await Qs.call(this,n,t,s);if(a!=="private"){if(s){let U=n.dek.get(s);U&&(L(U.bytes),n.dek.delete(s));}if(!r&&i){let U=u||await $e.call(this,i);if(U&&U.encrypted){if(U.encrypted.status==="failed")throw new c(`Cannot make record "${i}" non-private: its current contents could not be decrypted (${U.encrypted.reason}), so they cannot be written back in the clear. Unlock encryption, or supply the record's data with the access group change.`,{code:"ENCRYPTION_LOCKED"});return {send:U.data,plain:U.data,encrypted:false,omit:false}}}return {send:e,plain:e,encrypted:false,omit:!r}}if(jr(n,l))return {send:e,plain:e,encrypted:false,omit:false};if(n.ready&&!n.unlocking)try{await n.ready;}catch{}if(!r)return {send:e,plain:e,encrypted:false,omit:true};if(Ft.call(this,e))throw new c("This record's data could not be decrypted by this session, so it cannot be written back. Writing it would replace the record with the placeholder.",{code:"ENCRYPTION_CANNOT_REWRITE_WITHHELD"});if(n.status!=="unlocked"||!n.mk)throw new c("Encryption is enabled but locked, so this private record cannot be written. Call unlockEncryption({ password }) first, or the user must log in with their password.",{code:"ENCRYPTION_LOCKED"});if(e&&typeof e=="object"&&!Array.isArray(e)&&Object.prototype.hasOwnProperty.call(e,Ve))throw new c(`"${Ve}" is a reserved key in record data.`,{code:"INVALID_PARAMETER"});if(t?.service&&t.service!==this.service||t?.owner&&t.owner!==this.owner)throw new c("Encrypted records cannot be written to another project. The encryption key is derived per project, so a record written under one service and read under another could never be decrypted. Construct a separate Skapi instance for that project.",{code:"INVALID_REQUEST"});let d=this.user?.user_id;if(!d)throw new c("User login is required to write an encrypted record.",{code:"INVALID_REQUEST"});let f=Pe.call(this),g=false;if(i&&n.roll.has(i)){g=true,n.roll.delete(i);let U=n.dek.get(i);n.dek.delete(i),U&&L(U.bytes);}let h=null;if(i&&!g&&(h=n.dek.get(i)||null,!h)){let U=u||await $e.call(this,i);if(U&&(s=U.record_id||i,h=n.dek.get(s)||null,!o&&U.unique_id&&(o=U.unique_id),!h&&U.encrypted?.status==="failed"))throw new c(`Cannot update encrypted record "${i}": its current contents could not be decrypted (${U.encrypted.reason}), so its existing key wraps cannot be preserved. Updating anyway would revoke everyone it is shared with.`,{code:"ENCRYPTION_LOCKED"})}s===i&&h&&h.rid&&(s=h.rid),!o&&h&&h.anch==="uid"&&h.uid&&(o=h.uid);let m,y,b;if(h)m=h.bytes,y=h.key,b=Object.assign({},h.recipients);else {let U=await Ar();m=U.bytes,y=U.key,b={};}let _=o?"uid":s?"rid":"new",w=_==="uid"?o:_==="rid"?s:"",T=Lt(f,d,_,w),k=Fe(T,d,"mk"),S=await ee(n.mk,m,k);b[d]={t:"mk",iv:O(S.iv),ct:O(S.ct)},h&&(h.anch!==_||Mt(h)!==w)&&(b=await Gs.call(this,n,m,b,f,d,_,w,T));let C=B(JSON.stringify(e===void 0?null:e)),x=await ee(y,C,T);L(C);let $={[Ve]:Fr,enc:"A256GCM",kw:"ECDH-ES+A256GCM",anch:_,uid:o,rid:s,own:d,iv:O(x.iv),ct:O(x.ct),k:b},v=JSON.stringify($).length;if(v>2*1024*1024)throw new c(`Encrypted record data is too large: once encrypted and base64 encoded it becomes ${v} bytes, over the ${2*1024*1024} byte limit. Encryption costs about 33% plus roughly 230 bytes per additional recipient.`,{code:"ENCRYPTED_DATA_TOO_LARGE"});return s&&n.dek.set(s,{bytes:m,key:y,recipients:b,anch:_,uid:o,rid:s,own:d,access_group:"private"}),{send:$,plain:e,encrypted:true,omit:false,dek:{bytes:m,key:y,recipients:b,anch:_,uid:o,rid:s,own:d,access_group:"private"}}}function Hr(e,t){let r=D.call(this);!r||!t||!e||r.dek.has(e)||r.dek.set(e,Object.assign({},t,{rid:e}));}async function Gs(e,t,r,n,i,s,o,a){let l=Object.keys(r).filter(f=>f!==i);if(!l.length)return r;let u=await Qt.call(this,l),d={[i]:r[i]};for(let f of l){let g=u[f];g&&(d[f]=await Wr.call(this,t,g,n,o,i,f,a));}return d}async function Wr(e,t,r,n,i,s,o){let a=Br(r,n,i,s,t.fpr),l=Fe(o,s,t.fpr),u=await Pr(t.pubRaw,e,a,l);return {t:"ecdh",epk:O(u.epk),iv:O(u.iv),ct:O(u.ct),fpr:t.fpr}}async function $t(e,t){if(!it(e))return {value:e};if(t.access_group!=="private")return {value:e};let r=D.call(this);if(!r)return {value:null,flag:{status:"failed",reason:"ENCRYPTION_DISABLED"}};if(jr(r,t.table_name))return {value:e};if(e[Ve]!==Fr)return {value:ne(r.cfg,"UNSUPPORTED_VERSION"),flag:{status:"failed",reason:"UNSUPPORTED_VERSION"}};if(r.ready&&!r.unlocking)try{await r.ready;}catch{}if(e.own!==t.user_id)return {value:ne(r.cfg,"BINDING_MISMATCH"),flag:{status:"failed",reason:"BINDING_MISMATCH"}};if(e.uid&&t.unique_id&&e.uid!==t.unique_id)return {value:ne(r.cfg,"BINDING_MISMATCH"),flag:{status:"failed",reason:"BINDING_MISMATCH"}};if(e.rid&&t.record_id&&e.rid!==t.record_id)return {value:ne(r.cfg,"BINDING_MISMATCH"),flag:{status:"failed",reason:"BINDING_MISMATCH"}};let n=this.user?.user_id,i=n?e.k[n]:null;if(!i)return {value:ne(r.cfg,"NOT_A_RECIPIENT",Object.keys(e.k)),flag:{status:"failed",reason:"NOT_A_RECIPIENT",recipients:Object.keys(e.k)}};if(r.status!=="unlocked"||!r.mk)return {value:ne(r.cfg,"NO_SESSION_KEY"),flag:{status:"failed",reason:"NO_SESSION_KEY"}};let s=Pe.call(this),o=Mt(e),a=Lt(s,e.own,e.anch,o),l;try{if(i.t==="mk")l=await re(r.mk,F(i.iv),F(i.ct),Fe(a,n,"mk"));else if(i.t==="ecdh"){if(!r.ikPriv)return {value:ne(r.cfg,"NO_SESSION_KEY"),flag:{status:"failed",reason:"NO_SESSION_KEY"}};l=await Tr(r.ikPriv,F(i.epk),F(i.iv),F(i.ct),Br(s,o,e.own,n,i.fpr),Fe(a,n,i.fpr));}else return {value:ne(r.cfg,"UNSUPPORTED_VERSION"),flag:{status:"failed",reason:"UNSUPPORTED_VERSION"}}}catch{return {value:ne(r.cfg,"BAD_KEY"),flag:{status:"failed",reason:"BAD_KEY"}}}let u,d;try{d=await te(l),u=await re(d,F(e.iv),F(e.ct),a);}catch{return L(l),{value:ne(r.cfg,"CORRUPT"),flag:{status:"failed",reason:"CORRUPT"}}}let f;try{f=JSON.parse(De(u));}catch{return L(u),L(l),{value:ne(r.cfg,"CORRUPT"),flag:{status:"failed",reason:"CORRUPT"}}}if(L(u),t.record_id){let g=r.dek.get(t.record_id);g?(g.bytes=l,g.key=d,g.recipients=e.k,g.anch=e.anch,g.uid=e.uid,g.own=e.own,g.access_group="private"):r.dek.set(t.record_id,{bytes:l,key:d,recipients:e.k,anch:e.anch,uid:e.uid,rid:t.record_id,own:e.own,access_group:"private"});}else L(l);return {value:f,flag:{status:"encrypted",recipients:Object.keys(e.k)}}}function qe(e,t){let[r,n]=e.split("/");return B(`${z}|kek|${r}|${n}|${t}`)}function je(e,t,r,n){let[i,s]=e.split("/");return B(`${z}|mk|${i}|${s}|${t}|PBKDF2-SHA256|${r}|${n}`)}function Qr(e,t){let[r,n]=e.split("/");return B(`${z}|recovery|${r}|${n}|${t}`)}function Gr(e,t,r){let[n,i]=e.split("/");return B(`${z}|rk|${n}|${i}|${t}|HKDF-SHA256|${r}`)}function zr(e,t){let[r,n]=e.split("/");return B(`${z}|self|${r}|${n}|${t}`)}function Jr(e,t){let[r,n]=e.split("/");return B(`${z}|ik|${r}|${n}|${t}`)}async function st(e){let r=((await this.getRecords({table:{name:e.cfg.table,access_group:"private"},index:{name:"$user_id",value:this.user.user_id,condition:"="}},{limit:2}))?.list||[]).filter(n=>n.user_id===this.user.user_id);return r.length?(r.sort((n,i)=>n.uploaded-i.uploaded),r[0]):null}async function qt(e,t,r){let n=J(Oe),i=kr(n),s=J(16),o=O(s),a=await xt(n,s,Qr(e,t)),l=await ee(a,r,Gr(e,t,o));return L(n),{code:i,wrap:{id:O(J(6)),p:"recovery",kdf:{a:"HKDF-SHA256",s:o},iv:O(l.iv),ct:O(l.ct),created:Date.now()}}}async function zs(e,t,r,n){let i=vr(n),s=(r||[]).filter(o=>o.p==="recovery");s.sort((o,a)=>(a.created||0)-(o.created||0));for(let o of s)try{let a=await xt(i,F(o.kdf.s),Qr(e,t)),l=await re(a,F(o.iv),F(o.ct),Gr(e,t,o.kdf.s));return L(i),l}catch{}return L(i),null}async function Js(e,t,r,n,i){let s=J(16),o=O(s),a=await Ie(n,s,e.cfg.iterations,qe(t,r)),l=await ee(a,i,je(t,r,e.cfg.iterations,o));return {id:O(J(6)),p:"password",kdf:{a:"PBKDF2-SHA256",it:e.cfg.iterations,s:o},iv:O(l.iv),ct:O(l.ct),created:Date.now()}}async function Ys(e,t){let r=this.user.user_id,n=e.scope,i=J(16),s=O(i),o=await Ie(t,i,e.cfg.iterations,qe(n,r)),a=J(32),l=await ee(o,a,je(n,r,e.cfg.iterations,s)),u=await te(a),d=await Rr(),f=await ee(u,d.pkcs8,Jr(n,r));L(d.pkcs8);let g=null;e.cfg.recovery==="code"&&(g=await qt(n,r,a));let h=await ee(u,a,zr(n,r));L(a);let m=await Ut(d.pubRaw),y=Date.now(),b=[{id:O(J(6)),p:"password",kdf:{a:"PBKDF2-SHA256",it:e.cfg.iterations,s},iv:O(l.iv),ct:O(l.ct),created:y}];g&&b.push(g.wrap);let _={v:1,alg:"ECDH-P-256",user_id:r,wraps:b,ik:{iv:O(f.iv),ct:O(f.ct)},self:{iv:O(h.iv),ct:O(h.ct)},pub:O(d.pubRaw),fpr:m,pins:null,created:y,updated:y};await this.postRecord({v:1,alg:"ECDH-P-256",user_id:r,pub:O(d.pubRaw),fpr:m,created:y},{table:{name:e.cfg.table,access_group:"authorized"},index:{name:"pubkey",value:r}});let w=await this.postRecord(_,{table:{name:e.cfg.table,access_group:"private"}}),T=await st.call(this,e);if(T&&T.record_id!==w.record_id){await Yr.call(this,e,T,t);return}e.mk=u,e.ikPriv=d.priv,e.pubRaw=d.pubRaw,e.fpr=m,e.keyringRecordId=w.record_id,g&&(e.pendingRecoveryCode=g.code),e.user_id=r,e.pins={},e.status="unlocked",e.reason="";}async function Yr(e,t,r){let n=this.user.user_id,i=e.scope,s=t.data;if(t.user_id!==n||s&&s.user_id&&s.user_id!==n)throw new c("The encryption keyring does not belong to this user.",{code:"ENCRYPTION_KEYRING_CORRUPT"});let a=(Array.isArray(s?.wraps)?s.wraps:[]).filter(d=>d.p==="password");if(!a.length)throw new c("The keyring has no password wrap.",{code:"ENCRYPTION_KEYRING_CORRUPT"});a.sort((d,f)=>(f.created||0)-(d.created||0));let l=null;for(let d of a)try{let f=F(d.kdf.s),g=await Ie(r,f,d.kdf.it,qe(i,n));l=await re(g,F(d.iv),F(d.ct),je(i,n,d.kdf.it,d.kdf.s));break}catch{}if(!l)throw new c("Incorrect password: the encryption keyring could not be opened.",{code:"ENCRYPTION_BAD_PASSWORD"});let u=await te(l);L(l),await jt.call(this,e,t,u);}async function jt(e,t,r){let n=this.user.user_id,i=t.data,s=await re(r,F(i.ik.iv),F(i.ik.ct),Jr(e.scope,n)),o=await vt(s);L(s);let a={};if(i.pins&&typeof i.pins=="object"&&i.pins.ct)try{let l=await re(r,F(i.pins.iv),F(i.pins.ct),B(`${z}|pins|${e.scope}|${n}`));a=JSON.parse(De(l)),L(l);}catch{a={};}e.mk=r,e.ikPriv=o,e.pubRaw=F(i.pub),e.fpr=i.fpr,e.keyringRecordId=t.record_id,e.user_id=n,e.pins=a,e.status="unlocked",e.reason="";}async function ot(e){let t=D.call(this);if(!t||!this.user?.user_id)return;if(!kt()){t.status="locked",t.reason="NO_WEB_CRYPTO";return}if(this.user?.is_openid){t.status="locked",t.reason="OPENID_UNSUPPORTED";return}if(t.cfg.minPasswordLength&&e.length<t.cfg.minPasswordLength){t.status="locked",t.reason="WEAK_PASSWORD";return}t.scope=Pe.call(this);let r=await st.call(this,t);r?await Yr.call(this,t,r,e):await Ys.call(this,t,e),t.cfg.persistDevice&&await rn.call(this,t).catch(()=>{});}async function Xr(e){await this.__connection;let t=D.call(this);if(!t)throw new c("Encryption is not enabled for this instance.",{code:"INVALID_REQUEST"});if(!this.user?.user_id)throw new c("User login is required.",{code:"INVALID_REQUEST"});if(!e?.password||typeof e.password!="string")throw new c('"password" is required.',{code:"INVALID_PARAMETER"});if(await ot.call(this,e.password),t.status!=="unlocked")throw new c(`Encryption could not be unlocked: ${t.reason}`,{code:"ENCRYPTION_LOCKED"});return {status:t.status}}async function Zr(e){let t=D.call(this);return t?(e?.forgetDevice&&await Wt.call(this,t).catch(()=>{}),Ot.call(this),this.__cached_requests={},{status:t.status}):{status:"disabled"}}async function en(e,t){let r=D.call(this);if(!r)return;if(r.status!=="unlocked"||!r.mk)throw new c("Encryption must be unlocked before changing the password, or the encryption keyring would be left wrapped under a password that no longer exists. Call unlockEncryption({ password }) first.",{code:"ENCRYPTION_LOCKED"});let i=(await this.getRecords({record_id:r.keyringRecordId},{limit:1}))?.list?.[0];if(!i)throw new c("The encryption keyring could not be read, so the password change was stopped before it could strand it.",{code:"ENCRYPTION_KEYRING_CORRUPT"});let s=this.user.user_id,o=i.data,a=(o.wraps||[]).filter(y=>y.p==="password");a.sort((y,b)=>(b.created||0)-(y.created||0));let l=null;for(let y of a)try{let b=await Ie(e,F(y.kdf.s),y.kdf.it,qe(r.scope,s));l=await re(b,F(y.iv),F(y.ct),je(r.scope,s,y.kdf.it,y.kdf.s));break}catch{}if(!l)throw new c("Incorrect current password: the encryption keyring was not re-wrapped.",{code:"ENCRYPTION_BAD_PASSWORD"});let u=J(16),d=O(u),f=await Ie(t,u,r.cfg.iterations,qe(r.scope,s)),g=await ee(f,l,je(r.scope,s,r.cfg.iterations,d));L(l);let h=Date.now(),m=(o.wraps||[]).concat([{id:O(J(6)),p:"password",kdf:{a:"PBKDF2-SHA256",it:r.cfg.iterations,s:d},iv:O(g.iv),ct:O(g.ct),created:h}]);await this.postRecord(Object.assign({},o,{wraps:m,updated:h}),{record_id:r.keyringRecordId});}async function tn(){let e=D.call(this);if(!e||e.status!=="unlocked"||!e.keyringRecordId)return;let r=(await this.getRecords({record_id:e.keyringRecordId},{limit:1}))?.list?.[0];if(!r)return;let n=r.data,i=(n.wraps||[]).filter(o=>o.p==="password").sort((o,a)=>(a.created||0)-(o.created||0)),s=(n.wraps||[]).filter(o=>o.p!=="password");i.length<=1||await this.postRecord(Object.assign({},n,{wraps:[i[0]].concat(s),updated:Date.now()}),{record_id:e.keyringRecordId});}function Bt(){return typeof indexedDB<"u"&&!!indexedDB}function Kt(){return new Promise((e,t)=>{let r=indexedDB.open(Ws,1);r.onupgradeneeded=()=>{let n=r.result;n.objectStoreNames.contains(he)||n.createObjectStore(he);},r.onsuccess=()=>e(r.result),r.onerror=()=>t(r.error);})}function Ht(e){return `${e.scope}#${this.user?.user_id}`}async function rn(e){if(!Bt()||!e.mk)return;let t=await Kt();await new Promise((r,n)=>{let i=t.transaction(he,"readwrite");i.objectStore(he).put({mk:e.mk,keyringRecordId:e.keyringRecordId,saved:Date.now()},Ht.call(this,e)),i.oncomplete=()=>r(),i.onerror=()=>n(i.error);}),t.close();}async function Xs(e){if(!Bt())return null;let t=await Kt(),r=await new Promise((n,i)=>{let o=t.transaction(he,"readonly").objectStore(he).get(Ht.call(this,e));o.onsuccess=()=>n(o.result||null),o.onerror=()=>i(o.error);});return t.close(),r&&r.mk?r:null}async function Wt(e){if(!Bt())return;let t=await Kt();await new Promise((r,n)=>{let i=t.transaction(he,"readwrite");i.objectStore(he).delete(Ht.call(this,e)),i.oncomplete=()=>r(),i.onerror=()=>n(i.error);}),t.close();}function nn(){let e=D.call(this);!e||e.ready||(e.unlocking=true,e.ready=Zs.bind(this)().catch(()=>false).then(()=>{e.unlocking=false;}));}async function Zs(){let e=D.call(this);if(!e||!this.user?.user_id||!e.cfg.persistDevice||!kt())return false;e.scope=Pe.call(this);try{let t=await Xs.call(this,e);if(!t)return !1;let r=await st.call(this,e);return r?(await jt.call(this,e,r,t.mk),!0):(await Wt.call(this,e).catch(()=>{}),!1)}catch{return e.status="locked",e.reason="NO_SESSION_KEY",false}}async function Qt(e){let t=D.call(this);if(!t)throw new c("Encryption is not enabled for this instance.",{code:"INVALID_REQUEST"});let r={},n=[],i=false;for(let s of e){let o=t.peerPub.get(s);o?r[s]=o:n.push(s);}return await Promise.all(n.map(async s=>{let o=t.peerInflight.get(s);o||(o=(async()=>{let u=((await this.getRecords({table:{name:t.cfg.table,access_group:"authorized"},index:{name:"$user_id",value:s,condition:"="}},{limit:10}))?.list||[]).filter(h=>h.user_id===s&&h.data?.pub);if(!u.length)return null;u.sort((h,m)=>m.uploaded-h.uploaded);let d=F(u[0].data.pub),f=await Ut(d),g=t.pins[s];if(g&&g!==f)throw new c(`The public key for user "${s}" has changed since it was first seen. This is expected if they reset their account, and is what a key substitution attack also looks like. Verify the new fingerprint out of band, then call pinPeerKey({ user_id, fingerprint }).`,{code:"ENCRYPTION_PEER_KEY_CHANGED"});if(!g){if(t.cfg.trustPolicy==="strict")throw new c(`No pinned key for user "${s}" and trustPolicy is "strict". Pin it first with pinPeerKey().`,{code:"ENCRYPTION_PEER_NOT_PINNED"});t.pins[s]=f,i=true;}return {pubRaw:d,fpr:f}})().finally(()=>t.peerInflight.delete(s)),t.peerInflight.set(s,o));let a=await o;a&&t.peerPub.set(s,a),r[s]=a;})),i&&await ln.call(this,t).catch(()=>{}),r}async function sn(e,t){let r=Pe.call(this),n=e.dek.get(t);if(n)return {entry:n,scope:r};let i=await $e.call(this,t);if(!i)throw new c(`Record "${t}" not found.`,{code:"NOT_EXISTS"});if(i.encrypted?.status==="failed"&&i.encrypted.reason==="DATA_UNAVAILABLE")throw new c(`Cannot change sharing on record "${t}": its data could not be read, so whether it is encrypted is unknown. Retry once the record reads normally.`,{code:"ENCRYPTION_DATA_UNAVAILABLE"});if(!i.encrypted)return null;if(i.user_id!==this.user?.user_id)throw new c("Only the record owner can share or revoke an encrypted record, because adding or removing a key wrap means writing the record.",{code:"ENCRYPTION_GRANT_REQUIRES_OWNER"});let s=e.dek.get(i.record_id)||e.dek.get(t);if(!s)throw new c(`Cannot change sharing on record "${t}": its data could not be decrypted`+(i.encrypted.reason?` (${i.encrypted.reason})`:"")+".",{code:"ENCRYPTION_LOCKED"});return {entry:s,scope:r}}async function Gt(e,t){let r=D.call(this);if(!r)return;let n=await sn.call(this,r,e);if(!n)return;let{entry:i,scope:s}=n,o=this.user.user_id;if(i.own!==o)throw new c("Only the record owner can share an encrypted record, because adding a key wrap means writing the record.",{code:"ENCRYPTION_GRANT_REQUIRES_OWNER"});let a=await Qt.call(this,t),l=t.filter(g=>!a[g]);if(l.length)throw new c(`These users have no encryption key yet, so they cannot be given access: ${l.join(", ")}. A user's key is created the first time they log in with encryption enabled.`,{code:"ENCRYPTION_RECIPIENT_HAS_NO_KEY"});let u=Mt(i),d=Lt(s,i.own,i.anch,u),f=Object.assign({},i.recipients);for(let g of t)g!==o&&(f[g]=await Wr.call(this,i.bytes,a[g],s,u,i.own,g,d));await eo.call(this,r,e,i,f);}async function on(e,t){let r=D.call(this);if(!r)return;let n=await sn.call(this,r,e);if(!n)return;let{entry:i}=n,s=this.user.user_id;if(i.own!==s)throw new c("Only the record owner can revoke access to an encrypted record.",{code:"ENCRYPTION_GRANT_REQUIRES_OWNER"});let o=Object.keys(i.recipients).filter(u=>u===s?true:t?!t.includes(u):false).filter(u=>u!==s),a=await $e.call(this,e);if(!a)throw new c(`Record "${e}" not found.`,{code:"NOT_EXISTS"});an(a,e);let l={};if(o.length){l=await Qt.call(this,o);let u=o.filter(d=>!l[d]);if(u.length)throw new c(`Cannot revoke on record "${e}": these users keep access but their encryption keys could not be read, so re-sharing after the key roll would fail and lock them out: ${u.join(", ")}.`,{code:"ENCRYPTION_RECIPIENT_HAS_NO_KEY"})}r.roll.add(a.record_id||e),await this.postRecord(a.data,{record_id:a.record_id||e,table:{name:a.table.name,access_group:"private"}}),o.length&&await Gt.call(this,a.record_id||e,o);}function an(e,t){if(e?.encrypted?.status==="failed")throw new c(`Cannot change sharing on record "${t}": its current data could not be read (${e.encrypted.reason}), so re-writing the record would destroy it.`,{code:"ENCRYPTION_DATA_UNAVAILABLE"})}async function eo(e,t,r,n){let s=(await this.getRecords({record_id:t},{limit:1}))?.list?.[0];if(!s)throw new c(`Record "${t}" not found.`,{code:"NOT_EXISTS"});an(s,t),r.recipients=n,e.dek.set(t,r),await this.postRecord(s.data,{record_id:t});}async function cn(e){let t=D.call(this);if(!t||t.status!=="unlocked")throw new c("Encryption is locked.",{code:"ENCRYPTION_LOCKED"});t.pins[e.user_id]=e.fingerprint,t.peerPub.delete(e.user_id),await ln.call(this,t);}async function ln(e){if(!e.mk||!e.keyringRecordId)return;let r=(await this.getRecords({record_id:e.keyringRecordId},{limit:1}))?.list?.[0];if(!r)return;let n=await ee(e.mk,B(JSON.stringify(e.pins)),B(`${z}|pins|${e.scope}|${e.user_id}`));await this.postRecord(Object.assign({},r.data,{pins:{iv:O(n.iv),ct:O(n.ct)},updated:Date.now()}),{record_id:e.keyringRecordId});}function un(){let e=D.call(this);if(!e||!e.pendingRecoveryCode)return null;let t=e.pendingRecoveryCode;return e.pendingRecoveryCode="",t}async function dn(e){await this.__connection;let t=D.call(this);if(!t)throw new c("Encryption is not enabled for this instance.",{code:"INVALID_REQUEST"});if(!this.user?.user_id)throw new c("User login is required. Reset the password and log in first, then use the recovery code.",{code:"INVALID_REQUEST"});if(!e?.code||typeof e.code!="string")throw new c('"code" is required.',{code:"INVALID_PARAMETER"});t.scope=Pe.call(this);let r=this.user.user_id,n=await st.call(this,t);if(!n)throw new c("This account has no encryption keyring, so there is nothing to recover.",{code:"NOT_EXISTS"});let i=await zs(t.scope,r,n.data?.wraps||[],e.code);if(!i)throw new c("That recovery code did not open the keyring. Check it against the copy you saved when encryption was set up.",{code:"ENCRYPTION_BAD_RECOVERY_CODE"});let s=await te(i);await jt.call(this,t,n,s);let o=false,a=null,l=(n.data?.wraps||[]).slice();if(e.password&&(l=l.filter(u=>u.p!=="password"),l.push(await Js(t,t.scope,r,e.password,i)),o=true),t.cfg.recovery==="code"){let u=await qt(t.scope,r,i);l=l.filter(d=>d.p!=="recovery"),l.push(u.wrap),a=u.code;}return L(i),await this.postRecord(Object.assign({},n.data,{wraps:l,updated:Date.now()}),{record_id:n.record_id}),t.cfg.persistDevice&&await rn.call(this,t).catch(()=>{}),{status:t.status,repaired:o,recoveryCode:a}}async function fn(){await this.__connection;let e=D.call(this);if(!e)throw new c("Encryption is not enabled for this instance.",{code:"INVALID_REQUEST"});if(e.status!=="unlocked"||!e.mk)throw new c("Encryption must be unlocked to issue a recovery code. Only someone who can already decrypt can create one.",{code:"ENCRYPTION_LOCKED"});if(e.cfg.recovery!=="code")throw new c('Recovery codes are disabled for this instance ("recovery" is "none").',{code:"INVALID_REQUEST"});let r=(await this.getRecords({record_id:e.keyringRecordId},{limit:1}))?.list?.[0];if(!r)throw new c("The encryption keyring could not be read.",{code:"ENCRYPTION_KEYRING_CORRUPT"});let n=r.data?.self;if(!n||!n.ct)throw new c("This keyring predates recovery-code rotation and cannot issue a new code. Use unlockWithRecoveryCode() with the existing code, which issues a replacement.",{code:"ENCRYPTION_KEYRING_CORRUPT"});let i=await re(e.mk,F(n.iv),F(n.ct),zr(e.scope,e.user_id)),s=await qt(e.scope,e.user_id,i);L(i);let o=(r.data.wraps||[]).filter(a=>a.p!=="recovery").concat([s.wrap]);return await this.postRecord(Object.assign({},r.data,{wraps:o,updated:Date.now()}),{record_id:e.keyringRecordId}),{recoveryCode:s.code}}var nt="__skenc__",gn="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";function to(e){if(e===0)return "0";let t="";for(;e>0;)t=gn[e%62]+t,e=Math.floor(e/62);return t}function ro(e){let t=0;for(let r of e){let n=gn.indexOf(r);if(n<0)return NaN;t=t*62+n;}return t}function at(e){if(typeof e!="string")return null;let t=e.lastIndexOf(nt);if(t<0)return null;let r=ro(e.slice(t+nt.length));return Number.isFinite(r)?{key:e.slice(0,t),plainSize:r}:null}function zt(e){try{let t=String(e).split("?")[0].split("/").slice(3);if(t.length<12||t[4]!=="records"||t[7]!=="bin")return null;let r=at(t[10]);return r?{recordId:t[5],recordOwner:t[3],filename:t[t.length-1],plainSize:r.plainSize}:null}catch{return null}}function pn(e,t){return {service:this.service,owner:this.owner,recordOwner:t,recordId:e}}async function hn(e,t,r){let n=D.call(this);if(!n||!e)return {key:t,file:r,encrypted:false};let i=n.dek.get(e);if(!i)return {key:t,file:r,encrypted:false};if(at(t))throw new c(`"${nt}" is reserved in an upload form key.`,{code:"INVALID_PARAMETER"});let s=new Uint8Array(await r.arrayBuffer()),o={n:r.name,t:r.type||"",lm:r.lastModified||0},a=await Or(i.bytes,s,pn.call(this,e,i.own),o);return L(s),{key:`${t}${nt}${to(r.size)}`,file:new File([a],r.name,{type:"application/octet-stream"}),encrypted:true}}async function mn(e,t){let r=D.call(this),n=zt(e);if(!r||!n)return t;let i=r.dek.get(n.recordId);if(!i)throw new c(`Cannot open this file: the data key for record "${n.recordId}" is not available. Read the record first, and make sure encryption is unlocked.`,{code:"ENCRYPTION_LOCKED"});let s=new Uint8Array(await t.arrayBuffer());if(!Dt(s))throw new c("This file is marked as encrypted but its contents are not an encrypted container.",{code:"ENCRYPTION_FILE_CORRUPT"});let o=await Lr(i.bytes,s,pn.call(this,n.recordId,n.recordOwner)),a=o.meta&&o.meta.t||"application/octet-stream";return new Blob([o.bytes],{type:a})}var j=null;function Jt(e){let t={tkid:"ticket_id",cond:"condition",stmp:"timestamp",actn:"action",cnt:"count",ttl:"time_to_live",plch:"placeholder",hash:"hash",desc:"description",pmc:"limit_per_user"},r={};for(let n in e)if(n==="tkid"){let i=e[n].split("#");if(i.length===1){r.ticket_id=i[0];continue}r.ticket_id=i[1],r.consume_id=i[2],r.user_id=i[3];let s=i[2].slice(-4);if(r.is_test=s===":CHK",!e.stmp){let o=i[2].slice(0,-4);/^[0-9]+$/.test(o)?r.timestamp=parseInt(o,10):r.timestamp=X(i[2].slice(0,-4));}}else t[n]?r[t[n]]=e[n]:r[n]=e[n];return r}async function bn(e){if(!e.ticket_id)throw new c("Ticket ID is required.",{code:"INVALID_PARAMETER"});if(!e.method)throw new c('Method is required. Should be either "GET" or "POST"',{code:"INVALID_PARAMETER"});let t=e.ticket_id;await this.__connection;let r=await P.bind(this)(`https://${this.service.slice(0,4)}.${this.customApiDomain}/auth/consume/${this.service}/${this.owner}/${t}`,e?.data||{},{method:e.method,auth:!!e?.auth});return Jt(r)}async function _n(e,t){await this.__connection;let r=await P.bind(this)("ticket",Object.assign({exec:"list"},e||{}),{auth:true,fetchOptions:t});return r.list=r.list.map(Jt),r}async function wn(e,t){await this.__connection;let r=await P.bind(this)("ticket",Object.assign({exec:"consumed"},e||{}),{auth:true,fetchOptions:t});return r.list=r.list.map(Jt),r}async function En(e){return P.bind(this)("register-ticket",Object.assign({exec:"reg"},e),{auth:true})}async function An(e){return P.bind(this)("register-ticket",Object.assign({exec:"unreg"},e),{auth:true})}var co=3600;async function Se(){if(await this.__connection,this.session){let e=Math.floor(Date.now()/1e3),r=this.session.getIdToken().getExpiration();if(r<e+co){this.log("request:requesting new token",null);try{await Q.bind(this)().getSession({refreshToken:!0}),this.log("request:received new tokens",{exp:this.session?.idToken?.payload?.exp,currentTime:e,expiresIn:r-e,token:this.session?.accessToken?.jwtToken,refreshToken:this.session?.refreshToken?.token});}catch(n){throw this.log("request:new token error",n),new c("User login is required.",{code:"INVALID_REQUEST"})}}else this.log("request:tokens",{exp:this.session.idToken.payload.exp,currentTime:e,expiresIn:r-e,token:this.session.accessToken.jwtToken,refreshToken:this.session.refreshToken.token});return this.session?.idToken?.jwtToken}else throw this.log("request:no session",null),pe.bind(this)(),new c("User login is required.",{code:"INVALID_REQUEST"})}function yn(e,t){return new Promise((r,n)=>{t.refreshSession(e.getRefreshToken(),(i,s)=>{this.log("getSession:refreshSessionCallback",{refreshErr:i,refreshedSession:s}),i?(pe.bind(this)(),n(i)):s.isValid()?r(s):(pe.bind(this)(),n(new c("Invalid session.",{code:"INVALID_REQUEST"})));});})}function Q(){if(!this.userPool)throw new c("User pool is missing",{code:"INVALID_REQUEST"});let e=()=>{let s=j.getSignInUserSession().getIdToken().payload||null,o=xe(s);return this.log("normalized user attribute",o),this.__user=o,o},t=async s=>new Promise((o,a)=>{this.log("getSession:option",s);let{refreshToken:l=false,skipUserUpdateEventTrigger:u=false}=s||{};if(l&&u&&(u=false),j=this.userPool.getCurrentUser(),!j){this.log("getSession:cognitoUser",j),pe.bind(this)(),a(null);return}let d=f=>{let g=f.getIdToken().payload;if(this.log("getSession:respond:sessionAttribute",g),g["custom:service"]!==this.service)throw this.log("getSession:respond","invalid service, signing out"),pe.bind(this)(),new c("Invalid session.",{code:"INVALID_REQUEST"});return this.session=f,e(),u||this._runOnUserUpdateListeners(this.user),this.session};j.getSession((f,g)=>{if(this.log("getSession:getSessionCallback",{err:f,session:g}),!g){pe.bind(this)(),a(new c("Current session does not exist.",{code:"INVALID_REQUEST"}));return}if(f){yn.bind(this)(g,j).then(_=>o(d(_))).catch(a);return}let h=Math.floor(Date.now()/1e3),m=g.getIdToken(),y=m.getExpiration(),b=y<h;if(this.log("getSession:currentTime",h),this.log("getSession:idTokenExp",y),this.log("getSession:isExpired",b),this.log("getSession:existingBearerToken",this.bearerToken),this.bearerToken=m.getJwtToken(),b||l||!g.isValid())yn.bind(this)(g,j).then(_=>o(d(_))).catch(a);else try{o(d(g));}catch(_){a(_);}});}),r=(s,o)=>{let a=o||s.includes(this.service+"-")?s:this.service+"-"+H.hash(s);return {cognitoUser:new amazonCognitoIdentityJs.CognitoUser({Username:a,Pool:this.userPool}),cognitoUsername:a}};return {getSession:t,authenticateUser:(s,o,a=false,l=false)=>new Promise((u,d)=>{this.__request_signup_confirmation=null,this.__disabledAccount=null;let f=r(s,a),g=f.cognitoUsername,h=new amazonCognitoIdentityJs.AuthenticationDetails({Username:g,Password:o});f.cognitoUser.authenticateUser(h,{newPasswordRequired:(m,y)=>{this.__disabledAccount=null,this.__request_signup_confirmation=g,m["custom:signup_ticket"]==="PASS"||m["custom:signup_ticket"]==="MEMBER"||m["custom:signup_ticket"]==="OIDPASS"?f.cognitoUser.completeNewPasswordChallenge(o,{},{onSuccess:b=>{j=f.cognitoUser,t().then(async _=>{if(D.call(this))try{await ot.bind(this)(o);}catch(w){this.log("encryption:ensureKeyring:failed",w);}u(this.user);});},onFailure:b=>{d(new c(b.message||"Failed to authenticate user.",{code:b.code}));}}):d(new c("User's signup confirmation is required.",{code:"SIGNUP_CONFIRMATION_NEEDED"}));},onSuccess:m=>t({skipUserUpdateEventTrigger:true}).then(async y=>{if(this.__disabledAccount=null,D.call(this))try{await ot.bind(this)(o);}catch(b){this.log("encryption:ensureKeyring:failed",b);}this._runOnLoginListeners(this.user),this._runOnUserUpdateListeners(this.user),u(this.user);}),onFailure:m=>{let y=[],{parsed:b,code:_}=lt(m),w=typeof m?.message=="string"?m.message:"";if(_==="NotAuthorizedException"?w.includes("User is disabled.")?(this.__disabledAccount=g,y=["This account is disabled.","USER_IS_DISABLED"]):l?y=["The account already exists.","ACCOUNT_EXISTS"]:y=["Incorrect username or password.","INCORRECT_USERNAME_OR_PASSWORD"]:_==="UserNotFoundException"?y=["Incorrect username or password.","INCORRECT_USERNAME_OR_PASSWORD"]:_==="UserNotConfirmedException"?(this.__request_signup_confirmation=g,y=["User's signup confirmation is required.","SIGNUP_CONFIRMATION_NEEDED"]):(_==="TooManyRequestsException"||_==="LimitExceededException")&&(y=["Too many attempts. Please try again later.","REQUEST_EXCEED"]),b.code==="SIGNUP_CONFIRMATION_NEEDED"&&(this.__request_signup_confirmation=g),y.length){let T=y[1],k=y[0];d(new c(k,{code:T,cause:m}));}else d(b);}});}),createCognitoUser:r,signup:(s,o,a)=>new Promise((l,u)=>{this.userPool.signUp(s,o,a,null,(d,f)=>{if(d){let{parsed:g,code:h}=lt(d),m=[];h==="UsernameExistsException"?m=["The account already exists.","EXISTS"]:h==="InvalidPasswordException"?m=["Invalid password. Password must be at least 6 characters.","INVALID_PARAMETER"]:h==="InvalidParameterException"?m=[g.message||"Invalid parameter.","INVALID_PARAMETER"]:h==="TooManyRequestsException"||h==="LimitExceededException"?m=["Too many attempts. Please try again later.","REQUEST_EXCEED"]:h==="CodeDeliveryFailureException"?m=["Failed to deliver verification code.","CODE_DELIVERY_FAILURE"]:h==="UserLambdaValidationException"&&(m=[g.message||"Signup validation failed.","INVALID_REQUEST"]),m.length?u(new c(m[0],{code:m[1],cause:d})):u(g);return}l(f);});})}}function lt(e){let t=typeof e?.code=="string"&&e.code.trim()?e.code.trim():"ERROR",n=((typeof e?.message=="string"?e.message:typeof e=="string"?e:"An error occurred.")||"An error occurred.").trim();n||(n="An error occurred.");let i=n.match(/#([A-Za-z0-9_]+)\s*:\s*([\s\S]+)/),s=i?.[1]?.trim()||t,o=i?.[2]?.trim()||n;return {parsed:new c(o,{code:s,cause:e}),code:t}}async function Rn(e){await this.__authConnection;let t=e?.refreshToken||false;if(!t)return this.user;try{return await Q.bind(this)().getSession(Object.assign({skipUserUpdateEventTrigger:!t,refreshToken:t},e)),this.user}catch{return null}}async function In(e){await this.__connection,e=p.Params(e,{token:"string",id:"string",merge:o=>{if(o===void 0)return false;if(typeof o=="string")return [o];if(Array.isArray(o)){for(let a of o)if(typeof a!="string")throw new c('"merge" array items should be type: <string>.',{code:"INVALID_PARAMETER"})}if(typeof o!="boolean"&&!Array.isArray(o))throw new c('"merge" should be type: <boolean | string[]>.',{code:"INVALID_PARAMETER"});return o},template:o=>{if(typeof o!="object"||o===null)throw new c('"template" should be type: <object>.',{code:"INVALID_PARAMETER"});if(o.welcome!==void 0&&(typeof o.welcome!="string"||!o.welcome))throw new c('"template.welcome" should be a non-empty <string> (template message_id).',{code:"INVALID_PARAMETER"});return o}});let t={token:e.token,id:e.id,merge:e.merge};e.template?.welcome&&(t.template_welcome=e.template.welcome);let r=await P.bind(this)("openid-logger",t),n=r.logger.split("#"),i=this.service+"-"+n[0],s=n[1];return {userProfile:await Q.bind(this)().authenticateUser(i,s,true,true),openid:r.openid}}function lo(e){let t=typeof globalThis<"u"?globalThis:void 0;if(t?.Buffer)return t.Buffer.from(e,"base64").toString("utf8");if(typeof atob=="function"){let r=atob(e),n=new Uint8Array(r.length);for(let i=0;i<r.length;i++)n[i]=r.charCodeAt(i);return typeof TextDecoder<"u"?new TextDecoder().decode(n):r}throw new Error("No base64 decoder available in this environment")}function uo(e){let t=e.split(".");if(t.length!==3)throw new Error("Invalid JWT format");let n=t[1].replace(/-/g,"+").replace(/_/g,"/"),i=lo(n);return JSON.parse(i)}async function Pn(e){await this.__authConnection,this.log("loginWithToken:params",e),e=p.Params(e,{idToken:"string",accessToken:"string",refreshToken:"string"},["idToken"]);let t=uo(e.idToken);if(this.log("loginWithToken:idTokenPayload",t),t["custom:service"]!==this.service)throw new c("Token does not belong to this service.",{code:"INVALID_REQUEST"});let r=Math.floor(Date.now()/1e3);if(t.exp&&t.exp<r)throw new c("Token has expired.",{code:"INVALID_REQUEST"});if(this.__user=xe(t),this.session=null,e.accessToken&&e.refreshToken)try{if(this.session=new amazonCognitoIdentityJs.CognitoUserSession({IdToken:new amazonCognitoIdentityJs.CognitoIdToken({IdToken:e.idToken}),AccessToken:new amazonCognitoIdentityJs.CognitoAccessToken({AccessToken:e.accessToken}),RefreshToken:new amazonCognitoIdentityJs.CognitoRefreshToken({RefreshToken:e.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",t["cognito:username"]);let n={Username:t["cognito:username"],Pool:this.userPool};this.log("loginWithToken:cognitoUserParams",n),j=new amazonCognitoIdentityJs.CognitoUser(n),j.setSignInUserSession(this.session),this.log("loginWithToken:cognitoUserRestored",{cognitoUserType:typeof j,cognitoUserKeys:Object.keys(j||{}),cognitoUser:j});}}catch(n){this.log("loginWithToken:err",n);try{this.log("loginWithToken:err:stringified",JSON.stringify(n));}catch{this.log("loginWithToken:err:stringifyFail",String(n));}try{let i=Object.keys(n||{}),s=Object.getOwnPropertySymbols?Object.getOwnPropertySymbols(n||{}):[],o=Object.getOwnPropertyDescriptors?Object.getOwnPropertyDescriptors(n||{}):{};this.log("loginWithToken:createSessionError:allKeys",{keys:i,symbols:s,descriptors:o});}catch(i){this.log("loginWithToken:createSessionError:allKeysFail",String(i));}}return this._runOnLoginListeners(this.user),this._runOnUserUpdateListeners(this.user),this.user}async function W(){return await this.__connection,this.__user?.service===this.service?this.__user?.owner===this.host:(await Be.bind(this)(),false)}async function pe(e=false){let t=null;j&&(e?t=new Promise((n,i)=>{j.globalSignOut({onSuccess:s=>{this.log("globalSignOut:success",s),n(s);},onFailure:s=>{this.log("globalSignOut:error",s),i(s);}});}):j.signOut()),Ot.bind(this)();let r={session:null,__startKeyHistory:{},__cached_requests:{},__user:null};t&&(t=await t);for(let n in r)this[n]=r[n];return this._runOnUserUpdateListeners(null),this._runOnLoginListeners(null),t}async function Be(e){await this.__connection;let{data:t}=V(e);return await pe.bind(this)(t?.global),"SUCCESS: The user has been logged out."}async function Tn(){if(!this.__request_signup_confirmation)throw new c("Least one login attempt is required.",{code:"INVALID_REQUEST"});return await P.bind(this)("confirm-signup",{username:this.__request_signup_confirmation})}async function Sn(e=false){if(typeof e=="string")e=p.Url(e);else if(typeof e!="boolean")throw new c("Argument should be type: <boolean | string>.",{code:"INVALID_REQUEST"});if(!this.__disabledAccount)throw new c("Least one signin attempt of disabled account is required.",{code:"INVALID_REQUEST"});return await P.bind(this)("recover-account",{username:this.__disabledAccount,redirect:e}),"SUCCESS: Recovery e-mail has been sent."}async function Yt(e){let t=p.Params(e,{username:"string",email:"string",password:"string"},["password"]);if(await this.__authConnection,t.email)try{p.Email(t.email);}catch{t.username=t.email,delete t.email;}if(!t.username&&!t.email)throw new c('Least one of "username" or "email" is required.',{code:"INVALID_PARAMETER"});return await Q.bind(this)().authenticateUser(t.username||t.email,t.password)}async function kn(e,t){await this.__authConnection;let r={username:"string",password:u=>p.Password(u),email:u=>p.Email(u),name:"string",address:u=>{if(!u)return "";if(typeof u=="string")return u;if(typeof u=="object")return JSON.stringify(u)},gender:"string",birthdate:u=>u?p.Birthdate(u):"",phone_number:u=>u?p.PhoneNumber(u):"",email_public:["boolean",()=>false],address_public:["boolean",()=>false],gender_public:["boolean",()=>false],birthdate_public:["boolean",()=>false],phone_number_public:["boolean",()=>false],access_group:"number",misc:"string",picture:u=>u?p.Url(u):"",profile:u=>u?p.Url(u):"",family_name:"string",given_name:"string",middle_name:"string",nickname:"string",website:u=>u?p.Url(u):""},n=p.Params(e||{},r,["email","password"]);await Be.bind(this)(),t=p.Params(t||{},{email_subscription:u=>{if(typeof u!="boolean")throw new c('"option.email_subscription" should be type: <boolean>.',{code:"INVALID_PARAMETER"});if(!t?.signup_confirmation)throw new c('"option.signup_confirmation" is required for email subscription.',{code:"INVALID_PARAMETER"});return u},signup_confirmation:u=>{let d=u;if(typeof u=="string")d=p.Url(u);else if(typeof u=="boolean")d=u;else throw new c('"option.signup_confirmation" should be type: <string | boolean>.',{code:"INVALID_PARAMETER"});if(d&&!n.email)throw new c('"email" is required for signup confirmation.',{code:"INVALID_PARAMETER"});return d},login:u=>{if(typeof u=="boolean"){if(t.signup_confirmation&&u)throw new c('"login" is not allowed when "option.signup_confirmation" is true.',{code:"INVALID_PARAMETER"});return u}throw new c('"option.login" should be type: boolean.',{code:"INVALID_PARAMETER"})},template:u=>{if(typeof u!="object"||u===null)throw new c('"option.template" should be type: <object>.',{code:"INVALID_PARAMETER"});if(u.signup_confirmation!==void 0){if(typeof u.signup_confirmation!="string"||!u.signup_confirmation)throw new c('"option.template.signup_confirmation" should be a non-empty <string> (template message_id).',{code:"INVALID_PARAMETER"});if(!t?.signup_confirmation)throw new c('"option.signup_confirmation" is required when "option.template.signup_confirmation" is set.',{code:"INVALID_PARAMETER"})}if(u.welcome!==void 0&&(typeof u.welcome!="string"||!u.welcome))throw new c('"option.template.welcome" should be a non-empty <string> (template message_id).',{code:"INVALID_PARAMETER"});return u}});let i=t?.login||false;if(n.signup_confirmation=t?.signup_confirmation||false,n.email_subscription=t?.email_subscription||false,n.email_public&&!n.signup_confirmation)throw new c('"option.signup_confirmation" should be true if "email_public" is set to true.',{code:"INVALID_PARAMETER"});n.service=this.service,n.owner=this.owner;let s=Q.bind(this)().createCognitoUser(n.username||n.email);for(let u of ["email_public","address_public","gender_public","birthdate_public","phone_number_public"])n[u]=n[u]?"1":"0";n.access_group&&(n.access_group=n.access_group.toString());let o=(await P.bind(this)("signupkey",{username:s.cognitoUsername,signup_confirmation:typeof n.signup_confirmation=="boolean"?JSON.stringify(n.signup_confirmation):n.signup_confirmation,email_subscription:n.email_subscription,template_confirmation:t?.template?.signup_confirmation||"",template_welcome:t?.template?.welcome||""})).split(":"),a=o.slice(1).join(":"),l=[new amazonCognitoIdentityJs.CognitoUserAttribute({Name:"custom:signup",Value:o[0]}),new amazonCognitoIdentityJs.CognitoUserAttribute({Name:"locale",Value:a.split("#")[1]}),new amazonCognitoIdentityJs.CognitoUserAttribute({Name:"custom:signup_ticket",Value:a})];for(let u in r){let d=["email_public","address_public","gender_public","birthdate_public","phone_number_public","misc","service","owner"];n[u]!==""&&(u==="username"||u==="password"||u==="access_group"||(d.includes(u)?l.push(new amazonCognitoIdentityJs.CognitoUserAttribute({Name:"custom:"+u,Value:n[u]})):l.push(new amazonCognitoIdentityJs.CognitoUserAttribute({Name:u,Value:n[u]}))));}return await Q.bind(this)().signup(s.cognitoUsername,n.password,l),n.signup_confirmation?(j=s.cognitoUser,this.__request_signup_confirmation=s.cognitoUsername,"SUCCESS: The account has been created. User's signup confirmation is required."):i?Yt.bind(this)({email:n.username||n.email,password:n.password}):"SUCCESS: The account has been created."}async function vn(){await this.__connection;let e=await P.bind(this)("remove-account",{disable:this.__user.user_id},{auth:true});return await Be.bind(this)(),e}async function Un(e){await this.__connection;let t=p.Params(e,{email:i=>p.Email(i),code:["number","string"],new_password:i=>p.Password(i)},["email","code","new_password"]),r=t.code,n=t.new_password;return typeof r=="number"&&(r=r.toString()),new Promise(async(i,s)=>{Q.bind(this)().createCognitoUser(t.email).cognitoUser.confirmPassword(r,n,{onSuccess:a=>{i("SUCCESS: New password has been set.");},onFailure:a=>{s(new c(a?.message||"Failed to reset password.",{code:a?.code||"ERROR",cause:a}));}});})}async function Nn(e,t,r){await this.__connection;let n;if(!j)throw new c("The user has to be logged in.",{code:"INVALID_REQUEST"});if(e==="email"||e==="phone_number"){if(!this.__user.hasOwnProperty(e))throw new c(`No ${e==="email"?"e-mail":"phone number"} to verify`,{code:"INVALID_REQUEST"});if(this.__user?.[`${e}_verified`])return `SUCCESS: "${e}" is verified.`;n=(t?p.Params(t,{code:"string"}):{}).code||"";}else return;let i,s=r?.template?.verification;if(s!==void 0){if(typeof s!="string"||!s)throw new c('"template.verification" should be a non-empty <string> (template message_id).',{code:"INVALID_PARAMETER"});i={template_verification:s};}return new Promise((o,a)=>{let l={onSuccess:u=>{n?Q.bind(this)().getSession({refreshToken:true}).then(()=>{this.__user&&(this.__user[e+"_verified"]=true),o(`SUCCESS: "${e}" is verified.`);}).catch(d=>{a(d);}):o("SUCCESS: Verification code has been sent.");},onFailure:u=>{a(new c(u.message||"Failed to request verification code.",{code:u?.code}));}};n?j?.verifyAttribute(e,n,l):(l.inputVerificationCode=null,j?.getAttributeVerificationCode(e,l,i));})}function xn(e,t){return Nn.bind(this)("phone_number",e,t)}function Dn(e,t){return Nn.bind(this)("email",e,t)}async function Cn(e,t){await this.__connection;let r=p.Params(e,{email:s=>p.Email(s)},["email"]),n,i=t?.template?.verification;if(i!==void 0){if(typeof i!="string"||!i)throw new c('"template.verification" should be a non-empty <string> (template message_id).',{code:"INVALID_PARAMETER"});n={template_verification:i};}return new Promise(async(s,o)=>{Q.bind(this)().createCognitoUser(r.email).cognitoUser.forgotPassword({onSuccess:l=>{s("SUCCESS: Verification code has been sent.");},onFailure:l=>{let{parsed:u,code:d}=lt(l),f={UserNotFoundException:"NOT_EXISTS",InvalidParameterException:"INVALID_PARAMETER",NotAuthorizedException:"INVALID_REQUEST",LimitExceededException:"REQUEST_EXCEED",TooManyRequestsException:"REQUEST_EXCEED",CodeDeliveryFailureException:"CODE_DELIVERY_FAILURE"}[d]||u.code||d||"ERROR";o(new c(u.message,{code:f,cause:l}));}},n);})}async function On(e){if(await this.__connection,!this.session)throw new c("User login is required.",{code:"INVALID_REQUEST"});let t=p.Params(e,{current_password:"string",new_password:"string"});if(!t?.current_password)throw new c('"current_password" is required to change password.',{code:"INVALID_PARAMETER"});if(!t?.new_password)throw new c('"new_password" is required to change password.',{code:"INVALID_PARAMETER"});return p.Password(t.current_password),p.Password(t.new_password),D.call(this)&&await en.bind(this)(t.current_password,t.new_password),new Promise((r,n)=>{j.changePassword(t.current_password,t.new_password,(i,s)=>{if(i){if(i?.code==="InvalidParameterException")n(new c("Invalid password parameter.",{code:"INVALID_PARAMETER"}));else if(i?.code==="NotAuthorizedException")n(new c("Incorrect password.",{code:"INVALID_REQUEST"}));else if(i?.code==="TooManyRequestsException"||i?.code==="LimitExceededException")n(new c("Too many attempts. Please try again later.",{code:"REQUEST_EXCEED"}));else {let{parsed:o}=lt(i);n(o);}return}D.call(this)&&tn.bind(this)().catch(o=>this.log("encryption:prune:failed",o)),r("SUCCESS: Password has been changed.");});})}async function Ln(e){if(await this.__connection,!this.session)throw new c("User login is required.",{code:"INVALID_REQUEST"});let t=p.Params(e||{},{user_id:i=>p.UserId(i),email:i=>p.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?p.Birthdate(i):"",phone_number:i=>i?p.PhoneNumber(i):"",email_public:"boolean",phone_number_public:"boolean",address_public:"boolean",gender_public:"boolean",birthdate_public:"boolean",misc:"string",picture:i=>i?p.Url(i):"",profile:i=>i?p.Url(i):"",family_name:"string",given_name:"string",middle_name:"string",nickname:"string",website:i=>i?p.Url(i):""});if(t&&typeof t=="object"&&!Object.keys(t).length)return this.user;t.email&&(t.preferred_username=this.service+"-"+H.hash(t.email));let r=[["email_public","email_verified","User's e-mail should be verified to set"],["phone_number_public","phone_number_verified","User's phone number should be verified to set"]];if(this.__user){for(let i of r)if(t[i[0]]&&!this.__user[i[1]])throw new c(`${i[2]} "${i[0]}" to true.`,{code:"INVALID_REQUEST"})}let n=[];for(let i in t){if(t[i]===this.user[i]){n.push(i);continue}if(["email_public","phone_number_public","address_public","gender_public","birthdate_public","misc"].includes(i)){let o=t[i];typeof o=="boolean"&&(o=o?"1":"0"),t["custom:"+i]=o,n.push(i);}}for(let i of n)delete t[i];if(t.user_id)if(t.user_id===this.user.user_id)delete t.user_id;else return P.bind(this)("admin-edit-profile",{attributes:t},{auth:true});if(t&&typeof t=="object"&&Object.keys(t).length){let i=[];for(let s in t)i.push(new amazonCognitoIdentityJs.CognitoUserAttribute({Name:s,Value:t[s]}));return await new Promise((s,o)=>{j?.updateAttributes(i,(a,l)=>{a&&o([a?.code||a?.name,a?.message||"Failed to update user settings."]),s(l);});}),await Q.bind(this)().getSession({refreshToken:true}),this.user}return this.user}async function Mn(e,t){e=V(e).data,e||(e={searchFor:"timestamp",condition:">",value:0},t||(t={}),t.ascending=false),await this.__connection;let r={user_id:i=>Array.isArray(i)?i.map(s=>p.UserId(s)):p.UserId(i),email:"string",phone_number:"string",locale:i=>{if(typeof i!="string"||typeof i=="string"&&i.length>5)throw new c('Value of "locale" should be a country code.',{code:"INVALID_PARAMETER"});return i},name:"string",address:"string",gender:"string",birthdate:i=>p.Birthdate(i),subscribers:"number",timestamp:"number",access_group:"number",approved:"string"},n=["searchFor","value"];if(e=p.Params(e,{searchFor:["user_id","name","email","phone_number","address","gender","birthdate","locale","subscribers","timestamp","access_group","approved"],condition:[">",">=","=","<","<=","gt","gte","eq","lt","lte",()=>"="],value:i=>{let s=r[e.searchFor];if(typeof s=="function")return s(i);if(typeof i!==s)throw new c(`Value does not match the type of "${e.searchFor}" index.`,{code:"INVALID_PARAMETER"});return i},range:i=>{let s=r[e.searchFor];if(typeof s=="function")return s(i);if(typeof i!==s)throw new c(`Range does not match the type of "${e.searchFor}" index.`,{code:"INVALID_PARAMETER"});return i}},n),e?.condition&&e?.condition!=="="&&e.hasOwnProperty("range"))throw new c("Conditions does not apply on range search.",{code:"INVALID_PARAMETER"});if(e.searchFor==="user_id"&&(e.condition!=="="||e.range))throw new c(`Conditions are not allowed on "${e.searchFor}"`,{code:"INVALID_PARAMETER"});if(typeof e?.value=="string"&&!e?.value)throw new c("Value should not be an empty string.",{code:"INVALID_PARAMETER"});if(typeof e?.searchFor=="string"&&!e?.searchFor)throw new c('"searchFor" should not be an empty string.',{code:"INVALID_PARAMETER"});return P.bind(this)("get-users",e,{auth:true,fetchOptions:t})}async function Fn(e){await this.__connection;let t=await P.bind(this)("last-verified-email",e,{auth:true});return t.includes("SUCCESS")?(await Q.bind(this)().getSession({refreshToken:true}),this.user):t}async function Vn(e){return await this.__connection,e=p.Params(e,{username:p.Email,redirect:p.Url},["username"]),await P.bind(this)("request-username-change",e,{auth:true})}var ke=null,qn=typeof SubmitEvent<"u",go=typeof HTMLFormElement<"u",He=G(),Xt=0;function jn(e){if(!e)return null;let t=Number(e);if(Number.isFinite(t))return Math.max(0,t*1e3);let r=Date.parse(e);return Number.isNaN(r)?null:Math.max(0,r-Date.now())}function Zt(e,t){return t>0?e/t*100:0}var $n=e=>{let{auth:t,type:r,endpoints:n,stable:i}=e,s=n[0],o=n[1];if(Xt++,r==="admin"){let a=Object.entries(s).filter(([l,u])=>l.includes(t?"_private":"_public")&&l!=="get_users_private"&&l!=="service_public"&&typeof u=="string").map(([,l])=>l);if(!a.length)throw new c("No available admin gateways.",{code:"INVALID_REQUEST"});return a[Xt%a.length]}if(r==="record"){let a=Object.entries(o).filter(([l,u])=>l.includes(t?"record_private":"record_public")&&typeof u=="string").map(([,l])=>l);if(!a.length)throw new c("No available record gateways.",{code:"INVALID_REQUEST"});return i?a[0]:a[Xt%a.length]}throw new c("Invalid gateway type.",{code:"INVALID_REQUEST"})};async function po(e,t,r){let n=await Promise.all([this.admin_endpoint,this.record_endpoint]),i=n[0],s=n[1],o=e.split("?"),a=o.length>1?"?"+o[1]:"";switch(e=o[0],e){case "get-users":return i.get_users_private+e+a;case "service":return i.service_public+e+a;case "get-newsletters":case "get-public-newsletters":case "subscribe-newsletter":case "subscribe-public-newsletter":case "signupkey":case "admin-newsletter-request":case "admin-signup":case "confirm-signup":case "openid-logger":case "block-account":case "admin-edit-profile":case "remove-account":case "post-secure":case "recover-account":case "mock":case "grant-access":case "last-verified-email":case "ticket":case "register-ticket":case "get-newsletter-subscription":case "request-username-change":case "send-inquiry":case "register-newsletter-group":case "newsletter-group-endpoint":case "invitation-list":case "csr":case "csr-poll":case "csr-cancel":return $n.bind(this)({auth:t,type:"admin",endpoints:n})+e+a;case "post-record":return (t?s.post_private:s.post_public)+e+a;case "get-records":return (t?s.get_private:s.get_public)+e+a;case "del-files":case "del-records":return s.del_private+e+a;case "store-subscription":case "get-vapid-public-key":case "push-notification":case "delete-subscription":case "subscription":case "get-subscription":case "get-table":case "get-tag":case "get-uniqueid":case "get-index":case "get-signed-url":case "extract-file-text":case "grant-private-access":case "request-private-access-key":case "get-ws-group":case "check-schema":case "get-feed":case "castspell":case "dopamine":case "getspell":return $n.bind(this)({auth:t,type:"record",endpoints:n,stable:r})+e+a;default:return p.Url(e)+a}}var Ke={};function Bn(){ke&&(ke.terminate(),ke=null);}async function P(e,t=null,r,n){this.log("request",{url:e,data:t,options:r,_etc:n||{}}),r=r||{};let{auth:i=false,method:s="post",bypassAwaitConnection:o=false}=r;s=s.toUpperCase();let a=null,l=t?.service||this.service,u=t?.owner||this.owner,d=null,f=await po.bind(this)(e,!!i,!!r.stableGateway);if(!o&&(a=await this.__connection,!a))throw new c("Invalid connection. The service could have been disabled, or has a restricted CORS.",{code:"INVALID_REQUEST"});let g=r?.tokenHeaders?.idToken===true;(i||g)&&(d=await Se.bind(this)());let h={},{fetchMore:m=false,progress:y}=r?.fetchOptions||{};if(r?.fetchOptions&&Object.keys(r.fetchOptions).length){for(let v of ["limit","startKey","ascending"])if(r.fetchOptions.hasOwnProperty(v)){if(v==="startKey"&&r.fetchOptions[v]===null)continue;h[v]=r.fetchOptions[v];}h=p.Params(h,{limit:v=>{if(typeof v!="number")throw new c("Fetch limit should be a number.",{code:"INVALID_REQUEST"});if(v>1e3)throw new c("Fetch limit should be below 1000.",{code:"INVALID_REQUEST"});return v},startKey:v=>v,ascending:"boolean"});}let b=n?.ignoreService?{}:{service:l,owner:u};Object.assign(b,h),t=V(t).data,t?t&&typeof t=="object"&&(t=Object.assign(b,t)):t=b;let _=`${s}:${i?"auth":"public"}:${e}`,w=(()=>{if(t&&typeof t=="object"&&Object.keys(t).length&&!(He&&t instanceof FormData)){let v=function(U){return typeof U=="object"&&U!==null?Object.keys(U).sort().reduce((M,q)=>(typeof U[q]=="object"&&U[q]!==null?M[q]=v(U[q]):M[q]=U[q],M),{}):U};return H.hash(_+"/"+JSON.stringify(v(t)))}return H.hash(_+"/"+l)})(),{requestKey:T,requestKeyWithStartKey:k}=ho.bind(this)({params:t,url:e,fetchMore:m,hashedParams:w});if(!T||T&&typeof T=="object")return T;if(this.log("requestKey",k),typeof k=="string"&&Ke[k]instanceof Promise)return this.log("request:returning pending",k),Ke[k];let S={Accept:"*/*"};if(Object.prototype.hasOwnProperty.call(r,"contentType")&&r.contentType!==void 0){let v=r.contentType===null?"application/x-www-form-urlencoded":r.contentType;v&&(S["Content-Type"]=v);}else S["Content-Type"]="application/json";if(d&&(S.Authorization=d),r?.tokenHeaders){let v=(q,Je)=>typeof q=="string"?q:q===true?Je:null,U=v(r.tokenHeaders.accessToken,this.session?.accessToken?.jwtToken||null),M=v(r.tokenHeaders.idToken,this.bearerToken||this.session?.idToken?.jwtToken||d||null);U&&(S["X-Access-Token"]=U),M&&(S["X-Id-Token"]=M);}let x={public_identifier:this.__public_identifier,service:l,owner:u};S["Content-Meta"]=JSON.stringify(x),r.revalidate&&(S["Cache-Control"]="no-cache",S.Pragma="no-cache");let $={headers:S};if(r?.responseType&&($.responseType=r.responseType),s==="GET"){if(t){let v=[];if(He&&t instanceof FormData?v=Array.from(t.entries()).map(([U,M])=>{let q=typeof M=="string"?M:M.name;return encodeURIComponent(U)+"="+encodeURIComponent(q)}):v=Object.keys(t).map(U=>{let M=t[U];return typeof M!="string"&&(M=JSON.stringify(M)),encodeURIComponent(U)+"="+encodeURIComponent(M)}),v.length){let U=f.includes("?")?f.endsWith("?")||f.endsWith("&")?"":"&":"?";f+=U+v.join("&");}}$.body=null;}else if(He&&t instanceof FormData)$.body=t;else if(S["Content-Type"]==="application/x-www-form-urlencoded"&&t&&typeof t=="object"){let v=new URLSearchParams;for(let U of Object.keys(t)){let M=t[U];v.append(U,typeof M=="string"?M:JSON.stringify(M));}$.body=v.toString();}else typeof t=="string"?$.body=t:$.body=t?JSON.stringify(t):null;if($.method=s,ke===null){let v={batchSize:this.requestBatchSize,breakWhenError:false,onProgress:U=>{this.onBatchProcess.forEach(M=>M(U));}};ke=new Ti__default.default(v);}return this.log("request-opt",$),new Promise((v,U)=>{ke.add([async()=>{let M=Kn.bind(this)(f,$,y);Ke[k]=M;try{let q=yo.bind(this)({hashedParam:T,requestKeyWithStartKey:k,url:e,fetched:await M});return delete Ke[k],this.log("request:end",q),v(q),q}catch(q){throw delete Ke[k],this.log("request:err",q),U(q),q}}]);})}function ho(e){let{params:t={},url:r,fetchMore:n=false,hashedParams:i}=e||{};if(t.startKey){if(!(typeof t.startKey=="object"&&Object.keys(t.startKey).length)&&t.startKey!=="start"&&t.startKey!=="end")throw new c(`"${t.startKey}" is invalid startKey key.`,{code:"INVALID_PARAMETER"});t.startKey==="start"&&(n=false,delete t.startKey);}if(!n){if(this.__cached_requests?.[r]?.[i]&&delete this.__cached_requests[r][i],this.__startKeyHistory?.[r]?.[i]){if(Array.isArray(this.__startKeyHistory[r][i])&&this.__startKeyHistory[r][i].length)for(let l of this.__startKeyHistory[r][i]){let u=i+H.hash(l);this.__cached_requests?.[r]&&this.__cached_requests?.[r]?.[u]&&delete this.__cached_requests[r][u];}delete this.__startKeyHistory[r][i];}return {requestKeyWithStartKey:i,requestKey:i}}if(!Array.isArray(this.__startKeyHistory?.[r]?.[i]))return {requestKeyWithStartKey:i,requestKey:i};let s=this.__startKeyHistory[r][i],o=s[s.length-1],a=i;if(o){if(o==="end")return {requestKey:{list:[],startKey:"end",endOfList:true,startKeyHistory:s},requestKeyWithStartKey:a};a+=H.hash(o),t.startKey=JSON.parse(o);}return this.__cached_requests?.[r]?.[a]?{requestKey:this.__cached_requests[r][a],requestKeyWithStartKey:a}:{requestKeyWithStartKey:a,requestKey:i}}function mo(e){let t=r=>r&&typeof r=="object"&&r.encrypted?Object.assign({},r,{data:null}):r;return Array.isArray(e)?e.map(t):e&&typeof e=="object"?Array.isArray(e.list)?Object.assign({},e,{list:e.list.map(t)}):t(e):e}function Kn(e,t,r){return new Promise((n,i)=>{let s=new XMLHttpRequest;s.open(t.method||"GET",e);for(var o in t.headers||{})s.setRequestHeader(o,t.headers[o]);t.responseType&&(s.responseType=t.responseType),s.onload=()=>{if(s.status<400)if(t.responseType=="json"||t.responseType=="blob")n(s.response);else {let a=s.responseText;try{a=JSON.parse(a);}catch{}n(a);}else if(s.status===429){let a=s.getResponseHeader("Retry-After"),l=jn(a);l!==null?setTimeout(()=>{Kn(e,t,r).then(n,i);},l):i("Too many requests");}else {let a=s.status,l=["INVALID_CORS","INVALID_REQUEST","SERVICE_DISABLED","INVALID_PARAMETER","ERROR","EXISTS","NOT_EXISTS"],u=t.responseType=="blob"?s.response:s.responseText;try{u=JSON.parse(u);}catch{}if(typeof u=="string"){let d=u.split(":"),f=d.splice(0,1)[0].trim(),g=d.join(":").trim();i(new c(g||u,{code:l.includes(f)?f:"ERROR"}));}else if(typeof u=="object"&&u?.message){let d=u?.code||(a?a.toString():null)||"ERROR",f=u.message,g=u?.cause;typeof f=="string"&&(f=f.trim()),i(new c(f,{cause:g,code:d}));}else i(u);}},s.onerror=()=>i("Network error"),s.onabort=()=>i("Aborted"),s.ontimeout=()=>i("Timeout"),typeof r=="function"&&(s.onprogress=a=>{r({status:"download",progress:Zt(a.loaded,a.total),loaded:a.loaded,total:a.total,abort:()=>s.abort()});},s.upload&&(s.upload.onprogress=a=>{r({status:"upload",progress:Zt(a.loaded,a.total),loaded:a.loaded,total:a.total,abort:()=>s.abort()});})),s.send(t.body);})}function yo(e){let{hashedParam:t,requestKeyWithStartKey:r,url:n,fetched:i}=e;if(!i?.startKey)return i;this.__startKeyHistory.hasOwnProperty(n)||(this.__startKeyHistory[n]={}),this.__startKeyHistory[n].hasOwnProperty(t)||(this.__startKeyHistory[n][t]=[]);let s=i.startKey==="end"?"end":JSON.stringify(i.startKey);return this.__startKeyHistory[n][t].includes(s)||this.__startKeyHistory[n][t].push(s),this.__cached_requests?.[n]||(this.__cached_requests[n]={}),this.__cached_requests[n][r]=i,Object.assign({startKeyHistory:this.__startKeyHistory[n][t]},i)}async function dt(e,t){await this.__connection;let{record_id:r,service:n=this.service,progress:i}=t;if(!r)throw new c('"record_id" is required.',{code:"INVALID_PARAMETER"});if(qn&&e instanceof SubmitEvent&&(e=e.target),go&&e instanceof HTMLFormElement&&(e=new FormData(e)),!He||!(e instanceof FormData))throw new c('"fileList" should be a FormData or HTMLFormElement.',{code:"INVALID_PARAMETER"});let o={reserved_key:be(),service:n,request:"post"};t?.record_id&&(o.id=t.record_id);let a,l=(h,m,y)=>new Promise((b,_)=>{a=new XMLHttpRequest,a.open("POST",h),a.onload=()=>{let w=a.responseText;try{w=JSON.parse(w);}catch{}if(a.status>=200&&a.status<300)b(w);else if(a.status===429){let T=a.getResponseHeader("Retry-After"),k=jn(T);k!==null?setTimeout(()=>{l(h,m,y).then(b,_);},k):_("Too many requests");}else _(w);},a.onerror=()=>_("Network error"),a.onabort=()=>_("Aborted"),a.ontimeout=()=>_("Timeout"),a.upload&&typeof y=="function"&&(a.upload.onprogress=y),a.send(m);});function u(h){let m="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";if(h===0)return m[0];let y="";for(;h>0;)y=m[h%62]+y,h=Math.floor(h/62);return y}let d=[],f=[],g=[];for(let[h,m]of e.entries()){if(!(m instanceof File))continue;let y=await hn.bind(this)(r,h,m),b=y.file,_=y.key,w=Object.assign({key:_+"/"+b.name,sizeKey:u(b.size),contentType:b.type||null},o),{fields:T=null,url:k,cdn:S}=await P.bind(this)("get-signed-url",w,{auth:!!this.__user});g.push(S);let C=new FormData;for(let x in T)C.append(x,T[x]);C.append("file",b);try{await l(k,C,typeof i=="function"?x=>i({status:"upload",progress:Zt(x.loaded,x.total),currentFile:m,completed:d,failed:f,loaded:x.loaded,total:x.total,abort:()=>a.abort()}):null),d.push(m);}catch{f.push(m);}}return {completed:d,failed:f,bin_endpoints:g}}var ut={};function I(e){let{preventMultipleCalls:t=false}=e||{};return function(r,n,i){let s=i.value;i.value=function(...o){let a=o[0],l=true,u=null,d="",f={},g=false;if(qn&&a instanceof SubmitEvent){a.preventDefault();let _=window.location.href;u=a.target;let w=new URL(u.action);d=w.href;let T=d?d.match(/(?<=\{).*?(?=\})/g):"";if(T)for(let k of T){if(!k)continue;let S=u.querySelector(`[name="${k}"]`);if(S)if(S.type==="file")for(let C=0;C<=S.files.length-1;C++)S.files[C]&&(f[k]||(f[k]=[]),f[k].push(new Promise((x,$)=>{let v=new FileReader;v.onload=function(){x(v.result);},v.readAsDataURL(S.files[C]),v.onerror=$;})));else d=d.replace(`{${k}}`,S.value);}u.getAttribute("action")===null?l=false:g=w.href===_;}let h=async _=>{if(d)for(let w in f)f[w].length&&(d=d.replace(`{${w}}`,(await Promise.all(f[w])).join(",")));if(u&&l){let w=D.call(this)?mo(_):_;window.sessionStorage.setItem(`${this.service}:${H.hash(d)}`,JSON.stringify(w)),g?window.location.replace(d):window.location.href=d;}return _},m,y=_=>{throw _ instanceof c?_.name=n+"()":_=_ instanceof Error?_:new c(_,{name:n+"()"}),_},b=async()=>{try{if(m=s.bind(this)(...o),m instanceof Promise){let _=await m;return h(_)}return h(m)}catch(_){throw y(_)}};if(t){let _=`${n}:${this?.__public_identifier||""}:${this?.service||""}:${this?.owner||""}`;return ut?.[_]||(ut[_]=b().finally(()=>{delete ut[_];})),ut[_]}return b()};}}async function Hn(){await this.__connection;let e=`${this.service}:${H.hash(window.location.href.split("?")[0])}`,t=window.sessionStorage.getItem(e);if(window.sessionStorage.removeItem(e),t!==null){try{t=JSON.parse(t);}catch{}return t}return null}var bo=256,_o=256,wo=256,Wn=256,Eo="\u{10FFFF}",Ao=/[\u0000-\u001F\u007F]|\u{10FFFF}/u,Ro={"/":"%2F","!":"%21","*":"%2A","#":"%23"},Io={"%2F":"/","%21":"!","%2A":"*","%23":"#"};function Po(e){return e.replace(/%/g,"%25").replace(/[\/!*#]/g,r=>Ro[r]||r)}function Y(e){return typeof e!="string"?e:e.replace(/%(2F|21|2A|23)/gi,r=>{let n=r.toUpperCase();return Io[n]||r}).replace(/%25/gi,"%")}function oe(e,t,r={}){let{allowEmpty:n=false,maxLength:i,blockKeyDelimiters:s=false,disallowLeadingDollar:o=false,onlyAlphanumeric:a=false}=r;if(typeof e!="string")throw new c(`"${t}" should be type: <string>.`,{code:"INVALID_PARAMETER"});if(a&&/[^a-zA-Z0-9]/.test(e))throw new c(`"${t}" should only contain alphanumeric characters.`,{code:"INVALID_PARAMETER"});if(!n&&e.length===0)throw new c(`"${t}" is required.`,{code:"INVALID_PARAMETER"});if(i&&e.length>i)throw new c(`"${t}" should be <= ${i} characters.`,{code:"INVALID_PARAMETER"});if(Ao.test(e)||e.includes(Eo))throw new c(`"${t}" cannot include control characters or unsupported sentinel characters.`,{code:"INVALID_PARAMETER"});if(s&&(e=Po(e),i&&e.length>i))throw new c(`"${t}" should be <= ${i} characters. "/", "!", "*", "#" and "%" count as 3 characters each.`,{code:"INVALID_PARAMETER"});if(o&&e.startsWith("$"))throw new c(`"${t}" cannot start with "$".`,{code:"INVALID_PARAMETER"});return e}function ve(e,t="table.name",r={}){return oe(e,t,{allowEmpty:r.allowEmpty===true,maxLength:bo,blockKeyDelimiters:true})}function gt(e,t="tag",r={}){return oe(e,t,{allowEmpty:r.allowEmpty===true,maxLength:_o,blockKeyDelimiters:true})}function We(e,t="index.name",r={}){return oe(e,t,{allowEmpty:r.allowEmpty===true,maxLength:wo,blockKeyDelimiters:true,disallowLeadingDollar:true})}function Qn(e,t="index.value"){return oe(e,t,{allowEmpty:true,maxLength:Wn})}function er(e){return typeof e=="string"&&e.slice(-1)==="."}function tr(e,t){return oe(e,t,{allowEmpty:true,maxLength:Wn,blockKeyDelimiters:true})}function Gn(e){if(!e.record_id&&!e.unique_id)return null;let t={};return e?.service&&(t.service=e.service),e?.owner&&(t.owner=e.owner),e?.record_id?t.record_id=oe(e.record_id,"record_id",{allowEmpty:false,onlyAlphanumeric:true}):e?.unique_id&&(t.unique_id=e.unique_id),t}function rr(e){if(e===void 0)return 0;if(typeof e=="number"){if(e>99||e<0)throw new c('"table.access_group" value should be within a range of 0 ~ 99.',{code:"INVALID_REQUEST"})}else if(typeof e=="string"){if(e={private:"private",public:0,authorized:1,admin:99}[e],e===void 0)throw new c('"table.access_group" is invalid.',{code:"INVALID_PARAMETER"})}else throw new c('"table.access_group" should be type: <number | string>.',{code:"INVALID_PARAMETER"});if(!this.__user&&e)throw new c("Unsigned users have no access to records with access group.",{code:"INVALID_REQUEST"});return e}var ft=4503599627370496;function pt(e){if(typeof e=="number"){if(e>ft||e<-ft)throw new c(`Number value should be within range -${ft} ~ +${ft}`,{code:"INVALID_PARAMETER"});return e}if(typeof e=="boolean")return e;if(typeof e=="string")return Qn(e,"index.value");throw new c('"index.value" should be type: <number | boolean | string>.',{code:"INVALID_PARAMETER"})}function zn(e,t){if(!t.index||!("value"in t.index))throw new c('"index.value" is required.',{code:"INVALID_PARAMETER"});if(t.index.name==="$record_id")throw new c(`Cannot do "index.range" on ${t.index.name}`,{code:"INVALID_PARAMETER"});if(typeof t.index.value!=typeof e)throw new c('"index.range" type should match the type of "index.value".',{code:"INVALID_PARAMETER"});return typeof e=="string"?er(t.index.name)?tr(e,"index.range"):Qn(e,"index.range"):e}var ht={},To=10080*60,So=3600,Jn=2;function ko(e,t){if(!t)return String(Jn);let r=Math.max(60,e-300)*1e3;return Jn+"."+Math.floor(Date.now()/r)}function vo(e){if(!this.user?.user_id)return false;let t=e[6]==="**"?"**":parseInt(e[6]),r=this.user?.access_group??-1;return !(this.user.user_id!==e[3]&&(t==="**"||r<t))}function Yn(e){if(typeof e=="string"){if(e.startsWith("!J%"))try{return JSON.parse(e.substring(3))}catch{return e}return e==="!D%{}"?{}:e==="!L%[]"?[]:e}if(e&&typeof e=="object"&&!Array.isArray(e)&&typeof e.__json__=="string"&&Object.keys(e).length===1)try{return JSON.parse(e.__json__)}catch{}return e}async function Xn(e){return typeof e=="string"?e:e&&typeof e.text=="function"?await e.text():await new Promise((t,r)=>{try{let n=new FileReader;n.onload=()=>t(n.result),n.onerror=()=>r(n.error||new Error("Failed to read blob")),n.readAsText(e);}catch(n){r(n);}})}async function Ue(e,t,r=false,n=false){let i={user_id:"",record_id:"",updated:0,uploaded:0,readonly:false,table:{name:"",access_group:0,subscription:{is_subscription_record:false,upload_to_feed:false,notify_subscribers:false,feed_referencing_records:false,notify_referencing_records:false}},referenced_count:0,source:{referencing_limit:null,prevent_multiple_referencing:false,can_remove_referencing_records:false,only_granted_can_reference:false},ip:"",bin:{}},s=false,o=[];function a(d){let f=d=="**"?"private":parseInt(d);return f=f==0?"public":f==1?"authorized":f==99?"admin":f,f}let l={ip:d=>{let f=d.split("#"),g=f[0];f.length>1&&(i.unique_id=f.slice(1).join("#")),g.slice(-1)==="R"?(i.readonly=true,g=g.slice(0,-1)):i.readonly=false,/^\d{1,3}-\d{1,3}-\d{1,3}-\d{1,3}$/.test(g)&&(g=g.split("-").join("."),s=true),i.ip=g;},rec:d=>{if(!d)return;i.record_id=d;let f=d.substring(0,d.length-9),g=X(f);i.uploaded=g;},usr:d=>{i.user_id=d;},tbl:d=>{if(d&&!i.table.name){let f=d.split("/");i.table.name=Y(f[0]),i.table.access_group=a(f[2]),f?.[3]&&(i.table.subscription.is_subscription_record=true);}},usr_tbl:d=>{let f=d.split("/");i.user_id||(i.user_id=f[0]),i.table.name||(i.table.name=Y(f[1]),i.table.access_group=a(f[3]),f?.[4]&&(i.table.subscription.is_subscription_record=true));},idx:d=>{if(!d)return;let f=d.split("!"),g=Y(f.splice(0,1)[0]),h=Uo("!"+f.join("!"));i.index={name:g,value:h};},ref:d=>{d&&(i.reference=d.split("/")[0]);},tags:d=>{i.tags=Array.isArray(d)?d.map(f=>Y(f)):d;},upd:d=>{i.updated=d;},acpt_mrf:d=>{i.source.prevent_multiple_referencing=!d;},ref_limt:d=>{i.source.referencing_limit=d;},rfd:d=>{i.referenced_count=d;},bin:async d=>{let f={},g=i?.reference||null;if(Array.isArray(d)){let h=await Promise.all(d.map(async m=>{try{let y=m.split("/").slice(3).join("/"),b=y.split("/");if(b.length<12)return null;let _=b[b.length-1],w=b[10];if(w==="__data__"&&_==="__json__.json")return {isDataFile:!0,rawUrl:m};let T=at(w),k=b[9],S=b[8],C=a(b[6]),x=m,$=C!=="public"&&vo.call(this,b)?{expires:So,browserCache:To}:null;if(C!=="public")try{x=await Ee.bind(this)(m,{dataType:"endpoint",_ref:g});}catch(U){console.error("Error getting signed url for private file:",U),x=m;}let v={access_group:C,filename:_,url:x,path:y,size:T?T.plainSize:X(k),uploaded:X(S),getFile:(U,M)=>{let q={dataType:U||"download",progress:M,_ref:g},Je=()=>Ee.bind(this)(x,Object.assign({},q,{_update:v}));return $?Ee.bind(this)(m,Object.assign({},q,$)).catch(()=>Je()):Je()}};return T&&(v.encrypted=!0,v.stored_size=X(k)),{pathKey:T?T.key:w,obj:v}}catch{return null}}));for(let m of h)if(m&&!m.isDataFile){if(f[m.pathKey]){f[m.pathKey].push(m.obj);continue}f[m.pathKey]=[m.obj];}}i.bin=f;},prv_acs:d=>{for(let f in d)["notify_subscribers","upload_to_feed","feed_referencing_records","notify_referencing_records"].includes(f)?i.table.subscription[f]=d[f]:f==="referencing_index_restrictions"&&Array.isArray(d[f])?i.source[f]=d[f].map(h=>h&&typeof h=="object"&&typeof h.name=="string"?Object.assign({},h,{name:Y(h.name)}):h):i.source[f]=d[f];},data:async d=>{let f={access_group:i.table.access_group,table_name:i.table.name,user_id:i.user_id,record_id:i.record_id,unique_id:i.unique_id},g=()=>{D.call(this)&&(i.encrypted={status:"failed",reason:"DATA_UNAVAILABLE"});},h=async y=>{if(n||!D.call(this)&&!it(y))return y;let b=await $t.bind(this)(y,f);return b.flag&&(i.encrypted=b.flag),b.value},m=Yn(d);if(m!==d){i.data=await h(m);return}if(d&&typeof d=="object"&&!Array.isArray(d)&&typeof d.__data__=="string"&&Object.keys(d).length===1&&d.__data__.endsWith("/__data__/__json__.json")){let y=d.__data__,b=o.find(_=>_.endsWith(y))||null;if(!b&&!r&&g(),b){if(r){i.data=d;return}try{let _=await Ee.bind(this)(b,{dataType:"blob",_ref:i.reference||null}),w=await Xn(_);i.data=await h(JSON.parse(w));}catch(_){console.error("Failed to fetch offloaded record data:",_),i.data=null,g();}return}}i.data=await h(d);}};if(e.record_id)return e;if(Array.isArray(e.bin))for(let d of e.bin)try{if(typeof d!="string")continue;let f=d.split("/").slice(3);f.length>=12&&f[10]==="__data__"&&f[f.length-1]==="__json__.json"&&o.push(d);}catch{}let u=[];for(let d in l)if(e.hasOwnProperty(d)){let f=l[d](e[d]);f instanceof Promise&&u.push(f);}return s&&(i.user_id="anonymous:"+i.user_id),await Promise.all(u),i}function Uo(e){let t=e.substring(3);switch(e.substring(0,3)){case "!S%":return t;case "!N%":let n=t.split("."),i=Number(n[0])-4503599627370496;return n.length===1?i:parseFloat(i.toString()+"."+n[1]);case "!B%":return t==="1";case "!L%":case "!D%":try{return JSON.parse(t)}catch{throw new c("Value parse error.",{code:"PARSE_ERROR"})}default:return e}}async function Zn(e){let{endpoints:t}=e;if(typeof t=="string"&&(t=[t]),!Array.isArray(t))throw new c('"endpoints" should be type: array | string.',{code:"INVALID_PARAMETER"});let r=await P.bind(this)("del-files",{endpoints:t,storage:"records"},{auth:true,method:"post"}),n=[];for(let i in r)n.push(Ue.bind(this)(r[i]));return Promise.all(n)}async function Ee(e,t){if(typeof e!="string")throw new c('"url" should be type: string.',{code:"INVALID_PARAMETER"});let r=e,n=e.split("?"),i=n.shift()||"",s=n.length?"?"+n.join("?"):"",o=p.Url(i);e=o+s;let a=false,l=o.split("/"),d=l[2].split("."),f=null;d.length===3&&d[1]==="skapi"&&(f=d[0],a=true);let g=l.slice(3),h=false;if(!a&&(g[0]==="auth"||g[0]==="publ"))try{p.UserId(g[2]),p.UserId(g[3]),h=g[0]=="auth",a=!0;}catch{throw new c("Invalid file url.",{code:"INVALID_PARAMETER"})}let m=f?null:g[1];if(t=p.Params(t,{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}),t?.dataType==="info")return {url:e,filename:g[g.length-1],fileKey:g[g.length-2],access_group:g[6]==="**"?"private":g[6]==="01"?"authorized":g[6]==="00"?"public":parseInt(g[6]),uploader:g[3],record_id:g[4]==="records"?g[5]:"N/A",filesize:X(g[9]),uploaded:X(g[8])};let y=e.split("/").slice(-1)[0],b=t.expires;if(b){if(!a)throw new c("Expires option can only be used on skapi cdn endpoints.",{code:"INVALID_PARAMETER"});if(b<0)throw new c('"config.expires" should be > 0. (seconds)',{code:"INVALID_PARAMETER"});let T={request:f?"get-host":"get",id:f||g[5],key:r.split("?")[0],expires:b};m&&(T.service=m);let k=t.browserCache,S={auth:true};if(k){if(k<0)throw new c('"config.browserCache" should be > 0. (seconds)',{code:"INVALID_PARAMETER"});S.method="get",S.stableGateway=true,T.browser_cache=k;let C=this.session?.idToken?.payload?.sub||this.user?.user_id;C&&(T.uid=C),T.nocache=ko(b,t.refresh);}e=(await P.bind(this)("get-signed-url",T,S)).url;}else if(h){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 Q.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(x){throw this.log("getFile:new token error",x),new c("User login is required.",{code:"INVALID_REQUEST"})}}let k=this.bearerToken||this.session?.idToken?.jwtToken;if(!k||!this.user?.user_id)throw new c("User login is required.",{code:"INVALID_REQUEST"});e+=`${e.includes("?")?"&":"?"}t=${encodeURIComponent(k)}`;let S=g[6]==="**"?"**":parseInt(g[6]),C=this.user?.access_group??-1;if(this.user.user_id!==g[3]&&(S==="**"||C<S)){let x=g[5];if(this.__private_access_key[x]&&typeof this.__private_access_key[x]=="string")e+=`&p=${encodeURIComponent(this.__private_access_key[x])}`;else if(this.owner!==this.host)try{let $=await this.requestPrivateRecordAccessKey({record_id:x,reference_id:t?._ref});e+=`&p=${encodeURIComponent($)}`;}catch{}}}if((D.call(this)?zt(e):null)&&t?.dataType!=="endpoint"&&t?.dataType!=="info"){let T=await P.bind(this)(e,null,{method:"get",contentType:null,responseType:"blob",fetchOptions:{progress:t?.progress}},{ignoreService:true}),k=await mn.bind(this)(e,T);if(t?.dataType==="blob")return k;if(t?.dataType==="text")return await Xn(k);if(t?.dataType==="base64")return await new Promise((x,$)=>{let v=new FileReader;v.onloadend=()=>x(v.result),v.onerror=()=>$(v.error),v.readAsDataURL(k);});let S=URL.createObjectURL(k),C=document.createElement("a");return C.href=S,document.body.appendChild(C),C.setAttribute("download",y),C.click(),document.body.removeChild(C),setTimeout(()=>URL.revokeObjectURL(S),6e4),null}if(t?.dataType==="endpoint")return t._update&&(t._update.url=e),e;if(t?.dataType==="download"){let T=document.createElement("a");return T.href=e,document.body.appendChild(T),T.setAttribute("download",y),T.target="_blank",T.click(),document.body.removeChild(T),null}return new Promise(async(T,k)=>{try{let S=await P.bind(this)(e,null,{method:"get",contentType:null,responseType:t?.dataType==="text"?"text":"blob",fetchOptions:{progress:t?.progress}},{ignoreService:!0});if(t?.dataType==="base64"){let C=new FileReader;C.onloadend=()=>T(C.result),C.readAsDataURL(S);}else T(S);}catch(S){if(t?.browserCache&&!t?.refresh)try{T(await Ee.bind(this)(r,Object.assign({},t,{refresh:!0})));return}catch(C){k(C);return}k(S);}})}function mt(e,t){return `${e||this.service}/${t||this.owner}`}function nr(e,t){let r=this.__my_unique_ids[e];return r?r[t]:void 0}function ei(e,t,r){this.__my_unique_ids[e]||(this.__my_unique_ids[e]={}),this.__my_unique_ids[e][t]=r;}function No(e,t){this.__my_unique_ids[e]&&delete this.__my_unique_ids[e][t];}async function ti(e,t=false){e=V(e,{ignoreEmpty:true}).data||{};let r=mt.bind(this)(e?.service,e?.owner),n="",i=Gn(e);if(i){if(e=i,n=e.record_id||e.unique_id,typeof n=="string"){typeof this.__private_access_key?.[n]=="string"&&(e.private_key=this.__private_access_key?.[n]||void 0);let s=nr.bind(this)(r,n);s&&(t?No.bind(this)(r,n):e.record_id=s);}}else {let s=await W.bind(this)(),o=e?.reference,a=false;typeof o=="object"&&Object.keys(o).length&&(o?.record_id||o?.unique_id?(n=o.record_id||o.unique_id,n&&typeof this.__private_access_key?.[n]=="string"&&(e.private_key=this.__private_access_key?.[n]||void 0),e.reference=n):o?.user_id&&(a=o.user_id===this.user?.user_id,e.reference=o.user_id)),typeof e?.table=="string"&&(e.table={name:e.table,access_group:0}),e.index&&e.index.hasOwnProperty("range")&&e.index.hasOwnProperty("condition")&&delete e.index.range;let l=u=>({table:{name:d=>ve(d,"table.name"),access_group:rr.bind(this),subscription:d=>p.UserId(d,'User ID in "subscription"')},reference:"string",index:{name:["$updated","$uploaded","$referenced_count","$user_id",d=>We(d,"index.name")],value:d=>{let f={$updated:"number",$uploaded:"number",$referenced_count:"number",$user_id:p.UserId};if(f.hasOwnProperty(u.index.name)){let g=f[u.index.name];if(typeof g=="function")return g(d);if(g!==typeof d)throw new c(`"index.value" should be type: ${g}.`,{code:"INVALID_PARAMETER"});return d}return typeof d=="string"&&!d?"":typeof d=="string"&&er(u.index.name)?tr(d,"index.value"):pt(d)},condition:["gt","gte","lt","lte",">",">=","<","<=","=","eq"],range:d=>zn(d,u)},tag:d=>{if(d==null)return d;if(typeof d=="string")return gt(d,"tag");throw new c('"tag" should be type: string.',{code:"INVALID_PARAMETER"})},private_key:"string"});e=p.Params(e||{},l(e),a||s?[]:["table"],{ignoreEmpty:true});}return {query:e,is_reference_fetch:n}}async function ri(e,t){await this.__connection;let r=await ti.bind(this)(e),n=r.is_reference_fetch,i=await P.bind(this)("get-records",r.query,{fetchOptions:t,auth:!!this.__user,method:this.__user?"post":"get"});n&&i?.reference_private_key&&typeof i.reference_private_key=="string"&&(this.__private_access_key[n]=i.reference_private_key);let s=[];for(let o in i.list)s.push(Ue.bind(this)(i.list[o]));return i.list=await Promise.all(s),i}function ni(e){let t="",r=[],n=mt.bind(this)(e?.service,e?.owner),i=p.Params(e||{},{record_id:o=>{let a=typeof o=="string"?nr.bind(this)(n,o):void 0;return a||oe(o,"record_id",{allowEmpty:false})},unique_id:["string",null],readonly:"boolean",table:{name:o=>ve(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:rr.bind(this)},source:{referencing_limit:o=>{if(o===null)return null;if(typeof o=="number"){if(0>o)throw new c('"reference_limit" should be >= 0',{code:"INVALID_PARAMETER"});if(o>4503599627370546)throw new c('"reference_limit" should be <= 4503599627370546',{code:"INVALID_PARAMETER"});return o}throw new c('"reference_limit" should be type: <number | null>',{code:"INVALID_PARAMETER"})},prevent_multiple_referencing:"boolean",can_remove_referencing_records:"boolean",only_granted_can_reference:"boolean",allow_granted_to_grant_others:"boolean",referencing_index_restrictions:o=>{if(o===void 0)return;if(!o||Array.isArray(o)&&!o.length)return null;let a={name:u=>We(u,'"name" in "index_restrictions"'),value:u=>pt(u),condition:["gt","gte","lt","lte",">",">=","<","<=","=","eq","!=","ne",()=>null],range:u=>{if(u!==null&&typeof o.value!=typeof u)throw new c('Index restriction "range" type should match the type of "value".',{code:"INVALID_PARAMETER"});if(!o.hasOwnProperty("value"))throw new c('Index restriction "value" is required.',{code:"INVALID_PARAMETER"});return u}};Array.isArray(o)||(o=[o]);let l=o.map(u=>p.Params(u,a,["name"]));if(l.length)for(let u of l)u.condition&&u.hasOwnProperty("range")&&delete u.range;return l}},reference:o=>{if(o===null)return {record_id:null};if(o){if(typeof o=="string"){t=o;let a=nr.bind(this)(n,o);return a||o}if(typeof o!="object")throw new c('"reference" should be type: <string | object>.',{code:"INVALID_PARAMETER"});return p.Params(o,{unique_id:"string",record_id:a=>a==null?a:(t=a,typeof this.__private_access_key?.[a]=="string"&&(e.reference_private_key=this.__private_access_key[a]||void 0),oe(a,"reference.record_id",{allowEmpty:false,onlyAlphanumeric:true}))})}},index:[null,{name:o=>We(o,"index.name"),value:o=>pt(o)}],tags:o=>{if(o==null)return o;if(typeof o=="string"&&(o=o.split(",").map(a=>a.trim())),!Array.isArray(o))throw new c('"tag" should be type: <string | string[]>.',{code:"INVALID_PARAMETER"});return o.map(a=>gt(a,"tag"))},remove_bin:o=>{if(!o)return null;let a=[];if(Array.isArray(o))for(let l of o)if(typeof l=="string")a.push(l.split("?")[0]);else if(l.url&&l.size&&l.filename){let d=l.url.split("/").slice(0,3).join("/")+"/"+l.path;a.push(d);}else throw new c('"remove_bin" should be type: <string[] | BinaryFile[] | null>',{code:"INVALID_PARAMETER"});else throw new c('"remove_bin" should be type: <string[] | BinaryFile[] | null>',{code:"INVALID_PARAMETER"});return a},progress:"function",data:o=>o},[],{precall:o=>{let a=o?.data||{};if(!a?.record_id&&!a.table)throw new c('"table.name" is required.',{code:"INVALID_PARAMETER"});typeof a.table=="string"&&(a.table={name:a.table,access_group:0}),o.files&&(r=o.files);}}),s=e.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 c("Public users cannot update existing records.",{code:"INVALID_REQUEST"});if(i.table.access_group!=="public"&&i.table.access_group!==0)throw new c("Public users can only post records to public tables.",{code:"INVALID_REQUEST"});if(o)throw new c("Public users cannot post subscription records.",{code:"INVALID_REQUEST"});if(i.remove_bin)throw new c("Public users cannot remove files from records.",{code:"INVALID_REQUEST"});if(i.unique_id)throw new c("Public users cannot set unique_id for records.",{code:"INVALID_REQUEST"})}return {config:i,progress:s,is_reference_post:t,files:r}}async function ii(e){if(await this.__connection,!Array.isArray(e)||!e.length)throw new c('"params" should be a non-empty array.',{code:"INVALID_PARAMETER"});let t=[],r,n,i=null,s={},a={_is_bulk_:await Promise.all(e.map(async(h,m)=>{if(!h||typeof h!="object"||Array.isArray(h))throw new c(`"params[${m}]" should be type: <object>.`,{code:"INVALID_PARAMETER"});let y=ni.bind(this)(h),b=y.config;if(D.call(this)){let _=Object.prototype.hasOwnProperty.call(b,"data"),w=await Vt.bind(this)(b.data,h,_);w.encrypted&&(b.data=w.send,s[m]=w.plain);}if(y.is_reference_post&&t.push(y.is_reference_post),typeof b.progress=="function"&&i===null&&(i=b.progress),b.service!==void 0){if(r===void 0)r=b.service;else if(r!==b.service)throw new c('All bulk params should share the same "service" value.',{code:"INVALID_PARAMETER"})}if(b.owner!==void 0){if(n===void 0)n=b.owner;else if(n!==b.owner)throw new c('All bulk params should share the same "owner" value.',{code:"INVALID_PARAMETER"})}return delete b.progress,delete b.service,delete b.owner,b})),service:"",owner:""};r!==void 0&&(a.service=r),n!==void 0&&(a.owner=n);let l={auth:!!this.__user,method:"post"},u={};Object.keys(u).length&&Object.assign(l,{fetchOptions:u});let d=await P.bind(this)("post-record",a,l),f=await Promise.all(d.map((h,m)=>Ue.bind(this)(h,"called from postRecord",false,s.hasOwnProperty(m))));for(let h=0;h<f.length;h++)s.hasOwnProperty(h)&&f[h]&&!f[h].error&&(f[h].data=s[h],f[h].encrypted={status:"encrypted"});let g=mt.bind(this)(r,n);for(let h=0;h<d.length;h++){let m=d[h],y=f[h];if(m&&typeof m=="object"&&m.error&&y&&!y.record_id&&(y.error=m.error),typeof m?.reference_private_key=="string")for(let b of t)this.__private_access_key[b]=m.reference_private_key;y?.unique_id&&ei.bind(this)(g,y.unique_id,y.record_id);}return f}async function si(e,t,r){if(await this.__connection,!t)throw new c('"config" argument is required.',{code:"INVALID_PARAMETER"});let n=ni.bind(this)(t),i=n.config,s=n.progress,o=n.is_reference_post,a={auth:!!this.__user,method:"post"},l=[],u=V(e);r&&Array.isArray(r)&&r.length&&(l=l.concat(r)),u.files&&Array.isArray(u.files)&&u.files.length&&(l=l.concat(u.files));let d=t?.data!==void 0?t.data:u.data,f=d!==void 0,g=await Vt.bind(this)(d,t,f),h=null;h=Object.assign({},i),delete h.data,g.omit||(h.data=g.send);let m={};typeof s=="function"&&(m.progress=s),Object.keys(m).length&&Object.assign(a,{fetchOptions:m});let y=await P.bind(this)("post-record",h,a);if(g.encrypted&&y?.rec&&Hr.bind(this)(y.rec,g.dek),G()&&l.length){let w=new FormData;for(let S of l)w.append(S.name,S.file,S.file.name);let T={record_id:y.rec,progress:s};i.hasOwnProperty("service")&&(T.service=i.service);let{bin_endpoints:k}=await dt.bind(this)(w,T);y.bin?y.bin.push(...k):y.bin=k;}o&&typeof y?.reference_private_key=="string"&&(this.__private_access_key[o]=y.reference_private_key);let b=!!y&&y.data&&typeof y.data=="object"&&!Array.isArray(y.data)&&typeof y.data.__data__=="string"&&y.data.__data__.endsWith("/__data__/__json__.json"),_=await Ue.bind(this)(y,"called from postRecord",true,g.encrypted);if(b&&(_.data=u.data),g.encrypted&&(_.data=g.plain,_.encrypted={status:"encrypted",recipients:Object.keys(g.send.k||{})}),_.unique_id){let w=mt.bind(this)(i?.service,i?.owner);ei.bind(this)(w,_.unique_id,_.record_id),G()&&(this.__uniqueIdsPersistTimer!==null&&clearTimeout(this.__uniqueIdsPersistTimer),this.__uniqueIdsPersistTimer=setTimeout(()=>{this.__uniqueIdsPersistTimer=null;try{window.sessionStorage.setItem(`${w}:uniqueids`,JSON.stringify(this.__my_unique_ids[w]||{}));}catch{}},500));}return _}async function oi(e,t){let r=await P.bind(this)("get-table",p.Params(e||{},{table:i=>ve(i,"table",{allowEmpty:true}),condition:["gt","gte","lt","lte",">",">=","<","<=","=","eq","!=","ne"]}),Object.assign({auth:!!this.__user},{fetchOptions:t})),n={cnt_rec:"number_of_records",tbl:"table",srvc:"service",grp_:"number_of_records_in_access_group_"};if(Array.isArray(r?.list))for(let i of r.list){for(let s in n){if(s==="grp_"){for(let o in i)if(o.startsWith("grp_")){let a=o.substring(4);a==="pv"?a="private":a==="00"?a="public":a==="01"?a="authorized":a==="99"&&(a="admin"),i[`number_of_records_in_access_group_${a}`]=i[o],delete i[o];}}i.hasOwnProperty(s)&&(i[n[s]]=i[s],delete i[s]);}typeof i.table=="string"&&(i.table=Y(i.table));}return r}async function ai(e,t){if(!e?.table)throw new c('"table" is required.',{code:"INVALID_PARAMETER"});let r=p.Params(e||{},{table:s=>ve(s,"table",{allowEmpty:true}),index:s=>We(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(e?.order?.by==="index_name"&&typeof s=="string")return oe(s,"order.value",{allowEmpty:true,maxLength:256,blockKeyDelimiters:true});if(typeof s!="string"&&typeof s!="number"&&typeof s!="boolean")throw new c('"order.value" should be type: <string | number | boolean>.',{code:"INVALID_PARAMETER"});return s},condition:["gt","gte","lt","lte",">",">=","<","<=","=","eq","!=","ne"]}},["table"]);if(r.hasOwnProperty("order")){if(!r.order?.by)throw new c('"order.by" is required.',{code:"INVALID_PARAMETER"});if(r.order.hasOwnProperty("condition")&&!r.order.hasOwnProperty("value"))throw new c('"value" is required for "condition".',{code:"INVALID_PARAMETER"});if(r.hasOwnProperty("index")&&r.index.substring(r.index.length-1)!==".")throw new c('"index" should be a parent index name of the compound index when using "order.by"',{code:"INVALID_PARAMETER"})}let n=await P.bind(this)("get-index",r,Object.assign({auth:!!this.__user},{fetchOptions:t})),i={cnt_bool:"boolean_count",cnt_numb:"number_count",totl_numb:"total_number",totl_bool:"total_bool",avrg_numb:"average_number",avrg_bool:"average_bool",cnt_str:"string_count"};return Array.isArray(n?.list)&&(n.list=n.list.map(s=>{let o=s.idx.split("/"),a={table:Y(o[1]),index:Y(o[2]),number_of_records:s.cnt_rec};for(let l in i)Object.prototype.hasOwnProperty.call(s,l)&&(a[i[l]]=s[l]);return a})),n}async function ci(e,t){let r=await P.bind(this)("get-tag",p.Params(e||{},{table:n=>ve(n,"table",{allowEmpty:true}),tag:n=>gt(n,"tag",{allowEmpty:true}),condition:["gt","gte","lt","lte",">",">=","<","<=","=","eq","!=","ne"]}),Object.assign({auth:!!this.__user},{fetchOptions:t}));return Array.isArray(r?.list)&&(r.list=r.list.map(n=>{let i=n.tag.split("/");return {table:Y(i[1]),tag:Y(i[0]),number_of_records:n.cnt_rec}})),r}async function li(e,t){let r=await P.bind(this)("get-uniqueid",p.Params(e||{},{unique_id:"string",condition:["gt","gte","lt","lte",">",">=","<","<=","=","eq","!=","ne"]}),Object.assign({auth:!!this.__user},{fetchOptions:t}));if(Array.isArray(r?.list))for(let n in r.list){let i=r.list[n];r.list[n]={unique_id:i.unq,record_id:i.rec};}return r}function xo(e){if(!e||typeof e!="object")return null;let t="",r="",n=0;if(typeof e.usr_tbl=="string"){let s=e.usr_tbl.split("/");t=s[0]||"",r=Y(s[1]||""),n=s[3];}else if(typeof e.tbl=="string"){let s=e.tbl.split("/");r=Y(s[0]||""),n=s[2],t=e.usr||"";}else return null;let i="";if(typeof e.ip=="string"){let s=e.ip.indexOf("#");s>=0&&(i=e.ip.slice(s+1));}return {access_group:n==="**"?"private":parseInt(n),table_name:r,user_id:t,record_id:e.rec||"",unique_id:i}}async function ui(e,t){await this.__connection;let r=await ti.bind(this)(e,true),n=r.is_reference_fetch,i=await P.bind(this)("del-records",r.query,{auth:true,fetchOptions:t});if(n&&typeof i?.reference_private_key=="string"&&(this.__private_access_key[n]=i.reference_private_key),Array.isArray(i?.list)){for(let s of i.list)if(s&&typeof s=="object"&&"data"in s&&(s.data=Yn(s.data),D.call(this)&&it(s.data))){let o=xo(s);if(o){let a=await $t.bind(this)(s.data,o);s.data=a.value,a.flag&&(s.encrypted=a.flag);}else s.data=null,s.encrypted={status:"failed",reason:"BINDING_MISMATCH"};}}return i?.message||i}async function di(e){if(D.call(this)){let t=typeof e.user_id=="string"?[e.user_id]:e.user_id;Array.isArray(t)&&t.length&&await Gt.bind(this)(e.record_id,t);}return hi.bind(this)({record_id:e.record_id,user_id:e.user_id,execute:"add"})}async function fi(e){let t=await hi.bind(this)({record_id:e.record_id,user_id:e.user_id||null,execute:"remove"});if(D.call(this)){let r=typeof e.user_id=="string"?[e.user_id]:e.user_id;await on.bind(this)(e.record_id,Array.isArray(r)&&r.length?r:null);}return t}async function gi(e,t){let r={record_id:e.record_id||void 0,user_id:e.user_id||void 0,execute:"list"};if(!r.record_id&&!r.user_id)throw new c("Either record_id or user_id must be provided.",{code:"INVALID_PARAMETER"});if(r.user_id)if(typeof r.user_id=="string")p.UserId(r.user_id),r.user_id=[r.user_id];else if(Array.isArray(r.user_id))for(let s of r.user_id)p.UserId(s);else throw new c("user_id should be type: <string | string[]>",{code:"INVALID_PARAMETER"});let n=s=>(s.rec_usr?(s.record_id=s.rec_usr.split("/")[0],s.user_id=s.rec_usr.split("/")[1]):s.usr_rec&&(s.user_id=s.usr_rec.split("/")[0],s.record_id=s.usr_rec.split("/")[1]),s),i=await P.bind(this)("grant-private-access",r,{auth:true,fetchOptions:t});return i.list=i.list.map(n),i}function pi(e){let t=e.record_id,r=e.reference_id||void 0;if(!t)throw new c("Record ID is required.",{code:"INVALID_PARAMETER"});if(typeof t!="string")throw new c("Record ID should be type: <string | string[]>",{code:"INVALID_PARAMETER"});if(r&&typeof r!="string")throw new c("Reference ID should be type: <string>",{code:"INVALID_PARAMETER"});if(typeof this.__private_access_key[t]=="string")return Promise.resolve(this.__private_access_key[t]);if(ht[t])return ht[t];let n=P.bind(this)("request-private-access-key",{record_id:t,reference_id:r},{auth:true}).then(i=>{let s=typeof i=="string"?i:i?.private_key;if(typeof s!="string")throw new c("Invalid private access key response.",{code:"ERROR"});return this.__private_access_key[t]=s,s}).finally(()=>{delete ht[t];});return ht[t]=n,n}function hi(e){e.execute;let r=p.Params(e,{record_id:"string",user_id:n=>{if(!n)throw new c("User ID is required.",{code:"INVALID_PARAMETER"});let i=n;if(typeof i=="string"&&(i=[i]),i.length>100)throw new c("Cannot process more than 100 users at once.",{code:"INVALID_REQUEST"});for(let s of i)p.UserId(s,'User ID in "user_id"');return i},execute:["add","remove"]},["execute","record_id","user_id"]);return r.user_id||(r.user_id=null),P.bind(this)("grant-private-access",r,{auth:true})}var N={},K={},ie={},ce={},ae={},yt={},bt={};function mi(e,t,r){e[t]||(e[t]=[]),e[t].push(r);}async function _t(e,t,r){let n=[];if(e[t]){for(let i of e[t])if(i){let s=r(i);s instanceof Promise&&(s=await s),n.push(s);}delete e[t];}return n}async function sr(e,t){if(!this?.session?.accessToken?.jwtToken)throw new c("Access token is required.",{code:"INVALID_PARAMETER"});let r=await this.__socket;async function n(i,s,o){this.log("answerSdpOffer from",s),await N[s].setRemoteDescription(new RTCSessionDescription(i));let a=await N[s].createAnswer();await N[s].setLocalDescription(a),o.send(JSON.stringify({action:"rtc",uid:s,content:{sdpanswer:a},token:this.session.accessToken.jwtToken}));}N?.[t]?e?(await _t(bt,t,i=>n.bind(this)(i,t,r)),await n.bind(this)(e,t,r)):await _t(bt,t,i=>n.bind(this)(i,t,r)):e&&mi(bt,t,e);}async function or(e,t){if(this.log("receiveIceCandidate",e),N?.[t]&&N[t]?.remoteDescription&&N[t]?.remoteDescription?.type){if(!e)return _t(yt,t,r=>N[t].addIceCandidate(r));await _t(yt,t,r=>N[t].addIceCandidate(r)),await N[t].addIceCandidate(e);}else mi(yt,t,e);}async function se(e){if(typeof window>"u"||window._runningInNodeJS)throw new c("WebRTC is not supported in Node.js environment.",{code:"NOT_SUPPORTED"});p.Params(e,{cid:s=>{if(typeof s!="string")throw new c('"cid" should be type: <string>.',{code:"INVALID_PARAMETER"});if(s&&s.slice(0,4)!=="cid:")throw new c('"cid" should be a valid connection id.',{code:"INVALID_PARAMETER"});return s},close:"boolean"});let t=await this.__socket,{cid:r,close_all:n=false}=e||{};if(!n&&!r)throw new c('"cid" is required.',{code:"INVALID_PARAMETER"});let i=s=>{if(!s)throw new c('"cid" is required.',{code:"INVALID_PARAMETER"});if(delete bt[s],delete yt[s],K[s]&&Object.values(K[s]).forEach(o=>{o.readyState!=="closed"&&o.close();}),delete K[s],N?.[s]){N[s].connectionState!=="closed"&&(N[s].close(),t.send(JSON.stringify({action:"rtc",uid:s,content:{hungup:this.user.user_id},token:this.session.accessToken.jwtToken})));let o={type:"connectionstatechange",target:N[s],timestamp:new Date().toISOString(),state:N[s].connectionState,iceState:N[s].iceConnectionState,signalingState:N[s].signalingState};ae[s]&&ae[s](o),this.log("closeRTC",o);}delete ae[s],delete ce[s],delete ie[s],delete N[s];};if(n)for(let s in N)i(s);else i(r);this.log("Cleaning up media stream..."),this.__mediaStream&&(this.__mediaStream.getTracks().forEach(s=>{s.stop();}),this.__mediaStream=null);}async function yi(e){if(e instanceof MediaStream)return e;if(!e.video&&!e.audio){let t=new MediaStream,r=document.createElement("canvas");r.width=1,r.height=1;let i=r.captureStream().getVideoTracks()[0];return t.addTrack(i),t}return window.navigator.mediaDevices.getUserMedia(e)}async function bi(e,t){if(typeof window>"u"||window._runningInNodeJS)throw new c("WebRTC is not supported in Node.js environment.",{code:"NOT_SUPPORTED"});if(typeof t!="function")throw new c("Callback is required.",{code:"INVALID_PARAMETER"});if(!this?.session?.accessToken?.jwtToken)throw new c("Access token is required.",{code:"INVALID_PARAMETER"});e=p.Params(e,{cid:o=>{if(typeof o!="string")throw new c('"cid" should be type: <string>.',{code:"INVALID_PARAMETER"});if(o&&o.slice(0,4)!=="cid:")throw new c('"cid" should be a valid connection id.',{code:"INVALID_PARAMETER"});return o},ice:["string",()=>"stun:stun.skapi.com:3468"],media:o=>o,channels:["text-chat","file-transfer","video-chat","voice-chat","gaming",{ordered:"boolean",maxPacketLifeTime:"number",maxRetransmits:"number",protocol:"string"},()=>[{ordered:true,maxPacketLifeTime:10,protocol:"default"}]]},["cid"]);let{cid:r,ice:n}=e;if(!(e?.media instanceof MediaStream)&&(e?.media?.video||e?.media?.audio)&&window.location.hostname!=="localhost"&&window.location.protocol!=="https:")throw new c("Media stream is only supported on either localhost or https.",{code:"INVALID_REQUEST"});let i=this.__socket?await this.__socket:this.__socket;if(!i)throw new c("No realtime connection. Execute connectRealtime() before this method.",{code:"INVALID_REQUEST"});if(i.readyState!==1)throw new c("Realtime connection is not ready.",{code:"INVALID_REQUEST"});let s={iceServers:[{urls:n}]};N?.[r]||(N[r]=new RTCPeerConnection(s)),e?.media&&(this.__mediaStream=await yi(e.media),this.__mediaStream.getTracks().forEach(o=>{N[r].addTrack(o,this.__mediaStream);})),ae[r]=t,K[r]||(K[r]={});for(let o=0;o<e.channels.length;o++){let a=e.channels[o];if(typeof a=="string")switch(a){case "text-chat":a={ordered:true,maxRetransmits:10,protocol:"text-chat"};break;case "file-transfer":a={ordered:false,maxPacketLifeTime:3e3,protocol:"file-transfer"};break;case "video-chat":a={ordered:true,maxRetransmits:10,protocol:"video-chat"};break;case "voice-chat":a={ordered:true,maxRetransmits:10,protocol:"voice-chat"};break;case "gaming":a={ordered:false,maxPacketLifeTime:100,protocol:"gaming"};break;default:a={ordered:true,maxRetransmits:10,protocol:"default"};break}let l=a.protocol||"default";if(Object.keys(K[r]).includes(l))throw new c(`Data channel with the protocol "${l}" already exists.`,{code:"INVALID_REQUEST"});let u=N[r].createDataChannel(l,a);K[r][l]=u;}for(let o in K[r]){let a=K[r][o];Ei.bind(this)(r,a);}return wi.bind(this)(r,["onnegotiationneeded"]),await ir.bind(this)(r),{hangup:()=>ie[r]&&ie[r](false),connection:new Promise(o=>{ie[r]=(a=>{if(this.log("receiver picked up the call",r),!a)return se.bind(this)({cid:r}),null;N[r].onnegotiationneeded=()=>{this.log("onnegotiationneeded",`sending offer to "${r}".`),ir.bind(this)(r),ae[r]&&ae[r]({type:"negotiationneeded",target:N[r],timestamp:new Date().toISOString(),signalingState:N[r].signalingState,connectionState:N[r].iceConnectionState,gatheringState:N[r].iceGatheringState});},o({target:N[r],channels:K[r],hangup:()=>se.bind(this)({cid:r}),media:this.__mediaStream});}).bind(this);})}}function _i(e){return async(t,r)=>{t=t||{},t=V(t).data;let n=e.sender_cid,i=await this.__socket;if(!ce[n])return null;if(typeof r!="function")throw new c("Callback is required.",{code:"INVALID_PARAMETER"});if(!(t?.media instanceof MediaStream)&&(t?.media?.video||t?.media?.audio)&&window.location.hostname!=="localhost"&&window.location.protocol!=="https:")throw new c("Media stream is only supported on either localhost or https.",{code:"INVALID_REQUEST"});let{ice:s="stun:stun.skapi.com:3468"}=t;return N?.[n]||(N[n]=new RTCPeerConnection({iceServers:[{urls:s}]})),t?.media&&(this.__mediaStream=await yi(t.media),this.__mediaStream.getTracks().forEach(o=>{N[n].addTrack(o,this.__mediaStream);})),delete ce[n],ae[n]=r,K[n]||(K[n]={}),N[n].ondatachannel=o=>{this.log("ondatachannel",`received data channel "${o.channel.label}".`);let a=o.channel;K[n][a.label]=a,Ei.bind(this)(n,a);},wi.bind(this)(n,["onnegotiationneeded"]),await sr.bind(this)(null,n),await or.bind(this)(null,n),i.send(JSON.stringify({action:"rtc",uid:n,content:{pickup:this.user.user_id},token:this.session.accessToken.jwtToken})),{target:N[n],channels:K[n],hangup:()=>se.bind(this)({cid:n}),media:this.__mediaStream}}}async function ir(e){if(!this?.session?.accessToken?.jwtToken)throw new c("Access token is required.",{code:"INVALID_PARAMETER"});this.log("sendOffer",e);let t=await this.__socket,r=await N[e].createOffer();await N[e].setLocalDescription(r);let n=N[e].localDescription;this.log("rtcSdpOffer to",n),t.send(JSON.stringify({action:"rtc",uid:e,content:{sdpoffer:n},token:this.session.accessToken.jwtToken}));}async function Do(e,t){if(!this?.session?.accessToken?.jwtToken)throw new c("Access token is required.",{code:"INVALID_PARAMETER"});this.log("sendIceCandidate to",t);let r=await this.__socket;if(!e.candidate){this.log("candidate-end","all ice candidates have been sent");return}let n=ae[t]||(()=>{}),i=e.candidate;this.log("ice gathering state set to",N[t].iceGatheringState),n({type:"icecandidate",target:N[t],timestamp:new Date().toISOString(),candidate:e.candidate.candidate,sdpMid:e.candidate.sdpMid,sdpMLineIndex:e.candidate.sdpMLineIndex,usernameFragment:e.candidate.usernameFragment,protocol:e.candidate.protocol,gatheringState:N[t].iceGatheringState,connectionState:N[t].iceConnectionState}),r.send(JSON.stringify({action:"rtc",uid:t,content:{candidate:i},token:this.session.accessToken.jwtToken}));}function wi(e,t){let r=new Set(t),n=ae[e]||(o=>{}),i=N[e],s={ontrack:o=>{n({type:"track",target:i,timeStamp:o.timeStamp,streams:o.streams,track:o.track});},onicecandidate:o=>{Do.bind(this)(o,e),o.candidate?n({type:"icecandidate",target:i,timestamp:new Date().toISOString(),candidate:o.candidate.candidate,sdpMid:o.candidate.sdpMid,sdpMLineIndex:o.candidate.sdpMLineIndex,usernameFragment:o.candidate.usernameFragment,protocol:o.candidate.protocol,gatheringState:i.iceGatheringState,connectionState:i.iceConnectionState}):n({type:"icecandidateend",target:i,timestamp:new Date().toISOString()});},onicecandidateerror:o=>{n({type:"icecandidateerror",target:i,timestamp:new Date().toISOString(),errorCode:o.errorCode,errorText:o.errorText,url:o.url,hostCandidate:o.hostCandidate,gatheringState:i.iceGatheringState,connectionState:i.iceConnectionState});},oniceconnectionstatechange:()=>{n({type:"iceconnectionstatechange",target:i,timestamp:new Date().toISOString(),state:i.iceConnectionState,gatheringState:i.iceGatheringState,signalingState:i.signalingState});},onicegatheringstatechange:()=>{n({type:"icegatheringstatechange",target:i,timestamp:new Date().toISOString(),state:i.iceGatheringState,connectionState:i.iceConnectionState,signalingState:i.signalingState});},onsignalingstatechange:()=>{n({type:"signalingstatechange",target:i,timestamp:new Date().toISOString(),state:i.signalingState,connectionState:i.iceConnectionState,gatheringState:i.iceGatheringState});},onnegotiationneeded:()=>{ir.bind(this)(e),n({type:"negotiationneeded",target:i,timestamp:new Date().toISOString(),signalingState:i.signalingState,connectionState:i.iceConnectionState,gatheringState:i.iceGatheringState});},onconnectionstatechange:()=>{n({type:"connectionstatechange",target:i,timestamp:new Date().toISOString(),state:i.connectionState,iceState:i.iceConnectionState,signalingState:i.signalingState});let o=i.connectionState;(o==="disconnected"||o==="failed"||o==="closed")&&se.bind(this)({cid:e});}};for(let[o,a]of Object.entries(s))r.has(o)||(i[o]=a);}function Ei(e,t,r){let n=new Set(r),i=ae[e]||(o=>{}),s={onmessage:o=>{let a={type:o.type,target:t,timeStamp:o.timeStamp,data:o.data,lastEventId:o.lastEventId,origin:o.origin,readyState:t.readyState,bufferedAmount:t.bufferedAmount};this.log(`${t.label}: message`,o.data),i(a);},onerror:o=>{let a={type:o.type,target:t,timeStamp:o.timeStamp,error:o.error.message,errorCode:o.error.errorDetail,readyState:t.readyState,label:t.label};this.log(`${t.label}: error`,o.error.message),i(a);},onclose:o=>{let a={type:o.type,target:t,timeStamp:o.timeStamp,readyState:t.readyState,label:t.label,id:t.id};this.log(`${t.label}: closed`,null),i(a),K[e]&&(delete K[e][t.label],Object.keys(K[e]).length===0&&se.bind(this)({cid:e}));},onbufferedamountlow:o=>{let a={target:t,bufferedAmount:t.bufferedAmount,bufferedAmountLowThreshold:t.bufferedAmountLowThreshold,type:o.type,timeStamp:o.timeStamp};this.log(`${t.label}: bufferedamountlow`,t.bufferedAmount),i(a);},onopen:o=>{this.log("dataChannel",`data channel: "${t.label}" is open and ready to send messages.`);let a={type:o.type,target:t,timeStamp:o.timeStamp,readyState:t.readyState,label:t.label,id:t.id,ordered:t.ordered,maxRetransmits:t.maxRetransmits,protocol:t.protocol};i(a);}};for(let[o,a]of Object.entries(s))n.has(o)||(t[o]=a);}var ye,me=null,Qe=true,Ne=0;async function Co(){if(typeof window>"u"||window._runningInNodeJS)throw new c("WebSocket is not supported in Node.js environment.",{code:"NOT_SUPPORTED"});if(await this.getProfile(),!this.session)throw new c("No access.",{code:"INVALID_REQUEST"});let e=await this.record_endpoint;return new WebSocket(e.websocket_private+"?token="+this.session.accessToken.jwtToken)}var ar=null;async function Ai(){if(typeof window>"u"||window._runningInNodeJS)throw new c("WebSocket is not supported in Node.js environment.",{code:"NOT_SUPPORTED"});Qe=true;let e=this.__socket?await this.__socket:this.__socket;se.bind(this)({close_all:true}),ye&&cr.bind(this)({group:null}),Ne=0,me&&(me.terminate(),me=null);try{e&&e.close();}catch{}return window.removeEventListener("visibilitychange",ar),this.__socket=null,null}async function wt(e,t=50,r){if(typeof window>"u"||window._runningInNodeJS)throw new c("WebSocket is not supported in Node.js environment.",{code:"NOT_SUPPORTED"});if(typeof e!="function")throw new c("Callback must be a function.",{code:"INVALID_REQUEST"});if(r==="reconnect"){if(this.__socket instanceof Promise){let n=await this.__socket;if(n.readyState!==WebSocket.CLOSED&&n.readyState!==WebSocket.CLOSING)return this.__socket}}else if(Qe&&(ar=()=>{!document.hidden&&!Qe&&wt.bind(this)(e,0,"reconnect");},this.__socket instanceof Promise))return this.__socket;me&&(me.terminate(),me=null),this.__socket=new Promise(async n=>{await Se.bind(this)(),setTimeout(async()=>{let i=await Co.bind(this)();i.onopen=()=>{Qe=false,Ne=0,r!=="reconnect"&&window.addEventListener("visibilitychange",ar),this.log("realtime onopen","Connected to WebSocket server."),e({type:"success",message:"Connected to WebSocket server."}),ye&&i.send(JSON.stringify({action:"joinRoom",rid:ye,token:this.session.accessToken.jwtToken}));let s=`
206
+ var Us=Object.defineProperty;var Ns=Object.getOwnPropertyDescriptor;var Se=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(t,r)=>(typeof require<"u"?require:t)[r]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')});var I=(e,t,r,n)=>{for(var i=Ns(t,r),s=e.length-1,o;s>=0;s--)(o=e[s])&&(i=(o(t,r,i))||i);return i&&Us(t,r,i),i};function Tr(e){let r=(typeof globalThis<"u"?globalThis:void 0)?.process;if(r&&typeof r.getBuiltinModule=="function")try{return r.getBuiltinModule(e)}catch{}try{if(typeof Se=="function")return Se(e)}catch{}return null}var kt,vt,Ut=()=>kt!==void 0?kt:kt=Tr("fs"),Nt=()=>vt!==void 0?vt:vt=Tr("path"),pe=typeof globalThis<"u"?globalThis:void 0,st=pe?.window;function Ds(e){if(Buffer)return Buffer.from(e).toString("base64");let t="",r=new Uint8Array(e),n=32768;for(let i=0;i<r.length;i+=n){let s=r.subarray(i,i+n);t+=String.fromCharCode.apply(null,Array.from(s));}if(typeof btoa=="function")return btoa(t);throw new Error("No base64 encoder available in this environment.")}if(st)st.global=st,st.global._runningInNodeJS=false;else if(pe&&(pe.global=pe,typeof pe.window>"u")){class e{constructor(){this.result=null;this.error=null;this.onload=null;this.onloadend=null;this.onerror=null;}readAsDataURL(n){n.arrayBuffer().then(i=>{let s=Ds(i),o=n.type||"application/octet-stream";this.result=`data:${o};base64,${s}`,this.onload&&this.onload({target:this}),this.onloadend&&this.onloadend({target:this});}).catch(i=>{this.error=i,this.onerror&&this.onerror({target:this});});}readAsArrayBuffer(n){n.arrayBuffer().then(i=>{this.result=i,this.onload&&this.onload({target:this}),this.onloadend&&this.onloadend({target:this});}).catch(i=>{this.error=i,this.onerror&&this.onerror({target:this});});}readAsText(n,i="utf-8"){n.text().then(s=>{this.result=s,this.onload&&this.onload({target:this}),this.onloadend&&this.onloadend({target:this});}).catch(s=>{this.error=s,this.onerror&&this.onerror({target:this});});}}pe.FileReader=e;class t{constructor(){this.status=0;this.statusText="";this.readyState=0;this.responseText="";this.response=null;this.responseType="";this.responseURL="";this.timeout=0;this.withCredentials=false;this.onload=null;this.onerror=null;this.onabort=null;this.ontimeout=null;this.onprogress=null;this.onreadystatechange=null;this.upload={onprogress:null};this._method="GET";this._url="";this._headers={};this._aborted=false;}open(n,i){this._method=n,this._url=i,this.readyState=1;}setRequestHeader(n,i){this._headers[n]=i;}getResponseHeader(n){return null}abort(){this._aborted=true,this.onabort&&this.onabort({});}send(n){if(this._aborted)return;let i={method:this._method,headers:this._headers};n&&this._method!=="GET"&&this._method!=="HEAD"&&(i.body=n),fetch(this._url,i).then(async s=>{if(!this._aborted){if(this.status=s.status,this.statusText=s.statusText,this.responseURL=s.url,this.readyState=4,this.responseType==="blob")this.response=await s.blob();else if(this.responseType==="json")try{this.response=await s.json();}catch{this.response=null;}else this.responseType==="arraybuffer"?this.response=await s.arrayBuffer():(this.responseText=await s.text(),this.response=this.responseText);this.onload&&this.onload({});}}).catch(s=>{this._aborted||this.onerror&&this.onerror(s);});}}pe.XMLHttpRequest=t,pe.window={_runningInNodeJS:true,alert:r=>console.error("[Alert]",r),sessionStorage:{getItem:r=>null,setItem:(r,n)=>{},removeItem:r=>{}},localStorage:{getItem:r=>{let n=Ut(),i=Nt();if(!n||!i)return null;try{let s=i.resolve(process.cwd(),"states","localStorage",`${r}.skapi`);return n.existsSync(s)?n.readFileSync(s,"utf8"):null}catch{return null}},setItem:(r,n)=>{let i=Ut(),s=Nt();if(!(!i||!s))try{let o=s.resolve(process.cwd(),"states","localStorage");i.existsSync(o)||i.mkdirSync(o,{recursive:!0});let c=s.resolve(o,`${r}.skapi`);i.writeFileSync(c,n,"utf8");}catch{}},removeItem:r=>{let n=Ut(),i=Nt();if(!(!n||!i))try{let s=i.resolve(process.cwd(),"states","localStorage",`${r}.skapi`);n.existsSync(s)&&n.unlinkSync(s);}catch{}}},location:{href:"",origin:"",hostname:"",protocol:"",replace:r=>{}},navigator:{userAgent:`nodejs/${pe?.process?.versions?.node||"unknown"}`,mediaDevices:{getUserMedia:async r=>{throw new Error("getUserMedia is not supported in Node.js environment.")}}},addEventListener:()=>{},removeEventListener:()=>{}};}var a=class extends Error{constructor(t,r){if(Array.isArray(t)&&t.length<=2){let n=t[1];if(t.length>2)for(let i=2;i<t.length&&typeof t[i]=="string";i++)n+=t[i];super((n||"Something went wrong.").trim()),this.name=r?.name||"SKAPI",this.code=r?.code||t[0]||"ERROR",r?.cause&&(this.cause=r.cause);}else super((t?.message||(typeof t=="string"?t:"Something went wrong.")).trim()),typeof t=="string"?(this.name=r?.name||"SKAPI",this.code=r?.code||"ERROR",r?.cause&&(this.cause=r.cause)):t instanceof Error?(this.cause=t,this.name=t.name,t.hasOwnProperty("code")&&(this.code=t.code)):typeof t=="object"&&t?.code&&t?.message&&(this.name=r?.name||"SKAPI",this.code=r?.code||"ERROR",this.cause=t?.cause);}};var he="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",Dt=BigInt(he.length),xs=2*1024*1024,Cs=["aud","cognito:username","event_id","exp","iat","iss","jti","origin_jti","secret_key","token_use"],Sr={auth_time:"log",sub:"user_id"},Os=["0","1","2","3","4","5","6","7","8","9","a","b","c","d","e","f","g","h","i","j","k","l"],Dr=["us31","us72","ap51","ap22","ap41","eu71","ap21","us32","us71","af51","ap31","ap43","ap23","ap42","ca01","eu01","eu72","eu51","eu73","eu11","me51","sa31"],kr=typeof TextEncoder<"u"?new TextEncoder:null;function Ls(){if(typeof globalThis<"u")return globalThis.Buffer}function K(e){if(kr)return kr.encode(e);let t=unescape(encodeURIComponent(e)),r=new Uint8Array(t.length);for(let n=0;n<t.length;n++)r[n]=t.charCodeAt(n);return r}function xt(e){if(e instanceof Uint8Array)return e;if(typeof e=="string")return K(e);if(typeof ArrayBuffer<"u"&&e instanceof ArrayBuffer)return new Uint8Array(e);if(typeof ArrayBuffer<"u"&&ArrayBuffer.isView(e))return new Uint8Array(e.buffer,e.byteOffset,e.byteLength);if(Array.isArray(e))return Uint8Array.from(e);let t=Ls();if(t)return new Uint8Array(t.from(e));throw new Error("No byte conversion available in this environment.")}var A=class A{static hash(t){typeof t!="string"&&(console.warn("coercing non-string value to empty string"),t="");let r=A.sb(t),n=1732584193,i=-271733879,s=-1732584194,o=271733878,c,l,u,g;for(let f=0;f<r.length;f+=16)c=n,l=i,u=s,g=o,n=A.ff(n,i,s,o,r[f],7,-680876936),o=A.ff(o,n,i,s,r[f+1],12,-389564586),s=A.ff(s,o,n,i,r[f+2],17,606105819),i=A.ff(i,s,o,n,r[f+3],22,-1044525330),n=A.ff(n,i,s,o,r[f+4],7,-176418897),o=A.ff(o,n,i,s,r[f+5],12,1200080426),s=A.ff(s,o,n,i,r[f+6],17,-1473231341),i=A.ff(i,s,o,n,r[f+7],22,-45705983),n=A.ff(n,i,s,o,r[f+8],7,1770035416),o=A.ff(o,n,i,s,r[f+9],12,-1958414417),s=A.ff(s,o,n,i,r[f+10],17,-42063),i=A.ff(i,s,o,n,r[f+11],22,-1990404162),n=A.ff(n,i,s,o,r[f+12],7,1804603682),o=A.ff(o,n,i,s,r[f+13],12,-40341101),s=A.ff(s,o,n,i,r[f+14],17,-1502002290),i=A.ff(i,s,o,n,r[f+15],22,1236535329),n=A.gg(n,i,s,o,r[f+1],5,-165796510),o=A.gg(o,n,i,s,r[f+6],9,-1069501632),s=A.gg(s,o,n,i,r[f+11],14,643717713),i=A.gg(i,s,o,n,r[f],20,-373897302),n=A.gg(n,i,s,o,r[f+5],5,-701558691),o=A.gg(o,n,i,s,r[f+10],9,38016083),s=A.gg(s,o,n,i,r[f+15],14,-660478335),i=A.gg(i,s,o,n,r[f+4],20,-405537848),n=A.gg(n,i,s,o,r[f+9],5,568446438),o=A.gg(o,n,i,s,r[f+14],9,-1019803690),s=A.gg(s,o,n,i,r[f+3],14,-187363961),i=A.gg(i,s,o,n,r[f+8],20,1163531501),n=A.gg(n,i,s,o,r[f+13],5,-1444681467),o=A.gg(o,n,i,s,r[f+2],9,-51403784),s=A.gg(s,o,n,i,r[f+7],14,1735328473),i=A.gg(i,s,o,n,r[f+12],20,-1926607734),n=A.hh(n,i,s,o,r[f+5],4,-378558),o=A.hh(o,n,i,s,r[f+8],11,-2022574463),s=A.hh(s,o,n,i,r[f+11],16,1839030562),i=A.hh(i,s,o,n,r[f+14],23,-35309556),n=A.hh(n,i,s,o,r[f+1],4,-1530992060),o=A.hh(o,n,i,s,r[f+4],11,1272893353),s=A.hh(s,o,n,i,r[f+7],16,-155497632),i=A.hh(i,s,o,n,r[f+10],23,-1094730640),n=A.hh(n,i,s,o,r[f+13],4,681279174),o=A.hh(o,n,i,s,r[f],11,-358537222),s=A.hh(s,o,n,i,r[f+3],16,-722521979),i=A.hh(i,s,o,n,r[f+6],23,76029189),n=A.hh(n,i,s,o,r[f+9],4,-640364487),o=A.hh(o,n,i,s,r[f+12],11,-421815835),s=A.hh(s,o,n,i,r[f+15],16,530742520),i=A.hh(i,s,o,n,r[f+2],23,-995338651),n=A.ii(n,i,s,o,r[f],6,-198630844),o=A.ii(o,n,i,s,r[f+7],10,1126891415),s=A.ii(s,o,n,i,r[f+14],15,-1416354905),i=A.ii(i,s,o,n,r[f+5],21,-57434055),n=A.ii(n,i,s,o,r[f+12],6,1700485571),o=A.ii(o,n,i,s,r[f+3],10,-1894986606),s=A.ii(s,o,n,i,r[f+10],15,-1051523),i=A.ii(i,s,o,n,r[f+1],21,-2054922799),n=A.ii(n,i,s,o,r[f+8],6,1873313359),o=A.ii(o,n,i,s,r[f+15],10,-30611744),s=A.ii(s,o,n,i,r[f+6],15,-1560198380),i=A.ii(i,s,o,n,r[f+13],21,1309151649),n=A.ii(n,i,s,o,r[f+4],6,-145523070),o=A.ii(o,n,i,s,r[f+11],10,-1120210379),s=A.ii(s,o,n,i,r[f+2],15,718787259),i=A.ii(i,s,o,n,r[f+9],21,-343485551),n=A.ad(n,c),i=A.ad(i,l),s=A.ad(s,u),o=A.ad(o,g);return A.rh(n)+A.rh(i)+A.rh(s)+A.rh(o)}static rh(t){let r="";for(let n=0;n<=3;n++)r+=A.alphabet.charAt(t>>n*8+4&15)+A.alphabet.charAt(t>>n*8&15);return r}static ad(t,r){let n=(t&65535)+(r&65535);return (t>>16)+(r>>16)+(n>>16)<<16|n&65535}static rl(t,r){return t<<r|t>>>32-r}static cm(t,r,n,i,s,o){return A.ad(A.rl(A.ad(A.ad(r,t),A.ad(i,o)),s),n)}static ff(t,r,n,i,s,o,c){return A.cm(r&n|~r&i,t,r,s,o,c)}static gg(t,r,n,i,s,o,c){return A.cm(r&i|n&~i,t,r,s,o,c)}static hh(t,r,n,i,s,o,c){return A.cm(r^n^i,t,r,s,o,c)}static ii(t,r,n,i,s,o,c){return A.cm(n^(r|~i),t,r,s,o,c)}static sb(t){let r,n=(t.length+8>>6)+1,i=new Array(n*16);for(r=0;r<n*16;r++)i[r]=0;for(r=0;r<t.length;r++)i[r>>2]|=t.charCodeAt(r)<<r%4*8;return i[r>>2]|=128<<r%4*8,i[n*16-2]=t.length*8,i}};A.alphabet="0123456789abcdef";var W=A;function xr(e){if(e===0)return he[0];let t="";for(;e>0;)t=he[e%62]+t,e=Math.floor(e/62);return t}function te(e){return e.split("").reverse().reduce((t,r,n)=>t+he.indexOf(r)*62**n,0)}function Ee(e=6){let t="",r="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",n=r.length,i=0;for(;i<e;)t+=r.charAt(Math.floor(Math.random()*n)),i+=1;return t}function Ct(){return typeof window>"u"||!!window?._runningInNodeJS}function J(){return !Ct()&&typeof document<"u"&&typeof document.createElement=="function"}function ot(e){let t;try{t=JSON.stringify(e);}catch{throw new a("Invalid data type.",{code:"INVALID_REQUEST"})}if(new Blob([t]).size>xs)throw new a("Data should not exceed 2MB",{code:"INVALID_REQUEST"})}function vr(e){return e===""||e==="on"||e==="true"}function Ur(e){return e==="false"}function Nr(e,t,r){t.name&&r(e,t.name,t.value);}var at=J(),Fs=typeof SubmitEvent<"u",Ms=typeof HTMLFormElement<"u";function q(e,t,r){let n={},i=[];function s(l,u,g){if(t?.ignoreEmpty&&g==="")return;if(t?.nullIfEmpty&&g===""&&(g=null),typeof r=="function"){let p=r(u,g);p!==void 0&&(g=p);}let f=u.split("[").map(p=>{let m=p.replace("]",""),h=Number(m);return !isNaN(h)&&!m.includes(".")?m=h:(m[0]==='"'&&m[m.length-1]==='"'||m[0]==="'"&&m[m.length-1]==="'")&&(m=m.replace(/"/g,"").replace(/'/g,"")),m}),d=l;if(typeof f[0]=="number")throw new a("Form key cannot start with an array index.",{code:"INVALID_REQUEST"});for(let p=0;p<f.length;p++){let m=f[p];p<f.length-1?(d[m]===void 0&&(typeof f[p+1]=="number"?d[m]=[]:d[m]={}),d=d[m]):d[m]===void 0?d[m]=g:Array.isArray(d[m])?d[m].push(g):d[m]=[d[m],g];}}function o(l,u,g){if(g instanceof File)l.push({name:u,file:g});else if(g instanceof FileList&&g&&g.length>0)for(let f=0;f<=g.length-1;f++){let d=g.item(f);d&&l.push({name:u,file:d});}}let c=l=>{l.name&&(l.type==="number"?l.value&&s(n,l.name,Number(l.value)):l.type==="checkbox"||l.type==="radio"?l.checked?l.type==="checkbox"&&l.value===""||vr(l.value)?s(n,l.name,true):Ur(l.value)?s(n,l.name,false):l.value&&s(n,l.name,l.value):l.type==="checkbox"&&(vr(l.value)?s(n,l.name,false):Ur(l.value)&&s(n,l.name,true)):l.type==="file"?l.files&&l.files.length>0&&o(i,l.name,l.files):s(n,l.name,l.value));};if(at&&(e instanceof HTMLInputElement||e instanceof HTMLSelectElement||e instanceof HTMLTextAreaElement))return c(e),ot(n),{data:n,files:i};if(at&&e instanceof FormData){for(let l of e.entries()){let u=l[0],g=l[1];if(g instanceof File||g instanceof FileList)o(i,u,g);else if(g instanceof Blob){let f=g;if(f.type==="application/json")try{let d=JSON.parse(f.text());s(n,u,d);}catch{s(n,u,f);}}else s(n,u,g);}return ot(n),{data:n,files:i}}if(at&&Fs&&e instanceof SubmitEvent&&(e=e.target),at&&Ms&&e instanceof HTMLFormElement){let l=e.querySelectorAll("input"),u=e.querySelectorAll("select"),g=e.querySelectorAll("textarea");for(let f=0;f<u.length;f++)Nr(n,u[f],s);for(let f=0;f<g.length;f++)Nr(n,g[f],s);for(let f=0;f<l.length;f++)c(l[f]);return ot(n),{data:n,files:i}}return ot(e),{data:e,files:i}}function $e(e){let t={};for(let r in e){let n=e[r];if(!Cs.includes(r))if(Sr[r])t[Sr[r]]=n;else if(r.includes("custom:"))t[r.replace("custom:","")]=n;else if(r==="address"){let i=n;if(i&&typeof i=="object"&&Object.keys(i).length){if(i?.formatted)try{t[r]=JSON.parse(i.formatted);}catch{t[r]=i.formatted;}}else t[r]=i;}else t[r]=n;}for(let r of ["address_public","birthdate_public","email_public","gender_public","phone_number_public","access_group"])r.includes("_public")?t.hasOwnProperty(r.split("_")[0])?t[r]=t.hasOwnProperty(r)?!!Number(t[r]):false:delete t[r]:t[r]=t.hasOwnProperty(r)?Number(t[r]):0;for(let r of ["email","phone_number"])t.hasOwnProperty(r)?t[r+"_verified"]=t[r+"_verified"]===true:delete t[r+"_verified"];return t}function Ot(e){if(e=Ws(e),e.split("-").length===7){let t=e.split("-"),r,n;try{r=Dr[te(t[1][0])],n=t.slice(2).join("-");}catch{throw new Error("INVALID_PARAMETER: Service ID is invalid: "+e)}if(!r)throw new Error("INVALID_PARAMETER: Service ID is invalid: "+e);return {service:r+t[0]+t[1].slice(1),owner:n}}return {service:e,owner:""}}function Lt(e,t){let r=Dr.indexOf(e.slice(0,4)),n=Os[r],s=`${e.slice(4,-4)}-${n}${e.slice(-4)}-${t}`;return Hs(s)}function $s(e){let t=0n;for(let r of e){let n=he.indexOf(r);if(n<0)throw new Error(`INVALID_PARAMETER: Invalid base62 character: ${r}`);t=t*Dt+BigInt(n);}return t}function Vs(e,t=1){if(e<0n)throw new Error("INVALID_PARAMETER: Negative values are not supported.");if(e===0n)return "0".repeat(Math.max(1,t));let r="",n=e;for(;n>0n;){let i=Number(n%Dt);r=he[i]+r,n/=Dt;}return r.length<t&&(r="0".repeat(t-r.length)+r),r}function qs(e){if(e===0n)return Uint8Array.from([0]);let t=[],r=e;for(;r>0n;)t.push(Number(r&0xffn)),r>>=8n;return t.reverse(),Uint8Array.from(t)}function js(e){let t=0n;for(let r of e)t=(t<<8n)+BigInt(r);return t}function Bs(e){let t=String(e).replace(/-/g,"");if(!/^[0-9a-fA-F]{32}$/.test(t))throw new Error("INVALID_PARAMETER: Invalid UUID format.");let r=new Uint8Array(16);for(let n=0;n<16;n++)r[n]=parseInt(t.slice(n*2,n*2+2),16);return r}function Ks(e){let t=Array.from(xt(e),r=>r.toString(16).padStart(2,"0")).join("");return [t.slice(0,8),t.slice(8,12),t.slice(12,16),t.slice(16,20),t.slice(20)].join("-")}function Hs(e){let t=String(e);if(t.split("-").length===2)return t;let r=t.match(/^([0-9A-Za-z]+)-([0-9A-Za-z]+)-([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/);if(!r)throw new Error("INVALID_PARAMETER: Input must match <base62>-<base62>-<uuid>.");let[,n,i,s]=r;if(n.length<2)throw new Error("INVALID_PARAMETER: The first part must contain at least 2 characters.");if(i.length>=he.length)throw new Error("INVALID_PARAMETER: The middle section is too long to encode.");let o=n.slice(0,2),c=n.slice(2),l=i+o,u=he[i.length]+c+l,g=Bs(s),f=Vs(js(g));return `${u}-${f}`}function Ws(e){let t=String(e);if(t.split("-").length!==2)return t;let r=t.split("-");if(r.length!==2||!r[0]||!r[1])throw new Error("INVALID_PARAMETER: Corrupt compressed token: "+t);let[n,i]=r,s=he.indexOf(n[0]);if(s<0)throw new Error("INVALID_PARAMETER: Corrupt compressed token: "+t);let o=n.slice(1),c=s+2;if(o.length<c)throw new Error("INVALID_PARAMETER: Corrupt compressed token: "+t);let l=o.slice(0,o.length-c),u=o.slice(o.length-c),g=u.slice(s),f=u.slice(0,s),d=g+l;if(!/^[0-9A-Za-z]+$/.test(d)||!/^[0-9A-Za-z]+$/.test(f))throw new Error("INVALID_PARAMETER: Corrupt compressed token: "+t);let p=$s(i),m=qs(p);if(m.length>16)throw new Error("INVALID_PARAMETER: Corrupt compressed token: "+t);let h=new Uint8Array(16);h.set(m,16-m.length);let _=Ks(h);return `${d}-${f}-${_}`}function Ve(e){if(typeof TextDecoder<"u")return new TextDecoder().decode(e);let t="";for(let r=0;r<e.length;r++)t+=String.fromCharCode(e[r]);return decodeURIComponent(escape(t))}function Ft(...e){let t=0;for(let i of e)t+=i.length;let r=new Uint8Array(t),n=0;for(let i of e)r.set(i,n),n+=i.length;return r}function Gs(e,t="User ID"){let r=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;if(e){if(typeof e!="string")throw new a(`${t} should be type: string.`,{code:"INVALID_PARAMETER"});if(!e.match(r))throw new a(`${t} is invalid.`,{code:"INVALID_PARAMETER"})}else throw new a(`${t} is empty.`,{code:"INVALID_PARAMETER"});return e}function zs(e){if(e&&(typeof e!="string"||e.charAt(0)!=="+"||isNaN(Number(e.substring(1)))))throw new a('"phone_number" is invalid. The format should be "+00123456789". Type: string.',{code:"INVALID_PARAMETER"});return e||""}function Js(e){if(e){if(typeof e!="string")throw new a('"birthdate" is invalid. The format should be "yyyy-mm-dd". Type: string.',{code:"INVALID_PARAMETER"});{let t=new RegExp(/([12]\d{3}-(0[1-9]|1[0-2])-(0[1-9]|[12]\d|3[01]))/);if(e.length!==10||e.split("-").length!==3||!t.test(e))throw new a('"birthdate" is invalid. The format should be "yyyy-mm-dd". Type: string.',{code:"INVALID_PARAMETER"})}}return e||""}function Ys(e){if(e){if(typeof e!="string")throw new a('"password" should be type: string.',{code:"INVALID_PARAMETER"});if(e.length<6)throw new a('"password" should be at least 6 characters.',{code:"INVALID_PARAMETER"});if(e.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 e}function Xs(e,t="email"){if(e){if(typeof e!="string")throw new a(`"${t}"should be type: string.`,{code:"INVALID_PARAMETER"});if(e.length<5)throw new a(`"${t}" should be at least 5 characters.`,{code:"INVALID_PARAMETER"});if(/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/.test(e)&&(e=e.trim(),e.split("@")[1].split(".").length>=2))return e.toLowerCase()}else throw new a(`"${t}" is required.`,{code:"INVALID_PARAMETER"});throw new a(`"${e}" is an invalid email.`,{code:"INVALID_PARAMETER"})}function Zs(e){let t=typeof window<"u",r=(()=>{let i=t&&window.location.origin||null;return i&&i.slice(-1)==="/"&&(i=i.slice(0,-1)),i})(),n=i=>{if(typeof i=="string"){if(i==="*")return "*";{let s=i.trim();if(s[0]==="/"&&r){if(r.slice(0,5)==="file:")throw new a(`"${i}" is an invalid url. Relative URL does not work on local file system. Use full URL string.`,{code:"INVALID_PARAMETER"});s=r+s;}else if(s[0]==="."&&r){if(r.slice(0,5)==="file:")throw new a(`"${i}" is an invalid url. Relative URL does not work on local file system. Use full URL string.`,{code:"INVALID_PARAMETER"});let c=t?window.location.href.split("?")[0]:"";c.slice(-1)!=="/"&&(c+="/"),s=c+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(e)?e.map(i=>n(i)):n(e)}function eo(e,t,r=[],n){let i=q(e,n),s=i.data;t.service="string",t.owner="string";let o={};for(let c in t)if(s&&typeof s=="object"&&!Array.isArray(s)&&s.hasOwnProperty(c))if(typeof s[c]=="function")o[c]=s[c];else try{o[c]=JSON.parse(JSON.stringify(s[c]));}catch{o[c]=s[c];}n?.precall&&n.precall({data:o,files:i?.files||[]});try{return Qs__default.default(o,t,r)}catch(c){throw new a(c.message,{code:"INVALID_PARAMETER"})}}var y={UserId:Gs,PhoneNumber:zs,Birthdate:Js,Password:Ys,Email:Xs,Url:Zs,Params:eo};var Y="skapi.enc.v1",Lr=6e5,qe=12,ct=null,ke=null;function Fr(){return new a("Encryption requires Web Crypto, which needs a secure context (https, or localhost) in the browser, or Node 18 or newer. A page served over plain http has crypto.getRandomValues but crypto.subtle is undefined.",{code:"NOT_SUPPORTED"})}function Mr(){if(ke)return ke;let e=typeof globalThis<"u"?globalThis:void 0;if(e?.crypto?.subtle&&typeof e.crypto.getRandomValues=="function")return ke=e.crypto,ke;try{let t=typeof globalThis<"u"?globalThis:void 0,r=null;if(t?.process&&typeof t.process.getBuiltinModule=="function"&&(r=t.process.getBuiltinModule("crypto")),!r&&typeof Se=="function"&&(r=Se("crypto")),r?.webcrypto?.subtle)return ke=r.webcrypto,ke}catch{}throw Fr()}function re(){if(ct)return ct;let e=Mr();if(!e.subtle)throw Fr();return ct=e.subtle,ct}function $t(){try{return re(),!0}catch{return false}}function X(e){let t=Mr(),r=new Uint8Array(e),n=65536;for(let i=0;i<e;i+=n)t.getRandomValues(r.subarray(i,Math.min(i+n,e)));return r}function C(e){let t=xt(e),r;if(typeof Buffer<"u"&&typeof Buffer.from=="function")r=Buffer.from(t).toString("base64");else if(typeof btoa=="function"){let n="";for(let s=0;s<t.length;s+=32768)n+=String.fromCharCode.apply(null,Array.from(t.subarray(s,s+32768)));r=btoa(n);}else throw new a("No base64 encoder available in this environment.",{code:"NOT_SUPPORTED"});return r.replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function $(e){if(typeof e!="string")throw new a("Expected a base64url string.",{code:"INVALID_PARAMETER"});let t=e.replace(/-/g,"+").replace(/_/g,"/"),r=t.length%4;if(r===2)t+="==";else if(r===3)t+="=";else if(r===1)throw new a("Malformed base64url string.",{code:"INVALID_PARAMETER"});if(typeof Buffer<"u"&&typeof Buffer.from=="function"){let n=Buffer.from(t,"base64");return new Uint8Array(n.buffer,n.byteOffset,n.byteLength)}if(typeof atob=="function"){let n=atob(t),i=new Uint8Array(n.length);for(let s=0;s<n.length;s++)i[s]=n.charCodeAt(s);return i}throw new a("No base64 decoder available in this environment.",{code:"NOT_SUPPORTED"})}async function lt(e){let t=await re().digest("SHA-256",e);return new Uint8Array(t)}async function Ke(e,t,r,n){let i=re(),s=await i.importKey("raw",e,"HKDF",false,["deriveBits"]),o=await i.deriveBits({name:"HKDF",hash:"SHA-256",salt:t,info:r},s,n*8);return new Uint8Array(o)}async function Ue(e,t,r,n){let i=re(),s=K(e.normalize("NFC")),o=await i.importKey("raw",s,"PBKDF2",false,["deriveBits"]),c=new Uint8Array(await i.deriveBits({name:"PBKDF2",salt:t,iterations:r,hash:"SHA-256"},o,256)),l=await Ke(c,t,n,32);x(c),x(s);let u=await ie(l);return x(l),u}async function ie(e){return re().importKey("raw",e,{name:"AES-GCM"},false,["encrypt","decrypt"])}async function $r(){let e=X(32),t=await ie(e);return {bytes:e,key:t}}async function ne(e,t,r){let n=X(qe),i=await re().encrypt({name:"AES-GCM",iv:n,additionalData:r,tagLength:128},e,t);return {iv:n,ct:new Uint8Array(i)}}async function se(e,t,r,n){let i=await re().decrypt({name:"AES-GCM",iv:t,additionalData:n,tagLength:128},e,r);return new Uint8Array(i)}var ut={name:"ECDH",namedCurve:"P-256"};async function Vr(){let e=re(),t=await e.generateKey(ut,true,["deriveBits"]),r=new Uint8Array(await e.exportKey("raw",t.publicKey)),n=new Uint8Array(await e.exportKey("pkcs8",t.privateKey)),i=await Vt(n);return {pubRaw:r,pkcs8:n,priv:i}}async function Vt(e){return re().importKey("pkcs8",e,ut,false,["deriveBits"])}async function qr(e){if(e.length!==65||e[0]!==4)throw new a("Malformed public key: expected a 65 byte uncompressed P-256 point.",{code:"INVALID_PARAMETER"});return re().importKey("raw",e,ut,false,[])}async function qt(e){return C(await lt(e))}async function jr(e,t,r,n){let i=re(),s=await qr(e),o=await i.generateKey(ut,true,["deriveBits"]),c=new Uint8Array(await i.deriveBits({name:"ECDH",public:s},o.privateKey,256)),l=await Ke(c,new Uint8Array(32),r,32);x(c);let u=await ie(l);x(l);let{iv:g,ct:f}=await ne(u,t,n);return {epk:new Uint8Array(await i.exportKey("raw",o.publicKey)),iv:g,ct:f}}async function Br(e,t,r,n,i,s){let o=re(),c=await qr(t),l=new Uint8Array(await o.deriveBits({name:"ECDH",public:c},e,256)),u=await Ke(l,new Uint8Array(32),i,32);x(l);let g=await ie(u);return x(u),se(g,r,n,s)}function x(e){e&&e.length&&e.fill(0);}function to(e,t){if(e.length!==t.length)return false;let r=0;for(let n=0;n<e.length;n++)r|=e[n]^t[n];return r===0}function jt(e){return K(JSON.stringify(e))}function He(e,t,r){return Ft(e,new Uint8Array([0]),K(t),new Uint8Array([0]),K(r))}var Ae="0123456789ABCDEFGHJKMNPQRSTVWXYZ",je=16,Cr=26,Or=28;function Kr(e){let t=2166136261;for(let r=0;r<e.length;r++)t^=e[r],t=t*16777619>>>0;return t&1023}function Hr(e){if(e.length!==je)throw new a(`A recovery code needs exactly ${je} bytes.`,{code:"INVALID_PARAMETER"});let t="",r=0,n=0;for(let s=0;s<e.length;s++)for(r=r<<8|e[s],n+=8;n>=5;)n-=5,t+=Ae[r>>n&31];n>0&&(t+=Ae[r<<5-n&31]);let i=Kr(e);return t+=Ae[i>>5&31]+Ae[i&31],(t.match(/.{1,4}/g)||[]).join("-")}function Wr(e){if(typeof e!="string")throw new a("Recovery code should be a string.",{code:"INVALID_PARAMETER"});let t=e.toUpperCase().replace(/[\s\-_]/g,"").replace(/O/g,"0").replace(/[IL]/g,"1");if(t.length!==Or)throw new a(`That does not look like a recovery code: expected ${Or} characters, got ${t.length}.`,{code:"ENCRYPTION_BAD_RECOVERY_CODE"});let r=t.slice(0,Cr),n=t.slice(Cr),i=0,s=0,o=[];for(let u=0;u<r.length;u++){let g=Ae.indexOf(r[u]);if(g<0)throw new a(`That does not look like a recovery code: "${r[u]}" is not a valid character.`,{code:"ENCRYPTION_BAD_RECOVERY_CODE"});i=i<<5|g,s+=5,s>=8&&(s-=8,o.push(i>>s&255));}let c=new Uint8Array(o.slice(0,je)),l=Kr(c);if(n!==Ae[l>>5&31]+Ae[l&31])throw new a("That recovery code has a typo in it: the check characters do not match.",{code:"ENCRYPTION_BAD_RECOVERY_CODE"});return c}async function Bt(e,t,r){let n=await Ke(e,t,r,32),i=await ie(n);return x(n),i}var Mt=[83,75,69,78,67,70],Qr=2,Be=56,Gr=16,ro=4*1024*1024;function Kt(e){if(!e||e.length<Be)return false;for(let t=0;t<Mt.length;t++)if(e[t]!==Mt[t])return false;return true}function Re(e,t,r){e[t]=r>>>24&255,e[t+1]=r>>>16&255,e[t+2]=r>>>8&255,e[t+3]=r&255;}function ve(e,t){return (e[t]<<24>>>0)+(e[t+1]<<16)+(e[t+2]<<8)+e[t+3]}function no(e,t,r){let n=Math.floor(r/4294967296);Re(e,t,n),Re(e,t+4,r>>>0);}function io(e,t){return ve(e,t)*4294967296+ve(e,t+4)}async function zr(e,t,r,n,i,s){let o=K(`${Y}|binfile|${r}|${n}|${i}|${s}`),c=await Ke(e,t,o,32),l=await ie(c);return x(c),l}async function Jr(e){return (await lt(Ft(K(`${Y}|dekid`),e))).subarray(0,8)}function Yr(e,t,r){return jt([`${Y}|binchunk`,C(e),t,r])}function so(e,t,r,n,i,s){let o=new Uint8Array(Be+s.length);return o.set(Mt,0),o[6]=Qr,o[7]=s.length?1:0,Re(o,8,e),Re(o,12,t),o.set(r,16),no(o,32,n),o.set(i,40),Re(o,48,s.length),Re(o,52,0),s.length&&o.set(s,Be),o}async function Xr(e,t,r,n,i=ro){let s=X(Gr),o=await zr(e,s,r.service,r.owner,r.recordOwner,r.recordId),c=await Jr(e),l=n?K(JSON.stringify(n)):new Uint8Array(0);if(l.length>4096)throw new a("Encrypted file metadata is too large.",{code:"INVALID_PARAMETER"});let u=t.length===0?1:Math.ceil(t.length/i),g=so(i,u,s,t.length,c,l),f=await lt(g),d=[],p=g.length;for(let _=0;_<u;_++){let w=t.subarray(_*i,Math.min((_+1)*i,t.length)),b=await ne(o,w,Yr(f,_,u));d.push(b),p+=4+b.iv.length+b.ct.length;}let m=new Uint8Array(p);m.set(g,0);let h=g.length;for(let _ of d)Re(m,h,_.iv.length+_.ct.length),h+=4,m.set(_.iv,h),h+=_.iv.length,m.set(_.ct,h),h+=_.ct.length;return m}function oo(e){if(!Kt(e))throw new a("This file is not an encrypted skapi file.",{code:"INVALID_PARAMETER"});let t=ve(e,48),r=Be+t;if(e.length<r)throw new a("Encrypted file header is truncated.",{code:"INVALID_REQUEST"});let n=null;return t&&(n=JSON.parse(Ve(e.subarray(Be,r)))),{version:e[6],chunkBytes:ve(e,8),count:ve(e,12),fileId:e.subarray(16,16+Gr),plainLen:io(e,32),dekId:e.subarray(40,48),meta:n,headerLen:r}}async function Zr(e,t,r){let n=oo(t);if(n.version!==Qr)throw new a(`This file was encrypted by a different version of the SDK (container v${n.version}).`,{code:"NOT_SUPPORTED"});if(!n.count||!n.chunkBytes)throw new a("Encrypted file header is malformed.",{code:"INVALID_PARAMETER"});let i=await Jr(e);if(!to(i,n.dekId))throw new a("This file was encrypted under a previous data key for this record, so it can no longer be opened. It was most likely left behind by an interrupted access change.",{code:"ENCRYPTION_FILE_STALE_KEY"});let s=await zr(e,n.fileId,r.service,r.owner,r.recordOwner,r.recordId),o=await lt(t.subarray(0,n.headerLen)),c=[],l=n.headerLen,u=0;for(let d=0;d<n.count;d++){if(l+4>t.length)throw new a("Encrypted file is truncated.",{code:"INVALID_REQUEST"});let p=ve(t,l);if(l+=4,p<qe+16||l+p>t.length)throw new a("Encrypted file is truncated.",{code:"INVALID_REQUEST"});let m=await se(s,t.subarray(l,l+qe),t.subarray(l+qe,l+p),Yr(o,d,n.count));l+=p,c.push(m),u+=m.length;}let g=new Uint8Array(u),f=0;for(let d of c)g.set(d,f),f+=d.length;return {bytes:g,meta:n.meta}}var ao="skapi__keyring",We="__skapi_enc__",tn=1,co="skapi-enc",be="keys",Wt=new WeakMap;function rn(e){if(!e)return null;if(e===true&&(e={}),typeof e!="object")throw new a('"options.encryption" should be a boolean or an object.',{code:"INVALID_PARAMETER"});let t=typeof e.iterations=="number"?e.iterations:Lr;if(t<1e5)throw new a('"encryption.iterations" must be at least 100000.',{code:"INVALID_PARAMETER"});let r=e.trustPolicy==="strict"?"strict":"tofu";return {enabled:true,iterations:t,trustPolicy:r,persistDevice:e.persistDevice!==false,minPasswordLength:typeof e.minPasswordLength=="number"?e.minPasswordLength:0,withheld:e.withheld==="sentinel"?"sentinel":"null",recovery:e.recovery==="none"?"none":"code",table:typeof e.table=="string"&&e.table?e.table:ao}}function N(){return Wt.get(this)||null}function nn(e){if(!e){Wt.delete(this);return}Wt.set(this,{cfg:e,status:"locked",reason:"NO_SESSION_KEY",user_id:"",scope:"",mk:null,ikPriv:null,pubRaw:null,fpr:"",keyringRecordId:"",pins:{},dek:new Map,roll:new Set,passthrough:new Map,rawRead:false,ready:null,unlocking:false,pendingRecoveryCode:"",peerPub:new Map,peerInflight:new Map});}function Qt(){let e=N.call(this);if(e){e.user_id&&ir.call(this,e).catch(()=>{}),e.ready=null,e.unlocking=false,e.pendingRecoveryCode="";for(let[,t]of e.dek)x(t.bytes);e.dek.clear(),e.roll.clear(),e.passthrough.clear(),e.peerPub.clear(),e.peerInflight.clear(),e.pins={},e.mk=null,e.ikPriv=null,e.pubRaw=null,e.fpr="",e.keyringRecordId="",e.user_id="",e.status="locked",e.reason="NO_SESSION_KEY";}}function sn(){let e=N.call(this);return e?{status:e.status,reason:e.status==="unlocked"?void 0:e.reason,user_id:e.user_id||void 0,fingerprint:e.fpr||void 0}:{status:"disabled"}}function on(e,t){return typeof t=="string"&&t===e.cfg.table}function Ne(){return `${this.service}/${this.owner}`}function Gt(e,t,r,n){let[i,s]=e.split("/");return jt([Y,i,s,t,r,n])}function an(e,t,r,n,i){let[s,o]=e.split("/");return K(`${Y}|dekwrap|${s}|${o}|${t}|${r}|${n}|${i}`)}function zt(e){return e.anch==="uid"?e.uid:e.anch==="rid"?e.rid:""}function ft(e){return !!e&&typeof e=="object"&&!Array.isArray(e)&&typeof e[We]=="number"&&typeof e.ct=="string"&&typeof e.iv=="string"&&typeof e.own=="string"&&typeof e.anch=="string"&&!!e.k&&typeof e.k=="object"&&!Array.isArray(e.k)}var cn="__skapi_no_access__";function Z(e,t,r){if(e.withheld!=="sentinel")return null;let n={[cn]:true,reason:t};return r&&(n.recipients=r),Object.freeze(n)}function Jt(e){return !!e&&typeof e=="object"&&e[cn]===true}var lo=256*1024,ze="__skenc_ct__",ln="payload.bin",uo=`/${ze}/${ln}`;function Yt(e,t){return e===ze&&t===ln}async function fo(e,t,r){let n=t?.table,i=typeof n=="string"?n:n?.name;if(n&&(typeof n=="string"||n.access_group!==void 0))return {group:typeof n=="string"?0:en(n.access_group),table:i,record:null};if(!r)return {group:n?.access_group!==void 0?en(n.access_group):0,table:i,record:null};let s=e.dek.get(r);if(s)return {group:s.access_group,table:i,record:null};let o=await me.call(this,r);if(!o)throw new a(`Record "${r}" not found.`,{code:"NOT_EXISTS"});return {group:o.table.access_group,table:o.table.name,record:o}}function go(e){return this.getFile(e,{dataType:"blob"})}async function me(e){let t=/^[a-zA-Z0-9]+$/.test(e)?{record_id:e}:{unique_id:e};return (await this.getRecords(t,{limit:1}))?.list?.[0]||null}function en(e){return e==="private"||e==="**"?"private":e==="public"?0:e==="authorized"?1:e==="admin"?99:typeof e=="number"?e:0}function Ht(e,t,r){let n=this.user?.user_id;if(!(!e||!e.user_id||!n||e.user_id===n))throw new a(`Record "${t}" belongs to another user (${e.user_id}), so ${r} would either seal it under the wrong key or strand its contents. Encryption only operates on records you own, no matter what access level you hold.`,{code:"ENCRYPTION_NOT_RECORD_OWNER"})}async function Xt(e,t,r){let n=N.call(this);if(!n)return {send:e,plain:e,encrypted:false,omit:false};let i=t?.record_id||"",s=i,o=t?.unique_id||"";if(i&&n.passthrough.has(i)){let j=n.passthrough.get(i);return n.passthrough.delete(i),{send:j,plain:e,encrypted:true,omit:false}}let{group:c,table:l,record:u}=await fo.call(this,n,t,s);if(c!=="private"){let j=true;if(!r&&i){let G=u||await me.call(this,i);if(G&&G.encrypted){if(Ht.call(this,G,i,"making it non-private"),G.encrypted.status==="failed")throw new a(`Cannot make record "${i}" non-private: its current contents could not be decrypted (${G.encrypted.reason}), so they cannot be written back in the clear. Unlock encryption, or supply the record's data with the access group change.`,{code:"ENCRYPTION_LOCKED"});let Me=!!G.bin&&Object.keys(G.bin).some(it=>(G.bin[it]||[]).some(Pr=>Pr&&Pr.encrypted));if(!Me&&s){let it=n.dek.get(s);it&&(x(it.bytes),n.dek.delete(s));}return {send:G.data,plain:G.data,encrypted:false,omit:false,files:Me?"decrypt":void 0}}}let ee=u;i&&!ee&&(ee=await me.call(this,i).catch(()=>null)),ee&&ee.encrypted&&Ht.call(this,ee,i,"making it non-private");let Ir=!!ee&&!!ee.bin&&Object.keys(ee.bin).some(G=>(ee.bin[G]||[]).some(Me=>Me&&Me.encrypted));if(Ir&&(j=false),j&&s){let G=n.dek.get(s);G&&(x(G.bytes),n.dek.delete(s));}return {send:e,plain:e,encrypted:false,omit:!r,files:Ir?"decrypt":void 0}}if(on(n,l))return {send:e,plain:e,encrypted:false,omit:false};if(n.ready&&!n.unlocking)try{await n.ready;}catch{}if(!r)return {send:e,plain:e,encrypted:false,omit:true};if(Jt.call(this,e))throw new a("This record's data could not be decrypted by this session, so it cannot be written back. Writing it would replace the record with the placeholder.",{code:"ENCRYPTION_CANNOT_REWRITE_WITHHELD"});if(n.status!=="unlocked"||!n.mk)throw new a("Encryption is enabled but locked, so this private record cannot be written. Call unlockEncryption({ password }) first, or the user must log in with their password.",{code:"ENCRYPTION_LOCKED"});if(e&&typeof e=="object"&&!Array.isArray(e)&&Object.prototype.hasOwnProperty.call(e,We))throw new a(`"${We}" is a reserved key in record data.`,{code:"INVALID_PARAMETER"});if(t?.service&&t.service!==this.service||t?.owner&&t.owner!==this.owner)throw new a("Encrypted records cannot be written to another project. The encryption key is derived per project, so a record written under one service and read under another could never be decrypted. Construct a separate Skapi instance for that project.",{code:"INVALID_REQUEST"});let g=this.user?.user_id;if(!g)throw new a("User login is required to write an encrypted record.",{code:"INVALID_REQUEST"});let f=Ne.call(this),d=false;if(i&&n.roll.has(i)){d=true,n.roll.delete(i);let j=n.dek.get(i);n.dek.delete(i),j&&x(j.bytes);}let p=u;i&&!p&&!n.dek.has(i)&&(p=await me.call(this,i).catch(()=>null)),p&&Ht.call(this,p,i,"making it private");let m=!!p&&!p.encrypted&&!!p.bin&&Object.keys(p.bin).some(j=>(p.bin[j]||[]).some(ee=>ee&&!ee.encrypted)),h=null;if(i&&!d&&(h=n.dek.get(i)||null,!h)){let j=p||u||await me.call(this,i);if(j&&(s=j.record_id||i,h=n.dek.get(s)||null,!o&&j.unique_id&&(o=j.unique_id),!h&&j.encrypted?.status==="failed"))throw new a(`Cannot update encrypted record "${i}": its current contents could not be decrypted (${j.encrypted.reason}), so its existing key wraps cannot be preserved. Updating anyway would revoke everyone it is shared with.`,{code:"ENCRYPTION_LOCKED"})}s===i&&h&&h.rid&&(s=h.rid),!o&&h&&h.anch==="uid"&&h.uid&&(o=h.uid);let _,w,b;if(h){if(h.own&&h.own!==g)throw new a(`Record "${i}" belongs to another user (${h.own}). Encryption only operates on records you own.`,{code:"ENCRYPTION_NOT_RECORD_OWNER"});_=h.bytes,w=h.key,b=Object.assign({},h.recipients);}else {let j=await $r();_=j.bytes,w=j.key,b={};}let E=o?"uid":s?"rid":"new",k=E==="uid"?o:E==="rid"?s:"",S=Gt(f,g,E,k),O=He(S,g,"mk"),L=await ne(n.mk,_,O);b[g]={t:"mk",iv:C(L.iv),ct:C(L.ct)},h&&(h.anch!==E||zt(h)!==k)&&(b=await po.call(this,n,_,b,f,g,E,k,S));let V=K(JSON.stringify(e===void 0?null:e)),v=await ne(w,V,S);x(V);let D={[We]:tn,enc:"A256GCM",kw:"ECDH-ES+A256GCM",anch:E,uid:o,rid:s,own:g,iv:C(v.iv),ct:C(v.ct),k:b},F,M,Te=D.ct;s&&Te.length>lo&&(F=$(Te),D.ct="",D.ct_ref=uo,h&&h.ctRef&&(M=h.ctRef));let Fe=JSON.stringify(D).length;if(Fe>2*1024*1024)throw new a(`Encrypted record data is too large: once encrypted and base64 encoded it becomes ${Fe} bytes, over the ${2*1024*1024} byte limit. Encryption costs about 33% plus roughly 230 bytes per additional recipient.`,{code:"ENCRYPTED_DATA_TOO_LARGE"});return s&&n.dek.set(s,{bytes:_,key:w,recipients:b,anch:E,uid:o,rid:s,own:g,access_group:"private"}),{send:D,plain:e,encrypted:true,omit:false,spill:F,retireCt:M,dek:{bytes:_,key:w,recipients:b,anch:E,uid:o,rid:s,own:g,access_group:"private"},files:m?"encrypt":void 0}}function un(e,t){let r=N.call(this);!r||!t||!e||r.dek.has(e)||r.dek.set(e,Object.assign({},t,{rid:e}));}async function po(e,t,r,n,i,s,o,c){let l=Object.keys(r).filter(f=>f!==i);if(!l.length)return r;let u=await sr.call(this,l),g={[i]:r[i]};for(let f of l){let d=u[f];d&&(g[f]=await dn.call(this,t,d,n,o,i,f,c));}return g}async function dn(e,t,r,n,i,s,o){let c=an(r,n,i,s,t.fpr),l=He(o,s,t.fpr),u=await jr(t.pubRaw,e,c,l);return {t:"ecdh",epk:C(u.epk),iv:C(u.iv),ct:C(u.ct),fpr:t.fpr}}async function fn(e,t){if(!ft(e))return {value:e};if(t.access_group!=="private")return {value:e};let r=N.call(this);if(!r)return {value:null,flag:{status:"failed",reason:"ENCRYPTION_DISABLED"}};if(r.rawRead)return {value:e};if(on(r,t.table_name))return {value:e};if(e[We]!==tn)return {value:Z(r.cfg,"UNSUPPORTED_VERSION"),flag:{status:"failed",reason:"UNSUPPORTED_VERSION"}};if(r.ready&&!r.unlocking)try{await r.ready;}catch{}if(e.own!==t.user_id)return {value:Z(r.cfg,"BINDING_MISMATCH"),flag:{status:"failed",reason:"BINDING_MISMATCH"}};if(e.uid&&t.unique_id&&e.uid!==t.unique_id)return {value:Z(r.cfg,"BINDING_MISMATCH"),flag:{status:"failed",reason:"BINDING_MISMATCH"}};if(e.rid&&t.record_id&&e.rid!==t.record_id)return {value:Z(r.cfg,"BINDING_MISMATCH"),flag:{status:"failed",reason:"BINDING_MISMATCH"}};let n=this.user?.user_id,i=n?e.k[n]:null;if(!i)return {value:Z(r.cfg,"NOT_A_RECIPIENT",Object.keys(e.k)),flag:{status:"failed",reason:"NOT_A_RECIPIENT",recipients:Object.keys(e.k)}};if(r.status!=="unlocked"||!r.mk)return {value:Z(r.cfg,"NO_SESSION_KEY"),flag:{status:"failed",reason:"NO_SESSION_KEY"}};let s=Ne.call(this),o=zt(e),c=Gt(s,e.own,e.anch,o),l;try{if(i.t==="mk")l=await se(r.mk,$(i.iv),$(i.ct),He(c,n,"mk"));else if(i.t==="ecdh"){if(!r.ikPriv)return {value:Z(r.cfg,"NO_SESSION_KEY"),flag:{status:"failed",reason:"NO_SESSION_KEY"}};l=await Br(r.ikPriv,$(i.epk),$(i.iv),$(i.ct),an(s,o,e.own,n,i.fpr),He(c,n,i.fpr));}else return {value:Z(r.cfg,"UNSUPPORTED_VERSION"),flag:{status:"failed",reason:"UNSUPPORTED_VERSION"}}}catch{return {value:Z(r.cfg,"BAD_KEY"),flag:{status:"failed",reason:"BAD_KEY"}}}let u;try{if(e.ct_ref){if(!t.ctUrl)return x(l),{value:Z(r.cfg,"DATA_UNAVAILABLE"),flag:{status:"failed",reason:"DATA_UNAVAILABLE"}};let p=await go.call(this,t.ctUrl);u=new Uint8Array(await p.arrayBuffer());}else u=$(e.ct);}catch{return x(l),{value:Z(r.cfg,"DATA_UNAVAILABLE"),flag:{status:"failed",reason:"DATA_UNAVAILABLE"}}}let g,f;try{f=await ie(l),g=await se(f,$(e.iv),u,c);}catch{return x(l),{value:Z(r.cfg,"CORRUPT"),flag:{status:"failed",reason:"CORRUPT"}}}let d;try{d=JSON.parse(Ve(g));}catch{return x(g),x(l),{value:Z(r.cfg,"CORRUPT"),flag:{status:"failed",reason:"CORRUPT"}}}if(x(g),t.record_id){let p=r.dek.get(t.record_id);p?(p.bytes=l,p.key=f,p.recipients=e.k,p.anch=e.anch,p.uid=e.uid,p.own=e.own,p.access_group="private",p.ctRef=e.ct_ref||""):r.dek.set(t.record_id,{bytes:l,key:f,recipients:e.k,anch:e.anch,uid:e.uid,rid:t.record_id,own:e.own,access_group:"private",ctRef:e.ct_ref||""});}else x(l);return {value:d,flag:{status:"encrypted",recipients:Object.keys(e.k)}}}function Qe(e,t){let[r,n]=e.split("/");return K(`${Y}|kek|${r}|${n}|${t}`)}function Ge(e,t,r,n){let[i,s]=e.split("/");return K(`${Y}|mk|${i}|${s}|${t}|PBKDF2-SHA256|${r}|${n}`)}function gn(e,t){let[r,n]=e.split("/");return K(`${Y}|recovery|${r}|${n}|${t}`)}function pn(e,t,r){let[n,i]=e.split("/");return K(`${Y}|rk|${n}|${i}|${t}|HKDF-SHA256|${r}`)}function hn(e,t){let[r,n]=e.split("/");return K(`${Y}|self|${r}|${n}|${t}`)}function yn(e,t){let[r,n]=e.split("/");return K(`${Y}|ik|${r}|${n}|${t}`)}async function gt(e){let r=((await this.getRecords({table:{name:e.cfg.table,access_group:"private"},index:{name:"$user_id",value:this.user.user_id,condition:"="}},{limit:2}))?.list||[]).filter(n=>n.user_id===this.user.user_id);return r.length?(r.sort((n,i)=>n.uploaded-i.uploaded),r[0]):null}async function Zt(e,t,r){let n=X(je),i=Hr(n),s=X(16),o=C(s),c=await Bt(n,s,gn(e,t)),l=await ne(c,r,pn(e,t,o));return x(n),{code:i,wrap:{id:C(X(6)),p:"recovery",kdf:{a:"HKDF-SHA256",s:o},iv:C(l.iv),ct:C(l.ct),created:Date.now()}}}async function ho(e,t,r,n){let i=Wr(n),s=(r||[]).filter(o=>o.p==="recovery");s.sort((o,c)=>(c.created||0)-(o.created||0));for(let o of s)try{let c=await Bt(i,$(o.kdf.s),gn(e,t)),l=await se(c,$(o.iv),$(o.ct),pn(e,t,o.kdf.s));return x(i),l}catch{}return x(i),null}async function yo(e,t,r,n,i){let s=X(16),o=C(s),c=await Ue(n,s,e.cfg.iterations,Qe(t,r)),l=await ne(c,i,Ge(t,r,e.cfg.iterations,o));return {id:C(X(6)),p:"password",kdf:{a:"PBKDF2-SHA256",it:e.cfg.iterations,s:o},iv:C(l.iv),ct:C(l.ct),created:Date.now()}}async function mo(e,t){let r=this.user.user_id,n=e.scope,i=X(16),s=C(i),o=await Ue(t,i,e.cfg.iterations,Qe(n,r)),c=X(32),l=await ne(o,c,Ge(n,r,e.cfg.iterations,s)),u=await ie(c),g=await Vr(),f=await ne(u,g.pkcs8,yn(n,r));x(g.pkcs8);let d=null;e.cfg.recovery==="code"&&(d=await Zt(n,r,c));let p=await ne(u,c,hn(n,r));x(c);let m=await qt(g.pubRaw),h=Date.now(),_=[{id:C(X(6)),p:"password",kdf:{a:"PBKDF2-SHA256",it:e.cfg.iterations,s},iv:C(l.iv),ct:C(l.ct),created:h}];d&&_.push(d.wrap);let w={v:1,alg:"ECDH-P-256",user_id:r,wraps:_,ik:{iv:C(f.iv),ct:C(f.ct)},self:{iv:C(p.iv),ct:C(p.ct)},pub:C(g.pubRaw),fpr:m,pins:null,created:h,updated:h};await this.postRecord({v:1,alg:"ECDH-P-256",user_id:r,pub:C(g.pubRaw),fpr:m,created:h},{table:{name:e.cfg.table,access_group:"authorized"},index:{name:"pubkey",value:r}});let b=await this.postRecord(w,{table:{name:e.cfg.table,access_group:"private"}}),E=await gt.call(this,e);if(E&&E.record_id!==b.record_id){await mn.call(this,e,E,t);return}e.mk=u,e.ikPriv=g.priv,e.pubRaw=g.pubRaw,e.fpr=m,e.keyringRecordId=b.record_id,d&&(e.pendingRecoveryCode=d.code),e.user_id=r,e.pins={},e.status="unlocked",e.reason="";}async function mn(e,t,r){let n=this.user.user_id,i=e.scope,s=t.data;if(t.user_id!==n||s&&s.user_id&&s.user_id!==n)throw new a("The encryption keyring does not belong to this user.",{code:"ENCRYPTION_KEYRING_CORRUPT"});let c=(Array.isArray(s?.wraps)?s.wraps:[]).filter(g=>g.p==="password");if(!c.length)throw new a("The keyring has no password wrap.",{code:"ENCRYPTION_KEYRING_CORRUPT"});c.sort((g,f)=>(f.created||0)-(g.created||0));let l=null;for(let g of c)try{let f=$(g.kdf.s),d=await Ue(r,f,g.kdf.it,Qe(i,n));l=await se(d,$(g.iv),$(g.ct),Ge(i,n,g.kdf.it,g.kdf.s));break}catch{}if(!l)throw new a("Incorrect password: the encryption keyring could not be opened.",{code:"ENCRYPTION_BAD_PASSWORD"});let u=await ie(l);x(l),await er.call(this,e,t,u);}async function er(e,t,r){let n=this.user.user_id,i=t.data,s=await se(r,$(i.ik.iv),$(i.ik.ct),yn(e.scope,n)),o=await Vt(s);x(s);let c={};if(i.pins&&typeof i.pins=="object"&&i.pins.ct)try{let l=await se(r,$(i.pins.iv),$(i.pins.ct),K(`${Y}|pins|${e.scope}|${n}`));c=JSON.parse(Ve(l)),x(l);}catch{c={};}e.mk=r,e.ikPriv=o,e.pubRaw=$(i.pub),e.fpr=i.fpr,e.keyringRecordId=t.record_id,e.user_id=n,e.pins=c,e.status="unlocked",e.reason="";}async function pt(e){let t=N.call(this);if(!t||!this.user?.user_id)return;if(!$t()){t.status="locked",t.reason="NO_WEB_CRYPTO";return}if(this.user?.is_openid){t.status="locked",t.reason="OPENID_UNSUPPORTED";return}if(t.cfg.minPasswordLength&&e.length<t.cfg.minPasswordLength){t.status="locked",t.reason="WEAK_PASSWORD";return}t.scope=Ne.call(this);let r=await gt.call(this,t);r?await mn.call(this,t,r,e):await mo.call(this,t,e),t.cfg.persistDevice&&await An.call(this,t).catch(()=>{});}async function bn(e){await this.__connection;let t=N.call(this);if(!t)throw new a("Encryption is not enabled for this instance.",{code:"INVALID_REQUEST"});if(!this.user?.user_id)throw new a("User login is required.",{code:"INVALID_REQUEST"});if(!e?.password||typeof e.password!="string")throw new a('"password" is required.',{code:"INVALID_PARAMETER"});if(await pt.call(this,e.password),t.status!=="unlocked")throw new a(`Encryption could not be unlocked: ${t.reason}`,{code:"ENCRYPTION_LOCKED"});return {status:t.status}}async function _n(e){let t=N.call(this);return t?(e?.forgetDevice&&await ir.call(this,t).catch(()=>{}),Qt.call(this),this.__cached_requests={},{status:t.status}):{status:"disabled"}}async function wn(e,t){let r=N.call(this);if(!r)return;if(r.status!=="unlocked"||!r.mk)throw new a("Encryption must be unlocked before changing the password, or the encryption keyring would be left wrapped under a password that no longer exists. Call unlockEncryption({ password }) first.",{code:"ENCRYPTION_LOCKED"});let i=(await this.getRecords({record_id:r.keyringRecordId},{limit:1}))?.list?.[0];if(!i)throw new a("The encryption keyring could not be read, so the password change was stopped before it could strand it.",{code:"ENCRYPTION_KEYRING_CORRUPT"});let s=this.user.user_id,o=i.data,c=(o.wraps||[]).filter(h=>h.p==="password");c.sort((h,_)=>(_.created||0)-(h.created||0));let l=null;for(let h of c)try{let _=await Ue(e,$(h.kdf.s),h.kdf.it,Qe(r.scope,s));l=await se(_,$(h.iv),$(h.ct),Ge(r.scope,s,h.kdf.it,h.kdf.s));break}catch{}if(!l)throw new a("Incorrect current password: the encryption keyring was not re-wrapped.",{code:"ENCRYPTION_BAD_PASSWORD"});let u=X(16),g=C(u),f=await Ue(t,u,r.cfg.iterations,Qe(r.scope,s)),d=await ne(f,l,Ge(r.scope,s,r.cfg.iterations,g));x(l);let p=Date.now(),m=(o.wraps||[]).concat([{id:C(X(6)),p:"password",kdf:{a:"PBKDF2-SHA256",it:r.cfg.iterations,s:g},iv:C(d.iv),ct:C(d.ct),created:p}]);await this.postRecord(Object.assign({},o,{wraps:m,updated:p}),{record_id:r.keyringRecordId});}async function En(){let e=N.call(this);if(!e||e.status!=="unlocked"||!e.keyringRecordId)return;let r=(await this.getRecords({record_id:e.keyringRecordId},{limit:1}))?.list?.[0];if(!r)return;let n=r.data,i=(n.wraps||[]).filter(o=>o.p==="password").sort((o,c)=>(c.created||0)-(o.created||0)),s=(n.wraps||[]).filter(o=>o.p!=="password");i.length<=1||await this.postRecord(Object.assign({},n,{wraps:[i[0]].concat(s),updated:Date.now()}),{record_id:e.keyringRecordId});}function tr(){return typeof indexedDB<"u"&&!!indexedDB}function rr(){return new Promise((e,t)=>{let r=indexedDB.open(co,1);r.onupgradeneeded=()=>{let n=r.result;n.objectStoreNames.contains(be)||n.createObjectStore(be);},r.onsuccess=()=>e(r.result),r.onerror=()=>t(r.error);})}function nr(e){return `${e.scope}#${this.user?.user_id}`}async function An(e){if(!tr()||!e.mk)return;let t=await rr();await new Promise((r,n)=>{let i=t.transaction(be,"readwrite");i.objectStore(be).put({mk:e.mk,keyringRecordId:e.keyringRecordId,saved:Date.now()},nr.call(this,e)),i.oncomplete=()=>r(),i.onerror=()=>n(i.error);}),t.close();}async function bo(e){if(!tr())return null;let t=await rr(),r=await new Promise((n,i)=>{let o=t.transaction(be,"readonly").objectStore(be).get(nr.call(this,e));o.onsuccess=()=>n(o.result||null),o.onerror=()=>i(o.error);});return t.close(),r&&r.mk?r:null}async function ir(e){if(!tr())return;let t=await rr();await new Promise((r,n)=>{let i=t.transaction(be,"readwrite");i.objectStore(be).delete(nr.call(this,e)),i.oncomplete=()=>r(),i.onerror=()=>n(i.error);}),t.close();}function Rn(){let e=N.call(this);!e||e.ready||(e.unlocking=true,e.ready=_o.bind(this)().catch(()=>false).then(()=>{e.unlocking=false;}));}async function _o(){let e=N.call(this);if(!e||!this.user?.user_id||!e.cfg.persistDevice||!$t())return false;e.scope=Ne.call(this);try{let t=await bo.call(this,e);if(!t)return !1;let r=await gt.call(this,e);return r?(await er.call(this,e,r,t.mk),!0):(await ir.call(this,e).catch(()=>{}),!1)}catch{return e.status="locked",e.reason="NO_SESSION_KEY",false}}async function sr(e){let t=N.call(this);if(!t)throw new a("Encryption is not enabled for this instance.",{code:"INVALID_REQUEST"});let r={},n=[],i=false;for(let s of e){let o=t.peerPub.get(s);o?r[s]=o:n.push(s);}return await Promise.all(n.map(async s=>{let o=t.peerInflight.get(s);o||(o=(async()=>{let u=((await this.getRecords({table:{name:t.cfg.table,access_group:"authorized"},index:{name:"$user_id",value:s,condition:"="}},{limit:10}))?.list||[]).filter(p=>p.user_id===s&&p.data?.pub);if(!u.length)return null;u.sort((p,m)=>m.uploaded-p.uploaded);let g=$(u[0].data.pub),f=await qt(g),d=t.pins[s];if(d&&d!==f)throw new a(`The public key for user "${s}" has changed since it was first seen. This is expected if they reset their account, and is what a key substitution attack also looks like. Verify the new fingerprint out of band, then call pinPeerKey({ user_id, fingerprint }).`,{code:"ENCRYPTION_PEER_KEY_CHANGED"});if(!d){if(t.cfg.trustPolicy==="strict")throw new a(`No pinned key for user "${s}" and trustPolicy is "strict". Pin it first with pinPeerKey().`,{code:"ENCRYPTION_PEER_NOT_PINNED"});t.pins[s]=f,i=true;}return {pubRaw:g,fpr:f}})().finally(()=>t.peerInflight.delete(s)),t.peerInflight.set(s,o));let c=await o;c&&t.peerPub.set(s,c),r[s]=c;})),i&&await Sn.call(this,t).catch(()=>{}),r}async function In(e,t){let r=Ne.call(this),n=e.dek.get(t);if(n)return {entry:n,scope:r};let i=await me.call(this,t);if(!i)throw new a(`Record "${t}" not found.`,{code:"NOT_EXISTS"});if(i.encrypted?.status==="failed"&&i.encrypted.reason==="DATA_UNAVAILABLE")throw new a(`Cannot change sharing on record "${t}": its data could not be read, so whether it is encrypted is unknown. Retry once the record reads normally.`,{code:"ENCRYPTION_DATA_UNAVAILABLE"});if(!i.encrypted)return null;if(i.user_id!==this.user?.user_id)throw new a("Only the record owner can share or revoke an encrypted record, because adding or removing a key wrap means writing the record.",{code:"ENCRYPTION_GRANT_REQUIRES_OWNER"});let s=e.dek.get(i.record_id)||e.dek.get(t);if(!s)throw new a(`Cannot change sharing on record "${t}": its data could not be decrypted`+(i.encrypted.reason?` (${i.encrypted.reason})`:"")+".",{code:"ENCRYPTION_LOCKED"});return {entry:s,scope:r}}async function or(e,t){let r=N.call(this);if(!r)return;let n=await In.call(this,r,e);if(!n)return;let{entry:i,scope:s}=n,o=this.user.user_id;if(i.own!==o)throw new a("Only the record owner can share an encrypted record, because adding a key wrap means writing the record.",{code:"ENCRYPTION_GRANT_REQUIRES_OWNER"});let c=await sr.call(this,t),l=t.filter(d=>!c[d]);if(l.length)throw new a(`These users have no encryption key yet, so they cannot be given access: ${l.join(", ")}. A user's key is created the first time they log in with encryption enabled.`,{code:"ENCRYPTION_RECIPIENT_HAS_NO_KEY"});let u=zt(i),g=Gt(s,i.own,i.anch,u),f=Object.assign({},i.recipients);for(let d of t)d!==o&&(f[d]=await dn.call(this,i.bytes,c[d],s,u,i.own,d,g));await Eo.call(this,r,e,i,f);}async function Pn(e,t){let r=N.call(this);if(!r)return;let n=await In.call(this,r,e);if(!n)return;let{entry:i}=n,s=this.user.user_id;if(i.own!==s)throw new a("Only the record owner can revoke access to an encrypted record.",{code:"ENCRYPTION_GRANT_REQUIRES_OWNER"});let o=Object.keys(i.recipients).filter(u=>u===s?true:t?!t.includes(u):false).filter(u=>u!==s),c=await me.call(this,e);if(!c)throw new a(`Record "${e}" not found.`,{code:"NOT_EXISTS"});wo(c,e);let l={};if(o.length){l=await sr.call(this,o);let u=o.filter(g=>!l[g]);if(u.length)throw new a(`Cannot revoke on record "${e}": these users keep access but their encryption keys could not be read, so re-sharing after the key roll would fail and lock them out: ${u.join(", ")}.`,{code:"ENCRYPTION_RECIPIENT_HAS_NO_KEY"})}r.roll.add(c.record_id||e),await this.postRecord(c.data,{record_id:c.record_id||e,table:{name:c.table.name,access_group:"private"}}),o.length&&await or.call(this,c.record_id||e,o);}function wo(e,t){if(e?.encrypted?.status==="failed")throw new a(`Cannot change sharing on record "${t}": its current data could not be read (${e.encrypted.reason}), so re-writing the record would destroy it.`,{code:"ENCRYPTION_DATA_UNAVAILABLE"})}async function Eo(e,t,r,n){let i=await Ao.call(this,t);if(!i)throw new a(`Cannot change sharing on record "${t}": its stored envelope could not be read.`,{code:"ENCRYPTION_DATA_UNAVAILABLE"});r.recipients=n,e.dek.set(t,r);let s=Object.assign({},i,{k:n});e.passthrough.set(t,s),await this.postRecord(void 0,{record_id:t});}async function Ao(e){let t=N.call(this);if(!t)return null;t.rawRead=true;let r;try{r=(await this.getRecords({record_id:e},{limit:1}))?.list?.[0];}finally{t.rawRead=false;}return r&&ft(r.data)?r.data:null}async function Tn(e){let t=N.call(this);if(!t||t.status!=="unlocked")throw new a("Encryption is locked.",{code:"ENCRYPTION_LOCKED"});t.pins[e.user_id]=e.fingerprint,t.peerPub.delete(e.user_id),await Sn.call(this,t);}async function Sn(e){if(!e.mk||!e.keyringRecordId)return;let r=(await this.getRecords({record_id:e.keyringRecordId},{limit:1}))?.list?.[0];if(!r)return;let n=await ne(e.mk,K(JSON.stringify(e.pins)),K(`${Y}|pins|${e.scope}|${e.user_id}`));await this.postRecord(Object.assign({},r.data,{pins:{iv:C(n.iv),ct:C(n.ct)},updated:Date.now()}),{record_id:e.keyringRecordId});}function kn(){let e=N.call(this);if(!e||!e.pendingRecoveryCode)return null;let t=e.pendingRecoveryCode;return e.pendingRecoveryCode="",t}async function vn(e){await this.__connection;let t=N.call(this);if(!t)throw new a("Encryption is not enabled for this instance.",{code:"INVALID_REQUEST"});if(!this.user?.user_id)throw new a("User login is required. Reset the password and log in first, then use the recovery code.",{code:"INVALID_REQUEST"});if(!e?.code||typeof e.code!="string")throw new a('"code" is required.',{code:"INVALID_PARAMETER"});t.scope=Ne.call(this);let r=this.user.user_id,n=await gt.call(this,t);if(!n)throw new a("This account has no encryption keyring, so there is nothing to recover.",{code:"NOT_EXISTS"});let i=await ho(t.scope,r,n.data?.wraps||[],e.code);if(!i)throw new a("That recovery code did not open the keyring. Check it against the copy you saved when encryption was set up.",{code:"ENCRYPTION_BAD_RECOVERY_CODE"});let s=await ie(i);await er.call(this,t,n,s);let o=false,c=null,l=(n.data?.wraps||[]).slice();if(e.password&&(l=l.filter(u=>u.p!=="password"),l.push(await yo(t,t.scope,r,e.password,i)),o=true),t.cfg.recovery==="code"){let u=await Zt(t.scope,r,i);l=l.filter(g=>g.p!=="recovery"),l.push(u.wrap),c=u.code;}return x(i),await this.postRecord(Object.assign({},n.data,{wraps:l,updated:Date.now()}),{record_id:n.record_id}),t.cfg.persistDevice&&await An.call(this,t).catch(()=>{}),{status:t.status,repaired:o,recoveryCode:c}}async function Un(){await this.__connection;let e=N.call(this);if(!e)throw new a("Encryption is not enabled for this instance.",{code:"INVALID_REQUEST"});if(e.status!=="unlocked"||!e.mk)throw new a("Encryption must be unlocked to issue a recovery code. Only someone who can already decrypt can create one.",{code:"ENCRYPTION_LOCKED"});if(e.cfg.recovery!=="code")throw new a('Recovery codes are disabled for this instance ("recovery" is "none").',{code:"INVALID_REQUEST"});let r=(await this.getRecords({record_id:e.keyringRecordId},{limit:1}))?.list?.[0];if(!r)throw new a("The encryption keyring could not be read.",{code:"ENCRYPTION_KEYRING_CORRUPT"});let n=r.data?.self;if(!n||!n.ct)throw new a("This keyring predates recovery-code rotation and cannot issue a new code. Use unlockWithRecoveryCode() with the existing code, which issues a replacement.",{code:"ENCRYPTION_KEYRING_CORRUPT"});let i=await se(e.mk,$(n.iv),$(n.ct),hn(e.scope,e.user_id)),s=await Zt(e.scope,e.user_id,i);x(i);let o=(r.data.wraps||[]).filter(c=>c.p!=="recovery").concat([s.wrap]);return await this.postRecord(Object.assign({},r.data,{wraps:o,updated:Date.now()}),{record_id:e.keyringRecordId}),{recoveryCode:s.code}}var dt="__skenc__",Nn="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";function Ro(e){if(e===0)return "0";let t="";for(;e>0;)t=Nn[e%62]+t,e=Math.floor(e/62);return t}function Io(e){let t=0;for(let r of e){let n=Nn.indexOf(r);if(n<0)return NaN;t=t*62+n;}return t}function ht(e){if(typeof e!="string")return null;let t=e.lastIndexOf(dt);if(t<0)return null;let r=Io(e.slice(t+dt.length));return Number.isFinite(r)?{key:e.slice(0,t),plainSize:r}:null}function ar(e){try{let t=String(e).split("?")[0].split("/").slice(3);if(t.length<12||t[4]!=="records"||t[7]!=="bin")return null;let r=ht(t[10]);return r?{recordId:t[5],recordOwner:t[3],filename:t[t.length-1],plainSize:r.plainSize}:null}catch{return null}}function Dn(e,t){return {service:this.service,owner:this.owner,recordOwner:t,recordId:e}}async function xn(e,t,r){let n=N.call(this);if(!n||!e)return {key:t,file:r,encrypted:false};let i=n.dek.get(e);if(!i)return {key:t,file:r,encrypted:false};if(ht(t))throw new a(`"${dt}" is reserved in an upload form key.`,{code:"INVALID_PARAMETER"});if(t===ze)return {key:t,file:r,encrypted:false};let s=new Uint8Array(await r.arrayBuffer()),o={n:r.name,t:r.type||"",lm:r.lastModified||0},c=await Xr(i.bytes,s,Dn.call(this,e,i.own),o);return x(s),{key:`${t}${dt}${Ro(r.size)}`,file:new File([c],r.name,{type:"application/octet-stream"}),encrypted:true}}async function Cn(e,t){let r=N.call(this),n=ar(e);if(!r||!n)return t;let i=r.dek.get(n.recordId);if(!i)throw new a(`Cannot open this file: the data key for record "${n.recordId}" is not available. Read the record first, and make sure encryption is unlocked.`,{code:"ENCRYPTION_LOCKED"});let s=new Uint8Array(await t.arrayBuffer());if(!Kt(s))throw new a("This file is marked as encrypted but its contents are not an encrypted container.",{code:"ENCRYPTION_FILE_CORRUPT"});let o=await Zr(i.bytes,s,Dn.call(this,n.recordId,n.recordOwner)),c=o.meta&&o.meta.t||"application/octet-stream";return new Blob([o.bytes],{type:c})}function Po(e){let t=[];for(let r in e?.bin||{})for(let n of e.bin[r]||[])n&&n.encrypted&&t.push({formKey:r,url:n.url,filename:n.filename});return t}function To(e){let t=[];for(let r in e?.bin||{})for(let n of e.bin[r]||[])n&&!n.encrypted&&t.push({formKey:r,url:n.url,filename:n.filename});return t}async function cr(e,t,r){let n=N.call(this);if(!n)return [];let i=await me.call(this,e);if(!i)return [];let s=t==="decrypt"?Po(i):To(i);if(!s.length)return [];let o=[],c=new FormData,l=false;for(let u of s){let g=i.bin[u.formKey].find(d=>d.url===u.url);if(!g||typeof g.getFile!="function")continue;let f=await g.getFile("blob");f&&(c.append(u.formKey,new File([f],u.filename,{type:f.type||"application/octet-stream"})),o.push(u.url),l=true);}if(!l)return [];if(t==="decrypt"){let u=n.dek.get(e);u&&(x(u.bytes),n.dek.delete(e));}return await this.uploadFiles(c,{record_id:e,progress:r}),o}var B=null;function lr(e){let t={tkid:"ticket_id",cond:"condition",stmp:"timestamp",actn:"action",cnt:"count",ttl:"time_to_live",plch:"placeholder",hash:"hash",desc:"description",pmc:"limit_per_user"},r={};for(let n in e)if(n==="tkid"){let i=e[n].split("#");if(i.length===1){r.ticket_id=i[0];continue}r.ticket_id=i[1],r.consume_id=i[2],r.user_id=i[3];let s=i[2].slice(-4);if(r.is_test=s===":CHK",!e.stmp){let o=i[2].slice(0,-4);/^[0-9]+$/.test(o)?r.timestamp=parseInt(o,10):r.timestamp=te(i[2].slice(0,-4));}}else t[n]?r[t[n]]=e[n]:r[n]=e[n];return r}async function Ln(e){if(!e.ticket_id)throw new a("Ticket ID is required.",{code:"INVALID_PARAMETER"});if(!e.method)throw new a('Method is required. Should be either "GET" or "POST"',{code:"INVALID_PARAMETER"});let t=e.ticket_id;await this.__connection;let r=await T.bind(this)(`https://${this.service.slice(0,4)}.${this.customApiDomain}/auth/consume/${this.service}/${this.owner}/${t}`,e?.data||{},{method:e.method,auth:!!e?.auth});return lr(r)}async function Fn(e,t){await this.__connection;let r=await T.bind(this)("ticket",Object.assign({exec:"list"},e||{}),{auth:true,fetchOptions:t});return r.list=r.list.map(lr),r}async function Mn(e,t){await this.__connection;let r=await T.bind(this)("ticket",Object.assign({exec:"consumed"},e||{}),{auth:true,fetchOptions:t});return r.list=r.list.map(lr),r}async function $n(e){return T.bind(this)("register-ticket",Object.assign({exec:"reg"},e),{auth:true})}async function Vn(e){return T.bind(this)("register-ticket",Object.assign({exec:"unreg"},e),{auth:true})}var Do=3600;async function xe(){if(await this.__connection,this.session){let e=Math.floor(Date.now()/1e3),r=this.session.getIdToken().getExpiration();if(r<e+Do){this.log("request:requesting new token",null);try{await z.bind(this)().getSession({refreshToken:!0}),this.log("request:received new tokens",{exp:this.session?.idToken?.payload?.exp,currentTime:e,expiresIn:r-e,token:this.session?.accessToken?.jwtToken,refreshToken:this.session?.refreshToken?.token});}catch(n){throw this.log("request:new token error",n),new a("User login is required.",{code:"INVALID_REQUEST"})}}else this.log("request:tokens",{exp:this.session.idToken.payload.exp,currentTime:e,expiresIn:r-e,token:this.session.accessToken.jwtToken,refreshToken:this.session.refreshToken.token});return this.session?.idToken?.jwtToken}else throw this.log("request:no session",null),ye.bind(this)(),new a("User login is required.",{code:"INVALID_REQUEST"})}function On(e,t){return new Promise((r,n)=>{t.refreshSession(e.getRefreshToken(),(i,s)=>{this.log("getSession:refreshSessionCallback",{refreshErr:i,refreshedSession:s}),i?(ye.bind(this)(),n(i)):s.isValid()?r(s):(ye.bind(this)(),n(new a("Invalid session.",{code:"INVALID_REQUEST"})));});})}function z(){if(!this.userPool)throw new a("User pool is missing",{code:"INVALID_REQUEST"});let e=()=>{let s=B.getSignInUserSession().getIdToken().payload||null,o=$e(s);return this.log("normalized user attribute",o),this.__user=o,o},t=async s=>new Promise((o,c)=>{this.log("getSession:option",s);let{refreshToken:l=false,skipUserUpdateEventTrigger:u=false}=s||{};if(l&&u&&(u=false),B=this.userPool.getCurrentUser(),!B){this.log("getSession:cognitoUser",B),ye.bind(this)(),c(null);return}let g=f=>{let d=f.getIdToken().payload;if(this.log("getSession:respond:sessionAttribute",d),d["custom:service"]!==this.service)throw this.log("getSession:respond","invalid service, signing out"),ye.bind(this)(),new a("Invalid session.",{code:"INVALID_REQUEST"});return this.session=f,e(),u||this._runOnUserUpdateListeners(this.user),this.session};B.getSession((f,d)=>{if(this.log("getSession:getSessionCallback",{err:f,session:d}),!d){ye.bind(this)(),c(new a("Current session does not exist.",{code:"INVALID_REQUEST"}));return}if(f){On.bind(this)(d,B).then(w=>o(g(w))).catch(c);return}let p=Math.floor(Date.now()/1e3),m=d.getIdToken(),h=m.getExpiration(),_=h<p;if(this.log("getSession:currentTime",p),this.log("getSession:idTokenExp",h),this.log("getSession:isExpired",_),this.log("getSession:existingBearerToken",this.bearerToken),this.bearerToken=m.getJwtToken(),_||l||!d.isValid())On.bind(this)(d,B).then(w=>o(g(w))).catch(c);else try{o(g(d));}catch(w){c(w);}});}),r=(s,o)=>{let c=o||s.includes(this.service+"-")?s:this.service+"-"+W.hash(s);return {cognitoUser:new amazonCognitoIdentityJs.CognitoUser({Username:c,Pool:this.userPool}),cognitoUsername:c}};return {getSession:t,authenticateUser:(s,o,c=false,l=false)=>new Promise((u,g)=>{this.__request_signup_confirmation=null,this.__disabledAccount=null;let f=r(s,c),d=f.cognitoUsername,p=new amazonCognitoIdentityJs.AuthenticationDetails({Username:d,Password:o});f.cognitoUser.authenticateUser(p,{newPasswordRequired:(m,h)=>{this.__disabledAccount=null,this.__request_signup_confirmation=d,m["custom:signup_ticket"]==="PASS"||m["custom:signup_ticket"]==="MEMBER"||m["custom:signup_ticket"]==="OIDPASS"?f.cognitoUser.completeNewPasswordChallenge(o,{},{onSuccess:_=>{B=f.cognitoUser,t().then(async w=>{if(N.call(this))try{await pt.bind(this)(o);}catch(b){this.log("encryption:ensureKeyring:failed",b);}u(this.user);});},onFailure:_=>{g(new a(_.message||"Failed to authenticate user.",{code:_.code}));}}):g(new a("User's signup confirmation is required.",{code:"SIGNUP_CONFIRMATION_NEEDED"}));},onSuccess:m=>t({skipUserUpdateEventTrigger:true}).then(async h=>{if(this.__disabledAccount=null,N.call(this))try{await pt.bind(this)(o);}catch(_){this.log("encryption:ensureKeyring:failed",_);}this._runOnLoginListeners(this.user),this._runOnUserUpdateListeners(this.user),u(this.user);}),onFailure:m=>{let h=[],{parsed:_,code:w}=mt(m),b=typeof m?.message=="string"?m.message:"";if(w==="NotAuthorizedException"?b.includes("User is disabled.")?(this.__disabledAccount=d,h=["This account is disabled.","USER_IS_DISABLED"]):l?h=["The account already exists.","ACCOUNT_EXISTS"]:h=["Incorrect username or password.","INCORRECT_USERNAME_OR_PASSWORD"]:w==="UserNotFoundException"?h=["Incorrect username or password.","INCORRECT_USERNAME_OR_PASSWORD"]:w==="UserNotConfirmedException"?(this.__request_signup_confirmation=d,h=["User's signup confirmation is required.","SIGNUP_CONFIRMATION_NEEDED"]):(w==="TooManyRequestsException"||w==="LimitExceededException")&&(h=["Too many attempts. Please try again later.","REQUEST_EXCEED"]),_.code==="SIGNUP_CONFIRMATION_NEEDED"&&(this.__request_signup_confirmation=d),h.length){let E=h[1],k=h[0];g(new a(k,{code:E,cause:m}));}else g(_);}});}),createCognitoUser:r,signup:(s,o,c)=>new Promise((l,u)=>{this.userPool.signUp(s,o,c,null,(g,f)=>{if(g){let{parsed:d,code:p}=mt(g),m=[];p==="UsernameExistsException"?m=["The account already exists.","EXISTS"]:p==="InvalidPasswordException"?m=["Invalid password. Password must be at least 6 characters.","INVALID_PARAMETER"]:p==="InvalidParameterException"?m=[d.message||"Invalid parameter.","INVALID_PARAMETER"]:p==="TooManyRequestsException"||p==="LimitExceededException"?m=["Too many attempts. Please try again later.","REQUEST_EXCEED"]:p==="CodeDeliveryFailureException"?m=["Failed to deliver verification code.","CODE_DELIVERY_FAILURE"]:p==="UserLambdaValidationException"&&(m=[d.message||"Signup validation failed.","INVALID_REQUEST"]),m.length?u(new a(m[0],{code:m[1],cause:g})):u(d);return}l(f);});})}}function mt(e){let t=typeof e?.code=="string"&&e.code.trim()?e.code.trim():"ERROR",n=((typeof e?.message=="string"?e.message:typeof e=="string"?e:"An error occurred.")||"An error occurred.").trim();n||(n="An error occurred.");let i=n.match(/#([A-Za-z0-9_]+)\s*:\s*([\s\S]+)/),s=i?.[1]?.trim()||t,o=i?.[2]?.trim()||n;return {parsed:new a(o,{code:s,cause:e}),code:t}}async function qn(e){await this.__authConnection;let t=e?.refreshToken||false;if(!t)return this.user;try{return await z.bind(this)().getSession(Object.assign({skipUserUpdateEventTrigger:!t,refreshToken:t},e)),this.user}catch{return null}}async function jn(e){await this.__connection,e=y.Params(e,{token:"string",id:"string",merge:o=>{if(o===void 0)return false;if(typeof o=="string")return [o];if(Array.isArray(o)){for(let c of o)if(typeof c!="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 t={token:e.token,id:e.id,merge:e.merge};e.template?.welcome&&(t.template_welcome=e.template.welcome);let r=await T.bind(this)("openid-logger",t),n=r.logger.split("#"),i=this.service+"-"+n[0],s=n[1];return {userProfile:await z.bind(this)().authenticateUser(i,s,true,true),openid:r.openid}}function xo(e){let t=typeof globalThis<"u"?globalThis:void 0;if(t?.Buffer)return t.Buffer.from(e,"base64").toString("utf8");if(typeof atob=="function"){let r=atob(e),n=new Uint8Array(r.length);for(let i=0;i<r.length;i++)n[i]=r.charCodeAt(i);return typeof TextDecoder<"u"?new TextDecoder().decode(n):r}throw new Error("No base64 decoder available in this environment")}function Co(e){let t=e.split(".");if(t.length!==3)throw new Error("Invalid JWT format");let n=t[1].replace(/-/g,"+").replace(/_/g,"/"),i=xo(n);return JSON.parse(i)}async function Bn(e){await this.__authConnection,this.log("loginWithToken:params",e),e=y.Params(e,{idToken:"string",accessToken:"string",refreshToken:"string"},["idToken"]);let t=Co(e.idToken);if(this.log("loginWithToken:idTokenPayload",t),t["custom:service"]!==this.service)throw new a("Token does not belong to this service.",{code:"INVALID_REQUEST"});let r=Math.floor(Date.now()/1e3);if(t.exp&&t.exp<r)throw new a("Token has expired.",{code:"INVALID_REQUEST"});if(this.__user=$e(t),this.session=null,e.accessToken&&e.refreshToken)try{if(this.session=new amazonCognitoIdentityJs.CognitoUserSession({IdToken:new amazonCognitoIdentityJs.CognitoIdToken({IdToken:e.idToken}),AccessToken:new amazonCognitoIdentityJs.CognitoAccessToken({AccessToken:e.accessToken}),RefreshToken:new amazonCognitoIdentityJs.CognitoRefreshToken({RefreshToken:e.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",t["cognito:username"]);let n={Username:t["cognito:username"],Pool:this.userPool};this.log("loginWithToken:cognitoUserParams",n),B=new amazonCognitoIdentityJs.CognitoUser(n),B.setSignInUserSession(this.session),this.log("loginWithToken:cognitoUserRestored",{cognitoUserType:typeof B,cognitoUserKeys:Object.keys(B||{}),cognitoUser:B});}}catch(n){this.log("loginWithToken:err",n);try{this.log("loginWithToken:err:stringified",JSON.stringify(n));}catch{this.log("loginWithToken:err:stringifyFail",String(n));}try{let i=Object.keys(n||{}),s=Object.getOwnPropertySymbols?Object.getOwnPropertySymbols(n||{}):[],o=Object.getOwnPropertyDescriptors?Object.getOwnPropertyDescriptors(n||{}):{};this.log("loginWithToken:createSessionError:allKeys",{keys:i,symbols:s,descriptors:o});}catch(i){this.log("loginWithToken:createSessionError:allKeysFail",String(i));}}return this._runOnLoginListeners(this.user),this._runOnUserUpdateListeners(this.user),this.user}async function Q(){return await this.__connection,this.__user?.service===this.service?this.__user?.owner===this.host:(await Je.bind(this)(),false)}async function ye(e=false){let t=null;B&&(e?t=new Promise((n,i)=>{B.globalSignOut({onSuccess:s=>{this.log("globalSignOut:success",s),n(s);},onFailure:s=>{this.log("globalSignOut:error",s),i(s);}});}):B.signOut()),Qt.bind(this)();let r={session:null,__startKeyHistory:{},__cached_requests:{},__user:null};t&&(t=await t);for(let n in r)this[n]=r[n];return this._runOnUserUpdateListeners(null),this._runOnLoginListeners(null),t}async function Je(e){await this.__connection;let{data:t}=q(e);return await ye.bind(this)(t?.global),"SUCCESS: The user has been logged out."}async function Kn(){if(!this.__request_signup_confirmation)throw new a("Least one login attempt is required.",{code:"INVALID_REQUEST"});return await T.bind(this)("confirm-signup",{username:this.__request_signup_confirmation})}async function Hn(e=false){if(typeof e=="string")e=y.Url(e);else if(typeof e!="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 T.bind(this)("recover-account",{username:this.__disabledAccount,redirect:e}),"SUCCESS: Recovery e-mail has been sent."}async function ur(e){let t=y.Params(e,{username:"string",email:"string",password:"string"},["password"]);if(await this.__authConnection,t.email)try{y.Email(t.email);}catch{t.username=t.email,delete t.email;}if(!t.username&&!t.email)throw new a('Least one of "username" or "email" is required.',{code:"INVALID_PARAMETER"});return await z.bind(this)().authenticateUser(t.username||t.email,t.password)}async function Wn(e,t){await this.__authConnection;let r={username:"string",password:u=>y.Password(u),email:u=>y.Email(u),name:"string",address:u=>{if(!u)return "";if(typeof u=="string")return u;if(typeof u=="object")return JSON.stringify(u)},gender:"string",birthdate:u=>u?y.Birthdate(u):"",phone_number:u=>u?y.PhoneNumber(u):"",email_public:["boolean",()=>false],address_public:["boolean",()=>false],gender_public:["boolean",()=>false],birthdate_public:["boolean",()=>false],phone_number_public:["boolean",()=>false],access_group:"number",misc:"string",picture:u=>u?y.Url(u):"",profile:u=>u?y.Url(u):"",family_name:"string",given_name:"string",middle_name:"string",nickname:"string",website:u=>u?y.Url(u):""},n=y.Params(e||{},r,["email","password"]);await Je.bind(this)(),t=y.Params(t||{},{email_subscription:u=>{if(typeof u!="boolean")throw new a('"option.email_subscription" should be type: <boolean>.',{code:"INVALID_PARAMETER"});if(!t?.signup_confirmation)throw new a('"option.signup_confirmation" is required for email subscription.',{code:"INVALID_PARAMETER"});return u},signup_confirmation:u=>{let g=u;if(typeof u=="string")g=y.Url(u);else if(typeof u=="boolean")g=u;else throw new a('"option.signup_confirmation" should be type: <string | boolean>.',{code:"INVALID_PARAMETER"});if(g&&!n.email)throw new a('"email" is required for signup confirmation.',{code:"INVALID_PARAMETER"});return g},login:u=>{if(typeof u=="boolean"){if(t.signup_confirmation&&u)throw new a('"login" is not allowed when "option.signup_confirmation" is true.',{code:"INVALID_PARAMETER"});return u}throw new a('"option.login" should be type: boolean.',{code:"INVALID_PARAMETER"})},template:u=>{if(typeof u!="object"||u===null)throw new a('"option.template" should be type: <object>.',{code:"INVALID_PARAMETER"});if(u.signup_confirmation!==void 0){if(typeof u.signup_confirmation!="string"||!u.signup_confirmation)throw new a('"option.template.signup_confirmation" should be a non-empty <string> (template message_id).',{code:"INVALID_PARAMETER"});if(!t?.signup_confirmation)throw new a('"option.signup_confirmation" is required when "option.template.signup_confirmation" is set.',{code:"INVALID_PARAMETER"})}if(u.welcome!==void 0&&(typeof u.welcome!="string"||!u.welcome))throw new a('"option.template.welcome" should be a non-empty <string> (template message_id).',{code:"INVALID_PARAMETER"});return u}});let i=t?.login||false;if(n.signup_confirmation=t?.signup_confirmation||false,n.email_subscription=t?.email_subscription||false,n.email_public&&!n.signup_confirmation)throw new a('"option.signup_confirmation" should be true if "email_public" is set to true.',{code:"INVALID_PARAMETER"});n.service=this.service,n.owner=this.owner;let s=z.bind(this)().createCognitoUser(n.username||n.email);for(let u of ["email_public","address_public","gender_public","birthdate_public","phone_number_public"])n[u]=n[u]?"1":"0";n.access_group&&(n.access_group=n.access_group.toString());let o=(await T.bind(this)("signupkey",{username:s.cognitoUsername,signup_confirmation:typeof n.signup_confirmation=="boolean"?JSON.stringify(n.signup_confirmation):n.signup_confirmation,email_subscription:n.email_subscription,template_confirmation:t?.template?.signup_confirmation||"",template_welcome:t?.template?.welcome||""})).split(":"),c=o.slice(1).join(":"),l=[new amazonCognitoIdentityJs.CognitoUserAttribute({Name:"custom:signup",Value:o[0]}),new amazonCognitoIdentityJs.CognitoUserAttribute({Name:"locale",Value:c.split("#")[1]}),new amazonCognitoIdentityJs.CognitoUserAttribute({Name:"custom:signup_ticket",Value:c})];for(let u in r){let g=["email_public","address_public","gender_public","birthdate_public","phone_number_public","misc","service","owner"];n[u]!==""&&(u==="username"||u==="password"||u==="access_group"||(g.includes(u)?l.push(new amazonCognitoIdentityJs.CognitoUserAttribute({Name:"custom:"+u,Value:n[u]})):l.push(new amazonCognitoIdentityJs.CognitoUserAttribute({Name:u,Value:n[u]}))));}return await z.bind(this)().signup(s.cognitoUsername,n.password,l),n.signup_confirmation?(B=s.cognitoUser,this.__request_signup_confirmation=s.cognitoUsername,"SUCCESS: The account has been created. User's signup confirmation is required."):i?ur.bind(this)({email:n.username||n.email,password:n.password}):"SUCCESS: The account has been created."}async function Qn(){await this.__connection;let e=await T.bind(this)("remove-account",{disable:this.__user.user_id},{auth:true});return await Je.bind(this)(),e}async function Gn(e){await this.__connection;let t=y.Params(e,{email:i=>y.Email(i),code:["number","string"],new_password:i=>y.Password(i)},["email","code","new_password"]),r=t.code,n=t.new_password;return typeof r=="number"&&(r=r.toString()),new Promise(async(i,s)=>{z.bind(this)().createCognitoUser(t.email).cognitoUser.confirmPassword(r,n,{onSuccess:c=>{i("SUCCESS: New password has been set.");},onFailure:c=>{s(new a(c?.message||"Failed to reset password.",{code:c?.code||"ERROR",cause:c}));}});})}async function zn(e,t,r){await this.__connection;let n;if(!B)throw new a("The user has to be logged in.",{code:"INVALID_REQUEST"});if(e==="email"||e==="phone_number"){if(!this.__user.hasOwnProperty(e))throw new a(`No ${e==="email"?"e-mail":"phone number"} to verify`,{code:"INVALID_REQUEST"});if(this.__user?.[`${e}_verified`])return `SUCCESS: "${e}" is verified.`;n=(t?y.Params(t,{code:"string"}):{}).code||"";}else return;let i,s=r?.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,c)=>{let l={onSuccess:u=>{n?z.bind(this)().getSession({refreshToken:true}).then(()=>{this.__user&&(this.__user[e+"_verified"]=true),o(`SUCCESS: "${e}" is verified.`);}).catch(g=>{c(g);}):o("SUCCESS: Verification code has been sent.");},onFailure:u=>{c(new a(u.message||"Failed to request verification code.",{code:u?.code}));}};n?B?.verifyAttribute(e,n,l):(l.inputVerificationCode=null,B?.getAttributeVerificationCode(e,l,i));})}function Jn(e,t){return zn.bind(this)("phone_number",e,t)}function Yn(e,t){return zn.bind(this)("email",e,t)}async function Xn(e,t){await this.__connection;let r=y.Params(e,{email:s=>y.Email(s)},["email"]),n,i=t?.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"});n={template_verification:i};}return new Promise(async(s,o)=>{z.bind(this)().createCognitoUser(r.email).cognitoUser.forgotPassword({onSuccess:l=>{s("SUCCESS: Verification code has been sent.");},onFailure:l=>{let{parsed:u,code:g}=mt(l),f={UserNotFoundException:"NOT_EXISTS",InvalidParameterException:"INVALID_PARAMETER",NotAuthorizedException:"INVALID_REQUEST",LimitExceededException:"REQUEST_EXCEED",TooManyRequestsException:"REQUEST_EXCEED",CodeDeliveryFailureException:"CODE_DELIVERY_FAILURE"}[g]||u.code||g||"ERROR";o(new a(u.message,{code:f,cause:l}));}},n);})}async function Zn(e){if(await this.__connection,!this.session)throw new a("User login is required.",{code:"INVALID_REQUEST"});let t=y.Params(e,{current_password:"string",new_password:"string"});if(!t?.current_password)throw new a('"current_password" is required to change password.',{code:"INVALID_PARAMETER"});if(!t?.new_password)throw new a('"new_password" is required to change password.',{code:"INVALID_PARAMETER"});return y.Password(t.current_password),y.Password(t.new_password),N.call(this)&&await wn.bind(this)(t.current_password,t.new_password),new Promise((r,n)=>{B.changePassword(t.current_password,t.new_password,(i,s)=>{if(i){if(i?.code==="InvalidParameterException")n(new a("Invalid password parameter.",{code:"INVALID_PARAMETER"}));else if(i?.code==="NotAuthorizedException")n(new a("Incorrect password.",{code:"INVALID_REQUEST"}));else if(i?.code==="TooManyRequestsException"||i?.code==="LimitExceededException")n(new a("Too many attempts. Please try again later.",{code:"REQUEST_EXCEED"}));else {let{parsed:o}=mt(i);n(o);}return}N.call(this)&&En.bind(this)().catch(o=>this.log("encryption:prune:failed",o)),r("SUCCESS: Password has been changed.");});})}async function ei(e){if(await this.__connection,!this.session)throw new a("User login is required.",{code:"INVALID_REQUEST"});let t=y.Params(e||{},{user_id:i=>y.UserId(i),email:i=>y.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?y.Birthdate(i):"",phone_number:i=>i?y.PhoneNumber(i):"",email_public:"boolean",phone_number_public:"boolean",address_public:"boolean",gender_public:"boolean",birthdate_public:"boolean",misc:"string",picture:i=>i?y.Url(i):"",profile:i=>i?y.Url(i):"",family_name:"string",given_name:"string",middle_name:"string",nickname:"string",website:i=>i?y.Url(i):""});if(t&&typeof t=="object"&&!Object.keys(t).length)return this.user;t.email&&(t.preferred_username=this.service+"-"+W.hash(t.email));let r=[["email_public","email_verified","User's e-mail should be verified to set"],["phone_number_public","phone_number_verified","User's phone number should be verified to set"]];if(this.__user){for(let i of r)if(t[i[0]]&&!this.__user[i[1]])throw new a(`${i[2]} "${i[0]}" to true.`,{code:"INVALID_REQUEST"})}let n=[];for(let i in t){if(t[i]===this.user[i]){n.push(i);continue}if(["email_public","phone_number_public","address_public","gender_public","birthdate_public","misc"].includes(i)){let o=t[i];typeof o=="boolean"&&(o=o?"1":"0"),t["custom:"+i]=o,n.push(i);}}for(let i of n)delete t[i];if(t.user_id)if(t.user_id===this.user.user_id)delete t.user_id;else return T.bind(this)("admin-edit-profile",{attributes:t},{auth:true});if(t&&typeof t=="object"&&Object.keys(t).length){let i=[];for(let s in t)i.push(new amazonCognitoIdentityJs.CognitoUserAttribute({Name:s,Value:t[s]}));return await new Promise((s,o)=>{B?.updateAttributes(i,(c,l)=>{c&&o([c?.code||c?.name,c?.message||"Failed to update user settings."]),s(l);});}),await z.bind(this)().getSession({refreshToken:true}),this.user}return this.user}async function ti(e,t){e=q(e).data,e||(e={searchFor:"timestamp",condition:">",value:0},t||(t={}),t.ascending=false),await this.__connection;let r={user_id:i=>Array.isArray(i)?i.map(s=>y.UserId(s)):y.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=>y.Birthdate(i),subscribers:"number",timestamp:"number",access_group:"number",approved:"string"},n=["searchFor","value"];if(e=y.Params(e,{searchFor:["user_id","name","email","phone_number","address","gender","birthdate","locale","subscribers","timestamp","access_group","approved"],condition:[">",">=","=","<","<=","gt","gte","eq","lt","lte",()=>"="],value:i=>{let s=r[e.searchFor];if(typeof s=="function")return s(i);if(typeof i!==s)throw new a(`Value does not match the type of "${e.searchFor}" index.`,{code:"INVALID_PARAMETER"});return i},range:i=>{let s=r[e.searchFor];if(typeof s=="function")return s(i);if(typeof i!==s)throw new a(`Range does not match the type of "${e.searchFor}" index.`,{code:"INVALID_PARAMETER"});return i}},n),e?.condition&&e?.condition!=="="&&e.hasOwnProperty("range"))throw new a("Conditions does not apply on range search.",{code:"INVALID_PARAMETER"});if(e.searchFor==="user_id"&&(e.condition!=="="||e.range))throw new a(`Conditions are not allowed on "${e.searchFor}"`,{code:"INVALID_PARAMETER"});if(typeof e?.value=="string"&&!e?.value)throw new a("Value should not be an empty string.",{code:"INVALID_PARAMETER"});if(typeof e?.searchFor=="string"&&!e?.searchFor)throw new a('"searchFor" should not be an empty string.',{code:"INVALID_PARAMETER"});return T.bind(this)("get-users",e,{auth:true,fetchOptions:t})}async function ri(e){await this.__connection;let t=await T.bind(this)("last-verified-email",e,{auth:true});return t.includes("SUCCESS")?(await z.bind(this)().getSession({refreshToken:true}),this.user):t}async function ni(e){return await this.__connection,e=y.Params(e,{username:y.Email,redirect:y.Url},["username"]),await T.bind(this)("request-username-change",e,{auth:true})}var Ce=null,si=typeof SubmitEvent<"u",Lo=typeof HTMLFormElement<"u",Xe=J(),dr=0;function oi(e){if(!e)return null;let t=Number(e);if(Number.isFinite(t))return Math.max(0,t*1e3);let r=Date.parse(e);return Number.isNaN(r)?null:Math.max(0,r-Date.now())}function fr(e,t){return t>0?e/t*100:0}var ii=e=>{let{auth:t,type:r,endpoints:n,stable:i}=e,s=n[0],o=n[1];if(dr++,r==="admin"){let c=Object.entries(s).filter(([l,u])=>l.includes(t?"_private":"_public")&&l!=="get_users_private"&&l!=="service_public"&&typeof u=="string").map(([,l])=>l);if(!c.length)throw new a("No available admin gateways.",{code:"INVALID_REQUEST"});return c[dr%c.length]}if(r==="record"){let c=Object.entries(o).filter(([l,u])=>l.includes(t?"record_private":"record_public")&&typeof u=="string").map(([,l])=>l);if(!c.length)throw new a("No available record gateways.",{code:"INVALID_REQUEST"});return i?c[0]:c[dr%c.length]}throw new a("Invalid gateway type.",{code:"INVALID_REQUEST"})};async function Fo(e,t,r){let n=await Promise.all([this.admin_endpoint,this.record_endpoint]),i=n[0],s=n[1],o=e.split("?"),c=o.length>1?"?"+o[1]:"";switch(e=o[0],e){case "get-users":return i.get_users_private+e+c;case "service":return i.service_public+e+c;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 ii.bind(this)({auth:t,type:"admin",endpoints:n})+e+c;case "post-record":return (t?s.post_private:s.post_public)+e+c;case "get-records":return (t?s.get_private:s.get_public)+e+c;case "del-files":case "del-records":return s.del_private+e+c;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 ii.bind(this)({auth:t,type:"record",endpoints:n,stable:r})+e+c;default:return y.Url(e)+c}}var Ye={};function ai(){Ce&&(Ce.terminate(),Ce=null);}async function T(e,t=null,r,n){this.log("request",{url:e,data:t,options:r,_etc:n||{}}),r=r||{};let{auth:i=false,method:s="post",bypassAwaitConnection:o=false}=r;s=s.toUpperCase();let c=null,l=t?.service||this.service,u=t?.owner||this.owner,g=null,f=await Fo.bind(this)(e,!!i,!!r.stableGateway);if(!o&&(c=await this.__connection,!c))throw new a("Invalid connection. The service could have been disabled, or has a restricted CORS.",{code:"INVALID_REQUEST"});let d=r?.tokenHeaders?.idToken===true;(i||d)&&(g=await xe.bind(this)());let p={},{fetchMore:m=false,progress:h}=r?.fetchOptions||{};if(r?.fetchOptions&&Object.keys(r.fetchOptions).length){for(let v of ["limit","startKey","ascending"])if(r.fetchOptions.hasOwnProperty(v)){if(v==="startKey"&&r.fetchOptions[v]===null)continue;p[v]=r.fetchOptions[v];}p=y.Params(p,{limit:v=>{if(typeof v!="number")throw new a("Fetch limit should be a number.",{code:"INVALID_REQUEST"});if(v>1e3)throw new a("Fetch limit should be below 1000.",{code:"INVALID_REQUEST"});return v},startKey:v=>v,ascending:"boolean"});}let _=n?.ignoreService?{}:{service:l,owner:u};Object.assign(_,p),t=q(t).data,t?t&&typeof t=="object"&&(t=Object.assign(_,t)):t=_;let w=`${s}:${i?"auth":"public"}:${e}`,b=(()=>{if(t&&typeof t=="object"&&Object.keys(t).length&&!(Xe&&t instanceof FormData)){let v=function(D){return typeof D=="object"&&D!==null?Object.keys(D).sort().reduce((F,M)=>(typeof D[M]=="object"&&D[M]!==null?F[M]=v(D[M]):F[M]=D[M],F),{}):D};return W.hash(w+"/"+JSON.stringify(v(t)))}return W.hash(w+"/"+l)})(),{requestKey:E,requestKeyWithStartKey:k}=Mo.bind(this)({params:t,url:e,fetchMore:m,hashedParams:b});if(!E||E&&typeof E=="object")return E;if(this.log("requestKey",k),typeof k=="string"&&Ye[k]instanceof Promise)return this.log("request:returning pending",k),Ye[k];let S={Accept:"*/*"};if(Object.prototype.hasOwnProperty.call(r,"contentType")&&r.contentType!==void 0){let v=r.contentType===null?"application/x-www-form-urlencoded":r.contentType;v&&(S["Content-Type"]=v);}else S["Content-Type"]="application/json";if(g&&(S.Authorization=g),r?.tokenHeaders){let v=(M,Te)=>typeof M=="string"?M:M===true?Te:null,D=v(r.tokenHeaders.accessToken,this.session?.accessToken?.jwtToken||null),F=v(r.tokenHeaders.idToken,this.bearerToken||this.session?.idToken?.jwtToken||g||null);D&&(S["X-Access-Token"]=D),F&&(S["X-Id-Token"]=F);}let L={public_identifier:this.__public_identifier,service:l,owner:u};S["Content-Meta"]=JSON.stringify(L),r.revalidate&&(S["Cache-Control"]="no-cache",S.Pragma="no-cache");let V={headers:S};if(r?.responseType&&(V.responseType=r.responseType),s==="GET"){if(t){let v=[];if(Xe&&t instanceof FormData?v=Array.from(t.entries()).map(([D,F])=>{let M=typeof F=="string"?F:F.name;return encodeURIComponent(D)+"="+encodeURIComponent(M)}):v=Object.keys(t).map(D=>{let F=t[D];return typeof F!="string"&&(F=JSON.stringify(F)),encodeURIComponent(D)+"="+encodeURIComponent(F)}),v.length){let D=f.includes("?")?f.endsWith("?")||f.endsWith("&")?"":"&":"?";f+=D+v.join("&");}}V.body=null;}else if(Xe&&t instanceof FormData)V.body=t;else if(S["Content-Type"]==="application/x-www-form-urlencoded"&&t&&typeof t=="object"){let v=new URLSearchParams;for(let D of Object.keys(t)){let F=t[D];v.append(D,typeof F=="string"?F:JSON.stringify(F));}V.body=v.toString();}else typeof t=="string"?V.body=t:V.body=t?JSON.stringify(t):null;if(V.method=s,Ce===null){let v={batchSize:this.requestBatchSize,breakWhenError:false,onProgress:D=>{this.onBatchProcess.forEach(F=>F(D));}};Ce=new ji__default.default(v);}return this.log("request-opt",V),new Promise((v,D)=>{Ce.add([async()=>{let F=ci.bind(this)(f,V,h);Ye[k]=F;try{let M=Vo.bind(this)({hashedParam:E,requestKeyWithStartKey:k,url:e,fetched:await F});return delete Ye[k],this.log("request:end",M),v(M),M}catch(M){throw delete Ye[k],this.log("request:err",M),D(M),M}}]);})}function Mo(e){let{params:t={},url:r,fetchMore:n=false,hashedParams:i}=e||{};if(t.startKey){if(!(typeof t.startKey=="object"&&Object.keys(t.startKey).length)&&t.startKey!=="start"&&t.startKey!=="end")throw new a(`"${t.startKey}" is invalid startKey key.`,{code:"INVALID_PARAMETER"});t.startKey==="start"&&(n=false,delete t.startKey);}if(!n){if(this.__cached_requests?.[r]?.[i]&&delete this.__cached_requests[r][i],this.__startKeyHistory?.[r]?.[i]){if(Array.isArray(this.__startKeyHistory[r][i])&&this.__startKeyHistory[r][i].length)for(let l of this.__startKeyHistory[r][i]){let u=i+W.hash(l);this.__cached_requests?.[r]&&this.__cached_requests?.[r]?.[u]&&delete this.__cached_requests[r][u];}delete this.__startKeyHistory[r][i];}return {requestKeyWithStartKey:i,requestKey:i}}if(!Array.isArray(this.__startKeyHistory?.[r]?.[i]))return {requestKeyWithStartKey:i,requestKey:i};let s=this.__startKeyHistory[r][i],o=s[s.length-1],c=i;if(o){if(o==="end")return {requestKey:{list:[],startKey:"end",endOfList:true,startKeyHistory:s},requestKeyWithStartKey:c};c+=W.hash(o),t.startKey=JSON.parse(o);}return this.__cached_requests?.[r]?.[c]?{requestKey:this.__cached_requests[r][c],requestKeyWithStartKey:c}:{requestKeyWithStartKey:c,requestKey:i}}function $o(e){let t=r=>r&&typeof r=="object"&&r.encrypted?Object.assign({},r,{data:null}):r;return Array.isArray(e)?e.map(t):e&&typeof e=="object"?Array.isArray(e.list)?Object.assign({},e,{list:e.list.map(t)}):t(e):e}function ci(e,t,r){return new Promise((n,i)=>{let s=new XMLHttpRequest;s.open(t.method||"GET",e);for(var o in t.headers||{})s.setRequestHeader(o,t.headers[o]);t.responseType&&(s.responseType=t.responseType),s.onload=()=>{if(s.status<400)if(t.responseType=="json"||t.responseType=="blob")n(s.response);else {let c=s.responseText;try{c=JSON.parse(c);}catch{}n(c);}else if(s.status===429){let c=s.getResponseHeader("Retry-After"),l=oi(c);l!==null?setTimeout(()=>{ci(e,t,r).then(n,i);},l):i("Too many requests");}else {let c=s.status,l=["INVALID_CORS","INVALID_REQUEST","SERVICE_DISABLED","INVALID_PARAMETER","ERROR","EXISTS","NOT_EXISTS"],u=t.responseType=="blob"?s.response:s.responseText;try{u=JSON.parse(u);}catch{}if(typeof u=="string"){let g=u.split(":"),f=g.splice(0,1)[0].trim(),d=g.join(":").trim();i(new a(d||u,{code:l.includes(f)?f:"ERROR"}));}else if(typeof u=="object"&&u?.message){let g=u?.code||(c?c.toString():null)||"ERROR",f=u.message,d=u?.cause;typeof f=="string"&&(f=f.trim()),i(new a(f,{cause:d,code:g}));}else i(u);}},s.onerror=()=>i("Network error"),s.onabort=()=>i("Aborted"),s.ontimeout=()=>i("Timeout"),typeof r=="function"&&(s.onprogress=c=>{r({status:"download",progress:fr(c.loaded,c.total),loaded:c.loaded,total:c.total,abort:()=>s.abort()});},s.upload&&(s.upload.onprogress=c=>{r({status:"upload",progress:fr(c.loaded,c.total),loaded:c.loaded,total:c.total,abort:()=>s.abort()});})),s.send(t.body);})}function Vo(e){let{hashedParam:t,requestKeyWithStartKey:r,url:n,fetched:i}=e;if(!i?.startKey)return i;this.__startKeyHistory.hasOwnProperty(n)||(this.__startKeyHistory[n]={}),this.__startKeyHistory[n].hasOwnProperty(t)||(this.__startKeyHistory[n][t]=[]);let s=i.startKey==="end"?"end":JSON.stringify(i.startKey);return this.__startKeyHistory[n][t].includes(s)||this.__startKeyHistory[n][t].push(s),this.__cached_requests?.[n]||(this.__cached_requests[n]={}),this.__cached_requests[n][r]=i,Object.assign({startKeyHistory:this.__startKeyHistory[n][t]},i)}async function Ze(e,t){await this.__connection;let{record_id:r,service:n=this.service,progress:i}=t;if(!r)throw new a('"record_id" is required.',{code:"INVALID_PARAMETER"});if(si&&e instanceof SubmitEvent&&(e=e.target),Lo&&e instanceof HTMLFormElement&&(e=new FormData(e)),!Xe||!(e instanceof FormData))throw new a('"fileList" should be a FormData or HTMLFormElement.',{code:"INVALID_PARAMETER"});let o={reserved_key:Ee(),service:n,request:"post"};t?.record_id&&(o.id=t.record_id);let c,l=(p,m,h)=>new Promise((_,w)=>{c=new XMLHttpRequest,c.open("POST",p),c.onload=()=>{let b=c.responseText;try{b=JSON.parse(b);}catch{}if(c.status>=200&&c.status<300)_(b);else if(c.status===429){let E=c.getResponseHeader("Retry-After"),k=oi(E);k!==null?setTimeout(()=>{l(p,m,h).then(_,w);},k):w("Too many requests");}else w(b);},c.onerror=()=>w("Network error"),c.onabort=()=>w("Aborted"),c.ontimeout=()=>w("Timeout"),c.upload&&typeof h=="function"&&(c.upload.onprogress=h),c.send(m);});function u(p){let m="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";if(p===0)return m[0];let h="";for(;p>0;)h=m[p%62]+h,p=Math.floor(p/62);return h}let g=[],f=[],d=[];for(let[p,m]of e.entries()){if(!(m instanceof File))continue;let h=await xn.bind(this)(r,p,m),_=h.file,w=h.key,b=Object.assign({key:w+"/"+_.name,sizeKey:u(_.size),contentType:_.type||null},o),{fields:E=null,url:k,cdn:S}=await T.bind(this)("get-signed-url",b,{auth:!!this.__user});d.push(S);let O=new FormData;for(let L in E)O.append(L,E[L]);O.append("file",_);try{await l(k,O,typeof i=="function"?L=>i({status:"upload",progress:fr(L.loaded,L.total),currentFile:m,completed:g,failed:f,loaded:L.loaded,total:L.total,abort:()=>c.abort()}):null),g.push(m);}catch{f.push(m);}}return {completed:g,failed:f,bin_endpoints:d}}var bt={};function P(e){let{preventMultipleCalls:t=false}=e||{};return function(r,n,i){let s=i.value;i.value=function(...o){let c=o[0],l=true,u=null,g="",f={},d=false;if(si&&c instanceof SubmitEvent){c.preventDefault();let w=window.location.href;u=c.target;let b=new URL(u.action);g=b.href;let E=g?g.match(/(?<=\{).*?(?=\})/g):"";if(E)for(let k of E){if(!k)continue;let S=u.querySelector(`[name="${k}"]`);if(S)if(S.type==="file")for(let O=0;O<=S.files.length-1;O++)S.files[O]&&(f[k]||(f[k]=[]),f[k].push(new Promise((L,V)=>{let v=new FileReader;v.onload=function(){L(v.result);},v.readAsDataURL(S.files[O]),v.onerror=V;})));else g=g.replace(`{${k}}`,S.value);}u.getAttribute("action")===null?l=false:d=b.href===w;}let p=async w=>{if(g)for(let b in f)f[b].length&&(g=g.replace(`{${b}}`,(await Promise.all(f[b])).join(",")));if(u&&l){let b=N.call(this)?$o(w):w;window.sessionStorage.setItem(`${this.service}:${W.hash(g)}`,JSON.stringify(b)),d?window.location.replace(g):window.location.href=g;}return w},m,h=w=>{throw w instanceof a?w.name=n+"()":w=w instanceof Error?w:new a(w,{name:n+"()"}),w},_=async()=>{try{if(m=s.bind(this)(...o),m instanceof Promise){let w=await m;return p(w)}return p(m)}catch(w){throw h(w)}};if(t){let w=`${n}:${this?.__public_identifier||""}:${this?.service||""}:${this?.owner||""}`;return bt?.[w]||(bt[w]=_().finally(()=>{delete bt[w];})),bt[w]}return _()};}}async function li(){await this.__connection;let e=`${this.service}:${W.hash(window.location.href.split("?")[0])}`,t=window.sessionStorage.getItem(e);if(window.sessionStorage.removeItem(e),t!==null){try{t=JSON.parse(t);}catch{}return t}return null}var qo=256,jo=256,Bo=256,ui=256,Ko="\u{10FFFF}",Ho=/[\u0000-\u001F\u007F]|\u{10FFFF}/u,Wo={"/":"%2F","!":"%21","*":"%2A","#":"%23"},Qo={"%2F":"/","%21":"!","%2A":"*","%23":"#"};function Go(e){return e.replace(/%/g,"%25").replace(/[\/!*#]/g,r=>Wo[r]||r)}function oe(e){return typeof e!="string"?e:e.replace(/%(2F|21|2A|23)/gi,r=>{let n=r.toUpperCase();return Qo[n]||r}).replace(/%25/gi,"%")}function le(e,t,r={}){let{allowEmpty:n=false,maxLength:i,blockKeyDelimiters:s=false,disallowLeadingDollar:o=false,onlyAlphanumeric:c=false}=r;if(typeof e!="string")throw new a(`"${t}" should be type: <string>.`,{code:"INVALID_PARAMETER"});if(c&&/[^a-zA-Z0-9]/.test(e))throw new a(`"${t}" should only contain alphanumeric characters.`,{code:"INVALID_PARAMETER"});if(!n&&e.length===0)throw new a(`"${t}" is required.`,{code:"INVALID_PARAMETER"});if(i&&e.length>i)throw new a(`"${t}" should be <= ${i} characters.`,{code:"INVALID_PARAMETER"});if(Ho.test(e)||e.includes(Ko))throw new a(`"${t}" cannot include control characters or unsupported sentinel characters.`,{code:"INVALID_PARAMETER"});if(s&&(e=Go(e),i&&e.length>i))throw new a(`"${t}" should be <= ${i} characters. "/", "!", "*", "#" and "%" count as 3 characters each.`,{code:"INVALID_PARAMETER"});if(o&&e.startsWith("$"))throw new a(`"${t}" cannot start with "$".`,{code:"INVALID_PARAMETER"});return e}function Oe(e,t="table.name",r={}){return le(e,t,{allowEmpty:r.allowEmpty===true,maxLength:qo,blockKeyDelimiters:true})}function wt(e,t="tag",r={}){return le(e,t,{allowEmpty:r.allowEmpty===true,maxLength:jo,blockKeyDelimiters:true})}function et(e,t="index.name",r={}){return le(e,t,{allowEmpty:r.allowEmpty===true,maxLength:Bo,blockKeyDelimiters:true,disallowLeadingDollar:true})}function di(e,t="index.value"){return le(e,t,{allowEmpty:true,maxLength:ui})}function gr(e){return typeof e=="string"&&e.slice(-1)==="."}function pr(e,t){return le(e,t,{allowEmpty:true,maxLength:ui,blockKeyDelimiters:true})}function fi(e){if(!e.record_id&&!e.unique_id)return null;let t={};return e?.service&&(t.service=e.service),e?.owner&&(t.owner=e.owner),e?.record_id?t.record_id=le(e.record_id,"record_id",{allowEmpty:false,onlyAlphanumeric:true}):e?.unique_id&&(t.unique_id=e.unique_id),t}function hr(e){if(e===void 0)return 0;if(typeof e=="number"){if(e>99||e<0)throw new a('"table.access_group" value should be within a range of 0 ~ 99.',{code:"INVALID_REQUEST"})}else if(typeof e=="string"){if(e={private:"private",public:0,authorized:1,admin:99}[e],e===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&&e)throw new a("Unsigned users have no access to records with access group.",{code:"INVALID_REQUEST"});return e}var _t=4503599627370496;function Et(e){if(typeof e=="number"){if(e>_t||e<-_t)throw new a(`Number value should be within range -${_t} ~ +${_t}`,{code:"INVALID_PARAMETER"});return e}if(typeof e=="boolean")return e;if(typeof e=="string")return di(e,"index.value");throw new a('"index.value" should be type: <number | boolean | string>.',{code:"INVALID_PARAMETER"})}function gi(e,t){if(!t.index||!("value"in t.index))throw new a('"index.value" is required.',{code:"INVALID_PARAMETER"});if(t.index.name==="$record_id")throw new a(`Cannot do "index.range" on ${t.index.name}`,{code:"INVALID_PARAMETER"});if(typeof t.index.value!=typeof e)throw new a('"index.range" type should match the type of "index.value".',{code:"INVALID_PARAMETER"});return typeof e=="string"?gr(t.index.name)?pr(e,"index.range"):di(e,"index.range"):e}var At={},zo=10080*60,Jo=3600,pi=2;function Yo(e,t){if(!t)return String(pi);let r=Math.max(60,e-300)*1e3;return "g"+pi+"w"+Math.floor(Date.now()/r)}function Xo(e){if(!this.user?.user_id)return false;let t=e[6]==="**"?"**":parseInt(e[6]),r=this.user?.access_group??-1;return !(this.user.user_id!==e[3]&&(t==="**"||r<t))}function Zo(e){if(typeof e=="string"){if(e.startsWith("!J%"))try{return JSON.parse(e.substring(3))}catch{return e}return e==="!D%{}"?{}:e==="!L%[]"?[]:e}if(e&&typeof e=="object"&&!Array.isArray(e)&&typeof e.__json__=="string"&&Object.keys(e).length===1)try{return JSON.parse(e.__json__)}catch{}return e}async function hi(e){return typeof e=="string"?e:e&&typeof e.text=="function"?await e.text():await new Promise((t,r)=>{try{let n=new FileReader;n.onload=()=>t(n.result),n.onerror=()=>r(n.error||new Error("Failed to read blob")),n.readAsText(e);}catch(n){r(n);}})}async function Pe(e,t,r=false,n=false,i=false){let s={user_id:"",record_id:"",updated:0,uploaded:0,readonly:false,table:{name:"",access_group:0,subscription:{is_subscription_record:false,upload_to_feed:false,notify_subscribers:false,feed_referencing_records:false,notify_referencing_records:false}},referenced_count:0,source:{referencing_limit:null,prevent_multiple_referencing:false,can_remove_referencing_records:false,only_granted_can_reference:false},ip:"",bin:{}},o=false,c=[],l=null;function u(d){let p=d=="**"?"private":parseInt(d);return p=p==0?"public":p==1?"authorized":p==99?"admin":p,p}let g={ip:d=>{let p=d.split("#"),m=p[0];p.length>1&&(s.unique_id=p.slice(1).join("#")),m.slice(-1)==="R"?(s.readonly=true,m=m.slice(0,-1)):s.readonly=false,/^\d{1,3}-\d{1,3}-\d{1,3}-\d{1,3}$/.test(m)&&(m=m.split("-").join("."),o=true),s.ip=m;},rec:d=>{if(!d)return;s.record_id=d;let p=d.substring(0,d.length-9),m=te(p);s.uploaded=m;},usr:d=>{s.user_id=d;},tbl:d=>{if(d&&!s.table.name){let p=d.split("/");s.table.name=oe(p[0]),s.table.access_group=u(p[2]),p?.[3]&&(s.table.subscription.is_subscription_record=true);}},usr_tbl:d=>{let p=d.split("/");s.user_id||(s.user_id=p[0]),s.table.name||(s.table.name=oe(p[1]),s.table.access_group=u(p[3]),p?.[4]&&(s.table.subscription.is_subscription_record=true));},idx:d=>{if(!d)return;let p=d.split("!"),m=oe(p.splice(0,1)[0]),h=ea("!"+p.join("!"));s.index={name:m,value:h};},ref:d=>{d&&(s.reference=d.split("/")[0]);},tags:d=>{s.tags=Array.isArray(d)?d.map(p=>oe(p)):d;},upd:d=>{s.updated=d;},acpt_mrf:d=>{s.source.prevent_multiple_referencing=!d;},ref_limt:d=>{s.source.referencing_limit=d;},rfd:d=>{s.referenced_count=d;},bin:async d=>{let p={},m=s?.reference||null;if(Array.isArray(d)){let h=await Promise.all(d.map(async _=>{try{let w=_.split("/").slice(3).join("/"),b=w.split("/");if(b.length<12)return null;let E=b[b.length-1],k=b[10];if(k==="__data__"&&E==="__json__.json")return {isDataFile:!0,rawUrl:_};if(Yt(k,E))return {isDataFile:!0,rawUrl:_};let S=ht(k),O=b[9],L=b[8],V=u(b[6]),v=_,D=V!=="public"&&Xo.call(this,b)?{expires:Jo,browserCache:zo}:null;if(V!=="public"&&!i)try{v=await Ie.bind(this)(_,{dataType:"endpoint",_ref:m});}catch(M){console.error("Error getting signed url for private file:",M),v=_;}let F={access_group:V,filename:E,url:v,path:w,size:S?S.plainSize:te(O),uploaded:te(L),getFile:(M,Te)=>{let Fe={dataType:M||"download",progress:Te,_ref:m},j=()=>Ie.bind(this)(v,Object.assign({},Fe,{_update:F}));return D?Ie.bind(this)(_,Object.assign({},Fe,D)).catch(()=>j()):j()}};return S&&(F.encrypted=!0,F.stored_size=te(O)),{pathKey:S?S.key:k,obj:F}}catch{return null}}));for(let _ of h)if(_&&!_.isDataFile){if(p[_.pathKey]){p[_.pathKey].push(_.obj);continue}p[_.pathKey]=[_.obj];}}s.bin=p;},prv_acs:d=>{for(let p in d)["notify_subscribers","upload_to_feed","feed_referencing_records","notify_referencing_records"].includes(p)?s.table.subscription[p]=d[p]:p==="referencing_index_restrictions"&&Array.isArray(d[p])?s.source[p]=d[p].map(h=>h&&typeof h=="object"&&typeof h.name=="string"?Object.assign({},h,{name:oe(h.name)}):h):s.source[p]=d[p];},data:async d=>{let p={access_group:s.table.access_group,table_name:s.table.name,user_id:s.user_id,record_id:s.record_id,unique_id:s.unique_id,ctUrl:l},m=()=>{N.call(this)&&(s.encrypted={status:"failed",reason:"DATA_UNAVAILABLE"});},h=async w=>{if(n||!N.call(this)&&!ft(w))return w;let b=await fn.bind(this)(w,p);return b.flag&&(s.encrypted=b.flag),b.value},_=Zo(d);if(_!==d){s.data=await h(_);return}if(d&&typeof d=="object"&&!Array.isArray(d)&&typeof d.__data__=="string"&&Object.keys(d).length===1&&d.__data__.endsWith("/__data__/__json__.json")){let w=d.__data__,b=c.find(E=>E.endsWith(w))||null;if(!b&&!r&&m(),b){if(r){s.data=d;return}try{let E=await Ie.bind(this)(b,{dataType:"blob",_ref:s.reference||null}),k=await hi(E);s.data=await h(JSON.parse(k));}catch(E){console.error("Failed to fetch offloaded record data:",E),s.data=null,m();}return}}s.data=await h(d);}};if(e.record_id)return e;if(Array.isArray(e.bin))for(let d of e.bin)try{if(typeof d!="string")continue;let p=d.split("/").slice(3);p.length>=12&&p[10]==="__data__"&&p[p.length-1]==="__json__.json"&&c.push(d),p.length>=12&&Yt(p[10],p[p.length-1])&&(l=d);}catch{}let f=[];for(let d in g)if(e.hasOwnProperty(d)){let p=g[d](e[d]);p instanceof Promise&&f.push(p);}return o&&(s.user_id="anonymous:"+s.user_id),await Promise.all(f),s}function ea(e){let t=e.substring(3);switch(e.substring(0,3)){case "!S%":return t;case "!N%":let n=t.split("."),i=Number(n[0])-4503599627370496;return n.length===1?i:parseFloat(i.toString()+"."+n[1]);case "!B%":return t==="1";case "!L%":case "!D%":try{return JSON.parse(t)}catch{throw new a("Value parse error.",{code:"PARSE_ERROR"})}default:return e}}async function yi(e){let{endpoints:t}=e;if(typeof t=="string"&&(t=[t]),!Array.isArray(t))throw new a('"endpoints" should be type: array | string.',{code:"INVALID_PARAMETER"});let r=await T.bind(this)("del-files",{endpoints:t,storage:"records"},{auth:true,method:"post"}),n=[];for(let i in r)n.push(Pe.bind(this)(r[i]));return Promise.all(n)}async function Ie(e,t){if(typeof e!="string")throw new a('"url" should be type: string.',{code:"INVALID_PARAMETER"});let r=e,n=e.split("?"),i=n.shift()||"",s=n.length?"?"+n.join("?"):"",o=y.Url(i);e=o+s;let c=false,l=o.split("/"),g=l[2].split("."),f=null;g.length===3&&g[1]==="skapi"&&(f=g[0],c=true);let d=l.slice(3),p=false;if(!c&&(d[0]==="auth"||d[0]==="publ"))try{y.UserId(d[2]),y.UserId(d[3]),p=d[0]=="auth",c=!0;}catch{throw new a("Invalid file url.",{code:"INVALID_PARAMETER"})}let m=f?null:d[1];if(t=y.Params(t,{expires:["number",()=>0],browserCache:["number",()=>0],refresh:["boolean",()=>false],dataType:["base64","blob","endpoint","text","info",()=>"download"],progress:["function","undefined",null],_ref:[null,"string"],_update:E=>E}),t?.dataType==="info")return {url:e,filename:d[d.length-1],fileKey:d[d.length-2],access_group:d[6]==="**"?"private":d[6]==="01"?"authorized":d[6]==="00"?"public":parseInt(d[6]),uploader:d[3],record_id:d[4]==="records"?d[5]:"N/A",filesize:te(d[9]),uploaded:te(d[8])};let h=e.split("/").slice(-1)[0],_=t.expires;if(_){if(!c)throw new a("Expires option can only be used on skapi cdn endpoints.",{code:"INVALID_PARAMETER"});if(_<0)throw new a('"config.expires" should be > 0. (seconds)',{code:"INVALID_PARAMETER"});let E={request:f?"get-host":"get",id:f||d[5],key:r.split("?")[0],expires:_};m&&(E.service=m);let k=t.browserCache,S={auth:true};if(k){if(k<0)throw new a('"config.browserCache" should be > 0. (seconds)',{code:"INVALID_PARAMETER"});S.method="get",S.stableGateway=true,E.browser_cache=k;let O=this.session?.idToken?.payload?.sub||this.user?.user_id;O&&(E.uid=O),E.nocache=Yo(_,t.refresh);}e=(await T.bind(this)("get-signed-url",E,S)).url;}else if(p){let E=Math.floor(Date.now()/1e3);if(!this.bearerToken&&(!this.session?.idToken?.payload?.exp||this.session.idToken.payload.exp<E)){this.log("getFile:requesting new token",null);try{await z.bind(this)().getSession({refreshToken:!0}),this.log("getFile:received new tokens",{exp:this.session?.idToken?.payload?.exp,currTime:E,expiresIn:this.session?.idToken?.payload?.exp-E,token:this.session?.accessToken?.jwtToken,refreshToken:this.session?.refreshToken?.token});}catch(L){throw this.log("getFile:new token error",L),new a("User login is required.",{code:"INVALID_REQUEST"})}}let k=this.bearerToken||this.session?.idToken?.jwtToken;if(!k||!this.user?.user_id)throw new a("User login is required.",{code:"INVALID_REQUEST"});e+=`${e.includes("?")?"&":"?"}t=${encodeURIComponent(k)}`;let S=d[6]==="**"?"**":parseInt(d[6]),O=this.user?.access_group??-1;if(this.user.user_id!==d[3]&&(S==="**"||O<S)){let L=d[5];if(this.__private_access_key[L]&&typeof this.__private_access_key[L]=="string")e+=`&p=${encodeURIComponent(this.__private_access_key[L])}`;else if(this.owner!==this.host)try{let V=await this.requestPrivateRecordAccessKey({record_id:L,reference_id:t?._ref});e+=`&p=${encodeURIComponent(V)}`;}catch{}}}if((N.call(this)?ar(e):null)&&t?.dataType!=="endpoint"&&t?.dataType!=="info"){let E=await T.bind(this)(e,null,{method:"get",contentType:null,responseType:"blob",fetchOptions:{progress:t?.progress}},{ignoreService:true}),k=await Cn.bind(this)(e,E);if(t?.dataType==="blob")return k;if(t?.dataType==="text")return await hi(k);if(t?.dataType==="base64")return await new Promise((L,V)=>{let v=new FileReader;v.onloadend=()=>L(v.result),v.onerror=()=>V(v.error),v.readAsDataURL(k);});let S=URL.createObjectURL(k),O=document.createElement("a");return O.href=S,document.body.appendChild(O),O.setAttribute("download",h),O.click(),document.body.removeChild(O),setTimeout(()=>URL.revokeObjectURL(S),6e4),null}if(t?.dataType==="endpoint")return t._update&&(t._update.url=e),e;if(t?.dataType==="download"){let E=document.createElement("a");return E.href=e,document.body.appendChild(E),E.setAttribute("download",h),E.target="_blank",E.click(),document.body.removeChild(E),null}return new Promise(async(E,k)=>{try{let S=await T.bind(this)(e,null,{method:"get",contentType:null,responseType:t?.dataType==="text"?"text":"blob",fetchOptions:{progress:t?.progress}},{ignoreService:!0});if(t?.dataType==="base64"){let O=new FileReader;O.onloadend=()=>E(O.result),O.readAsDataURL(S);}else E(S);}catch(S){if(t?.browserCache&&!t?.refresh)try{E(await Ie.bind(this)(r,Object.assign({},t,{refresh:!0})));return}catch(O){k(O);return}k(S);}})}function Rt(e,t){return `${e||this.service}/${t||this.owner}`}function yr(e,t){let r=this.__my_unique_ids[e];return r?r[t]:void 0}function mi(e,t,r){this.__my_unique_ids[e]||(this.__my_unique_ids[e]={}),this.__my_unique_ids[e][t]=r;}function ta(e,t){this.__my_unique_ids[e]&&delete this.__my_unique_ids[e][t];}async function bi(e,t=false){e=q(e,{ignoreEmpty:true}).data||{};let r=Rt.bind(this)(e?.service,e?.owner),n="",i=fi(e);if(i){if(e=i,n=e.record_id||e.unique_id,typeof n=="string"){typeof this.__private_access_key?.[n]=="string"&&(e.private_key=this.__private_access_key?.[n]||void 0);let s=yr.bind(this)(r,n);s&&(t?ta.bind(this)(r,n):e.record_id=s);}}else {let s=await Q.bind(this)(),o=e?.reference,c=false;typeof o=="object"&&Object.keys(o).length&&(o?.record_id||o?.unique_id?(n=o.record_id||o.unique_id,n&&typeof this.__private_access_key?.[n]=="string"&&(e.private_key=this.__private_access_key?.[n]||void 0),e.reference=n):o?.user_id&&(c=o.user_id===this.user?.user_id,e.reference=o.user_id)),typeof e?.table=="string"&&(e.table={name:e.table,access_group:0}),e.index&&e.index.hasOwnProperty("range")&&e.index.hasOwnProperty("condition")&&delete e.index.range;let l=u=>({table:{name:g=>Oe(g,"table.name"),access_group:hr.bind(this),subscription:g=>y.UserId(g,'User ID in "subscription"')},reference:"string",index:{name:["$updated","$uploaded","$referenced_count","$user_id",g=>et(g,"index.name")],value:g=>{let f={$updated:"number",$uploaded:"number",$referenced_count:"number",$user_id:y.UserId};if(f.hasOwnProperty(u.index.name)){let d=f[u.index.name];if(typeof d=="function")return d(g);if(d!==typeof g)throw new a(`"index.value" should be type: ${d}.`,{code:"INVALID_PARAMETER"});return g}return typeof g=="string"&&!g?"":typeof g=="string"&&gr(u.index.name)?pr(g,"index.value"):Et(g)},condition:["gt","gte","lt","lte",">",">=","<","<=","=","eq"],range:g=>gi(g,u)},tag:g=>{if(g==null)return g;if(typeof g=="string")return wt(g,"tag");throw new a('"tag" should be type: string.',{code:"INVALID_PARAMETER"})},private_key:"string"});e=y.Params(e||{},l(e),c||s?[]:["table"],{ignoreEmpty:true});}return {query:e,is_reference_fetch:n}}async function _i(e,t){await this.__connection;let r=await bi.bind(this)(e),n=r.is_reference_fetch,i=await T.bind(this)("get-records",r.query,{fetchOptions:t,auth:!!this.__user,method:this.__user?"post":"get"});n&&i?.reference_private_key&&typeof i.reference_private_key=="string"&&(this.__private_access_key[n]=i.reference_private_key);let s=[];for(let o in i.list)s.push(Pe.bind(this)(i.list[o]));return i.list=await Promise.all(s),i}function wi(e){let t="",r=[],n=Rt.bind(this)(e?.service,e?.owner),i=y.Params(e||{},{record_id:o=>{let c=typeof o=="string"?yr.bind(this)(n,o):void 0;return c||le(o,"record_id",{allowEmpty:false})},unique_id:["string",null],readonly:"boolean",table:{name:o=>Oe(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:hr.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 c={name:u=>et(u,'"name" in "index_restrictions"'),value:u=>Et(u),condition:["gt","gte","lt","lte",">",">=","<","<=","=","eq","!=","ne",()=>null],range:u=>{if(u!==null&&typeof o.value!=typeof u)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 u}};Array.isArray(o)||(o=[o]);let l=o.map(u=>y.Params(u,c,["name"]));if(l.length)for(let u of l)u.condition&&u.hasOwnProperty("range")&&delete u.range;return l}},reference:o=>{if(o===null)return {record_id:null};if(o){if(typeof o=="string"){t=o;let c=yr.bind(this)(n,o);return c||o}if(typeof o!="object")throw new a('"reference" should be type: <string | object>.',{code:"INVALID_PARAMETER"});return y.Params(o,{unique_id:"string",record_id:c=>c==null?c:(t=c,typeof this.__private_access_key?.[c]=="string"&&(e.reference_private_key=this.__private_access_key[c]||void 0),le(c,"reference.record_id",{allowEmpty:false,onlyAlphanumeric:true}))})}},index:[null,{name:o=>et(o,"index.name"),value:o=>Et(o)}],tags:o=>{if(o==null)return o;if(typeof o=="string"&&(o=o.split(",").map(c=>c.trim())),!Array.isArray(o))throw new a('"tag" should be type: <string | string[]>.',{code:"INVALID_PARAMETER"});return o.map(c=>wt(c,"tag"))},remove_bin:o=>{if(!o)return null;let c=[];if(Array.isArray(o))for(let l of o)if(typeof l=="string")c.push(l.split("?")[0]);else if(l.url&&l.size&&l.filename){let g=l.url.split("/").slice(0,3).join("/")+"/"+l.path;c.push(g);}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 c},progress:"function",data:o=>o},[],{precall:o=>{let c=o?.data||{};if(!c?.record_id&&!c.table)throw new a('"table.name" is required.',{code:"INVALID_PARAMETER"});typeof c.table=="string"&&(c.table={name:c.table,access_group:0}),o.files&&(r=o.files);}}),s=e.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:t,files:r}}async function Ei(e){if(await this.__connection,!Array.isArray(e)||!e.length)throw new a('"params" should be a non-empty array.',{code:"INVALID_PARAMETER"});let t=[],r,n,i=null,s={},c={_is_bulk_:await Promise.all(e.map(async(p,m)=>{if(!p||typeof p!="object"||Array.isArray(p))throw new a(`"params[${m}]" should be type: <object>.`,{code:"INVALID_PARAMETER"});let h=wi.bind(this)(p),_=h.config;if(N.call(this)){let w=Object.prototype.hasOwnProperty.call(_,"data"),b=await Xt.bind(this)(_.data,p,w);b.encrypted&&(_.data=b.send,s[m]=b.plain);}if(h.is_reference_post&&t.push(h.is_reference_post),typeof _.progress=="function"&&i===null&&(i=_.progress),_.service!==void 0){if(r===void 0)r=_.service;else if(r!==_.service)throw new a('All bulk params should share the same "service" value.',{code:"INVALID_PARAMETER"})}if(_.owner!==void 0){if(n===void 0)n=_.owner;else if(n!==_.owner)throw new a('All bulk params should share the same "owner" value.',{code:"INVALID_PARAMETER"})}return delete _.progress,delete _.service,delete _.owner,_})),service:"",owner:""};r!==void 0&&(c.service=r),n!==void 0&&(c.owner=n);let l={auth:!!this.__user,method:"post"},u={};Object.keys(u).length&&Object.assign(l,{fetchOptions:u});let g=await T.bind(this)("post-record",c,l),f=await Promise.all(g.map((p,m)=>Pe.bind(this)(p,"called from postRecord",false,s.hasOwnProperty(m))));for(let p=0;p<f.length;p++)s.hasOwnProperty(p)&&f[p]&&!f[p].error&&(f[p].data=s[p],f[p].encrypted={status:"encrypted"});let d=Rt.bind(this)(r,n);for(let p=0;p<g.length;p++){let m=g[p],h=f[p];if(m&&typeof m=="object"&&m.error&&h&&!h.record_id&&(h.error=m.error),typeof m?.reference_private_key=="string")for(let _ of t)this.__private_access_key[_]=m.reference_private_key;h?.unique_id&&mi.bind(this)(d,h.unique_id,h.record_id);}return f}async function mr(e,t,r){if(await this.__connection,!t)throw new a('"config" argument is required.',{code:"INVALID_PARAMETER"});let n=wi.bind(this)(t),i=n.config,s=n.progress,o=n.is_reference_post,c={auth:!!this.__user,method:"post"},l=[],u=q(e);r&&Array.isArray(r)&&r.length&&(l=l.concat(r)),u.files&&Array.isArray(u.files)&&u.files.length&&(l=l.concat(u.files));let g=t?.data!==void 0?t.data:u.data,f=g!==void 0,d=await Xt.bind(this)(g,t,f),p=null;p=Object.assign({},i),delete p.data,d.omit||(p.data=d.send);let m={};if(typeof s=="function"&&(m.progress=s),Object.keys(m).length&&Object.assign(c,{fetchOptions:m}),d.files==="decrypt"&&t?.record_id){let b=await cr.bind(this)(t.record_id,"decrypt",s);if(b.length){let E=p.remove_bin;p.remove_bin=Array.isArray(E)?E.concat(b):b;}}if(d.spill&&t?.record_id){let b=new FormData;if(b.append(ze,new File([d.spill],"payload.bin",{type:"application/octet-stream"})),await Ze.bind(this)(b,{record_id:t.record_id}),d.retireCt){let E=p.remove_bin,k=[d.retireCt];p.remove_bin=Array.isArray(E)?E.concat(k):k;}}let h=await T.bind(this)("post-record",p,c);if(d.encrypted&&h?.rec&&un.bind(this)(h.rec,d.dek),d.files==="encrypt"&&h?.rec)try{let b=await cr.bind(this)(h.rec,"encrypt",s);b.length&&await mr.bind(this)(void 0,{record_id:h.rec,remove_bin:b});}catch(b){console.error("Failed to encrypt existing attachments after making the record private:",b);}if(J()&&l.length){let b=new FormData;for(let S of l)b.append(S.name,S.file,S.file.name);let E={record_id:h.rec,progress:s};i.hasOwnProperty("service")&&(E.service=i.service);let{bin_endpoints:k}=await Ze.bind(this)(b,E);h.bin?h.bin.push(...k):h.bin=k;}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"),w=await Pe.bind(this)(h,"called from postRecord",true,d.encrypted);if(_&&(w.data=u.data),d.encrypted&&(w.data=d.plain,w.encrypted={status:"encrypted",recipients:Object.keys(d.send.k||{})}),w.unique_id){let b=Rt.bind(this)(i?.service,i?.owner);mi.bind(this)(b,w.unique_id,w.record_id),J()&&(this.__uniqueIdsPersistTimer!==null&&clearTimeout(this.__uniqueIdsPersistTimer),this.__uniqueIdsPersistTimer=setTimeout(()=>{this.__uniqueIdsPersistTimer=null;try{window.sessionStorage.setItem(`${b}:uniqueids`,JSON.stringify(this.__my_unique_ids[b]||{}));}catch{}},500));}return w}async function Ai(e,t){let r=await T.bind(this)("get-table",y.Params(e||{},{table:i=>Oe(i,"table",{allowEmpty:true}),condition:["gt","gte","lt","lte",">",">=","<","<=","=","eq","!=","ne"]}),Object.assign({auth:!!this.__user},{fetchOptions:t})),n={cnt_rec:"number_of_records",tbl:"table",srvc:"service",grp_:"number_of_records_in_access_group_"};if(Array.isArray(r?.list))for(let i of r.list){for(let s in n){if(s==="grp_"){for(let o in i)if(o.startsWith("grp_")){let c=o.substring(4);c==="pv"?c="private":c==="00"?c="public":c==="01"?c="authorized":c==="99"&&(c="admin"),i[`number_of_records_in_access_group_${c}`]=i[o],delete i[o];}}i.hasOwnProperty(s)&&(i[n[s]]=i[s],delete i[s]);}typeof i.table=="string"&&(i.table=oe(i.table));}return r}async function Ri(e,t){if(!e?.table)throw new a('"table" is required.',{code:"INVALID_PARAMETER"});let r=y.Params(e||{},{table:s=>Oe(s,"table",{allowEmpty:true}),index:s=>et(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(e?.order?.by==="index_name"&&typeof s=="string")return le(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(r.hasOwnProperty("order")){if(!r.order?.by)throw new a('"order.by" is required.',{code:"INVALID_PARAMETER"});if(r.order.hasOwnProperty("condition")&&!r.order.hasOwnProperty("value"))throw new a('"value" is required for "condition".',{code:"INVALID_PARAMETER"});if(r.hasOwnProperty("index")&&r.index.substring(r.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 n=await T.bind(this)("get-index",r,Object.assign({auth:!!this.__user},{fetchOptions:t})),i={cnt_bool:"boolean_count",cnt_numb:"number_count",totl_numb:"total_number",totl_bool:"total_bool",avrg_numb:"average_number",avrg_bool:"average_bool",cnt_str:"string_count"};return Array.isArray(n?.list)&&(n.list=n.list.map(s=>{let o=s.idx.split("/"),c={table:oe(o[1]),index:oe(o[2]),number_of_records:s.cnt_rec};for(let l in i)Object.prototype.hasOwnProperty.call(s,l)&&(c[i[l]]=s[l]);return c})),n}async function Ii(e,t){let r=await T.bind(this)("get-tag",y.Params(e||{},{table:n=>Oe(n,"table",{allowEmpty:true}),tag:n=>wt(n,"tag",{allowEmpty:true}),condition:["gt","gte","lt","lte",">",">=","<","<=","=","eq","!=","ne"]}),Object.assign({auth:!!this.__user},{fetchOptions:t}));return Array.isArray(r?.list)&&(r.list=r.list.map(n=>{let i=n.tag.split("/");return {table:oe(i[1]),tag:oe(i[0]),number_of_records:n.cnt_rec}})),r}async function Pi(e,t){let r=await T.bind(this)("get-uniqueid",y.Params(e||{},{unique_id:"string",condition:["gt","gte","lt","lte",">",">=","<","<=","=","eq","!=","ne"]}),Object.assign({auth:!!this.__user},{fetchOptions:t}));if(Array.isArray(r?.list))for(let n in r.list){let i=r.list[n];r.list[n]={unique_id:i.unq,record_id:i.rec};}return r}async function Ti(e,t){await this.__connection;let r=await bi.bind(this)(e,true),n=r.is_reference_fetch,i=await T.bind(this)("del-records",r.query,{auth:true,fetchOptions:t});return n&&typeof i?.reference_private_key=="string"&&(this.__private_access_key[n]=i.reference_private_key),Array.isArray(i?.list)&&(i.list=await Promise.all(i.list.map(async s=>{if(!s||typeof s!="object")return s;try{return await Pe.bind(this)(s,"called from deleteRecords",!0,!1,!0)}catch{return s}}))),i?.message||i}async function Si(e){if(N.call(this)){let t=typeof e.user_id=="string"?[e.user_id]:e.user_id;Array.isArray(t)&&t.length&&await or.bind(this)(e.record_id,t);}return Ni.bind(this)({record_id:e.record_id,user_id:e.user_id,execute:"add"})}async function ki(e){let t=await Ni.bind(this)({record_id:e.record_id,user_id:e.user_id||null,execute:"remove"});if(N.call(this)){let r=typeof e.user_id=="string"?[e.user_id]:e.user_id;await Pn.bind(this)(e.record_id,Array.isArray(r)&&r.length?r:null);}return t}async function vi(e,t){let r={record_id:e.record_id||void 0,user_id:e.user_id||void 0,execute:"list"};if(!r.record_id&&!r.user_id)throw new a("Either record_id or user_id must be provided.",{code:"INVALID_PARAMETER"});if(r.user_id)if(typeof r.user_id=="string")y.UserId(r.user_id),r.user_id=[r.user_id];else if(Array.isArray(r.user_id))for(let s of r.user_id)y.UserId(s);else throw new a("user_id should be type: <string | string[]>",{code:"INVALID_PARAMETER"});let n=s=>(s.rec_usr?(s.record_id=s.rec_usr.split("/")[0],s.user_id=s.rec_usr.split("/")[1]):s.usr_rec&&(s.user_id=s.usr_rec.split("/")[0],s.record_id=s.usr_rec.split("/")[1]),s),i=await T.bind(this)("grant-private-access",r,{auth:true,fetchOptions:t});return i.list=i.list.map(n),i}function Ui(e){let t=e.record_id,r=e.reference_id||void 0;if(!t)throw new a("Record ID is required.",{code:"INVALID_PARAMETER"});if(typeof t!="string")throw new a("Record ID should be type: <string | string[]>",{code:"INVALID_PARAMETER"});if(r&&typeof r!="string")throw new a("Reference ID should be type: <string>",{code:"INVALID_PARAMETER"});if(typeof this.__private_access_key[t]=="string")return Promise.resolve(this.__private_access_key[t]);if(At[t])return At[t];let n=T.bind(this)("request-private-access-key",{record_id:t,reference_id:r},{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[t]=s,s}).finally(()=>{delete At[t];});return At[t]=n,n}function Ni(e){e.execute;let r=y.Params(e,{record_id:"string",user_id:n=>{if(!n)throw new a("User ID is required.",{code:"INVALID_PARAMETER"});let i=n;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)y.UserId(s,'User ID in "user_id"');return i},execute:["add","remove"]},["execute","record_id","user_id"]);return r.user_id||(r.user_id=null),T.bind(this)("grant-private-access",r,{auth:true})}var U={},H={},ae={},de={},ue={},It={},Pt={};function Di(e,t,r){e[t]||(e[t]=[]),e[t].push(r);}async function Tt(e,t,r){let n=[];if(e[t]){for(let i of e[t])if(i){let s=r(i);s instanceof Promise&&(s=await s),n.push(s);}delete e[t];}return n}async function _r(e,t){if(!this?.session?.accessToken?.jwtToken)throw new a("Access token is required.",{code:"INVALID_PARAMETER"});let r=await this.__socket;async function n(i,s,o){this.log("answerSdpOffer from",s),await U[s].setRemoteDescription(new RTCSessionDescription(i));let c=await U[s].createAnswer();await U[s].setLocalDescription(c),o.send(JSON.stringify({action:"rtc",uid:s,content:{sdpanswer:c},token:this.session.accessToken.jwtToken}));}U?.[t]?e?(await Tt(Pt,t,i=>n.bind(this)(i,t,r)),await n.bind(this)(e,t,r)):await Tt(Pt,t,i=>n.bind(this)(i,t,r)):e&&Di(Pt,t,e);}async function wr(e,t){if(this.log("receiveIceCandidate",e),U?.[t]&&U[t]?.remoteDescription&&U[t]?.remoteDescription?.type){if(!e)return Tt(It,t,r=>U[t].addIceCandidate(r));await Tt(It,t,r=>U[t].addIceCandidate(r)),await U[t].addIceCandidate(e);}else Di(It,t,e);}async function ce(e){if(typeof window>"u"||window._runningInNodeJS)throw new a("WebRTC is not supported in Node.js environment.",{code:"NOT_SUPPORTED"});y.Params(e,{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 t=await this.__socket,{cid:r,close_all:n=false}=e||{};if(!n&&!r)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 Pt[s],delete It[s],H[s]&&Object.values(H[s]).forEach(o=>{o.readyState!=="closed"&&o.close();}),delete H[s],U?.[s]){U[s].connectionState!=="closed"&&(U[s].close(),t.send(JSON.stringify({action:"rtc",uid:s,content:{hungup:this.user.user_id},token:this.session.accessToken.jwtToken})));let o={type:"connectionstatechange",target:U[s],timestamp:new Date().toISOString(),state:U[s].connectionState,iceState:U[s].iceConnectionState,signalingState:U[s].signalingState};ue[s]&&ue[s](o),this.log("closeRTC",o);}delete ue[s],delete de[s],delete ae[s],delete U[s];};if(n)for(let s in U)i(s);else i(r);this.log("Cleaning up media stream..."),this.__mediaStream&&(this.__mediaStream.getTracks().forEach(s=>{s.stop();}),this.__mediaStream=null);}async function xi(e){if(e instanceof MediaStream)return e;if(!e.video&&!e.audio){let t=new MediaStream,r=document.createElement("canvas");r.width=1,r.height=1;let i=r.captureStream().getVideoTracks()[0];return t.addTrack(i),t}return window.navigator.mediaDevices.getUserMedia(e)}async function Ci(e,t){if(typeof window>"u"||window._runningInNodeJS)throw new a("WebRTC is not supported in Node.js environment.",{code:"NOT_SUPPORTED"});if(typeof t!="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"});e=y.Params(e,{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:r,ice:n}=e;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 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:n}]};U?.[r]||(U[r]=new RTCPeerConnection(s)),e?.media&&(this.__mediaStream=await xi(e.media),this.__mediaStream.getTracks().forEach(o=>{U[r].addTrack(o,this.__mediaStream);})),ue[r]=t,H[r]||(H[r]={});for(let o=0;o<e.channels.length;o++){let c=e.channels[o];if(typeof c=="string")switch(c){case "text-chat":c={ordered:true,maxRetransmits:10,protocol:"text-chat"};break;case "file-transfer":c={ordered:false,maxPacketLifeTime:3e3,protocol:"file-transfer"};break;case "video-chat":c={ordered:true,maxRetransmits:10,protocol:"video-chat"};break;case "voice-chat":c={ordered:true,maxRetransmits:10,protocol:"voice-chat"};break;case "gaming":c={ordered:false,maxPacketLifeTime:100,protocol:"gaming"};break;default:c={ordered:true,maxRetransmits:10,protocol:"default"};break}let l=c.protocol||"default";if(Object.keys(H[r]).includes(l))throw new a(`Data channel with the protocol "${l}" already exists.`,{code:"INVALID_REQUEST"});let u=U[r].createDataChannel(l,c);H[r][l]=u;}for(let o in H[r]){let c=H[r][o];Fi.bind(this)(r,c);}return Li.bind(this)(r,["onnegotiationneeded"]),await br.bind(this)(r),{hangup:()=>ae[r]&&ae[r](false),connection:new Promise(o=>{ae[r]=(c=>{if(this.log("receiver picked up the call",r),!c)return ce.bind(this)({cid:r}),null;U[r].onnegotiationneeded=()=>{this.log("onnegotiationneeded",`sending offer to "${r}".`),br.bind(this)(r),ue[r]&&ue[r]({type:"negotiationneeded",target:U[r],timestamp:new Date().toISOString(),signalingState:U[r].signalingState,connectionState:U[r].iceConnectionState,gatheringState:U[r].iceGatheringState});},o({target:U[r],channels:H[r],hangup:()=>ce.bind(this)({cid:r}),media:this.__mediaStream});}).bind(this);})}}function Oi(e){return async(t,r)=>{t=t||{},t=q(t).data;let n=e.sender_cid,i=await this.__socket;if(!de[n])return null;if(typeof r!="function")throw new a("Callback is required.",{code:"INVALID_PARAMETER"});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{ice:s="stun:stun.skapi.com:3468"}=t;return U?.[n]||(U[n]=new RTCPeerConnection({iceServers:[{urls:s}]})),t?.media&&(this.__mediaStream=await xi(t.media),this.__mediaStream.getTracks().forEach(o=>{U[n].addTrack(o,this.__mediaStream);})),delete de[n],ue[n]=r,H[n]||(H[n]={}),U[n].ondatachannel=o=>{this.log("ondatachannel",`received data channel "${o.channel.label}".`);let c=o.channel;H[n][c.label]=c,Fi.bind(this)(n,c);},Li.bind(this)(n,["onnegotiationneeded"]),await _r.bind(this)(null,n),await wr.bind(this)(null,n),i.send(JSON.stringify({action:"rtc",uid:n,content:{pickup:this.user.user_id},token:this.session.accessToken.jwtToken})),{target:U[n],channels:H[n],hangup:()=>ce.bind(this)({cid:n}),media:this.__mediaStream}}}async function br(e){if(!this?.session?.accessToken?.jwtToken)throw new a("Access token is required.",{code:"INVALID_PARAMETER"});this.log("sendOffer",e);let t=await this.__socket,r=await U[e].createOffer();await U[e].setLocalDescription(r);let n=U[e].localDescription;this.log("rtcSdpOffer to",n),t.send(JSON.stringify({action:"rtc",uid:e,content:{sdpoffer:n},token:this.session.accessToken.jwtToken}));}async function ra(e,t){if(!this?.session?.accessToken?.jwtToken)throw new a("Access token is required.",{code:"INVALID_PARAMETER"});this.log("sendIceCandidate to",t);let r=await this.__socket;if(!e.candidate){this.log("candidate-end","all ice candidates have been sent");return}let n=ue[t]||(()=>{}),i=e.candidate;this.log("ice gathering state set to",U[t].iceGatheringState),n({type:"icecandidate",target:U[t],timestamp:new Date().toISOString(),candidate:e.candidate.candidate,sdpMid:e.candidate.sdpMid,sdpMLineIndex:e.candidate.sdpMLineIndex,usernameFragment:e.candidate.usernameFragment,protocol:e.candidate.protocol,gatheringState:U[t].iceGatheringState,connectionState:U[t].iceConnectionState}),r.send(JSON.stringify({action:"rtc",uid:t,content:{candidate:i},token:this.session.accessToken.jwtToken}));}function Li(e,t){let r=new Set(t),n=ue[e]||(o=>{}),i=U[e],s={ontrack:o=>{n({type:"track",target:i,timeStamp:o.timeStamp,streams:o.streams,track:o.track});},onicecandidate:o=>{ra.bind(this)(o,e),o.candidate?n({type:"icecandidate",target:i,timestamp:new Date().toISOString(),candidate:o.candidate.candidate,sdpMid:o.candidate.sdpMid,sdpMLineIndex:o.candidate.sdpMLineIndex,usernameFragment:o.candidate.usernameFragment,protocol:o.candidate.protocol,gatheringState:i.iceGatheringState,connectionState:i.iceConnectionState}):n({type:"icecandidateend",target:i,timestamp:new Date().toISOString()});},onicecandidateerror:o=>{n({type:"icecandidateerror",target:i,timestamp:new Date().toISOString(),errorCode:o.errorCode,errorText:o.errorText,url:o.url,hostCandidate:o.hostCandidate,gatheringState:i.iceGatheringState,connectionState:i.iceConnectionState});},oniceconnectionstatechange:()=>{n({type:"iceconnectionstatechange",target:i,timestamp:new Date().toISOString(),state:i.iceConnectionState,gatheringState:i.iceGatheringState,signalingState:i.signalingState});},onicegatheringstatechange:()=>{n({type:"icegatheringstatechange",target:i,timestamp:new Date().toISOString(),state:i.iceGatheringState,connectionState:i.iceConnectionState,signalingState:i.signalingState});},onsignalingstatechange:()=>{n({type:"signalingstatechange",target:i,timestamp:new Date().toISOString(),state:i.signalingState,connectionState:i.iceConnectionState,gatheringState:i.iceGatheringState});},onnegotiationneeded:()=>{br.bind(this)(e),n({type:"negotiationneeded",target:i,timestamp:new Date().toISOString(),signalingState:i.signalingState,connectionState:i.iceConnectionState,gatheringState:i.iceGatheringState});},onconnectionstatechange:()=>{n({type:"connectionstatechange",target:i,timestamp:new Date().toISOString(),state:i.connectionState,iceState:i.iceConnectionState,signalingState:i.signalingState});let o=i.connectionState;(o==="disconnected"||o==="failed"||o==="closed")&&ce.bind(this)({cid:e});}};for(let[o,c]of Object.entries(s))r.has(o)||(i[o]=c);}function Fi(e,t,r){let n=new Set(r),i=ue[e]||(o=>{}),s={onmessage:o=>{let c={type:o.type,target:t,timeStamp:o.timeStamp,data:o.data,lastEventId:o.lastEventId,origin:o.origin,readyState:t.readyState,bufferedAmount:t.bufferedAmount};this.log(`${t.label}: message`,o.data),i(c);},onerror:o=>{let c={type:o.type,target:t,timeStamp:o.timeStamp,error:o.error.message,errorCode:o.error.errorDetail,readyState:t.readyState,label:t.label};this.log(`${t.label}: error`,o.error.message),i(c);},onclose:o=>{let c={type:o.type,target:t,timeStamp:o.timeStamp,readyState:t.readyState,label:t.label,id:t.id};this.log(`${t.label}: closed`,null),i(c),H[e]&&(delete H[e][t.label],Object.keys(H[e]).length===0&&ce.bind(this)({cid:e}));},onbufferedamountlow:o=>{let c={target:t,bufferedAmount:t.bufferedAmount,bufferedAmountLowThreshold:t.bufferedAmountLowThreshold,type:o.type,timeStamp:o.timeStamp};this.log(`${t.label}: bufferedamountlow`,t.bufferedAmount),i(c);},onopen:o=>{this.log("dataChannel",`data channel: "${t.label}" is open and ready to send messages.`);let c={type:o.type,target:t,timeStamp:o.timeStamp,readyState:t.readyState,label:t.label,id:t.id,ordered:t.ordered,maxRetransmits:t.maxRetransmits,protocol:t.protocol};i(c);}};for(let[o,c]of Object.entries(s))n.has(o)||(t[o]=c);}var we,_e=null,tt=true,Le=0;async function na(){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 e=await this.record_endpoint;return new WebSocket(e.websocket_private+"?token="+this.session.accessToken.jwtToken)}var Er=null;async function Mi(){if(typeof window>"u"||window._runningInNodeJS)throw new a("WebSocket is not supported in Node.js environment.",{code:"NOT_SUPPORTED"});tt=true;let e=this.__socket?await this.__socket:this.__socket;ce.bind(this)({close_all:true}),we&&Ar.bind(this)({group:null}),Le=0,_e&&(_e.terminate(),_e=null);try{e&&e.close();}catch{}return window.removeEventListener("visibilitychange",Er),this.__socket=null,null}async function St(e,t=50,r){if(typeof window>"u"||window._runningInNodeJS)throw new a("WebSocket is not supported in Node.js environment.",{code:"NOT_SUPPORTED"});if(typeof e!="function")throw new a("Callback must be a function.",{code:"INVALID_REQUEST"});if(r==="reconnect"){if(this.__socket instanceof Promise){let n=await this.__socket;if(n.readyState!==WebSocket.CLOSED&&n.readyState!==WebSocket.CLOSING)return this.__socket}}else if(tt&&(Er=()=>{!document.hidden&&!tt&&St.bind(this)(e,0,"reconnect");},this.__socket instanceof Promise))return this.__socket;_e&&(_e.terminate(),_e=null),this.__socket=new Promise(async n=>{await xe.bind(this)(),setTimeout(async()=>{let i=await na.bind(this)();i.onopen=()=>{tt=false,Le=0,r!=="reconnect"&&window.addEventListener("visibilitychange",Er),this.log("realtime onopen","Connected to WebSocket server."),e({type:"success",message:"Connected to WebSocket server."}),we&&i.send(JSON.stringify({action:"joinRoom",rid:we,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 ps=Object.defineProperty;var hs=Object.getOwnPropertyDescriptor;var de=(e=>t
212
212
  }
213
213
 
214
214
  runInterval(); // Start interval
215
- `,o=new Blob([s],{type:"application/javascript"});me=new Worker(URL.createObjectURL(o)),me.onmessage=a=>{i.readyState===1&&i.send(JSON.stringify({action:"keepAlive"}));},n(i);},i.onmessage=async s=>{let o="";try{o=JSON.parse(decodeURI(s.data)),this.log("socket onmessage",o);}catch{return}let a;switch(true){case !!o?.["#message"]:a="message";break;case !!o?.["#private"]:a="private";break;case !!o?.["#notice"]:a="notice";break;case !!o?.["#rtc"]:a="rtc";break;case !!o?.["#error"]:a="error";break}if(!a)return;let l={type:a,message:o?.["#rtc"]||o?.["#message"]||o?.["#private"]||o?.["#notice"]||o?.["#error"]||null,sender:o?.["#user_id"]||null,sender_cid:o?.["#scid"]?"cid:"+o["#scid"]:null,sender_rid:o?.["#srid"]||null,code:o?.["#code"]||null};if(a==="notice")e(l);else if(a==="rtc"){if(l.sender!==this.user.user_id){let u=l.message;if(u.hungup){ie[l.sender_cid]&&(ie[l.sender_cid](false),delete ie[l.sender_cid]),ce[l.sender_cid]&&delete ce[l.sender_cid],N?.[l.sender_cid]&&se.bind(this)({cid:l.sender_cid}),l.type="rtc:closed",e(l);return}if(u.candidate&&or.bind(this)(u.candidate,l.sender_cid),u.sdpoffer&&(sr.bind(this)(u.sdpoffer,l.sender_cid),ce[l.sender_cid]||(ce[l.sender_cid]=l.sender_cid,delete l.message,l.connectRTC=_i.bind(this)(l),l.type="rtc:incoming",l.hangup=(()=>{N[l.sender_cid]?se.bind(this)({cid:l.sender_cid}):ce[l.sender_cid]&&(delete ce[l.sender_cid],i.send(JSON.stringify({action:"rtc",uid:l.sender_cid,content:{hungup:this.user.user_id},token:this.session.accessToken.jwtToken})));}).bind(this),e(l))),u.pickup&&ie[l.sender_cid]&&(ie[l.sender_cid](true),delete ie[l.sender_cid]),u.sdpanswer&&N[l.sender_cid])if(N[l.sender_cid].signalingState==="have-local-offer")await N[l.sender_cid].setRemoteDescription(new RTCSessionDescription(u.sdpanswer));else throw new c("Invalid signaling state.",{code:"INVALID_REQUEST"})}}else e(l);},i.onclose=()=>{Qe?(this.log("realtime onclose","WebSocket connection closed."),e({type:"close",message:"WebSocket connection closed."})):(this.log("realtime onclose","WebSocket unexpected close."),e({type:"error",message:"Skapi: WebSocket unexpected close."}),Ne++,Ne<3?(this.log("realtime onclose","Reconnecting to WebSocket server..."+Ne),e({type:"reconnect",message:"Reconnecting to WebSocket server..."+Ne}),wt.bind(this)(e,3e3,"reconnect")):(this.log("realtime onclose","Max reconnection attempts reached."),e({type:"error",message:"Skapi: Max reconnection attempts reached."})));},i.onerror=()=>{this.log("realtime onerror","WebSocket connection error."),e({type:"error",message:"Skapi: WebSocket connection error."});};},t);});}async function Ri(e,t,r){if(typeof window>"u"||window._runningInNodeJS)throw new c("WebSocket is not supported in Node.js environment.",{code:"NOT_SUPPORTED"});let n=this.__socket?await this.__socket:this.__socket;if(!n)throw new c("No realtime connection. Execute connectRealtime() before this method.",{code:"INVALID_REQUEST"});if(!t)throw new c("No recipient.",{code:"INVALID_REQUEST"});await Se.bind(this)(),e=V(e).data;let i="";if(r&&(r=p.Params(r,{config:{always:"boolean"},title:"string",body:"string"},["title","body"]),i=JSON.stringify({title:r.title,body:r.body}),new Blob([i]).size>3072))throw new c("Notification size exceeds 3kb.",{code:"INVALID_PARAMETER"});if(n.readyState===1){try{p.UserId(t),n.send(JSON.stringify({action:"sendMessage",uid:t,content:e,notification:i,notificationConfig:r?.config||{},token:`IdT:${this.service}:${this.owner}:`+(this.bearerToken||this.session?.idToken?.jwtToken||"null")}));}catch(s){if(this.log("postRealtime:err",{err:s}),ye!==t)throw new c(`User has not joined to the recipient group. Run joinRealtime({ group: "${t}" })`,{code:"INVALID_REQUEST"});n.send(JSON.stringify({action:"broadcast",rid:t,content:e,notification:i,notificationConfig:r?.config||{},token:`IdT:${this.service}:${this.owner}:`+(this.bearerToken||this.session?.idToken?.jwtToken||"null")}));}return {type:"success",message:"Message sent."}}throw new c("Realtime connection is not open. Try reconnecting with connectRealtime().",{code:"INVALID_REQUEST"})}async function cr(e){if(typeof window>"u"||window._runningInNodeJS)throw new c("WebSocket is not supported in Node.js environment.",{code:"NOT_SUPPORTED"});let t=this.__socket?await this.__socket:this.__socket;if(!t)throw new c("No realtime connection. Execute connectRealtime() before this method.",{code:"INVALID_REQUEST"});await Se.bind(this)(),e=V(e,{nullIfEmpty:true}).data;let{group:r=null}=e;if(!r&&!ye)return {type:"success",message:"Left realtime message group."};if(r!==null&&typeof r!="string")throw new c('"group" must be a string | null.',{code:"INVALID_PARAMETER"});return t.send(JSON.stringify({action:"joinRoom",rid:r,token:this.session.accessToken.jwtToken})),ye=r,{type:"success",message:r?`Joined realtime message group: "${r}".`:"Left realtime message group."}}async function Ii(e,t){e=p.Params(e,{user_id:n=>p.UserId(n,'User ID in "user_id"'),group:["string",()=>{if(!ye)throw new c('No group has been joined. Otherwise "group" is required.',{code:"INVALID_REQUEST"});return ye}]});let r=await P.bind(this)("get-ws-group",e,{fetchOptions:t,auth:true,method:"post"});return r.list=r.list.map(n=>({user_id:n.uid.split("#")[1],cid:"cid:"+n.cid})),r}async function Pi(e,t){if(await this.__connection,e||(e={searchFor:"group",value:" ",condition:">"}),e=p.Params(e,{searchFor:["group","number_of_users",()=>"group"],value:["string","number",()=>e?.searchFor&&e?.searchFor==="number_of_users"?0:" "],condition:[">",">=","=","<","<=","!=","gt","gte","eq","lt","lte","ne"],range:["string","number"]}),e.condition||(e.value===" "||!e.value?e.condition=">":e.condition="="),e.range&&e.condition&&delete e.condition,e.searchFor==="number_of_users"&&typeof e.value!="number")throw new c('"value" must be a number.',{code:"INVALID_PARAMETER"});if(e.searchFor==="group"&&typeof e.value!="string")throw new c('"value" must be a string.',{code:"INVALID_PARAMETER"});if(e.hasOwnProperty("range")&&typeof e.range!=typeof e.value)throw new c(`"range" must be a ${typeof e.value}.`,{code:"INVALID_PARAMETER"});let r=await P.bind(this)("get-ws-group",e,{fetchOptions:t,auth:true,method:"post"});return r.list=r.list.map(n=>({group:n.rid.split("#")[1],number_of_users:n.cnt})),r}var Si=typeof FormData<"u",ki=typeof HTMLFormElement<"u",vi=typeof SubmitEvent<"u",le={},Ge={},ue={};function lr(e){return Object.freeze({id:e,status:"stopped"})}function Ui(e){return !!e&&typeof e=="object"&&e.status==="stopped"}function Ni({id:e,auth:t,service:r,owner:n,latency:i=1e3,queue:s,onResponse:o,onError:a}){if(typeof i!="number")throw new c('"latency" should be a number.',{code:"INVALID_PARAMETER"});if(i<0)throw new c('"latency" should be a non-negative number.',{code:"INVALID_PARAMETER"});s&&!le?.[s]&&(le[s]=new Ti__default.default({breakWhenError:false,batchSize:1}));let l={stop:null,aborted:false,queue:s};ue[e]=l;let u=()=>{ue[e]===l&&delete ue[e];},d=()=>new Promise((g,h)=>{let m=false;if(l.aborted){u(),g(lr(e));return}let y=setInterval(async()=>{try{let b=await P.bind(this)("csr-poll",{id:e,service:r,owner:n},{auth:t});if(b.status==="running"||b.status==="pending"||m)return;m=!0,o&&o(b),clearInterval(y),u(),g(b);}catch(b){if(m)return;m=true,a&&a(b),clearInterval(y),u(),h(b);}},i);l.stop=()=>{m||(m=true,clearInterval(y),u(),g(lr(e)));};}),f=()=>{let g=ue[e];g&&(g.stop?g.stop():(g.aborted=true,delete ue[e]));};if(s){let g=new Promise((h,m)=>{let y=false,b=le[s].add([async()=>{try{let _=await d();return y||(y=!0,h(_)),_}catch(_){throw y||(y=true,m(_)),_}}])[0];Ge[e]=b,l.stop=()=>{if(!y){l.aborted=true;try{le[s]&&le[s].remove(Ge[e]);}catch{}delete Ge[e],u(),y=true,h(lr(e));}};});return Object.assign(g,{stop:f})}else return Object.assign(d(),{stop:f})}function xi(e){let t=0,r=[];if(e?.id){if(e.url&&e.method){let n=e.service||this.service;r.push(`[${e.method.toUpperCase()}]${e.url.toLowerCase()}#${n}:${e.id}`);}r.push(e.id);}else if(e?.queue)for(let n in ue)ue[n]?.queue===e.queue&&r.push(n);else for(let n in ue)r.push(n);for(let n of r){let i=ue[n];i&&(i.stop?i.stop():(i.aborted=true,delete ue[n]),t+=1);}return t}function Di(e,t){if(!e.queue)throw new c('"queue" is required.',{code:"INVALID_PARAMETER"});let r={service:e.service||this.service,owner:e.owner||this.owner,queue:e.queue+":"};return P.bind(this)("csr-poll",r,{auth:true})}async function Ci(e){let t=false;if(typeof e.poll=="number"&&e.poll<0)throw new c('"poll" should be a non-negative number.',{code:"INVALID_PARAMETER"});let r=e?.onResponse,n=e?.onError,i=typeof e.poll=="number"?e.poll:e.poll?1e3:0;delete e.poll,i&&!e.queue&&(e.queue=(this.__user?.user_id||"anonymous")+"-"+be());let s=l=>{for(let u in l)if(typeof l[u]=="string"&&l[u].includes("$CLIENT_SECRET")){t=true;break}};if(e=p.Params(e,{url:l=>{if(!l||typeof l!="string")throw new c('"url" should be type: <string>.',{code:"INVALID_PARAMETER"});return p.Url(l),l.includes("$CLIENT_SECRET")&&(t=true),l},clientSecretName:"string",method:l=>{if(l&&typeof l!="string")throw new c('"method" should be either "GET" or "POST" or "DELETE" or "PUT".',{code:"INVALID_PARAMETER"});let u=l.toLowerCase();if(u!=="get"&&u!=="post"&&u!=="delete"&&u!=="put")throw new c('"method" should be either "GET" or "POST" or "DELETE" or "PUT".',{code:"INVALID_PARAMETER"});return u},headers:l=>{if(l&&typeof l!="object")throw new c('"headers" should be type: <object>.',{code:"INVALID_PARAMETER"});return s(l),l},data:l=>{if(l&&typeof l!="object")throw new c('"data" should be type: <object>.',{code:"INVALID_PARAMETER"});return s(l),l},params:l=>{if(l&&typeof l!="object")throw new c('"params" should be type: <object>.',{code:"INVALID_PARAMETER"});return s(l),l},expires:"number",queue:"string"},["clientSecretName","method","url"]),!t)throw new c(`At least one parameter value should include "$CLIENT_SECRET" in ${e.method.toLowerCase()==="post"?'"data"':'"params"'} or "headers".`,{code:"INVALID_PARAMETER"});await this.__connection;let o=!!this.__user,a=()=>P.bind(this)("csr",e,{auth:o,tokenHeaders:{accessToken:!!o}}).then(l=>{if(l.status==="running"||l.status==="pending"){let u=`[${e.method.toUpperCase()}]${e.url.toLowerCase()}`,d=e.service||this.service,f=e.owner||this.owner,g=`${u}#${d}:${l.id}`;Object.assign(l,{poll:h=>Ni.call(this,{id:g,auth:o,service:d,owner:f,latency:h?.latency||1e3,queue:e?.queue,onResponse:r,onError:n})});}return r?r(l):l}).catch(l=>{if(n)return n(l);throw l});if(e?.queue){let l="base:"+e.queue;return le?.[l]||(le[l]=new Ti__default.default({breakWhenError:false,batchSize:1})),new Promise((u,d)=>{le[l].add([async()=>{try{let f=await a();if(i>0){let g=f.poll({latency:i});return u(g),g}return u(f),f}catch(f){throw d(f),f}}]);})}else return a()}async function Oi(e,t){await this.__connection;let r=e.service||this.service,n=e.owner||this.owner;e=p.Params(e,{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=`[${e.method.toUpperCase()}]${e.url.toLowerCase()}#${r}:`,o={id:s,queue:e?.queue,status:e?.status,service:r,owner:n};e?.compact&&(o.compact=true),e?.queue_exact&&(o.queue_exact=true),e?.queue_exclude&&(o.queue_exclude=e.queue_exclude),Object.keys(o).forEach(l=>{o[l]||delete o[l];}),o.queue&&(o.id_prefix=o.id,delete o.id);let a=await P.bind(this)("csr-poll",o,{auth:i,fetchOptions:t});return a.list=a.list.map(l=>{let u={id:l.id,status_code:l.rslv?.status_code||null,response_body:l.rslv?.body||l.rslv?.truncated||null,error:l?.err,created:l?.stmp,updated:l?.utmp,request_body:l?.reqbdy,expires:l?.expt,status:l.stts,queue_name:l?.qid,request_text:l?.reqtxt,response_text:l?.rslvtxt,response_complete_marker:l?.rslvmk!=null?!!l.rslvmk:void 0,compact:l?.cmpct?true:void 0};for(let d in u)u[d]===void 0&&delete u[d];return (u.status==="running"||u.status==="pending")&&(u.poll=d=>Ni.call(this,{id:s+u.id,auth:i,service:r,owner:n,latency:d?.latency||1e3,queue:l?.qid,onResponse:d?.onResponse,onError:d?.onError})),u}),a}async function Li(e){await this.__connection,e=p.Params(e,{url:"string",method:["GET","POST","DELETE","PUT"],id:"string",queue:"string"},["url","method","id"]);let t=e?.service||this.service,r=e?.owner||this.owner,n=!!this.__user,i=`[${e.method.toUpperCase()}]${e.url.toLowerCase()}#${t}`,s=e.id,o=`${i}:${s}`,a=e?.queue;return a&&le?.[a]&&(le[a].remove(Ge[o]),delete Ge[o]),P.bind(this)("csr-cancel",{id:o,service:t,owner:r},{auth:n})}async function Mi(e){await this.__connection;let t={name:"string",email:r=>(p.Email(r),r),subject:"string",message:"string"};return e=p.Params(e,t,["name","email","subject","message"]),await P.bind(this)("send-inquiry",e),"SUCCESS: Inquiry has been sent."}async function Fi(e,t){if(await this.__connection,Si&&e instanceof FormData||ki&&e instanceof HTMLFormElement||vi&&e instanceof SubmitEvent){if(!t)throw new c("Url string as a second argument is required when form is passed.",{code:"INVALID_PARAMETER"});let n=V(e);e={url:t,data:n.data,sync:true};}let r={url:n=>p.Url(n),data:n=>n,sync:["boolean",()=>true]};if(Array.isArray(e))for(let n of e)n=p.Params(n,r);else e=p.Params(e,r);return P.bind(this)("post-secure",e,{auth:true})}async function Vi(e,t){await this.__connection;let{auth:r=false,method:n="POST",bypassAwaitConnection:i=false,responseType:s,contentType:o,tokenHeaders:a,progress:l}=t||{};if(t=Object.assign({auth:r,method:n,bypassAwaitConnection:i,responseType:s,contentType:o,tokenHeaders:a},{fetchOptions:{progress:l}}),typeof e!="object"&&(o==="application/json"||o===void 0))throw new c('"data" should be type: <object>.',{code:"INVALID_PARAMETER"});return P.bind(this)("mock",e,t)}async function $i(e,t){if(await this.__connection,!t?.url||typeof t.url!="string")throw new c('"url" is required in the second argument.',{code:"INVALID_PARAMETER"});p.Url(t.url);let n=(await this.admin_endpoint)?.forward_request;if(!n)throw new c("forwardRequest is not available on this service region yet.",{code:"NOT_EXISTS"});let i=null,s=null,o=vi&&e instanceof SubmitEvent?e.target:ki&&e instanceof HTMLFormElement?e:null;o?i=new FormData(o):Si&&e instanceof FormData?i=e:e!=null&&(i=JSON.stringify(e),s="application/json");let a={public_identifier:this.__public_identifier,service:this.service,owner:this.owner,forward:{url:t.url,method:t.method||"POST",headers:t.headers||{},apiKeyHeader:t.apiKeyHeader,apiKeyScheme:t.apiKeyScheme}},l=JSON.stringify(a).replace(/[\u007f-\uffff]/g,h=>"\\u"+h.charCodeAt(0).toString(16).padStart(4,"0"));if(l.length>4096)throw new c("Destination url and headers are too large for Content-Meta.",{code:"INVALID_PARAMETER"});let u=this.bearerToken||this.session?.idToken?.jwtToken||null;if(!u)throw new c("User login is required.",{code:"INVALID_REQUEST"});let d={"Content-Meta":l,Authorization:u};s&&(d["Content-Type"]=s);let f=await fetch(n,{method:"POST",headers:d,body:i,signal:t.signal});if(t.responseType==="response")return f;if(!f.ok){let h=await f.text();try{h=JSON.parse(h);}catch{}throw new c(h?.message||(typeof h=="string"?h:JSON.stringify(h)),{code:h?.code||"ERROR"})}if(t.onStream&&f.body){let h=f.body.getReader(),m=new TextDecoder,y="";for(;;){let{done:b,value:_}=await h.read();if(b)break;let w=m.decode(_,{stream:true});y+=w;try{t.onStream(w);}catch(T){console.error(T);}}return y}let g=await f.text();if(t.responseType==="text")return g;try{return JSON.parse(g)}catch{return g}}async function qi(e,t){await this.__connection,e=p.Params(e||{},{access_group:n=>{if(n==="authorized"&&(n=1),n==="public"&&(n=0),typeof n!="number")throw new c('"access_group" should be type number.',{code:"INVALID_PARAMETER"});if(n<0)throw new c('"access_group" should be zero or a positive number.',{code:"INVALID_PARAMETER"});if(n>this.__user.access_group)throw new c("User has no access.",{code:"INVALID_REQUEST"});return n}});let r=await P.bind(this)("get-feed",e,{auth:true,fetchOptions:t});for(let n in r.list)r.list[n]=await Ue.bind(this)(r.list[n]);return r}function ze(e){if(e===this.__user.user_id)throw new c(`"user_id" cannot be the user's own ID.`,{code:"INVALID_PARAMETER"});return p.UserId(e,'"user_id"')}async function ji(e,t){if(e=V(e,{ignoreEmpty:true}).data,e=p.Params(e,{subscriber:n=>p.UserId(n,'User ID in "subscriber"'),subscription:ze.bind(this),blocked:"boolean"}),!e.subscriber&&!e.subscription)throw new c('At least either "subscriber" or "subscription" should have a value.',{code:"INVALID_PARAMETER"});let r=await P.bind(this)("get-subscription",e,Object.assign({auth:true},{fetchOptions:t}));return r.list=r.list.map((n=>{let i={};if(n.sub){let s=n.sub.split("#");i.subscriber=s[2],i.subscription=s[0];}else i.subscriber=n.subscriber,i.subscription=n.subscription;return i.timestamp=n?.timestamp||n.stmp,i.blocked=n?.blocked||n.grp.substring(0,1)==="N",Object.assign(i,n.opt),i})),r}async function Bi(e){await this.__connection,e=p.Params(e,{user_id:ze.bind(this),get_feed:["boolean",()=>false],get_notified:["boolean",()=>false],get_email:n=>{if(n&&!this.__user.email||!this.__user.email_verified)throw new c("User has no verified email address.",{code:"INVALID_REQUEST"});return !!n}},["user_id"]);let t=await P.bind(this)("subscription",{subscribe:e.user_id,option:{get_feed:e.get_feed,get_notified:e.get_notified,get_email:e.get_email||false}},{auth:true}),r={};if(t.sub){let n=t.sub.split("#");r.subscriber=n[2],r.subscription=n[0];}else r.subscriber=t.subscriber,r.subscription=t.subscription;return r.timestamp=t?.timestamp||t.stmp,r.blocked=t?.blocked||t.grp.substring(0,1)==="N",Object.assign(r,t.opt),r}async function Ki(e){await this.__connection;let{user_id:t}=p.Params(e,{user_id:ze.bind(this)},["user_id"]);return await P.bind(this)("subscription",{unsubscribe:t},{auth:true})}async function Hi(e){await this.__connection;let{user_id:t}=p.Params(e,{user_id:ze.bind(this)},["user_id"]);return await P.bind(this)("subscription",{block:t},{auth:true})}async function Wi(e){await this.__connection;let{user_id:t}=p.Params(e,{user_id:ze.bind(this)},["user_id"]);return await P.bind(this)("subscription",{unblock:t},{auth:true})}async function Qi(e,t){await this.__connection;let r=await W.bind(this)();e=p.Params(e,{user_id:o=>{if(o!==this.__user.user_id&&!r)throw new c("No access.",{code:"INVALID_REQUEST"});return o},group:o=>{if(o==="public"&&(o=0),o==="authorized"&&(o=1),typeof o!="number")throw new c('"group" should be type number | "public" | "authorized".',{code:"INVALID_PARAMETER"});return o}});let n=await P.bind(this)("get-newsletter-subscription",e,{auth:true,fetchOptions:t||null}),i=n?.list||n,s=[];Array.isArray(i)||(i=[]);for(let o of i){let a=o.subt.split("#"),l=true;a[0].charAt(0)==="@"&&(l=false,a[0]=a[0].substring(1));let u=parseInt(a[0]);s.push({timestamp:o.stmp,group:u,subscribed_email:a[1],active:l});}return n?.list?(n.list=s,n):s}async function Gi(e){await this.__connection;let t=p.Params(e||{},{email:r=>Array.isArray(r)&&r.length>0?r.length===1?p.Email(r[0]):r.map(n=>p.Email(n)):p.Email(r),group:["number","public","authorized","admin",r=>{if(typeof r!="string"||r.length>20||!/^[a-zA-Z0-9]+$/.test(r))throw new c('"group" should be an alphanumeric string without spaces and less than 20 characters.',{code:"INVALID_PARAMETER"});return r}],redirect:r=>p.Url(r)},this.__user?["group"]:["email","group"]);return P.bind(this)(`subscribe-${this.__user?"":"public-"}newsletter`,t,{auth:!!this.__user})}async function zi(e){await this.__connection,e=p.Params(e,{group:["number","public","authorized","admin"]},["group"]);let t=Object.assign({action:"unsubscribe"},e);return P.bind(this)("subscribe-newsletter",t,{auth:true})}async function Ji(e,t){let r=await W.bind(this)(),n={message_id:"string",timestamp:"number",read:"number",complaint:"number",subject:"string",bounced:"number"};e||(t=Object.assign({ascending:false},t||{})),e=V(e).data,e=e||{searchFor:"timestamp",value:Date.now(),condition:"<",group:"public"},e=p.Params(e,{searchFor:["message_id","timestamp","subject","complaint","read","bounced"],value:l=>{if(typeof l!==n[e.searchFor])throw new c(`"value" type does not match the type of "${e.searchFor}" index.`,{code:"INVALID_PARAMETER"});if(typeof l=="string"&&!l)throw new c('"value" should not be empty string.',{code:"INVALID_PARAMETER"});return l},range:l=>{if(!e.hasOwnProperty("value")||typeof l!=typeof e.value)throw new c('"range" should match type of "value".',{code:"INVALID_PARAMETER"});return l},condition:[">",">=","=","<","<=","gt","gte","eq","lt","lte",()=>"="],group:l=>{if(l==="public")return 0;if(!this.session)throw new c("User should be logged in.",{code:"INVALID_REQUEST"});if(l==="authorized")return 1;if(typeof l=="number"){if(!r&&l>parseInt(this.user?.access_group||this.session?.idToken?.payload?.access_group))throw new c("User has no access.",{code:"INVALID_REQUEST"});return l}throw new c('"group" should be type: number | "public" | "authorized".',{code:"INVALID_PARAMETER"})}},["searchFor","value","group"]);let i=e.group===0?"get-public-newsletters":"get-newsletters",s=await P.bind(this)(i,e,Object.assign({method:"get",auth:i==="get-public-newsletters"?!!this.__user:true},{fetchOptions:t})),o={message_id:"mid",timestamp:"stmp",complaint:"cmpl",read:"read",subject:"subj",bounced:"bnce",url:"url",delivered:"delv"},a={message_id:"",timestamp:0,complaint:0,read:0,subject:"",bounced:"",url:"",delivered:0};return s.list=s.list.map(l=>{let u={};for(let d in o)u[d]=l[o[d]]||a[d];return u.bounced=String(u.bounced),u}),s}async function Yi(e){let t=p.Params(e,{user_id:n=>p.UserId(n,'"user_id"')},["user_id"]);if(t?.service&&t?.owner?t={service:t?.service,owner:t?.owner,block:t.user_id}:t={block:t.user_id},!await W.bind(this)()){if(!this.__user)throw new c("User needs to login.",{code:"INVALID_REQUEST"});if(this.__user.access_group<90)throw new c("Invalid access.",{code:"INVALID_REQUEST"})}return await P.bind(this)("block-account",t,{auth:true})}async function Xi(e){let t=p.Params(e,{user_id:n=>p.UserId(n,'"user_id"')},["user_id"]);if(t?.service&&t?.owner?t={service:t?.service,owner:t?.owner,unblock:t.user_id}:t={unblock:t.user_id},!await W.bind(this)()){if(!this.__user)throw new c("User needs to login.",{code:"INVALID_REQUEST"});if(this.__user.access_group<90)throw new c("Invalid access.",{code:"INVALID_REQUEST"})}return await P.bind(this)("block-account",t,{auth:true})}async function Zi(e){let t=p.Params(e,{user_id:n=>p.UserId(n,'"user_id"')},["user_id"]);if(t?.service&&t?.owner?t={service:t?.service,owner:t?.owner,delete:t.user_id}:t={delete:t.user_id},!await W.bind(this)()){if(!this.__user)throw new c("User needs to login.",{code:"INVALID_REQUEST"});if(this.__user.access_group<90)throw new c("Invalid access.",{code:"INVALID_REQUEST"})}return await P.bind(this)("remove-account",t,{auth:true})}async function es(e,t){let r={email:s=>p.Email(s),password:s=>p.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=>p.Birthdate(s),phone_number:s=>p.PhoneNumber(s),picture:s=>{if(s)return p.Url(s)},profile:s=>{if(s)return p.Url(s)},website:s=>{if(s)return p.Url(s)},nickname:"string",misc:"string",email_public:["boolean",()=>false],gender_public:["boolean",()=>false],address_public:["boolean",()=>false],birthdate_public:["boolean",()=>false],phone_number_public:["boolean",()=>false],openid_id:"string",access_group:s=>{try{typeof s=="string"&&(s=s==="admin"?99:parseInt(s));}catch{throw new c('"access_group" is invalid. Should be type <number>.',{code:"INVALID_PARAMETER"})}if(typeof s!="number"||s<1||s>100)throw new c('"access_group" is invalid. Should be type <number> of range 1~99',{code:"INVALID_PARAMETER"});return s}},n=p.Params(e,r,["email"]);if(t=p.Params(t,{confirmation_url:s=>{let o=s;if(typeof s=="string")o=p.Url(s);else throw new c('"options.confirmation_url" should be type: <string>.',{code:"INVALID_PARAMETER"});if(o&&!n.email)throw new c('"email" is required for signup confirmation.',{code:"INVALID_PARAMETER"});return o},email_subscription:s=>{if(typeof s!="boolean")throw new c('"options.email_subscription" should be type: <boolean>.',{code:"INVALID_PARAMETER"});if(!t?.confirmation_url)throw new c('"options.confirmation_url" is required for email subscription.',{code:"INVALID_PARAMETER"});return s},template:s=>{if(typeof s!="object"||!s.url||!s.subject)throw new c('"options.template" should be type: <object> with "url" and "subject".',{code:"INVALID_PARAMETER"});return {url:p.Url(s.url),subject:s.subject}}}),n.signup_confirmation=t?.confirmation_url||true,n.email_subscription=t?.email_subscription||false,n.template=t?.template||{},!await W.bind(this)()){if(!this.__user)throw new c("User needs to login.",{code:"INVALID_REQUEST"});if(this.__user.access_group<90)throw new c("Invalid access.",{code:"INVALID_REQUEST"})}return await P.bind(this)("admin-signup",n,{auth:true})}async function ts(e){let t={email:s=>p.Email(s),password:s=>p.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=>p.Birthdate(s),phone_number:s=>p.PhoneNumber(s),picture:s=>s?p.Url(s):"",profile:s=>s?p.Url(s):"",website:s=>s?p.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 c('"access_group" is invalid. Should be type <number>.',{code:"INVALID_PARAMETER"})}if(typeof s!="number"||s<1||s>100)throw new c('"access_group" is invalid. Should be type <number> of range 1~99',{code:"INVALID_PARAMETER"});return s}},r=["email","password"],n=p.Params(e,t,r);if(!await W.bind(this)()){if(!this.__user)throw new c("User needs to login.",{code:"INVALID_REQUEST"});if(this.__user.access_group<90)throw new c("Invalid access.",{code:"INVALID_REQUEST"})}return await P.bind(this)("admin-signup",n,{auth:true})}async function rs(e){if(e=p.Params(e,{user_id:r=>p.UserId(r,'"user_id"'),access_group:r=>{try{typeof r=="string"&&(r=parseInt(r));}catch{throw new c('"access_group" is invalid. Should be type <number>.',{code:"INVALID_PARAMETER"})}if(typeof r=="number"&&r>0&&r<100)return r;throw new c('"access_group" is invalid. Should be type <number> of range 1~99',{code:"INVALID_PARAMETER"})}},["user_id","access_group"]),!await W.bind(this)()){if(!this.__user)throw new c("User needs to login.",{code:"INVALID_REQUEST"});if(this.__user.access_group<90)throw new c("Invalid access.",{code:"INVALID_REQUEST"})}return await P.bind(this)("grant-access",e,{auth:true})}async function ns(e,t){if(e=p.Params(e,{email:"string"}),!await W.bind(this)()){if(!this.__user)throw new c("User needs to login.",{code:"INVALID_REQUEST"});if(this.__user.access_group<90)throw new c("Invalid access.",{code:"INVALID_REQUEST"})}let n=await P.bind(this)("invitation-list",Object.assign({mode:"search"},e),{fetchOptions:t,auth:true});return n.list=n.list.map(i=>xe(i.user)),n}async function is(e){if(e=p.Params(e,{email:r=>p.Email(r)},["email"]),!await W.bind(this)()){if(!this.__user)throw new c("User needs to login.",{code:"INVALID_REQUEST"});if(this.__user.access_group<90)throw new c("Invalid access.",{code:"INVALID_REQUEST"})}return await P.bind(this)("invitation-list",Object.assign({mode:"cancel"},e),{auth:true})}async function ss(e){if(e=p.Params(e,{email:r=>p.Email(r)},["email"]),!await W.bind(this)()){if(!this.__user)throw new c("User needs to login.",{code:"INVALID_REQUEST"});if(this.__user.access_group<90)throw new c("Invalid access.",{code:"INVALID_REQUEST"})}return await P.bind(this)("invitation-list",Object.assign({mode:"resend"},e),{auth:true})}async function os(e){let t=p.Params(e,{user_id:o=>p.UserId(o,'"user_id"'),email:o=>p.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?p.Birthdate(o):"",phone_number:o=>o?p.PhoneNumber(o):"",email_public:"boolean",phone_number_public:"boolean",address_public:"boolean",gender_public:"boolean",birthdate_public:"boolean",misc:"string",picture:o=>o?p.Url(o):"",profile:o=>o?p.Url(o):"",nickname:"string",website:o=>o?p.Url(o):""},["user_id"]),r=t.service,n=t.owner;if(delete t.service,delete t.owner,Object.keys(t).filter(o=>o!=="user_id"&&t[o]!==void 0).length===0)throw new c("At least one attribute to update is required.",{code:"INVALID_PARAMETER"});if(!await W.bind(this)()){if(!this.__user)throw new c("User needs to login.",{code:"INVALID_REQUEST"});if(this.__user.access_group<90)throw new c("Invalid access.",{code:"INVALID_REQUEST"})}t.email&&(t.preferred_username=(r||this.service)+"-"+H.hash(t.email));let s={attributes:t};return r&&n&&(s.service=r,s.owner=n),await P.bind(this)("admin-edit-profile",s,{auth:true})}async function as(e){if(typeof window>"u"||window._runningInNodeJS)throw new c("Push Notifications are not supported in Node.js environment.",{code:"NOT_SUPPORTED"});if(await this.__connection,!e.endpoint)throw new c("Missing parameter: endpoint",{code:"INVALID_PARAMETER"});if(!e.keys||!e.keys.p256dh||!e.keys.auth)throw new c("Missing parameter: keys.p256dh or keys.auth",{code:"INVALID_PARAMETER"});return await P.bind(this)("store-subscription",{endpoint:e.endpoint,keys:e.keys},{auth:true}),"SUCCESS: Subscribed to receive notifications."}async function cs(e){if(typeof window>"u"||window._runningInNodeJS)throw new c("Push Notifications are not supported in Node.js environment.",{code:"NOT_SUPPORTED"});if(await this.__connection,!e.endpoint)throw new c("Missing parameter: endpoint",{code:"INVALID_PARAMETER"});if(!e.keys||!e.keys.p256dh||!e.keys.auth)throw new c("Missing parameter: keys.p256dh or keys.auth",{code:"INVALID_PARAMETER"});return await P.bind(this)("delete-subscription",{endpoint:e.endpoint,keys:e.keys},{auth:true}),"SUCCESS: Unsubscribed from notifications."}async function ls(){if(typeof window>"u"||window._runningInNodeJS)throw new c("Push Notifications are not supported in Node.js environment.",{code:"NOT_SUPPORTED"});return await this.__connection,{VAPIDPublicKey:await P.bind(this)("get-vapid-public-key",null,{auth:true})}}async function us(e,t){if(typeof window>"u"||window._runningInNodeJS)throw new c("Push Notifications are not supported in Node.js environment.",{code:"NOT_SUPPORTED"});await this.__connection;let{title:r,body:n}=V(e||{},{nullIfEmpty:true}).data;if(!r)throw new c("Missing parameter: message title",{code:"INVALID_PARAMETER"});if(!n)throw new c("Missing parameter: message body",{code:"INVALID_PARAMETER"});let i={title:r,body:n};return t?(typeof t=="string"&&(t=[t]),i.user_ids=t):i.user_ids="all_users",await P.bind(this)("push-notification",i,{auth:true}),"SUCCESS: Notification sent."}async function ds(e){await this.__connection,e=p.Params(e,{spell:"string",name:"string",magic:r=>r},["spell","name"]);await P.bind(this)("castspell",e);return `The spell "${e.spell}" has been cast.`}async function fs(e){return await this.__connection,e=p.Params(e||{},{search:["spell","name",()=>"spell"],value:"string"}),await P.bind(this)("getspell",e)}async function gs(e){await this.__connection,e=p.Params(e,{message:"string",name:"string"},["message","name"]);let t=await P.bind(this)("dopamine",e,{auth:true}),r=t?.previous_message?.message,n=t?.previous_message?.name;if(G())r&&n&&window.alert(`${n} said: ${r}`),window.location.href=t.video;else return r&&n?`${n} said: ${r}
215
+ `,o=new Blob([s],{type:"application/javascript"});_e=new Worker(URL.createObjectURL(o)),_e.onmessage=c=>{i.readyState===1&&i.send(JSON.stringify({action:"keepAlive"}));},n(i);},i.onmessage=async s=>{let o="";try{o=JSON.parse(decodeURI(s.data)),this.log("socket onmessage",o);}catch{return}let c;switch(true){case !!o?.["#message"]:c="message";break;case !!o?.["#private"]:c="private";break;case !!o?.["#notice"]:c="notice";break;case !!o?.["#rtc"]:c="rtc";break;case !!o?.["#error"]:c="error";break}if(!c)return;let l={type:c,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(c==="notice")e(l);else if(c==="rtc"){if(l.sender!==this.user.user_id){let u=l.message;if(u.hungup){ae[l.sender_cid]&&(ae[l.sender_cid](false),delete ae[l.sender_cid]),de[l.sender_cid]&&delete de[l.sender_cid],U?.[l.sender_cid]&&ce.bind(this)({cid:l.sender_cid}),l.type="rtc:closed",e(l);return}if(u.candidate&&wr.bind(this)(u.candidate,l.sender_cid),u.sdpoffer&&(_r.bind(this)(u.sdpoffer,l.sender_cid),de[l.sender_cid]||(de[l.sender_cid]=l.sender_cid,delete l.message,l.connectRTC=Oi.bind(this)(l),l.type="rtc:incoming",l.hangup=(()=>{U[l.sender_cid]?ce.bind(this)({cid:l.sender_cid}):de[l.sender_cid]&&(delete de[l.sender_cid],i.send(JSON.stringify({action:"rtc",uid:l.sender_cid,content:{hungup:this.user.user_id},token:this.session.accessToken.jwtToken})));}).bind(this),e(l))),u.pickup&&ae[l.sender_cid]&&(ae[l.sender_cid](true),delete ae[l.sender_cid]),u.sdpanswer&&U[l.sender_cid])if(U[l.sender_cid].signalingState==="have-local-offer")await U[l.sender_cid].setRemoteDescription(new RTCSessionDescription(u.sdpanswer));else throw new a("Invalid signaling state.",{code:"INVALID_REQUEST"})}}else e(l);},i.onclose=()=>{tt?(this.log("realtime onclose","WebSocket connection closed."),e({type:"close",message:"WebSocket connection closed."})):(this.log("realtime onclose","WebSocket unexpected close."),e({type:"error",message:"Skapi: WebSocket unexpected close."}),Le++,Le<3?(this.log("realtime onclose","Reconnecting to WebSocket server..."+Le),e({type:"reconnect",message:"Reconnecting to WebSocket server..."+Le}),St.bind(this)(e,3e3,"reconnect")):(this.log("realtime onclose","Max reconnection attempts reached."),e({type:"error",message:"Skapi: Max reconnection attempts reached."})));},i.onerror=()=>{this.log("realtime onerror","WebSocket connection error."),e({type:"error",message:"Skapi: WebSocket connection error."});};},t);});}async function $i(e,t,r){if(typeof window>"u"||window._runningInNodeJS)throw new a("WebSocket is not supported in Node.js environment.",{code:"NOT_SUPPORTED"});let n=this.__socket?await this.__socket:this.__socket;if(!n)throw new a("No realtime connection. Execute connectRealtime() before this method.",{code:"INVALID_REQUEST"});if(!t)throw new a("No recipient.",{code:"INVALID_REQUEST"});await xe.bind(this)(),e=q(e).data;let i="";if(r&&(r=y.Params(r,{config:{always:"boolean"},title:"string",body:"string"},["title","body"]),i=JSON.stringify({title:r.title,body:r.body}),new Blob([i]).size>3072))throw new a("Notification size exceeds 3kb.",{code:"INVALID_PARAMETER"});if(n.readyState===1){try{y.UserId(t),n.send(JSON.stringify({action:"sendMessage",uid:t,content:e,notification:i,notificationConfig:r?.config||{},token:`IdT:${this.service}:${this.owner}:`+(this.bearerToken||this.session?.idToken?.jwtToken||"null")}));}catch(s){if(this.log("postRealtime:err",{err:s}),we!==t)throw new a(`User has not joined to the recipient group. Run joinRealtime({ group: "${t}" })`,{code:"INVALID_REQUEST"});n.send(JSON.stringify({action:"broadcast",rid:t,content:e,notification:i,notificationConfig:r?.config||{},token:`IdT:${this.service}:${this.owner}:`+(this.bearerToken||this.session?.idToken?.jwtToken||"null")}));}return {type:"success",message:"Message sent."}}throw new a("Realtime connection is not open. Try reconnecting with connectRealtime().",{code:"INVALID_REQUEST"})}async function Ar(e){if(typeof window>"u"||window._runningInNodeJS)throw new a("WebSocket is not supported in Node.js environment.",{code:"NOT_SUPPORTED"});let t=this.__socket?await this.__socket:this.__socket;if(!t)throw new a("No realtime connection. Execute connectRealtime() before this method.",{code:"INVALID_REQUEST"});await xe.bind(this)(),e=q(e,{nullIfEmpty:true}).data;let{group:r=null}=e;if(!r&&!we)return {type:"success",message:"Left realtime message group."};if(r!==null&&typeof r!="string")throw new a('"group" must be a string | null.',{code:"INVALID_PARAMETER"});return t.send(JSON.stringify({action:"joinRoom",rid:r,token:this.session.accessToken.jwtToken})),we=r,{type:"success",message:r?`Joined realtime message group: "${r}".`:"Left realtime message group."}}async function Vi(e,t){e=y.Params(e,{user_id:n=>y.UserId(n,'User ID in "user_id"'),group:["string",()=>{if(!we)throw new a('No group has been joined. Otherwise "group" is required.',{code:"INVALID_REQUEST"});return we}]});let r=await T.bind(this)("get-ws-group",e,{fetchOptions:t,auth:true,method:"post"});return r.list=r.list.map(n=>({user_id:n.uid.split("#")[1],cid:"cid:"+n.cid})),r}async function qi(e,t){if(await this.__connection,e||(e={searchFor:"group",value:" ",condition:">"}),e=y.Params(e,{searchFor:["group","number_of_users",()=>"group"],value:["string","number",()=>e?.searchFor&&e?.searchFor==="number_of_users"?0:" "],condition:[">",">=","=","<","<=","!=","gt","gte","eq","lt","lte","ne"],range:["string","number"]}),e.condition||(e.value===" "||!e.value?e.condition=">":e.condition="="),e.range&&e.condition&&delete e.condition,e.searchFor==="number_of_users"&&typeof e.value!="number")throw new a('"value" must be a number.',{code:"INVALID_PARAMETER"});if(e.searchFor==="group"&&typeof e.value!="string")throw new a('"value" must be a string.',{code:"INVALID_PARAMETER"});if(e.hasOwnProperty("range")&&typeof e.range!=typeof e.value)throw new a(`"range" must be a ${typeof e.value}.`,{code:"INVALID_PARAMETER"});let r=await T.bind(this)("get-ws-group",e,{fetchOptions:t,auth:true,method:"post"});return r.list=r.list.map(n=>({group:n.rid.split("#")[1],number_of_users:n.cnt})),r}var Bi=typeof FormData<"u",Ki=typeof HTMLFormElement<"u",Hi=typeof SubmitEvent<"u",fe={},rt={},ge={};function Rr(e){return Object.freeze({id:e,status:"stopped"})}function Wi(e){return !!e&&typeof e=="object"&&e.status==="stopped"}function Qi({id:e,auth:t,service:r,owner:n,latency:i=1e3,queue:s,onResponse:o,onError:c}){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&&!fe?.[s]&&(fe[s]=new ji__default.default({breakWhenError:false,batchSize:1}));let l={stop:null,aborted:false,queue:s};ge[e]=l;let u=()=>{ge[e]===l&&delete ge[e];},g=()=>new Promise((d,p)=>{let m=false;if(l.aborted){u(),d(Rr(e));return}let h=setInterval(async()=>{try{let _=await T.bind(this)("csr-poll",{id:e,service:r,owner:n},{auth:t});if(_.status==="running"||_.status==="pending"||m)return;m=!0,o&&o(_),clearInterval(h),u(),d(_);}catch(_){if(m)return;m=true,c&&c(_),clearInterval(h),u(),p(_);}},i);l.stop=()=>{m||(m=true,clearInterval(h),u(),d(Rr(e)));};}),f=()=>{let d=ge[e];d&&(d.stop?d.stop():(d.aborted=true,delete ge[e]));};if(s){let d=new Promise((p,m)=>{let h=false,_=fe[s].add([async()=>{try{let w=await g();return h||(h=!0,p(w)),w}catch(w){throw h||(h=true,m(w)),w}}])[0];rt[e]=_,l.stop=()=>{if(!h){l.aborted=true;try{fe[s]&&fe[s].remove(rt[e]);}catch{}delete rt[e],u(),h=true,p(Rr(e));}};});return Object.assign(d,{stop:f})}else return Object.assign(g(),{stop:f})}function Gi(e){let t=0,r=[];if(e?.id){if(e.url&&e.method){let n=e.service||this.service;r.push(`[${e.method.toUpperCase()}]${e.url.toLowerCase()}#${n}:${e.id}`);}r.push(e.id);}else if(e?.queue)for(let n in ge)ge[n]?.queue===e.queue&&r.push(n);else for(let n in ge)r.push(n);for(let n of r){let i=ge[n];i&&(i.stop?i.stop():(i.aborted=true,delete ge[n]),t+=1);}return t}function zi(e,t){if(!e.queue)throw new a('"queue" is required.',{code:"INVALID_PARAMETER"});let r={service:e.service||this.service,owner:e.owner||this.owner,queue:e.queue+":"};return T.bind(this)("csr-poll",r,{auth:true})}async function Ji(e){let t=false;if(typeof e.poll=="number"&&e.poll<0)throw new a('"poll" should be a non-negative number.',{code:"INVALID_PARAMETER"});let r=e?.onResponse,n=e?.onError,i=typeof e.poll=="number"?e.poll:e.poll?1e3:0;delete e.poll,i&&!e.queue&&(e.queue=(this.__user?.user_id||"anonymous")+"-"+Ee());let s=l=>{for(let u in l)if(typeof l[u]=="string"&&l[u].includes("$CLIENT_SECRET")){t=true;break}};if(e=y.Params(e,{url:l=>{if(!l||typeof l!="string")throw new a('"url" should be type: <string>.',{code:"INVALID_PARAMETER"});return y.Url(l),l.includes("$CLIENT_SECRET")&&(t=true),l},clientSecretName:"string",method:l=>{if(l&&typeof l!="string")throw new a('"method" should be either "GET" or "POST" or "DELETE" or "PUT".',{code:"INVALID_PARAMETER"});let u=l.toLowerCase();if(u!=="get"&&u!=="post"&&u!=="delete"&&u!=="put")throw new a('"method" should be either "GET" or "POST" or "DELETE" or "PUT".',{code:"INVALID_PARAMETER"});return u},headers:l=>{if(l&&typeof l!="object")throw new a('"headers" should be type: <object>.',{code:"INVALID_PARAMETER"});return s(l),l},data:l=>{if(l&&typeof l!="object")throw new a('"data" should be type: <object>.',{code:"INVALID_PARAMETER"});return s(l),l},params:l=>{if(l&&typeof l!="object")throw new a('"params" should be type: <object>.',{code:"INVALID_PARAMETER"});return s(l),l},expires:"number",queue:"string"},["clientSecretName","method","url"]),!t)throw new a(`At least one parameter value should include "$CLIENT_SECRET" in ${e.method.toLowerCase()==="post"?'"data"':'"params"'} or "headers".`,{code:"INVALID_PARAMETER"});await this.__connection;let o=!!this.__user,c=()=>T.bind(this)("csr",e,{auth:o,tokenHeaders:{accessToken:!!o}}).then(l=>{if(l.status==="running"||l.status==="pending"){let u=`[${e.method.toUpperCase()}]${e.url.toLowerCase()}`,g=e.service||this.service,f=e.owner||this.owner,d=`${u}#${g}:${l.id}`;Object.assign(l,{poll:p=>Qi.call(this,{id:d,auth:o,service:g,owner:f,latency:p?.latency||1e3,queue:e?.queue,onResponse:r,onError:n})});}return r?r(l):l}).catch(l=>{if(n)return n(l);throw l});if(e?.queue){let l="base:"+e.queue;return fe?.[l]||(fe[l]=new ji__default.default({breakWhenError:false,batchSize:1})),new Promise((u,g)=>{fe[l].add([async()=>{try{let f=await c();if(i>0){let d=f.poll({latency:i});return u(d),d}return u(f),f}catch(f){throw g(f),f}}]);})}else return c()}async function Yi(e,t){await this.__connection;let r=e.service||this.service,n=e.owner||this.owner;e=y.Params(e,{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=`[${e.method.toUpperCase()}]${e.url.toLowerCase()}#${r}:`,o={id:s,queue:e?.queue,status:e?.status,service:r,owner:n};e?.compact&&(o.compact=true),e?.queue_exact&&(o.queue_exact=true),e?.queue_exclude&&(o.queue_exclude=e.queue_exclude),Object.keys(o).forEach(l=>{o[l]||delete o[l];}),o.queue&&(o.id_prefix=o.id,delete o.id);let c=await T.bind(this)("csr-poll",o,{auth:i,fetchOptions:t});return c.list=c.list.map(l=>{let u={id:l.id,status_code:l.rslv?.status_code||null,response_body:l.rslv?.body||l.rslv?.truncated||null,error:l?.err,created:l?.stmp,updated:l?.utmp,request_body:l?.reqbdy,expires:l?.expt,status:l.stts,queue_name:l?.qid,request_text:l?.reqtxt,response_text:l?.rslvtxt,response_complete_marker:l?.rslvmk!=null?!!l.rslvmk:void 0,compact:l?.cmpct?true:void 0};for(let g in u)u[g]===void 0&&delete u[g];return (u.status==="running"||u.status==="pending")&&(u.poll=g=>Qi.call(this,{id:s+u.id,auth:i,service:r,owner:n,latency:g?.latency||1e3,queue:l?.qid,onResponse:g?.onResponse,onError:g?.onError})),u}),c}async function Xi(e){await this.__connection,e=y.Params(e,{url:"string",method:["GET","POST","DELETE","PUT"],id:"string",queue:"string"},["url","method","id"]);let t=e?.service||this.service,r=e?.owner||this.owner,n=!!this.__user,i=`[${e.method.toUpperCase()}]${e.url.toLowerCase()}#${t}`,s=e.id,o=`${i}:${s}`,c=e?.queue;return c&&fe?.[c]&&(fe[c].remove(rt[o]),delete rt[o]),T.bind(this)("csr-cancel",{id:o,service:t,owner:r},{auth:n})}async function Zi(e){await this.__connection;let t={name:"string",email:r=>(y.Email(r),r),subject:"string",message:"string"};return e=y.Params(e,t,["name","email","subject","message"]),await T.bind(this)("send-inquiry",e),"SUCCESS: Inquiry has been sent."}async function es(e,t){if(await this.__connection,Bi&&e instanceof FormData||Ki&&e instanceof HTMLFormElement||Hi&&e instanceof SubmitEvent){if(!t)throw new a("Url string as a second argument is required when form is passed.",{code:"INVALID_PARAMETER"});let n=q(e);e={url:t,data:n.data,sync:true};}let r={url:n=>y.Url(n),data:n=>n,sync:["boolean",()=>true]};if(Array.isArray(e))for(let n of e)n=y.Params(n,r);else e=y.Params(e,r);return T.bind(this)("post-secure",e,{auth:true})}async function ts(e,t){await this.__connection;let{auth:r=false,method:n="POST",bypassAwaitConnection:i=false,responseType:s,contentType:o,tokenHeaders:c,progress:l}=t||{};if(t=Object.assign({auth:r,method:n,bypassAwaitConnection:i,responseType:s,contentType:o,tokenHeaders:c},{fetchOptions:{progress:l}}),typeof e!="object"&&(o==="application/json"||o===void 0))throw new a('"data" should be type: <object>.',{code:"INVALID_PARAMETER"});return T.bind(this)("mock",e,t)}async function rs(e,t){if(await this.__connection,!t?.url||typeof t.url!="string")throw new a('"url" is required in the second argument.',{code:"INVALID_PARAMETER"});y.Url(t.url);let n=(await this.admin_endpoint)?.forward_request;if(!n)throw new a("forwardRequest is not available on this service region yet.",{code:"NOT_EXISTS"});let i=null,s=null,o=Hi&&e instanceof SubmitEvent?e.target:Ki&&e instanceof HTMLFormElement?e:null;o?i=new FormData(o):Bi&&e instanceof FormData?i=e:e!=null&&(i=JSON.stringify(e),s="application/json");let c={public_identifier:this.__public_identifier,service:this.service,owner:this.owner,forward:{url:t.url,method:t.method||"POST",headers:t.headers||{},apiKeyHeader:t.apiKeyHeader,apiKeyScheme:t.apiKeyScheme}},l=JSON.stringify(c).replace(/[\u007f-\uffff]/g,p=>"\\u"+p.charCodeAt(0).toString(16).padStart(4,"0"));if(l.length>4096)throw new a("Destination url and headers are too large for Content-Meta.",{code:"INVALID_PARAMETER"});let u=this.bearerToken||this.session?.idToken?.jwtToken||null;if(!u)throw new a("User login is required.",{code:"INVALID_REQUEST"});let g={"Content-Meta":l,Authorization:u};s&&(g["Content-Type"]=s);let f=await fetch(n,{method:"POST",headers:g,body:i,signal:t.signal});if(t.responseType==="response")return f;if(!f.ok){let p=await f.text();try{p=JSON.parse(p);}catch{}throw new a(p?.message||(typeof p=="string"?p:JSON.stringify(p)),{code:p?.code||"ERROR"})}if(t.onStream&&f.body){let p=f.body.getReader(),m=new TextDecoder,h="";for(;;){let{done:_,value:w}=await p.read();if(_)break;let b=m.decode(w,{stream:true});h+=b;try{t.onStream(b);}catch(E){console.error(E);}}return h}let d=await f.text();if(t.responseType==="text")return d;try{return JSON.parse(d)}catch{return d}}async function ns(e,t){await this.__connection,e=y.Params(e||{},{access_group:n=>{if(n==="authorized"&&(n=1),n==="public"&&(n=0),typeof n!="number")throw new a('"access_group" should be type number.',{code:"INVALID_PARAMETER"});if(n<0)throw new a('"access_group" should be zero or a positive number.',{code:"INVALID_PARAMETER"});if(n>this.__user.access_group)throw new a("User has no access.",{code:"INVALID_REQUEST"});return n}});let r=await T.bind(this)("get-feed",e,{auth:true,fetchOptions:t});for(let n in r.list)r.list[n]=await Pe.bind(this)(r.list[n]);return r}function nt(e){if(e===this.__user.user_id)throw new a(`"user_id" cannot be the user's own ID.`,{code:"INVALID_PARAMETER"});return y.UserId(e,'"user_id"')}async function is(e,t){if(e=q(e,{ignoreEmpty:true}).data,e=y.Params(e,{subscriber:n=>y.UserId(n,'User ID in "subscriber"'),subscription:nt.bind(this),blocked:"boolean"}),!e.subscriber&&!e.subscription)throw new a('At least either "subscriber" or "subscription" should have a value.',{code:"INVALID_PARAMETER"});let r=await T.bind(this)("get-subscription",e,Object.assign({auth:true},{fetchOptions:t}));return r.list=r.list.map((n=>{let i={};if(n.sub){let s=n.sub.split("#");i.subscriber=s[2],i.subscription=s[0];}else i.subscriber=n.subscriber,i.subscription=n.subscription;return i.timestamp=n?.timestamp||n.stmp,i.blocked=n?.blocked||n.grp.substring(0,1)==="N",Object.assign(i,n.opt),i})),r}async function ss(e){await this.__connection,e=y.Params(e,{user_id:nt.bind(this),get_feed:["boolean",()=>false],get_notified:["boolean",()=>false],get_email:n=>{if(n&&!this.__user.email||!this.__user.email_verified)throw new a("User has no verified email address.",{code:"INVALID_REQUEST"});return !!n}},["user_id"]);let t=await T.bind(this)("subscription",{subscribe:e.user_id,option:{get_feed:e.get_feed,get_notified:e.get_notified,get_email:e.get_email||false}},{auth:true}),r={};if(t.sub){let n=t.sub.split("#");r.subscriber=n[2],r.subscription=n[0];}else r.subscriber=t.subscriber,r.subscription=t.subscription;return r.timestamp=t?.timestamp||t.stmp,r.blocked=t?.blocked||t.grp.substring(0,1)==="N",Object.assign(r,t.opt),r}async function os(e){await this.__connection;let{user_id:t}=y.Params(e,{user_id:nt.bind(this)},["user_id"]);return await T.bind(this)("subscription",{unsubscribe:t},{auth:true})}async function as(e){await this.__connection;let{user_id:t}=y.Params(e,{user_id:nt.bind(this)},["user_id"]);return await T.bind(this)("subscription",{block:t},{auth:true})}async function cs(e){await this.__connection;let{user_id:t}=y.Params(e,{user_id:nt.bind(this)},["user_id"]);return await T.bind(this)("subscription",{unblock:t},{auth:true})}async function ls(e,t){await this.__connection;let r=await Q.bind(this)();e=y.Params(e,{user_id:o=>{if(o!==this.__user.user_id&&!r)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 n=await T.bind(this)("get-newsletter-subscription",e,{auth:true,fetchOptions:t||null}),i=n?.list||n,s=[];Array.isArray(i)||(i=[]);for(let o of i){let c=o.subt.split("#"),l=true;c[0].charAt(0)==="@"&&(l=false,c[0]=c[0].substring(1));let u=parseInt(c[0]);s.push({timestamp:o.stmp,group:u,subscribed_email:c[1],active:l});}return n?.list?(n.list=s,n):s}async function us(e){await this.__connection;let t=y.Params(e||{},{email:r=>Array.isArray(r)&&r.length>0?r.length===1?y.Email(r[0]):r.map(n=>y.Email(n)):y.Email(r),group:["number","public","authorized","admin",r=>{if(typeof r!="string"||r.length>20||!/^[a-zA-Z0-9]+$/.test(r))throw new a('"group" should be an alphanumeric string without spaces and less than 20 characters.',{code:"INVALID_PARAMETER"});return r}],redirect:r=>y.Url(r)},this.__user?["group"]:["email","group"]);return T.bind(this)(`subscribe-${this.__user?"":"public-"}newsletter`,t,{auth:!!this.__user})}async function ds(e){await this.__connection,e=y.Params(e,{group:["number","public","authorized","admin"]},["group"]);let t=Object.assign({action:"unsubscribe"},e);return T.bind(this)("subscribe-newsletter",t,{auth:true})}async function fs(e,t){let r=await Q.bind(this)(),n={message_id:"string",timestamp:"number",read:"number",complaint:"number",subject:"string",bounced:"number"};e||(t=Object.assign({ascending:false},t||{})),e=q(e).data,e=e||{searchFor:"timestamp",value:Date.now(),condition:"<",group:"public"},e=y.Params(e,{searchFor:["message_id","timestamp","subject","complaint","read","bounced"],value:l=>{if(typeof l!==n[e.searchFor])throw new a(`"value" type does not match the type of "${e.searchFor}" index.`,{code:"INVALID_PARAMETER"});if(typeof l=="string"&&!l)throw new a('"value" should not be empty string.',{code:"INVALID_PARAMETER"});return l},range:l=>{if(!e.hasOwnProperty("value")||typeof l!=typeof e.value)throw new a('"range" should match type of "value".',{code:"INVALID_PARAMETER"});return l},condition:[">",">=","=","<","<=","gt","gte","eq","lt","lte",()=>"="],group:l=>{if(l==="public")return 0;if(!this.session)throw new a("User should be logged in.",{code:"INVALID_REQUEST"});if(l==="authorized")return 1;if(typeof l=="number"){if(!r&&l>parseInt(this.user?.access_group||this.session?.idToken?.payload?.access_group))throw new a("User has no access.",{code:"INVALID_REQUEST"});return l}throw new a('"group" should be type: number | "public" | "authorized".',{code:"INVALID_PARAMETER"})}},["searchFor","value","group"]);let i=e.group===0?"get-public-newsletters":"get-newsletters",s=await T.bind(this)(i,e,Object.assign({method:"get",auth:i==="get-public-newsletters"?!!this.__user:true},{fetchOptions:t})),o={message_id:"mid",timestamp:"stmp",complaint:"cmpl",read:"read",subject:"subj",bounced:"bnce",url:"url",delivered:"delv"},c={message_id:"",timestamp:0,complaint:0,read:0,subject:"",bounced:"",url:"",delivered:0};return s.list=s.list.map(l=>{let u={};for(let g in o)u[g]=l[o[g]]||c[g];return u.bounced=String(u.bounced),u}),s}async function gs(e){let t=y.Params(e,{user_id:n=>y.UserId(n,'"user_id"')},["user_id"]);if(t?.service&&t?.owner?t={service:t?.service,owner:t?.owner,block:t.user_id}:t={block:t.user_id},!await Q.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 T.bind(this)("block-account",t,{auth:true})}async function ps(e){let t=y.Params(e,{user_id:n=>y.UserId(n,'"user_id"')},["user_id"]);if(t?.service&&t?.owner?t={service:t?.service,owner:t?.owner,unblock:t.user_id}:t={unblock:t.user_id},!await Q.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 T.bind(this)("block-account",t,{auth:true})}async function hs(e){let t=y.Params(e,{user_id:n=>y.UserId(n,'"user_id"')},["user_id"]);if(t?.service&&t?.owner?t={service:t?.service,owner:t?.owner,delete:t.user_id}:t={delete:t.user_id},!await Q.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 T.bind(this)("remove-account",t,{auth:true})}async function ys(e,t){let r={email:s=>y.Email(s),password:s=>y.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=>y.Birthdate(s),phone_number:s=>y.PhoneNumber(s),picture:s=>{if(s)return y.Url(s)},profile:s=>{if(s)return y.Url(s)},website:s=>{if(s)return y.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}},n=y.Params(e,r,["email"]);if(t=y.Params(t,{confirmation_url:s=>{let o=s;if(typeof s=="string")o=y.Url(s);else throw new a('"options.confirmation_url" should be type: <string>.',{code:"INVALID_PARAMETER"});if(o&&!n.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(!t?.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:y.Url(s.url),subject:s.subject}}}),n.signup_confirmation=t?.confirmation_url||true,n.email_subscription=t?.email_subscription||false,n.template=t?.template||{},!await Q.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 T.bind(this)("admin-signup",n,{auth:true})}async function ms(e){let t={email:s=>y.Email(s),password:s=>y.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=>y.Birthdate(s),phone_number:s=>y.PhoneNumber(s),picture:s=>s?y.Url(s):"",profile:s=>s?y.Url(s):"",website:s=>s?y.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}},r=["email","password"],n=y.Params(e,t,r);if(!await Q.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 T.bind(this)("admin-signup",n,{auth:true})}async function bs(e){if(e=y.Params(e,{user_id:r=>y.UserId(r,'"user_id"'),access_group:r=>{try{typeof r=="string"&&(r=parseInt(r));}catch{throw new a('"access_group" is invalid. Should be type <number>.',{code:"INVALID_PARAMETER"})}if(typeof r=="number"&&r>0&&r<100)return r;throw new a('"access_group" is invalid. Should be type <number> of range 1~99',{code:"INVALID_PARAMETER"})}},["user_id","access_group"]),!await Q.bind(this)()){if(!this.__user)throw new a("User needs to login.",{code:"INVALID_REQUEST"});if(this.__user.access_group<90)throw new a("Invalid access.",{code:"INVALID_REQUEST"})}return await T.bind(this)("grant-access",e,{auth:true})}async function _s(e,t){if(e=y.Params(e,{email:"string"}),!await Q.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 n=await T.bind(this)("invitation-list",Object.assign({mode:"search"},e),{fetchOptions:t,auth:true});return n.list=n.list.map(i=>$e(i.user)),n}async function ws(e){if(e=y.Params(e,{email:r=>y.Email(r)},["email"]),!await Q.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 T.bind(this)("invitation-list",Object.assign({mode:"cancel"},e),{auth:true})}async function Es(e){if(e=y.Params(e,{email:r=>y.Email(r)},["email"]),!await Q.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 T.bind(this)("invitation-list",Object.assign({mode:"resend"},e),{auth:true})}async function As(e){let t=y.Params(e,{user_id:o=>y.UserId(o,'"user_id"'),email:o=>y.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?y.Birthdate(o):"",phone_number:o=>o?y.PhoneNumber(o):"",email_public:"boolean",phone_number_public:"boolean",address_public:"boolean",gender_public:"boolean",birthdate_public:"boolean",misc:"string",picture:o=>o?y.Url(o):"",profile:o=>o?y.Url(o):"",nickname:"string",website:o=>o?y.Url(o):""},["user_id"]),r=t.service,n=t.owner;if(delete t.service,delete t.owner,Object.keys(t).filter(o=>o!=="user_id"&&t[o]!==void 0).length===0)throw new a("At least one attribute to update is required.",{code:"INVALID_PARAMETER"});if(!await Q.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"})}t.email&&(t.preferred_username=(r||this.service)+"-"+W.hash(t.email));let s={attributes:t};return r&&n&&(s.service=r,s.owner=n),await T.bind(this)("admin-edit-profile",s,{auth:true})}async function Rs(e){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,!e.endpoint)throw new a("Missing parameter: endpoint",{code:"INVALID_PARAMETER"});if(!e.keys||!e.keys.p256dh||!e.keys.auth)throw new a("Missing parameter: keys.p256dh or keys.auth",{code:"INVALID_PARAMETER"});return await T.bind(this)("store-subscription",{endpoint:e.endpoint,keys:e.keys},{auth:true}),"SUCCESS: Subscribed to receive notifications."}async function Is(e){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,!e.endpoint)throw new a("Missing parameter: endpoint",{code:"INVALID_PARAMETER"});if(!e.keys||!e.keys.p256dh||!e.keys.auth)throw new a("Missing parameter: keys.p256dh or keys.auth",{code:"INVALID_PARAMETER"});return await T.bind(this)("delete-subscription",{endpoint:e.endpoint,keys:e.keys},{auth:true}),"SUCCESS: Unsubscribed from notifications."}async function Ps(){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 T.bind(this)("get-vapid-public-key",null,{auth:true})}}async function Ts(e,t){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:r,body:n}=q(e||{},{nullIfEmpty:true}).data;if(!r)throw new a("Missing parameter: message title",{code:"INVALID_PARAMETER"});if(!n)throw new a("Missing parameter: message body",{code:"INVALID_PARAMETER"});let i={title:r,body:n};return t?(typeof t=="string"&&(t=[t]),i.user_ids=t):i.user_ids="all_users",await T.bind(this)("push-notification",i,{auth:true}),"SUCCESS: Notification sent."}async function Ss(e){await this.__connection,e=y.Params(e,{spell:"string",name:"string",magic:r=>r},["spell","name"]);await T.bind(this)("castspell",e);return `The spell "${e.spell}" has been cast.`}async function ks(e){return await this.__connection,e=y.Params(e||{},{search:["spell","name",()=>"spell"],value:"string"}),await T.bind(this)("getspell",e)}async function vs(e){await this.__connection,e=y.Params(e,{message:"string",name:"string"},["message","name"]);let t=await T.bind(this)("dopamine",e,{auth:true}),r=t?.previous_message?.message,n=t?.previous_message?.name;if(J())r&&n&&window.alert(`${n} said: ${r}`),window.location.href=t.video;else return r&&n?`${n} said: ${r}
216
216
  Watch the video here: ${t.video}`:`Your message has been uploaded for future generations to receive.
217
- Watch the video here: ${t.video}`}var A=class{constructor(t,r,n,i){this.__version="2.0.0-rc.7";this.project_id="";this.session=null;this.connection=null;this.__my_unique_ids={};this.__uniqueIdsPersistTimer=null;this.userPool=null;this.__socket=null;this.__mediaStream=null;this.host="skapi";this.hostDomain="skapi.com";this.target_cdn="d3e9syvbtso631";this.customApiDomain="skapi.dev";this.requestBatchSize=30;this.__disabledAccount=null;this.__cached_requests={};this.__startKeyHistory={};this.__request_signup_confirmation=null;this.__private_access_key={};this.__class_properties_has_been_cached=false;this.__user=null;this._userProfileListeners=[];this._onLoginListeners=[];this._onBatchProcessListeners=[];this.validate={userId(t){try{return p.UserId(t),!0}catch{return false}},url(t){try{return p.Url(t),!0}catch{return false}},phoneNumber(t){try{return p.PhoneNumber(t),!0}catch{return false}},birthdate(t){try{return p.Birthdate(t),!0}catch{return false}},email(t){try{return p.Email(t),!0}catch{return false}},params(t,r,n){return p.Params(t,r,n)}};this.util={MD5:H,generateRandom:be,toBase62:mr,fromBase62:X,decodeProjectId:It,formatServiceId:Pt,extractFormData:V,terminatePendingRequests:Bn,request:(t,r,n)=>P.bind(this)(t,r,n,{ignoreService:true})};this.__network_logs=false;this.__endpoint_version="v2";this.__public_identifier="";this.bearerToken="";this.registerTicket=En.bind(this);this.unregisterTicket=An.bind(this);if(!t||typeof t!="string")throw this._alert("Service ID is required."),new c("Service ID is required.",{code:"INVALID_PARAMETER"});let s=t.trim().toLowerCase().replace(/^<|>$/g,"").replace(/[\s_\-.]+/g,"");if(s==="serviceid"||s==="projectid")throw this._alert(`Replace "${t}" with your actual Project ID.`),new c("Project ID is required.",{code:"INVALID_PARAMETER"});let o=t.split("-").length;if(o===2||o===7)try{let w=It(t);n&&typeof n=="object"&&(i=n),r&&typeof r=="object"&&(n=r),r=w.owner,t=w.service;}catch{throw this._alert("Service ID is invalid."),new c("Service ID is invalid.",{code:"INVALID_PARAMETER"})}if(!r||typeof r!="string")throw this._alert("Owner ID is invalid."),new c("Owner ID is invalid.",{code:"INVALID_PARAMETER"});if(r!==this.host)try{p.UserId(r,'"owner"');}catch{throw this._alert("Owner ID is invalid."),new c("Owner ID is invalid.",{code:"INVALID_PARAMETER"})}this.service=t,this.owner=r;try{this.project_id=Pt(t,r);}catch{this.project_id="";}let u=true,d=false,f=null;if(n&&(typeof n.refetchServiceInfo=="boolean"&&(d=n.refetchServiceInfo),typeof n.autoLogin=="boolean"&&(u=n.autoLogin),n.encryption&&(f=Vr(n.encryption)),typeof n.requestBatchSize=="number")){if(n.requestBatchSize<1)throw new c('"requestBatchSize" must be greater than 0.',{code:"INVALID_PARAMETER"});this.requestBatchSize=n.requestBatchSize;}n?.eventListener&&typeof n.eventListener=="object"&&(n.eventListener?.onLogin&&typeof n.eventListener.onLogin=="function"&&(this.onLogin=n.eventListener.onLogin),n.eventListener?.onUserUpdate&&typeof n.eventListener.onUserUpdate=="function"&&(this.onUserUpdate=n.eventListener.onUserUpdate),n.eventListener?.onBatchProcess&&typeof n.eventListener.onBatchProcess=="function"&&(this.onBatchProcess=n.eventListener.onBatchProcess)),this.target_cdn=i?.target_cdn||this.target_cdn,this.hostDomain=i?.hostDomain||this.hostDomain,this.customApiDomain=i?.customApiDomain||this.customApiDomain,this.__network_logs=!!i?.network_logs;let g=`https://${this.target_cdn}.cloudfront.net`,h=t.substring(0,4);this.admin_endpoint=fetch(`${g}/${h}/admin-${this.__endpoint_version}.json`).then(w=>w.blob()).then(w=>new Promise((T,k)=>{let S=new FileReader;S.onloadend=()=>T(S.result),S.onerror=k,S.readAsDataURL(w);})).then(w=>{try{return typeof w=="string"?JSON.parse(atob(w.split(",")[1])):null}catch{throw new c("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(w=>w.blob()).then(w=>new Promise((T,k)=>{let S=new FileReader;S.onloadend=()=>T(S.result),S.onerror=k,S.readAsDataURL(w);})).then(w=>{try{return typeof w=="string"?JSON.parse(atob(w.split(",")[1])):null}catch{throw new c("Service does not exist. Create your service from skapi.com",{code:"NOT_EXISTS"})}});let m=G();if(m&&!window.sessionStorage)throw this._alert("This browser is not supported."),new Error("This browser is not supported.");let y=m?JSON.parse(window.sessionStorage.getItem(`${t}#${r}`)||"null"):null;if(this.log("constructor:restore",y),y?.connection){for(let w in y)this[w]=y[w];y.__public_identifier||(this.__public_identifier=`${this.service}:${this.owner}:${be(16)}`);}$r.bind(this)(f),this.__authConnection=(async()=>{let w=await this.admin_endpoint,T={UserPoolId:w.userpool_id,ClientId:w.userpool_client};Rt()&&(T.Storage=window.localStorage),this.userPool=new amazonCognitoIdentityJs.CognitoUserPool(T);try{this.user||await Q.bind(this)().getSession({skipUserUpdateEventTrigger:!0}),this.user&&(!y?.connection&&!u?pe.bind(this)():(f&&nn.bind(this)(),this._runOnLoginListeners(this.user),this._runOnUserUpdateListeners(this.user)));}catch{}})();let b=`${this.service}/${this.owner}`,_=m?window.sessionStorage.getItem(`${b}:uniqueids`):null;if(_)try{let w=JSON.parse(_);this.__my_unique_ids=w&&typeof w=="object"&&!Array.isArray(w)?{[b]:w}:{};}catch{this.__my_unique_ids={};}this.__connection=(async()=>{let w=null;await this.record_endpoint,y?.connection||(w=this._updateConnection({refresh:d}));let T=()=>{if(this.__class_properties_has_been_cached)return;let k=()=>{let S={},C=["__startKeyHistory","__disabledAccount","__cached_requests","__request_signup_confirmation","__public_identifier","connection"];if(this.connection){for(let x of C)S[x]=this[x];if(f&&(S.__cached_requests={},S.__startKeyHistory={}),m){let x=`${t}#${r}`;try{window.sessionStorage.setItem(x,JSON.stringify(S));}catch{try{let v=Object.assign({},S,{__cached_requests:{},__startKeyHistory:{}});window.sessionStorage.setItem(x,JSON.stringify(v));}catch{try{window.sessionStorage.removeItem(x);}catch{}}}}this.__class_properties_has_been_cached=true;}};return w instanceof Promise?w.then(()=>k()):k()};return m&&(window.addEventListener("beforeunload",()=>{this.closeRealtime(),T();}),window.addEventListener("visibilitychange",()=>{T();})),await w,await this.__authConnection,this.connection})(),this.__connection.then(w=>{((w?.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(t){}get onLogin(){return this._onLoginListeners}set onLogin(t){typeof t=="function"&&this._onLoginListeners.push(t);}get onUserUpdate(){return this._userProfileListeners}set onUserUpdate(t){typeof t=="function"&&this._userProfileListeners.push(t);}_runOnUserUpdateListeners(t){for(let r of this._userProfileListeners)typeof r=="function"&&r(t);}_runOnLoginListeners(t){for(let r of this._onLoginListeners)typeof r=="function"&&r(t);}get onBatchProcess(){return this._onBatchProcessListeners}set onBatchProcess(t){typeof t=="function"&&this._onBatchProcessListeners.push(t);}_alert(t){G()&&typeof window.alert=="function"&&window.alert(t);}async getConnectionInfo(t){t?.refresh&&(this.__connection instanceof Promise&&await this.__connection,this.__connection=this._updateConnection({refresh:true}));let n=await this.__connection,i=n?.user_agent||(G()&&typeof window.navigator?.userAgent=="string"?window.navigator.userAgent:`skapi-node/${globalThis?.process?.versions?.node||"unknown"}`);return {project_id:this.project_id,user_ip:n.ip,user_agent:i,user_location:n.locale,service_name:n.service_name,version:this.__version,service_description:n?.service_description||"",ai_agent:n?.ai_agent||"",conf:n?.opt}}async _updateConnection(t){let r=t?.refresh||false;try{this.connection=await P.bind(this)("service",{service:this.service,owner:this.owner,refresh:r},{bypassAwaitConnection:!0,method:"get"});}catch(n){throw this.log("connection fail",n),this._alert("Service is not available: "+(n.message||n.toString())),this.connection=null,n}return this.connection}async version(){if(await this.__connection,G()){let r=`Built with:
217
+ Watch the video here: ${t.video}`}var R=class{constructor(t,r,n,i){this.__version="2.0.0-rc.8";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(t){try{return y.UserId(t),!0}catch{return false}},url(t){try{return y.Url(t),!0}catch{return false}},phoneNumber(t){try{return y.PhoneNumber(t),!0}catch{return false}},birthdate(t){try{return y.Birthdate(t),!0}catch{return false}},email(t){try{return y.Email(t),!0}catch{return false}},params(t,r,n){return y.Params(t,r,n)}};this.util={MD5:W,generateRandom:Ee,toBase62:xr,fromBase62:te,decodeProjectId:Ot,formatServiceId:Lt,extractFormData:q,terminatePendingRequests:ai,request:(t,r,n)=>T.bind(this)(t,r,n,{ignoreService:true})};this.__network_logs=false;this.__endpoint_version="v2";this.__public_identifier="";this.bearerToken="";this.registerTicket=$n.bind(this);this.unregisterTicket=Vn.bind(this);if(!t||typeof t!="string")throw this._alert("Service ID is required."),new a("Service ID is required.",{code:"INVALID_PARAMETER"});let s=t.trim().toLowerCase().replace(/^<|>$/g,"").replace(/[\s_\-.]+/g,"");if(s==="serviceid"||s==="projectid")throw this._alert(`Replace "${t}" with your actual Project ID.`),new a("Project ID is required.",{code:"INVALID_PARAMETER"});let o=t.split("-").length;if(o===2||o===7)try{let b=Ot(t);n&&typeof n=="object"&&(i=n),r&&typeof r=="object"&&(n=r),r=b.owner,t=b.service;}catch{throw this._alert("Service ID is invalid."),new a("Service ID is invalid.",{code:"INVALID_PARAMETER"})}if(!r||typeof r!="string")throw this._alert("Owner ID is invalid."),new a("Owner ID is invalid.",{code:"INVALID_PARAMETER"});if(r!==this.host)try{y.UserId(r,'"owner"');}catch{throw this._alert("Owner ID is invalid."),new a("Owner ID is invalid.",{code:"INVALID_PARAMETER"})}this.service=t,this.owner=r;try{this.project_id=Lt(t,r);}catch{this.project_id="";}let u=true,g=false,f=null;if(n&&(typeof n.refetchServiceInfo=="boolean"&&(g=n.refetchServiceInfo),typeof n.autoLogin=="boolean"&&(u=n.autoLogin),n.encryption&&(f=rn(n.encryption)),typeof n.requestBatchSize=="number")){if(n.requestBatchSize<1)throw new a('"requestBatchSize" must be greater than 0.',{code:"INVALID_PARAMETER"});this.requestBatchSize=n.requestBatchSize;}n?.eventListener&&typeof n.eventListener=="object"&&(n.eventListener?.onLogin&&typeof n.eventListener.onLogin=="function"&&(this.onLogin=n.eventListener.onLogin),n.eventListener?.onUserUpdate&&typeof n.eventListener.onUserUpdate=="function"&&(this.onUserUpdate=n.eventListener.onUserUpdate),n.eventListener?.onBatchProcess&&typeof n.eventListener.onBatchProcess=="function"&&(this.onBatchProcess=n.eventListener.onBatchProcess)),this.target_cdn=i?.target_cdn||this.target_cdn,this.hostDomain=i?.hostDomain||this.hostDomain,this.customApiDomain=i?.customApiDomain||this.customApiDomain,this.__network_logs=!!i?.network_logs;let d=`https://${this.target_cdn}.cloudfront.net`,p=t.substring(0,4);this.admin_endpoint=fetch(`${d}/${p}/admin-${this.__endpoint_version}.json`).then(b=>b.blob()).then(b=>new Promise((E,k)=>{let S=new FileReader;S.onloadend=()=>E(S.result),S.onerror=k,S.readAsDataURL(b);})).then(b=>{try{return typeof b=="string"?JSON.parse(atob(b.split(",")[1])):null}catch{throw new a("Service does not exist. Create your service from skapi.com",{code:"NOT_EXISTS"})}}),this.record_endpoint=fetch(`${d}/${p}/record-${this.__endpoint_version}.json`).then(b=>b.blob()).then(b=>new Promise((E,k)=>{let S=new FileReader;S.onloadend=()=>E(S.result),S.onerror=k,S.readAsDataURL(b);})).then(b=>{try{return typeof b=="string"?JSON.parse(atob(b.split(",")[1])):null}catch{throw new a("Service does not exist. Create your service from skapi.com",{code:"NOT_EXISTS"})}});let m=J();if(m&&!window.sessionStorage)throw this._alert("This browser is not supported."),new Error("This browser is not supported.");let h=m?JSON.parse(window.sessionStorage.getItem(`${t}#${r}`)||"null"):null;if(this.log("constructor:restore",h),h?.connection){for(let b in h)this[b]=h[b];h.__public_identifier||(this.__public_identifier=`${this.service}:${this.owner}:${Ee(16)}`);}nn.bind(this)(f),this.__authConnection=(async()=>{let b=await this.admin_endpoint,E={UserPoolId:b.userpool_id,ClientId:b.userpool_client};Ct()&&(E.Storage=window.localStorage),this.userPool=new amazonCognitoIdentityJs.CognitoUserPool(E);try{this.user||await z.bind(this)().getSession({skipUserUpdateEventTrigger:!0}),this.user&&(!h?.connection&&!u?ye.bind(this)():(f&&Rn.bind(this)(),this._runOnLoginListeners(this.user),this._runOnUserUpdateListeners(this.user)));}catch{}})();let _=`${this.service}/${this.owner}`,w=m?window.sessionStorage.getItem(`${_}:uniqueids`):null;if(w)try{let b=JSON.parse(w);this.__my_unique_ids=b&&typeof b=="object"&&!Array.isArray(b)?{[_]:b}:{};}catch{this.__my_unique_ids={};}this.__connection=(async()=>{let b=null;await this.record_endpoint,h?.connection||(b=this._updateConnection({refresh:g}));let E=()=>{if(this.__class_properties_has_been_cached)return;let k=()=>{let S={},O=["__startKeyHistory","__disabledAccount","__cached_requests","__request_signup_confirmation","__public_identifier","connection"];if(this.connection){for(let L of O)S[L]=this[L];if(f&&(S.__cached_requests={},S.__startKeyHistory={}),m){let L=`${t}#${r}`;try{window.sessionStorage.setItem(L,JSON.stringify(S));}catch{try{let v=Object.assign({},S,{__cached_requests:{},__startKeyHistory:{}});window.sessionStorage.setItem(L,JSON.stringify(v));}catch{try{window.sessionStorage.removeItem(L);}catch{}}}}this.__class_properties_has_been_cached=true;}};return b instanceof Promise?b.then(()=>k()):k()};return m&&(window.addEventListener("beforeunload",()=>{this.closeRealtime(),E();}),window.addEventListener("visibilitychange",()=>{E();})),await b,await this.__authConnection,this.connection})(),this.__connection.then(b=>{((b?.group||0)<3||this.__network_logs)&&this.version();});}get user(){return this.__user&&Object.keys(this.__user).length?JSON.parse(JSON.stringify(this.__user)):null}set user(t){}get onLogin(){return this._onLoginListeners}set onLogin(t){typeof t=="function"&&this._onLoginListeners.push(t);}get onUserUpdate(){return this._userProfileListeners}set onUserUpdate(t){typeof t=="function"&&this._userProfileListeners.push(t);}_runOnUserUpdateListeners(t){for(let r of this._userProfileListeners)typeof r=="function"&&r(t);}_runOnLoginListeners(t){for(let r of this._onLoginListeners)typeof r=="function"&&r(t);}get onBatchProcess(){return this._onBatchProcessListeners}set onBatchProcess(t){typeof t=="function"&&this._onBatchProcessListeners.push(t);}_alert(t){J()&&typeof window.alert=="function"&&window.alert(t);}async getConnectionInfo(t){t?.refresh&&(this.__connection instanceof Promise&&await this.__connection,this.__connection=this._updateConnection({refresh:true}));let n=await this.__connection,i=n?.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:n.ip,user_agent:i,user_location:n.locale,service_name:n.service_name,version:this.__version,service_description:n?.service_description||"",ai_agent:n?.ai_agent||"",conf:n?.opt}}async _updateConnection(t){let r=t?.refresh||false;try{this.connection=await T.bind(this)("service",{service:this.service,owner:this.owner,refresh:r},{bypassAwaitConnection:!0,method:"get"});}catch(n){throw this.log("connection fail",n),this._alert("Service is not available: "+(n.message||n.toString())),this.connection=null,n}return this.connection}async version(){if(await this.__connection,J()){let r=`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(r,"font-family: monospace; color:blue;"),this.connection.group===1&&console.log("%cSKAPI: THE SERVICE IS IN TRIAL MODE.","font-family: monospace; color:red;");}return this.__version}log(t,r){if(this.__network_logs){if(r!==null&&typeof r=="object")try{G()?r=JSON.parse(JSON.stringify(r)):r=JSON.stringify(r,null,2);}catch{r=String(r);}else typeof r=="string"&&r.length>100&&(r=r.substring(0,100)+"...");console.log(`%c${t}:`,"color: blue;",r);}}getFeed(t,r){return qi.bind(this)(t,r)}closeRTC(t){return se.bind(this)(t)}connectRTC(t,r){return bi.bind(this)(t,r)}connectRealtime(t){return wt.bind(this)(t)}spellcast(t){return ds.bind(this)(t)}getspell(t){return fs.bind(this)(t)}dopamine(t){return gs.bind(this)(t)}getUniqueId(t,r){return li.bind(this)(t,r)}resendInvitation(t){return ss.bind(this)(t)}cancelInvitation(t){return is.bind(this)(t)}getInvitations(t,r){return ns.bind(this)(t,r)}openIdLogin(t){return In.bind(this)(t)}loginWithToken(t){return Pn.bind(this)(t)}clientSecretRequest(t){return Ci.bind(this)(t)}clientSecretRequestHistory(t,r){return Oi.bind(this)(t,r)}cancelClientSecretRequest(t){return Li.bind(this)(t)}stopClientSecretPolling(t){return xi.bind(this)(t||{})}isPollStopped(t){return Ui(t)}clientSecretRequestQueueCount(t){return Di.bind(this)(t)}consumeTicket(t){return bn.bind(this)(t)}getConsumedTickets(t,r){return wn.bind(this)(t,r)}getTickets(t,r){return _n.bind(this)(t,r)}closeRealtime(){return Ai.bind(this)()}getRealtimeUsers(t,r){return Ii.bind(this)(t,r)}sendInquiry(t){return Mi.bind(this)(t)}blockAccount(t){return Yi.bind(this)(t)}unblockAccount(t){return Xi.bind(this)(t)}deleteAccount(t){return Zi.bind(this)(t)}inviteUser(t,r){return es.bind(this)(t,r)}createAccount(t){return ts.bind(this)(t)}grantAccess(t){return rs.bind(this)(t)}updateUserAttributes(t){return os.bind(this)(t)}getRealtimeGroups(t,r){return Pi.bind(this)(t,r)}postRealtime(t,r,n){return Ri.bind(this)(t,r,n)}joinRealtime(t){return cr.bind(this)(t)}getProfile(t){return Rn.bind(this)(t)}getFile(t,r){return Ee.bind(this)(t,r)}secureRequest(t,r){return Fi.bind(this)(t,r)}forwardRequest(t,r){return $i.bind(this)(t,r)}getFormResponse(){return Hn.bind(this)()}getRecords(t,r){return ri.bind(this)(t,r)}getTables(t,r){return oi.bind(this)(t,r)}getIndexes(t,r){return ai.bind(this)(t,r)}getTags(t,r){return ci.bind(this)(t,r)}deleteRecords(t,r){return ui.bind(this)(t,r)}resendSignupConfirmation(){return Tn.bind(this)()}recoverAccount(t=false){return Sn.bind(this)(t)}getUsers(t,r){return Mn.bind(this)(t,r)}disableAccount(){return vn.bind(this)()}lastVerifiedEmail(t){return Fn.bind(this)(t)}unsubscribeNewsletter(t){return zi.bind(this)(t)}subscribeNotification(t,r){return as.bind(this)({endpoint:t,keys:r})}unsubscribeNotification(t,r){return cs.bind(this)({endpoint:t,keys:r})}vapidPublicKey(){return ls.bind(this)()}pushNotification(t,r){return us.bind(this)(t,r)}getNewsletters(t,r){return Ji.bind(this)(t,r)}getNewsletterSubscription(t,r){return Qi.bind(this)(t,r)}requestUsernameChange(t){return Vn.bind(this)(t)}getEncryptionStatus(){return qr.bind(this)()}isWithheld(t){return Ft.call(this,t)}unlockEncryption(t){return Xr.bind(this)(t)}lockEncryption(t){return Zr.bind(this)(t)}takeRecoveryCode(){return un.bind(this)()}unlockWithRecoveryCode(t){return dn.bind(this)(t)}regenerateRecoveryCode(){return fn.bind(this)()}pinPeerKey(t){return cn.bind(this)(t)}grantPrivateRecordAccess(t){return di.bind(this)(t)}removePrivateRecordAccess(t){return fi.bind(this)(t)}listPrivateRecordAccess(t,r){return gi.bind(this)(t,r)}requestPrivateRecordAccessKey(t){return pi.bind(this)(t)}deleteFiles(t){return Zn.bind(this)(t)}uploadFiles(t,r){return dt.bind(this)(t,r)}mock(t,r){return Vi.bind(this)(t,r)}login(t){return Yt.bind(this)(t)}logout(t){return Be.bind(this)(t)}signup(t,r){return kn.bind(this)(t,r)}resetPassword(t){return Un.bind(this)(t)}verifyEmail(t,r){return Dn.bind(this)(t,r)}verifyPhoneNumber(t,r){return xn.bind(this)(t,r)}forgotPassword(t,r){return Cn.bind(this)(t,r)}changePassword(t){return On.bind(this)(t)}updateProfile(t){return Ln.bind(this)(t)}postRecord(t,r,n){return si.bind(this)(t,r,n)}getSubscriptions(t,r){return ji.bind(this)(t,r)}subscribe(t){return Bi.bind(this)(t)}unsubscribe(t){return Ki.bind(this)(t)}blockSubscriber(t){return Hi.bind(this)(t)}unblockSubscriber(t){return Wi.bind(this)(t)}subscribeNewsletter(t){return Gi.bind(this)(t)}bulkPostRecords(t){return ii.bind(this)(t)}};R([I()],A.prototype,"getFeed"),R([I()],A.prototype,"closeRTC"),R([I()],A.prototype,"connectRTC"),R([I()],A.prototype,"spellcast"),R([I()],A.prototype,"getspell"),R([I()],A.prototype,"dopamine"),R([I()],A.prototype,"getUniqueId"),R([I()],A.prototype,"resendInvitation"),R([I()],A.prototype,"cancelInvitation"),R([I()],A.prototype,"getInvitations"),R([I()],A.prototype,"openIdLogin"),R([I()],A.prototype,"loginWithToken"),R([I()],A.prototype,"clientSecretRequest"),R([I()],A.prototype,"clientSecretRequestHistory"),R([I()],A.prototype,"cancelClientSecretRequest"),R([I()],A.prototype,"consumeTicket"),R([I()],A.prototype,"getConsumedTickets"),R([I()],A.prototype,"getTickets"),R([I()],A.prototype,"getRealtimeUsers"),R([I()],A.prototype,"sendInquiry"),R([I()],A.prototype,"blockAccount"),R([I()],A.prototype,"unblockAccount"),R([I()],A.prototype,"deleteAccount"),R([I()],A.prototype,"inviteUser"),R([I()],A.prototype,"createAccount"),R([I()],A.prototype,"grantAccess"),R([I()],A.prototype,"updateUserAttributes"),R([I()],A.prototype,"getRealtimeGroups"),R([I()],A.prototype,"postRealtime"),R([I()],A.prototype,"joinRealtime"),R([I()],A.prototype,"getProfile"),R([I()],A.prototype,"getFile"),R([I()],A.prototype,"secureRequest"),R([I()],A.prototype,"forwardRequest"),R([I()],A.prototype,"getFormResponse"),R([I()],A.prototype,"getRecords"),R([I()],A.prototype,"getTables"),R([I()],A.prototype,"getIndexes"),R([I()],A.prototype,"getTags"),R([I()],A.prototype,"deleteRecords"),R([I()],A.prototype,"resendSignupConfirmation"),R([I()],A.prototype,"recoverAccount"),R([I()],A.prototype,"getUsers"),R([I()],A.prototype,"disableAccount"),R([I()],A.prototype,"lastVerifiedEmail"),R([I()],A.prototype,"unsubscribeNewsletter"),R([I()],A.prototype,"subscribeNotification"),R([I()],A.prototype,"unsubscribeNotification"),R([I()],A.prototype,"vapidPublicKey"),R([I()],A.prototype,"pushNotification"),R([I()],A.prototype,"getNewsletters"),R([I()],A.prototype,"getNewsletterSubscription"),R([I()],A.prototype,"requestUsernameChange"),R([I()],A.prototype,"unlockEncryption"),R([I()],A.prototype,"unlockWithRecoveryCode"),R([I()],A.prototype,"grantPrivateRecordAccess"),R([I()],A.prototype,"removePrivateRecordAccess"),R([I()],A.prototype,"listPrivateRecordAccess"),R([I()],A.prototype,"requestPrivateRecordAccessKey"),R([I()],A.prototype,"deleteFiles"),R([I()],A.prototype,"uploadFiles"),R([I()],A.prototype,"mock"),R([I({preventMultipleCalls:true})],A.prototype,"login"),R([I()],A.prototype,"logout"),R([I({preventMultipleCalls:true})],A.prototype,"signup"),R([I({preventMultipleCalls:true})],A.prototype,"resetPassword"),R([I({preventMultipleCalls:true})],A.prototype,"verifyEmail"),R([I({preventMultipleCalls:true})],A.prototype,"verifyPhoneNumber"),R([I({preventMultipleCalls:true})],A.prototype,"forgotPassword"),R([I({preventMultipleCalls:true})],A.prototype,"changePassword"),R([I({preventMultipleCalls:true})],A.prototype,"updateProfile"),R([I()],A.prototype,"postRecord"),R([I()],A.prototype,"getSubscriptions"),R([I()],A.prototype,"subscribe"),R([I()],A.prototype,"unsubscribe"),R([I()],A.prototype,"blockSubscriber"),R([I()],A.prototype,"unblockSubscriber"),R([I()],A.prototype,"subscribeNewsletter");var Lo={};
233
- exports.Skapi=A;exports.SkapiError=c;exports.Types=Lo;//# sourceMappingURL=skapi.cjs.map
232
+ Full Documentation: https://docs.skapi.com/skapi.md`;console.log(r,"font-family: monospace; color:blue;"),this.connection.group===1&&console.log("%cSKAPI: THE SERVICE IS IN TRIAL MODE.","font-family: monospace; color:red;");}return this.__version}log(t,r){if(this.__network_logs){if(r!==null&&typeof r=="object")try{J()?r=JSON.parse(JSON.stringify(r)):r=JSON.stringify(r,null,2);}catch{r=String(r);}else typeof r=="string"&&r.length>100&&(r=r.substring(0,100)+"...");console.log(`%c${t}:`,"color: blue;",r);}}getFeed(t,r){return ns.bind(this)(t,r)}closeRTC(t){return ce.bind(this)(t)}connectRTC(t,r){return Ci.bind(this)(t,r)}connectRealtime(t){return St.bind(this)(t)}spellcast(t){return Ss.bind(this)(t)}getspell(t){return ks.bind(this)(t)}dopamine(t){return vs.bind(this)(t)}getUniqueId(t,r){return Pi.bind(this)(t,r)}resendInvitation(t){return Es.bind(this)(t)}cancelInvitation(t){return ws.bind(this)(t)}getInvitations(t,r){return _s.bind(this)(t,r)}openIdLogin(t){return jn.bind(this)(t)}loginWithToken(t){return Bn.bind(this)(t)}clientSecretRequest(t){return Ji.bind(this)(t)}clientSecretRequestHistory(t,r){return Yi.bind(this)(t,r)}cancelClientSecretRequest(t){return Xi.bind(this)(t)}stopClientSecretPolling(t){return Gi.bind(this)(t||{})}isPollStopped(t){return Wi(t)}clientSecretRequestQueueCount(t){return zi.bind(this)(t)}consumeTicket(t){return Ln.bind(this)(t)}getConsumedTickets(t,r){return Mn.bind(this)(t,r)}getTickets(t,r){return Fn.bind(this)(t,r)}closeRealtime(){return Mi.bind(this)()}getRealtimeUsers(t,r){return Vi.bind(this)(t,r)}sendInquiry(t){return Zi.bind(this)(t)}blockAccount(t){return gs.bind(this)(t)}unblockAccount(t){return ps.bind(this)(t)}deleteAccount(t){return hs.bind(this)(t)}inviteUser(t,r){return ys.bind(this)(t,r)}createAccount(t){return ms.bind(this)(t)}grantAccess(t){return bs.bind(this)(t)}updateUserAttributes(t){return As.bind(this)(t)}getRealtimeGroups(t,r){return qi.bind(this)(t,r)}postRealtime(t,r,n){return $i.bind(this)(t,r,n)}joinRealtime(t){return Ar.bind(this)(t)}getProfile(t){return qn.bind(this)(t)}getFile(t,r){return Ie.bind(this)(t,r)}secureRequest(t,r){return es.bind(this)(t,r)}forwardRequest(t,r){return rs.bind(this)(t,r)}getFormResponse(){return li.bind(this)()}getRecords(t,r){return _i.bind(this)(t,r)}getTables(t,r){return Ai.bind(this)(t,r)}getIndexes(t,r){return Ri.bind(this)(t,r)}getTags(t,r){return Ii.bind(this)(t,r)}deleteRecords(t,r){return Ti.bind(this)(t,r)}resendSignupConfirmation(){return Kn.bind(this)()}recoverAccount(t=false){return Hn.bind(this)(t)}getUsers(t,r){return ti.bind(this)(t,r)}disableAccount(){return Qn.bind(this)()}lastVerifiedEmail(t){return ri.bind(this)(t)}unsubscribeNewsletter(t){return ds.bind(this)(t)}subscribeNotification(t,r){return Rs.bind(this)({endpoint:t,keys:r})}unsubscribeNotification(t,r){return Is.bind(this)({endpoint:t,keys:r})}vapidPublicKey(){return Ps.bind(this)()}pushNotification(t,r){return Ts.bind(this)(t,r)}getNewsletters(t,r){return fs.bind(this)(t,r)}getNewsletterSubscription(t,r){return ls.bind(this)(t,r)}requestUsernameChange(t){return ni.bind(this)(t)}getEncryptionStatus(){return sn.bind(this)()}isWithheld(t){return Jt.call(this,t)}unlockEncryption(t){return bn.bind(this)(t)}lockEncryption(t){return _n.bind(this)(t)}takeRecoveryCode(){return kn.bind(this)()}unlockWithRecoveryCode(t){return vn.bind(this)(t)}regenerateRecoveryCode(){return Un.bind(this)()}pinPeerKey(t){return Tn.bind(this)(t)}grantPrivateRecordAccess(t){return Si.bind(this)(t)}removePrivateRecordAccess(t){return ki.bind(this)(t)}listPrivateRecordAccess(t,r){return vi.bind(this)(t,r)}requestPrivateRecordAccessKey(t){return Ui.bind(this)(t)}deleteFiles(t){return yi.bind(this)(t)}uploadFiles(t,r){return Ze.bind(this)(t,r)}mock(t,r){return ts.bind(this)(t,r)}login(t){return ur.bind(this)(t)}logout(t){return Je.bind(this)(t)}signup(t,r){return Wn.bind(this)(t,r)}resetPassword(t){return Gn.bind(this)(t)}verifyEmail(t,r){return Yn.bind(this)(t,r)}verifyPhoneNumber(t,r){return Jn.bind(this)(t,r)}forgotPassword(t,r){return Xn.bind(this)(t,r)}changePassword(t){return Zn.bind(this)(t)}updateProfile(t){return ei.bind(this)(t)}postRecord(t,r,n){return mr.bind(this)(t,r,n)}getSubscriptions(t,r){return is.bind(this)(t,r)}subscribe(t){return ss.bind(this)(t)}unsubscribe(t){return os.bind(this)(t)}blockSubscriber(t){return as.bind(this)(t)}unblockSubscriber(t){return cs.bind(this)(t)}subscribeNewsletter(t){return us.bind(this)(t)}bulkPostRecords(t){return Ei.bind(this)(t)}};I([P()],R.prototype,"getFeed"),I([P()],R.prototype,"closeRTC"),I([P()],R.prototype,"connectRTC"),I([P()],R.prototype,"spellcast"),I([P()],R.prototype,"getspell"),I([P()],R.prototype,"dopamine"),I([P()],R.prototype,"getUniqueId"),I([P()],R.prototype,"resendInvitation"),I([P()],R.prototype,"cancelInvitation"),I([P()],R.prototype,"getInvitations"),I([P()],R.prototype,"openIdLogin"),I([P()],R.prototype,"loginWithToken"),I([P()],R.prototype,"clientSecretRequest"),I([P()],R.prototype,"clientSecretRequestHistory"),I([P()],R.prototype,"cancelClientSecretRequest"),I([P()],R.prototype,"consumeTicket"),I([P()],R.prototype,"getConsumedTickets"),I([P()],R.prototype,"getTickets"),I([P()],R.prototype,"getRealtimeUsers"),I([P()],R.prototype,"sendInquiry"),I([P()],R.prototype,"blockAccount"),I([P()],R.prototype,"unblockAccount"),I([P()],R.prototype,"deleteAccount"),I([P()],R.prototype,"inviteUser"),I([P()],R.prototype,"createAccount"),I([P()],R.prototype,"grantAccess"),I([P()],R.prototype,"updateUserAttributes"),I([P()],R.prototype,"getRealtimeGroups"),I([P()],R.prototype,"postRealtime"),I([P()],R.prototype,"joinRealtime"),I([P()],R.prototype,"getProfile"),I([P()],R.prototype,"getFile"),I([P()],R.prototype,"secureRequest"),I([P()],R.prototype,"forwardRequest"),I([P()],R.prototype,"getFormResponse"),I([P()],R.prototype,"getRecords"),I([P()],R.prototype,"getTables"),I([P()],R.prototype,"getIndexes"),I([P()],R.prototype,"getTags"),I([P()],R.prototype,"deleteRecords"),I([P()],R.prototype,"resendSignupConfirmation"),I([P()],R.prototype,"recoverAccount"),I([P()],R.prototype,"getUsers"),I([P()],R.prototype,"disableAccount"),I([P()],R.prototype,"lastVerifiedEmail"),I([P()],R.prototype,"unsubscribeNewsletter"),I([P()],R.prototype,"subscribeNotification"),I([P()],R.prototype,"unsubscribeNotification"),I([P()],R.prototype,"vapidPublicKey"),I([P()],R.prototype,"pushNotification"),I([P()],R.prototype,"getNewsletters"),I([P()],R.prototype,"getNewsletterSubscription"),I([P()],R.prototype,"requestUsernameChange"),I([P()],R.prototype,"unlockEncryption"),I([P()],R.prototype,"unlockWithRecoveryCode"),I([P()],R.prototype,"grantPrivateRecordAccess"),I([P()],R.prototype,"removePrivateRecordAccess"),I([P()],R.prototype,"listPrivateRecordAccess"),I([P()],R.prototype,"requestPrivateRecordAccessKey"),I([P()],R.prototype,"deleteFiles"),I([P()],R.prototype,"uploadFiles"),I([P()],R.prototype,"mock"),I([P({preventMultipleCalls:true})],R.prototype,"login"),I([P()],R.prototype,"logout"),I([P({preventMultipleCalls:true})],R.prototype,"signup"),I([P({preventMultipleCalls:true})],R.prototype,"resetPassword"),I([P({preventMultipleCalls:true})],R.prototype,"verifyEmail"),I([P({preventMultipleCalls:true})],R.prototype,"verifyPhoneNumber"),I([P({preventMultipleCalls:true})],R.prototype,"forgotPassword"),I([P({preventMultipleCalls:true})],R.prototype,"changePassword"),I([P({preventMultipleCalls:true})],R.prototype,"updateProfile"),I([P()],R.prototype,"postRecord"),I([P()],R.prototype,"getSubscriptions"),I([P()],R.prototype,"subscribe"),I([P()],R.prototype,"unsubscribe"),I([P()],R.prototype,"blockSubscriber"),I([P()],R.prototype,"unblockSubscriber"),I([P()],R.prototype,"subscribeNewsletter");var sa={};
233
+ exports.Skapi=R;exports.SkapiError=a;exports.Types=sa;//# sourceMappingURL=skapi.cjs.map
234
234
  //# sourceMappingURL=skapi.cjs.map