skapi-js 2.2.11 → 2.2.13

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'),zo=require('cocochex'),Ts=require('qpass');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var zo__default=/*#__PURE__*/_interopDefault(zo);var Ts__default=/*#__PURE__*/_interopDefault(Ts);/**
1
+ 'use strict';var amazonCognitoIdentityJs=require('amazon-cognito-identity-js'),Da=require('cocochex'),oo=require('qpass');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var Da__default=/*#__PURE__*/_interopDefault(Da);var oo__default=/*#__PURE__*/_interopDefault(oo);/**
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 Uo=Object.defineProperty;var Co=Object.getOwnPropertyDescriptor;var ke=(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 P=(e,t,r,n)=>{for(var i=Co(t,r),s=e.length-1,o;s>=0;s--)(o=e[s])&&(i=(o(t,r,i))||i);return i&&Uo(t,r,i),i};function ve(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 ke=="function")return ke(e)}catch{}return null}var Gt,Wt,Qt=()=>Gt!==void 0?Gt:Gt=ve("fs"),zt=()=>Wt!==void 0?Wt:Wt=ve("path"),me=typeof globalThis<"u"?globalThis:void 0,mt=me?.window;function Oo(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(mt)mt.global=mt,mt.global._runningInNodeJS=false;else if(me&&(me.global=me,typeof me.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=Oo(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});});}}me.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);});}}me.XMLHttpRequest=t,me.window={_runningInNodeJS:true,alert:r=>console.error("[Alert]",r),sessionStorage:(()=>{let r=new Map;return {getItem:n=>r.has(n)?r.get(n):null,setItem:(n,i)=>{r.set(n,String(i));},removeItem:n=>{r.delete(n);}}})(),localStorage:{getItem:r=>{let n=Qt(),i=zt();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=Qt(),s=zt();if(!(!i||!s))try{let o=s.resolve(process.cwd(),"states","localStorage");i.existsSync(o)||i.mkdirSync(o,{recursive:!0});let l=s.resolve(o,`${r}.skapi`);i.writeFileSync(l,n,"utf8");}catch{}},removeItem:r=>{let n=Qt(),i=zt();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/${me?.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 ye="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",Jt=BigInt(ye.length),Lo=2*1024*1024,Mo=["aud","cognito:username","event_id","exp","iat","iss","jti","origin_jti","secret_key","token_use"],Xr={auth_time:"log",sub:"user_id"},nn=["0","1","2","3","4","5","6","7","8","9","a","b","c","d","e","f","g","h","i","j","k","l"],sn=["us31","us72","ap51","ap22","ap41","eu71","ap21","us32","us71","af51","ap31","ap43","ap23","ap42","ca01","eu01","eu72","eu51","eu73","eu11","me51","sa31"],Zr=typeof TextEncoder<"u"?new TextEncoder:null;function Fo(){if(typeof globalThis<"u")return globalThis.Buffer}function K(e){if(Zr)return Zr.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 Yt(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=Fo();if(t)return new Uint8Array(t.from(e));throw new Error("No byte conversion available in this environment.")}var R=class R{static hash(t){typeof t!="string"&&(console.warn("coercing non-string value to empty string"),t="");let r=R.sb(t),n=1732584193,i=-271733879,s=-1732584194,o=271733878,l,u,c,f;for(let p=0;p<r.length;p+=16)l=n,u=i,c=s,f=o,n=R.ff(n,i,s,o,r[p],7,-680876936),o=R.ff(o,n,i,s,r[p+1],12,-389564586),s=R.ff(s,o,n,i,r[p+2],17,606105819),i=R.ff(i,s,o,n,r[p+3],22,-1044525330),n=R.ff(n,i,s,o,r[p+4],7,-176418897),o=R.ff(o,n,i,s,r[p+5],12,1200080426),s=R.ff(s,o,n,i,r[p+6],17,-1473231341),i=R.ff(i,s,o,n,r[p+7],22,-45705983),n=R.ff(n,i,s,o,r[p+8],7,1770035416),o=R.ff(o,n,i,s,r[p+9],12,-1958414417),s=R.ff(s,o,n,i,r[p+10],17,-42063),i=R.ff(i,s,o,n,r[p+11],22,-1990404162),n=R.ff(n,i,s,o,r[p+12],7,1804603682),o=R.ff(o,n,i,s,r[p+13],12,-40341101),s=R.ff(s,o,n,i,r[p+14],17,-1502002290),i=R.ff(i,s,o,n,r[p+15],22,1236535329),n=R.gg(n,i,s,o,r[p+1],5,-165796510),o=R.gg(o,n,i,s,r[p+6],9,-1069501632),s=R.gg(s,o,n,i,r[p+11],14,643717713),i=R.gg(i,s,o,n,r[p],20,-373897302),n=R.gg(n,i,s,o,r[p+5],5,-701558691),o=R.gg(o,n,i,s,r[p+10],9,38016083),s=R.gg(s,o,n,i,r[p+15],14,-660478335),i=R.gg(i,s,o,n,r[p+4],20,-405537848),n=R.gg(n,i,s,o,r[p+9],5,568446438),o=R.gg(o,n,i,s,r[p+14],9,-1019803690),s=R.gg(s,o,n,i,r[p+3],14,-187363961),i=R.gg(i,s,o,n,r[p+8],20,1163531501),n=R.gg(n,i,s,o,r[p+13],5,-1444681467),o=R.gg(o,n,i,s,r[p+2],9,-51403784),s=R.gg(s,o,n,i,r[p+7],14,1735328473),i=R.gg(i,s,o,n,r[p+12],20,-1926607734),n=R.hh(n,i,s,o,r[p+5],4,-378558),o=R.hh(o,n,i,s,r[p+8],11,-2022574463),s=R.hh(s,o,n,i,r[p+11],16,1839030562),i=R.hh(i,s,o,n,r[p+14],23,-35309556),n=R.hh(n,i,s,o,r[p+1],4,-1530992060),o=R.hh(o,n,i,s,r[p+4],11,1272893353),s=R.hh(s,o,n,i,r[p+7],16,-155497632),i=R.hh(i,s,o,n,r[p+10],23,-1094730640),n=R.hh(n,i,s,o,r[p+13],4,681279174),o=R.hh(o,n,i,s,r[p],11,-358537222),s=R.hh(s,o,n,i,r[p+3],16,-722521979),i=R.hh(i,s,o,n,r[p+6],23,76029189),n=R.hh(n,i,s,o,r[p+9],4,-640364487),o=R.hh(o,n,i,s,r[p+12],11,-421815835),s=R.hh(s,o,n,i,r[p+15],16,530742520),i=R.hh(i,s,o,n,r[p+2],23,-995338651),n=R.ii(n,i,s,o,r[p],6,-198630844),o=R.ii(o,n,i,s,r[p+7],10,1126891415),s=R.ii(s,o,n,i,r[p+14],15,-1416354905),i=R.ii(i,s,o,n,r[p+5],21,-57434055),n=R.ii(n,i,s,o,r[p+12],6,1700485571),o=R.ii(o,n,i,s,r[p+3],10,-1894986606),s=R.ii(s,o,n,i,r[p+10],15,-1051523),i=R.ii(i,s,o,n,r[p+1],21,-2054922799),n=R.ii(n,i,s,o,r[p+8],6,1873313359),o=R.ii(o,n,i,s,r[p+15],10,-30611744),s=R.ii(s,o,n,i,r[p+6],15,-1560198380),i=R.ii(i,s,o,n,r[p+13],21,1309151649),n=R.ii(n,i,s,o,r[p+4],6,-145523070),o=R.ii(o,n,i,s,r[p+11],10,-1120210379),s=R.ii(s,o,n,i,r[p+2],15,718787259),i=R.ii(i,s,o,n,r[p+9],21,-343485551),n=R.ad(n,l),i=R.ad(i,u),s=R.ad(s,c),o=R.ad(o,f);return R.rh(n)+R.rh(i)+R.rh(s)+R.rh(o)}static rh(t){let r="";for(let n=0;n<=3;n++)r+=R.alphabet.charAt(t>>n*8+4&15)+R.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 R.ad(R.rl(R.ad(R.ad(r,t),R.ad(i,o)),s),n)}static ff(t,r,n,i,s,o,l){return R.cm(r&n|~r&i,t,r,s,o,l)}static gg(t,r,n,i,s,o,l){return R.cm(r&i|n&~i,t,r,s,o,l)}static hh(t,r,n,i,s,o,l){return R.cm(r^n^i,t,r,s,o,l)}static ii(t,r,n,i,s,o,l){return R.cm(n^(r|~i),t,r,s,o,l)}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}};R.alphabet="0123456789abcdef";var Z=R;function on(e){if(e===0)return ye[0];let t="";for(;e>0;)t=ye[e%62]+t,e=Math.floor(e/62);return t}function se(e){return e.split("").reverse().reduce((t,r,n)=>t+ye.indexOf(r)*62**n,0)}function Te(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 Xt(){return typeof window>"u"||!!window?._runningInNodeJS}function H(){return !Xt()&&typeof document<"u"&&typeof document.createElement=="function"}function yt(e){let t;try{t=JSON.stringify(e);}catch{throw new a("Invalid data type.",{code:"INVALID_REQUEST"})}if(new Blob([t]).size>Lo)throw new a("Data should not exceed 2MB",{code:"INVALID_REQUEST"})}function en(e){return e===""||e==="on"||e==="true"}function tn(e){return e==="false"}function rn(e,t,r){t.name&&r(e,t.name,t.value);}var bt=H(),qo=typeof SubmitEvent<"u",Vo=typeof HTMLFormElement<"u";function j(e,t,r){let n={},i=[];function s(u,c,f){if(t?.ignoreEmpty&&f==="")return;if(t?.nullIfEmpty&&f===""&&(f=null),typeof r=="function"){let g=r(c,f);g!==void 0&&(f=g);}let p=c.split("[").map(g=>{let h=g.replace("]",""),m=Number(h);return !isNaN(m)&&!h.includes(".")?h=m:(h[0]==='"'&&h[h.length-1]==='"'||h[0]==="'"&&h[h.length-1]==="'")&&(h=h.replace(/"/g,"").replace(/'/g,"")),h}),d=u;if(typeof p[0]=="number")throw new a("Form key cannot start with an array index.",{code:"INVALID_REQUEST"});for(let g=0;g<p.length;g++){let h=p[g];g<p.length-1?(d[h]===void 0&&(typeof p[g+1]=="number"?d[h]=[]:d[h]={}),d=d[h]):d[h]===void 0?d[h]=f:Array.isArray(d[h])?d[h].push(f):d[h]=[d[h],f];}}function o(u,c,f){if(f instanceof File)u.push({name:c,file:f});else if(f instanceof FileList&&f&&f.length>0)for(let p=0;p<=f.length-1;p++){let d=f.item(p);d&&u.push({name:c,file:d});}}let l=u=>{u.name&&(u.type==="number"?u.value&&s(n,u.name,Number(u.value)):u.type==="checkbox"||u.type==="radio"?u.checked?u.type==="checkbox"&&u.value===""||en(u.value)?s(n,u.name,true):tn(u.value)?s(n,u.name,false):u.value&&s(n,u.name,u.value):u.type==="checkbox"&&(en(u.value)?s(n,u.name,false):tn(u.value)&&s(n,u.name,true)):u.type==="file"?u.files&&u.files.length>0&&o(i,u.name,u.files):s(n,u.name,u.value));};if(bt&&(e instanceof HTMLInputElement||e instanceof HTMLSelectElement||e instanceof HTMLTextAreaElement))return l(e),yt(n),{data:n,files:i};if(bt&&e instanceof FormData){for(let u of e.entries()){let c=u[0],f=u[1];if(f instanceof File||f instanceof FileList)o(i,c,f);else if(f instanceof Blob){let p=f;if(p.type==="application/json")try{let d=JSON.parse(p.text());s(n,c,d);}catch{s(n,c,p);}}else s(n,c,f);}return yt(n),{data:n,files:i}}if(bt&&qo&&e instanceof SubmitEvent&&(e=e.target),bt&&Vo&&e instanceof HTMLFormElement){let u=e.querySelectorAll("input"),c=e.querySelectorAll("select"),f=e.querySelectorAll("textarea");for(let p=0;p<c.length;p++)rn(n,c[p],s);for(let p=0;p<f.length;p++)rn(n,f[p],s);for(let p=0;p<u.length;p++)l(u[p]);return yt(n),{data:n,files:i}}return yt(e),{data:e,files:i}}function Ge(e){let t={};for(let r in e){let n=e[r];if(!Mo.includes(r))if(Xr[r])t[Xr[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 Zt(e){if(e=Qo(e),e.split("-").length===7){let t=e.split("-"),r,n;try{r=sn[nn.indexOf(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 er(e,t){let r=sn.indexOf(e.slice(0,4)),n=nn[r],s=`${e.slice(4,-4)}-${n}${e.slice(-4)}-${t}`;return Wo(s)}function jo(e){let t=0n;for(let r of e){let n=ye.indexOf(r);if(n<0)throw new Error(`INVALID_PARAMETER: Invalid base62 character: ${r}`);t=t*Jt+BigInt(n);}return t}function $o(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%Jt);r=ye[i]+r,n/=Jt;}return r.length<t&&(r="0".repeat(t-r.length)+r),r}function Bo(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 Ko(e){let t=0n;for(let r of e)t=(t<<8n)+BigInt(r);return t}function Ho(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 Go(e){let t=Array.from(Yt(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 Wo(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>=ye.length)throw new Error("INVALID_PARAMETER: The middle section is too long to encode.");let o=n.slice(0,2),l=n.slice(2),u=i+o,c=ye[i.length]+l+u,f=Ho(s),p=$o(Ko(f));return `${c}-${p}`}function Qo(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=ye.indexOf(n[0]);if(s<0)throw new Error("INVALID_PARAMETER: Corrupt compressed token: "+t);let o=n.slice(1),l=s+2;if(o.length<l)throw new Error("INVALID_PARAMETER: Corrupt compressed token: "+t);let u=o.slice(0,o.length-l),c=o.slice(o.length-l),f=c.slice(s),p=c.slice(0,s),d=f+u;if(!/^[0-9A-Za-z]+$/.test(d)||!/^[0-9A-Za-z]+$/.test(p))throw new Error("INVALID_PARAMETER: Corrupt compressed token: "+t);let g=jo(i),h=Bo(g);if(h.length>16)throw new Error("INVALID_PARAMETER: Corrupt compressed token: "+t);let m=new Uint8Array(16);m.set(h,16-h.length);let _=Go(m);return `${d}-${p}-${_}`}function We(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 tr(...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 Jo(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 Yo(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 Xo(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 Zo(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 ea(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 ta(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 l=t?window.location.href.split("?")[0]:"";l.slice(-1)!=="/"&&(l+="/"),s=l+s.slice(1);}let o;try{o=new URL(s);}catch{throw new a(`"${i}" is an invalid url.`,{code:"INVALID_PARAMETER"})}if(o.protocol)return o.href}}throw new a(`"${i}" is an invalid url.`,{code:"INVALID_PARAMETER"})};return Array.isArray(e)?e.map(i=>n(i)):n(e)}var ra=/^[a-z0-9]{2,20}$/,na=/[a-z]/,ia=/^[0-9]+e[0-9]+$/,sa=["tp","admin","public","authorized","newsletter","forward","all","true","false","null"];function oa(e,t){if(e==null){if(t?.allowNull)return null;throw new a('"group" is required.',{code:"INVALID_PARAMETER"})}if(!t?.nameOnly){if(e==="public")return 0;if(e==="authorized")return 1;if(typeof e=="number"){if(!Number.isInteger(e)||e<0||e>99)throw new a('"group" should be an integer between 0 and 99.',{code:"INVALID_PARAMETER"});return e}}if(typeof e!="string"||!ra.test(e)||!na.test(e)||ia.test(e)||sa.includes(e))throw new a("Newsletter group name must be 2-20 lowercase alphanumeric characters, contain a letter, and not be a reserved name.",{code:"INVALID_PARAMETER"});return e}function aa(e,t,r=[],n){let i=j(e,n),s=i.data;t.service="string",t.owner="string";let o={};for(let l in t)if(s&&typeof s=="object"&&!Array.isArray(s)&&s.hasOwnProperty(l))if(typeof s[l]=="function")o[l]=s[l];else try{o[l]=JSON.parse(JSON.stringify(s[l]));}catch{o[l]=s[l];}n?.precall&&n.precall({data:o,files:i?.files||[]});try{return zo__default.default(o,t,r)}catch(l){throw new a(l.message,{code:"INVALID_PARAMETER"})}}var y={UserId:Jo,PhoneNumber:Yo,Birthdate:Xo,Password:Zo,Email:ea,Url:ta,newsletterGroup:oa,Params:aa};var Y="skapi.enc.v1",cn=6e5,Qe=12,_t=null,Ne=null;function un(){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 dn(){if(Ne)return Ne;let e=typeof globalThis<"u"?globalThis:void 0;if(e?.crypto?.subtle&&typeof e.crypto.getRandomValues=="function")return Ne=e.crypto,Ne;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 ke=="function"&&(r=ke("crypto")),r?.webcrypto?.subtle)return Ne=r.webcrypto,Ne}catch{}throw un()}function re(){if(_t)return _t;let e=dn();if(!e.subtle)throw un();return _t=e.subtle,_t}function nr(){try{return re(),!0}catch{return false}}function X(e){let t=dn(),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 V(e){let t=Yt(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 wt(e){let t=await re().digest("SHA-256",e);return new Uint8Array(t)}async function Ye(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 xe(e,t,r,n){let i=re(),s=K(e.normalize("NFC")),o=await i.importKey("raw",s,"PBKDF2",false,["deriveBits"]),l=new Uint8Array(await i.deriveBits({name:"PBKDF2",salt:t,iterations:r,hash:"SHA-256"},o,256)),u=await Ye(l,t,n,32);q(l),q(s);let c=await oe(u);return q(u),c}async function oe(e){return re().importKey("raw",e,{name:"AES-GCM"},false,["encrypt","decrypt"])}async function fn(){let e=X(32),t=await oe(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 ae(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 Et={name:"ECDH",namedCurve:"P-256"};async function pn(){let e=re(),t=await e.generateKey(Et,true,["deriveBits"]),r=new Uint8Array(await e.exportKey("raw",t.publicKey)),n=new Uint8Array(await e.exportKey("pkcs8",t.privateKey)),i=await ir(n);return {pubRaw:r,pkcs8:n,priv:i}}async function ir(e){return re().importKey("pkcs8",e,Et,false,["deriveBits"])}async function gn(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,Et,false,[])}async function sr(e){return V(await wt(e))}async function hn(e,t,r,n){let i=re(),s=await gn(e),o=await i.generateKey(Et,true,["deriveBits"]),l=new Uint8Array(await i.deriveBits({name:"ECDH",public:s},o.privateKey,256)),u=await Ye(l,new Uint8Array(32),r,32);q(l);let c=await oe(u);q(u);let{iv:f,ct:p}=await ne(c,t,n);return {epk:new Uint8Array(await i.exportKey("raw",o.publicKey)),iv:f,ct:p}}async function mn(e,t,r,n,i,s){let o=re(),l=await gn(t),u=new Uint8Array(await o.deriveBits({name:"ECDH",public:l},e,256)),c=await Ye(u,new Uint8Array(32),i,32);q(u);let f=await oe(c);return q(c),ae(f,r,n,s)}function q(e){e&&e.length&&e.fill(0);}function la(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 or(e){return K(JSON.stringify(e))}function Xe(e,t,r){return tr(e,new Uint8Array([0]),K(t),new Uint8Array([0]),K(r))}var Ie="0123456789ABCDEFGHJKMNPQRSTVWXYZ",ze=16,an=26,ln=28;function yn(e){let t=2166136261;for(let r=0;r<e.length;r++)t^=e[r],t=t*16777619>>>0;return t&1023}function bn(e){if(e.length!==ze)throw new a(`A recovery code needs exactly ${ze} 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+=Ie[r>>n&31];n>0&&(t+=Ie[r<<5-n&31]);let i=yn(e);return t+=Ie[i>>5&31]+Ie[i&31],(t.match(/.{1,4}/g)||[]).join("-")}function _n(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!==ln)throw new a(`That does not look like a recovery code: expected ${ln} characters, got ${t.length}.`,{code:"ENCRYPTION_BAD_RECOVERY_CODE"});let r=t.slice(0,an),n=t.slice(an),i=0,s=0,o=[];for(let c=0;c<r.length;c++){let f=Ie.indexOf(r[c]);if(f<0)throw new a(`That does not look like a recovery code: "${r[c]}" is not a valid character.`,{code:"ENCRYPTION_BAD_RECOVERY_CODE"});i=i<<5|f,s+=5,s>=8&&(s-=8,o.push(i>>s&255));}let l=new Uint8Array(o.slice(0,ze)),u=yn(l);if(n!==Ie[u>>5&31]+Ie[u&31])throw new a("That recovery code has a typo in it: the check characters do not match.",{code:"ENCRYPTION_BAD_RECOVERY_CODE"});return l}async function ar(e,t,r){let n=await Ye(e,t,r,32),i=await oe(n);return q(n),i}var rr=[83,75,69,78,67,70],wn=2,Je=56,En=16,ca=4*1024*1024;function lr(e){if(!e||e.length<Je)return false;for(let t=0;t<rr.length;t++)if(e[t]!==rr[t])return false;return true}function Pe(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 De(e,t){return (e[t]<<24>>>0)+(e[t+1]<<16)+(e[t+2]<<8)+e[t+3]}function ua(e,t,r){let n=Math.floor(r/4294967296);Pe(e,t,n),Pe(e,t+4,r>>>0);}function da(e,t){return De(e,t)*4294967296+De(e,t+4)}async function An(e,t,r,n,i,s){let o=K(`${Y}|binfile|${r}|${n}|${i}|${s}`),l=await Ye(e,t,o,32),u=await oe(l);return q(l),u}async function Rn(e){return (await wt(tr(K(`${Y}|dekid`),e))).subarray(0,8)}function Tn(e,t,r){return or([`${Y}|binchunk`,V(e),t,r])}function fa(e,t,r,n,i,s){let o=new Uint8Array(Je+s.length);return o.set(rr,0),o[6]=wn,o[7]=s.length?1:0,Pe(o,8,e),Pe(o,12,t),o.set(r,16),ua(o,32,n),o.set(i,40),Pe(o,48,s.length),Pe(o,52,0),s.length&&o.set(s,Je),o}async function In(e,t,r,n,i=ca){let s=X(En),o=await An(e,s,r.service,r.owner,r.recordOwner,r.recordId),l=await Rn(e),u=n?K(JSON.stringify(n)):new Uint8Array(0);if(u.length>4096)throw new a("Encrypted file metadata is too large.",{code:"INVALID_PARAMETER"});let c=t.length===0?1:Math.ceil(t.length/i),f=fa(i,c,s,t.length,l,u),p=await wt(f),d=[],g=f.length;for(let _=0;_<c;_++){let b=t.subarray(_*i,Math.min((_+1)*i,t.length)),A=await ne(o,b,Tn(p,_,c));d.push(A),g+=4+A.iv.length+A.ct.length;}let h=new Uint8Array(g);h.set(f,0);let m=f.length;for(let _ of d)Pe(h,m,_.iv.length+_.ct.length),m+=4,h.set(_.iv,m),m+=_.iv.length,h.set(_.ct,m),m+=_.ct.length;return h}function pa(e){if(!lr(e))throw new a("This file is not an encrypted skapi file.",{code:"INVALID_PARAMETER"});let t=De(e,48),r=Je+t;if(e.length<r)throw new a("Encrypted file header is truncated.",{code:"INVALID_REQUEST"});let n=null;return t&&(n=JSON.parse(We(e.subarray(Je,r)))),{version:e[6],chunkBytes:De(e,8),count:De(e,12),fileId:e.subarray(16,16+En),plainLen:da(e,32),dekId:e.subarray(40,48),meta:n,headerLen:r}}async function Pn(e,t,r){let n=pa(t);if(n.version!==wn)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 Rn(e);if(!la(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 An(e,n.fileId,r.service,r.owner,r.recordOwner,r.recordId),o=await wt(t.subarray(0,n.headerLen)),l=[],u=n.headerLen,c=0;for(let d=0;d<n.count;d++){if(u+4>t.length)throw new a("Encrypted file is truncated.",{code:"INVALID_REQUEST"});let g=De(t,u);if(u+=4,g<Qe+16||u+g>t.length)throw new a("Encrypted file is truncated.",{code:"INVALID_REQUEST"});let h=await ae(s,t.subarray(u,u+Qe),t.subarray(u+Qe,u+g),Tn(o,d,n.count));u+=g,l.push(h),c+=h.length;}let f=new Uint8Array(c),p=0;for(let d of l)f.set(d,p),p+=d.length;return {bytes:f,meta:n.meta}}var ga="__skapi__keyring",Ze="__skapi_enc__",kn=1,ha="skapi-enc",Ae="keys",ur=new WeakMap;function vn(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:cn;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:ga}}function L(){return ur.get(this)||null}function Nn(e){if(!e){ur.delete(this);return}ur.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 dr(){let e=L.call(this);if(e){e.user_id&&Ar.call(this,e).catch(()=>{}),e.ready=null,e.unlocking=false,e.pendingRecoveryCode="";for(let[,t]of e.dek)q(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 Dn(){let e=L.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 xn(e,t){return typeof t=="string"&&t===e.cfg.table}function Ue(){return `${this.service}/${this.owner}`}function fr(e,t,r,n){let[i,s]=e.split("/");return or([Y,i,s,t,r,n])}function Un(e,t,r,n,i){let[s,o]=e.split("/");return K(`${Y}|dekwrap|${s}|${o}|${t}|${r}|${n}|${i}`)}function pr(e){return e.anch==="uid"?e.uid:e.anch==="rid"?e.rid:""}function Rt(e){return !!e&&typeof e=="object"&&!Array.isArray(e)&&typeof e[Ze]=="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 ee(e,t,r){if(e.withheld!=="sentinel")return null;let n={[Cn]:true,reason:t};return r&&(n.recipients=r),Object.freeze(n)}function gr(e){return !!e&&typeof e=="object"&&e[Cn]===true}var ma=256*1024,rt="__skenc_ct__",On="payload.bin",ya=`/${rt}/${On}`;function hr(e,t){return e===rt&&t===On}async function ba(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:Sn(n.access_group),table:i,record:null};if(!r)return {group:n?.access_group!==void 0?Sn(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 Ee.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 _a(e){return this.getFile(e,{dataType:"blob"})}async function Ee(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 Sn(e){return e==="private"||e==="*"||e==="**"?"private":e==="public"?0:e==="authorized"?1:e==="admin"?99:typeof e=="number"?e:0}function cr(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 mr(e,t,r){let n=L.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 F=n.passthrough.get(i);return n.passthrough.delete(i),{send:F,plain:e,encrypted:true,omit:false}}let{group:l,table:u,record:c}=await ba.call(this,n,t,s);if(l!=="private"){let F=true;if(!r&&i){let z=c||await Ee.call(this,i);if(z&&z.encrypted){if(cr.call(this,z,i,"making it non-private"),z.encrypted.status==="failed")throw new a(`Cannot make record "${i}" non-private: its current contents could not be decrypted (${z.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 He=!!z.bin&&Object.keys(z.bin).some(ht=>(z.bin[ht]||[]).some(Yr=>Yr&&Yr.encrypted));if(!He&&s){let ht=n.dek.get(s);ht&&(q(ht.bytes),n.dek.delete(s));}return {send:z.data,plain:z.data,encrypted:false,omit:false,files:He?"decrypt":void 0}}}let J=c;i&&!J&&(J=await Ee.call(this,i).catch(()=>null)),J&&J.encrypted&&cr.call(this,J,i,"making it non-private");let gt=!!J&&!!J.bin&&Object.keys(J.bin).some(z=>(J.bin[z]||[]).some(He=>He&&He.encrypted));if(gt&&(F=false),F&&s){let z=n.dek.get(s);z&&(q(z.bytes),n.dek.delete(s));}return {send:e,plain:e,encrypted:false,omit:!r,files:gt?"decrypt":void 0}}if(xn(n,u))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(gr.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,Ze))throw new a(`"${Ze}" 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 f=this.user?.user_id;if(!f)throw new a("User login is required to write an encrypted record.",{code:"INVALID_REQUEST"});let p=Ue.call(this),d=false;if(i&&n.roll.has(i)){d=true,n.roll.delete(i);let F=n.dek.get(i);n.dek.delete(i),F&&q(F.bytes);}let g=c;i&&!g&&!n.dek.has(i)&&(g=await Ee.call(this,i).catch(()=>null)),g&&cr.call(this,g,i,"making it private");let h=!!g&&!g.encrypted&&!!g.bin&&Object.keys(g.bin).some(F=>(g.bin[F]||[]).some(J=>J&&!J.encrypted)),m=null;if(i&&!d&&(m=n.dek.get(i)||null,!m)){let F=g||c||await Ee.call(this,i);if(F&&(s=F.record_id||i,m=n.dek.get(s)||null,!o&&F.unique_id&&(o=F.unique_id),!m&&F.encrypted?.status==="failed"))throw new a(`Cannot update encrypted record "${i}": its current contents could not be decrypted (${F.encrypted.reason}), so its existing key wraps cannot be preserved. Updating anyway would revoke everyone it is shared with.`,{code:"ENCRYPTION_LOCKED"})}s===i&&m&&m.rid&&(s=m.rid),!o&&m&&m.anch==="uid"&&m.uid&&(o=m.uid);let _,b,A;if(m){if(m.own&&m.own!==f)throw new a(`Record "${i}" belongs to another user (${m.own}). Encryption only operates on records you own.`,{code:"ENCRYPTION_NOT_RECORD_OWNER"});_=m.bytes,b=m.key,A=Object.assign({},m.recipients);}else {let F=await fn();_=F.bytes,b=F.key,A={};}let w=o?"uid":s?"rid":"new",I=w==="uid"?o:w==="rid"?s:"",E=fr(p,f,w,I),N=Xe(E,f,"mk"),C=await ne(n.mk,_,N);A[f]={t:"mk",iv:V(C.iv),ct:V(C.ct)},m&&(m.anch!==w||pr(m)!==I)&&(A=await wa.call(this,n,_,A,p,f,w,I,E));let D=K(JSON.stringify(e===void 0?null:e)),v=await ne(b,D,E);q(D);let x={[Ze]:kn,enc:"A256GCM",kw:"ECDH-ES+A256GCM",anch:w,uid:o,rid:s,own:f,iv:V(v.iv),ct:V(v.ct),k:A},U,M,de=x.ct;s&&de.length>ma&&(U=$(de),x.ct="",x.ct_ref=ya,m&&m.ctRef&&(M=m.ctRef));let ie=JSON.stringify(x).length;if(ie>2*1024*1024)throw new a(`Encrypted record data is too large: once encrypted and base64 encoded it becomes ${ie} bytes, over the ${2*1024*1024} byte limit. Encryption costs about 33% plus roughly 230 bytes per additional recipient.`,{code:"ENCRYPTED_DATA_TOO_LARGE"});return s&&n.dek.set(s,{bytes:_,key:b,recipients:A,anch:w,uid:o,rid:s,own:f,access_group:"private"}),{send:x,plain:e,encrypted:true,omit:false,spill:U,retireCt:M,dek:{bytes:_,key:b,recipients:A,anch:w,uid:o,rid:s,own:f,access_group:"private"},files:h?"encrypt":void 0}}function Ln(e,t){let r=L.call(this);!r||!t||!e||r.dek.has(e)||r.dek.set(e,Object.assign({},t,{rid:e}));}async function wa(e,t,r,n,i,s,o,l){let u=Object.keys(r).filter(p=>p!==i);if(!u.length)return r;let c=await Rr.call(this,u),f={[i]:r[i]};for(let p of u){let d=c[p];d&&(f[p]=await Mn.call(this,t,d,n,o,i,p,l));}return f}async function Mn(e,t,r,n,i,s,o){let l=Un(r,n,i,s,t.fpr),u=Xe(o,s,t.fpr),c=await hn(t.pubRaw,e,l,u);return {t:"ecdh",epk:V(c.epk),iv:V(c.iv),ct:V(c.ct),fpr:t.fpr}}async function Fn(e,t){if(!Rt(e))return {value:e};if(t.access_group!=="private")return {value:e};let r=L.call(this);if(!r)return {value:null,flag:{status:"failed",reason:"ENCRYPTION_DISABLED"}};if(r.rawRead)return {value:e};if(xn(r,t.table_name))return {value:e};if(e[Ze]!==kn)return {value:ee(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:ee(r.cfg,"BINDING_MISMATCH"),flag:{status:"failed",reason:"BINDING_MISMATCH"}};if(e.uid&&t.unique_id&&e.uid!==t.unique_id)return {value:ee(r.cfg,"BINDING_MISMATCH"),flag:{status:"failed",reason:"BINDING_MISMATCH"}};if(e.rid&&t.record_id&&e.rid!==t.record_id)return {value:ee(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:ee(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:ee(r.cfg,"NO_SESSION_KEY"),flag:{status:"failed",reason:"NO_SESSION_KEY"}};let s=Ue.call(this),o=pr(e),l=fr(s,e.own,e.anch,o),u;try{if(i.t==="mk")u=await ae(r.mk,$(i.iv),$(i.ct),Xe(l,n,"mk"));else if(i.t==="ecdh"){if(!r.ikPriv)return {value:ee(r.cfg,"NO_SESSION_KEY"),flag:{status:"failed",reason:"NO_SESSION_KEY"}};u=await mn(r.ikPriv,$(i.epk),$(i.iv),$(i.ct),Un(s,o,e.own,n,i.fpr),Xe(l,n,i.fpr));}else return {value:ee(r.cfg,"UNSUPPORTED_VERSION"),flag:{status:"failed",reason:"UNSUPPORTED_VERSION"}}}catch{return {value:ee(r.cfg,"BAD_KEY"),flag:{status:"failed",reason:"BAD_KEY"}}}let c;try{if(e.ct_ref){if(!t.ctUrl)return q(u),{value:ee(r.cfg,"DATA_UNAVAILABLE"),flag:{status:"failed",reason:"DATA_UNAVAILABLE"}};let g=await _a.call(this,t.ctUrl);c=new Uint8Array(await g.arrayBuffer());}else c=$(e.ct);}catch{return q(u),{value:ee(r.cfg,"DATA_UNAVAILABLE"),flag:{status:"failed",reason:"DATA_UNAVAILABLE"}}}let f,p;try{p=await oe(u),f=await ae(p,$(e.iv),c,l);}catch{return q(u),{value:ee(r.cfg,"CORRUPT"),flag:{status:"failed",reason:"CORRUPT"}}}let d;try{d=JSON.parse(We(f));}catch{return q(f),q(u),{value:ee(r.cfg,"CORRUPT"),flag:{status:"failed",reason:"CORRUPT"}}}if(q(f),t.record_id){let g=r.dek.get(t.record_id);g?(g.bytes=u,g.key=p,g.recipients=e.k,g.anch=e.anch,g.uid=e.uid,g.own=e.own,g.access_group="private",g.ctRef=e.ct_ref||""):r.dek.set(t.record_id,{bytes:u,key:p,recipients:e.k,anch:e.anch,uid:e.uid,rid:t.record_id,own:e.own,access_group:"private",ctRef:e.ct_ref||""});}else q(u);return {value:d,flag:{status:"encrypted",recipients:Object.keys(e.k)}}}function et(e,t){let[r,n]=e.split("/");return K(`${Y}|kek|${r}|${n}|${t}`)}function tt(e,t,r,n){let[i,s]=e.split("/");return K(`${Y}|mk|${i}|${s}|${t}|PBKDF2-SHA256|${r}|${n}`)}function qn(e,t){let[r,n]=e.split("/");return K(`${Y}|recovery|${r}|${n}|${t}`)}function Vn(e,t,r){let[n,i]=e.split("/");return K(`${Y}|rk|${n}|${i}|${t}|HKDF-SHA256|${r}`)}function jn(e,t){let[r,n]=e.split("/");return K(`${Y}|self|${r}|${n}|${t}`)}function $n(e,t){let[r,n]=e.split("/");return K(`${Y}|ik|${r}|${n}|${t}`)}async function Tt(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 yr(e,t,r){let n=X(ze),i=bn(n),s=X(16),o=V(s),l=await ar(n,s,qn(e,t)),u=await ne(l,r,Vn(e,t,o));return q(n),{code:i,wrap:{id:V(X(6)),p:"recovery",kdf:{a:"HKDF-SHA256",s:o},iv:V(u.iv),ct:V(u.ct),created:Date.now()}}}async function Ea(e,t,r,n){let i=_n(n),s=(r||[]).filter(o=>o.p==="recovery");s.sort((o,l)=>(l.created||0)-(o.created||0));for(let o of s)try{let l=await ar(i,$(o.kdf.s),qn(e,t)),u=await ae(l,$(o.iv),$(o.ct),Vn(e,t,o.kdf.s));return q(i),u}catch{}return q(i),null}async function Aa(e,t,r,n,i){let s=X(16),o=V(s),l=await xe(n,s,e.cfg.iterations,et(t,r)),u=await ne(l,i,tt(t,r,e.cfg.iterations,o));return {id:V(X(6)),p:"password",kdf:{a:"PBKDF2-SHA256",it:e.cfg.iterations,s:o},iv:V(u.iv),ct:V(u.ct),created:Date.now()}}async function Ra(e,t){let r=this.user.user_id,n=e.scope,i=X(16),s=V(i),o=await xe(t,i,e.cfg.iterations,et(n,r)),l=X(32),u=await ne(o,l,tt(n,r,e.cfg.iterations,s)),c=await oe(l),f=await pn(),p=await ne(c,f.pkcs8,$n(n,r));q(f.pkcs8);let d=null;e.cfg.recovery==="code"&&(d=await yr(n,r,l));let g=await ne(c,l,jn(n,r));q(l);let h=await sr(f.pubRaw),m=Date.now(),_=[{id:V(X(6)),p:"password",kdf:{a:"PBKDF2-SHA256",it:e.cfg.iterations,s},iv:V(u.iv),ct:V(u.ct),created:m}];d&&_.push(d.wrap);let b={v:1,alg:"ECDH-P-256",user_id:r,wraps:_,ik:{iv:V(p.iv),ct:V(p.ct)},self:{iv:V(g.iv),ct:V(g.ct)},pub:V(f.pubRaw),fpr:h,pins:null,created:m,updated:m};await this.postRecord({v:1,alg:"ECDH-P-256",user_id:r,pub:V(f.pubRaw),fpr:h,created:m},{table:{name:e.cfg.table,access_group:"authorized"},index:{name:"pubkey",value:r}});let A=await this.postRecord(b,{table:{name:e.cfg.table,access_group:"private"}}),w=await Tt.call(this,e);if(w&&w.record_id!==A.record_id){await Bn.call(this,e,w,t);return}e.mk=c,e.ikPriv=f.priv,e.pubRaw=f.pubRaw,e.fpr=h,e.keyringRecordId=A.record_id,d&&(e.pendingRecoveryCode=d.code),e.user_id=r,e.pins={},e.status="unlocked",e.reason="";}async function Bn(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 l=(Array.isArray(s?.wraps)?s.wraps:[]).filter(f=>f.p==="password");if(!l.length)throw new a("The keyring has no password wrap.",{code:"ENCRYPTION_KEYRING_CORRUPT"});l.sort((f,p)=>(p.created||0)-(f.created||0));let u=null;for(let f of l)try{let p=$(f.kdf.s),d=await xe(r,p,f.kdf.it,et(i,n));u=await ae(d,$(f.iv),$(f.ct),tt(i,n,f.kdf.it,f.kdf.s));break}catch{}if(!u)throw new a("Incorrect password: the encryption keyring could not be opened.",{code:"ENCRYPTION_BAD_PASSWORD"});let c=await oe(u);q(u),await br.call(this,e,t,c);}async function br(e,t,r){let n=this.user.user_id,i=t.data,s=await ae(r,$(i.ik.iv),$(i.ik.ct),$n(e.scope,n)),o=await ir(s);q(s);let l={};if(i.pins&&typeof i.pins=="object"&&i.pins.ct)try{let u=await ae(r,$(i.pins.iv),$(i.pins.ct),K(`${Y}|pins|${e.scope}|${n}`));l=JSON.parse(We(u)),q(u);}catch{l={};}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=l,e.status="unlocked",e.reason="";}async function It(e){let t=L.call(this);if(!t||!this.user?.user_id)return;if(!nr()){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=Ue.call(this);let r=await Tt.call(this,t);r?await Bn.call(this,t,r,e):await Ra.call(this,t,e),t.cfg.persistDevice&&await Qn.call(this,t).catch(()=>{});}async function Kn(e){await this.__connection;let t=L.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 It.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 Hn(e){this.__projectIdInput&&await this.__projectIdInput;let t=L.call(this);return t?(e?.forgetDevice&&await Ar.call(this,t).catch(()=>{}),dr.call(this),this.__cached_requests={},{status:t.status}):{status:"disabled"}}async function Gn(e,t){let r=L.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,l=(o.wraps||[]).filter(m=>m.p==="password");l.sort((m,_)=>(_.created||0)-(m.created||0));let u=null;for(let m of l)try{let _=await xe(e,$(m.kdf.s),m.kdf.it,et(r.scope,s));u=await ae(_,$(m.iv),$(m.ct),tt(r.scope,s,m.kdf.it,m.kdf.s));break}catch{}if(!u)throw new a("Incorrect current password: the encryption keyring was not re-wrapped.",{code:"ENCRYPTION_BAD_PASSWORD"});let c=X(16),f=V(c),p=await xe(t,c,r.cfg.iterations,et(r.scope,s)),d=await ne(p,u,tt(r.scope,s,r.cfg.iterations,f));q(u);let g=Date.now(),h=(o.wraps||[]).concat([{id:V(X(6)),p:"password",kdf:{a:"PBKDF2-SHA256",it:r.cfg.iterations,s:f},iv:V(d.iv),ct:V(d.ct),created:g}]);await this.postRecord(Object.assign({},o,{wraps:h,updated:g}),{record_id:r.keyringRecordId});}async function Wn(){let e=L.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,l)=>(l.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 _r(){return typeof indexedDB<"u"&&!!indexedDB}function wr(){return new Promise((e,t)=>{let r=indexedDB.open(ha,1);r.onupgradeneeded=()=>{let n=r.result;n.objectStoreNames.contains(Ae)||n.createObjectStore(Ae);},r.onsuccess=()=>e(r.result),r.onerror=()=>t(r.error);})}function Er(e){return `${e.scope}#${this.user?.user_id}`}async function Qn(e){if(!_r()||!e.mk)return;let t=await wr();await new Promise((r,n)=>{let i=t.transaction(Ae,"readwrite");i.objectStore(Ae).put({mk:e.mk,keyringRecordId:e.keyringRecordId,saved:Date.now()},Er.call(this,e)),i.oncomplete=()=>r(),i.onerror=()=>n(i.error);}),t.close();}async function Ta(e){if(!_r())return null;let t=await wr(),r=await new Promise((n,i)=>{let o=t.transaction(Ae,"readonly").objectStore(Ae).get(Er.call(this,e));o.onsuccess=()=>n(o.result||null),o.onerror=()=>i(o.error);});return t.close(),r&&r.mk?r:null}async function Ar(e){if(!_r())return;let t=await wr();await new Promise((r,n)=>{let i=t.transaction(Ae,"readwrite");i.objectStore(Ae).delete(Er.call(this,e)),i.oncomplete=()=>r(),i.onerror=()=>n(i.error);}),t.close();}function zn(){let e=L.call(this);!e||e.ready||(e.unlocking=true,e.ready=Ia.bind(this)().catch(()=>false).then(()=>{e.unlocking=false;}));}async function Ia(){let e=L.call(this);if(!e||!this.user?.user_id||!e.cfg.persistDevice||!nr())return false;e.scope=Ue.call(this);try{let t=await Ta.call(this,e);if(!t)return !1;let r=await Tt.call(this,e);return r?(await br.call(this,e,r,t.mk),!0):(await Ar.call(this,e).catch(()=>{}),!1)}catch{return e.status="locked",e.reason="NO_SESSION_KEY",false}}async function Rr(e){let t=L.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 c=((await this.getRecords({table:{name:t.cfg.table,access_group:"authorized"},index:{name:"$user_id",value:s,condition:"="}},{limit:10}))?.list||[]).filter(g=>g.user_id===s&&g.data?.pub);if(!c.length)return null;c.sort((g,h)=>h.uploaded-g.uploaded);let f=$(c[0].data.pub),p=await sr(f),d=t.pins[s];if(d&&d!==p)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]=p,i=true;}return {pubRaw:f,fpr:p}})().finally(()=>t.peerInflight.delete(s)),t.peerInflight.set(s,o));let l=await o;l&&t.peerPub.set(s,l),r[s]=l;})),i&&await Zn.call(this,t).catch(()=>{}),r}async function Jn(e,t){let r=Ue.call(this),n=e.dek.get(t);if(n)return {entry:n,scope:r};let i=await Ee.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 Tr(e,t){let r=L.call(this);if(!r)return;let n=await Jn.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 l=await Rr.call(this,t),u=t.filter(d=>!l[d]);if(u.length)throw new a(`These users have no encryption key yet, so they cannot be given access: ${u.join(", ")}. A user's key is created the first time they log in with encryption enabled.`,{code:"ENCRYPTION_RECIPIENT_HAS_NO_KEY"});let c=pr(i),f=fr(s,i.own,i.anch,c),p=Object.assign({},i.recipients);for(let d of t)d!==o&&(p[d]=await Mn.call(this,i.bytes,l[d],s,c,i.own,d,f));await Sa.call(this,r,e,i,p);}async function Yn(e,t){let r=L.call(this);if(!r)return;let n=await Jn.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(c=>c===s?true:t?!t.includes(c):false).filter(c=>c!==s),l=await Ee.call(this,e);if(!l)throw new a(`Record "${e}" not found.`,{code:"NOT_EXISTS"});Pa(l,e);let u={};if(o.length){u=await Rr.call(this,o);let c=o.filter(f=>!u[f]);if(c.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: ${c.join(", ")}.`,{code:"ENCRYPTION_RECIPIENT_HAS_NO_KEY"})}r.roll.add(l.record_id||e),await this.postRecord(l.data,{record_id:l.record_id||e,table:{name:l.table.name,access_group:"private"}}),o.length&&await Tr.call(this,l.record_id||e,o);}function Pa(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 Sa(e,t,r,n){let i=await ka.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 ka(e){let t=L.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&&Rt(r.data)?r.data:null}async function Xn(e){this.__projectIdInput&&await this.__projectIdInput;let t=L.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 Zn.call(this,t);}async function Zn(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:V(n.iv),ct:V(n.ct)},updated:Date.now()}),{record_id:e.keyringRecordId});}function ei(){let e=L.call(this);if(!e||!e.pendingRecoveryCode)return null;let t=e.pendingRecoveryCode;return e.pendingRecoveryCode="",t}async function ti(e){await this.__connection;let t=L.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=Ue.call(this);let r=this.user.user_id,n=await Tt.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 Ea(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 oe(i);await br.call(this,t,n,s);let o=false,l=null,u=(n.data?.wraps||[]).slice();if(e.password&&(u=u.filter(c=>c.p!=="password"),u.push(await Aa(t,t.scope,r,e.password,i)),o=true),t.cfg.recovery==="code"){let c=await yr(t.scope,r,i);u=u.filter(f=>f.p!=="recovery"),u.push(c.wrap),l=c.code;}return q(i),await this.postRecord(Object.assign({},n.data,{wraps:u,updated:Date.now()}),{record_id:n.record_id}),t.cfg.persistDevice&&await Qn.call(this,t).catch(()=>{}),{status:t.status,repaired:o,recoveryCode:l}}async function ri(){await this.__connection;let e=L.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 ae(e.mk,$(n.iv),$(n.ct),jn(e.scope,e.user_id)),s=await yr(e.scope,e.user_id,i);q(i);let o=(r.data.wraps||[]).filter(l=>l.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 At="__skenc__",ni="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";function va(e){if(e===0)return "0";let t="";for(;e>0;)t=ni[e%62]+t,e=Math.floor(e/62);return t}function Na(e){let t=0;for(let r of e){let n=ni.indexOf(r);if(n<0)return NaN;t=t*62+n;}return t}function Pt(e){if(typeof e!="string")return null;let t=e.lastIndexOf(At);if(t<0)return null;let r=Na(e.slice(t+At.length));return Number.isFinite(r)?{key:e.slice(0,t),plainSize:r}:null}function Ir(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=Pt(t[10]);return r?{recordId:t[5],recordOwner:t[3],filename:t[t.length-1],plainSize:r.plainSize}:null}catch{return null}}function ii(e,t){return {service:this.service,owner:this.owner,recordOwner:t,recordId:e}}async function si(e,t,r){let n=L.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(Pt(t))throw new a(`"${At}" is reserved in an upload form key.`,{code:"INVALID_PARAMETER"});if(t===rt)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},l=await In(i.bytes,s,ii.call(this,e,i.own),o);return q(s),{key:`${t}${At}${va(r.size)}`,file:new File([l],r.name,{type:"application/octet-stream"}),encrypted:true}}async function oi(e,t){let r=L.call(this),n=Ir(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(!lr(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 Pn(i.bytes,s,ii.call(this,n.recordId,n.recordOwner)),l=o.meta&&o.meta.t||"application/octet-stream";return new Blob([o.bytes],{type:l})}function Da(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 xa(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 Pr(e,t,r){let n=L.call(this);if(!n)return [];let i=await Ee.call(this,e);if(!i)return [];let s=t==="decrypt"?Da(i):xa(i);if(!s.length)return [];let o=[],l=new FormData,u=false;for(let c of s){let f=i.bin[c.formKey].find(d=>d.url===c.url);if(!f||typeof f.getFile!="function")continue;let p=await f.getFile("blob");p&&(l.append(c.formKey,new File([p],c.filename,{type:p.type||"application/octet-stream"})),o.push(c.url),u=true);}if(!u)return [];if(t==="decrypt"){let c=n.dek.get(e);c&&(q(c.bytes),n.dek.delete(e));}return await this.uploadFiles(l,{record_id:e,progress:r}),o}var B=null;function vt(e){let t={tkid:"ticket_id",cond:"condition",stmp:"timestamp",upd:"updated",acts:"actions",actn:"action",cnt:"count",ttl:"time_to_live",plch:"placeholder",hash:"hash",desc:"description",pmc:"limit_per_user",fail:"failed",rv:"rules_version"},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.slice(3).join("#");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=se(i[2].slice(0,-4));}}else t[n]?r[t[n]]=e[n]:r[n]=e[n];return r}async function li(e){if(!e?.ticket_id)throw new a("Ticket ID is required.",{code:"INVALID_PARAMETER"});if(!/^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$/.test(e.ticket_id))throw new a('Invalid "ticket_id". Use letters, digits, "_" and "-" (up to 64 chars, starting with a letter or digit).',{code:"INVALID_PARAMETER"});if(!e.method)throw new a('Method is required. Should be either "GET" or "POST"',{code:"INVALID_PARAMETER"});let t=String(e.method).toUpperCase();if(t!=="GET"&&t!=="POST")throw new a('Method should be either "GET" or "POST".',{code:"INVALID_PARAMETER"});let r=!!e.auth;if(r&&t==="GET")throw new a("Signed-in consumption is POST only.",{code:"INVALID_PARAMETER"});await this.__connection;let n=r?"tpa":t==="GET"?"tg":"tp",i=`https://${this.service.slice(0,4)}.${this.customApiDomain}/${n}/${this.service}/${e.ticket_id}`,s=await S.bind(this)(i,e.data||{},{method:t,auth:r},{ignoreService:true});if(s&&typeof s=="object"&&s.stage)throw new a(s.message,{code:s.code,cause:s});return !s||typeof s!="object"||Array.isArray(s)||typeof s.tkid!="string"?s:vt(s)}async function ci(e,t){await this.__connection;let r=await S.bind(this)("ticket",Object.assign({exec:"list"},e||{}),{auth:true,fetchOptions:t});return r.list=r.list.map(vt),r}async function ui(e){if(!e?.ticket_id)throw new a("Ticket ID is required.",{code:"INVALID_PARAMETER"});let t=e.before===void 0||e.before===null?Date.now():e.before;if(typeof t!="number"||!Number.isInteger(t)||t<=0)throw new a('"before" should be a time in milliseconds since the epoch.',{code:"INVALID_PARAMETER"});return S.bind(this)("register-ticket",{exec:"clearlog",ticket_id:e.ticket_id,before:t},{auth:true})}async function di(e,t){await this.__connection;let r=await S.bind(this)("ticket",Object.assign({exec:"consumed"},e||{}),{auth:true,fetchOptions:t});return r.list=r.list.map(vt),r}async function fi(e){let t=await S.bind(this)("register-ticket",Object.assign({exec:"reg"},e),{auth:true});return t&&typeof t=="object"&&t.ticket&&(t.ticket=vt(t.ticket)),t}async function pi(e){return S.bind(this)("register-ticket",Object.assign({exec:"unreg"},e),{auth:true})}var Fa=3600;async function Oe(){if(await this.__connection,this.session){let e=Math.floor(Date.now()/1e3),r=this.session.getIdToken().getExpiration();if(r<e+Fa){this.log("request:requesting new token",null);try{await W.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),be.bind(this)(),new a("User login is required.",{code:"INVALID_REQUEST"})}function ai(e,t){return new Promise((r,n)=>{t.refreshSession(e.getRefreshToken(),(i,s)=>{this.log("getSession:refreshSessionCallback",{refreshErr:i,refreshedSession:s}),i?(be.bind(this)(),n(i)):s.isValid()?r(s):(be.bind(this)(),n(new a("Invalid session.",{code:"INVALID_REQUEST"})));});})}function W(){if(!this.userPool)throw new a("User pool is missing",{code:"INVALID_REQUEST"});let e=()=>{let s=B.getSignInUserSession().getIdToken().payload||null,o=Ge(s);return this.log("normalized user attribute",o),this.__user=o,o},t=async s=>new Promise((o,l)=>{this.log("getSession:option",s);let{refreshToken:u=false,skipUserUpdateEventTrigger:c=false}=s||{};if(u&&c&&(c=false),B=this.userPool.getCurrentUser(),!B){this.log("getSession:cognitoUser",B),be.bind(this)(),l(null);return}let f=p=>{let d=p.getIdToken().payload;if(this.log("getSession:respond:sessionAttribute",d),d["custom:service"]!==this.service)throw this.log("getSession:respond","invalid service, signing out"),be.bind(this)(),new a("Invalid session.",{code:"INVALID_REQUEST"});return this.session=p,e(),c||this._runOnUserUpdateListeners(this.user),this.session};B.getSession((p,d)=>{if(this.log("getSession:getSessionCallback",{err:p,session:d}),!d){be.bind(this)(),l(new a("Current session does not exist.",{code:"INVALID_REQUEST"}));return}if(p){ai.bind(this)(d,B).then(b=>o(f(b))).catch(l);return}let g=Math.floor(Date.now()/1e3),h=d.getIdToken(),m=h.getExpiration(),_=m<g;if(this.log("getSession:currentTime",g),this.log("getSession:idTokenExp",m),this.log("getSession:isExpired",_),this.log("getSession:existingBearerToken",this.bearerToken),this.bearerToken=h.getJwtToken(),_||u||!d.isValid())ai.bind(this)(d,B).then(b=>o(f(b))).catch(l);else try{o(f(d));}catch(b){l(b);}});}),r=(s,o)=>{let l=o||s.includes(this.service+"-")?s:this.service+"-"+Z.hash(s);return {cognitoUser:new amazonCognitoIdentityJs.CognitoUser({Username:l,Pool:this.userPool}),cognitoUsername:l}};return {getSession:t,authenticateUser:(s,o,l=false,u=false)=>new Promise((c,f)=>{this.__request_signup_confirmation=null,this.__disabledAccount=null;let p=r(s,l),d=p.cognitoUsername,g=new amazonCognitoIdentityJs.AuthenticationDetails({Username:d,Password:o});p.cognitoUser.authenticateUser(g,{newPasswordRequired:(h,m)=>{this.__disabledAccount=null,this.__request_signup_confirmation=d,h["custom:signup_ticket"]==="PASS"||h["custom:signup_ticket"]==="MEMBER"||h["custom:signup_ticket"]==="OIDPASS"?p.cognitoUser.completeNewPasswordChallenge(o,{},{onSuccess:_=>{B=p.cognitoUser,t().then(async b=>{if(L.call(this))try{await It.bind(this)(o);}catch(A){this.log("encryption:ensureKeyring:failed",A);}c(this.user);});},onFailure:_=>{f(new a(_.message||"Failed to authenticate user.",{code:_.code}));}}):f(new a("User's signup confirmation is required.",{code:"SIGNUP_CONFIRMATION_NEEDED"}));},onSuccess:h=>t({skipUserUpdateEventTrigger:true}).then(async m=>{if(this.__disabledAccount=null,L.call(this))try{await It.bind(this)(o);}catch(_){this.log("encryption:ensureKeyring:failed",_);}this._runOnLoginListeners(this.user),this._runOnUserUpdateListeners(this.user),c(this.user);}),onFailure:h=>{let m=[],{parsed:_,code:b}=kt(h),A=typeof h?.message=="string"?h.message:"";if(b==="NotAuthorizedException"?A.includes("User is disabled.")?(this.__disabledAccount=d,m=["This account is disabled.","USER_IS_DISABLED"]):u?m=["The account already exists.","ACCOUNT_EXISTS"]:m=["Incorrect username or password.","INCORRECT_USERNAME_OR_PASSWORD"]:b==="UserNotFoundException"?m=["Incorrect username or password.","INCORRECT_USERNAME_OR_PASSWORD"]:b==="UserNotConfirmedException"?(this.__request_signup_confirmation=d,m=["User's signup confirmation is required.","SIGNUP_CONFIRMATION_NEEDED"]):(b==="TooManyRequestsException"||b==="LimitExceededException")&&(m=["Too many attempts. Please try again later.","REQUEST_EXCEED"]),_.code==="SIGNUP_CONFIRMATION_NEEDED"&&(this.__request_signup_confirmation=d),m.length){let w=m[1],I=m[0];f(new a(I,{code:w,cause:h}));}else f(_);}});}),createCognitoUser:r,signup:(s,o,l)=>new Promise((u,c)=>{this.userPool.signUp(s,o,l,null,(f,p)=>{if(f){let{parsed:d,code:g}=kt(f),h=[];g==="UsernameExistsException"?h=["The account already exists.","EXISTS"]:g==="InvalidPasswordException"?h=["Invalid password. Password must be at least 6 characters.","INVALID_PARAMETER"]:g==="InvalidParameterException"?h=[d.message||"Invalid parameter.","INVALID_PARAMETER"]:g==="TooManyRequestsException"||g==="LimitExceededException"?h=["Too many attempts. Please try again later.","REQUEST_EXCEED"]:g==="CodeDeliveryFailureException"?h=["Failed to deliver verification code.","CODE_DELIVERY_FAILURE"]:g==="UserLambdaValidationException"&&(h=[d.message||"Signup validation failed.",d.code==="EXISTS"?"EXISTS":"INVALID_REQUEST"]),h.length?c(new a(h[0],{code:h[1],cause:f})):c(d);return}u(p);});})}}function kt(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 gi(e){await this.__authConnection;let t=e?.refreshToken||false;if(!t)return this.user;try{return await W.bind(this)().getSession(Object.assign({skipUserUpdateEventTrigger:!t,refreshToken:t},e)),this.user}catch{return null}}async function hi(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 l of o)if(typeof l!="string")throw new a('"merge" array items should be type: <string>.',{code:"INVALID_PARAMETER"})}if(typeof o!="boolean"&&!Array.isArray(o))throw new a('"merge" should be type: <boolean | string[]>.',{code:"INVALID_PARAMETER"});return o},template:o=>{if(typeof o!="object"||o===null)throw new a('"template" should be type: <object>.',{code:"INVALID_PARAMETER"});if(o.welcome!==void 0&&(typeof o.welcome!="string"||!o.welcome))throw new a('"template.welcome" should be a non-empty <string> (template message_id).',{code:"INVALID_PARAMETER"});return o}});let t={token:e.token,id:e.id,merge:e.merge};e.template?.welcome&&(t.template_welcome=e.template.welcome);let r=await S.bind(this)("openid-logger",t),n=r.logger.split("#"),i=this.service+"-"+n[0],s=n[1];return {userProfile:await W.bind(this)().authenticateUser(i,s,true,true),openid:r.openid}}function qa(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 Va(e){let t=e.split(".");if(t.length!==3)throw new Error("Invalid JWT format");let n=t[1].replace(/-/g,"+").replace(/_/g,"/"),i=qa(n);return JSON.parse(i)}async function mi(e){await this.__authConnection,this.log("loginWithToken:params",e),e=y.Params(e,{idToken:"string",accessToken:"string",refreshToken:"string"},["idToken"]);let t=Va(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=Ge(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 nt.bind(this)(),false)}async function be(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()),dr.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 nt(e){await this.__connection;let{data:t}=j(e);return await be.bind(this)(t?.global),"SUCCESS: The user has been logged out."}async function yi(){if(!this.__request_signup_confirmation)throw new a("Least one login attempt is required.",{code:"INVALID_REQUEST"});return await S.bind(this)("confirm-signup",{username:this.__request_signup_confirmation})}async function bi(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 S.bind(this)("recover-account",{username:this.__disabledAccount,redirect:e}),"SUCCESS: Recovery e-mail has been sent."}async function Sr(e){let t=y.Params(e,{username:"string",email:"string",password:"string"},["password"]);await this.__authConnection;let r=null;if(t.email)try{r=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"});let n=t.username||t.email;try{return await W.bind(this)().authenticateUser(n,t.password)}catch(i){if((i?.code==="UserNotFoundException"||i?.code==="NotAuthorizedException")&&r&&r!==n)return await W.bind(this)().authenticateUser(r,t.password);throw i}}async function _i(e,t){await this.__authConnection;let r={username:"string",password:c=>y.Password(c),email:c=>y.Email(c),name:"string",address:c=>{if(!c)return "";if(typeof c=="string")return c;if(typeof c=="object")return JSON.stringify(c)},gender:"string",birthdate:c=>c?y.Birthdate(c):"",phone_number:c=>c?y.PhoneNumber(c):"",email_public:["boolean",()=>false],address_public:["boolean",()=>false],gender_public:["boolean",()=>false],birthdate_public:["boolean",()=>false],phone_number_public:["boolean",()=>false],access_group:"number",misc:"string",picture:c=>c?y.Url(c):"",profile:c=>c?y.Url(c):"",family_name:"string",given_name:"string",middle_name:"string",nickname:"string",website:c=>c?y.Url(c):""},n=y.Params(e||{},r,["email","password"]);await nt.bind(this)(),t=y.Params(t||{},{email_subscription:c=>{let f=c;if(typeof c=="number"||typeof c=="string"&&c!=="public"&&c!=="authorized"){let p=y.newsletterGroup(c);if(typeof p=="number"&&p!==0&&p!==1)throw new a('"option.email_subscription" takes 0 (public), 1 (authorized), true, false or the name of a newsletter group.',{code:"INVALID_PARAMETER"});f=p;}else if(typeof c!="boolean"&&typeof c!="string")throw new a('"option.email_subscription" takes 0 (public), 1 (authorized), true, false or the name of a newsletter group.',{code:"INVALID_PARAMETER"});if(f!==false&&!t?.signup_confirmation)throw new a('"option.signup_confirmation" is required for email subscription.',{code:"INVALID_PARAMETER"});return f},signup_confirmation:c=>{let f=c;if(typeof c=="string")f=y.Url(c);else if(typeof c=="boolean")f=c;else throw new a('"option.signup_confirmation" should be type: <string | boolean>.',{code:"INVALID_PARAMETER"});if(f&&!n.email)throw new a('"email" is required for signup confirmation.',{code:"INVALID_PARAMETER"});return f},login:c=>{if(typeof c=="boolean"){if(t.signup_confirmation&&c)throw new a('"login" is not allowed when "option.signup_confirmation" is true.',{code:"INVALID_PARAMETER"});return c}throw new a('"option.login" should be type: boolean.',{code:"INVALID_PARAMETER"})},template:c=>{if(typeof c!="object"||c===null)throw new a('"option.template" should be type: <object>.',{code:"INVALID_PARAMETER"});if(c.signup_confirmation!==void 0){if(typeof c.signup_confirmation!="string"||!c.signup_confirmation)throw new a('"option.template.signup_confirmation" should be a non-empty <string> (template message_id).',{code:"INVALID_PARAMETER"});if(!t?.signup_confirmation)throw new a('"option.signup_confirmation" is required when "option.template.signup_confirmation" is set.',{code:"INVALID_PARAMETER"})}if(c.welcome!==void 0&&(typeof c.welcome!="string"||!c.welcome))throw new a('"option.template.welcome" should be a non-empty <string> (template message_id).',{code:"INVALID_PARAMETER"});return c}});let i=t?.login||false;if(n.signup_confirmation=t?.signup_confirmation||false,n.email_subscription=t?.email_subscription===void 0||t?.email_subscription===null?false:t.email_subscription,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=W.bind(this)().createCognitoUser(n.username||n.email);for(let c of ["email_public","address_public","gender_public","birthdate_public","phone_number_public"])n[c]=n[c]?"1":"0";n.access_group&&(n.access_group=n.access_group.toString());let o=(await S.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(":"),l=o.slice(1).join(":"),u=[new amazonCognitoIdentityJs.CognitoUserAttribute({Name:"custom:signup",Value:o[0]}),new amazonCognitoIdentityJs.CognitoUserAttribute({Name:"locale",Value:l.split("#")[1]}),new amazonCognitoIdentityJs.CognitoUserAttribute({Name:"custom:signup_ticket",Value:l})];for(let c in r){let f=["email_public","address_public","gender_public","birthdate_public","phone_number_public","misc","service","owner"];n[c]!==""&&(c==="username"||c==="password"||c==="access_group"||(f.includes(c)?u.push(new amazonCognitoIdentityJs.CognitoUserAttribute({Name:"custom:"+c,Value:n[c]})):u.push(new amazonCognitoIdentityJs.CognitoUserAttribute({Name:c,Value:n[c]}))));}return await W.bind(this)().signup(s.cognitoUsername,n.password,u),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?Sr.bind(this)({email:n.username||n.email,password:n.password}):"SUCCESS: The account has been created."}async function wi(){await this.__connection;let e=await S.bind(this)("remove-account",{disable:this.__user.user_id},{auth:true});return await nt.bind(this)(),e}async function Ei(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)=>{W.bind(this)().createCognitoUser(t.email).cognitoUser.confirmPassword(r,n,{onSuccess:l=>{i("SUCCESS: New password has been set.");},onFailure:l=>{s(new a(l?.message||"Failed to reset password.",{code:l?.code||"ERROR",cause:l}));}});})}async function Ai(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,l)=>{let u={onSuccess:c=>{n?W.bind(this)().getSession({refreshToken:true}).then(()=>{this.__user&&(this.__user[e+"_verified"]=true),o(`SUCCESS: "${e}" is verified.`);}).catch(f=>{l(f);}):o("SUCCESS: Verification code has been sent.");},onFailure:c=>{l(new a(c.message||"Failed to request verification code.",{code:c?.code}));}};n?B?.verifyAttribute(e,n,u):(u.inputVerificationCode=null,B?.getAttributeVerificationCode(e,u,i));})}function Ri(e,t){return Ai.bind(this)("phone_number",e,t)}function Ti(e,t){return Ai.bind(this)("email",e,t)}async function Ii(e,t){await this.__connection;let r=y.Params(e,{email:i=>y.Email(i)},["email"]),n;if(t?.template!==void 0){if(typeof t.template!="object"||t.template===null||Array.isArray(t.template))throw new a('"template" should be type: <object>.',{code:"INVALID_PARAMETER"});if(t.template.verification!==void 0)throw new a('"template.verification" is not an option of forgotPassword(). Use "template.forgot_password" (template message_id).',{code:"INVALID_PARAMETER"});let i=t.template.forgot_password;if(i!==void 0){if(typeof i!="string"||!i)throw new a('"template.forgot_password" should be a non-empty <string> (template message_id).',{code:"INVALID_PARAMETER"});n={template_forgot_password:i};}}return new Promise(async(i,s)=>{W.bind(this)().createCognitoUser(r.email).cognitoUser.forgotPassword({onSuccess:l=>{i("SUCCESS: Verification code has been sent.");},onFailure:l=>{let{parsed:u,code:c}=kt(l),f={UserNotFoundException:"NOT_EXISTS",InvalidParameterException:"INVALID_PARAMETER",NotAuthorizedException:"INVALID_REQUEST",LimitExceededException:"REQUEST_EXCEED",TooManyRequestsException:"REQUEST_EXCEED",CodeDeliveryFailureException:"CODE_DELIVERY_FAILURE"}[c]||u.code||c||"ERROR";s(new a(u.message,{code:f,cause:l}));}},n);})}async function Pi(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),L.call(this)&&await Gn.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}=kt(i);n(o);}return}L.call(this)&&Wn.bind(this)().catch(o=>this.log("encryption:prune:failed",o)),r("SUCCESS: Password has been changed.");});})}async function Si(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;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 S.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,(l,u)=>{l&&o([l?.code||l?.name,l?.message||"Failed to update user settings."]),s(u);});}),await W.bind(this)().getSession({refreshToken:true}),this.user}return this.user}async function ki(e,t){e=j(e).data,e||(e={searchFor:"timestamp",condition:">",value:0},t||(t={}),t.ascending=false),await this.__connection;let r={user_id:s=>y.UserId(s),email:"string",phone_number:"string",locale:s=>{if(typeof s!="string"||typeof s=="string"&&s.length>5)throw new a('Value of "locale" should be a country code.',{code:"INVALID_PARAMETER"});return s},name:"string",address:"string",gender:"string",birthdate:s=>y.Birthdate(s),subscribers:"number",timestamp:"number",access_group:"number",approved:"string"},n=["searchFor","value"],i=(s,o)=>{let l=r[e.searchFor];if(typeof l=="function")return l(s);if(typeof s!==l)throw new a(`${o} does not match the type of "${e.searchFor}" index.`,{code:"INVALID_PARAMETER"});return s};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:s=>Array.isArray(s)?s.map(o=>i(o,"Value")):i(s,"Value"),range:s=>i(s,"Range")},n),e?.condition&&e?.condition!=="="&&e.hasOwnProperty("range"))throw new a("Conditions does not apply on range search.",{code:"INVALID_PARAMETER"});if(Array.isArray(e.value)&&(e.condition!=="="||e.range))throw new a(`Conditions are not allowed on a list of "${e.searchFor}" values. Search for a single value to use a condition or range.`,{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 S.bind(this)("get-users",e,{auth:true,fetchOptions:t})}async function vi(e){await this.__connection;let t=await S.bind(this)("last-verified-email",e,{auth:true});return t.includes("SUCCESS")?(await W.bind(this)().getSession({refreshToken:true}),this.user):t}var Le=null,xi=typeof SubmitEvent<"u",$a=typeof HTMLFormElement<"u",st=H(),kr=0;function Ui(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())}var Nr=6,Ni=6e4;function Ci(e,t){let r=e>0?e:Math.min(Ni,500*Math.pow(2,t));r=Math.min(Ni,r);let n=Math.floor(Math.random()*Math.min(1e3,Math.max(50,r*.25)));return r+n}function Oi(e){return new a(`Too many requests: ${e} still answered 429 after ${Nr} retries.`,{code:"TOO_MANY_REQUESTS"})}function vr(e,t){return t>0?e/t*100:0}var Di=e=>{let{auth:t,type:r,endpoints:n,stable:i}=e,s=n[0],o=n[1];if(kr++,r==="admin"){let l=Object.entries(s).filter(([u,c])=>u.includes(t?"_private":"_public")&&u!=="get_users_private"&&u!=="service_public"&&typeof c=="string").map(([,u])=>u);if(!l.length)throw new a("No available admin gateways.",{code:"INVALID_REQUEST"});return l[kr%l.length]}if(r==="record"){let l=Object.entries(o).filter(([u,c])=>u.includes(t?"record_private":"record_public")&&typeof c=="string").map(([,u])=>u);if(!l.length)throw new a("No available record gateways.",{code:"INVALID_REQUEST"});return i?l[0]:l[kr%l.length]}throw new a("Invalid gateway type.",{code:"INVALID_REQUEST"})};async function Ba(e,t,r){let n=await Promise.all([this.admin_endpoint,this.record_endpoint]),i=n[0],s=n[1],o=e.split("?"),l=o.length>1?"?"+o[1]:"";switch(e=o[0],e){case "get-users":return i.get_users_private+e+l;case "service":return i.service_public+e+l;case "get-newsletters":case "get-public-newsletters":case "subscribe-newsletter":case "subscribe-public-newsletter":case "signupkey":case "admin-newsletter-request":case "admin-signup":case "confirm-signup":case "openid-logger":case "block-account":case "admin-edit-profile":case "remove-account":case "post-secure":case "recover-account":case "mock":case "grant-access":case "last-verified-email":case "ticket":case "register-ticket":case "get-newsletter-subscription":case "send-inquiry":case "register-newsletter-group":case "delete-newsletter-group":case "newsletter-group-endpoint":case "invitation-list":case "csr":case "csr-poll":case "csr-cancel":case "csr-finalize":return Di.bind(this)({auth:t,type:"admin",endpoints:n})+e+l;case "post-record":return (t?s.post_private:s.post_public)+e+l;case "get-records":return (t?s.get_private:s.get_public)+e+l;case "del-files":case "del-records":return s.del_private+e+l;case "store-subscription":case "get-vapid-public-key":case "push-notification":case "delete-subscription":case "subscription":case "get-subscription":case "get-table":case "get-tag":case "get-uniqueid":case "get-index":case "get-signed-url":case "get-signed-urls":case "extract-file-text":case "grid-query":case "grant-private-access":case "request-private-access-key":case "get-ws-group":case "check-schema":case "get-feed":case "castspell":case "dopamine":case "getspell":return Di.bind(this)({auth:t,type:"record",endpoints:n,stable:r})+e+l;default:return y.Url(e)+l}}var it={};function Li(){Le&&(Le.terminate(),Le=null);}async function S(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 l=null,u=null,c=await Ba.bind(this)(e,!!i,!!r.stableGateway),f=t?.service||this.service,p=t?.owner||this.owner;if(!o&&(l=await this.__connection,!l))throw new a("Invalid connection. The service could have been disabled, or has a restricted CORS.",{code:"INVALID_REQUEST"});let d=r?.tokenHeaders?.idToken===true;(i||d)&&(u=await Oe.bind(this)());let g={},{fetchMore:h=false,progress:m}=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;g[v]=r.fetchOptions[v];}g=y.Params(g,{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:f,owner:p};Object.assign(_,g),t=j(t).data,t?t&&typeof t=="object"&&(t=Object.assign(_,t)):t=_;let b=`${s}:${i?"auth":"public"}:${e}`,A=(()=>{if(t&&typeof t=="object"&&Object.keys(t).length&&!(st&&t instanceof FormData)){let v=function(x){return typeof x=="object"&&x!==null?Object.keys(x).sort().reduce((U,M)=>(typeof x[M]=="object"&&x[M]!==null?U[M]=v(x[M]):U[M]=x[M],U),{}):x};return Z.hash(b+"/"+JSON.stringify(v(t)))}return Z.hash(b+"/"+f)})(),{requestKey:w,requestKeyWithStartKey:I}=Ka.bind(this)({params:t,url:e,fetchMore:h,hashedParams:A});if(!w||w&&typeof w=="object")return w;if(this.log("requestKey",I),typeof I=="string"&&it[I]instanceof Promise)return this.log("request:returning pending",I),it[I];let E={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&&(E["Content-Type"]=v);}else E["Content-Type"]="application/json";if(u&&(E.Authorization=u),r?.tokenHeaders){let v=(M,de)=>typeof M=="string"?M:M===true?de:null,x=v(r.tokenHeaders.accessToken,this.session?.accessToken?.jwtToken||null),U=v(r.tokenHeaders.idToken,this.bearerToken||this.session?.idToken?.jwtToken||u||null);x&&(E["X-Access-Token"]=x),U&&(E["X-Id-Token"]=U);}let C={public_identifier:this.__public_identifier,service:f,owner:p,resolves_offloaded_data:true};E["Content-Meta"]=JSON.stringify(C),r.revalidate&&(E["Cache-Control"]="no-cache",E.Pragma="no-cache");let D={headers:E};if(r?.responseType&&(D.responseType=r.responseType),s==="GET"){if(t){let v=[];if(st&&t instanceof FormData?v=Array.from(t.entries()).map(([x,U])=>{let M=typeof U=="string"?U:U.name;return encodeURIComponent(x)+"="+encodeURIComponent(M)}):v=Object.keys(t).map(x=>{let U=t[x];return typeof U!="string"&&(U=JSON.stringify(U)),encodeURIComponent(x)+"="+encodeURIComponent(U)}),v.length){let x=c.includes("?")?c.endsWith("?")||c.endsWith("&")?"":"&":"?";c+=x+v.join("&");}}D.body=null;}else if(st&&t instanceof FormData)D.body=t;else if(E["Content-Type"]==="application/x-www-form-urlencoded"&&t&&typeof t=="object"){let v=new URLSearchParams;for(let x of Object.keys(t)){let U=t[x];v.append(x,typeof U=="string"?U:JSON.stringify(U));}D.body=v.toString();}else typeof t=="string"?D.body=t:D.body=t?JSON.stringify(t):null;if(D.method=s,Le===null){let v={batchSize:this.requestBatchSize,breakWhenError:false,onProgress:x=>{this.onBatchProcess.forEach(U=>U(x));}};Le=new Ts__default.default(v);}return this.log("request-opt",D),new Promise((v,x)=>{Le.add([async()=>{let U=Mi.bind(this)(c,D,m);it[I]=U;try{let M=Ga.bind(this)({hashedParam:w,requestKeyWithStartKey:I,url:e,fetched:await U});return delete it[I],this.log("request:end",M),v(M),M}catch(M){throw delete it[I],this.log("request:err",M),x(M),M}}]);})}function Ka(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 u of this.__startKeyHistory[r][i]){let c=i+Z.hash(u);this.__cached_requests?.[r]&&this.__cached_requests?.[r]?.[c]&&delete this.__cached_requests[r][c];}delete this.__startKeyHistory[r][i];}return {requestKeyWithStartKey:i,requestKey:i}}if(!Array.isArray(this.__startKeyHistory?.[r]?.[i]))return {requestKeyWithStartKey:i,requestKey:i};let s=this.__startKeyHistory[r][i],o=s[s.length-1],l=i;if(o){if(o==="end")return {requestKey:{list:[],startKey:"end",endOfList:true,startKeyHistory:s},requestKeyWithStartKey:l};l+=Z.hash(o),t.startKey=JSON.parse(o);}return this.__cached_requests?.[r]?.[l]?{requestKey:this.__cached_requests[r][l],requestKeyWithStartKey:l}:{requestKeyWithStartKey:l,requestKey:i}}function Ha(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 Mi(e,t,r,n=0){return new Promise((i,s)=>{let o=new XMLHttpRequest;o.open(t.method||"GET",e);for(var l in t.headers||{})o.setRequestHeader(l,t.headers[l]);t.responseType&&(o.responseType=t.responseType),o.onload=()=>{if(o.status<400)if(t.responseType=="json"||t.responseType=="blob")i(o.response);else {let u=o.responseText;try{u=JSON.parse(u);}catch{}i(u);}else if(o.status===429){let u=o.getResponseHeader("Retry-After"),c=Ui(u);if(c!==null){if(n>=Nr){s(Oi(`"${e.split("?")[0]}"`));return}setTimeout(()=>{Mi(e,t,r,n+1).then(i,s);},Ci(c,n));}else s("Too many requests");}else {let u=o.status,c=["INVALID_CORS","INVALID_REQUEST","SERVICE_DISABLED","INVALID_PARAMETER","ERROR","EXISTS","NOT_EXISTS"],f=t.responseType=="blob"?o.response:o.responseText;try{f=JSON.parse(f);}catch{}if(typeof f=="string"){let p=f.split(":"),d=p.splice(0,1)[0].trim(),g=p.join(":").trim();s(new a(g||f,{code:c.includes(d)?d:"ERROR"}));}else if(typeof f=="object"&&(f?.message||f?.stage||f?.code)){let p=f?.code||(u?u.toString():null)||"ERROR",d=f.message,g=f?.cause;g===void 0&&f.stage&&(g=f),typeof d=="string"&&(d=d.trim()),d||(d=String(p)),s(new a(d,{cause:g,code:p}));}else s(f);}},o.onerror=()=>s("Network error"),o.onabort=()=>s("Aborted"),o.ontimeout=()=>s("Timeout"),typeof r=="function"&&(o.onprogress=u=>{r({status:"download",progress:vr(u.loaded,u.total),loaded:u.loaded,total:u.total,abort:()=>o.abort()});},o.upload&&(o.upload.onprogress=u=>{r({status:"upload",progress:vr(u.loaded,u.total),loaded:u.loaded,total:u.total,abort:()=>o.abort()});})),o.send(t.body);})}function Ga(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)}function Wa(e){if(e instanceof a)return e;if(typeof e=="string"){let t=e.trim();if(t==="Network error")return new a("Network error",{code:"NETWORK_ERROR"});if(t==="Aborted")return new a("Aborted",{code:"ABORTED"});if(t==="Timeout")return new a("Timeout",{code:"TIMEOUT"});if(t==="Too many requests")return new a("Too many requests",{code:"TOO_MANY_REQUESTS"});let r=/<Code>([^<]+)<\/Code>/.exec(t)?.[1]?.trim()||"",n=/<Message>([^<]+)<\/Message>/.exec(t)?.[1]?.trim()||"";return r||n?new a(n||r,{code:r||"UPLOAD_FAILED",cause:t}):new a(t.length>300?t.slice(0,300):t||"Upload failed.",{code:"UPLOAD_FAILED",cause:t})}if(e&&typeof e=="object"){let t=e.code||e.Code,r=e.message||e.Message;if(t||r)return new a(String(r||t),{code:String(t||"UPLOAD_FAILED"),cause:e})}return new a("Upload failed.",{code:"UPLOAD_FAILED",cause:e})}var Qa=5,za=100;function Ja(e){let t=String(e?.code??"");if(t==="404"||t==="501")return true;let r=String(e?.message??e??"");return /missing authentication token/i.test(r)||/not implemented/i.test(r)||t==="403"&&/not found/i.test(r)}function Ya(e,t){let r=Array.isArray(e?.list)?e.list:[],n=Array.isArray(e?.failed)?e.failed:[],i=new Array(t);for(let s of n)s&&Number.isInteger(s.index)&&s.index>=0&&s.index<t&&(i[s.index]=new a(String(s.message||"Upload permit refused."),{code:String(s.code||"ERROR")}));for(let s=0;s<t;s++){if(i[s])continue;let o=r[s];o&&typeof o.url=="string"?i[s]={fields:o.fields||null,url:o.url,cdn:o.cdn}:i[s]=new a("No upload permit was answered for this file.",{code:"ERROR"});}return i}async function ot(e,t){await this.__connection;let{record_id:r,service:n=this.service,progress:i,timeout:s,throwOnFileError:o=false}=t;if(!r)throw new a('"record_id" is required.',{code:"INVALID_PARAMETER"});if(s!=null){if(typeof s!="number"||!Number.isFinite(s)||s<0)throw new a('"timeout" should be a number of milliseconds, 0 or more.',{code:"INVALID_PARAMETER"})}else s=0;if(xi&&e instanceof SubmitEvent&&(e=e.target),$a&&e instanceof HTMLFormElement&&(e=new FormData(e)),!st||!(e instanceof FormData))throw new a('"fileList" should be a FormData or HTMLFormElement.',{code:"INVALID_PARAMETER"});let u={reserved_key:Te(),service:n,request:"post"};t?.record_id&&(u.id=t.record_id);let c,f=(w,I,E,N,C=0)=>new Promise((D,v)=>{c=new XMLHttpRequest,c.open("POST",w),s>0&&(c.timeout=s),c.onload=()=>{let x=c.responseText;try{x=JSON.parse(x);}catch{}if(c.status>=200&&c.status<300)D(x);else if(c.status===429){let U=c.getResponseHeader("Retry-After"),M=Ui(U);if(M!==null){if(C>=Nr){v(Oi(`the upload of "${N}" to "${w}"`));return}setTimeout(()=>{f(w,I,E,N,C+1).then(D,v);},Ci(M,C));}else v("Too many requests");}else v(x);},c.onerror=()=>v("Network error"),c.onabort=()=>v("Aborted"),c.ontimeout=()=>v(new a(`Upload timeout: "${N}" was not finished within ${s} ms.`,{code:"TIMEOUT"})),c.upload&&typeof E=="function"&&(c.upload.onprogress=E),c.send(I);});function p(w){let I="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";if(w===0)return I[0];let E="";for(;w>0;)E=I[w%62]+E,w=Math.floor(w/62);return E}let d=[],g=[],h=[],m=[],_=[];for(let[w,I]of e.entries())I instanceof File&&_.push([w,I]);let b=_.length>=Qa&&!this.__bulkPermitsUnavailable,A=0;for(;A<_.length;){let w=_.slice(A,A+(b?za:1));A+=w.length;let I=[];for(let[N,C]of w){let D=await si.bind(this)(r,N,C);I.push({file:C,uploadFile:D.file,params:{key:D.key+"/"+D.file.name,sizeKey:p(D.file.size),contentType:D.file.type||null}});}let E=null;if(b)try{let N=await S.bind(this)("get-signed-urls",Object.assign({files:I.map(C=>C.params)},u),{auth:!!this.__user});E=Ya(N,I.length);}catch(N){if(!Ja(N))throw N;this.__bulkPermitsUnavailable=true,b=false;}if(!E){E=[];for(let N of I){let{fields:C=null,url:D,cdn:v}=await S.bind(this)("get-signed-url",Object.assign(N.params,u),{auth:!!this.__user});E.push({fields:C,url:D,cdn:v});}}for(let N=0;N<I.length;N++){let{file:C,uploadFile:D}=I[N],v=E[N];if(v instanceof a){if(m.push(""),g.push(C),h.push({file:C,name:C.name,error:v}),o)throw v;continue}m.push(v.cdn);let x=new FormData;for(let U in v.fields||{})x.append(U,v.fields[U]);x.append("file",D);try{await f(v.url,x,typeof i=="function"?U=>i({status:"upload",progress:vr(U.loaded,U.total),currentFile:C,completed:d,failed:g,loaded:U.loaded,total:U.total,abort:()=>c.abort()}):null,C.name),d.push(C);}catch(U){g.push(C);let M=Wa(U);if(h.push({file:C,name:C.name,error:M}),o)throw M}}}return {completed:d,failed:g,errors:h,bin_endpoints:m}}var Nt={};function k(e){let{preventMultipleCalls:t=false}=e||{};return function(r,n,i){let s=i.value;i.value=function(...o){let l=o[0],u=true,c=null,f="",p={},d=false;if(xi&&l instanceof SubmitEvent){l.preventDefault();let b=window.location.href;c=l.target;let A=new URL(c.action);f=A.href;let w=f?f.match(/(?<=\{).*?(?=\})/g):"";if(w)for(let I of w){if(!I)continue;let E=c.querySelector(`[name="${I}"]`);if(E)if(E.type==="file")for(let N=0;N<=E.files.length-1;N++)E.files[N]&&(p[I]||(p[I]=[]),p[I].push(new Promise((C,D)=>{let v=new FileReader;v.onload=function(){C(v.result);},v.readAsDataURL(E.files[N]),v.onerror=D;})));else f=f.replace(`{${I}}`,E.value);}c.getAttribute("action")===null?u=false:d=A.href===b;}let g=async b=>{if(f)for(let A in p)p[A].length&&(f=f.replace(`{${A}}`,(await Promise.all(p[A])).join(",")));if(c&&u){let A=L.call(this)?Ha(b):b;window.sessionStorage.setItem(`${this.service}:${Z.hash(f)}`,JSON.stringify(A)),d?window.location.replace(f):window.location.href=f;}return b},h,m=b=>{throw b instanceof a?b.name=n+"()":b=b instanceof Error?b:new a(b,{name:n+"()"}),b},_=async()=>{try{if(this.__projectIdInput&&await this.__projectIdInput,h=s.bind(this)(...o),h instanceof Promise){let b=await h;return g(b)}return g(h)}catch(b){throw m(b)}};if(t){let b=`${n}:${this?.__public_identifier||""}:${this?.service||""}:${this?.owner||""}`;return Nt?.[b]||(Nt[b]=_().finally(()=>{delete Nt[b];})),Nt[b]}return _()};}}async function Fi(){await this.__connection;let e=`${this.service}:${Z.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 Xa=256,Za=256,el=256,qi=256,tl="\u{10FFFF}",rl=/[\u0000-\u001F\u007F]|\u{10FFFF}/u,nl={"/":"%2F","!":"%21","*":"%2A","#":"%23"},il={"%2F":"/","%21":"!","%2A":"*","%23":"#"};function sl(e){return e.replace(/%/g,"%25").replace(/[\/!*#]/g,r=>nl[r]||r)}function le(e){return typeof e!="string"?e:e.replace(/%(2F|21|2A|23)/gi,r=>{let n=r.toUpperCase();return il[n]||r}).replace(/%25/gi,"%")}function fe(e,t,r={}){let{allowEmpty:n=false,maxLength:i,blockKeyDelimiters:s=false,disallowLeadingDollar:o=false,onlyAlphanumeric:l=false}=r;if(typeof e!="string")throw new a(`"${t}" should be type: <string>.`,{code:"INVALID_PARAMETER"});if(l&&/[^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(rl.test(e)||e.includes(tl))throw new a(`"${t}" cannot include control characters or unsupported sentinel characters.`,{code:"INVALID_PARAMETER"});if(s&&(e=sl(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 Me(e,t="table.name",r={}){return fe(e,t,{allowEmpty:r.allowEmpty===true,maxLength:Xa,blockKeyDelimiters:true})}function xt(e,t="tag",r={}){return fe(e,t,{allowEmpty:r.allowEmpty===true,maxLength:Za,blockKeyDelimiters:true})}function at(e,t="index.name",r={}){return fe(e,t,{allowEmpty:r.allowEmpty===true,maxLength:el,blockKeyDelimiters:true,disallowLeadingDollar:true})}function Vi(e,t="index.value"){return fe(e,t,{allowEmpty:true,maxLength:qi})}function Dr(e){return typeof e=="string"&&e.slice(-1)==="."}function xr(e,t){return fe(e,t,{allowEmpty:true,maxLength:qi,blockKeyDelimiters:true})}function ji(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=fe(e.record_id,"record_id",{allowEmpty:false,onlyAlphanumeric:true}):e?.unique_id&&(t.unique_id=e.unique_id),t}function Ur(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:"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 Dt=4503599627370496;function Ut(e){if(typeof e=="number"){if(e>Dt||e<-Dt)throw new a(`Number value should be within range -${Dt} ~ +${Dt}`,{code:"INVALID_PARAMETER"});return e}if(typeof e=="boolean")return e;if(typeof e=="string")return Vi(e,"index.value");throw new a('"index.value" should be type: <number | boolean | string>.',{code:"INVALID_PARAMETER"})}function $i(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"?Dr(t.index.name)?xr(e,"index.range"):Vi(e,"index.range"):e}var Ct={},ol=10080*60,al=3600,Bi=2;function ll(e,t){if(!t)return String(Bi);let r=Math.max(60,e-300)*1e3;return "g"+Bi+"w"+Math.floor(Date.now()/r)}function cl(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 ul(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 Ot(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);}})}function Or(e){return !!e&&typeof e=="object"&&!Array.isArray(e)&&typeof e.__data__=="string"&&Object.keys(e).length===1&&e.__data__.endsWith("/__data__/__json__.json")}var Fe=new Map,dl=1024,fl=/^[0-9A-Za-z]+\/[0-9A-Za-z]+\/__data__\/__json__\.json$/,Hi=/^[0-9A-Za-z_-]+$/,pl=/^(\d{2}|\*\*)$/;function Gi(e){if(typeof e!="string")return null;let t=e.split("?")[0].split("/");if(t.length<15||t[0]!=="https:"||t[1]!==""||!t[2])return null;let r=t.slice(3);return r[0]!=="publ"&&r[0]!=="auth"||r[4]!=="records"||r[7]!=="bin"||!Hi.test(r[1])?null:{origin:t.slice(0,3).join("/"),service:r[1]}}function gl(e){let t=Gi(e);!t||Fe.get(t.service)===t.origin||(Fe.size>=dl&&!Fe.has(t.service)&&Fe.clear(),Fe.set(t.service,t.origin));}function Ki(e,t){if(typeof t!="string"||!fl.test(t))return null;let r=typeof e.usr_tbl=="string"?e.usr_tbl.split("/"):null,n=typeof e.tbl=="string"?e.tbl.split("/"):null,i=null,s=null;if(typeof e.srvc=="string"){let f=e.srvc.split("!")[0].split("/");f.length===2&&(i=f[0],s=f[1]);}i||(i=r?.[2]||n?.[1]||null,i&&i===this.service&&(s=this.owner));let o=typeof e.usr=="string"&&e.usr?e.usr:r?.[0]||null,l=r?.[3]||n?.[2]||null,u=e.rec;for(let f of [i,s,o,u])if(typeof f!="string"||!Hi.test(f))return null;if(typeof l!="string"||!pl.test(l))return null;let c=null;if(Array.isArray(e.bin))for(let f of e.bin){let p=Gi(f);if(p&&p.service===i){c=p.origin;break}}return c=c||Fe.get(i)||null,c?`${c}/${l==="00"?"publ":"auth"}/${i}/${s}/${o}/records/${u}/${l}/bin/${t}`:null}async function Se(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,l=[],u=null;function c(d){let g=d=="**"?"private":parseInt(d);return g=g==0?"public":g==1?"authorized":g==99?"admin":g,g}let f={ip:d=>{let g=d.split("#"),h=g[0];g.length>1&&(s.unique_id=g.slice(1).join("#")),h.slice(-1)==="R"?(s.readonly=true,h=h.slice(0,-1)):s.readonly=false,/^\d{1,3}-\d{1,3}-\d{1,3}-\d{1,3}$/.test(h)&&(h=h.split("-").join("."),o=true),s.ip=h;},rec:d=>{if(!d)return;s.record_id=d;let g=d.substring(0,d.length-9),h=se(g);s.uploaded=h;},usr:d=>{s.user_id=d;},tbl:d=>{if(d&&!s.table.name){let g=d.split("/");s.table.name=le(g[0]),s.table.access_group=c(g[2]),g?.[3]&&(s.table.subscription.is_subscription_record=true);}},usr_tbl:d=>{let g=d.split("/");s.user_id||(s.user_id=g[0]),s.table.name||(s.table.name=le(g[1]),s.table.access_group=c(g[3]),g?.[4]&&(s.table.subscription.is_subscription_record=true));},idx:d=>{if(!d)return;let g=d.split("!"),h=le(g.splice(0,1)[0]),m=hl("!"+g.join("!"));s.index={name:h,value:m};},ref:d=>{d&&(s.reference=d.split("/")[0]);},tags:d=>{s.tags=Array.isArray(d)?d.map(g=>le(g)):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 g={},h=s?.reference||null;if(Array.isArray(d)){let m=await Promise.all(d.map(async _=>{try{let b=_.split("/").slice(3).join("/"),A=b.split("/");if(A.length<12)return null;let w=A[A.length-1],I=A[10];if(I==="__data__"&&w==="__json__.json")return {isDataFile:!0,rawUrl:_};if(hr(I,w))return {isDataFile:!0,rawUrl:_};let E=Pt(I),N=A[9],C=A[8],D=c(A[6]),v=_,x=D!=="public"&&cl.call(this,A)?{expires:al,browserCache:ol}:null;if(D!=="public"&&!i)try{v=await _e.bind(this)(_,{dataType:"endpoint",_ref:h});}catch(M){console.error("Error getting signed url for private file:",M),v=_;}let U={access_group:D,filename:w,url:v,path:b,size:E?E.plainSize:se(N),uploaded:se(C),getFile:(M,de)=>{let ie={dataType:M||"download",progress:de,_ref:h},F=()=>_e.bind(this)(v,Object.assign({},ie,{_update:U}));return x?_e.bind(this)(_,Object.assign({},ie,x)).catch(()=>F()):F()}};return E&&(U.encrypted=!0,U.stored_size=se(N)),{pathKey:E?E.key:I,obj:U}}catch{return null}}));for(let _ of m)if(_&&!_.isDataFile){if(g[_.pathKey]){g[_.pathKey].push(_.obj);continue}g[_.pathKey]=[_.obj];}}s.bin=g;},prv_acs:d=>{for(let g in d)["notify_subscribers","upload_to_feed","feed_referencing_records","notify_referencing_records"].includes(g)?s.table.subscription[g]=d[g]:g==="referencing_index_restrictions"&&Array.isArray(d[g])?s.source[g]=d[g].map(m=>m&&typeof m=="object"&&typeof m.name=="string"?Object.assign({},m,{name:le(m.name)}):m):s.source[g]=d[g];},data:async d=>{let g={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:u},h=()=>{L.call(this)&&(s.encrypted={status:"failed",reason:"DATA_UNAVAILABLE"});},m=async b=>{if(n||!L.call(this)&&!Rt(b))return b;let A=await Fn.bind(this)(b,g);return A.flag&&(s.encrypted=A.flag),A.value},_=ul(d);if(_!==d){s.data=await m(_);return}if(Or(d)){let b=d.__data__,A=l.find(w=>w.endsWith(b))||null;if(!A&&!r){await Promise.resolve();let w=Ki.call(this,e,b),I=false,E;if(w)try{let N=await _e.bind(this)(w,{dataType:"blob",_ref:s.reference||null});E=JSON.parse(await Ot(N)),I=!0;}catch{}if(I){s.data=await m(E);return}h();}if(A){if(r){s.data=d;return}try{let w=await _e.bind(this)(A,{dataType:"blob",_ref:s.reference||null}),I=await Ot(w);s.data=await m(JSON.parse(I));}catch(w){let I=Ki.call(this,e,b),E=false,N;if(I&&I!==A)try{let C=await _e.bind(this)(I,{dataType:"blob",_ref:s.reference||null});N=JSON.parse(await Ot(C)),E=!0;}catch{}if(E){s.data=await m(N);return}console.error("Failed to fetch offloaded record data:",w),s.data=null,h();}return}}s.data=await m(d);}};if(e.record_id)return e;if(Array.isArray(e.bin))for(let d of e.bin)try{if(typeof d!="string")continue;gl(d);let g=d.split("/").slice(3);g.length>=12&&g[10]==="__data__"&&g[g.length-1]==="__json__.json"&&l.push(d),g.length>=12&&hr(g[10],g[g.length-1])&&(u=d);}catch{}let p=[];for(let d in f)if(e.hasOwnProperty(d)){let g=f[d](e[d]);g instanceof Promise&&p.push(g);}return o&&(s.user_id="anonymous:"+s.user_id),await Promise.all(p),s}function hl(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 Wi(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 S.bind(this)("del-files",{endpoints:t,storage:"records"},{auth:true,method:"post"}),n=[];for(let i in r)n.push(Se.bind(this)(r[i]));return Promise.all(n)}async function _e(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 l=false,u=o.split("/"),f=u[2].split("."),p=null;f.length===3&&f[1]==="skapi"&&(p=f[0],l=true);let d=u.slice(3),g=false;if(!l&&(d[0]==="auth"||d[0]==="publ"))try{y.UserId(d[2]),y.UserId(d[3]),g=d[0]=="auth",l=!0;}catch{throw new a("Invalid file url.",{code:"INVALID_PARAMETER"})}let h=p?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:w=>w}),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:se(d[9]),uploaded:se(d[8])};let m=e.split("/").slice(-1)[0],_=t.expires;if(_){if(!l)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 w={request:p?"get-host":"get",id:p||d[5],key:r.split("?")[0],expires:_};h&&(w.service=h);let I=t.browserCache,E={auth:true};if(I){if(I<0)throw new a('"config.browserCache" should be > 0. (seconds)',{code:"INVALID_PARAMETER"});E.method="get",E.stableGateway=true,w.browser_cache=I;let N=this.session?.idToken?.payload?.sub||this.user?.user_id;N&&(w.uid=N),w.nocache=ll(_,t.refresh);}e=(await S.bind(this)("get-signed-url",w,E)).url;}else if(g){let w=Math.floor(Date.now()/1e3);if(!this.bearerToken&&(!this.session?.idToken?.payload?.exp||this.session.idToken.payload.exp<w)){this.log("getFile:requesting new token",null);try{await W.bind(this)().getSession({refreshToken:!0}),this.log("getFile:received new tokens",{exp:this.session?.idToken?.payload?.exp,currTime:w,expiresIn:this.session?.idToken?.payload?.exp-w,token:this.session?.accessToken?.jwtToken,refreshToken:this.session?.refreshToken?.token});}catch(C){throw this.log("getFile:new token error",C),new a("User login is required.",{code:"INVALID_REQUEST"})}}let I=this.bearerToken||this.session?.idToken?.jwtToken;if(!I||!this.user?.user_id)throw new a("User login is required.",{code:"INVALID_REQUEST"});e+=`${e.includes("?")?"&":"?"}t=${encodeURIComponent(I)}`;let E=d[6]==="**"?"**":parseInt(d[6]),N=this.user?.access_group??-1;if(this.user.user_id!==d[3]&&(E==="**"||N<E)){let C=d[5];if(this.__private_access_key[C]&&typeof this.__private_access_key[C]=="string")e+=`&p=${encodeURIComponent(this.__private_access_key[C])}`;else if(this.owner!==this.host)try{let D=await this.requestPrivateRecordAccessKey({record_id:C,reference_id:t?._ref});e+=`&p=${encodeURIComponent(D)}`;}catch{}}}if((L.call(this)?Ir(e):null)&&t?.dataType!=="endpoint"&&t?.dataType!=="info"){let w=await S.bind(this)(e,null,{method:"get",contentType:null,responseType:"blob",fetchOptions:{progress:t?.progress}},{ignoreService:true}),I=await oi.bind(this)(e,w);if(t?.dataType==="blob")return I;if(t?.dataType==="text")return await Ot(I);if(t?.dataType==="base64")return await new Promise((C,D)=>{let v=new FileReader;v.onloadend=()=>C(v.result),v.onerror=()=>D(v.error),v.readAsDataURL(I);});let E=URL.createObjectURL(I),N=document.createElement("a");return N.href=E,document.body.appendChild(N),N.setAttribute("download",m),N.click(),document.body.removeChild(N),setTimeout(()=>URL.revokeObjectURL(E),6e4),null}if(t?.dataType==="endpoint")return t._update&&(t._update.url=e),e;if(t?.dataType==="download"){let w=document.createElement("a");return w.href=e,document.body.appendChild(w),w.setAttribute("download",m),w.target="_blank",w.click(),document.body.removeChild(w),null}return new Promise(async(w,I)=>{try{let E=await S.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 N=new FileReader;N.onloadend=()=>w(N.result),N.readAsDataURL(E);}else w(E);}catch(E){if(t?.browserCache&&!t?.refresh)try{w(await _e.bind(this)(r,Object.assign({},t,{refresh:!0})));return}catch(N){I(N);return}I(E);}})}function Lt(e,t){return `${e||this.service}/${t||this.owner}`}function Cr(e,t){let r=this.__my_unique_ids[e];return r?r[t]:void 0}function Qi(e,t,r){this.__my_unique_ids[e]||(this.__my_unique_ids[e]={}),this.__my_unique_ids[e][t]=r;}function ml(e,t){this.__my_unique_ids[e]&&delete this.__my_unique_ids[e][t];}function zi(e,t){return !t||t.table===void 0?e:Object.assign({},e,{table:t.table})}async function lt(e){if(await this.__connection,!this.__user&&this.connection?.opt?.require_login===true)throw new a(`This project requires users to sign in before reading its database, so "${e}" is not available to a signed-out visitor.`,{code:"REQUIRE_LOGIN"})}async function Ji(e,t=false){e=j(e,{ignoreEmpty:true}).data||{};let r=Lt.bind(this)(e?.service,e?.owner),n="",i=ji(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=Cr.bind(this)(r,n);s&&(t?ml.bind(this)(r,n):e.record_id=s);}}else {let s=await Q.bind(this)(),o=e?.reference,l=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&&(l=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 u=c=>({table:{name:f=>Me(f,"table.name"),access_group:Ur.bind(this),subscription:f=>y.UserId(f,'User ID in "subscription"')},reference:"string",index:{name:["$updated","$uploaded","$referenced_count","$user_id",f=>at(f,"index.name")],value:f=>{let p={$updated:"number",$uploaded:"number",$referenced_count:"number",$user_id:y.UserId};if(p.hasOwnProperty(c.index.name)){let d=p[c.index.name];if(typeof d=="function")return d(f);if(d!==typeof f)throw new a(`"index.value" should be type: ${d}.`,{code:"INVALID_PARAMETER"});return f}return typeof f=="string"&&!f?"":typeof f=="string"&&Dr(c.index.name)?xr(f,"index.value"):Ut(f)},condition:["gt","gte","lt","lte",">",">=","<","<=","=","eq"],range:f=>$i(f,c)},tag:f=>{if(f==null)return f;if(typeof f=="string")return xt(f,"tag");throw new a('"tag" should be type: string.',{code:"INVALID_PARAMETER"})},private_key:"string"});e=y.Params(e||{},u(e),l||s?[]:["table"],{ignoreEmpty:true});}return {query:e,is_reference_fetch:n}}async function Yi(e,t){await this.__connection,await lt.call(this,"getRecords");let r=await Ji.bind(this)(e),n=r.is_reference_fetch,i=await S.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(Se.bind(this)(i.list[o]));return i.list=await Promise.all(s),i}function Lr(e){let t="",r=[],n=Lt.bind(this)(e?.service,e?.owner),i=y.Params(e||{},{record_id:o=>{let l=typeof o=="string"?Cr.bind(this)(n,o):void 0;return l||fe(o,"record_id",{allowEmpty:false})},unique_id:["string",null],readonly:"boolean",table:{name:o=>Me(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:Ur.bind(this)},notification:o=>{if(o==null)return o;if(typeof o!="object"||Array.isArray(o))throw new a('"notification" should be an object with "title" and "body".',{code:"INVALID_PARAMETER"});for(let l of ["title","body"])if(typeof o[l]!="string"||!o[l].trim())throw new a(`"notification.${l}" is required.`,{code:"INVALID_PARAMETER"});return {title:o.title,body:o.body}},source:{referencing_limit:o=>{if(o===null)return null;if(typeof o=="number"){if(0>o)throw new a('"reference_limit" should be >= 0',{code:"INVALID_PARAMETER"});if(o>4503599627370546)throw new a('"reference_limit" should be <= 4503599627370546',{code:"INVALID_PARAMETER"});return o}throw new a('"reference_limit" should be type: <number | null>',{code:"INVALID_PARAMETER"})},prevent_multiple_referencing:"boolean",can_remove_referencing_records:"boolean",only_granted_can_reference:"boolean",allow_granted_to_grant_others:"boolean",referencing_index_restrictions:o=>{if(o===void 0)return;if(!o||Array.isArray(o)&&!o.length)return null;let l={name:c=>at(c,'"name" in "index_restrictions"'),value:c=>Ut(c),condition:["gt","gte","lt","lte",">",">=","<","<=","=","eq","!=","ne",()=>null],range:c=>{if(c!==null&&typeof o.value!=typeof c)throw new a('Index restriction "range" type should match the type of "value".',{code:"INVALID_PARAMETER"});if(!o.hasOwnProperty("value"))throw new a('Index restriction "value" is required.',{code:"INVALID_PARAMETER"});return c}};Array.isArray(o)||(o=[o]);let u=o.map(c=>y.Params(c,l,["name"]));if(u.length)for(let c of u)c.condition&&c.hasOwnProperty("range")&&delete c.range;return u}},reference:o=>{if(o===null)return {record_id:null};if(o){if(typeof o=="string"){t=o;let l=Cr.bind(this)(n,o);return l||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:l=>l==null?l:(t=l,typeof this.__private_access_key?.[l]=="string"&&(e.reference_private_key=this.__private_access_key[l]||void 0),fe(l,"reference.record_id",{allowEmpty:false,onlyAlphanumeric:true}))})}},index:[null,{name:o=>at(o,"index.name"),value:o=>Ut(o)}],tags:o=>{if(o==null)return o;if(typeof o=="string"&&(o=o.split(",").map(l=>l.trim())),!Array.isArray(o))throw new a('"tag" should be type: <string | string[]>.',{code:"INVALID_PARAMETER"});return o.map(l=>xt(l,"tag"))},remove_bin:o=>{if(!o)return null;let l=[];if(Array.isArray(o))for(let u of o)if(typeof u=="string")l.push(u.split("?")[0]);else if(u.url&&u.size&&u.filename){let f=u.url.split("/").slice(0,3).join("/")+"/"+u.path;l.push(f);}else throw new a('"remove_bin" should be type: <string[] | BinaryFile[] | null>',{code:"INVALID_PARAMETER"});else throw new a('"remove_bin" should be type: <string[] | BinaryFile[] | null>',{code:"INVALID_PARAMETER"});return l},progress:"function",data:o=>o},[],{precall:o=>{let l=o?.data||{};if(!l?.record_id&&!l.table)throw new a('"table.name" is required.',{code:"INVALID_PARAMETER"});typeof l.table=="string"&&(l.table={name:l.table},l?.record_id||(l.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 Mr(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={},o={},u={_is_bulk_:await Promise.all(e.map(async(h,m)=>{if(!h||typeof h!="object"||Array.isArray(h))throw new a(`"params[${m}]" should be type: <object>.`,{code:"INVALID_PARAMETER"});o[m]={has:h.data!==void 0,value:h.data};let _=Lr.bind(this)(h),b=_.config;if(L.call(this)){let A=Object.prototype.hasOwnProperty.call(b,"data"),w=await mr.bind(this)(b.data,zi(h,b),A);w.encrypted&&(b.data=w.send,s[m]=w.plain);}if(_.is_reference_post&&t.push(_.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 a('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 a('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&&(u.service=r),n!==void 0&&(u.owner=n);let c={auth:!!this.__user,method:"post"},f={};Object.keys(f).length&&Object.assign(c,{fetchOptions:f});let p=await S.bind(this)("post-record",u,c),d=await Promise.all(p.map((h,m)=>Se.bind(this)(h,"called from postRecord",o[m]?.has===true,s.hasOwnProperty(m))));for(let h=0;h<d.length;h++)s.hasOwnProperty(h)&&d[h]&&!d[h].error?(d[h].data=s[h],d[h].encrypted={status:"encrypted"}):o[h]?.has&&d[h]&&!p[h]?.error&&Or(p[h]?.data)&&(d[h].data=o[h].value);let g=Lt.bind(this)(r,n);for(let h=0;h<p.length;h++){let m=p[h],_=d[h];if(m&&typeof m=="object"&&m.error&&_&&!_.record_id&&(_.error=m.error),typeof m?.reference_private_key=="string")for(let b of t)this.__private_access_key[b]=m.reference_private_key;_?.unique_id&&Qi.bind(this)(g,_.unique_id,_.record_id);}return d}async function Fr(e,t,r){if(await this.__connection,!t)throw new a('"config" argument is required.',{code:"INVALID_PARAMETER"});let n=Lr.bind(this)(t),i=n.config,s=n.progress,o=n.is_reference_post,l={auth:!!this.__user,method:"post"},u=[],c=j(e);r&&Array.isArray(r)&&r.length&&(u=u.concat(r)),c.files&&Array.isArray(c.files)&&c.files.length&&(u=u.concat(c.files));let f=t?.data!==void 0?t.data:c.data,p=f!==void 0,d=await mr.bind(this)(f,zi(t,i),p),g=null;g=Object.assign({},i),delete g.data,d.omit||(g.data=d.send);let h={};if(typeof s=="function"&&(h.progress=s),Object.keys(h).length&&Object.assign(l,{fetchOptions:h}),d.files==="decrypt"&&t?.record_id){let w=await Pr.bind(this)(t.record_id,"decrypt",s);if(w.length){let I=g.remove_bin;g.remove_bin=Array.isArray(I)?I.concat(w):w;}}if(d.spill&&t?.record_id){let w=new FormData;if(w.append(rt,new File([d.spill],"payload.bin",{type:"application/octet-stream"})),await ot.bind(this)(w,{record_id:t.record_id}),d.retireCt){let I=g.remove_bin,E=[d.retireCt];g.remove_bin=Array.isArray(I)?I.concat(E):E;}}let m=await S.bind(this)("post-record",g,l);if(d.encrypted&&m?.rec&&Ln.bind(this)(m.rec,d.dek),d.files==="encrypt"&&m?.rec)try{let w=await Pr.bind(this)(m.rec,"encrypt",s);w.length&&await Fr.bind(this)(void 0,{record_id:m.rec,remove_bin:w});}catch(w){console.error("Failed to encrypt existing attachments after making the record private:",w);}if(H()&&u.length){let w=new FormData;for(let N of u)w.append(N.name,N.file,N.file.name);let I={record_id:m.rec,progress:s};i.hasOwnProperty("service")&&(I.service=i.service);let{bin_endpoints:E}=await ot.bind(this)(w,I);m.bin?m.bin.push(...E):m.bin=E;}o&&typeof m?.reference_private_key=="string"&&(this.__private_access_key[o]=m.reference_private_key);let _=!!m&&Or(m.data),b=!d.omit&&d.send!==void 0,A=await Se.bind(this)(m,"called from postRecord",b,d.encrypted);if(_&&b&&!d.encrypted&&(A.data=d.plain),d.encrypted&&(A.data=d.plain,A.encrypted={status:"encrypted",recipients:Object.keys(d.send.k||{})}),A.unique_id){let w=Lt.bind(this)(i?.service,i?.owner);Qi.bind(this)(w,A.unique_id,A.record_id),H()&&(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 A}async function Xi(e,t){await lt.call(this,"getTables");let r=await S.bind(this)("get-table",y.Params(e||{},{table:i=>Me(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 l=o.substring(4);l==="pv"?l="private":l==="00"?l="public":l==="01"?l="authorized":l==="99"&&(l="admin"),i[`number_of_records_in_access_group_${l}`]=i[o],delete i[o];}}i.hasOwnProperty(s)&&(i[n[s]]=i[s],delete i[s]);}typeof i.table=="string"&&(i.table=le(i.table));}return r}async function Zi(e,t){if(await lt.call(this,"getIndexes"),!e?.table)throw new a('"table" is required.',{code:"INVALID_PARAMETER"});let r=y.Params(e||{},{table:s=>Me(s,"table",{allowEmpty:true}),index:s=>at(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 fe(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 S.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("/"),l={table:le(o[1]),index:le(o[2]),number_of_records:s.cnt_rec};for(let u in i)Object.prototype.hasOwnProperty.call(s,u)&&(l[i[u]]=s[u]);return l})),n}async function es(e,t){await lt.call(this,"getTags");let r=await S.bind(this)("get-tag",y.Params(e||{},{table:n=>Me(n,"table",{allowEmpty:true}),tag:n=>xt(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:le(i[1]),tag:le(i[0]),number_of_records:n.cnt_rec}})),r}async function ts(e,t){await lt.call(this,"getUniqueId");let r=await S.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 rs(e,t){await this.__connection;let r=await Ji.bind(this)(e,true),n=r.is_reference_fetch,i=await S.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 Se.bind(this)(s,"called from deleteRecords",!0,!1,!0)}catch{return s}}))),i?.message||i}async function ns(e){if(L.call(this)){let t=typeof e.user_id=="string"?[e.user_id]:e.user_id;Array.isArray(t)&&t.length&&await Tr.bind(this)(e.record_id,t);}return as.bind(this)({record_id:e.record_id,user_id:e.user_id,execute:"add"})}async function is(e){let t=await as.bind(this)({record_id:e.record_id,user_id:e.user_id||null,execute:"remove"});if(L.call(this)){let r=typeof e.user_id=="string"?[e.user_id]:e.user_id;await Yn.bind(this)(e.record_id,Array.isArray(r)&&r.length?r:null);}return t}async function ss(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 S.bind(this)("grant-private-access",r,{auth:true,fetchOptions:t});return i.list=i.list.map(n),i}function os(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(Ct[t])return Ct[t];let n=S.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 Ct[t];});return Ct[t]=n,n}function as(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),S.bind(this)("grant-private-access",r,{auth:true})}var yl=100;async function ls(e){if(await this.__connection,!Array.isArray(e)||!e.length)throw new a('"items" should be a non-empty array.',{code:"INVALID_PARAMETER"});let t=[],r=[],n=[];for(let s=0;s<e.length;s++){let o=e[s];try{if(!o||typeof o!="object"||Array.isArray(o))throw new a(`"items[${s}]" should be an object with "config".`,{code:"INVALID_PARAMETER"});let l=o.config;if(!l||typeof l!="object"||Array.isArray(l))throw new a(`"items[${s}].config" is required.`,{code:"INVALID_PARAMETER"});Lr.bind(this)(Object.assign({},l));let u=Object.assign({},l);delete u.data;let c=l.data!==void 0?l.data:o.data;if(c!==void 0){let f=c!==null&&typeof c=="object"?j(c):{data:c,files:[]};if(f.files&&f.files.length)throw new a(`"items[${s}].data" carries files. postRecords() does not attach files; use uploadFiles() on the saved record.`,{code:"INVALID_PARAMETER"});u.data=f.data;}n.push({index:s,config:u});}catch(l){r.push({index:s,code:String(l?.code||"INVALID_PARAMETER"),message:String(l?.message||l)});}}let i=0;for(;i<n.length;){let s=n.slice(i,i+yl),o=await Mr.bind(this)(s.map(u=>Object.assign({},u.config)));if(!Array.isArray(o)||!o.length){for(let u of s)r.push({index:u.index,code:"ERROR",message:"The server answered nothing for this record."});i+=s.length;continue}let l=Math.min(o.length,s.length);for(let u=0;u<l;u++){let c=o[u];if(c&&c.record_id)t.push(c);else {let f=c?.error||{};r.push({index:s[u].index,code:String(f.code||"ERROR"),message:String(f.message||"The record was not saved.")});}}i+=l;}return r.sort((s,o)=>s.index-o.index),{list:t,failed:r}}var O={},G={},ce={},ge={},pe={},Mt={},Ft={};function cs(e,t,r){e[t]||(e[t]=[]),e[t].push(r);}async function qt(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}var qr="stun:stun.skapi.com:3468";async function us(){let e=ys();if(!e)try{e=await $r.bind(this)();}catch{e=null;}let t=e?e.servers:[{urls:qr}];return t.some(r=>(Array.isArray(r.urls)?r.urls:[r.urls]).some(n=>/^stuns?:/.test(n)))?t:[{urls:qr},...t]}function ds(e){if(e==null||e==="")return [{urls:qr}];let t=r=>typeof r=="string"&&/^(stun|stuns|turn|turns):/.test(r);if(typeof e=="string"){if(!t(e))throw new a('"ice" should be a "stun:", "stuns:", "turn:" or "turns:" url, or a list of { urls, username, credential }.',{code:"INVALID_PARAMETER"});return [{urls:e}]}if(!Array.isArray(e)||!e.length)throw new a('"ice" should be a url string, or a non-empty list of { urls, username, credential }.',{code:"INVALID_PARAMETER"});return e.map((r,n)=>{if(!r||typeof r!="object"||Array.isArray(r))throw new a(`"ice[${n}]" should be an object: { urls, username, credential }.`,{code:"INVALID_PARAMETER"});let i=r.urls,s=Array.isArray(i)?i:[i];if(!s.length||!s.every(t))throw new a(`"ice[${n}].urls" should be a "stun:", "stuns:", "turn:" or "turns:" url, or a list of them.`,{code:"INVALID_PARAMETER"});let o={urls:i};for(let l of ["username","credential"])if(r[l]!==void 0){if(typeof r[l]!="string")throw new a(`"ice[${n}].${l}" should be type: <string>.`,{code:"INVALID_PARAMETER"});o[l]=r[l];}if(s.some(l=>/^turns?:/.test(l))&&(!o.username||!o.credential))throw new a(`"ice[${n}]" is a TURN server: it needs "username" and "credential".`,{code:"INVALID_PARAMETER"});return o})}async function jr(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 O[s].setRemoteDescription(new RTCSessionDescription(i));let l=await O[s].createAnswer();await O[s].setLocalDescription(l),o.send(JSON.stringify({action:"rtc",uid:s,content:{sdpanswer:l},token:this.session.accessToken.jwtToken}));}O?.[t]?e?(await qt(Ft,t,i=>n.bind(this)(i,t,r)),await n.bind(this)(e,t,r)):await qt(Ft,t,i=>n.bind(this)(i,t,r)):e&&cs(Ft,t,e);}async function Vt(e,t){if(this.log("receiveIceCandidate",e),O?.[t]&&O[t]?.remoteDescription&&O[t]?.remoteDescription?.type){if(!e)return qt(Mt,t,r=>O[t].addIceCandidate(r));await qt(Mt,t,r=>O[t].addIceCandidate(r)),await O[t].addIceCandidate(e);}else cs(Mt,t,e);}async function ue(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 Ft[s],delete Mt[s],G[s]&&Object.values(G[s]).forEach(o=>{o.readyState!=="closed"&&o.close();}),delete G[s],O?.[s]){O[s].connectionState!=="closed"&&(O[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:O[s],timestamp:new Date().toISOString(),state:O[s].connectionState,iceState:O[s].iceConnectionState,signalingState:O[s].signalingState};pe[s]&&pe[s](o),this.log("closeRTC",o);}delete pe[s],delete ge[s],delete ce[s],delete O[s];};if(n)for(let s in O)i(s);else i(r);this.log("Cleaning up media stream..."),this.__mediaStream&&(this.__mediaStream.getTracks().forEach(s=>{s.stop();}),this.__mediaStream=null);}async function fs(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 ps(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:o=>o,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:n==null||n===""?await us.bind(this)():ds(n)};O?.[r]||(O[r]=new RTCPeerConnection(s)),e?.media&&(this.__mediaStream=await fs(e.media),this.__mediaStream.getTracks().forEach(o=>{O[r].addTrack(o,this.__mediaStream);})),pe[r]=t,G[r]||(G[r]={});for(let o=0;o<e.channels.length;o++){let l=e.channels[o];if(typeof l=="string")switch(l){case "text-chat":l={ordered:true,maxRetransmits:10,protocol:"text-chat"};break;case "file-transfer":l={ordered:false,maxPacketLifeTime:3e3,protocol:"file-transfer"};break;case "video-chat":l={ordered:true,maxRetransmits:10,protocol:"video-chat"};break;case "voice-chat":l={ordered:true,maxRetransmits:10,protocol:"voice-chat"};break;case "gaming":l={ordered:false,maxPacketLifeTime:100,protocol:"gaming"};break;default:l={ordered:true,maxRetransmits:10,protocol:"default"};break}let u=l.protocol||"default";if(Object.keys(G[r]).includes(u))throw new a(`Data channel with the protocol "${u}" already exists.`,{code:"INVALID_REQUEST"});let c=O[r].createDataChannel(u,l);G[r][u]=c;}for(let o in G[r]){let l=G[r][o];ms.bind(this)(r,l);}return hs.bind(this)(r,["onnegotiationneeded"]),await Vr.bind(this)(r),{hangup:()=>ce[r]&&ce[r](false),connection:new Promise(o=>{ce[r]=(l=>{if(this.log("receiver picked up the call",r),!l)return ue.bind(this)({cid:r}),null;O[r].onnegotiationneeded=()=>{this.log("onnegotiationneeded",`sending offer to "${r}".`),Vr.bind(this)(r),pe[r]&&pe[r]({type:"negotiationneeded",target:O[r],timestamp:new Date().toISOString(),signalingState:O[r].signalingState,connectionState:O[r].iceConnectionState,gatheringState:O[r].iceGatheringState});},o({target:O[r],channels:G[r],hangup:()=>ue.bind(this)({cid:r}),media:this.__mediaStream});}).bind(this);})}}function gs(e){return async(t,r)=>{t=t||{},t=j(t).data;let n=e.sender_cid,i=await this.__socket;if(!ge[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 s=t.ice===void 0||t.ice===null||t.ice===""?await us.bind(this)():ds(t.ice);return O?.[n]||(O[n]=new RTCPeerConnection({iceServers:s})),t?.media&&(this.__mediaStream=await fs(t.media),this.__mediaStream.getTracks().forEach(o=>{O[n].addTrack(o,this.__mediaStream);})),delete ge[n],pe[n]=r,G[n]||(G[n]={}),O[n].ondatachannel=o=>{this.log("ondatachannel",`received data channel "${o.channel.label}".`);let l=o.channel;G[n][l.label]=l,ms.bind(this)(n,l);},hs.bind(this)(n,["onnegotiationneeded"]),await jr.bind(this)(null,n),await Vt.bind(this)(null,n),i.send(JSON.stringify({action:"rtc",uid:n,content:{pickup:this.user.user_id},token:this.session.accessToken.jwtToken})),{target:O[n],channels:G[n],hangup:()=>ue.bind(this)({cid:n}),media:this.__mediaStream}}}async function Vr(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 O[e].createOffer();await O[e].setLocalDescription(r);let n=O[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 bl(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=pe[t]||(()=>{}),i=e.candidate;this.log("ice gathering state set to",O[t].iceGatheringState),n({type:"icecandidate",target:O[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:O[t].iceGatheringState,connectionState:O[t].iceConnectionState}),r.send(JSON.stringify({action:"rtc",uid:t,content:{candidate:i},token:this.session.accessToken.jwtToken}));}function hs(e,t){let r=new Set(t),n=pe[e]||(o=>{}),i=O[e],s={ontrack:o=>{n({type:"track",target:i,timeStamp:o.timeStamp,streams:o.streams,track:o.track});},onicecandidate:o=>{bl.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:()=>{Vr.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")&&ue.bind(this)({cid:e});}};for(let[o,l]of Object.entries(s))r.has(o)||(i[o]=l);}function ms(e,t,r){let n=new Set(r),i=pe[e]||(o=>{}),s={onmessage:o=>{let l={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(l);},onerror:o=>{let l={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(l);},onclose:o=>{let l={type:o.type,target:t,timeStamp:o.timeStamp,readyState:t.readyState,label:t.label,id:t.id};this.log(`${t.label}: closed`,null),i(l),G[e]&&(delete G[e][t.label],Object.keys(G[e]).length===0&&ue.bind(this)({cid:e}));},onbufferedamountlow:o=>{let l={target:t,bufferedAmount:t.bufferedAmount,bufferedAmountLowThreshold:t.bufferedAmountLowThreshold,type:o.type,timeStamp:o.timeStamp};this.log(`${t.label}: bufferedamountlow`,t.bufferedAmount),i(l);},onopen:o=>{this.log("dataChannel",`data channel: "${t.label}" is open and ready to send messages.`);let l={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(l);}};for(let[o,l]of Object.entries(s))n.has(o)||(t[o]=l);}var je=[],qe=null;function bs(e){return e&&Array.isArray(e.servers)&&e.servers.length?{servers:e.servers,expires:typeof e.expires=="number"?e.expires:null}:null}function ys(){if(!qe)return null;let e=Math.floor(Date.now()/1e3);return (qe.expires??qe.at+3600)-60>e?{servers:qe.servers,expires:qe.expires}:null}async function $r(e=2500,t){let r=t||(this.__socket?await this.__socket:null);return !r||r.readyState!==1||!this?.session?.accessToken?.jwtToken?null:new Promise(n=>{let i=false,s=setTimeout(()=>{i||(i=true,je=je.filter(l=>l!==o),n(null));},e),o=l=>{i||(i=true,clearTimeout(s),n(bs(l)));};je.push(o);try{r.send(JSON.stringify({action:"ice",token:this.session.accessToken.jwtToken}));}catch{o(null);}})}var we;function _s(){return we}var Re=null,ct=true,Ve=0;async function _l(){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 Br=null;async function jt(){if(typeof window>"u"||window._runningInNodeJS)throw new a("WebSocket is not supported in Node.js environment.",{code:"NOT_SUPPORTED"});ct=true;let e=this.__socket?await this.__socket:this.__socket;ue.bind(this)({close_all:true}),we&&Be.bind(this)({group:null}),Ve=0,Re&&(Re.terminate(),Re=null);try{e&&e.close();}catch{}return window.removeEventListener("visibilitychange",Br),this.__socket=null,null}async function $e(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 i=await this.__socket;if(i.readyState!==WebSocket.CLOSED&&i.readyState!==WebSocket.CLOSING)return this.__socket}}else if(ct&&(Br=()=>{!document.hidden&&!ct&&$e.bind(this)(e,0,"reconnect");},this.__socket instanceof Promise))return this.__socket;Re&&(Re.terminate(),Re=null);let n={value:null};return this.__socket=new Promise(async(i,s)=>{let o=l=>{this.__socket===n.value&&(this.__socket=null),s(l);};try{await Oe.bind(this)();}catch(l){o(l);return}setTimeout(async()=>{try{let l=await _l.bind(this)();l.onopen=()=>{ct=!1,Ve=0,r!=="reconnect"&&window.addEventListener("visibilitychange",Br),this.log("realtime onopen","Connected to WebSocket server."),e({type:"success",message:"Connected to WebSocket server."}),we&&l.send(JSON.stringify({action:"joinRoom",rid:we,token:this.session.accessToken.jwtToken})),$r.bind(this)(5e3,l).catch(()=>null);let u=`
206
+ var ha=Object.defineProperty;var ma=Object.getOwnPropertyDescriptor;var Ce=(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 P=(e,t,r,n)=>{for(var s=ma(t,r),i=e.length-1,o;i>=0;i--)(o=e[i])&&(s=(o(t,r,s))||s);return s&&ha(t,r,s),s};function xe(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 Ce=="function")return Ce(e)}catch{}return null}var tr,rr,nr=()=>tr!==void 0?tr:tr=xe("fs"),ir=()=>rr!==void 0?rr:rr=xe("path"),we=typeof globalThis<"u"?globalThis:void 0,At=we?.window;function ya(e){if(Buffer)return Buffer.from(e).toString("base64");let t="",r=new Uint8Array(e),n=32768;for(let s=0;s<r.length;s+=n){let i=r.subarray(s,s+n);t+=String.fromCharCode.apply(null,Array.from(i));}if(typeof btoa=="function")return btoa(t);throw new Error("No base64 encoder available in this environment.")}if(At)At.global=At,At.global._runningInNodeJS=false;else if(we&&(we.global=we,typeof we.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(s=>{let i=ya(s),o=n.type||"application/octet-stream";this.result=`data:${o};base64,${i}`,this.onload&&this.onload({target:this}),this.onloadend&&this.onloadend({target:this});}).catch(s=>{this.error=s,this.onerror&&this.onerror({target:this});});}readAsArrayBuffer(n){n.arrayBuffer().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});});}readAsText(n,s="utf-8"){n.text().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});});}}we.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,s){this._method=n,this._url=s,this.readyState=1;}setRequestHeader(n,s){this._headers[n]=s;}getResponseHeader(n){return null}abort(){this._aborted=true,this.onabort&&this.onabort({});}send(n){if(this._aborted)return;let s={method:this._method,headers:this._headers};n&&this._method!=="GET"&&this._method!=="HEAD"&&(s.body=n),fetch(this._url,s).then(async i=>{if(!this._aborted){if(this.status=i.status,this.statusText=i.statusText,this.responseURL=i.url,this.readyState=4,this.responseType==="blob")this.response=await i.blob();else if(this.responseType==="json")try{this.response=await i.json();}catch{this.response=null;}else this.responseType==="arraybuffer"?this.response=await i.arrayBuffer():(this.responseText=await i.text(),this.response=this.responseText);this.onload&&this.onload({});}}).catch(i=>{this._aborted||this.onerror&&this.onerror(i);});}}we.XMLHttpRequest=t,we.window={_runningInNodeJS:true,alert:r=>console.error("[Alert]",r),sessionStorage:(()=>{let r=new Map;return {getItem:n=>r.has(n)?r.get(n):null,setItem:(n,s)=>{r.set(n,String(s));},removeItem:n=>{r.delete(n);}}})(),localStorage:{getItem:r=>{let n=nr(),s=ir();if(!n||!s)return null;try{let i=s.resolve(process.cwd(),"states","localStorage",`${r}.skapi`);return n.existsSync(i)?n.readFileSync(i,"utf8"):null}catch{return null}},setItem:(r,n)=>{let s=nr(),i=ir();if(!(!s||!i))try{let o=i.resolve(process.cwd(),"states","localStorage");s.existsSync(o)||s.mkdirSync(o,{recursive:!0});let a=i.resolve(o,`${r}.skapi`);s.writeFileSync(a,n,"utf8");}catch{}},removeItem:r=>{let n=nr(),s=ir();if(!(!n||!s))try{let i=s.resolve(process.cwd(),"states","localStorage",`${r}.skapi`);n.existsSync(i)&&n.unlinkSync(i);}catch{}}},location:{href:"",origin:"",hostname:"",protocol:"",replace:r=>{}},navigator:{userAgent:`nodejs/${we?.process?.versions?.node||"unknown"}`,mediaDevices:{getUserMedia:async r=>{throw new Error("getUserMedia is not supported in Node.js environment.")}}},addEventListener:()=>{},removeEventListener:()=>{}};}var l=class extends Error{constructor(t,r){if(Array.isArray(t)&&t.length<=2){let n=t[1];if(t.length>2)for(let s=2;s<t.length&&typeof t[s]=="string";s++)n+=t[s];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 Ee="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",sr=BigInt(Ee.length),ba=2*1024*1024,_a=["aud","cognito:username","event_id","exp","iat","iss","jti","origin_jti","secret_key","token_use"],un={auth_time:"log",sub:"user_id"},hn=["0","1","2","3","4","5","6","7","8","9","a","b","c","d","e","f","g","h","i","j","k","l"],mn=["us31","us72","ap51","ap22","ap41","eu71","ap21","us32","us71","af51","ap31","ap43","ap23","ap42","ca01","eu01","eu72","eu51","eu73","eu11","me51","sa31"],dn=typeof TextEncoder<"u"?new TextEncoder:null;function wa(){if(typeof globalThis<"u")return globalThis.Buffer}function W(e){if(dn)return dn.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 or(e){if(e instanceof Uint8Array)return e;if(typeof e=="string")return W(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=wa();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,s=-271733879,i=-1732584194,o=271733878,a,u,c,f;for(let p=0;p<r.length;p+=16)a=n,u=s,c=i,f=o,n=A.ff(n,s,i,o,r[p],7,-680876936),o=A.ff(o,n,s,i,r[p+1],12,-389564586),i=A.ff(i,o,n,s,r[p+2],17,606105819),s=A.ff(s,i,o,n,r[p+3],22,-1044525330),n=A.ff(n,s,i,o,r[p+4],7,-176418897),o=A.ff(o,n,s,i,r[p+5],12,1200080426),i=A.ff(i,o,n,s,r[p+6],17,-1473231341),s=A.ff(s,i,o,n,r[p+7],22,-45705983),n=A.ff(n,s,i,o,r[p+8],7,1770035416),o=A.ff(o,n,s,i,r[p+9],12,-1958414417),i=A.ff(i,o,n,s,r[p+10],17,-42063),s=A.ff(s,i,o,n,r[p+11],22,-1990404162),n=A.ff(n,s,i,o,r[p+12],7,1804603682),o=A.ff(o,n,s,i,r[p+13],12,-40341101),i=A.ff(i,o,n,s,r[p+14],17,-1502002290),s=A.ff(s,i,o,n,r[p+15],22,1236535329),n=A.gg(n,s,i,o,r[p+1],5,-165796510),o=A.gg(o,n,s,i,r[p+6],9,-1069501632),i=A.gg(i,o,n,s,r[p+11],14,643717713),s=A.gg(s,i,o,n,r[p],20,-373897302),n=A.gg(n,s,i,o,r[p+5],5,-701558691),o=A.gg(o,n,s,i,r[p+10],9,38016083),i=A.gg(i,o,n,s,r[p+15],14,-660478335),s=A.gg(s,i,o,n,r[p+4],20,-405537848),n=A.gg(n,s,i,o,r[p+9],5,568446438),o=A.gg(o,n,s,i,r[p+14],9,-1019803690),i=A.gg(i,o,n,s,r[p+3],14,-187363961),s=A.gg(s,i,o,n,r[p+8],20,1163531501),n=A.gg(n,s,i,o,r[p+13],5,-1444681467),o=A.gg(o,n,s,i,r[p+2],9,-51403784),i=A.gg(i,o,n,s,r[p+7],14,1735328473),s=A.gg(s,i,o,n,r[p+12],20,-1926607734),n=A.hh(n,s,i,o,r[p+5],4,-378558),o=A.hh(o,n,s,i,r[p+8],11,-2022574463),i=A.hh(i,o,n,s,r[p+11],16,1839030562),s=A.hh(s,i,o,n,r[p+14],23,-35309556),n=A.hh(n,s,i,o,r[p+1],4,-1530992060),o=A.hh(o,n,s,i,r[p+4],11,1272893353),i=A.hh(i,o,n,s,r[p+7],16,-155497632),s=A.hh(s,i,o,n,r[p+10],23,-1094730640),n=A.hh(n,s,i,o,r[p+13],4,681279174),o=A.hh(o,n,s,i,r[p],11,-358537222),i=A.hh(i,o,n,s,r[p+3],16,-722521979),s=A.hh(s,i,o,n,r[p+6],23,76029189),n=A.hh(n,s,i,o,r[p+9],4,-640364487),o=A.hh(o,n,s,i,r[p+12],11,-421815835),i=A.hh(i,o,n,s,r[p+15],16,530742520),s=A.hh(s,i,o,n,r[p+2],23,-995338651),n=A.ii(n,s,i,o,r[p],6,-198630844),o=A.ii(o,n,s,i,r[p+7],10,1126891415),i=A.ii(i,o,n,s,r[p+14],15,-1416354905),s=A.ii(s,i,o,n,r[p+5],21,-57434055),n=A.ii(n,s,i,o,r[p+12],6,1700485571),o=A.ii(o,n,s,i,r[p+3],10,-1894986606),i=A.ii(i,o,n,s,r[p+10],15,-1051523),s=A.ii(s,i,o,n,r[p+1],21,-2054922799),n=A.ii(n,s,i,o,r[p+8],6,1873313359),o=A.ii(o,n,s,i,r[p+15],10,-30611744),i=A.ii(i,o,n,s,r[p+6],15,-1560198380),s=A.ii(s,i,o,n,r[p+13],21,1309151649),n=A.ii(n,s,i,o,r[p+4],6,-145523070),o=A.ii(o,n,s,i,r[p+11],10,-1120210379),i=A.ii(i,o,n,s,r[p+2],15,718787259),s=A.ii(s,i,o,n,r[p+9],21,-343485551),n=A.ad(n,a),s=A.ad(s,u),i=A.ad(i,c),o=A.ad(o,f);return A.rh(n)+A.rh(s)+A.rh(i)+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,s,i,o){return A.ad(A.rl(A.ad(A.ad(r,t),A.ad(s,o)),i),n)}static ff(t,r,n,s,i,o,a){return A.cm(r&n|~r&s,t,r,i,o,a)}static gg(t,r,n,s,i,o,a){return A.cm(r&s|n&~s,t,r,i,o,a)}static hh(t,r,n,s,i,o,a){return A.cm(r^n^s,t,r,i,o,a)}static ii(t,r,n,s,i,o,a){return A.cm(n^(r|~s),t,r,i,o,a)}static sb(t){let r,n=(t.length+8>>6)+1,s=new Array(n*16);for(r=0;r<n*16;r++)s[r]=0;for(r=0;r<t.length;r++)s[r>>2]|=t.charCodeAt(r)<<r%4*8;return s[r>>2]|=128<<r%4*8,s[n*16-2]=t.length*8,s}};A.alphabet="0123456789abcdef";var ne=A;function yn(e){if(e===0)return Ee[0];let t="";for(;e>0;)t=Ee[e%62]+t,e=Math.floor(e/62);return t}function de(e){return e.split("").reverse().reduce((t,r,n)=>t+Ee.indexOf(r)*62**n,0)}function Se(e=6){let t="",r="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",n=r.length,s=0;for(;s<e;)t+=r.charAt(Math.floor(Math.random()*n)),s+=1;return t}function ar(){return typeof window>"u"||!!window?._runningInNodeJS}function Q(){return !ar()&&typeof document<"u"&&typeof document.createElement=="function"}function Tt(e){let t;try{t=JSON.stringify(e);}catch{throw new l("Invalid data type.",{code:"INVALID_REQUEST"})}if(new Blob([t]).size>ba)throw new l("Data should not exceed 2MB",{code:"INVALID_REQUEST"})}function fn(e){return e===""||e==="on"||e==="true"}function pn(e){return e==="false"}function gn(e,t,r){t.name&&r(e,t.name,t.value);}var It=Q(),Ea=typeof SubmitEvent<"u",Ra=typeof HTMLFormElement<"u";function $(e,t,r){let n={},s=[];function i(u,c,f){if(t?.ignoreEmpty&&f==="")return;if(t?.nullIfEmpty&&f===""&&(f=null),typeof r=="function"){let g=r(c,f);g!==void 0&&(f=g);}let p=c.split("[").map(g=>{let h=g.replace("]",""),m=Number(h);return !isNaN(m)&&!h.includes(".")?h=m:(h[0]==='"'&&h[h.length-1]==='"'||h[0]==="'"&&h[h.length-1]==="'")&&(h=h.replace(/"/g,"").replace(/'/g,"")),h}),d=u;if(typeof p[0]=="number")throw new l("Form key cannot start with an array index.",{code:"INVALID_REQUEST"});for(let g=0;g<p.length;g++){let h=p[g];g<p.length-1?(d[h]===void 0&&(typeof p[g+1]=="number"?d[h]=[]:d[h]={}),d=d[h]):d[h]===void 0?d[h]=f:Array.isArray(d[h])?d[h].push(f):d[h]=[d[h],f];}}function o(u,c,f){if(f instanceof File)u.push({name:c,file:f});else if(f instanceof FileList&&f&&f.length>0)for(let p=0;p<=f.length-1;p++){let d=f.item(p);d&&u.push({name:c,file:d});}}let a=u=>{u.name&&(u.type==="number"?u.value&&i(n,u.name,Number(u.value)):u.type==="checkbox"||u.type==="radio"?u.checked?u.type==="checkbox"&&u.value===""||fn(u.value)?i(n,u.name,true):pn(u.value)?i(n,u.name,false):u.value&&i(n,u.name,u.value):u.type==="checkbox"&&(fn(u.value)?i(n,u.name,false):pn(u.value)&&i(n,u.name,true)):u.type==="file"?u.files&&u.files.length>0&&o(s,u.name,u.files):i(n,u.name,u.value));};if(It&&(e instanceof HTMLInputElement||e instanceof HTMLSelectElement||e instanceof HTMLTextAreaElement))return a(e),Tt(n),{data:n,files:s};if(It&&e instanceof FormData){for(let u of e.entries()){let c=u[0],f=u[1];if(f instanceof File||f instanceof FileList)o(s,c,f);else if(f instanceof Blob){let p=f;if(p.type==="application/json")try{let d=JSON.parse(p.text());i(n,c,d);}catch{i(n,c,p);}}else i(n,c,f);}return Tt(n),{data:n,files:s}}if(It&&Ea&&e instanceof SubmitEvent&&(e=e.target),It&&Ra&&e instanceof HTMLFormElement){let u=e.querySelectorAll("input"),c=e.querySelectorAll("select"),f=e.querySelectorAll("textarea");for(let p=0;p<c.length;p++)gn(n,c[p],i);for(let p=0;p<f.length;p++)gn(n,f[p],i);for(let p=0;p<u.length;p++)a(u[p]);return Tt(n),{data:n,files:s}}return Tt(e),{data:e,files:s}}function Ye(e){let t={};for(let r in e){let n=e[r];if(!_a.includes(r))if(un[r])t[un[r]]=n;else if(r.includes("custom:"))t[r.replace("custom:","")]=n;else if(r==="address"){let s=n;if(s&&typeof s=="object"&&Object.keys(s).length){if(s?.formatted)try{t[r]=JSON.parse(s.formatted);}catch{t[r]=s.formatted;}}else t[r]=s;}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 lr(e){if(e=Na(e),e.split("-").length===7){let t=e.split("-"),r,n;try{r=mn[hn.indexOf(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 cr(e,t){let r=mn.indexOf(e.slice(0,4)),n=hn[r],i=`${e.slice(4,-4)}-${n}${e.slice(-4)}-${t}`;return va(i)}function Aa(e){let t=0n;for(let r of e){let n=Ee.indexOf(r);if(n<0)throw new Error(`INVALID_PARAMETER: Invalid base62 character: ${r}`);t=t*sr+BigInt(n);}return t}function Ta(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 s=Number(n%sr);r=Ee[s]+r,n/=sr;}return r.length<t&&(r="0".repeat(t-r.length)+r),r}function Ia(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 ka(e){let t=0n;for(let r of e)t=(t<<8n)+BigInt(r);return t}function Pa(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 Sa(e){let t=Array.from(or(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 va(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,s,i]=r;if(n.length<2)throw new Error("INVALID_PARAMETER: The first part must contain at least 2 characters.");if(s.length>=Ee.length)throw new Error("INVALID_PARAMETER: The middle section is too long to encode.");let o=n.slice(0,2),a=n.slice(2),u=s+o,c=Ee[s.length]+a+u,f=Pa(i),p=Ta(ka(f));return `${c}-${p}`}function Na(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,s]=r,i=Ee.indexOf(n[0]);if(i<0)throw new Error("INVALID_PARAMETER: Corrupt compressed token: "+t);let o=n.slice(1),a=i+2;if(o.length<a)throw new Error("INVALID_PARAMETER: Corrupt compressed token: "+t);let u=o.slice(0,o.length-a),c=o.slice(o.length-a),f=c.slice(i),p=c.slice(0,i),d=f+u;if(!/^[0-9A-Za-z]+$/.test(d)||!/^[0-9A-Za-z]+$/.test(p))throw new Error("INVALID_PARAMETER: Corrupt compressed token: "+t);let g=Aa(s),h=Ia(g);if(h.length>16)throw new Error("INVALID_PARAMETER: Corrupt compressed token: "+t);let m=new Uint8Array(16);m.set(h,16-h.length);let _=Sa(m);return `${d}-${p}-${_}`}function Xe(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 ur(...e){let t=0;for(let s of e)t+=s.length;let r=new Uint8Array(t),n=0;for(let s of e)r.set(s,n),n+=s.length;return r}function Ca(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 l(`${t} should be type: string.`,{code:"INVALID_PARAMETER"});if(!e.match(r))throw new l(`${t} is invalid.`,{code:"INVALID_PARAMETER"})}else throw new l(`${t} is empty.`,{code:"INVALID_PARAMETER"});return e}function xa(e){if(e&&(typeof e!="string"||e.charAt(0)!=="+"||isNaN(Number(e.substring(1)))))throw new l('"phone_number" is invalid. The format should be "+00123456789". Type: string.',{code:"INVALID_PARAMETER"});return e||""}function Ua(e){if(e){if(typeof e!="string")throw new l('"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 l('"birthdate" is invalid. The format should be "yyyy-mm-dd". Type: string.',{code:"INVALID_PARAMETER"})}}return e||""}function Oa(e){if(e){if(typeof e!="string")throw new l('"password" should be type: string.',{code:"INVALID_PARAMETER"});if(e.length<6)throw new l('"password" should be at least 6 characters.',{code:"INVALID_PARAMETER"});if(e.length>60)throw new l('"password" can be up to 60 characters max.',{code:"INVALID_PARAMETER"})}else throw new l('"password" is required.',{code:"INVALID_PARAMETER"});return e}function La(e,t="email"){if(e){if(typeof e!="string")throw new l(`"${t}"should be type: string.`,{code:"INVALID_PARAMETER"});if(e.length<5)throw new l(`"${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 l(`"${t}" is required.`,{code:"INVALID_PARAMETER"});throw new l(`"${e}" is an invalid email.`,{code:"INVALID_PARAMETER"})}function Ma(e){let t=typeof window<"u",r=(()=>{let s=t&&window.location.origin||null;return s&&s.slice(-1)==="/"&&(s=s.slice(0,-1)),s})(),n=s=>{if(typeof s=="string"){if(s==="*")return "*";{let i=s.trim();if(i[0]==="/"&&r){if(r.slice(0,5)==="file:")throw new l(`"${s}" is an invalid url. Relative URL does not work on local file system. Use full URL string.`,{code:"INVALID_PARAMETER"});i=r+i;}else if(i[0]==="."&&r){if(r.slice(0,5)==="file:")throw new l(`"${s}" 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+="/"),i=a+i.slice(1);}let o;try{o=new URL(i);}catch{throw new l(`"${s}" is an invalid url.`,{code:"INVALID_PARAMETER"})}if(o.protocol)return o.href}}throw new l(`"${s}" is an invalid url.`,{code:"INVALID_PARAMETER"})};return Array.isArray(e)?e.map(s=>n(s)):n(e)}var Fa=/^[a-z0-9]{2,20}$/,qa=/[a-z]/,Va=/^[0-9]+e[0-9]+$/,ja=["tp","admin","public","authorized","newsletter","forward","all","true","false","null"];function $a(e,t){if(e==null){if(t?.allowNull)return null;throw new l('"group" is required.',{code:"INVALID_PARAMETER"})}if(!t?.nameOnly){if(e==="public")return 0;if(e==="authorized")return 1;if(typeof e=="number"){if(!Number.isInteger(e)||e<0||e>99)throw new l('"group" should be an integer between 0 and 99.',{code:"INVALID_PARAMETER"});return e}}if(typeof e!="string"||!Fa.test(e)||!qa.test(e)||Va.test(e)||ja.includes(e))throw new l("Newsletter group name must be 2-20 lowercase alphanumeric characters, contain a letter, and not be a reserved name.",{code:"INVALID_PARAMETER"});return e}function Ba(e,t,r=[],n){let s=$(e,n),i=s.data;t.service="string",t.owner="string";let o={};for(let a in t)if(i&&typeof i=="object"&&!Array.isArray(i)&&i.hasOwnProperty(a))if(typeof i[a]=="function")o[a]=i[a];else try{o[a]=JSON.parse(JSON.stringify(i[a]));}catch{o[a]=i[a];}n?.precall&&n.precall({data:o,files:s?.files||[]});try{return Da__default.default(o,t,r)}catch(a){throw new l(a.message,{code:"INVALID_PARAMETER"})}}var y={UserId:Ca,PhoneNumber:xa,Birthdate:Ua,Password:Oa,Email:La,Url:Ma,newsletterGroup:$a,Params:Ba};var ee="skapi.enc.v1",wn=6e5,Ze=12,kt=null,Ue=null;function En(){return new l("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 Rn(){if(Ue)return Ue;let e=typeof globalThis<"u"?globalThis:void 0;if(e?.crypto?.subtle&&typeof e.crypto.getRandomValues=="function")return Ue=e.crypto,Ue;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 Ce=="function"&&(r=Ce("crypto")),r?.webcrypto?.subtle)return Ue=r.webcrypto,Ue}catch{}throw En()}function oe(){if(kt)return kt;let e=Rn();if(!e.subtle)throw En();return kt=e.subtle,kt}function fr(){try{return oe(),!0}catch{return false}}function te(e){let t=Rn(),r=new Uint8Array(e),n=65536;for(let s=0;s<e;s+=n)t.getRandomValues(r.subarray(s,Math.min(s+n,e)));return r}function V(e){let t=or(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 i=0;i<t.length;i+=32768)n+=String.fromCharCode.apply(null,Array.from(t.subarray(i,i+32768)));r=btoa(n);}else throw new l("No base64 encoder available in this environment.",{code:"NOT_SUPPORTED"});return r.replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function B(e){if(typeof e!="string")throw new l("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 l("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),s=new Uint8Array(n.length);for(let i=0;i<n.length;i++)s[i]=n.charCodeAt(i);return s}throw new l("No base64 decoder available in this environment.",{code:"NOT_SUPPORTED"})}async function Pt(e){let t=await oe().digest("SHA-256",e);return new Uint8Array(t)}async function rt(e,t,r,n){let s=oe(),i=await s.importKey("raw",e,"HKDF",false,["deriveBits"]),o=await s.deriveBits({name:"HKDF",hash:"SHA-256",salt:t,info:r},i,n*8);return new Uint8Array(o)}async function Le(e,t,r,n){let s=oe(),i=W(e.normalize("NFC")),o=await s.importKey("raw",i,"PBKDF2",false,["deriveBits"]),a=new Uint8Array(await s.deriveBits({name:"PBKDF2",salt:t,iterations:r,hash:"SHA-256"},o,256)),u=await rt(a,t,n,32);q(a),q(i);let c=await fe(u);return q(u),c}async function fe(e){return oe().importKey("raw",e,{name:"AES-GCM"},false,["encrypt","decrypt"])}async function An(){let e=te(32),t=await fe(e);return {bytes:e,key:t}}async function ae(e,t,r){let n=te(Ze),s=await oe().encrypt({name:"AES-GCM",iv:n,additionalData:r,tagLength:128},e,t);return {iv:n,ct:new Uint8Array(s)}}async function pe(e,t,r,n){let s=await oe().decrypt({name:"AES-GCM",iv:t,additionalData:n,tagLength:128},e,r);return new Uint8Array(s)}var St={name:"ECDH",namedCurve:"P-256"};async function Tn(){let e=oe(),t=await e.generateKey(St,true,["deriveBits"]),r=new Uint8Array(await e.exportKey("raw",t.publicKey)),n=new Uint8Array(await e.exportKey("pkcs8",t.privateKey)),s=await pr(n);return {pubRaw:r,pkcs8:n,priv:s}}async function pr(e){return oe().importKey("pkcs8",e,St,false,["deriveBits"])}async function In(e){if(e.length!==65||e[0]!==4)throw new l("Malformed public key: expected a 65 byte uncompressed P-256 point.",{code:"INVALID_PARAMETER"});return oe().importKey("raw",e,St,false,[])}async function gr(e){return V(await Pt(e))}async function kn(e,t,r,n){let s=oe(),i=await In(e),o=await s.generateKey(St,true,["deriveBits"]),a=new Uint8Array(await s.deriveBits({name:"ECDH",public:i},o.privateKey,256)),u=await rt(a,new Uint8Array(32),r,32);q(a);let c=await fe(u);q(u);let{iv:f,ct:p}=await ae(c,t,n);return {epk:new Uint8Array(await s.exportKey("raw",o.publicKey)),iv:f,ct:p}}async function Pn(e,t,r,n,s,i){let o=oe(),a=await In(t),u=new Uint8Array(await o.deriveBits({name:"ECDH",public:a},e,256)),c=await rt(u,new Uint8Array(32),s,32);q(u);let f=await fe(c);return q(c),pe(f,r,n,i)}function q(e){e&&e.length&&e.fill(0);}function Ka(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 hr(e){return W(JSON.stringify(e))}function nt(e,t,r){return ur(e,new Uint8Array([0]),W(t),new Uint8Array([0]),W(r))}var ve="0123456789ABCDEFGHJKMNPQRSTVWXYZ",et=16,bn=26,_n=28;function Sn(e){let t=2166136261;for(let r=0;r<e.length;r++)t^=e[r],t=t*16777619>>>0;return t&1023}function vn(e){if(e.length!==et)throw new l(`A recovery code needs exactly ${et} bytes.`,{code:"INVALID_PARAMETER"});let t="",r=0,n=0;for(let i=0;i<e.length;i++)for(r=r<<8|e[i],n+=8;n>=5;)n-=5,t+=ve[r>>n&31];n>0&&(t+=ve[r<<5-n&31]);let s=Sn(e);return t+=ve[s>>5&31]+ve[s&31],(t.match(/.{1,4}/g)||[]).join("-")}function Nn(e){if(typeof e!="string")throw new l("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!==_n)throw new l(`That does not look like a recovery code: expected ${_n} characters, got ${t.length}.`,{code:"ENCRYPTION_BAD_RECOVERY_CODE"});let r=t.slice(0,bn),n=t.slice(bn),s=0,i=0,o=[];for(let c=0;c<r.length;c++){let f=ve.indexOf(r[c]);if(f<0)throw new l(`That does not look like a recovery code: "${r[c]}" is not a valid character.`,{code:"ENCRYPTION_BAD_RECOVERY_CODE"});s=s<<5|f,i+=5,i>=8&&(i-=8,o.push(s>>i&255));}let a=new Uint8Array(o.slice(0,et)),u=Sn(a);if(n!==ve[u>>5&31]+ve[u&31])throw new l("That recovery code has a typo in it: the check characters do not match.",{code:"ENCRYPTION_BAD_RECOVERY_CODE"});return a}async function mr(e,t,r){let n=await rt(e,t,r,32),s=await fe(n);return q(n),s}var dr=[83,75,69,78,67,70],Dn=2,tt=56,Cn=16,Ha=4*1024*1024;function yr(e){if(!e||e.length<tt)return false;for(let t=0;t<dr.length;t++)if(e[t]!==dr[t])return false;return true}function Ne(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 Oe(e,t){return (e[t]<<24>>>0)+(e[t+1]<<16)+(e[t+2]<<8)+e[t+3]}function Ga(e,t,r){let n=Math.floor(r/4294967296);Ne(e,t,n),Ne(e,t+4,r>>>0);}function Wa(e,t){return Oe(e,t)*4294967296+Oe(e,t+4)}async function xn(e,t,r,n,s,i){let o=W(`${ee}|binfile|${r}|${n}|${s}|${i}`),a=await rt(e,t,o,32),u=await fe(a);return q(a),u}async function Un(e){return (await Pt(ur(W(`${ee}|dekid`),e))).subarray(0,8)}function On(e,t,r){return hr([`${ee}|binchunk`,V(e),t,r])}function Qa(e,t,r,n,s,i){let o=new Uint8Array(tt+i.length);return o.set(dr,0),o[6]=Dn,o[7]=i.length?1:0,Ne(o,8,e),Ne(o,12,t),o.set(r,16),Ga(o,32,n),o.set(s,40),Ne(o,48,i.length),Ne(o,52,0),i.length&&o.set(i,tt),o}async function Ln(e,t,r,n,s=Ha){let i=te(Cn),o=await xn(e,i,r.service,r.owner,r.recordOwner,r.recordId),a=await Un(e),u=n?W(JSON.stringify(n)):new Uint8Array(0);if(u.length>4096)throw new l("Encrypted file metadata is too large.",{code:"INVALID_PARAMETER"});let c=t.length===0?1:Math.ceil(t.length/s),f=Qa(s,c,i,t.length,a,u),p=await Pt(f),d=[],g=f.length;for(let _=0;_<c;_++){let b=t.subarray(_*s,Math.min((_+1)*s,t.length)),E=await ae(o,b,On(p,_,c));d.push(E),g+=4+E.iv.length+E.ct.length;}let h=new Uint8Array(g);h.set(f,0);let m=f.length;for(let _ of d)Ne(h,m,_.iv.length+_.ct.length),m+=4,h.set(_.iv,m),m+=_.iv.length,h.set(_.ct,m),m+=_.ct.length;return h}function za(e){if(!yr(e))throw new l("This file is not an encrypted skapi file.",{code:"INVALID_PARAMETER"});let t=Oe(e,48),r=tt+t;if(e.length<r)throw new l("Encrypted file header is truncated.",{code:"INVALID_REQUEST"});let n=null;return t&&(n=JSON.parse(Xe(e.subarray(tt,r)))),{version:e[6],chunkBytes:Oe(e,8),count:Oe(e,12),fileId:e.subarray(16,16+Cn),plainLen:Wa(e,32),dekId:e.subarray(40,48),meta:n,headerLen:r}}async function Mn(e,t,r){let n=za(t);if(n.version!==Dn)throw new l(`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 l("Encrypted file header is malformed.",{code:"INVALID_PARAMETER"});let s=await Un(e);if(!Ka(s,n.dekId))throw new l("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 i=await xn(e,n.fileId,r.service,r.owner,r.recordOwner,r.recordId),o=await Pt(t.subarray(0,n.headerLen)),a=[],u=n.headerLen,c=0;for(let d=0;d<n.count;d++){if(u+4>t.length)throw new l("Encrypted file is truncated.",{code:"INVALID_REQUEST"});let g=Oe(t,u);if(u+=4,g<Ze+16||u+g>t.length)throw new l("Encrypted file is truncated.",{code:"INVALID_REQUEST"});let h=await pe(i,t.subarray(u,u+Ze),t.subarray(u+Ze,u+g),On(o,d,n.count));u+=g,a.push(h),c+=h.length;}let f=new Uint8Array(c),p=0;for(let d of a)f.set(d,p),p+=d.length;return {bytes:f,meta:n.meta}}var Ja="__skapi__keyring",it="__skapi_enc__",qn=1,Ya="skapi-enc",ke="keys",_r=new WeakMap;function Vn(e){if(!e)return null;if(e===true&&(e={}),typeof e!="object")throw new l('"options.encryption" should be a boolean or an object.',{code:"INVALID_PARAMETER"});let t=typeof e.iterations=="number"?e.iterations:wn;if(t<1e5)throw new l('"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:Ja}}function L(){return _r.get(this)||null}function jn(e){if(!e){_r.delete(this);return}_r.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 wr(){let e=L.call(this);if(e){e.user_id&&Dr.call(this,e).catch(()=>{}),e.ready=null,e.unlocking=false,e.pendingRecoveryCode="";for(let[,t]of e.dek)q(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 $n(){let e=L.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 Bn(e,t){return typeof t=="string"&&t===e.cfg.table}function Me(){return `${this.service}/${this.owner}`}function Er(e,t,r,n){let[s,i]=e.split("/");return hr([ee,s,i,t,r,n])}function Kn(e,t,r,n,s){let[i,o]=e.split("/");return W(`${ee}|dekwrap|${i}|${o}|${t}|${r}|${n}|${s}`)}function Rr(e){return e.anch==="uid"?e.uid:e.anch==="rid"?e.rid:""}function Nt(e){return !!e&&typeof e=="object"&&!Array.isArray(e)&&typeof e[it]=="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 Hn="__skapi_no_access__";function ie(e,t,r){if(e.withheld!=="sentinel")return null;let n={[Hn]:true,reason:t};return r&&(n.recipients=r),Object.freeze(n)}function Ar(e){return !!e&&typeof e=="object"&&e[Hn]===true}var Xa=256*1024,at="__skenc_ct__",Gn="payload.bin",Za=`/${at}/${Gn}`;function Tr(e,t){return e===at&&t===Gn}async function el(e,t,r){let n=t?.table,s=typeof n=="string"?n:n?.name;if(n&&(typeof n=="string"||n.access_group!==void 0))return {group:typeof n=="string"?0:Fn(n.access_group),table:s,record:null};if(!r)return {group:n?.access_group!==void 0?Fn(n.access_group):0,table:s,record:null};let i=e.dek.get(r);if(i)return {group:i.access_group,table:s,record:null};let o=await Ie.call(this,r);if(!o)throw new l(`Record "${r}" not found.`,{code:"NOT_EXISTS"});return {group:o.table.access_group,table:o.table.name,record:o}}function tl(e){return this.getFile(e,{dataType:"blob"})}async function Ie(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 Fn(e){return e==="private"||e==="*"||e==="**"?"private":e==="public"?0:e==="authorized"?1:e==="admin"?99:typeof e=="number"?e:0}function br(e,t,r){let n=this.user?.user_id;if(!(!e||!e.user_id||!n||e.user_id===n))throw new l(`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 Ir(e,t,r){let n=L.call(this);if(!n)return {send:e,plain:e,encrypted:false,omit:false};let s=t?.record_id||"",i=s,o=t?.unique_id||"";if(s&&n.passthrough.has(s)){let F=n.passthrough.get(s);return n.passthrough.delete(s),{send:F,plain:e,encrypted:true,omit:false}}let{group:a,table:u,record:c}=await el.call(this,n,t,i);if(a!=="private"){let F=true;if(!r&&s){let X=c||await Ie.call(this,s);if(X&&X.encrypted){if(br.call(this,X,s,"making it non-private"),X.encrypted.status==="failed")throw new l(`Cannot make record "${s}" non-private: its current contents could not be decrypted (${X.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 Je=!!X.bin&&Object.keys(X.bin).some(Rt=>(X.bin[Rt]||[]).some(cn=>cn&&cn.encrypted));if(!Je&&i){let Rt=n.dek.get(i);Rt&&(q(Rt.bytes),n.dek.delete(i));}return {send:X.data,plain:X.data,encrypted:false,omit:false,files:Je?"decrypt":void 0}}}let Z=c;s&&!Z&&(Z=await Ie.call(this,s).catch(()=>null)),Z&&Z.encrypted&&br.call(this,Z,s,"making it non-private");let Et=!!Z&&!!Z.bin&&Object.keys(Z.bin).some(X=>(Z.bin[X]||[]).some(Je=>Je&&Je.encrypted));if(Et&&(F=false),F&&i){let X=n.dek.get(i);X&&(q(X.bytes),n.dek.delete(i));}return {send:e,plain:e,encrypted:false,omit:!r,files:Et?"decrypt":void 0}}if(Bn(n,u))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(Ar.call(this,e))throw new l("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 l("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,it))throw new l(`"${it}" 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 l("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 f=this.user?.user_id;if(!f)throw new l("User login is required to write an encrypted record.",{code:"INVALID_REQUEST"});let p=Me.call(this),d=false;if(s&&n.roll.has(s)){d=true,n.roll.delete(s);let F=n.dek.get(s);n.dek.delete(s),F&&q(F.bytes);}let g=c;s&&!g&&!n.dek.has(s)&&(g=await Ie.call(this,s).catch(()=>null)),g&&br.call(this,g,s,"making it private");let h=!!g&&!g.encrypted&&!!g.bin&&Object.keys(g.bin).some(F=>(g.bin[F]||[]).some(Z=>Z&&!Z.encrypted)),m=null;if(s&&!d&&(m=n.dek.get(s)||null,!m)){let F=g||c||await Ie.call(this,s);if(F&&(i=F.record_id||s,m=n.dek.get(i)||null,!o&&F.unique_id&&(o=F.unique_id),!m&&F.encrypted?.status==="failed"))throw new l(`Cannot update encrypted record "${s}": its current contents could not be decrypted (${F.encrypted.reason}), so its existing key wraps cannot be preserved. Updating anyway would revoke everyone it is shared with.`,{code:"ENCRYPTION_LOCKED"})}i===s&&m&&m.rid&&(i=m.rid),!o&&m&&m.anch==="uid"&&m.uid&&(o=m.uid);let _,b,E;if(m){if(m.own&&m.own!==f)throw new l(`Record "${s}" belongs to another user (${m.own}). Encryption only operates on records you own.`,{code:"ENCRYPTION_NOT_RECORD_OWNER"});_=m.bytes,b=m.key,E=Object.assign({},m.recipients);}else {let F=await An();_=F.bytes,b=F.key,E={};}let w=o?"uid":i?"rid":"new",I=w==="uid"?o:w==="rid"?i:"",R=Er(p,f,w,I),N=nt(R,f,"mk"),U=await ae(n.mk,_,N);E[f]={t:"mk",iv:V(U.iv),ct:V(U.ct)},m&&(m.anch!==w||Rr(m)!==I)&&(E=await rl.call(this,n,_,E,p,f,w,I,R));let D=W(JSON.stringify(e===void 0?null:e)),v=await ae(b,D,R);q(D);let C={[it]:qn,enc:"A256GCM",kw:"ECDH-ES+A256GCM",anch:w,uid:o,rid:i,own:f,iv:V(v.iv),ct:V(v.ct),k:E},x,M,ye=C.ct;i&&ye.length>Xa&&(x=B(ye),C.ct="",C.ct_ref=Za,m&&m.ctRef&&(M=m.ctRef));let ue=JSON.stringify(C).length;if(ue>2*1024*1024)throw new l(`Encrypted record data is too large: once encrypted and base64 encoded it becomes ${ue} 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 i&&n.dek.set(i,{bytes:_,key:b,recipients:E,anch:w,uid:o,rid:i,own:f,access_group:"private"}),{send:C,plain:e,encrypted:true,omit:false,spill:x,retireCt:M,dek:{bytes:_,key:b,recipients:E,anch:w,uid:o,rid:i,own:f,access_group:"private"},files:h?"encrypt":void 0}}function Wn(e,t){let r=L.call(this);!r||!t||!e||r.dek.has(e)||r.dek.set(e,Object.assign({},t,{rid:e}));}async function rl(e,t,r,n,s,i,o,a){let u=Object.keys(r).filter(p=>p!==s);if(!u.length)return r;let c=await Cr.call(this,u),f={[s]:r[s]};for(let p of u){let d=c[p];d&&(f[p]=await Qn.call(this,t,d,n,o,s,p,a));}return f}async function Qn(e,t,r,n,s,i,o){let a=Kn(r,n,s,i,t.fpr),u=nt(o,i,t.fpr),c=await kn(t.pubRaw,e,a,u);return {t:"ecdh",epk:V(c.epk),iv:V(c.iv),ct:V(c.ct),fpr:t.fpr}}async function zn(e,t){if(!Nt(e))return {value:e};if(t.access_group!=="private")return {value:e};let r=L.call(this);if(!r)return {value:null,flag:{status:"failed",reason:"ENCRYPTION_DISABLED"}};if(r.rawRead)return {value:e};if(Bn(r,t.table_name))return {value:e};if(e[it]!==qn)return {value:ie(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:ie(r.cfg,"BINDING_MISMATCH"),flag:{status:"failed",reason:"BINDING_MISMATCH"}};if(e.uid&&t.unique_id&&e.uid!==t.unique_id)return {value:ie(r.cfg,"BINDING_MISMATCH"),flag:{status:"failed",reason:"BINDING_MISMATCH"}};if(e.rid&&t.record_id&&e.rid!==t.record_id)return {value:ie(r.cfg,"BINDING_MISMATCH"),flag:{status:"failed",reason:"BINDING_MISMATCH"}};let n=this.user?.user_id,s=n?e.k[n]:null;if(!s)return {value:ie(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:ie(r.cfg,"NO_SESSION_KEY"),flag:{status:"failed",reason:"NO_SESSION_KEY"}};let i=Me.call(this),o=Rr(e),a=Er(i,e.own,e.anch,o),u;try{if(s.t==="mk")u=await pe(r.mk,B(s.iv),B(s.ct),nt(a,n,"mk"));else if(s.t==="ecdh"){if(!r.ikPriv)return {value:ie(r.cfg,"NO_SESSION_KEY"),flag:{status:"failed",reason:"NO_SESSION_KEY"}};u=await Pn(r.ikPriv,B(s.epk),B(s.iv),B(s.ct),Kn(i,o,e.own,n,s.fpr),nt(a,n,s.fpr));}else return {value:ie(r.cfg,"UNSUPPORTED_VERSION"),flag:{status:"failed",reason:"UNSUPPORTED_VERSION"}}}catch{return {value:ie(r.cfg,"BAD_KEY"),flag:{status:"failed",reason:"BAD_KEY"}}}let c;try{if(e.ct_ref){if(!t.ctUrl)return q(u),{value:ie(r.cfg,"DATA_UNAVAILABLE"),flag:{status:"failed",reason:"DATA_UNAVAILABLE"}};let g=await tl.call(this,t.ctUrl);c=new Uint8Array(await g.arrayBuffer());}else c=B(e.ct);}catch{return q(u),{value:ie(r.cfg,"DATA_UNAVAILABLE"),flag:{status:"failed",reason:"DATA_UNAVAILABLE"}}}let f,p;try{p=await fe(u),f=await pe(p,B(e.iv),c,a);}catch{return q(u),{value:ie(r.cfg,"CORRUPT"),flag:{status:"failed",reason:"CORRUPT"}}}let d;try{d=JSON.parse(Xe(f));}catch{return q(f),q(u),{value:ie(r.cfg,"CORRUPT"),flag:{status:"failed",reason:"CORRUPT"}}}if(q(f),t.record_id){let g=r.dek.get(t.record_id);g?(g.bytes=u,g.key=p,g.recipients=e.k,g.anch=e.anch,g.uid=e.uid,g.own=e.own,g.access_group="private",g.ctRef=e.ct_ref||""):r.dek.set(t.record_id,{bytes:u,key:p,recipients:e.k,anch:e.anch,uid:e.uid,rid:t.record_id,own:e.own,access_group:"private",ctRef:e.ct_ref||""});}else q(u);return {value:d,flag:{status:"encrypted",recipients:Object.keys(e.k)}}}function st(e,t){let[r,n]=e.split("/");return W(`${ee}|kek|${r}|${n}|${t}`)}function ot(e,t,r,n){let[s,i]=e.split("/");return W(`${ee}|mk|${s}|${i}|${t}|PBKDF2-SHA256|${r}|${n}`)}function Jn(e,t){let[r,n]=e.split("/");return W(`${ee}|recovery|${r}|${n}|${t}`)}function Yn(e,t,r){let[n,s]=e.split("/");return W(`${ee}|rk|${n}|${s}|${t}|HKDF-SHA256|${r}`)}function Xn(e,t){let[r,n]=e.split("/");return W(`${ee}|self|${r}|${n}|${t}`)}function Zn(e,t){let[r,n]=e.split("/");return W(`${ee}|ik|${r}|${n}|${t}`)}async function Dt(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,s)=>n.uploaded-s.uploaded),r[0]):null}async function kr(e,t,r){let n=te(et),s=vn(n),i=te(16),o=V(i),a=await mr(n,i,Jn(e,t)),u=await ae(a,r,Yn(e,t,o));return q(n),{code:s,wrap:{id:V(te(6)),p:"recovery",kdf:{a:"HKDF-SHA256",s:o},iv:V(u.iv),ct:V(u.ct),created:Date.now()}}}async function nl(e,t,r,n){let s=Nn(n),i=(r||[]).filter(o=>o.p==="recovery");i.sort((o,a)=>(a.created||0)-(o.created||0));for(let o of i)try{let a=await mr(s,B(o.kdf.s),Jn(e,t)),u=await pe(a,B(o.iv),B(o.ct),Yn(e,t,o.kdf.s));return q(s),u}catch{}return q(s),null}async function il(e,t,r,n,s){let i=te(16),o=V(i),a=await Le(n,i,e.cfg.iterations,st(t,r)),u=await ae(a,s,ot(t,r,e.cfg.iterations,o));return {id:V(te(6)),p:"password",kdf:{a:"PBKDF2-SHA256",it:e.cfg.iterations,s:o},iv:V(u.iv),ct:V(u.ct),created:Date.now()}}async function sl(e,t){let r=this.user.user_id,n=e.scope,s=te(16),i=V(s),o=await Le(t,s,e.cfg.iterations,st(n,r)),a=te(32),u=await ae(o,a,ot(n,r,e.cfg.iterations,i)),c=await fe(a),f=await Tn(),p=await ae(c,f.pkcs8,Zn(n,r));q(f.pkcs8);let d=null;e.cfg.recovery==="code"&&(d=await kr(n,r,a));let g=await ae(c,a,Xn(n,r));q(a);let h=await gr(f.pubRaw),m=Date.now(),_=[{id:V(te(6)),p:"password",kdf:{a:"PBKDF2-SHA256",it:e.cfg.iterations,s:i},iv:V(u.iv),ct:V(u.ct),created:m}];d&&_.push(d.wrap);let b={v:1,alg:"ECDH-P-256",user_id:r,wraps:_,ik:{iv:V(p.iv),ct:V(p.ct)},self:{iv:V(g.iv),ct:V(g.ct)},pub:V(f.pubRaw),fpr:h,pins:null,created:m,updated:m};await this.postRecord({v:1,alg:"ECDH-P-256",user_id:r,pub:V(f.pubRaw),fpr:h,created:m},{table:{name:e.cfg.table,access_group:"authorized"},index:{name:"pubkey",value:r}});let E=await this.postRecord(b,{table:{name:e.cfg.table,access_group:"private"}}),w=await Dt.call(this,e);if(w&&w.record_id!==E.record_id){await ei.call(this,e,w,t);return}e.mk=c,e.ikPriv=f.priv,e.pubRaw=f.pubRaw,e.fpr=h,e.keyringRecordId=E.record_id,d&&(e.pendingRecoveryCode=d.code),e.user_id=r,e.pins={},e.status="unlocked",e.reason="";}async function ei(e,t,r){let n=this.user.user_id,s=e.scope,i=t.data;if(t.user_id!==n||i&&i.user_id&&i.user_id!==n)throw new l("The encryption keyring does not belong to this user.",{code:"ENCRYPTION_KEYRING_CORRUPT"});let a=(Array.isArray(i?.wraps)?i.wraps:[]).filter(f=>f.p==="password");if(!a.length)throw new l("The keyring has no password wrap.",{code:"ENCRYPTION_KEYRING_CORRUPT"});a.sort((f,p)=>(p.created||0)-(f.created||0));let u=null;for(let f of a)try{let p=B(f.kdf.s),d=await Le(r,p,f.kdf.it,st(s,n));u=await pe(d,B(f.iv),B(f.ct),ot(s,n,f.kdf.it,f.kdf.s));break}catch{}if(!u)throw new l("Incorrect password: the encryption keyring could not be opened.",{code:"ENCRYPTION_BAD_PASSWORD"});let c=await fe(u);q(u),await Pr.call(this,e,t,c);}async function Pr(e,t,r){let n=this.user.user_id,s=t.data,i=await pe(r,B(s.ik.iv),B(s.ik.ct),Zn(e.scope,n)),o=await pr(i);q(i);let a={};if(s.pins&&typeof s.pins=="object"&&s.pins.ct)try{let u=await pe(r,B(s.pins.iv),B(s.pins.ct),W(`${ee}|pins|${e.scope}|${n}`));a=JSON.parse(Xe(u)),q(u);}catch{a={};}e.mk=r,e.ikPriv=o,e.pubRaw=B(s.pub),e.fpr=s.fpr,e.keyringRecordId=t.record_id,e.user_id=n,e.pins=a,e.status="unlocked",e.reason="";}async function Ct(e){let t=L.call(this);if(!t||!this.user?.user_id)return;if(!fr()){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=Me.call(this);let r=await Dt.call(this,t);r?await ei.call(this,t,r,e):await sl.call(this,t,e),t.cfg.persistDevice&&await si.call(this,t).catch(()=>{});}async function ti(e){await this.__connection;let t=L.call(this);if(!t)throw new l("Encryption is not enabled for this instance.",{code:"INVALID_REQUEST"});if(!this.user?.user_id)throw new l("User login is required.",{code:"INVALID_REQUEST"});if(!e?.password||typeof e.password!="string")throw new l('"password" is required.',{code:"INVALID_PARAMETER"});if(await Ct.call(this,e.password),t.status!=="unlocked")throw new l(`Encryption could not be unlocked: ${t.reason}`,{code:"ENCRYPTION_LOCKED"});return {status:t.status}}async function ri(e){this.__projectIdInput&&await this.__projectIdInput;let t=L.call(this);return t?(e?.forgetDevice&&await Dr.call(this,t).catch(()=>{}),wr.call(this),this.__cached_requests={},{status:t.status}):{status:"disabled"}}async function ni(e,t){let r=L.call(this);if(!r)return;if(r.status!=="unlocked"||!r.mk)throw new l("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 s=(await this.getRecords({record_id:r.keyringRecordId},{limit:1}))?.list?.[0];if(!s)throw new l("The encryption keyring could not be read, so the password change was stopped before it could strand it.",{code:"ENCRYPTION_KEYRING_CORRUPT"});let i=this.user.user_id,o=s.data,a=(o.wraps||[]).filter(m=>m.p==="password");a.sort((m,_)=>(_.created||0)-(m.created||0));let u=null;for(let m of a)try{let _=await Le(e,B(m.kdf.s),m.kdf.it,st(r.scope,i));u=await pe(_,B(m.iv),B(m.ct),ot(r.scope,i,m.kdf.it,m.kdf.s));break}catch{}if(!u)throw new l("Incorrect current password: the encryption keyring was not re-wrapped.",{code:"ENCRYPTION_BAD_PASSWORD"});let c=te(16),f=V(c),p=await Le(t,c,r.cfg.iterations,st(r.scope,i)),d=await ae(p,u,ot(r.scope,i,r.cfg.iterations,f));q(u);let g=Date.now(),h=(o.wraps||[]).concat([{id:V(te(6)),p:"password",kdf:{a:"PBKDF2-SHA256",it:r.cfg.iterations,s:f},iv:V(d.iv),ct:V(d.ct),created:g}]);await this.postRecord(Object.assign({},o,{wraps:h,updated:g}),{record_id:r.keyringRecordId});}async function ii(){let e=L.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,s=(n.wraps||[]).filter(o=>o.p==="password").sort((o,a)=>(a.created||0)-(o.created||0)),i=(n.wraps||[]).filter(o=>o.p!=="password");s.length<=1||await this.postRecord(Object.assign({},n,{wraps:[s[0]].concat(i),updated:Date.now()}),{record_id:e.keyringRecordId});}function Sr(){return typeof indexedDB<"u"&&!!indexedDB}function vr(){return new Promise((e,t)=>{let r=indexedDB.open(Ya,1);r.onupgradeneeded=()=>{let n=r.result;n.objectStoreNames.contains(ke)||n.createObjectStore(ke);},r.onsuccess=()=>e(r.result),r.onerror=()=>t(r.error);})}function Nr(e){return `${e.scope}#${this.user?.user_id}`}async function si(e){if(!Sr()||!e.mk)return;let t=await vr();await new Promise((r,n)=>{let s=t.transaction(ke,"readwrite");s.objectStore(ke).put({mk:e.mk,keyringRecordId:e.keyringRecordId,saved:Date.now()},Nr.call(this,e)),s.oncomplete=()=>r(),s.onerror=()=>n(s.error);}),t.close();}async function ol(e){if(!Sr())return null;let t=await vr(),r=await new Promise((n,s)=>{let o=t.transaction(ke,"readonly").objectStore(ke).get(Nr.call(this,e));o.onsuccess=()=>n(o.result||null),o.onerror=()=>s(o.error);});return t.close(),r&&r.mk?r:null}async function Dr(e){if(!Sr())return;let t=await vr();await new Promise((r,n)=>{let s=t.transaction(ke,"readwrite");s.objectStore(ke).delete(Nr.call(this,e)),s.oncomplete=()=>r(),s.onerror=()=>n(s.error);}),t.close();}function oi(){let e=L.call(this);!e||e.ready||(e.unlocking=true,e.ready=al.bind(this)().catch(()=>false).then(()=>{e.unlocking=false;}));}async function al(){let e=L.call(this);if(!e||!this.user?.user_id||!e.cfg.persistDevice||!fr())return false;e.scope=Me.call(this);try{let t=await ol.call(this,e);if(!t)return !1;let r=await Dt.call(this,e);return r?(await Pr.call(this,e,r,t.mk),!0):(await Dr.call(this,e).catch(()=>{}),!1)}catch{return e.status="locked",e.reason="NO_SESSION_KEY",false}}async function Cr(e){let t=L.call(this);if(!t)throw new l("Encryption is not enabled for this instance.",{code:"INVALID_REQUEST"});let r={},n=[],s=false;for(let i of e){let o=t.peerPub.get(i);o?r[i]=o:n.push(i);}return await Promise.all(n.map(async i=>{let o=t.peerInflight.get(i);o||(o=(async()=>{let c=((await this.getRecords({table:{name:t.cfg.table,access_group:"authorized"},index:{name:"$user_id",value:i,condition:"="}},{limit:10}))?.list||[]).filter(g=>g.user_id===i&&g.data?.pub);if(!c.length)return null;c.sort((g,h)=>h.uploaded-g.uploaded);let f=B(c[0].data.pub),p=await gr(f),d=t.pins[i];if(d&&d!==p)throw new l(`The public key for user "${i}" 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 l(`No pinned key for user "${i}" and trustPolicy is "strict". Pin it first with pinPeerKey().`,{code:"ENCRYPTION_PEER_NOT_PINNED"});t.pins[i]=p,s=true;}return {pubRaw:f,fpr:p}})().finally(()=>t.peerInflight.delete(i)),t.peerInflight.set(i,o));let a=await o;a&&t.peerPub.set(i,a),r[i]=a;})),s&&await ui.call(this,t).catch(()=>{}),r}async function ai(e,t){let r=Me.call(this),n=e.dek.get(t);if(n)return {entry:n,scope:r};let s=await Ie.call(this,t);if(!s)throw new l(`Record "${t}" not found.`,{code:"NOT_EXISTS"});if(s.encrypted?.status==="failed"&&s.encrypted.reason==="DATA_UNAVAILABLE")throw new l(`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(!s.encrypted)return null;if(s.user_id!==this.user?.user_id)throw new l("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 i=e.dek.get(s.record_id)||e.dek.get(t);if(!i)throw new l(`Cannot change sharing on record "${t}": its data could not be decrypted`+(s.encrypted.reason?` (${s.encrypted.reason})`:"")+".",{code:"ENCRYPTION_LOCKED"});return {entry:i,scope:r}}async function xr(e,t){let r=L.call(this);if(!r)return;let n=await ai.call(this,r,e);if(!n)return;let{entry:s,scope:i}=n,o=this.user.user_id;if(s.own!==o)throw new l("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 Cr.call(this,t),u=t.filter(d=>!a[d]);if(u.length)throw new l(`These users have no encryption key yet, so they cannot be given access: ${u.join(", ")}. A user's key is created the first time they log in with encryption enabled.`,{code:"ENCRYPTION_RECIPIENT_HAS_NO_KEY"});let c=Rr(s),f=Er(i,s.own,s.anch,c),p=Object.assign({},s.recipients);for(let d of t)d!==o&&(p[d]=await Qn.call(this,s.bytes,a[d],i,c,s.own,d,f));await cl.call(this,r,e,s,p);}async function li(e,t){let r=L.call(this);if(!r)return;let n=await ai.call(this,r,e);if(!n)return;let{entry:s}=n,i=this.user.user_id;if(s.own!==i)throw new l("Only the record owner can revoke access to an encrypted record.",{code:"ENCRYPTION_GRANT_REQUIRES_OWNER"});let o=Object.keys(s.recipients).filter(c=>c===i?true:t?!t.includes(c):false).filter(c=>c!==i),a=await Ie.call(this,e);if(!a)throw new l(`Record "${e}" not found.`,{code:"NOT_EXISTS"});ll(a,e);let u={};if(o.length){u=await Cr.call(this,o);let c=o.filter(f=>!u[f]);if(c.length)throw new l(`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: ${c.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 xr.call(this,a.record_id||e,o);}function ll(e,t){if(e?.encrypted?.status==="failed")throw new l(`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 cl(e,t,r,n){let s=await ul.call(this,t);if(!s)throw new l(`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 i=Object.assign({},s,{k:n});e.passthrough.set(t,i),await this.postRecord(void 0,{record_id:t});}async function ul(e){let t=L.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&&Nt(r.data)?r.data:null}async function ci(e){this.__projectIdInput&&await this.__projectIdInput;let t=L.call(this);if(!t||t.status!=="unlocked")throw new l("Encryption is locked.",{code:"ENCRYPTION_LOCKED"});t.pins[e.user_id]=e.fingerprint,t.peerPub.delete(e.user_id),await ui.call(this,t);}async function ui(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 ae(e.mk,W(JSON.stringify(e.pins)),W(`${ee}|pins|${e.scope}|${e.user_id}`));await this.postRecord(Object.assign({},r.data,{pins:{iv:V(n.iv),ct:V(n.ct)},updated:Date.now()}),{record_id:e.keyringRecordId});}function di(){let e=L.call(this);if(!e||!e.pendingRecoveryCode)return null;let t=e.pendingRecoveryCode;return e.pendingRecoveryCode="",t}async function fi(e){await this.__connection;let t=L.call(this);if(!t)throw new l("Encryption is not enabled for this instance.",{code:"INVALID_REQUEST"});if(!this.user?.user_id)throw new l("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 l('"code" is required.',{code:"INVALID_PARAMETER"});t.scope=Me.call(this);let r=this.user.user_id,n=await Dt.call(this,t);if(!n)throw new l("This account has no encryption keyring, so there is nothing to recover.",{code:"NOT_EXISTS"});let s=await nl(t.scope,r,n.data?.wraps||[],e.code);if(!s)throw new l("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 i=await fe(s);await Pr.call(this,t,n,i);let o=false,a=null,u=(n.data?.wraps||[]).slice();if(e.password&&(u=u.filter(c=>c.p!=="password"),u.push(await il(t,t.scope,r,e.password,s)),o=true),t.cfg.recovery==="code"){let c=await kr(t.scope,r,s);u=u.filter(f=>f.p!=="recovery"),u.push(c.wrap),a=c.code;}return q(s),await this.postRecord(Object.assign({},n.data,{wraps:u,updated:Date.now()}),{record_id:n.record_id}),t.cfg.persistDevice&&await si.call(this,t).catch(()=>{}),{status:t.status,repaired:o,recoveryCode:a}}async function pi(){await this.__connection;let e=L.call(this);if(!e)throw new l("Encryption is not enabled for this instance.",{code:"INVALID_REQUEST"});if(e.status!=="unlocked"||!e.mk)throw new l("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 l('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 l("The encryption keyring could not be read.",{code:"ENCRYPTION_KEYRING_CORRUPT"});let n=r.data?.self;if(!n||!n.ct)throw new l("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 s=await pe(e.mk,B(n.iv),B(n.ct),Xn(e.scope,e.user_id)),i=await kr(e.scope,e.user_id,s);q(s);let o=(r.data.wraps||[]).filter(a=>a.p!=="recovery").concat([i.wrap]);return await this.postRecord(Object.assign({},r.data,{wraps:o,updated:Date.now()}),{record_id:e.keyringRecordId}),{recoveryCode:i.code}}var vt="__skenc__",gi="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";function dl(e){if(e===0)return "0";let t="";for(;e>0;)t=gi[e%62]+t,e=Math.floor(e/62);return t}function fl(e){let t=0;for(let r of e){let n=gi.indexOf(r);if(n<0)return NaN;t=t*62+n;}return t}function xt(e){if(typeof e!="string")return null;let t=e.lastIndexOf(vt);if(t<0)return null;let r=fl(e.slice(t+vt.length));return Number.isFinite(r)?{key:e.slice(0,t),plainSize:r}:null}function Ur(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=xt(t[10]);return r?{recordId:t[5],recordOwner:t[3],filename:t[t.length-1],plainSize:r.plainSize}:null}catch{return null}}function hi(e,t){return {service:this.service,owner:this.owner,recordOwner:t,recordId:e}}async function mi(e,t,r){let n=L.call(this);if(!n||!e)return {key:t,file:r,encrypted:false};let s=n.dek.get(e);if(!s)return {key:t,file:r,encrypted:false};if(xt(t))throw new l(`"${vt}" is reserved in an upload form key.`,{code:"INVALID_PARAMETER"});if(t===at)return {key:t,file:r,encrypted:false};let i=new Uint8Array(await r.arrayBuffer()),o={n:r.name,t:r.type||"",lm:r.lastModified||0},a=await Ln(s.bytes,i,hi.call(this,e,s.own),o);return q(i),{key:`${t}${vt}${dl(r.size)}`,file:new File([a],r.name,{type:"application/octet-stream"}),encrypted:true}}async function yi(e,t){let r=L.call(this),n=Ur(e);if(!r||!n)return t;let s=r.dek.get(n.recordId);if(!s)throw new l(`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 i=new Uint8Array(await t.arrayBuffer());if(!yr(i))throw new l("This file is marked as encrypted but its contents are not an encrypted container.",{code:"ENCRYPTION_FILE_CORRUPT"});let o=await Mn(s.bytes,i,hi.call(this,n.recordId,n.recordOwner)),a=o.meta&&o.meta.t||"application/octet-stream";return new Blob([o.bytes],{type:a})}function pl(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 gl(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 Or(e,t,r){let n=L.call(this);if(!n)return [];let s=await Ie.call(this,e);if(!s)return [];let i=t==="decrypt"?pl(s):gl(s);if(!i.length)return [];let o=[],a=new FormData,u=false;for(let c of i){let f=s.bin[c.formKey].find(d=>d.url===c.url);if(!f||typeof f.getFile!="function")continue;let p=await f.getFile("blob");p&&(a.append(c.formKey,new File([p],c.filename,{type:p.type||"application/octet-stream"})),o.push(c.url),u=true);}if(!u)return [];if(t==="decrypt"){let c=n.dek.get(e);c&&(q(c.bytes),n.dek.delete(e));}return await this.uploadFiles(a,{record_id:e,progress:r}),o}var H=null;function lt(e){let t={tkid:"ticket_id",cond:"condition",stmp:"timestamp",upd:"updated",acts:"actions",actn:"action",cnt:"count",ttl:"time_to_live",plch:"placeholder",hash:"hash",desc:"description",pmc:"limit_per_user",fail:"failed",rv:"rules_version",on:"enabled"},r={};for(let n in e)if(n==="tkid"){let s=e[n].split("#");if(s.length===1){r.ticket_id=s[0];continue}r.ticket_id=s[1],r.consume_id=s[2],r.user_id=s.slice(3).join("#");let i=s[2].slice(-4);if(r.is_test=i===":CHK",!e.stmp){let o=s[2].slice(0,-4);/^[0-9]+$/.test(o)?r.timestamp=parseInt(o,10):r.timestamp=de(s[2].slice(0,-4));}}else t[n]?r[t[n]]=e[n]:r[n]=e[n];return r}async function _i(e){if(!e?.ticket_id)throw new l("Ticket ID is required.",{code:"INVALID_PARAMETER"});if(!/^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$/.test(e.ticket_id))throw new l('Invalid "ticket_id". Use letters, digits, "_" and "-" (up to 64 chars, starting with a letter or digit).',{code:"INVALID_PARAMETER"});if(!e.method)throw new l('Method is required. Should be either "GET" or "POST"',{code:"INVALID_PARAMETER"});let t=String(e.method).toUpperCase();if(t!=="GET"&&t!=="POST")throw new l('Method should be either "GET" or "POST".',{code:"INVALID_PARAMETER"});let r=!!e.auth;if(r&&t==="GET")throw new l("Signed-in consumption is POST only.",{code:"INVALID_PARAMETER"});await this.__connection;let n=r?"tpa":t==="GET"?"tg":"tp",s=`https://${this.service.slice(0,4)}.${this.customApiDomain}/${n}/${this.service}/${e.ticket_id}`,i=await k.bind(this)(s,e.data||{},{method:t,auth:r},{ignoreService:true});if(i&&typeof i=="object"&&i.stage)throw new l(i.message,{code:i.code,cause:i});return !i||typeof i!="object"||Array.isArray(i)||typeof i.tkid!="string"?i:lt(i)}async function wi(e,t){await this.__connection;let r=await k.bind(this)("ticket",Object.assign({exec:"list"},e||{}),{auth:true,fetchOptions:t});return r.list=r.list.map(lt),r}async function Ei(e){if(!e?.ticket_id)throw new l("Ticket ID is required.",{code:"INVALID_PARAMETER"});let t=e.before===void 0||e.before===null?Date.now():e.before;if(typeof t!="number"||!Number.isInteger(t)||t<=0)throw new l('"before" should be a time in milliseconds since the epoch.',{code:"INVALID_PARAMETER"});return k.bind(this)("register-ticket",{exec:"clearlog",ticket_id:e.ticket_id,before:t},{auth:true})}async function Ri(e,t){await this.__connection;let r=await k.bind(this)("ticket",Object.assign({exec:"consumed"},e||{}),{auth:true,fetchOptions:t});return r.list=r.list.map(lt),r}async function Ai(e){let t=await k.bind(this)("register-ticket",Object.assign({exec:"reg"},e),{auth:true});return t&&typeof t=="object"&&t.ticket&&(t.ticket=lt(t.ticket)),t}async function Ti(e){return k.bind(this)("register-ticket",Object.assign({exec:"unreg"},e),{auth:true})}async function Ii(e){if(!e?.ticket_id)throw new l('"ticket_id" is required.',{code:"INVALID_PARAMETER"});if(typeof e.enabled!="boolean")throw new l('"enabled" should be true or false.',{code:"INVALID_PARAMETER"});let t=await k.bind(this)("register-ticket",{exec:"update",ticket_id:e.ticket_id,enabled:e.enabled},{auth:true});return t?.ticket&&(t.ticket=lt(t.ticket)),t}var wl=3600;async function qe(){if(await this.__connection,this.session){let e=Math.floor(Date.now()/1e3),r=this.session.getIdToken().getExpiration();if(r<e+wl){this.log("request:requesting new token",null);try{await J.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 l("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),Re.bind(this)(),new l("User login is required.",{code:"INVALID_REQUEST"})}function bi(e,t){return new Promise((r,n)=>{t.refreshSession(e.getRefreshToken(),(s,i)=>{this.log("getSession:refreshSessionCallback",{refreshErr:s,refreshedSession:i}),s?(Re.bind(this)(),n(s)):i.isValid()?r(i):(Re.bind(this)(),n(new l("Invalid session.",{code:"INVALID_REQUEST"})));});})}function J(){if(!this.userPool)throw new l("User pool is missing",{code:"INVALID_REQUEST"});let e=()=>{let i=H.getSignInUserSession().getIdToken().payload||null,o=Ye(i);return this.log("normalized user attribute",o),this.__user=o,o},t=async i=>new Promise((o,a)=>{this.log("getSession:option",i);let{refreshToken:u=false,skipUserUpdateEventTrigger:c=false}=i||{};if(u&&c&&(c=false),H=this.userPool.getCurrentUser(),!H){this.log("getSession:cognitoUser",H),Re.bind(this)(),a(null);return}let f=p=>{let d=p.getIdToken().payload;if(this.log("getSession:respond:sessionAttribute",d),d["custom:service"]!==this.service)throw this.log("getSession:respond","invalid service, signing out"),Re.bind(this)(),new l("Invalid session.",{code:"INVALID_REQUEST"});return this.session=p,e(),c||this._runOnUserUpdateListeners(this.user),this.session};H.getSession((p,d)=>{if(this.log("getSession:getSessionCallback",{err:p,session:d}),!d){Re.bind(this)(),a(new l("Current session does not exist.",{code:"INVALID_REQUEST"}));return}if(p){bi.bind(this)(d,H).then(b=>o(f(b))).catch(a);return}let g=Math.floor(Date.now()/1e3),h=d.getIdToken(),m=h.getExpiration(),_=m<g;if(this.log("getSession:currentTime",g),this.log("getSession:idTokenExp",m),this.log("getSession:isExpired",_),this.log("getSession:existingBearerToken",this.bearerToken),this.bearerToken=h.getJwtToken(),_||u||!d.isValid())bi.bind(this)(d,H).then(b=>o(f(b))).catch(a);else try{o(f(d));}catch(b){a(b);}});}),r=(i,o)=>{let a=o||i.includes(this.service+"-")?i:this.service+"-"+ne.hash(i);return {cognitoUser:new amazonCognitoIdentityJs.CognitoUser({Username:a,Pool:this.userPool}),cognitoUsername:a}};return {getSession:t,authenticateUser:(i,o,a=false,u=false)=>new Promise((c,f)=>{this.__request_signup_confirmation=null,this.__disabledAccount=null;let p=r(i,a),d=p.cognitoUsername,g=new amazonCognitoIdentityJs.AuthenticationDetails({Username:d,Password:o});p.cognitoUser.authenticateUser(g,{newPasswordRequired:(h,m)=>{this.__disabledAccount=null,this.__request_signup_confirmation=d,h["custom:signup_ticket"]==="PASS"||h["custom:signup_ticket"]==="MEMBER"||h["custom:signup_ticket"]==="OIDPASS"?p.cognitoUser.completeNewPasswordChallenge(o,{},{onSuccess:_=>{H=p.cognitoUser,t().then(async b=>{if(L.call(this))try{await Ct.bind(this)(o);}catch(E){this.log("encryption:ensureKeyring:failed",E);}c(this.user);});},onFailure:_=>{f(new l(_.message||"Failed to authenticate user.",{code:_.code}));}}):f(new l("User's signup confirmation is required.",{code:"SIGNUP_CONFIRMATION_NEEDED"}));},onSuccess:h=>t({skipUserUpdateEventTrigger:true}).then(async m=>{if(this.__disabledAccount=null,L.call(this))try{await Ct.bind(this)(o);}catch(_){this.log("encryption:ensureKeyring:failed",_);}this._runOnLoginListeners(this.user),this._runOnUserUpdateListeners(this.user),c(this.user);}),onFailure:h=>{let m=[],{parsed:_,code:b}=Ot(h),E=typeof h?.message=="string"?h.message:"";if(b==="NotAuthorizedException"?E.includes("User is disabled.")?(this.__disabledAccount=d,m=["This account is disabled.","USER_IS_DISABLED"]):u?m=["The account already exists.","ACCOUNT_EXISTS"]:m=["Incorrect username or password.","INCORRECT_USERNAME_OR_PASSWORD"]:b==="UserNotFoundException"?m=["Incorrect username or password.","INCORRECT_USERNAME_OR_PASSWORD"]:b==="UserNotConfirmedException"?(this.__request_signup_confirmation=d,m=["User's signup confirmation is required.","SIGNUP_CONFIRMATION_NEEDED"]):(b==="TooManyRequestsException"||b==="LimitExceededException")&&(m=["Too many attempts. Please try again later.","REQUEST_EXCEED"]),_.code==="SIGNUP_CONFIRMATION_NEEDED"&&(this.__request_signup_confirmation=d),m.length){let w=m[1],I=m[0];f(new l(I,{code:w,cause:h}));}else f(_);}});}),createCognitoUser:r,signup:(i,o,a)=>new Promise((u,c)=>{this.userPool.signUp(i,o,a,null,(f,p)=>{if(f){let{parsed:d,code:g}=Ot(f),h=[];g==="UsernameExistsException"?h=["The account already exists.","EXISTS"]:g==="InvalidPasswordException"?h=["Invalid password. Password must be at least 6 characters.","INVALID_PARAMETER"]:g==="InvalidParameterException"?h=[d.message||"Invalid parameter.","INVALID_PARAMETER"]:g==="TooManyRequestsException"||g==="LimitExceededException"?h=["Too many attempts. Please try again later.","REQUEST_EXCEED"]:g==="CodeDeliveryFailureException"?h=["Failed to deliver verification code.","CODE_DELIVERY_FAILURE"]:g==="UserLambdaValidationException"&&(h=[d.message||"Signup validation failed.",d.code==="EXISTS"?"EXISTS":"INVALID_REQUEST"]),h.length?c(new l(h[0],{code:h[1],cause:f})):c(d);return}u(p);});})}}function Ot(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 s=n.match(/#([A-Za-z0-9_]+)\s*:\s*([\s\S]+)/),i=s?.[1]?.trim()||t,o=s?.[2]?.trim()||n;return {parsed:new l(o,{code:i,cause:e}),code:t}}async function ki(e){await this.__authConnection;let t=e?.refreshToken||false;if(!t)return this.user;try{return await J.bind(this)().getSession(Object.assign({skipUserUpdateEventTrigger:!t,refreshToken:t},e)),this.user}catch{return null}}async function Pi(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 a of o)if(typeof a!="string")throw new l('"merge" array items should be type: <string>.',{code:"INVALID_PARAMETER"})}if(typeof o!="boolean"&&!Array.isArray(o))throw new l('"merge" should be type: <boolean | string[]>.',{code:"INVALID_PARAMETER"});return o},template:o=>{if(typeof o!="object"||o===null)throw new l('"template" should be type: <object>.',{code:"INVALID_PARAMETER"});if(o.welcome!==void 0&&(typeof o.welcome!="string"||!o.welcome))throw new l('"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 k.bind(this)("openid-logger",t),n=r.logger.split("#"),s=this.service+"-"+n[0],i=n[1];return {userProfile:await J.bind(this)().authenticateUser(s,i,true,true),openid:r.openid}}function El(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 s=0;s<r.length;s++)n[s]=r.charCodeAt(s);return typeof TextDecoder<"u"?new TextDecoder().decode(n):r}throw new Error("No base64 decoder available in this environment")}function Rl(e){let t=e.split(".");if(t.length!==3)throw new Error("Invalid JWT format");let n=t[1].replace(/-/g,"+").replace(/_/g,"/"),s=El(n);return JSON.parse(s)}async function Si(e){await this.__authConnection,this.log("loginWithToken:params",e),e=y.Params(e,{idToken:"string",accessToken:"string",refreshToken:"string"},["idToken"]);let t=Rl(e.idToken);if(this.log("loginWithToken:idTokenPayload",t),t["custom:service"]!==this.service)throw new l("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 l("Token has expired.",{code:"INVALID_REQUEST"});if(this.__user=Ye(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),H=new amazonCognitoIdentityJs.CognitoUser(n),H.setSignInUserSession(this.session),this.log("loginWithToken:cognitoUserRestored",{cognitoUserType:typeof H,cognitoUserKeys:Object.keys(H||{}),cognitoUser:H});}}catch(n){this.log("loginWithToken:err",n);try{this.log("loginWithToken:err:stringified",JSON.stringify(n));}catch{this.log("loginWithToken:err:stringifyFail",String(n));}try{let s=Object.keys(n||{}),i=Object.getOwnPropertySymbols?Object.getOwnPropertySymbols(n||{}):[],o=Object.getOwnPropertyDescriptors?Object.getOwnPropertyDescriptors(n||{}):{};this.log("loginWithToken:createSessionError:allKeys",{keys:s,symbols:i,descriptors:o});}catch(s){this.log("loginWithToken:createSessionError:allKeysFail",String(s));}}return this._runOnLoginListeners(this.user),this._runOnUserUpdateListeners(this.user),this.user}async function Y(){return await this.__connection,this.__user?.service===this.service?this.__user?.owner===this.host:(await ct.bind(this)(),false)}async function Re(e=false){let t=null;H&&(e?t=new Promise((n,s)=>{H.globalSignOut({onSuccess:i=>{this.log("globalSignOut:success",i),n(i);},onFailure:i=>{this.log("globalSignOut:error",i),s(i);}});}):H.signOut()),wr.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 ct(e){await this.__connection;let{data:t}=$(e);return await Re.bind(this)(t?.global),"SUCCESS: The user has been logged out."}async function vi(){if(!this.__request_signup_confirmation)throw new l("Least one login attempt is required.",{code:"INVALID_REQUEST"});return await k.bind(this)("confirm-signup",{username:this.__request_signup_confirmation})}async function Ni(e=false){if(typeof e=="string")e=y.Url(e);else if(typeof e!="boolean")throw new l("Argument should be type: <boolean | string>.",{code:"INVALID_REQUEST"});if(!this.__disabledAccount)throw new l("Least one signin attempt of disabled account is required.",{code:"INVALID_REQUEST"});return await k.bind(this)("recover-account",{username:this.__disabledAccount,redirect:e}),"SUCCESS: Recovery e-mail has been sent."}async function Lr(e){let t=y.Params(e,{username:"string",email:"string",password:"string"},["password"]);await this.__authConnection;let r=null;if(t.email)try{r=y.Email(t.email);}catch{t.username=t.email,delete t.email;}if(!t.username&&!t.email)throw new l('Least one of "username" or "email" is required.',{code:"INVALID_PARAMETER"});let n=t.username||t.email;try{return await J.bind(this)().authenticateUser(n,t.password)}catch(s){if((s?.code==="UserNotFoundException"||s?.code==="NotAuthorizedException")&&r&&r!==n)return await J.bind(this)().authenticateUser(r,t.password);throw s}}async function Di(e,t){await this.__authConnection;let r={username:"string",password:c=>y.Password(c),email:c=>y.Email(c),name:"string",address:c=>{if(!c)return "";if(typeof c=="string")return c;if(typeof c=="object")return JSON.stringify(c)},gender:"string",birthdate:c=>c?y.Birthdate(c):"",phone_number:c=>c?y.PhoneNumber(c):"",email_public:["boolean",()=>false],address_public:["boolean",()=>false],gender_public:["boolean",()=>false],birthdate_public:["boolean",()=>false],phone_number_public:["boolean",()=>false],access_group:"number",misc:"string",picture:c=>c?y.Url(c):"",profile:c=>c?y.Url(c):"",family_name:"string",given_name:"string",middle_name:"string",nickname:"string",website:c=>c?y.Url(c):""},n=y.Params(e||{},r,["email","password"]);await ct.bind(this)(),t=y.Params(t||{},{email_subscription:c=>{let f=c;if(typeof c=="number"||typeof c=="string"&&c!=="public"&&c!=="authorized"){let p=y.newsletterGroup(c);if(typeof p=="number"&&p!==0&&p!==1)throw new l('"option.email_subscription" takes 0 (public), 1 (authorized), true, false or the name of a newsletter group.',{code:"INVALID_PARAMETER"});f=p;}else if(typeof c!="boolean"&&typeof c!="string")throw new l('"option.email_subscription" takes 0 (public), 1 (authorized), true, false or the name of a newsletter group.',{code:"INVALID_PARAMETER"});if(f!==false&&!t?.signup_confirmation)throw new l('"option.signup_confirmation" is required for email subscription.',{code:"INVALID_PARAMETER"});return f},signup_confirmation:c=>{let f=c;if(typeof c=="string")f=y.Url(c);else if(typeof c=="boolean")f=c;else throw new l('"option.signup_confirmation" should be type: <string | boolean>.',{code:"INVALID_PARAMETER"});if(f&&!n.email)throw new l('"email" is required for signup confirmation.',{code:"INVALID_PARAMETER"});return f},login:c=>{if(typeof c=="boolean"){if(t.signup_confirmation&&c)throw new l('"login" is not allowed when "option.signup_confirmation" is true.',{code:"INVALID_PARAMETER"});return c}throw new l('"option.login" should be type: boolean.',{code:"INVALID_PARAMETER"})},template:c=>{if(typeof c!="object"||c===null)throw new l('"option.template" should be type: <object>.',{code:"INVALID_PARAMETER"});if(c.signup_confirmation!==void 0){if(typeof c.signup_confirmation!="string"||!c.signup_confirmation)throw new l('"option.template.signup_confirmation" should be a non-empty <string> (template message_id).',{code:"INVALID_PARAMETER"});if(!t?.signup_confirmation)throw new l('"option.signup_confirmation" is required when "option.template.signup_confirmation" is set.',{code:"INVALID_PARAMETER"})}if(c.welcome!==void 0&&(typeof c.welcome!="string"||!c.welcome))throw new l('"option.template.welcome" should be a non-empty <string> (template message_id).',{code:"INVALID_PARAMETER"});return c}});let s=t?.login||false;if(n.signup_confirmation=t?.signup_confirmation||false,n.email_subscription=t?.email_subscription===void 0||t?.email_subscription===null?false:t.email_subscription,n.email_public&&!n.signup_confirmation)throw new l('"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 i=J.bind(this)().createCognitoUser(n.username||n.email);for(let c of ["email_public","address_public","gender_public","birthdate_public","phone_number_public"])n[c]=n[c]?"1":"0";n.access_group&&(n.access_group=n.access_group.toString());let o=(await k.bind(this)("signupkey",{username:i.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(":"),u=[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 c in r){let f=["email_public","address_public","gender_public","birthdate_public","phone_number_public","misc","service","owner"];n[c]!==""&&(c==="username"||c==="password"||c==="access_group"||(f.includes(c)?u.push(new amazonCognitoIdentityJs.CognitoUserAttribute({Name:"custom:"+c,Value:n[c]})):u.push(new amazonCognitoIdentityJs.CognitoUserAttribute({Name:c,Value:n[c]}))));}return await J.bind(this)().signup(i.cognitoUsername,n.password,u),n.signup_confirmation?(H=i.cognitoUser,this.__request_signup_confirmation=i.cognitoUsername,"SUCCESS: The account has been created. User's signup confirmation is required."):s?Lr.bind(this)({email:n.username||n.email,password:n.password}):"SUCCESS: The account has been created."}async function Ci(){await this.__connection;let e=await k.bind(this)("remove-account",{disable:this.__user.user_id},{auth:true});return await ct.bind(this)(),e}async function xi(e){await this.__connection;let t=y.Params(e,{email:s=>y.Email(s),code:["number","string"],new_password:s=>y.Password(s)},["email","code","new_password"]),r=t.code,n=t.new_password;return typeof r=="number"&&(r=r.toString()),new Promise(async(s,i)=>{J.bind(this)().createCognitoUser(t.email).cognitoUser.confirmPassword(r,n,{onSuccess:a=>{s("SUCCESS: New password has been set.");},onFailure:a=>{i(new l(a?.message||"Failed to reset password.",{code:a?.code||"ERROR",cause:a}));}});})}async function Ui(e,t,r){await this.__connection;let n;if(!H)throw new l("The user has to be logged in.",{code:"INVALID_REQUEST"});if(e==="email"||e==="phone_number"){if(!this.__user.hasOwnProperty(e))throw new l(`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 s,i=r?.template?.verification;if(i!==void 0){if(typeof i!="string"||!i)throw new l('"template.verification" should be a non-empty <string> (template message_id).',{code:"INVALID_PARAMETER"});s={template_verification:i};}return new Promise((o,a)=>{let u={onSuccess:c=>{n?J.bind(this)().getSession({refreshToken:true}).then(()=>{this.__user&&(this.__user[e+"_verified"]=true),o(`SUCCESS: "${e}" is verified.`);}).catch(f=>{a(f);}):o("SUCCESS: Verification code has been sent.");},onFailure:c=>{a(new l(c.message||"Failed to request verification code.",{code:c?.code}));}};n?H?.verifyAttribute(e,n,u):(u.inputVerificationCode=null,H?.getAttributeVerificationCode(e,u,s));})}function Oi(e,t){return Ui.bind(this)("phone_number",e,t)}function Li(e,t){return Ui.bind(this)("email",e,t)}async function Mi(e,t){await this.__connection;let r=y.Params(e,{email:s=>y.Email(s)},["email"]),n;if(t?.template!==void 0){if(typeof t.template!="object"||t.template===null||Array.isArray(t.template))throw new l('"template" should be type: <object>.',{code:"INVALID_PARAMETER"});if(t.template.verification!==void 0)throw new l('"template.verification" is not an option of forgotPassword(). Use "template.forgot_password" (template message_id).',{code:"INVALID_PARAMETER"});let s=t.template.forgot_password;if(s!==void 0){if(typeof s!="string"||!s)throw new l('"template.forgot_password" should be a non-empty <string> (template message_id).',{code:"INVALID_PARAMETER"});n={template_forgot_password:s};}}return new Promise(async(s,i)=>{J.bind(this)().createCognitoUser(r.email).cognitoUser.forgotPassword({onSuccess:a=>{s("SUCCESS: Verification code has been sent.");},onFailure:a=>{let{parsed:u,code:c}=Ot(a),f={UserNotFoundException:"NOT_EXISTS",InvalidParameterException:"INVALID_PARAMETER",NotAuthorizedException:"INVALID_REQUEST",LimitExceededException:"REQUEST_EXCEED",TooManyRequestsException:"REQUEST_EXCEED",CodeDeliveryFailureException:"CODE_DELIVERY_FAILURE"}[c]||u.code||c||"ERROR";i(new l(u.message,{code:f,cause:a}));}},n);})}async function Fi(e){if(await this.__connection,!this.session)throw new l("User login is required.",{code:"INVALID_REQUEST"});let t=y.Params(e,{current_password:"string",new_password:"string"});if(!t?.current_password)throw new l('"current_password" is required to change password.',{code:"INVALID_PARAMETER"});if(!t?.new_password)throw new l('"new_password" is required to change password.',{code:"INVALID_PARAMETER"});return y.Password(t.current_password),y.Password(t.new_password),L.call(this)&&await ni.bind(this)(t.current_password,t.new_password),new Promise((r,n)=>{H.changePassword(t.current_password,t.new_password,(s,i)=>{if(s){if(s?.code==="InvalidParameterException")n(new l("Invalid password parameter.",{code:"INVALID_PARAMETER"}));else if(s?.code==="NotAuthorizedException")n(new l("Incorrect password.",{code:"INVALID_REQUEST"}));else if(s?.code==="TooManyRequestsException"||s?.code==="LimitExceededException")n(new l("Too many attempts. Please try again later.",{code:"REQUEST_EXCEED"}));else {let{parsed:o}=Ot(s);n(o);}return}L.call(this)&&ii.bind(this)().catch(o=>this.log("encryption:prune:failed",o)),r("SUCCESS: Password has been changed.");});})}async function qi(e){if(await this.__connection,!this.session)throw new l("User login is required.",{code:"INVALID_REQUEST"});let t=y.Params(e||{},{user_id:s=>y.UserId(s),email:s=>y.Email(s),address:s=>{if(!s)return "";if(typeof s=="string")return s;if(typeof s=="object")return JSON.stringify(s)},name:"string",gender:"string",birthdate:s=>s?y.Birthdate(s):"",phone_number:s=>s?y.PhoneNumber(s):"",email_public:"boolean",phone_number_public:"boolean",address_public:"boolean",gender_public:"boolean",birthdate_public:"boolean",misc:"string",picture:s=>s?y.Url(s):"",profile:s=>s?y.Url(s):"",family_name:"string",given_name:"string",middle_name:"string",nickname:"string",website:s=>s?y.Url(s):""});if(t&&typeof t=="object"&&!Object.keys(t).length)return this.user;let r=[["email_public","email_verified","User's e-mail should be verified to set"],["phone_number_public","phone_number_verified","User's phone number should be verified to set"]];if(this.__user){for(let s of r)if(t[s[0]]&&!this.__user[s[1]])throw new l(`${s[2]} "${s[0]}" to true.`,{code:"INVALID_REQUEST"})}let n=[];for(let s in t){if(t[s]===this.user[s]){n.push(s);continue}if(["email_public","phone_number_public","address_public","gender_public","birthdate_public","misc"].includes(s)){let o=t[s];typeof o=="boolean"&&(o=o?"1":"0"),t["custom:"+s]=o,n.push(s);}}for(let s of n)delete t[s];if(t.user_id)if(t.user_id===this.user.user_id)delete t.user_id;else return k.bind(this)("admin-edit-profile",{attributes:t},{auth:true});if(t&&typeof t=="object"&&Object.keys(t).length){let s=[];for(let i in t)s.push(new amazonCognitoIdentityJs.CognitoUserAttribute({Name:i,Value:t[i]}));return await new Promise((i,o)=>{H?.updateAttributes(s,(a,u)=>{a&&o([a?.code||a?.name,a?.message||"Failed to update user settings."]),i(u);});}),await J.bind(this)().getSession({refreshToken:true}),this.user}return this.user}async function Vi(e,t){e=$(e).data,e||(e={searchFor:"timestamp",condition:">",value:0},t||(t={}),t.ascending=false),await this.__connection;let r={user_id:i=>y.UserId(i),email:"string",phone_number:"string",locale:i=>{if(typeof i!="string"||typeof i=="string"&&i.length>5)throw new l('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"],s=(i,o)=>{let a=r[e.searchFor];if(typeof a=="function")return a(i);if(typeof i!==a)throw new l(`${o} does not match the type of "${e.searchFor}" index.`,{code:"INVALID_PARAMETER"});return i};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=>Array.isArray(i)?i.map(o=>s(o,"Value")):s(i,"Value"),range:i=>s(i,"Range")},n),e?.condition&&e?.condition!=="="&&e.hasOwnProperty("range"))throw new l("Conditions does not apply on range search.",{code:"INVALID_PARAMETER"});if(Array.isArray(e.value)&&(e.condition!=="="||e.range))throw new l(`Conditions are not allowed on a list of "${e.searchFor}" values. Search for a single value to use a condition or range.`,{code:"INVALID_PARAMETER"});if(typeof e?.value=="string"&&!e?.value)throw new l("Value should not be an empty string.",{code:"INVALID_PARAMETER"});if(typeof e?.searchFor=="string"&&!e?.searchFor)throw new l('"searchFor" should not be an empty string.',{code:"INVALID_PARAMETER"});return k.bind(this)("get-users",e,{auth:true,fetchOptions:t})}async function ji(e){await this.__connection;let t=await k.bind(this)("last-verified-email",e,{auth:true});return t.includes("SUCCESS")?(await J.bind(this)().getSession({refreshToken:true}),this.user):t}var Ve=null,Ki=typeof SubmitEvent<"u",Tl=typeof HTMLFormElement<"u",dt=Q(),Mr=0;function Hi(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())}var qr=6,$i=6e4;function Gi(e,t){let r=e>0?e:Math.min($i,500*Math.pow(2,t));r=Math.min($i,r);let n=Math.floor(Math.random()*Math.min(1e3,Math.max(50,r*.25)));return r+n}function Wi(e){return new l(`Too many requests: ${e} still answered 429 after ${qr} retries.`,{code:"TOO_MANY_REQUESTS"})}function Fr(e,t){return t>0?e/t*100:0}var Bi=e=>{let{auth:t,type:r,endpoints:n,stable:s}=e,i=n[0],o=n[1];if(Mr++,r==="admin"){let a=Object.entries(i).filter(([u,c])=>u.includes(t?"_private":"_public")&&u!=="get_users_private"&&u!=="service_public"&&typeof c=="string").map(([,u])=>u);if(!a.length)throw new l("No available admin gateways.",{code:"INVALID_REQUEST"});return a[Mr%a.length]}if(r==="record"){let a=Object.entries(o).filter(([u,c])=>u.includes(t?"record_private":"record_public")&&typeof c=="string").map(([,u])=>u);if(!a.length)throw new l("No available record gateways.",{code:"INVALID_REQUEST"});return s?a[0]:a[Mr%a.length]}throw new l("Invalid gateway type.",{code:"INVALID_REQUEST"})};async function Il(e,t,r){let n=await Promise.all([this.admin_endpoint,this.record_endpoint]),s=n[0],i=n[1],o=e.split("?"),a=o.length>1?"?"+o[1]:"";switch(e=o[0],e){case "get-users":return s.get_users_private+e+a;case "service":return s.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 "send-inquiry":case "register-newsletter-group":case "delete-newsletter-group":case "newsletter-group-endpoint":case "invitation-list":case "csr":case "csr-poll":case "csr-cancel":case "csr-finalize":return Bi.bind(this)({auth:t,type:"admin",endpoints:n})+e+a;case "post-record":return (t?i.post_private:i.post_public)+e+a;case "get-records":return (t?i.get_private:i.get_public)+e+a;case "del-files":case "del-records":return i.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 "get-signed-urls":case "extract-file-text":case "grid-query":case "grant-private-access":case "request-private-access-key":case "get-ws-group":case "check-schema":case "get-feed":case "castspell":case "dopamine":case "getspell":return Bi.bind(this)({auth:t,type:"record",endpoints:n,stable:r})+e+a;default:return y.Url(e)+a}}var ut={};function Qi(){Ve&&(Ve.terminate(),Ve=null);}async function k(e,t=null,r,n){this.log("request",{url:e,data:t,options:r,_etc:n||{}}),r=r||{};let{auth:s=false,method:i="post",bypassAwaitConnection:o=false}=r;i=i.toUpperCase();let a=null,u=null,c=await Il.bind(this)(e,!!s,!!r.stableGateway),f=t?.service||this.service,p=t?.owner||this.owner;if(!o&&(a=await this.__connection,!a))throw new l("Invalid connection. The service could have been disabled, or has a restricted CORS.",{code:"INVALID_REQUEST"});let d=r?.tokenHeaders?.idToken===true;(s||d)&&(u=await qe.bind(this)());let g={},{fetchMore:h=false,progress:m}=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;g[v]=r.fetchOptions[v];}g=y.Params(g,{limit:v=>{if(typeof v!="number")throw new l("Fetch limit should be a number.",{code:"INVALID_REQUEST"});if(v>1e3)throw new l("Fetch limit should be below 1000.",{code:"INVALID_REQUEST"});return v},startKey:v=>v,ascending:"boolean"});}let _=n?.ignoreService?{}:{service:f,owner:p};Object.assign(_,g),t=$(t).data,t?t&&typeof t=="object"&&(t=Object.assign(_,t)):t=_;let b=`${i}:${s?"auth":"public"}:${e}`,E=(()=>{if(t&&typeof t=="object"&&Object.keys(t).length&&!(dt&&t instanceof FormData)){let v=function(C){return typeof C=="object"&&C!==null?Object.keys(C).sort().reduce((x,M)=>(typeof C[M]=="object"&&C[M]!==null?x[M]=v(C[M]):x[M]=C[M],x),{}):C};return ne.hash(b+"/"+JSON.stringify(v(t)))}return ne.hash(b+"/"+f)})(),{requestKey:w,requestKeyWithStartKey:I}=kl.bind(this)({params:t,url:e,fetchMore:h,hashedParams:E});if(!w||w&&typeof w=="object")return w;if(this.log("requestKey",I),typeof I=="string"&&ut[I]instanceof Promise)return this.log("request:returning pending",I),ut[I];let R={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&&(R["Content-Type"]=v);}else R["Content-Type"]="application/json";if(u&&(R.Authorization=u),r?.tokenHeaders){let v=(M,ye)=>typeof M=="string"?M:M===true?ye:null,C=v(r.tokenHeaders.accessToken,this.session?.accessToken?.jwtToken||null),x=v(r.tokenHeaders.idToken,this.bearerToken||this.session?.idToken?.jwtToken||u||null);C&&(R["X-Access-Token"]=C),x&&(R["X-Id-Token"]=x);}let U={public_identifier:this.__public_identifier,service:f,owner:p,resolves_offloaded_data:true};R["Content-Meta"]=JSON.stringify(U),r.revalidate&&(R["Cache-Control"]="no-cache",R.Pragma="no-cache");let D={headers:R};if(r?.responseType&&(D.responseType=r.responseType),i==="GET"){if(t){let v=[];if(dt&&t instanceof FormData?v=Array.from(t.entries()).map(([C,x])=>{let M=typeof x=="string"?x:x.name;return encodeURIComponent(C)+"="+encodeURIComponent(M)}):v=Object.keys(t).map(C=>{let x=t[C];return typeof x!="string"&&(x=JSON.stringify(x)),encodeURIComponent(C)+"="+encodeURIComponent(x)}),v.length){let C=c.includes("?")?c.endsWith("?")||c.endsWith("&")?"":"&":"?";c+=C+v.join("&");}}D.body=null;}else if(dt&&t instanceof FormData)D.body=t;else if(R["Content-Type"]==="application/x-www-form-urlencoded"&&t&&typeof t=="object"){let v=new URLSearchParams;for(let C of Object.keys(t)){let x=t[C];v.append(C,typeof x=="string"?x:JSON.stringify(x));}D.body=v.toString();}else typeof t=="string"?D.body=t:D.body=t?JSON.stringify(t):null;if(D.method=i,Ve===null){let v={batchSize:this.requestBatchSize,breakWhenError:false,onProgress:C=>{this.onBatchProcess.forEach(x=>x(C));}};Ve=new oo__default.default(v);}return this.log("request-opt",D),new Promise((v,C)=>{Ve.add([async()=>{let x=zi.bind(this)(c,D,m);ut[I]=x;try{let M=Sl.bind(this)({hashedParam:w,requestKeyWithStartKey:I,url:e,fetched:await x});return delete ut[I],this.log("request:end",M),v(M),M}catch(M){throw delete ut[I],this.log("request:err",M),C(M),M}}]);})}function kl(e){let{params:t={},url:r,fetchMore:n=false,hashedParams:s}=e||{};if(t.startKey){if(!(typeof t.startKey=="object"&&Object.keys(t.startKey).length)&&t.startKey!=="start"&&t.startKey!=="end")throw new l(`"${t.startKey}" is invalid startKey key.`,{code:"INVALID_PARAMETER"});t.startKey==="start"&&(n=false,delete t.startKey);}if(!n){if(this.__cached_requests?.[r]?.[s]&&delete this.__cached_requests[r][s],this.__startKeyHistory?.[r]?.[s]){if(Array.isArray(this.__startKeyHistory[r][s])&&this.__startKeyHistory[r][s].length)for(let u of this.__startKeyHistory[r][s]){let c=s+ne.hash(u);this.__cached_requests?.[r]&&this.__cached_requests?.[r]?.[c]&&delete this.__cached_requests[r][c];}delete this.__startKeyHistory[r][s];}return {requestKeyWithStartKey:s,requestKey:s}}if(!Array.isArray(this.__startKeyHistory?.[r]?.[s]))return {requestKeyWithStartKey:s,requestKey:s};let i=this.__startKeyHistory[r][s],o=i[i.length-1],a=s;if(o){if(o==="end")return {requestKey:{list:[],startKey:"end",endOfList:true,startKeyHistory:i},requestKeyWithStartKey:a};a+=ne.hash(o),t.startKey=JSON.parse(o);}return this.__cached_requests?.[r]?.[a]?{requestKey:this.__cached_requests[r][a],requestKeyWithStartKey:a}:{requestKeyWithStartKey:a,requestKey:s}}function Pl(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 zi(e,t,r,n=0){return new Promise((s,i)=>{let o=new XMLHttpRequest;o.open(t.method||"GET",e);for(var a in t.headers||{})o.setRequestHeader(a,t.headers[a]);t.responseType&&(o.responseType=t.responseType),o.onload=()=>{if(o.status<400)if(t.responseType=="json"||t.responseType=="blob")s(o.response);else {let u=o.responseText;try{u=JSON.parse(u);}catch{}s(u);}else if(o.status===429){let u=o.getResponseHeader("Retry-After"),c=Hi(u);if(c!==null){if(n>=qr){i(Wi(`"${e.split("?")[0]}"`));return}setTimeout(()=>{zi(e,t,r,n+1).then(s,i);},Gi(c,n));}else i("Too many requests");}else {let u=o.status,c=["INVALID_CORS","INVALID_REQUEST","SERVICE_DISABLED","INVALID_PARAMETER","ERROR","EXISTS","NOT_EXISTS"],f=t.responseType=="blob"?o.response:o.responseText;try{f=JSON.parse(f);}catch{}if(typeof f=="string"){let p=f.split(":"),d=p.splice(0,1)[0].trim(),g=p.join(":").trim();i(new l(g||f,{code:c.includes(d)?d:"ERROR"}));}else if(typeof f=="object"&&(f?.message||f?.stage||f?.code)){let p=f?.code||(u?u.toString():null)||"ERROR",d=f.message,g=f?.cause;g===void 0&&f.stage&&(g=f),typeof d=="string"&&(d=d.trim()),d||(d=String(p)),i(new l(d,{cause:g,code:p}));}else i(f);}},o.onerror=()=>i("Network error"),o.onabort=()=>i("Aborted"),o.ontimeout=()=>i("Timeout"),typeof r=="function"&&(o.onprogress=u=>{r({status:"download",progress:Fr(u.loaded,u.total),loaded:u.loaded,total:u.total,abort:()=>o.abort()});},o.upload&&(o.upload.onprogress=u=>{r({status:"upload",progress:Fr(u.loaded,u.total),loaded:u.loaded,total:u.total,abort:()=>o.abort()});})),o.send(t.body);})}function Sl(e){let{hashedParam:t,requestKeyWithStartKey:r,url:n,fetched:s}=e;if(!s?.startKey)return s;this.__startKeyHistory.hasOwnProperty(n)||(this.__startKeyHistory[n]={}),this.__startKeyHistory[n].hasOwnProperty(t)||(this.__startKeyHistory[n][t]=[]);let i=s.startKey==="end"?"end":JSON.stringify(s.startKey);return this.__startKeyHistory[n][t].includes(i)||this.__startKeyHistory[n][t].push(i),this.__cached_requests?.[n]||(this.__cached_requests[n]={}),this.__cached_requests[n][r]=s,Object.assign({startKeyHistory:this.__startKeyHistory[n][t]},s)}function vl(e){if(e instanceof l)return e;if(typeof e=="string"){let t=e.trim();if(t==="Network error")return new l("Network error",{code:"NETWORK_ERROR"});if(t==="Aborted")return new l("Aborted",{code:"ABORTED"});if(t==="Timeout")return new l("Timeout",{code:"TIMEOUT"});if(t==="Too many requests")return new l("Too many requests",{code:"TOO_MANY_REQUESTS"});let r=/<Code>([^<]+)<\/Code>/.exec(t)?.[1]?.trim()||"",n=/<Message>([^<]+)<\/Message>/.exec(t)?.[1]?.trim()||"";return r||n?new l(n||r,{code:r||"UPLOAD_FAILED",cause:t}):new l(t.length>300?t.slice(0,300):t||"Upload failed.",{code:"UPLOAD_FAILED",cause:t})}if(e&&typeof e=="object"){let t=e.code||e.Code,r=e.message||e.Message;if(t||r)return new l(String(r||t),{code:String(t||"UPLOAD_FAILED"),cause:e})}return new l("Upload failed.",{code:"UPLOAD_FAILED",cause:e})}var Nl=5,Dl=100;function Cl(e){let t=String(e?.code??"");if(t==="404"||t==="501")return true;let r=String(e?.message??e??"");return /missing authentication token/i.test(r)||/not implemented/i.test(r)||t==="403"&&/not found/i.test(r)}function xl(e,t){let r=Array.isArray(e?.list)?e.list:[],n=Array.isArray(e?.failed)?e.failed:[],s=new Array(t);for(let i of n)i&&Number.isInteger(i.index)&&i.index>=0&&i.index<t&&(s[i.index]=new l(String(i.message||"Upload permit refused."),{code:String(i.code||"ERROR")}));for(let i=0;i<t;i++){if(s[i])continue;let o=r[i];o&&typeof o.url=="string"?s[i]={fields:o.fields||null,url:o.url,cdn:o.cdn}:s[i]=new l("No upload permit was answered for this file.",{code:"ERROR"});}return s}async function ft(e,t){await this.__connection;let{record_id:r,service:n=this.service,progress:s,timeout:i,throwOnFileError:o=false}=t;if(!r)throw new l('"record_id" is required.',{code:"INVALID_PARAMETER"});if(i!=null){if(typeof i!="number"||!Number.isFinite(i)||i<0)throw new l('"timeout" should be a number of milliseconds, 0 or more.',{code:"INVALID_PARAMETER"})}else i=0;if(Ki&&e instanceof SubmitEvent&&(e=e.target),Tl&&e instanceof HTMLFormElement&&(e=new FormData(e)),!dt||!(e instanceof FormData))throw new l('"fileList" should be a FormData or HTMLFormElement.',{code:"INVALID_PARAMETER"});let u={reserved_key:Se(),service:n,request:"post"};t?.record_id&&(u.id=t.record_id);let c,f=(w,I,R,N,U=0)=>new Promise((D,v)=>{c=new XMLHttpRequest,c.open("POST",w),i>0&&(c.timeout=i),c.onload=()=>{let C=c.responseText;try{C=JSON.parse(C);}catch{}if(c.status>=200&&c.status<300)D(C);else if(c.status===429){let x=c.getResponseHeader("Retry-After"),M=Hi(x);if(M!==null){if(U>=qr){v(Wi(`the upload of "${N}" to "${w}"`));return}setTimeout(()=>{f(w,I,R,N,U+1).then(D,v);},Gi(M,U));}else v("Too many requests");}else v(C);},c.onerror=()=>v("Network error"),c.onabort=()=>v("Aborted"),c.ontimeout=()=>v(new l(`Upload timeout: "${N}" was not finished within ${i} ms.`,{code:"TIMEOUT"})),c.upload&&typeof R=="function"&&(c.upload.onprogress=R),c.send(I);});function p(w){let I="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";if(w===0)return I[0];let R="";for(;w>0;)R=I[w%62]+R,w=Math.floor(w/62);return R}let d=[],g=[],h=[],m=[],_=[];for(let[w,I]of e.entries())I instanceof File&&_.push([w,I]);let b=_.length>=Nl&&!this.__bulkPermitsUnavailable,E=0;for(;E<_.length;){let w=_.slice(E,E+(b?Dl:1));E+=w.length;let I=[];for(let[N,U]of w){let D=await mi.bind(this)(r,N,U);I.push({file:U,uploadFile:D.file,params:{key:D.key+"/"+D.file.name,sizeKey:p(D.file.size),contentType:D.file.type||null}});}let R=null;if(b)try{let N=await k.bind(this)("get-signed-urls",Object.assign({files:I.map(U=>U.params)},u),{auth:!!this.__user});R=xl(N,I.length);}catch(N){if(!Cl(N))throw N;this.__bulkPermitsUnavailable=true,b=false;}if(!R){R=[];for(let N of I){let{fields:U=null,url:D,cdn:v}=await k.bind(this)("get-signed-url",Object.assign(N.params,u),{auth:!!this.__user});R.push({fields:U,url:D,cdn:v});}}for(let N=0;N<I.length;N++){let{file:U,uploadFile:D}=I[N],v=R[N];if(v instanceof l){if(m.push(""),g.push(U),h.push({file:U,name:U.name,error:v}),o)throw v;continue}m.push(v.cdn);let C=new FormData;for(let x in v.fields||{})C.append(x,v.fields[x]);C.append("file",D);try{await f(v.url,C,typeof s=="function"?x=>s({status:"upload",progress:Fr(x.loaded,x.total),currentFile:U,completed:d,failed:g,loaded:x.loaded,total:x.total,abort:()=>c.abort()}):null,U.name),d.push(U);}catch(x){g.push(U);let M=vl(x);if(h.push({file:U,name:U.name,error:M}),o)throw M}}}return {completed:d,failed:g,errors:h,bin_endpoints:m}}var Lt={};function S(e){let{preventMultipleCalls:t=false}=e||{};return function(r,n,s){let i=s.value;s.value=function(...o){let a=o[0],u=true,c=null,f="",p={},d=false;if(Ki&&a instanceof SubmitEvent){a.preventDefault();let b=window.location.href;c=a.target;let E=new URL(c.action);f=E.href;let w=f?f.match(/(?<=\{).*?(?=\})/g):"";if(w)for(let I of w){if(!I)continue;let R=c.querySelector(`[name="${I}"]`);if(R)if(R.type==="file")for(let N=0;N<=R.files.length-1;N++)R.files[N]&&(p[I]||(p[I]=[]),p[I].push(new Promise((U,D)=>{let v=new FileReader;v.onload=function(){U(v.result);},v.readAsDataURL(R.files[N]),v.onerror=D;})));else f=f.replace(`{${I}}`,R.value);}c.getAttribute("action")===null?u=false:d=E.href===b;}let g=async b=>{if(f)for(let E in p)p[E].length&&(f=f.replace(`{${E}}`,(await Promise.all(p[E])).join(",")));if(c&&u){let E=L.call(this)?Pl(b):b;window.sessionStorage.setItem(`${this.service}:${ne.hash(f)}`,JSON.stringify(E)),d?window.location.replace(f):window.location.href=f;}return b},h,m=b=>{throw b instanceof l?b.name=n+"()":b=b instanceof Error?b:new l(b,{name:n+"()"}),b},_=async()=>{try{if(this.__projectIdInput&&await this.__projectIdInput,h=i.bind(this)(...o),h instanceof Promise){let b=await h;return g(b)}return g(h)}catch(b){throw m(b)}};if(t){let b=`${n}:${this?.__public_identifier||""}:${this?.service||""}:${this?.owner||""}`;return Lt?.[b]||(Lt[b]=_().finally(()=>{delete Lt[b];})),Lt[b]}return _()};}}async function Ji(){await this.__connection;let e=`${this.service}:${ne.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 Ul=256,Ol=256,Ll=256,Yi=256,Ml="\u{10FFFF}",Fl=/[\u0000-\u001F\u007F]|\u{10FFFF}/u,ql={"/":"%2F","!":"%21","*":"%2A","#":"%23"},Vl={"%2F":"/","%21":"!","%2A":"*","%23":"#"};function jl(e){return e.replace(/%/g,"%25").replace(/[\/!*#]/g,r=>ql[r]||r)}function ge(e){return typeof e!="string"?e:e.replace(/%(2F|21|2A|23)/gi,r=>{let n=r.toUpperCase();return Vl[n]||r}).replace(/%25/gi,"%")}function be(e,t,r={}){let{allowEmpty:n=false,maxLength:s,blockKeyDelimiters:i=false,disallowLeadingDollar:o=false,onlyAlphanumeric:a=false}=r;if(typeof e!="string")throw new l(`"${t}" should be type: <string>.`,{code:"INVALID_PARAMETER"});if(a&&/[^a-zA-Z0-9]/.test(e))throw new l(`"${t}" should only contain alphanumeric characters.`,{code:"INVALID_PARAMETER"});if(!n&&e.length===0)throw new l(`"${t}" is required.`,{code:"INVALID_PARAMETER"});if(s&&e.length>s)throw new l(`"${t}" should be <= ${s} characters.`,{code:"INVALID_PARAMETER"});if(Fl.test(e)||e.includes(Ml))throw new l(`"${t}" cannot include control characters or unsupported sentinel characters.`,{code:"INVALID_PARAMETER"});if(i&&(e=jl(e),s&&e.length>s))throw new l(`"${t}" should be <= ${s} characters. "/", "!", "*", "#" and "%" count as 3 characters each.`,{code:"INVALID_PARAMETER"});if(o&&e.startsWith("$"))throw new l(`"${t}" cannot start with "$".`,{code:"INVALID_PARAMETER"});return e}function je(e,t="table.name",r={}){return be(e,t,{allowEmpty:r.allowEmpty===true,maxLength:Ul,blockKeyDelimiters:true})}function Ft(e,t="tag",r={}){return be(e,t,{allowEmpty:r.allowEmpty===true,maxLength:Ol,blockKeyDelimiters:true})}function pt(e,t="index.name",r={}){return be(e,t,{allowEmpty:r.allowEmpty===true,maxLength:Ll,blockKeyDelimiters:true,disallowLeadingDollar:true})}function Xi(e,t="index.value"){return be(e,t,{allowEmpty:true,maxLength:Yi})}function Vr(e){return typeof e=="string"&&e.slice(-1)==="."}function jr(e,t){return be(e,t,{allowEmpty:true,maxLength:Yi,blockKeyDelimiters:true})}function Zi(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=be(e.record_id,"record_id",{allowEmpty:false,onlyAlphanumeric:true}):e?.unique_id&&(t.unique_id=e.unique_id),t}function $r(e){if(e===void 0)return 0;if(typeof e=="number"){if(e>99||e<0)throw new l('"table.access_group" value should be within a range of 0 ~ 99.',{code:"INVALID_REQUEST"})}else if(typeof e=="string"){if(e={"*":"private",private:"private",public:0,authorized:1,admin:99}[e],e===void 0)throw new l('"table.access_group" is invalid.',{code:"INVALID_PARAMETER"})}else throw new l('"table.access_group" should be type: <number | string>.',{code:"INVALID_PARAMETER"});if(!this.__user&&e)throw new l("Unsigned users have no access to records with access group.",{code:"INVALID_REQUEST"});return e}var Mt=4503599627370496;function qt(e){if(typeof e=="number"){if(e>Mt||e<-Mt)throw new l(`Number value should be within range -${Mt} ~ +${Mt}`,{code:"INVALID_PARAMETER"});return e}if(typeof e=="boolean")return e;if(typeof e=="string")return Xi(e,"index.value");throw new l('"index.value" should be type: <number | boolean | string>.',{code:"INVALID_PARAMETER"})}function es(e,t){if(!t.index||!("value"in t.index))throw new l('"index.value" is required.',{code:"INVALID_PARAMETER"});if(t.index.name==="$record_id")throw new l(`Cannot do "index.range" on ${t.index.name}`,{code:"INVALID_PARAMETER"});if(typeof t.index.value!=typeof e)throw new l('"index.range" type should match the type of "index.value".',{code:"INVALID_PARAMETER"});return typeof e=="string"?Vr(t.index.name)?jr(e,"index.range"):Xi(e,"index.range"):e}var Vt={},$l=10080*60,Bl=3600,ts=2;function Kl(e,t){if(!t)return String(ts);let r=Math.max(60,e-300)*1e3;return "g"+ts+"w"+Math.floor(Date.now()/r)}function Hl(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 Gl(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 jt(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);}})}function Kr(e){return !!e&&typeof e=="object"&&!Array.isArray(e)&&typeof e.__data__=="string"&&Object.keys(e).length===1&&e.__data__.endsWith("/__data__/__json__.json")}var $e=new Map,Wl=1024,Ql=/^[0-9A-Za-z]+\/[0-9A-Za-z]+\/__data__\/__json__\.json$/,ns=/^[0-9A-Za-z_-]+$/,zl=/^(\d{2}|\*\*)$/;function is(e){if(typeof e!="string")return null;let t=e.split("?")[0].split("/");if(t.length<15||t[0]!=="https:"||t[1]!==""||!t[2])return null;let r=t.slice(3);return r[0]!=="publ"&&r[0]!=="auth"||r[4]!=="records"||r[7]!=="bin"||!ns.test(r[1])?null:{origin:t.slice(0,3).join("/"),service:r[1]}}function Jl(e){let t=is(e);!t||$e.get(t.service)===t.origin||($e.size>=Wl&&!$e.has(t.service)&&$e.clear(),$e.set(t.service,t.origin));}function rs(e,t){if(typeof t!="string"||!Ql.test(t))return null;let r=typeof e.usr_tbl=="string"?e.usr_tbl.split("/"):null,n=typeof e.tbl=="string"?e.tbl.split("/"):null,s=null,i=null;if(typeof e.srvc=="string"){let f=e.srvc.split("!")[0].split("/");f.length===2&&(s=f[0],i=f[1]);}s||(s=r?.[2]||n?.[1]||null,s&&s===this.service&&(i=this.owner));let o=typeof e.usr=="string"&&e.usr?e.usr:r?.[0]||null,a=r?.[3]||n?.[2]||null,u=e.rec;for(let f of [s,i,o,u])if(typeof f!="string"||!ns.test(f))return null;if(typeof a!="string"||!zl.test(a))return null;let c=null;if(Array.isArray(e.bin))for(let f of e.bin){let p=is(f);if(p&&p.service===s){c=p.origin;break}}return c=c||$e.get(s)||null,c?`${c}/${a==="00"?"publ":"auth"}/${s}/${i}/${o}/records/${u}/${a}/bin/${t}`:null}async function De(e,t,r=false,n=false,s=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:{}},o=false,a=[],u=null;function c(d){let g=d=="**"?"private":parseInt(d);return g=g==0?"public":g==1?"authorized":g==99?"admin":g,g}let f={ip:d=>{let g=d.split("#"),h=g[0];g.length>1&&(i.unique_id=g.slice(1).join("#")),h.slice(-1)==="R"?(i.readonly=true,h=h.slice(0,-1)):i.readonly=false,/^\d{1,3}-\d{1,3}-\d{1,3}-\d{1,3}$/.test(h)&&(h=h.split("-").join("."),o=true),i.ip=h;},rec:d=>{if(!d)return;i.record_id=d;let g=d.substring(0,d.length-9),h=de(g);i.uploaded=h;},usr:d=>{i.user_id=d;},tbl:d=>{if(d&&!i.table.name){let g=d.split("/");i.table.name=ge(g[0]),i.table.access_group=c(g[2]),g?.[3]&&(i.table.subscription.is_subscription_record=true);}},usr_tbl:d=>{let g=d.split("/");i.user_id||(i.user_id=g[0]),i.table.name||(i.table.name=ge(g[1]),i.table.access_group=c(g[3]),g?.[4]&&(i.table.subscription.is_subscription_record=true));},idx:d=>{if(!d)return;let g=d.split("!"),h=ge(g.splice(0,1)[0]),m=Yl("!"+g.join("!"));i.index={name:h,value:m};},ref:d=>{d&&(i.reference=d.split("/")[0]);},tags:d=>{i.tags=Array.isArray(d)?d.map(g=>ge(g)):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 g={},h=i?.reference||null;if(Array.isArray(d)){let m=await Promise.all(d.map(async _=>{try{let b=_.split("/").slice(3).join("/"),E=b.split("/");if(E.length<12)return null;let w=E[E.length-1],I=E[10];if(I==="__data__"&&w==="__json__.json")return {isDataFile:!0,rawUrl:_};if(Tr(I,w))return {isDataFile:!0,rawUrl:_};let R=xt(I),N=E[9],U=E[8],D=c(E[6]),v=_,C=D!=="public"&&Hl.call(this,E)?{expires:Bl,browserCache:$l}:null;if(D!=="public"&&!s)try{v=await Ae.bind(this)(_,{dataType:"endpoint",_ref:h});}catch(M){console.error("Error getting signed url for private file:",M),v=_;}let x={access_group:D,filename:w,url:v,path:b,size:R?R.plainSize:de(N),uploaded:de(U),getFile:(M,ye)=>{let ue={dataType:M||"download",progress:ye,_ref:h},F=()=>Ae.bind(this)(v,Object.assign({},ue,{_update:x}));return C?Ae.bind(this)(_,Object.assign({},ue,C)).catch(()=>F()):F()}};return R&&(x.encrypted=!0,x.stored_size=de(N)),{pathKey:R?R.key:I,obj:x}}catch{return null}}));for(let _ of m)if(_&&!_.isDataFile){if(g[_.pathKey]){g[_.pathKey].push(_.obj);continue}g[_.pathKey]=[_.obj];}}i.bin=g;},prv_acs:d=>{for(let g in d)["notify_subscribers","upload_to_feed","feed_referencing_records","notify_referencing_records"].includes(g)?i.table.subscription[g]=d[g]:g==="referencing_index_restrictions"&&Array.isArray(d[g])?i.source[g]=d[g].map(m=>m&&typeof m=="object"&&typeof m.name=="string"?Object.assign({},m,{name:ge(m.name)}):m):i.source[g]=d[g];},data:async d=>{let g={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,ctUrl:u},h=()=>{L.call(this)&&(i.encrypted={status:"failed",reason:"DATA_UNAVAILABLE"});},m=async b=>{if(n||!L.call(this)&&!Nt(b))return b;let E=await zn.bind(this)(b,g);return E.flag&&(i.encrypted=E.flag),E.value},_=Gl(d);if(_!==d){i.data=await m(_);return}if(Kr(d)){let b=d.__data__,E=a.find(w=>w.endsWith(b))||null;if(!E&&!r){await Promise.resolve();let w=rs.call(this,e,b),I=false,R;if(w)try{let N=await Ae.bind(this)(w,{dataType:"blob",_ref:i.reference||null});R=JSON.parse(await jt(N)),I=!0;}catch{}if(I){i.data=await m(R);return}h();}if(E){if(r){i.data=d;return}try{let w=await Ae.bind(this)(E,{dataType:"blob",_ref:i.reference||null}),I=await jt(w);i.data=await m(JSON.parse(I));}catch(w){let I=rs.call(this,e,b),R=false,N;if(I&&I!==E)try{let U=await Ae.bind(this)(I,{dataType:"blob",_ref:i.reference||null});N=JSON.parse(await jt(U)),R=!0;}catch{}if(R){i.data=await m(N);return}console.error("Failed to fetch offloaded record data:",w),i.data=null,h();}return}}i.data=await m(d);}};if(e.record_id)return e;if(Array.isArray(e.bin))for(let d of e.bin)try{if(typeof d!="string")continue;Jl(d);let g=d.split("/").slice(3);g.length>=12&&g[10]==="__data__"&&g[g.length-1]==="__json__.json"&&a.push(d),g.length>=12&&Tr(g[10],g[g.length-1])&&(u=d);}catch{}let p=[];for(let d in f)if(e.hasOwnProperty(d)){let g=f[d](e[d]);g instanceof Promise&&p.push(g);}return o&&(i.user_id="anonymous:"+i.user_id),await Promise.all(p),i}function Yl(e){let t=e.substring(3);switch(e.substring(0,3)){case "!S%":return t;case "!N%":let n=t.split("."),s=Number(n[0])-4503599627370496;return n.length===1?s:parseFloat(s.toString()+"."+n[1]);case "!B%":return t==="1";case "!L%":case "!D%":try{return JSON.parse(t)}catch{throw new l("Value parse error.",{code:"PARSE_ERROR"})}default:return e}}async function ss(e){let{endpoints:t}=e;if(typeof t=="string"&&(t=[t]),!Array.isArray(t))throw new l('"endpoints" should be type: array | string.',{code:"INVALID_PARAMETER"});let r=await k.bind(this)("del-files",{endpoints:t,storage:"records"},{auth:true,method:"post"}),n=[];for(let s in r)n.push(De.bind(this)(r[s]));return Promise.all(n)}async function Ae(e,t){if(typeof e!="string")throw new l('"url" should be type: string.',{code:"INVALID_PARAMETER"});let r=e,n=e.split("?"),s=n.shift()||"",i=n.length?"?"+n.join("?"):"",o=y.Url(s);e=o+i;let a=false,u=o.split("/"),f=u[2].split("."),p=null;f.length===3&&f[1]==="skapi"&&(p=f[0],a=true);let d=u.slice(3),g=false;if(!a&&(d[0]==="auth"||d[0]==="publ"))try{y.UserId(d[2]),y.UserId(d[3]),g=d[0]=="auth",a=!0;}catch{throw new l("Invalid file url.",{code:"INVALID_PARAMETER"})}let h=p?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:w=>w}),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:de(d[9]),uploaded:de(d[8])};let m=e.split("/").slice(-1)[0],_=t.expires;if(_){if(!a)throw new l("Expires option can only be used on skapi cdn endpoints.",{code:"INVALID_PARAMETER"});if(_<0)throw new l('"config.expires" should be > 0. (seconds)',{code:"INVALID_PARAMETER"});let w={request:p?"get-host":"get",id:p||d[5],key:r.split("?")[0],expires:_};h&&(w.service=h);let I=t.browserCache,R={auth:true};if(I){if(I<0)throw new l('"config.browserCache" should be > 0. (seconds)',{code:"INVALID_PARAMETER"});R.method="get",R.stableGateway=true,w.browser_cache=I;let N=this.session?.idToken?.payload?.sub||this.user?.user_id;N&&(w.uid=N),w.nocache=Kl(_,t.refresh);}e=(await k.bind(this)("get-signed-url",w,R)).url;}else if(g){let w=Math.floor(Date.now()/1e3);if(!this.bearerToken&&(!this.session?.idToken?.payload?.exp||this.session.idToken.payload.exp<w)){this.log("getFile:requesting new token",null);try{await J.bind(this)().getSession({refreshToken:!0}),this.log("getFile:received new tokens",{exp:this.session?.idToken?.payload?.exp,currTime:w,expiresIn:this.session?.idToken?.payload?.exp-w,token:this.session?.accessToken?.jwtToken,refreshToken:this.session?.refreshToken?.token});}catch(U){throw this.log("getFile:new token error",U),new l("User login is required.",{code:"INVALID_REQUEST"})}}let I=this.bearerToken||this.session?.idToken?.jwtToken;if(!I||!this.user?.user_id)throw new l("User login is required.",{code:"INVALID_REQUEST"});e+=`${e.includes("?")?"&":"?"}t=${encodeURIComponent(I)}`;let R=d[6]==="**"?"**":parseInt(d[6]),N=this.user?.access_group??-1;if(this.user.user_id!==d[3]&&(R==="**"||N<R)){let U=d[5];if(this.__private_access_key[U]&&typeof this.__private_access_key[U]=="string")e+=`&p=${encodeURIComponent(this.__private_access_key[U])}`;else if(this.owner!==this.host)try{let D=await this.requestPrivateRecordAccessKey({record_id:U,reference_id:t?._ref});e+=`&p=${encodeURIComponent(D)}`;}catch{}}}if((L.call(this)?Ur(e):null)&&t?.dataType!=="endpoint"&&t?.dataType!=="info"){let w=await k.bind(this)(e,null,{method:"get",contentType:null,responseType:"blob",fetchOptions:{progress:t?.progress}},{ignoreService:true}),I=await yi.bind(this)(e,w);if(t?.dataType==="blob")return I;if(t?.dataType==="text")return await jt(I);if(t?.dataType==="base64")return await new Promise((U,D)=>{let v=new FileReader;v.onloadend=()=>U(v.result),v.onerror=()=>D(v.error),v.readAsDataURL(I);});let R=URL.createObjectURL(I),N=document.createElement("a");return N.href=R,document.body.appendChild(N),N.setAttribute("download",m),N.click(),document.body.removeChild(N),setTimeout(()=>URL.revokeObjectURL(R),6e4),null}if(t?.dataType==="endpoint")return t._update&&(t._update.url=e),e;if(t?.dataType==="download"){let w=document.createElement("a");return w.href=e,document.body.appendChild(w),w.setAttribute("download",m),w.target="_blank",w.click(),document.body.removeChild(w),null}return new Promise(async(w,I)=>{try{let R=await k.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 N=new FileReader;N.onloadend=()=>w(N.result),N.readAsDataURL(R);}else w(R);}catch(R){if(t?.browserCache&&!t?.refresh)try{w(await Ae.bind(this)(r,Object.assign({},t,{refresh:!0})));return}catch(N){I(N);return}I(R);}})}function $t(e,t){return `${e||this.service}/${t||this.owner}`}function Br(e,t){let r=this.__my_unique_ids[e];return r?r[t]:void 0}function os(e,t,r){this.__my_unique_ids[e]||(this.__my_unique_ids[e]={}),this.__my_unique_ids[e][t]=r;}function Xl(e,t){this.__my_unique_ids[e]&&delete this.__my_unique_ids[e][t];}function as(e,t){return !t||t.table===void 0?e:Object.assign({},e,{table:t.table})}async function gt(e){if(await this.__connection,!this.__user&&this.connection?.opt?.require_login===true)throw new l(`This project requires users to sign in before reading its database, so "${e}" is not available to a signed-out visitor.`,{code:"REQUIRE_LOGIN"})}async function ls(e,t=false){e=$(e,{ignoreEmpty:true}).data||{};let r=$t.bind(this)(e?.service,e?.owner),n="",s=Zi(e);if(s){if(e=s,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 i=Br.bind(this)(r,n);i&&(t?Xl.bind(this)(r,n):e.record_id=i);}}else {let i=await Y.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 u=c=>({table:{name:f=>je(f,"table.name"),access_group:$r.bind(this),subscription:f=>y.UserId(f,'User ID in "subscription"')},reference:"string",index:{name:["$updated","$uploaded","$referenced_count","$user_id",f=>pt(f,"index.name")],value:f=>{let p={$updated:"number",$uploaded:"number",$referenced_count:"number",$user_id:y.UserId};if(p.hasOwnProperty(c.index.name)){let d=p[c.index.name];if(typeof d=="function")return d(f);if(d!==typeof f)throw new l(`"index.value" should be type: ${d}.`,{code:"INVALID_PARAMETER"});return f}return typeof f=="string"&&!f?"":typeof f=="string"&&Vr(c.index.name)?jr(f,"index.value"):qt(f)},condition:["gt","gte","lt","lte",">",">=","<","<=","=","eq"],range:f=>es(f,c)},tag:f=>{if(f==null)return f;if(typeof f=="string")return Ft(f,"tag");throw new l('"tag" should be type: string.',{code:"INVALID_PARAMETER"})},private_key:"string"});e=y.Params(e||{},u(e),a||i?[]:["table"],{ignoreEmpty:true});}return {query:e,is_reference_fetch:n}}async function cs(e,t){await this.__connection,await gt.call(this,"getRecords");let r=await ls.bind(this)(e),n=r.is_reference_fetch,s=await k.bind(this)("get-records",r.query,{fetchOptions:t,auth:!!this.__user,method:this.__user?"post":"get"});n&&s?.reference_private_key&&typeof s.reference_private_key=="string"&&(this.__private_access_key[n]=s.reference_private_key);let i=[];for(let o in s.list)i.push(De.bind(this)(s.list[o]));return s.list=await Promise.all(i),s}function Hr(e){let t="",r=[],n=$t.bind(this)(e?.service,e?.owner),s=y.Params(e||{},{record_id:o=>{let a=typeof o=="string"?Br.bind(this)(n,o):void 0;return a||be(o,"record_id",{allowEmpty:false})},unique_id:["string",null],readonly:"boolean",table:{name:o=>je(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:$r.bind(this)},notification:o=>{if(o==null)return o;if(typeof o!="object"||Array.isArray(o))throw new l('"notification" should be an object with "title" and "body".',{code:"INVALID_PARAMETER"});for(let a of ["title","body"])if(typeof o[a]!="string"||!o[a].trim())throw new l(`"notification.${a}" is required.`,{code:"INVALID_PARAMETER"});return {title:o.title,body:o.body}},source:{referencing_limit:o=>{if(o===null)return null;if(typeof o=="number"){if(0>o)throw new l('"reference_limit" should be >= 0',{code:"INVALID_PARAMETER"});if(o>4503599627370546)throw new l('"reference_limit" should be <= 4503599627370546',{code:"INVALID_PARAMETER"});return o}throw new l('"reference_limit" should be type: <number | null>',{code:"INVALID_PARAMETER"})},prevent_multiple_referencing:"boolean",can_remove_referencing_records:"boolean",only_granted_can_reference:"boolean",allow_granted_to_grant_others:"boolean",referencing_index_restrictions:o=>{if(o===void 0)return;if(!o||Array.isArray(o)&&!o.length)return null;let a={name:c=>pt(c,'"name" in "index_restrictions"'),value:c=>qt(c),condition:["gt","gte","lt","lte",">",">=","<","<=","=","eq","!=","ne",()=>null],range:c=>{if(c!==null&&typeof o.value!=typeof c)throw new l('Index restriction "range" type should match the type of "value".',{code:"INVALID_PARAMETER"});if(!o.hasOwnProperty("value"))throw new l('Index restriction "value" is required.',{code:"INVALID_PARAMETER"});return c}};Array.isArray(o)||(o=[o]);let u=o.map(c=>y.Params(c,a,["name"]));if(u.length)for(let c of u)c.condition&&c.hasOwnProperty("range")&&delete c.range;return u}},reference:o=>{if(o===null)return {record_id:null};if(o){if(typeof o=="string"){t=o;let a=Br.bind(this)(n,o);return a||o}if(typeof o!="object")throw new l('"reference" should be type: <string | object>.',{code:"INVALID_PARAMETER"});return y.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),be(a,"reference.record_id",{allowEmpty:false,onlyAlphanumeric:true}))})}},index:[null,{name:o=>pt(o,"index.name"),value:o=>qt(o)}],tags:o=>{if(o==null)return o;if(typeof o=="string"&&(o=o.split(",").map(a=>a.trim())),!Array.isArray(o))throw new l('"tag" should be type: <string | string[]>.',{code:"INVALID_PARAMETER"});return o.map(a=>Ft(a,"tag"))},remove_bin:o=>{if(!o)return null;let a=[];if(Array.isArray(o))for(let u of o)if(typeof u=="string")a.push(u.split("?")[0]);else if(u.url&&u.size&&u.filename){let f=u.url.split("/").slice(0,3).join("/")+"/"+u.path;a.push(f);}else throw new l('"remove_bin" should be type: <string[] | BinaryFile[] | null>',{code:"INVALID_PARAMETER"});else throw new l('"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 l('"table.name" is required.',{code:"INVALID_PARAMETER"});typeof a.table=="string"&&(a.table={name:a.table},a?.record_id||(a.table.access_group=0)),o.files&&(r=o.files);}}),i=e.progress||null;if(delete s.progress,!this.__user){let o=!!(s.table?.subscription?.is_subscription_record||s.table?.subscription?.upload_to_feed||s.table?.subscription?.notify_subscribers||s.table?.subscription?.feed_referencing_records||s.table?.subscription?.notify_referencing_records);if(s.record_id)throw new l("Public users cannot update existing records.",{code:"INVALID_REQUEST"});if(s.table.access_group!=="public"&&s.table.access_group!==0)throw new l("Public users can only post records to public tables.",{code:"INVALID_REQUEST"});if(o)throw new l("Public users cannot post subscription records.",{code:"INVALID_REQUEST"});if(s.remove_bin)throw new l("Public users cannot remove files from records.",{code:"INVALID_REQUEST"});if(s.unique_id)throw new l("Public users cannot set unique_id for records.",{code:"INVALID_REQUEST"})}return {config:s,progress:i,is_reference_post:t,files:r}}async function Gr(e){if(await this.__connection,!Array.isArray(e)||!e.length)throw new l('"params" should be a non-empty array.',{code:"INVALID_PARAMETER"});let t=[],r,n,s=null,i={},o={},u={_is_bulk_:await Promise.all(e.map(async(h,m)=>{if(!h||typeof h!="object"||Array.isArray(h))throw new l(`"params[${m}]" should be type: <object>.`,{code:"INVALID_PARAMETER"});o[m]={has:h.data!==void 0,value:h.data};let _=Hr.bind(this)(h),b=_.config;if(L.call(this)){let E=Object.prototype.hasOwnProperty.call(b,"data"),w=await Ir.bind(this)(b.data,as(h,b),E);w.encrypted&&(b.data=w.send,i[m]=w.plain);}if(_.is_reference_post&&t.push(_.is_reference_post),typeof b.progress=="function"&&s===null&&(s=b.progress),b.service!==void 0){if(r===void 0)r=b.service;else if(r!==b.service)throw new l('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 l('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&&(u.service=r),n!==void 0&&(u.owner=n);let c={auth:!!this.__user,method:"post"},f={};Object.keys(f).length&&Object.assign(c,{fetchOptions:f});let p=await k.bind(this)("post-record",u,c),d=await Promise.all(p.map((h,m)=>De.bind(this)(h,"called from postRecord",o[m]?.has===true,i.hasOwnProperty(m))));for(let h=0;h<d.length;h++)i.hasOwnProperty(h)&&d[h]&&!d[h].error?(d[h].data=i[h],d[h].encrypted={status:"encrypted"}):o[h]?.has&&d[h]&&!p[h]?.error&&Kr(p[h]?.data)&&(d[h].data=o[h].value);let g=$t.bind(this)(r,n);for(let h=0;h<p.length;h++){let m=p[h],_=d[h];if(m&&typeof m=="object"&&m.error&&_&&!_.record_id&&(_.error=m.error),typeof m?.reference_private_key=="string")for(let b of t)this.__private_access_key[b]=m.reference_private_key;_?.unique_id&&os.bind(this)(g,_.unique_id,_.record_id);}return d}async function Wr(e,t,r){if(await this.__connection,!t)throw new l('"config" argument is required.',{code:"INVALID_PARAMETER"});let n=Hr.bind(this)(t),s=n.config,i=n.progress,o=n.is_reference_post,a={auth:!!this.__user,method:"post"},u=[],c=$(e);r&&Array.isArray(r)&&r.length&&(u=u.concat(r)),c.files&&Array.isArray(c.files)&&c.files.length&&(u=u.concat(c.files));let f=t?.data!==void 0?t.data:c.data,p=f!==void 0,d=await Ir.bind(this)(f,as(t,s),p),g=null;g=Object.assign({},s),delete g.data,d.omit||(g.data=d.send);let h={};if(typeof i=="function"&&(h.progress=i),Object.keys(h).length&&Object.assign(a,{fetchOptions:h}),d.files==="decrypt"&&t?.record_id){let w=await Or.bind(this)(t.record_id,"decrypt",i);if(w.length){let I=g.remove_bin;g.remove_bin=Array.isArray(I)?I.concat(w):w;}}if(d.spill&&t?.record_id){let w=new FormData;if(w.append(at,new File([d.spill],"payload.bin",{type:"application/octet-stream"})),await ft.bind(this)(w,{record_id:t.record_id}),d.retireCt){let I=g.remove_bin,R=[d.retireCt];g.remove_bin=Array.isArray(I)?I.concat(R):R;}}let m=await k.bind(this)("post-record",g,a);if(d.encrypted&&m?.rec&&Wn.bind(this)(m.rec,d.dek),d.files==="encrypt"&&m?.rec)try{let w=await Or.bind(this)(m.rec,"encrypt",i);w.length&&await Wr.bind(this)(void 0,{record_id:m.rec,remove_bin:w});}catch(w){console.error("Failed to encrypt existing attachments after making the record private:",w);}if(Q()&&u.length){let w=new FormData;for(let N of u)w.append(N.name,N.file,N.file.name);let I={record_id:m.rec,progress:i};s.hasOwnProperty("service")&&(I.service=s.service);let{bin_endpoints:R}=await ft.bind(this)(w,I);m.bin?m.bin.push(...R):m.bin=R;}o&&typeof m?.reference_private_key=="string"&&(this.__private_access_key[o]=m.reference_private_key);let _=!!m&&Kr(m.data),b=!d.omit&&d.send!==void 0,E=await De.bind(this)(m,"called from postRecord",b,d.encrypted);if(_&&b&&!d.encrypted&&(E.data=d.plain),d.encrypted&&(E.data=d.plain,E.encrypted={status:"encrypted",recipients:Object.keys(d.send.k||{})}),E.unique_id){let w=$t.bind(this)(s?.service,s?.owner);os.bind(this)(w,E.unique_id,E.record_id),Q()&&(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 E}async function us(e,t){await gt.call(this,"getTables");let r=await k.bind(this)("get-table",y.Params(e||{},{table:s=>je(s,"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 s of r.list){for(let i in n){if(i==="grp_"){for(let o in s)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"),s[`number_of_records_in_access_group_${a}`]=s[o],delete s[o];}}s.hasOwnProperty(i)&&(s[n[i]]=s[i],delete s[i]);}typeof s.table=="string"&&(s.table=ge(s.table));}return r}async function ds(e,t){if(await gt.call(this,"getIndexes"),!e?.table)throw new l('"table" is required.',{code:"INVALID_PARAMETER"});let r=y.Params(e||{},{table:i=>je(i,"table",{allowEmpty:true}),index:i=>pt(i,"index.name"),order:{by:["average_number","total_number","number_count","average_bool","total_bool","bool_count","string_count","index_name","number_of_records"],value:i=>{if(e?.order?.by==="index_name"&&typeof i=="string")return be(i,"order.value",{allowEmpty:true,maxLength:256,blockKeyDelimiters:true});if(typeof i!="string"&&typeof i!="number"&&typeof i!="boolean")throw new l('"order.value" should be type: <string | number | boolean>.',{code:"INVALID_PARAMETER"});return i},condition:["gt","gte","lt","lte",">",">=","<","<=","=","eq","!=","ne"]}},["table"]);if(r.hasOwnProperty("order")){if(!r.order?.by)throw new l('"order.by" is required.',{code:"INVALID_PARAMETER"});if(r.order.hasOwnProperty("condition")&&!r.order.hasOwnProperty("value"))throw new l('"value" is required for "condition".',{code:"INVALID_PARAMETER"});if(r.hasOwnProperty("index")&&r.index.substring(r.index.length-1)!==".")throw new l('"index" should be a parent index name of the compound index when using "order.by"',{code:"INVALID_PARAMETER"})}let n=await k.bind(this)("get-index",r,Object.assign({auth:!!this.__user},{fetchOptions:t})),s={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(i=>{let o=i.idx.split("/"),a={table:ge(o[1]),index:ge(o[2]),number_of_records:i.cnt_rec};for(let u in s)Object.prototype.hasOwnProperty.call(i,u)&&(a[s[u]]=i[u]);return a})),n}async function fs(e,t){await gt.call(this,"getTags");let r=await k.bind(this)("get-tag",y.Params(e||{},{table:n=>je(n,"table",{allowEmpty:true}),tag:n=>Ft(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 s=n.tag.split("/");return {table:ge(s[1]),tag:ge(s[0]),number_of_records:n.cnt_rec}})),r}async function ps(e,t){await gt.call(this,"getUniqueId");let r=await k.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 s=r.list[n];r.list[n]={unique_id:s.unq,record_id:s.rec};}return r}async function gs(e,t){await this.__connection;let r=await ls.bind(this)(e,true),n=r.is_reference_fetch,s=await k.bind(this)("del-records",r.query,{auth:true,fetchOptions:t});return n&&typeof s?.reference_private_key=="string"&&(this.__private_access_key[n]=s.reference_private_key),Array.isArray(s?.list)&&(s.list=await Promise.all(s.list.map(async i=>{if(!i||typeof i!="object")return i;try{return await De.bind(this)(i,"called from deleteRecords",!0,!1,!0)}catch{return i}}))),s?.message||s}async function hs(e){if(L.call(this)){let t=typeof e.user_id=="string"?[e.user_id]:e.user_id;Array.isArray(t)&&t.length&&await xr.bind(this)(e.record_id,t);}return _s.bind(this)({record_id:e.record_id,user_id:e.user_id,execute:"add"})}async function ms(e){let t=await _s.bind(this)({record_id:e.record_id,user_id:e.user_id||null,execute:"remove"});if(L.call(this)){let r=typeof e.user_id=="string"?[e.user_id]:e.user_id;await li.bind(this)(e.record_id,Array.isArray(r)&&r.length?r:null);}return t}async function ys(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 l("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 i of r.user_id)y.UserId(i);else throw new l("user_id should be type: <string | string[]>",{code:"INVALID_PARAMETER"});let n=i=>(i.rec_usr?(i.record_id=i.rec_usr.split("/")[0],i.user_id=i.rec_usr.split("/")[1]):i.usr_rec&&(i.user_id=i.usr_rec.split("/")[0],i.record_id=i.usr_rec.split("/")[1]),i),s=await k.bind(this)("grant-private-access",r,{auth:true,fetchOptions:t});return s.list=s.list.map(n),s}function bs(e){let t=e.record_id,r=e.reference_id||void 0;if(!t)throw new l("Record ID is required.",{code:"INVALID_PARAMETER"});if(typeof t!="string")throw new l("Record ID should be type: <string | string[]>",{code:"INVALID_PARAMETER"});if(r&&typeof r!="string")throw new l("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(Vt[t])return Vt[t];let n=k.bind(this)("request-private-access-key",{record_id:t,reference_id:r},{auth:true}).then(s=>{let i=typeof s=="string"?s:s?.private_key;if(typeof i!="string")throw new l("Invalid private access key response.",{code:"ERROR"});return this.__private_access_key[t]=i,i}).finally(()=>{delete Vt[t];});return Vt[t]=n,n}function _s(e){e.execute;let r=y.Params(e,{record_id:"string",user_id:n=>{if(!n)throw new l("User ID is required.",{code:"INVALID_PARAMETER"});let s=n;if(typeof s=="string"&&(s=[s]),s.length>100)throw new l("Cannot process more than 100 users at once.",{code:"INVALID_REQUEST"});for(let i of s)y.UserId(i,'User ID in "user_id"');return s},execute:["add","remove"]},["execute","record_id","user_id"]);return r.user_id||(r.user_id=null),k.bind(this)("grant-private-access",r,{auth:true})}var Zl=100;async function ws(e){if(await this.__connection,!Array.isArray(e)||!e.length)throw new l('"items" should be a non-empty array.',{code:"INVALID_PARAMETER"});let t=[],r=[],n=[];for(let i=0;i<e.length;i++){let o=e[i];try{if(!o||typeof o!="object"||Array.isArray(o))throw new l(`"items[${i}]" should be an object with "config".`,{code:"INVALID_PARAMETER"});let a=o.config;if(!a||typeof a!="object"||Array.isArray(a))throw new l(`"items[${i}].config" is required.`,{code:"INVALID_PARAMETER"});Hr.bind(this)(Object.assign({},a));let u=Object.assign({},a);delete u.data;let c=a.data!==void 0?a.data:o.data;if(c!==void 0){let f=c!==null&&typeof c=="object"?$(c):{data:c,files:[]};if(f.files&&f.files.length)throw new l(`"items[${i}].data" carries files. postRecords() does not attach files; use uploadFiles() on the saved record.`,{code:"INVALID_PARAMETER"});u.data=f.data;}n.push({index:i,config:u});}catch(a){r.push({index:i,code:String(a?.code||"INVALID_PARAMETER"),message:String(a?.message||a)});}}let s=0;for(;s<n.length;){let i=n.slice(s,s+Zl),o=await Gr.bind(this)(i.map(u=>Object.assign({},u.config)));if(!Array.isArray(o)||!o.length){for(let u of i)r.push({index:u.index,code:"ERROR",message:"The server answered nothing for this record."});s+=i.length;continue}let a=Math.min(o.length,i.length);for(let u=0;u<a;u++){let c=o[u];if(c&&c.record_id)t.push(c);else {let f=c?.error||{};r.push({index:i[u].index,code:String(f.code||"ERROR"),message:String(f.message||"The record was not saved.")});}}s+=a;}return r.sort((i,o)=>i.index-o.index),{list:t,failed:r}}var O={},G={},re={},he={},ce={},K={},Kt={};function Be(e,t){let r=(Kt[e]||Promise.resolve()).then(t,t);return Kt[e]=r.catch(()=>{}),r}var Ht={},Gt={};function As(e,t,r){e[t]||(e[t]=[]),e[t].push(r);}async function Ts(e,t,r){let n=[];if(e[t]){let s=e[t];delete e[t];for(let i of s)if(i){let o=r(i);o instanceof Promise&&(o=await o),n.push(o);}}return n}var Qr="stun:stun.skapi.com:3468",Is=["text","detail","motion"],Es={"text-chat":{ordered:true,maxRetransmits:10,protocol:"text-chat"},"file-transfer":{ordered:false,maxPacketLifeTime:3e3,protocol:"file-transfer"},"video-chat":{ordered:true,maxRetransmits:10,protocol:"video-chat"},"voice-chat":{ordered:true,maxRetransmits:10,protocol:"voice-chat"},gaming:{ordered:false,maxPacketLifeTime:100,protocol:"gaming"},default:{ordered:true,maxRetransmits:10,protocol:"default"}};function j(e){return new l(e,{code:"INVALID_PARAMETER"})}function z(e){return !!e&&typeof e=="object"&&!Array.isArray(e)}function Yr(){return typeof MediaStream<"u"}function le(){return new Date().toISOString()}async function ec(){let e=Zs();if(!e)try{e=await Zr.bind(this)();}catch{e=null;}let t=e?e.servers:[{urls:Qr}];return t.some(r=>(Array.isArray(r.urls)?r.urls:[r.urls]).some(n=>/^stuns?:/.test(n)))?t:[{urls:Qr},...t]}function tc(e){if(e==null||e==="")return [{urls:Qr}];let t=r=>typeof r=="string"&&/^(stun|stuns|turn|turns):/.test(r);if(typeof e=="string"){if(!t(e))throw j('"ice" should be a "stun:", "stuns:", "turn:" or "turns:" url, or a list of { urls, username, credential }.');return [{urls:e}]}if(!Array.isArray(e)||!e.length)throw j('"ice" should be a url string, or a non-empty list of { urls, username, credential }.');return e.map((r,n)=>{if(!z(r))throw j(`"ice[${n}]" should be an object: { urls, username, credential }.`);let s=r.urls,i=Array.isArray(s)?s:[s];if(!i.length||!i.every(t))throw j(`"ice[${n}].urls" should be a "stun:", "stuns:", "turn:" or "turns:" url, or a list of them.`);let o={urls:s};for(let a of ["username","credential"])if(r[a]!==void 0){if(typeof r[a]!="string")throw j(`"ice[${n}].${a}" should be type: <string>.`);o[a]=r[a];}if(i.some(a=>/^turns?:/.test(a))&&(!o.username||!o.credential))throw j(`"ice[${n}]" is a TURN server: it needs "username" and "credential".`);return o})}async function ks(e,t){let r={iceServers:e==null||e===""?await ec.bind(this)():tc(e)};return t&&(r.iceTransportPolicy=t),r}function Ps(e){if(typeof e!="string")throw j('"cid" should be type: <string>.');if(e&&e.slice(0,4)!=="cid:")throw j('"cid" should be a valid connection id.');return e}function Ss(e){if(e!=null){if(e!=="all"&&e!=="relay")throw j('"icePolicy" should be "all" or "relay".');return e}}function vs(e){if(!(e==null||e===false)){if(Yr()&&e instanceof MediaStream)return e;if(!z(e))throw j('"media" should be a MediaStream, or an object: { audio, video, screen }.');for(let t of ["audio","video"])if(e[t]!==void 0&&typeof e[t]!="boolean"&&!z(e[t]))throw j(`"media.${t}" should be a boolean or track constraints.`);if(e.screen!==void 0&&typeof e.screen!="boolean"&&!z(e.screen))throw j('"media.screen" should be true, or the options of getDisplayMedia().');if(z(e.screen)&&e.screen.contentHint!==void 0&&!Is.includes(e.screen.contentHint))throw j('"media.screen.contentHint" should be "text", "detail" or "motion".');return e}}function Ns(e){return z(e)&&!!(e.audio||e.video||e.screen)}function Wt(){if(window.location.hostname!=="localhost"&&window.location.protocol!=="https:")throw new l("Media stream is only supported on either localhost or https.",{code:"INVALID_REQUEST"})}function Ds(e){if(e!=null){if(!z(e))throw j('"receive" should be an object: { audio, video }.');for(let t of ["audio","video"])if(e[t]!==void 0&&typeof e[t]!="boolean")throw j(`"receive.${t}" should be type: <boolean>.`);return e}}function Cs(e){if(e==null)return null;if(!z(e))throw j('"encoding" should be an object: { video, audio }.');for(let t of ["video","audio"]){let r=e[t];if(r!==void 0){if(!z(r))throw j(`"encoding.${t}" should be an object.`);if(r.codecs!==void 0&&(!Array.isArray(r.codecs)||!r.codecs.every(n=>typeof n=="string"&&n)))throw j(`"encoding.${t}.codecs" should be a list of codec names.`);for(let n of ["maxBitrate","maxFramerate","scaleResolutionDownBy"])if(r[n]!==void 0&&!(typeof r[n]=="number"&&r[n]>0))throw j(`"encoding.${t}.${n}" should be a positive number.`)}}return e}function xs(e,t){if(e==null)return t;if(!Array.isArray(e))throw j('"channels" should be an array of preset names or RTCDataChannelInit objects.');let r={ordered:"boolean",maxPacketLifeTime:"number",maxRetransmits:"number",protocol:"string",negotiated:"boolean",id:"number"};return e.map((n,s)=>{if(typeof n=="string"){if(!n)throw j(`"channels[${s}]" should be a preset name or RTCDataChannelInit.`);return n}if(!z(n))throw j(`"channels[${s}]" should be a preset name or RTCDataChannelInit.`);for(let[i,o]of Object.entries(r))if(n[i]!==void 0&&typeof n[i]!==o)throw j(`"channels[${s}].${i}" should be type: <${o}>.`);if(n.negotiated&&typeof n.id!="number")throw j(`"channels[${s}]" is negotiated: it needs an "id" both sides open it with.`);return n})}function rc(e){if(e==null)return {};if(!z(e))throw j('"meta" should be an object.');try{return JSON.parse(JSON.stringify(e))}catch{throw j('"meta" should be a JSON object.')}}function Us(e,t,r){return {polite:e,makingOffer:false,ignoreOffer:false,armed:false,meta:t,media:new MediaStream,user:null,sources:new Map,wires:new Map,cleanup:new Map,remoteSources:{},encoding:r,receive:null,ringTimer:null}}function zr(e){let t=K[e];if(t){clearTimeout(t.ringTimer);for(let r of t.cleanup.values())r();for(let r of t.media.getTracks())r.stop();}O[e]&&O[e].signalingState!=="closed"&&O[e].close(),delete K[e],delete O[e],delete G[e],delete ce[e],delete Kt[e];}async function Os(e,t){let r=K[e],{contentHint:n,source:s,...i}=z(t)?t:{},a=(await window.navigator.mediaDevices.getDisplayMedia(Object.keys(i).length?i:{video:true})).getTracks();for(let u of a)if(r.sources.set(u,"screen"),u.kind==="video"&&n)try{u.contentHint=n;}catch{}return a}async function Ls(e,t){let r=K[e],n=await window.navigator.mediaDevices.getUserMedia(t),s=n.getTracks();for(let i of s)r.sources.set(i,i.kind==="audio"?"microphone":"camera");if(!r.user)r.user=n;else for(let i of s)r.user.addTrack(i);return s}async function Ms(e,t){let r=K[e];if(!t||!r)return;if(Yr()&&t instanceof MediaStream){for(let i of t.getTracks())r.sources.set(i,"custom");Bt.call(this,e,t.getTracks(),t);return}let{screen:n,...s}=t;if(s.audio||s.video){let i=await Ls(e,s);Bt.call(this,e,i,r.user);}if(n){let i=await Os(e,n===true?{}:n);Bt.call(this,e,i,new MediaStream(i));}}function Bt(e,t,r){let n=O[e],s=K[e];if(!(!n||!s)){for(let i of t){s.sources.has(i)||s.sources.set(i,"custom"),r.getTracks().includes(i)||r.addTrack(i),s.wires.set(i,r),s.media.getTracks().includes(i)||s.media.addTrack(i),n.getSenders().some(a=>a.track===i)||n.addTrack(i,r);let o=()=>Jr.call(this,e,i,false,true);i.addEventListener("ended",o,{once:true}),s.cleanup.set(i,()=>i.removeEventListener("ended",o));}qs.call(this,e),ht.call(this,e);}}function Jr(e,t,r,n=false){let s=O[e],i=K[e];if(!i||!i.sources.has(t)){r&&t.stop();return}let o=i.sources.get(t),a=i.cleanup.get(t);if(a&&a(),i.cleanup.delete(t),s&&s.signalingState!=="closed"){let f=s.getSenders().find(p=>p.track===t);if(f)try{s.removeTrack(f);}catch(p){this.log("removeTrack",p);}}let u=i.wires.get(t);u&&u.removeTrack(t),i.wires.delete(t),i.media.removeTrack(t),i.sources.delete(t),r&&t.stop();let c=ce[e];c&&c({type:"unshare",target:s,timestamp:le(),track:t,source:o,ended:n});}function Fs(e,t){let r=O[e];if(!(!r||!t))for(let n of ["audio","video"]){if(!t[n])continue;r.getTransceivers().some(i=>i.sender.track&&i.sender.track.kind===n||i.receiver.track&&i.receiver.track.kind===n)||r.addTransceiver(n,{direction:"recvonly"});}}function nc(e,t){let r=typeof RTCRtpReceiver<"u"?RTCRtpReceiver:null,n=r&&typeof r.getCapabilities=="function"?r.getCapabilities(e):null;if(!n||!n.codecs)return null;let s=t.map(o=>(o.includes("/")?o:`${e}/${o}`).toLowerCase()),i=[];for(let o of s)for(let a of n.codecs)a.mimeType.toLowerCase()===o&&!i.includes(a)&&i.push(a);return i.length?[...i,...n.codecs.filter(o=>!i.includes(o))]:null}function qs(e){let t=O[e],r=K[e];if(!(!t||!r||!r.encoding))for(let n of ["audio","video"]){let s=r.encoding[n]&&r.encoding[n].codecs;if(!s||!s.length)continue;let i=nc(n,s);if(i){for(let o of t.getTransceivers())if((o.sender.track&&o.sender.track.kind||o.receiver.track&&o.receiver.track.kind)===n&&typeof o.setCodecPreferences=="function")try{o.setCodecPreferences(i);}catch(u){this.log("setCodecPreferences",u);}}}}function ht(e){let t=O[e],r=K[e];if(!(!t||!r||!r.encoding))for(let n of t.getSenders()){let s=n.track;if(!s)continue;let i=r.encoding[s.kind];if(!i)continue;let o={};for(let c of ["maxBitrate","maxFramerate","scaleResolutionDownBy"])i[c]!==void 0&&(o[c]=i[c]);if(!Object.keys(o).length)continue;let a;try{a=n.getParameters();}catch{continue}if(!a.encodings||!a.encodings.length)continue;let u=false;for(let c in o)a.encodings[0][c]!==o[c]&&(a.encodings[0][c]=o[c],u=true);u&&n.setParameters(a).catch(c=>this.log("setParameters",c));}}function Xr(e,t){let r=O[e];if(!r||r.signalingState==="closed")throw new l("The call is closed.",{code:"INVALID_REQUEST"});let n=typeof t=="string"?Es[t]||{...Es.default,protocol:t}:{...t},s=n.protocol||"default";if(G[e]||(G[e]={}),G[e][s])throw new l(`Data channel with the protocol "${s}" already exists.`,{code:"INVALID_REQUEST"});let i=r.createDataChannel(s,n);return G[e][s]=i,Xs.call(this,e,i,s),i}function Vs(e){let t=O[e];t.ondatachannel=r=>{let n=r.channel;G[e]||(G[e]={});let s=n.label;G[e][s]&&G[e][s]!==n&&(s=`${n.label}#${n.id}`),this.log("ondatachannel",`received data channel "${s}".`),G[e][s]=n,Xs.call(this,e,n,s);};}async function js(e,t){if(!this?.session?.accessToken?.jwtToken)throw new l("Access token is required.",{code:"INVALID_PARAMETER"});let r=await this.__socket;if(!r||r.readyState!==1)throw new l("Realtime connection is not ready.",{code:"INVALID_REQUEST"});r.send(JSON.stringify({action:"rtc",uid:e,content:t,token:this.session.accessToken.jwtToken}));}function $s(e){let t=O[e],r=K[e],n={};if(!t||!r)return n;for(let s of t.getTransceivers())s.mid&&s.sender.track&&r.sources.has(s.sender.track)&&(n[s.mid]=r.sources.get(s.sender.track));return n}function Bs(e,t){let r=K[e];if(r&&z(t))for(let n in t)typeof t[n]=="string"&&(r.remoteSources[n]=t[n]);}async function Ks(e,t={}){let r=O[e],n=K[e];if(!(!r||!n||r.signalingState==="closed"))try{n.makingOffer=!0;let s=await r.createOffer();if(r.signalingState!=="stable"){this.log("sendOffer",`offer to "${e}" dropped: an offer from the other side came first.`);return}await r.setLocalDescription(s),ht.call(this,e),this.log("rtcSdpOffer to",e),await js.call(this,e,{sdpoffer:r.localDescription,sources:$s(e),...t});}finally{n.makingOffer=false;}}function Hs(e){let t=O[e],r=K[e];!t||!r||r.armed||(r.armed=true,t.onnegotiationneeded=()=>{this.log("onnegotiationneeded",`sending offer to "${e}".`),Ks.call(this,e).catch(s=>this.log("onnegotiationneeded",s));let n=ce[e];n&&n({type:"negotiationneeded",target:t,timestamp:le(),signalingState:t.signalingState,connectionState:t.iceConnectionState,gatheringState:t.iceGatheringState});});}async function Rs(e,t){let r=O[t],n=K[t];if(!r||!n||r.signalingState==="closed"||!e?.sdpoffer)return;let s=n.makingOffer||r.signalingState!=="stable";if(n.ignoreOffer=!n.polite&&s,n.ignoreOffer){this.log("answerSdpOffer",`offer from "${t}" ignored: this side is offering.`);return}Bs(t,e.sources),this.log("answerSdpOffer from",t),await r.setRemoteDescription(new RTCSessionDescription(e.sdpoffer)),n.receive&&(Fs(t,n.receive),n.receive=null),qs.call(this,t);let i=await r.createAnswer();Hs.call(this,t),await r.setLocalDescription(i),ht.call(this,t),await js.call(this,t,{sdpanswer:r.localDescription,sources:$s(t)}),await zt.call(this,null,t);}async function Qt(e,t){if(!this?.session?.accessToken?.jwtToken)throw new l("Access token is required.",{code:"INVALID_PARAMETER"});O?.[t]&&K[t]?(await Ts(Gt,t,r=>Rs.call(this,r,t)),e&&await Rs.call(this,e,t)):e&&As(Gt,t,e);}async function Gs(e,t){let r=O[t],n=K[t];if(!(!r||!n||!e?.sdpanswer)){if(r.signalingState!=="have-local-offer"){this.log("sdpanswer",`answer from "${t}" ignored in signaling state "${r.signalingState}".`);return}Bs(t,e.sources),Hs.call(this,t),await r.setRemoteDescription(new RTCSessionDescription(e.sdpanswer)),ht.call(this,t),await zt.call(this,null,t);}}function Ws(e){delete Gt[e],delete Ht[e];}async function zt(e,t){this.log("receiveIceCandidate",e);let r=O?.[t];if(r&&r.remoteDescription&&r.remoteDescription.type){let n=async s=>{try{await r.addIceCandidate(s);}catch(i){K[t]?.ignoreOffer||this.log("addIceCandidate",i);}};await Ts(Ht,t,n),e&&await n(e);}else As(Ht,t,e);}async function me(e){if(typeof window>"u"||window._runningInNodeJS)throw new l("WebRTC is not supported in Node.js environment.",{code:"NOT_SUPPORTED"});y.Params(e,{cid:Ps,close_all:"boolean"});let t=this.__socket?await this.__socket:null,{cid:r,close_all:n=false}=e||{};if(!n&&!r)throw new l('"cid" is required.',{code:"INVALID_PARAMETER"});let s=i=>{if(!i)throw new l('"cid" is required.',{code:"INVALID_PARAMETER"});delete Gt[i],delete Ht[i];let o=K[i];if(o){clearTimeout(o.ringTimer);for(let a of o.cleanup.values())a();}if(G[i]&&Object.values(G[i]).forEach(a=>{a.readyState!=="closed"&&a.close();}),delete G[i],O?.[i]){O[i].connectionState!=="closed"&&(O[i].close(),t&&t.readyState===1&&this?.session?.accessToken?.jwtToken&&t.send(JSON.stringify({action:"rtc",uid:i,content:{hungup:this.user.user_id},token:this.session.accessToken.jwtToken})));let a={type:"connectionstatechange",target:O[i],timestamp:le(),state:O[i].connectionState,iceState:O[i].iceConnectionState,signalingState:O[i].signalingState};ce[i]&&ce[i](a),this.log("closeRTC",a);}if(o){this.log("Cleaning up media stream...",i);for(let a of o.media.getTracks())a.stop();}delete K[i],delete ce[i],delete he[i],delete re[i],delete O[i],delete Kt[i];};if(n)for(let i in O)s(i);else s(r);}function Qs(e){let t=this,r=O[e],n=K[e],s=()=>{if(!K[e]||!O[e]||O[e].signalingState==="closed")throw new l("The call is closed.",{code:"INVALID_REQUEST"})},i=a=>{if(typeof MediaStreamTrack<"u"&&a instanceof MediaStreamTrack)return n.sources.has(a)?[a]:[];if(typeof a!="string")throw j('Name a source ("camera", "microphone", "screen", or a name given to share()), or pass a MediaStreamTrack.');let u=[];for(let[c,f]of n.sources)f===a&&u.push(c);return u},o=a=>{let u=()=>Jr.call(t,e,a,false,true);a.addEventListener("ended",u,{once:true}),n.cleanup.set(a,()=>a.removeEventListener("ended",u));};return {cid:e,target:r,channels:G[e],media:n.media,meta:n.meta,hangup:()=>me.call(t,{cid:e}),tracks:a=>a===void 0?Array.from(n.sources.keys()):i(a),share:async(a,u)=>{s();let c=z(u)?u:{};if(c.contentHint!==void 0&&!Is.includes(c.contentHint))throw j('"contentHint" should be "text", "detail" or "motion".');let f,p;if(a==="screen")Wt(),f=await Os(e,c),p=new MediaStream(f);else if(a==="camera"||a==="microphone"){Wt();let{contentHint:d,source:g,...h}=c,m=Object.keys(h).length?h:true;f=await Ls(e,a==="camera"?{video:m}:{audio:m}),p=n.user;}else if(Yr()&&a instanceof MediaStream){f=a.getTracks(),p=a;for(let d of f)n.sources.set(d,typeof c.source=="string"&&c.source?c.source:"custom");}else if(typeof MediaStreamTrack<"u"&&a instanceof MediaStreamTrack)f=[a],p=new MediaStream([a]),n.sources.set(a,typeof c.source=="string"&&c.source?c.source:"custom");else throw j('share() takes "screen", "camera", "microphone", a MediaStream or a MediaStreamTrack.');if(c.contentHint){for(let d of f)if(d.kind==="video")try{d.contentHint=c.contentHint;}catch{}}return s(),Bt.call(t,e,f,p),f},unshare:a=>{for(let u of i(a))Jr.call(t,e,u,true);},replace:async(a,u)=>{if(s(),typeof MediaStreamTrack>"u"||!(u instanceof MediaStreamTrack))throw j("replace() needs the MediaStreamTrack to send instead.");let c=i(a).find(h=>h.kind===u.kind);if(!c)throw new l(`No ${u.kind} track of "${typeof a=="string"?a:"that track"}" is on the call.`,{code:"INVALID_REQUEST"});let f=r.getSenders().find(h=>h.track===c);if(!f)throw new l("The track is not being sent.",{code:"INVALID_REQUEST"});await f.replaceTrack(u);let p=n.sources.get(c),d=n.wires.get(c),g=n.cleanup.get(c);g&&g(),n.cleanup.delete(c),d&&(d.removeTrack(c),d.addTrack(u),n.wires.set(u,d)),n.media.removeTrack(c),n.media.addTrack(u),n.sources.delete(c),n.wires.delete(c),c.stop(),n.sources.set(u,p),o(u),ht.call(t,e);},mute:a=>{if(!z(a))throw j("mute() takes { audio, video, screen }.");for(let[u,c]of n.sources)c==="screen"?typeof a.screen=="boolean"&&(u.enabled=!a.screen):u.kind==="audio"?typeof a.audio=="boolean"&&(u.enabled=!a.audio):typeof a.video=="boolean"&&(u.enabled=!a.video);},addChannel:(a,u)=>{if(s(),typeof a!="string"||!a)throw j("addChannel() needs the name of the channel.");if(u!==void 0&&!z(u))throw j("addChannel() takes RTCDataChannelInit as its second argument.");return Xr.call(t,e,u?{...u,protocol:a}:a)}}}async function zs(e,t){if(typeof window>"u"||window._runningInNodeJS)throw new l("WebRTC is not supported in Node.js environment.",{code:"NOT_SUPPORTED"});if(typeof t!="function")throw new l("Callback is required.",{code:"INVALID_PARAMETER"});if(!this?.session?.accessToken?.jwtToken)throw new l("Access token is required.",{code:"INVALID_PARAMETER"});let r=$(e||{}).data||{},{media:n,...s}=r,i=y.Params(s,{cid:Ps,ice:E=>E,icePolicy:E=>E,receive:E=>E,encoding:E=>E,channels:E=>E,meta:E=>E,ringTimeout:"number"},["cid"]),o=i.cid,a=vs(n),u=Ss(i.icePolicy),c=Ds(i.receive),f=Cs(i.encoding),p=xs(i.channels,["default"]),d=rc(i.meta);if(i.ringTimeout!==void 0&&!(i.ringTimeout>0))throw j('"ringTimeout" should be a positive number of milliseconds.');Ns(a)&&Wt();let g=this.__socket?await this.__socket:this.__socket;if(!g)throw new l("No realtime connection. Execute connectRealtime() before this method.",{code:"INVALID_REQUEST"});if(g.readyState!==1)throw new l("Realtime connection is not ready.",{code:"INVALID_REQUEST"});let h=await ks.call(this,i.ice,u),m=!O?.[o];m&&(O[o]=new RTCPeerConnection(h),K[o]=Us(false,d,f));let _=O[o],b=K[o];m||(b.meta=d,b.encoding=f),ce[o]=t,G[o]||(G[o]={}),Vs.call(this,o);try{await Ms.call(this,o,a);}catch(E){throw m&&zr(o),E}Fs(o,c);for(let E of p)Xr.call(this,o,E);return Ys.call(this,o),await Ks.call(this,o,{meta:d}),i.ringTimeout&&(b.ringTimer=setTimeout(()=>{if(!re[o])return;this.log("ringTimeout",`no answer from "${o}" within ${i.ringTimeout} ms.`);let E=ce[o];E&&E({type:"ringtimeout",target:_,timestamp:le(),cid:o}),re[o](false);},i.ringTimeout)),{hangup:()=>re[o]?re[o](false):me.call(this,{cid:o}),connection:new Promise(E=>{re[o]=(w=>{if(clearTimeout(b.ringTimer),delete re[o],this.log("receiver picked up the call",o,w),!w)return me.call(this,{cid:o}),null;E(Qs.call(this,o));}).bind(this);})}}function Js(e){return async(t,r)=>{let n=$(t||{}).data||{},{media:s,...i}=n,o=y.Params(i,{ice:b=>b,icePolicy:b=>b,receive:b=>b,encoding:b=>b,channels:b=>b}),a=e.sender_cid,u=await this.__socket;if(!he[a])return null;if(typeof r!="function")throw new l("Callback is required.",{code:"INVALID_PARAMETER"});let c=vs(s),f=Ss(o.icePolicy),p=Ds(o.receive),d=Cs(o.encoding),g=xs(o.channels,[]);Ns(c)&&Wt();let h=await ks.call(this,o.ice,f),m=!O?.[a];m&&(O[a]=new RTCPeerConnection(h),K[a]=Us(true,z(e.meta)?e.meta:{},d));let _=K[a];ce[a]=r,G[a]||(G[a]={}),Vs.call(this,a);try{await Ms.call(this,a,c);}catch(b){throw m&&zr(a),b}if(!he[a])return zr(a),null;delete he[a],_.receive=p||null;for(let b of g)Xr.call(this,a,b);return Ys.call(this,a),await Be(a,()=>Qt.call(this,null,a)),u.send(JSON.stringify({action:"rtc",uid:a,content:{pickup:this.user.user_id},token:this.session.accessToken.jwtToken})),Qs.call(this,a)}}async function ic(e,t){if(!this?.session?.accessToken?.jwtToken)throw new l("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=e.candidate;this.log("ice gathering state set to",O[t]?.iceGatheringState),r.send(JSON.stringify({action:"rtc",uid:t,content:{candidate:n},token:this.session.accessToken.jwtToken}));}function Ys(e){let t=ce[e]||(i=>{}),r=O[e],n=i=>{let o=K[e];return o&&i!==null&&i!==void 0?o.remoteSources[i]:void 0},s={ontrack:i=>{let o=i.transceiver?i.transceiver.mid:null;t({type:"track",target:r,timeStamp:i.timeStamp,streams:i.streams,track:i.track,source:n(o),mid:o});for(let a of ["mute","unmute","ended"])i.track.addEventListener(a,()=>{let u=ce[e];u&&u({type:"track"+a,target:r,timestamp:le(),track:i.track,streams:i.streams,source:n(o),mid:o});});},onicecandidate:i=>{ic.bind(this)(i,e),i.candidate?t({type:"icecandidate",target:r,timestamp:le(),candidate:i.candidate.candidate,sdpMid:i.candidate.sdpMid,sdpMLineIndex:i.candidate.sdpMLineIndex,usernameFragment:i.candidate.usernameFragment,protocol:i.candidate.protocol,gatheringState:r.iceGatheringState,connectionState:r.iceConnectionState}):t({type:"icecandidateend",target:r,timestamp:le()});},onicecandidateerror:i=>{t({type:"icecandidateerror",target:r,timestamp:le(),errorCode:i.errorCode,errorText:i.errorText,url:i.url,hostCandidate:i.hostCandidate,gatheringState:r.iceGatheringState,connectionState:r.iceConnectionState});},oniceconnectionstatechange:()=>{t({type:"iceconnectionstatechange",target:r,timestamp:le(),state:r.iceConnectionState,gatheringState:r.iceGatheringState,signalingState:r.signalingState});},onicegatheringstatechange:()=>{t({type:"icegatheringstatechange",target:r,timestamp:le(),state:r.iceGatheringState,connectionState:r.iceConnectionState,signalingState:r.signalingState});},onsignalingstatechange:()=>{t({type:"signalingstatechange",target:r,timestamp:le(),state:r.signalingState,connectionState:r.iceConnectionState,gatheringState:r.iceGatheringState});},onconnectionstatechange:()=>{t({type:"connectionstatechange",target:r,timestamp:le(),state:r.connectionState,iceState:r.iceConnectionState,signalingState:r.signalingState});let i=r.connectionState;(i==="disconnected"||i==="failed"||i==="closed")&&me.bind(this)({cid:e});}};for(let[i,o]of Object.entries(s))r[i]=o;}function Xs(e,t,r){let n=ce[e]||(o=>{}),s=r||t.label,i={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,label:t.label};this.log(`${t.label}: message`,o.data),n(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),n(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),n(a),G[e]&&G[e][s]===t&&(delete G[e][s],Object.keys(G[e]).length===0&&me.bind(this)({cid:e}));},onbufferedamountlow:o=>{let a={target:t,bufferedAmount:t.bufferedAmount,bufferedAmountLowThreshold:t.bufferedAmountLowThreshold,type:o.type,timeStamp:o.timeStamp,label:t.label};this.log(`${t.label}: bufferedamountlow`,t.bufferedAmount),n(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};n(a);}};for(let[o,a]of Object.entries(i))t[o]=a;}var Ge=[],Ke=null;function eo(e){return e&&Array.isArray(e.servers)&&e.servers.length?{servers:e.servers,expires:typeof e.expires=="number"?e.expires:null}:null}function Zs(){if(!Ke)return null;let e=Math.floor(Date.now()/1e3);return (Ke.expires??Ke.at+3600)-60>e?{servers:Ke.servers,expires:Ke.expires}:null}async function Zr(e=2500,t){let r=t||(this.__socket?await this.__socket:null);return !r||r.readyState!==1||!this?.session?.accessToken?.jwtToken?null:new Promise(n=>{let s=false,i=setTimeout(()=>{s||(s=true,Ge=Ge.filter(a=>a!==o),n(null));},e),o=a=>{s||(s=true,clearTimeout(i),n(eo(a)));};Ge.push(o);try{r.send(JSON.stringify({action:"ice",token:this.session.accessToken.jwtToken}));}catch{o(null);}})}var Te;function to(){return Te}var Pe=null,mt=true,He=0;async function sc(){if(typeof window>"u"||window._runningInNodeJS)throw new l("WebSocket is not supported in Node.js environment.",{code:"NOT_SUPPORTED"});if(await this.getProfile(),!this.session)throw new l("No access.",{code:"INVALID_REQUEST"});let e=await this.record_endpoint;return new WebSocket(e.websocket_private+"?token="+this.session.accessToken.jwtToken)}var en=null;async function Jt(){if(typeof window>"u"||window._runningInNodeJS)throw new l("WebSocket is not supported in Node.js environment.",{code:"NOT_SUPPORTED"});mt=true;let e=this.__socket?await this.__socket:this.__socket;me.bind(this)({close_all:true}),Te&&Qe.bind(this)({group:null}),He=0,Pe&&(Pe.terminate(),Pe=null);try{e&&e.close();}catch{}return window.removeEventListener("visibilitychange",en),this.__socket=null,null}async function We(e,t=50,r){if(typeof window>"u"||window._runningInNodeJS)throw new l("WebSocket is not supported in Node.js environment.",{code:"NOT_SUPPORTED"});if(typeof e!="function")throw new l("Callback must be a function.",{code:"INVALID_REQUEST"});if(r==="reconnect"){if(this.__socket instanceof Promise){let s=await this.__socket;if(s.readyState!==WebSocket.CLOSED&&s.readyState!==WebSocket.CLOSING)return this.__socket}}else if(mt&&(en=()=>{!document.hidden&&!mt&&We.bind(this)(e,0,"reconnect");},this.__socket instanceof Promise))return this.__socket;Pe&&(Pe.terminate(),Pe=null);let n={value:null};return this.__socket=new Promise(async(s,i)=>{let o=a=>{this.__socket===n.value&&(this.__socket=null),i(a);};try{await qe.bind(this)();}catch(a){o(a);return}setTimeout(async()=>{try{let a=await sc.bind(this)();a.onopen=()=>{mt=!1,He=0,r!=="reconnect"&&window.addEventListener("visibilitychange",en),this.log("realtime onopen","Connected to WebSocket server."),e({type:"success",message:"Connected to WebSocket server."}),Te&&a.send(JSON.stringify({action:"joinRoom",rid:Te,token:this.session.accessToken.jwtToken})),Zr.bind(this)(5e3,a).catch(()=>null);let u=`
207
207
  let interval = 15000; // Set interval time 15 seconds
208
208
 
209
209
  function runInterval() {
@@ -212,19 +212,19 @@ var Uo=Object.defineProperty;var Co=Object.getOwnPropertyDescriptor;var ke=(e=>t
212
212
  }
213
213
 
214
214
  runInterval(); // Start interval
215
- `,c=new Blob([u],{type:"application/javascript"});Re=new Worker(URL.createObjectURL(c)),Re.onmessage=f=>{l.readyState===1&&l.send(JSON.stringify({action:"keepAlive"}));},i(l);},l.onmessage=async u=>{let c="";try{c=JSON.parse(decodeURI(u.data)),this.log("socket onmessage",c);}catch{return}let f;switch(!0){case !!c?.["#message"]:f="message";break;case !!c?.["#private"]:f="private";break;case !!c?.["#notice"]:f="notice";break;case !!c?.["#rtc"]:f="rtc";break;case !!c?.["#error"]:f="error";break;case !!c?.["#ice"]:f="ice";break}if(!f){if(c?.requestId&&c?.connectionId&&je.length){let d=je.splice(0);for(let g of d)g(null);}return}if(f==="ice"){let d=bs(c["#ice"]);d&&(qe={...d,at:Math.floor(Date.now()/1e3)});let g=je.splice(0);for(let h of g)h(c["#ice"]);return}let p={type:f,message:c?.["#rtc"]||c?.["#message"]||c?.["#private"]||c?.["#notice"]||c?.["#error"]||null,sender:c?.["#user_id"]||null,sender_cid:c?.["#scid"]?"cid:"+c["#scid"]:null,sender_rid:c?.["#srid"]||null,code:c?.["#code"]||null};if(f==="notice")e(p);else if(f==="rtc"){if(p.sender!==this.user.user_id){let d=p.message;if(d.hungup){ce[p.sender_cid]&&(ce[p.sender_cid](!1),delete ce[p.sender_cid]),ge[p.sender_cid]&&delete ge[p.sender_cid],O?.[p.sender_cid]&&ue.bind(this)({cid:p.sender_cid}),p.type="rtc:closed",e(p);return}if(d.candidate&&Vt.bind(this)(d.candidate,p.sender_cid),d.sdpoffer&&(jr.bind(this)(d.sdpoffer,p.sender_cid),ge[p.sender_cid]||(ge[p.sender_cid]=p.sender_cid,delete p.message,p.connectRTC=gs.bind(this)(p),p.type="rtc:incoming",p.hangup=(()=>{O[p.sender_cid]?ue.bind(this)({cid:p.sender_cid}):ge[p.sender_cid]&&(delete ge[p.sender_cid],l.send(JSON.stringify({action:"rtc",uid:p.sender_cid,content:{hungup:this.user.user_id},token:this.session.accessToken.jwtToken})));}).bind(this),e(p))),d.pickup&&ce[p.sender_cid]&&(ce[p.sender_cid](!0),delete ce[p.sender_cid]),d.sdpanswer&&O[p.sender_cid])if(O[p.sender_cid].signalingState==="have-local-offer")await O[p.sender_cid].setRemoteDescription(new RTCSessionDescription(d.sdpanswer)),await Vt.bind(this)(null,p.sender_cid);else throw new a("Invalid signaling state.",{code:"INVALID_REQUEST"})}}else e(p);},l.onclose=()=>{ct?(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."}),Ve++,Ve<3?(this.log("realtime onclose","Reconnecting to WebSocket server..."+Ve),e({type:"reconnect",message:"Reconnecting to WebSocket server..."+Ve}),$e.bind(this)(e,3e3,"reconnect")):(this.log("realtime onclose","Max reconnection attempts reached."),e({type:"error",message:"Skapi: Max reconnection attempts reached."})));},l.onerror=()=>{this.log("realtime onerror","WebSocket connection error."),e({type:"error",message:"Skapi: WebSocket connection error."});};}catch(l){o(l);}},t);}),n.value=this.__socket,this.__socket}async function ws(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 Oe.bind(this)(),e=j(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 Be(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 Oe.bind(this)(),e=j(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.readyState===1&&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 Es(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 S.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 As(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 S.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 wl=typeof FormData<"u",Is=typeof HTMLFormElement<"u",Ps=typeof SubmitEvent<"u",he={},ut={},te={};function dt(e){return Object.freeze({id:e,status:"stopped"})}function Hr(e){return !!e&&typeof e=="object"&&e.status==="stopped"}var Ss=3;function ks(e,t,r){let n=false,i=Array.isArray(e?.chunks)?e.chunks.slice():[];i.sort((s,o)=>(s?.seq||0)-(o?.seq||0));for(let s of i)if(!(!s||typeof s.seq!="number"||s.seq<=t.seq)&&(t.seq=s.seq,n=true,r&&typeof s.txt=="string"&&s.txt!==""))try{r(s.txt,s.seq,"poll");}catch(o){console.error(o);}return typeof e?.last_seq=="number"&&e.last_seq>t.seq&&(t.seq=e.last_seq,n=true),n}var El=2e3,vs=5e3,Al=2e3,Rl=5,Tl=1500,$t=null;function Ns(e,t,r){let n=new Map,i=false,s=false,o=0,l={socket:0,poll:0},u=(d,g,h)=>{if(e.seq=d,!(!t||typeof g!="string"||g===""))try{t(g,d,h);}catch(m){console.error(m);}},c=()=>{for(let d of Array.from(n.keys()))d<=e.seq&&n.delete(d);for(;;){let d=e.seq+1;if(!n.has(d))break;let g=n.get(d);n.delete(d),u(d,g.txt,g.via);}};return {cursor:e,open:()=>{i||s||(i=true,c());},fromPoll:d=>{if(s)return false;let g=e.seq,h=e.seq,m=Array.isArray(d?.chunks)?d.chunks:[];for(let b of m){if(!b||typeof b.seq!="number"||b.seq<=e.seq)continue;let A=!n.has(b.seq);A&&(l.poll++,r&&l.poll===1&&r("poll",b.seq)),n.set(b.seq,{txt:typeof b.txt=="string"?b.txt:"",via:A?"poll":n.get(b.seq).via}),b.seq>h&&(h=b.seq);}typeof d?.last_seq=="number"&&d.last_seq>h&&(h=d.last_seq);let _=Array.from(n.keys()).sort((b,A)=>b-A);for(let b of _){if(b<=e.seq){n.delete(b);continue}if(b>h)break;let A=n.get(b);n.delete(b),u(b,A.txt,A.via);}return h>e.seq&&(e.seq=h),c(),e.seq>g},fromSocket:(d,g)=>{s||typeof d!="number"||!Number.isFinite(d)||(o=Date.now(),!(d<=e.seq)&&(!n.has(d)&&n.size>=Al||(n.has(d)||(l.socket++,r&&l.socket===1&&r("socket",d)),n.set(d,{txt:typeof g=="string"?g:"",via:n.has(d)?n.get(d).via:"socket"}),i&&c())));},warm:()=>o!==0&&Date.now()-o<El,stats:()=>({socket:l.socket,poll:l.poll}),close:()=>{s=true,n.clear();}}}function Ds(e){if(!this||!this.__network_logs)return {onTransport:void 0,done:()=>{}};let t=Date.now(),r=false;return {onTransport:(n,i)=>{console.log(`%cSKAPI: stream chunk arrived over ${n==="socket"?"WEBSOCKET":"POLL"}`,`color: ${n==="socket"?"green":"orange"};`,{id:e,first_seq:i,after_ms:Date.now()-t});},done:n=>{if(r||!n)return;r=true;let i=n.stats();console.log("%cSKAPI: stream transport","color: blue;",{id:e,over_websocket:i.socket,over_poll:i.poll,took_ms:Date.now()-t});}}}function xs(e,t){let r={stop:()=>{}};if(typeof window>"u"||window._runningInNodeJS||$t)return r;let n={stopped:false,socket:null,opened:null,joined:false,attempts:0,unavailable:false};$t=n;let i=c=>{if(n.stopped)return;let f=c?.data;if(typeof f!="string")return;let p=null;try{p=JSON.parse(f);}catch{try{p=JSON.parse(decodeURI(f));}catch{return}}let d=p?.["#message"];if(d==null)return;if(typeof d=="string")try{d=JSON.parse(d);}catch{return}if(typeof d!="object")return;let g=p?.["#srid"];if(typeof g=="string"&&g!==e)return;let h=d.seq;typeof h=="string"&&h!==""&&(h=Number(h)),t.fromSocket(h,d.txt);},s=()=>{if(n.socket){try{n.socket.removeEventListener("message",i);}catch{}try{n.socket.removeEventListener("close",l);}catch{}n.socket=null;}},o=async()=>{let c=n.opened,f=n.joined;if(n.opened=null,n.joined=false,s(),!(!f&&!c))try{let p=this.__socket?await this.__socket:null;if(c&&p===c){await jt.bind(this)();return}f&&p&&_s()===room&&await Be.bind(this)({group:null});}catch{}},l=()=>{n.stopped||(s(),!n.unavailable&&(n.attempts>=Rl||(n.attempts+=1,setTimeout(()=>{n.stopped||u();},Tl))));},u=async()=>{try{let c=this.__socket?await this.__socket:null;if(n.stopped){o();return}if(!c){if(!this.session){n.unavailable=!0,o();return}if(await $e.bind(this)(()=>{},0),c=this.__socket?await this.__socket:null,n.stopped){o();return}c&&!n.opened&&(n.opened=c);}if(!c||c.readyState!==1)return;if(c.addEventListener("message",i),c.addEventListener("close",l),n.socket=c,!n.joined&&(await Be.bind(this)({group:e}),n.joined=!0,n.stopped)){o();return}}catch{}};return u(),{stop:()=>{n.stopped||(n.stopped=true,$t===n&&($t=null),o());}}}function Us(e){return e?.status==="running"||e?.status==="pending"}function Cs(e){return !!e&&typeof e=="object"&&!Array.isArray(e)&&typeof e.status=="string"&&typeof e.id=="string"&&"in_queue"in e}function Os(e,t,r,n){if(!e||typeof e!="string")throw new a('"requestId" should be type: <string>.',{code:"INVALID_PARAMETER"});if(e.includes("#"))return e;if(!t||typeof t!="string"||!r||typeof r!="string")throw new a('"url" and "method" are required to address a request by its short id.',{code:"INVALID_PARAMETER"});return y.Url(t),`[${r.toUpperCase()}]${t.toLowerCase()}#${n}:${e}`}function Ls({id:e,auth:t,service:r,owner:n,latency:i=1e3,queue:s,seedExecuted:o,onResponse:l,onError:u,onStream:c,realtimeGroup:f}){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&&!he?.[s]&&(he[s]=new Ts__default.default({breakWhenError:false,batchSize:1}));let p={stop:null,aborted:false,queue:s};te[e]=p;let d=null,g=()=>{te[e]===p&&delete te[e];},h=()=>new Promise((_,b)=>{let A=false;if(p.aborted){g(),_(dt(e));return}let w={seq:0},I=Ds.call(this,e),E=c&&f?Ns(w,c,I.onTransport):null,N=E?xs.call(this,f,E):null,C=()=>{I.done(E),N&&N.stop(),E&&E.close();};d=C;let D=0,v=false,x=0,U=typeof o=="number"&&o>0?o:void 0,M=async()=>{if(!(A||v)&&!(E&&E.warm()&&Date.now()-D<vs)){v=true;try{for(;;){let ie={id:e,service:r,owner:n};c&&(ie.since=w.seq),D=Date.now();let F=await S.bind(this)("csr-poll",ie,{auth:t});if(A)return;let J=E?E.fromPoll(F):c?ks(F,w,c):!1;E&&E.open();let gt=Us(F);if(typeof F?.executed=="number"&&F.executed>0&&(U=F.executed),F?.more&&J){x=0;continue}if(gt){x=0;return}if(x=F?.more?x+1:0,F?.more&&x<Ss)return;A=!0,l&&l(F,U!==void 0?{executed:U}:void 0),clearInterval(de),C(),g(),_(F);return}}catch(ie){if(A)return;A=true,u&&u(ie),clearInterval(de),C(),g(),b(ie);}finally{v=false;}}},de=setInterval(M,i);E&&M(),p.stop=()=>{A||(A=true,clearInterval(de),C(),g(),_(dt(e)));};}),m=()=>{let _=te[e];_&&(_.stop?_.stop():(_.aborted=true,delete te[e]));};if(s){let _=new Promise((b,A)=>{let w=false,I=he[s].add([async()=>{try{let E=await h();return w||(w=!0,b(E)),E}catch(E){throw w||(w=true,A(E)),E}}])[0];ut[e]=I,p.stop=()=>{if(!w){p.aborted=true,d&&d();try{he[s]&&he[s].remove(ut[e]);}catch{}delete ut[e],g(),w=true,b(dt(e));}};});return Object.assign(_,{stop:m})}else return Object.assign(h(),{stop:m})}function Kt(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 te)te[n]?.queue===e.queue&&r.push(n);else for(let n in te)r.push(n);for(let n of r){let i=te[n];i&&(i.stop?i.stop():(i.aborted=true,delete te[n]),t+=1);}return t}function Gr(e,t){if(!e.queue)throw new a('"queue" is required.',{code:"INVALID_PARAMETER"});let r=()=>S.bind(this)("csr-poll",{service:e.service||this.service,owner:e.owner||this.owner,queue:e.queue+":"},{auth:true});return this.__projectIdInput?this.__projectIdInput.then(r):r()}function Il(e){if(typeof Buffer<"u"&&typeof Buffer.from=="function")return Buffer.from(e).toString("base64");if(typeof btoa=="function"){let t="";for(let n=0;n<e.length;n+=32768)t+=String.fromCharCode.apply(null,Array.from(e.subarray(n,n+32768)));return btoa(t)}throw new a("No base64 encoder available in this environment.",{code:"NOT_SUPPORTED"})}var Rs=2*1024*1024-64*1024;function Bt(e){return typeof File<"u"&&e instanceof File||typeof Blob<"u"&&e instanceof Blob}function Kr(e){if(Array.isArray(e)){let t=[];for(let r of e)Bt(r)||t.push(Kr(r));return t}if(e&&typeof e=="object"&&!Bt(e)){let t=Object.getPrototypeOf(e);if(t!==Object.prototype&&t!==null)return e;let r={};for(let n in e)Bt(e[n])||(r[n]=Kr(e[n]));return r}return e}function Pl(e){if(e==null)return null;let t=j(e)?.data;return !t||typeof t!="object"||Array.isArray(t)?null:Kr(t)}function Ms(e,t,r){if(r!==void 0){if(Array.isArray(r)){for(let n of r)Ms(e,t,n);return}if(Bt(r)){e.append(t,r);return}if(r===null){e.append(t,"");return}if(typeof r=="object"){e.append(t,JSON.stringify(r));return}e.append(t,String(r));}}async function Sl(e){if(e==null)throw new a('"multipart": true needs a form body in the first argument.',{code:"INVALID_PARAMETER"});if(typeof FormData>"u"||typeof Response>"u")throw new a('"multipart": true is not available in this environment.',{code:"NOT_SUPPORTED"});let t;if(Ps&&e instanceof SubmitEvent)t=new FormData(e.target);else if(Is&&e instanceof HTMLFormElement)t=new FormData(e);else if(e instanceof FormData)t=e;else if(typeof e=="object"&&!Array.isArray(e)){t=new FormData;for(let s in e)Ms(t,s,e[s]);}else throw new a('"form" should be a submit event, a form element, FormData, or an object.',{code:"INVALID_PARAMETER"});let r=new Response(t),n=r.headers.get("content-type"),i=Il(new Uint8Array(await r.arrayBuffer()));if(i.length>Rs)throw new a(`Multipart body is too large: ${i.length} bytes once base64 encoded, and the limit is ${Rs}. Upload the file first and send its url instead.`,{code:"INVALID_PARAMETER"});return {body_b64:i,body_content_type:n}}function kl(e){if(e!=null){if(typeof e=="boolean")return e;if(typeof e=="object"&&!Array.isArray(e))return {user:!!e.user,service:!!e.service};throw new a('"skapiHeaders" should be type: <boolean> or { user?: boolean; service?: boolean }.',{code:"INVALID_PARAMETER"})}}function vl(e){if(!(!e||typeof e!="object")){for(let t in e)if(typeof t=="string"&&t.toLowerCase().indexOf("x-skapi-")===0)throw new a(`"headers" cannot set "${t}": the "x-skapi-" prefix is reserved. Use "skapiHeaders" to tell the destination who the caller is.`,{code:"INVALID_PARAMETER"})}}async function Fs(e,t){let r=false,n=!!(e?.secretName||e?.clientSecretName),i=t?.signal;if(i?.aborted)throw new a('"signal" was already aborted.',{code:"INVALID_REQUEST"});if(typeof e.poll=="number"&&e.poll<0)throw new a('"poll" should be a non-negative number.',{code:"INVALID_PARAMETER"});let s=e?.onResponse,o=e?.onError,l=e?.onStream,u=typeof e.poll=="number"?e.poll:e.poll?1e3:0;delete e.poll,(u||e.stream)&&!e.queue&&(e.queue=(this.__user?.user_id||"anonymous")+"-"+Te());let c=(d,g=new WeakSet)=>{if(!(r||!d||typeof d!="object"||g.has(d))){g.add(d);for(let h in d){let m=d[h];if(typeof m=="string"){if(m.includes("$CLIENT_SECRET")){r=true;return}}else m&&typeof m=="object"&&c(m,g);}}};if(e=y.Params(e,{url:d=>{if(!d||typeof d!="string")throw new a('"url" should be type: <string>.',{code:"INVALID_PARAMETER"});return y.Url(d),d.includes("$CLIENT_SECRET")&&(r=true),d},secretName:"string",clientSecretName:"string",method:d=>{if(d&&typeof d!="string")throw new a('"method" should be one of "GET", "POST", "PUT", "PATCH", "DELETE" or "HEAD".',{code:"INVALID_PARAMETER"});let g=d.toLowerCase();if(g!=="get"&&g!=="post"&&g!=="delete"&&g!=="put"&&g!=="patch"&&g!=="head")throw new a('"method" should be one of "GET", "POST", "PUT", "PATCH", "DELETE" or "HEAD".',{code:"INVALID_PARAMETER"});return g},stream:d=>{if(d!=null&&typeof d!="boolean")throw new a('"stream" should be type: <boolean>.',{code:"INVALID_PARAMETER"});return !!d},realtime:d=>{if(d!=null&&typeof d!="boolean")throw new a('"realtime" should be type: <boolean>.',{code:"INVALID_PARAMETER"});return !!d},headers:d=>{if(d&&typeof d!="object")throw new a('"headers" should be type: <object>.',{code:"INVALID_PARAMETER"});return vl(d),c(d),d},skapiHeaders:d=>kl(d),data:d=>{if(d&&typeof d!="object")throw new a('"data" should be type: <object>.',{code:"INVALID_PARAMETER"});return c(d),d},params:d=>{if(d&&typeof d!="object")throw new a('"params" should be type: <object>.',{code:"INVALID_PARAMETER"});return c(d),d},body_b64:"string",body_content_type:"string",expires:"number",queue:"string"},t?.requireSecretName?["clientSecretName","method","url"]:["method","url"]),e.realtime&&!e.stream)throw new a('"realtime" requires "stream": true.',{code:"INVALID_PARAMETER"});if(e.body_b64&&e.data)throw new a('"data" cannot be sent with "multipart": true.',{code:"INVALID_PARAMETER"});n&&!r&&(delete e.secretName,delete e.clientSecretName),await this.__connection;let f=!!this.__user,p=()=>S.bind(this)("csr",e,{auth:f,tokenHeaders:{accessToken:!!f}}).then(d=>{if(d.status==="running"||d.status==="pending"){let g=`[${e.method.toUpperCase()}]${e.url.toLowerCase()}`,h=e.service||this.service,m=e.owner||this.owner,_=`${g}#${h}:${d.id}`;if(i){let b=()=>{Kt.call(this,{id:_});};i.aborted?b():i.addEventListener("abort",b,{once:true});}Object.assign(d,{poll:b=>Ls.call(this,{id:_,auth:f,service:h,owner:m,latency:b?.latency||1e3,queue:e?.queue,onResponse:s,onError:o,onStream:b?.onStream||l,realtimeGroup:d?.realtime_group})});}return s?s(d):d}).catch(d=>{if(o)return o(d);throw d});if(e?.queue){let d="base:"+e.queue;return he?.[d]||(he[d]=new Ts__default.default({breakWhenError:false,batchSize:1})),new Promise((g,h)=>{he[d].add([async()=>{try{let m=await p();if(u>0){let _=m.poll({latency:u});return i&&(i.aborted?_.stop():i.addEventListener("abort",()=>_.stop(),{once:!0})),g(_),_}return g(m),m}catch(m){throw h(m),m}}]);})}else return p()}async function qs(e,t){if(!t||typeof t!="object")throw new a('"options" is required in the second argument.',{code:"INVALID_PARAMETER"});if(t.apiKeyHeader!==void 0||t.apiKeyScheme!==void 0)throw new a('"apiKeyHeader" and "apiKeyScheme" are no longer supported. Store the key as a client secret, name it with "secretName", and put "$CLIENT_SECRET" where the key goes.',{code:"INVALID_PARAMETER"});if(t.multipart!==void 0&&t.multipart!==null&&typeof t.multipart!="boolean")throw new a('"multipart" should be type: <boolean>.',{code:"INVALID_PARAMETER"});let r=t.responseType;if(r!=null){if(r==="response")throw new a(`"responseType": "response" is not available here. The request is relayed from the server and what comes back is the stored answer, not a live Response; the destination's status code is the "status_code" of the row forwardRequestHistory lists.`,{code:"INVALID_PARAMETER"});if(r!=="json"&&r!=="text")throw new a('"responseType" should be either "json" or "text".',{code:"INVALID_PARAMETER"})}let n=t.method||"POST",i=typeof n=="string"?n.toLowerCase():"",s=i==="get"||i==="delete"||i==="head"?"params":"data",o={url:t.url,method:n};if(t.secretName!==void 0&&(o.secretName=t.secretName),t.headers!==void 0&&(o.headers=t.headers),t.data!==void 0&&(o.data=t.data),t.params!==void 0&&(o.params=t.params),t.skapiHeaders!==void 0&&(o.skapiHeaders=t.skapiHeaders),t.service!==void 0&&(o.service=t.service),t.owner!==void 0&&(o.owner=t.owner),t.queue!==void 0&&(o.queue=t.queue),t.expires!==void 0&&(o.expires=t.expires),t.stream!==void 0&&(o.stream=t.stream),t.realtime!==void 0&&(o.realtime=t.realtime),t.poll!==void 0&&(o.poll=t.poll),t.onStream!==void 0&&(o.onStream=t.onStream),t.onResponse!==void 0&&(o.onResponse=t.onResponse),t.onError!==void 0&&(o.onError=t.onError),t.multipart){if(t.data!==void 0&&t.data!==null)throw new a('"data" cannot be sent with "multipart": true. The form itself is the body.',{code:"INVALID_PARAMETER"});let u=await Sl(e);o.body_b64=u.body_b64,o.body_content_type=u.body_content_type;}else {let u=Pl(e);u&&Object.keys(u).length&&(o[s]=Object.assign({},u,o[s]||{}));}let l=Fs.call(this,o,{signal:t.signal});return r?l.then(u=>{if(Cs(u)||Hr(u))return u;if(r==="text")return typeof u=="string"?u:JSON.stringify(u);if(typeof u=="string")try{return JSON.parse(u)}catch{return u}return u}):l}async function Vs(e){return Fs.call(this,e,{requireSecretName:true})}async function Wr(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","PUT","PATCH","DELETE","HEAD"],queue:"string",status:["pending","running","resolved","failed"],compact:"boolean",queue_exact:"boolean",queue_exclude:"string"},["url","method"]);let i=!!this.__user,s=`[${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(u=>{o[u]||delete o[u];}),o.queue&&(o.id_prefix=o.id,delete o.id);let l=await S.bind(this)("csr-poll",o,{auth:i,fetchOptions:t});return l.list=l.list.map(u=>{let c={id:u.id,status_code:u.rslv?.status_code||null,response_body:u.rslv?.body||u.rslv?.truncated||null,error:u?.err,created:u?.stmp,updated:u?.utmp,executed:typeof u?.att=="number"?u.att*1e3:void 0,responded:typeof u?.rtmp=="number"?u.rtmp:void 0,request_body:u?.reqbdy,expires:u?.expt,status:u.stts,queue_name:u?.qid,request_text:u?.reqtxt,response_text:u?.rslvtxt,response_complete_marker:u?.rslvmk!=null?!!u.rslvmk:void 0,compact:u?.cmpct?true:void 0};for(let f in c)c[f]===void 0&&delete c[f];return (c.status==="running"||c.status==="pending")&&(c.poll=f=>Ls.call(this,{id:s+c.id,auth:i,service:r,owner:n,latency:f?.latency||1e3,queue:u?.qid,seedExecuted:c.executed,onResponse:f?.onResponse,onError:f?.onError,onStream:f?.onStream})),c}),l}async function Qr(e){await this.__connection,e=y.Params(e,{url:"string",method:["GET","POST","PUT","PATCH","DELETE","HEAD"],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}`,l=e?.queue;return l&&he?.[l]&&(he[l].remove(ut[o]),delete ut[o]),S.bind(this)("csr-cancel",{id:o,service:t,owner:r},{auth:n})}function zr(e,t){let r=typeof t?.poll=="number"?t.poll:1e3;if(!Number.isFinite(r)||r<0)throw new a('"poll" should be a non-negative number.',{code:"INVALID_PARAMETER"});if(!e||typeof e!="string")throw new a('"requestId" should be type: <string>.',{code:"INVALID_PARAMETER"});if(t?.since!==void 0&&typeof t.since!="number")throw new a('"since" should be a number.',{code:"INVALID_PARAMETER"});if(t?.realtimeGroup!==void 0&&t.realtimeGroup!==null&&typeof t.realtimeGroup!="string")throw new a('"realtimeGroup" should be type: <string>.',{code:"INVALID_PARAMETER"});let n=typeof t?.since=="number"&&t.since>0?t.since:0,i=t?.onStream,s=t?.onResponse,o=t?.onError,l={stopped:false,fullId:e,resolve:null},u=null,c={stop:null,aborted:false},f=()=>{te[l.fullId]===c&&delete te[l.fullId];},p=()=>{l.stopped||(l.stopped=true,u&&u(),f(),l.resolve&&l.resolve(dt(l.fullId)));};c.stop=p;let d=new Promise(async(g,h)=>{l.resolve=g;try{await this.__connection;let m=!!this.__user,_=t?.service||this.service,b=t?.owner||this.owner;if(l.fullId=Os(e,t?.url,t?.method,_),l.stopped){g(dt(l.fullId));return}te[l.fullId]=c;let A={seq:n},w=0,I=Ds.call(this,l.fullId),E=i&&t?.realtimeGroup?Ns(A,i,I.onTransport):null,N=E?xs.call(this,t.realtimeGroup,E):null,C=()=>{I.done(E),N&&N.stop(),E&&E.close();};for(u=C;;){let D=await S.bind(this)("csr-poll",{id:l.fullId,service:_,owner:b,since:A.seq},{auth:m});if(l.stopped)return;if(!Cs(D)){C(),f(),s&&s(D),g(D);return}let v=E?E.fromPoll(D):ks(D,A,i);E&&E.open();let x=Us(D);if(D.more&&v){w=0;continue}if(w=D.more?w+1:0,!x&&(!D.more||w>=Ss)){C(),f(),s&&s(D),g(D);return}if(await new Promise(U=>setTimeout(U,E&&E.warm()?Math.max(r,vs):r)),l.stopped)return}}catch(m){if(l.stopped)return;u&&u(),f(),o&&o(m),h(m);}});return Object.assign(d,{stop:p})}async function Jr(e,t,r){await this.__connection;let n=r?.service||this.service,i=r?.owner||this.owner,s=!!this.__user,o=Os(e,r?.url,r?.method,n);return S.bind(this)("csr-finalize",{id:o,data:t,service:n,owner:i},{auth:s})}var js=zr,$s=Jr,Bs=Wr,Ks=Qr,Hs=Kt,Gs=Gr;async function Ws(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 S.bind(this)("send-inquiry",e),"SUCCESS: Inquiry has been sent."}async function Qs(e,t){if(await this.__connection,wl&&e instanceof FormData||Is&&e instanceof HTMLFormElement||Ps&&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=j(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 S.bind(this)("post-secure",e,{auth:true})}async function zs(e,t){await this.__connection;let{auth:r=false,method:n="POST",bypassAwaitConnection:i=false,responseType:s,contentType:o,tokenHeaders:l,progress:u}=t||{};if(t=Object.assign({auth:r,method:n,bypassAwaitConnection:i,responseType:s,contentType:o,tokenHeaders:l},{fetchOptions:{progress:u}}),typeof e!="object"&&(o==="application/json"||o===void 0))throw new a('"data" should be type: <object>.',{code:"INVALID_PARAMETER"});return S.bind(this)("mock",e,t)}async function Js(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 S.bind(this)("get-feed",e,{auth:true,fetchOptions:t});return Array.isArray(r?.list)&&(r.list=await Promise.all(r.list.map(n=>Se.bind(this)(n)))),r}function ft(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 Ys(e,t){if(e=j(e,{ignoreEmpty:true}).data,e=y.Params(e,{subscriber:n=>y.UserId(n,'User ID in "subscriber"'),subscription:ft.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 S.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 Xs(e){await this.__connection,e=y.Params(e,{user_id:ft.bind(this),get_feed:"boolean",get_notified:"boolean",get_email:i=>{if(i&&(!this.__user.email||!this.__user.email_verified))throw new a("User has no verified email address.",{code:"INVALID_REQUEST"});return !!i}},["user_id"]);let t={};for(let i of ["get_feed","get_notified","get_email"])typeof e[i]=="boolean"&&(t[i]=e[i]);let r=await S.bind(this)("subscription",{subscribe:e.user_id,option:t},{auth:true}),n={};if(r.sub){let i=r.sub.split("#");n.subscriber=i[2],n.subscription=i[0];}else n.subscriber=r.subscriber,n.subscription=r.subscription;return n.timestamp=r?.timestamp||r.stmp,n.blocked=r?.blocked||r.grp.substring(0,1)==="N",Object.assign(n,r.opt),n}async function Zs(e){await this.__connection;let{user_id:t}=y.Params(e,{user_id:ft.bind(this)},["user_id"]);return await S.bind(this)("subscription",{unsubscribe:t},{auth:true})}async function eo(e){await this.__connection;let{user_id:t}=y.Params(e,{user_id:ft.bind(this)},["user_id"]);return await S.bind(this)("subscription",{block:t},{auth:true})}async function to(e){await this.__connection;let{user_id:t}=y.Params(e,{user_id:ft.bind(this)},["user_id"]);return await S.bind(this)("subscription",{unblock:t},{auth:true})}async function ro(e,t){await this.__connection;let r=await Q.bind(this)();if(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=>y.newsletterGroup(o,{allowNull:true}),email:o=>{if(typeof o!="string"||!o.trim())throw new a('"email" should be a non-empty string.',{code:"INVALID_PARAMETER"});if(o.trim().length>255)throw new a('"email" should be at most 255 characters.',{code:"INVALID_PARAMETER"});return o.trim().toLowerCase()}}),e.email!==void 0){if(e.user_id!==void 0&&e.user_id!==null)throw new a('"email" cannot be used with "user_id".',{code:"INVALID_PARAMETER"});if(e.group===void 0||e.group===null)throw new a('"group" is required to search by "email".',{code:"INVALID_PARAMETER"})}let n=await S.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 l=o.subt.split("#"),u=true;l[0].charAt(0)==="@"&&(u=false,l[0]=l[0].substring(1));let c=/^\d+$/.test(l[0])?parseInt(l[0]):l[0],f={timestamp:o.stmp,group:c,subscribed_email:l[1],active:u};typeof o.email_token=="string"&&o.email_token&&(f.subscriber_token=o.email_token),s.push(f);}return n?.list?(n.list=s,n):s}async function no(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:r=>y.newsletterGroup(r),redirect:r=>y.Url(r)},this.__user?["group"]:["email","group"]);return S.bind(this)(`subscribe-${this.__user?"":"public-"}newsletter`,t,{auth:!!this.__user})}async function io(e){await this.__connection;let t=y.Params(e||{},{group:r=>y.newsletterGroup(r,{nameOnly:true}),restriction:r=>{if(typeof r!="number"||!Number.isInteger(r)||r<0||r>99)throw new a('"restriction" should be a number between 0 and 99.',{code:"INVALID_PARAMETER"});return r},name:r=>{if(typeof r!="string"||r.length>60)throw new a('"name" should be a string of 60 characters or less.',{code:"INVALID_PARAMETER"});return r}},["group"]);return S.bind(this)("register-newsletter-group",t,{auth:true})}async function so(e){await this.__connection;let t=y.Params(e||{},{group:r=>y.newsletterGroup(r,{nameOnly:true})},["group"]);return S.bind(this)("delete-newsletter-group",t,{auth:true})}async function oo(){return await this.__connection,S.bind(this)("newsletter-group-endpoint",null,{auth:true})}async function ao(e){await this.__connection,e=y.Params(e,{group:r=>y.newsletterGroup(r,{allowNull:true})},["group"]);let t=Object.assign({action:"unsubscribe"},e);return S.bind(this)("subscribe-newsletter",t,{auth:true})}async function lo(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=j(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:u=>{if(typeof u!==n[e.searchFor])throw new a(`"value" type does not match the type of "${e.searchFor}" index.`,{code:"INVALID_PARAMETER"});if(typeof u=="string"&&!u)throw new a('"value" should not be empty string.',{code:"INVALID_PARAMETER"});return u},range:u=>{if(!e.hasOwnProperty("value")||typeof u!=typeof e.value)throw new a('"range" should match type of "value".',{code:"INVALID_PARAMETER"});return u},condition:[">",">=","=","<","<=","gt","gte","eq","lt","lte",()=>"="],group:u=>{let c=y.newsletterGroup(u);if(c===0)return 0;if(typeof c=="string")return c;if(!this.session)throw new a("User should be logged in.",{code:"INVALID_REQUEST"});if(u==="authorized")return 1;if(!r&&c>parseInt(this.user?.access_group||this.session?.idToken?.payload?.access_group))throw new a("User has no access.",{code:"INVALID_REQUEST"});return c}},["searchFor","value","group"]);let i=e.group===0||typeof e.group=="string"&&!this.__user?"get-public-newsletters":"get-newsletters",s=await S.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",group:"grp",dry:"dry",sent:"sent"},l={message_id:"",timestamp:0,complaint:0,read:0,subject:"",bounced:"",url:"",delivered:0,group:e.group,dry:false,sent:0};return s.list=s.list.map(u=>{let c={};for(let f in o)c[f]=u[o[f]]||l[f];return c.bounced=String(c.bounced),c.dry=!!c.dry,c.sent||delete c.sent,c}),s}var Ke="skapi:project_id";function co(e){let t=e.trim().toLowerCase().replace(/^<|>$/g,"").replace(/[\s_\-.]+/g,"");return t==="serviceid"||t==="projectid"}function uo(){try{return window.sessionStorage.getItem(Ke)||null}catch{return null}}function fo(e){try{window.sessionStorage.setItem(Ke,e);}catch{}}function Ht(e){try{window.sessionStorage.getItem(Ke)===e&&window.sessionStorage.removeItem(Ke);}catch{}}function po(){if(H())return typeof window.prompt=="function";let e=ve("tty");return !!(e&&ve("readline")&&e.isatty(0)&&e.isatty(2))}function go(){return new a("Project ID is required.",{code:"INVALID_PARAMETER"})}var pt=null;function ho(e,t){if(!pt){pt=H()?Nl(e,t):Dl(e,t);let r=()=>{pt=null;};pt.then(r,r);}return pt}async function Nl(e,t){await new Promise(o=>setTimeout(o,0));let r=`new Skapi() was given the placeholder "${e}" instead of your Project ID.`,n=`Enter your Project ID to continue. This browser tab remembers it until the tab is closed. To stop being asked, replace "${e}" in your code with the ID.`,i=`${r}
215
+ `,c=new Blob([u],{type:"application/javascript"});Pe=new Worker(URL.createObjectURL(c)),Pe.onmessage=f=>{a.readyState===1&&a.send(JSON.stringify({action:"keepAlive"}));},s(a);},a.onmessage=async u=>{let c="";try{c=JSON.parse(decodeURI(u.data)),this.log("socket onmessage",c);}catch{return}let f;switch(!0){case !!c?.["#message"]:f="message";break;case !!c?.["#private"]:f="private";break;case !!c?.["#notice"]:f="notice";break;case !!c?.["#rtc"]:f="rtc";break;case !!c?.["#error"]:f="error";break;case !!c?.["#ice"]:f="ice";break}if(!f){if(c?.requestId&&c?.connectionId&&Ge.length){let d=Ge.splice(0);for(let g of d)g(null);}return}if(f==="ice"){let d=eo(c["#ice"]);d&&(Ke={...d,at:Math.floor(Date.now()/1e3)});let g=Ge.splice(0);for(let h of g)h(c["#ice"]);return}let p={type:f,message:c?.["#rtc"]||c?.["#message"]||c?.["#private"]||c?.["#notice"]||c?.["#error"]||null,sender:c?.["#user_id"]||null,sender_cid:c?.["#scid"]?"cid:"+c["#scid"]:null,sender_rid:c?.["#srid"]||null,code:c?.["#code"]||null};if(f==="notice")e(p);else if(f==="rtc"){if(p.sender!==this.user.user_id){let d=p.message;if(d.hungup){re[p.sender_cid]&&(re[p.sender_cid](!1),delete re[p.sender_cid]),he[p.sender_cid]&&delete he[p.sender_cid],O?.[p.sender_cid]?me.bind(this)({cid:p.sender_cid}):Ws(p.sender_cid),p.type="rtc:closed",e(p);return}d.candidate&&Be(p.sender_cid,()=>zt.bind(this)(d.candidate,p.sender_cid)).catch(g=>this.log("rtc candidate",g)),d.sdpoffer&&(O?.[p.sender_cid]?Be(p.sender_cid,()=>Qt.bind(this)(d,p.sender_cid)).catch(g=>this.log("rtc offer",g)):(Be(p.sender_cid,()=>Qt.bind(this)(d,p.sender_cid)).catch(g=>this.log("rtc offer",g)),he[p.sender_cid]||(he[p.sender_cid]=p.sender_cid,delete p.message,p.meta=d.meta&&typeof d.meta=="object"&&!Array.isArray(d.meta)?d.meta:{},p.sources=d.sources&&typeof d.sources=="object"?Array.from(new Set(Object.values(d.sources).filter(g=>typeof g=="string"))):[],p.connectRTC=Js.bind(this)(p),p.type="rtc:incoming",p.hangup=(()=>{O[p.sender_cid]?me.bind(this)({cid:p.sender_cid}):he[p.sender_cid]&&(delete he[p.sender_cid],a.send(JSON.stringify({action:"rtc",uid:p.sender_cid,content:{hungup:this.user.user_id},token:this.session.accessToken.jwtToken})));}).bind(this),e(p)))),d.pickup&&re[p.sender_cid]&&(re[p.sender_cid](!0),delete re[p.sender_cid]),d.sdpanswer&&Be(p.sender_cid,()=>Gs.bind(this)(d,p.sender_cid)).catch(g=>this.log("rtc answer",g));}}else e(p);},a.onclose=()=>{mt?(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."}),He++,He<3?(this.log("realtime onclose","Reconnecting to WebSocket server..."+He),e({type:"reconnect",message:"Reconnecting to WebSocket server..."+He}),We.bind(this)(e,3e3,"reconnect")):(this.log("realtime onclose","Max reconnection attempts reached."),e({type:"error",message:"Skapi: Max reconnection attempts reached."})));},a.onerror=()=>{this.log("realtime onerror","WebSocket connection error."),e({type:"error",message:"Skapi: WebSocket connection error."});};}catch(a){o(a);}},t);}),n.value=this.__socket,this.__socket}async function ro(e,t,r){if(typeof window>"u"||window._runningInNodeJS)throw new l("WebSocket is not supported in Node.js environment.",{code:"NOT_SUPPORTED"});let n=this.__socket?await this.__socket:this.__socket;if(!n)throw new l("No realtime connection. Execute connectRealtime() before this method.",{code:"INVALID_REQUEST"});if(!t)throw new l("No recipient.",{code:"INVALID_REQUEST"});await qe.bind(this)(),e=$(e).data;let s="";if(r&&(r=y.Params(r,{config:{always:"boolean"},title:"string",body:"string"},["title","body"]),s=JSON.stringify({title:r.title,body:r.body}),new Blob([s]).size>3072))throw new l("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:s,notificationConfig:r?.config||{},token:`IdT:${this.service}:${this.owner}:`+(this.bearerToken||this.session?.idToken?.jwtToken||"null")}));}catch(i){if(this.log("postRealtime:err",{err:i}),Te!==t)throw new l(`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:s,notificationConfig:r?.config||{},token:`IdT:${this.service}:${this.owner}:`+(this.bearerToken||this.session?.idToken?.jwtToken||"null")}));}return {type:"success",message:"Message sent."}}throw new l("Realtime connection is not open. Try reconnecting with connectRealtime().",{code:"INVALID_REQUEST"})}async function Qe(e){if(typeof window>"u"||window._runningInNodeJS)throw new l("WebSocket is not supported in Node.js environment.",{code:"NOT_SUPPORTED"});let t=this.__socket?await this.__socket:this.__socket;if(!t)throw new l("No realtime connection. Execute connectRealtime() before this method.",{code:"INVALID_REQUEST"});await qe.bind(this)(),e=$(e,{nullIfEmpty:true}).data;let{group:r=null}=e;if(!r&&!Te)return {type:"success",message:"Left realtime message group."};if(r!==null&&typeof r!="string")throw new l('"group" must be a string | null.',{code:"INVALID_PARAMETER"});return t.readyState===1&&t.send(JSON.stringify({action:"joinRoom",rid:r,token:this.session.accessToken.jwtToken})),Te=r,{type:"success",message:r?`Joined realtime message group: "${r}".`:"Left realtime message group."}}async function no(e,t){e=y.Params(e,{user_id:n=>y.UserId(n,'User ID in "user_id"'),group:["string",()=>{if(!Te)throw new l('No group has been joined. Otherwise "group" is required.',{code:"INVALID_REQUEST"});return Te}]});let r=await k.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 io(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 l('"value" must be a number.',{code:"INVALID_PARAMETER"});if(e.searchFor==="group"&&typeof e.value!="string")throw new l('"value" must be a string.',{code:"INVALID_PARAMETER"});if(e.hasOwnProperty("range")&&typeof e.range!=typeof e.value)throw new l(`"range" must be a ${typeof e.value}.`,{code:"INVALID_PARAMETER"});let r=await k.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 oc=typeof FormData<"u",ao=typeof HTMLFormElement<"u",lo=typeof SubmitEvent<"u",_e={},yt={},se={};function bt(e){return Object.freeze({id:e,status:"stopped"})}function rn(e){return !!e&&typeof e=="object"&&e.status==="stopped"}var co=3;function uo(e,t,r){let n=false,s=Array.isArray(e?.chunks)?e.chunks.slice():[];s.sort((i,o)=>(i?.seq||0)-(o?.seq||0));for(let i of s)if(!(!i||typeof i.seq!="number"||i.seq<=t.seq)&&(t.seq=i.seq,n=true,r&&typeof i.txt=="string"&&i.txt!==""))try{r(i.txt,i.seq,"poll");}catch(o){console.error(o);}return typeof e?.last_seq=="number"&&e.last_seq>t.seq&&(t.seq=e.last_seq,n=true),n}var ac=2e3,fo=5e3,lc=2e3,cc=5,uc=1500,Yt=null;function po(e,t,r){let n=new Map,s=false,i=false,o=0,a={socket:0,poll:0},u=(d,g,h)=>{if(e.seq=d,!(!t||typeof g!="string"||g===""))try{t(g,d,h);}catch(m){console.error(m);}},c=()=>{for(let d of Array.from(n.keys()))d<=e.seq&&n.delete(d);for(;;){let d=e.seq+1;if(!n.has(d))break;let g=n.get(d);n.delete(d),u(d,g.txt,g.via);}};return {cursor:e,open:()=>{s||i||(s=true,c());},fromPoll:d=>{if(i)return false;let g=e.seq,h=e.seq,m=Array.isArray(d?.chunks)?d.chunks:[];for(let b of m){if(!b||typeof b.seq!="number"||b.seq<=e.seq)continue;let E=!n.has(b.seq);E&&(a.poll++,r&&a.poll===1&&r("poll",b.seq)),n.set(b.seq,{txt:typeof b.txt=="string"?b.txt:"",via:E?"poll":n.get(b.seq).via}),b.seq>h&&(h=b.seq);}typeof d?.last_seq=="number"&&d.last_seq>h&&(h=d.last_seq);let _=Array.from(n.keys()).sort((b,E)=>b-E);for(let b of _){if(b<=e.seq){n.delete(b);continue}if(b>h)break;let E=n.get(b);n.delete(b),u(b,E.txt,E.via);}return h>e.seq&&(e.seq=h),c(),e.seq>g},fromSocket:(d,g)=>{i||typeof d!="number"||!Number.isFinite(d)||(o=Date.now(),!(d<=e.seq)&&(!n.has(d)&&n.size>=lc||(n.has(d)||(a.socket++,r&&a.socket===1&&r("socket",d)),n.set(d,{txt:typeof g=="string"?g:"",via:n.has(d)?n.get(d).via:"socket"}),s&&c())));},warm:()=>o!==0&&Date.now()-o<ac,stats:()=>({socket:a.socket,poll:a.poll}),close:()=>{i=true,n.clear();}}}function go(e){if(!this||!this.__network_logs)return {onTransport:void 0,done:()=>{}};let t=Date.now(),r=false;return {onTransport:(n,s)=>{console.log(`%cSKAPI: stream chunk arrived over ${n==="socket"?"WEBSOCKET":"POLL"}`,`color: ${n==="socket"?"green":"orange"};`,{id:e,first_seq:s,after_ms:Date.now()-t});},done:n=>{if(r||!n)return;r=true;let s=n.stats();console.log("%cSKAPI: stream transport","color: blue;",{id:e,over_websocket:s.socket,over_poll:s.poll,took_ms:Date.now()-t});}}}function ho(e,t){let r={stop:()=>{}};if(typeof window>"u"||window._runningInNodeJS||Yt)return r;let n={stopped:false,socket:null,opened:null,joined:false,attempts:0,unavailable:false};Yt=n;let s=c=>{if(n.stopped)return;let f=c?.data;if(typeof f!="string")return;let p=null;try{p=JSON.parse(f);}catch{try{p=JSON.parse(decodeURI(f));}catch{return}}let d=p?.["#message"];if(d==null)return;if(typeof d=="string")try{d=JSON.parse(d);}catch{return}if(typeof d!="object")return;let g=p?.["#srid"];if(typeof g=="string"&&g!==e)return;let h=d.seq;typeof h=="string"&&h!==""&&(h=Number(h)),t.fromSocket(h,d.txt);},i=()=>{if(n.socket){try{n.socket.removeEventListener("message",s);}catch{}try{n.socket.removeEventListener("close",a);}catch{}n.socket=null;}},o=async()=>{let c=n.opened,f=n.joined;if(n.opened=null,n.joined=false,i(),!(!f&&!c))try{let p=this.__socket?await this.__socket:null;if(c&&p===c){await Jt.bind(this)();return}f&&p&&to()===room&&await Qe.bind(this)({group:null});}catch{}},a=()=>{n.stopped||(i(),!n.unavailable&&(n.attempts>=cc||(n.attempts+=1,setTimeout(()=>{n.stopped||u();},uc))));},u=async()=>{try{let c=this.__socket?await this.__socket:null;if(n.stopped){o();return}if(!c){if(!this.session){n.unavailable=!0,o();return}if(await We.bind(this)(()=>{},0),c=this.__socket?await this.__socket:null,n.stopped){o();return}c&&!n.opened&&(n.opened=c);}if(!c||c.readyState!==1)return;if(c.addEventListener("message",s),c.addEventListener("close",a),n.socket=c,!n.joined&&(await Qe.bind(this)({group:e}),n.joined=!0,n.stopped)){o();return}}catch{}};return u(),{stop:()=>{n.stopped||(n.stopped=true,Yt===n&&(Yt=null),o());}}}function mo(e){return e?.status==="running"||e?.status==="pending"}function yo(e){return !!e&&typeof e=="object"&&!Array.isArray(e)&&typeof e.status=="string"&&typeof e.id=="string"&&"in_queue"in e}function bo(e,t,r,n){if(!e||typeof e!="string")throw new l('"requestId" should be type: <string>.',{code:"INVALID_PARAMETER"});if(e.includes("#"))return e;if(!t||typeof t!="string"||!r||typeof r!="string")throw new l('"url" and "method" are required to address a request by its short id.',{code:"INVALID_PARAMETER"});return y.Url(t),`[${r.toUpperCase()}]${t.toLowerCase()}#${n}:${e}`}function _o({id:e,auth:t,service:r,owner:n,latency:s=1e3,queue:i,seedExecuted:o,onResponse:a,onError:u,onStream:c,realtimeGroup:f}){if(typeof s!="number")throw new l('"latency" should be a number.',{code:"INVALID_PARAMETER"});if(s<0)throw new l('"latency" should be a non-negative number.',{code:"INVALID_PARAMETER"});i&&!_e?.[i]&&(_e[i]=new oo__default.default({breakWhenError:false,batchSize:1}));let p={stop:null,aborted:false,queue:i};se[e]=p;let d=null,g=()=>{se[e]===p&&delete se[e];},h=()=>new Promise((_,b)=>{let E=false;if(p.aborted){g(),_(bt(e));return}let w={seq:0},I=go.call(this,e),R=c&&f?po(w,c,I.onTransport):null,N=R?ho.call(this,f,R):null,U=()=>{I.done(R),N&&N.stop(),R&&R.close();};d=U;let D=0,v=false,C=0,x=typeof o=="number"&&o>0?o:void 0,M=async()=>{if(!(E||v)&&!(R&&R.warm()&&Date.now()-D<fo)){v=true;try{for(;;){let ue={id:e,service:r,owner:n};c&&(ue.since=w.seq),D=Date.now();let F=await k.bind(this)("csr-poll",ue,{auth:t});if(E)return;let Z=R?R.fromPoll(F):c?uo(F,w,c):!1;R&&R.open();let Et=mo(F);if(typeof F?.executed=="number"&&F.executed>0&&(x=F.executed),F?.more&&Z){C=0;continue}if(Et){C=0;return}if(C=F?.more?C+1:0,F?.more&&C<co)return;E=!0,a&&a(F,x!==void 0?{executed:x}:void 0),clearInterval(ye),U(),g(),_(F);return}}catch(ue){if(E)return;E=true,u&&u(ue),clearInterval(ye),U(),g(),b(ue);}finally{v=false;}}},ye=setInterval(M,s);R&&M(),p.stop=()=>{E||(E=true,clearInterval(ye),U(),g(),_(bt(e)));};}),m=()=>{let _=se[e];_&&(_.stop?_.stop():(_.aborted=true,delete se[e]));};if(i){let _=new Promise((b,E)=>{let w=false,I=_e[i].add([async()=>{try{let R=await h();return w||(w=!0,b(R)),R}catch(R){throw w||(w=true,E(R)),R}}])[0];yt[e]=I,p.stop=()=>{if(!w){p.aborted=true,d&&d();try{_e[i]&&_e[i].remove(yt[e]);}catch{}delete yt[e],g(),w=true,b(bt(e));}};});return Object.assign(_,{stop:m})}else return Object.assign(h(),{stop:m})}function Zt(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 se)se[n]?.queue===e.queue&&r.push(n);else for(let n in se)r.push(n);for(let n of r){let s=se[n];s&&(s.stop?s.stop():(s.aborted=true,delete se[n]),t+=1);}return t}function nn(e,t){if(!e.queue)throw new l('"queue" is required.',{code:"INVALID_PARAMETER"});let r=()=>k.bind(this)("csr-poll",{service:e.service||this.service,owner:e.owner||this.owner,queue:e.queue+":"},{auth:true});return this.__projectIdInput?this.__projectIdInput.then(r):r()}function dc(e){if(typeof Buffer<"u"&&typeof Buffer.from=="function")return Buffer.from(e).toString("base64");if(typeof btoa=="function"){let t="";for(let n=0;n<e.length;n+=32768)t+=String.fromCharCode.apply(null,Array.from(e.subarray(n,n+32768)));return btoa(t)}throw new l("No base64 encoder available in this environment.",{code:"NOT_SUPPORTED"})}var so=2*1024*1024-64*1024;function Xt(e){return typeof File<"u"&&e instanceof File||typeof Blob<"u"&&e instanceof Blob}function tn(e){if(Array.isArray(e)){let t=[];for(let r of e)Xt(r)||t.push(tn(r));return t}if(e&&typeof e=="object"&&!Xt(e)){let t=Object.getPrototypeOf(e);if(t!==Object.prototype&&t!==null)return e;let r={};for(let n in e)Xt(e[n])||(r[n]=tn(e[n]));return r}return e}function fc(e){if(e==null)return null;let t=$(e)?.data;return !t||typeof t!="object"||Array.isArray(t)?null:tn(t)}function wo(e,t,r){if(r!==void 0){if(Array.isArray(r)){for(let n of r)wo(e,t,n);return}if(Xt(r)){e.append(t,r);return}if(r===null){e.append(t,"");return}if(typeof r=="object"){e.append(t,JSON.stringify(r));return}e.append(t,String(r));}}async function pc(e){if(e==null)throw new l('"multipart": true needs a form body in the first argument.',{code:"INVALID_PARAMETER"});if(typeof FormData>"u"||typeof Response>"u")throw new l('"multipart": true is not available in this environment.',{code:"NOT_SUPPORTED"});let t;if(lo&&e instanceof SubmitEvent)t=new FormData(e.target);else if(ao&&e instanceof HTMLFormElement)t=new FormData(e);else if(e instanceof FormData)t=e;else if(typeof e=="object"&&!Array.isArray(e)){t=new FormData;for(let i in e)wo(t,i,e[i]);}else throw new l('"form" should be a submit event, a form element, FormData, or an object.',{code:"INVALID_PARAMETER"});let r=new Response(t),n=r.headers.get("content-type"),s=dc(new Uint8Array(await r.arrayBuffer()));if(s.length>so)throw new l(`Multipart body is too large: ${s.length} bytes once base64 encoded, and the limit is ${so}. Upload the file first and send its url instead.`,{code:"INVALID_PARAMETER"});return {body_b64:s,body_content_type:n}}function gc(e){if(e!=null){if(typeof e=="boolean")return e;if(typeof e=="object"&&!Array.isArray(e))return {user:!!e.user,service:!!e.service};throw new l('"skapiHeaders" should be type: <boolean> or { user?: boolean; service?: boolean }.',{code:"INVALID_PARAMETER"})}}function hc(e){if(!(!e||typeof e!="object")){for(let t in e)if(typeof t=="string"&&t.toLowerCase().indexOf("x-skapi-")===0)throw new l(`"headers" cannot set "${t}": the "x-skapi-" prefix is reserved. Use "skapiHeaders" to tell the destination who the caller is.`,{code:"INVALID_PARAMETER"})}}async function Eo(e,t){let r=false,n=!!(e?.secretName||e?.clientSecretName),s=t?.signal;if(s?.aborted)throw new l('"signal" was already aborted.',{code:"INVALID_REQUEST"});if(typeof e.poll=="number"&&e.poll<0)throw new l('"poll" should be a non-negative number.',{code:"INVALID_PARAMETER"});let i=e?.onResponse,o=e?.onError,a=e?.onStream,u=typeof e.poll=="number"?e.poll:e.poll?1e3:0;delete e.poll,(u||e.stream)&&!e.queue&&(e.queue=(this.__user?.user_id||"anonymous")+"-"+Se());let c=(d,g=new WeakSet)=>{if(!(r||!d||typeof d!="object"||g.has(d))){g.add(d);for(let h in d){let m=d[h];if(typeof m=="string"){if(m.includes("$CLIENT_SECRET")){r=true;return}}else m&&typeof m=="object"&&c(m,g);}}};if(e=y.Params(e,{url:d=>{if(!d||typeof d!="string")throw new l('"url" should be type: <string>.',{code:"INVALID_PARAMETER"});return y.Url(d),d.includes("$CLIENT_SECRET")&&(r=true),d},secretName:"string",clientSecretName:"string",method:d=>{if(d&&typeof d!="string")throw new l('"method" should be one of "GET", "POST", "PUT", "PATCH", "DELETE" or "HEAD".',{code:"INVALID_PARAMETER"});let g=d.toLowerCase();if(g!=="get"&&g!=="post"&&g!=="delete"&&g!=="put"&&g!=="patch"&&g!=="head")throw new l('"method" should be one of "GET", "POST", "PUT", "PATCH", "DELETE" or "HEAD".',{code:"INVALID_PARAMETER"});return g},stream:d=>{if(d!=null&&typeof d!="boolean")throw new l('"stream" should be type: <boolean>.',{code:"INVALID_PARAMETER"});return !!d},realtime:d=>{if(d!=null&&typeof d!="boolean")throw new l('"realtime" should be type: <boolean>.',{code:"INVALID_PARAMETER"});return !!d},headers:d=>{if(d&&typeof d!="object")throw new l('"headers" should be type: <object>.',{code:"INVALID_PARAMETER"});return hc(d),c(d),d},skapiHeaders:d=>gc(d),data:d=>{if(d&&typeof d!="object")throw new l('"data" should be type: <object>.',{code:"INVALID_PARAMETER"});return c(d),d},params:d=>{if(d&&typeof d!="object")throw new l('"params" should be type: <object>.',{code:"INVALID_PARAMETER"});return c(d),d},body_b64:"string",body_content_type:"string",expires:"number",queue:"string"},t?.requireSecretName?["clientSecretName","method","url"]:["method","url"]),e.realtime&&!e.stream)throw new l('"realtime" requires "stream": true.',{code:"INVALID_PARAMETER"});if(e.body_b64&&e.data)throw new l('"data" cannot be sent with "multipart": true.',{code:"INVALID_PARAMETER"});n&&!r&&(delete e.secretName,delete e.clientSecretName),await this.__connection;let f=!!this.__user,p=()=>k.bind(this)("csr",e,{auth:f,tokenHeaders:{accessToken:!!f}}).then(d=>{if(d.status==="running"||d.status==="pending"){let g=`[${e.method.toUpperCase()}]${e.url.toLowerCase()}`,h=e.service||this.service,m=e.owner||this.owner,_=`${g}#${h}:${d.id}`;if(s){let b=()=>{Zt.call(this,{id:_});};s.aborted?b():s.addEventListener("abort",b,{once:true});}Object.assign(d,{poll:b=>_o.call(this,{id:_,auth:f,service:h,owner:m,latency:b?.latency||1e3,queue:e?.queue,onResponse:i,onError:o,onStream:b?.onStream||a,realtimeGroup:d?.realtime_group})});}return i?i(d):d}).catch(d=>{if(o)return o(d);throw d});if(e?.queue){let d="base:"+e.queue;return _e?.[d]||(_e[d]=new oo__default.default({breakWhenError:false,batchSize:1})),new Promise((g,h)=>{_e[d].add([async()=>{try{let m=await p();if(u>0){let _=m.poll({latency:u});return s&&(s.aborted?_.stop():s.addEventListener("abort",()=>_.stop(),{once:!0})),g(_),_}return g(m),m}catch(m){throw h(m),m}}]);})}else return p()}async function Ro(e,t){if(!t||typeof t!="object")throw new l('"options" is required in the second argument.',{code:"INVALID_PARAMETER"});if(t.apiKeyHeader!==void 0||t.apiKeyScheme!==void 0)throw new l('"apiKeyHeader" and "apiKeyScheme" are no longer supported. Store the key as a client secret, name it with "secretName", and put "$CLIENT_SECRET" where the key goes.',{code:"INVALID_PARAMETER"});if(t.multipart!==void 0&&t.multipart!==null&&typeof t.multipart!="boolean")throw new l('"multipart" should be type: <boolean>.',{code:"INVALID_PARAMETER"});let r=t.responseType;if(r!=null){if(r==="response")throw new l(`"responseType": "response" is not available here. The request is relayed from the server and what comes back is the stored answer, not a live Response; the destination's status code is the "status_code" of the row forwardRequestHistory lists.`,{code:"INVALID_PARAMETER"});if(r!=="json"&&r!=="text")throw new l('"responseType" should be either "json" or "text".',{code:"INVALID_PARAMETER"})}let n=t.method||"POST",s=typeof n=="string"?n.toLowerCase():"",i=s==="get"||s==="delete"||s==="head"?"params":"data",o={url:t.url,method:n};if(t.secretName!==void 0&&(o.secretName=t.secretName),t.headers!==void 0&&(o.headers=t.headers),t.data!==void 0&&(o.data=t.data),t.params!==void 0&&(o.params=t.params),t.skapiHeaders!==void 0&&(o.skapiHeaders=t.skapiHeaders),t.service!==void 0&&(o.service=t.service),t.owner!==void 0&&(o.owner=t.owner),t.queue!==void 0&&(o.queue=t.queue),t.expires!==void 0&&(o.expires=t.expires),t.stream!==void 0&&(o.stream=t.stream),t.realtime!==void 0&&(o.realtime=t.realtime),t.poll!==void 0&&(o.poll=t.poll),t.onStream!==void 0&&(o.onStream=t.onStream),t.onResponse!==void 0&&(o.onResponse=t.onResponse),t.onError!==void 0&&(o.onError=t.onError),t.multipart){if(t.data!==void 0&&t.data!==null)throw new l('"data" cannot be sent with "multipart": true. The form itself is the body.',{code:"INVALID_PARAMETER"});let u=await pc(e);o.body_b64=u.body_b64,o.body_content_type=u.body_content_type;}else {let u=fc(e);u&&Object.keys(u).length&&(o[i]=Object.assign({},u,o[i]||{}));}let a=Eo.call(this,o,{signal:t.signal});return r?a.then(u=>{if(yo(u)||rn(u))return u;if(r==="text")return typeof u=="string"?u:JSON.stringify(u);if(typeof u=="string")try{return JSON.parse(u)}catch{return u}return u}):a}async function Ao(e){return Eo.call(this,e,{requireSecretName:true})}async function sn(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","PUT","PATCH","DELETE","HEAD"],queue:"string",status:["pending","running","resolved","failed"],compact:"boolean",queue_exact:"boolean",queue_exclude:"string"},["url","method"]);let s=!!this.__user,i=`[${e.method.toUpperCase()}]${e.url.toLowerCase()}#${r}:`,o={id:i,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(u=>{o[u]||delete o[u];}),o.queue&&(o.id_prefix=o.id,delete o.id);let a=await k.bind(this)("csr-poll",o,{auth:s,fetchOptions:t});return a.list=a.list.map(u=>{let c={id:u.id,status_code:u.rslv?.status_code||null,response_body:u.rslv?.body||u.rslv?.truncated||null,error:u?.err,created:u?.stmp,updated:u?.utmp,executed:typeof u?.att=="number"?u.att*1e3:void 0,responded:typeof u?.rtmp=="number"?u.rtmp:void 0,request_body:u?.reqbdy,expires:u?.expt,status:u.stts,queue_name:u?.qid,request_text:u?.reqtxt,response_text:u?.rslvtxt,response_complete_marker:u?.rslvmk!=null?!!u.rslvmk:void 0,compact:u?.cmpct?true:void 0};for(let f in c)c[f]===void 0&&delete c[f];return (c.status==="running"||c.status==="pending")&&(c.poll=f=>_o.call(this,{id:i+c.id,auth:s,service:r,owner:n,latency:f?.latency||1e3,queue:u?.qid,seedExecuted:c.executed,onResponse:f?.onResponse,onError:f?.onError,onStream:f?.onStream})),c}),a}async function on(e){await this.__connection,e=y.Params(e,{url:"string",method:["GET","POST","PUT","PATCH","DELETE","HEAD"],id:"string",queue:"string"},["url","method","id"]);let t=e?.service||this.service,r=e?.owner||this.owner,n=!!this.__user,s=`[${e.method.toUpperCase()}]${e.url.toLowerCase()}#${t}`,i=e.id,o=`${s}:${i}`,a=e?.queue;return a&&_e?.[a]&&(_e[a].remove(yt[o]),delete yt[o]),k.bind(this)("csr-cancel",{id:o,service:t,owner:r},{auth:n})}function an(e,t){let r=typeof t?.poll=="number"?t.poll:1e3;if(!Number.isFinite(r)||r<0)throw new l('"poll" should be a non-negative number.',{code:"INVALID_PARAMETER"});if(!e||typeof e!="string")throw new l('"requestId" should be type: <string>.',{code:"INVALID_PARAMETER"});if(t?.since!==void 0&&typeof t.since!="number")throw new l('"since" should be a number.',{code:"INVALID_PARAMETER"});if(t?.realtimeGroup!==void 0&&t.realtimeGroup!==null&&typeof t.realtimeGroup!="string")throw new l('"realtimeGroup" should be type: <string>.',{code:"INVALID_PARAMETER"});let n=typeof t?.since=="number"&&t.since>0?t.since:0,s=t?.onStream,i=t?.onResponse,o=t?.onError,a={stopped:false,fullId:e,resolve:null},u=null,c={stop:null,aborted:false},f=()=>{se[a.fullId]===c&&delete se[a.fullId];},p=()=>{a.stopped||(a.stopped=true,u&&u(),f(),a.resolve&&a.resolve(bt(a.fullId)));};c.stop=p;let d=new Promise(async(g,h)=>{a.resolve=g;try{await this.__connection;let m=!!this.__user,_=t?.service||this.service,b=t?.owner||this.owner;if(a.fullId=bo(e,t?.url,t?.method,_),a.stopped){g(bt(a.fullId));return}se[a.fullId]=c;let E={seq:n},w=0,I=go.call(this,a.fullId),R=s&&t?.realtimeGroup?po(E,s,I.onTransport):null,N=R?ho.call(this,t.realtimeGroup,R):null,U=()=>{I.done(R),N&&N.stop(),R&&R.close();};for(u=U;;){let D=await k.bind(this)("csr-poll",{id:a.fullId,service:_,owner:b,since:E.seq},{auth:m});if(a.stopped)return;if(!yo(D)){U(),f(),i&&i(D),g(D);return}let v=R?R.fromPoll(D):uo(D,E,s);R&&R.open();let C=mo(D);if(D.more&&v){w=0;continue}if(w=D.more?w+1:0,!C&&(!D.more||w>=co)){U(),f(),i&&i(D),g(D);return}if(await new Promise(x=>setTimeout(x,R&&R.warm()?Math.max(r,fo):r)),a.stopped)return}}catch(m){if(a.stopped)return;u&&u(),f(),o&&o(m),h(m);}});return Object.assign(d,{stop:p})}async function ln(e,t,r){await this.__connection;let n=r?.service||this.service,s=r?.owner||this.owner,i=!!this.__user,o=bo(e,r?.url,r?.method,n);return k.bind(this)("csr-finalize",{id:o,data:t,service:n,owner:s},{auth:i})}var To=an,Io=ln,ko=sn,Po=on,So=Zt,vo=nn;async function No(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 k.bind(this)("send-inquiry",e),"SUCCESS: Inquiry has been sent."}async function Do(e,t){if(await this.__connection,oc&&e instanceof FormData||ao&&e instanceof HTMLFormElement||lo&&e instanceof SubmitEvent){if(!t)throw new l("Url string as a second argument is required when form is passed.",{code:"INVALID_PARAMETER"});let n=$(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 k.bind(this)("post-secure",e,{auth:true})}async function Co(e,t){await this.__connection;let{auth:r=false,method:n="POST",bypassAwaitConnection:s=false,responseType:i,contentType:o,tokenHeaders:a,progress:u}=t||{};if(t=Object.assign({auth:r,method:n,bypassAwaitConnection:s,responseType:i,contentType:o,tokenHeaders:a},{fetchOptions:{progress:u}}),typeof e!="object"&&(o==="application/json"||o===void 0))throw new l('"data" should be type: <object>.',{code:"INVALID_PARAMETER"});return k.bind(this)("mock",e,t)}async function xo(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 l('"access_group" should be type number.',{code:"INVALID_PARAMETER"});if(n<0)throw new l('"access_group" should be zero or a positive number.',{code:"INVALID_PARAMETER"});if(n>this.__user.access_group)throw new l("User has no access.",{code:"INVALID_REQUEST"});return n}});let r=await k.bind(this)("get-feed",e,{auth:true,fetchOptions:t});return Array.isArray(r?.list)&&(r.list=await Promise.all(r.list.map(n=>De.bind(this)(n)))),r}function _t(e){if(e===this.__user.user_id)throw new l(`"user_id" cannot be the user's own ID.`,{code:"INVALID_PARAMETER"});return y.UserId(e,'"user_id"')}async function Uo(e,t){if(e=$(e,{ignoreEmpty:true}).data,e=y.Params(e,{subscriber:n=>y.UserId(n,'User ID in "subscriber"'),subscription:_t.bind(this),blocked:"boolean"}),!e.subscriber&&!e.subscription)throw new l('At least either "subscriber" or "subscription" should have a value.',{code:"INVALID_PARAMETER"});let r=await k.bind(this)("get-subscription",e,Object.assign({auth:true},{fetchOptions:t}));return r.list=r.list.map((n=>{let s={};if(n.sub){let i=n.sub.split("#");s.subscriber=i[2],s.subscription=i[0];}else s.subscriber=n.subscriber,s.subscription=n.subscription;return s.timestamp=n?.timestamp||n.stmp,s.blocked=n?.blocked||n.grp.substring(0,1)==="N",Object.assign(s,n.opt),s})),r}async function Oo(e){await this.__connection,e=y.Params(e,{user_id:_t.bind(this),get_feed:"boolean",get_notified:"boolean",get_email:s=>{if(s&&(!this.__user.email||!this.__user.email_verified))throw new l("User has no verified email address.",{code:"INVALID_REQUEST"});return !!s}},["user_id"]);let t={};for(let s of ["get_feed","get_notified","get_email"])typeof e[s]=="boolean"&&(t[s]=e[s]);let r=await k.bind(this)("subscription",{subscribe:e.user_id,option:t},{auth:true}),n={};if(r.sub){let s=r.sub.split("#");n.subscriber=s[2],n.subscription=s[0];}else n.subscriber=r.subscriber,n.subscription=r.subscription;return n.timestamp=r?.timestamp||r.stmp,n.blocked=r?.blocked||r.grp.substring(0,1)==="N",Object.assign(n,r.opt),n}async function Lo(e){await this.__connection;let{user_id:t}=y.Params(e,{user_id:_t.bind(this)},["user_id"]);return await k.bind(this)("subscription",{unsubscribe:t},{auth:true})}async function Mo(e){await this.__connection;let{user_id:t}=y.Params(e,{user_id:_t.bind(this)},["user_id"]);return await k.bind(this)("subscription",{block:t},{auth:true})}async function Fo(e){await this.__connection;let{user_id:t}=y.Params(e,{user_id:_t.bind(this)},["user_id"]);return await k.bind(this)("subscription",{unblock:t},{auth:true})}async function qo(e,t){await this.__connection;let r=await Y.bind(this)();if(e=y.Params(e||{},{user_id:o=>{if(o!==this.__user.user_id&&!r)throw new l("No access.",{code:"INVALID_REQUEST"});return o},group:o=>y.newsletterGroup(o,{allowNull:true}),email:o=>{if(typeof o!="string"||!o.trim())throw new l('"email" should be a non-empty string.',{code:"INVALID_PARAMETER"});if(o.trim().length>255)throw new l('"email" should be at most 255 characters.',{code:"INVALID_PARAMETER"});return o.trim().toLowerCase()}}),e.email!==void 0){if(e.user_id!==void 0&&e.user_id!==null)throw new l('"email" cannot be used with "user_id".',{code:"INVALID_PARAMETER"});if(e.group===void 0||e.group===null)throw new l('"group" is required to search by "email".',{code:"INVALID_PARAMETER"})}let n=await k.bind(this)("get-newsletter-subscription",e,{auth:true,fetchOptions:t||null}),s=n?.list||n,i=[];Array.isArray(s)||(s=[]);for(let o of s){let a=o.subt.split("#"),u=true;a[0].charAt(0)==="@"&&(u=false,a[0]=a[0].substring(1));let c=/^\d+$/.test(a[0])?parseInt(a[0]):a[0],f={timestamp:o.stmp,group:c,subscribed_email:a[1],active:u};typeof o.email_token=="string"&&o.email_token&&(f.subscriber_token=o.email_token),i.push(f);}return n?.list?(n.list=i,n):i}async function Vo(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:r=>y.newsletterGroup(r),redirect:r=>y.Url(r)},this.__user?["group"]:["email","group"]);return k.bind(this)(`subscribe-${this.__user?"":"public-"}newsletter`,t,{auth:!!this.__user})}async function jo(e){await this.__connection;let t=y.Params(e||{},{group:r=>y.newsletterGroup(r,{nameOnly:true}),restriction:r=>{if(typeof r!="number"||!Number.isInteger(r)||r<0||r>99)throw new l('"restriction" should be a number between 0 and 99.',{code:"INVALID_PARAMETER"});return r},name:r=>{if(typeof r!="string"||r.length>60)throw new l('"name" should be a string of 60 characters or less.',{code:"INVALID_PARAMETER"});return r}},["group"]);return k.bind(this)("register-newsletter-group",t,{auth:true})}async function $o(e){await this.__connection;let t=y.Params(e||{},{group:r=>y.newsletterGroup(r,{nameOnly:true})},["group"]);return k.bind(this)("delete-newsletter-group",t,{auth:true})}async function Bo(){return await this.__connection,k.bind(this)("newsletter-group-endpoint",null,{auth:true})}async function Ko(e){await this.__connection,e=y.Params(e,{group:r=>y.newsletterGroup(r,{allowNull:true})},["group"]);let t=Object.assign({action:"unsubscribe"},e);return k.bind(this)("subscribe-newsletter",t,{auth:true})}async function Ho(e,t){let r=await Y.bind(this)(),n={message_id:"string",timestamp:"number",read:"number",complaint:"number",subject:"string",bounced:"number"};e||(t=Object.assign({ascending:false},t||{})),e=$(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:u=>{if(typeof u!==n[e.searchFor])throw new l(`"value" type does not match the type of "${e.searchFor}" index.`,{code:"INVALID_PARAMETER"});if(typeof u=="string"&&!u)throw new l('"value" should not be empty string.',{code:"INVALID_PARAMETER"});return u},range:u=>{if(!e.hasOwnProperty("value")||typeof u!=typeof e.value)throw new l('"range" should match type of "value".',{code:"INVALID_PARAMETER"});return u},condition:[">",">=","=","<","<=","gt","gte","eq","lt","lte",()=>"="],group:u=>{let c=y.newsletterGroup(u);if(c===0)return 0;if(typeof c=="string")return c;if(!this.session)throw new l("User should be logged in.",{code:"INVALID_REQUEST"});if(u==="authorized")return 1;if(!r&&c>parseInt(this.user?.access_group||this.session?.idToken?.payload?.access_group))throw new l("User has no access.",{code:"INVALID_REQUEST"});return c}},["searchFor","value","group"]);let s=e.group===0||typeof e.group=="string"&&!this.__user?"get-public-newsletters":"get-newsletters",i=await k.bind(this)(s,e,Object.assign({method:"get",auth:s==="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",group:"grp",dry:"dry",sent:"sent"},a={message_id:"",timestamp:0,complaint:0,read:0,subject:"",bounced:"",url:"",delivered:0,group:e.group,dry:false,sent:0};return i.list=i.list.map(u=>{let c={};for(let f in o)c[f]=u[o[f]]||a[f];return c.bounced=String(c.bounced),c.dry=!!c.dry,c.sent||delete c.sent,c}),i}var ze="skapi:project_id";function Go(e){let t=e.trim().toLowerCase().replace(/^<|>$/g,"").replace(/[\s_\-.]+/g,"");return t==="serviceid"||t==="projectid"}function Wo(){try{return window.sessionStorage.getItem(ze)||null}catch{return null}}function Qo(e){try{window.sessionStorage.setItem(ze,e);}catch{}}function er(e){try{window.sessionStorage.getItem(ze)===e&&window.sessionStorage.removeItem(ze);}catch{}}function zo(){if(Q())return typeof window.prompt=="function";let e=xe("tty");return !!(e&&xe("readline")&&e.isatty(0)&&e.isatty(2))}function Jo(){return new l("Project ID is required.",{code:"INVALID_PARAMETER"})}var wt=null;function Yo(e,t){if(!wt){wt=Q()?mc(e,t):yc(e,t);let r=()=>{wt=null;};wt.then(r,r);}return wt}async function mc(e,t){await new Promise(o=>setTimeout(o,0));let r=`new Skapi() was given the placeholder "${e}" instead of your Project ID.`,n=`Enter your Project ID to continue. This browser tab remembers it until the tab is closed. To stop being asked, replace "${e}" in your code with the ID.`,s=`${r}
216
216
 
217
- ${n}`,s="";for(;;){let o=window.prompt(i,s);if(o===null)throw go();if(s=o.trim(),!s){i=`${r}
217
+ ${n}`,i="";for(;;){let o=window.prompt(s,i);if(o===null)throw Jo();if(i=o.trim(),!i){s=`${r}
218
218
 
219
- ${n}`;continue}try{return t(s),s}catch{i=`"${s}" is not a valid Project ID.
219
+ ${n}`;continue}try{return t(i),i}catch{s=`"${i}" is not a valid Project ID.
220
220
 
221
- ${n}`;}}}function Dl(e,t){let r=globalThis.process,n=ve("readline");return new Promise((i,s)=>{let o=n.createInterface({input:r.stdin,output:r.stderr,terminal:false}),l=false;o.on("close",()=>{l||(r.stderr.write(`
222
- `),s(go()));});let u=()=>o.question("Enter your Project ID: ",c=>{let f=c.trim();if(f)try{t(f),l=!0,o.close(),i(f);return}catch{r.stderr.write(`"${f}" is not a valid Project ID.
221
+ ${n}`;}}}function yc(e,t){let r=globalThis.process,n=xe("readline");return new Promise((s,i)=>{let o=n.createInterface({input:r.stdin,output:r.stderr,terminal:false}),a=false;o.on("close",()=>{a||(r.stderr.write(`
222
+ `),i(Jo()));});let u=()=>o.question("Enter your Project ID: ",c=>{let f=c.trim();if(f)try{t(f),a=!0,o.close(),s(f);return}catch{r.stderr.write(`"${f}" is not a valid Project ID.
223
223
  `);}u();});r.stderr.write(`new Skapi() was given the placeholder "${e}" instead of your Project ID.
224
224
  This process remembers the ID until it exits. To stop being asked, replace "${e}" in your code with the ID.
225
- `),u();})}async function mo(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 S.bind(this)("block-account",t,{auth:true})}async function yo(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 S.bind(this)("block-account",t,{auth:true})}async function bo(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 S.bind(this)("remove-account",t,{auth:true})}async function _o(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 S.bind(this)("admin-signup",n,{auth:true})}async function wo(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 S.bind(this)("admin-signup",n,{auth:true})}async function Eo(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 S.bind(this)("grant-access",e,{auth:true})}async function Ao(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 S.bind(this)("invitation-list",Object.assign({mode:"search"},e),{fetchOptions:t,auth:true});return n.list=n.list.map(i=>Ge(i.user)),n}async function Ro(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 S.bind(this)("invitation-list",Object.assign({mode:"cancel"},e),{auth:true})}async function To(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 S.bind(this)("invitation-list",Object.assign({mode:"resend"},e),{auth:true})}async function Io(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):"",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,await this.__connection,this.__user?.user_id&&t.user_id===this.__user.user_id)throw new a("Cannot modify attributes of the current user.",{code:"INVALID_REQUEST"});if(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"})}let s={attributes:t};return r&&n&&(s.service=r,s.owner=n),await S.bind(this)("admin-edit-profile",s,{auth:true})}async function Po(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 S.bind(this)("store-subscription",{endpoint:e.endpoint,keys:e.keys},{auth:true}),"SUCCESS: Subscribed to receive notifications."}async function So(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 S.bind(this)("delete-subscription",{endpoint:e.endpoint,keys:e.keys},{auth:true}),"SUCCESS: Unsubscribed from notifications."}async function ko(){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 S.bind(this)("get-vapid-public-key",null,{auth:true})}}async function vo(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}=j(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 S.bind(this)("push-notification",i,{auth:true}),"SUCCESS: Notification sent."}async function No(e){await this.__connection,e=y.Params(e,{spell:"string",name:"string",magic:r=>r},["spell","name"]);await S.bind(this)("castspell",e);return `The spell "${e.spell}" has been cast.`}async function Do(e){return await this.__connection,e=y.Params(e||{},{search:["spell","name",()=>"spell"],value:"string"}),await S.bind(this)("getspell",e)}async function xo(e){await this.__connection,e=y.Params(e,{message:"string",name:"string"},["message","name"]);let t=await S.bind(this)("dopamine",e,{auth:true}),r=t?.previous_message?.message,n=t?.previous_message?.name;if(H())r&&n&&window.alert(`${n} said: ${r}`),window.location.href=t.video;else return r&&n?`${n} said: ${r}
225
+ `),u();})}async function Xo(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 Y.bind(this)()){if(!this.__user)throw new l("User needs to login.",{code:"INVALID_REQUEST"});if(this.__user.access_group<90)throw new l("Invalid access.",{code:"INVALID_REQUEST"})}return await k.bind(this)("block-account",t,{auth:true})}async function Zo(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 Y.bind(this)()){if(!this.__user)throw new l("User needs to login.",{code:"INVALID_REQUEST"});if(this.__user.access_group<90)throw new l("Invalid access.",{code:"INVALID_REQUEST"})}return await k.bind(this)("block-account",t,{auth:true})}async function ea(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 Y.bind(this)()){if(!this.__user)throw new l("User needs to login.",{code:"INVALID_REQUEST"});if(this.__user.access_group<90)throw new l("Invalid access.",{code:"INVALID_REQUEST"})}return await k.bind(this)("remove-account",t,{auth:true})}async function ta(e,t){let r={email:i=>y.Email(i),password:i=>y.Password(i),name:"string",username:"string",gender:"string",address:i=>{if(!i)return "";if(typeof i=="string")return i;if(typeof i=="object")return JSON.stringify(i)},birthdate:i=>y.Birthdate(i),phone_number:i=>y.PhoneNumber(i),picture:i=>{if(i)return y.Url(i)},profile:i=>{if(i)return y.Url(i)},website:i=>{if(i)return y.Url(i)},nickname:"string",misc:"string",email_public:["boolean",()=>false],gender_public:["boolean",()=>false],address_public:["boolean",()=>false],birthdate_public:["boolean",()=>false],phone_number_public:["boolean",()=>false],openid_id:"string",access_group:i=>{try{typeof i=="string"&&(i=i==="admin"?99:parseInt(i));}catch{throw new l('"access_group" is invalid. Should be type <number>.',{code:"INVALID_PARAMETER"})}if(typeof i!="number"||i<1||i>100)throw new l('"access_group" is invalid. Should be type <number> of range 1~99',{code:"INVALID_PARAMETER"});return i}},n=y.Params(e,r,["email"]);if(t=y.Params(t,{confirmation_url:i=>{let o=i;if(typeof i=="string")o=y.Url(i);else throw new l('"options.confirmation_url" should be type: <string>.',{code:"INVALID_PARAMETER"});if(o&&!n.email)throw new l('"email" is required for signup confirmation.',{code:"INVALID_PARAMETER"});return o},email_subscription:i=>{if(typeof i!="boolean")throw new l('"options.email_subscription" should be type: <boolean>.',{code:"INVALID_PARAMETER"});if(!t?.confirmation_url)throw new l('"options.confirmation_url" is required for email subscription.',{code:"INVALID_PARAMETER"});return i},template:i=>{if(typeof i!="object"||!i.url||!i.subject)throw new l('"options.template" should be type: <object> with "url" and "subject".',{code:"INVALID_PARAMETER"});return {url:y.Url(i.url),subject:i.subject}}}),n.signup_confirmation=t?.confirmation_url||true,n.email_subscription=t?.email_subscription||false,n.template=t?.template||{},!await Y.bind(this)()){if(!this.__user)throw new l("User needs to login.",{code:"INVALID_REQUEST"});if(this.__user.access_group<90)throw new l("Invalid access.",{code:"INVALID_REQUEST"})}return await k.bind(this)("admin-signup",n,{auth:true})}async function ra(e){let t={email:i=>y.Email(i),password:i=>y.Password(i),openid_id:"string",name:"string",username:"string",gender:"string",address:i=>{if(!i)return "";if(typeof i=="string")return i;if(typeof i=="object")return JSON.stringify(i)},birthdate:i=>y.Birthdate(i),phone_number:i=>y.PhoneNumber(i),picture:i=>i?y.Url(i):"",profile:i=>i?y.Url(i):"",website:i=>i?y.Url(i):"",nickname:"string",misc:"string",email_public:["boolean",()=>false],gender_public:["boolean",()=>false],address_public:["boolean",()=>false],birthdate_public:["boolean",()=>false],phone_number_public:["boolean",()=>false],access_group:i=>{try{typeof i=="string"&&(i=parseInt(i));}catch{throw new l('"access_group" is invalid. Should be type <number>.',{code:"INVALID_PARAMETER"})}if(typeof i!="number"||i<1||i>100)throw new l('"access_group" is invalid. Should be type <number> of range 1~99',{code:"INVALID_PARAMETER"});return i}},r=["email","password"],n=y.Params(e,t,r);if(!await Y.bind(this)()){if(!this.__user)throw new l("User needs to login.",{code:"INVALID_REQUEST"});if(this.__user.access_group<90)throw new l("Invalid access.",{code:"INVALID_REQUEST"})}return await k.bind(this)("admin-signup",n,{auth:true})}async function na(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 l('"access_group" is invalid. Should be type <number>.',{code:"INVALID_PARAMETER"})}if(typeof r=="number"&&r>0&&r<100)return r;throw new l('"access_group" is invalid. Should be type <number> of range 1~99',{code:"INVALID_PARAMETER"})}},["user_id","access_group"]),!await Y.bind(this)()){if(!this.__user)throw new l("User needs to login.",{code:"INVALID_REQUEST"});if(this.__user.access_group<90)throw new l("Invalid access.",{code:"INVALID_REQUEST"})}return await k.bind(this)("grant-access",e,{auth:true})}async function ia(e,t){if(e=y.Params(e,{email:"string"}),!await Y.bind(this)()){if(!this.__user)throw new l("User needs to login.",{code:"INVALID_REQUEST"});if(this.__user.access_group<90)throw new l("Invalid access.",{code:"INVALID_REQUEST"})}let n=await k.bind(this)("invitation-list",Object.assign({mode:"search"},e),{fetchOptions:t,auth:true});return n.list=n.list.map(s=>Ye(s.user)),n}async function sa(e){if(e=y.Params(e,{email:r=>y.Email(r)},["email"]),!await Y.bind(this)()){if(!this.__user)throw new l("User needs to login.",{code:"INVALID_REQUEST"});if(this.__user.access_group<90)throw new l("Invalid access.",{code:"INVALID_REQUEST"})}return await k.bind(this)("invitation-list",Object.assign({mode:"cancel"},e),{auth:true})}async function oa(e){if(e=y.Params(e,{email:r=>y.Email(r)},["email"]),!await Y.bind(this)()){if(!this.__user)throw new l("User needs to login.",{code:"INVALID_REQUEST"});if(this.__user.access_group<90)throw new l("Invalid access.",{code:"INVALID_REQUEST"})}return await k.bind(this)("invitation-list",Object.assign({mode:"resend"},e),{auth:true})}async function aa(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):"",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,await this.__connection,this.__user?.user_id&&t.user_id===this.__user.user_id)throw new l("Cannot modify attributes of the current user.",{code:"INVALID_REQUEST"});if(Object.keys(t).filter(o=>o!=="user_id"&&t[o]!==void 0).length===0)throw new l("At least one attribute to update is required.",{code:"INVALID_PARAMETER"});if(!await Y.bind(this)()){if(!this.__user)throw new l("User needs to login.",{code:"INVALID_REQUEST"});if(this.__user.access_group<90)throw new l("Invalid access.",{code:"INVALID_REQUEST"})}let i={attributes:t};return r&&n&&(i.service=r,i.owner=n),await k.bind(this)("admin-edit-profile",i,{auth:true})}async function la(e){if(typeof window>"u"||window._runningInNodeJS)throw new l("Push Notifications are not supported in Node.js environment.",{code:"NOT_SUPPORTED"});if(await this.__connection,!e.endpoint)throw new l("Missing parameter: endpoint",{code:"INVALID_PARAMETER"});if(!e.keys||!e.keys.p256dh||!e.keys.auth)throw new l("Missing parameter: keys.p256dh or keys.auth",{code:"INVALID_PARAMETER"});return await k.bind(this)("store-subscription",{endpoint:e.endpoint,keys:e.keys},{auth:true}),"SUCCESS: Subscribed to receive notifications."}async function ca(e){if(typeof window>"u"||window._runningInNodeJS)throw new l("Push Notifications are not supported in Node.js environment.",{code:"NOT_SUPPORTED"});if(await this.__connection,!e.endpoint)throw new l("Missing parameter: endpoint",{code:"INVALID_PARAMETER"});if(!e.keys||!e.keys.p256dh||!e.keys.auth)throw new l("Missing parameter: keys.p256dh or keys.auth",{code:"INVALID_PARAMETER"});return await k.bind(this)("delete-subscription",{endpoint:e.endpoint,keys:e.keys},{auth:true}),"SUCCESS: Unsubscribed from notifications."}async function ua(){if(typeof window>"u"||window._runningInNodeJS)throw new l("Push Notifications are not supported in Node.js environment.",{code:"NOT_SUPPORTED"});return await this.__connection,{VAPIDPublicKey:await k.bind(this)("get-vapid-public-key",null,{auth:true})}}async function da(e,t){if(typeof window>"u"||window._runningInNodeJS)throw new l("Push Notifications are not supported in Node.js environment.",{code:"NOT_SUPPORTED"});await this.__connection;let{title:r,body:n}=$(e||{},{nullIfEmpty:true}).data;if(!r)throw new l("Missing parameter: message title",{code:"INVALID_PARAMETER"});if(!n)throw new l("Missing parameter: message body",{code:"INVALID_PARAMETER"});let s={title:r,body:n};return t?(typeof t=="string"&&(t=[t]),s.user_ids=t):s.user_ids="all_users",await k.bind(this)("push-notification",s,{auth:true}),"SUCCESS: Notification sent."}async function fa(e){await this.__connection,e=y.Params(e,{spell:"string",name:"string",magic:r=>r},["spell","name"]);await k.bind(this)("castspell",e);return `The spell "${e.spell}" has been cast.`}async function pa(e){return await this.__connection,e=y.Params(e||{},{search:["spell","name",()=>"spell"],value:"string"}),await k.bind(this)("getspell",e)}async function ga(e){await this.__connection,e=y.Params(e,{message:"string",name:"string"},["message","name"]);let t=await k.bind(this)("dopamine",e,{auth:true}),r=t?.previous_message?.message,n=t?.previous_message?.name;if(Q())r&&n&&window.alert(`${n} said: ${r}`),window.location.href=t.video;else return r&&n?`${n} said: ${r}
226
226
  Watch the video here: ${t.video}`:`Your message has been uploaded for future generations to receive.
227
- Watch the video here: ${t.video}`}var T=class{constructor(t,r,n,i){this.__version="2.2.11";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=50;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:Z,generateRandom:Te,toBase62:on,fromBase62:se,decodeProjectId:Zt,formatServiceId:er,extractFormData:j,terminatePendingRequests:Li,request:(t,r,n)=>S.bind(this)(t,r,n,{ignoreService:true})};this.__projectIdInput=null;this.__network_logs=false;this.__endpoint_version="v2";this.__public_identifier="";this.bearerToken="";this.registerTicket=fi.bind(this);this.unregisterTicket=pi.bind(this);if(!t||typeof t!="string")throw this._alert("Service ID is required."),new a("Service ID is required.",{code:"INVALID_PARAMETER"});if(co(t)){let o=uo(),l=null;if(o)try{l=this._resolveProject(o,r,n,i);}catch{Ht(o);}if(l)H()&&console.info(`Skapi: "${t}" was replaced with the Project ID entered earlier in this tab (${o}). It is kept in sessionStorage under "${Ke}"; delete that entry to enter a different one.`),this._start(l),this.__connection.catch(()=>Ht(o));else if(po())this._startAfterProjectIdInput(t,r,n,i);else throw this._alert(`Replace "${t}" with your actual Project ID.`),new a("Project ID is required.",{code:"INVALID_PARAMETER"});return}let s;try{s=this._resolveProject(t,r,n,i);}catch(o){throw this._alert(o.message),o}this._start(s);}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){H()&&typeof window.alert=="function"&&window.alert(t);}_resolveProject(t,r,n,i){let s=t.split("-").length;if(s===2||s===7)try{let u=Zt(t);n&&typeof n=="object"&&(i=n),r&&typeof r=="object"&&(n=r),r=u.owner,t=u.service;}catch{throw new a("Service ID is invalid.",{code:"INVALID_PARAMETER"})}if(!r||typeof r!="string")throw new a("Owner ID is invalid.",{code:"INVALID_PARAMETER"});if(r!==this.host)try{y.UserId(r,'"owner"');}catch{throw new a("Owner ID is invalid.",{code:"INVALID_PARAMETER"})}return {service:t,owner:r,options:n,__etc:i}}_startAfterProjectIdInput(t,r,n,i){let s=ho(t,o=>{this._resolveProject(o,r,n,i);}).then(o=>{fo(o),this._start(this._resolveProject(o,r,n,i)),this.__connection.catch(()=>Ht(o));});this.__projectIdInput=s,this.admin_endpoint=s.then(()=>this.admin_endpoint),this.record_endpoint=s.then(()=>this.record_endpoint),this.__authConnection=s.then(()=>this.__authConnection),this.__connection=s.then(()=>this.__connection);for(let o of [s,this.admin_endpoint,this.record_endpoint,this.__authConnection,this.__connection])o.catch(()=>{});}_start({service:t,owner:r,options:n,__etc:i}){this.service=t,this.owner=r;try{this.project_id=er(t,r);}catch{this.project_id="";}let s=true,o=false,l=null;if(n&&(typeof n.refetchServiceInfo=="boolean"&&(o=n.refetchServiceInfo),typeof n.autoLogin=="boolean"&&(s=n.autoLogin),n.encryption&&(l=vn(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 u=`https://${this.target_cdn}.cloudfront.net`,c=t.substring(0,4);this.admin_endpoint=fetch(`${u}/${c}/admin-${this.__endpoint_version}.json`).then(h=>h.blob()).then(h=>new Promise((m,_)=>{let b=new FileReader;b.onloadend=()=>m(b.result),b.onerror=_,b.readAsDataURL(h);})).then(h=>{try{return typeof h=="string"?JSON.parse(atob(h.split(",")[1])):null}catch{throw new a("Service does not exist. Create your service from skapi.com",{code:"NOT_EXISTS"})}}),this.record_endpoint=fetch(`${u}/${c}/record-${this.__endpoint_version}.json`).then(h=>h.blob()).then(h=>new Promise((m,_)=>{let b=new FileReader;b.onloadend=()=>m(b.result),b.onerror=_,b.readAsDataURL(h);})).then(h=>{try{return typeof h=="string"?JSON.parse(atob(h.split(",")[1])):null}catch{throw new a("Service does not exist. Create your service from skapi.com",{code:"NOT_EXISTS"})}});let f=H();if(f&&!window.sessionStorage)throw this._alert("This browser is not supported."),new Error("This browser is not supported.");let p=f?JSON.parse(window.sessionStorage.getItem(`${t}#${r}`)||"null"):null;if(this.log("constructor:restore",p),p?.connection){for(let h in p)this[h]=p[h];p.__public_identifier||(this.__public_identifier=`${this.service}:${this.owner}:${Te(16)}`);}Nn.bind(this)(l),this.__authConnection=(async()=>{let h=await this.admin_endpoint,m={UserPoolId:h.userpool_id,ClientId:h.userpool_client};Xt()&&(m.Storage=window.localStorage),this.userPool=new amazonCognitoIdentityJs.CognitoUserPool(m);try{this.user||await W.bind(this)().getSession({skipUserUpdateEventTrigger:!0}),this.user&&(!p?.connection&&!s?be.bind(this)():(l&&zn.bind(this)(),this._runOnLoginListeners(this.user),this._runOnUserUpdateListeners(this.user)));}catch{}})();let d=`${this.service}/${this.owner}`,g=f?window.sessionStorage.getItem(`${d}:uniqueids`):null;if(g)try{let h=JSON.parse(g);this.__my_unique_ids=h&&typeof h=="object"&&!Array.isArray(h)?{[d]:h}:{};}catch{this.__my_unique_ids={};}this.__connection=(async()=>{let h=null;await this.record_endpoint,p?.connection||(h=this._updateConnection({refresh:o}));let m=()=>{if(this.__class_properties_has_been_cached)return;let _=()=>{let b={},A=["__startKeyHistory","__disabledAccount","__cached_requests","__request_signup_confirmation","__public_identifier","connection"];if(this.connection){for(let w of A)b[w]=this[w];if(l&&(b.__cached_requests={},b.__startKeyHistory={}),f){let w=`${t}#${r}`;try{window.sessionStorage.setItem(w,JSON.stringify(b));}catch{try{let E=Object.assign({},b,{__cached_requests:{},__startKeyHistory:{}});window.sessionStorage.setItem(w,JSON.stringify(E));}catch{try{window.sessionStorage.removeItem(w);}catch{}}}}this.__class_properties_has_been_cached=true;}};return h instanceof Promise?h.then(()=>_()):_()};return f&&(window.addEventListener("beforeunload",()=>{this.closeRealtime(),m();}),window.addEventListener("visibilitychange",()=>{m();})),await h,await this.__authConnection,this.connection})(),this.__connection.then(h=>{((h?.group||0)<3||this.__network_logs)&&this.version();}).catch(()=>{});}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||(H()&&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 S.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,H()){let r=`Built with:
227
+ Watch the video here: ${t.video}`}var T=class{constructor(t,r,n,s){this.__version="2.2.13";this.project_id="";this.session=null;this.connection=null;this.__my_unique_ids={};this.__uniqueIdsPersistTimer=null;this.userPool=null;this.__socket=null;this.host="skapi";this.hostDomain="skapi.com";this.target_cdn="d3e9syvbtso631";this.customApiDomain="skapi.dev";this.requestBatchSize=50;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:ne,generateRandom:Se,toBase62:yn,fromBase62:de,decodeProjectId:lr,formatServiceId:cr,extractFormData:$,terminatePendingRequests:Qi,request:(t,r,n)=>k.bind(this)(t,r,n,{ignoreService:true})};this.__projectIdInput=null;this.__network_logs=false;this.__endpoint_version="v2";this.__public_identifier="";this.bearerToken="";this.registerTicket=Ai.bind(this);this.unregisterTicket=Ti.bind(this);this.updateTicket=Ii.bind(this);if(!t||typeof t!="string")throw this._alert("Service ID is required."),new l("Service ID is required.",{code:"INVALID_PARAMETER"});if(Go(t)){let o=Wo(),a=null;if(o)try{a=this._resolveProject(o,r,n,s);}catch{er(o);}if(a)Q()&&console.info(`Skapi: "${t}" was replaced with the Project ID entered earlier in this tab (${o}). It is kept in sessionStorage under "${ze}"; delete that entry to enter a different one.`),this._start(a),this.__connection.catch(()=>er(o));else if(zo())this._startAfterProjectIdInput(t,r,n,s);else throw this._alert(`Replace "${t}" with your actual Project ID.`),new l("Project ID is required.",{code:"INVALID_PARAMETER"});return}let i;try{i=this._resolveProject(t,r,n,s);}catch(o){throw this._alert(o.message),o}this._start(i);}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){Q()&&typeof window.alert=="function"&&window.alert(t);}_resolveProject(t,r,n,s){let i=t.split("-").length;if(i===2||i===7)try{let u=lr(t);n&&typeof n=="object"&&(s=n),r&&typeof r=="object"&&(n=r),r=u.owner,t=u.service;}catch{throw new l("Service ID is invalid.",{code:"INVALID_PARAMETER"})}if(!r||typeof r!="string")throw new l("Owner ID is invalid.",{code:"INVALID_PARAMETER"});if(r!==this.host)try{y.UserId(r,'"owner"');}catch{throw new l("Owner ID is invalid.",{code:"INVALID_PARAMETER"})}return {service:t,owner:r,options:n,__etc:s}}_startAfterProjectIdInput(t,r,n,s){let i=Yo(t,o=>{this._resolveProject(o,r,n,s);}).then(o=>{Qo(o),this._start(this._resolveProject(o,r,n,s)),this.__connection.catch(()=>er(o));});this.__projectIdInput=i,this.admin_endpoint=i.then(()=>this.admin_endpoint),this.record_endpoint=i.then(()=>this.record_endpoint),this.__authConnection=i.then(()=>this.__authConnection),this.__connection=i.then(()=>this.__connection);for(let o of [i,this.admin_endpoint,this.record_endpoint,this.__authConnection,this.__connection])o.catch(()=>{});}_start({service:t,owner:r,options:n,__etc:s}){this.service=t,this.owner=r;try{this.project_id=cr(t,r);}catch{this.project_id="";}let i=true,o=false,a=null;if(n&&(typeof n.refetchServiceInfo=="boolean"&&(o=n.refetchServiceInfo),typeof n.autoLogin=="boolean"&&(i=n.autoLogin),n.encryption&&(a=Vn(n.encryption)),typeof n.requestBatchSize=="number")){if(n.requestBatchSize<1)throw new l('"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=s?.target_cdn||this.target_cdn,this.hostDomain=s?.hostDomain||this.hostDomain,this.customApiDomain=s?.customApiDomain||this.customApiDomain,this.__network_logs=!!s?.network_logs;let u=`https://${this.target_cdn}.cloudfront.net`,c=t.substring(0,4);this.admin_endpoint=fetch(`${u}/${c}/admin-${this.__endpoint_version}.json`).then(h=>h.blob()).then(h=>new Promise((m,_)=>{let b=new FileReader;b.onloadend=()=>m(b.result),b.onerror=_,b.readAsDataURL(h);})).then(h=>{try{return typeof h=="string"?JSON.parse(atob(h.split(",")[1])):null}catch{throw new l("Service does not exist. Create your service from skapi.com",{code:"NOT_EXISTS"})}}),this.record_endpoint=fetch(`${u}/${c}/record-${this.__endpoint_version}.json`).then(h=>h.blob()).then(h=>new Promise((m,_)=>{let b=new FileReader;b.onloadend=()=>m(b.result),b.onerror=_,b.readAsDataURL(h);})).then(h=>{try{return typeof h=="string"?JSON.parse(atob(h.split(",")[1])):null}catch{throw new l("Service does not exist. Create your service from skapi.com",{code:"NOT_EXISTS"})}});let f=Q();if(f&&!window.sessionStorage)throw this._alert("This browser is not supported."),new Error("This browser is not supported.");let p=f?JSON.parse(window.sessionStorage.getItem(`${t}#${r}`)||"null"):null;if(this.log("constructor:restore",p),p?.connection){for(let h in p)this[h]=p[h];p.__public_identifier||(this.__public_identifier=`${this.service}:${this.owner}:${Se(16)}`);}jn.bind(this)(a),this.__authConnection=(async()=>{let h=await this.admin_endpoint,m={UserPoolId:h.userpool_id,ClientId:h.userpool_client};ar()&&(m.Storage=window.localStorage),this.userPool=new amazonCognitoIdentityJs.CognitoUserPool(m);try{this.user||await J.bind(this)().getSession({skipUserUpdateEventTrigger:!0}),this.user&&(!p?.connection&&!i?Re.bind(this)():(a&&oi.bind(this)(),this._runOnLoginListeners(this.user),this._runOnUserUpdateListeners(this.user)));}catch{}})();let d=`${this.service}/${this.owner}`,g=f?window.sessionStorage.getItem(`${d}:uniqueids`):null;if(g)try{let h=JSON.parse(g);this.__my_unique_ids=h&&typeof h=="object"&&!Array.isArray(h)?{[d]:h}:{};}catch{this.__my_unique_ids={};}this.__connection=(async()=>{let h=null;await this.record_endpoint,p?.connection||(h=this._updateConnection({refresh:o}));let m=()=>{if(this.__class_properties_has_been_cached)return;let _=()=>{let b={},E=["__startKeyHistory","__disabledAccount","__cached_requests","__request_signup_confirmation","__public_identifier","connection"];if(this.connection){for(let w of E)b[w]=this[w];if(a&&(b.__cached_requests={},b.__startKeyHistory={}),f){let w=`${t}#${r}`;try{window.sessionStorage.setItem(w,JSON.stringify(b));}catch{try{let R=Object.assign({},b,{__cached_requests:{},__startKeyHistory:{}});window.sessionStorage.setItem(w,JSON.stringify(R));}catch{try{window.sessionStorage.removeItem(w);}catch{}}}}this.__class_properties_has_been_cached=true;}};return h instanceof Promise?h.then(()=>_()):_()};return f&&(window.addEventListener("beforeunload",()=>{this.closeRealtime(),m();}),window.addEventListener("visibilitychange",()=>{m();})),await h,await this.__authConnection,this.connection})(),this.__connection.then(h=>{((h?.group||0)<3||this.__network_logs)&&this.version();}).catch(()=>{});}async getConnectionInfo(t){t?.refresh&&(this.__connection instanceof Promise&&await this.__connection,this.__connection=this._updateConnection({refresh:true}));let n=await this.__connection,s=n?.user_agent||(Q()&&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:s,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 k.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,Q()){let r=`Built with:
228
228
  %c\r
229
229
  ##\\ ##\\ \r
230
230
  ## | \\__|\r
@@ -237,5 +237,5 @@ Watch the video here: ${t.video}`}var T=class{constructor(t,r,n,i){this.__versio
237
237
  ## | \r
238
238
  ## | \r
239
239
  \\__| \r
240
- Version: ${this.__version}`;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{H()?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 Js.bind(this)(t,r)}closeRTC(t){return ue.bind(this)(t)}connectRTC(t,r){return ps.bind(this)(t,r)}connectRealtime(t){return $e.bind(this)(t)}spellcast(t){return No.bind(this)(t)}getspell(t){return Do.bind(this)(t)}dopamine(t){return xo.bind(this)(t)}getUniqueId(t,r){return ts.bind(this)(t,r)}resendInvitation(t){return To.bind(this)(t)}cancelInvitation(t){return Ro.bind(this)(t)}getInvitations(t,r){return Ao.bind(this)(t,r)}openIdLogin(t){return hi.bind(this)(t)}loginWithToken(t){return mi.bind(this)(t)}registerNewsletterGroup(t){return io.bind(this)(t)}deleteNewsletterGroup(t){return so.bind(this)(t)}clientSecretRequest(t){return Vs.bind(this)(t)}clientSecretRequestHistory(t,r){return Wr.bind(this)(t,r)}clientSecretRequestStream(t,r){return zr.bind(this)(t,r)}clientSecretRequestFinalize(t,r,n){return Jr.bind(this)(t,r,n)}cancelClientSecretRequest(t){return Qr.bind(this)(t)}stopClientSecretPolling(t){return Kt.bind(this)(t||{})}isPollStopped(t){return Hr(t)}clientSecretRequestQueueCount(t){return Gr.bind(this)(t)}forwardRequestHistory(t,r){return Bs.bind(this)(t,r)}forwardRequestStream(t,r){return js.bind(this)(t,r)}forwardRequestFinalize(t,r,n){return $s.bind(this)(t,r,n)}cancelForwardRequest(t){return Ks.bind(this)(t)}stopForwardRequestPolling(t){return Hs.bind(this)(t||{})}forwardRequestQueueCount(t){return Gs.bind(this)(t)}consumeTicket(t){return li.bind(this)(t)}getConsumedTickets(t,r){return di.bind(this)(t,r)}getTickets(t,r){return ci.bind(this)(t,r)}clearTicketLog(t){return ui.bind(this)(t)}closeRealtime(){return jt.bind(this)()}getRealtimeUsers(t,r){return Es.bind(this)(t,r)}sendInquiry(t){return Ws.bind(this)(t)}blockAccount(t){return mo.bind(this)(t)}unblockAccount(t){return yo.bind(this)(t)}deleteAccount(t){return bo.bind(this)(t)}inviteUser(t,r){return _o.bind(this)(t,r)}createAccount(t){return wo.bind(this)(t)}grantAccess(t){return Eo.bind(this)(t)}updateUserAttributes(t){return Io.bind(this)(t)}getRealtimeGroups(t,r){return As.bind(this)(t,r)}newsletterGroupEndpoint(){return oo.bind(this)()}postRealtime(t,r,n){return ws.bind(this)(t,r,n)}joinRealtime(t){return Be.bind(this)(t)}getProfile(t){return gi.bind(this)(t)}getFile(t,r){return _e.bind(this)(t,r)}secureRequest(t,r){return Qs.bind(this)(t,r)}forwardRequest(t,r){return qs.bind(this)(t,r)}getFormResponse(){return Fi.bind(this)()}getRecords(t,r){return Yi.bind(this)(t,r)}getTables(t,r){return Xi.bind(this)(t,r)}getIndexes(t,r){return Zi.bind(this)(t,r)}getTags(t,r){return es.bind(this)(t,r)}deleteRecords(t,r){return rs.bind(this)(t,r)}resendSignupConfirmation(){return yi.bind(this)()}recoverAccount(t=false){return bi.bind(this)(t)}getUsers(t,r){return ki.bind(this)(t,r)}disableAccount(){return wi.bind(this)()}lastVerifiedEmail(t){return vi.bind(this)(t)}unsubscribeNewsletter(t){return ao.bind(this)(t)}subscribeNotification(t,r){return Po.bind(this)({endpoint:t,keys:r})}unsubscribeNotification(t,r){return So.bind(this)({endpoint:t,keys:r})}vapidPublicKey(){return ko.bind(this)()}pushNotification(t,r){return vo.bind(this)(t,r)}getNewsletters(t,r){return lo.bind(this)(t,r)}getNewsletterSubscription(t,r){return ro.bind(this)(t,r)}getEncryptionStatus(){return Dn.bind(this)()}isWithheld(t){return gr.call(this,t)}unlockEncryption(t){return Kn.bind(this)(t)}lockEncryption(t){return Hn.bind(this)(t)}takeRecoveryCode(){return ei.bind(this)()}unlockWithRecoveryCode(t){return ti.bind(this)(t)}regenerateRecoveryCode(){return ri.bind(this)()}pinPeerKey(t){return Xn.bind(this)(t)}grantPrivateRecordAccess(t){return ns.bind(this)(t)}removePrivateRecordAccess(t){return is.bind(this)(t)}listPrivateRecordAccess(t,r){return ss.bind(this)(t,r)}requestPrivateRecordAccessKey(t){return os.bind(this)(t)}deleteFiles(t){return Wi.bind(this)(t)}uploadFiles(t,r){return ot.bind(this)(t,r)}mock(t,r){return zs.bind(this)(t,r)}login(t){return Sr.bind(this)(t)}logout(t){return nt.bind(this)(t)}signup(t,r){return _i.bind(this)(t,r)}resetPassword(t){return Ei.bind(this)(t)}verifyEmail(t,r){return Ti.bind(this)(t,r)}verifyPhoneNumber(t,r){return Ri.bind(this)(t,r)}forgotPassword(t,r){return Ii.bind(this)(t,r)}changePassword(t){return Pi.bind(this)(t)}updateProfile(t){return Si.bind(this)(t)}postRecord(t,r,n){return Fr.bind(this)(t,r,n)}postRecords(t){return ls.bind(this)(t)}getSubscriptions(t,r){return Ys.bind(this)(t,r)}subscribe(t){return Xs.bind(this)(t)}unsubscribe(t){return Zs.bind(this)(t)}blockSubscriber(t){return eo.bind(this)(t)}unblockSubscriber(t){return to.bind(this)(t)}subscribeNewsletter(t){return no.bind(this)(t)}bulkPostRecords(t){return Mr.bind(this)(t)}};P([k()],T.prototype,"getFeed"),P([k()],T.prototype,"closeRTC"),P([k()],T.prototype,"connectRTC"),P([k()],T.prototype,"spellcast"),P([k()],T.prototype,"getspell"),P([k()],T.prototype,"dopamine"),P([k()],T.prototype,"getUniqueId"),P([k()],T.prototype,"resendInvitation"),P([k()],T.prototype,"cancelInvitation"),P([k()],T.prototype,"getInvitations"),P([k()],T.prototype,"openIdLogin"),P([k()],T.prototype,"loginWithToken"),P([k()],T.prototype,"registerNewsletterGroup"),P([k()],T.prototype,"deleteNewsletterGroup"),P([k()],T.prototype,"clientSecretRequest"),P([k()],T.prototype,"clientSecretRequestHistory"),P([k()],T.prototype,"cancelClientSecretRequest"),P([k()],T.prototype,"forwardRequestHistory"),P([k()],T.prototype,"cancelForwardRequest"),P([k()],T.prototype,"consumeTicket"),P([k()],T.prototype,"getConsumedTickets"),P([k()],T.prototype,"getTickets"),P([k()],T.prototype,"clearTicketLog"),P([k()],T.prototype,"getRealtimeUsers"),P([k()],T.prototype,"sendInquiry"),P([k()],T.prototype,"blockAccount"),P([k()],T.prototype,"unblockAccount"),P([k()],T.prototype,"deleteAccount"),P([k()],T.prototype,"inviteUser"),P([k()],T.prototype,"createAccount"),P([k()],T.prototype,"grantAccess"),P([k()],T.prototype,"updateUserAttributes"),P([k()],T.prototype,"getRealtimeGroups"),P([k()],T.prototype,"newsletterGroupEndpoint"),P([k()],T.prototype,"postRealtime"),P([k()],T.prototype,"joinRealtime"),P([k()],T.prototype,"getProfile"),P([k()],T.prototype,"getFile"),P([k()],T.prototype,"secureRequest"),P([k()],T.prototype,"forwardRequest"),P([k()],T.prototype,"getFormResponse"),P([k()],T.prototype,"getRecords"),P([k()],T.prototype,"getTables"),P([k()],T.prototype,"getIndexes"),P([k()],T.prototype,"getTags"),P([k()],T.prototype,"deleteRecords"),P([k()],T.prototype,"resendSignupConfirmation"),P([k()],T.prototype,"recoverAccount"),P([k()],T.prototype,"getUsers"),P([k()],T.prototype,"disableAccount"),P([k()],T.prototype,"lastVerifiedEmail"),P([k()],T.prototype,"unsubscribeNewsletter"),P([k()],T.prototype,"subscribeNotification"),P([k()],T.prototype,"unsubscribeNotification"),P([k()],T.prototype,"vapidPublicKey"),P([k()],T.prototype,"pushNotification"),P([k()],T.prototype,"getNewsletters"),P([k()],T.prototype,"getNewsletterSubscription"),P([k()],T.prototype,"unlockEncryption"),P([k()],T.prototype,"unlockWithRecoveryCode"),P([k()],T.prototype,"grantPrivateRecordAccess"),P([k()],T.prototype,"removePrivateRecordAccess"),P([k()],T.prototype,"listPrivateRecordAccess"),P([k()],T.prototype,"requestPrivateRecordAccessKey"),P([k()],T.prototype,"deleteFiles"),P([k()],T.prototype,"uploadFiles"),P([k()],T.prototype,"mock"),P([k({preventMultipleCalls:true})],T.prototype,"login"),P([k()],T.prototype,"logout"),P([k({preventMultipleCalls:true})],T.prototype,"signup"),P([k({preventMultipleCalls:true})],T.prototype,"resetPassword"),P([k({preventMultipleCalls:true})],T.prototype,"verifyEmail"),P([k({preventMultipleCalls:true})],T.prototype,"verifyPhoneNumber"),P([k({preventMultipleCalls:true})],T.prototype,"forgotPassword"),P([k({preventMultipleCalls:true})],T.prototype,"changePassword"),P([k({preventMultipleCalls:true})],T.prototype,"updateProfile"),P([k()],T.prototype,"postRecord"),P([k()],T.prototype,"getSubscriptions"),P([k()],T.prototype,"subscribe"),P([k()],T.prototype,"unsubscribe"),P([k()],T.prototype,"blockSubscriber"),P([k()],T.prototype,"unblockSubscriber"),P([k()],T.prototype,"subscribeNewsletter");var Ul={};exports.Skapi=T;exports.SkapiError=a;exports.Types=Ul;//# sourceMappingURL=skapi.cjs.map
240
+ Version: ${this.__version}`;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{Q()?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 xo.bind(this)(t,r)}closeRTC(t){return me.bind(this)(t)}connectRTC(t,r){return zs.bind(this)(t,r)}connectRealtime(t){return We.bind(this)(t)}spellcast(t){return fa.bind(this)(t)}getspell(t){return pa.bind(this)(t)}dopamine(t){return ga.bind(this)(t)}getUniqueId(t,r){return ps.bind(this)(t,r)}resendInvitation(t){return oa.bind(this)(t)}cancelInvitation(t){return sa.bind(this)(t)}getInvitations(t,r){return ia.bind(this)(t,r)}openIdLogin(t){return Pi.bind(this)(t)}loginWithToken(t){return Si.bind(this)(t)}registerNewsletterGroup(t){return jo.bind(this)(t)}deleteNewsletterGroup(t){return $o.bind(this)(t)}clientSecretRequest(t){return Ao.bind(this)(t)}clientSecretRequestHistory(t,r){return sn.bind(this)(t,r)}clientSecretRequestStream(t,r){return an.bind(this)(t,r)}clientSecretRequestFinalize(t,r,n){return ln.bind(this)(t,r,n)}cancelClientSecretRequest(t){return on.bind(this)(t)}stopClientSecretPolling(t){return Zt.bind(this)(t||{})}isPollStopped(t){return rn(t)}clientSecretRequestQueueCount(t){return nn.bind(this)(t)}forwardRequestHistory(t,r){return ko.bind(this)(t,r)}forwardRequestStream(t,r){return To.bind(this)(t,r)}forwardRequestFinalize(t,r,n){return Io.bind(this)(t,r,n)}cancelForwardRequest(t){return Po.bind(this)(t)}stopForwardRequestPolling(t){return So.bind(this)(t||{})}forwardRequestQueueCount(t){return vo.bind(this)(t)}consumeTicket(t){return _i.bind(this)(t)}getConsumedTickets(t,r){return Ri.bind(this)(t,r)}getTickets(t,r){return wi.bind(this)(t,r)}clearTicketLog(t){return Ei.bind(this)(t)}closeRealtime(){return Jt.bind(this)()}getRealtimeUsers(t,r){return no.bind(this)(t,r)}sendInquiry(t){return No.bind(this)(t)}blockAccount(t){return Xo.bind(this)(t)}unblockAccount(t){return Zo.bind(this)(t)}deleteAccount(t){return ea.bind(this)(t)}inviteUser(t,r){return ta.bind(this)(t,r)}createAccount(t){return ra.bind(this)(t)}grantAccess(t){return na.bind(this)(t)}updateUserAttributes(t){return aa.bind(this)(t)}getRealtimeGroups(t,r){return io.bind(this)(t,r)}newsletterGroupEndpoint(){return Bo.bind(this)()}postRealtime(t,r,n){return ro.bind(this)(t,r,n)}joinRealtime(t){return Qe.bind(this)(t)}getProfile(t){return ki.bind(this)(t)}getFile(t,r){return Ae.bind(this)(t,r)}secureRequest(t,r){return Do.bind(this)(t,r)}forwardRequest(t,r){return Ro.bind(this)(t,r)}getFormResponse(){return Ji.bind(this)()}getRecords(t,r){return cs.bind(this)(t,r)}getTables(t,r){return us.bind(this)(t,r)}getIndexes(t,r){return ds.bind(this)(t,r)}getTags(t,r){return fs.bind(this)(t,r)}deleteRecords(t,r){return gs.bind(this)(t,r)}resendSignupConfirmation(){return vi.bind(this)()}recoverAccount(t=false){return Ni.bind(this)(t)}getUsers(t,r){return Vi.bind(this)(t,r)}disableAccount(){return Ci.bind(this)()}lastVerifiedEmail(t){return ji.bind(this)(t)}unsubscribeNewsletter(t){return Ko.bind(this)(t)}subscribeNotification(t,r){return la.bind(this)({endpoint:t,keys:r})}unsubscribeNotification(t,r){return ca.bind(this)({endpoint:t,keys:r})}vapidPublicKey(){return ua.bind(this)()}pushNotification(t,r){return da.bind(this)(t,r)}getNewsletters(t,r){return Ho.bind(this)(t,r)}getNewsletterSubscription(t,r){return qo.bind(this)(t,r)}getEncryptionStatus(){return $n.bind(this)()}isWithheld(t){return Ar.call(this,t)}unlockEncryption(t){return ti.bind(this)(t)}lockEncryption(t){return ri.bind(this)(t)}takeRecoveryCode(){return di.bind(this)()}unlockWithRecoveryCode(t){return fi.bind(this)(t)}regenerateRecoveryCode(){return pi.bind(this)()}pinPeerKey(t){return ci.bind(this)(t)}grantPrivateRecordAccess(t){return hs.bind(this)(t)}removePrivateRecordAccess(t){return ms.bind(this)(t)}listPrivateRecordAccess(t,r){return ys.bind(this)(t,r)}requestPrivateRecordAccessKey(t){return bs.bind(this)(t)}deleteFiles(t){return ss.bind(this)(t)}uploadFiles(t,r){return ft.bind(this)(t,r)}mock(t,r){return Co.bind(this)(t,r)}login(t){return Lr.bind(this)(t)}logout(t){return ct.bind(this)(t)}signup(t,r){return Di.bind(this)(t,r)}resetPassword(t){return xi.bind(this)(t)}verifyEmail(t,r){return Li.bind(this)(t,r)}verifyPhoneNumber(t,r){return Oi.bind(this)(t,r)}forgotPassword(t,r){return Mi.bind(this)(t,r)}changePassword(t){return Fi.bind(this)(t)}updateProfile(t){return qi.bind(this)(t)}postRecord(t,r,n){return Wr.bind(this)(t,r,n)}postRecords(t){return ws.bind(this)(t)}getSubscriptions(t,r){return Uo.bind(this)(t,r)}subscribe(t){return Oo.bind(this)(t)}unsubscribe(t){return Lo.bind(this)(t)}blockSubscriber(t){return Mo.bind(this)(t)}unblockSubscriber(t){return Fo.bind(this)(t)}subscribeNewsletter(t){return Vo.bind(this)(t)}bulkPostRecords(t){return Gr.bind(this)(t)}};P([S()],T.prototype,"getFeed"),P([S()],T.prototype,"closeRTC"),P([S()],T.prototype,"connectRTC"),P([S()],T.prototype,"spellcast"),P([S()],T.prototype,"getspell"),P([S()],T.prototype,"dopamine"),P([S()],T.prototype,"getUniqueId"),P([S()],T.prototype,"resendInvitation"),P([S()],T.prototype,"cancelInvitation"),P([S()],T.prototype,"getInvitations"),P([S()],T.prototype,"openIdLogin"),P([S()],T.prototype,"loginWithToken"),P([S()],T.prototype,"registerNewsletterGroup"),P([S()],T.prototype,"deleteNewsletterGroup"),P([S()],T.prototype,"clientSecretRequest"),P([S()],T.prototype,"clientSecretRequestHistory"),P([S()],T.prototype,"cancelClientSecretRequest"),P([S()],T.prototype,"forwardRequestHistory"),P([S()],T.prototype,"cancelForwardRequest"),P([S()],T.prototype,"consumeTicket"),P([S()],T.prototype,"getConsumedTickets"),P([S()],T.prototype,"getTickets"),P([S()],T.prototype,"clearTicketLog"),P([S()],T.prototype,"getRealtimeUsers"),P([S()],T.prototype,"sendInquiry"),P([S()],T.prototype,"blockAccount"),P([S()],T.prototype,"unblockAccount"),P([S()],T.prototype,"deleteAccount"),P([S()],T.prototype,"inviteUser"),P([S()],T.prototype,"createAccount"),P([S()],T.prototype,"grantAccess"),P([S()],T.prototype,"updateUserAttributes"),P([S()],T.prototype,"getRealtimeGroups"),P([S()],T.prototype,"newsletterGroupEndpoint"),P([S()],T.prototype,"postRealtime"),P([S()],T.prototype,"joinRealtime"),P([S()],T.prototype,"getProfile"),P([S()],T.prototype,"getFile"),P([S()],T.prototype,"secureRequest"),P([S()],T.prototype,"forwardRequest"),P([S()],T.prototype,"getFormResponse"),P([S()],T.prototype,"getRecords"),P([S()],T.prototype,"getTables"),P([S()],T.prototype,"getIndexes"),P([S()],T.prototype,"getTags"),P([S()],T.prototype,"deleteRecords"),P([S()],T.prototype,"resendSignupConfirmation"),P([S()],T.prototype,"recoverAccount"),P([S()],T.prototype,"getUsers"),P([S()],T.prototype,"disableAccount"),P([S()],T.prototype,"lastVerifiedEmail"),P([S()],T.prototype,"unsubscribeNewsletter"),P([S()],T.prototype,"subscribeNotification"),P([S()],T.prototype,"unsubscribeNotification"),P([S()],T.prototype,"vapidPublicKey"),P([S()],T.prototype,"pushNotification"),P([S()],T.prototype,"getNewsletters"),P([S()],T.prototype,"getNewsletterSubscription"),P([S()],T.prototype,"unlockEncryption"),P([S()],T.prototype,"unlockWithRecoveryCode"),P([S()],T.prototype,"grantPrivateRecordAccess"),P([S()],T.prototype,"removePrivateRecordAccess"),P([S()],T.prototype,"listPrivateRecordAccess"),P([S()],T.prototype,"requestPrivateRecordAccessKey"),P([S()],T.prototype,"deleteFiles"),P([S()],T.prototype,"uploadFiles"),P([S()],T.prototype,"mock"),P([S({preventMultipleCalls:true})],T.prototype,"login"),P([S()],T.prototype,"logout"),P([S({preventMultipleCalls:true})],T.prototype,"signup"),P([S({preventMultipleCalls:true})],T.prototype,"resetPassword"),P([S({preventMultipleCalls:true})],T.prototype,"verifyEmail"),P([S({preventMultipleCalls:true})],T.prototype,"verifyPhoneNumber"),P([S({preventMultipleCalls:true})],T.prototype,"forgotPassword"),P([S({preventMultipleCalls:true})],T.prototype,"changePassword"),P([S({preventMultipleCalls:true})],T.prototype,"updateProfile"),P([S()],T.prototype,"postRecord"),P([S()],T.prototype,"getSubscriptions"),P([S()],T.prototype,"subscribe"),P([S()],T.prototype,"unsubscribe"),P([S()],T.prototype,"blockSubscriber"),P([S()],T.prototype,"unblockSubscriber"),P([S()],T.prototype,"subscribeNewsletter");var _c={};exports.Skapi=T;exports.SkapiError=l;exports.Types=_c;//# sourceMappingURL=skapi.cjs.map
241
241
  //# sourceMappingURL=skapi.cjs.map