skapi-js 2.0.0 → 2.0.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/skapi.browser.mjs +6 -6
- package/dist/skapi.browser.mjs.map +1 -1
- package/dist/skapi.cjs +6 -6
- package/dist/skapi.cjs.map +1 -1
- package/dist/skapi.d.mts +71 -10
- package/dist/skapi.d.ts +71 -10
- package/dist/skapi.js +6 -6
- package/dist/skapi.js.map +1 -1
- package/dist/skapi.mjs +6 -6
- package/dist/skapi.mjs.map +1 -1
- package/package.json +2 -2
package/dist/skapi.mjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {CognitoUserPool,AuthenticationDetails,CognitoUserSession,CognitoRefreshToken,CognitoAccessToken,CognitoIdToken,CognitoUser,CognitoUserAttribute}from'amazon-cognito-identity-js';import
|
|
1
|
+
import {CognitoUserPool,AuthenticationDetails,CognitoUserSession,CognitoRefreshToken,CognitoAccessToken,CognitoIdToken,CognitoUser,CognitoUserAttribute}from'amazon-cognito-identity-js';import uo from'cocochex';import Wi from'qpass';/**
|
|
2
2
|
* @license
|
|
3
3
|
Apache License
|
|
4
4
|
Version 2.0, January 2004
|
|
@@ -203,7 +203,7 @@ import {CognitoUserPool,AuthenticationDetails,CognitoUserSession,CognitoRefreshT
|
|
|
203
203
|
limitations under the License.
|
|
204
204
|
|
|
205
205
|
*/
|
|
206
|
-
var Ks=Object.defineProperty;var Hs=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 S=(e,t,r,n)=>{for(var i=Hs(t,r),s=e.length-1,o;s>=0;s--)(o=e[s])&&(i=(o(t,r,i))||i);return i&&Ks(t,r,i),i};function vr(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 xt,Ct,Lt=()=>xt!==void 0?xt:xt=vr("fs"),Ot=()=>Ct!==void 0?Ct:Ct=vr("path"),he=typeof globalThis<"u"?globalThis:void 0,ct=he?.window;function Ws(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(ct)ct.global=ct,ct.global._runningInNodeJS=false;else if(he&&(he.global=he,typeof he.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=Ws(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});});}}he.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);});}}he.XMLHttpRequest=t,he.window={_runningInNodeJS:true,alert:r=>console.error("[Alert]",r),sessionStorage:{getItem:r=>null,setItem:(r,n)=>{},removeItem:r=>{}},localStorage:{getItem:r=>{let n=Lt(),i=Ot();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=Lt(),s=Ot();if(!(!i||!s))try{let o=s.resolve(process.cwd(),"states","localStorage");i.existsSync(o)||i.mkdirSync(o,{recursive:!0});let a=s.resolve(o,`${r}.skapi`);i.writeFileSync(a,n,"utf8");}catch{}},removeItem:r=>{let n=Lt(),i=Ot();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/${he?.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 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 me="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",Mt=BigInt(me.length),Qs=2*1024*1024,Gs=["aud","cognito:username","event_id","exp","iat","iss","jti","origin_jti","secret_key","token_use"],Nr={auth_time:"log",sub:"user_id"},zs=["0","1","2","3","4","5","6","7","8","9","a","b","c","d","e","f","g","h","i","j","k","l"],Lr=["us31","us72","ap51","ap22","ap41","eu71","ap21","us32","us71","af51","ap31","ap43","ap23","ap42","ca01","eu01","eu72","eu51","eu73","eu11","me51","sa31"],Ur=typeof TextEncoder<"u"?new TextEncoder:null;function Js(){if(typeof globalThis<"u")return globalThis.Buffer}function K(e){if(Ur)return Ur.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 Ft(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=Js();if(t)return new Uint8Array(t.from(e));throw new Error("No byte conversion available in this environment.")}var A=class A{static hash(t){typeof t!="string"&&(console.warn("coercing non-string value to empty string"),t="");let r=A.sb(t),n=1732584193,i=-271733879,s=-1732584194,o=271733878,a,u,c,g;for(let f=0;f<r.length;f+=16)a=n,u=i,c=s,g=o,n=A.ff(n,i,s,o,r[f],7,-680876936),o=A.ff(o,n,i,s,r[f+1],12,-389564586),s=A.ff(s,o,n,i,r[f+2],17,606105819),i=A.ff(i,s,o,n,r[f+3],22,-1044525330),n=A.ff(n,i,s,o,r[f+4],7,-176418897),o=A.ff(o,n,i,s,r[f+5],12,1200080426),s=A.ff(s,o,n,i,r[f+6],17,-1473231341),i=A.ff(i,s,o,n,r[f+7],22,-45705983),n=A.ff(n,i,s,o,r[f+8],7,1770035416),o=A.ff(o,n,i,s,r[f+9],12,-1958414417),s=A.ff(s,o,n,i,r[f+10],17,-42063),i=A.ff(i,s,o,n,r[f+11],22,-1990404162),n=A.ff(n,i,s,o,r[f+12],7,1804603682),o=A.ff(o,n,i,s,r[f+13],12,-40341101),s=A.ff(s,o,n,i,r[f+14],17,-1502002290),i=A.ff(i,s,o,n,r[f+15],22,1236535329),n=A.gg(n,i,s,o,r[f+1],5,-165796510),o=A.gg(o,n,i,s,r[f+6],9,-1069501632),s=A.gg(s,o,n,i,r[f+11],14,643717713),i=A.gg(i,s,o,n,r[f],20,-373897302),n=A.gg(n,i,s,o,r[f+5],5,-701558691),o=A.gg(o,n,i,s,r[f+10],9,38016083),s=A.gg(s,o,n,i,r[f+15],14,-660478335),i=A.gg(i,s,o,n,r[f+4],20,-405537848),n=A.gg(n,i,s,o,r[f+9],5,568446438),o=A.gg(o,n,i,s,r[f+14],9,-1019803690),s=A.gg(s,o,n,i,r[f+3],14,-187363961),i=A.gg(i,s,o,n,r[f+8],20,1163531501),n=A.gg(n,i,s,o,r[f+13],5,-1444681467),o=A.gg(o,n,i,s,r[f+2],9,-51403784),s=A.gg(s,o,n,i,r[f+7],14,1735328473),i=A.gg(i,s,o,n,r[f+12],20,-1926607734),n=A.hh(n,i,s,o,r[f+5],4,-378558),o=A.hh(o,n,i,s,r[f+8],11,-2022574463),s=A.hh(s,o,n,i,r[f+11],16,1839030562),i=A.hh(i,s,o,n,r[f+14],23,-35309556),n=A.hh(n,i,s,o,r[f+1],4,-1530992060),o=A.hh(o,n,i,s,r[f+4],11,1272893353),s=A.hh(s,o,n,i,r[f+7],16,-155497632),i=A.hh(i,s,o,n,r[f+10],23,-1094730640),n=A.hh(n,i,s,o,r[f+13],4,681279174),o=A.hh(o,n,i,s,r[f],11,-358537222),s=A.hh(s,o,n,i,r[f+3],16,-722521979),i=A.hh(i,s,o,n,r[f+6],23,76029189),n=A.hh(n,i,s,o,r[f+9],4,-640364487),o=A.hh(o,n,i,s,r[f+12],11,-421815835),s=A.hh(s,o,n,i,r[f+15],16,530742520),i=A.hh(i,s,o,n,r[f+2],23,-995338651),n=A.ii(n,i,s,o,r[f],6,-198630844),o=A.ii(o,n,i,s,r[f+7],10,1126891415),s=A.ii(s,o,n,i,r[f+14],15,-1416354905),i=A.ii(i,s,o,n,r[f+5],21,-57434055),n=A.ii(n,i,s,o,r[f+12],6,1700485571),o=A.ii(o,n,i,s,r[f+3],10,-1894986606),s=A.ii(s,o,n,i,r[f+10],15,-1051523),i=A.ii(i,s,o,n,r[f+1],21,-2054922799),n=A.ii(n,i,s,o,r[f+8],6,1873313359),o=A.ii(o,n,i,s,r[f+15],10,-30611744),s=A.ii(s,o,n,i,r[f+6],15,-1560198380),i=A.ii(i,s,o,n,r[f+13],21,1309151649),n=A.ii(n,i,s,o,r[f+4],6,-145523070),o=A.ii(o,n,i,s,r[f+11],10,-1120210379),s=A.ii(s,o,n,i,r[f+2],15,718787259),i=A.ii(i,s,o,n,r[f+9],21,-343485551),n=A.ad(n,a),i=A.ad(i,u),s=A.ad(s,c),o=A.ad(o,g);return A.rh(n)+A.rh(i)+A.rh(s)+A.rh(o)}static rh(t){let r="";for(let n=0;n<=3;n++)r+=A.alphabet.charAt(t>>n*8+4&15)+A.alphabet.charAt(t>>n*8&15);return r}static ad(t,r){let n=(t&65535)+(r&65535);return (t>>16)+(r>>16)+(n>>16)<<16|n&65535}static rl(t,r){return t<<r|t>>>32-r}static cm(t,r,n,i,s,o){return A.ad(A.rl(A.ad(A.ad(r,t),A.ad(i,o)),s),n)}static ff(t,r,n,i,s,o,a){return A.cm(r&n|~r&i,t,r,s,o,a)}static gg(t,r,n,i,s,o,a){return A.cm(r&i|n&~i,t,r,s,o,a)}static hh(t,r,n,i,s,o,a){return A.cm(r^n^i,t,r,s,o,a)}static ii(t,r,n,i,s,o,a){return A.cm(n^(r|~i),t,r,s,o,a)}static sb(t){let r,n=(t.length+8>>6)+1,i=new Array(n*16);for(r=0;r<n*16;r++)i[r]=0;for(r=0;r<t.length;r++)i[r>>2]|=t.charCodeAt(r)<<r%4*8;return i[r>>2]|=128<<r%4*8,i[n*16-2]=t.length*8,i}};A.alphabet="0123456789abcdef";var W=A;function Or(e){if(e===0)return me[0];let t="";for(;e>0;)t=me[e%62]+t,e=Math.floor(e/62);return t}function ne(e){return e.split("").reverse().reduce((t,r,n)=>t+me.indexOf(r)*62**n,0)}function Re(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 qt(){return typeof window>"u"||!!window?._runningInNodeJS}function Y(){return !qt()&&typeof document<"u"&&typeof document.createElement=="function"}function ut(e){let t;try{t=JSON.stringify(e);}catch{throw new l("Invalid data type.",{code:"INVALID_REQUEST"})}if(new Blob([t]).size>Qs)throw new l("Data should not exceed 2MB",{code:"INVALID_REQUEST"})}function Dr(e){return e===""||e==="on"||e==="true"}function xr(e){return e==="false"}function Cr(e,t,r){t.name&&r(e,t.name,t.value);}var dt=Y(),Ys=typeof SubmitEvent<"u",Xs=typeof HTMLFormElement<"u";function j(e,t,r){let n={},i=[];function s(u,c,g){if(t?.ignoreEmpty&&g==="")return;if(t?.nullIfEmpty&&g===""&&(g=null),typeof r=="function"){let p=r(c,g);p!==void 0&&(g=p);}let f=c.split("[").map(p=>{let m=p.replace("]",""),h=Number(m);return !isNaN(h)&&!m.includes(".")?m=h:(m[0]==='"'&&m[m.length-1]==='"'||m[0]==="'"&&m[m.length-1]==="'")&&(m=m.replace(/"/g,"").replace(/'/g,"")),m}),d=u;if(typeof f[0]=="number")throw new l("Form key cannot start with an array index.",{code:"INVALID_REQUEST"});for(let p=0;p<f.length;p++){let m=f[p];p<f.length-1?(d[m]===void 0&&(typeof f[p+1]=="number"?d[m]=[]:d[m]={}),d=d[m]):d[m]===void 0?d[m]=g:Array.isArray(d[m])?d[m].push(g):d[m]=[d[m],g];}}function o(u,c,g){if(g instanceof File)u.push({name:c,file:g});else if(g instanceof FileList&&g&&g.length>0)for(let f=0;f<=g.length-1;f++){let d=g.item(f);d&&u.push({name:c,file:d});}}let a=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===""||Dr(u.value)?s(n,u.name,true):xr(u.value)?s(n,u.name,false):u.value&&s(n,u.name,u.value):u.type==="checkbox"&&(Dr(u.value)?s(n,u.name,false):xr(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(dt&&(e instanceof HTMLInputElement||e instanceof HTMLSelectElement||e instanceof HTMLTextAreaElement))return a(e),ut(n),{data:n,files:i};if(dt&&e instanceof FormData){for(let u of e.entries()){let c=u[0],g=u[1];if(g instanceof File||g instanceof FileList)o(i,c,g);else if(g instanceof Blob){let f=g;if(f.type==="application/json")try{let d=JSON.parse(f.text());s(n,c,d);}catch{s(n,c,f);}}else s(n,c,g);}return ut(n),{data:n,files:i}}if(dt&&Ys&&e instanceof SubmitEvent&&(e=e.target),dt&&Xs&&e instanceof HTMLFormElement){let u=e.querySelectorAll("input"),c=e.querySelectorAll("select"),g=e.querySelectorAll("textarea");for(let f=0;f<c.length;f++)Cr(n,c[f],s);for(let f=0;f<g.length;f++)Cr(n,g[f],s);for(let f=0;f<u.length;f++)a(u[f]);return ut(n),{data:n,files:i}}return ut(e),{data:e,files:i}}function $e(e){let t={};for(let r in e){let n=e[r];if(!Gs.includes(r))if(Nr[r])t[Nr[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 Vt(e){if(e=oo(e),e.split("-").length===7){let t=e.split("-"),r,n;try{r=Lr[ne(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 $t(e,t){let r=Lr.indexOf(e.slice(0,4)),n=zs[r],s=`${e.slice(4,-4)}-${n}${e.slice(-4)}-${t}`;return so(s)}function Zs(e){let t=0n;for(let r of e){let n=me.indexOf(r);if(n<0)throw new Error(`INVALID_PARAMETER: Invalid base62 character: ${r}`);t=t*Mt+BigInt(n);}return t}function eo(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%Mt);r=me[i]+r,n/=Mt;}return r.length<t&&(r="0".repeat(t-r.length)+r),r}function to(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 ro(e){let t=0n;for(let r of e)t=(t<<8n)+BigInt(r);return t}function no(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 io(e){let t=Array.from(Ft(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 so(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>=me.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=i+o,c=me[i.length]+a+u,g=no(s),f=eo(ro(g));return `${c}-${f}`}function oo(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=me.indexOf(n[0]);if(s<0)throw new Error("INVALID_PARAMETER: Corrupt compressed token: "+t);let o=n.slice(1),a=s+2;if(o.length<a)throw new Error("INVALID_PARAMETER: Corrupt compressed token: "+t);let u=o.slice(0,o.length-a),c=o.slice(o.length-a),g=c.slice(s),f=c.slice(0,s),d=g+u;if(!/^[0-9A-Za-z]+$/.test(d)||!/^[0-9A-Za-z]+$/.test(f))throw new Error("INVALID_PARAMETER: Corrupt compressed token: "+t);let p=Zs(i),m=to(p);if(m.length>16)throw new Error("INVALID_PARAMETER: Corrupt compressed token: "+t);let h=new Uint8Array(16);h.set(m,16-m.length);let _=io(h);return `${d}-${f}-${_}`}function je(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 jt(...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 lo(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 co(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 uo(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 fo(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 go(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 po(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 l(`"${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 l(`"${i}" is an invalid url. Relative URL does not work on local file system. Use full URL string.`,{code:"INVALID_PARAMETER"});let a=t?window.location.href.split("?")[0]:"";a.slice(-1)!=="/"&&(a+="/"),s=a+s.slice(1);}let o;try{o=new URL(s);}catch{throw new l(`"${i}" is an invalid url.`,{code:"INVALID_PARAMETER"})}if(o.protocol)return o.href}}throw new l(`"${i}" is an invalid url.`,{code:"INVALID_PARAMETER"})};return Array.isArray(e)?e.map(i=>n(i)):n(e)}function ho(e,t,r=[],n){let i=j(e,n),s=i.data;t.service="string",t.owner="string";let o={};for(let a in t)if(s&&typeof s=="object"&&!Array.isArray(s)&&s.hasOwnProperty(a))if(typeof s[a]=="function")o[a]=s[a];else try{o[a]=JSON.parse(JSON.stringify(s[a]));}catch{o[a]=s[a];}n?.precall&&n.precall({data:o,files:i?.files||[]});try{return ao(o,t,r)}catch(a){throw new l(a.message,{code:"INVALID_PARAMETER"})}}var y={UserId:lo,PhoneNumber:co,Birthdate:uo,Password:fo,Email:go,Url:po,Params:ho};var X="skapi.enc.v1",qr=6e5,Be=12,ft=null,ve=null;function Vr(){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 $r(){if(ve)return ve;let e=typeof globalThis<"u"?globalThis:void 0;if(e?.crypto?.subtle&&typeof e.crypto.getRandomValues=="function")return ve=e.crypto,ve;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 ve=r.webcrypto,ve}catch{}throw Vr()}function ie(){if(ft)return ft;let e=$r();if(!e.subtle)throw Vr();return ft=e.subtle,ft}function Kt(){try{return ie(),!0}catch{return false}}function Z(e){let t=$r(),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 F(e){let t=Ft(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 l("No base64 encoder available in this environment.",{code:"NOT_SUPPORTED"});return r.replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function V(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),i=new Uint8Array(n.length);for(let s=0;s<n.length;s++)i[s]=n.charCodeAt(s);return i}throw new l("No base64 decoder available in this environment.",{code:"NOT_SUPPORTED"})}async function gt(e){let t=await ie().digest("SHA-256",e);return new Uint8Array(t)}async function We(e,t,r,n){let i=ie(),s=await i.importKey("raw",e,"HKDF",false,["deriveBits"]),o=await i.deriveBits({name:"HKDF",hash:"SHA-256",salt:t,info:r},s,n*8);return new Uint8Array(o)}async function Ue(e,t,r,n){let i=ie(),s=K(e.normalize("NFC")),o=await i.importKey("raw",s,"PBKDF2",false,["deriveBits"]),a=new Uint8Array(await i.deriveBits({name:"PBKDF2",salt:t,iterations:r,hash:"SHA-256"},o,256)),u=await We(a,t,n,32);M(a),M(s);let c=await oe(u);return M(u),c}async function oe(e){return ie().importKey("raw",e,{name:"AES-GCM"},false,["encrypt","decrypt"])}async function jr(){let e=Z(32),t=await oe(e);return {bytes:e,key:t}}async function se(e,t,r){let n=Z(Be),i=await ie().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 ie().decrypt({name:"AES-GCM",iv:t,additionalData:n,tagLength:128},e,r);return new Uint8Array(i)}var pt={name:"ECDH",namedCurve:"P-256"};async function Br(){let e=ie(),t=await e.generateKey(pt,true,["deriveBits"]),r=new Uint8Array(await e.exportKey("raw",t.publicKey)),n=new Uint8Array(await e.exportKey("pkcs8",t.privateKey)),i=await Ht(n);return {pubRaw:r,pkcs8:n,priv:i}}async function Ht(e){return ie().importKey("pkcs8",e,pt,false,["deriveBits"])}async function Kr(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 ie().importKey("raw",e,pt,false,[])}async function Wt(e){return F(await gt(e))}async function Hr(e,t,r,n){let i=ie(),s=await Kr(e),o=await i.generateKey(pt,true,["deriveBits"]),a=new Uint8Array(await i.deriveBits({name:"ECDH",public:s},o.privateKey,256)),u=await We(a,new Uint8Array(32),r,32);M(a);let c=await oe(u);M(u);let{iv:g,ct:f}=await se(c,t,n);return {epk:new Uint8Array(await i.exportKey("raw",o.publicKey)),iv:g,ct:f}}async function Wr(e,t,r,n,i,s){let o=ie(),a=await Kr(t),u=new Uint8Array(await o.deriveBits({name:"ECDH",public:a},e,256)),c=await We(u,new Uint8Array(32),i,32);M(u);let g=await oe(c);return M(c),ae(g,r,n,s)}function M(e){e&&e.length&&e.fill(0);}function mo(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 Qt(e){return K(JSON.stringify(e))}function Qe(e,t,r){return jt(e,new Uint8Array([0]),K(t),new Uint8Array([0]),K(r))}var Ie="0123456789ABCDEFGHJKMNPQRSTVWXYZ",Ke=16,Mr=26,Fr=28;function Qr(e){let t=2166136261;for(let r=0;r<e.length;r++)t^=e[r],t=t*16777619>>>0;return t&1023}function Gr(e){if(e.length!==Ke)throw new l(`A recovery code needs exactly ${Ke} 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=Qr(e);return t+=Ie[i>>5&31]+Ie[i&31],(t.match(/.{1,4}/g)||[]).join("-")}function zr(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!==Fr)throw new l(`That does not look like a recovery code: expected ${Fr} characters, got ${t.length}.`,{code:"ENCRYPTION_BAD_RECOVERY_CODE"});let r=t.slice(0,Mr),n=t.slice(Mr),i=0,s=0,o=[];for(let c=0;c<r.length;c++){let g=Ie.indexOf(r[c]);if(g<0)throw new l(`That does not look like a recovery code: "${r[c]}" is not a valid character.`,{code:"ENCRYPTION_BAD_RECOVERY_CODE"});i=i<<5|g,s+=5,s>=8&&(s-=8,o.push(i>>s&255));}let a=new Uint8Array(o.slice(0,Ke)),u=Qr(a);if(n!==Ie[u>>5&31]+Ie[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 Gt(e,t,r){let n=await We(e,t,r,32),i=await oe(n);return M(n),i}var Bt=[83,75,69,78,67,70],Jr=2,He=56,Yr=16,yo=4*1024*1024;function zt(e){if(!e||e.length<He)return false;for(let t=0;t<Bt.length;t++)if(e[t]!==Bt[t])return false;return true}function Te(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 Ne(e,t){return (e[t]<<24>>>0)+(e[t+1]<<16)+(e[t+2]<<8)+e[t+3]}function bo(e,t,r){let n=Math.floor(r/4294967296);Te(e,t,n),Te(e,t+4,r>>>0);}function _o(e,t){return Ne(e,t)*4294967296+Ne(e,t+4)}async function Xr(e,t,r,n,i,s){let o=K(`${X}|binfile|${r}|${n}|${i}|${s}`),a=await We(e,t,o,32),u=await oe(a);return M(a),u}async function Zr(e){return (await gt(jt(K(`${X}|dekid`),e))).subarray(0,8)}function en(e,t,r){return Qt([`${X}|binchunk`,F(e),t,r])}function wo(e,t,r,n,i,s){let o=new Uint8Array(He+s.length);return o.set(Bt,0),o[6]=Jr,o[7]=s.length?1:0,Te(o,8,e),Te(o,12,t),o.set(r,16),bo(o,32,n),o.set(i,40),Te(o,48,s.length),Te(o,52,0),s.length&&o.set(s,He),o}async function tn(e,t,r,n,i=yo){let s=Z(Yr),o=await Xr(e,s,r.service,r.owner,r.recordOwner,r.recordId),a=await Zr(e),u=n?K(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/i),g=wo(i,c,s,t.length,a,u),f=await gt(g),d=[],p=g.length;for(let _=0;_<c;_++){let w=t.subarray(_*i,Math.min((_+1)*i,t.length)),b=await se(o,w,en(f,_,c));d.push(b),p+=4+b.iv.length+b.ct.length;}let m=new Uint8Array(p);m.set(g,0);let h=g.length;for(let _ of d)Te(m,h,_.iv.length+_.ct.length),h+=4,m.set(_.iv,h),h+=_.iv.length,m.set(_.ct,h),h+=_.ct.length;return m}function Eo(e){if(!zt(e))throw new l("This file is not an encrypted skapi file.",{code:"INVALID_PARAMETER"});let t=Ne(e,48),r=He+t;if(e.length<r)throw new l("Encrypted file header is truncated.",{code:"INVALID_REQUEST"});let n=null;return t&&(n=JSON.parse(je(e.subarray(He,r)))),{version:e[6],chunkBytes:Ne(e,8),count:Ne(e,12),fileId:e.subarray(16,16+Yr),plainLen:_o(e,32),dekId:e.subarray(40,48),meta:n,headerLen:r}}async function rn(e,t,r){let n=Eo(t);if(n.version!==Jr)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 i=await Zr(e);if(!mo(i,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 s=await Xr(e,n.fileId,r.service,r.owner,r.recordOwner,r.recordId),o=await gt(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 p=Ne(t,u);if(u+=4,p<Be+16||u+p>t.length)throw new l("Encrypted file is truncated.",{code:"INVALID_REQUEST"});let m=await ae(s,t.subarray(u,u+Be),t.subarray(u+Be,u+p),en(o,d,n.count));u+=p,a.push(m),c+=m.length;}let g=new Uint8Array(c),f=0;for(let d of a)g.set(d,f),f+=d.length;return {bytes:g,meta:n.meta}}var Ao="__skapi__keyring",Ge="__skapi_enc__",sn=1,Ro="skapi-enc",we="keys",Yt=new WeakMap;function on(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:qr;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:Ao}}function O(){return Yt.get(this)||null}function an(e){if(!e){Yt.delete(this);return}Yt.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 Xt(){let e=O.call(this);if(e){e.user_id&&cr.call(this,e).catch(()=>{}),e.ready=null,e.unlocking=false,e.pendingRecoveryCode="";for(let[,t]of e.dek)M(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 ln(){let e=O.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 cn(e,t){return typeof t=="string"&&t===e.cfg.table}function De(){return `${this.service}/${this.owner}`}function Zt(e,t,r,n){let[i,s]=e.split("/");return Qt([X,i,s,t,r,n])}function un(e,t,r,n,i){let[s,o]=e.split("/");return K(`${X}|dekwrap|${s}|${o}|${t}|${r}|${n}|${i}`)}function er(e){return e.anch==="uid"?e.uid:e.anch==="rid"?e.rid:""}function mt(e){return !!e&&typeof e=="object"&&!Array.isArray(e)&&typeof e[Ge]=="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 dn="__skapi_no_access__";function ee(e,t,r){if(e.withheld!=="sentinel")return null;let n={[dn]:true,reason:t};return r&&(n.recipients=r),Object.freeze(n)}function tr(e){return !!e&&typeof e=="object"&&e[dn]===true}var Io=256*1024,Ye="__skenc_ct__",fn="payload.bin",To=`/${Ye}/${fn}`;function rr(e,t){return e===Ye&&t===fn}async function Po(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:nn(n.access_group),table:i,record:null};if(!r)return {group:n?.access_group!==void 0?nn(n.access_group):0,table:i,record:null};let s=e.dek.get(r);if(s)return {group:s.access_group,table:i,record:null};let o=await _e.call(this,r);if(!o)throw new l(`Record "${r}" not found.`,{code:"NOT_EXISTS"});return {group:o.table.access_group,table:o.table.name,record:o}}function So(e){return this.getFile(e,{dataType:"blob"})}async function _e(e){let t=/^[a-zA-Z0-9]+$/.test(e)?{record_id:e}:{unique_id:e};return (await this.getRecords(t,{limit:1}))?.list?.[0]||null}function nn(e){return e==="private"||e==="*"||e==="**"?"private":e==="public"?0:e==="authorized"?1:e==="admin"?99:typeof e=="number"?e:0}function Jt(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 nr(e,t,r){let n=O.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 $=n.passthrough.get(i);return n.passthrough.delete(i),{send:$,plain:e,encrypted:true,omit:false}}let{group:a,table:u,record:c}=await Po.call(this,n,t,s);if(a!=="private"){let $=true;if(!r&&i){let z=c||await _e.call(this,i);if(z&&z.encrypted){if(Jt.call(this,z,i,"making it non-private"),z.encrypted.status==="failed")throw new l(`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 Ve=!!z.bin&&Object.keys(z.bin).some(lt=>(z.bin[lt]||[]).some(kr=>kr&&kr.encrypted));if(!Ve&&s){let lt=n.dek.get(s);lt&&(M(lt.bytes),n.dek.delete(s));}return {send:z.data,plain:z.data,encrypted:false,omit:false,files:Ve?"decrypt":void 0}}}let re=c;i&&!re&&(re=await _e.call(this,i).catch(()=>null)),re&&re.encrypted&&Jt.call(this,re,i,"making it non-private");let Sr=!!re&&!!re.bin&&Object.keys(re.bin).some(z=>(re.bin[z]||[]).some(Ve=>Ve&&Ve.encrypted));if(Sr&&($=false),$&&s){let z=n.dek.get(s);z&&(M(z.bytes),n.dek.delete(s));}return {send:e,plain:e,encrypted:false,omit:!r,files:Sr?"decrypt":void 0}}if(cn(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(tr.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,Ge))throw new l(`"${Ge}" 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 g=this.user?.user_id;if(!g)throw new l("User login is required to write an encrypted record.",{code:"INVALID_REQUEST"});let f=De.call(this),d=false;if(i&&n.roll.has(i)){d=true,n.roll.delete(i);let $=n.dek.get(i);n.dek.delete(i),$&&M($.bytes);}let p=c;i&&!p&&!n.dek.has(i)&&(p=await _e.call(this,i).catch(()=>null)),p&&Jt.call(this,p,i,"making it private");let m=!!p&&!p.encrypted&&!!p.bin&&Object.keys(p.bin).some($=>(p.bin[$]||[]).some(re=>re&&!re.encrypted)),h=null;if(i&&!d&&(h=n.dek.get(i)||null,!h)){let $=p||c||await _e.call(this,i);if($&&(s=$.record_id||i,h=n.dek.get(s)||null,!o&&$.unique_id&&(o=$.unique_id),!h&&$.encrypted?.status==="failed"))throw new l(`Cannot update encrypted record "${i}": its current contents could not be decrypted (${$.encrypted.reason}), so its existing key wraps cannot be preserved. Updating anyway would revoke everyone it is shared with.`,{code:"ENCRYPTION_LOCKED"})}s===i&&h&&h.rid&&(s=h.rid),!o&&h&&h.anch==="uid"&&h.uid&&(o=h.uid);let _,w,b;if(h){if(h.own&&h.own!==g)throw new l(`Record "${i}" belongs to another user (${h.own}). Encryption only operates on records you own.`,{code:"ENCRYPTION_NOT_RECORD_OWNER"});_=h.bytes,w=h.key,b=Object.assign({},h.recipients);}else {let $=await jr();_=$.bytes,w=$.key,b={};}let E=o?"uid":s?"rid":"new",R=E==="uid"?o:E==="rid"?s:"",T=Zt(f,g,E,R),U=Qe(T,g,"mk"),D=await se(n.mk,_,U);b[g]={t:"mk",iv:F(D.iv),ct:F(D.ct)},h&&(h.anch!==E||er(h)!==R)&&(b=await ko.call(this,n,_,b,f,g,E,R,T));let x=K(JSON.stringify(e===void 0?null:e)),v=await se(w,x,T);M(x);let C={[Ge]:sn,enc:"A256GCM",kw:"ECDH-ES+A256GCM",anch:E,uid:o,rid:s,own:g,iv:F(v.iv),ct:F(v.ct),k:b},L,q,G=C.ct;s&&G.length>Io&&(L=V(G),C.ct="",C.ct_ref=To,h&&h.ctRef&&(q=h.ctRef));let Ae=JSON.stringify(C).length;if(Ae>2*1024*1024)throw new l(`Encrypted record data is too large: once encrypted and base64 encoded it becomes ${Ae} bytes, over the ${2*1024*1024} byte limit. Encryption costs about 33% plus roughly 230 bytes per additional recipient.`,{code:"ENCRYPTED_DATA_TOO_LARGE"});return s&&n.dek.set(s,{bytes:_,key:w,recipients:b,anch:E,uid:o,rid:s,own:g,access_group:"private"}),{send:C,plain:e,encrypted:true,omit:false,spill:L,retireCt:q,dek:{bytes:_,key:w,recipients:b,anch:E,uid:o,rid:s,own:g,access_group:"private"},files:m?"encrypt":void 0}}function gn(e,t){let r=O.call(this);!r||!t||!e||r.dek.has(e)||r.dek.set(e,Object.assign({},t,{rid:e}));}async function ko(e,t,r,n,i,s,o,a){let u=Object.keys(r).filter(f=>f!==i);if(!u.length)return r;let c=await ur.call(this,u),g={[i]:r[i]};for(let f of u){let d=c[f];d&&(g[f]=await pn.call(this,t,d,n,o,i,f,a));}return g}async function pn(e,t,r,n,i,s,o){let a=un(r,n,i,s,t.fpr),u=Qe(o,s,t.fpr),c=await Hr(t.pubRaw,e,a,u);return {t:"ecdh",epk:F(c.epk),iv:F(c.iv),ct:F(c.ct),fpr:t.fpr}}async function hn(e,t){if(!mt(e))return {value:e};if(t.access_group!=="private")return {value:e};let r=O.call(this);if(!r)return {value:null,flag:{status:"failed",reason:"ENCRYPTION_DISABLED"}};if(r.rawRead)return {value:e};if(cn(r,t.table_name))return {value:e};if(e[Ge]!==sn)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=De.call(this),o=er(e),a=Zt(s,e.own,e.anch,o),u;try{if(i.t==="mk")u=await ae(r.mk,V(i.iv),V(i.ct),Qe(a,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 Wr(r.ikPriv,V(i.epk),V(i.iv),V(i.ct),un(s,o,e.own,n,i.fpr),Qe(a,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 M(u),{value:ee(r.cfg,"DATA_UNAVAILABLE"),flag:{status:"failed",reason:"DATA_UNAVAILABLE"}};let p=await So.call(this,t.ctUrl);c=new Uint8Array(await p.arrayBuffer());}else c=V(e.ct);}catch{return M(u),{value:ee(r.cfg,"DATA_UNAVAILABLE"),flag:{status:"failed",reason:"DATA_UNAVAILABLE"}}}let g,f;try{f=await oe(u),g=await ae(f,V(e.iv),c,a);}catch{return M(u),{value:ee(r.cfg,"CORRUPT"),flag:{status:"failed",reason:"CORRUPT"}}}let d;try{d=JSON.parse(je(g));}catch{return M(g),M(u),{value:ee(r.cfg,"CORRUPT"),flag:{status:"failed",reason:"CORRUPT"}}}if(M(g),t.record_id){let p=r.dek.get(t.record_id);p?(p.bytes=u,p.key=f,p.recipients=e.k,p.anch=e.anch,p.uid=e.uid,p.own=e.own,p.access_group="private",p.ctRef=e.ct_ref||""):r.dek.set(t.record_id,{bytes:u,key:f,recipients:e.k,anch:e.anch,uid:e.uid,rid:t.record_id,own:e.own,access_group:"private",ctRef:e.ct_ref||""});}else M(u);return {value:d,flag:{status:"encrypted",recipients:Object.keys(e.k)}}}function ze(e,t){let[r,n]=e.split("/");return K(`${X}|kek|${r}|${n}|${t}`)}function Je(e,t,r,n){let[i,s]=e.split("/");return K(`${X}|mk|${i}|${s}|${t}|PBKDF2-SHA256|${r}|${n}`)}function mn(e,t){let[r,n]=e.split("/");return K(`${X}|recovery|${r}|${n}|${t}`)}function yn(e,t,r){let[n,i]=e.split("/");return K(`${X}|rk|${n}|${i}|${t}|HKDF-SHA256|${r}`)}function bn(e,t){let[r,n]=e.split("/");return K(`${X}|self|${r}|${n}|${t}`)}function _n(e,t){let[r,n]=e.split("/");return K(`${X}|ik|${r}|${n}|${t}`)}async function yt(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 ir(e,t,r){let n=Z(Ke),i=Gr(n),s=Z(16),o=F(s),a=await Gt(n,s,mn(e,t)),u=await se(a,r,yn(e,t,o));return M(n),{code:i,wrap:{id:F(Z(6)),p:"recovery",kdf:{a:"HKDF-SHA256",s:o},iv:F(u.iv),ct:F(u.ct),created:Date.now()}}}async function vo(e,t,r,n){let i=zr(n),s=(r||[]).filter(o=>o.p==="recovery");s.sort((o,a)=>(a.created||0)-(o.created||0));for(let o of s)try{let a=await Gt(i,V(o.kdf.s),mn(e,t)),u=await ae(a,V(o.iv),V(o.ct),yn(e,t,o.kdf.s));return M(i),u}catch{}return M(i),null}async function No(e,t,r,n,i){let s=Z(16),o=F(s),a=await Ue(n,s,e.cfg.iterations,ze(t,r)),u=await se(a,i,Je(t,r,e.cfg.iterations,o));return {id:F(Z(6)),p:"password",kdf:{a:"PBKDF2-SHA256",it:e.cfg.iterations,s:o},iv:F(u.iv),ct:F(u.ct),created:Date.now()}}async function Uo(e,t){let r=this.user.user_id,n=e.scope,i=Z(16),s=F(i),o=await Ue(t,i,e.cfg.iterations,ze(n,r)),a=Z(32),u=await se(o,a,Je(n,r,e.cfg.iterations,s)),c=await oe(a),g=await Br(),f=await se(c,g.pkcs8,_n(n,r));M(g.pkcs8);let d=null;e.cfg.recovery==="code"&&(d=await ir(n,r,a));let p=await se(c,a,bn(n,r));M(a);let m=await Wt(g.pubRaw),h=Date.now(),_=[{id:F(Z(6)),p:"password",kdf:{a:"PBKDF2-SHA256",it:e.cfg.iterations,s},iv:F(u.iv),ct:F(u.ct),created:h}];d&&_.push(d.wrap);let w={v:1,alg:"ECDH-P-256",user_id:r,wraps:_,ik:{iv:F(f.iv),ct:F(f.ct)},self:{iv:F(p.iv),ct:F(p.ct)},pub:F(g.pubRaw),fpr:m,pins:null,created:h,updated:h};await this.postRecord({v:1,alg:"ECDH-P-256",user_id:r,pub:F(g.pubRaw),fpr:m,created:h},{table:{name:e.cfg.table,access_group:"authorized"},index:{name:"pubkey",value:r}});let b=await this.postRecord(w,{table:{name:e.cfg.table,access_group:"private"}}),E=await yt.call(this,e);if(E&&E.record_id!==b.record_id){await wn.call(this,e,E,t);return}e.mk=c,e.ikPriv=g.priv,e.pubRaw=g.pubRaw,e.fpr=m,e.keyringRecordId=b.record_id,d&&(e.pendingRecoveryCode=d.code),e.user_id=r,e.pins={},e.status="unlocked",e.reason="";}async function wn(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 l("The encryption keyring does not belong to this user.",{code:"ENCRYPTION_KEYRING_CORRUPT"});let a=(Array.isArray(s?.wraps)?s.wraps:[]).filter(g=>g.p==="password");if(!a.length)throw new l("The keyring has no password wrap.",{code:"ENCRYPTION_KEYRING_CORRUPT"});a.sort((g,f)=>(f.created||0)-(g.created||0));let u=null;for(let g of a)try{let f=V(g.kdf.s),d=await Ue(r,f,g.kdf.it,ze(i,n));u=await ae(d,V(g.iv),V(g.ct),Je(i,n,g.kdf.it,g.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 oe(u);M(u),await sr.call(this,e,t,c);}async function sr(e,t,r){let n=this.user.user_id,i=t.data,s=await ae(r,V(i.ik.iv),V(i.ik.ct),_n(e.scope,n)),o=await Ht(s);M(s);let a={};if(i.pins&&typeof i.pins=="object"&&i.pins.ct)try{let u=await ae(r,V(i.pins.iv),V(i.pins.ct),K(`${X}|pins|${e.scope}|${n}`));a=JSON.parse(je(u)),M(u);}catch{a={};}e.mk=r,e.ikPriv=o,e.pubRaw=V(i.pub),e.fpr=i.fpr,e.keyringRecordId=t.record_id,e.user_id=n,e.pins=a,e.status="unlocked",e.reason="";}async function bt(e){let t=O.call(this);if(!t||!this.user?.user_id)return;if(!Kt()){t.status="locked",t.reason="NO_WEB_CRYPTO";return}if(this.user?.is_openid){t.status="locked",t.reason="OPENID_UNSUPPORTED";return}if(t.cfg.minPasswordLength&&e.length<t.cfg.minPasswordLength){t.status="locked",t.reason="WEAK_PASSWORD";return}t.scope=De.call(this);let r=await yt.call(this,t);r?await wn.call(this,t,r,e):await Uo.call(this,t,e),t.cfg.persistDevice&&await Tn.call(this,t).catch(()=>{});}async function En(e){await this.__connection;let t=O.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 bt.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 An(e){let t=O.call(this);return t?(e?.forgetDevice&&await cr.call(this,t).catch(()=>{}),Xt.call(this),this.__cached_requests={},{status:t.status}):{status:"disabled"}}async function Rn(e,t){let r=O.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 i=(await this.getRecords({record_id:r.keyringRecordId},{limit:1}))?.list?.[0];if(!i)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 s=this.user.user_id,o=i.data,a=(o.wraps||[]).filter(h=>h.p==="password");a.sort((h,_)=>(_.created||0)-(h.created||0));let u=null;for(let h of a)try{let _=await Ue(e,V(h.kdf.s),h.kdf.it,ze(r.scope,s));u=await ae(_,V(h.iv),V(h.ct),Je(r.scope,s,h.kdf.it,h.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=Z(16),g=F(c),f=await Ue(t,c,r.cfg.iterations,ze(r.scope,s)),d=await se(f,u,Je(r.scope,s,r.cfg.iterations,g));M(u);let p=Date.now(),m=(o.wraps||[]).concat([{id:F(Z(6)),p:"password",kdf:{a:"PBKDF2-SHA256",it:r.cfg.iterations,s:g},iv:F(d.iv),ct:F(d.ct),created:p}]);await this.postRecord(Object.assign({},o,{wraps:m,updated:p}),{record_id:r.keyringRecordId});}async function In(){let e=O.call(this);if(!e||e.status!=="unlocked"||!e.keyringRecordId)return;let r=(await this.getRecords({record_id:e.keyringRecordId},{limit:1}))?.list?.[0];if(!r)return;let n=r.data,i=(n.wraps||[]).filter(o=>o.p==="password").sort((o,a)=>(a.created||0)-(o.created||0)),s=(n.wraps||[]).filter(o=>o.p!=="password");i.length<=1||await this.postRecord(Object.assign({},n,{wraps:[i[0]].concat(s),updated:Date.now()}),{record_id:e.keyringRecordId});}function or(){return typeof indexedDB<"u"&&!!indexedDB}function ar(){return new Promise((e,t)=>{let r=indexedDB.open(Ro,1);r.onupgradeneeded=()=>{let n=r.result;n.objectStoreNames.contains(we)||n.createObjectStore(we);},r.onsuccess=()=>e(r.result),r.onerror=()=>t(r.error);})}function lr(e){return `${e.scope}#${this.user?.user_id}`}async function Tn(e){if(!or()||!e.mk)return;let t=await ar();await new Promise((r,n)=>{let i=t.transaction(we,"readwrite");i.objectStore(we).put({mk:e.mk,keyringRecordId:e.keyringRecordId,saved:Date.now()},lr.call(this,e)),i.oncomplete=()=>r(),i.onerror=()=>n(i.error);}),t.close();}async function Do(e){if(!or())return null;let t=await ar(),r=await new Promise((n,i)=>{let o=t.transaction(we,"readonly").objectStore(we).get(lr.call(this,e));o.onsuccess=()=>n(o.result||null),o.onerror=()=>i(o.error);});return t.close(),r&&r.mk?r:null}async function cr(e){if(!or())return;let t=await ar();await new Promise((r,n)=>{let i=t.transaction(we,"readwrite");i.objectStore(we).delete(lr.call(this,e)),i.oncomplete=()=>r(),i.onerror=()=>n(i.error);}),t.close();}function Pn(){let e=O.call(this);!e||e.ready||(e.unlocking=true,e.ready=xo.bind(this)().catch(()=>false).then(()=>{e.unlocking=false;}));}async function xo(){let e=O.call(this);if(!e||!this.user?.user_id||!e.cfg.persistDevice||!Kt())return false;e.scope=De.call(this);try{let t=await Do.call(this,e);if(!t)return !1;let r=await yt.call(this,e);return r?(await sr.call(this,e,r,t.mk),!0):(await cr.call(this,e).catch(()=>{}),!1)}catch{return e.status="locked",e.reason="NO_SESSION_KEY",false}}async function ur(e){let t=O.call(this);if(!t)throw new l("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(p=>p.user_id===s&&p.data?.pub);if(!c.length)return null;c.sort((p,m)=>m.uploaded-p.uploaded);let g=V(c[0].data.pub),f=await Wt(g),d=t.pins[s];if(d&&d!==f)throw new l(`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 l(`No pinned key for user "${s}" and trustPolicy is "strict". Pin it first with pinPeerKey().`,{code:"ENCRYPTION_PEER_NOT_PINNED"});t.pins[s]=f,i=true;}return {pubRaw:g,fpr:f}})().finally(()=>t.peerInflight.delete(s)),t.peerInflight.set(s,o));let a=await o;a&&t.peerPub.set(s,a),r[s]=a;})),i&&await Nn.call(this,t).catch(()=>{}),r}async function Sn(e,t){let r=De.call(this),n=e.dek.get(t);if(n)return {entry:n,scope:r};let i=await _e.call(this,t);if(!i)throw new l(`Record "${t}" not found.`,{code:"NOT_EXISTS"});if(i.encrypted?.status==="failed"&&i.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(!i.encrypted)return null;if(i.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 s=e.dek.get(i.record_id)||e.dek.get(t);if(!s)throw new l(`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 dr(e,t){let r=O.call(this);if(!r)return;let n=await Sn.call(this,r,e);if(!n)return;let{entry:i,scope:s}=n,o=this.user.user_id;if(i.own!==o)throw new 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 ur.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=er(i),g=Zt(s,i.own,i.anch,c),f=Object.assign({},i.recipients);for(let d of t)d!==o&&(f[d]=await pn.call(this,i.bytes,a[d],s,c,i.own,d,g));await Lo.call(this,r,e,i,f);}async function kn(e,t){let r=O.call(this);if(!r)return;let n=await Sn.call(this,r,e);if(!n)return;let{entry:i}=n,s=this.user.user_id;if(i.own!==s)throw new l("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),a=await _e.call(this,e);if(!a)throw new l(`Record "${e}" not found.`,{code:"NOT_EXISTS"});Co(a,e);let u={};if(o.length){u=await ur.call(this,o);let c=o.filter(g=>!u[g]);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 dr.call(this,a.record_id||e,o);}function Co(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 Lo(e,t,r,n){let i=await Oo.call(this,t);if(!i)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 s=Object.assign({},i,{k:n});e.passthrough.set(t,s),await this.postRecord(void 0,{record_id:t});}async function Oo(e){let t=O.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&&mt(r.data)?r.data:null}async function vn(e){let t=O.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 Nn.call(this,t);}async function Nn(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 se(e.mk,K(JSON.stringify(e.pins)),K(`${X}|pins|${e.scope}|${e.user_id}`));await this.postRecord(Object.assign({},r.data,{pins:{iv:F(n.iv),ct:F(n.ct)},updated:Date.now()}),{record_id:e.keyringRecordId});}function Un(){let e=O.call(this);if(!e||!e.pendingRecoveryCode)return null;let t=e.pendingRecoveryCode;return e.pendingRecoveryCode="",t}async function Dn(e){await this.__connection;let t=O.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=De.call(this);let r=this.user.user_id,n=await yt.call(this,t);if(!n)throw new l("This account has no encryption keyring, so there is nothing to recover.",{code:"NOT_EXISTS"});let i=await vo(t.scope,r,n.data?.wraps||[],e.code);if(!i)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 s=await oe(i);await sr.call(this,t,n,s);let o=false,a=null,u=(n.data?.wraps||[]).slice();if(e.password&&(u=u.filter(c=>c.p!=="password"),u.push(await No(t,t.scope,r,e.password,i)),o=true),t.cfg.recovery==="code"){let c=await ir(t.scope,r,i);u=u.filter(g=>g.p!=="recovery"),u.push(c.wrap),a=c.code;}return M(i),await this.postRecord(Object.assign({},n.data,{wraps:u,updated:Date.now()}),{record_id:n.record_id}),t.cfg.persistDevice&&await Tn.call(this,t).catch(()=>{}),{status:t.status,repaired:o,recoveryCode:a}}async function xn(){await this.__connection;let e=O.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 i=await ae(e.mk,V(n.iv),V(n.ct),bn(e.scope,e.user_id)),s=await ir(e.scope,e.user_id,i);M(i);let o=(r.data.wraps||[]).filter(a=>a.p!=="recovery").concat([s.wrap]);return await this.postRecord(Object.assign({},r.data,{wraps:o,updated:Date.now()}),{record_id:e.keyringRecordId}),{recoveryCode:s.code}}var ht="__skenc__",Cn="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";function Mo(e){if(e===0)return "0";let t="";for(;e>0;)t=Cn[e%62]+t,e=Math.floor(e/62);return t}function Fo(e){let t=0;for(let r of e){let n=Cn.indexOf(r);if(n<0)return NaN;t=t*62+n;}return t}function _t(e){if(typeof e!="string")return null;let t=e.lastIndexOf(ht);if(t<0)return null;let r=Fo(e.slice(t+ht.length));return Number.isFinite(r)?{key:e.slice(0,t),plainSize:r}:null}function fr(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=_t(t[10]);return r?{recordId:t[5],recordOwner:t[3],filename:t[t.length-1],plainSize:r.plainSize}:null}catch{return null}}function Ln(e,t){return {service:this.service,owner:this.owner,recordOwner:t,recordId:e}}async function On(e,t,r){let n=O.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(_t(t))throw new l(`"${ht}" is reserved in an upload form key.`,{code:"INVALID_PARAMETER"});if(t===Ye)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},a=await tn(i.bytes,s,Ln.call(this,e,i.own),o);return M(s),{key:`${t}${ht}${Mo(r.size)}`,file:new File([a],r.name,{type:"application/octet-stream"}),encrypted:true}}async function Mn(e,t){let r=O.call(this),n=fr(e);if(!r||!n)return t;let i=r.dek.get(n.recordId);if(!i)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 s=new Uint8Array(await t.arrayBuffer());if(!zt(s))throw new l("This file is marked as encrypted but its contents are not an encrypted container.",{code:"ENCRYPTION_FILE_CORRUPT"});let o=await rn(i.bytes,s,Ln.call(this,n.recordId,n.recordOwner)),a=o.meta&&o.meta.t||"application/octet-stream";return new Blob([o.bytes],{type:a})}function qo(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 Vo(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 gr(e,t,r){let n=O.call(this);if(!n)return [];let i=await _e.call(this,e);if(!i)return [];let s=t==="decrypt"?qo(i):Vo(i);if(!s.length)return [];let o=[],a=new FormData,u=false;for(let c of s){let g=i.bin[c.formKey].find(d=>d.url===c.url);if(!g||typeof g.getFile!="function")continue;let f=await g.getFile("blob");f&&(a.append(c.formKey,new File([f],c.filename,{type:f.type||"application/octet-stream"})),o.push(c.url),u=true);}if(!u)return [];if(t==="decrypt"){let c=n.dek.get(e);c&&(M(c.bytes),n.dek.delete(e));}return await this.uploadFiles(a,{record_id:e,progress:r}),o}var B=null;function pr(e){let t={tkid:"ticket_id",cond:"condition",stmp:"timestamp",actn:"action",cnt:"count",ttl:"time_to_live",plch:"placeholder",hash:"hash",desc:"description",pmc:"limit_per_user"},r={};for(let n in e)if(n==="tkid"){let i=e[n].split("#");if(i.length===1){r.ticket_id=i[0];continue}r.ticket_id=i[1],r.consume_id=i[2],r.user_id=i[3];let s=i[2].slice(-4);if(r.is_test=s===":CHK",!e.stmp){let o=i[2].slice(0,-4);/^[0-9]+$/.test(o)?r.timestamp=parseInt(o,10):r.timestamp=ne(i[2].slice(0,-4));}}else t[n]?r[t[n]]=e[n]:r[n]=e[n];return r}async function qn(e){if(!e.ticket_id)throw new l("Ticket ID is required.",{code:"INVALID_PARAMETER"});if(!e.method)throw new l('Method is required. Should be either "GET" or "POST"',{code:"INVALID_PARAMETER"});let t=e.ticket_id;await this.__connection;let r=await P.bind(this)(`https://${this.service.slice(0,4)}.${this.customApiDomain}/auth/consume/${this.service}/${this.owner}/${t}`,e?.data||{},{method:e.method,auth:!!e?.auth});return pr(r)}async function Vn(e,t){await this.__connection;let r=await P.bind(this)("ticket",Object.assign({exec:"list"},e||{}),{auth:true,fetchOptions:t});return r.list=r.list.map(pr),r}async function $n(e,t){await this.__connection;let r=await P.bind(this)("ticket",Object.assign({exec:"consumed"},e||{}),{auth:true,fetchOptions:t});return r.list=r.list.map(pr),r}async function jn(e){return P.bind(this)("register-ticket",Object.assign({exec:"reg"},e),{auth:true})}async function Bn(e){return P.bind(this)("register-ticket",Object.assign({exec:"unreg"},e),{auth:true})}var Wo=3600;async function Ce(){if(await this.__connection,this.session){let e=Math.floor(Date.now()/1e3),r=this.session.getIdToken().getExpiration();if(r<e+Wo){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),ye.bind(this)(),new l("User login is required.",{code:"INVALID_REQUEST"})}function Fn(e,t){return new Promise((r,n)=>{t.refreshSession(e.getRefreshToken(),(i,s)=>{this.log("getSession:refreshSessionCallback",{refreshErr:i,refreshedSession:s}),i?(ye.bind(this)(),n(i)):s.isValid()?r(s):(ye.bind(this)(),n(new l("Invalid session.",{code:"INVALID_REQUEST"})));});})}function J(){if(!this.userPool)throw new l("User pool is missing",{code:"INVALID_REQUEST"});let e=()=>{let s=B.getSignInUserSession().getIdToken().payload||null,o=$e(s);return this.log("normalized user attribute",o),this.__user=o,o},t=async s=>new Promise((o,a)=>{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),ye.bind(this)(),a(null);return}let g=f=>{let d=f.getIdToken().payload;if(this.log("getSession:respond:sessionAttribute",d),d["custom:service"]!==this.service)throw this.log("getSession:respond","invalid service, signing out"),ye.bind(this)(),new l("Invalid session.",{code:"INVALID_REQUEST"});return this.session=f,e(),c||this._runOnUserUpdateListeners(this.user),this.session};B.getSession((f,d)=>{if(this.log("getSession:getSessionCallback",{err:f,session:d}),!d){ye.bind(this)(),a(new l("Current session does not exist.",{code:"INVALID_REQUEST"}));return}if(f){Fn.bind(this)(d,B).then(w=>o(g(w))).catch(a);return}let p=Math.floor(Date.now()/1e3),m=d.getIdToken(),h=m.getExpiration(),_=h<p;if(this.log("getSession:currentTime",p),this.log("getSession:idTokenExp",h),this.log("getSession:isExpired",_),this.log("getSession:existingBearerToken",this.bearerToken),this.bearerToken=m.getJwtToken(),_||u||!d.isValid())Fn.bind(this)(d,B).then(w=>o(g(w))).catch(a);else try{o(g(d));}catch(w){a(w);}});}),r=(s,o)=>{let a=o||s.includes(this.service+"-")?s:this.service+"-"+W.hash(s);return {cognitoUser:new CognitoUser({Username:a,Pool:this.userPool}),cognitoUsername:a}};return {getSession:t,authenticateUser:(s,o,a=false,u=false)=>new Promise((c,g)=>{this.__request_signup_confirmation=null,this.__disabledAccount=null;let f=r(s,a),d=f.cognitoUsername,p=new AuthenticationDetails({Username:d,Password:o});f.cognitoUser.authenticateUser(p,{newPasswordRequired:(m,h)=>{this.__disabledAccount=null,this.__request_signup_confirmation=d,m["custom:signup_ticket"]==="PASS"||m["custom:signup_ticket"]==="MEMBER"||m["custom:signup_ticket"]==="OIDPASS"?f.cognitoUser.completeNewPasswordChallenge(o,{},{onSuccess:_=>{B=f.cognitoUser,t().then(async w=>{if(O.call(this))try{await bt.bind(this)(o);}catch(b){this.log("encryption:ensureKeyring:failed",b);}c(this.user);});},onFailure:_=>{g(new l(_.message||"Failed to authenticate user.",{code:_.code}));}}):g(new l("User's signup confirmation is required.",{code:"SIGNUP_CONFIRMATION_NEEDED"}));},onSuccess:m=>t({skipUserUpdateEventTrigger:true}).then(async h=>{if(this.__disabledAccount=null,O.call(this))try{await bt.bind(this)(o);}catch(_){this.log("encryption:ensureKeyring:failed",_);}this._runOnLoginListeners(this.user),this._runOnUserUpdateListeners(this.user),c(this.user);}),onFailure:m=>{let h=[],{parsed:_,code:w}=Et(m),b=typeof m?.message=="string"?m.message:"";if(w==="NotAuthorizedException"?b.includes("User is disabled.")?(this.__disabledAccount=d,h=["This account is disabled.","USER_IS_DISABLED"]):u?h=["The account already exists.","ACCOUNT_EXISTS"]:h=["Incorrect username or password.","INCORRECT_USERNAME_OR_PASSWORD"]:w==="UserNotFoundException"?h=["Incorrect username or password.","INCORRECT_USERNAME_OR_PASSWORD"]:w==="UserNotConfirmedException"?(this.__request_signup_confirmation=d,h=["User's signup confirmation is required.","SIGNUP_CONFIRMATION_NEEDED"]):(w==="TooManyRequestsException"||w==="LimitExceededException")&&(h=["Too many attempts. Please try again later.","REQUEST_EXCEED"]),_.code==="SIGNUP_CONFIRMATION_NEEDED"&&(this.__request_signup_confirmation=d),h.length){let E=h[1],R=h[0];g(new l(R,{code:E,cause:m}));}else g(_);}});}),createCognitoUser:r,signup:(s,o,a)=>new Promise((u,c)=>{this.userPool.signUp(s,o,a,null,(g,f)=>{if(g){let{parsed:d,code:p}=Et(g),m=[];p==="UsernameExistsException"?m=["The account already exists.","EXISTS"]:p==="InvalidPasswordException"?m=["Invalid password. Password must be at least 6 characters.","INVALID_PARAMETER"]:p==="InvalidParameterException"?m=[d.message||"Invalid parameter.","INVALID_PARAMETER"]:p==="TooManyRequestsException"||p==="LimitExceededException"?m=["Too many attempts. Please try again later.","REQUEST_EXCEED"]:p==="CodeDeliveryFailureException"?m=["Failed to deliver verification code.","CODE_DELIVERY_FAILURE"]:p==="UserLambdaValidationException"&&(m=[d.message||"Signup validation failed.","INVALID_REQUEST"]),m.length?c(new l(m[0],{code:m[1],cause:g})):c(d);return}u(f);});})}}function Et(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 l(o,{code:s,cause:e}),code:t}}async function Kn(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 Hn(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 P.bind(this)("openid-logger",t),n=r.logger.split("#"),i=this.service+"-"+n[0],s=n[1];return {userProfile:await J.bind(this)().authenticateUser(i,s,true,true),openid:r.openid}}function Qo(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 Go(e){let t=e.split(".");if(t.length!==3)throw new Error("Invalid JWT format");let n=t[1].replace(/-/g,"+").replace(/_/g,"/"),i=Qo(n);return JSON.parse(i)}async function Wn(e){await this.__authConnection,this.log("loginWithToken:params",e),e=y.Params(e,{idToken:"string",accessToken:"string",refreshToken:"string"},["idToken"]);let t=Go(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=$e(t),this.session=null,e.accessToken&&e.refreshToken)try{if(this.session=new CognitoUserSession({IdToken:new CognitoIdToken({IdToken:e.idToken}),AccessToken:new CognitoAccessToken({AccessToken:e.accessToken}),RefreshToken:new CognitoRefreshToken({RefreshToken:e.refreshToken})}),this.log("loginWithToken:session",this.session),this.log("loginWithToken:CognitoUser",CognitoUser),this.log("loginWithToken:userPool",this.userPool),CognitoUser&&this.userPool){this.log("loginWithToken:cognito:username",t["cognito:username"]);let n={Username:t["cognito:username"],Pool:this.userPool};this.log("loginWithToken:cognitoUserParams",n),B=new 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 Xe.bind(this)(),false)}async function ye(e=false){let t=null;B&&(e?t=new Promise((n,i)=>{B.globalSignOut({onSuccess:s=>{this.log("globalSignOut:success",s),n(s);},onFailure:s=>{this.log("globalSignOut:error",s),i(s);}});}):B.signOut()),Xt.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 Xe(e){await this.__connection;let{data:t}=j(e);return await ye.bind(this)(t?.global),"SUCCESS: The user has been logged out."}async function Qn(){if(!this.__request_signup_confirmation)throw new l("Least one login attempt is required.",{code:"INVALID_REQUEST"});return await P.bind(this)("confirm-signup",{username:this.__request_signup_confirmation})}async function Gn(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 P.bind(this)("recover-account",{username:this.__disabledAccount,redirect:e}),"SUCCESS: Recovery e-mail has been sent."}async function hr(e){let t=y.Params(e,{username:"string",email:"string",password:"string"},["password"]);if(await this.__authConnection,t.email)try{y.Email(t.email);}catch{t.username=t.email,delete t.email;}if(!t.username&&!t.email)throw new l('Least one of "username" or "email" is required.',{code:"INVALID_PARAMETER"});return await J.bind(this)().authenticateUser(t.username||t.email,t.password)}async function zn(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 Xe.bind(this)(),t=y.Params(t||{},{email_subscription:c=>{if(typeof c!="boolean")throw new l('"option.email_subscription" should be type: <boolean>.',{code:"INVALID_PARAMETER"});if(!t?.signup_confirmation)throw new l('"option.signup_confirmation" is required for email subscription.',{code:"INVALID_PARAMETER"});return c},signup_confirmation:c=>{let g=c;if(typeof c=="string")g=y.Url(c);else if(typeof c=="boolean")g=c;else throw new l('"option.signup_confirmation" should be type: <string | boolean>.',{code:"INVALID_PARAMETER"});if(g&&!n.email)throw new l('"email" is required for signup confirmation.',{code:"INVALID_PARAMETER"});return g},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 i=t?.login||false;if(n.signup_confirmation=t?.signup_confirmation||false,n.email_subscription=t?.email_subscription||false,n.email_public&&!n.signup_confirmation)throw new 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 s=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 P.bind(this)("signupkey",{username:s.cognitoUsername,signup_confirmation:typeof n.signup_confirmation=="boolean"?JSON.stringify(n.signup_confirmation):n.signup_confirmation,email_subscription:n.email_subscription,template_confirmation:t?.template?.signup_confirmation||"",template_welcome:t?.template?.welcome||""})).split(":"),a=o.slice(1).join(":"),u=[new CognitoUserAttribute({Name:"custom:signup",Value:o[0]}),new CognitoUserAttribute({Name:"locale",Value:a.split("#")[1]}),new CognitoUserAttribute({Name:"custom:signup_ticket",Value:a})];for(let c in r){let g=["email_public","address_public","gender_public","birthdate_public","phone_number_public","misc","service","owner"];n[c]!==""&&(c==="username"||c==="password"||c==="access_group"||(g.includes(c)?u.push(new CognitoUserAttribute({Name:"custom:"+c,Value:n[c]})):u.push(new CognitoUserAttribute({Name:c,Value:n[c]}))));}return await J.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?hr.bind(this)({email:n.username||n.email,password:n.password}):"SUCCESS: The account has been created."}async function Jn(){await this.__connection;let e=await P.bind(this)("remove-account",{disable:this.__user.user_id},{auth:true});return await Xe.bind(this)(),e}async function Yn(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)=>{J.bind(this)().createCognitoUser(t.email).cognitoUser.confirmPassword(r,n,{onSuccess:a=>{i("SUCCESS: New password has been set.");},onFailure:a=>{s(new l(a?.message||"Failed to reset password.",{code:a?.code||"ERROR",cause:a}));}});})}async function Xn(e,t,r){await this.__connection;let n;if(!B)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 i,s=r?.template?.verification;if(s!==void 0){if(typeof s!="string"||!s)throw new l('"template.verification" should be a non-empty <string> (template message_id).',{code:"INVALID_PARAMETER"});i={template_verification:s};}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(g=>{a(g);}):o("SUCCESS: Verification code has been sent.");},onFailure:c=>{a(new l(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 Zn(e,t){return Xn.bind(this)("phone_number",e,t)}function ei(e,t){return Xn.bind(this)("email",e,t)}async function ti(e,t){await this.__connection;let r=y.Params(e,{email:s=>y.Email(s)},["email"]),n,i=t?.template?.verification;if(i!==void 0){if(typeof i!="string"||!i)throw new l('"template.verification" should be a non-empty <string> (template message_id).',{code:"INVALID_PARAMETER"});n={template_verification:i};}return new Promise(async(s,o)=>{J.bind(this)().createCognitoUser(r.email).cognitoUser.forgotPassword({onSuccess:u=>{s("SUCCESS: Verification code has been sent.");},onFailure:u=>{let{parsed:c,code:g}=Et(u),f={UserNotFoundException:"NOT_EXISTS",InvalidParameterException:"INVALID_PARAMETER",NotAuthorizedException:"INVALID_REQUEST",LimitExceededException:"REQUEST_EXCEED",TooManyRequestsException:"REQUEST_EXCEED",CodeDeliveryFailureException:"CODE_DELIVERY_FAILURE"}[g]||c.code||g||"ERROR";o(new l(c.message,{code:f,cause:u}));}},n);})}async function ri(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),O.call(this)&&await Rn.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 l("Invalid password parameter.",{code:"INVALID_PARAMETER"}));else if(i?.code==="NotAuthorizedException")n(new l("Incorrect password.",{code:"INVALID_REQUEST"}));else if(i?.code==="TooManyRequestsException"||i?.code==="LimitExceededException")n(new l("Too many attempts. Please try again later.",{code:"REQUEST_EXCEED"}));else {let{parsed:o}=Et(i);n(o);}return}O.call(this)&&In.bind(this)().catch(o=>this.log("encryption:prune:failed",o)),r("SUCCESS: Password has been changed.");});})}async function ni(e){if(await this.__connection,!this.session)throw new l("User login is required.",{code:"INVALID_REQUEST"});let t=y.Params(e||{},{user_id:i=>y.UserId(i),email:i=>y.Email(i),address:i=>{if(!i)return "";if(typeof i=="string")return i;if(typeof i=="object")return JSON.stringify(i)},name:"string",gender:"string",birthdate:i=>i?y.Birthdate(i):"",phone_number:i=>i?y.PhoneNumber(i):"",email_public:"boolean",phone_number_public:"boolean",address_public:"boolean",gender_public:"boolean",birthdate_public:"boolean",misc:"string",picture:i=>i?y.Url(i):"",profile:i=>i?y.Url(i):"",family_name:"string",given_name:"string",middle_name:"string",nickname:"string",website:i=>i?y.Url(i):""});if(t&&typeof t=="object"&&!Object.keys(t).length)return this.user;t.email&&(t.preferred_username=this.service+"-"+W.hash(t.email));let r=[["email_public","email_verified","User's e-mail should be verified to set"],["phone_number_public","phone_number_verified","User's phone number should be verified to set"]];if(this.__user){for(let i of r)if(t[i[0]]&&!this.__user[i[1]])throw new l(`${i[2]} "${i[0]}" to true.`,{code:"INVALID_REQUEST"})}let n=[];for(let i in t){if(t[i]===this.user[i]){n.push(i);continue}if(["email_public","phone_number_public","address_public","gender_public","birthdate_public","misc"].includes(i)){let o=t[i];typeof o=="boolean"&&(o=o?"1":"0"),t["custom:"+i]=o,n.push(i);}}for(let i of n)delete t[i];if(t.user_id)if(t.user_id===this.user.user_id)delete t.user_id;else return P.bind(this)("admin-edit-profile",{attributes:t},{auth:true});if(t&&typeof t=="object"&&Object.keys(t).length){let i=[];for(let s in t)i.push(new CognitoUserAttribute({Name:s,Value:t[s]}));return await new Promise((s,o)=>{B?.updateAttributes(i,(a,u)=>{a&&o([a?.code||a?.name,a?.message||"Failed to update user settings."]),s(u);});}),await J.bind(this)().getSession({refreshToken:true}),this.user}return this.user}async function ii(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:i=>Array.isArray(i)?i.map(s=>y.UserId(s)):y.UserId(i),email:"string",phone_number:"string",locale:i=>{if(typeof i!="string"||typeof i=="string"&&i.length>5)throw new 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"];if(e=y.Params(e,{searchFor:["user_id","name","email","phone_number","address","gender","birthdate","locale","subscribers","timestamp","access_group","approved"],condition:[">",">=","=","<","<=","gt","gte","eq","lt","lte",()=>"="],value:i=>{let s=r[e.searchFor];if(typeof s=="function")return s(i);if(typeof i!==s)throw new l(`Value does not match the type of "${e.searchFor}" index.`,{code:"INVALID_PARAMETER"});return i},range:i=>{let s=r[e.searchFor];if(typeof s=="function")return s(i);if(typeof i!==s)throw new l(`Range does not match the type of "${e.searchFor}" index.`,{code:"INVALID_PARAMETER"});return i}},n),e?.condition&&e?.condition!=="="&&e.hasOwnProperty("range"))throw new l("Conditions does not apply on range search.",{code:"INVALID_PARAMETER"});if(e.searchFor==="user_id"&&(e.condition!=="="||e.range))throw new l(`Conditions are not allowed on "${e.searchFor}"`,{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 P.bind(this)("get-users",e,{auth:true,fetchOptions:t})}async function si(e){await this.__connection;let t=await P.bind(this)("last-verified-email",e,{auth:true});return t.includes("SUCCESS")?(await J.bind(this)().getSession({refreshToken:true}),this.user):t}async function oi(e){return await this.__connection,e=y.Params(e,{username:y.Email,redirect:y.Url},["username"]),await P.bind(this)("request-username-change",e,{auth:true})}var Le=null,li=typeof SubmitEvent<"u",Jo=typeof HTMLFormElement<"u",et=Y(),mr=0;function ci(e){if(!e)return null;let t=Number(e);if(Number.isFinite(t))return Math.max(0,t*1e3);let r=Date.parse(e);return Number.isNaN(r)?null:Math.max(0,r-Date.now())}function yr(e,t){return t>0?e/t*100:0}var ai=e=>{let{auth:t,type:r,endpoints:n,stable:i}=e,s=n[0],o=n[1];if(mr++,r==="admin"){let a=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(!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 i?a[0]:a[mr%a.length]}throw new l("Invalid gateway type.",{code:"INVALID_REQUEST"})};async function Yo(e,t,r){let n=await Promise.all([this.admin_endpoint,this.record_endpoint]),i=n[0],s=n[1],o=e.split("?"),a=o.length>1?"?"+o[1]:"";switch(e=o[0],e){case "get-users":return i.get_users_private+e+a;case "service":return i.service_public+e+a;case "get-newsletters":case "get-public-newsletters":case "subscribe-newsletter":case "subscribe-public-newsletter":case "signupkey":case "admin-newsletter-request":case "admin-signup":case "confirm-signup":case "openid-logger":case "block-account":case "admin-edit-profile":case "remove-account":case "post-secure":case "recover-account":case "mock":case "grant-access":case "last-verified-email":case "ticket":case "register-ticket":case "get-newsletter-subscription":case "request-username-change":case "send-inquiry":case "register-newsletter-group":case "newsletter-group-endpoint":case "invitation-list":case "csr":case "csr-poll":case "csr-cancel":case "csr-finalize":return ai.bind(this)({auth:t,type:"admin",endpoints:n})+e+a;case "post-record":return (t?s.post_private:s.post_public)+e+a;case "get-records":return (t?s.get_private:s.get_public)+e+a;case "del-files":case "del-records":return s.del_private+e+a;case "store-subscription":case "get-vapid-public-key":case "push-notification":case "delete-subscription":case "subscription":case "get-subscription":case "get-table":case "get-tag":case "get-uniqueid":case "get-index":case "get-signed-url":case "extract-file-text":case "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 ai.bind(this)({auth:t,type:"record",endpoints:n,stable:r})+e+a;default:return y.Url(e)+a}}var Ze={};function ui(){Le&&(Le.terminate(),Le=null);}async function P(e,t=null,r,n){this.log("request",{url:e,data:t,options:r,_etc:n||{}}),r=r||{};let{auth:i=false,method:s="post",bypassAwaitConnection:o=false}=r;s=s.toUpperCase();let a=null,u=t?.service||this.service,c=t?.owner||this.owner,g=null,f=await Yo.bind(this)(e,!!i,!!r.stableGateway);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;(i||d)&&(g=await Ce.bind(this)());let p={},{fetchMore:m=false,progress:h}=r?.fetchOptions||{};if(r?.fetchOptions&&Object.keys(r.fetchOptions).length){for(let v of ["limit","startKey","ascending"])if(r.fetchOptions.hasOwnProperty(v)){if(v==="startKey"&&r.fetchOptions[v]===null)continue;p[v]=r.fetchOptions[v];}p=y.Params(p,{limit:v=>{if(typeof v!="number")throw new 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:u,owner:c};Object.assign(_,p),t=j(t).data,t?t&&typeof t=="object"&&(t=Object.assign(_,t)):t=_;let w=`${s}:${i?"auth":"public"}:${e}`,b=(()=>{if(t&&typeof t=="object"&&Object.keys(t).length&&!(et&&t instanceof FormData)){let v=function(C){return typeof C=="object"&&C!==null?Object.keys(C).sort().reduce((L,q)=>(typeof C[q]=="object"&&C[q]!==null?L[q]=v(C[q]):L[q]=C[q],L),{}):C};return W.hash(w+"/"+JSON.stringify(v(t)))}return W.hash(w+"/"+u)})(),{requestKey:E,requestKeyWithStartKey:R}=Xo.bind(this)({params:t,url:e,fetchMore:m,hashedParams:b});if(!E||E&&typeof E=="object")return E;if(this.log("requestKey",R),typeof R=="string"&&Ze[R]instanceof Promise)return this.log("request:returning pending",R),Ze[R];let T={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&&(T["Content-Type"]=v);}else T["Content-Type"]="application/json";if(g&&(T.Authorization=g),r?.tokenHeaders){let v=(q,G)=>typeof q=="string"?q:q===true?G:null,C=v(r.tokenHeaders.accessToken,this.session?.accessToken?.jwtToken||null),L=v(r.tokenHeaders.idToken,this.bearerToken||this.session?.idToken?.jwtToken||g||null);C&&(T["X-Access-Token"]=C),L&&(T["X-Id-Token"]=L);}let D={public_identifier:this.__public_identifier,service:u,owner:c};T["Content-Meta"]=JSON.stringify(D),r.revalidate&&(T["Cache-Control"]="no-cache",T.Pragma="no-cache");let x={headers:T};if(r?.responseType&&(x.responseType=r.responseType),s==="GET"){if(t){let v=[];if(et&&t instanceof FormData?v=Array.from(t.entries()).map(([C,L])=>{let q=typeof L=="string"?L:L.name;return encodeURIComponent(C)+"="+encodeURIComponent(q)}):v=Object.keys(t).map(C=>{let L=t[C];return typeof L!="string"&&(L=JSON.stringify(L)),encodeURIComponent(C)+"="+encodeURIComponent(L)}),v.length){let C=f.includes("?")?f.endsWith("?")||f.endsWith("&")?"":"&":"?";f+=C+v.join("&");}}x.body=null;}else if(et&&t instanceof FormData)x.body=t;else if(T["Content-Type"]==="application/x-www-form-urlencoded"&&t&&typeof t=="object"){let v=new URLSearchParams;for(let C of Object.keys(t)){let L=t[C];v.append(C,typeof L=="string"?L:JSON.stringify(L));}x.body=v.toString();}else typeof t=="string"?x.body=t:x.body=t?JSON.stringify(t):null;if(x.method=s,Le===null){let v={batchSize:this.requestBatchSize,breakWhenError:false,onProgress:C=>{this.onBatchProcess.forEach(L=>L(C));}};Le=new Wi(v);}return this.log("request-opt",x),new Promise((v,C)=>{Le.add([async()=>{let L=di.bind(this)(f,x,h);Ze[R]=L;try{let q=ea.bind(this)({hashedParam:E,requestKeyWithStartKey:R,url:e,fetched:await L});return delete Ze[R],this.log("request:end",q),v(q),q}catch(q){throw delete Ze[R],this.log("request:err",q),C(q),q}}]);})}function Xo(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 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]?.[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+W.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],a=i;if(o){if(o==="end")return {requestKey:{list:[],startKey:"end",endOfList:true,startKeyHistory:s},requestKeyWithStartKey:a};a+=W.hash(o),t.startKey=JSON.parse(o);}return this.__cached_requests?.[r]?.[a]?{requestKey:this.__cached_requests[r][a],requestKeyWithStartKey:a}:{requestKeyWithStartKey:a,requestKey:i}}function Zo(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 di(e,t,r){return new Promise((n,i)=>{let s=new XMLHttpRequest;s.open(t.method||"GET",e);for(var o in t.headers||{})s.setRequestHeader(o,t.headers[o]);t.responseType&&(s.responseType=t.responseType),s.onload=()=>{if(s.status<400)if(t.responseType=="json"||t.responseType=="blob")n(s.response);else {let a=s.responseText;try{a=JSON.parse(a);}catch{}n(a);}else if(s.status===429){let a=s.getResponseHeader("Retry-After"),u=ci(a);u!==null?setTimeout(()=>{di(e,t,r).then(n,i);},u):i("Too many requests");}else {let a=s.status,u=["INVALID_CORS","INVALID_REQUEST","SERVICE_DISABLED","INVALID_PARAMETER","ERROR","EXISTS","NOT_EXISTS"],c=t.responseType=="blob"?s.response:s.responseText;try{c=JSON.parse(c);}catch{}if(typeof c=="string"){let g=c.split(":"),f=g.splice(0,1)[0].trim(),d=g.join(":").trim();i(new l(d||c,{code:u.includes(f)?f:"ERROR"}));}else if(typeof c=="object"&&c?.message){let g=c?.code||(a?a.toString():null)||"ERROR",f=c.message,d=c?.cause;typeof f=="string"&&(f=f.trim()),i(new l(f,{cause:d,code:g}));}else i(c);}},s.onerror=()=>i("Network error"),s.onabort=()=>i("Aborted"),s.ontimeout=()=>i("Timeout"),typeof r=="function"&&(s.onprogress=a=>{r({status:"download",progress:yr(a.loaded,a.total),loaded:a.loaded,total:a.total,abort:()=>s.abort()});},s.upload&&(s.upload.onprogress=a=>{r({status:"upload",progress:yr(a.loaded,a.total),loaded:a.loaded,total:a.total,abort:()=>s.abort()});})),s.send(t.body);})}function ea(e){let{hashedParam:t,requestKeyWithStartKey:r,url:n,fetched:i}=e;if(!i?.startKey)return i;this.__startKeyHistory.hasOwnProperty(n)||(this.__startKeyHistory[n]={}),this.__startKeyHistory[n].hasOwnProperty(t)||(this.__startKeyHistory[n][t]=[]);let s=i.startKey==="end"?"end":JSON.stringify(i.startKey);return this.__startKeyHistory[n][t].includes(s)||this.__startKeyHistory[n][t].push(s),this.__cached_requests?.[n]||(this.__cached_requests[n]={}),this.__cached_requests[n][r]=i,Object.assign({startKeyHistory:this.__startKeyHistory[n][t]},i)}async function tt(e,t){await this.__connection;let{record_id:r,service:n=this.service,progress:i}=t;if(!r)throw new l('"record_id" is required.',{code:"INVALID_PARAMETER"});if(li&&e instanceof SubmitEvent&&(e=e.target),Jo&&e instanceof HTMLFormElement&&(e=new FormData(e)),!et||!(e instanceof FormData))throw new l('"fileList" should be a FormData or HTMLFormElement.',{code:"INVALID_PARAMETER"});let o={reserved_key:Re(),service:n,request:"post"};t?.record_id&&(o.id=t.record_id);let a,u=(p,m,h)=>new Promise((_,w)=>{a=new XMLHttpRequest,a.open("POST",p),a.onload=()=>{let b=a.responseText;try{b=JSON.parse(b);}catch{}if(a.status>=200&&a.status<300)_(b);else if(a.status===429){let E=a.getResponseHeader("Retry-After"),R=ci(E);R!==null?setTimeout(()=>{u(p,m,h).then(_,w);},R):w("Too many requests");}else w(b);},a.onerror=()=>w("Network error"),a.onabort=()=>w("Aborted"),a.ontimeout=()=>w("Timeout"),a.upload&&typeof h=="function"&&(a.upload.onprogress=h),a.send(m);});function c(p){let m="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";if(p===0)return m[0];let h="";for(;p>0;)h=m[p%62]+h,p=Math.floor(p/62);return h}let g=[],f=[],d=[];for(let[p,m]of e.entries()){if(!(m instanceof File))continue;let h=await On.bind(this)(r,p,m),_=h.file,w=h.key,b=Object.assign({key:w+"/"+_.name,sizeKey:c(_.size),contentType:_.type||null},o),{fields:E=null,url:R,cdn:T}=await P.bind(this)("get-signed-url",b,{auth:!!this.__user});d.push(T);let U=new FormData;for(let D in E)U.append(D,E[D]);U.append("file",_);try{await u(R,U,typeof i=="function"?D=>i({status:"upload",progress:yr(D.loaded,D.total),currentFile:m,completed:g,failed:f,loaded:D.loaded,total:D.total,abort:()=>a.abort()}):null),g.push(m);}catch{f.push(m);}}return {completed:g,failed:f,bin_endpoints:d}}var At={};function k(e){let{preventMultipleCalls:t=false}=e||{};return function(r,n,i){let s=i.value;i.value=function(...o){let a=o[0],u=true,c=null,g="",f={},d=false;if(li&&a instanceof SubmitEvent){a.preventDefault();let w=window.location.href;c=a.target;let b=new URL(c.action);g=b.href;let E=g?g.match(/(?<=\{).*?(?=\})/g):"";if(E)for(let R of E){if(!R)continue;let T=c.querySelector(`[name="${R}"]`);if(T)if(T.type==="file")for(let U=0;U<=T.files.length-1;U++)T.files[U]&&(f[R]||(f[R]=[]),f[R].push(new Promise((D,x)=>{let v=new FileReader;v.onload=function(){D(v.result);},v.readAsDataURL(T.files[U]),v.onerror=x;})));else g=g.replace(`{${R}}`,T.value);}c.getAttribute("action")===null?u=false:d=b.href===w;}let p=async w=>{if(g)for(let b in f)f[b].length&&(g=g.replace(`{${b}}`,(await Promise.all(f[b])).join(",")));if(c&&u){let b=O.call(this)?Zo(w):w;window.sessionStorage.setItem(`${this.service}:${W.hash(g)}`,JSON.stringify(b)),d?window.location.replace(g):window.location.href=g;}return w},m,h=w=>{throw w instanceof l?w.name=n+"()":w=w instanceof Error?w:new l(w,{name:n+"()"}),w},_=async()=>{try{if(m=s.bind(this)(...o),m instanceof Promise){let w=await m;return p(w)}return p(m)}catch(w){throw h(w)}};if(t){let w=`${n}:${this?.__public_identifier||""}:${this?.service||""}:${this?.owner||""}`;return At?.[w]||(At[w]=_().finally(()=>{delete At[w];})),At[w]}return _()};}}async function fi(){await this.__connection;let e=`${this.service}:${W.hash(window.location.href.split("?")[0])}`,t=window.sessionStorage.getItem(e);if(window.sessionStorage.removeItem(e),t!==null){try{t=JSON.parse(t);}catch{}return t}return null}var ta=256,ra=256,na=256,gi=256,ia="\u{10FFFF}",sa=/[\u0000-\u001F\u007F]|\u{10FFFF}/u,oa={"/":"%2F","!":"%21","*":"%2A","#":"%23"},aa={"%2F":"/","%21":"!","%2A":"*","%23":"#"};function la(e){return e.replace(/%/g,"%25").replace(/[\/!*#]/g,r=>oa[r]||r)}function le(e){return typeof e!="string"?e:e.replace(/%(2F|21|2A|23)/gi,r=>{let n=r.toUpperCase();return aa[n]||r}).replace(/%25/gi,"%")}function de(e,t,r={}){let{allowEmpty:n=false,maxLength:i,blockKeyDelimiters:s=false,disallowLeadingDollar:o=false,onlyAlphanumeric:a=false}=r;if(typeof e!="string")throw new 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(i&&e.length>i)throw new l(`"${t}" should be <= ${i} characters.`,{code:"INVALID_PARAMETER"});if(sa.test(e)||e.includes(ia))throw new l(`"${t}" cannot include control characters or unsupported sentinel characters.`,{code:"INVALID_PARAMETER"});if(s&&(e=la(e),i&&e.length>i))throw new l(`"${t}" should be <= ${i} 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 Oe(e,t="table.name",r={}){return de(e,t,{allowEmpty:r.allowEmpty===true,maxLength:ta,blockKeyDelimiters:true})}function It(e,t="tag",r={}){return de(e,t,{allowEmpty:r.allowEmpty===true,maxLength:ra,blockKeyDelimiters:true})}function rt(e,t="index.name",r={}){return de(e,t,{allowEmpty:r.allowEmpty===true,maxLength:na,blockKeyDelimiters:true,disallowLeadingDollar:true})}function pi(e,t="index.value"){return de(e,t,{allowEmpty:true,maxLength:gi})}function br(e){return typeof e=="string"&&e.slice(-1)==="."}function _r(e,t){return de(e,t,{allowEmpty:true,maxLength:gi,blockKeyDelimiters:true})}function hi(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=de(e.record_id,"record_id",{allowEmpty:false,onlyAlphanumeric:true}):e?.unique_id&&(t.unique_id=e.unique_id),t}function wr(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 Rt=4503599627370496;function Tt(e){if(typeof e=="number"){if(e>Rt||e<-Rt)throw new l(`Number value should be within range -${Rt} ~ +${Rt}`,{code:"INVALID_PARAMETER"});return e}if(typeof e=="boolean")return e;if(typeof e=="string")return pi(e,"index.value");throw new l('"index.value" should be type: <number | boolean | string>.',{code:"INVALID_PARAMETER"})}function mi(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"?br(t.index.name)?_r(e,"index.range"):pi(e,"index.range"):e}var Pt={},ca=10080*60,ua=3600,yi=2;function da(e,t){if(!t)return String(yi);let r=Math.max(60,e-300)*1e3;return "g"+yi+"w"+Math.floor(Date.now()/r)}function fa(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 ga(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 bi(e){return typeof e=="string"?e:e&&typeof e.text=="function"?await e.text():await new Promise((t,r)=>{try{let n=new FileReader;n.onload=()=>t(n.result),n.onerror=()=>r(n.error||new Error("Failed to read blob")),n.readAsText(e);}catch(n){r(n);}})}async function 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,a=[],u=null;function c(d){let p=d=="**"?"private":parseInt(d);return p=p==0?"public":p==1?"authorized":p==99?"admin":p,p}let g={ip:d=>{let p=d.split("#"),m=p[0];p.length>1&&(s.unique_id=p.slice(1).join("#")),m.slice(-1)==="R"?(s.readonly=true,m=m.slice(0,-1)):s.readonly=false,/^\d{1,3}-\d{1,3}-\d{1,3}-\d{1,3}$/.test(m)&&(m=m.split("-").join("."),o=true),s.ip=m;},rec:d=>{if(!d)return;s.record_id=d;let p=d.substring(0,d.length-9),m=ne(p);s.uploaded=m;},usr:d=>{s.user_id=d;},tbl:d=>{if(d&&!s.table.name){let p=d.split("/");s.table.name=le(p[0]),s.table.access_group=c(p[2]),p?.[3]&&(s.table.subscription.is_subscription_record=true);}},usr_tbl:d=>{let p=d.split("/");s.user_id||(s.user_id=p[0]),s.table.name||(s.table.name=le(p[1]),s.table.access_group=c(p[3]),p?.[4]&&(s.table.subscription.is_subscription_record=true));},idx:d=>{if(!d)return;let p=d.split("!"),m=le(p.splice(0,1)[0]),h=pa("!"+p.join("!"));s.index={name:m,value:h};},ref:d=>{d&&(s.reference=d.split("/")[0]);},tags:d=>{s.tags=Array.isArray(d)?d.map(p=>le(p)):d;},upd:d=>{s.updated=d;},acpt_mrf:d=>{s.source.prevent_multiple_referencing=!d;},ref_limt:d=>{s.source.referencing_limit=d;},rfd:d=>{s.referenced_count=d;},bin:async d=>{let p={},m=s?.reference||null;if(Array.isArray(d)){let h=await Promise.all(d.map(async _=>{try{let w=_.split("/").slice(3).join("/"),b=w.split("/");if(b.length<12)return null;let E=b[b.length-1],R=b[10];if(R==="__data__"&&E==="__json__.json")return {isDataFile:!0,rawUrl:_};if(rr(R,E))return {isDataFile:!0,rawUrl:_};let T=_t(R),U=b[9],D=b[8],x=c(b[6]),v=_,C=x!=="public"&&fa.call(this,b)?{expires:ua,browserCache:ca}:null;if(x!=="public"&&!i)try{v=await Pe.bind(this)(_,{dataType:"endpoint",_ref:m});}catch(q){console.error("Error getting signed url for private file:",q),v=_;}let L={access_group:x,filename:E,url:v,path:w,size:T?T.plainSize:ne(U),uploaded:ne(D),getFile:(q,G)=>{let Ae={dataType:q||"download",progress:G,_ref:m},$=()=>Pe.bind(this)(v,Object.assign({},Ae,{_update:L}));return C?Pe.bind(this)(_,Object.assign({},Ae,C)).catch(()=>$()):$()}};return T&&(L.encrypted=!0,L.stored_size=ne(U)),{pathKey:T?T.key:R,obj:L}}catch{return null}}));for(let _ of h)if(_&&!_.isDataFile){if(p[_.pathKey]){p[_.pathKey].push(_.obj);continue}p[_.pathKey]=[_.obj];}}s.bin=p;},prv_acs:d=>{for(let p in d)["notify_subscribers","upload_to_feed","feed_referencing_records","notify_referencing_records"].includes(p)?s.table.subscription[p]=d[p]:p==="referencing_index_restrictions"&&Array.isArray(d[p])?s.source[p]=d[p].map(h=>h&&typeof h=="object"&&typeof h.name=="string"?Object.assign({},h,{name:le(h.name)}):h):s.source[p]=d[p];},data:async d=>{let p={access_group:s.table.access_group,table_name:s.table.name,user_id:s.user_id,record_id:s.record_id,unique_id:s.unique_id,ctUrl:u},m=()=>{O.call(this)&&(s.encrypted={status:"failed",reason:"DATA_UNAVAILABLE"});},h=async w=>{if(n||!O.call(this)&&!mt(w))return w;let b=await hn.bind(this)(w,p);return b.flag&&(s.encrypted=b.flag),b.value},_=ga(d);if(_!==d){s.data=await h(_);return}if(d&&typeof d=="object"&&!Array.isArray(d)&&typeof d.__data__=="string"&&Object.keys(d).length===1&&d.__data__.endsWith("/__data__/__json__.json")){let w=d.__data__,b=a.find(E=>E.endsWith(w))||null;if(!b&&!r&&m(),b){if(r){s.data=d;return}try{let E=await Pe.bind(this)(b,{dataType:"blob",_ref:s.reference||null}),R=await bi(E);s.data=await h(JSON.parse(R));}catch(E){console.error("Failed to fetch offloaded record data:",E),s.data=null,m();}return}}s.data=await h(d);}};if(e.record_id)return e;if(Array.isArray(e.bin))for(let d of e.bin)try{if(typeof d!="string")continue;let p=d.split("/").slice(3);p.length>=12&&p[10]==="__data__"&&p[p.length-1]==="__json__.json"&&a.push(d),p.length>=12&&rr(p[10],p[p.length-1])&&(u=d);}catch{}let f=[];for(let d in g)if(e.hasOwnProperty(d)){let p=g[d](e[d]);p instanceof Promise&&f.push(p);}return o&&(s.user_id="anonymous:"+s.user_id),await Promise.all(f),s}function pa(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 l("Value parse error.",{code:"PARSE_ERROR"})}default:return e}}async function _i(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 P.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 Pe(e,t){if(typeof e!="string")throw new l('"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 a=false,u=o.split("/"),g=u[2].split("."),f=null;g.length===3&&g[1]==="skapi"&&(f=g[0],a=true);let d=u.slice(3),p=false;if(!a&&(d[0]==="auth"||d[0]==="publ"))try{y.UserId(d[2]),y.UserId(d[3]),p=d[0]=="auth",a=!0;}catch{throw new l("Invalid file url.",{code:"INVALID_PARAMETER"})}let m=f?null:d[1];if(t=y.Params(t,{expires:["number",()=>0],browserCache:["number",()=>0],refresh:["boolean",()=>false],dataType:["base64","blob","endpoint","text","info",()=>"download"],progress:["function","undefined",null],_ref:[null,"string"],_update:E=>E}),t?.dataType==="info")return {url:e,filename:d[d.length-1],fileKey:d[d.length-2],access_group:d[6]==="**"?"private":d[6]==="01"?"authorized":d[6]==="00"?"public":parseInt(d[6]),uploader:d[3],record_id:d[4]==="records"?d[5]:"N/A",filesize:ne(d[9]),uploaded:ne(d[8])};let h=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 E={request:f?"get-host":"get",id:f||d[5],key:r.split("?")[0],expires:_};m&&(E.service=m);let R=t.browserCache,T={auth:true};if(R){if(R<0)throw new l('"config.browserCache" should be > 0. (seconds)',{code:"INVALID_PARAMETER"});T.method="get",T.stableGateway=true,E.browser_cache=R;let U=this.session?.idToken?.payload?.sub||this.user?.user_id;U&&(E.uid=U),E.nocache=da(_,t.refresh);}e=(await P.bind(this)("get-signed-url",E,T)).url;}else if(p){let E=Math.floor(Date.now()/1e3);if(!this.bearerToken&&(!this.session?.idToken?.payload?.exp||this.session.idToken.payload.exp<E)){this.log("getFile:requesting new token",null);try{await J.bind(this)().getSession({refreshToken:!0}),this.log("getFile:received new tokens",{exp:this.session?.idToken?.payload?.exp,currTime:E,expiresIn:this.session?.idToken?.payload?.exp-E,token:this.session?.accessToken?.jwtToken,refreshToken:this.session?.refreshToken?.token});}catch(D){throw this.log("getFile:new token error",D),new l("User login is required.",{code:"INVALID_REQUEST"})}}let R=this.bearerToken||this.session?.idToken?.jwtToken;if(!R||!this.user?.user_id)throw new l("User login is required.",{code:"INVALID_REQUEST"});e+=`${e.includes("?")?"&":"?"}t=${encodeURIComponent(R)}`;let T=d[6]==="**"?"**":parseInt(d[6]),U=this.user?.access_group??-1;if(this.user.user_id!==d[3]&&(T==="**"||U<T)){let D=d[5];if(this.__private_access_key[D]&&typeof this.__private_access_key[D]=="string")e+=`&p=${encodeURIComponent(this.__private_access_key[D])}`;else if(this.owner!==this.host)try{let x=await this.requestPrivateRecordAccessKey({record_id:D,reference_id:t?._ref});e+=`&p=${encodeURIComponent(x)}`;}catch{}}}if((O.call(this)?fr(e):null)&&t?.dataType!=="endpoint"&&t?.dataType!=="info"){let E=await P.bind(this)(e,null,{method:"get",contentType:null,responseType:"blob",fetchOptions:{progress:t?.progress}},{ignoreService:true}),R=await Mn.bind(this)(e,E);if(t?.dataType==="blob")return R;if(t?.dataType==="text")return await bi(R);if(t?.dataType==="base64")return await new Promise((D,x)=>{let v=new FileReader;v.onloadend=()=>D(v.result),v.onerror=()=>x(v.error),v.readAsDataURL(R);});let T=URL.createObjectURL(R),U=document.createElement("a");return U.href=T,document.body.appendChild(U),U.setAttribute("download",h),U.click(),document.body.removeChild(U),setTimeout(()=>URL.revokeObjectURL(T),6e4),null}if(t?.dataType==="endpoint")return t._update&&(t._update.url=e),e;if(t?.dataType==="download"){let E=document.createElement("a");return E.href=e,document.body.appendChild(E),E.setAttribute("download",h),E.target="_blank",E.click(),document.body.removeChild(E),null}return new Promise(async(E,R)=>{try{let T=await P.bind(this)(e,null,{method:"get",contentType:null,responseType:t?.dataType==="text"?"text":"blob",fetchOptions:{progress:t?.progress}},{ignoreService:!0});if(t?.dataType==="base64"){let U=new FileReader;U.onloadend=()=>E(U.result),U.readAsDataURL(T);}else E(T);}catch(T){if(t?.browserCache&&!t?.refresh)try{E(await Pe.bind(this)(r,Object.assign({},t,{refresh:!0})));return}catch(U){R(U);return}R(T);}})}function St(e,t){return `${e||this.service}/${t||this.owner}`}function Er(e,t){let r=this.__my_unique_ids[e];return r?r[t]:void 0}function wi(e,t,r){this.__my_unique_ids[e]||(this.__my_unique_ids[e]={}),this.__my_unique_ids[e][t]=r;}function ha(e,t){this.__my_unique_ids[e]&&delete this.__my_unique_ids[e][t];}function Ei(e,t){return !t||t.table===void 0?e:Object.assign({},e,{table:t.table})}async function nt(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 Ai(e,t=false){e=j(e,{ignoreEmpty:true}).data||{};let r=St.bind(this)(e?.service,e?.owner),n="",i=hi(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=Er.bind(this)(r,n);s&&(t?ha.bind(this)(r,n):e.record_id=s);}}else {let s=await Q.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:g=>Oe(g,"table.name"),access_group:wr.bind(this),subscription:g=>y.UserId(g,'User ID in "subscription"')},reference:"string",index:{name:["$updated","$uploaded","$referenced_count","$user_id",g=>rt(g,"index.name")],value:g=>{let f={$updated:"number",$uploaded:"number",$referenced_count:"number",$user_id:y.UserId};if(f.hasOwnProperty(c.index.name)){let d=f[c.index.name];if(typeof d=="function")return d(g);if(d!==typeof g)throw new l(`"index.value" should be type: ${d}.`,{code:"INVALID_PARAMETER"});return g}return typeof g=="string"&&!g?"":typeof g=="string"&&br(c.index.name)?_r(g,"index.value"):Tt(g)},condition:["gt","gte","lt","lte",">",">=","<","<=","=","eq"],range:g=>mi(g,c)},tag:g=>{if(g==null)return g;if(typeof g=="string")return It(g,"tag");throw new l('"tag" should be type: string.',{code:"INVALID_PARAMETER"})},private_key:"string"});e=y.Params(e||{},u(e),a||s?[]:["table"],{ignoreEmpty:true});}return {query:e,is_reference_fetch:n}}async function Ri(e,t){await this.__connection,await nt.call(this,"getRecords");let r=await Ai.bind(this)(e),n=r.is_reference_fetch,i=await P.bind(this)("get-records",r.query,{fetchOptions:t,auth:!!this.__user,method:this.__user?"post":"get"});n&&i?.reference_private_key&&typeof i.reference_private_key=="string"&&(this.__private_access_key[n]=i.reference_private_key);let s=[];for(let o in i.list)s.push(Se.bind(this)(i.list[o]));return i.list=await Promise.all(s),i}function Ii(e){let t="",r=[],n=St.bind(this)(e?.service,e?.owner),i=y.Params(e||{},{record_id:o=>{let a=typeof o=="string"?Er.bind(this)(n,o):void 0;return a||de(o,"record_id",{allowEmpty:false})},unique_id:["string",null],readonly:"boolean",table:{name:o=>Oe(o,"table.name"),subscription:[null,{is_subscription_record:"boolean",upload_to_feed:"boolean",notify_subscribers:"boolean",feed_referencing_records:"boolean",notify_referencing_records:"boolean"}],access_group:wr.bind(this)},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=>rt(c,'"name" in "index_restrictions"'),value:c=>Tt(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=Er.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),de(a,"reference.record_id",{allowEmpty:false,onlyAlphanumeric:true}))})}},index:[null,{name:o=>rt(o,"index.name"),value:o=>Tt(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=>It(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 g=u.url.split("/").slice(0,3).join("/")+"/"+u.path;a.push(g);}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);}}),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 l("Public users cannot update existing records.",{code:"INVALID_REQUEST"});if(i.table.access_group!=="public"&&i.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(i.remove_bin)throw new l("Public users cannot remove files from records.",{code:"INVALID_REQUEST"});if(i.unique_id)throw new l("Public users cannot set unique_id for records.",{code:"INVALID_REQUEST"})}return {config:i,progress:s,is_reference_post:t,files:r}}async function Ti(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,i=null,s={},a={_is_bulk_:await Promise.all(e.map(async(p,m)=>{if(!p||typeof p!="object"||Array.isArray(p))throw new l(`"params[${m}]" should be type: <object>.`,{code:"INVALID_PARAMETER"});let h=Ii.bind(this)(p),_=h.config;if(O.call(this)){let w=Object.prototype.hasOwnProperty.call(_,"data"),b=await nr.bind(this)(_.data,Ei(p,_),w);b.encrypted&&(_.data=b.send,s[m]=b.plain);}if(h.is_reference_post&&t.push(h.is_reference_post),typeof _.progress=="function"&&i===null&&(i=_.progress),_.service!==void 0){if(r===void 0)r=_.service;else if(r!==_.service)throw new l('All bulk params should share the same "service" value.',{code:"INVALID_PARAMETER"})}if(_.owner!==void 0){if(n===void 0)n=_.owner;else if(n!==_.owner)throw new l('All bulk params should share the same "owner" value.',{code:"INVALID_PARAMETER"})}return delete _.progress,delete _.service,delete _.owner,_})),service:"",owner:""};r!==void 0&&(a.service=r),n!==void 0&&(a.owner=n);let u={auth:!!this.__user,method:"post"},c={};Object.keys(c).length&&Object.assign(u,{fetchOptions:c});let g=await P.bind(this)("post-record",a,u),f=await Promise.all(g.map((p,m)=>Se.bind(this)(p,"called from postRecord",false,s.hasOwnProperty(m))));for(let p=0;p<f.length;p++)s.hasOwnProperty(p)&&f[p]&&!f[p].error&&(f[p].data=s[p],f[p].encrypted={status:"encrypted"});let d=St.bind(this)(r,n);for(let p=0;p<g.length;p++){let m=g[p],h=f[p];if(m&&typeof m=="object"&&m.error&&h&&!h.record_id&&(h.error=m.error),typeof m?.reference_private_key=="string")for(let _ of t)this.__private_access_key[_]=m.reference_private_key;h?.unique_id&&wi.bind(this)(d,h.unique_id,h.record_id);}return f}async function Ar(e,t,r){if(await this.__connection,!t)throw new l('"config" argument is required.',{code:"INVALID_PARAMETER"});let n=Ii.bind(this)(t),i=n.config,s=n.progress,o=n.is_reference_post,a={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 g=t?.data!==void 0?t.data:c.data,f=g!==void 0,d=await nr.bind(this)(g,Ei(t,i),f),p=null;p=Object.assign({},i),delete p.data,d.omit||(p.data=d.send);let m={};if(typeof s=="function"&&(m.progress=s),Object.keys(m).length&&Object.assign(a,{fetchOptions:m}),d.files==="decrypt"&&t?.record_id){let b=await gr.bind(this)(t.record_id,"decrypt",s);if(b.length){let E=p.remove_bin;p.remove_bin=Array.isArray(E)?E.concat(b):b;}}if(d.spill&&t?.record_id){let b=new FormData;if(b.append(Ye,new File([d.spill],"payload.bin",{type:"application/octet-stream"})),await tt.bind(this)(b,{record_id:t.record_id}),d.retireCt){let E=p.remove_bin,R=[d.retireCt];p.remove_bin=Array.isArray(E)?E.concat(R):R;}}let h=await P.bind(this)("post-record",p,a);if(d.encrypted&&h?.rec&&gn.bind(this)(h.rec,d.dek),d.files==="encrypt"&&h?.rec)try{let b=await gr.bind(this)(h.rec,"encrypt",s);b.length&&await Ar.bind(this)(void 0,{record_id:h.rec,remove_bin:b});}catch(b){console.error("Failed to encrypt existing attachments after making the record private:",b);}if(Y()&&u.length){let b=new FormData;for(let T of u)b.append(T.name,T.file,T.file.name);let E={record_id:h.rec,progress:s};i.hasOwnProperty("service")&&(E.service=i.service);let{bin_endpoints:R}=await tt.bind(this)(b,E);h.bin?h.bin.push(...R):h.bin=R;}o&&typeof h?.reference_private_key=="string"&&(this.__private_access_key[o]=h.reference_private_key);let _=!!h&&h.data&&typeof h.data=="object"&&!Array.isArray(h.data)&&typeof h.data.__data__=="string"&&h.data.__data__.endsWith("/__data__/__json__.json"),w=await Se.bind(this)(h,"called from postRecord",true,d.encrypted);if(_&&(w.data=c.data),d.encrypted&&(w.data=d.plain,w.encrypted={status:"encrypted",recipients:Object.keys(d.send.k||{})}),w.unique_id){let b=St.bind(this)(i?.service,i?.owner);wi.bind(this)(b,w.unique_id,w.record_id),Y()&&(this.__uniqueIdsPersistTimer!==null&&clearTimeout(this.__uniqueIdsPersistTimer),this.__uniqueIdsPersistTimer=setTimeout(()=>{this.__uniqueIdsPersistTimer=null;try{window.sessionStorage.setItem(`${b}:uniqueids`,JSON.stringify(this.__my_unique_ids[b]||{}));}catch{}},500));}return w}async function Pi(e,t){await nt.call(this,"getTables");let r=await P.bind(this)("get-table",y.Params(e||{},{table:i=>Oe(i,"table",{allowEmpty:true}),condition:["gt","gte","lt","lte",">",">=","<","<=","=","eq","!=","ne"]}),Object.assign({auth:!!this.__user},{fetchOptions:t})),n={cnt_rec:"number_of_records",tbl:"table",srvc:"service",grp_:"number_of_records_in_access_group_"};if(Array.isArray(r?.list))for(let i of r.list){for(let s in n){if(s==="grp_"){for(let o in i)if(o.startsWith("grp_")){let a=o.substring(4);a==="pv"?a="private":a==="00"?a="public":a==="01"?a="authorized":a==="99"&&(a="admin"),i[`number_of_records_in_access_group_${a}`]=i[o],delete i[o];}}i.hasOwnProperty(s)&&(i[n[s]]=i[s],delete i[s]);}typeof i.table=="string"&&(i.table=le(i.table));}return r}async function Si(e,t){if(await nt.call(this,"getIndexes"),!e?.table)throw new l('"table" is required.',{code:"INVALID_PARAMETER"});let r=y.Params(e||{},{table:s=>Oe(s,"table",{allowEmpty:true}),index:s=>rt(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 de(s,"order.value",{allowEmpty:true,maxLength:256,blockKeyDelimiters:true});if(typeof s!="string"&&typeof s!="number"&&typeof s!="boolean")throw new l('"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 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 P.bind(this)("get-index",r,Object.assign({auth:!!this.__user},{fetchOptions:t})),i={cnt_bool:"boolean_count",cnt_numb:"number_count",totl_numb:"total_number",totl_bool:"total_bool",avrg_numb:"average_number",avrg_bool:"average_bool",cnt_str:"string_count"};return Array.isArray(n?.list)&&(n.list=n.list.map(s=>{let o=s.idx.split("/"),a={table:le(o[1]),index:le(o[2]),number_of_records:s.cnt_rec};for(let u in i)Object.prototype.hasOwnProperty.call(s,u)&&(a[i[u]]=s[u]);return a})),n}async function ki(e,t){await nt.call(this,"getTags");let r=await P.bind(this)("get-tag",y.Params(e||{},{table:n=>Oe(n,"table",{allowEmpty:true}),tag:n=>It(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 vi(e,t){await nt.call(this,"getUniqueId");let r=await P.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 Ni(e,t){await this.__connection;let r=await Ai.bind(this)(e,true),n=r.is_reference_fetch,i=await P.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 Ui(e){if(O.call(this)){let t=typeof e.user_id=="string"?[e.user_id]:e.user_id;Array.isArray(t)&&t.length&&await dr.bind(this)(e.record_id,t);}return Li.bind(this)({record_id:e.record_id,user_id:e.user_id,execute:"add"})}async function Di(e){let t=await Li.bind(this)({record_id:e.record_id,user_id:e.user_id||null,execute:"remove"});if(O.call(this)){let r=typeof e.user_id=="string"?[e.user_id]:e.user_id;await kn.bind(this)(e.record_id,Array.isArray(r)&&r.length?r:null);}return t}async function xi(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 s of r.user_id)y.UserId(s);else throw new l("user_id should be type: <string | string[]>",{code:"INVALID_PARAMETER"});let n=s=>(s.rec_usr?(s.record_id=s.rec_usr.split("/")[0],s.user_id=s.rec_usr.split("/")[1]):s.usr_rec&&(s.user_id=s.usr_rec.split("/")[0],s.record_id=s.usr_rec.split("/")[1]),s),i=await P.bind(this)("grant-private-access",r,{auth:true,fetchOptions:t});return i.list=i.list.map(n),i}function Ci(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(Pt[t])return Pt[t];let n=P.bind(this)("request-private-access-key",{record_id:t,reference_id:r},{auth:true}).then(i=>{let s=typeof i=="string"?i:i?.private_key;if(typeof s!="string")throw new l("Invalid private access key response.",{code:"ERROR"});return this.__private_access_key[t]=s,s}).finally(()=>{delete Pt[t];});return Pt[t]=n,n}function Li(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 i=n;if(typeof i=="string"&&(i=[i]),i.length>100)throw new l("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),P.bind(this)("grant-private-access",r,{auth:true})}var N={},H={},ce={},ge={},fe={},kt={},vt={};function Oi(e,t,r){e[t]||(e[t]=[]),e[t].push(r);}async function Nt(e,t,r){let n=[];if(e[t]){for(let i of e[t])if(i){let s=r(i);s instanceof Promise&&(s=await s),n.push(s);}delete e[t];}return n}async function Ir(e,t){if(!this?.session?.accessToken?.jwtToken)throw new l("Access token is required.",{code:"INVALID_PARAMETER"});let r=await this.__socket;async function n(i,s,o){this.log("answerSdpOffer from",s),await N[s].setRemoteDescription(new RTCSessionDescription(i));let a=await N[s].createAnswer();await N[s].setLocalDescription(a),o.send(JSON.stringify({action:"rtc",uid:s,content:{sdpanswer:a},token:this.session.accessToken.jwtToken}));}N?.[t]?e?(await Nt(vt,t,i=>n.bind(this)(i,t,r)),await n.bind(this)(e,t,r)):await Nt(vt,t,i=>n.bind(this)(i,t,r)):e&&Oi(vt,t,e);}async function Tr(e,t){if(this.log("receiveIceCandidate",e),N?.[t]&&N[t]?.remoteDescription&&N[t]?.remoteDescription?.type){if(!e)return Nt(kt,t,r=>N[t].addIceCandidate(r));await Nt(kt,t,r=>N[t].addIceCandidate(r)),await N[t].addIceCandidate(e);}else Oi(kt,t,e);}async function ue(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:s=>{if(typeof s!="string")throw new l('"cid" should be type: <string>.',{code:"INVALID_PARAMETER"});if(s&&s.slice(0,4)!=="cid:")throw new l('"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 l('"cid" is required.',{code:"INVALID_PARAMETER"});let i=s=>{if(!s)throw new l('"cid" is required.',{code:"INVALID_PARAMETER"});if(delete vt[s],delete kt[s],H[s]&&Object.values(H[s]).forEach(o=>{o.readyState!=="closed"&&o.close();}),delete H[s],N?.[s]){N[s].connectionState!=="closed"&&(N[s].close(),t.send(JSON.stringify({action:"rtc",uid:s,content:{hungup:this.user.user_id},token:this.session.accessToken.jwtToken})));let o={type:"connectionstatechange",target:N[s],timestamp:new Date().toISOString(),state:N[s].connectionState,iceState:N[s].iceConnectionState,signalingState:N[s].signalingState};fe[s]&&fe[s](o),this.log("closeRTC",o);}delete fe[s],delete ge[s],delete ce[s],delete N[s];};if(n)for(let s in N)i(s);else i(r);this.log("Cleaning up media stream..."),this.__mediaStream&&(this.__mediaStream.getTracks().forEach(s=>{s.stop();}),this.__mediaStream=null);}async function Mi(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 Fi(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"});e=y.Params(e,{cid:o=>{if(typeof o!="string")throw new l('"cid" should be type: <string>.',{code:"INVALID_PARAMETER"});if(o&&o.slice(0,4)!=="cid:")throw new l('"cid" should be a valid connection id.',{code:"INVALID_PARAMETER"});return o},ice:["string",()=>"stun:stun.skapi.com:3468"],media:o=>o,channels:["text-chat","file-transfer","video-chat","voice-chat","gaming",{ordered:"boolean",maxPacketLifeTime:"number",maxRetransmits:"number",protocol:"string"},()=>[{ordered:true,maxPacketLifeTime:10,protocol:"default"}]]},["cid"]);let{cid:r,ice:n}=e;if(!(e?.media instanceof MediaStream)&&(e?.media?.video||e?.media?.audio)&&window.location.hostname!=="localhost"&&window.location.protocol!=="https:")throw new l("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 l("No realtime connection. Execute connectRealtime() before this method.",{code:"INVALID_REQUEST"});if(i.readyState!==1)throw new l("Realtime connection is not ready.",{code:"INVALID_REQUEST"});let s={iceServers:[{urls:n}]};N?.[r]||(N[r]=new RTCPeerConnection(s)),e?.media&&(this.__mediaStream=await Mi(e.media),this.__mediaStream.getTracks().forEach(o=>{N[r].addTrack(o,this.__mediaStream);})),fe[r]=t,H[r]||(H[r]={});for(let o=0;o<e.channels.length;o++){let a=e.channels[o];if(typeof a=="string")switch(a){case "text-chat":a={ordered:true,maxRetransmits:10,protocol:"text-chat"};break;case "file-transfer":a={ordered:false,maxPacketLifeTime:3e3,protocol:"file-transfer"};break;case "video-chat":a={ordered:true,maxRetransmits:10,protocol:"video-chat"};break;case "voice-chat":a={ordered:true,maxRetransmits:10,protocol:"voice-chat"};break;case "gaming":a={ordered:false,maxPacketLifeTime:100,protocol:"gaming"};break;default:a={ordered:true,maxRetransmits:10,protocol:"default"};break}let u=a.protocol||"default";if(Object.keys(H[r]).includes(u))throw new l(`Data channel with the protocol "${u}" already exists.`,{code:"INVALID_REQUEST"});let c=N[r].createDataChannel(u,a);H[r][u]=c;}for(let o in H[r]){let a=H[r][o];$i.bind(this)(r,a);}return Vi.bind(this)(r,["onnegotiationneeded"]),await Rr.bind(this)(r),{hangup:()=>ce[r]&&ce[r](false),connection:new Promise(o=>{ce[r]=(a=>{if(this.log("receiver picked up the call",r),!a)return ue.bind(this)({cid:r}),null;N[r].onnegotiationneeded=()=>{this.log("onnegotiationneeded",`sending offer to "${r}".`),Rr.bind(this)(r),fe[r]&&fe[r]({type:"negotiationneeded",target:N[r],timestamp:new Date().toISOString(),signalingState:N[r].signalingState,connectionState:N[r].iceConnectionState,gatheringState:N[r].iceGatheringState});},o({target:N[r],channels:H[r],hangup:()=>ue.bind(this)({cid:r}),media:this.__mediaStream});}).bind(this);})}}function qi(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 l("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 l("Media stream is only supported on either localhost or https.",{code:"INVALID_REQUEST"});let{ice:s="stun:stun.skapi.com:3468"}=t;return N?.[n]||(N[n]=new RTCPeerConnection({iceServers:[{urls:s}]})),t?.media&&(this.__mediaStream=await Mi(t.media),this.__mediaStream.getTracks().forEach(o=>{N[n].addTrack(o,this.__mediaStream);})),delete ge[n],fe[n]=r,H[n]||(H[n]={}),N[n].ondatachannel=o=>{this.log("ondatachannel",`received data channel "${o.channel.label}".`);let a=o.channel;H[n][a.label]=a,$i.bind(this)(n,a);},Vi.bind(this)(n,["onnegotiationneeded"]),await Ir.bind(this)(null,n),await Tr.bind(this)(null,n),i.send(JSON.stringify({action:"rtc",uid:n,content:{pickup:this.user.user_id},token:this.session.accessToken.jwtToken})),{target:N[n],channels:H[n],hangup:()=>ue.bind(this)({cid:n}),media:this.__mediaStream}}}async function Rr(e){if(!this?.session?.accessToken?.jwtToken)throw new l("Access token is required.",{code:"INVALID_PARAMETER"});this.log("sendOffer",e);let t=await this.__socket,r=await N[e].createOffer();await N[e].setLocalDescription(r);let n=N[e].localDescription;this.log("rtcSdpOffer to",n),t.send(JSON.stringify({action:"rtc",uid:e,content:{sdpoffer:n},token:this.session.accessToken.jwtToken}));}async function ma(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=fe[t]||(()=>{}),i=e.candidate;this.log("ice gathering state set to",N[t].iceGatheringState),n({type:"icecandidate",target:N[t],timestamp:new Date().toISOString(),candidate:e.candidate.candidate,sdpMid:e.candidate.sdpMid,sdpMLineIndex:e.candidate.sdpMLineIndex,usernameFragment:e.candidate.usernameFragment,protocol:e.candidate.protocol,gatheringState:N[t].iceGatheringState,connectionState:N[t].iceConnectionState}),r.send(JSON.stringify({action:"rtc",uid:t,content:{candidate:i},token:this.session.accessToken.jwtToken}));}function Vi(e,t){let r=new Set(t),n=fe[e]||(o=>{}),i=N[e],s={ontrack:o=>{n({type:"track",target:i,timeStamp:o.timeStamp,streams:o.streams,track:o.track});},onicecandidate:o=>{ma.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:()=>{Rr.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,a]of Object.entries(s))r.has(o)||(i[o]=a);}function $i(e,t,r){let n=new Set(r),i=fe[e]||(o=>{}),s={onmessage:o=>{let a={type:o.type,target:t,timeStamp:o.timeStamp,data:o.data,lastEventId:o.lastEventId,origin:o.origin,readyState:t.readyState,bufferedAmount:t.bufferedAmount};this.log(`${t.label}: message`,o.data),i(a);},onerror:o=>{let a={type:o.type,target:t,timeStamp:o.timeStamp,error:o.error.message,errorCode:o.error.errorDetail,readyState:t.readyState,label:t.label};this.log(`${t.label}: error`,o.error.message),i(a);},onclose:o=>{let a={type:o.type,target:t,timeStamp:o.timeStamp,readyState:t.readyState,label:t.label,id:t.id};this.log(`${t.label}: closed`,null),i(a),H[e]&&(delete H[e][t.label],Object.keys(H[e]).length===0&&ue.bind(this)({cid:e}));},onbufferedamountlow:o=>{let a={target:t,bufferedAmount:t.bufferedAmount,bufferedAmountLowThreshold:t.bufferedAmountLowThreshold,type:o.type,timeStamp:o.timeStamp};this.log(`${t.label}: bufferedamountlow`,t.bufferedAmount),i(a);},onopen:o=>{this.log("dataChannel",`data channel: "${t.label}" is open and ready to send messages.`);let a={type:o.type,target:t,timeStamp:o.timeStamp,readyState:t.readyState,label:t.label,id:t.id,ordered:t.ordered,maxRetransmits:t.maxRetransmits,protocol:t.protocol};i(a);}};for(let[o,a]of Object.entries(s))n.has(o)||(t[o]=a);}var be;function ji(){return be}var Ee=null,it=true,Me=0;async function ya(){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 Pr=null;async function Ut(){if(typeof window>"u"||window._runningInNodeJS)throw new l("WebSocket is not supported in Node.js environment.",{code:"NOT_SUPPORTED"});it=true;let e=this.__socket?await this.__socket:this.__socket;ue.bind(this)({close_all:true}),be&&qe.bind(this)({group:null}),Me=0,Ee&&(Ee.terminate(),Ee=null);try{e&&e.close();}catch{}return window.removeEventListener("visibilitychange",Pr),this.__socket=null,null}async function Fe(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 i=await this.__socket;if(i.readyState!==WebSocket.CLOSED&&i.readyState!==WebSocket.CLOSING)return this.__socket}}else if(it&&(Pr=()=>{!document.hidden&&!it&&Fe.bind(this)(e,0,"reconnect");},this.__socket instanceof Promise))return this.__socket;Ee&&(Ee.terminate(),Ee=null);let n={value:null};return this.__socket=new Promise(async(i,s)=>{let o=a=>{this.__socket===n.value&&(this.__socket=null),s(a);};try{await Ce.bind(this)();}catch(a){o(a);return}setTimeout(async()=>{try{let a=await ya.bind(this)();a.onopen=()=>{it=!1,Me=0,r!=="reconnect"&&window.addEventListener("visibilitychange",Pr),this.log("realtime onopen","Connected to WebSocket server."),e({type:"success",message:"Connected to WebSocket server."}),be&&a.send(JSON.stringify({action:"joinRoom",rid:be,token:this.session.accessToken.jwtToken}));let u=`
|
|
206
|
+
var Qs=Object.defineProperty;var zs=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=zs(t,r),s=e.length-1,o;s>=0;s--)(o=e[s])&&(i=(o(t,r,i))||i);return i&&Qs(t,r,i),i};function vr(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 xt,Ct,Lt=()=>xt!==void 0?xt:xt=vr("fs"),Ot=()=>Ct!==void 0?Ct:Ct=vr("path"),he=typeof globalThis<"u"?globalThis:void 0,ct=he?.window;function Js(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(ct)ct.global=ct,ct.global._runningInNodeJS=false;else if(he&&(he.global=he,typeof he.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=Js(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});});}}he.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);});}}he.XMLHttpRequest=t,he.window={_runningInNodeJS:true,alert:r=>console.error("[Alert]",r),sessionStorage:{getItem:r=>null,setItem:(r,n)=>{},removeItem:r=>{}},localStorage:{getItem:r=>{let n=Lt(),i=Ot();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=Lt(),s=Ot();if(!(!i||!s))try{let o=s.resolve(process.cwd(),"states","localStorage");i.existsSync(o)||i.mkdirSync(o,{recursive:!0});let a=s.resolve(o,`${r}.skapi`);i.writeFileSync(a,n,"utf8");}catch{}},removeItem:r=>{let n=Lt(),i=Ot();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/${he?.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 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 me="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",Mt=BigInt(me.length),Ys=2*1024*1024,Xs=["aud","cognito:username","event_id","exp","iat","iss","jti","origin_jti","secret_key","token_use"],Nr={auth_time:"log",sub:"user_id"},Lr=["0","1","2","3","4","5","6","7","8","9","a","b","c","d","e","f","g","h","i","j","k","l"],Or=["us31","us72","ap51","ap22","ap41","eu71","ap21","us32","us71","af51","ap31","ap43","ap23","ap42","ca01","eu01","eu72","eu51","eu73","eu11","me51","sa31"],Ur=typeof TextEncoder<"u"?new TextEncoder:null;function Zs(){if(typeof globalThis<"u")return globalThis.Buffer}function K(e){if(Ur)return Ur.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 Ft(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=Zs();if(t)return new Uint8Array(t.from(e));throw new Error("No byte conversion available in this environment.")}var A=class A{static hash(t){typeof t!="string"&&(console.warn("coercing non-string value to empty string"),t="");let r=A.sb(t),n=1732584193,i=-271733879,s=-1732584194,o=271733878,a,u,c,g;for(let f=0;f<r.length;f+=16)a=n,u=i,c=s,g=o,n=A.ff(n,i,s,o,r[f],7,-680876936),o=A.ff(o,n,i,s,r[f+1],12,-389564586),s=A.ff(s,o,n,i,r[f+2],17,606105819),i=A.ff(i,s,o,n,r[f+3],22,-1044525330),n=A.ff(n,i,s,o,r[f+4],7,-176418897),o=A.ff(o,n,i,s,r[f+5],12,1200080426),s=A.ff(s,o,n,i,r[f+6],17,-1473231341),i=A.ff(i,s,o,n,r[f+7],22,-45705983),n=A.ff(n,i,s,o,r[f+8],7,1770035416),o=A.ff(o,n,i,s,r[f+9],12,-1958414417),s=A.ff(s,o,n,i,r[f+10],17,-42063),i=A.ff(i,s,o,n,r[f+11],22,-1990404162),n=A.ff(n,i,s,o,r[f+12],7,1804603682),o=A.ff(o,n,i,s,r[f+13],12,-40341101),s=A.ff(s,o,n,i,r[f+14],17,-1502002290),i=A.ff(i,s,o,n,r[f+15],22,1236535329),n=A.gg(n,i,s,o,r[f+1],5,-165796510),o=A.gg(o,n,i,s,r[f+6],9,-1069501632),s=A.gg(s,o,n,i,r[f+11],14,643717713),i=A.gg(i,s,o,n,r[f],20,-373897302),n=A.gg(n,i,s,o,r[f+5],5,-701558691),o=A.gg(o,n,i,s,r[f+10],9,38016083),s=A.gg(s,o,n,i,r[f+15],14,-660478335),i=A.gg(i,s,o,n,r[f+4],20,-405537848),n=A.gg(n,i,s,o,r[f+9],5,568446438),o=A.gg(o,n,i,s,r[f+14],9,-1019803690),s=A.gg(s,o,n,i,r[f+3],14,-187363961),i=A.gg(i,s,o,n,r[f+8],20,1163531501),n=A.gg(n,i,s,o,r[f+13],5,-1444681467),o=A.gg(o,n,i,s,r[f+2],9,-51403784),s=A.gg(s,o,n,i,r[f+7],14,1735328473),i=A.gg(i,s,o,n,r[f+12],20,-1926607734),n=A.hh(n,i,s,o,r[f+5],4,-378558),o=A.hh(o,n,i,s,r[f+8],11,-2022574463),s=A.hh(s,o,n,i,r[f+11],16,1839030562),i=A.hh(i,s,o,n,r[f+14],23,-35309556),n=A.hh(n,i,s,o,r[f+1],4,-1530992060),o=A.hh(o,n,i,s,r[f+4],11,1272893353),s=A.hh(s,o,n,i,r[f+7],16,-155497632),i=A.hh(i,s,o,n,r[f+10],23,-1094730640),n=A.hh(n,i,s,o,r[f+13],4,681279174),o=A.hh(o,n,i,s,r[f],11,-358537222),s=A.hh(s,o,n,i,r[f+3],16,-722521979),i=A.hh(i,s,o,n,r[f+6],23,76029189),n=A.hh(n,i,s,o,r[f+9],4,-640364487),o=A.hh(o,n,i,s,r[f+12],11,-421815835),s=A.hh(s,o,n,i,r[f+15],16,530742520),i=A.hh(i,s,o,n,r[f+2],23,-995338651),n=A.ii(n,i,s,o,r[f],6,-198630844),o=A.ii(o,n,i,s,r[f+7],10,1126891415),s=A.ii(s,o,n,i,r[f+14],15,-1416354905),i=A.ii(i,s,o,n,r[f+5],21,-57434055),n=A.ii(n,i,s,o,r[f+12],6,1700485571),o=A.ii(o,n,i,s,r[f+3],10,-1894986606),s=A.ii(s,o,n,i,r[f+10],15,-1051523),i=A.ii(i,s,o,n,r[f+1],21,-2054922799),n=A.ii(n,i,s,o,r[f+8],6,1873313359),o=A.ii(o,n,i,s,r[f+15],10,-30611744),s=A.ii(s,o,n,i,r[f+6],15,-1560198380),i=A.ii(i,s,o,n,r[f+13],21,1309151649),n=A.ii(n,i,s,o,r[f+4],6,-145523070),o=A.ii(o,n,i,s,r[f+11],10,-1120210379),s=A.ii(s,o,n,i,r[f+2],15,718787259),i=A.ii(i,s,o,n,r[f+9],21,-343485551),n=A.ad(n,a),i=A.ad(i,u),s=A.ad(s,c),o=A.ad(o,g);return A.rh(n)+A.rh(i)+A.rh(s)+A.rh(o)}static rh(t){let r="";for(let n=0;n<=3;n++)r+=A.alphabet.charAt(t>>n*8+4&15)+A.alphabet.charAt(t>>n*8&15);return r}static ad(t,r){let n=(t&65535)+(r&65535);return (t>>16)+(r>>16)+(n>>16)<<16|n&65535}static rl(t,r){return t<<r|t>>>32-r}static cm(t,r,n,i,s,o){return A.ad(A.rl(A.ad(A.ad(r,t),A.ad(i,o)),s),n)}static ff(t,r,n,i,s,o,a){return A.cm(r&n|~r&i,t,r,s,o,a)}static gg(t,r,n,i,s,o,a){return A.cm(r&i|n&~i,t,r,s,o,a)}static hh(t,r,n,i,s,o,a){return A.cm(r^n^i,t,r,s,o,a)}static ii(t,r,n,i,s,o,a){return A.cm(n^(r|~i),t,r,s,o,a)}static sb(t){let r,n=(t.length+8>>6)+1,i=new Array(n*16);for(r=0;r<n*16;r++)i[r]=0;for(r=0;r<t.length;r++)i[r>>2]|=t.charCodeAt(r)<<r%4*8;return i[r>>2]|=128<<r%4*8,i[n*16-2]=t.length*8,i}};A.alphabet="0123456789abcdef";var G=A;function Mr(e){if(e===0)return me[0];let t="";for(;e>0;)t=me[e%62]+t,e=Math.floor(e/62);return t}function se(e){return e.split("").reverse().reduce((t,r,n)=>t+me.indexOf(r)*62**n,0)}function Re(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 qt(){return typeof window>"u"||!!window?._runningInNodeJS}function Y(){return !qt()&&typeof document<"u"&&typeof document.createElement=="function"}function ut(e){let t;try{t=JSON.stringify(e);}catch{throw new l("Invalid data type.",{code:"INVALID_REQUEST"})}if(new Blob([t]).size>Ys)throw new l("Data should not exceed 2MB",{code:"INVALID_REQUEST"})}function Dr(e){return e===""||e==="on"||e==="true"}function xr(e){return e==="false"}function Cr(e,t,r){t.name&&r(e,t.name,t.value);}var dt=Y(),eo=typeof SubmitEvent<"u",to=typeof HTMLFormElement<"u";function j(e,t,r){let n={},i=[];function s(u,c,g){if(t?.ignoreEmpty&&g==="")return;if(t?.nullIfEmpty&&g===""&&(g=null),typeof r=="function"){let p=r(c,g);p!==void 0&&(g=p);}let f=c.split("[").map(p=>{let y=p.replace("]",""),h=Number(y);return !isNaN(h)&&!y.includes(".")?y=h:(y[0]==='"'&&y[y.length-1]==='"'||y[0]==="'"&&y[y.length-1]==="'")&&(y=y.replace(/"/g,"").replace(/'/g,"")),y}),d=u;if(typeof f[0]=="number")throw new l("Form key cannot start with an array index.",{code:"INVALID_REQUEST"});for(let p=0;p<f.length;p++){let y=f[p];p<f.length-1?(d[y]===void 0&&(typeof f[p+1]=="number"?d[y]=[]:d[y]={}),d=d[y]):d[y]===void 0?d[y]=g:Array.isArray(d[y])?d[y].push(g):d[y]=[d[y],g];}}function o(u,c,g){if(g instanceof File)u.push({name:c,file:g});else if(g instanceof FileList&&g&&g.length>0)for(let f=0;f<=g.length-1;f++){let d=g.item(f);d&&u.push({name:c,file:d});}}let a=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===""||Dr(u.value)?s(n,u.name,true):xr(u.value)?s(n,u.name,false):u.value&&s(n,u.name,u.value):u.type==="checkbox"&&(Dr(u.value)?s(n,u.name,false):xr(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(dt&&(e instanceof HTMLInputElement||e instanceof HTMLSelectElement||e instanceof HTMLTextAreaElement))return a(e),ut(n),{data:n,files:i};if(dt&&e instanceof FormData){for(let u of e.entries()){let c=u[0],g=u[1];if(g instanceof File||g instanceof FileList)o(i,c,g);else if(g instanceof Blob){let f=g;if(f.type==="application/json")try{let d=JSON.parse(f.text());s(n,c,d);}catch{s(n,c,f);}}else s(n,c,g);}return ut(n),{data:n,files:i}}if(dt&&eo&&e instanceof SubmitEvent&&(e=e.target),dt&&to&&e instanceof HTMLFormElement){let u=e.querySelectorAll("input"),c=e.querySelectorAll("select"),g=e.querySelectorAll("textarea");for(let f=0;f<c.length;f++)Cr(n,c[f],s);for(let f=0;f<g.length;f++)Cr(n,g[f],s);for(let f=0;f<u.length;f++)a(u[f]);return ut(n),{data:n,files:i}}return ut(e),{data:e,files:i}}function $e(e){let t={};for(let r in e){let n=e[r];if(!Xs.includes(r))if(Nr[r])t[Nr[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 Vt(e){if(e=co(e),e.split("-").length===7){let t=e.split("-"),r,n;try{r=Or[Lr.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 $t(e,t){let r=Or.indexOf(e.slice(0,4)),n=Lr[r],s=`${e.slice(4,-4)}-${n}${e.slice(-4)}-${t}`;return lo(s)}function ro(e){let t=0n;for(let r of e){let n=me.indexOf(r);if(n<0)throw new Error(`INVALID_PARAMETER: Invalid base62 character: ${r}`);t=t*Mt+BigInt(n);}return t}function no(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%Mt);r=me[i]+r,n/=Mt;}return r.length<t&&(r="0".repeat(t-r.length)+r),r}function io(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 so(e){let t=0n;for(let r of e)t=(t<<8n)+BigInt(r);return t}function oo(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 ao(e){let t=Array.from(Ft(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 lo(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>=me.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=i+o,c=me[i.length]+a+u,g=oo(s),f=no(so(g));return `${c}-${f}`}function co(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=me.indexOf(n[0]);if(s<0)throw new Error("INVALID_PARAMETER: Corrupt compressed token: "+t);let o=n.slice(1),a=s+2;if(o.length<a)throw new Error("INVALID_PARAMETER: Corrupt compressed token: "+t);let u=o.slice(0,o.length-a),c=o.slice(o.length-a),g=c.slice(s),f=c.slice(0,s),d=g+u;if(!/^[0-9A-Za-z]+$/.test(d)||!/^[0-9A-Za-z]+$/.test(f))throw new Error("INVALID_PARAMETER: Corrupt compressed token: "+t);let p=ro(i),y=io(p);if(y.length>16)throw new Error("INVALID_PARAMETER: Corrupt compressed token: "+t);let h=new Uint8Array(16);h.set(y,16-y.length);let _=ao(h);return `${d}-${f}-${_}`}function je(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 jt(...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 fo(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 go(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 po(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 ho(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 mo(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 yo(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 l(`"${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 l(`"${i}" is an invalid url. Relative URL does not work on local file system. Use full URL string.`,{code:"INVALID_PARAMETER"});let a=t?window.location.href.split("?")[0]:"";a.slice(-1)!=="/"&&(a+="/"),s=a+s.slice(1);}let o;try{o=new URL(s);}catch{throw new l(`"${i}" is an invalid url.`,{code:"INVALID_PARAMETER"})}if(o.protocol)return o.href}}throw new l(`"${i}" is an invalid url.`,{code:"INVALID_PARAMETER"})};return Array.isArray(e)?e.map(i=>n(i)):n(e)}var bo=/^[a-z0-9]{2,20}$/,_o=/[a-z]/,wo=/^[0-9]+e[0-9]+$/,Eo=["tp","admin","public","authorized","newsletter","forward","all","true","false","null"];function Ao(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"||!bo.test(e)||!_o.test(e)||wo.test(e)||Eo.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 Ro(e,t,r=[],n){let i=j(e,n),s=i.data;t.service="string",t.owner="string";let o={};for(let a in t)if(s&&typeof s=="object"&&!Array.isArray(s)&&s.hasOwnProperty(a))if(typeof s[a]=="function")o[a]=s[a];else try{o[a]=JSON.parse(JSON.stringify(s[a]));}catch{o[a]=s[a];}n?.precall&&n.precall({data:o,files:i?.files||[]});try{return uo(o,t,r)}catch(a){throw new l(a.message,{code:"INVALID_PARAMETER"})}}var m={UserId:fo,PhoneNumber:go,Birthdate:po,Password:ho,Email:mo,Url:yo,newsletterGroup:Ao,Params:Ro};var X="skapi.enc.v1",Vr=6e5,Be=12,ft=null,ve=null;function $r(){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 jr(){if(ve)return ve;let e=typeof globalThis<"u"?globalThis:void 0;if(e?.crypto?.subtle&&typeof e.crypto.getRandomValues=="function")return ve=e.crypto,ve;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 ve=r.webcrypto,ve}catch{}throw $r()}function ne(){if(ft)return ft;let e=jr();if(!e.subtle)throw $r();return ft=e.subtle,ft}function Kt(){try{return ne(),!0}catch{return false}}function Z(e){let t=jr(),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 F(e){let t=Ft(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 l("No base64 encoder available in this environment.",{code:"NOT_SUPPORTED"});return r.replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function V(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),i=new Uint8Array(n.length);for(let s=0;s<n.length;s++)i[s]=n.charCodeAt(s);return i}throw new l("No base64 decoder available in this environment.",{code:"NOT_SUPPORTED"})}async function gt(e){let t=await ne().digest("SHA-256",e);return new Uint8Array(t)}async function Ge(e,t,r,n){let i=ne(),s=await i.importKey("raw",e,"HKDF",false,["deriveBits"]),o=await i.deriveBits({name:"HKDF",hash:"SHA-256",salt:t,info:r},s,n*8);return new Uint8Array(o)}async function Ue(e,t,r,n){let i=ne(),s=K(e.normalize("NFC")),o=await i.importKey("raw",s,"PBKDF2",false,["deriveBits"]),a=new Uint8Array(await i.deriveBits({name:"PBKDF2",salt:t,iterations:r,hash:"SHA-256"},o,256)),u=await Ge(a,t,n,32);M(a),M(s);let c=await oe(u);return M(u),c}async function oe(e){return ne().importKey("raw",e,{name:"AES-GCM"},false,["encrypt","decrypt"])}async function Br(){let e=Z(32),t=await oe(e);return {bytes:e,key:t}}async function ie(e,t,r){let n=Z(Be),i=await ne().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 ne().decrypt({name:"AES-GCM",iv:t,additionalData:n,tagLength:128},e,r);return new Uint8Array(i)}var pt={name:"ECDH",namedCurve:"P-256"};async function Kr(){let e=ne(),t=await e.generateKey(pt,true,["deriveBits"]),r=new Uint8Array(await e.exportKey("raw",t.publicKey)),n=new Uint8Array(await e.exportKey("pkcs8",t.privateKey)),i=await Ht(n);return {pubRaw:r,pkcs8:n,priv:i}}async function Ht(e){return ne().importKey("pkcs8",e,pt,false,["deriveBits"])}async function Hr(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 ne().importKey("raw",e,pt,false,[])}async function Gt(e){return F(await gt(e))}async function Gr(e,t,r,n){let i=ne(),s=await Hr(e),o=await i.generateKey(pt,true,["deriveBits"]),a=new Uint8Array(await i.deriveBits({name:"ECDH",public:s},o.privateKey,256)),u=await Ge(a,new Uint8Array(32),r,32);M(a);let c=await oe(u);M(u);let{iv:g,ct:f}=await ie(c,t,n);return {epk:new Uint8Array(await i.exportKey("raw",o.publicKey)),iv:g,ct:f}}async function Wr(e,t,r,n,i,s){let o=ne(),a=await Hr(t),u=new Uint8Array(await o.deriveBits({name:"ECDH",public:a},e,256)),c=await Ge(u,new Uint8Array(32),i,32);M(u);let g=await oe(c);return M(c),ae(g,r,n,s)}function M(e){e&&e.length&&e.fill(0);}function Io(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 Wt(e){return K(JSON.stringify(e))}function We(e,t,r){return jt(e,new Uint8Array([0]),K(t),new Uint8Array([0]),K(r))}var Ie="0123456789ABCDEFGHJKMNPQRSTVWXYZ",Ke=16,Fr=26,qr=28;function Qr(e){let t=2166136261;for(let r=0;r<e.length;r++)t^=e[r],t=t*16777619>>>0;return t&1023}function zr(e){if(e.length!==Ke)throw new l(`A recovery code needs exactly ${Ke} 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=Qr(e);return t+=Ie[i>>5&31]+Ie[i&31],(t.match(/.{1,4}/g)||[]).join("-")}function Jr(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!==qr)throw new l(`That does not look like a recovery code: expected ${qr} characters, got ${t.length}.`,{code:"ENCRYPTION_BAD_RECOVERY_CODE"});let r=t.slice(0,Fr),n=t.slice(Fr),i=0,s=0,o=[];for(let c=0;c<r.length;c++){let g=Ie.indexOf(r[c]);if(g<0)throw new l(`That does not look like a recovery code: "${r[c]}" is not a valid character.`,{code:"ENCRYPTION_BAD_RECOVERY_CODE"});i=i<<5|g,s+=5,s>=8&&(s-=8,o.push(i>>s&255));}let a=new Uint8Array(o.slice(0,Ke)),u=Qr(a);if(n!==Ie[u>>5&31]+Ie[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 Qt(e,t,r){let n=await Ge(e,t,r,32),i=await oe(n);return M(n),i}var Bt=[83,75,69,78,67,70],Yr=2,He=56,Xr=16,To=4*1024*1024;function zt(e){if(!e||e.length<He)return false;for(let t=0;t<Bt.length;t++)if(e[t]!==Bt[t])return false;return true}function Te(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 Ne(e,t){return (e[t]<<24>>>0)+(e[t+1]<<16)+(e[t+2]<<8)+e[t+3]}function Po(e,t,r){let n=Math.floor(r/4294967296);Te(e,t,n),Te(e,t+4,r>>>0);}function So(e,t){return Ne(e,t)*4294967296+Ne(e,t+4)}async function Zr(e,t,r,n,i,s){let o=K(`${X}|binfile|${r}|${n}|${i}|${s}`),a=await Ge(e,t,o,32),u=await oe(a);return M(a),u}async function en(e){return (await gt(jt(K(`${X}|dekid`),e))).subarray(0,8)}function tn(e,t,r){return Wt([`${X}|binchunk`,F(e),t,r])}function ko(e,t,r,n,i,s){let o=new Uint8Array(He+s.length);return o.set(Bt,0),o[6]=Yr,o[7]=s.length?1:0,Te(o,8,e),Te(o,12,t),o.set(r,16),Po(o,32,n),o.set(i,40),Te(o,48,s.length),Te(o,52,0),s.length&&o.set(s,He),o}async function rn(e,t,r,n,i=To){let s=Z(Xr),o=await Zr(e,s,r.service,r.owner,r.recordOwner,r.recordId),a=await en(e),u=n?K(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/i),g=ko(i,c,s,t.length,a,u),f=await gt(g),d=[],p=g.length;for(let _=0;_<c;_++){let w=t.subarray(_*i,Math.min((_+1)*i,t.length)),b=await ie(o,w,tn(f,_,c));d.push(b),p+=4+b.iv.length+b.ct.length;}let y=new Uint8Array(p);y.set(g,0);let h=g.length;for(let _ of d)Te(y,h,_.iv.length+_.ct.length),h+=4,y.set(_.iv,h),h+=_.iv.length,y.set(_.ct,h),h+=_.ct.length;return y}function vo(e){if(!zt(e))throw new l("This file is not an encrypted skapi file.",{code:"INVALID_PARAMETER"});let t=Ne(e,48),r=He+t;if(e.length<r)throw new l("Encrypted file header is truncated.",{code:"INVALID_REQUEST"});let n=null;return t&&(n=JSON.parse(je(e.subarray(He,r)))),{version:e[6],chunkBytes:Ne(e,8),count:Ne(e,12),fileId:e.subarray(16,16+Xr),plainLen:So(e,32),dekId:e.subarray(40,48),meta:n,headerLen:r}}async function nn(e,t,r){let n=vo(t);if(n.version!==Yr)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 i=await en(e);if(!Io(i,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 s=await Zr(e,n.fileId,r.service,r.owner,r.recordOwner,r.recordId),o=await gt(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 p=Ne(t,u);if(u+=4,p<Be+16||u+p>t.length)throw new l("Encrypted file is truncated.",{code:"INVALID_REQUEST"});let y=await ae(s,t.subarray(u,u+Be),t.subarray(u+Be,u+p),tn(o,d,n.count));u+=p,a.push(y),c+=y.length;}let g=new Uint8Array(c),f=0;for(let d of a)g.set(d,f),f+=d.length;return {bytes:g,meta:n.meta}}var No="__skapi__keyring",Qe="__skapi_enc__",on=1,Uo="skapi-enc",we="keys",Yt=new WeakMap;function an(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:Vr;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:No}}function O(){return Yt.get(this)||null}function ln(e){if(!e){Yt.delete(this);return}Yt.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 Xt(){let e=O.call(this);if(e){e.user_id&&cr.call(this,e).catch(()=>{}),e.ready=null,e.unlocking=false,e.pendingRecoveryCode="";for(let[,t]of e.dek)M(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 cn(){let e=O.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 un(e,t){return typeof t=="string"&&t===e.cfg.table}function De(){return `${this.service}/${this.owner}`}function Zt(e,t,r,n){let[i,s]=e.split("/");return Wt([X,i,s,t,r,n])}function dn(e,t,r,n,i){let[s,o]=e.split("/");return K(`${X}|dekwrap|${s}|${o}|${t}|${r}|${n}|${i}`)}function er(e){return e.anch==="uid"?e.uid:e.anch==="rid"?e.rid:""}function mt(e){return !!e&&typeof e=="object"&&!Array.isArray(e)&&typeof e[Qe]=="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 fn="__skapi_no_access__";function ee(e,t,r){if(e.withheld!=="sentinel")return null;let n={[fn]:true,reason:t};return r&&(n.recipients=r),Object.freeze(n)}function tr(e){return !!e&&typeof e=="object"&&e[fn]===true}var Do=256*1024,Ye="__skenc_ct__",gn="payload.bin",xo=`/${Ye}/${gn}`;function rr(e,t){return e===Ye&&t===gn}async function Co(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 _e.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 Lo(e){return this.getFile(e,{dataType:"blob"})}async function _e(e){let t=/^[a-zA-Z0-9]+$/.test(e)?{record_id:e}:{unique_id:e};return (await this.getRecords(t,{limit:1}))?.list?.[0]||null}function sn(e){return e==="private"||e==="*"||e==="**"?"private":e==="public"?0:e==="authorized"?1:e==="admin"?99:typeof e=="number"?e:0}function Jt(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 nr(e,t,r){let n=O.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 $=n.passthrough.get(i);return n.passthrough.delete(i),{send:$,plain:e,encrypted:true,omit:false}}let{group:a,table:u,record:c}=await Co.call(this,n,t,s);if(a!=="private"){let $=true;if(!r&&i){let z=c||await _e.call(this,i);if(z&&z.encrypted){if(Jt.call(this,z,i,"making it non-private"),z.encrypted.status==="failed")throw new l(`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 Ve=!!z.bin&&Object.keys(z.bin).some(lt=>(z.bin[lt]||[]).some(kr=>kr&&kr.encrypted));if(!Ve&&s){let lt=n.dek.get(s);lt&&(M(lt.bytes),n.dek.delete(s));}return {send:z.data,plain:z.data,encrypted:false,omit:false,files:Ve?"decrypt":void 0}}}let re=c;i&&!re&&(re=await _e.call(this,i).catch(()=>null)),re&&re.encrypted&&Jt.call(this,re,i,"making it non-private");let Sr=!!re&&!!re.bin&&Object.keys(re.bin).some(z=>(re.bin[z]||[]).some(Ve=>Ve&&Ve.encrypted));if(Sr&&($=false),$&&s){let z=n.dek.get(s);z&&(M(z.bytes),n.dek.delete(s));}return {send:e,plain:e,encrypted:false,omit:!r,files:Sr?"decrypt":void 0}}if(un(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(tr.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,Qe))throw new l(`"${Qe}" 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 g=this.user?.user_id;if(!g)throw new l("User login is required to write an encrypted record.",{code:"INVALID_REQUEST"});let f=De.call(this),d=false;if(i&&n.roll.has(i)){d=true,n.roll.delete(i);let $=n.dek.get(i);n.dek.delete(i),$&&M($.bytes);}let p=c;i&&!p&&!n.dek.has(i)&&(p=await _e.call(this,i).catch(()=>null)),p&&Jt.call(this,p,i,"making it private");let y=!!p&&!p.encrypted&&!!p.bin&&Object.keys(p.bin).some($=>(p.bin[$]||[]).some(re=>re&&!re.encrypted)),h=null;if(i&&!d&&(h=n.dek.get(i)||null,!h)){let $=p||c||await _e.call(this,i);if($&&(s=$.record_id||i,h=n.dek.get(s)||null,!o&&$.unique_id&&(o=$.unique_id),!h&&$.encrypted?.status==="failed"))throw new l(`Cannot update encrypted record "${i}": its current contents could not be decrypted (${$.encrypted.reason}), so its existing key wraps cannot be preserved. Updating anyway would revoke everyone it is shared with.`,{code:"ENCRYPTION_LOCKED"})}s===i&&h&&h.rid&&(s=h.rid),!o&&h&&h.anch==="uid"&&h.uid&&(o=h.uid);let _,w,b;if(h){if(h.own&&h.own!==g)throw new l(`Record "${i}" belongs to another user (${h.own}). Encryption only operates on records you own.`,{code:"ENCRYPTION_NOT_RECORD_OWNER"});_=h.bytes,w=h.key,b=Object.assign({},h.recipients);}else {let $=await Br();_=$.bytes,w=$.key,b={};}let E=o?"uid":s?"rid":"new",R=E==="uid"?o:E==="rid"?s:"",k=Zt(f,g,E,R),U=We(k,g,"mk"),D=await ie(n.mk,_,U);b[g]={t:"mk",iv:F(D.iv),ct:F(D.ct)},h&&(h.anch!==E||er(h)!==R)&&(b=await Oo.call(this,n,_,b,f,g,E,R,k));let x=K(JSON.stringify(e===void 0?null:e)),v=await ie(w,x,k);M(x);let C={[Qe]:on,enc:"A256GCM",kw:"ECDH-ES+A256GCM",anch:E,uid:o,rid:s,own:g,iv:F(v.iv),ct:F(v.ct),k:b},L,q,Q=C.ct;s&&Q.length>Do&&(L=V(Q),C.ct="",C.ct_ref=xo,h&&h.ctRef&&(q=h.ctRef));let Ae=JSON.stringify(C).length;if(Ae>2*1024*1024)throw new l(`Encrypted record data is too large: once encrypted and base64 encoded it becomes ${Ae} bytes, over the ${2*1024*1024} byte limit. Encryption costs about 33% plus roughly 230 bytes per additional recipient.`,{code:"ENCRYPTED_DATA_TOO_LARGE"});return s&&n.dek.set(s,{bytes:_,key:w,recipients:b,anch:E,uid:o,rid:s,own:g,access_group:"private"}),{send:C,plain:e,encrypted:true,omit:false,spill:L,retireCt:q,dek:{bytes:_,key:w,recipients:b,anch:E,uid:o,rid:s,own:g,access_group:"private"},files:y?"encrypt":void 0}}function pn(e,t){let r=O.call(this);!r||!t||!e||r.dek.has(e)||r.dek.set(e,Object.assign({},t,{rid:e}));}async function Oo(e,t,r,n,i,s,o,a){let u=Object.keys(r).filter(f=>f!==i);if(!u.length)return r;let c=await ur.call(this,u),g={[i]:r[i]};for(let f of u){let d=c[f];d&&(g[f]=await hn.call(this,t,d,n,o,i,f,a));}return g}async function hn(e,t,r,n,i,s,o){let a=dn(r,n,i,s,t.fpr),u=We(o,s,t.fpr),c=await Gr(t.pubRaw,e,a,u);return {t:"ecdh",epk:F(c.epk),iv:F(c.iv),ct:F(c.ct),fpr:t.fpr}}async function mn(e,t){if(!mt(e))return {value:e};if(t.access_group!=="private")return {value:e};let r=O.call(this);if(!r)return {value:null,flag:{status:"failed",reason:"ENCRYPTION_DISABLED"}};if(r.rawRead)return {value:e};if(un(r,t.table_name))return {value:e};if(e[Qe]!==on)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=De.call(this),o=er(e),a=Zt(s,e.own,e.anch,o),u;try{if(i.t==="mk")u=await ae(r.mk,V(i.iv),V(i.ct),We(a,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 Wr(r.ikPriv,V(i.epk),V(i.iv),V(i.ct),dn(s,o,e.own,n,i.fpr),We(a,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 M(u),{value:ee(r.cfg,"DATA_UNAVAILABLE"),flag:{status:"failed",reason:"DATA_UNAVAILABLE"}};let p=await Lo.call(this,t.ctUrl);c=new Uint8Array(await p.arrayBuffer());}else c=V(e.ct);}catch{return M(u),{value:ee(r.cfg,"DATA_UNAVAILABLE"),flag:{status:"failed",reason:"DATA_UNAVAILABLE"}}}let g,f;try{f=await oe(u),g=await ae(f,V(e.iv),c,a);}catch{return M(u),{value:ee(r.cfg,"CORRUPT"),flag:{status:"failed",reason:"CORRUPT"}}}let d;try{d=JSON.parse(je(g));}catch{return M(g),M(u),{value:ee(r.cfg,"CORRUPT"),flag:{status:"failed",reason:"CORRUPT"}}}if(M(g),t.record_id){let p=r.dek.get(t.record_id);p?(p.bytes=u,p.key=f,p.recipients=e.k,p.anch=e.anch,p.uid=e.uid,p.own=e.own,p.access_group="private",p.ctRef=e.ct_ref||""):r.dek.set(t.record_id,{bytes:u,key:f,recipients:e.k,anch:e.anch,uid:e.uid,rid:t.record_id,own:e.own,access_group:"private",ctRef:e.ct_ref||""});}else M(u);return {value:d,flag:{status:"encrypted",recipients:Object.keys(e.k)}}}function ze(e,t){let[r,n]=e.split("/");return K(`${X}|kek|${r}|${n}|${t}`)}function Je(e,t,r,n){let[i,s]=e.split("/");return K(`${X}|mk|${i}|${s}|${t}|PBKDF2-SHA256|${r}|${n}`)}function yn(e,t){let[r,n]=e.split("/");return K(`${X}|recovery|${r}|${n}|${t}`)}function bn(e,t,r){let[n,i]=e.split("/");return K(`${X}|rk|${n}|${i}|${t}|HKDF-SHA256|${r}`)}function _n(e,t){let[r,n]=e.split("/");return K(`${X}|self|${r}|${n}|${t}`)}function wn(e,t){let[r,n]=e.split("/");return K(`${X}|ik|${r}|${n}|${t}`)}async function yt(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 ir(e,t,r){let n=Z(Ke),i=zr(n),s=Z(16),o=F(s),a=await Qt(n,s,yn(e,t)),u=await ie(a,r,bn(e,t,o));return M(n),{code:i,wrap:{id:F(Z(6)),p:"recovery",kdf:{a:"HKDF-SHA256",s:o},iv:F(u.iv),ct:F(u.ct),created:Date.now()}}}async function Mo(e,t,r,n){let i=Jr(n),s=(r||[]).filter(o=>o.p==="recovery");s.sort((o,a)=>(a.created||0)-(o.created||0));for(let o of s)try{let a=await Qt(i,V(o.kdf.s),yn(e,t)),u=await ae(a,V(o.iv),V(o.ct),bn(e,t,o.kdf.s));return M(i),u}catch{}return M(i),null}async function Fo(e,t,r,n,i){let s=Z(16),o=F(s),a=await Ue(n,s,e.cfg.iterations,ze(t,r)),u=await ie(a,i,Je(t,r,e.cfg.iterations,o));return {id:F(Z(6)),p:"password",kdf:{a:"PBKDF2-SHA256",it:e.cfg.iterations,s:o},iv:F(u.iv),ct:F(u.ct),created:Date.now()}}async function qo(e,t){let r=this.user.user_id,n=e.scope,i=Z(16),s=F(i),o=await Ue(t,i,e.cfg.iterations,ze(n,r)),a=Z(32),u=await ie(o,a,Je(n,r,e.cfg.iterations,s)),c=await oe(a),g=await Kr(),f=await ie(c,g.pkcs8,wn(n,r));M(g.pkcs8);let d=null;e.cfg.recovery==="code"&&(d=await ir(n,r,a));let p=await ie(c,a,_n(n,r));M(a);let y=await Gt(g.pubRaw),h=Date.now(),_=[{id:F(Z(6)),p:"password",kdf:{a:"PBKDF2-SHA256",it:e.cfg.iterations,s},iv:F(u.iv),ct:F(u.ct),created:h}];d&&_.push(d.wrap);let w={v:1,alg:"ECDH-P-256",user_id:r,wraps:_,ik:{iv:F(f.iv),ct:F(f.ct)},self:{iv:F(p.iv),ct:F(p.ct)},pub:F(g.pubRaw),fpr:y,pins:null,created:h,updated:h};await this.postRecord({v:1,alg:"ECDH-P-256",user_id:r,pub:F(g.pubRaw),fpr:y,created:h},{table:{name:e.cfg.table,access_group:"authorized"},index:{name:"pubkey",value:r}});let b=await this.postRecord(w,{table:{name:e.cfg.table,access_group:"private"}}),E=await yt.call(this,e);if(E&&E.record_id!==b.record_id){await En.call(this,e,E,t);return}e.mk=c,e.ikPriv=g.priv,e.pubRaw=g.pubRaw,e.fpr=y,e.keyringRecordId=b.record_id,d&&(e.pendingRecoveryCode=d.code),e.user_id=r,e.pins={},e.status="unlocked",e.reason="";}async function En(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 l("The encryption keyring does not belong to this user.",{code:"ENCRYPTION_KEYRING_CORRUPT"});let a=(Array.isArray(s?.wraps)?s.wraps:[]).filter(g=>g.p==="password");if(!a.length)throw new l("The keyring has no password wrap.",{code:"ENCRYPTION_KEYRING_CORRUPT"});a.sort((g,f)=>(f.created||0)-(g.created||0));let u=null;for(let g of a)try{let f=V(g.kdf.s),d=await Ue(r,f,g.kdf.it,ze(i,n));u=await ae(d,V(g.iv),V(g.ct),Je(i,n,g.kdf.it,g.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 oe(u);M(u),await sr.call(this,e,t,c);}async function sr(e,t,r){let n=this.user.user_id,i=t.data,s=await ae(r,V(i.ik.iv),V(i.ik.ct),wn(e.scope,n)),o=await Ht(s);M(s);let a={};if(i.pins&&typeof i.pins=="object"&&i.pins.ct)try{let u=await ae(r,V(i.pins.iv),V(i.pins.ct),K(`${X}|pins|${e.scope}|${n}`));a=JSON.parse(je(u)),M(u);}catch{a={};}e.mk=r,e.ikPriv=o,e.pubRaw=V(i.pub),e.fpr=i.fpr,e.keyringRecordId=t.record_id,e.user_id=n,e.pins=a,e.status="unlocked",e.reason="";}async function bt(e){let t=O.call(this);if(!t||!this.user?.user_id)return;if(!Kt()){t.status="locked",t.reason="NO_WEB_CRYPTO";return}if(this.user?.is_openid){t.status="locked",t.reason="OPENID_UNSUPPORTED";return}if(t.cfg.minPasswordLength&&e.length<t.cfg.minPasswordLength){t.status="locked",t.reason="WEAK_PASSWORD";return}t.scope=De.call(this);let r=await yt.call(this,t);r?await En.call(this,t,r,e):await qo.call(this,t,e),t.cfg.persistDevice&&await Pn.call(this,t).catch(()=>{});}async function An(e){await this.__connection;let t=O.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 bt.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 Rn(e){let t=O.call(this);return t?(e?.forgetDevice&&await cr.call(this,t).catch(()=>{}),Xt.call(this),this.__cached_requests={},{status:t.status}):{status:"disabled"}}async function In(e,t){let r=O.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 i=(await this.getRecords({record_id:r.keyringRecordId},{limit:1}))?.list?.[0];if(!i)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 s=this.user.user_id,o=i.data,a=(o.wraps||[]).filter(h=>h.p==="password");a.sort((h,_)=>(_.created||0)-(h.created||0));let u=null;for(let h of a)try{let _=await Ue(e,V(h.kdf.s),h.kdf.it,ze(r.scope,s));u=await ae(_,V(h.iv),V(h.ct),Je(r.scope,s,h.kdf.it,h.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=Z(16),g=F(c),f=await Ue(t,c,r.cfg.iterations,ze(r.scope,s)),d=await ie(f,u,Je(r.scope,s,r.cfg.iterations,g));M(u);let p=Date.now(),y=(o.wraps||[]).concat([{id:F(Z(6)),p:"password",kdf:{a:"PBKDF2-SHA256",it:r.cfg.iterations,s:g},iv:F(d.iv),ct:F(d.ct),created:p}]);await this.postRecord(Object.assign({},o,{wraps:y,updated:p}),{record_id:r.keyringRecordId});}async function Tn(){let e=O.call(this);if(!e||e.status!=="unlocked"||!e.keyringRecordId)return;let r=(await this.getRecords({record_id:e.keyringRecordId},{limit:1}))?.list?.[0];if(!r)return;let n=r.data,i=(n.wraps||[]).filter(o=>o.p==="password").sort((o,a)=>(a.created||0)-(o.created||0)),s=(n.wraps||[]).filter(o=>o.p!=="password");i.length<=1||await this.postRecord(Object.assign({},n,{wraps:[i[0]].concat(s),updated:Date.now()}),{record_id:e.keyringRecordId});}function or(){return typeof indexedDB<"u"&&!!indexedDB}function ar(){return new Promise((e,t)=>{let r=indexedDB.open(Uo,1);r.onupgradeneeded=()=>{let n=r.result;n.objectStoreNames.contains(we)||n.createObjectStore(we);},r.onsuccess=()=>e(r.result),r.onerror=()=>t(r.error);})}function lr(e){return `${e.scope}#${this.user?.user_id}`}async function Pn(e){if(!or()||!e.mk)return;let t=await ar();await new Promise((r,n)=>{let i=t.transaction(we,"readwrite");i.objectStore(we).put({mk:e.mk,keyringRecordId:e.keyringRecordId,saved:Date.now()},lr.call(this,e)),i.oncomplete=()=>r(),i.onerror=()=>n(i.error);}),t.close();}async function Vo(e){if(!or())return null;let t=await ar(),r=await new Promise((n,i)=>{let o=t.transaction(we,"readonly").objectStore(we).get(lr.call(this,e));o.onsuccess=()=>n(o.result||null),o.onerror=()=>i(o.error);});return t.close(),r&&r.mk?r:null}async function cr(e){if(!or())return;let t=await ar();await new Promise((r,n)=>{let i=t.transaction(we,"readwrite");i.objectStore(we).delete(lr.call(this,e)),i.oncomplete=()=>r(),i.onerror=()=>n(i.error);}),t.close();}function Sn(){let e=O.call(this);!e||e.ready||(e.unlocking=true,e.ready=$o.bind(this)().catch(()=>false).then(()=>{e.unlocking=false;}));}async function $o(){let e=O.call(this);if(!e||!this.user?.user_id||!e.cfg.persistDevice||!Kt())return false;e.scope=De.call(this);try{let t=await Vo.call(this,e);if(!t)return !1;let r=await yt.call(this,e);return r?(await sr.call(this,e,r,t.mk),!0):(await cr.call(this,e).catch(()=>{}),!1)}catch{return e.status="locked",e.reason="NO_SESSION_KEY",false}}async function ur(e){let t=O.call(this);if(!t)throw new l("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(p=>p.user_id===s&&p.data?.pub);if(!c.length)return null;c.sort((p,y)=>y.uploaded-p.uploaded);let g=V(c[0].data.pub),f=await Gt(g),d=t.pins[s];if(d&&d!==f)throw new l(`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 l(`No pinned key for user "${s}" and trustPolicy is "strict". Pin it first with pinPeerKey().`,{code:"ENCRYPTION_PEER_NOT_PINNED"});t.pins[s]=f,i=true;}return {pubRaw:g,fpr:f}})().finally(()=>t.peerInflight.delete(s)),t.peerInflight.set(s,o));let a=await o;a&&t.peerPub.set(s,a),r[s]=a;})),i&&await Un.call(this,t).catch(()=>{}),r}async function kn(e,t){let r=De.call(this),n=e.dek.get(t);if(n)return {entry:n,scope:r};let i=await _e.call(this,t);if(!i)throw new l(`Record "${t}" not found.`,{code:"NOT_EXISTS"});if(i.encrypted?.status==="failed"&&i.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(!i.encrypted)return null;if(i.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 s=e.dek.get(i.record_id)||e.dek.get(t);if(!s)throw new l(`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 dr(e,t){let r=O.call(this);if(!r)return;let n=await kn.call(this,r,e);if(!n)return;let{entry:i,scope:s}=n,o=this.user.user_id;if(i.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 ur.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=er(i),g=Zt(s,i.own,i.anch,c),f=Object.assign({},i.recipients);for(let d of t)d!==o&&(f[d]=await hn.call(this,i.bytes,a[d],s,c,i.own,d,g));await Bo.call(this,r,e,i,f);}async function vn(e,t){let r=O.call(this);if(!r)return;let n=await kn.call(this,r,e);if(!n)return;let{entry:i}=n,s=this.user.user_id;if(i.own!==s)throw new l("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),a=await _e.call(this,e);if(!a)throw new l(`Record "${e}" not found.`,{code:"NOT_EXISTS"});jo(a,e);let u={};if(o.length){u=await ur.call(this,o);let c=o.filter(g=>!u[g]);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 dr.call(this,a.record_id||e,o);}function jo(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 Bo(e,t,r,n){let i=await Ko.call(this,t);if(!i)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 s=Object.assign({},i,{k:n});e.passthrough.set(t,s),await this.postRecord(void 0,{record_id:t});}async function Ko(e){let t=O.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&&mt(r.data)?r.data:null}async function Nn(e){let t=O.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 Un.call(this,t);}async function Un(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 ie(e.mk,K(JSON.stringify(e.pins)),K(`${X}|pins|${e.scope}|${e.user_id}`));await this.postRecord(Object.assign({},r.data,{pins:{iv:F(n.iv),ct:F(n.ct)},updated:Date.now()}),{record_id:e.keyringRecordId});}function Dn(){let e=O.call(this);if(!e||!e.pendingRecoveryCode)return null;let t=e.pendingRecoveryCode;return e.pendingRecoveryCode="",t}async function xn(e){await this.__connection;let t=O.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=De.call(this);let r=this.user.user_id,n=await yt.call(this,t);if(!n)throw new l("This account has no encryption keyring, so there is nothing to recover.",{code:"NOT_EXISTS"});let i=await Mo(t.scope,r,n.data?.wraps||[],e.code);if(!i)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 s=await oe(i);await sr.call(this,t,n,s);let o=false,a=null,u=(n.data?.wraps||[]).slice();if(e.password&&(u=u.filter(c=>c.p!=="password"),u.push(await Fo(t,t.scope,r,e.password,i)),o=true),t.cfg.recovery==="code"){let c=await ir(t.scope,r,i);u=u.filter(g=>g.p!=="recovery"),u.push(c.wrap),a=c.code;}return M(i),await this.postRecord(Object.assign({},n.data,{wraps:u,updated:Date.now()}),{record_id:n.record_id}),t.cfg.persistDevice&&await Pn.call(this,t).catch(()=>{}),{status:t.status,repaired:o,recoveryCode:a}}async function Cn(){await this.__connection;let e=O.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 i=await ae(e.mk,V(n.iv),V(n.ct),_n(e.scope,e.user_id)),s=await ir(e.scope,e.user_id,i);M(i);let o=(r.data.wraps||[]).filter(a=>a.p!=="recovery").concat([s.wrap]);return await this.postRecord(Object.assign({},r.data,{wraps:o,updated:Date.now()}),{record_id:e.keyringRecordId}),{recoveryCode:s.code}}var ht="__skenc__",Ln="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";function Ho(e){if(e===0)return "0";let t="";for(;e>0;)t=Ln[e%62]+t,e=Math.floor(e/62);return t}function Go(e){let t=0;for(let r of e){let n=Ln.indexOf(r);if(n<0)return NaN;t=t*62+n;}return t}function _t(e){if(typeof e!="string")return null;let t=e.lastIndexOf(ht);if(t<0)return null;let r=Go(e.slice(t+ht.length));return Number.isFinite(r)?{key:e.slice(0,t),plainSize:r}:null}function fr(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=_t(t[10]);return r?{recordId:t[5],recordOwner:t[3],filename:t[t.length-1],plainSize:r.plainSize}:null}catch{return null}}function On(e,t){return {service:this.service,owner:this.owner,recordOwner:t,recordId:e}}async function Mn(e,t,r){let n=O.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(_t(t))throw new l(`"${ht}" is reserved in an upload form key.`,{code:"INVALID_PARAMETER"});if(t===Ye)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},a=await rn(i.bytes,s,On.call(this,e,i.own),o);return M(s),{key:`${t}${ht}${Ho(r.size)}`,file:new File([a],r.name,{type:"application/octet-stream"}),encrypted:true}}async function Fn(e,t){let r=O.call(this),n=fr(e);if(!r||!n)return t;let i=r.dek.get(n.recordId);if(!i)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 s=new Uint8Array(await t.arrayBuffer());if(!zt(s))throw new l("This file is marked as encrypted but its contents are not an encrypted container.",{code:"ENCRYPTION_FILE_CORRUPT"});let o=await nn(i.bytes,s,On.call(this,n.recordId,n.recordOwner)),a=o.meta&&o.meta.t||"application/octet-stream";return new Blob([o.bytes],{type:a})}function Wo(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 Qo(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 gr(e,t,r){let n=O.call(this);if(!n)return [];let i=await _e.call(this,e);if(!i)return [];let s=t==="decrypt"?Wo(i):Qo(i);if(!s.length)return [];let o=[],a=new FormData,u=false;for(let c of s){let g=i.bin[c.formKey].find(d=>d.url===c.url);if(!g||typeof g.getFile!="function")continue;let f=await g.getFile("blob");f&&(a.append(c.formKey,new File([f],c.filename,{type:f.type||"application/octet-stream"})),o.push(c.url),u=true);}if(!u)return [];if(t==="decrypt"){let c=n.dek.get(e);c&&(M(c.bytes),n.dek.delete(e));}return await this.uploadFiles(a,{record_id:e,progress:r}),o}var B=null;function pr(e){let t={tkid:"ticket_id",cond:"condition",stmp:"timestamp",actn:"action",cnt:"count",ttl:"time_to_live",plch:"placeholder",hash:"hash",desc:"description",pmc:"limit_per_user"},r={};for(let n in e)if(n==="tkid"){let i=e[n].split("#");if(i.length===1){r.ticket_id=i[0];continue}r.ticket_id=i[1],r.consume_id=i[2],r.user_id=i[3];let s=i[2].slice(-4);if(r.is_test=s===":CHK",!e.stmp){let o=i[2].slice(0,-4);/^[0-9]+$/.test(o)?r.timestamp=parseInt(o,10):r.timestamp=se(i[2].slice(0,-4));}}else t[n]?r[t[n]]=e[n]:r[n]=e[n];return r}async function Vn(e){if(!e.ticket_id)throw new l("Ticket ID is required.",{code:"INVALID_PARAMETER"});if(!e.method)throw new l('Method is required. Should be either "GET" or "POST"',{code:"INVALID_PARAMETER"});let t=e.ticket_id;await this.__connection;let r=await T.bind(this)(`https://${this.service.slice(0,4)}.${this.customApiDomain}/auth/consume/${this.service}/${this.owner}/${t}`,e?.data||{},{method:e.method,auth:!!e?.auth});return pr(r)}async function $n(e,t){await this.__connection;let r=await T.bind(this)("ticket",Object.assign({exec:"list"},e||{}),{auth:true,fetchOptions:t});return r.list=r.list.map(pr),r}async function jn(e,t){await this.__connection;let r=await T.bind(this)("ticket",Object.assign({exec:"consumed"},e||{}),{auth:true,fetchOptions:t});return r.list=r.list.map(pr),r}async function Bn(e){return T.bind(this)("register-ticket",Object.assign({exec:"reg"},e),{auth:true})}async function Kn(e){return T.bind(this)("register-ticket",Object.assign({exec:"unreg"},e),{auth:true})}var ea=3600;async function Ce(){if(await this.__connection,this.session){let e=Math.floor(Date.now()/1e3),r=this.session.getIdToken().getExpiration();if(r<e+ea){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),ye.bind(this)(),new l("User login is required.",{code:"INVALID_REQUEST"})}function qn(e,t){return new Promise((r,n)=>{t.refreshSession(e.getRefreshToken(),(i,s)=>{this.log("getSession:refreshSessionCallback",{refreshErr:i,refreshedSession:s}),i?(ye.bind(this)(),n(i)):s.isValid()?r(s):(ye.bind(this)(),n(new l("Invalid session.",{code:"INVALID_REQUEST"})));});})}function J(){if(!this.userPool)throw new l("User pool is missing",{code:"INVALID_REQUEST"});let e=()=>{let s=B.getSignInUserSession().getIdToken().payload||null,o=$e(s);return this.log("normalized user attribute",o),this.__user=o,o},t=async s=>new Promise((o,a)=>{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),ye.bind(this)(),a(null);return}let g=f=>{let d=f.getIdToken().payload;if(this.log("getSession:respond:sessionAttribute",d),d["custom:service"]!==this.service)throw this.log("getSession:respond","invalid service, signing out"),ye.bind(this)(),new l("Invalid session.",{code:"INVALID_REQUEST"});return this.session=f,e(),c||this._runOnUserUpdateListeners(this.user),this.session};B.getSession((f,d)=>{if(this.log("getSession:getSessionCallback",{err:f,session:d}),!d){ye.bind(this)(),a(new l("Current session does not exist.",{code:"INVALID_REQUEST"}));return}if(f){qn.bind(this)(d,B).then(w=>o(g(w))).catch(a);return}let p=Math.floor(Date.now()/1e3),y=d.getIdToken(),h=y.getExpiration(),_=h<p;if(this.log("getSession:currentTime",p),this.log("getSession:idTokenExp",h),this.log("getSession:isExpired",_),this.log("getSession:existingBearerToken",this.bearerToken),this.bearerToken=y.getJwtToken(),_||u||!d.isValid())qn.bind(this)(d,B).then(w=>o(g(w))).catch(a);else try{o(g(d));}catch(w){a(w);}});}),r=(s,o)=>{let a=o||s.includes(this.service+"-")?s:this.service+"-"+G.hash(s);return {cognitoUser:new CognitoUser({Username:a,Pool:this.userPool}),cognitoUsername:a}};return {getSession:t,authenticateUser:(s,o,a=false,u=false)=>new Promise((c,g)=>{this.__request_signup_confirmation=null,this.__disabledAccount=null;let f=r(s,a),d=f.cognitoUsername,p=new AuthenticationDetails({Username:d,Password:o});f.cognitoUser.authenticateUser(p,{newPasswordRequired:(y,h)=>{this.__disabledAccount=null,this.__request_signup_confirmation=d,y["custom:signup_ticket"]==="PASS"||y["custom:signup_ticket"]==="MEMBER"||y["custom:signup_ticket"]==="OIDPASS"?f.cognitoUser.completeNewPasswordChallenge(o,{},{onSuccess:_=>{B=f.cognitoUser,t().then(async w=>{if(O.call(this))try{await bt.bind(this)(o);}catch(b){this.log("encryption:ensureKeyring:failed",b);}c(this.user);});},onFailure:_=>{g(new l(_.message||"Failed to authenticate user.",{code:_.code}));}}):g(new l("User's signup confirmation is required.",{code:"SIGNUP_CONFIRMATION_NEEDED"}));},onSuccess:y=>t({skipUserUpdateEventTrigger:true}).then(async h=>{if(this.__disabledAccount=null,O.call(this))try{await bt.bind(this)(o);}catch(_){this.log("encryption:ensureKeyring:failed",_);}this._runOnLoginListeners(this.user),this._runOnUserUpdateListeners(this.user),c(this.user);}),onFailure:y=>{let h=[],{parsed:_,code:w}=Et(y),b=typeof y?.message=="string"?y.message:"";if(w==="NotAuthorizedException"?b.includes("User is disabled.")?(this.__disabledAccount=d,h=["This account is disabled.","USER_IS_DISABLED"]):u?h=["The account already exists.","ACCOUNT_EXISTS"]:h=["Incorrect username or password.","INCORRECT_USERNAME_OR_PASSWORD"]:w==="UserNotFoundException"?h=["Incorrect username or password.","INCORRECT_USERNAME_OR_PASSWORD"]:w==="UserNotConfirmedException"?(this.__request_signup_confirmation=d,h=["User's signup confirmation is required.","SIGNUP_CONFIRMATION_NEEDED"]):(w==="TooManyRequestsException"||w==="LimitExceededException")&&(h=["Too many attempts. Please try again later.","REQUEST_EXCEED"]),_.code==="SIGNUP_CONFIRMATION_NEEDED"&&(this.__request_signup_confirmation=d),h.length){let E=h[1],R=h[0];g(new l(R,{code:E,cause:y}));}else g(_);}});}),createCognitoUser:r,signup:(s,o,a)=>new Promise((u,c)=>{this.userPool.signUp(s,o,a,null,(g,f)=>{if(g){let{parsed:d,code:p}=Et(g),y=[];p==="UsernameExistsException"?y=["The account already exists.","EXISTS"]:p==="InvalidPasswordException"?y=["Invalid password. Password must be at least 6 characters.","INVALID_PARAMETER"]:p==="InvalidParameterException"?y=[d.message||"Invalid parameter.","INVALID_PARAMETER"]:p==="TooManyRequestsException"||p==="LimitExceededException"?y=["Too many attempts. Please try again later.","REQUEST_EXCEED"]:p==="CodeDeliveryFailureException"?y=["Failed to deliver verification code.","CODE_DELIVERY_FAILURE"]:p==="UserLambdaValidationException"&&(y=[d.message||"Signup validation failed.","INVALID_REQUEST"]),y.length?c(new l(y[0],{code:y[1],cause:g})):c(d);return}u(f);});})}}function Et(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 l(o,{code:s,cause:e}),code:t}}async function Hn(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 Gn(e){await this.__connection,e=m.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 T.bind(this)("openid-logger",t),n=r.logger.split("#"),i=this.service+"-"+n[0],s=n[1];return {userProfile:await J.bind(this)().authenticateUser(i,s,true,true),openid:r.openid}}function ta(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 ra(e){let t=e.split(".");if(t.length!==3)throw new Error("Invalid JWT format");let n=t[1].replace(/-/g,"+").replace(/_/g,"/"),i=ta(n);return JSON.parse(i)}async function Wn(e){await this.__authConnection,this.log("loginWithToken:params",e),e=m.Params(e,{idToken:"string",accessToken:"string",refreshToken:"string"},["idToken"]);let t=ra(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=$e(t),this.session=null,e.accessToken&&e.refreshToken)try{if(this.session=new CognitoUserSession({IdToken:new CognitoIdToken({IdToken:e.idToken}),AccessToken:new CognitoAccessToken({AccessToken:e.accessToken}),RefreshToken:new CognitoRefreshToken({RefreshToken:e.refreshToken})}),this.log("loginWithToken:session",this.session),this.log("loginWithToken:CognitoUser",CognitoUser),this.log("loginWithToken:userPool",this.userPool),CognitoUser&&this.userPool){this.log("loginWithToken:cognito:username",t["cognito:username"]);let n={Username:t["cognito:username"],Pool:this.userPool};this.log("loginWithToken:cognitoUserParams",n),B=new 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 W(){return await this.__connection,this.__user?.service===this.service?this.__user?.owner===this.host:(await Xe.bind(this)(),false)}async function ye(e=false){let t=null;B&&(e?t=new Promise((n,i)=>{B.globalSignOut({onSuccess:s=>{this.log("globalSignOut:success",s),n(s);},onFailure:s=>{this.log("globalSignOut:error",s),i(s);}});}):B.signOut()),Xt.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 Xe(e){await this.__connection;let{data:t}=j(e);return await ye.bind(this)(t?.global),"SUCCESS: The user has been logged out."}async function Qn(){if(!this.__request_signup_confirmation)throw new l("Least one login attempt is required.",{code:"INVALID_REQUEST"});return await T.bind(this)("confirm-signup",{username:this.__request_signup_confirmation})}async function zn(e=false){if(typeof e=="string")e=m.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 T.bind(this)("recover-account",{username:this.__disabledAccount,redirect:e}),"SUCCESS: Recovery e-mail has been sent."}async function hr(e){let t=m.Params(e,{username:"string",email:"string",password:"string"},["password"]);if(await this.__authConnection,t.email)try{m.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"});return await J.bind(this)().authenticateUser(t.username||t.email,t.password)}async function Jn(e,t){await this.__authConnection;let r={username:"string",password:c=>m.Password(c),email:c=>m.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?m.Birthdate(c):"",phone_number:c=>c?m.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?m.Url(c):"",profile:c=>c?m.Url(c):"",family_name:"string",given_name:"string",middle_name:"string",nickname:"string",website:c=>c?m.Url(c):""},n=m.Params(e||{},r,["email","password"]);await Xe.bind(this)(),t=m.Params(t||{},{email_subscription:c=>{if(typeof c!="boolean")throw new l('"option.email_subscription" should be type: <boolean>.',{code:"INVALID_PARAMETER"});if(!t?.signup_confirmation)throw new l('"option.signup_confirmation" is required for email subscription.',{code:"INVALID_PARAMETER"});return c},signup_confirmation:c=>{let g=c;if(typeof c=="string")g=m.Url(c);else if(typeof c=="boolean")g=c;else throw new l('"option.signup_confirmation" should be type: <string | boolean>.',{code:"INVALID_PARAMETER"});if(g&&!n.email)throw new l('"email" is required for signup confirmation.',{code:"INVALID_PARAMETER"});return g},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 i=t?.login||false;if(n.signup_confirmation=t?.signup_confirmation||false,n.email_subscription=t?.email_subscription||false,n.email_public&&!n.signup_confirmation)throw new 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 s=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 T.bind(this)("signupkey",{username:s.cognitoUsername,signup_confirmation:typeof n.signup_confirmation=="boolean"?JSON.stringify(n.signup_confirmation):n.signup_confirmation,email_subscription:n.email_subscription,template_confirmation:t?.template?.signup_confirmation||"",template_welcome:t?.template?.welcome||""})).split(":"),a=o.slice(1).join(":"),u=[new CognitoUserAttribute({Name:"custom:signup",Value:o[0]}),new CognitoUserAttribute({Name:"locale",Value:a.split("#")[1]}),new CognitoUserAttribute({Name:"custom:signup_ticket",Value:a})];for(let c in r){let g=["email_public","address_public","gender_public","birthdate_public","phone_number_public","misc","service","owner"];n[c]!==""&&(c==="username"||c==="password"||c==="access_group"||(g.includes(c)?u.push(new CognitoUserAttribute({Name:"custom:"+c,Value:n[c]})):u.push(new CognitoUserAttribute({Name:c,Value:n[c]}))));}return await J.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?hr.bind(this)({email:n.username||n.email,password:n.password}):"SUCCESS: The account has been created."}async function Yn(){await this.__connection;let e=await T.bind(this)("remove-account",{disable:this.__user.user_id},{auth:true});return await Xe.bind(this)(),e}async function Xn(e){await this.__connection;let t=m.Params(e,{email:i=>m.Email(i),code:["number","string"],new_password:i=>m.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)=>{J.bind(this)().createCognitoUser(t.email).cognitoUser.confirmPassword(r,n,{onSuccess:a=>{i("SUCCESS: New password has been set.");},onFailure:a=>{s(new l(a?.message||"Failed to reset password.",{code:a?.code||"ERROR",cause:a}));}});})}async function Zn(e,t,r){await this.__connection;let n;if(!B)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?m.Params(t,{code:"string"}):{}).code||"";}else return;let i,s=r?.template?.verification;if(s!==void 0){if(typeof s!="string"||!s)throw new l('"template.verification" should be a non-empty <string> (template message_id).',{code:"INVALID_PARAMETER"});i={template_verification:s};}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(g=>{a(g);}):o("SUCCESS: Verification code has been sent.");},onFailure:c=>{a(new l(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 ei(e,t){return Zn.bind(this)("phone_number",e,t)}function ti(e,t){return Zn.bind(this)("email",e,t)}async function ri(e,t){await this.__connection;let r=m.Params(e,{email:s=>m.Email(s)},["email"]),n,i=t?.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"});n={template_verification:i};}return new Promise(async(s,o)=>{J.bind(this)().createCognitoUser(r.email).cognitoUser.forgotPassword({onSuccess:u=>{s("SUCCESS: Verification code has been sent.");},onFailure:u=>{let{parsed:c,code:g}=Et(u),f={UserNotFoundException:"NOT_EXISTS",InvalidParameterException:"INVALID_PARAMETER",NotAuthorizedException:"INVALID_REQUEST",LimitExceededException:"REQUEST_EXCEED",TooManyRequestsException:"REQUEST_EXCEED",CodeDeliveryFailureException:"CODE_DELIVERY_FAILURE"}[g]||c.code||g||"ERROR";o(new l(c.message,{code:f,cause:u}));}},n);})}async function ni(e){if(await this.__connection,!this.session)throw new l("User login is required.",{code:"INVALID_REQUEST"});let t=m.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 m.Password(t.current_password),m.Password(t.new_password),O.call(this)&&await In.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 l("Invalid password parameter.",{code:"INVALID_PARAMETER"}));else if(i?.code==="NotAuthorizedException")n(new l("Incorrect password.",{code:"INVALID_REQUEST"}));else if(i?.code==="TooManyRequestsException"||i?.code==="LimitExceededException")n(new l("Too many attempts. Please try again later.",{code:"REQUEST_EXCEED"}));else {let{parsed:o}=Et(i);n(o);}return}O.call(this)&&Tn.bind(this)().catch(o=>this.log("encryption:prune:failed",o)),r("SUCCESS: Password has been changed.");});})}async function ii(e){if(await this.__connection,!this.session)throw new l("User login is required.",{code:"INVALID_REQUEST"});let t=m.Params(e||{},{user_id:i=>m.UserId(i),email:i=>m.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?m.Birthdate(i):"",phone_number:i=>i?m.PhoneNumber(i):"",email_public:"boolean",phone_number_public:"boolean",address_public:"boolean",gender_public:"boolean",birthdate_public:"boolean",misc:"string",picture:i=>i?m.Url(i):"",profile:i=>i?m.Url(i):"",family_name:"string",given_name:"string",middle_name:"string",nickname:"string",website:i=>i?m.Url(i):""});if(t&&typeof t=="object"&&!Object.keys(t).length)return this.user;t.email&&(t.preferred_username=this.service+"-"+G.hash(t.email));let r=[["email_public","email_verified","User's e-mail should be verified to set"],["phone_number_public","phone_number_verified","User's phone number should be verified to set"]];if(this.__user){for(let i of r)if(t[i[0]]&&!this.__user[i[1]])throw new l(`${i[2]} "${i[0]}" to true.`,{code:"INVALID_REQUEST"})}let n=[];for(let i in t){if(t[i]===this.user[i]){n.push(i);continue}if(["email_public","phone_number_public","address_public","gender_public","birthdate_public","misc"].includes(i)){let o=t[i];typeof o=="boolean"&&(o=o?"1":"0"),t["custom:"+i]=o,n.push(i);}}for(let i of n)delete t[i];if(t.user_id)if(t.user_id===this.user.user_id)delete t.user_id;else return T.bind(this)("admin-edit-profile",{attributes:t},{auth:true});if(t&&typeof t=="object"&&Object.keys(t).length){let i=[];for(let s in t)i.push(new CognitoUserAttribute({Name:s,Value:t[s]}));return await new Promise((s,o)=>{B?.updateAttributes(i,(a,u)=>{a&&o([a?.code||a?.name,a?.message||"Failed to update user settings."]),s(u);});}),await J.bind(this)().getSession({refreshToken:true}),this.user}return this.user}async function si(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:i=>Array.isArray(i)?i.map(s=>m.UserId(s)):m.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=>m.Birthdate(i),subscribers:"number",timestamp:"number",access_group:"number",approved:"string"},n=["searchFor","value"];if(e=m.Params(e,{searchFor:["user_id","name","email","phone_number","address","gender","birthdate","locale","subscribers","timestamp","access_group","approved"],condition:[">",">=","=","<","<=","gt","gte","eq","lt","lte",()=>"="],value:i=>{let s=r[e.searchFor];if(typeof s=="function")return s(i);if(typeof i!==s)throw new l(`Value does not match the type of "${e.searchFor}" index.`,{code:"INVALID_PARAMETER"});return i},range:i=>{let s=r[e.searchFor];if(typeof s=="function")return s(i);if(typeof i!==s)throw new l(`Range does not match the type of "${e.searchFor}" index.`,{code:"INVALID_PARAMETER"});return i}},n),e?.condition&&e?.condition!=="="&&e.hasOwnProperty("range"))throw new l("Conditions does not apply on range search.",{code:"INVALID_PARAMETER"});if(e.searchFor==="user_id"&&(e.condition!=="="||e.range))throw new l(`Conditions are not allowed on "${e.searchFor}"`,{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 T.bind(this)("get-users",e,{auth:true,fetchOptions:t})}async function oi(e){await this.__connection;let t=await T.bind(this)("last-verified-email",e,{auth:true});return t.includes("SUCCESS")?(await J.bind(this)().getSession({refreshToken:true}),this.user):t}async function ai(e){return await this.__connection,e=m.Params(e,{username:m.Email,redirect:m.Url},["username"]),await T.bind(this)("request-username-change",e,{auth:true})}var Le=null,ci=typeof SubmitEvent<"u",ia=typeof HTMLFormElement<"u",et=Y(),mr=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())}function yr(e,t){return t>0?e/t*100:0}var li=e=>{let{auth:t,type:r,endpoints:n,stable:i}=e,s=n[0],o=n[1];if(mr++,r==="admin"){let a=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(!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 i?a[0]:a[mr%a.length]}throw new l("Invalid gateway type.",{code:"INVALID_REQUEST"})};async function sa(e,t,r){let n=await Promise.all([this.admin_endpoint,this.record_endpoint]),i=n[0],s=n[1],o=e.split("?"),a=o.length>1?"?"+o[1]:"";switch(e=o[0],e){case "get-users":return i.get_users_private+e+a;case "service":return i.service_public+e+a;case "get-newsletters":case "get-public-newsletters":case "subscribe-newsletter":case "subscribe-public-newsletter":case "signupkey":case "admin-newsletter-request":case "admin-signup":case "confirm-signup":case "openid-logger":case "block-account":case "admin-edit-profile":case "remove-account":case "post-secure":case "recover-account":case "mock":case "grant-access":case "last-verified-email":case "ticket":case "register-ticket":case "get-newsletter-subscription":case "request-username-change":case "send-inquiry":case "register-newsletter-group":case "delete-newsletter-group":case "newsletter-group-endpoint":case "invitation-list":case "csr":case "csr-poll":case "csr-cancel":case "csr-finalize":return li.bind(this)({auth:t,type:"admin",endpoints:n})+e+a;case "post-record":return (t?s.post_private:s.post_public)+e+a;case "get-records":return (t?s.get_private:s.get_public)+e+a;case "del-files":case "del-records":return s.del_private+e+a;case "store-subscription":case "get-vapid-public-key":case "push-notification":case "delete-subscription":case "subscription":case "get-subscription":case "get-table":case "get-tag":case "get-uniqueid":case "get-index":case "get-signed-url":case "extract-file-text":case "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 li.bind(this)({auth:t,type:"record",endpoints:n,stable:r})+e+a;default:return m.Url(e)+a}}var Ze={};function di(){Le&&(Le.terminate(),Le=null);}async function T(e,t=null,r,n){this.log("request",{url:e,data:t,options:r,_etc:n||{}}),r=r||{};let{auth:i=false,method:s="post",bypassAwaitConnection:o=false}=r;s=s.toUpperCase();let a=null,u=t?.service||this.service,c=t?.owner||this.owner,g=null,f=await sa.bind(this)(e,!!i,!!r.stableGateway);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;(i||d)&&(g=await Ce.bind(this)());let p={},{fetchMore:y=false,progress:h}=r?.fetchOptions||{};if(r?.fetchOptions&&Object.keys(r.fetchOptions).length){for(let v of ["limit","startKey","ascending"])if(r.fetchOptions.hasOwnProperty(v)){if(v==="startKey"&&r.fetchOptions[v]===null)continue;p[v]=r.fetchOptions[v];}p=m.Params(p,{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:u,owner:c};Object.assign(_,p),t=j(t).data,t?t&&typeof t=="object"&&(t=Object.assign(_,t)):t=_;let w=`${s}:${i?"auth":"public"}:${e}`,b=(()=>{if(t&&typeof t=="object"&&Object.keys(t).length&&!(et&&t instanceof FormData)){let v=function(C){return typeof C=="object"&&C!==null?Object.keys(C).sort().reduce((L,q)=>(typeof C[q]=="object"&&C[q]!==null?L[q]=v(C[q]):L[q]=C[q],L),{}):C};return G.hash(w+"/"+JSON.stringify(v(t)))}return G.hash(w+"/"+u)})(),{requestKey:E,requestKeyWithStartKey:R}=oa.bind(this)({params:t,url:e,fetchMore:y,hashedParams:b});if(!E||E&&typeof E=="object")return E;if(this.log("requestKey",R),typeof R=="string"&&Ze[R]instanceof Promise)return this.log("request:returning pending",R),Ze[R];let k={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&&(k["Content-Type"]=v);}else k["Content-Type"]="application/json";if(g&&(k.Authorization=g),r?.tokenHeaders){let v=(q,Q)=>typeof q=="string"?q:q===true?Q:null,C=v(r.tokenHeaders.accessToken,this.session?.accessToken?.jwtToken||null),L=v(r.tokenHeaders.idToken,this.bearerToken||this.session?.idToken?.jwtToken||g||null);C&&(k["X-Access-Token"]=C),L&&(k["X-Id-Token"]=L);}let D={public_identifier:this.__public_identifier,service:u,owner:c};k["Content-Meta"]=JSON.stringify(D),r.revalidate&&(k["Cache-Control"]="no-cache",k.Pragma="no-cache");let x={headers:k};if(r?.responseType&&(x.responseType=r.responseType),s==="GET"){if(t){let v=[];if(et&&t instanceof FormData?v=Array.from(t.entries()).map(([C,L])=>{let q=typeof L=="string"?L:L.name;return encodeURIComponent(C)+"="+encodeURIComponent(q)}):v=Object.keys(t).map(C=>{let L=t[C];return typeof L!="string"&&(L=JSON.stringify(L)),encodeURIComponent(C)+"="+encodeURIComponent(L)}),v.length){let C=f.includes("?")?f.endsWith("?")||f.endsWith("&")?"":"&":"?";f+=C+v.join("&");}}x.body=null;}else if(et&&t instanceof FormData)x.body=t;else if(k["Content-Type"]==="application/x-www-form-urlencoded"&&t&&typeof t=="object"){let v=new URLSearchParams;for(let C of Object.keys(t)){let L=t[C];v.append(C,typeof L=="string"?L:JSON.stringify(L));}x.body=v.toString();}else typeof t=="string"?x.body=t:x.body=t?JSON.stringify(t):null;if(x.method=s,Le===null){let v={batchSize:this.requestBatchSize,breakWhenError:false,onProgress:C=>{this.onBatchProcess.forEach(L=>L(C));}};Le=new Wi(v);}return this.log("request-opt",x),new Promise((v,C)=>{Le.add([async()=>{let L=fi.bind(this)(f,x,h);Ze[R]=L;try{let q=la.bind(this)({hashedParam:E,requestKeyWithStartKey:R,url:e,fetched:await L});return delete Ze[R],this.log("request:end",q),v(q),q}catch(q){throw delete Ze[R],this.log("request:err",q),C(q),q}}]);})}function oa(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 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]?.[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+G.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],a=i;if(o){if(o==="end")return {requestKey:{list:[],startKey:"end",endOfList:true,startKeyHistory:s},requestKeyWithStartKey:a};a+=G.hash(o),t.startKey=JSON.parse(o);}return this.__cached_requests?.[r]?.[a]?{requestKey:this.__cached_requests[r][a],requestKeyWithStartKey:a}:{requestKeyWithStartKey:a,requestKey:i}}function aa(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 fi(e,t,r){return new Promise((n,i)=>{let s=new XMLHttpRequest;s.open(t.method||"GET",e);for(var o in t.headers||{})s.setRequestHeader(o,t.headers[o]);t.responseType&&(s.responseType=t.responseType),s.onload=()=>{if(s.status<400)if(t.responseType=="json"||t.responseType=="blob")n(s.response);else {let a=s.responseText;try{a=JSON.parse(a);}catch{}n(a);}else if(s.status===429){let a=s.getResponseHeader("Retry-After"),u=ui(a);u!==null?setTimeout(()=>{fi(e,t,r).then(n,i);},u):i("Too many requests");}else {let a=s.status,u=["INVALID_CORS","INVALID_REQUEST","SERVICE_DISABLED","INVALID_PARAMETER","ERROR","EXISTS","NOT_EXISTS"],c=t.responseType=="blob"?s.response:s.responseText;try{c=JSON.parse(c);}catch{}if(typeof c=="string"){let g=c.split(":"),f=g.splice(0,1)[0].trim(),d=g.join(":").trim();i(new l(d||c,{code:u.includes(f)?f:"ERROR"}));}else if(typeof c=="object"&&c?.message){let g=c?.code||(a?a.toString():null)||"ERROR",f=c.message,d=c?.cause;typeof f=="string"&&(f=f.trim()),i(new l(f,{cause:d,code:g}));}else i(c);}},s.onerror=()=>i("Network error"),s.onabort=()=>i("Aborted"),s.ontimeout=()=>i("Timeout"),typeof r=="function"&&(s.onprogress=a=>{r({status:"download",progress:yr(a.loaded,a.total),loaded:a.loaded,total:a.total,abort:()=>s.abort()});},s.upload&&(s.upload.onprogress=a=>{r({status:"upload",progress:yr(a.loaded,a.total),loaded:a.loaded,total:a.total,abort:()=>s.abort()});})),s.send(t.body);})}function la(e){let{hashedParam:t,requestKeyWithStartKey:r,url:n,fetched:i}=e;if(!i?.startKey)return i;this.__startKeyHistory.hasOwnProperty(n)||(this.__startKeyHistory[n]={}),this.__startKeyHistory[n].hasOwnProperty(t)||(this.__startKeyHistory[n][t]=[]);let s=i.startKey==="end"?"end":JSON.stringify(i.startKey);return this.__startKeyHistory[n][t].includes(s)||this.__startKeyHistory[n][t].push(s),this.__cached_requests?.[n]||(this.__cached_requests[n]={}),this.__cached_requests[n][r]=i,Object.assign({startKeyHistory:this.__startKeyHistory[n][t]},i)}async function tt(e,t){await this.__connection;let{record_id:r,service:n=this.service,progress:i}=t;if(!r)throw new l('"record_id" is required.',{code:"INVALID_PARAMETER"});if(ci&&e instanceof SubmitEvent&&(e=e.target),ia&&e instanceof HTMLFormElement&&(e=new FormData(e)),!et||!(e instanceof FormData))throw new l('"fileList" should be a FormData or HTMLFormElement.',{code:"INVALID_PARAMETER"});let o={reserved_key:Re(),service:n,request:"post"};t?.record_id&&(o.id=t.record_id);let a,u=(p,y,h)=>new Promise((_,w)=>{a=new XMLHttpRequest,a.open("POST",p),a.onload=()=>{let b=a.responseText;try{b=JSON.parse(b);}catch{}if(a.status>=200&&a.status<300)_(b);else if(a.status===429){let E=a.getResponseHeader("Retry-After"),R=ui(E);R!==null?setTimeout(()=>{u(p,y,h).then(_,w);},R):w("Too many requests");}else w(b);},a.onerror=()=>w("Network error"),a.onabort=()=>w("Aborted"),a.ontimeout=()=>w("Timeout"),a.upload&&typeof h=="function"&&(a.upload.onprogress=h),a.send(y);});function c(p){let y="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";if(p===0)return y[0];let h="";for(;p>0;)h=y[p%62]+h,p=Math.floor(p/62);return h}let g=[],f=[],d=[];for(let[p,y]of e.entries()){if(!(y instanceof File))continue;let h=await Mn.bind(this)(r,p,y),_=h.file,w=h.key,b=Object.assign({key:w+"/"+_.name,sizeKey:c(_.size),contentType:_.type||null},o),{fields:E=null,url:R,cdn:k}=await T.bind(this)("get-signed-url",b,{auth:!!this.__user});d.push(k);let U=new FormData;for(let D in E)U.append(D,E[D]);U.append("file",_);try{await u(R,U,typeof i=="function"?D=>i({status:"upload",progress:yr(D.loaded,D.total),currentFile:y,completed:g,failed:f,loaded:D.loaded,total:D.total,abort:()=>a.abort()}):null),g.push(y);}catch{f.push(y);}}return {completed:g,failed:f,bin_endpoints:d}}var At={};function S(e){let{preventMultipleCalls:t=false}=e||{};return function(r,n,i){let s=i.value;i.value=function(...o){let a=o[0],u=true,c=null,g="",f={},d=false;if(ci&&a instanceof SubmitEvent){a.preventDefault();let w=window.location.href;c=a.target;let b=new URL(c.action);g=b.href;let E=g?g.match(/(?<=\{).*?(?=\})/g):"";if(E)for(let R of E){if(!R)continue;let k=c.querySelector(`[name="${R}"]`);if(k)if(k.type==="file")for(let U=0;U<=k.files.length-1;U++)k.files[U]&&(f[R]||(f[R]=[]),f[R].push(new Promise((D,x)=>{let v=new FileReader;v.onload=function(){D(v.result);},v.readAsDataURL(k.files[U]),v.onerror=x;})));else g=g.replace(`{${R}}`,k.value);}c.getAttribute("action")===null?u=false:d=b.href===w;}let p=async w=>{if(g)for(let b in f)f[b].length&&(g=g.replace(`{${b}}`,(await Promise.all(f[b])).join(",")));if(c&&u){let b=O.call(this)?aa(w):w;window.sessionStorage.setItem(`${this.service}:${G.hash(g)}`,JSON.stringify(b)),d?window.location.replace(g):window.location.href=g;}return w},y,h=w=>{throw w instanceof l?w.name=n+"()":w=w instanceof Error?w:new l(w,{name:n+"()"}),w},_=async()=>{try{if(y=s.bind(this)(...o),y instanceof Promise){let w=await y;return p(w)}return p(y)}catch(w){throw h(w)}};if(t){let w=`${n}:${this?.__public_identifier||""}:${this?.service||""}:${this?.owner||""}`;return At?.[w]||(At[w]=_().finally(()=>{delete At[w];})),At[w]}return _()};}}async function gi(){await this.__connection;let e=`${this.service}:${G.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 ca=256,ua=256,da=256,pi=256,fa="\u{10FFFF}",ga=/[\u0000-\u001F\u007F]|\u{10FFFF}/u,pa={"/":"%2F","!":"%21","*":"%2A","#":"%23"},ha={"%2F":"/","%21":"!","%2A":"*","%23":"#"};function ma(e){return e.replace(/%/g,"%25").replace(/[\/!*#]/g,r=>pa[r]||r)}function le(e){return typeof e!="string"?e:e.replace(/%(2F|21|2A|23)/gi,r=>{let n=r.toUpperCase();return ha[n]||r}).replace(/%25/gi,"%")}function de(e,t,r={}){let{allowEmpty:n=false,maxLength:i,blockKeyDelimiters:s=false,disallowLeadingDollar:o=false,onlyAlphanumeric:a=false}=r;if(typeof e!="string")throw new 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(i&&e.length>i)throw new l(`"${t}" should be <= ${i} characters.`,{code:"INVALID_PARAMETER"});if(ga.test(e)||e.includes(fa))throw new l(`"${t}" cannot include control characters or unsupported sentinel characters.`,{code:"INVALID_PARAMETER"});if(s&&(e=ma(e),i&&e.length>i))throw new l(`"${t}" should be <= ${i} 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 Oe(e,t="table.name",r={}){return de(e,t,{allowEmpty:r.allowEmpty===true,maxLength:ca,blockKeyDelimiters:true})}function It(e,t="tag",r={}){return de(e,t,{allowEmpty:r.allowEmpty===true,maxLength:ua,blockKeyDelimiters:true})}function rt(e,t="index.name",r={}){return de(e,t,{allowEmpty:r.allowEmpty===true,maxLength:da,blockKeyDelimiters:true,disallowLeadingDollar:true})}function hi(e,t="index.value"){return de(e,t,{allowEmpty:true,maxLength:pi})}function br(e){return typeof e=="string"&&e.slice(-1)==="."}function _r(e,t){return de(e,t,{allowEmpty:true,maxLength:pi,blockKeyDelimiters:true})}function mi(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=de(e.record_id,"record_id",{allowEmpty:false,onlyAlphanumeric:true}):e?.unique_id&&(t.unique_id=e.unique_id),t}function wr(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 Rt=4503599627370496;function Tt(e){if(typeof e=="number"){if(e>Rt||e<-Rt)throw new l(`Number value should be within range -${Rt} ~ +${Rt}`,{code:"INVALID_PARAMETER"});return e}if(typeof e=="boolean")return e;if(typeof e=="string")return hi(e,"index.value");throw new l('"index.value" should be type: <number | boolean | string>.',{code:"INVALID_PARAMETER"})}function yi(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"?br(t.index.name)?_r(e,"index.range"):hi(e,"index.range"):e}var Pt={},ya=10080*60,ba=3600,bi=2;function _a(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 wa(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 Ea(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 _i(e){return typeof e=="string"?e:e&&typeof e.text=="function"?await e.text():await new Promise((t,r)=>{try{let n=new FileReader;n.onload=()=>t(n.result),n.onerror=()=>r(n.error||new Error("Failed to read blob")),n.readAsText(e);}catch(n){r(n);}})}async function 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,a=[],u=null;function c(d){let p=d=="**"?"private":parseInt(d);return p=p==0?"public":p==1?"authorized":p==99?"admin":p,p}let g={ip:d=>{let p=d.split("#"),y=p[0];p.length>1&&(s.unique_id=p.slice(1).join("#")),y.slice(-1)==="R"?(s.readonly=true,y=y.slice(0,-1)):s.readonly=false,/^\d{1,3}-\d{1,3}-\d{1,3}-\d{1,3}$/.test(y)&&(y=y.split("-").join("."),o=true),s.ip=y;},rec:d=>{if(!d)return;s.record_id=d;let p=d.substring(0,d.length-9),y=se(p);s.uploaded=y;},usr:d=>{s.user_id=d;},tbl:d=>{if(d&&!s.table.name){let p=d.split("/");s.table.name=le(p[0]),s.table.access_group=c(p[2]),p?.[3]&&(s.table.subscription.is_subscription_record=true);}},usr_tbl:d=>{let p=d.split("/");s.user_id||(s.user_id=p[0]),s.table.name||(s.table.name=le(p[1]),s.table.access_group=c(p[3]),p?.[4]&&(s.table.subscription.is_subscription_record=true));},idx:d=>{if(!d)return;let p=d.split("!"),y=le(p.splice(0,1)[0]),h=Aa("!"+p.join("!"));s.index={name:y,value:h};},ref:d=>{d&&(s.reference=d.split("/")[0]);},tags:d=>{s.tags=Array.isArray(d)?d.map(p=>le(p)):d;},upd:d=>{s.updated=d;},acpt_mrf:d=>{s.source.prevent_multiple_referencing=!d;},ref_limt:d=>{s.source.referencing_limit=d;},rfd:d=>{s.referenced_count=d;},bin:async d=>{let p={},y=s?.reference||null;if(Array.isArray(d)){let h=await Promise.all(d.map(async _=>{try{let w=_.split("/").slice(3).join("/"),b=w.split("/");if(b.length<12)return null;let E=b[b.length-1],R=b[10];if(R==="__data__"&&E==="__json__.json")return {isDataFile:!0,rawUrl:_};if(rr(R,E))return {isDataFile:!0,rawUrl:_};let k=_t(R),U=b[9],D=b[8],x=c(b[6]),v=_,C=x!=="public"&&wa.call(this,b)?{expires:ba,browserCache:ya}:null;if(x!=="public"&&!i)try{v=await Pe.bind(this)(_,{dataType:"endpoint",_ref:y});}catch(q){console.error("Error getting signed url for private file:",q),v=_;}let L={access_group:x,filename:E,url:v,path:w,size:k?k.plainSize:se(U),uploaded:se(D),getFile:(q,Q)=>{let Ae={dataType:q||"download",progress:Q,_ref:y},$=()=>Pe.bind(this)(v,Object.assign({},Ae,{_update:L}));return C?Pe.bind(this)(_,Object.assign({},Ae,C)).catch(()=>$()):$()}};return k&&(L.encrypted=!0,L.stored_size=se(U)),{pathKey:k?k.key:R,obj:L}}catch{return null}}));for(let _ of h)if(_&&!_.isDataFile){if(p[_.pathKey]){p[_.pathKey].push(_.obj);continue}p[_.pathKey]=[_.obj];}}s.bin=p;},prv_acs:d=>{for(let p in d)["notify_subscribers","upload_to_feed","feed_referencing_records","notify_referencing_records"].includes(p)?s.table.subscription[p]=d[p]:p==="referencing_index_restrictions"&&Array.isArray(d[p])?s.source[p]=d[p].map(h=>h&&typeof h=="object"&&typeof h.name=="string"?Object.assign({},h,{name:le(h.name)}):h):s.source[p]=d[p];},data:async d=>{let p={access_group:s.table.access_group,table_name:s.table.name,user_id:s.user_id,record_id:s.record_id,unique_id:s.unique_id,ctUrl:u},y=()=>{O.call(this)&&(s.encrypted={status:"failed",reason:"DATA_UNAVAILABLE"});},h=async w=>{if(n||!O.call(this)&&!mt(w))return w;let b=await mn.bind(this)(w,p);return b.flag&&(s.encrypted=b.flag),b.value},_=Ea(d);if(_!==d){s.data=await h(_);return}if(d&&typeof d=="object"&&!Array.isArray(d)&&typeof d.__data__=="string"&&Object.keys(d).length===1&&d.__data__.endsWith("/__data__/__json__.json")){let w=d.__data__,b=a.find(E=>E.endsWith(w))||null;if(!b&&!r&&y(),b){if(r){s.data=d;return}try{let E=await Pe.bind(this)(b,{dataType:"blob",_ref:s.reference||null}),R=await _i(E);s.data=await h(JSON.parse(R));}catch(E){console.error("Failed to fetch offloaded record data:",E),s.data=null,y();}return}}s.data=await h(d);}};if(e.record_id)return e;if(Array.isArray(e.bin))for(let d of e.bin)try{if(typeof d!="string")continue;let p=d.split("/").slice(3);p.length>=12&&p[10]==="__data__"&&p[p.length-1]==="__json__.json"&&a.push(d),p.length>=12&&rr(p[10],p[p.length-1])&&(u=d);}catch{}let f=[];for(let d in g)if(e.hasOwnProperty(d)){let p=g[d](e[d]);p instanceof Promise&&f.push(p);}return o&&(s.user_id="anonymous:"+s.user_id),await Promise.all(f),s}function Aa(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 l("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 l('"endpoints" should be type: array | string.',{code:"INVALID_PARAMETER"});let r=await T.bind(this)("del-files",{endpoints:t,storage:"records"},{auth:true,method:"post"}),n=[];for(let i in r)n.push(Se.bind(this)(r[i]));return Promise.all(n)}async function Pe(e,t){if(typeof e!="string")throw new l('"url" should be type: string.',{code:"INVALID_PARAMETER"});let r=e,n=e.split("?"),i=n.shift()||"",s=n.length?"?"+n.join("?"):"",o=m.Url(i);e=o+s;let a=false,u=o.split("/"),g=u[2].split("."),f=null;g.length===3&&g[1]==="skapi"&&(f=g[0],a=true);let d=u.slice(3),p=false;if(!a&&(d[0]==="auth"||d[0]==="publ"))try{m.UserId(d[2]),m.UserId(d[3]),p=d[0]=="auth",a=!0;}catch{throw new l("Invalid file url.",{code:"INVALID_PARAMETER"})}let y=f?null:d[1];if(t=m.Params(t,{expires:["number",()=>0],browserCache:["number",()=>0],refresh:["boolean",()=>false],dataType:["base64","blob","endpoint","text","info",()=>"download"],progress:["function","undefined",null],_ref:[null,"string"],_update:E=>E}),t?.dataType==="info")return {url:e,filename:d[d.length-1],fileKey:d[d.length-2],access_group:d[6]==="**"?"private":d[6]==="01"?"authorized":d[6]==="00"?"public":parseInt(d[6]),uploader:d[3],record_id:d[4]==="records"?d[5]:"N/A",filesize:se(d[9]),uploaded:se(d[8])};let h=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 E={request:f?"get-host":"get",id:f||d[5],key:r.split("?")[0],expires:_};y&&(E.service=y);let R=t.browserCache,k={auth:true};if(R){if(R<0)throw new l('"config.browserCache" should be > 0. (seconds)',{code:"INVALID_PARAMETER"});k.method="get",k.stableGateway=true,E.browser_cache=R;let U=this.session?.idToken?.payload?.sub||this.user?.user_id;U&&(E.uid=U),E.nocache=_a(_,t.refresh);}e=(await T.bind(this)("get-signed-url",E,k)).url;}else if(p){let E=Math.floor(Date.now()/1e3);if(!this.bearerToken&&(!this.session?.idToken?.payload?.exp||this.session.idToken.payload.exp<E)){this.log("getFile:requesting new token",null);try{await J.bind(this)().getSession({refreshToken:!0}),this.log("getFile:received new tokens",{exp:this.session?.idToken?.payload?.exp,currTime:E,expiresIn:this.session?.idToken?.payload?.exp-E,token:this.session?.accessToken?.jwtToken,refreshToken:this.session?.refreshToken?.token});}catch(D){throw this.log("getFile:new token error",D),new l("User login is required.",{code:"INVALID_REQUEST"})}}let R=this.bearerToken||this.session?.idToken?.jwtToken;if(!R||!this.user?.user_id)throw new l("User login is required.",{code:"INVALID_REQUEST"});e+=`${e.includes("?")?"&":"?"}t=${encodeURIComponent(R)}`;let k=d[6]==="**"?"**":parseInt(d[6]),U=this.user?.access_group??-1;if(this.user.user_id!==d[3]&&(k==="**"||U<k)){let D=d[5];if(this.__private_access_key[D]&&typeof this.__private_access_key[D]=="string")e+=`&p=${encodeURIComponent(this.__private_access_key[D])}`;else if(this.owner!==this.host)try{let x=await this.requestPrivateRecordAccessKey({record_id:D,reference_id:t?._ref});e+=`&p=${encodeURIComponent(x)}`;}catch{}}}if((O.call(this)?fr(e):null)&&t?.dataType!=="endpoint"&&t?.dataType!=="info"){let E=await T.bind(this)(e,null,{method:"get",contentType:null,responseType:"blob",fetchOptions:{progress:t?.progress}},{ignoreService:true}),R=await Fn.bind(this)(e,E);if(t?.dataType==="blob")return R;if(t?.dataType==="text")return await _i(R);if(t?.dataType==="base64")return await new Promise((D,x)=>{let v=new FileReader;v.onloadend=()=>D(v.result),v.onerror=()=>x(v.error),v.readAsDataURL(R);});let k=URL.createObjectURL(R),U=document.createElement("a");return U.href=k,document.body.appendChild(U),U.setAttribute("download",h),U.click(),document.body.removeChild(U),setTimeout(()=>URL.revokeObjectURL(k),6e4),null}if(t?.dataType==="endpoint")return t._update&&(t._update.url=e),e;if(t?.dataType==="download"){let E=document.createElement("a");return E.href=e,document.body.appendChild(E),E.setAttribute("download",h),E.target="_blank",E.click(),document.body.removeChild(E),null}return new Promise(async(E,R)=>{try{let k=await T.bind(this)(e,null,{method:"get",contentType:null,responseType:t?.dataType==="text"?"text":"blob",fetchOptions:{progress:t?.progress}},{ignoreService:!0});if(t?.dataType==="base64"){let U=new FileReader;U.onloadend=()=>E(U.result),U.readAsDataURL(k);}else E(k);}catch(k){if(t?.browserCache&&!t?.refresh)try{E(await Pe.bind(this)(r,Object.assign({},t,{refresh:!0})));return}catch(U){R(U);return}R(k);}})}function St(e,t){return `${e||this.service}/${t||this.owner}`}function Er(e,t){let r=this.__my_unique_ids[e];return r?r[t]:void 0}function Ei(e,t,r){this.__my_unique_ids[e]||(this.__my_unique_ids[e]={}),this.__my_unique_ids[e][t]=r;}function Ra(e,t){this.__my_unique_ids[e]&&delete this.__my_unique_ids[e][t];}function Ai(e,t){return !t||t.table===void 0?e:Object.assign({},e,{table:t.table})}async function nt(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 Ri(e,t=false){e=j(e,{ignoreEmpty:true}).data||{};let r=St.bind(this)(e?.service,e?.owner),n="",i=mi(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=Er.bind(this)(r,n);s&&(t?Ra.bind(this)(r,n):e.record_id=s);}}else {let s=await W.bind(this)(),o=e?.reference,a=false;typeof o=="object"&&Object.keys(o).length&&(o?.record_id||o?.unique_id?(n=o.record_id||o.unique_id,n&&typeof this.__private_access_key?.[n]=="string"&&(e.private_key=this.__private_access_key?.[n]||void 0),e.reference=n):o?.user_id&&(a=o.user_id===this.user?.user_id,e.reference=o.user_id)),typeof e?.table=="string"&&(e.table={name:e.table,access_group:0}),e.index&&e.index.hasOwnProperty("range")&&e.index.hasOwnProperty("condition")&&delete e.index.range;let u=c=>({table:{name:g=>Oe(g,"table.name"),access_group:wr.bind(this),subscription:g=>m.UserId(g,'User ID in "subscription"')},reference:"string",index:{name:["$updated","$uploaded","$referenced_count","$user_id",g=>rt(g,"index.name")],value:g=>{let f={$updated:"number",$uploaded:"number",$referenced_count:"number",$user_id:m.UserId};if(f.hasOwnProperty(c.index.name)){let d=f[c.index.name];if(typeof d=="function")return d(g);if(d!==typeof g)throw new l(`"index.value" should be type: ${d}.`,{code:"INVALID_PARAMETER"});return g}return typeof g=="string"&&!g?"":typeof g=="string"&&br(c.index.name)?_r(g,"index.value"):Tt(g)},condition:["gt","gte","lt","lte",">",">=","<","<=","=","eq"],range:g=>yi(g,c)},tag:g=>{if(g==null)return g;if(typeof g=="string")return It(g,"tag");throw new l('"tag" should be type: string.',{code:"INVALID_PARAMETER"})},private_key:"string"});e=m.Params(e||{},u(e),a||s?[]:["table"],{ignoreEmpty:true});}return {query:e,is_reference_fetch:n}}async function Ii(e,t){await this.__connection,await nt.call(this,"getRecords");let r=await Ri.bind(this)(e),n=r.is_reference_fetch,i=await T.bind(this)("get-records",r.query,{fetchOptions:t,auth:!!this.__user,method:this.__user?"post":"get"});n&&i?.reference_private_key&&typeof i.reference_private_key=="string"&&(this.__private_access_key[n]=i.reference_private_key);let s=[];for(let o in i.list)s.push(Se.bind(this)(i.list[o]));return i.list=await Promise.all(s),i}function Ti(e){let t="",r=[],n=St.bind(this)(e?.service,e?.owner),i=m.Params(e||{},{record_id:o=>{let a=typeof o=="string"?Er.bind(this)(n,o):void 0;return a||de(o,"record_id",{allowEmpty:false})},unique_id:["string",null],readonly:"boolean",table:{name:o=>Oe(o,"table.name"),subscription:[null,{is_subscription_record:"boolean",upload_to_feed:"boolean",notify_subscribers:"boolean",feed_referencing_records:"boolean",notify_referencing_records:"boolean"}],access_group:wr.bind(this)},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=>rt(c,'"name" in "index_restrictions"'),value:c=>Tt(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=>m.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=Er.bind(this)(n,o);return a||o}if(typeof o!="object")throw new l('"reference" should be type: <string | object>.',{code:"INVALID_PARAMETER"});return m.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),de(a,"reference.record_id",{allowEmpty:false,onlyAlphanumeric:true}))})}},index:[null,{name:o=>rt(o,"index.name"),value:o=>Tt(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=>It(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 g=u.url.split("/").slice(0,3).join("/")+"/"+u.path;a.push(g);}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);}}),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 l("Public users cannot update existing records.",{code:"INVALID_REQUEST"});if(i.table.access_group!=="public"&&i.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(i.remove_bin)throw new l("Public users cannot remove files from records.",{code:"INVALID_REQUEST"});if(i.unique_id)throw new l("Public users cannot set unique_id for records.",{code:"INVALID_REQUEST"})}return {config:i,progress:s,is_reference_post:t,files:r}}async function Pi(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,i=null,s={},a={_is_bulk_:await Promise.all(e.map(async(p,y)=>{if(!p||typeof p!="object"||Array.isArray(p))throw new l(`"params[${y}]" should be type: <object>.`,{code:"INVALID_PARAMETER"});let h=Ti.bind(this)(p),_=h.config;if(O.call(this)){let w=Object.prototype.hasOwnProperty.call(_,"data"),b=await nr.bind(this)(_.data,Ai(p,_),w);b.encrypted&&(_.data=b.send,s[y]=b.plain);}if(h.is_reference_post&&t.push(h.is_reference_post),typeof _.progress=="function"&&i===null&&(i=_.progress),_.service!==void 0){if(r===void 0)r=_.service;else if(r!==_.service)throw new l('All bulk params should share the same "service" value.',{code:"INVALID_PARAMETER"})}if(_.owner!==void 0){if(n===void 0)n=_.owner;else if(n!==_.owner)throw new l('All bulk params should share the same "owner" value.',{code:"INVALID_PARAMETER"})}return delete _.progress,delete _.service,delete _.owner,_})),service:"",owner:""};r!==void 0&&(a.service=r),n!==void 0&&(a.owner=n);let u={auth:!!this.__user,method:"post"},c={};Object.keys(c).length&&Object.assign(u,{fetchOptions:c});let g=await T.bind(this)("post-record",a,u),f=await Promise.all(g.map((p,y)=>Se.bind(this)(p,"called from postRecord",false,s.hasOwnProperty(y))));for(let p=0;p<f.length;p++)s.hasOwnProperty(p)&&f[p]&&!f[p].error&&(f[p].data=s[p],f[p].encrypted={status:"encrypted"});let d=St.bind(this)(r,n);for(let p=0;p<g.length;p++){let y=g[p],h=f[p];if(y&&typeof y=="object"&&y.error&&h&&!h.record_id&&(h.error=y.error),typeof y?.reference_private_key=="string")for(let _ of t)this.__private_access_key[_]=y.reference_private_key;h?.unique_id&&Ei.bind(this)(d,h.unique_id,h.record_id);}return f}async function Ar(e,t,r){if(await this.__connection,!t)throw new l('"config" argument is required.',{code:"INVALID_PARAMETER"});let n=Ti.bind(this)(t),i=n.config,s=n.progress,o=n.is_reference_post,a={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 g=t?.data!==void 0?t.data:c.data,f=g!==void 0,d=await nr.bind(this)(g,Ai(t,i),f),p=null;p=Object.assign({},i),delete p.data,d.omit||(p.data=d.send);let y={};if(typeof s=="function"&&(y.progress=s),Object.keys(y).length&&Object.assign(a,{fetchOptions:y}),d.files==="decrypt"&&t?.record_id){let b=await gr.bind(this)(t.record_id,"decrypt",s);if(b.length){let E=p.remove_bin;p.remove_bin=Array.isArray(E)?E.concat(b):b;}}if(d.spill&&t?.record_id){let b=new FormData;if(b.append(Ye,new File([d.spill],"payload.bin",{type:"application/octet-stream"})),await tt.bind(this)(b,{record_id:t.record_id}),d.retireCt){let E=p.remove_bin,R=[d.retireCt];p.remove_bin=Array.isArray(E)?E.concat(R):R;}}let h=await T.bind(this)("post-record",p,a);if(d.encrypted&&h?.rec&&pn.bind(this)(h.rec,d.dek),d.files==="encrypt"&&h?.rec)try{let b=await gr.bind(this)(h.rec,"encrypt",s);b.length&&await Ar.bind(this)(void 0,{record_id:h.rec,remove_bin:b});}catch(b){console.error("Failed to encrypt existing attachments after making the record private:",b);}if(Y()&&u.length){let b=new FormData;for(let k of u)b.append(k.name,k.file,k.file.name);let E={record_id:h.rec,progress:s};i.hasOwnProperty("service")&&(E.service=i.service);let{bin_endpoints:R}=await tt.bind(this)(b,E);h.bin?h.bin.push(...R):h.bin=R;}o&&typeof h?.reference_private_key=="string"&&(this.__private_access_key[o]=h.reference_private_key);let _=!!h&&h.data&&typeof h.data=="object"&&!Array.isArray(h.data)&&typeof h.data.__data__=="string"&&h.data.__data__.endsWith("/__data__/__json__.json"),w=await Se.bind(this)(h,"called from postRecord",true,d.encrypted);if(_&&(w.data=c.data),d.encrypted&&(w.data=d.plain,w.encrypted={status:"encrypted",recipients:Object.keys(d.send.k||{})}),w.unique_id){let b=St.bind(this)(i?.service,i?.owner);Ei.bind(this)(b,w.unique_id,w.record_id),Y()&&(this.__uniqueIdsPersistTimer!==null&&clearTimeout(this.__uniqueIdsPersistTimer),this.__uniqueIdsPersistTimer=setTimeout(()=>{this.__uniqueIdsPersistTimer=null;try{window.sessionStorage.setItem(`${b}:uniqueids`,JSON.stringify(this.__my_unique_ids[b]||{}));}catch{}},500));}return w}async function Si(e,t){await nt.call(this,"getTables");let r=await T.bind(this)("get-table",m.Params(e||{},{table:i=>Oe(i,"table",{allowEmpty:true}),condition:["gt","gte","lt","lte",">",">=","<","<=","=","eq","!=","ne"]}),Object.assign({auth:!!this.__user},{fetchOptions:t})),n={cnt_rec:"number_of_records",tbl:"table",srvc:"service",grp_:"number_of_records_in_access_group_"};if(Array.isArray(r?.list))for(let i of r.list){for(let s in n){if(s==="grp_"){for(let o in i)if(o.startsWith("grp_")){let a=o.substring(4);a==="pv"?a="private":a==="00"?a="public":a==="01"?a="authorized":a==="99"&&(a="admin"),i[`number_of_records_in_access_group_${a}`]=i[o],delete i[o];}}i.hasOwnProperty(s)&&(i[n[s]]=i[s],delete i[s]);}typeof i.table=="string"&&(i.table=le(i.table));}return r}async function ki(e,t){if(await nt.call(this,"getIndexes"),!e?.table)throw new l('"table" is required.',{code:"INVALID_PARAMETER"});let r=m.Params(e||{},{table:s=>Oe(s,"table",{allowEmpty:true}),index:s=>rt(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 de(s,"order.value",{allowEmpty:true,maxLength:256,blockKeyDelimiters:true});if(typeof s!="string"&&typeof s!="number"&&typeof s!="boolean")throw new l('"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 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 T.bind(this)("get-index",r,Object.assign({auth:!!this.__user},{fetchOptions:t})),i={cnt_bool:"boolean_count",cnt_numb:"number_count",totl_numb:"total_number",totl_bool:"total_bool",avrg_numb:"average_number",avrg_bool:"average_bool",cnt_str:"string_count"};return Array.isArray(n?.list)&&(n.list=n.list.map(s=>{let o=s.idx.split("/"),a={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)&&(a[i[u]]=s[u]);return a})),n}async function vi(e,t){await nt.call(this,"getTags");let r=await T.bind(this)("get-tag",m.Params(e||{},{table:n=>Oe(n,"table",{allowEmpty:true}),tag:n=>It(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 Ni(e,t){await nt.call(this,"getUniqueId");let r=await T.bind(this)("get-uniqueid",m.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 Ui(e,t){await this.__connection;let r=await Ri.bind(this)(e,true),n=r.is_reference_fetch,i=await T.bind(this)("del-records",r.query,{auth:true,fetchOptions:t});return n&&typeof i?.reference_private_key=="string"&&(this.__private_access_key[n]=i.reference_private_key),Array.isArray(i?.list)&&(i.list=await Promise.all(i.list.map(async s=>{if(!s||typeof s!="object")return s;try{return await Se.bind(this)(s,"called from deleteRecords",!0,!1,!0)}catch{return s}}))),i?.message||i}async function Di(e){if(O.call(this)){let t=typeof e.user_id=="string"?[e.user_id]:e.user_id;Array.isArray(t)&&t.length&&await dr.bind(this)(e.record_id,t);}return Oi.bind(this)({record_id:e.record_id,user_id:e.user_id,execute:"add"})}async function xi(e){let t=await Oi.bind(this)({record_id:e.record_id,user_id:e.user_id||null,execute:"remove"});if(O.call(this)){let r=typeof e.user_id=="string"?[e.user_id]:e.user_id;await vn.bind(this)(e.record_id,Array.isArray(r)&&r.length?r:null);}return t}async function Ci(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")m.UserId(r.user_id),r.user_id=[r.user_id];else if(Array.isArray(r.user_id))for(let s of r.user_id)m.UserId(s);else throw new l("user_id should be type: <string | string[]>",{code:"INVALID_PARAMETER"});let n=s=>(s.rec_usr?(s.record_id=s.rec_usr.split("/")[0],s.user_id=s.rec_usr.split("/")[1]):s.usr_rec&&(s.user_id=s.usr_rec.split("/")[0],s.record_id=s.usr_rec.split("/")[1]),s),i=await T.bind(this)("grant-private-access",r,{auth:true,fetchOptions:t});return i.list=i.list.map(n),i}function Li(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(Pt[t])return Pt[t];let n=T.bind(this)("request-private-access-key",{record_id:t,reference_id:r},{auth:true}).then(i=>{let s=typeof i=="string"?i:i?.private_key;if(typeof s!="string")throw new l("Invalid private access key response.",{code:"ERROR"});return this.__private_access_key[t]=s,s}).finally(()=>{delete Pt[t];});return Pt[t]=n,n}function Oi(e){e.execute;let r=m.Params(e,{record_id:"string",user_id:n=>{if(!n)throw new l("User ID is required.",{code:"INVALID_PARAMETER"});let i=n;if(typeof i=="string"&&(i=[i]),i.length>100)throw new l("Cannot process more than 100 users at once.",{code:"INVALID_REQUEST"});for(let s of i)m.UserId(s,'User ID in "user_id"');return i},execute:["add","remove"]},["execute","record_id","user_id"]);return r.user_id||(r.user_id=null),T.bind(this)("grant-private-access",r,{auth:true})}var N={},H={},ce={},ge={},fe={},kt={},vt={};function Mi(e,t,r){e[t]||(e[t]=[]),e[t].push(r);}async function Nt(e,t,r){let n=[];if(e[t]){for(let i of e[t])if(i){let s=r(i);s instanceof Promise&&(s=await s),n.push(s);}delete e[t];}return n}async function Ir(e,t){if(!this?.session?.accessToken?.jwtToken)throw new l("Access token is required.",{code:"INVALID_PARAMETER"});let r=await this.__socket;async function n(i,s,o){this.log("answerSdpOffer from",s),await N[s].setRemoteDescription(new RTCSessionDescription(i));let a=await N[s].createAnswer();await N[s].setLocalDescription(a),o.send(JSON.stringify({action:"rtc",uid:s,content:{sdpanswer:a},token:this.session.accessToken.jwtToken}));}N?.[t]?e?(await Nt(vt,t,i=>n.bind(this)(i,t,r)),await n.bind(this)(e,t,r)):await Nt(vt,t,i=>n.bind(this)(i,t,r)):e&&Mi(vt,t,e);}async function Tr(e,t){if(this.log("receiveIceCandidate",e),N?.[t]&&N[t]?.remoteDescription&&N[t]?.remoteDescription?.type){if(!e)return Nt(kt,t,r=>N[t].addIceCandidate(r));await Nt(kt,t,r=>N[t].addIceCandidate(r)),await N[t].addIceCandidate(e);}else Mi(kt,t,e);}async function ue(e){if(typeof window>"u"||window._runningInNodeJS)throw new l("WebRTC is not supported in Node.js environment.",{code:"NOT_SUPPORTED"});m.Params(e,{cid:s=>{if(typeof s!="string")throw new l('"cid" should be type: <string>.',{code:"INVALID_PARAMETER"});if(s&&s.slice(0,4)!=="cid:")throw new l('"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 l('"cid" is required.',{code:"INVALID_PARAMETER"});let i=s=>{if(!s)throw new l('"cid" is required.',{code:"INVALID_PARAMETER"});if(delete vt[s],delete kt[s],H[s]&&Object.values(H[s]).forEach(o=>{o.readyState!=="closed"&&o.close();}),delete H[s],N?.[s]){N[s].connectionState!=="closed"&&(N[s].close(),t.send(JSON.stringify({action:"rtc",uid:s,content:{hungup:this.user.user_id},token:this.session.accessToken.jwtToken})));let o={type:"connectionstatechange",target:N[s],timestamp:new Date().toISOString(),state:N[s].connectionState,iceState:N[s].iceConnectionState,signalingState:N[s].signalingState};fe[s]&&fe[s](o),this.log("closeRTC",o);}delete fe[s],delete ge[s],delete ce[s],delete N[s];};if(n)for(let s in N)i(s);else i(r);this.log("Cleaning up media stream..."),this.__mediaStream&&(this.__mediaStream.getTracks().forEach(s=>{s.stop();}),this.__mediaStream=null);}async function Fi(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 qi(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"});e=m.Params(e,{cid:o=>{if(typeof o!="string")throw new l('"cid" should be type: <string>.',{code:"INVALID_PARAMETER"});if(o&&o.slice(0,4)!=="cid:")throw new l('"cid" should be a valid connection id.',{code:"INVALID_PARAMETER"});return o},ice:["string",()=>"stun:stun.skapi.com:3468"],media:o=>o,channels:["text-chat","file-transfer","video-chat","voice-chat","gaming",{ordered:"boolean",maxPacketLifeTime:"number",maxRetransmits:"number",protocol:"string"},()=>[{ordered:true,maxPacketLifeTime:10,protocol:"default"}]]},["cid"]);let{cid:r,ice:n}=e;if(!(e?.media instanceof MediaStream)&&(e?.media?.video||e?.media?.audio)&&window.location.hostname!=="localhost"&&window.location.protocol!=="https:")throw new l("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 l("No realtime connection. Execute connectRealtime() before this method.",{code:"INVALID_REQUEST"});if(i.readyState!==1)throw new l("Realtime connection is not ready.",{code:"INVALID_REQUEST"});let s={iceServers:[{urls:n}]};N?.[r]||(N[r]=new RTCPeerConnection(s)),e?.media&&(this.__mediaStream=await Fi(e.media),this.__mediaStream.getTracks().forEach(o=>{N[r].addTrack(o,this.__mediaStream);})),fe[r]=t,H[r]||(H[r]={});for(let o=0;o<e.channels.length;o++){let a=e.channels[o];if(typeof a=="string")switch(a){case "text-chat":a={ordered:true,maxRetransmits:10,protocol:"text-chat"};break;case "file-transfer":a={ordered:false,maxPacketLifeTime:3e3,protocol:"file-transfer"};break;case "video-chat":a={ordered:true,maxRetransmits:10,protocol:"video-chat"};break;case "voice-chat":a={ordered:true,maxRetransmits:10,protocol:"voice-chat"};break;case "gaming":a={ordered:false,maxPacketLifeTime:100,protocol:"gaming"};break;default:a={ordered:true,maxRetransmits:10,protocol:"default"};break}let u=a.protocol||"default";if(Object.keys(H[r]).includes(u))throw new l(`Data channel with the protocol "${u}" already exists.`,{code:"INVALID_REQUEST"});let c=N[r].createDataChannel(u,a);H[r][u]=c;}for(let o in H[r]){let a=H[r][o];ji.bind(this)(r,a);}return $i.bind(this)(r,["onnegotiationneeded"]),await Rr.bind(this)(r),{hangup:()=>ce[r]&&ce[r](false),connection:new Promise(o=>{ce[r]=(a=>{if(this.log("receiver picked up the call",r),!a)return ue.bind(this)({cid:r}),null;N[r].onnegotiationneeded=()=>{this.log("onnegotiationneeded",`sending offer to "${r}".`),Rr.bind(this)(r),fe[r]&&fe[r]({type:"negotiationneeded",target:N[r],timestamp:new Date().toISOString(),signalingState:N[r].signalingState,connectionState:N[r].iceConnectionState,gatheringState:N[r].iceGatheringState});},o({target:N[r],channels:H[r],hangup:()=>ue.bind(this)({cid:r}),media:this.__mediaStream});}).bind(this);})}}function Vi(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 l("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 l("Media stream is only supported on either localhost or https.",{code:"INVALID_REQUEST"});let{ice:s="stun:stun.skapi.com:3468"}=t;return N?.[n]||(N[n]=new RTCPeerConnection({iceServers:[{urls:s}]})),t?.media&&(this.__mediaStream=await Fi(t.media),this.__mediaStream.getTracks().forEach(o=>{N[n].addTrack(o,this.__mediaStream);})),delete ge[n],fe[n]=r,H[n]||(H[n]={}),N[n].ondatachannel=o=>{this.log("ondatachannel",`received data channel "${o.channel.label}".`);let a=o.channel;H[n][a.label]=a,ji.bind(this)(n,a);},$i.bind(this)(n,["onnegotiationneeded"]),await Ir.bind(this)(null,n),await Tr.bind(this)(null,n),i.send(JSON.stringify({action:"rtc",uid:n,content:{pickup:this.user.user_id},token:this.session.accessToken.jwtToken})),{target:N[n],channels:H[n],hangup:()=>ue.bind(this)({cid:n}),media:this.__mediaStream}}}async function Rr(e){if(!this?.session?.accessToken?.jwtToken)throw new l("Access token is required.",{code:"INVALID_PARAMETER"});this.log("sendOffer",e);let t=await this.__socket,r=await N[e].createOffer();await N[e].setLocalDescription(r);let n=N[e].localDescription;this.log("rtcSdpOffer to",n),t.send(JSON.stringify({action:"rtc",uid:e,content:{sdpoffer:n},token:this.session.accessToken.jwtToken}));}async function Ia(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=fe[t]||(()=>{}),i=e.candidate;this.log("ice gathering state set to",N[t].iceGatheringState),n({type:"icecandidate",target:N[t],timestamp:new Date().toISOString(),candidate:e.candidate.candidate,sdpMid:e.candidate.sdpMid,sdpMLineIndex:e.candidate.sdpMLineIndex,usernameFragment:e.candidate.usernameFragment,protocol:e.candidate.protocol,gatheringState:N[t].iceGatheringState,connectionState:N[t].iceConnectionState}),r.send(JSON.stringify({action:"rtc",uid:t,content:{candidate:i},token:this.session.accessToken.jwtToken}));}function $i(e,t){let r=new Set(t),n=fe[e]||(o=>{}),i=N[e],s={ontrack:o=>{n({type:"track",target:i,timeStamp:o.timeStamp,streams:o.streams,track:o.track});},onicecandidate:o=>{Ia.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:()=>{Rr.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,a]of Object.entries(s))r.has(o)||(i[o]=a);}function ji(e,t,r){let n=new Set(r),i=fe[e]||(o=>{}),s={onmessage:o=>{let a={type:o.type,target:t,timeStamp:o.timeStamp,data:o.data,lastEventId:o.lastEventId,origin:o.origin,readyState:t.readyState,bufferedAmount:t.bufferedAmount};this.log(`${t.label}: message`,o.data),i(a);},onerror:o=>{let a={type:o.type,target:t,timeStamp:o.timeStamp,error:o.error.message,errorCode:o.error.errorDetail,readyState:t.readyState,label:t.label};this.log(`${t.label}: error`,o.error.message),i(a);},onclose:o=>{let a={type:o.type,target:t,timeStamp:o.timeStamp,readyState:t.readyState,label:t.label,id:t.id};this.log(`${t.label}: closed`,null),i(a),H[e]&&(delete H[e][t.label],Object.keys(H[e]).length===0&&ue.bind(this)({cid:e}));},onbufferedamountlow:o=>{let a={target:t,bufferedAmount:t.bufferedAmount,bufferedAmountLowThreshold:t.bufferedAmountLowThreshold,type:o.type,timeStamp:o.timeStamp};this.log(`${t.label}: bufferedamountlow`,t.bufferedAmount),i(a);},onopen:o=>{this.log("dataChannel",`data channel: "${t.label}" is open and ready to send messages.`);let a={type:o.type,target:t,timeStamp:o.timeStamp,readyState:t.readyState,label:t.label,id:t.id,ordered:t.ordered,maxRetransmits:t.maxRetransmits,protocol:t.protocol};i(a);}};for(let[o,a]of Object.entries(s))n.has(o)||(t[o]=a);}var be;function Bi(){return be}var Ee=null,it=true,Me=0;async function Ta(){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 Pr=null;async function Ut(){if(typeof window>"u"||window._runningInNodeJS)throw new l("WebSocket is not supported in Node.js environment.",{code:"NOT_SUPPORTED"});it=true;let e=this.__socket?await this.__socket:this.__socket;ue.bind(this)({close_all:true}),be&&qe.bind(this)({group:null}),Me=0,Ee&&(Ee.terminate(),Ee=null);try{e&&e.close();}catch{}return window.removeEventListener("visibilitychange",Pr),this.__socket=null,null}async function Fe(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 i=await this.__socket;if(i.readyState!==WebSocket.CLOSED&&i.readyState!==WebSocket.CLOSING)return this.__socket}}else if(it&&(Pr=()=>{!document.hidden&&!it&&Fe.bind(this)(e,0,"reconnect");},this.__socket instanceof Promise))return this.__socket;Ee&&(Ee.terminate(),Ee=null);let n={value:null};return this.__socket=new Promise(async(i,s)=>{let o=a=>{this.__socket===n.value&&(this.__socket=null),s(a);};try{await Ce.bind(this)();}catch(a){o(a);return}setTimeout(async()=>{try{let a=await Ta.bind(this)();a.onopen=()=>{it=!1,Me=0,r!=="reconnect"&&window.addEventListener("visibilitychange",Pr),this.log("realtime onopen","Connected to WebSocket server."),e({type:"success",message:"Connected to WebSocket server."}),be&&a.send(JSON.stringify({action:"joinRoom",rid:be,token:this.session.accessToken.jwtToken}));let u=`
|
|
207
207
|
let interval = 15000; // Set interval time 15 seconds
|
|
208
208
|
|
|
209
209
|
function runInterval() {
|
|
@@ -212,9 +212,9 @@ var Ks=Object.defineProperty;var Hs=Object.getOwnPropertyDescriptor;var ke=(e=>t
|
|
|
212
212
|
}
|
|
213
213
|
|
|
214
214
|
runInterval(); // Start interval
|
|
215
|
-
`,c=new Blob([u],{type:"application/javascript"});Ee=new Worker(URL.createObjectURL(c)),Ee.onmessage=g=>{a.readyState===1&&a.send(JSON.stringify({action:"keepAlive"}));},i(a);},a.onmessage=async u=>{let c="";try{c=JSON.parse(decodeURI(u.data)),this.log("socket onmessage",c);}catch{return}let g;switch(!0){case !!c?.["#message"]:g="message";break;case !!c?.["#private"]:g="private";break;case !!c?.["#notice"]:g="notice";break;case !!c?.["#rtc"]:g="rtc";break;case !!c?.["#error"]:g="error";break}if(!g)return;let f={type:g,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(g==="notice")e(f);else if(g==="rtc"){if(f.sender!==this.user.user_id){let d=f.message;if(d.hungup){ce[f.sender_cid]&&(ce[f.sender_cid](!1),delete ce[f.sender_cid]),ge[f.sender_cid]&&delete ge[f.sender_cid],N?.[f.sender_cid]&&ue.bind(this)({cid:f.sender_cid}),f.type="rtc:closed",e(f);return}if(d.candidate&&Tr.bind(this)(d.candidate,f.sender_cid),d.sdpoffer&&(Ir.bind(this)(d.sdpoffer,f.sender_cid),ge[f.sender_cid]||(ge[f.sender_cid]=f.sender_cid,delete f.message,f.connectRTC=qi.bind(this)(f),f.type="rtc:incoming",f.hangup=(()=>{N[f.sender_cid]?ue.bind(this)({cid:f.sender_cid}):ge[f.sender_cid]&&(delete ge[f.sender_cid],a.send(JSON.stringify({action:"rtc",uid:f.sender_cid,content:{hungup:this.user.user_id},token:this.session.accessToken.jwtToken})));}).bind(this),e(f))),d.pickup&&ce[f.sender_cid]&&(ce[f.sender_cid](!0),delete ce[f.sender_cid]),d.sdpanswer&&N[f.sender_cid])if(N[f.sender_cid].signalingState==="have-local-offer")await N[f.sender_cid].setRemoteDescription(new RTCSessionDescription(d.sdpanswer));else throw new l("Invalid signaling state.",{code:"INVALID_REQUEST"})}}else e(f);},a.onclose=()=>{it?(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."}),Me++,Me<3?(this.log("realtime onclose","Reconnecting to WebSocket server..."+Me),e({type:"reconnect",message:"Reconnecting to WebSocket server..."+Me}),Fe.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 Bi(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 Ce.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 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: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}),be!==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: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 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 Ce.bind(this)(),e=j(e,{nullIfEmpty:true}).data;let{group:r=null}=e;if(!r&&!be)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})),be=r,{type:"success",message:r?`Joined realtime message group: "${r}".`:"Left realtime message group."}}async function Ki(e,t){e=y.Params(e,{user_id:n=>y.UserId(n,'User ID in "user_id"'),group:["string",()=>{if(!be)throw new l('No group has been joined. Otherwise "group" is required.',{code:"INVALID_REQUEST"});return be}]});let r=await P.bind(this)("get-ws-group",e,{fetchOptions:t,auth:true,method:"post"});return r.list=r.list.map(n=>({user_id:n.uid.split("#")[1],cid:"cid:"+n.cid})),r}async function Hi(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 P.bind(this)("get-ws-group",e,{fetchOptions:t,auth:true,method:"post"});return r.list=r.list.map(n=>({group:n.rid.split("#")[1],number_of_users:n.cnt})),r}var Qi=typeof FormData<"u",Gi=typeof HTMLFormElement<"u",zi=typeof SubmitEvent<"u",pe={},st={},te={};function ot(e){return Object.freeze({id:e,status:"stopped"})}function Ji(e){return !!e&&typeof e=="object"&&e.status==="stopped"}var Yi=3;function Xi(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 ba=2e3,Zi=5e3,_a=2e3,wa=5,Ea=1500,Dt=null;function es(e,t,r){let n=new Map,i=false,s=false,o=0,a={socket:0,poll:0},u=(d,p,m)=>{if(e.seq=d,!(!t||typeof p!="string"||p===""))try{t(p,d,m);}catch(h){console.error(h);}},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 p=n.get(d);n.delete(d),u(d,p.txt,p.via);}};return {cursor:e,open:()=>{i||s||(i=true,c());},fromPoll:d=>{if(s)return false;let p=e.seq,m=e.seq,h=Array.isArray(d?.chunks)?d.chunks:[];for(let w of h){if(!w||typeof w.seq!="number"||w.seq<=e.seq)continue;let b=!n.has(w.seq);b&&(a.poll++,r&&a.poll===1&&r("poll",w.seq)),n.set(w.seq,{txt:typeof w.txt=="string"?w.txt:"",via:b?"poll":n.get(w.seq).via}),w.seq>m&&(m=w.seq);}typeof d?.last_seq=="number"&&d.last_seq>m&&(m=d.last_seq);let _=Array.from(n.keys()).sort((w,b)=>w-b);for(let w of _){if(w<=e.seq){n.delete(w);continue}if(w>m)break;let b=n.get(w);n.delete(w),u(w,b.txt,b.via);}return m>e.seq&&(e.seq=m),c(),e.seq>p},fromSocket:(d,p)=>{s||typeof d!="number"||!Number.isFinite(d)||(o=Date.now(),!(d<=e.seq)&&(!n.has(d)&&n.size>=_a||(n.has(d)||(a.socket++,r&&a.socket===1&&r("socket",d)),n.set(d,{txt:typeof p=="string"?p:"",via:n.has(d)?n.get(d).via:"socket"}),i&&c())));},warm:()=>o!==0&&Date.now()-o<ba,stats:()=>({socket:a.socket,poll:a.poll}),close:()=>{s=true,n.clear();}}}function ts(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 rs(e,t){let r={stop:()=>{}};if(typeof window>"u"||window._runningInNodeJS||Dt)return r;let n={stopped:false,socket:null,opened:null,joined:false,attempts:0,unavailable:false};Dt=n;let i=c=>{if(n.stopped)return;let g=c?.data;if(typeof g!="string")return;let f=null;try{f=JSON.parse(g);}catch{try{f=JSON.parse(decodeURI(g));}catch{return}}let d=f?.["#message"];if(d==null)return;if(typeof d=="string")try{d=JSON.parse(d);}catch{return}if(typeof d!="object")return;let p=f?.["#srid"];if(typeof p=="string"&&p!==e)return;let m=d.seq;typeof m=="string"&&m!==""&&(m=Number(m)),t.fromSocket(m,d.txt);},s=()=>{if(n.socket){try{n.socket.removeEventListener("message",i);}catch{}try{n.socket.removeEventListener("close",a);}catch{}n.socket=null;}},o=async()=>{let c=n.opened,g=n.joined;if(n.opened=null,n.joined=false,s(),!(!g&&!c))try{let f=this.__socket?await this.__socket:null;if(c&&f===c){await Ut.bind(this)();return}g&&f&&ji()===room&&await qe.bind(this)({group:null});}catch{}},a=()=>{n.stopped||(s(),!n.unavailable&&(n.attempts>=wa||(n.attempts+=1,setTimeout(()=>{n.stopped||u();},Ea))));},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 Fe.bind(this)(()=>{},0),c=this.__socket?await this.__socket:null,n.stopped){o();return}c&&!n.opened&&(n.opened=c);}if(!c||c.readyState!==1)return;if(c.addEventListener("message",i),c.addEventListener("close",a),n.socket=c,!n.joined&&(await qe.bind(this)({group:e}),n.joined=!0,n.stopped)){o();return}}catch{}};return u(),{stop:()=>{n.stopped||(n.stopped=true,Dt===n&&(Dt=null),o());}}}function ns(e){return e?.status==="running"||e?.status==="pending"}function Aa(e){return !!e&&typeof e=="object"&&!Array.isArray(e)&&typeof e.status=="string"&&typeof e.id=="string"&&"in_queue"in e}function is(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 ss({id:e,auth:t,service:r,owner:n,latency:i=1e3,queue:s,onResponse:o,onError:a,onStream:u,realtimeGroup:c}){if(typeof i!="number")throw new l('"latency" should be a number.',{code:"INVALID_PARAMETER"});if(i<0)throw new l('"latency" should be a non-negative number.',{code:"INVALID_PARAMETER"});s&&!pe?.[s]&&(pe[s]=new Wi({breakWhenError:false,batchSize:1}));let g={stop:null,aborted:false,queue:s};te[e]=g;let f=null,d=()=>{te[e]===g&&delete te[e];},p=()=>new Promise((h,_)=>{let w=false;if(g.aborted){d(),h(ot(e));return}let b={seq:0},E=ts.call(this,e),R=u&&c?es(b,u,E.onTransport):null,T=R?rs.call(this,c,R):null,U=()=>{E.done(R),T&&T.stop(),R&&R.close();};f=U;let D=0,x=false,v=0,C=async()=>{if(!(w||x)&&!(R&&R.warm()&&Date.now()-D<Zi)){x=true;try{for(;;){let q={id:e,service:r,owner:n};u&&(q.since=b.seq),D=Date.now();let G=await P.bind(this)("csr-poll",q,{auth:t});if(w)return;let Ae=R?R.fromPoll(G):u?Xi(G,b,u):!1;R&&R.open();let $=ns(G);if(G?.more&&Ae){v=0;continue}if($){v=0;return}if(v=G?.more?v+1:0,G?.more&&v<Yi)return;w=!0,o&&o(G),clearInterval(L),U(),d(),h(G);return}}catch(q){if(w)return;w=true,a&&a(q),clearInterval(L),U(),d(),_(q);}finally{x=false;}}},L=setInterval(C,i);R&&C(),g.stop=()=>{w||(w=true,clearInterval(L),U(),d(),h(ot(e)));};}),m=()=>{let h=te[e];h&&(h.stop?h.stop():(h.aborted=true,delete te[e]));};if(s){let h=new Promise((_,w)=>{let b=false,E=pe[s].add([async()=>{try{let R=await p();return b||(b=!0,_(R)),R}catch(R){throw b||(b=true,w(R)),R}}])[0];st[e]=E,g.stop=()=>{if(!b){g.aborted=true,f&&f();try{pe[s]&&pe[s].remove(st[e]);}catch{}delete st[e],d(),b=true,_(ot(e));}};});return Object.assign(h,{stop:m})}else return Object.assign(p(),{stop:m})}function os(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 as(e,t){if(!e.queue)throw new l('"queue" is required.',{code:"INVALID_PARAMETER"});let r={service:e.service||this.service,owner:e.owner||this.owner,queue:e.queue+":"};return P.bind(this)("csr-poll",r,{auth:true})}async function ls(e){let t=false;if(typeof e.poll=="number"&&e.poll<0)throw new l('"poll" should be a non-negative number.',{code:"INVALID_PARAMETER"});let r=e?.onResponse,n=e?.onError,i=e?.onStream,s=typeof e.poll=="number"?e.poll:e.poll?1e3:0;delete e.poll,(s||e.stream)&&!e.queue&&(e.queue=(this.__user?.user_id||"anonymous")+"-"+Re());let o=c=>{for(let g in c)if(typeof c[g]=="string"&&c[g].includes("$CLIENT_SECRET")){t=true;break}};if(e=y.Params(e,{url:c=>{if(!c||typeof c!="string")throw new l('"url" should be type: <string>.',{code:"INVALID_PARAMETER"});return y.Url(c),c.includes("$CLIENT_SECRET")&&(t=true),c},clientSecretName:"string",method:c=>{if(c&&typeof c!="string")throw new l('"method" should be either "GET" or "POST" or "DELETE" or "PUT".',{code:"INVALID_PARAMETER"});let g=c.toLowerCase();if(g!=="get"&&g!=="post"&&g!=="delete"&&g!=="put")throw new l('"method" should be either "GET" or "POST" or "DELETE" or "PUT".',{code:"INVALID_PARAMETER"});return g},stream:c=>{if(c!=null&&typeof c!="boolean")throw new l('"stream" should be type: <boolean>.',{code:"INVALID_PARAMETER"});return !!c},realtime:c=>{if(c!=null&&typeof c!="boolean")throw new l('"realtime" should be type: <boolean>.',{code:"INVALID_PARAMETER"});return !!c},headers:c=>{if(c&&typeof c!="object")throw new l('"headers" should be type: <object>.',{code:"INVALID_PARAMETER"});return o(c),c},data:c=>{if(c&&typeof c!="object")throw new l('"data" should be type: <object>.',{code:"INVALID_PARAMETER"});return o(c),c},params:c=>{if(c&&typeof c!="object")throw new l('"params" should be type: <object>.',{code:"INVALID_PARAMETER"});return o(c),c},expires:"number",queue:"string"},["clientSecretName","method","url"]),e.realtime&&!e.stream)throw new l('"realtime" requires "stream": true.',{code:"INVALID_PARAMETER"});if(!t)throw new l(`At least one parameter value should include "$CLIENT_SECRET" in ${e.method.toLowerCase()==="post"?'"data"':'"params"'} or "headers".`,{code:"INVALID_PARAMETER"});await this.__connection;let a=!!this.__user,u=()=>P.bind(this)("csr",e,{auth:a,tokenHeaders:{accessToken:!!a}}).then(c=>{if(c.status==="running"||c.status==="pending"){let g=`[${e.method.toUpperCase()}]${e.url.toLowerCase()}`,f=e.service||this.service,d=e.owner||this.owner,p=`${g}#${f}:${c.id}`;Object.assign(c,{poll:m=>ss.call(this,{id:p,auth:a,service:f,owner:d,latency:m?.latency||1e3,queue:e?.queue,onResponse:r,onError:n,onStream:m?.onStream||i,realtimeGroup:c?.realtime_group})});}return r?r(c):c}).catch(c=>{if(n)return n(c);throw c});if(e?.queue){let c="base:"+e.queue;return pe?.[c]||(pe[c]=new Wi({breakWhenError:false,batchSize:1})),new Promise((g,f)=>{pe[c].add([async()=>{try{let d=await u();if(s>0){let p=d.poll({latency:s});return g(p),p}return g(d),d}catch(d){throw f(d),d}}]);})}else return u()}async function cs(e,t){await this.__connection;let r=e.service||this.service,n=e.owner||this.owner;e=y.Params(e,{url:"string",method:["GET","POST","DELETE","PUT"],queue:"string",status:["pending","running","resolved","failed"],compact:"boolean",queue_exact:"boolean",queue_exclude:"string"},["url","method"]);let i=!!this.__user,s=`[${e.method.toUpperCase()}]${e.url.toLowerCase()}#${r}:`,o={id:s,queue:e?.queue,status:e?.status,service:r,owner:n};e?.compact&&(o.compact=true),e?.queue_exact&&(o.queue_exact=true),e?.queue_exclude&&(o.queue_exclude=e.queue_exclude),Object.keys(o).forEach(u=>{o[u]||delete o[u];}),o.queue&&(o.id_prefix=o.id,delete o.id);let a=await P.bind(this)("csr-poll",o,{auth:i,fetchOptions:t});return a.list=a.list.map(u=>{let c={id:u.id,status_code:u.rslv?.status_code||null,response_body:u.rslv?.body||u.rslv?.truncated||null,error:u?.err,created:u?.stmp,updated:u?.utmp,request_body:u?.reqbdy,expires:u?.expt,status:u.stts,queue_name:u?.qid,request_text:u?.reqtxt,response_text:u?.rslvtxt,response_complete_marker:u?.rslvmk!=null?!!u.rslvmk:void 0,compact:u?.cmpct?true:void 0};for(let g in c)c[g]===void 0&&delete c[g];return (c.status==="running"||c.status==="pending")&&(c.poll=g=>ss.call(this,{id:s+c.id,auth:i,service:r,owner:n,latency:g?.latency||1e3,queue:u?.qid,onResponse:g?.onResponse,onError:g?.onError,onStream:g?.onStream})),c}),a}async function us(e){await this.__connection,e=y.Params(e,{url:"string",method:["GET","POST","DELETE","PUT"],id:"string",queue:"string"},["url","method","id"]);let t=e?.service||this.service,r=e?.owner||this.owner,n=!!this.__user,i=`[${e.method.toUpperCase()}]${e.url.toLowerCase()}#${t}`,s=e.id,o=`${i}:${s}`,a=e?.queue;return a&&pe?.[a]&&(pe[a].remove(st[o]),delete st[o]),P.bind(this)("csr-cancel",{id:o,service:t,owner:r},{auth:n})}function ds(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,i=t?.onStream,s=t?.onResponse,o=t?.onError,a={stopped:false,fullId:e,resolve:null},u=null,c={stop:null,aborted:false},g=()=>{te[a.fullId]===c&&delete te[a.fullId];},f=()=>{a.stopped||(a.stopped=true,u&&u(),g(),a.resolve&&a.resolve(ot(a.fullId)));};c.stop=f;let d=new Promise(async(p,m)=>{a.resolve=p;try{await this.__connection;let h=!!this.__user,_=t?.service||this.service,w=t?.owner||this.owner;if(a.fullId=is(e,t?.url,t?.method,_),a.stopped){p(ot(a.fullId));return}te[a.fullId]=c;let b={seq:n},E=0,R=ts.call(this,a.fullId),T=i&&t?.realtimeGroup?es(b,i,R.onTransport):null,U=T?rs.call(this,t.realtimeGroup,T):null,D=()=>{R.done(T),U&&U.stop(),T&&T.close();};for(u=D;;){let x=await P.bind(this)("csr-poll",{id:a.fullId,service:_,owner:w,since:b.seq},{auth:h});if(a.stopped)return;if(!Aa(x)){D(),g(),s&&s(x),p(x);return}let v=T?T.fromPoll(x):Xi(x,b,i);T&&T.open();let C=ns(x);if(x.more&&v){E=0;continue}if(E=x.more?E+1:0,!C&&(!x.more||E>=Yi)){D(),g(),s&&s(x),p(x);return}if(await new Promise(L=>setTimeout(L,T&&T.warm()?Math.max(r,Zi):r)),a.stopped)return}}catch(h){if(a.stopped)return;u&&u(),g(),o&&o(h),m(h);}});return Object.assign(d,{stop:f})}async function fs(e,t,r){await this.__connection;let n=r?.service||this.service,i=r?.owner||this.owner,s=!!this.__user,o=is(e,r?.url,r?.method,n);return P.bind(this)("csr-finalize",{id:o,data:t,service:n,owner:i},{auth:s})}async function gs(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 P.bind(this)("send-inquiry",e),"SUCCESS: Inquiry has been sent."}async function ps(e,t){if(await this.__connection,Qi&&e instanceof FormData||Gi&&e instanceof HTMLFormElement||zi&&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=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 P.bind(this)("post-secure",e,{auth:true})}async function hs(e,t){await this.__connection;let{auth:r=false,method:n="POST",bypassAwaitConnection:i=false,responseType:s,contentType:o,tokenHeaders:a,progress:u}=t||{};if(t=Object.assign({auth:r,method:n,bypassAwaitConnection:i,responseType:s,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 P.bind(this)("mock",e,t)}async function ms(e,t){if(await this.__connection,!t?.url||typeof t.url!="string")throw new l('"url" is required in the second argument.',{code:"INVALID_PARAMETER"});y.Url(t.url);let n=(await this.admin_endpoint)?.forward_request;if(!n)throw new l("forwardRequest is not available on this service region yet.",{code:"NOT_EXISTS"});let i=null,s=null,o=zi&&e instanceof SubmitEvent?e.target:Gi&&e instanceof HTMLFormElement?e:null;o?i=new FormData(o):Qi&&e instanceof FormData?i=e:e!=null&&(i=JSON.stringify(e),s="application/json");let a={public_identifier:this.__public_identifier,service:this.service,owner:this.owner,forward:{url:t.url,method:t.method||"POST",headers:t.headers||{},apiKeyHeader:t.apiKeyHeader,apiKeyScheme:t.apiKeyScheme}},u=JSON.stringify(a).replace(/[\u007f-\uffff]/g,p=>"\\u"+p.charCodeAt(0).toString(16).padStart(4,"0"));if(u.length>4096)throw new l("Destination url and headers are too large for Content-Meta.",{code:"INVALID_PARAMETER"});let c=this.bearerToken||this.session?.idToken?.jwtToken||null;if(!c)throw new l("User login is required.",{code:"INVALID_REQUEST"});let g={"Content-Meta":u,Authorization:c};s&&(g["Content-Type"]=s);let f=await fetch(n,{method:"POST",headers:g,body:i,signal:t.signal});if(t.responseType==="response")return f;if(!f.ok){let p=await f.text();try{p=JSON.parse(p);}catch{}throw new l(p?.message||(typeof p=="string"?p:JSON.stringify(p)),{code:p?.code||"ERROR"})}if(t.onStream&&f.body){let p=f.body.getReader(),m=new TextDecoder,h="";for(;;){let{done:_,value:w}=await p.read();if(_)break;let b=m.decode(w,{stream:true});h+=b;try{t.onStream(b);}catch(E){console.error(E);}}return h}let d=await f.text();if(t.responseType==="text")return d;try{return JSON.parse(d)}catch{return d}}async function ys(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 P.bind(this)("get-feed",e,{auth:true,fetchOptions:t});for(let n in r.list)r.list[n]=await Se.bind(this)(r.list[n]);return r}function at(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 bs(e,t){if(e=j(e,{ignoreEmpty:true}).data,e=y.Params(e,{subscriber:n=>y.UserId(n,'User ID in "subscriber"'),subscription:at.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 P.bind(this)("get-subscription",e,Object.assign({auth:true},{fetchOptions:t}));return r.list=r.list.map((n=>{let i={};if(n.sub){let s=n.sub.split("#");i.subscriber=s[2],i.subscription=s[0];}else i.subscriber=n.subscriber,i.subscription=n.subscription;return i.timestamp=n?.timestamp||n.stmp,i.blocked=n?.blocked||n.grp.substring(0,1)==="N",Object.assign(i,n.opt),i})),r}async function _s(e){await this.__connection,e=y.Params(e,{user_id:at.bind(this),get_feed:["boolean",()=>false],get_notified:["boolean",()=>false],get_email:n=>{if(n&&!this.__user.email||!this.__user.email_verified)throw new l("User has no verified email address.",{code:"INVALID_REQUEST"});return !!n}},["user_id"]);let t=await P.bind(this)("subscription",{subscribe:e.user_id,option:{get_feed:e.get_feed,get_notified:e.get_notified,get_email:e.get_email||false}},{auth:true}),r={};if(t.sub){let n=t.sub.split("#");r.subscriber=n[2],r.subscription=n[0];}else r.subscriber=t.subscriber,r.subscription=t.subscription;return r.timestamp=t?.timestamp||t.stmp,r.blocked=t?.blocked||t.grp.substring(0,1)==="N",Object.assign(r,t.opt),r}async function ws(e){await this.__connection;let{user_id:t}=y.Params(e,{user_id:at.bind(this)},["user_id"]);return await P.bind(this)("subscription",{unsubscribe:t},{auth:true})}async function Es(e){await this.__connection;let{user_id:t}=y.Params(e,{user_id:at.bind(this)},["user_id"]);return await P.bind(this)("subscription",{block:t},{auth:true})}async function As(e){await this.__connection;let{user_id:t}=y.Params(e,{user_id:at.bind(this)},["user_id"]);return await P.bind(this)("subscription",{unblock:t},{auth:true})}async function Rs(e,t){await this.__connection;let r=await Q.bind(this)();e=y.Params(e,{user_id:o=>{if(o!==this.__user.user_id&&!r)throw new l("No access.",{code:"INVALID_REQUEST"});return o},group:o=>{if(o==="public"&&(o=0),o==="authorized"&&(o=1),typeof o!="number")throw new l('"group" should be type number | "public" | "authorized".',{code:"INVALID_PARAMETER"});return o}});let n=await P.bind(this)("get-newsletter-subscription",e,{auth:true,fetchOptions:t||null}),i=n?.list||n,s=[];Array.isArray(i)||(i=[]);for(let o of i){let a=o.subt.split("#"),u=true;a[0].charAt(0)==="@"&&(u=false,a[0]=a[0].substring(1));let c=parseInt(a[0]);s.push({timestamp:o.stmp,group:c,subscribed_email:a[1],active:u});}return n?.list?(n.list=s,n):s}async function Is(e){await this.__connection;let t=y.Params(e||{},{email:r=>Array.isArray(r)&&r.length>0?r.length===1?y.Email(r[0]):r.map(n=>y.Email(n)):y.Email(r),group:["number","public","authorized","admin",r=>{if(typeof r!="string"||r.length>20||!/^[a-zA-Z0-9]+$/.test(r))throw new l('"group" should be an alphanumeric string without spaces and less than 20 characters.',{code:"INVALID_PARAMETER"});return r}],redirect:r=>y.Url(r)},this.__user?["group"]:["email","group"]);return P.bind(this)(`subscribe-${this.__user?"":"public-"}newsletter`,t,{auth:!!this.__user})}async function Ts(e){await this.__connection,e=y.Params(e,{group:["number","public","authorized","admin"]},["group"]);let t=Object.assign({action:"unsubscribe"},e);return P.bind(this)("subscribe-newsletter",t,{auth:true})}async function Ps(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 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=>{if(u==="public")return 0;if(!this.session)throw new l("User should be logged in.",{code:"INVALID_REQUEST"});if(u==="authorized")return 1;if(typeof u=="number"){if(!r&&u>parseInt(this.user?.access_group||this.session?.idToken?.payload?.access_group))throw new l("User has no access.",{code:"INVALID_REQUEST"});return u}throw new l('"group" should be type: number | "public" | "authorized".',{code:"INVALID_PARAMETER"})}},["searchFor","value","group"]);let i=e.group===0?"get-public-newsletters":"get-newsletters",s=await P.bind(this)(i,e,Object.assign({method:"get",auth:i==="get-public-newsletters"?!!this.__user:true},{fetchOptions:t})),o={message_id:"mid",timestamp:"stmp",complaint:"cmpl",read:"read",subject:"subj",bounced:"bnce",url:"url",delivered:"delv"},a={message_id:"",timestamp:0,complaint:0,read:0,subject:"",bounced:"",url:"",delivered:0};return s.list=s.list.map(u=>{let c={};for(let g in o)c[g]=u[o[g]]||a[g];return c.bounced=String(c.bounced),c}),s}async function Ss(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 l("User needs to login.",{code:"INVALID_REQUEST"});if(this.__user.access_group<90)throw new l("Invalid access.",{code:"INVALID_REQUEST"})}return await P.bind(this)("block-account",t,{auth:true})}async function ks(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 l("User needs to login.",{code:"INVALID_REQUEST"});if(this.__user.access_group<90)throw new l("Invalid access.",{code:"INVALID_REQUEST"})}return await P.bind(this)("block-account",t,{auth:true})}async function vs(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 l("User needs to login.",{code:"INVALID_REQUEST"});if(this.__user.access_group<90)throw new l("Invalid access.",{code:"INVALID_REQUEST"})}return await P.bind(this)("remove-account",t,{auth:true})}async function Ns(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 l('"access_group" is invalid. Should be type <number>.',{code:"INVALID_PARAMETER"})}if(typeof s!="number"||s<1||s>100)throw new l('"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 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:s=>{if(typeof s!="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 s},template:s=>{if(typeof s!="object"||!s.url||!s.subject)throw new l('"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 l("User needs to login.",{code:"INVALID_REQUEST"});if(this.__user.access_group<90)throw new l("Invalid access.",{code:"INVALID_REQUEST"})}return await P.bind(this)("admin-signup",n,{auth:true})}async function Us(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 l('"access_group" is invalid. Should be type <number>.',{code:"INVALID_PARAMETER"})}if(typeof s!="number"||s<1||s>100)throw new l('"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 l("User needs to login.",{code:"INVALID_REQUEST"});if(this.__user.access_group<90)throw new l("Invalid access.",{code:"INVALID_REQUEST"})}return await P.bind(this)("admin-signup",n,{auth:true})}async function Ds(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 Q.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 P.bind(this)("grant-access",e,{auth:true})}async function xs(e,t){if(e=y.Params(e,{email:"string"}),!await Q.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 P.bind(this)("invitation-list",Object.assign({mode:"search"},e),{fetchOptions:t,auth:true});return n.list=n.list.map(i=>$e(i.user)),n}async function Cs(e){if(e=y.Params(e,{email:r=>y.Email(r)},["email"]),!await Q.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 P.bind(this)("invitation-list",Object.assign({mode:"cancel"},e),{auth:true})}async function Ls(e){if(e=y.Params(e,{email:r=>y.Email(r)},["email"]),!await Q.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 P.bind(this)("invitation-list",Object.assign({mode:"resend"},e),{auth:true})}async function Os(e){let t=y.Params(e,{user_id:o=>y.UserId(o,'"user_id"'),email:o=>y.Email(o),address:o=>{if(!o)return "";if(typeof o=="string")return o;if(typeof o=="object")return JSON.stringify(o)},name:"string",gender:"string",birthdate:o=>o?y.Birthdate(o):"",phone_number:o=>o?y.PhoneNumber(o):"",email_public:"boolean",phone_number_public:"boolean",address_public:"boolean",gender_public:"boolean",birthdate_public:"boolean",misc:"string",picture:o=>o?y.Url(o):"",profile:o=>o?y.Url(o):"",nickname:"string",website:o=>o?y.Url(o):""},["user_id"]),r=t.service,n=t.owner;if(delete t.service,delete t.owner,Object.keys(t).filter(o=>o!=="user_id"&&t[o]!==void 0).length===0)throw new l("At least one attribute to update is required.",{code:"INVALID_PARAMETER"});if(!await Q.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"})}t.email&&(t.preferred_username=(r||this.service)+"-"+W.hash(t.email));let s={attributes:t};return r&&n&&(s.service=r,s.owner=n),await P.bind(this)("admin-edit-profile",s,{auth:true})}async function Ms(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 P.bind(this)("store-subscription",{endpoint:e.endpoint,keys:e.keys},{auth:true}),"SUCCESS: Subscribed to receive notifications."}async function Fs(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 P.bind(this)("delete-subscription",{endpoint:e.endpoint,keys:e.keys},{auth:true}),"SUCCESS: Unsubscribed from notifications."}async function qs(){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 P.bind(this)("get-vapid-public-key",null,{auth:true})}}async function Vs(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}=j(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 i={title:r,body:n};return t?(typeof t=="string"&&(t=[t]),i.user_ids=t):i.user_ids="all_users",await P.bind(this)("push-notification",i,{auth:true}),"SUCCESS: Notification sent."}async function $s(e){await this.__connection,e=y.Params(e,{spell:"string",name:"string",magic:r=>r},["spell","name"]);await P.bind(this)("castspell",e);return `The spell "${e.spell}" has been cast.`}async function js(e){return await this.__connection,e=y.Params(e||{},{search:["spell","name",()=>"spell"],value:"string"}),await P.bind(this)("getspell",e)}async function Bs(e){await this.__connection,e=y.Params(e,{message:"string",name:"string"},["message","name"]);let t=await P.bind(this)("dopamine",e,{auth:true}),r=t?.previous_message?.message,n=t?.previous_message?.name;if(Y())r&&n&&window.alert(`${n} said: ${r}`),window.location.href=t.video;else return r&&n?`${n} said: ${r}
|
|
215
|
+
`,c=new Blob([u],{type:"application/javascript"});Ee=new Worker(URL.createObjectURL(c)),Ee.onmessage=g=>{a.readyState===1&&a.send(JSON.stringify({action:"keepAlive"}));},i(a);},a.onmessage=async u=>{let c="";try{c=JSON.parse(decodeURI(u.data)),this.log("socket onmessage",c);}catch{return}let g;switch(!0){case !!c?.["#message"]:g="message";break;case !!c?.["#private"]:g="private";break;case !!c?.["#notice"]:g="notice";break;case !!c?.["#rtc"]:g="rtc";break;case !!c?.["#error"]:g="error";break}if(!g)return;let f={type:g,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(g==="notice")e(f);else if(g==="rtc"){if(f.sender!==this.user.user_id){let d=f.message;if(d.hungup){ce[f.sender_cid]&&(ce[f.sender_cid](!1),delete ce[f.sender_cid]),ge[f.sender_cid]&&delete ge[f.sender_cid],N?.[f.sender_cid]&&ue.bind(this)({cid:f.sender_cid}),f.type="rtc:closed",e(f);return}if(d.candidate&&Tr.bind(this)(d.candidate,f.sender_cid),d.sdpoffer&&(Ir.bind(this)(d.sdpoffer,f.sender_cid),ge[f.sender_cid]||(ge[f.sender_cid]=f.sender_cid,delete f.message,f.connectRTC=Vi.bind(this)(f),f.type="rtc:incoming",f.hangup=(()=>{N[f.sender_cid]?ue.bind(this)({cid:f.sender_cid}):ge[f.sender_cid]&&(delete ge[f.sender_cid],a.send(JSON.stringify({action:"rtc",uid:f.sender_cid,content:{hungup:this.user.user_id},token:this.session.accessToken.jwtToken})));}).bind(this),e(f))),d.pickup&&ce[f.sender_cid]&&(ce[f.sender_cid](!0),delete ce[f.sender_cid]),d.sdpanswer&&N[f.sender_cid])if(N[f.sender_cid].signalingState==="have-local-offer")await N[f.sender_cid].setRemoteDescription(new RTCSessionDescription(d.sdpanswer));else throw new l("Invalid signaling state.",{code:"INVALID_REQUEST"})}}else e(f);},a.onclose=()=>{it?(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."}),Me++,Me<3?(this.log("realtime onclose","Reconnecting to WebSocket server..."+Me),e({type:"reconnect",message:"Reconnecting to WebSocket server..."+Me}),Fe.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 Ki(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 Ce.bind(this)(),e=j(e).data;let i="";if(r&&(r=m.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 l("Notification size exceeds 3kb.",{code:"INVALID_PARAMETER"});if(n.readyState===1){try{m.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}),be!==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: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 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 Ce.bind(this)(),e=j(e,{nullIfEmpty:true}).data;let{group:r=null}=e;if(!r&&!be)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})),be=r,{type:"success",message:r?`Joined realtime message group: "${r}".`:"Left realtime message group."}}async function Hi(e,t){e=m.Params(e,{user_id:n=>m.UserId(n,'User ID in "user_id"'),group:["string",()=>{if(!be)throw new l('No group has been joined. Otherwise "group" is required.',{code:"INVALID_REQUEST"});return be}]});let r=await T.bind(this)("get-ws-group",e,{fetchOptions:t,auth:true,method:"post"});return r.list=r.list.map(n=>({user_id:n.uid.split("#")[1],cid:"cid:"+n.cid})),r}async function Gi(e,t){if(await this.__connection,e||(e={searchFor:"group",value:" ",condition:">"}),e=m.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 T.bind(this)("get-ws-group",e,{fetchOptions:t,auth:true,method:"post"});return r.list=r.list.map(n=>({group:n.rid.split("#")[1],number_of_users:n.cnt})),r}var Qi=typeof FormData<"u",zi=typeof HTMLFormElement<"u",Ji=typeof SubmitEvent<"u",pe={},st={},te={};function ot(e){return Object.freeze({id:e,status:"stopped"})}function Yi(e){return !!e&&typeof e=="object"&&e.status==="stopped"}var Xi=3;function Zi(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 Pa=2e3,es=5e3,Sa=2e3,ka=5,va=1500,Dt=null;function ts(e,t,r){let n=new Map,i=false,s=false,o=0,a={socket:0,poll:0},u=(d,p,y)=>{if(e.seq=d,!(!t||typeof p!="string"||p===""))try{t(p,d,y);}catch(h){console.error(h);}},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 p=n.get(d);n.delete(d),u(d,p.txt,p.via);}};return {cursor:e,open:()=>{i||s||(i=true,c());},fromPoll:d=>{if(s)return false;let p=e.seq,y=e.seq,h=Array.isArray(d?.chunks)?d.chunks:[];for(let w of h){if(!w||typeof w.seq!="number"||w.seq<=e.seq)continue;let b=!n.has(w.seq);b&&(a.poll++,r&&a.poll===1&&r("poll",w.seq)),n.set(w.seq,{txt:typeof w.txt=="string"?w.txt:"",via:b?"poll":n.get(w.seq).via}),w.seq>y&&(y=w.seq);}typeof d?.last_seq=="number"&&d.last_seq>y&&(y=d.last_seq);let _=Array.from(n.keys()).sort((w,b)=>w-b);for(let w of _){if(w<=e.seq){n.delete(w);continue}if(w>y)break;let b=n.get(w);n.delete(w),u(w,b.txt,b.via);}return y>e.seq&&(e.seq=y),c(),e.seq>p},fromSocket:(d,p)=>{s||typeof d!="number"||!Number.isFinite(d)||(o=Date.now(),!(d<=e.seq)&&(!n.has(d)&&n.size>=Sa||(n.has(d)||(a.socket++,r&&a.socket===1&&r("socket",d)),n.set(d,{txt:typeof p=="string"?p:"",via:n.has(d)?n.get(d).via:"socket"}),i&&c())));},warm:()=>o!==0&&Date.now()-o<Pa,stats:()=>({socket:a.socket,poll:a.poll}),close:()=>{s=true,n.clear();}}}function rs(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 ns(e,t){let r={stop:()=>{}};if(typeof window>"u"||window._runningInNodeJS||Dt)return r;let n={stopped:false,socket:null,opened:null,joined:false,attempts:0,unavailable:false};Dt=n;let i=c=>{if(n.stopped)return;let g=c?.data;if(typeof g!="string")return;let f=null;try{f=JSON.parse(g);}catch{try{f=JSON.parse(decodeURI(g));}catch{return}}let d=f?.["#message"];if(d==null)return;if(typeof d=="string")try{d=JSON.parse(d);}catch{return}if(typeof d!="object")return;let p=f?.["#srid"];if(typeof p=="string"&&p!==e)return;let y=d.seq;typeof y=="string"&&y!==""&&(y=Number(y)),t.fromSocket(y,d.txt);},s=()=>{if(n.socket){try{n.socket.removeEventListener("message",i);}catch{}try{n.socket.removeEventListener("close",a);}catch{}n.socket=null;}},o=async()=>{let c=n.opened,g=n.joined;if(n.opened=null,n.joined=false,s(),!(!g&&!c))try{let f=this.__socket?await this.__socket:null;if(c&&f===c){await Ut.bind(this)();return}g&&f&&Bi()===room&&await qe.bind(this)({group:null});}catch{}},a=()=>{n.stopped||(s(),!n.unavailable&&(n.attempts>=ka||(n.attempts+=1,setTimeout(()=>{n.stopped||u();},va))));},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 Fe.bind(this)(()=>{},0),c=this.__socket?await this.__socket:null,n.stopped){o();return}c&&!n.opened&&(n.opened=c);}if(!c||c.readyState!==1)return;if(c.addEventListener("message",i),c.addEventListener("close",a),n.socket=c,!n.joined&&(await qe.bind(this)({group:e}),n.joined=!0,n.stopped)){o();return}}catch{}};return u(),{stop:()=>{n.stopped||(n.stopped=true,Dt===n&&(Dt=null),o());}}}function is(e){return e?.status==="running"||e?.status==="pending"}function Na(e){return !!e&&typeof e=="object"&&!Array.isArray(e)&&typeof e.status=="string"&&typeof e.id=="string"&&"in_queue"in e}function ss(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 m.Url(t),`[${r.toUpperCase()}]${t.toLowerCase()}#${n}:${e}`}function os({id:e,auth:t,service:r,owner:n,latency:i=1e3,queue:s,onResponse:o,onError:a,onStream:u,realtimeGroup:c}){if(typeof i!="number")throw new l('"latency" should be a number.',{code:"INVALID_PARAMETER"});if(i<0)throw new l('"latency" should be a non-negative number.',{code:"INVALID_PARAMETER"});s&&!pe?.[s]&&(pe[s]=new Wi({breakWhenError:false,batchSize:1}));let g={stop:null,aborted:false,queue:s};te[e]=g;let f=null,d=()=>{te[e]===g&&delete te[e];},p=()=>new Promise((h,_)=>{let w=false;if(g.aborted){d(),h(ot(e));return}let b={seq:0},E=rs.call(this,e),R=u&&c?ts(b,u,E.onTransport):null,k=R?ns.call(this,c,R):null,U=()=>{E.done(R),k&&k.stop(),R&&R.close();};f=U;let D=0,x=false,v=0,C=async()=>{if(!(w||x)&&!(R&&R.warm()&&Date.now()-D<es)){x=true;try{for(;;){let q={id:e,service:r,owner:n};u&&(q.since=b.seq),D=Date.now();let Q=await T.bind(this)("csr-poll",q,{auth:t});if(w)return;let Ae=R?R.fromPoll(Q):u?Zi(Q,b,u):!1;R&&R.open();let $=is(Q);if(Q?.more&&Ae){v=0;continue}if($){v=0;return}if(v=Q?.more?v+1:0,Q?.more&&v<Xi)return;w=!0,o&&o(Q),clearInterval(L),U(),d(),h(Q);return}}catch(q){if(w)return;w=true,a&&a(q),clearInterval(L),U(),d(),_(q);}finally{x=false;}}},L=setInterval(C,i);R&&C(),g.stop=()=>{w||(w=true,clearInterval(L),U(),d(),h(ot(e)));};}),y=()=>{let h=te[e];h&&(h.stop?h.stop():(h.aborted=true,delete te[e]));};if(s){let h=new Promise((_,w)=>{let b=false,E=pe[s].add([async()=>{try{let R=await p();return b||(b=!0,_(R)),R}catch(R){throw b||(b=true,w(R)),R}}])[0];st[e]=E,g.stop=()=>{if(!b){g.aborted=true,f&&f();try{pe[s]&&pe[s].remove(st[e]);}catch{}delete st[e],d(),b=true,_(ot(e));}};});return Object.assign(h,{stop:y})}else return Object.assign(p(),{stop:y})}function as(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 ls(e,t){if(!e.queue)throw new l('"queue" is required.',{code:"INVALID_PARAMETER"});let r={service:e.service||this.service,owner:e.owner||this.owner,queue:e.queue+":"};return T.bind(this)("csr-poll",r,{auth:true})}async function cs(e){let t=false;if(typeof e.poll=="number"&&e.poll<0)throw new l('"poll" should be a non-negative number.',{code:"INVALID_PARAMETER"});let r=e?.onResponse,n=e?.onError,i=e?.onStream,s=typeof e.poll=="number"?e.poll:e.poll?1e3:0;delete e.poll,(s||e.stream)&&!e.queue&&(e.queue=(this.__user?.user_id||"anonymous")+"-"+Re());let o=c=>{for(let g in c)if(typeof c[g]=="string"&&c[g].includes("$CLIENT_SECRET")){t=true;break}};if(e=m.Params(e,{url:c=>{if(!c||typeof c!="string")throw new l('"url" should be type: <string>.',{code:"INVALID_PARAMETER"});return m.Url(c),c.includes("$CLIENT_SECRET")&&(t=true),c},clientSecretName:"string",method:c=>{if(c&&typeof c!="string")throw new l('"method" should be either "GET" or "POST" or "DELETE" or "PUT".',{code:"INVALID_PARAMETER"});let g=c.toLowerCase();if(g!=="get"&&g!=="post"&&g!=="delete"&&g!=="put")throw new l('"method" should be either "GET" or "POST" or "DELETE" or "PUT".',{code:"INVALID_PARAMETER"});return g},stream:c=>{if(c!=null&&typeof c!="boolean")throw new l('"stream" should be type: <boolean>.',{code:"INVALID_PARAMETER"});return !!c},realtime:c=>{if(c!=null&&typeof c!="boolean")throw new l('"realtime" should be type: <boolean>.',{code:"INVALID_PARAMETER"});return !!c},headers:c=>{if(c&&typeof c!="object")throw new l('"headers" should be type: <object>.',{code:"INVALID_PARAMETER"});return o(c),c},data:c=>{if(c&&typeof c!="object")throw new l('"data" should be type: <object>.',{code:"INVALID_PARAMETER"});return o(c),c},params:c=>{if(c&&typeof c!="object")throw new l('"params" should be type: <object>.',{code:"INVALID_PARAMETER"});return o(c),c},expires:"number",queue:"string"},["clientSecretName","method","url"]),e.realtime&&!e.stream)throw new l('"realtime" requires "stream": true.',{code:"INVALID_PARAMETER"});if(!t)throw new l(`At least one parameter value should include "$CLIENT_SECRET" in ${e.method.toLowerCase()==="post"?'"data"':'"params"'} or "headers".`,{code:"INVALID_PARAMETER"});await this.__connection;let a=!!this.__user,u=()=>T.bind(this)("csr",e,{auth:a,tokenHeaders:{accessToken:!!a}}).then(c=>{if(c.status==="running"||c.status==="pending"){let g=`[${e.method.toUpperCase()}]${e.url.toLowerCase()}`,f=e.service||this.service,d=e.owner||this.owner,p=`${g}#${f}:${c.id}`;Object.assign(c,{poll:y=>os.call(this,{id:p,auth:a,service:f,owner:d,latency:y?.latency||1e3,queue:e?.queue,onResponse:r,onError:n,onStream:y?.onStream||i,realtimeGroup:c?.realtime_group})});}return r?r(c):c}).catch(c=>{if(n)return n(c);throw c});if(e?.queue){let c="base:"+e.queue;return pe?.[c]||(pe[c]=new Wi({breakWhenError:false,batchSize:1})),new Promise((g,f)=>{pe[c].add([async()=>{try{let d=await u();if(s>0){let p=d.poll({latency:s});return g(p),p}return g(d),d}catch(d){throw f(d),d}}]);})}else return u()}async function us(e,t){await this.__connection;let r=e.service||this.service,n=e.owner||this.owner;e=m.Params(e,{url:"string",method:["GET","POST","DELETE","PUT"],queue:"string",status:["pending","running","resolved","failed"],compact:"boolean",queue_exact:"boolean",queue_exclude:"string"},["url","method"]);let i=!!this.__user,s=`[${e.method.toUpperCase()}]${e.url.toLowerCase()}#${r}:`,o={id:s,queue:e?.queue,status:e?.status,service:r,owner:n};e?.compact&&(o.compact=true),e?.queue_exact&&(o.queue_exact=true),e?.queue_exclude&&(o.queue_exclude=e.queue_exclude),Object.keys(o).forEach(u=>{o[u]||delete o[u];}),o.queue&&(o.id_prefix=o.id,delete o.id);let a=await T.bind(this)("csr-poll",o,{auth:i,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,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 g in c)c[g]===void 0&&delete c[g];return (c.status==="running"||c.status==="pending")&&(c.poll=g=>os.call(this,{id:s+c.id,auth:i,service:r,owner:n,latency:g?.latency||1e3,queue:u?.qid,onResponse:g?.onResponse,onError:g?.onError,onStream:g?.onStream})),c}),a}async function ds(e){await this.__connection,e=m.Params(e,{url:"string",method:["GET","POST","DELETE","PUT"],id:"string",queue:"string"},["url","method","id"]);let t=e?.service||this.service,r=e?.owner||this.owner,n=!!this.__user,i=`[${e.method.toUpperCase()}]${e.url.toLowerCase()}#${t}`,s=e.id,o=`${i}:${s}`,a=e?.queue;return a&&pe?.[a]&&(pe[a].remove(st[o]),delete st[o]),T.bind(this)("csr-cancel",{id:o,service:t,owner:r},{auth:n})}function fs(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,i=t?.onStream,s=t?.onResponse,o=t?.onError,a={stopped:false,fullId:e,resolve:null},u=null,c={stop:null,aborted:false},g=()=>{te[a.fullId]===c&&delete te[a.fullId];},f=()=>{a.stopped||(a.stopped=true,u&&u(),g(),a.resolve&&a.resolve(ot(a.fullId)));};c.stop=f;let d=new Promise(async(p,y)=>{a.resolve=p;try{await this.__connection;let h=!!this.__user,_=t?.service||this.service,w=t?.owner||this.owner;if(a.fullId=ss(e,t?.url,t?.method,_),a.stopped){p(ot(a.fullId));return}te[a.fullId]=c;let b={seq:n},E=0,R=rs.call(this,a.fullId),k=i&&t?.realtimeGroup?ts(b,i,R.onTransport):null,U=k?ns.call(this,t.realtimeGroup,k):null,D=()=>{R.done(k),U&&U.stop(),k&&k.close();};for(u=D;;){let x=await T.bind(this)("csr-poll",{id:a.fullId,service:_,owner:w,since:b.seq},{auth:h});if(a.stopped)return;if(!Na(x)){D(),g(),s&&s(x),p(x);return}let v=k?k.fromPoll(x):Zi(x,b,i);k&&k.open();let C=is(x);if(x.more&&v){E=0;continue}if(E=x.more?E+1:0,!C&&(!x.more||E>=Xi)){D(),g(),s&&s(x),p(x);return}if(await new Promise(L=>setTimeout(L,k&&k.warm()?Math.max(r,es):r)),a.stopped)return}}catch(h){if(a.stopped)return;u&&u(),g(),o&&o(h),y(h);}});return Object.assign(d,{stop:f})}async function gs(e,t,r){await this.__connection;let n=r?.service||this.service,i=r?.owner||this.owner,s=!!this.__user,o=ss(e,r?.url,r?.method,n);return T.bind(this)("csr-finalize",{id:o,data:t,service:n,owner:i},{auth:s})}async function ps(e){await this.__connection;let t={name:"string",email:r=>(m.Email(r),r),subject:"string",message:"string"};return e=m.Params(e,t,["name","email","subject","message"]),await T.bind(this)("send-inquiry",e),"SUCCESS: Inquiry has been sent."}async function hs(e,t){if(await this.__connection,Qi&&e instanceof FormData||zi&&e instanceof HTMLFormElement||Ji&&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=j(e);e={url:t,data:n.data,sync:true};}let r={url:n=>m.Url(n),data:n=>n,sync:["boolean",()=>true]};if(Array.isArray(e))for(let n of e)n=m.Params(n,r);else e=m.Params(e,r);return T.bind(this)("post-secure",e,{auth:true})}async function ms(e,t){await this.__connection;let{auth:r=false,method:n="POST",bypassAwaitConnection:i=false,responseType:s,contentType:o,tokenHeaders:a,progress:u}=t||{};if(t=Object.assign({auth:r,method:n,bypassAwaitConnection:i,responseType:s,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 T.bind(this)("mock",e,t)}async function ys(e,t){if(await this.__connection,!t?.url||typeof t.url!="string")throw new l('"url" is required in the second argument.',{code:"INVALID_PARAMETER"});m.Url(t.url);let n=(await this.admin_endpoint)?.forward_request;if(!n)throw new l("forwardRequest is not available on this service region yet.",{code:"NOT_EXISTS"});let i=null,s=null,o=Ji&&e instanceof SubmitEvent?e.target:zi&&e instanceof HTMLFormElement?e:null;o?i=new FormData(o):Qi&&e instanceof FormData?i=e:e!=null&&(i=JSON.stringify(e),s="application/json");let a={public_identifier:this.__public_identifier,service:this.service,owner:this.owner,forward:{url:t.url,method:t.method||"POST",headers:t.headers||{},apiKeyHeader:t.apiKeyHeader,apiKeyScheme:t.apiKeyScheme}},u=JSON.stringify(a).replace(/[\u007f-\uffff]/g,p=>"\\u"+p.charCodeAt(0).toString(16).padStart(4,"0"));if(u.length>4096)throw new l("Destination url and headers are too large for Content-Meta.",{code:"INVALID_PARAMETER"});let c=this.bearerToken||this.session?.idToken?.jwtToken||null;if(!c)throw new l("User login is required.",{code:"INVALID_REQUEST"});let g={"Content-Meta":u,Authorization:c};s&&(g["Content-Type"]=s);let f=await fetch(n,{method:"POST",headers:g,body:i,signal:t.signal});if(t.responseType==="response")return f;if(!f.ok){let p=await f.text();try{p=JSON.parse(p);}catch{}throw new l(p?.message||(typeof p=="string"?p:JSON.stringify(p)),{code:p?.code||"ERROR"})}if(t.onStream&&f.body){let p=f.body.getReader(),y=new TextDecoder,h="";for(;;){let{done:_,value:w}=await p.read();if(_)break;let b=y.decode(w,{stream:true});h+=b;try{t.onStream(b);}catch(E){console.error(E);}}return h}let d=await f.text();if(t.responseType==="text")return d;try{return JSON.parse(d)}catch{return d}}async function bs(e,t){await this.__connection,e=m.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 T.bind(this)("get-feed",e,{auth:true,fetchOptions:t});for(let n in r.list)r.list[n]=await Se.bind(this)(r.list[n]);return r}function at(e){if(e===this.__user.user_id)throw new l(`"user_id" cannot be the user's own ID.`,{code:"INVALID_PARAMETER"});return m.UserId(e,'"user_id"')}async function _s(e,t){if(e=j(e,{ignoreEmpty:true}).data,e=m.Params(e,{subscriber:n=>m.UserId(n,'User ID in "subscriber"'),subscription:at.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 T.bind(this)("get-subscription",e,Object.assign({auth:true},{fetchOptions:t}));return r.list=r.list.map((n=>{let i={};if(n.sub){let s=n.sub.split("#");i.subscriber=s[2],i.subscription=s[0];}else i.subscriber=n.subscriber,i.subscription=n.subscription;return i.timestamp=n?.timestamp||n.stmp,i.blocked=n?.blocked||n.grp.substring(0,1)==="N",Object.assign(i,n.opt),i})),r}async function ws(e){await this.__connection,e=m.Params(e,{user_id:at.bind(this),get_feed:["boolean",()=>false],get_notified:["boolean",()=>false],get_email:n=>{if(n&&!this.__user.email||!this.__user.email_verified)throw new l("User has no verified email address.",{code:"INVALID_REQUEST"});return !!n}},["user_id"]);let t=await T.bind(this)("subscription",{subscribe:e.user_id,option:{get_feed:e.get_feed,get_notified:e.get_notified,get_email:e.get_email||false}},{auth:true}),r={};if(t.sub){let n=t.sub.split("#");r.subscriber=n[2],r.subscription=n[0];}else r.subscriber=t.subscriber,r.subscription=t.subscription;return r.timestamp=t?.timestamp||t.stmp,r.blocked=t?.blocked||t.grp.substring(0,1)==="N",Object.assign(r,t.opt),r}async function Es(e){await this.__connection;let{user_id:t}=m.Params(e,{user_id:at.bind(this)},["user_id"]);return await T.bind(this)("subscription",{unsubscribe:t},{auth:true})}async function As(e){await this.__connection;let{user_id:t}=m.Params(e,{user_id:at.bind(this)},["user_id"]);return await T.bind(this)("subscription",{block:t},{auth:true})}async function Rs(e){await this.__connection;let{user_id:t}=m.Params(e,{user_id:at.bind(this)},["user_id"]);return await T.bind(this)("subscription",{unblock:t},{auth:true})}async function Is(e,t){await this.__connection;let r=await W.bind(this)();e=m.Params(e||{},{user_id:o=>{if(o!==this.__user.user_id&&!r)throw new l("No access.",{code:"INVALID_REQUEST"});return o},group:o=>m.newsletterGroup(o,{allowNull:true})});let n=await T.bind(this)("get-newsletter-subscription",e,{auth:true,fetchOptions:t||null}),i=n?.list||n,s=[];Array.isArray(i)||(i=[]);for(let o of i){let 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];s.push({timestamp:o.stmp,group:c,subscribed_email:a[1],active:u});}return n?.list?(n.list=s,n):s}async function Ts(e){await this.__connection;let t=m.Params(e||{},{email:r=>Array.isArray(r)&&r.length>0?r.length===1?m.Email(r[0]):r.map(n=>m.Email(n)):m.Email(r),group:r=>m.newsletterGroup(r),redirect:r=>m.Url(r)},this.__user?["group"]:["email","group"]);return T.bind(this)(`subscribe-${this.__user?"":"public-"}newsletter`,t,{auth:!!this.__user})}async function Ps(e){await this.__connection;let t=m.Params(e||{},{group:r=>m.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 T.bind(this)("register-newsletter-group",t,{auth:true})}async function Ss(e){await this.__connection;let t=m.Params(e||{},{group:r=>m.newsletterGroup(r,{nameOnly:true})},["group"]);return T.bind(this)("delete-newsletter-group",t,{auth:true})}async function ks(){return await this.__connection,T.bind(this)("newsletter-group-endpoint",null,{auth:true})}async function vs(e){await this.__connection,e=m.Params(e,{group:r=>m.newsletterGroup(r,{allowNull:true})},["group"]);let t=Object.assign({action:"unsubscribe"},e);return T.bind(this)("subscribe-newsletter",t,{auth:true})}async function Ns(e,t){let r=await W.bind(this)(),n={message_id:"string",timestamp:"number",read:"number",complaint:"number",subject:"string",bounced:"number"};e||(t=Object.assign({ascending:false},t||{})),e=j(e).data,e=e||{searchFor:"timestamp",value:Date.now(),condition:"<",group:"public"},e=m.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=m.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 i=e.group===0||typeof e.group=="string"&&!this.__user?"get-public-newsletters":"get-newsletters",s=await T.bind(this)(i,e,Object.assign({method:"get",auth:i==="get-public-newsletters"?!!this.__user:true},{fetchOptions:t})),o={message_id:"mid",timestamp:"stmp",complaint:"cmpl",read:"read",subject:"subj",bounced:"bnce",url:"url",delivered:"delv",group:"grp"},a={message_id:"",timestamp:0,complaint:0,read:0,subject:"",bounced:"",url:"",delivered:0,group:e.group};return s.list=s.list.map(u=>{let c={};for(let g in o)c[g]=u[o[g]]||a[g];return c.bounced=String(c.bounced),c}),s}async function Us(e){let t=m.Params(e,{user_id:n=>m.UserId(n,'"user_id"')},["user_id"]);if(t?.service&&t?.owner?t={service:t?.service,owner:t?.owner,block:t.user_id}:t={block:t.user_id},!await W.bind(this)()){if(!this.__user)throw new l("User needs to login.",{code:"INVALID_REQUEST"});if(this.__user.access_group<90)throw new l("Invalid access.",{code:"INVALID_REQUEST"})}return await T.bind(this)("block-account",t,{auth:true})}async function Ds(e){let t=m.Params(e,{user_id:n=>m.UserId(n,'"user_id"')},["user_id"]);if(t?.service&&t?.owner?t={service:t?.service,owner:t?.owner,unblock:t.user_id}:t={unblock:t.user_id},!await W.bind(this)()){if(!this.__user)throw new l("User needs to login.",{code:"INVALID_REQUEST"});if(this.__user.access_group<90)throw new l("Invalid access.",{code:"INVALID_REQUEST"})}return await T.bind(this)("block-account",t,{auth:true})}async function xs(e){let t=m.Params(e,{user_id:n=>m.UserId(n,'"user_id"')},["user_id"]);if(t?.service&&t?.owner?t={service:t?.service,owner:t?.owner,delete:t.user_id}:t={delete:t.user_id},!await W.bind(this)()){if(!this.__user)throw new l("User needs to login.",{code:"INVALID_REQUEST"});if(this.__user.access_group<90)throw new l("Invalid access.",{code:"INVALID_REQUEST"})}return await T.bind(this)("remove-account",t,{auth:true})}async function Cs(e,t){let r={email:s=>m.Email(s),password:s=>m.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=>m.Birthdate(s),phone_number:s=>m.PhoneNumber(s),picture:s=>{if(s)return m.Url(s)},profile:s=>{if(s)return m.Url(s)},website:s=>{if(s)return m.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 l('"access_group" is invalid. Should be type <number>.',{code:"INVALID_PARAMETER"})}if(typeof s!="number"||s<1||s>100)throw new l('"access_group" is invalid. Should be type <number> of range 1~99',{code:"INVALID_PARAMETER"});return s}},n=m.Params(e,r,["email"]);if(t=m.Params(t,{confirmation_url:s=>{let o=s;if(typeof s=="string")o=m.Url(s);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:s=>{if(typeof s!="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 s},template:s=>{if(typeof s!="object"||!s.url||!s.subject)throw new l('"options.template" should be type: <object> with "url" and "subject".',{code:"INVALID_PARAMETER"});return {url:m.Url(s.url),subject:s.subject}}}),n.signup_confirmation=t?.confirmation_url||true,n.email_subscription=t?.email_subscription||false,n.template=t?.template||{},!await W.bind(this)()){if(!this.__user)throw new l("User needs to login.",{code:"INVALID_REQUEST"});if(this.__user.access_group<90)throw new l("Invalid access.",{code:"INVALID_REQUEST"})}return await T.bind(this)("admin-signup",n,{auth:true})}async function Ls(e){let t={email:s=>m.Email(s),password:s=>m.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=>m.Birthdate(s),phone_number:s=>m.PhoneNumber(s),picture:s=>s?m.Url(s):"",profile:s=>s?m.Url(s):"",website:s=>s?m.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 l('"access_group" is invalid. Should be type <number>.',{code:"INVALID_PARAMETER"})}if(typeof s!="number"||s<1||s>100)throw new l('"access_group" is invalid. Should be type <number> of range 1~99',{code:"INVALID_PARAMETER"});return s}},r=["email","password"],n=m.Params(e,t,r);if(!await W.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 T.bind(this)("admin-signup",n,{auth:true})}async function Os(e){if(e=m.Params(e,{user_id:r=>m.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 W.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 T.bind(this)("grant-access",e,{auth:true})}async function Ms(e,t){if(e=m.Params(e,{email:"string"}),!await W.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 T.bind(this)("invitation-list",Object.assign({mode:"search"},e),{fetchOptions:t,auth:true});return n.list=n.list.map(i=>$e(i.user)),n}async function Fs(e){if(e=m.Params(e,{email:r=>m.Email(r)},["email"]),!await W.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 T.bind(this)("invitation-list",Object.assign({mode:"cancel"},e),{auth:true})}async function qs(e){if(e=m.Params(e,{email:r=>m.Email(r)},["email"]),!await W.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 T.bind(this)("invitation-list",Object.assign({mode:"resend"},e),{auth:true})}async function Vs(e){let t=m.Params(e,{user_id:o=>m.UserId(o,'"user_id"'),email:o=>m.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?m.Birthdate(o):"",phone_number:o=>o?m.PhoneNumber(o):"",email_public:"boolean",phone_number_public:"boolean",address_public:"boolean",gender_public:"boolean",birthdate_public:"boolean",misc:"string",picture:o=>o?m.Url(o):"",profile:o=>o?m.Url(o):"",nickname:"string",website:o=>o?m.Url(o):""},["user_id"]),r=t.service,n=t.owner;if(delete t.service,delete t.owner,Object.keys(t).filter(o=>o!=="user_id"&&t[o]!==void 0).length===0)throw new l("At least one attribute to update is required.",{code:"INVALID_PARAMETER"});if(!await W.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"})}t.email&&(t.preferred_username=(r||this.service)+"-"+G.hash(t.email));let s={attributes:t};return r&&n&&(s.service=r,s.owner=n),await T.bind(this)("admin-edit-profile",s,{auth:true})}async function $s(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 T.bind(this)("store-subscription",{endpoint:e.endpoint,keys:e.keys},{auth:true}),"SUCCESS: Subscribed to receive notifications."}async function js(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 T.bind(this)("delete-subscription",{endpoint:e.endpoint,keys:e.keys},{auth:true}),"SUCCESS: Unsubscribed from notifications."}async function Bs(){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 T.bind(this)("get-vapid-public-key",null,{auth:true})}}async function Ks(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}=j(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 i={title:r,body:n};return t?(typeof t=="string"&&(t=[t]),i.user_ids=t):i.user_ids="all_users",await T.bind(this)("push-notification",i,{auth:true}),"SUCCESS: Notification sent."}async function Hs(e){await this.__connection,e=m.Params(e,{spell:"string",name:"string",magic:r=>r},["spell","name"]);await T.bind(this)("castspell",e);return `The spell "${e.spell}" has been cast.`}async function Gs(e){return await this.__connection,e=m.Params(e||{},{search:["spell","name",()=>"spell"],value:"string"}),await T.bind(this)("getspell",e)}async function Ws(e){await this.__connection,e=m.Params(e,{message:"string",name:"string"},["message","name"]);let t=await T.bind(this)("dopamine",e,{auth:true}),r=t?.previous_message?.message,n=t?.previous_message?.name;if(Y())r&&n&&window.alert(`${n} said: ${r}`),window.location.href=t.video;else return r&&n?`${n} said: ${r}
|
|
216
216
|
Watch the video here: ${t.video}`:`Your message has been uploaded for future generations to receive.
|
|
217
|
-
Watch the video here: ${t.video}`}var I=class{constructor(t,r,n,i){this.__version="2.0.
|
|
217
|
+
Watch the video here: ${t.video}`}var I=class{constructor(t,r,n,i){this.__version="2.0.2";this.project_id="";this.session=null;this.connection=null;this.__my_unique_ids={};this.__uniqueIdsPersistTimer=null;this.userPool=null;this.__socket=null;this.__mediaStream=null;this.host="skapi";this.hostDomain="skapi.com";this.target_cdn="d3e9syvbtso631";this.customApiDomain="skapi.dev";this.requestBatchSize=30;this.__disabledAccount=null;this.__cached_requests={};this.__startKeyHistory={};this.__request_signup_confirmation=null;this.__private_access_key={};this.__class_properties_has_been_cached=false;this.__user=null;this._userProfileListeners=[];this._onLoginListeners=[];this._onBatchProcessListeners=[];this.validate={userId(t){try{return m.UserId(t),!0}catch{return false}},url(t){try{return m.Url(t),!0}catch{return false}},phoneNumber(t){try{return m.PhoneNumber(t),!0}catch{return false}},birthdate(t){try{return m.Birthdate(t),!0}catch{return false}},email(t){try{return m.Email(t),!0}catch{return false}},params(t,r,n){return m.Params(t,r,n)}};this.util={MD5:G,generateRandom:Re,toBase62:Mr,fromBase62:se,decodeProjectId:Vt,formatServiceId:$t,extractFormData:j,terminatePendingRequests:di,request:(t,r,n)=>T.bind(this)(t,r,n,{ignoreService:true})};this.__network_logs=false;this.__endpoint_version="v2";this.__public_identifier="";this.bearerToken="";this.registerTicket=Bn.bind(this);this.unregisterTicket=Kn.bind(this);if(!t||typeof t!="string")throw this._alert("Service ID is required."),new l("Service ID is required.",{code:"INVALID_PARAMETER"});let s=t.trim().toLowerCase().replace(/^<|>$/g,"").replace(/[\s_\-.]+/g,"");if(s==="serviceid"||s==="projectid")throw this._alert(`Replace "${t}" with your actual Project ID.`),new l("Project ID is required.",{code:"INVALID_PARAMETER"});let o=t.split("-").length;if(o===2||o===7)try{let b=Vt(t);n&&typeof n=="object"&&(i=n),r&&typeof r=="object"&&(n=r),r=b.owner,t=b.service;}catch{throw this._alert("Service ID is invalid."),new l("Service ID is invalid.",{code:"INVALID_PARAMETER"})}if(!r||typeof r!="string")throw this._alert("Owner ID is invalid."),new l("Owner ID is invalid.",{code:"INVALID_PARAMETER"});if(r!==this.host)try{m.UserId(r,'"owner"');}catch{throw this._alert("Owner ID is invalid."),new l("Owner ID is invalid.",{code:"INVALID_PARAMETER"})}this.service=t,this.owner=r;try{this.project_id=$t(t,r);}catch{this.project_id="";}let c=true,g=false,f=null;if(n&&(typeof n.refetchServiceInfo=="boolean"&&(g=n.refetchServiceInfo),typeof n.autoLogin=="boolean"&&(c=n.autoLogin),n.encryption&&(f=an(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=i?.target_cdn||this.target_cdn,this.hostDomain=i?.hostDomain||this.hostDomain,this.customApiDomain=i?.customApiDomain||this.customApiDomain,this.__network_logs=!!i?.network_logs;let d=`https://${this.target_cdn}.cloudfront.net`,p=t.substring(0,4);this.admin_endpoint=fetch(`${d}/${p}/admin-${this.__endpoint_version}.json`).then(b=>b.blob()).then(b=>new Promise((E,R)=>{let k=new FileReader;k.onloadend=()=>E(k.result),k.onerror=R,k.readAsDataURL(b);})).then(b=>{try{return typeof b=="string"?JSON.parse(atob(b.split(",")[1])):null}catch{throw new l("Service does not exist. Create your service from skapi.com",{code:"NOT_EXISTS"})}}),this.record_endpoint=fetch(`${d}/${p}/record-${this.__endpoint_version}.json`).then(b=>b.blob()).then(b=>new Promise((E,R)=>{let k=new FileReader;k.onloadend=()=>E(k.result),k.onerror=R,k.readAsDataURL(b);})).then(b=>{try{return typeof b=="string"?JSON.parse(atob(b.split(",")[1])):null}catch{throw new l("Service does not exist. Create your service from skapi.com",{code:"NOT_EXISTS"})}});let y=Y();if(y&&!window.sessionStorage)throw this._alert("This browser is not supported."),new Error("This browser is not supported.");let h=y?JSON.parse(window.sessionStorage.getItem(`${t}#${r}`)||"null"):null;if(this.log("constructor:restore",h),h?.connection){for(let b in h)this[b]=h[b];h.__public_identifier||(this.__public_identifier=`${this.service}:${this.owner}:${Re(16)}`);}ln.bind(this)(f),this.__authConnection=(async()=>{let b=await this.admin_endpoint,E={UserPoolId:b.userpool_id,ClientId:b.userpool_client};qt()&&(E.Storage=window.localStorage),this.userPool=new CognitoUserPool(E);try{this.user||await J.bind(this)().getSession({skipUserUpdateEventTrigger:!0}),this.user&&(!h?.connection&&!c?ye.bind(this)():(f&&Sn.bind(this)(),this._runOnLoginListeners(this.user),this._runOnUserUpdateListeners(this.user)));}catch{}})();let _=`${this.service}/${this.owner}`,w=y?window.sessionStorage.getItem(`${_}:uniqueids`):null;if(w)try{let b=JSON.parse(w);this.__my_unique_ids=b&&typeof b=="object"&&!Array.isArray(b)?{[_]:b}:{};}catch{this.__my_unique_ids={};}this.__connection=(async()=>{let b=null;await this.record_endpoint,h?.connection||(b=this._updateConnection({refresh:g}));let E=()=>{if(this.__class_properties_has_been_cached)return;let R=()=>{let k={},U=["__startKeyHistory","__disabledAccount","__cached_requests","__request_signup_confirmation","__public_identifier","connection"];if(this.connection){for(let D of U)k[D]=this[D];if(f&&(k.__cached_requests={},k.__startKeyHistory={}),y){let D=`${t}#${r}`;try{window.sessionStorage.setItem(D,JSON.stringify(k));}catch{try{let v=Object.assign({},k,{__cached_requests:{},__startKeyHistory:{}});window.sessionStorage.setItem(D,JSON.stringify(v));}catch{try{window.sessionStorage.removeItem(D);}catch{}}}}this.__class_properties_has_been_cached=true;}};return b instanceof Promise?b.then(()=>R()):R()};return y&&(window.addEventListener("beforeunload",()=>{this.closeRealtime(),E();}),window.addEventListener("visibilitychange",()=>{E();})),await b,await this.__authConnection,this.connection})(),this.__connection.then(b=>{((b?.group||0)<3||this.__network_logs)&&this.version();}).catch(()=>{});}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){Y()&&typeof window.alert=="function"&&window.alert(t);}async getConnectionInfo(t){t?.refresh&&(this.__connection instanceof Promise&&await this.__connection,this.__connection=this._updateConnection({refresh:true}));let n=await this.__connection,i=n?.user_agent||(Y()&&typeof window.navigator?.userAgent=="string"?window.navigator.userAgent:`skapi-node/${globalThis?.process?.versions?.node||"unknown"}`);return {project_id:this.project_id,user_ip:n.ip,user_agent:i,user_location:n.locale,service_name:n.service_name,version:this.__version,service_description:n?.service_description||"",ai_agent:n?.ai_agent||"",conf:n?.opt}}async _updateConnection(t){let r=t?.refresh||false;try{this.connection=await T.bind(this)("service",{service:this.service,owner:this.owner,refresh:r},{bypassAwaitConnection:!0,method:"get"});}catch(n){throw this.log("connection fail",n),this._alert("Service is not available: "+(n.message||n.toString())),this.connection=null,n}return this.connection}async version(){if(await this.__connection,Y()){let r=`Built with:
|
|
218
218
|
%c\r
|
|
219
219
|
$$\\ $$\\ \r
|
|
220
220
|
$$ | \\__|\r
|
|
@@ -229,6 +229,6 @@ $$$$$$$ |$$ | \\$$\\\\$$$$$$$ |$$$$$$$ |$$ |\r
|
|
|
229
229
|
\\__| \r
|
|
230
230
|
Version: ${this.__version}
|
|
231
231
|
|
|
232
|
-
Full Documentation: https://docs.skapi.com/skapi.md`;console.log(r,"font-family: monospace; color:blue;"),this.connection.group===1&&console.log("%cSKAPI: THE SERVICE IS IN TRIAL MODE.","font-family: monospace; color:red;");}return this.__version}log(t,r){if(this.__network_logs){if(r!==null&&typeof r=="object")try{Y()?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
|
|
233
|
-
export{I as Skapi,l as SkapiError,
|
|
232
|
+
Full Documentation: https://docs.skapi.com/skapi.md`;console.log(r,"font-family: monospace; color:blue;"),this.connection.group===1&&console.log("%cSKAPI: THE SERVICE IS IN TRIAL MODE.","font-family: monospace; color:red;");}return this.__version}log(t,r){if(this.__network_logs){if(r!==null&&typeof r=="object")try{Y()?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 bs.bind(this)(t,r)}closeRTC(t){return ue.bind(this)(t)}connectRTC(t,r){return qi.bind(this)(t,r)}connectRealtime(t){return Fe.bind(this)(t)}spellcast(t){return Hs.bind(this)(t)}getspell(t){return Gs.bind(this)(t)}dopamine(t){return Ws.bind(this)(t)}getUniqueId(t,r){return Ni.bind(this)(t,r)}resendInvitation(t){return qs.bind(this)(t)}cancelInvitation(t){return Fs.bind(this)(t)}getInvitations(t,r){return Ms.bind(this)(t,r)}openIdLogin(t){return Gn.bind(this)(t)}loginWithToken(t){return Wn.bind(this)(t)}registerNewsletterGroup(t){return Ps.bind(this)(t)}deleteNewsletterGroup(t){return Ss.bind(this)(t)}clientSecretRequest(t){return cs.bind(this)(t)}clientSecretRequestHistory(t,r){return us.bind(this)(t,r)}clientSecretRequestStream(t,r){return fs.bind(this)(t,r)}clientSecretRequestFinalize(t,r,n){return gs.bind(this)(t,r,n)}cancelClientSecretRequest(t){return ds.bind(this)(t)}stopClientSecretPolling(t){return as.bind(this)(t||{})}isPollStopped(t){return Yi(t)}clientSecretRequestQueueCount(t){return ls.bind(this)(t)}consumeTicket(t){return Vn.bind(this)(t)}getConsumedTickets(t,r){return jn.bind(this)(t,r)}getTickets(t,r){return $n.bind(this)(t,r)}closeRealtime(){return Ut.bind(this)()}getRealtimeUsers(t,r){return Hi.bind(this)(t,r)}sendInquiry(t){return ps.bind(this)(t)}blockAccount(t){return Us.bind(this)(t)}unblockAccount(t){return Ds.bind(this)(t)}deleteAccount(t){return xs.bind(this)(t)}inviteUser(t,r){return Cs.bind(this)(t,r)}createAccount(t){return Ls.bind(this)(t)}grantAccess(t){return Os.bind(this)(t)}updateUserAttributes(t){return Vs.bind(this)(t)}getRealtimeGroups(t,r){return Gi.bind(this)(t,r)}newsletterGroupEndpoint(){return ks.bind(this)()}postRealtime(t,r,n){return Ki.bind(this)(t,r,n)}joinRealtime(t){return qe.bind(this)(t)}getProfile(t){return Hn.bind(this)(t)}getFile(t,r){return Pe.bind(this)(t,r)}secureRequest(t,r){return hs.bind(this)(t,r)}forwardRequest(t,r){return ys.bind(this)(t,r)}getFormResponse(){return gi.bind(this)()}getRecords(t,r){return Ii.bind(this)(t,r)}getTables(t,r){return Si.bind(this)(t,r)}getIndexes(t,r){return ki.bind(this)(t,r)}getTags(t,r){return vi.bind(this)(t,r)}deleteRecords(t,r){return Ui.bind(this)(t,r)}resendSignupConfirmation(){return Qn.bind(this)()}recoverAccount(t=false){return zn.bind(this)(t)}getUsers(t,r){return si.bind(this)(t,r)}disableAccount(){return Yn.bind(this)()}lastVerifiedEmail(t){return oi.bind(this)(t)}unsubscribeNewsletter(t){return vs.bind(this)(t)}subscribeNotification(t,r){return $s.bind(this)({endpoint:t,keys:r})}unsubscribeNotification(t,r){return js.bind(this)({endpoint:t,keys:r})}vapidPublicKey(){return Bs.bind(this)()}pushNotification(t,r){return Ks.bind(this)(t,r)}getNewsletters(t,r){return Ns.bind(this)(t,r)}getNewsletterSubscription(t,r){return Is.bind(this)(t,r)}requestUsernameChange(t){return ai.bind(this)(t)}getEncryptionStatus(){return cn.bind(this)()}isWithheld(t){return tr.call(this,t)}unlockEncryption(t){return An.bind(this)(t)}lockEncryption(t){return Rn.bind(this)(t)}takeRecoveryCode(){return Dn.bind(this)()}unlockWithRecoveryCode(t){return xn.bind(this)(t)}regenerateRecoveryCode(){return Cn.bind(this)()}pinPeerKey(t){return Nn.bind(this)(t)}grantPrivateRecordAccess(t){return Di.bind(this)(t)}removePrivateRecordAccess(t){return xi.bind(this)(t)}listPrivateRecordAccess(t,r){return Ci.bind(this)(t,r)}requestPrivateRecordAccessKey(t){return Li.bind(this)(t)}deleteFiles(t){return wi.bind(this)(t)}uploadFiles(t,r){return tt.bind(this)(t,r)}mock(t,r){return ms.bind(this)(t,r)}login(t){return hr.bind(this)(t)}logout(t){return Xe.bind(this)(t)}signup(t,r){return Jn.bind(this)(t,r)}resetPassword(t){return Xn.bind(this)(t)}verifyEmail(t,r){return ti.bind(this)(t,r)}verifyPhoneNumber(t,r){return ei.bind(this)(t,r)}forgotPassword(t,r){return ri.bind(this)(t,r)}changePassword(t){return ni.bind(this)(t)}updateProfile(t){return ii.bind(this)(t)}postRecord(t,r,n){return Ar.bind(this)(t,r,n)}getSubscriptions(t,r){return _s.bind(this)(t,r)}subscribe(t){return ws.bind(this)(t)}unsubscribe(t){return Es.bind(this)(t)}blockSubscriber(t){return As.bind(this)(t)}unblockSubscriber(t){return Rs.bind(this)(t)}subscribeNewsletter(t){return Ts.bind(this)(t)}bulkPostRecords(t){return Pi.bind(this)(t)}};P([S()],I.prototype,"getFeed"),P([S()],I.prototype,"closeRTC"),P([S()],I.prototype,"connectRTC"),P([S()],I.prototype,"spellcast"),P([S()],I.prototype,"getspell"),P([S()],I.prototype,"dopamine"),P([S()],I.prototype,"getUniqueId"),P([S()],I.prototype,"resendInvitation"),P([S()],I.prototype,"cancelInvitation"),P([S()],I.prototype,"getInvitations"),P([S()],I.prototype,"openIdLogin"),P([S()],I.prototype,"loginWithToken"),P([S()],I.prototype,"registerNewsletterGroup"),P([S()],I.prototype,"deleteNewsletterGroup"),P([S()],I.prototype,"clientSecretRequest"),P([S()],I.prototype,"clientSecretRequestHistory"),P([S()],I.prototype,"cancelClientSecretRequest"),P([S()],I.prototype,"consumeTicket"),P([S()],I.prototype,"getConsumedTickets"),P([S()],I.prototype,"getTickets"),P([S()],I.prototype,"getRealtimeUsers"),P([S()],I.prototype,"sendInquiry"),P([S()],I.prototype,"blockAccount"),P([S()],I.prototype,"unblockAccount"),P([S()],I.prototype,"deleteAccount"),P([S()],I.prototype,"inviteUser"),P([S()],I.prototype,"createAccount"),P([S()],I.prototype,"grantAccess"),P([S()],I.prototype,"updateUserAttributes"),P([S()],I.prototype,"getRealtimeGroups"),P([S()],I.prototype,"newsletterGroupEndpoint"),P([S()],I.prototype,"postRealtime"),P([S()],I.prototype,"joinRealtime"),P([S()],I.prototype,"getProfile"),P([S()],I.prototype,"getFile"),P([S()],I.prototype,"secureRequest"),P([S()],I.prototype,"forwardRequest"),P([S()],I.prototype,"getFormResponse"),P([S()],I.prototype,"getRecords"),P([S()],I.prototype,"getTables"),P([S()],I.prototype,"getIndexes"),P([S()],I.prototype,"getTags"),P([S()],I.prototype,"deleteRecords"),P([S()],I.prototype,"resendSignupConfirmation"),P([S()],I.prototype,"recoverAccount"),P([S()],I.prototype,"getUsers"),P([S()],I.prototype,"disableAccount"),P([S()],I.prototype,"lastVerifiedEmail"),P([S()],I.prototype,"unsubscribeNewsletter"),P([S()],I.prototype,"subscribeNotification"),P([S()],I.prototype,"unsubscribeNotification"),P([S()],I.prototype,"vapidPublicKey"),P([S()],I.prototype,"pushNotification"),P([S()],I.prototype,"getNewsletters"),P([S()],I.prototype,"getNewsletterSubscription"),P([S()],I.prototype,"requestUsernameChange"),P([S()],I.prototype,"unlockEncryption"),P([S()],I.prototype,"unlockWithRecoveryCode"),P([S()],I.prototype,"grantPrivateRecordAccess"),P([S()],I.prototype,"removePrivateRecordAccess"),P([S()],I.prototype,"listPrivateRecordAccess"),P([S()],I.prototype,"requestPrivateRecordAccessKey"),P([S()],I.prototype,"deleteFiles"),P([S()],I.prototype,"uploadFiles"),P([S()],I.prototype,"mock"),P([S({preventMultipleCalls:true})],I.prototype,"login"),P([S()],I.prototype,"logout"),P([S({preventMultipleCalls:true})],I.prototype,"signup"),P([S({preventMultipleCalls:true})],I.prototype,"resetPassword"),P([S({preventMultipleCalls:true})],I.prototype,"verifyEmail"),P([S({preventMultipleCalls:true})],I.prototype,"verifyPhoneNumber"),P([S({preventMultipleCalls:true})],I.prototype,"forgotPassword"),P([S({preventMultipleCalls:true})],I.prototype,"changePassword"),P([S({preventMultipleCalls:true})],I.prototype,"updateProfile"),P([S()],I.prototype,"postRecord"),P([S()],I.prototype,"getSubscriptions"),P([S()],I.prototype,"subscribe"),P([S()],I.prototype,"unsubscribe"),P([S()],I.prototype,"blockSubscriber"),P([S()],I.prototype,"unblockSubscriber"),P([S()],I.prototype,"subscribeNewsletter");var Da={};
|
|
233
|
+
export{I as Skapi,l as SkapiError,Da as Types};//# sourceMappingURL=skapi.mjs.map
|
|
234
234
|
//# sourceMappingURL=skapi.mjs.map
|