skapi-js 2.2.1 → 2.2.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 +2 -2
- package/dist/skapi.browser.mjs.map +1 -1
- package/dist/skapi.cjs +2 -2
- package/dist/skapi.cjs.map +1 -1
- package/dist/skapi.js +2 -2
- package/dist/skapi.js.map +1 -1
- package/dist/skapi.mjs +2 -2
- package/dist/skapi.mjs.map +1 -1
- package/package.json +1 -1
package/dist/skapi.mjs
CHANGED
|
@@ -203,7 +203,7 @@ import {CognitoUserPool,AuthenticationDetails,CognitoUserSession,CognitoRefreshT
|
|
|
203
203
|
limitations under the License.
|
|
204
204
|
|
|
205
205
|
*/
|
|
206
|
-
var _o=Object.defineProperty;var wo=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 T=(e,t,r,n)=>{for(var i=wo(t,r),s=e.length-1,o;s>=0;s--)(o=e[s])&&(i=(o(t,r,i))||i);return i&&_o(t,r,i),i};function ve(e){let r=(typeof globalThis<"u"?globalThis:void 0)?.process;if(r&&typeof r.getBuiltinModule=="function")try{return r.getBuiltinModule(e)}catch{}try{if(typeof ke=="function")return ke(e)}catch{}return null}var Bt,Kt,Ht=()=>Bt!==void 0?Bt:Bt=ve("fs"),Gt=()=>Kt!==void 0?Kt:Kt=ve("path"),me=typeof globalThis<"u"?globalThis:void 0,pt=me?.window;function Eo(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(pt)pt.global=pt,pt.global._runningInNodeJS=false;else if(me&&(me.global=me,typeof me.window>"u")){class e{constructor(){this.result=null;this.error=null;this.onload=null;this.onloadend=null;this.onerror=null;}readAsDataURL(n){n.arrayBuffer().then(i=>{let s=Eo(i),o=n.type||"application/octet-stream";this.result=`data:${o};base64,${s}`,this.onload&&this.onload({target:this}),this.onloadend&&this.onloadend({target:this});}).catch(i=>{this.error=i,this.onerror&&this.onerror({target:this});});}readAsArrayBuffer(n){n.arrayBuffer().then(i=>{this.result=i,this.onload&&this.onload({target:this}),this.onloadend&&this.onloadend({target:this});}).catch(i=>{this.error=i,this.onerror&&this.onerror({target:this});});}readAsText(n,i="utf-8"){n.text().then(s=>{this.result=s,this.onload&&this.onload({target:this}),this.onloadend&&this.onloadend({target:this});}).catch(s=>{this.error=s,this.onerror&&this.onerror({target:this});});}}me.FileReader=e;class t{constructor(){this.status=0;this.statusText="";this.readyState=0;this.responseText="";this.response=null;this.responseType="";this.responseURL="";this.timeout=0;this.withCredentials=false;this.onload=null;this.onerror=null;this.onabort=null;this.ontimeout=null;this.onprogress=null;this.onreadystatechange=null;this.upload={onprogress:null};this._method="GET";this._url="";this._headers={};this._aborted=false;}open(n,i){this._method=n,this._url=i,this.readyState=1;}setRequestHeader(n,i){this._headers[n]=i;}getResponseHeader(n){return null}abort(){this._aborted=true,this.onabort&&this.onabort({});}send(n){if(this._aborted)return;let i={method:this._method,headers:this._headers};n&&this._method!=="GET"&&this._method!=="HEAD"&&(i.body=n),fetch(this._url,i).then(async s=>{if(!this._aborted){if(this.status=s.status,this.statusText=s.statusText,this.responseURL=s.url,this.readyState=4,this.responseType==="blob")this.response=await s.blob();else if(this.responseType==="json")try{this.response=await s.json();}catch{this.response=null;}else this.responseType==="arraybuffer"?this.response=await s.arrayBuffer():(this.responseText=await s.text(),this.response=this.responseText);this.onload&&this.onload({});}}).catch(s=>{this._aborted||this.onerror&&this.onerror(s);});}}me.XMLHttpRequest=t,me.window={_runningInNodeJS:true,alert:r=>console.error("[Alert]",r),sessionStorage:(()=>{let r=new Map;return {getItem:n=>r.has(n)?r.get(n):null,setItem:(n,i)=>{r.set(n,String(i));},removeItem:n=>{r.delete(n);}}})(),localStorage:{getItem:r=>{let n=Ht(),i=Gt();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=Ht(),s=Gt();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=Ht(),i=Gt();if(!(!n||!i))try{let s=i.resolve(process.cwd(),"states","localStorage",`${r}.skapi`);n.existsSync(s)&&n.unlinkSync(s);}catch{}}},location:{href:"",origin:"",hostname:"",protocol:"",replace:r=>{}},navigator:{userAgent:`nodejs/${me?.process?.versions?.node||"unknown"}`,mediaDevices:{getUserMedia:async r=>{throw new Error("getUserMedia is not supported in Node.js environment.")}}},addEventListener:()=>{},removeEventListener:()=>{}};}var 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 ye="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",Wt=BigInt(ye.length),Ao=2*1024*1024,Ro=["aud","cognito:username","event_id","exp","iat","iss","jti","origin_jti","secret_key","token_use"],Hr={auth_time:"log",sub:"user_id"},Jr=["0","1","2","3","4","5","6","7","8","9","a","b","c","d","e","f","g","h","i","j","k","l"],Yr=["us31","us72","ap51","ap22","ap41","eu71","ap21","us32","us71","af51","ap31","ap43","ap23","ap42","ca01","eu01","eu72","eu51","eu73","eu11","me51","sa31"],Gr=typeof TextEncoder<"u"?new TextEncoder:null;function Io(){if(typeof globalThis<"u")return globalThis.Buffer}function K(e){if(Gr)return Gr.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 Qt(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=Io();if(t)return new Uint8Array(t.from(e));throw new Error("No byte conversion available in this environment.")}var R=class R{static hash(t){typeof t!="string"&&(console.warn("coercing non-string value to empty string"),t="");let r=R.sb(t),n=1732584193,i=-271733879,s=-1732584194,o=271733878,a,d,c,g;for(let f=0;f<r.length;f+=16)a=n,d=i,c=s,g=o,n=R.ff(n,i,s,o,r[f],7,-680876936),o=R.ff(o,n,i,s,r[f+1],12,-389564586),s=R.ff(s,o,n,i,r[f+2],17,606105819),i=R.ff(i,s,o,n,r[f+3],22,-1044525330),n=R.ff(n,i,s,o,r[f+4],7,-176418897),o=R.ff(o,n,i,s,r[f+5],12,1200080426),s=R.ff(s,o,n,i,r[f+6],17,-1473231341),i=R.ff(i,s,o,n,r[f+7],22,-45705983),n=R.ff(n,i,s,o,r[f+8],7,1770035416),o=R.ff(o,n,i,s,r[f+9],12,-1958414417),s=R.ff(s,o,n,i,r[f+10],17,-42063),i=R.ff(i,s,o,n,r[f+11],22,-1990404162),n=R.ff(n,i,s,o,r[f+12],7,1804603682),o=R.ff(o,n,i,s,r[f+13],12,-40341101),s=R.ff(s,o,n,i,r[f+14],17,-1502002290),i=R.ff(i,s,o,n,r[f+15],22,1236535329),n=R.gg(n,i,s,o,r[f+1],5,-165796510),o=R.gg(o,n,i,s,r[f+6],9,-1069501632),s=R.gg(s,o,n,i,r[f+11],14,643717713),i=R.gg(i,s,o,n,r[f],20,-373897302),n=R.gg(n,i,s,o,r[f+5],5,-701558691),o=R.gg(o,n,i,s,r[f+10],9,38016083),s=R.gg(s,o,n,i,r[f+15],14,-660478335),i=R.gg(i,s,o,n,r[f+4],20,-405537848),n=R.gg(n,i,s,o,r[f+9],5,568446438),o=R.gg(o,n,i,s,r[f+14],9,-1019803690),s=R.gg(s,o,n,i,r[f+3],14,-187363961),i=R.gg(i,s,o,n,r[f+8],20,1163531501),n=R.gg(n,i,s,o,r[f+13],5,-1444681467),o=R.gg(o,n,i,s,r[f+2],9,-51403784),s=R.gg(s,o,n,i,r[f+7],14,1735328473),i=R.gg(i,s,o,n,r[f+12],20,-1926607734),n=R.hh(n,i,s,o,r[f+5],4,-378558),o=R.hh(o,n,i,s,r[f+8],11,-2022574463),s=R.hh(s,o,n,i,r[f+11],16,1839030562),i=R.hh(i,s,o,n,r[f+14],23,-35309556),n=R.hh(n,i,s,o,r[f+1],4,-1530992060),o=R.hh(o,n,i,s,r[f+4],11,1272893353),s=R.hh(s,o,n,i,r[f+7],16,-155497632),i=R.hh(i,s,o,n,r[f+10],23,-1094730640),n=R.hh(n,i,s,o,r[f+13],4,681279174),o=R.hh(o,n,i,s,r[f],11,-358537222),s=R.hh(s,o,n,i,r[f+3],16,-722521979),i=R.hh(i,s,o,n,r[f+6],23,76029189),n=R.hh(n,i,s,o,r[f+9],4,-640364487),o=R.hh(o,n,i,s,r[f+12],11,-421815835),s=R.hh(s,o,n,i,r[f+15],16,530742520),i=R.hh(i,s,o,n,r[f+2],23,-995338651),n=R.ii(n,i,s,o,r[f],6,-198630844),o=R.ii(o,n,i,s,r[f+7],10,1126891415),s=R.ii(s,o,n,i,r[f+14],15,-1416354905),i=R.ii(i,s,o,n,r[f+5],21,-57434055),n=R.ii(n,i,s,o,r[f+12],6,1700485571),o=R.ii(o,n,i,s,r[f+3],10,-1894986606),s=R.ii(s,o,n,i,r[f+10],15,-1051523),i=R.ii(i,s,o,n,r[f+1],21,-2054922799),n=R.ii(n,i,s,o,r[f+8],6,1873313359),o=R.ii(o,n,i,s,r[f+15],10,-30611744),s=R.ii(s,o,n,i,r[f+6],15,-1560198380),i=R.ii(i,s,o,n,r[f+13],21,1309151649),n=R.ii(n,i,s,o,r[f+4],6,-145523070),o=R.ii(o,n,i,s,r[f+11],10,-1120210379),s=R.ii(s,o,n,i,r[f+2],15,718787259),i=R.ii(i,s,o,n,r[f+9],21,-343485551),n=R.ad(n,a),i=R.ad(i,d),s=R.ad(s,c),o=R.ad(o,g);return R.rh(n)+R.rh(i)+R.rh(s)+R.rh(o)}static rh(t){let r="";for(let n=0;n<=3;n++)r+=R.alphabet.charAt(t>>n*8+4&15)+R.alphabet.charAt(t>>n*8&15);return r}static ad(t,r){let n=(t&65535)+(r&65535);return (t>>16)+(r>>16)+(n>>16)<<16|n&65535}static rl(t,r){return t<<r|t>>>32-r}static cm(t,r,n,i,s,o){return R.ad(R.rl(R.ad(R.ad(r,t),R.ad(i,o)),s),n)}static ff(t,r,n,i,s,o,a){return R.cm(r&n|~r&i,t,r,s,o,a)}static gg(t,r,n,i,s,o,a){return R.cm(r&i|n&~i,t,r,s,o,a)}static hh(t,r,n,i,s,o,a){return R.cm(r^n^i,t,r,s,o,a)}static ii(t,r,n,i,s,o,a){return R.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}};R.alphabet="0123456789abcdef";var Z=R;function Xr(e){if(e===0)return ye[0];let t="";for(;e>0;)t=ye[e%62]+t,e=Math.floor(e/62);return t}function se(e){return e.split("").reverse().reduce((t,r,n)=>t+ye.indexOf(r)*62**n,0)}function Ie(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 zt(){return typeof window>"u"||!!window?._runningInNodeJS}function H(){return !zt()&&typeof document<"u"&&typeof document.createElement=="function"}function ht(e){let t;try{t=JSON.stringify(e);}catch{throw new l("Invalid data type.",{code:"INVALID_REQUEST"})}if(new Blob([t]).size>Ao)throw new l("Data should not exceed 2MB",{code:"INVALID_REQUEST"})}function Wr(e){return e===""||e==="on"||e==="true"}function Qr(e){return e==="false"}function zr(e,t,r){t.name&&r(e,t.name,t.value);}var mt=H(),To=typeof SubmitEvent<"u",Po=typeof HTMLFormElement<"u";function $(e,t,r){let n={},i=[];function s(d,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 h=p.replace("]",""),m=Number(h);return !isNaN(m)&&!h.includes(".")?h=m:(h[0]==='"'&&h[h.length-1]==='"'||h[0]==="'"&&h[h.length-1]==="'")&&(h=h.replace(/"/g,"").replace(/'/g,"")),h}),u=d;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 h=f[p];p<f.length-1?(u[h]===void 0&&(typeof f[p+1]=="number"?u[h]=[]:u[h]={}),u=u[h]):u[h]===void 0?u[h]=g:Array.isArray(u[h])?u[h].push(g):u[h]=[u[h],g];}}function o(d,c,g){if(g instanceof File)d.push({name:c,file:g});else if(g instanceof FileList&&g&&g.length>0)for(let f=0;f<=g.length-1;f++){let u=g.item(f);u&&d.push({name:c,file:u});}}let a=d=>{d.name&&(d.type==="number"?d.value&&s(n,d.name,Number(d.value)):d.type==="checkbox"||d.type==="radio"?d.checked?d.type==="checkbox"&&d.value===""||Wr(d.value)?s(n,d.name,true):Qr(d.value)?s(n,d.name,false):d.value&&s(n,d.name,d.value):d.type==="checkbox"&&(Wr(d.value)?s(n,d.name,false):Qr(d.value)&&s(n,d.name,true)):d.type==="file"?d.files&&d.files.length>0&&o(i,d.name,d.files):s(n,d.name,d.value));};if(mt&&(e instanceof HTMLInputElement||e instanceof HTMLSelectElement||e instanceof HTMLTextAreaElement))return a(e),ht(n),{data:n,files:i};if(mt&&e instanceof FormData){for(let d of e.entries()){let c=d[0],g=d[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 u=JSON.parse(f.text());s(n,c,u);}catch{s(n,c,f);}}else s(n,c,g);}return ht(n),{data:n,files:i}}if(mt&&To&&e instanceof SubmitEvent&&(e=e.target),mt&&Po&&e instanceof HTMLFormElement){let d=e.querySelectorAll("input"),c=e.querySelectorAll("select"),g=e.querySelectorAll("textarea");for(let f=0;f<c.length;f++)zr(n,c[f],s);for(let f=0;f<g.length;f++)zr(n,g[f],s);for(let f=0;f<d.length;f++)a(d[f]);return ht(n),{data:n,files:i}}return ht(e),{data:e,files:i}}function Ke(e){let t={};for(let r in e){let n=e[r];if(!Ro.includes(r))if(Hr[r])t[Hr[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 Jt(e){if(e=Co(e),e.split("-").length===7){let t=e.split("-"),r,n;try{r=Yr[Jr.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 Yt(e,t){let r=Yr.indexOf(e.slice(0,4)),n=Jr[r],s=`${e.slice(4,-4)}-${n}${e.slice(-4)}-${t}`;return Uo(s)}function So(e){let t=0n;for(let r of e){let n=ye.indexOf(r);if(n<0)throw new Error(`INVALID_PARAMETER: Invalid base62 character: ${r}`);t=t*Wt+BigInt(n);}return t}function ko(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%Wt);r=ye[i]+r,n/=Wt;}return r.length<t&&(r="0".repeat(t-r.length)+r),r}function vo(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 No(e){let t=0n;for(let r of e)t=(t<<8n)+BigInt(r);return t}function Do(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 xo(e){let t=Array.from(Qt(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 Uo(e){let t=String(e);if(t.split("-").length===2)return t;let r=t.match(/^([0-9A-Za-z]+)-([0-9A-Za-z]+)-([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/);if(!r)throw new Error("INVALID_PARAMETER: Input must match <base62>-<base62>-<uuid>.");let[,n,i,s]=r;if(n.length<2)throw new Error("INVALID_PARAMETER: The first part must contain at least 2 characters.");if(i.length>=ye.length)throw new Error("INVALID_PARAMETER: The middle section is too long to encode.");let o=n.slice(0,2),a=n.slice(2),d=i+o,c=ye[i.length]+a+d,g=Do(s),f=ko(No(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=ye.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 d=o.slice(0,o.length-a),c=o.slice(o.length-a),g=c.slice(s),f=c.slice(0,s),u=g+d;if(!/^[0-9A-Za-z]+$/.test(u)||!/^[0-9A-Za-z]+$/.test(f))throw new Error("INVALID_PARAMETER: Corrupt compressed token: "+t);let p=So(i),h=vo(p);if(h.length>16)throw new Error("INVALID_PARAMETER: Corrupt compressed token: "+t);let m=new Uint8Array(16);m.set(h,16-h.length);let _=xo(m);return `${u}-${f}-${_}`}function He(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 Xt(...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 Mo(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 Fo(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 qo(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 Vo(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 jo(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 $o=/^[a-z0-9]{2,20}$/,Bo=/[a-z]/,Ko=/^[0-9]+e[0-9]+$/,Ho=["tp","admin","public","authorized","newsletter","forward","all","true","false","null"];function Go(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"||!$o.test(e)||!Bo.test(e)||Ko.test(e)||Ho.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 Wo(e,t,r=[],n){let i=$(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 Oo(o,t,r)}catch(a){throw new l(a.message,{code:"INVALID_PARAMETER"})}}var y={UserId:Lo,PhoneNumber:Mo,Birthdate:Fo,Password:qo,Email:Vo,Url:jo,newsletterGroup:Go,Params:Wo};var Y="skapi.enc.v1",tn=6e5,Ge=12,yt=null,Ne=null;function rn(){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 nn(){if(Ne)return Ne;let e=typeof globalThis<"u"?globalThis:void 0;if(e?.crypto?.subtle&&typeof e.crypto.getRandomValues=="function")return Ne=e.crypto,Ne;try{let t=typeof globalThis<"u"?globalThis:void 0,r=null;if(t?.process&&typeof t.process.getBuiltinModule=="function"&&(r=t.process.getBuiltinModule("crypto")),!r&&typeof ke=="function"&&(r=ke("crypto")),r?.webcrypto?.subtle)return Ne=r.webcrypto,Ne}catch{}throw rn()}function re(){if(yt)return yt;let e=nn();if(!e.subtle)throw rn();return yt=e.subtle,yt}function er(){try{return re(),!0}catch{return false}}function X(e){let t=nn(),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 q(e){let t=Qt(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 j(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 bt(e){let t=await re().digest("SHA-256",e);return new Uint8Array(t)}async function ze(e,t,r,n){let i=re(),s=await i.importKey("raw",e,"HKDF",false,["deriveBits"]),o=await i.deriveBits({name:"HKDF",hash:"SHA-256",salt:t,info:r},s,n*8);return new Uint8Array(o)}async function xe(e,t,r,n){let i=re(),s=K(e.normalize("NFC")),o=await i.importKey("raw",s,"PBKDF2",false,["deriveBits"]),a=new Uint8Array(await i.deriveBits({name:"PBKDF2",salt:t,iterations:r,hash:"SHA-256"},o,256)),d=await ze(a,t,n,32);F(a),F(s);let c=await oe(d);return F(d),c}async function oe(e){return re().importKey("raw",e,{name:"AES-GCM"},false,["encrypt","decrypt"])}async function sn(){let e=X(32),t=await oe(e);return {bytes:e,key:t}}async function ne(e,t,r){let n=X(Ge),i=await re().encrypt({name:"AES-GCM",iv:n,additionalData:r,tagLength:128},e,t);return {iv:n,ct:new Uint8Array(i)}}async function ae(e,t,r,n){let i=await re().decrypt({name:"AES-GCM",iv:t,additionalData:n,tagLength:128},e,r);return new Uint8Array(i)}var _t={name:"ECDH",namedCurve:"P-256"};async function on(){let e=re(),t=await e.generateKey(_t,true,["deriveBits"]),r=new Uint8Array(await e.exportKey("raw",t.publicKey)),n=new Uint8Array(await e.exportKey("pkcs8",t.privateKey)),i=await tr(n);return {pubRaw:r,pkcs8:n,priv:i}}async function tr(e){return re().importKey("pkcs8",e,_t,false,["deriveBits"])}async function an(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 re().importKey("raw",e,_t,false,[])}async function rr(e){return q(await bt(e))}async function ln(e,t,r,n){let i=re(),s=await an(e),o=await i.generateKey(_t,true,["deriveBits"]),a=new Uint8Array(await i.deriveBits({name:"ECDH",public:s},o.privateKey,256)),d=await ze(a,new Uint8Array(32),r,32);F(a);let c=await oe(d);F(d);let{iv:g,ct:f}=await ne(c,t,n);return {epk:new Uint8Array(await i.exportKey("raw",o.publicKey)),iv:g,ct:f}}async function cn(e,t,r,n,i,s){let o=re(),a=await an(t),d=new Uint8Array(await o.deriveBits({name:"ECDH",public:a},e,256)),c=await ze(d,new Uint8Array(32),i,32);F(d);let g=await oe(c);return F(c),ae(g,r,n,s)}function F(e){e&&e.length&&e.fill(0);}function Qo(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 nr(e){return K(JSON.stringify(e))}function Je(e,t,r){return Xt(e,new Uint8Array([0]),K(t),new Uint8Array([0]),K(r))}var Te="0123456789ABCDEFGHJKMNPQRSTVWXYZ",We=16,Zr=26,en=28;function un(e){let t=2166136261;for(let r=0;r<e.length;r++)t^=e[r],t=t*16777619>>>0;return t&1023}function dn(e){if(e.length!==We)throw new l(`A recovery code needs exactly ${We} 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+=Te[r>>n&31];n>0&&(t+=Te[r<<5-n&31]);let i=un(e);return t+=Te[i>>5&31]+Te[i&31],(t.match(/.{1,4}/g)||[]).join("-")}function fn(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!==en)throw new l(`That does not look like a recovery code: expected ${en} characters, got ${t.length}.`,{code:"ENCRYPTION_BAD_RECOVERY_CODE"});let r=t.slice(0,Zr),n=t.slice(Zr),i=0,s=0,o=[];for(let c=0;c<r.length;c++){let g=Te.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,We)),d=un(a);if(n!==Te[d>>5&31]+Te[d&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 ir(e,t,r){let n=await ze(e,t,r,32),i=await oe(n);return F(n),i}var Zt=[83,75,69,78,67,70],gn=2,Qe=56,pn=16,zo=4*1024*1024;function sr(e){if(!e||e.length<Qe)return false;for(let t=0;t<Zt.length;t++)if(e[t]!==Zt[t])return false;return true}function Pe(e,t,r){e[t]=r>>>24&255,e[t+1]=r>>>16&255,e[t+2]=r>>>8&255,e[t+3]=r&255;}function De(e,t){return (e[t]<<24>>>0)+(e[t+1]<<16)+(e[t+2]<<8)+e[t+3]}function Jo(e,t,r){let n=Math.floor(r/4294967296);Pe(e,t,n),Pe(e,t+4,r>>>0);}function Yo(e,t){return De(e,t)*4294967296+De(e,t+4)}async function hn(e,t,r,n,i,s){let o=K(`${Y}|binfile|${r}|${n}|${i}|${s}`),a=await ze(e,t,o,32),d=await oe(a);return F(a),d}async function mn(e){return (await bt(Xt(K(`${Y}|dekid`),e))).subarray(0,8)}function yn(e,t,r){return nr([`${Y}|binchunk`,q(e),t,r])}function Xo(e,t,r,n,i,s){let o=new Uint8Array(Qe+s.length);return o.set(Zt,0),o[6]=gn,o[7]=s.length?1:0,Pe(o,8,e),Pe(o,12,t),o.set(r,16),Jo(o,32,n),o.set(i,40),Pe(o,48,s.length),Pe(o,52,0),s.length&&o.set(s,Qe),o}async function bn(e,t,r,n,i=zo){let s=X(pn),o=await hn(e,s,r.service,r.owner,r.recordOwner,r.recordId),a=await mn(e),d=n?K(JSON.stringify(n)):new Uint8Array(0);if(d.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=Xo(i,c,s,t.length,a,d),f=await bt(g),u=[],p=g.length;for(let _=0;_<c;_++){let b=t.subarray(_*i,Math.min((_+1)*i,t.length)),A=await ne(o,b,yn(f,_,c));u.push(A),p+=4+A.iv.length+A.ct.length;}let h=new Uint8Array(p);h.set(g,0);let m=g.length;for(let _ of u)Pe(h,m,_.iv.length+_.ct.length),m+=4,h.set(_.iv,m),m+=_.iv.length,h.set(_.ct,m),m+=_.ct.length;return h}function Zo(e){if(!sr(e))throw new l("This file is not an encrypted skapi file.",{code:"INVALID_PARAMETER"});let t=De(e,48),r=Qe+t;if(e.length<r)throw new l("Encrypted file header is truncated.",{code:"INVALID_REQUEST"});let n=null;return t&&(n=JSON.parse(He(e.subarray(Qe,r)))),{version:e[6],chunkBytes:De(e,8),count:De(e,12),fileId:e.subarray(16,16+pn),plainLen:Yo(e,32),dekId:e.subarray(40,48),meta:n,headerLen:r}}async function _n(e,t,r){let n=Zo(t);if(n.version!==gn)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 mn(e);if(!Qo(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 hn(e,n.fileId,r.service,r.owner,r.recordOwner,r.recordId),o=await bt(t.subarray(0,n.headerLen)),a=[],d=n.headerLen,c=0;for(let u=0;u<n.count;u++){if(d+4>t.length)throw new l("Encrypted file is truncated.",{code:"INVALID_REQUEST"});let p=De(t,d);if(d+=4,p<Ge+16||d+p>t.length)throw new l("Encrypted file is truncated.",{code:"INVALID_REQUEST"});let h=await ae(s,t.subarray(d,d+Ge),t.subarray(d+Ge,d+p),yn(o,u,n.count));d+=p,a.push(h),c+=h.length;}let g=new Uint8Array(c),f=0;for(let u of a)g.set(u,f),f+=u.length;return {bytes:g,meta:n.meta}}var ea="__skapi__keyring",Ye="__skapi_enc__",En=1,ta="skapi-enc",Ae="keys",ar=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:tn;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:ea}}function L(){return ar.get(this)||null}function Rn(e){if(!e){ar.delete(this);return}ar.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 lr(){let e=L.call(this);if(e){e.user_id&&_r.call(this,e).catch(()=>{}),e.ready=null,e.unlocking=false,e.pendingRecoveryCode="";for(let[,t]of e.dek)F(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 In(){let e=L.call(this);return e?{status:e.status,reason:e.status==="unlocked"?void 0:e.reason,user_id:e.user_id||void 0,fingerprint:e.fpr||void 0}:{status:"disabled"}}function Tn(e,t){return typeof t=="string"&&t===e.cfg.table}function Ue(){return `${this.service}/${this.owner}`}function cr(e,t,r,n){let[i,s]=e.split("/");return nr([Y,i,s,t,r,n])}function Pn(e,t,r,n,i){let[s,o]=e.split("/");return K(`${Y}|dekwrap|${s}|${o}|${t}|${r}|${n}|${i}`)}function ur(e){return e.anch==="uid"?e.uid:e.anch==="rid"?e.rid:""}function Et(e){return !!e&&typeof e=="object"&&!Array.isArray(e)&&typeof e[Ye]=="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 Sn="__skapi_no_access__";function ee(e,t,r){if(e.withheld!=="sentinel")return null;let n={[Sn]:true,reason:t};return r&&(n.recipients=r),Object.freeze(n)}function dr(e){return !!e&&typeof e=="object"&&e[Sn]===true}var ra=256*1024,et="__skenc_ct__",kn="payload.bin",na=`/${et}/${kn}`;function fr(e,t){return e===et&&t===kn}async function ia(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:wn(n.access_group),table:i,record:null};if(!r)return {group:n?.access_group!==void 0?wn(n.access_group):0,table:i,record:null};let s=e.dek.get(r);if(s)return {group:s.access_group,table:i,record:null};let o=await Ee.call(this,r);if(!o)throw new l(`Record "${r}" not found.`,{code:"NOT_EXISTS"});return {group:o.table.access_group,table:o.table.name,record:o}}function sa(e){return this.getFile(e,{dataType:"blob"})}async function Ee(e){let t=/^[a-zA-Z0-9]+$/.test(e)?{record_id:e}:{unique_id:e};return (await this.getRecords(t,{limit:1}))?.list?.[0]||null}function wn(e){return e==="private"||e==="*"||e==="**"?"private":e==="public"?0:e==="authorized"?1:e==="admin"?99:typeof e=="number"?e:0}function or(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 gr(e,t,r){let n=L.call(this);if(!n)return {send:e,plain:e,encrypted:false,omit:false};let i=t?.record_id||"",s=i,o=t?.unique_id||"";if(i&&n.passthrough.has(i)){let M=n.passthrough.get(i);return n.passthrough.delete(i),{send:M,plain:e,encrypted:true,omit:false}}let{group:a,table:d,record:c}=await ia.call(this,n,t,s);if(a!=="private"){let M=true;if(!r&&i){let z=c||await Ee.call(this,i);if(z&&z.encrypted){if(or.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 Be=!!z.bin&&Object.keys(z.bin).some(gt=>(z.bin[gt]||[]).some(Kr=>Kr&&Kr.encrypted));if(!Be&&s){let gt=n.dek.get(s);gt&&(F(gt.bytes),n.dek.delete(s));}return {send:z.data,plain:z.data,encrypted:false,omit:false,files:Be?"decrypt":void 0}}}let J=c;i&&!J&&(J=await Ee.call(this,i).catch(()=>null)),J&&J.encrypted&&or.call(this,J,i,"making it non-private");let ft=!!J&&!!J.bin&&Object.keys(J.bin).some(z=>(J.bin[z]||[]).some(Be=>Be&&Be.encrypted));if(ft&&(M=false),M&&s){let z=n.dek.get(s);z&&(F(z.bytes),n.dek.delete(s));}return {send:e,plain:e,encrypted:false,omit:!r,files:ft?"decrypt":void 0}}if(Tn(n,d))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(dr.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,Ye))throw new l(`"${Ye}" 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=Ue.call(this),u=false;if(i&&n.roll.has(i)){u=true,n.roll.delete(i);let M=n.dek.get(i);n.dek.delete(i),M&&F(M.bytes);}let p=c;i&&!p&&!n.dek.has(i)&&(p=await Ee.call(this,i).catch(()=>null)),p&&or.call(this,p,i,"making it private");let h=!!p&&!p.encrypted&&!!p.bin&&Object.keys(p.bin).some(M=>(p.bin[M]||[]).some(J=>J&&!J.encrypted)),m=null;if(i&&!u&&(m=n.dek.get(i)||null,!m)){let M=p||c||await Ee.call(this,i);if(M&&(s=M.record_id||i,m=n.dek.get(s)||null,!o&&M.unique_id&&(o=M.unique_id),!m&&M.encrypted?.status==="failed"))throw new l(`Cannot update encrypted record "${i}": its current contents could not be decrypted (${M.encrypted.reason}), so its existing key wraps cannot be preserved. Updating anyway would revoke everyone it is shared with.`,{code:"ENCRYPTION_LOCKED"})}s===i&&m&&m.rid&&(s=m.rid),!o&&m&&m.anch==="uid"&&m.uid&&(o=m.uid);let _,b,A;if(m){if(m.own&&m.own!==g)throw new l(`Record "${i}" belongs to another user (${m.own}). Encryption only operates on records you own.`,{code:"ENCRYPTION_NOT_RECORD_OWNER"});_=m.bytes,b=m.key,A=Object.assign({},m.recipients);}else {let M=await sn();_=M.bytes,b=M.key,A={};}let w=o?"uid":s?"rid":"new",k=w==="uid"?o:w==="rid"?s:"",E=cr(f,g,w,k),N=Je(E,g,"mk"),U=await ne(n.mk,_,N);A[g]={t:"mk",iv:q(U.iv),ct:q(U.ct)},m&&(m.anch!==w||ur(m)!==k)&&(A=await oa.call(this,n,_,A,f,g,w,k,E));let C=K(JSON.stringify(e===void 0?null:e)),v=await ne(b,C,E);F(C);let x={[Ye]:En,enc:"A256GCM",kw:"ECDH-ES+A256GCM",anch:w,uid:o,rid:s,own:g,iv:q(v.iv),ct:q(v.ct),k:A},O,V,de=x.ct;s&&de.length>ra&&(O=j(de),x.ct="",x.ct_ref=na,m&&m.ctRef&&(V=m.ctRef));let ie=JSON.stringify(x).length;if(ie>2*1024*1024)throw new l(`Encrypted record data is too large: once encrypted and base64 encoded it becomes ${ie} bytes, over the ${2*1024*1024} byte limit. Encryption costs about 33% plus roughly 230 bytes per additional recipient.`,{code:"ENCRYPTED_DATA_TOO_LARGE"});return s&&n.dek.set(s,{bytes:_,key:b,recipients:A,anch:w,uid:o,rid:s,own:g,access_group:"private"}),{send:x,plain:e,encrypted:true,omit:false,spill:O,retireCt:V,dek:{bytes:_,key:b,recipients:A,anch:w,uid:o,rid:s,own:g,access_group:"private"},files:h?"encrypt":void 0}}function vn(e,t){let r=L.call(this);!r||!t||!e||r.dek.has(e)||r.dek.set(e,Object.assign({},t,{rid:e}));}async function oa(e,t,r,n,i,s,o,a){let d=Object.keys(r).filter(f=>f!==i);if(!d.length)return r;let c=await wr.call(this,d),g={[i]:r[i]};for(let f of d){let u=c[f];u&&(g[f]=await Nn.call(this,t,u,n,o,i,f,a));}return g}async function Nn(e,t,r,n,i,s,o){let a=Pn(r,n,i,s,t.fpr),d=Je(o,s,t.fpr),c=await ln(t.pubRaw,e,a,d);return {t:"ecdh",epk:q(c.epk),iv:q(c.iv),ct:q(c.ct),fpr:t.fpr}}async function Dn(e,t){if(!Et(e))return {value:e};if(t.access_group!=="private")return {value:e};let r=L.call(this);if(!r)return {value:null,flag:{status:"failed",reason:"ENCRYPTION_DISABLED"}};if(r.rawRead)return {value:e};if(Tn(r,t.table_name))return {value:e};if(e[Ye]!==En)return {value:ee(r.cfg,"UNSUPPORTED_VERSION"),flag:{status:"failed",reason:"UNSUPPORTED_VERSION"}};if(r.ready&&!r.unlocking)try{await r.ready;}catch{}if(e.own!==t.user_id)return {value:ee(r.cfg,"BINDING_MISMATCH"),flag:{status:"failed",reason:"BINDING_MISMATCH"}};if(e.uid&&t.unique_id&&e.uid!==t.unique_id)return {value:ee(r.cfg,"BINDING_MISMATCH"),flag:{status:"failed",reason:"BINDING_MISMATCH"}};if(e.rid&&t.record_id&&e.rid!==t.record_id)return {value:ee(r.cfg,"BINDING_MISMATCH"),flag:{status:"failed",reason:"BINDING_MISMATCH"}};let n=this.user?.user_id,i=n?e.k[n]:null;if(!i)return {value:ee(r.cfg,"NOT_A_RECIPIENT",Object.keys(e.k)),flag:{status:"failed",reason:"NOT_A_RECIPIENT",recipients:Object.keys(e.k)}};if(r.status!=="unlocked"||!r.mk)return {value:ee(r.cfg,"NO_SESSION_KEY"),flag:{status:"failed",reason:"NO_SESSION_KEY"}};let s=Ue.call(this),o=ur(e),a=cr(s,e.own,e.anch,o),d;try{if(i.t==="mk")d=await ae(r.mk,j(i.iv),j(i.ct),Je(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"}};d=await cn(r.ikPriv,j(i.epk),j(i.iv),j(i.ct),Pn(s,o,e.own,n,i.fpr),Je(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 F(d),{value:ee(r.cfg,"DATA_UNAVAILABLE"),flag:{status:"failed",reason:"DATA_UNAVAILABLE"}};let p=await sa.call(this,t.ctUrl);c=new Uint8Array(await p.arrayBuffer());}else c=j(e.ct);}catch{return F(d),{value:ee(r.cfg,"DATA_UNAVAILABLE"),flag:{status:"failed",reason:"DATA_UNAVAILABLE"}}}let g,f;try{f=await oe(d),g=await ae(f,j(e.iv),c,a);}catch{return F(d),{value:ee(r.cfg,"CORRUPT"),flag:{status:"failed",reason:"CORRUPT"}}}let u;try{u=JSON.parse(He(g));}catch{return F(g),F(d),{value:ee(r.cfg,"CORRUPT"),flag:{status:"failed",reason:"CORRUPT"}}}if(F(g),t.record_id){let p=r.dek.get(t.record_id);p?(p.bytes=d,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:d,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 F(d);return {value:u,flag:{status:"encrypted",recipients:Object.keys(e.k)}}}function Xe(e,t){let[r,n]=e.split("/");return K(`${Y}|kek|${r}|${n}|${t}`)}function Ze(e,t,r,n){let[i,s]=e.split("/");return K(`${Y}|mk|${i}|${s}|${t}|PBKDF2-SHA256|${r}|${n}`)}function xn(e,t){let[r,n]=e.split("/");return K(`${Y}|recovery|${r}|${n}|${t}`)}function Un(e,t,r){let[n,i]=e.split("/");return K(`${Y}|rk|${n}|${i}|${t}|HKDF-SHA256|${r}`)}function Cn(e,t){let[r,n]=e.split("/");return K(`${Y}|self|${r}|${n}|${t}`)}function On(e,t){let[r,n]=e.split("/");return K(`${Y}|ik|${r}|${n}|${t}`)}async function At(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 pr(e,t,r){let n=X(We),i=dn(n),s=X(16),o=q(s),a=await ir(n,s,xn(e,t)),d=await ne(a,r,Un(e,t,o));return F(n),{code:i,wrap:{id:q(X(6)),p:"recovery",kdf:{a:"HKDF-SHA256",s:o},iv:q(d.iv),ct:q(d.ct),created:Date.now()}}}async function aa(e,t,r,n){let i=fn(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 ir(i,j(o.kdf.s),xn(e,t)),d=await ae(a,j(o.iv),j(o.ct),Un(e,t,o.kdf.s));return F(i),d}catch{}return F(i),null}async function la(e,t,r,n,i){let s=X(16),o=q(s),a=await xe(n,s,e.cfg.iterations,Xe(t,r)),d=await ne(a,i,Ze(t,r,e.cfg.iterations,o));return {id:q(X(6)),p:"password",kdf:{a:"PBKDF2-SHA256",it:e.cfg.iterations,s:o},iv:q(d.iv),ct:q(d.ct),created:Date.now()}}async function ca(e,t){let r=this.user.user_id,n=e.scope,i=X(16),s=q(i),o=await xe(t,i,e.cfg.iterations,Xe(n,r)),a=X(32),d=await ne(o,a,Ze(n,r,e.cfg.iterations,s)),c=await oe(a),g=await on(),f=await ne(c,g.pkcs8,On(n,r));F(g.pkcs8);let u=null;e.cfg.recovery==="code"&&(u=await pr(n,r,a));let p=await ne(c,a,Cn(n,r));F(a);let h=await rr(g.pubRaw),m=Date.now(),_=[{id:q(X(6)),p:"password",kdf:{a:"PBKDF2-SHA256",it:e.cfg.iterations,s},iv:q(d.iv),ct:q(d.ct),created:m}];u&&_.push(u.wrap);let b={v:1,alg:"ECDH-P-256",user_id:r,wraps:_,ik:{iv:q(f.iv),ct:q(f.ct)},self:{iv:q(p.iv),ct:q(p.ct)},pub:q(g.pubRaw),fpr:h,pins:null,created:m,updated:m};await this.postRecord({v:1,alg:"ECDH-P-256",user_id:r,pub:q(g.pubRaw),fpr:h,created:m},{table:{name:e.cfg.table,access_group:"authorized"},index:{name:"pubkey",value:r}});let A=await this.postRecord(b,{table:{name:e.cfg.table,access_group:"private"}}),w=await At.call(this,e);if(w&&w.record_id!==A.record_id){await Ln.call(this,e,w,t);return}e.mk=c,e.ikPriv=g.priv,e.pubRaw=g.pubRaw,e.fpr=h,e.keyringRecordId=A.record_id,u&&(e.pendingRecoveryCode=u.code),e.user_id=r,e.pins={},e.status="unlocked",e.reason="";}async function Ln(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 d=null;for(let g of a)try{let f=j(g.kdf.s),u=await xe(r,f,g.kdf.it,Xe(i,n));d=await ae(u,j(g.iv),j(g.ct),Ze(i,n,g.kdf.it,g.kdf.s));break}catch{}if(!d)throw new l("Incorrect password: the encryption keyring could not be opened.",{code:"ENCRYPTION_BAD_PASSWORD"});let c=await oe(d);F(d),await hr.call(this,e,t,c);}async function hr(e,t,r){let n=this.user.user_id,i=t.data,s=await ae(r,j(i.ik.iv),j(i.ik.ct),On(e.scope,n)),o=await tr(s);F(s);let a={};if(i.pins&&typeof i.pins=="object"&&i.pins.ct)try{let d=await ae(r,j(i.pins.iv),j(i.pins.ct),K(`${Y}|pins|${e.scope}|${n}`));a=JSON.parse(He(d)),F(d);}catch{a={};}e.mk=r,e.ikPriv=o,e.pubRaw=j(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 Rt(e){let t=L.call(this);if(!t||!this.user?.user_id)return;if(!er()){t.status="locked",t.reason="NO_WEB_CRYPTO";return}if(this.user?.is_openid){t.status="locked",t.reason="OPENID_UNSUPPORTED";return}if(t.cfg.minPasswordLength&&e.length<t.cfg.minPasswordLength){t.status="locked",t.reason="WEAK_PASSWORD";return}t.scope=Ue.call(this);let r=await At.call(this,t);r?await Ln.call(this,t,r,e):await ca.call(this,t,e),t.cfg.persistDevice&&await jn.call(this,t).catch(()=>{});}async function Mn(e){await this.__connection;let t=L.call(this);if(!t)throw new l("Encryption is not enabled for this instance.",{code:"INVALID_REQUEST"});if(!this.user?.user_id)throw new l("User login is required.",{code:"INVALID_REQUEST"});if(!e?.password||typeof e.password!="string")throw new l('"password" is required.',{code:"INVALID_PARAMETER"});if(await Rt.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 Fn(e){this.__projectIdInput&&await this.__projectIdInput;let t=L.call(this);return t?(e?.forgetDevice&&await _r.call(this,t).catch(()=>{}),lr.call(this),this.__cached_requests={},{status:t.status}):{status:"disabled"}}async function qn(e,t){let r=L.call(this);if(!r)return;if(r.status!=="unlocked"||!r.mk)throw new l("Encryption must be unlocked before changing the password, or the encryption keyring would be left wrapped under a password that no longer exists. Call unlockEncryption({ password }) first.",{code:"ENCRYPTION_LOCKED"});let 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(m=>m.p==="password");a.sort((m,_)=>(_.created||0)-(m.created||0));let d=null;for(let m of a)try{let _=await xe(e,j(m.kdf.s),m.kdf.it,Xe(r.scope,s));d=await ae(_,j(m.iv),j(m.ct),Ze(r.scope,s,m.kdf.it,m.kdf.s));break}catch{}if(!d)throw new l("Incorrect current password: the encryption keyring was not re-wrapped.",{code:"ENCRYPTION_BAD_PASSWORD"});let c=X(16),g=q(c),f=await xe(t,c,r.cfg.iterations,Xe(r.scope,s)),u=await ne(f,d,Ze(r.scope,s,r.cfg.iterations,g));F(d);let p=Date.now(),h=(o.wraps||[]).concat([{id:q(X(6)),p:"password",kdf:{a:"PBKDF2-SHA256",it:r.cfg.iterations,s:g},iv:q(u.iv),ct:q(u.ct),created:p}]);await this.postRecord(Object.assign({},o,{wraps:h,updated:p}),{record_id:r.keyringRecordId});}async function Vn(){let e=L.call(this);if(!e||e.status!=="unlocked"||!e.keyringRecordId)return;let r=(await this.getRecords({record_id:e.keyringRecordId},{limit:1}))?.list?.[0];if(!r)return;let n=r.data,i=(n.wraps||[]).filter(o=>o.p==="password").sort((o,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 mr(){return typeof indexedDB<"u"&&!!indexedDB}function yr(){return new Promise((e,t)=>{let r=indexedDB.open(ta,1);r.onupgradeneeded=()=>{let n=r.result;n.objectStoreNames.contains(Ae)||n.createObjectStore(Ae);},r.onsuccess=()=>e(r.result),r.onerror=()=>t(r.error);})}function br(e){return `${e.scope}#${this.user?.user_id}`}async function jn(e){if(!mr()||!e.mk)return;let t=await yr();await new Promise((r,n)=>{let i=t.transaction(Ae,"readwrite");i.objectStore(Ae).put({mk:e.mk,keyringRecordId:e.keyringRecordId,saved:Date.now()},br.call(this,e)),i.oncomplete=()=>r(),i.onerror=()=>n(i.error);}),t.close();}async function ua(e){if(!mr())return null;let t=await yr(),r=await new Promise((n,i)=>{let o=t.transaction(Ae,"readonly").objectStore(Ae).get(br.call(this,e));o.onsuccess=()=>n(o.result||null),o.onerror=()=>i(o.error);});return t.close(),r&&r.mk?r:null}async function _r(e){if(!mr())return;let t=await yr();await new Promise((r,n)=>{let i=t.transaction(Ae,"readwrite");i.objectStore(Ae).delete(br.call(this,e)),i.oncomplete=()=>r(),i.onerror=()=>n(i.error);}),t.close();}function $n(){let e=L.call(this);!e||e.ready||(e.unlocking=true,e.ready=da.bind(this)().catch(()=>false).then(()=>{e.unlocking=false;}));}async function da(){let e=L.call(this);if(!e||!this.user?.user_id||!e.cfg.persistDevice||!er())return false;e.scope=Ue.call(this);try{let t=await ua.call(this,e);if(!t)return !1;let r=await At.call(this,e);return r?(await hr.call(this,e,r,t.mk),!0):(await _r.call(this,e).catch(()=>{}),!1)}catch{return e.status="locked",e.reason="NO_SESSION_KEY",false}}async function wr(e){let t=L.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,h)=>h.uploaded-p.uploaded);let g=j(c[0].data.pub),f=await rr(g),u=t.pins[s];if(u&&u!==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(!u){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 Gn.call(this,t).catch(()=>{}),r}async function Bn(e,t){let r=Ue.call(this),n=e.dek.get(t);if(n)return {entry:n,scope:r};let i=await Ee.call(this,t);if(!i)throw new 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 Er(e,t){let r=L.call(this);if(!r)return;let n=await Bn.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 wr.call(this,t),d=t.filter(u=>!a[u]);if(d.length)throw new l(`These users have no encryption key yet, so they cannot be given access: ${d.join(", ")}. A user's key is created the first time they log in with encryption enabled.`,{code:"ENCRYPTION_RECIPIENT_HAS_NO_KEY"});let c=ur(i),g=cr(s,i.own,i.anch,c),f=Object.assign({},i.recipients);for(let u of t)u!==o&&(f[u]=await Nn.call(this,i.bytes,a[u],s,c,i.own,u,g));await ga.call(this,r,e,i,f);}async function Kn(e,t){let r=L.call(this);if(!r)return;let n=await Bn.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 Ee.call(this,e);if(!a)throw new l(`Record "${e}" not found.`,{code:"NOT_EXISTS"});fa(a,e);let d={};if(o.length){d=await wr.call(this,o);let c=o.filter(g=>!d[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 Er.call(this,a.record_id||e,o);}function fa(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 ga(e,t,r,n){let i=await pa.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 pa(e){let t=L.call(this);if(!t)return null;t.rawRead=true;let r;try{r=(await this.getRecords({record_id:e},{limit:1}))?.list?.[0];}finally{t.rawRead=false;}return r&&Et(r.data)?r.data:null}async function Hn(e){this.__projectIdInput&&await this.__projectIdInput;let t=L.call(this);if(!t||t.status!=="unlocked")throw new l("Encryption is locked.",{code:"ENCRYPTION_LOCKED"});t.pins[e.user_id]=e.fingerprint,t.peerPub.delete(e.user_id),await Gn.call(this,t);}async function Gn(e){if(!e.mk||!e.keyringRecordId)return;let r=(await this.getRecords({record_id:e.keyringRecordId},{limit:1}))?.list?.[0];if(!r)return;let n=await ne(e.mk,K(JSON.stringify(e.pins)),K(`${Y}|pins|${e.scope}|${e.user_id}`));await this.postRecord(Object.assign({},r.data,{pins:{iv:q(n.iv),ct:q(n.ct)},updated:Date.now()}),{record_id:e.keyringRecordId});}function Wn(){let e=L.call(this);if(!e||!e.pendingRecoveryCode)return null;let t=e.pendingRecoveryCode;return e.pendingRecoveryCode="",t}async function Qn(e){await this.__connection;let t=L.call(this);if(!t)throw new l("Encryption is not enabled for this instance.",{code:"INVALID_REQUEST"});if(!this.user?.user_id)throw new l("User login is required. Reset the password and log in first, then use the recovery code.",{code:"INVALID_REQUEST"});if(!e?.code||typeof e.code!="string")throw new l('"code" is required.',{code:"INVALID_PARAMETER"});t.scope=Ue.call(this);let r=this.user.user_id,n=await At.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 aa(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 hr.call(this,t,n,s);let o=false,a=null,d=(n.data?.wraps||[]).slice();if(e.password&&(d=d.filter(c=>c.p!=="password"),d.push(await la(t,t.scope,r,e.password,i)),o=true),t.cfg.recovery==="code"){let c=await pr(t.scope,r,i);d=d.filter(g=>g.p!=="recovery"),d.push(c.wrap),a=c.code;}return F(i),await this.postRecord(Object.assign({},n.data,{wraps:d,updated:Date.now()}),{record_id:n.record_id}),t.cfg.persistDevice&&await jn.call(this,t).catch(()=>{}),{status:t.status,repaired:o,recoveryCode:a}}async function zn(){await this.__connection;let e=L.call(this);if(!e)throw new l("Encryption is not enabled for this instance.",{code:"INVALID_REQUEST"});if(e.status!=="unlocked"||!e.mk)throw new l("Encryption must be unlocked to issue a recovery code. Only someone who can already decrypt can create one.",{code:"ENCRYPTION_LOCKED"});if(e.cfg.recovery!=="code")throw new l('Recovery codes are disabled for this instance ("recovery" is "none").',{code:"INVALID_REQUEST"});let r=(await this.getRecords({record_id:e.keyringRecordId},{limit:1}))?.list?.[0];if(!r)throw new l("The encryption keyring could not be read.",{code:"ENCRYPTION_KEYRING_CORRUPT"});let n=r.data?.self;if(!n||!n.ct)throw new l("This keyring predates recovery-code rotation and cannot issue a new code. Use unlockWithRecoveryCode() with the existing code, which issues a replacement.",{code:"ENCRYPTION_KEYRING_CORRUPT"});let i=await ae(e.mk,j(n.iv),j(n.ct),Cn(e.scope,e.user_id)),s=await pr(e.scope,e.user_id,i);F(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 wt="__skenc__",Jn="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";function ha(e){if(e===0)return "0";let t="";for(;e>0;)t=Jn[e%62]+t,e=Math.floor(e/62);return t}function ma(e){let t=0;for(let r of e){let n=Jn.indexOf(r);if(n<0)return NaN;t=t*62+n;}return t}function It(e){if(typeof e!="string")return null;let t=e.lastIndexOf(wt);if(t<0)return null;let r=ma(e.slice(t+wt.length));return Number.isFinite(r)?{key:e.slice(0,t),plainSize:r}:null}function Ar(e){try{let t=String(e).split("?")[0].split("/").slice(3);if(t.length<12||t[4]!=="records"||t[7]!=="bin")return null;let r=It(t[10]);return r?{recordId:t[5],recordOwner:t[3],filename:t[t.length-1],plainSize:r.plainSize}:null}catch{return null}}function Yn(e,t){return {service:this.service,owner:this.owner,recordOwner:t,recordId:e}}async function Xn(e,t,r){let n=L.call(this);if(!n||!e)return {key:t,file:r,encrypted:false};let i=n.dek.get(e);if(!i)return {key:t,file:r,encrypted:false};if(It(t))throw new l(`"${wt}" is reserved in an upload form key.`,{code:"INVALID_PARAMETER"});if(t===et)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 bn(i.bytes,s,Yn.call(this,e,i.own),o);return F(s),{key:`${t}${wt}${ha(r.size)}`,file:new File([a],r.name,{type:"application/octet-stream"}),encrypted:true}}async function Zn(e,t){let r=L.call(this),n=Ar(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(!sr(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 _n(i.bytes,s,Yn.call(this,n.recordId,n.recordOwner)),a=o.meta&&o.meta.t||"application/octet-stream";return new Blob([o.bytes],{type:a})}function ya(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 ba(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 Rr(e,t,r){let n=L.call(this);if(!n)return [];let i=await Ee.call(this,e);if(!i)return [];let s=t==="decrypt"?ya(i):ba(i);if(!s.length)return [];let o=[],a=new FormData,d=false;for(let c of s){let g=i.bin[c.formKey].find(u=>u.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),d=true);}if(!d)return [];if(t==="decrypt"){let c=n.dek.get(e);c&&(F(c.bytes),n.dek.delete(e));}return await this.uploadFiles(a,{record_id:e,progress:r}),o}var B=null;function St(e){let t={tkid:"ticket_id",cond:"condition",stmp:"timestamp",upd:"updated",acts:"actions",actn:"action",cnt:"count",ttl:"time_to_live",plch:"placeholder",hash:"hash",desc:"description",pmc:"limit_per_user",fail:"failed"},r={};for(let n in e)if(n==="tkid"){let i=e[n].split("#");if(i.length===1){r.ticket_id=i[0];continue}r.ticket_id=i[1],r.consume_id=i[2],r.user_id=i.slice(3).join("#");let s=i[2].slice(-4);if(r.is_test=s===":CHK",!e.stmp){let o=i[2].slice(0,-4);/^[0-9]+$/.test(o)?r.timestamp=parseInt(o,10):r.timestamp=se(i[2].slice(0,-4));}}else t[n]?r[t[n]]=e[n]:r[n]=e[n];return r}async function ti(e){if(!e?.ticket_id)throw new l("Ticket ID is required.",{code:"INVALID_PARAMETER"});if(!/^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$/.test(e.ticket_id))throw new l('Invalid "ticket_id". Use letters, digits, "_" and "-" (up to 64 chars, starting with a letter or digit).',{code:"INVALID_PARAMETER"});if(!e.method)throw new l('Method is required. Should be either "GET" or "POST"',{code:"INVALID_PARAMETER"});let t=String(e.method).toUpperCase();if(t!=="GET"&&t!=="POST")throw new l('Method should be either "GET" or "POST".',{code:"INVALID_PARAMETER"});let r=!!e.auth;if(r&&t==="GET")throw new l("Signed-in consumption is POST only.",{code:"INVALID_PARAMETER"});await this.__connection;let n=r?"tpa":t==="GET"?"tg":"tp",i=`https://${this.service.slice(0,4)}.${this.customApiDomain}/${n}/${this.service}/${e.ticket_id}`,s=await S.bind(this)(i,e.data||{},{method:t,auth:r},{ignoreService:true});if(s&&typeof s=="object"&&s.stage)throw new l(s.message,{code:s.code,cause:s});return !s||typeof s!="object"?s:St(s)}async function ri(e,t){await this.__connection;let r=await S.bind(this)("ticket",Object.assign({exec:"list"},e||{}),{auth:true,fetchOptions:t});return r.list=r.list.map(St),r}async function ni(e,t){await this.__connection;let r=await S.bind(this)("ticket",Object.assign({exec:"consumed"},e||{}),{auth:true,fetchOptions:t});return r.list=r.list.map(St),r}async function ii(e){let t=await S.bind(this)("register-ticket",Object.assign({exec:"reg"},e),{auth:true});return t&&typeof t=="object"&&t.ticket&&(t.ticket=St(t.ticket)),t}async function si(e){return S.bind(this)("register-ticket",Object.assign({exec:"unreg"},e),{auth:true})}var Ia=3600;async function Oe(){if(await this.__connection,this.session){let e=Math.floor(Date.now()/1e3),r=this.session.getIdToken().getExpiration();if(r<e+Ia){this.log("request:requesting new token",null);try{await W.bind(this)().getSession({refreshToken:!0}),this.log("request:received new tokens",{exp:this.session?.idToken?.payload?.exp,currentTime:e,expiresIn:r-e,token:this.session?.accessToken?.jwtToken,refreshToken:this.session?.refreshToken?.token});}catch(n){throw this.log("request:new token error",n),new 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),be.bind(this)(),new l("User login is required.",{code:"INVALID_REQUEST"})}function ei(e,t){return new Promise((r,n)=>{t.refreshSession(e.getRefreshToken(),(i,s)=>{this.log("getSession:refreshSessionCallback",{refreshErr:i,refreshedSession:s}),i?(be.bind(this)(),n(i)):s.isValid()?r(s):(be.bind(this)(),n(new l("Invalid session.",{code:"INVALID_REQUEST"})));});})}function W(){if(!this.userPool)throw new l("User pool is missing",{code:"INVALID_REQUEST"});let e=()=>{let s=B.getSignInUserSession().getIdToken().payload||null,o=Ke(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:d=false,skipUserUpdateEventTrigger:c=false}=s||{};if(d&&c&&(c=false),B=this.userPool.getCurrentUser(),!B){this.log("getSession:cognitoUser",B),be.bind(this)(),a(null);return}let g=f=>{let u=f.getIdToken().payload;if(this.log("getSession:respond:sessionAttribute",u),u["custom:service"]!==this.service)throw this.log("getSession:respond","invalid service, signing out"),be.bind(this)(),new l("Invalid session.",{code:"INVALID_REQUEST"});return this.session=f,e(),c||this._runOnUserUpdateListeners(this.user),this.session};B.getSession((f,u)=>{if(this.log("getSession:getSessionCallback",{err:f,session:u}),!u){be.bind(this)(),a(new l("Current session does not exist.",{code:"INVALID_REQUEST"}));return}if(f){ei.bind(this)(u,B).then(b=>o(g(b))).catch(a);return}let p=Math.floor(Date.now()/1e3),h=u.getIdToken(),m=h.getExpiration(),_=m<p;if(this.log("getSession:currentTime",p),this.log("getSession:idTokenExp",m),this.log("getSession:isExpired",_),this.log("getSession:existingBearerToken",this.bearerToken),this.bearerToken=h.getJwtToken(),_||d||!u.isValid())ei.bind(this)(u,B).then(b=>o(g(b))).catch(a);else try{o(g(u));}catch(b){a(b);}});}),r=(s,o)=>{let a=o||s.includes(this.service+"-")?s:this.service+"-"+Z.hash(s);return {cognitoUser:new CognitoUser({Username:a,Pool:this.userPool}),cognitoUsername:a}};return {getSession:t,authenticateUser:(s,o,a=false,d=false)=>new Promise((c,g)=>{this.__request_signup_confirmation=null,this.__disabledAccount=null;let f=r(s,a),u=f.cognitoUsername,p=new AuthenticationDetails({Username:u,Password:o});f.cognitoUser.authenticateUser(p,{newPasswordRequired:(h,m)=>{this.__disabledAccount=null,this.__request_signup_confirmation=u,h["custom:signup_ticket"]==="PASS"||h["custom:signup_ticket"]==="MEMBER"||h["custom:signup_ticket"]==="OIDPASS"?f.cognitoUser.completeNewPasswordChallenge(o,{},{onSuccess:_=>{B=f.cognitoUser,t().then(async b=>{if(L.call(this))try{await Rt.bind(this)(o);}catch(A){this.log("encryption:ensureKeyring:failed",A);}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:h=>t({skipUserUpdateEventTrigger:true}).then(async m=>{if(this.__disabledAccount=null,L.call(this))try{await Rt.bind(this)(o);}catch(_){this.log("encryption:ensureKeyring:failed",_);}this._runOnLoginListeners(this.user),this._runOnUserUpdateListeners(this.user),c(this.user);}),onFailure:h=>{let m=[],{parsed:_,code:b}=Pt(h),A=typeof h?.message=="string"?h.message:"";if(b==="NotAuthorizedException"?A.includes("User is disabled.")?(this.__disabledAccount=u,m=["This account is disabled.","USER_IS_DISABLED"]):d?m=["The account already exists.","ACCOUNT_EXISTS"]:m=["Incorrect username or password.","INCORRECT_USERNAME_OR_PASSWORD"]:b==="UserNotFoundException"?m=["Incorrect username or password.","INCORRECT_USERNAME_OR_PASSWORD"]:b==="UserNotConfirmedException"?(this.__request_signup_confirmation=u,m=["User's signup confirmation is required.","SIGNUP_CONFIRMATION_NEEDED"]):(b==="TooManyRequestsException"||b==="LimitExceededException")&&(m=["Too many attempts. Please try again later.","REQUEST_EXCEED"]),_.code==="SIGNUP_CONFIRMATION_NEEDED"&&(this.__request_signup_confirmation=u),m.length){let w=m[1],k=m[0];g(new l(k,{code:w,cause:h}));}else g(_);}});}),createCognitoUser:r,signup:(s,o,a)=>new Promise((d,c)=>{this.userPool.signUp(s,o,a,null,(g,f)=>{if(g){let{parsed:u,code:p}=Pt(g),h=[];p==="UsernameExistsException"?h=["The account already exists.","EXISTS"]:p==="InvalidPasswordException"?h=["Invalid password. Password must be at least 6 characters.","INVALID_PARAMETER"]:p==="InvalidParameterException"?h=[u.message||"Invalid parameter.","INVALID_PARAMETER"]:p==="TooManyRequestsException"||p==="LimitExceededException"?h=["Too many attempts. Please try again later.","REQUEST_EXCEED"]:p==="CodeDeliveryFailureException"?h=["Failed to deliver verification code.","CODE_DELIVERY_FAILURE"]:p==="UserLambdaValidationException"&&(h=[u.message||"Signup validation failed.",u.code==="EXISTS"?"EXISTS":"INVALID_REQUEST"]),h.length?c(new l(h[0],{code:h[1],cause:g})):c(u);return}d(f);});})}}function Pt(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 oi(e){await this.__authConnection;let t=e?.refreshToken||false;if(!t)return this.user;try{return await W.bind(this)().getSession(Object.assign({skipUserUpdateEventTrigger:!t,refreshToken:t},e)),this.user}catch{return null}}async function ai(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 S.bind(this)("openid-logger",t),n=r.logger.split("#"),i=this.service+"-"+n[0],s=n[1];return {userProfile:await W.bind(this)().authenticateUser(i,s,true,true),openid:r.openid}}function 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 Pa(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 li(e){await this.__authConnection,this.log("loginWithToken:params",e),e=y.Params(e,{idToken:"string",accessToken:"string",refreshToken:"string"},["idToken"]);let t=Pa(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=Ke(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 tt.bind(this)(),false)}async function be(e=false){let t=null;B&&(e?t=new Promise((n,i)=>{B.globalSignOut({onSuccess:s=>{this.log("globalSignOut:success",s),n(s);},onFailure:s=>{this.log("globalSignOut:error",s),i(s);}});}):B.signOut()),lr.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 tt(e){await this.__connection;let{data:t}=$(e);return await be.bind(this)(t?.global),"SUCCESS: The user has been logged out."}async function ci(){if(!this.__request_signup_confirmation)throw new l("Least one login attempt is required.",{code:"INVALID_REQUEST"});return await S.bind(this)("confirm-signup",{username:this.__request_signup_confirmation})}async function ui(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 S.bind(this)("recover-account",{username:this.__disabledAccount,redirect:e}),"SUCCESS: Recovery e-mail has been sent."}async function Ir(e){let t=y.Params(e,{username:"string",email:"string",password:"string"},["password"]);await this.__authConnection;let r=null;if(t.email)try{r=y.Email(t.email);}catch{t.username=t.email,delete t.email;}if(!t.username&&!t.email)throw new l('Least one of "username" or "email" is required.',{code:"INVALID_PARAMETER"});let n=t.username||t.email;try{return await W.bind(this)().authenticateUser(n,t.password)}catch(i){if((i?.code==="UserNotFoundException"||i?.code==="NotAuthorizedException")&&r&&r!==n)return await W.bind(this)().authenticateUser(r,t.password);throw i}}async function di(e,t){await this.__authConnection;let r={username:"string",password:c=>y.Password(c),email:c=>y.Email(c),name:"string",address:c=>{if(!c)return "";if(typeof c=="string")return c;if(typeof c=="object")return JSON.stringify(c)},gender:"string",birthdate:c=>c?y.Birthdate(c):"",phone_number:c=>c?y.PhoneNumber(c):"",email_public:["boolean",()=>false],address_public:["boolean",()=>false],gender_public:["boolean",()=>false],birthdate_public:["boolean",()=>false],phone_number_public:["boolean",()=>false],access_group:"number",misc:"string",picture:c=>c?y.Url(c):"",profile:c=>c?y.Url(c):"",family_name:"string",given_name:"string",middle_name:"string",nickname:"string",website:c=>c?y.Url(c):""},n=y.Params(e||{},r,["email","password"]);await tt.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=W.bind(this)().createCognitoUser(n.username||n.email);for(let c of ["email_public","address_public","gender_public","birthdate_public","phone_number_public"])n[c]=n[c]?"1":"0";n.access_group&&(n.access_group=n.access_group.toString());let o=(await S.bind(this)("signupkey",{username:s.cognitoUsername,signup_confirmation:typeof n.signup_confirmation=="boolean"?JSON.stringify(n.signup_confirmation):n.signup_confirmation,email_subscription:n.email_subscription,template_confirmation:t?.template?.signup_confirmation||"",template_welcome:t?.template?.welcome||""})).split(":"),a=o.slice(1).join(":"),d=[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)?d.push(new CognitoUserAttribute({Name:"custom:"+c,Value:n[c]})):d.push(new CognitoUserAttribute({Name:c,Value:n[c]}))));}return await W.bind(this)().signup(s.cognitoUsername,n.password,d),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?Ir.bind(this)({email:n.username||n.email,password:n.password}):"SUCCESS: The account has been created."}async function fi(){await this.__connection;let e=await S.bind(this)("remove-account",{disable:this.__user.user_id},{auth:true});return await tt.bind(this)(),e}async function gi(e){await this.__connection;let t=y.Params(e,{email:i=>y.Email(i),code:["number","string"],new_password:i=>y.Password(i)},["email","code","new_password"]),r=t.code,n=t.new_password;return typeof r=="number"&&(r=r.toString()),new Promise(async(i,s)=>{W.bind(this)().createCognitoUser(t.email).cognitoUser.confirmPassword(r,n,{onSuccess: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 pi(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 d={onSuccess:c=>{n?W.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,d):(d.inputVerificationCode=null,B?.getAttributeVerificationCode(e,d,i));})}function hi(e,t){return pi.bind(this)("phone_number",e,t)}function mi(e,t){return pi.bind(this)("email",e,t)}async function yi(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)=>{W.bind(this)().createCognitoUser(r.email).cognitoUser.forgotPassword({onSuccess:d=>{s("SUCCESS: Verification code has been sent.");},onFailure:d=>{let{parsed:c,code:g}=Pt(d),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:d}));}},n);})}async function bi(e){if(await this.__connection,!this.session)throw new l("User login is required.",{code:"INVALID_REQUEST"});let t=y.Params(e,{current_password:"string",new_password:"string"});if(!t?.current_password)throw new l('"current_password" is required to change password.',{code:"INVALID_PARAMETER"});if(!t?.new_password)throw new l('"new_password" is required to change password.',{code:"INVALID_PARAMETER"});return y.Password(t.current_password),y.Password(t.new_password),L.call(this)&&await qn.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}=Pt(i);n(o);}return}L.call(this)&&Vn.bind(this)().catch(o=>this.log("encryption:prune:failed",o)),r("SUCCESS: Password has been changed.");});})}async function _i(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;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 S.bind(this)("admin-edit-profile",{attributes:t},{auth:true});if(t&&typeof t=="object"&&Object.keys(t).length){let i=[];for(let s in t)i.push(new CognitoUserAttribute({Name:s,Value:t[s]}));return await new Promise((s,o)=>{B?.updateAttributes(i,(a,d)=>{a&&o([a?.code||a?.name,a?.message||"Failed to update user settings."]),s(d);});}),await W.bind(this)().getSession({refreshToken:true}),this.user}return this.user}async function wi(e,t){e=$(e).data,e||(e={searchFor:"timestamp",condition:">",value:0},t||(t={}),t.ascending=false),await this.__connection;let r={user_id:i=>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 S.bind(this)("get-users",e,{auth:true,fetchOptions:t})}async function Ei(e){await this.__connection;let t=await S.bind(this)("last-verified-email",e,{auth:true});return t.includes("SUCCESS")?(await W.bind(this)().getSession({refreshToken:true}),this.user):t}var Le=null,Ri=typeof SubmitEvent<"u",ka=typeof HTMLFormElement<"u",nt=H(),Tr=0;function Ii(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 Pr(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(Tr++,r==="admin"){let a=Object.entries(s).filter(([d,c])=>d.includes(t?"_private":"_public")&&d!=="get_users_private"&&d!=="service_public"&&typeof c=="string").map(([,d])=>d);if(!a.length)throw new l("No available admin gateways.",{code:"INVALID_REQUEST"});return a[Tr%a.length]}if(r==="record"){let a=Object.entries(o).filter(([d,c])=>d.includes(t?"record_private":"record_public")&&typeof c=="string").map(([,d])=>d);if(!a.length)throw new l("No available record gateways.",{code:"INVALID_REQUEST"});return i?a[0]:a[Tr%a.length]}throw new l("Invalid gateway type.",{code:"INVALID_REQUEST"})};async function va(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 "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 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 rt={};function Ti(){Le&&(Le.terminate(),Le=null);}async function S(e,t=null,r,n){this.log("request",{url:e,data:t,options:r,_etc:n||{}}),r=r||{};let{auth:i=false,method:s="post",bypassAwaitConnection:o=false}=r;s=s.toUpperCase();let a=null,d=null,c=await va.bind(this)(e,!!i,!!r.stableGateway),g=t?.service||this.service,f=t?.owner||this.owner;if(!o&&(a=await this.__connection,!a))throw new l("Invalid connection. The service could have been disabled, or has a restricted CORS.",{code:"INVALID_REQUEST"});let u=r?.tokenHeaders?.idToken===true;(i||u)&&(d=await Oe.bind(this)());let p={},{fetchMore:h=false,progress:m}=r?.fetchOptions||{};if(r?.fetchOptions&&Object.keys(r.fetchOptions).length){for(let v of ["limit","startKey","ascending"])if(r.fetchOptions.hasOwnProperty(v)){if(v==="startKey"&&r.fetchOptions[v]===null)continue;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:g,owner:f};Object.assign(_,p),t=$(t).data,t?t&&typeof t=="object"&&(t=Object.assign(_,t)):t=_;let b=`${s}:${i?"auth":"public"}:${e}`,A=(()=>{if(t&&typeof t=="object"&&Object.keys(t).length&&!(nt&&t instanceof FormData)){let v=function(x){return typeof x=="object"&&x!==null?Object.keys(x).sort().reduce((O,V)=>(typeof x[V]=="object"&&x[V]!==null?O[V]=v(x[V]):O[V]=x[V],O),{}):x};return Z.hash(b+"/"+JSON.stringify(v(t)))}return Z.hash(b+"/"+g)})(),{requestKey:w,requestKeyWithStartKey:k}=Na.bind(this)({params:t,url:e,fetchMore:h,hashedParams:A});if(!w||w&&typeof w=="object")return w;if(this.log("requestKey",k),typeof k=="string"&&rt[k]instanceof Promise)return this.log("request:returning pending",k),rt[k];let E={Accept:"*/*"};if(Object.prototype.hasOwnProperty.call(r,"contentType")&&r.contentType!==void 0){let v=r.contentType===null?"application/x-www-form-urlencoded":r.contentType;v&&(E["Content-Type"]=v);}else E["Content-Type"]="application/json";if(d&&(E.Authorization=d),r?.tokenHeaders){let v=(V,de)=>typeof V=="string"?V:V===true?de:null,x=v(r.tokenHeaders.accessToken,this.session?.accessToken?.jwtToken||null),O=v(r.tokenHeaders.idToken,this.bearerToken||this.session?.idToken?.jwtToken||d||null);x&&(E["X-Access-Token"]=x),O&&(E["X-Id-Token"]=O);}let U={public_identifier:this.__public_identifier,service:g,owner:f,resolves_offloaded_data:true};E["Content-Meta"]=JSON.stringify(U),r.revalidate&&(E["Cache-Control"]="no-cache",E.Pragma="no-cache");let C={headers:E};if(r?.responseType&&(C.responseType=r.responseType),s==="GET"){if(t){let v=[];if(nt&&t instanceof FormData?v=Array.from(t.entries()).map(([x,O])=>{let V=typeof O=="string"?O:O.name;return encodeURIComponent(x)+"="+encodeURIComponent(V)}):v=Object.keys(t).map(x=>{let O=t[x];return typeof O!="string"&&(O=JSON.stringify(O)),encodeURIComponent(x)+"="+encodeURIComponent(O)}),v.length){let x=c.includes("?")?c.endsWith("?")||c.endsWith("&")?"":"&":"?";c+=x+v.join("&");}}C.body=null;}else if(nt&&t instanceof FormData)C.body=t;else if(E["Content-Type"]==="application/x-www-form-urlencoded"&&t&&typeof t=="object"){let v=new URLSearchParams;for(let x of Object.keys(t)){let O=t[x];v.append(x,typeof O=="string"?O:JSON.stringify(O));}C.body=v.toString();}else typeof t=="string"?C.body=t:C.body=t?JSON.stringify(t):null;if(C.method=s,Le===null){let v={batchSize:this.requestBatchSize,breakWhenError:false,onProgress:x=>{this.onBatchProcess.forEach(O=>O(x));}};Le=new us(v);}return this.log("request-opt",C),new Promise((v,x)=>{Le.add([async()=>{let O=Pi.bind(this)(c,C,m);rt[k]=O;try{let V=xa.bind(this)({hashedParam:w,requestKeyWithStartKey:k,url:e,fetched:await O});return delete rt[k],this.log("request:end",V),v(V),V}catch(V){throw delete rt[k],this.log("request:err",V),x(V),V}}]);})}function Na(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 d of this.__startKeyHistory[r][i]){let c=i+Z.hash(d);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+=Z.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 Da(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 Pi(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"),d=Ii(a);d!==null?setTimeout(()=>{Pi(e,t,r).then(n,i);},d):i("Too many requests");}else {let a=s.status,d=["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(),u=g.join(":").trim();i(new l(u||c,{code:d.includes(f)?f:"ERROR"}));}else if(typeof c=="object"&&(c?.message||c?.stage||c?.code)){let g=c?.code||(a?a.toString():null)||"ERROR",f=c.message,u=c?.cause;u===void 0&&c.stage&&(u=c),typeof f=="string"&&(f=f.trim()),f||(f=String(g)),i(new l(f,{cause:u,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:Pr(a.loaded,a.total),loaded:a.loaded,total:a.total,abort:()=>s.abort()});},s.upload&&(s.upload.onprogress=a=>{r({status:"upload",progress:Pr(a.loaded,a.total),loaded:a.loaded,total:a.total,abort:()=>s.abort()});})),s.send(t.body);})}function xa(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 it(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(Ri&&e instanceof SubmitEvent&&(e=e.target),ka&&e instanceof HTMLFormElement&&(e=new FormData(e)),!nt||!(e instanceof FormData))throw new l('"fileList" should be a FormData or HTMLFormElement.',{code:"INVALID_PARAMETER"});let o={reserved_key:Ie(),service:n,request:"post"};t?.record_id&&(o.id=t.record_id);let a,d=(p,h,m)=>new Promise((_,b)=>{a=new XMLHttpRequest,a.open("POST",p),a.onload=()=>{let A=a.responseText;try{A=JSON.parse(A);}catch{}if(a.status>=200&&a.status<300)_(A);else if(a.status===429){let w=a.getResponseHeader("Retry-After"),k=Ii(w);k!==null?setTimeout(()=>{d(p,h,m).then(_,b);},k):b("Too many requests");}else b(A);},a.onerror=()=>b("Network error"),a.onabort=()=>b("Aborted"),a.ontimeout=()=>b("Timeout"),a.upload&&typeof m=="function"&&(a.upload.onprogress=m),a.send(h);});function c(p){let h="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";if(p===0)return h[0];let m="";for(;p>0;)m=h[p%62]+m,p=Math.floor(p/62);return m}let g=[],f=[],u=[];for(let[p,h]of e.entries()){if(!(h instanceof File))continue;let m=await Xn.bind(this)(r,p,h),_=m.file,b=m.key,A=Object.assign({key:b+"/"+_.name,sizeKey:c(_.size),contentType:_.type||null},o),{fields:w=null,url:k,cdn:E}=await S.bind(this)("get-signed-url",A,{auth:!!this.__user});u.push(E);let N=new FormData;for(let U in w)N.append(U,w[U]);N.append("file",_);try{await d(k,N,typeof i=="function"?U=>i({status:"upload",progress:Pr(U.loaded,U.total),currentFile:h,completed:g,failed:f,loaded:U.loaded,total:U.total,abort:()=>a.abort()}):null),g.push(h);}catch{f.push(h);}}return {completed:g,failed:f,bin_endpoints:u}}var kt={};function P(e){let{preventMultipleCalls:t=false}=e||{};return function(r,n,i){let s=i.value;i.value=function(...o){let a=o[0],d=true,c=null,g="",f={},u=false;if(Ri&&a instanceof SubmitEvent){a.preventDefault();let b=window.location.href;c=a.target;let A=new URL(c.action);g=A.href;let w=g?g.match(/(?<=\{).*?(?=\})/g):"";if(w)for(let k of w){if(!k)continue;let E=c.querySelector(`[name="${k}"]`);if(E)if(E.type==="file")for(let N=0;N<=E.files.length-1;N++)E.files[N]&&(f[k]||(f[k]=[]),f[k].push(new Promise((U,C)=>{let v=new FileReader;v.onload=function(){U(v.result);},v.readAsDataURL(E.files[N]),v.onerror=C;})));else g=g.replace(`{${k}}`,E.value);}c.getAttribute("action")===null?d=false:u=A.href===b;}let p=async b=>{if(g)for(let A in f)f[A].length&&(g=g.replace(`{${A}}`,(await Promise.all(f[A])).join(",")));if(c&&d){let A=L.call(this)?Da(b):b;window.sessionStorage.setItem(`${this.service}:${Z.hash(g)}`,JSON.stringify(A)),u?window.location.replace(g):window.location.href=g;}return b},h,m=b=>{throw b instanceof l?b.name=n+"()":b=b instanceof Error?b:new l(b,{name:n+"()"}),b},_=async()=>{try{if(this.__projectIdInput&&await this.__projectIdInput,h=s.bind(this)(...o),h instanceof Promise){let b=await h;return p(b)}return p(h)}catch(b){throw m(b)}};if(t){let b=`${n}:${this?.__public_identifier||""}:${this?.service||""}:${this?.owner||""}`;return kt?.[b]||(kt[b]=_().finally(()=>{delete kt[b];})),kt[b]}return _()};}}async function Si(){await this.__connection;let e=`${this.service}:${Z.hash(window.location.href.split("?")[0])}`,t=window.sessionStorage.getItem(e);if(window.sessionStorage.removeItem(e),t!==null){try{t=JSON.parse(t);}catch{}return t}return null}var Ua=256,Ca=256,Oa=256,ki=256,La="\u{10FFFF}",Ma=/[\u0000-\u001F\u007F]|\u{10FFFF}/u,Fa={"/":"%2F","!":"%21","*":"%2A","#":"%23"},qa={"%2F":"/","%21":"!","%2A":"*","%23":"#"};function Va(e){return e.replace(/%/g,"%25").replace(/[\/!*#]/g,r=>Fa[r]||r)}function le(e){return typeof e!="string"?e:e.replace(/%(2F|21|2A|23)/gi,r=>{let n=r.toUpperCase();return qa[n]||r}).replace(/%25/gi,"%")}function fe(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(Ma.test(e)||e.includes(La))throw new l(`"${t}" cannot include control characters or unsupported sentinel characters.`,{code:"INVALID_PARAMETER"});if(s&&(e=Va(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 Me(e,t="table.name",r={}){return fe(e,t,{allowEmpty:r.allowEmpty===true,maxLength:Ua,blockKeyDelimiters:true})}function Nt(e,t="tag",r={}){return fe(e,t,{allowEmpty:r.allowEmpty===true,maxLength:Ca,blockKeyDelimiters:true})}function st(e,t="index.name",r={}){return fe(e,t,{allowEmpty:r.allowEmpty===true,maxLength:Oa,blockKeyDelimiters:true,disallowLeadingDollar:true})}function vi(e,t="index.value"){return fe(e,t,{allowEmpty:true,maxLength:ki})}function Sr(e){return typeof e=="string"&&e.slice(-1)==="."}function kr(e,t){return fe(e,t,{allowEmpty:true,maxLength:ki,blockKeyDelimiters:true})}function Ni(e){if(!e.record_id&&!e.unique_id)return null;let t={};return e?.service&&(t.service=e.service),e?.owner&&(t.owner=e.owner),e?.record_id?t.record_id=fe(e.record_id,"record_id",{allowEmpty:false,onlyAlphanumeric:true}):e?.unique_id&&(t.unique_id=e.unique_id),t}function vr(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 vt=4503599627370496;function Dt(e){if(typeof e=="number"){if(e>vt||e<-vt)throw new l(`Number value should be within range -${vt} ~ +${vt}`,{code:"INVALID_PARAMETER"});return e}if(typeof e=="boolean")return e;if(typeof e=="string")return vi(e,"index.value");throw new l('"index.value" should be type: <number | boolean | string>.',{code:"INVALID_PARAMETER"})}function Di(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"?Sr(t.index.name)?kr(e,"index.range"):vi(e,"index.range"):e}var xt={},ja=10080*60,$a=3600,xi=2;function Ba(e,t){if(!t)return String(xi);let r=Math.max(60,e-300)*1e3;return "g"+xi+"w"+Math.floor(Date.now()/r)}function Ka(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 Ha(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 Ut(e){return typeof e=="string"?e:e&&typeof e.text=="function"?await e.text():await new Promise((t,r)=>{try{let n=new FileReader;n.onload=()=>t(n.result),n.onerror=()=>r(n.error||new Error("Failed to read blob")),n.readAsText(e);}catch(n){r(n);}})}function Dr(e){return !!e&&typeof e=="object"&&!Array.isArray(e)&&typeof e.__data__=="string"&&Object.keys(e).length===1&&e.__data__.endsWith("/__data__/__json__.json")}var Fe=new Map,Ga=1024,Wa=/^[0-9A-Za-z]+\/[0-9A-Za-z]+\/__data__\/__json__\.json$/,Ci=/^[0-9A-Za-z_-]+$/,Qa=/^(\d{2}|\*\*)$/;function Oi(e){if(typeof e!="string")return null;let t=e.split("?")[0].split("/");if(t.length<15||t[0]!=="https:"||t[1]!==""||!t[2])return null;let r=t.slice(3);return r[0]!=="publ"&&r[0]!=="auth"||r[4]!=="records"||r[7]!=="bin"||!Ci.test(r[1])?null:{origin:t.slice(0,3).join("/"),service:r[1]}}function za(e){let t=Oi(e);!t||Fe.get(t.service)===t.origin||(Fe.size>=Ga&&!Fe.has(t.service)&&Fe.clear(),Fe.set(t.service,t.origin));}function Ui(e,t){if(typeof t!="string"||!Wa.test(t))return null;let r=typeof e.usr_tbl=="string"?e.usr_tbl.split("/"):null,n=typeof e.tbl=="string"?e.tbl.split("/"):null,i=null,s=null;if(typeof e.srvc=="string"){let g=e.srvc.split("!")[0].split("/");g.length===2&&(i=g[0],s=g[1]);}i||(i=r?.[2]||n?.[1]||null,i&&i===this.service&&(s=this.owner));let o=typeof e.usr=="string"&&e.usr?e.usr:r?.[0]||null,a=r?.[3]||n?.[2]||null,d=e.rec;for(let g of [i,s,o,d])if(typeof g!="string"||!Ci.test(g))return null;if(typeof a!="string"||!Qa.test(a))return null;let c=null;if(Array.isArray(e.bin))for(let g of e.bin){let f=Oi(g);if(f&&f.service===i){c=f.origin;break}}return c=c||Fe.get(i)||null,c?`${c}/${a==="00"?"publ":"auth"}/${i}/${s}/${o}/records/${d}/${a}/bin/${t}`:null}async function Se(e,t,r=false,n=false,i=false){let s={user_id:"",record_id:"",updated:0,uploaded:0,readonly:false,table:{name:"",access_group:0,subscription:{is_subscription_record:false,upload_to_feed:false,notify_subscribers:false,feed_referencing_records:false,notify_referencing_records:false}},referenced_count:0,source:{referencing_limit:null,prevent_multiple_referencing:false,can_remove_referencing_records:false,only_granted_can_reference:false},ip:"",bin:{}},o=false,a=[],d=null;function c(u){let p=u=="**"?"private":parseInt(u);return p=p==0?"public":p==1?"authorized":p==99?"admin":p,p}let g={ip:u=>{let p=u.split("#"),h=p[0];p.length>1&&(s.unique_id=p.slice(1).join("#")),h.slice(-1)==="R"?(s.readonly=true,h=h.slice(0,-1)):s.readonly=false,/^\d{1,3}-\d{1,3}-\d{1,3}-\d{1,3}$/.test(h)&&(h=h.split("-").join("."),o=true),s.ip=h;},rec:u=>{if(!u)return;s.record_id=u;let p=u.substring(0,u.length-9),h=se(p);s.uploaded=h;},usr:u=>{s.user_id=u;},tbl:u=>{if(u&&!s.table.name){let p=u.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:u=>{let p=u.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:u=>{if(!u)return;let p=u.split("!"),h=le(p.splice(0,1)[0]),m=Ja("!"+p.join("!"));s.index={name:h,value:m};},ref:u=>{u&&(s.reference=u.split("/")[0]);},tags:u=>{s.tags=Array.isArray(u)?u.map(p=>le(p)):u;},upd:u=>{s.updated=u;},acpt_mrf:u=>{s.source.prevent_multiple_referencing=!u;},ref_limt:u=>{s.source.referencing_limit=u;},rfd:u=>{s.referenced_count=u;},bin:async u=>{let p={},h=s?.reference||null;if(Array.isArray(u)){let m=await Promise.all(u.map(async _=>{try{let b=_.split("/").slice(3).join("/"),A=b.split("/");if(A.length<12)return null;let w=A[A.length-1],k=A[10];if(k==="__data__"&&w==="__json__.json")return {isDataFile:!0,rawUrl:_};if(fr(k,w))return {isDataFile:!0,rawUrl:_};let E=It(k),N=A[9],U=A[8],C=c(A[6]),v=_,x=C!=="public"&&Ka.call(this,A)?{expires:$a,browserCache:ja}:null;if(C!=="public"&&!i)try{v=await _e.bind(this)(_,{dataType:"endpoint",_ref:h});}catch(V){console.error("Error getting signed url for private file:",V),v=_;}let O={access_group:C,filename:w,url:v,path:b,size:E?E.plainSize:se(N),uploaded:se(U),getFile:(V,de)=>{let ie={dataType:V||"download",progress:de,_ref:h},M=()=>_e.bind(this)(v,Object.assign({},ie,{_update:O}));return x?_e.bind(this)(_,Object.assign({},ie,x)).catch(()=>M()):M()}};return E&&(O.encrypted=!0,O.stored_size=se(N)),{pathKey:E?E.key:k,obj:O}}catch{return null}}));for(let _ of m)if(_&&!_.isDataFile){if(p[_.pathKey]){p[_.pathKey].push(_.obj);continue}p[_.pathKey]=[_.obj];}}s.bin=p;},prv_acs:u=>{for(let p in u)["notify_subscribers","upload_to_feed","feed_referencing_records","notify_referencing_records"].includes(p)?s.table.subscription[p]=u[p]:p==="referencing_index_restrictions"&&Array.isArray(u[p])?s.source[p]=u[p].map(m=>m&&typeof m=="object"&&typeof m.name=="string"?Object.assign({},m,{name:le(m.name)}):m):s.source[p]=u[p];},data:async u=>{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:d},h=()=>{L.call(this)&&(s.encrypted={status:"failed",reason:"DATA_UNAVAILABLE"});},m=async b=>{if(n||!L.call(this)&&!Et(b))return b;let A=await Dn.bind(this)(b,p);return A.flag&&(s.encrypted=A.flag),A.value},_=Ha(u);if(_!==u){s.data=await m(_);return}if(Dr(u)){let b=u.__data__,A=a.find(w=>w.endsWith(b))||null;if(!A&&!r){await Promise.resolve();let w=Ui.call(this,e,b),k=false,E;if(w)try{let N=await _e.bind(this)(w,{dataType:"blob",_ref:s.reference||null});E=JSON.parse(await Ut(N)),k=!0;}catch{}if(k){s.data=await m(E);return}h();}if(A){if(r){s.data=u;return}try{let w=await _e.bind(this)(A,{dataType:"blob",_ref:s.reference||null}),k=await Ut(w);s.data=await m(JSON.parse(k));}catch(w){let k=Ui.call(this,e,b),E=false,N;if(k&&k!==A)try{let U=await _e.bind(this)(k,{dataType:"blob",_ref:s.reference||null});N=JSON.parse(await Ut(U)),E=!0;}catch{}if(E){s.data=await m(N);return}console.error("Failed to fetch offloaded record data:",w),s.data=null,h();}return}}s.data=await m(u);}};if(e.record_id)return e;if(Array.isArray(e.bin))for(let u of e.bin)try{if(typeof u!="string")continue;za(u);let p=u.split("/").slice(3);p.length>=12&&p[10]==="__data__"&&p[p.length-1]==="__json__.json"&&a.push(u),p.length>=12&&fr(p[10],p[p.length-1])&&(d=u);}catch{}let f=[];for(let u in g)if(e.hasOwnProperty(u)){let p=g[u](e[u]);p instanceof Promise&&f.push(p);}return o&&(s.user_id="anonymous:"+s.user_id),await Promise.all(f),s}function Ja(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 Li(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 S.bind(this)("del-files",{endpoints:t,storage:"records"},{auth:true,method:"post"}),n=[];for(let i in r)n.push(Se.bind(this)(r[i]));return Promise.all(n)}async function _e(e,t){if(typeof e!="string")throw new 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,d=o.split("/"),g=d[2].split("."),f=null;g.length===3&&g[1]==="skapi"&&(f=g[0],a=true);let u=d.slice(3),p=false;if(!a&&(u[0]==="auth"||u[0]==="publ"))try{y.UserId(u[2]),y.UserId(u[3]),p=u[0]=="auth",a=!0;}catch{throw new l("Invalid file url.",{code:"INVALID_PARAMETER"})}let h=f?null:u[1];if(t=y.Params(t,{expires:["number",()=>0],browserCache:["number",()=>0],refresh:["boolean",()=>false],dataType:["base64","blob","endpoint","text","info",()=>"download"],progress:["function","undefined",null],_ref:[null,"string"],_update:w=>w}),t?.dataType==="info")return {url:e,filename:u[u.length-1],fileKey:u[u.length-2],access_group:u[6]==="**"?"private":u[6]==="01"?"authorized":u[6]==="00"?"public":parseInt(u[6]),uploader:u[3],record_id:u[4]==="records"?u[5]:"N/A",filesize:se(u[9]),uploaded:se(u[8])};let m=e.split("/").slice(-1)[0],_=t.expires;if(_){if(!a)throw new l("Expires option can only be used on skapi cdn endpoints.",{code:"INVALID_PARAMETER"});if(_<0)throw new l('"config.expires" should be > 0. (seconds)',{code:"INVALID_PARAMETER"});let w={request:f?"get-host":"get",id:f||u[5],key:r.split("?")[0],expires:_};h&&(w.service=h);let k=t.browserCache,E={auth:true};if(k){if(k<0)throw new l('"config.browserCache" should be > 0. (seconds)',{code:"INVALID_PARAMETER"});E.method="get",E.stableGateway=true,w.browser_cache=k;let N=this.session?.idToken?.payload?.sub||this.user?.user_id;N&&(w.uid=N),w.nocache=Ba(_,t.refresh);}e=(await S.bind(this)("get-signed-url",w,E)).url;}else if(p){let w=Math.floor(Date.now()/1e3);if(!this.bearerToken&&(!this.session?.idToken?.payload?.exp||this.session.idToken.payload.exp<w)){this.log("getFile:requesting new token",null);try{await W.bind(this)().getSession({refreshToken:!0}),this.log("getFile:received new tokens",{exp:this.session?.idToken?.payload?.exp,currTime:w,expiresIn:this.session?.idToken?.payload?.exp-w,token:this.session?.accessToken?.jwtToken,refreshToken:this.session?.refreshToken?.token});}catch(U){throw this.log("getFile:new token error",U),new l("User login is required.",{code:"INVALID_REQUEST"})}}let k=this.bearerToken||this.session?.idToken?.jwtToken;if(!k||!this.user?.user_id)throw new l("User login is required.",{code:"INVALID_REQUEST"});e+=`${e.includes("?")?"&":"?"}t=${encodeURIComponent(k)}`;let E=u[6]==="**"?"**":parseInt(u[6]),N=this.user?.access_group??-1;if(this.user.user_id!==u[3]&&(E==="**"||N<E)){let U=u[5];if(this.__private_access_key[U]&&typeof this.__private_access_key[U]=="string")e+=`&p=${encodeURIComponent(this.__private_access_key[U])}`;else if(this.owner!==this.host)try{let C=await this.requestPrivateRecordAccessKey({record_id:U,reference_id:t?._ref});e+=`&p=${encodeURIComponent(C)}`;}catch{}}}if((L.call(this)?Ar(e):null)&&t?.dataType!=="endpoint"&&t?.dataType!=="info"){let w=await S.bind(this)(e,null,{method:"get",contentType:null,responseType:"blob",fetchOptions:{progress:t?.progress}},{ignoreService:true}),k=await Zn.bind(this)(e,w);if(t?.dataType==="blob")return k;if(t?.dataType==="text")return await Ut(k);if(t?.dataType==="base64")return await new Promise((U,C)=>{let v=new FileReader;v.onloadend=()=>U(v.result),v.onerror=()=>C(v.error),v.readAsDataURL(k);});let E=URL.createObjectURL(k),N=document.createElement("a");return N.href=E,document.body.appendChild(N),N.setAttribute("download",m),N.click(),document.body.removeChild(N),setTimeout(()=>URL.revokeObjectURL(E),6e4),null}if(t?.dataType==="endpoint")return t._update&&(t._update.url=e),e;if(t?.dataType==="download"){let w=document.createElement("a");return w.href=e,document.body.appendChild(w),w.setAttribute("download",m),w.target="_blank",w.click(),document.body.removeChild(w),null}return new Promise(async(w,k)=>{try{let E=await S.bind(this)(e,null,{method:"get",contentType:null,responseType:t?.dataType==="text"?"text":"blob",fetchOptions:{progress:t?.progress}},{ignoreService:!0});if(t?.dataType==="base64"){let N=new FileReader;N.onloadend=()=>w(N.result),N.readAsDataURL(E);}else w(E);}catch(E){if(t?.browserCache&&!t?.refresh)try{w(await _e.bind(this)(r,Object.assign({},t,{refresh:!0})));return}catch(N){k(N);return}k(E);}})}function Ct(e,t){return `${e||this.service}/${t||this.owner}`}function Nr(e,t){let r=this.__my_unique_ids[e];return r?r[t]:void 0}function Mi(e,t,r){this.__my_unique_ids[e]||(this.__my_unique_ids[e]={}),this.__my_unique_ids[e][t]=r;}function Ya(e,t){this.__my_unique_ids[e]&&delete this.__my_unique_ids[e][t];}function Fi(e,t){return !t||t.table===void 0?e:Object.assign({},e,{table:t.table})}async function ot(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 qi(e,t=false){e=$(e,{ignoreEmpty:true}).data||{};let r=Ct.bind(this)(e?.service,e?.owner),n="",i=Ni(e);if(i){if(e=i,n=e.record_id||e.unique_id,typeof n=="string"){typeof this.__private_access_key?.[n]=="string"&&(e.private_key=this.__private_access_key?.[n]||void 0);let s=Nr.bind(this)(r,n);s&&(t?Ya.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 d=c=>({table:{name:g=>Me(g,"table.name"),access_group:vr.bind(this),subscription:g=>y.UserId(g,'User ID in "subscription"')},reference:"string",index:{name:["$updated","$uploaded","$referenced_count","$user_id",g=>st(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 u=f[c.index.name];if(typeof u=="function")return u(g);if(u!==typeof g)throw new l(`"index.value" should be type: ${u}.`,{code:"INVALID_PARAMETER"});return g}return typeof g=="string"&&!g?"":typeof g=="string"&&Sr(c.index.name)?kr(g,"index.value"):Dt(g)},condition:["gt","gte","lt","lte",">",">=","<","<=","=","eq"],range:g=>Di(g,c)},tag:g=>{if(g==null)return g;if(typeof g=="string")return Nt(g,"tag");throw new l('"tag" should be type: string.',{code:"INVALID_PARAMETER"})},private_key:"string"});e=y.Params(e||{},d(e),a||s?[]:["table"],{ignoreEmpty:true});}return {query:e,is_reference_fetch:n}}async function Vi(e,t){await this.__connection,await ot.call(this,"getRecords");let r=await qi.bind(this)(e),n=r.is_reference_fetch,i=await S.bind(this)("get-records",r.query,{fetchOptions:t,auth:!!this.__user,method:this.__user?"post":"get"});n&&i?.reference_private_key&&typeof i.reference_private_key=="string"&&(this.__private_access_key[n]=i.reference_private_key);let s=[];for(let o in i.list)s.push(Se.bind(this)(i.list[o]));return i.list=await Promise.all(s),i}function ji(e){let t="",r=[],n=Ct.bind(this)(e?.service,e?.owner),i=y.Params(e||{},{record_id:o=>{let a=typeof o=="string"?Nr.bind(this)(n,o):void 0;return a||fe(o,"record_id",{allowEmpty:false})},unique_id:["string",null],readonly:"boolean",table:{name:o=>Me(o,"table.name"),subscription:[null,{is_subscription_record:"boolean",upload_to_feed:"boolean",notify_subscribers:"boolean",feed_referencing_records:"boolean",notify_referencing_records:"boolean"}],access_group:vr.bind(this)},notification:o=>{if(o==null)return o;if(typeof o!="object"||Array.isArray(o))throw new l('"notification" should be an object with "title" and "body".',{code:"INVALID_PARAMETER"});for(let a of ["title","body"])if(typeof o[a]!="string"||!o[a].trim())throw new l(`"notification.${a}" is required.`,{code:"INVALID_PARAMETER"});return {title:o.title,body:o.body}},source:{referencing_limit:o=>{if(o===null)return null;if(typeof o=="number"){if(0>o)throw new l('"reference_limit" should be >= 0',{code:"INVALID_PARAMETER"});if(o>4503599627370546)throw new l('"reference_limit" should be <= 4503599627370546',{code:"INVALID_PARAMETER"});return o}throw new l('"reference_limit" should be type: <number | null>',{code:"INVALID_PARAMETER"})},prevent_multiple_referencing:"boolean",can_remove_referencing_records:"boolean",only_granted_can_reference:"boolean",allow_granted_to_grant_others:"boolean",referencing_index_restrictions:o=>{if(o===void 0)return;if(!o||Array.isArray(o)&&!o.length)return null;let a={name:c=>st(c,'"name" in "index_restrictions"'),value:c=>Dt(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 d=o.map(c=>y.Params(c,a,["name"]));if(d.length)for(let c of d)c.condition&&c.hasOwnProperty("range")&&delete c.range;return d}},reference:o=>{if(o===null)return {record_id:null};if(o){if(typeof o=="string"){t=o;let a=Nr.bind(this)(n,o);return a||o}if(typeof o!="object")throw new 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),fe(a,"reference.record_id",{allowEmpty:false,onlyAlphanumeric:true}))})}},index:[null,{name:o=>st(o,"index.name"),value:o=>Dt(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=>Nt(a,"tag"))},remove_bin:o=>{if(!o)return null;let a=[];if(Array.isArray(o))for(let d of o)if(typeof d=="string")a.push(d.split("?")[0]);else if(d.url&&d.size&&d.filename){let g=d.url.split("/").slice(0,3).join("/")+"/"+d.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 $i(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={},o={},d={_is_bulk_:await Promise.all(e.map(async(h,m)=>{if(!h||typeof h!="object"||Array.isArray(h))throw new l(`"params[${m}]" should be type: <object>.`,{code:"INVALID_PARAMETER"});o[m]={has:h.data!==void 0,value:h.data};let _=ji.bind(this)(h),b=_.config;if(L.call(this)){let A=Object.prototype.hasOwnProperty.call(b,"data"),w=await gr.bind(this)(b.data,Fi(h,b),A);w.encrypted&&(b.data=w.send,s[m]=w.plain);}if(_.is_reference_post&&t.push(_.is_reference_post),typeof b.progress=="function"&&i===null&&(i=b.progress),b.service!==void 0){if(r===void 0)r=b.service;else if(r!==b.service)throw new l('All bulk params should share the same "service" value.',{code:"INVALID_PARAMETER"})}if(b.owner!==void 0){if(n===void 0)n=b.owner;else if(n!==b.owner)throw new l('All bulk params should share the same "owner" value.',{code:"INVALID_PARAMETER"})}return delete b.progress,delete b.service,delete b.owner,b})),service:"",owner:""};r!==void 0&&(d.service=r),n!==void 0&&(d.owner=n);let c={auth:!!this.__user,method:"post"},g={};Object.keys(g).length&&Object.assign(c,{fetchOptions:g});let f=await S.bind(this)("post-record",d,c),u=await Promise.all(f.map((h,m)=>Se.bind(this)(h,"called from postRecord",o[m]?.has===true,s.hasOwnProperty(m))));for(let h=0;h<u.length;h++)s.hasOwnProperty(h)&&u[h]&&!u[h].error?(u[h].data=s[h],u[h].encrypted={status:"encrypted"}):o[h]?.has&&u[h]&&!f[h]?.error&&Dr(f[h]?.data)&&(u[h].data=o[h].value);let p=Ct.bind(this)(r,n);for(let h=0;h<f.length;h++){let m=f[h],_=u[h];if(m&&typeof m=="object"&&m.error&&_&&!_.record_id&&(_.error=m.error),typeof m?.reference_private_key=="string")for(let b of t)this.__private_access_key[b]=m.reference_private_key;_?.unique_id&&Mi.bind(this)(p,_.unique_id,_.record_id);}return u}async function xr(e,t,r){if(await this.__connection,!t)throw new l('"config" argument is required.',{code:"INVALID_PARAMETER"});let n=ji.bind(this)(t),i=n.config,s=n.progress,o=n.is_reference_post,a={auth:!!this.__user,method:"post"},d=[],c=$(e);r&&Array.isArray(r)&&r.length&&(d=d.concat(r)),c.files&&Array.isArray(c.files)&&c.files.length&&(d=d.concat(c.files));let g=t?.data!==void 0?t.data:c.data,f=g!==void 0,u=await gr.bind(this)(g,Fi(t,i),f),p=null;p=Object.assign({},i),delete p.data,u.omit||(p.data=u.send);let h={};if(typeof s=="function"&&(h.progress=s),Object.keys(h).length&&Object.assign(a,{fetchOptions:h}),u.files==="decrypt"&&t?.record_id){let w=await Rr.bind(this)(t.record_id,"decrypt",s);if(w.length){let k=p.remove_bin;p.remove_bin=Array.isArray(k)?k.concat(w):w;}}if(u.spill&&t?.record_id){let w=new FormData;if(w.append(et,new File([u.spill],"payload.bin",{type:"application/octet-stream"})),await it.bind(this)(w,{record_id:t.record_id}),u.retireCt){let k=p.remove_bin,E=[u.retireCt];p.remove_bin=Array.isArray(k)?k.concat(E):E;}}let m=await S.bind(this)("post-record",p,a);if(u.encrypted&&m?.rec&&vn.bind(this)(m.rec,u.dek),u.files==="encrypt"&&m?.rec)try{let w=await Rr.bind(this)(m.rec,"encrypt",s);w.length&&await xr.bind(this)(void 0,{record_id:m.rec,remove_bin:w});}catch(w){console.error("Failed to encrypt existing attachments after making the record private:",w);}if(H()&&d.length){let w=new FormData;for(let N of d)w.append(N.name,N.file,N.file.name);let k={record_id:m.rec,progress:s};i.hasOwnProperty("service")&&(k.service=i.service);let{bin_endpoints:E}=await it.bind(this)(w,k);m.bin?m.bin.push(...E):m.bin=E;}o&&typeof m?.reference_private_key=="string"&&(this.__private_access_key[o]=m.reference_private_key);let _=!!m&&Dr(m.data),b=!u.omit&&u.send!==void 0,A=await Se.bind(this)(m,"called from postRecord",b,u.encrypted);if(_&&b&&!u.encrypted&&(A.data=u.plain),u.encrypted&&(A.data=u.plain,A.encrypted={status:"encrypted",recipients:Object.keys(u.send.k||{})}),A.unique_id){let w=Ct.bind(this)(i?.service,i?.owner);Mi.bind(this)(w,A.unique_id,A.record_id),H()&&(this.__uniqueIdsPersistTimer!==null&&clearTimeout(this.__uniqueIdsPersistTimer),this.__uniqueIdsPersistTimer=setTimeout(()=>{this.__uniqueIdsPersistTimer=null;try{window.sessionStorage.setItem(`${w}:uniqueids`,JSON.stringify(this.__my_unique_ids[w]||{}));}catch{}},500));}return A}async function Bi(e,t){await ot.call(this,"getTables");let r=await S.bind(this)("get-table",y.Params(e||{},{table:i=>Me(i,"table",{allowEmpty:true}),condition:["gt","gte","lt","lte",">",">=","<","<=","=","eq","!=","ne"]}),Object.assign({auth:!!this.__user},{fetchOptions:t})),n={cnt_rec:"number_of_records",tbl:"table",srvc:"service",grp_:"number_of_records_in_access_group_"};if(Array.isArray(r?.list))for(let i of r.list){for(let s in n){if(s==="grp_"){for(let o in i)if(o.startsWith("grp_")){let 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 ot.call(this,"getIndexes"),!e?.table)throw new l('"table" is required.',{code:"INVALID_PARAMETER"});let r=y.Params(e||{},{table:s=>Me(s,"table",{allowEmpty:true}),index:s=>st(s,"index.name"),order:{by:["average_number","total_number","number_count","average_bool","total_bool","bool_count","string_count","index_name","number_of_records"],value:s=>{if(e?.order?.by==="index_name"&&typeof s=="string")return fe(s,"order.value",{allowEmpty:true,maxLength:256,blockKeyDelimiters:true});if(typeof s!="string"&&typeof s!="number"&&typeof s!="boolean")throw new 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 S.bind(this)("get-index",r,Object.assign({auth:!!this.__user},{fetchOptions:t})),i={cnt_bool:"boolean_count",cnt_numb:"number_count",totl_numb:"total_number",totl_bool:"total_bool",avrg_numb:"average_number",avrg_bool:"average_bool",cnt_str:"string_count"};return Array.isArray(n?.list)&&(n.list=n.list.map(s=>{let o=s.idx.split("/"),a={table:le(o[1]),index:le(o[2]),number_of_records:s.cnt_rec};for(let d in i)Object.prototype.hasOwnProperty.call(s,d)&&(a[i[d]]=s[d]);return a})),n}async function Hi(e,t){await ot.call(this,"getTags");let r=await S.bind(this)("get-tag",y.Params(e||{},{table:n=>Me(n,"table",{allowEmpty:true}),tag:n=>Nt(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 Gi(e,t){await ot.call(this,"getUniqueId");let r=await S.bind(this)("get-uniqueid",y.Params(e||{},{unique_id:"string",condition:["gt","gte","lt","lte",">",">=","<","<=","=","eq","!=","ne"]}),Object.assign({auth:!!this.__user},{fetchOptions:t}));if(Array.isArray(r?.list))for(let n in r.list){let i=r.list[n];r.list[n]={unique_id:i.unq,record_id:i.rec};}return r}async function Wi(e,t){await this.__connection;let r=await qi.bind(this)(e,true),n=r.is_reference_fetch,i=await S.bind(this)("del-records",r.query,{auth:true,fetchOptions:t});return n&&typeof i?.reference_private_key=="string"&&(this.__private_access_key[n]=i.reference_private_key),Array.isArray(i?.list)&&(i.list=await Promise.all(i.list.map(async s=>{if(!s||typeof s!="object")return s;try{return await Se.bind(this)(s,"called from deleteRecords",!0,!1,!0)}catch{return s}}))),i?.message||i}async function Qi(e){if(L.call(this)){let t=typeof e.user_id=="string"?[e.user_id]:e.user_id;Array.isArray(t)&&t.length&&await Er.bind(this)(e.record_id,t);}return Xi.bind(this)({record_id:e.record_id,user_id:e.user_id,execute:"add"})}async function zi(e){let t=await Xi.bind(this)({record_id:e.record_id,user_id:e.user_id||null,execute:"remove"});if(L.call(this)){let r=typeof e.user_id=="string"?[e.user_id]:e.user_id;await Kn.bind(this)(e.record_id,Array.isArray(r)&&r.length?r:null);}return t}async function Ji(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 S.bind(this)("grant-private-access",r,{auth:true,fetchOptions:t});return i.list=i.list.map(n),i}function Yi(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(xt[t])return xt[t];let n=S.bind(this)("request-private-access-key",{record_id:t,reference_id:r},{auth:true}).then(i=>{let s=typeof i=="string"?i:i?.private_key;if(typeof s!="string")throw new l("Invalid private access key response.",{code:"ERROR"});return this.__private_access_key[t]=s,s}).finally(()=>{delete xt[t];});return xt[t]=n,n}function Xi(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),S.bind(this)("grant-private-access",r,{auth:true})}var D={},G={},ce={},pe={},ge={},Ot={},Lt={};function Zi(e,t,r){e[t]||(e[t]=[]),e[t].push(r);}async function Mt(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 Cr(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 D[s].setRemoteDescription(new RTCSessionDescription(i));let a=await D[s].createAnswer();await D[s].setLocalDescription(a),o.send(JSON.stringify({action:"rtc",uid:s,content:{sdpanswer:a},token:this.session.accessToken.jwtToken}));}D?.[t]?e?(await Mt(Lt,t,i=>n.bind(this)(i,t,r)),await n.bind(this)(e,t,r)):await Mt(Lt,t,i=>n.bind(this)(i,t,r)):e&&Zi(Lt,t,e);}async function Or(e,t){if(this.log("receiveIceCandidate",e),D?.[t]&&D[t]?.remoteDescription&&D[t]?.remoteDescription?.type){if(!e)return Mt(Ot,t,r=>D[t].addIceCandidate(r));await Mt(Ot,t,r=>D[t].addIceCandidate(r)),await D[t].addIceCandidate(e);}else Zi(Ot,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 Lt[s],delete Ot[s],G[s]&&Object.values(G[s]).forEach(o=>{o.readyState!=="closed"&&o.close();}),delete G[s],D?.[s]){D[s].connectionState!=="closed"&&(D[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:D[s],timestamp:new Date().toISOString(),state:D[s].connectionState,iceState:D[s].iceConnectionState,signalingState:D[s].signalingState};ge[s]&&ge[s](o),this.log("closeRTC",o);}delete ge[s],delete pe[s],delete ce[s],delete D[s];};if(n)for(let s in D)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 es(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 ts(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}]};D?.[r]||(D[r]=new RTCPeerConnection(s)),e?.media&&(this.__mediaStream=await es(e.media),this.__mediaStream.getTracks().forEach(o=>{D[r].addTrack(o,this.__mediaStream);})),ge[r]=t,G[r]||(G[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 d=a.protocol||"default";if(Object.keys(G[r]).includes(d))throw new l(`Data channel with the protocol "${d}" already exists.`,{code:"INVALID_REQUEST"});let c=D[r].createDataChannel(d,a);G[r][d]=c;}for(let o in G[r]){let a=G[r][o];is.bind(this)(r,a);}return ns.bind(this)(r,["onnegotiationneeded"]),await Ur.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;D[r].onnegotiationneeded=()=>{this.log("onnegotiationneeded",`sending offer to "${r}".`),Ur.bind(this)(r),ge[r]&&ge[r]({type:"negotiationneeded",target:D[r],timestamp:new Date().toISOString(),signalingState:D[r].signalingState,connectionState:D[r].iceConnectionState,gatheringState:D[r].iceGatheringState});},o({target:D[r],channels:G[r],hangup:()=>ue.bind(this)({cid:r}),media:this.__mediaStream});}).bind(this);})}}function rs(e){return async(t,r)=>{t=t||{},t=$(t).data;let n=e.sender_cid,i=await this.__socket;if(!pe[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 D?.[n]||(D[n]=new RTCPeerConnection({iceServers:[{urls:s}]})),t?.media&&(this.__mediaStream=await es(t.media),this.__mediaStream.getTracks().forEach(o=>{D[n].addTrack(o,this.__mediaStream);})),delete pe[n],ge[n]=r,G[n]||(G[n]={}),D[n].ondatachannel=o=>{this.log("ondatachannel",`received data channel "${o.channel.label}".`);let a=o.channel;G[n][a.label]=a,is.bind(this)(n,a);},ns.bind(this)(n,["onnegotiationneeded"]),await Cr.bind(this)(null,n),await Or.bind(this)(null,n),i.send(JSON.stringify({action:"rtc",uid:n,content:{pickup:this.user.user_id},token:this.session.accessToken.jwtToken})),{target:D[n],channels:G[n],hangup:()=>ue.bind(this)({cid:n}),media:this.__mediaStream}}}async function Ur(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 D[e].createOffer();await D[e].setLocalDescription(r);let n=D[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 Xa(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=ge[t]||(()=>{}),i=e.candidate;this.log("ice gathering state set to",D[t].iceGatheringState),n({type:"icecandidate",target:D[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:D[t].iceGatheringState,connectionState:D[t].iceConnectionState}),r.send(JSON.stringify({action:"rtc",uid:t,content:{candidate:i},token:this.session.accessToken.jwtToken}));}function ns(e,t){let r=new Set(t),n=ge[e]||(o=>{}),i=D[e],s={ontrack:o=>{n({type:"track",target:i,timeStamp:o.timeStamp,streams:o.streams,track:o.track});},onicecandidate:o=>{Xa.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:()=>{Ur.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 is(e,t,r){let n=new Set(r),i=ge[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),G[e]&&(delete G[e][t.label],Object.keys(G[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 we;function ss(){return we}var Re=null,at=true,qe=0;async function Za(){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 Lr=null;async function Ft(){if(typeof window>"u"||window._runningInNodeJS)throw new l("WebSocket is not supported in Node.js environment.",{code:"NOT_SUPPORTED"});at=true;let e=this.__socket?await this.__socket:this.__socket;ue.bind(this)({close_all:true}),we&&je.bind(this)({group:null}),qe=0,Re&&(Re.terminate(),Re=null);try{e&&e.close();}catch{}return window.removeEventListener("visibilitychange",Lr),this.__socket=null,null}async function Ve(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(at&&(Lr=()=>{!document.hidden&&!at&&Ve.bind(this)(e,0,"reconnect");},this.__socket instanceof Promise))return this.__socket;Re&&(Re.terminate(),Re=null);let n={value:null};return this.__socket=new Promise(async(i,s)=>{let o=a=>{this.__socket===n.value&&(this.__socket=null),s(a);};try{await Oe.bind(this)();}catch(a){o(a);return}setTimeout(async()=>{try{let a=await Za.bind(this)();a.onopen=()=>{at=!1,qe=0,r!=="reconnect"&&window.addEventListener("visibilitychange",Lr),this.log("realtime onopen","Connected to WebSocket server."),e({type:"success",message:"Connected to WebSocket server."}),we&&a.send(JSON.stringify({action:"joinRoom",rid:we,token:this.session.accessToken.jwtToken}));let d=`
|
|
206
|
+
var _o=Object.defineProperty;var wo=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 T=(e,t,r,n)=>{for(var i=wo(t,r),s=e.length-1,o;s>=0;s--)(o=e[s])&&(i=(o(t,r,i))||i);return i&&_o(t,r,i),i};function ve(e){let r=(typeof globalThis<"u"?globalThis:void 0)?.process;if(r&&typeof r.getBuiltinModule=="function")try{return r.getBuiltinModule(e)}catch{}try{if(typeof ke=="function")return ke(e)}catch{}return null}var Bt,Kt,Ht=()=>Bt!==void 0?Bt:Bt=ve("fs"),Gt=()=>Kt!==void 0?Kt:Kt=ve("path"),me=typeof globalThis<"u"?globalThis:void 0,pt=me?.window;function Eo(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(pt)pt.global=pt,pt.global._runningInNodeJS=false;else if(me&&(me.global=me,typeof me.window>"u")){class e{constructor(){this.result=null;this.error=null;this.onload=null;this.onloadend=null;this.onerror=null;}readAsDataURL(n){n.arrayBuffer().then(i=>{let s=Eo(i),o=n.type||"application/octet-stream";this.result=`data:${o};base64,${s}`,this.onload&&this.onload({target:this}),this.onloadend&&this.onloadend({target:this});}).catch(i=>{this.error=i,this.onerror&&this.onerror({target:this});});}readAsArrayBuffer(n){n.arrayBuffer().then(i=>{this.result=i,this.onload&&this.onload({target:this}),this.onloadend&&this.onloadend({target:this});}).catch(i=>{this.error=i,this.onerror&&this.onerror({target:this});});}readAsText(n,i="utf-8"){n.text().then(s=>{this.result=s,this.onload&&this.onload({target:this}),this.onloadend&&this.onloadend({target:this});}).catch(s=>{this.error=s,this.onerror&&this.onerror({target:this});});}}me.FileReader=e;class t{constructor(){this.status=0;this.statusText="";this.readyState=0;this.responseText="";this.response=null;this.responseType="";this.responseURL="";this.timeout=0;this.withCredentials=false;this.onload=null;this.onerror=null;this.onabort=null;this.ontimeout=null;this.onprogress=null;this.onreadystatechange=null;this.upload={onprogress:null};this._method="GET";this._url="";this._headers={};this._aborted=false;}open(n,i){this._method=n,this._url=i,this.readyState=1;}setRequestHeader(n,i){this._headers[n]=i;}getResponseHeader(n){return null}abort(){this._aborted=true,this.onabort&&this.onabort({});}send(n){if(this._aborted)return;let i={method:this._method,headers:this._headers};n&&this._method!=="GET"&&this._method!=="HEAD"&&(i.body=n),fetch(this._url,i).then(async s=>{if(!this._aborted){if(this.status=s.status,this.statusText=s.statusText,this.responseURL=s.url,this.readyState=4,this.responseType==="blob")this.response=await s.blob();else if(this.responseType==="json")try{this.response=await s.json();}catch{this.response=null;}else this.responseType==="arraybuffer"?this.response=await s.arrayBuffer():(this.responseText=await s.text(),this.response=this.responseText);this.onload&&this.onload({});}}).catch(s=>{this._aborted||this.onerror&&this.onerror(s);});}}me.XMLHttpRequest=t,me.window={_runningInNodeJS:true,alert:r=>console.error("[Alert]",r),sessionStorage:(()=>{let r=new Map;return {getItem:n=>r.has(n)?r.get(n):null,setItem:(n,i)=>{r.set(n,String(i));},removeItem:n=>{r.delete(n);}}})(),localStorage:{getItem:r=>{let n=Ht(),i=Gt();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=Ht(),s=Gt();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=Ht(),i=Gt();if(!(!n||!i))try{let s=i.resolve(process.cwd(),"states","localStorage",`${r}.skapi`);n.existsSync(s)&&n.unlinkSync(s);}catch{}}},location:{href:"",origin:"",hostname:"",protocol:"",replace:r=>{}},navigator:{userAgent:`nodejs/${me?.process?.versions?.node||"unknown"}`,mediaDevices:{getUserMedia:async r=>{throw new Error("getUserMedia is not supported in Node.js environment.")}}},addEventListener:()=>{},removeEventListener:()=>{}};}var 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 ye="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",Wt=BigInt(ye.length),Ao=2*1024*1024,Ro=["aud","cognito:username","event_id","exp","iat","iss","jti","origin_jti","secret_key","token_use"],Hr={auth_time:"log",sub:"user_id"},Jr=["0","1","2","3","4","5","6","7","8","9","a","b","c","d","e","f","g","h","i","j","k","l"],Yr=["us31","us72","ap51","ap22","ap41","eu71","ap21","us32","us71","af51","ap31","ap43","ap23","ap42","ca01","eu01","eu72","eu51","eu73","eu11","me51","sa31"],Gr=typeof TextEncoder<"u"?new TextEncoder:null;function Io(){if(typeof globalThis<"u")return globalThis.Buffer}function K(e){if(Gr)return Gr.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 Qt(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=Io();if(t)return new Uint8Array(t.from(e));throw new Error("No byte conversion available in this environment.")}var R=class R{static hash(t){typeof t!="string"&&(console.warn("coercing non-string value to empty string"),t="");let r=R.sb(t),n=1732584193,i=-271733879,s=-1732584194,o=271733878,a,d,c,g;for(let f=0;f<r.length;f+=16)a=n,d=i,c=s,g=o,n=R.ff(n,i,s,o,r[f],7,-680876936),o=R.ff(o,n,i,s,r[f+1],12,-389564586),s=R.ff(s,o,n,i,r[f+2],17,606105819),i=R.ff(i,s,o,n,r[f+3],22,-1044525330),n=R.ff(n,i,s,o,r[f+4],7,-176418897),o=R.ff(o,n,i,s,r[f+5],12,1200080426),s=R.ff(s,o,n,i,r[f+6],17,-1473231341),i=R.ff(i,s,o,n,r[f+7],22,-45705983),n=R.ff(n,i,s,o,r[f+8],7,1770035416),o=R.ff(o,n,i,s,r[f+9],12,-1958414417),s=R.ff(s,o,n,i,r[f+10],17,-42063),i=R.ff(i,s,o,n,r[f+11],22,-1990404162),n=R.ff(n,i,s,o,r[f+12],7,1804603682),o=R.ff(o,n,i,s,r[f+13],12,-40341101),s=R.ff(s,o,n,i,r[f+14],17,-1502002290),i=R.ff(i,s,o,n,r[f+15],22,1236535329),n=R.gg(n,i,s,o,r[f+1],5,-165796510),o=R.gg(o,n,i,s,r[f+6],9,-1069501632),s=R.gg(s,o,n,i,r[f+11],14,643717713),i=R.gg(i,s,o,n,r[f],20,-373897302),n=R.gg(n,i,s,o,r[f+5],5,-701558691),o=R.gg(o,n,i,s,r[f+10],9,38016083),s=R.gg(s,o,n,i,r[f+15],14,-660478335),i=R.gg(i,s,o,n,r[f+4],20,-405537848),n=R.gg(n,i,s,o,r[f+9],5,568446438),o=R.gg(o,n,i,s,r[f+14],9,-1019803690),s=R.gg(s,o,n,i,r[f+3],14,-187363961),i=R.gg(i,s,o,n,r[f+8],20,1163531501),n=R.gg(n,i,s,o,r[f+13],5,-1444681467),o=R.gg(o,n,i,s,r[f+2],9,-51403784),s=R.gg(s,o,n,i,r[f+7],14,1735328473),i=R.gg(i,s,o,n,r[f+12],20,-1926607734),n=R.hh(n,i,s,o,r[f+5],4,-378558),o=R.hh(o,n,i,s,r[f+8],11,-2022574463),s=R.hh(s,o,n,i,r[f+11],16,1839030562),i=R.hh(i,s,o,n,r[f+14],23,-35309556),n=R.hh(n,i,s,o,r[f+1],4,-1530992060),o=R.hh(o,n,i,s,r[f+4],11,1272893353),s=R.hh(s,o,n,i,r[f+7],16,-155497632),i=R.hh(i,s,o,n,r[f+10],23,-1094730640),n=R.hh(n,i,s,o,r[f+13],4,681279174),o=R.hh(o,n,i,s,r[f],11,-358537222),s=R.hh(s,o,n,i,r[f+3],16,-722521979),i=R.hh(i,s,o,n,r[f+6],23,76029189),n=R.hh(n,i,s,o,r[f+9],4,-640364487),o=R.hh(o,n,i,s,r[f+12],11,-421815835),s=R.hh(s,o,n,i,r[f+15],16,530742520),i=R.hh(i,s,o,n,r[f+2],23,-995338651),n=R.ii(n,i,s,o,r[f],6,-198630844),o=R.ii(o,n,i,s,r[f+7],10,1126891415),s=R.ii(s,o,n,i,r[f+14],15,-1416354905),i=R.ii(i,s,o,n,r[f+5],21,-57434055),n=R.ii(n,i,s,o,r[f+12],6,1700485571),o=R.ii(o,n,i,s,r[f+3],10,-1894986606),s=R.ii(s,o,n,i,r[f+10],15,-1051523),i=R.ii(i,s,o,n,r[f+1],21,-2054922799),n=R.ii(n,i,s,o,r[f+8],6,1873313359),o=R.ii(o,n,i,s,r[f+15],10,-30611744),s=R.ii(s,o,n,i,r[f+6],15,-1560198380),i=R.ii(i,s,o,n,r[f+13],21,1309151649),n=R.ii(n,i,s,o,r[f+4],6,-145523070),o=R.ii(o,n,i,s,r[f+11],10,-1120210379),s=R.ii(s,o,n,i,r[f+2],15,718787259),i=R.ii(i,s,o,n,r[f+9],21,-343485551),n=R.ad(n,a),i=R.ad(i,d),s=R.ad(s,c),o=R.ad(o,g);return R.rh(n)+R.rh(i)+R.rh(s)+R.rh(o)}static rh(t){let r="";for(let n=0;n<=3;n++)r+=R.alphabet.charAt(t>>n*8+4&15)+R.alphabet.charAt(t>>n*8&15);return r}static ad(t,r){let n=(t&65535)+(r&65535);return (t>>16)+(r>>16)+(n>>16)<<16|n&65535}static rl(t,r){return t<<r|t>>>32-r}static cm(t,r,n,i,s,o){return R.ad(R.rl(R.ad(R.ad(r,t),R.ad(i,o)),s),n)}static ff(t,r,n,i,s,o,a){return R.cm(r&n|~r&i,t,r,s,o,a)}static gg(t,r,n,i,s,o,a){return R.cm(r&i|n&~i,t,r,s,o,a)}static hh(t,r,n,i,s,o,a){return R.cm(r^n^i,t,r,s,o,a)}static ii(t,r,n,i,s,o,a){return R.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}};R.alphabet="0123456789abcdef";var Z=R;function Xr(e){if(e===0)return ye[0];let t="";for(;e>0;)t=ye[e%62]+t,e=Math.floor(e/62);return t}function se(e){return e.split("").reverse().reduce((t,r,n)=>t+ye.indexOf(r)*62**n,0)}function Ie(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 zt(){return typeof window>"u"||!!window?._runningInNodeJS}function H(){return !zt()&&typeof document<"u"&&typeof document.createElement=="function"}function ht(e){let t;try{t=JSON.stringify(e);}catch{throw new l("Invalid data type.",{code:"INVALID_REQUEST"})}if(new Blob([t]).size>Ao)throw new l("Data should not exceed 2MB",{code:"INVALID_REQUEST"})}function Wr(e){return e===""||e==="on"||e==="true"}function Qr(e){return e==="false"}function zr(e,t,r){t.name&&r(e,t.name,t.value);}var mt=H(),To=typeof SubmitEvent<"u",Po=typeof HTMLFormElement<"u";function $(e,t,r){let n={},i=[];function s(d,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 h=p.replace("]",""),m=Number(h);return !isNaN(m)&&!h.includes(".")?h=m:(h[0]==='"'&&h[h.length-1]==='"'||h[0]==="'"&&h[h.length-1]==="'")&&(h=h.replace(/"/g,"").replace(/'/g,"")),h}),u=d;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 h=f[p];p<f.length-1?(u[h]===void 0&&(typeof f[p+1]=="number"?u[h]=[]:u[h]={}),u=u[h]):u[h]===void 0?u[h]=g:Array.isArray(u[h])?u[h].push(g):u[h]=[u[h],g];}}function o(d,c,g){if(g instanceof File)d.push({name:c,file:g});else if(g instanceof FileList&&g&&g.length>0)for(let f=0;f<=g.length-1;f++){let u=g.item(f);u&&d.push({name:c,file:u});}}let a=d=>{d.name&&(d.type==="number"?d.value&&s(n,d.name,Number(d.value)):d.type==="checkbox"||d.type==="radio"?d.checked?d.type==="checkbox"&&d.value===""||Wr(d.value)?s(n,d.name,true):Qr(d.value)?s(n,d.name,false):d.value&&s(n,d.name,d.value):d.type==="checkbox"&&(Wr(d.value)?s(n,d.name,false):Qr(d.value)&&s(n,d.name,true)):d.type==="file"?d.files&&d.files.length>0&&o(i,d.name,d.files):s(n,d.name,d.value));};if(mt&&(e instanceof HTMLInputElement||e instanceof HTMLSelectElement||e instanceof HTMLTextAreaElement))return a(e),ht(n),{data:n,files:i};if(mt&&e instanceof FormData){for(let d of e.entries()){let c=d[0],g=d[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 u=JSON.parse(f.text());s(n,c,u);}catch{s(n,c,f);}}else s(n,c,g);}return ht(n),{data:n,files:i}}if(mt&&To&&e instanceof SubmitEvent&&(e=e.target),mt&&Po&&e instanceof HTMLFormElement){let d=e.querySelectorAll("input"),c=e.querySelectorAll("select"),g=e.querySelectorAll("textarea");for(let f=0;f<c.length;f++)zr(n,c[f],s);for(let f=0;f<g.length;f++)zr(n,g[f],s);for(let f=0;f<d.length;f++)a(d[f]);return ht(n),{data:n,files:i}}return ht(e),{data:e,files:i}}function Ke(e){let t={};for(let r in e){let n=e[r];if(!Ro.includes(r))if(Hr[r])t[Hr[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 Jt(e){if(e=Co(e),e.split("-").length===7){let t=e.split("-"),r,n;try{r=Yr[Jr.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 Yt(e,t){let r=Yr.indexOf(e.slice(0,4)),n=Jr[r],s=`${e.slice(4,-4)}-${n}${e.slice(-4)}-${t}`;return Uo(s)}function So(e){let t=0n;for(let r of e){let n=ye.indexOf(r);if(n<0)throw new Error(`INVALID_PARAMETER: Invalid base62 character: ${r}`);t=t*Wt+BigInt(n);}return t}function ko(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%Wt);r=ye[i]+r,n/=Wt;}return r.length<t&&(r="0".repeat(t-r.length)+r),r}function vo(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 No(e){let t=0n;for(let r of e)t=(t<<8n)+BigInt(r);return t}function Do(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 xo(e){let t=Array.from(Qt(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 Uo(e){let t=String(e);if(t.split("-").length===2)return t;let r=t.match(/^([0-9A-Za-z]+)-([0-9A-Za-z]+)-([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/);if(!r)throw new Error("INVALID_PARAMETER: Input must match <base62>-<base62>-<uuid>.");let[,n,i,s]=r;if(n.length<2)throw new Error("INVALID_PARAMETER: The first part must contain at least 2 characters.");if(i.length>=ye.length)throw new Error("INVALID_PARAMETER: The middle section is too long to encode.");let o=n.slice(0,2),a=n.slice(2),d=i+o,c=ye[i.length]+a+d,g=Do(s),f=ko(No(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=ye.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 d=o.slice(0,o.length-a),c=o.slice(o.length-a),g=c.slice(s),f=c.slice(0,s),u=g+d;if(!/^[0-9A-Za-z]+$/.test(u)||!/^[0-9A-Za-z]+$/.test(f))throw new Error("INVALID_PARAMETER: Corrupt compressed token: "+t);let p=So(i),h=vo(p);if(h.length>16)throw new Error("INVALID_PARAMETER: Corrupt compressed token: "+t);let m=new Uint8Array(16);m.set(h,16-h.length);let _=xo(m);return `${u}-${f}-${_}`}function He(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 Xt(...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 Mo(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 Fo(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 qo(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 Vo(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 jo(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 $o=/^[a-z0-9]{2,20}$/,Bo=/[a-z]/,Ko=/^[0-9]+e[0-9]+$/,Ho=["tp","admin","public","authorized","newsletter","forward","all","true","false","null"];function Go(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"||!$o.test(e)||!Bo.test(e)||Ko.test(e)||Ho.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 Wo(e,t,r=[],n){let i=$(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 Oo(o,t,r)}catch(a){throw new l(a.message,{code:"INVALID_PARAMETER"})}}var y={UserId:Lo,PhoneNumber:Mo,Birthdate:Fo,Password:qo,Email:Vo,Url:jo,newsletterGroup:Go,Params:Wo};var Y="skapi.enc.v1",tn=6e5,Ge=12,yt=null,Ne=null;function rn(){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 nn(){if(Ne)return Ne;let e=typeof globalThis<"u"?globalThis:void 0;if(e?.crypto?.subtle&&typeof e.crypto.getRandomValues=="function")return Ne=e.crypto,Ne;try{let t=typeof globalThis<"u"?globalThis:void 0,r=null;if(t?.process&&typeof t.process.getBuiltinModule=="function"&&(r=t.process.getBuiltinModule("crypto")),!r&&typeof ke=="function"&&(r=ke("crypto")),r?.webcrypto?.subtle)return Ne=r.webcrypto,Ne}catch{}throw rn()}function re(){if(yt)return yt;let e=nn();if(!e.subtle)throw rn();return yt=e.subtle,yt}function er(){try{return re(),!0}catch{return false}}function X(e){let t=nn(),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 q(e){let t=Qt(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 j(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 bt(e){let t=await re().digest("SHA-256",e);return new Uint8Array(t)}async function ze(e,t,r,n){let i=re(),s=await i.importKey("raw",e,"HKDF",false,["deriveBits"]),o=await i.deriveBits({name:"HKDF",hash:"SHA-256",salt:t,info:r},s,n*8);return new Uint8Array(o)}async function xe(e,t,r,n){let i=re(),s=K(e.normalize("NFC")),o=await i.importKey("raw",s,"PBKDF2",false,["deriveBits"]),a=new Uint8Array(await i.deriveBits({name:"PBKDF2",salt:t,iterations:r,hash:"SHA-256"},o,256)),d=await ze(a,t,n,32);F(a),F(s);let c=await oe(d);return F(d),c}async function oe(e){return re().importKey("raw",e,{name:"AES-GCM"},false,["encrypt","decrypt"])}async function sn(){let e=X(32),t=await oe(e);return {bytes:e,key:t}}async function ne(e,t,r){let n=X(Ge),i=await re().encrypt({name:"AES-GCM",iv:n,additionalData:r,tagLength:128},e,t);return {iv:n,ct:new Uint8Array(i)}}async function ae(e,t,r,n){let i=await re().decrypt({name:"AES-GCM",iv:t,additionalData:n,tagLength:128},e,r);return new Uint8Array(i)}var _t={name:"ECDH",namedCurve:"P-256"};async function on(){let e=re(),t=await e.generateKey(_t,true,["deriveBits"]),r=new Uint8Array(await e.exportKey("raw",t.publicKey)),n=new Uint8Array(await e.exportKey("pkcs8",t.privateKey)),i=await tr(n);return {pubRaw:r,pkcs8:n,priv:i}}async function tr(e){return re().importKey("pkcs8",e,_t,false,["deriveBits"])}async function an(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 re().importKey("raw",e,_t,false,[])}async function rr(e){return q(await bt(e))}async function ln(e,t,r,n){let i=re(),s=await an(e),o=await i.generateKey(_t,true,["deriveBits"]),a=new Uint8Array(await i.deriveBits({name:"ECDH",public:s},o.privateKey,256)),d=await ze(a,new Uint8Array(32),r,32);F(a);let c=await oe(d);F(d);let{iv:g,ct:f}=await ne(c,t,n);return {epk:new Uint8Array(await i.exportKey("raw",o.publicKey)),iv:g,ct:f}}async function cn(e,t,r,n,i,s){let o=re(),a=await an(t),d=new Uint8Array(await o.deriveBits({name:"ECDH",public:a},e,256)),c=await ze(d,new Uint8Array(32),i,32);F(d);let g=await oe(c);return F(c),ae(g,r,n,s)}function F(e){e&&e.length&&e.fill(0);}function Qo(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 nr(e){return K(JSON.stringify(e))}function Je(e,t,r){return Xt(e,new Uint8Array([0]),K(t),new Uint8Array([0]),K(r))}var Te="0123456789ABCDEFGHJKMNPQRSTVWXYZ",We=16,Zr=26,en=28;function un(e){let t=2166136261;for(let r=0;r<e.length;r++)t^=e[r],t=t*16777619>>>0;return t&1023}function dn(e){if(e.length!==We)throw new l(`A recovery code needs exactly ${We} 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+=Te[r>>n&31];n>0&&(t+=Te[r<<5-n&31]);let i=un(e);return t+=Te[i>>5&31]+Te[i&31],(t.match(/.{1,4}/g)||[]).join("-")}function fn(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!==en)throw new l(`That does not look like a recovery code: expected ${en} characters, got ${t.length}.`,{code:"ENCRYPTION_BAD_RECOVERY_CODE"});let r=t.slice(0,Zr),n=t.slice(Zr),i=0,s=0,o=[];for(let c=0;c<r.length;c++){let g=Te.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,We)),d=un(a);if(n!==Te[d>>5&31]+Te[d&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 ir(e,t,r){let n=await ze(e,t,r,32),i=await oe(n);return F(n),i}var Zt=[83,75,69,78,67,70],gn=2,Qe=56,pn=16,zo=4*1024*1024;function sr(e){if(!e||e.length<Qe)return false;for(let t=0;t<Zt.length;t++)if(e[t]!==Zt[t])return false;return true}function Pe(e,t,r){e[t]=r>>>24&255,e[t+1]=r>>>16&255,e[t+2]=r>>>8&255,e[t+3]=r&255;}function De(e,t){return (e[t]<<24>>>0)+(e[t+1]<<16)+(e[t+2]<<8)+e[t+3]}function Jo(e,t,r){let n=Math.floor(r/4294967296);Pe(e,t,n),Pe(e,t+4,r>>>0);}function Yo(e,t){return De(e,t)*4294967296+De(e,t+4)}async function hn(e,t,r,n,i,s){let o=K(`${Y}|binfile|${r}|${n}|${i}|${s}`),a=await ze(e,t,o,32),d=await oe(a);return F(a),d}async function mn(e){return (await bt(Xt(K(`${Y}|dekid`),e))).subarray(0,8)}function yn(e,t,r){return nr([`${Y}|binchunk`,q(e),t,r])}function Xo(e,t,r,n,i,s){let o=new Uint8Array(Qe+s.length);return o.set(Zt,0),o[6]=gn,o[7]=s.length?1:0,Pe(o,8,e),Pe(o,12,t),o.set(r,16),Jo(o,32,n),o.set(i,40),Pe(o,48,s.length),Pe(o,52,0),s.length&&o.set(s,Qe),o}async function bn(e,t,r,n,i=zo){let s=X(pn),o=await hn(e,s,r.service,r.owner,r.recordOwner,r.recordId),a=await mn(e),d=n?K(JSON.stringify(n)):new Uint8Array(0);if(d.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=Xo(i,c,s,t.length,a,d),f=await bt(g),u=[],p=g.length;for(let _=0;_<c;_++){let b=t.subarray(_*i,Math.min((_+1)*i,t.length)),A=await ne(o,b,yn(f,_,c));u.push(A),p+=4+A.iv.length+A.ct.length;}let h=new Uint8Array(p);h.set(g,0);let m=g.length;for(let _ of u)Pe(h,m,_.iv.length+_.ct.length),m+=4,h.set(_.iv,m),m+=_.iv.length,h.set(_.ct,m),m+=_.ct.length;return h}function Zo(e){if(!sr(e))throw new l("This file is not an encrypted skapi file.",{code:"INVALID_PARAMETER"});let t=De(e,48),r=Qe+t;if(e.length<r)throw new l("Encrypted file header is truncated.",{code:"INVALID_REQUEST"});let n=null;return t&&(n=JSON.parse(He(e.subarray(Qe,r)))),{version:e[6],chunkBytes:De(e,8),count:De(e,12),fileId:e.subarray(16,16+pn),plainLen:Yo(e,32),dekId:e.subarray(40,48),meta:n,headerLen:r}}async function _n(e,t,r){let n=Zo(t);if(n.version!==gn)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 mn(e);if(!Qo(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 hn(e,n.fileId,r.service,r.owner,r.recordOwner,r.recordId),o=await bt(t.subarray(0,n.headerLen)),a=[],d=n.headerLen,c=0;for(let u=0;u<n.count;u++){if(d+4>t.length)throw new l("Encrypted file is truncated.",{code:"INVALID_REQUEST"});let p=De(t,d);if(d+=4,p<Ge+16||d+p>t.length)throw new l("Encrypted file is truncated.",{code:"INVALID_REQUEST"});let h=await ae(s,t.subarray(d,d+Ge),t.subarray(d+Ge,d+p),yn(o,u,n.count));d+=p,a.push(h),c+=h.length;}let g=new Uint8Array(c),f=0;for(let u of a)g.set(u,f),f+=u.length;return {bytes:g,meta:n.meta}}var ea="__skapi__keyring",Ye="__skapi_enc__",En=1,ta="skapi-enc",Ae="keys",ar=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:tn;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:ea}}function L(){return ar.get(this)||null}function Rn(e){if(!e){ar.delete(this);return}ar.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 lr(){let e=L.call(this);if(e){e.user_id&&_r.call(this,e).catch(()=>{}),e.ready=null,e.unlocking=false,e.pendingRecoveryCode="";for(let[,t]of e.dek)F(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 In(){let e=L.call(this);return e?{status:e.status,reason:e.status==="unlocked"?void 0:e.reason,user_id:e.user_id||void 0,fingerprint:e.fpr||void 0}:{status:"disabled"}}function Tn(e,t){return typeof t=="string"&&t===e.cfg.table}function Ue(){return `${this.service}/${this.owner}`}function cr(e,t,r,n){let[i,s]=e.split("/");return nr([Y,i,s,t,r,n])}function Pn(e,t,r,n,i){let[s,o]=e.split("/");return K(`${Y}|dekwrap|${s}|${o}|${t}|${r}|${n}|${i}`)}function ur(e){return e.anch==="uid"?e.uid:e.anch==="rid"?e.rid:""}function Et(e){return !!e&&typeof e=="object"&&!Array.isArray(e)&&typeof e[Ye]=="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 Sn="__skapi_no_access__";function ee(e,t,r){if(e.withheld!=="sentinel")return null;let n={[Sn]:true,reason:t};return r&&(n.recipients=r),Object.freeze(n)}function dr(e){return !!e&&typeof e=="object"&&e[Sn]===true}var ra=256*1024,et="__skenc_ct__",kn="payload.bin",na=`/${et}/${kn}`;function fr(e,t){return e===et&&t===kn}async function ia(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:wn(n.access_group),table:i,record:null};if(!r)return {group:n?.access_group!==void 0?wn(n.access_group):0,table:i,record:null};let s=e.dek.get(r);if(s)return {group:s.access_group,table:i,record:null};let o=await Ee.call(this,r);if(!o)throw new l(`Record "${r}" not found.`,{code:"NOT_EXISTS"});return {group:o.table.access_group,table:o.table.name,record:o}}function sa(e){return this.getFile(e,{dataType:"blob"})}async function Ee(e){let t=/^[a-zA-Z0-9]+$/.test(e)?{record_id:e}:{unique_id:e};return (await this.getRecords(t,{limit:1}))?.list?.[0]||null}function wn(e){return e==="private"||e==="*"||e==="**"?"private":e==="public"?0:e==="authorized"?1:e==="admin"?99:typeof e=="number"?e:0}function or(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 gr(e,t,r){let n=L.call(this);if(!n)return {send:e,plain:e,encrypted:false,omit:false};let i=t?.record_id||"",s=i,o=t?.unique_id||"";if(i&&n.passthrough.has(i)){let M=n.passthrough.get(i);return n.passthrough.delete(i),{send:M,plain:e,encrypted:true,omit:false}}let{group:a,table:d,record:c}=await ia.call(this,n,t,s);if(a!=="private"){let M=true;if(!r&&i){let z=c||await Ee.call(this,i);if(z&&z.encrypted){if(or.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 Be=!!z.bin&&Object.keys(z.bin).some(gt=>(z.bin[gt]||[]).some(Kr=>Kr&&Kr.encrypted));if(!Be&&s){let gt=n.dek.get(s);gt&&(F(gt.bytes),n.dek.delete(s));}return {send:z.data,plain:z.data,encrypted:false,omit:false,files:Be?"decrypt":void 0}}}let J=c;i&&!J&&(J=await Ee.call(this,i).catch(()=>null)),J&&J.encrypted&&or.call(this,J,i,"making it non-private");let ft=!!J&&!!J.bin&&Object.keys(J.bin).some(z=>(J.bin[z]||[]).some(Be=>Be&&Be.encrypted));if(ft&&(M=false),M&&s){let z=n.dek.get(s);z&&(F(z.bytes),n.dek.delete(s));}return {send:e,plain:e,encrypted:false,omit:!r,files:ft?"decrypt":void 0}}if(Tn(n,d))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(dr.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,Ye))throw new l(`"${Ye}" 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=Ue.call(this),u=false;if(i&&n.roll.has(i)){u=true,n.roll.delete(i);let M=n.dek.get(i);n.dek.delete(i),M&&F(M.bytes);}let p=c;i&&!p&&!n.dek.has(i)&&(p=await Ee.call(this,i).catch(()=>null)),p&&or.call(this,p,i,"making it private");let h=!!p&&!p.encrypted&&!!p.bin&&Object.keys(p.bin).some(M=>(p.bin[M]||[]).some(J=>J&&!J.encrypted)),m=null;if(i&&!u&&(m=n.dek.get(i)||null,!m)){let M=p||c||await Ee.call(this,i);if(M&&(s=M.record_id||i,m=n.dek.get(s)||null,!o&&M.unique_id&&(o=M.unique_id),!m&&M.encrypted?.status==="failed"))throw new l(`Cannot update encrypted record "${i}": its current contents could not be decrypted (${M.encrypted.reason}), so its existing key wraps cannot be preserved. Updating anyway would revoke everyone it is shared with.`,{code:"ENCRYPTION_LOCKED"})}s===i&&m&&m.rid&&(s=m.rid),!o&&m&&m.anch==="uid"&&m.uid&&(o=m.uid);let _,b,A;if(m){if(m.own&&m.own!==g)throw new l(`Record "${i}" belongs to another user (${m.own}). Encryption only operates on records you own.`,{code:"ENCRYPTION_NOT_RECORD_OWNER"});_=m.bytes,b=m.key,A=Object.assign({},m.recipients);}else {let M=await sn();_=M.bytes,b=M.key,A={};}let w=o?"uid":s?"rid":"new",k=w==="uid"?o:w==="rid"?s:"",E=cr(f,g,w,k),N=Je(E,g,"mk"),U=await ne(n.mk,_,N);A[g]={t:"mk",iv:q(U.iv),ct:q(U.ct)},m&&(m.anch!==w||ur(m)!==k)&&(A=await oa.call(this,n,_,A,f,g,w,k,E));let C=K(JSON.stringify(e===void 0?null:e)),v=await ne(b,C,E);F(C);let x={[Ye]:En,enc:"A256GCM",kw:"ECDH-ES+A256GCM",anch:w,uid:o,rid:s,own:g,iv:q(v.iv),ct:q(v.ct),k:A},O,V,de=x.ct;s&&de.length>ra&&(O=j(de),x.ct="",x.ct_ref=na,m&&m.ctRef&&(V=m.ctRef));let ie=JSON.stringify(x).length;if(ie>2*1024*1024)throw new l(`Encrypted record data is too large: once encrypted and base64 encoded it becomes ${ie} bytes, over the ${2*1024*1024} byte limit. Encryption costs about 33% plus roughly 230 bytes per additional recipient.`,{code:"ENCRYPTED_DATA_TOO_LARGE"});return s&&n.dek.set(s,{bytes:_,key:b,recipients:A,anch:w,uid:o,rid:s,own:g,access_group:"private"}),{send:x,plain:e,encrypted:true,omit:false,spill:O,retireCt:V,dek:{bytes:_,key:b,recipients:A,anch:w,uid:o,rid:s,own:g,access_group:"private"},files:h?"encrypt":void 0}}function vn(e,t){let r=L.call(this);!r||!t||!e||r.dek.has(e)||r.dek.set(e,Object.assign({},t,{rid:e}));}async function oa(e,t,r,n,i,s,o,a){let d=Object.keys(r).filter(f=>f!==i);if(!d.length)return r;let c=await wr.call(this,d),g={[i]:r[i]};for(let f of d){let u=c[f];u&&(g[f]=await Nn.call(this,t,u,n,o,i,f,a));}return g}async function Nn(e,t,r,n,i,s,o){let a=Pn(r,n,i,s,t.fpr),d=Je(o,s,t.fpr),c=await ln(t.pubRaw,e,a,d);return {t:"ecdh",epk:q(c.epk),iv:q(c.iv),ct:q(c.ct),fpr:t.fpr}}async function Dn(e,t){if(!Et(e))return {value:e};if(t.access_group!=="private")return {value:e};let r=L.call(this);if(!r)return {value:null,flag:{status:"failed",reason:"ENCRYPTION_DISABLED"}};if(r.rawRead)return {value:e};if(Tn(r,t.table_name))return {value:e};if(e[Ye]!==En)return {value:ee(r.cfg,"UNSUPPORTED_VERSION"),flag:{status:"failed",reason:"UNSUPPORTED_VERSION"}};if(r.ready&&!r.unlocking)try{await r.ready;}catch{}if(e.own!==t.user_id)return {value:ee(r.cfg,"BINDING_MISMATCH"),flag:{status:"failed",reason:"BINDING_MISMATCH"}};if(e.uid&&t.unique_id&&e.uid!==t.unique_id)return {value:ee(r.cfg,"BINDING_MISMATCH"),flag:{status:"failed",reason:"BINDING_MISMATCH"}};if(e.rid&&t.record_id&&e.rid!==t.record_id)return {value:ee(r.cfg,"BINDING_MISMATCH"),flag:{status:"failed",reason:"BINDING_MISMATCH"}};let n=this.user?.user_id,i=n?e.k[n]:null;if(!i)return {value:ee(r.cfg,"NOT_A_RECIPIENT",Object.keys(e.k)),flag:{status:"failed",reason:"NOT_A_RECIPIENT",recipients:Object.keys(e.k)}};if(r.status!=="unlocked"||!r.mk)return {value:ee(r.cfg,"NO_SESSION_KEY"),flag:{status:"failed",reason:"NO_SESSION_KEY"}};let s=Ue.call(this),o=ur(e),a=cr(s,e.own,e.anch,o),d;try{if(i.t==="mk")d=await ae(r.mk,j(i.iv),j(i.ct),Je(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"}};d=await cn(r.ikPriv,j(i.epk),j(i.iv),j(i.ct),Pn(s,o,e.own,n,i.fpr),Je(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 F(d),{value:ee(r.cfg,"DATA_UNAVAILABLE"),flag:{status:"failed",reason:"DATA_UNAVAILABLE"}};let p=await sa.call(this,t.ctUrl);c=new Uint8Array(await p.arrayBuffer());}else c=j(e.ct);}catch{return F(d),{value:ee(r.cfg,"DATA_UNAVAILABLE"),flag:{status:"failed",reason:"DATA_UNAVAILABLE"}}}let g,f;try{f=await oe(d),g=await ae(f,j(e.iv),c,a);}catch{return F(d),{value:ee(r.cfg,"CORRUPT"),flag:{status:"failed",reason:"CORRUPT"}}}let u;try{u=JSON.parse(He(g));}catch{return F(g),F(d),{value:ee(r.cfg,"CORRUPT"),flag:{status:"failed",reason:"CORRUPT"}}}if(F(g),t.record_id){let p=r.dek.get(t.record_id);p?(p.bytes=d,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:d,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 F(d);return {value:u,flag:{status:"encrypted",recipients:Object.keys(e.k)}}}function Xe(e,t){let[r,n]=e.split("/");return K(`${Y}|kek|${r}|${n}|${t}`)}function Ze(e,t,r,n){let[i,s]=e.split("/");return K(`${Y}|mk|${i}|${s}|${t}|PBKDF2-SHA256|${r}|${n}`)}function xn(e,t){let[r,n]=e.split("/");return K(`${Y}|recovery|${r}|${n}|${t}`)}function Un(e,t,r){let[n,i]=e.split("/");return K(`${Y}|rk|${n}|${i}|${t}|HKDF-SHA256|${r}`)}function Cn(e,t){let[r,n]=e.split("/");return K(`${Y}|self|${r}|${n}|${t}`)}function On(e,t){let[r,n]=e.split("/");return K(`${Y}|ik|${r}|${n}|${t}`)}async function At(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 pr(e,t,r){let n=X(We),i=dn(n),s=X(16),o=q(s),a=await ir(n,s,xn(e,t)),d=await ne(a,r,Un(e,t,o));return F(n),{code:i,wrap:{id:q(X(6)),p:"recovery",kdf:{a:"HKDF-SHA256",s:o},iv:q(d.iv),ct:q(d.ct),created:Date.now()}}}async function aa(e,t,r,n){let i=fn(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 ir(i,j(o.kdf.s),xn(e,t)),d=await ae(a,j(o.iv),j(o.ct),Un(e,t,o.kdf.s));return F(i),d}catch{}return F(i),null}async function la(e,t,r,n,i){let s=X(16),o=q(s),a=await xe(n,s,e.cfg.iterations,Xe(t,r)),d=await ne(a,i,Ze(t,r,e.cfg.iterations,o));return {id:q(X(6)),p:"password",kdf:{a:"PBKDF2-SHA256",it:e.cfg.iterations,s:o},iv:q(d.iv),ct:q(d.ct),created:Date.now()}}async function ca(e,t){let r=this.user.user_id,n=e.scope,i=X(16),s=q(i),o=await xe(t,i,e.cfg.iterations,Xe(n,r)),a=X(32),d=await ne(o,a,Ze(n,r,e.cfg.iterations,s)),c=await oe(a),g=await on(),f=await ne(c,g.pkcs8,On(n,r));F(g.pkcs8);let u=null;e.cfg.recovery==="code"&&(u=await pr(n,r,a));let p=await ne(c,a,Cn(n,r));F(a);let h=await rr(g.pubRaw),m=Date.now(),_=[{id:q(X(6)),p:"password",kdf:{a:"PBKDF2-SHA256",it:e.cfg.iterations,s},iv:q(d.iv),ct:q(d.ct),created:m}];u&&_.push(u.wrap);let b={v:1,alg:"ECDH-P-256",user_id:r,wraps:_,ik:{iv:q(f.iv),ct:q(f.ct)},self:{iv:q(p.iv),ct:q(p.ct)},pub:q(g.pubRaw),fpr:h,pins:null,created:m,updated:m};await this.postRecord({v:1,alg:"ECDH-P-256",user_id:r,pub:q(g.pubRaw),fpr:h,created:m},{table:{name:e.cfg.table,access_group:"authorized"},index:{name:"pubkey",value:r}});let A=await this.postRecord(b,{table:{name:e.cfg.table,access_group:"private"}}),w=await At.call(this,e);if(w&&w.record_id!==A.record_id){await Ln.call(this,e,w,t);return}e.mk=c,e.ikPriv=g.priv,e.pubRaw=g.pubRaw,e.fpr=h,e.keyringRecordId=A.record_id,u&&(e.pendingRecoveryCode=u.code),e.user_id=r,e.pins={},e.status="unlocked",e.reason="";}async function Ln(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 d=null;for(let g of a)try{let f=j(g.kdf.s),u=await xe(r,f,g.kdf.it,Xe(i,n));d=await ae(u,j(g.iv),j(g.ct),Ze(i,n,g.kdf.it,g.kdf.s));break}catch{}if(!d)throw new l("Incorrect password: the encryption keyring could not be opened.",{code:"ENCRYPTION_BAD_PASSWORD"});let c=await oe(d);F(d),await hr.call(this,e,t,c);}async function hr(e,t,r){let n=this.user.user_id,i=t.data,s=await ae(r,j(i.ik.iv),j(i.ik.ct),On(e.scope,n)),o=await tr(s);F(s);let a={};if(i.pins&&typeof i.pins=="object"&&i.pins.ct)try{let d=await ae(r,j(i.pins.iv),j(i.pins.ct),K(`${Y}|pins|${e.scope}|${n}`));a=JSON.parse(He(d)),F(d);}catch{a={};}e.mk=r,e.ikPriv=o,e.pubRaw=j(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 Rt(e){let t=L.call(this);if(!t||!this.user?.user_id)return;if(!er()){t.status="locked",t.reason="NO_WEB_CRYPTO";return}if(this.user?.is_openid){t.status="locked",t.reason="OPENID_UNSUPPORTED";return}if(t.cfg.minPasswordLength&&e.length<t.cfg.minPasswordLength){t.status="locked",t.reason="WEAK_PASSWORD";return}t.scope=Ue.call(this);let r=await At.call(this,t);r?await Ln.call(this,t,r,e):await ca.call(this,t,e),t.cfg.persistDevice&&await jn.call(this,t).catch(()=>{});}async function Mn(e){await this.__connection;let t=L.call(this);if(!t)throw new l("Encryption is not enabled for this instance.",{code:"INVALID_REQUEST"});if(!this.user?.user_id)throw new l("User login is required.",{code:"INVALID_REQUEST"});if(!e?.password||typeof e.password!="string")throw new l('"password" is required.',{code:"INVALID_PARAMETER"});if(await Rt.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 Fn(e){this.__projectIdInput&&await this.__projectIdInput;let t=L.call(this);return t?(e?.forgetDevice&&await _r.call(this,t).catch(()=>{}),lr.call(this),this.__cached_requests={},{status:t.status}):{status:"disabled"}}async function qn(e,t){let r=L.call(this);if(!r)return;if(r.status!=="unlocked"||!r.mk)throw new l("Encryption must be unlocked before changing the password, or the encryption keyring would be left wrapped under a password that no longer exists. Call unlockEncryption({ password }) first.",{code:"ENCRYPTION_LOCKED"});let 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(m=>m.p==="password");a.sort((m,_)=>(_.created||0)-(m.created||0));let d=null;for(let m of a)try{let _=await xe(e,j(m.kdf.s),m.kdf.it,Xe(r.scope,s));d=await ae(_,j(m.iv),j(m.ct),Ze(r.scope,s,m.kdf.it,m.kdf.s));break}catch{}if(!d)throw new l("Incorrect current password: the encryption keyring was not re-wrapped.",{code:"ENCRYPTION_BAD_PASSWORD"});let c=X(16),g=q(c),f=await xe(t,c,r.cfg.iterations,Xe(r.scope,s)),u=await ne(f,d,Ze(r.scope,s,r.cfg.iterations,g));F(d);let p=Date.now(),h=(o.wraps||[]).concat([{id:q(X(6)),p:"password",kdf:{a:"PBKDF2-SHA256",it:r.cfg.iterations,s:g},iv:q(u.iv),ct:q(u.ct),created:p}]);await this.postRecord(Object.assign({},o,{wraps:h,updated:p}),{record_id:r.keyringRecordId});}async function Vn(){let e=L.call(this);if(!e||e.status!=="unlocked"||!e.keyringRecordId)return;let r=(await this.getRecords({record_id:e.keyringRecordId},{limit:1}))?.list?.[0];if(!r)return;let n=r.data,i=(n.wraps||[]).filter(o=>o.p==="password").sort((o,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 mr(){return typeof indexedDB<"u"&&!!indexedDB}function yr(){return new Promise((e,t)=>{let r=indexedDB.open(ta,1);r.onupgradeneeded=()=>{let n=r.result;n.objectStoreNames.contains(Ae)||n.createObjectStore(Ae);},r.onsuccess=()=>e(r.result),r.onerror=()=>t(r.error);})}function br(e){return `${e.scope}#${this.user?.user_id}`}async function jn(e){if(!mr()||!e.mk)return;let t=await yr();await new Promise((r,n)=>{let i=t.transaction(Ae,"readwrite");i.objectStore(Ae).put({mk:e.mk,keyringRecordId:e.keyringRecordId,saved:Date.now()},br.call(this,e)),i.oncomplete=()=>r(),i.onerror=()=>n(i.error);}),t.close();}async function ua(e){if(!mr())return null;let t=await yr(),r=await new Promise((n,i)=>{let o=t.transaction(Ae,"readonly").objectStore(Ae).get(br.call(this,e));o.onsuccess=()=>n(o.result||null),o.onerror=()=>i(o.error);});return t.close(),r&&r.mk?r:null}async function _r(e){if(!mr())return;let t=await yr();await new Promise((r,n)=>{let i=t.transaction(Ae,"readwrite");i.objectStore(Ae).delete(br.call(this,e)),i.oncomplete=()=>r(),i.onerror=()=>n(i.error);}),t.close();}function $n(){let e=L.call(this);!e||e.ready||(e.unlocking=true,e.ready=da.bind(this)().catch(()=>false).then(()=>{e.unlocking=false;}));}async function da(){let e=L.call(this);if(!e||!this.user?.user_id||!e.cfg.persistDevice||!er())return false;e.scope=Ue.call(this);try{let t=await ua.call(this,e);if(!t)return !1;let r=await At.call(this,e);return r?(await hr.call(this,e,r,t.mk),!0):(await _r.call(this,e).catch(()=>{}),!1)}catch{return e.status="locked",e.reason="NO_SESSION_KEY",false}}async function wr(e){let t=L.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,h)=>h.uploaded-p.uploaded);let g=j(c[0].data.pub),f=await rr(g),u=t.pins[s];if(u&&u!==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(!u){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 Gn.call(this,t).catch(()=>{}),r}async function Bn(e,t){let r=Ue.call(this),n=e.dek.get(t);if(n)return {entry:n,scope:r};let i=await Ee.call(this,t);if(!i)throw new 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 Er(e,t){let r=L.call(this);if(!r)return;let n=await Bn.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 wr.call(this,t),d=t.filter(u=>!a[u]);if(d.length)throw new l(`These users have no encryption key yet, so they cannot be given access: ${d.join(", ")}. A user's key is created the first time they log in with encryption enabled.`,{code:"ENCRYPTION_RECIPIENT_HAS_NO_KEY"});let c=ur(i),g=cr(s,i.own,i.anch,c),f=Object.assign({},i.recipients);for(let u of t)u!==o&&(f[u]=await Nn.call(this,i.bytes,a[u],s,c,i.own,u,g));await ga.call(this,r,e,i,f);}async function Kn(e,t){let r=L.call(this);if(!r)return;let n=await Bn.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 Ee.call(this,e);if(!a)throw new l(`Record "${e}" not found.`,{code:"NOT_EXISTS"});fa(a,e);let d={};if(o.length){d=await wr.call(this,o);let c=o.filter(g=>!d[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 Er.call(this,a.record_id||e,o);}function fa(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 ga(e,t,r,n){let i=await pa.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 pa(e){let t=L.call(this);if(!t)return null;t.rawRead=true;let r;try{r=(await this.getRecords({record_id:e},{limit:1}))?.list?.[0];}finally{t.rawRead=false;}return r&&Et(r.data)?r.data:null}async function Hn(e){this.__projectIdInput&&await this.__projectIdInput;let t=L.call(this);if(!t||t.status!=="unlocked")throw new l("Encryption is locked.",{code:"ENCRYPTION_LOCKED"});t.pins[e.user_id]=e.fingerprint,t.peerPub.delete(e.user_id),await Gn.call(this,t);}async function Gn(e){if(!e.mk||!e.keyringRecordId)return;let r=(await this.getRecords({record_id:e.keyringRecordId},{limit:1}))?.list?.[0];if(!r)return;let n=await ne(e.mk,K(JSON.stringify(e.pins)),K(`${Y}|pins|${e.scope}|${e.user_id}`));await this.postRecord(Object.assign({},r.data,{pins:{iv:q(n.iv),ct:q(n.ct)},updated:Date.now()}),{record_id:e.keyringRecordId});}function Wn(){let e=L.call(this);if(!e||!e.pendingRecoveryCode)return null;let t=e.pendingRecoveryCode;return e.pendingRecoveryCode="",t}async function Qn(e){await this.__connection;let t=L.call(this);if(!t)throw new l("Encryption is not enabled for this instance.",{code:"INVALID_REQUEST"});if(!this.user?.user_id)throw new l("User login is required. Reset the password and log in first, then use the recovery code.",{code:"INVALID_REQUEST"});if(!e?.code||typeof e.code!="string")throw new l('"code" is required.',{code:"INVALID_PARAMETER"});t.scope=Ue.call(this);let r=this.user.user_id,n=await At.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 aa(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 hr.call(this,t,n,s);let o=false,a=null,d=(n.data?.wraps||[]).slice();if(e.password&&(d=d.filter(c=>c.p!=="password"),d.push(await la(t,t.scope,r,e.password,i)),o=true),t.cfg.recovery==="code"){let c=await pr(t.scope,r,i);d=d.filter(g=>g.p!=="recovery"),d.push(c.wrap),a=c.code;}return F(i),await this.postRecord(Object.assign({},n.data,{wraps:d,updated:Date.now()}),{record_id:n.record_id}),t.cfg.persistDevice&&await jn.call(this,t).catch(()=>{}),{status:t.status,repaired:o,recoveryCode:a}}async function zn(){await this.__connection;let e=L.call(this);if(!e)throw new l("Encryption is not enabled for this instance.",{code:"INVALID_REQUEST"});if(e.status!=="unlocked"||!e.mk)throw new l("Encryption must be unlocked to issue a recovery code. Only someone who can already decrypt can create one.",{code:"ENCRYPTION_LOCKED"});if(e.cfg.recovery!=="code")throw new l('Recovery codes are disabled for this instance ("recovery" is "none").',{code:"INVALID_REQUEST"});let r=(await this.getRecords({record_id:e.keyringRecordId},{limit:1}))?.list?.[0];if(!r)throw new l("The encryption keyring could not be read.",{code:"ENCRYPTION_KEYRING_CORRUPT"});let n=r.data?.self;if(!n||!n.ct)throw new l("This keyring predates recovery-code rotation and cannot issue a new code. Use unlockWithRecoveryCode() with the existing code, which issues a replacement.",{code:"ENCRYPTION_KEYRING_CORRUPT"});let i=await ae(e.mk,j(n.iv),j(n.ct),Cn(e.scope,e.user_id)),s=await pr(e.scope,e.user_id,i);F(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 wt="__skenc__",Jn="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";function ha(e){if(e===0)return "0";let t="";for(;e>0;)t=Jn[e%62]+t,e=Math.floor(e/62);return t}function ma(e){let t=0;for(let r of e){let n=Jn.indexOf(r);if(n<0)return NaN;t=t*62+n;}return t}function It(e){if(typeof e!="string")return null;let t=e.lastIndexOf(wt);if(t<0)return null;let r=ma(e.slice(t+wt.length));return Number.isFinite(r)?{key:e.slice(0,t),plainSize:r}:null}function Ar(e){try{let t=String(e).split("?")[0].split("/").slice(3);if(t.length<12||t[4]!=="records"||t[7]!=="bin")return null;let r=It(t[10]);return r?{recordId:t[5],recordOwner:t[3],filename:t[t.length-1],plainSize:r.plainSize}:null}catch{return null}}function Yn(e,t){return {service:this.service,owner:this.owner,recordOwner:t,recordId:e}}async function Xn(e,t,r){let n=L.call(this);if(!n||!e)return {key:t,file:r,encrypted:false};let i=n.dek.get(e);if(!i)return {key:t,file:r,encrypted:false};if(It(t))throw new l(`"${wt}" is reserved in an upload form key.`,{code:"INVALID_PARAMETER"});if(t===et)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 bn(i.bytes,s,Yn.call(this,e,i.own),o);return F(s),{key:`${t}${wt}${ha(r.size)}`,file:new File([a],r.name,{type:"application/octet-stream"}),encrypted:true}}async function Zn(e,t){let r=L.call(this),n=Ar(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(!sr(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 _n(i.bytes,s,Yn.call(this,n.recordId,n.recordOwner)),a=o.meta&&o.meta.t||"application/octet-stream";return new Blob([o.bytes],{type:a})}function ya(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 ba(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 Rr(e,t,r){let n=L.call(this);if(!n)return [];let i=await Ee.call(this,e);if(!i)return [];let s=t==="decrypt"?ya(i):ba(i);if(!s.length)return [];let o=[],a=new FormData,d=false;for(let c of s){let g=i.bin[c.formKey].find(u=>u.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),d=true);}if(!d)return [];if(t==="decrypt"){let c=n.dek.get(e);c&&(F(c.bytes),n.dek.delete(e));}return await this.uploadFiles(a,{record_id:e,progress:r}),o}var B=null;function St(e){let t={tkid:"ticket_id",cond:"condition",stmp:"timestamp",upd:"updated",acts:"actions",actn:"action",cnt:"count",ttl:"time_to_live",plch:"placeholder",hash:"hash",desc:"description",pmc:"limit_per_user",fail:"failed"},r={};for(let n in e)if(n==="tkid"){let i=e[n].split("#");if(i.length===1){r.ticket_id=i[0];continue}r.ticket_id=i[1],r.consume_id=i[2],r.user_id=i.slice(3).join("#");let s=i[2].slice(-4);if(r.is_test=s===":CHK",!e.stmp){let o=i[2].slice(0,-4);/^[0-9]+$/.test(o)?r.timestamp=parseInt(o,10):r.timestamp=se(i[2].slice(0,-4));}}else t[n]?r[t[n]]=e[n]:r[n]=e[n];return r}async function ti(e){if(!e?.ticket_id)throw new l("Ticket ID is required.",{code:"INVALID_PARAMETER"});if(!/^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$/.test(e.ticket_id))throw new l('Invalid "ticket_id". Use letters, digits, "_" and "-" (up to 64 chars, starting with a letter or digit).',{code:"INVALID_PARAMETER"});if(!e.method)throw new l('Method is required. Should be either "GET" or "POST"',{code:"INVALID_PARAMETER"});let t=String(e.method).toUpperCase();if(t!=="GET"&&t!=="POST")throw new l('Method should be either "GET" or "POST".',{code:"INVALID_PARAMETER"});let r=!!e.auth;if(r&&t==="GET")throw new l("Signed-in consumption is POST only.",{code:"INVALID_PARAMETER"});await this.__connection;let n=r?"tpa":t==="GET"?"tg":"tp",i=`https://${this.service.slice(0,4)}.${this.customApiDomain}/${n}/${this.service}/${e.ticket_id}`,s=await S.bind(this)(i,e.data||{},{method:t,auth:r},{ignoreService:true});if(s&&typeof s=="object"&&s.stage)throw new l(s.message,{code:s.code,cause:s});return !s||typeof s!="object"?s:St(s)}async function ri(e,t){await this.__connection;let r=await S.bind(this)("ticket",Object.assign({exec:"list"},e||{}),{auth:true,fetchOptions:t});return r.list=r.list.map(St),r}async function ni(e,t){await this.__connection;let r=await S.bind(this)("ticket",Object.assign({exec:"consumed"},e||{}),{auth:true,fetchOptions:t});return r.list=r.list.map(St),r}async function ii(e){let t=await S.bind(this)("register-ticket",Object.assign({exec:"reg"},e),{auth:true});return t&&typeof t=="object"&&t.ticket&&(t.ticket=St(t.ticket)),t}async function si(e){return S.bind(this)("register-ticket",Object.assign({exec:"unreg"},e),{auth:true})}var Ia=3600;async function Oe(){if(await this.__connection,this.session){let e=Math.floor(Date.now()/1e3),r=this.session.getIdToken().getExpiration();if(r<e+Ia){this.log("request:requesting new token",null);try{await W.bind(this)().getSession({refreshToken:!0}),this.log("request:received new tokens",{exp:this.session?.idToken?.payload?.exp,currentTime:e,expiresIn:r-e,token:this.session?.accessToken?.jwtToken,refreshToken:this.session?.refreshToken?.token});}catch(n){throw this.log("request:new token error",n),new 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),be.bind(this)(),new l("User login is required.",{code:"INVALID_REQUEST"})}function ei(e,t){return new Promise((r,n)=>{t.refreshSession(e.getRefreshToken(),(i,s)=>{this.log("getSession:refreshSessionCallback",{refreshErr:i,refreshedSession:s}),i?(be.bind(this)(),n(i)):s.isValid()?r(s):(be.bind(this)(),n(new l("Invalid session.",{code:"INVALID_REQUEST"})));});})}function W(){if(!this.userPool)throw new l("User pool is missing",{code:"INVALID_REQUEST"});let e=()=>{let s=B.getSignInUserSession().getIdToken().payload||null,o=Ke(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:d=false,skipUserUpdateEventTrigger:c=false}=s||{};if(d&&c&&(c=false),B=this.userPool.getCurrentUser(),!B){this.log("getSession:cognitoUser",B),be.bind(this)(),a(null);return}let g=f=>{let u=f.getIdToken().payload;if(this.log("getSession:respond:sessionAttribute",u),u["custom:service"]!==this.service)throw this.log("getSession:respond","invalid service, signing out"),be.bind(this)(),new l("Invalid session.",{code:"INVALID_REQUEST"});return this.session=f,e(),c||this._runOnUserUpdateListeners(this.user),this.session};B.getSession((f,u)=>{if(this.log("getSession:getSessionCallback",{err:f,session:u}),!u){be.bind(this)(),a(new l("Current session does not exist.",{code:"INVALID_REQUEST"}));return}if(f){ei.bind(this)(u,B).then(b=>o(g(b))).catch(a);return}let p=Math.floor(Date.now()/1e3),h=u.getIdToken(),m=h.getExpiration(),_=m<p;if(this.log("getSession:currentTime",p),this.log("getSession:idTokenExp",m),this.log("getSession:isExpired",_),this.log("getSession:existingBearerToken",this.bearerToken),this.bearerToken=h.getJwtToken(),_||d||!u.isValid())ei.bind(this)(u,B).then(b=>o(g(b))).catch(a);else try{o(g(u));}catch(b){a(b);}});}),r=(s,o)=>{let a=o||s.includes(this.service+"-")?s:this.service+"-"+Z.hash(s);return {cognitoUser:new CognitoUser({Username:a,Pool:this.userPool}),cognitoUsername:a}};return {getSession:t,authenticateUser:(s,o,a=false,d=false)=>new Promise((c,g)=>{this.__request_signup_confirmation=null,this.__disabledAccount=null;let f=r(s,a),u=f.cognitoUsername,p=new AuthenticationDetails({Username:u,Password:o});f.cognitoUser.authenticateUser(p,{newPasswordRequired:(h,m)=>{this.__disabledAccount=null,this.__request_signup_confirmation=u,h["custom:signup_ticket"]==="PASS"||h["custom:signup_ticket"]==="MEMBER"||h["custom:signup_ticket"]==="OIDPASS"?f.cognitoUser.completeNewPasswordChallenge(o,{},{onSuccess:_=>{B=f.cognitoUser,t().then(async b=>{if(L.call(this))try{await Rt.bind(this)(o);}catch(A){this.log("encryption:ensureKeyring:failed",A);}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:h=>t({skipUserUpdateEventTrigger:true}).then(async m=>{if(this.__disabledAccount=null,L.call(this))try{await Rt.bind(this)(o);}catch(_){this.log("encryption:ensureKeyring:failed",_);}this._runOnLoginListeners(this.user),this._runOnUserUpdateListeners(this.user),c(this.user);}),onFailure:h=>{let m=[],{parsed:_,code:b}=Pt(h),A=typeof h?.message=="string"?h.message:"";if(b==="NotAuthorizedException"?A.includes("User is disabled.")?(this.__disabledAccount=u,m=["This account is disabled.","USER_IS_DISABLED"]):d?m=["The account already exists.","ACCOUNT_EXISTS"]:m=["Incorrect username or password.","INCORRECT_USERNAME_OR_PASSWORD"]:b==="UserNotFoundException"?m=["Incorrect username or password.","INCORRECT_USERNAME_OR_PASSWORD"]:b==="UserNotConfirmedException"?(this.__request_signup_confirmation=u,m=["User's signup confirmation is required.","SIGNUP_CONFIRMATION_NEEDED"]):(b==="TooManyRequestsException"||b==="LimitExceededException")&&(m=["Too many attempts. Please try again later.","REQUEST_EXCEED"]),_.code==="SIGNUP_CONFIRMATION_NEEDED"&&(this.__request_signup_confirmation=u),m.length){let w=m[1],k=m[0];g(new l(k,{code:w,cause:h}));}else g(_);}});}),createCognitoUser:r,signup:(s,o,a)=>new Promise((d,c)=>{this.userPool.signUp(s,o,a,null,(g,f)=>{if(g){let{parsed:u,code:p}=Pt(g),h=[];p==="UsernameExistsException"?h=["The account already exists.","EXISTS"]:p==="InvalidPasswordException"?h=["Invalid password. Password must be at least 6 characters.","INVALID_PARAMETER"]:p==="InvalidParameterException"?h=[u.message||"Invalid parameter.","INVALID_PARAMETER"]:p==="TooManyRequestsException"||p==="LimitExceededException"?h=["Too many attempts. Please try again later.","REQUEST_EXCEED"]:p==="CodeDeliveryFailureException"?h=["Failed to deliver verification code.","CODE_DELIVERY_FAILURE"]:p==="UserLambdaValidationException"&&(h=[u.message||"Signup validation failed.",u.code==="EXISTS"?"EXISTS":"INVALID_REQUEST"]),h.length?c(new l(h[0],{code:h[1],cause:g})):c(u);return}d(f);});})}}function Pt(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 oi(e){await this.__authConnection;let t=e?.refreshToken||false;if(!t)return this.user;try{return await W.bind(this)().getSession(Object.assign({skipUserUpdateEventTrigger:!t,refreshToken:t},e)),this.user}catch{return null}}async function ai(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 S.bind(this)("openid-logger",t),n=r.logger.split("#"),i=this.service+"-"+n[0],s=n[1];return {userProfile:await W.bind(this)().authenticateUser(i,s,true,true),openid:r.openid}}function 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 Pa(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 li(e){await this.__authConnection,this.log("loginWithToken:params",e),e=y.Params(e,{idToken:"string",accessToken:"string",refreshToken:"string"},["idToken"]);let t=Pa(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=Ke(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 tt.bind(this)(),false)}async function be(e=false){let t=null;B&&(e?t=new Promise((n,i)=>{B.globalSignOut({onSuccess:s=>{this.log("globalSignOut:success",s),n(s);},onFailure:s=>{this.log("globalSignOut:error",s),i(s);}});}):B.signOut()),lr.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 tt(e){await this.__connection;let{data:t}=$(e);return await be.bind(this)(t?.global),"SUCCESS: The user has been logged out."}async function ci(){if(!this.__request_signup_confirmation)throw new l("Least one login attempt is required.",{code:"INVALID_REQUEST"});return await S.bind(this)("confirm-signup",{username:this.__request_signup_confirmation})}async function ui(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 S.bind(this)("recover-account",{username:this.__disabledAccount,redirect:e}),"SUCCESS: Recovery e-mail has been sent."}async function Ir(e){let t=y.Params(e,{username:"string",email:"string",password:"string"},["password"]);await this.__authConnection;let r=null;if(t.email)try{r=y.Email(t.email);}catch{t.username=t.email,delete t.email;}if(!t.username&&!t.email)throw new l('Least one of "username" or "email" is required.',{code:"INVALID_PARAMETER"});let n=t.username||t.email;try{return await W.bind(this)().authenticateUser(n,t.password)}catch(i){if((i?.code==="UserNotFoundException"||i?.code==="NotAuthorizedException")&&r&&r!==n)return await W.bind(this)().authenticateUser(r,t.password);throw i}}async function di(e,t){await this.__authConnection;let r={username:"string",password:c=>y.Password(c),email:c=>y.Email(c),name:"string",address:c=>{if(!c)return "";if(typeof c=="string")return c;if(typeof c=="object")return JSON.stringify(c)},gender:"string",birthdate:c=>c?y.Birthdate(c):"",phone_number:c=>c?y.PhoneNumber(c):"",email_public:["boolean",()=>false],address_public:["boolean",()=>false],gender_public:["boolean",()=>false],birthdate_public:["boolean",()=>false],phone_number_public:["boolean",()=>false],access_group:"number",misc:"string",picture:c=>c?y.Url(c):"",profile:c=>c?y.Url(c):"",family_name:"string",given_name:"string",middle_name:"string",nickname:"string",website:c=>c?y.Url(c):""},n=y.Params(e||{},r,["email","password"]);await tt.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=W.bind(this)().createCognitoUser(n.username||n.email);for(let c of ["email_public","address_public","gender_public","birthdate_public","phone_number_public"])n[c]=n[c]?"1":"0";n.access_group&&(n.access_group=n.access_group.toString());let o=(await S.bind(this)("signupkey",{username:s.cognitoUsername,signup_confirmation:typeof n.signup_confirmation=="boolean"?JSON.stringify(n.signup_confirmation):n.signup_confirmation,email_subscription:n.email_subscription,template_confirmation:t?.template?.signup_confirmation||"",template_welcome:t?.template?.welcome||""})).split(":"),a=o.slice(1).join(":"),d=[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)?d.push(new CognitoUserAttribute({Name:"custom:"+c,Value:n[c]})):d.push(new CognitoUserAttribute({Name:c,Value:n[c]}))));}return await W.bind(this)().signup(s.cognitoUsername,n.password,d),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?Ir.bind(this)({email:n.username||n.email,password:n.password}):"SUCCESS: The account has been created."}async function fi(){await this.__connection;let e=await S.bind(this)("remove-account",{disable:this.__user.user_id},{auth:true});return await tt.bind(this)(),e}async function gi(e){await this.__connection;let t=y.Params(e,{email:i=>y.Email(i),code:["number","string"],new_password:i=>y.Password(i)},["email","code","new_password"]),r=t.code,n=t.new_password;return typeof r=="number"&&(r=r.toString()),new Promise(async(i,s)=>{W.bind(this)().createCognitoUser(t.email).cognitoUser.confirmPassword(r,n,{onSuccess: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 pi(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 d={onSuccess:c=>{n?W.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,d):(d.inputVerificationCode=null,B?.getAttributeVerificationCode(e,d,i));})}function hi(e,t){return pi.bind(this)("phone_number",e,t)}function mi(e,t){return pi.bind(this)("email",e,t)}async function yi(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)=>{W.bind(this)().createCognitoUser(r.email).cognitoUser.forgotPassword({onSuccess:d=>{s("SUCCESS: Verification code has been sent.");},onFailure:d=>{let{parsed:c,code:g}=Pt(d),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:d}));}},n);})}async function bi(e){if(await this.__connection,!this.session)throw new l("User login is required.",{code:"INVALID_REQUEST"});let t=y.Params(e,{current_password:"string",new_password:"string"});if(!t?.current_password)throw new l('"current_password" is required to change password.',{code:"INVALID_PARAMETER"});if(!t?.new_password)throw new l('"new_password" is required to change password.',{code:"INVALID_PARAMETER"});return y.Password(t.current_password),y.Password(t.new_password),L.call(this)&&await qn.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}=Pt(i);n(o);}return}L.call(this)&&Vn.bind(this)().catch(o=>this.log("encryption:prune:failed",o)),r("SUCCESS: Password has been changed.");});})}async function _i(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;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 S.bind(this)("admin-edit-profile",{attributes:t},{auth:true});if(t&&typeof t=="object"&&Object.keys(t).length){let i=[];for(let s in t)i.push(new CognitoUserAttribute({Name:s,Value:t[s]}));return await new Promise((s,o)=>{B?.updateAttributes(i,(a,d)=>{a&&o([a?.code||a?.name,a?.message||"Failed to update user settings."]),s(d);});}),await W.bind(this)().getSession({refreshToken:true}),this.user}return this.user}async function wi(e,t){e=$(e).data,e||(e={searchFor:"timestamp",condition:">",value:0},t||(t={}),t.ascending=false),await this.__connection;let r={user_id:s=>y.UserId(s),email:"string",phone_number:"string",locale:s=>{if(typeof s!="string"||typeof s=="string"&&s.length>5)throw new l('Value of "locale" should be a country code.',{code:"INVALID_PARAMETER"});return s},name:"string",address:"string",gender:"string",birthdate:s=>y.Birthdate(s),subscribers:"number",timestamp:"number",access_group:"number",approved:"string"},n=["searchFor","value"],i=(s,o)=>{let a=r[e.searchFor];if(typeof a=="function")return a(s);if(typeof s!==a)throw new l(`${o} does not match the type of "${e.searchFor}" index.`,{code:"INVALID_PARAMETER"});return s};if(e=y.Params(e,{searchFor:["user_id","name","email","phone_number","address","gender","birthdate","locale","subscribers","timestamp","access_group","approved"],condition:[">",">=","=","<","<=","gt","gte","eq","lt","lte",()=>"="],value:s=>Array.isArray(s)?s.map(o=>i(o,"Value")):i(s,"Value"),range:s=>i(s,"Range")},n),e?.condition&&e?.condition!=="="&&e.hasOwnProperty("range"))throw new l("Conditions does not apply on range search.",{code:"INVALID_PARAMETER"});if(Array.isArray(e.value)&&(e.condition!=="="||e.range))throw new l(`Conditions are not allowed on a list of "${e.searchFor}" values. Search for a single value to use a condition or range.`,{code:"INVALID_PARAMETER"});if(typeof e?.value=="string"&&!e?.value)throw new l("Value should not be an empty string.",{code:"INVALID_PARAMETER"});if(typeof e?.searchFor=="string"&&!e?.searchFor)throw new l('"searchFor" should not be an empty string.',{code:"INVALID_PARAMETER"});return S.bind(this)("get-users",e,{auth:true,fetchOptions:t})}async function Ei(e){await this.__connection;let t=await S.bind(this)("last-verified-email",e,{auth:true});return t.includes("SUCCESS")?(await W.bind(this)().getSession({refreshToken:true}),this.user):t}var Le=null,Ri=typeof SubmitEvent<"u",ka=typeof HTMLFormElement<"u",nt=H(),Tr=0;function Ii(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 Pr(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(Tr++,r==="admin"){let a=Object.entries(s).filter(([d,c])=>d.includes(t?"_private":"_public")&&d!=="get_users_private"&&d!=="service_public"&&typeof c=="string").map(([,d])=>d);if(!a.length)throw new l("No available admin gateways.",{code:"INVALID_REQUEST"});return a[Tr%a.length]}if(r==="record"){let a=Object.entries(o).filter(([d,c])=>d.includes(t?"record_private":"record_public")&&typeof c=="string").map(([,d])=>d);if(!a.length)throw new l("No available record gateways.",{code:"INVALID_REQUEST"});return i?a[0]:a[Tr%a.length]}throw new l("Invalid gateway type.",{code:"INVALID_REQUEST"})};async function va(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 "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 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 rt={};function Ti(){Le&&(Le.terminate(),Le=null);}async function S(e,t=null,r,n){this.log("request",{url:e,data:t,options:r,_etc:n||{}}),r=r||{};let{auth:i=false,method:s="post",bypassAwaitConnection:o=false}=r;s=s.toUpperCase();let a=null,d=null,c=await va.bind(this)(e,!!i,!!r.stableGateway),g=t?.service||this.service,f=t?.owner||this.owner;if(!o&&(a=await this.__connection,!a))throw new l("Invalid connection. The service could have been disabled, or has a restricted CORS.",{code:"INVALID_REQUEST"});let u=r?.tokenHeaders?.idToken===true;(i||u)&&(d=await Oe.bind(this)());let p={},{fetchMore:h=false,progress:m}=r?.fetchOptions||{};if(r?.fetchOptions&&Object.keys(r.fetchOptions).length){for(let v of ["limit","startKey","ascending"])if(r.fetchOptions.hasOwnProperty(v)){if(v==="startKey"&&r.fetchOptions[v]===null)continue;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:g,owner:f};Object.assign(_,p),t=$(t).data,t?t&&typeof t=="object"&&(t=Object.assign(_,t)):t=_;let b=`${s}:${i?"auth":"public"}:${e}`,A=(()=>{if(t&&typeof t=="object"&&Object.keys(t).length&&!(nt&&t instanceof FormData)){let v=function(x){return typeof x=="object"&&x!==null?Object.keys(x).sort().reduce((O,V)=>(typeof x[V]=="object"&&x[V]!==null?O[V]=v(x[V]):O[V]=x[V],O),{}):x};return Z.hash(b+"/"+JSON.stringify(v(t)))}return Z.hash(b+"/"+g)})(),{requestKey:w,requestKeyWithStartKey:k}=Na.bind(this)({params:t,url:e,fetchMore:h,hashedParams:A});if(!w||w&&typeof w=="object")return w;if(this.log("requestKey",k),typeof k=="string"&&rt[k]instanceof Promise)return this.log("request:returning pending",k),rt[k];let E={Accept:"*/*"};if(Object.prototype.hasOwnProperty.call(r,"contentType")&&r.contentType!==void 0){let v=r.contentType===null?"application/x-www-form-urlencoded":r.contentType;v&&(E["Content-Type"]=v);}else E["Content-Type"]="application/json";if(d&&(E.Authorization=d),r?.tokenHeaders){let v=(V,de)=>typeof V=="string"?V:V===true?de:null,x=v(r.tokenHeaders.accessToken,this.session?.accessToken?.jwtToken||null),O=v(r.tokenHeaders.idToken,this.bearerToken||this.session?.idToken?.jwtToken||d||null);x&&(E["X-Access-Token"]=x),O&&(E["X-Id-Token"]=O);}let U={public_identifier:this.__public_identifier,service:g,owner:f,resolves_offloaded_data:true};E["Content-Meta"]=JSON.stringify(U),r.revalidate&&(E["Cache-Control"]="no-cache",E.Pragma="no-cache");let C={headers:E};if(r?.responseType&&(C.responseType=r.responseType),s==="GET"){if(t){let v=[];if(nt&&t instanceof FormData?v=Array.from(t.entries()).map(([x,O])=>{let V=typeof O=="string"?O:O.name;return encodeURIComponent(x)+"="+encodeURIComponent(V)}):v=Object.keys(t).map(x=>{let O=t[x];return typeof O!="string"&&(O=JSON.stringify(O)),encodeURIComponent(x)+"="+encodeURIComponent(O)}),v.length){let x=c.includes("?")?c.endsWith("?")||c.endsWith("&")?"":"&":"?";c+=x+v.join("&");}}C.body=null;}else if(nt&&t instanceof FormData)C.body=t;else if(E["Content-Type"]==="application/x-www-form-urlencoded"&&t&&typeof t=="object"){let v=new URLSearchParams;for(let x of Object.keys(t)){let O=t[x];v.append(x,typeof O=="string"?O:JSON.stringify(O));}C.body=v.toString();}else typeof t=="string"?C.body=t:C.body=t?JSON.stringify(t):null;if(C.method=s,Le===null){let v={batchSize:this.requestBatchSize,breakWhenError:false,onProgress:x=>{this.onBatchProcess.forEach(O=>O(x));}};Le=new us(v);}return this.log("request-opt",C),new Promise((v,x)=>{Le.add([async()=>{let O=Pi.bind(this)(c,C,m);rt[k]=O;try{let V=xa.bind(this)({hashedParam:w,requestKeyWithStartKey:k,url:e,fetched:await O});return delete rt[k],this.log("request:end",V),v(V),V}catch(V){throw delete rt[k],this.log("request:err",V),x(V),V}}]);})}function Na(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 d of this.__startKeyHistory[r][i]){let c=i+Z.hash(d);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+=Z.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 Da(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 Pi(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"),d=Ii(a);d!==null?setTimeout(()=>{Pi(e,t,r).then(n,i);},d):i("Too many requests");}else {let a=s.status,d=["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(),u=g.join(":").trim();i(new l(u||c,{code:d.includes(f)?f:"ERROR"}));}else if(typeof c=="object"&&(c?.message||c?.stage||c?.code)){let g=c?.code||(a?a.toString():null)||"ERROR",f=c.message,u=c?.cause;u===void 0&&c.stage&&(u=c),typeof f=="string"&&(f=f.trim()),f||(f=String(g)),i(new l(f,{cause:u,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:Pr(a.loaded,a.total),loaded:a.loaded,total:a.total,abort:()=>s.abort()});},s.upload&&(s.upload.onprogress=a=>{r({status:"upload",progress:Pr(a.loaded,a.total),loaded:a.loaded,total:a.total,abort:()=>s.abort()});})),s.send(t.body);})}function xa(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 it(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(Ri&&e instanceof SubmitEvent&&(e=e.target),ka&&e instanceof HTMLFormElement&&(e=new FormData(e)),!nt||!(e instanceof FormData))throw new l('"fileList" should be a FormData or HTMLFormElement.',{code:"INVALID_PARAMETER"});let o={reserved_key:Ie(),service:n,request:"post"};t?.record_id&&(o.id=t.record_id);let a,d=(p,h,m)=>new Promise((_,b)=>{a=new XMLHttpRequest,a.open("POST",p),a.onload=()=>{let A=a.responseText;try{A=JSON.parse(A);}catch{}if(a.status>=200&&a.status<300)_(A);else if(a.status===429){let w=a.getResponseHeader("Retry-After"),k=Ii(w);k!==null?setTimeout(()=>{d(p,h,m).then(_,b);},k):b("Too many requests");}else b(A);},a.onerror=()=>b("Network error"),a.onabort=()=>b("Aborted"),a.ontimeout=()=>b("Timeout"),a.upload&&typeof m=="function"&&(a.upload.onprogress=m),a.send(h);});function c(p){let h="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";if(p===0)return h[0];let m="";for(;p>0;)m=h[p%62]+m,p=Math.floor(p/62);return m}let g=[],f=[],u=[];for(let[p,h]of e.entries()){if(!(h instanceof File))continue;let m=await Xn.bind(this)(r,p,h),_=m.file,b=m.key,A=Object.assign({key:b+"/"+_.name,sizeKey:c(_.size),contentType:_.type||null},o),{fields:w=null,url:k,cdn:E}=await S.bind(this)("get-signed-url",A,{auth:!!this.__user});u.push(E);let N=new FormData;for(let U in w)N.append(U,w[U]);N.append("file",_);try{await d(k,N,typeof i=="function"?U=>i({status:"upload",progress:Pr(U.loaded,U.total),currentFile:h,completed:g,failed:f,loaded:U.loaded,total:U.total,abort:()=>a.abort()}):null),g.push(h);}catch{f.push(h);}}return {completed:g,failed:f,bin_endpoints:u}}var kt={};function P(e){let{preventMultipleCalls:t=false}=e||{};return function(r,n,i){let s=i.value;i.value=function(...o){let a=o[0],d=true,c=null,g="",f={},u=false;if(Ri&&a instanceof SubmitEvent){a.preventDefault();let b=window.location.href;c=a.target;let A=new URL(c.action);g=A.href;let w=g?g.match(/(?<=\{).*?(?=\})/g):"";if(w)for(let k of w){if(!k)continue;let E=c.querySelector(`[name="${k}"]`);if(E)if(E.type==="file")for(let N=0;N<=E.files.length-1;N++)E.files[N]&&(f[k]||(f[k]=[]),f[k].push(new Promise((U,C)=>{let v=new FileReader;v.onload=function(){U(v.result);},v.readAsDataURL(E.files[N]),v.onerror=C;})));else g=g.replace(`{${k}}`,E.value);}c.getAttribute("action")===null?d=false:u=A.href===b;}let p=async b=>{if(g)for(let A in f)f[A].length&&(g=g.replace(`{${A}}`,(await Promise.all(f[A])).join(",")));if(c&&d){let A=L.call(this)?Da(b):b;window.sessionStorage.setItem(`${this.service}:${Z.hash(g)}`,JSON.stringify(A)),u?window.location.replace(g):window.location.href=g;}return b},h,m=b=>{throw b instanceof l?b.name=n+"()":b=b instanceof Error?b:new l(b,{name:n+"()"}),b},_=async()=>{try{if(this.__projectIdInput&&await this.__projectIdInput,h=s.bind(this)(...o),h instanceof Promise){let b=await h;return p(b)}return p(h)}catch(b){throw m(b)}};if(t){let b=`${n}:${this?.__public_identifier||""}:${this?.service||""}:${this?.owner||""}`;return kt?.[b]||(kt[b]=_().finally(()=>{delete kt[b];})),kt[b]}return _()};}}async function Si(){await this.__connection;let e=`${this.service}:${Z.hash(window.location.href.split("?")[0])}`,t=window.sessionStorage.getItem(e);if(window.sessionStorage.removeItem(e),t!==null){try{t=JSON.parse(t);}catch{}return t}return null}var Ua=256,Ca=256,Oa=256,ki=256,La="\u{10FFFF}",Ma=/[\u0000-\u001F\u007F]|\u{10FFFF}/u,Fa={"/":"%2F","!":"%21","*":"%2A","#":"%23"},qa={"%2F":"/","%21":"!","%2A":"*","%23":"#"};function Va(e){return e.replace(/%/g,"%25").replace(/[\/!*#]/g,r=>Fa[r]||r)}function le(e){return typeof e!="string"?e:e.replace(/%(2F|21|2A|23)/gi,r=>{let n=r.toUpperCase();return qa[n]||r}).replace(/%25/gi,"%")}function fe(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(Ma.test(e)||e.includes(La))throw new l(`"${t}" cannot include control characters or unsupported sentinel characters.`,{code:"INVALID_PARAMETER"});if(s&&(e=Va(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 Me(e,t="table.name",r={}){return fe(e,t,{allowEmpty:r.allowEmpty===true,maxLength:Ua,blockKeyDelimiters:true})}function Nt(e,t="tag",r={}){return fe(e,t,{allowEmpty:r.allowEmpty===true,maxLength:Ca,blockKeyDelimiters:true})}function st(e,t="index.name",r={}){return fe(e,t,{allowEmpty:r.allowEmpty===true,maxLength:Oa,blockKeyDelimiters:true,disallowLeadingDollar:true})}function vi(e,t="index.value"){return fe(e,t,{allowEmpty:true,maxLength:ki})}function Sr(e){return typeof e=="string"&&e.slice(-1)==="."}function kr(e,t){return fe(e,t,{allowEmpty:true,maxLength:ki,blockKeyDelimiters:true})}function Ni(e){if(!e.record_id&&!e.unique_id)return null;let t={};return e?.service&&(t.service=e.service),e?.owner&&(t.owner=e.owner),e?.record_id?t.record_id=fe(e.record_id,"record_id",{allowEmpty:false,onlyAlphanumeric:true}):e?.unique_id&&(t.unique_id=e.unique_id),t}function vr(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 vt=4503599627370496;function Dt(e){if(typeof e=="number"){if(e>vt||e<-vt)throw new l(`Number value should be within range -${vt} ~ +${vt}`,{code:"INVALID_PARAMETER"});return e}if(typeof e=="boolean")return e;if(typeof e=="string")return vi(e,"index.value");throw new l('"index.value" should be type: <number | boolean | string>.',{code:"INVALID_PARAMETER"})}function Di(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"?Sr(t.index.name)?kr(e,"index.range"):vi(e,"index.range"):e}var xt={},ja=10080*60,$a=3600,xi=2;function Ba(e,t){if(!t)return String(xi);let r=Math.max(60,e-300)*1e3;return "g"+xi+"w"+Math.floor(Date.now()/r)}function Ka(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 Ha(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 Ut(e){return typeof e=="string"?e:e&&typeof e.text=="function"?await e.text():await new Promise((t,r)=>{try{let n=new FileReader;n.onload=()=>t(n.result),n.onerror=()=>r(n.error||new Error("Failed to read blob")),n.readAsText(e);}catch(n){r(n);}})}function Dr(e){return !!e&&typeof e=="object"&&!Array.isArray(e)&&typeof e.__data__=="string"&&Object.keys(e).length===1&&e.__data__.endsWith("/__data__/__json__.json")}var Fe=new Map,Ga=1024,Wa=/^[0-9A-Za-z]+\/[0-9A-Za-z]+\/__data__\/__json__\.json$/,Ci=/^[0-9A-Za-z_-]+$/,Qa=/^(\d{2}|\*\*)$/;function Oi(e){if(typeof e!="string")return null;let t=e.split("?")[0].split("/");if(t.length<15||t[0]!=="https:"||t[1]!==""||!t[2])return null;let r=t.slice(3);return r[0]!=="publ"&&r[0]!=="auth"||r[4]!=="records"||r[7]!=="bin"||!Ci.test(r[1])?null:{origin:t.slice(0,3).join("/"),service:r[1]}}function za(e){let t=Oi(e);!t||Fe.get(t.service)===t.origin||(Fe.size>=Ga&&!Fe.has(t.service)&&Fe.clear(),Fe.set(t.service,t.origin));}function Ui(e,t){if(typeof t!="string"||!Wa.test(t))return null;let r=typeof e.usr_tbl=="string"?e.usr_tbl.split("/"):null,n=typeof e.tbl=="string"?e.tbl.split("/"):null,i=null,s=null;if(typeof e.srvc=="string"){let g=e.srvc.split("!")[0].split("/");g.length===2&&(i=g[0],s=g[1]);}i||(i=r?.[2]||n?.[1]||null,i&&i===this.service&&(s=this.owner));let o=typeof e.usr=="string"&&e.usr?e.usr:r?.[0]||null,a=r?.[3]||n?.[2]||null,d=e.rec;for(let g of [i,s,o,d])if(typeof g!="string"||!Ci.test(g))return null;if(typeof a!="string"||!Qa.test(a))return null;let c=null;if(Array.isArray(e.bin))for(let g of e.bin){let f=Oi(g);if(f&&f.service===i){c=f.origin;break}}return c=c||Fe.get(i)||null,c?`${c}/${a==="00"?"publ":"auth"}/${i}/${s}/${o}/records/${d}/${a}/bin/${t}`:null}async function Se(e,t,r=false,n=false,i=false){let s={user_id:"",record_id:"",updated:0,uploaded:0,readonly:false,table:{name:"",access_group:0,subscription:{is_subscription_record:false,upload_to_feed:false,notify_subscribers:false,feed_referencing_records:false,notify_referencing_records:false}},referenced_count:0,source:{referencing_limit:null,prevent_multiple_referencing:false,can_remove_referencing_records:false,only_granted_can_reference:false},ip:"",bin:{}},o=false,a=[],d=null;function c(u){let p=u=="**"?"private":parseInt(u);return p=p==0?"public":p==1?"authorized":p==99?"admin":p,p}let g={ip:u=>{let p=u.split("#"),h=p[0];p.length>1&&(s.unique_id=p.slice(1).join("#")),h.slice(-1)==="R"?(s.readonly=true,h=h.slice(0,-1)):s.readonly=false,/^\d{1,3}-\d{1,3}-\d{1,3}-\d{1,3}$/.test(h)&&(h=h.split("-").join("."),o=true),s.ip=h;},rec:u=>{if(!u)return;s.record_id=u;let p=u.substring(0,u.length-9),h=se(p);s.uploaded=h;},usr:u=>{s.user_id=u;},tbl:u=>{if(u&&!s.table.name){let p=u.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:u=>{let p=u.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:u=>{if(!u)return;let p=u.split("!"),h=le(p.splice(0,1)[0]),m=Ja("!"+p.join("!"));s.index={name:h,value:m};},ref:u=>{u&&(s.reference=u.split("/")[0]);},tags:u=>{s.tags=Array.isArray(u)?u.map(p=>le(p)):u;},upd:u=>{s.updated=u;},acpt_mrf:u=>{s.source.prevent_multiple_referencing=!u;},ref_limt:u=>{s.source.referencing_limit=u;},rfd:u=>{s.referenced_count=u;},bin:async u=>{let p={},h=s?.reference||null;if(Array.isArray(u)){let m=await Promise.all(u.map(async _=>{try{let b=_.split("/").slice(3).join("/"),A=b.split("/");if(A.length<12)return null;let w=A[A.length-1],k=A[10];if(k==="__data__"&&w==="__json__.json")return {isDataFile:!0,rawUrl:_};if(fr(k,w))return {isDataFile:!0,rawUrl:_};let E=It(k),N=A[9],U=A[8],C=c(A[6]),v=_,x=C!=="public"&&Ka.call(this,A)?{expires:$a,browserCache:ja}:null;if(C!=="public"&&!i)try{v=await _e.bind(this)(_,{dataType:"endpoint",_ref:h});}catch(V){console.error("Error getting signed url for private file:",V),v=_;}let O={access_group:C,filename:w,url:v,path:b,size:E?E.plainSize:se(N),uploaded:se(U),getFile:(V,de)=>{let ie={dataType:V||"download",progress:de,_ref:h},M=()=>_e.bind(this)(v,Object.assign({},ie,{_update:O}));return x?_e.bind(this)(_,Object.assign({},ie,x)).catch(()=>M()):M()}};return E&&(O.encrypted=!0,O.stored_size=se(N)),{pathKey:E?E.key:k,obj:O}}catch{return null}}));for(let _ of m)if(_&&!_.isDataFile){if(p[_.pathKey]){p[_.pathKey].push(_.obj);continue}p[_.pathKey]=[_.obj];}}s.bin=p;},prv_acs:u=>{for(let p in u)["notify_subscribers","upload_to_feed","feed_referencing_records","notify_referencing_records"].includes(p)?s.table.subscription[p]=u[p]:p==="referencing_index_restrictions"&&Array.isArray(u[p])?s.source[p]=u[p].map(m=>m&&typeof m=="object"&&typeof m.name=="string"?Object.assign({},m,{name:le(m.name)}):m):s.source[p]=u[p];},data:async u=>{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:d},h=()=>{L.call(this)&&(s.encrypted={status:"failed",reason:"DATA_UNAVAILABLE"});},m=async b=>{if(n||!L.call(this)&&!Et(b))return b;let A=await Dn.bind(this)(b,p);return A.flag&&(s.encrypted=A.flag),A.value},_=Ha(u);if(_!==u){s.data=await m(_);return}if(Dr(u)){let b=u.__data__,A=a.find(w=>w.endsWith(b))||null;if(!A&&!r){await Promise.resolve();let w=Ui.call(this,e,b),k=false,E;if(w)try{let N=await _e.bind(this)(w,{dataType:"blob",_ref:s.reference||null});E=JSON.parse(await Ut(N)),k=!0;}catch{}if(k){s.data=await m(E);return}h();}if(A){if(r){s.data=u;return}try{let w=await _e.bind(this)(A,{dataType:"blob",_ref:s.reference||null}),k=await Ut(w);s.data=await m(JSON.parse(k));}catch(w){let k=Ui.call(this,e,b),E=false,N;if(k&&k!==A)try{let U=await _e.bind(this)(k,{dataType:"blob",_ref:s.reference||null});N=JSON.parse(await Ut(U)),E=!0;}catch{}if(E){s.data=await m(N);return}console.error("Failed to fetch offloaded record data:",w),s.data=null,h();}return}}s.data=await m(u);}};if(e.record_id)return e;if(Array.isArray(e.bin))for(let u of e.bin)try{if(typeof u!="string")continue;za(u);let p=u.split("/").slice(3);p.length>=12&&p[10]==="__data__"&&p[p.length-1]==="__json__.json"&&a.push(u),p.length>=12&&fr(p[10],p[p.length-1])&&(d=u);}catch{}let f=[];for(let u in g)if(e.hasOwnProperty(u)){let p=g[u](e[u]);p instanceof Promise&&f.push(p);}return o&&(s.user_id="anonymous:"+s.user_id),await Promise.all(f),s}function Ja(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 Li(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 S.bind(this)("del-files",{endpoints:t,storage:"records"},{auth:true,method:"post"}),n=[];for(let i in r)n.push(Se.bind(this)(r[i]));return Promise.all(n)}async function _e(e,t){if(typeof e!="string")throw new 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,d=o.split("/"),g=d[2].split("."),f=null;g.length===3&&g[1]==="skapi"&&(f=g[0],a=true);let u=d.slice(3),p=false;if(!a&&(u[0]==="auth"||u[0]==="publ"))try{y.UserId(u[2]),y.UserId(u[3]),p=u[0]=="auth",a=!0;}catch{throw new l("Invalid file url.",{code:"INVALID_PARAMETER"})}let h=f?null:u[1];if(t=y.Params(t,{expires:["number",()=>0],browserCache:["number",()=>0],refresh:["boolean",()=>false],dataType:["base64","blob","endpoint","text","info",()=>"download"],progress:["function","undefined",null],_ref:[null,"string"],_update:w=>w}),t?.dataType==="info")return {url:e,filename:u[u.length-1],fileKey:u[u.length-2],access_group:u[6]==="**"?"private":u[6]==="01"?"authorized":u[6]==="00"?"public":parseInt(u[6]),uploader:u[3],record_id:u[4]==="records"?u[5]:"N/A",filesize:se(u[9]),uploaded:se(u[8])};let m=e.split("/").slice(-1)[0],_=t.expires;if(_){if(!a)throw new l("Expires option can only be used on skapi cdn endpoints.",{code:"INVALID_PARAMETER"});if(_<0)throw new l('"config.expires" should be > 0. (seconds)',{code:"INVALID_PARAMETER"});let w={request:f?"get-host":"get",id:f||u[5],key:r.split("?")[0],expires:_};h&&(w.service=h);let k=t.browserCache,E={auth:true};if(k){if(k<0)throw new l('"config.browserCache" should be > 0. (seconds)',{code:"INVALID_PARAMETER"});E.method="get",E.stableGateway=true,w.browser_cache=k;let N=this.session?.idToken?.payload?.sub||this.user?.user_id;N&&(w.uid=N),w.nocache=Ba(_,t.refresh);}e=(await S.bind(this)("get-signed-url",w,E)).url;}else if(p){let w=Math.floor(Date.now()/1e3);if(!this.bearerToken&&(!this.session?.idToken?.payload?.exp||this.session.idToken.payload.exp<w)){this.log("getFile:requesting new token",null);try{await W.bind(this)().getSession({refreshToken:!0}),this.log("getFile:received new tokens",{exp:this.session?.idToken?.payload?.exp,currTime:w,expiresIn:this.session?.idToken?.payload?.exp-w,token:this.session?.accessToken?.jwtToken,refreshToken:this.session?.refreshToken?.token});}catch(U){throw this.log("getFile:new token error",U),new l("User login is required.",{code:"INVALID_REQUEST"})}}let k=this.bearerToken||this.session?.idToken?.jwtToken;if(!k||!this.user?.user_id)throw new l("User login is required.",{code:"INVALID_REQUEST"});e+=`${e.includes("?")?"&":"?"}t=${encodeURIComponent(k)}`;let E=u[6]==="**"?"**":parseInt(u[6]),N=this.user?.access_group??-1;if(this.user.user_id!==u[3]&&(E==="**"||N<E)){let U=u[5];if(this.__private_access_key[U]&&typeof this.__private_access_key[U]=="string")e+=`&p=${encodeURIComponent(this.__private_access_key[U])}`;else if(this.owner!==this.host)try{let C=await this.requestPrivateRecordAccessKey({record_id:U,reference_id:t?._ref});e+=`&p=${encodeURIComponent(C)}`;}catch{}}}if((L.call(this)?Ar(e):null)&&t?.dataType!=="endpoint"&&t?.dataType!=="info"){let w=await S.bind(this)(e,null,{method:"get",contentType:null,responseType:"blob",fetchOptions:{progress:t?.progress}},{ignoreService:true}),k=await Zn.bind(this)(e,w);if(t?.dataType==="blob")return k;if(t?.dataType==="text")return await Ut(k);if(t?.dataType==="base64")return await new Promise((U,C)=>{let v=new FileReader;v.onloadend=()=>U(v.result),v.onerror=()=>C(v.error),v.readAsDataURL(k);});let E=URL.createObjectURL(k),N=document.createElement("a");return N.href=E,document.body.appendChild(N),N.setAttribute("download",m),N.click(),document.body.removeChild(N),setTimeout(()=>URL.revokeObjectURL(E),6e4),null}if(t?.dataType==="endpoint")return t._update&&(t._update.url=e),e;if(t?.dataType==="download"){let w=document.createElement("a");return w.href=e,document.body.appendChild(w),w.setAttribute("download",m),w.target="_blank",w.click(),document.body.removeChild(w),null}return new Promise(async(w,k)=>{try{let E=await S.bind(this)(e,null,{method:"get",contentType:null,responseType:t?.dataType==="text"?"text":"blob",fetchOptions:{progress:t?.progress}},{ignoreService:!0});if(t?.dataType==="base64"){let N=new FileReader;N.onloadend=()=>w(N.result),N.readAsDataURL(E);}else w(E);}catch(E){if(t?.browserCache&&!t?.refresh)try{w(await _e.bind(this)(r,Object.assign({},t,{refresh:!0})));return}catch(N){k(N);return}k(E);}})}function Ct(e,t){return `${e||this.service}/${t||this.owner}`}function Nr(e,t){let r=this.__my_unique_ids[e];return r?r[t]:void 0}function Mi(e,t,r){this.__my_unique_ids[e]||(this.__my_unique_ids[e]={}),this.__my_unique_ids[e][t]=r;}function Ya(e,t){this.__my_unique_ids[e]&&delete this.__my_unique_ids[e][t];}function Fi(e,t){return !t||t.table===void 0?e:Object.assign({},e,{table:t.table})}async function ot(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 qi(e,t=false){e=$(e,{ignoreEmpty:true}).data||{};let r=Ct.bind(this)(e?.service,e?.owner),n="",i=Ni(e);if(i){if(e=i,n=e.record_id||e.unique_id,typeof n=="string"){typeof this.__private_access_key?.[n]=="string"&&(e.private_key=this.__private_access_key?.[n]||void 0);let s=Nr.bind(this)(r,n);s&&(t?Ya.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 d=c=>({table:{name:g=>Me(g,"table.name"),access_group:vr.bind(this),subscription:g=>y.UserId(g,'User ID in "subscription"')},reference:"string",index:{name:["$updated","$uploaded","$referenced_count","$user_id",g=>st(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 u=f[c.index.name];if(typeof u=="function")return u(g);if(u!==typeof g)throw new l(`"index.value" should be type: ${u}.`,{code:"INVALID_PARAMETER"});return g}return typeof g=="string"&&!g?"":typeof g=="string"&&Sr(c.index.name)?kr(g,"index.value"):Dt(g)},condition:["gt","gte","lt","lte",">",">=","<","<=","=","eq"],range:g=>Di(g,c)},tag:g=>{if(g==null)return g;if(typeof g=="string")return Nt(g,"tag");throw new l('"tag" should be type: string.',{code:"INVALID_PARAMETER"})},private_key:"string"});e=y.Params(e||{},d(e),a||s?[]:["table"],{ignoreEmpty:true});}return {query:e,is_reference_fetch:n}}async function Vi(e,t){await this.__connection,await ot.call(this,"getRecords");let r=await qi.bind(this)(e),n=r.is_reference_fetch,i=await S.bind(this)("get-records",r.query,{fetchOptions:t,auth:!!this.__user,method:this.__user?"post":"get"});n&&i?.reference_private_key&&typeof i.reference_private_key=="string"&&(this.__private_access_key[n]=i.reference_private_key);let s=[];for(let o in i.list)s.push(Se.bind(this)(i.list[o]));return i.list=await Promise.all(s),i}function ji(e){let t="",r=[],n=Ct.bind(this)(e?.service,e?.owner),i=y.Params(e||{},{record_id:o=>{let a=typeof o=="string"?Nr.bind(this)(n,o):void 0;return a||fe(o,"record_id",{allowEmpty:false})},unique_id:["string",null],readonly:"boolean",table:{name:o=>Me(o,"table.name"),subscription:[null,{is_subscription_record:"boolean",upload_to_feed:"boolean",notify_subscribers:"boolean",feed_referencing_records:"boolean",notify_referencing_records:"boolean"}],access_group:vr.bind(this)},notification:o=>{if(o==null)return o;if(typeof o!="object"||Array.isArray(o))throw new l('"notification" should be an object with "title" and "body".',{code:"INVALID_PARAMETER"});for(let a of ["title","body"])if(typeof o[a]!="string"||!o[a].trim())throw new l(`"notification.${a}" is required.`,{code:"INVALID_PARAMETER"});return {title:o.title,body:o.body}},source:{referencing_limit:o=>{if(o===null)return null;if(typeof o=="number"){if(0>o)throw new l('"reference_limit" should be >= 0',{code:"INVALID_PARAMETER"});if(o>4503599627370546)throw new l('"reference_limit" should be <= 4503599627370546',{code:"INVALID_PARAMETER"});return o}throw new l('"reference_limit" should be type: <number | null>',{code:"INVALID_PARAMETER"})},prevent_multiple_referencing:"boolean",can_remove_referencing_records:"boolean",only_granted_can_reference:"boolean",allow_granted_to_grant_others:"boolean",referencing_index_restrictions:o=>{if(o===void 0)return;if(!o||Array.isArray(o)&&!o.length)return null;let a={name:c=>st(c,'"name" in "index_restrictions"'),value:c=>Dt(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 d=o.map(c=>y.Params(c,a,["name"]));if(d.length)for(let c of d)c.condition&&c.hasOwnProperty("range")&&delete c.range;return d}},reference:o=>{if(o===null)return {record_id:null};if(o){if(typeof o=="string"){t=o;let a=Nr.bind(this)(n,o);return a||o}if(typeof o!="object")throw new 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),fe(a,"reference.record_id",{allowEmpty:false,onlyAlphanumeric:true}))})}},index:[null,{name:o=>st(o,"index.name"),value:o=>Dt(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=>Nt(a,"tag"))},remove_bin:o=>{if(!o)return null;let a=[];if(Array.isArray(o))for(let d of o)if(typeof d=="string")a.push(d.split("?")[0]);else if(d.url&&d.size&&d.filename){let g=d.url.split("/").slice(0,3).join("/")+"/"+d.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 $i(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={},o={},d={_is_bulk_:await Promise.all(e.map(async(h,m)=>{if(!h||typeof h!="object"||Array.isArray(h))throw new l(`"params[${m}]" should be type: <object>.`,{code:"INVALID_PARAMETER"});o[m]={has:h.data!==void 0,value:h.data};let _=ji.bind(this)(h),b=_.config;if(L.call(this)){let A=Object.prototype.hasOwnProperty.call(b,"data"),w=await gr.bind(this)(b.data,Fi(h,b),A);w.encrypted&&(b.data=w.send,s[m]=w.plain);}if(_.is_reference_post&&t.push(_.is_reference_post),typeof b.progress=="function"&&i===null&&(i=b.progress),b.service!==void 0){if(r===void 0)r=b.service;else if(r!==b.service)throw new l('All bulk params should share the same "service" value.',{code:"INVALID_PARAMETER"})}if(b.owner!==void 0){if(n===void 0)n=b.owner;else if(n!==b.owner)throw new l('All bulk params should share the same "owner" value.',{code:"INVALID_PARAMETER"})}return delete b.progress,delete b.service,delete b.owner,b})),service:"",owner:""};r!==void 0&&(d.service=r),n!==void 0&&(d.owner=n);let c={auth:!!this.__user,method:"post"},g={};Object.keys(g).length&&Object.assign(c,{fetchOptions:g});let f=await S.bind(this)("post-record",d,c),u=await Promise.all(f.map((h,m)=>Se.bind(this)(h,"called from postRecord",o[m]?.has===true,s.hasOwnProperty(m))));for(let h=0;h<u.length;h++)s.hasOwnProperty(h)&&u[h]&&!u[h].error?(u[h].data=s[h],u[h].encrypted={status:"encrypted"}):o[h]?.has&&u[h]&&!f[h]?.error&&Dr(f[h]?.data)&&(u[h].data=o[h].value);let p=Ct.bind(this)(r,n);for(let h=0;h<f.length;h++){let m=f[h],_=u[h];if(m&&typeof m=="object"&&m.error&&_&&!_.record_id&&(_.error=m.error),typeof m?.reference_private_key=="string")for(let b of t)this.__private_access_key[b]=m.reference_private_key;_?.unique_id&&Mi.bind(this)(p,_.unique_id,_.record_id);}return u}async function xr(e,t,r){if(await this.__connection,!t)throw new l('"config" argument is required.',{code:"INVALID_PARAMETER"});let n=ji.bind(this)(t),i=n.config,s=n.progress,o=n.is_reference_post,a={auth:!!this.__user,method:"post"},d=[],c=$(e);r&&Array.isArray(r)&&r.length&&(d=d.concat(r)),c.files&&Array.isArray(c.files)&&c.files.length&&(d=d.concat(c.files));let g=t?.data!==void 0?t.data:c.data,f=g!==void 0,u=await gr.bind(this)(g,Fi(t,i),f),p=null;p=Object.assign({},i),delete p.data,u.omit||(p.data=u.send);let h={};if(typeof s=="function"&&(h.progress=s),Object.keys(h).length&&Object.assign(a,{fetchOptions:h}),u.files==="decrypt"&&t?.record_id){let w=await Rr.bind(this)(t.record_id,"decrypt",s);if(w.length){let k=p.remove_bin;p.remove_bin=Array.isArray(k)?k.concat(w):w;}}if(u.spill&&t?.record_id){let w=new FormData;if(w.append(et,new File([u.spill],"payload.bin",{type:"application/octet-stream"})),await it.bind(this)(w,{record_id:t.record_id}),u.retireCt){let k=p.remove_bin,E=[u.retireCt];p.remove_bin=Array.isArray(k)?k.concat(E):E;}}let m=await S.bind(this)("post-record",p,a);if(u.encrypted&&m?.rec&&vn.bind(this)(m.rec,u.dek),u.files==="encrypt"&&m?.rec)try{let w=await Rr.bind(this)(m.rec,"encrypt",s);w.length&&await xr.bind(this)(void 0,{record_id:m.rec,remove_bin:w});}catch(w){console.error("Failed to encrypt existing attachments after making the record private:",w);}if(H()&&d.length){let w=new FormData;for(let N of d)w.append(N.name,N.file,N.file.name);let k={record_id:m.rec,progress:s};i.hasOwnProperty("service")&&(k.service=i.service);let{bin_endpoints:E}=await it.bind(this)(w,k);m.bin?m.bin.push(...E):m.bin=E;}o&&typeof m?.reference_private_key=="string"&&(this.__private_access_key[o]=m.reference_private_key);let _=!!m&&Dr(m.data),b=!u.omit&&u.send!==void 0,A=await Se.bind(this)(m,"called from postRecord",b,u.encrypted);if(_&&b&&!u.encrypted&&(A.data=u.plain),u.encrypted&&(A.data=u.plain,A.encrypted={status:"encrypted",recipients:Object.keys(u.send.k||{})}),A.unique_id){let w=Ct.bind(this)(i?.service,i?.owner);Mi.bind(this)(w,A.unique_id,A.record_id),H()&&(this.__uniqueIdsPersistTimer!==null&&clearTimeout(this.__uniqueIdsPersistTimer),this.__uniqueIdsPersistTimer=setTimeout(()=>{this.__uniqueIdsPersistTimer=null;try{window.sessionStorage.setItem(`${w}:uniqueids`,JSON.stringify(this.__my_unique_ids[w]||{}));}catch{}},500));}return A}async function Bi(e,t){await ot.call(this,"getTables");let r=await S.bind(this)("get-table",y.Params(e||{},{table:i=>Me(i,"table",{allowEmpty:true}),condition:["gt","gte","lt","lte",">",">=","<","<=","=","eq","!=","ne"]}),Object.assign({auth:!!this.__user},{fetchOptions:t})),n={cnt_rec:"number_of_records",tbl:"table",srvc:"service",grp_:"number_of_records_in_access_group_"};if(Array.isArray(r?.list))for(let i of r.list){for(let s in n){if(s==="grp_"){for(let o in i)if(o.startsWith("grp_")){let 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 ot.call(this,"getIndexes"),!e?.table)throw new l('"table" is required.',{code:"INVALID_PARAMETER"});let r=y.Params(e||{},{table:s=>Me(s,"table",{allowEmpty:true}),index:s=>st(s,"index.name"),order:{by:["average_number","total_number","number_count","average_bool","total_bool","bool_count","string_count","index_name","number_of_records"],value:s=>{if(e?.order?.by==="index_name"&&typeof s=="string")return fe(s,"order.value",{allowEmpty:true,maxLength:256,blockKeyDelimiters:true});if(typeof s!="string"&&typeof s!="number"&&typeof s!="boolean")throw new 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 S.bind(this)("get-index",r,Object.assign({auth:!!this.__user},{fetchOptions:t})),i={cnt_bool:"boolean_count",cnt_numb:"number_count",totl_numb:"total_number",totl_bool:"total_bool",avrg_numb:"average_number",avrg_bool:"average_bool",cnt_str:"string_count"};return Array.isArray(n?.list)&&(n.list=n.list.map(s=>{let o=s.idx.split("/"),a={table:le(o[1]),index:le(o[2]),number_of_records:s.cnt_rec};for(let d in i)Object.prototype.hasOwnProperty.call(s,d)&&(a[i[d]]=s[d]);return a})),n}async function Hi(e,t){await ot.call(this,"getTags");let r=await S.bind(this)("get-tag",y.Params(e||{},{table:n=>Me(n,"table",{allowEmpty:true}),tag:n=>Nt(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 Gi(e,t){await ot.call(this,"getUniqueId");let r=await S.bind(this)("get-uniqueid",y.Params(e||{},{unique_id:"string",condition:["gt","gte","lt","lte",">",">=","<","<=","=","eq","!=","ne"]}),Object.assign({auth:!!this.__user},{fetchOptions:t}));if(Array.isArray(r?.list))for(let n in r.list){let i=r.list[n];r.list[n]={unique_id:i.unq,record_id:i.rec};}return r}async function Wi(e,t){await this.__connection;let r=await qi.bind(this)(e,true),n=r.is_reference_fetch,i=await S.bind(this)("del-records",r.query,{auth:true,fetchOptions:t});return n&&typeof i?.reference_private_key=="string"&&(this.__private_access_key[n]=i.reference_private_key),Array.isArray(i?.list)&&(i.list=await Promise.all(i.list.map(async s=>{if(!s||typeof s!="object")return s;try{return await Se.bind(this)(s,"called from deleteRecords",!0,!1,!0)}catch{return s}}))),i?.message||i}async function Qi(e){if(L.call(this)){let t=typeof e.user_id=="string"?[e.user_id]:e.user_id;Array.isArray(t)&&t.length&&await Er.bind(this)(e.record_id,t);}return Xi.bind(this)({record_id:e.record_id,user_id:e.user_id,execute:"add"})}async function zi(e){let t=await Xi.bind(this)({record_id:e.record_id,user_id:e.user_id||null,execute:"remove"});if(L.call(this)){let r=typeof e.user_id=="string"?[e.user_id]:e.user_id;await Kn.bind(this)(e.record_id,Array.isArray(r)&&r.length?r:null);}return t}async function Ji(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 S.bind(this)("grant-private-access",r,{auth:true,fetchOptions:t});return i.list=i.list.map(n),i}function Yi(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(xt[t])return xt[t];let n=S.bind(this)("request-private-access-key",{record_id:t,reference_id:r},{auth:true}).then(i=>{let s=typeof i=="string"?i:i?.private_key;if(typeof s!="string")throw new l("Invalid private access key response.",{code:"ERROR"});return this.__private_access_key[t]=s,s}).finally(()=>{delete xt[t];});return xt[t]=n,n}function Xi(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),S.bind(this)("grant-private-access",r,{auth:true})}var D={},G={},ce={},pe={},ge={},Ot={},Lt={};function Zi(e,t,r){e[t]||(e[t]=[]),e[t].push(r);}async function Mt(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 Cr(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 D[s].setRemoteDescription(new RTCSessionDescription(i));let a=await D[s].createAnswer();await D[s].setLocalDescription(a),o.send(JSON.stringify({action:"rtc",uid:s,content:{sdpanswer:a},token:this.session.accessToken.jwtToken}));}D?.[t]?e?(await Mt(Lt,t,i=>n.bind(this)(i,t,r)),await n.bind(this)(e,t,r)):await Mt(Lt,t,i=>n.bind(this)(i,t,r)):e&&Zi(Lt,t,e);}async function Or(e,t){if(this.log("receiveIceCandidate",e),D?.[t]&&D[t]?.remoteDescription&&D[t]?.remoteDescription?.type){if(!e)return Mt(Ot,t,r=>D[t].addIceCandidate(r));await Mt(Ot,t,r=>D[t].addIceCandidate(r)),await D[t].addIceCandidate(e);}else Zi(Ot,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 Lt[s],delete Ot[s],G[s]&&Object.values(G[s]).forEach(o=>{o.readyState!=="closed"&&o.close();}),delete G[s],D?.[s]){D[s].connectionState!=="closed"&&(D[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:D[s],timestamp:new Date().toISOString(),state:D[s].connectionState,iceState:D[s].iceConnectionState,signalingState:D[s].signalingState};ge[s]&&ge[s](o),this.log("closeRTC",o);}delete ge[s],delete pe[s],delete ce[s],delete D[s];};if(n)for(let s in D)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 es(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 ts(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}]};D?.[r]||(D[r]=new RTCPeerConnection(s)),e?.media&&(this.__mediaStream=await es(e.media),this.__mediaStream.getTracks().forEach(o=>{D[r].addTrack(o,this.__mediaStream);})),ge[r]=t,G[r]||(G[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 d=a.protocol||"default";if(Object.keys(G[r]).includes(d))throw new l(`Data channel with the protocol "${d}" already exists.`,{code:"INVALID_REQUEST"});let c=D[r].createDataChannel(d,a);G[r][d]=c;}for(let o in G[r]){let a=G[r][o];is.bind(this)(r,a);}return ns.bind(this)(r,["onnegotiationneeded"]),await Ur.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;D[r].onnegotiationneeded=()=>{this.log("onnegotiationneeded",`sending offer to "${r}".`),Ur.bind(this)(r),ge[r]&&ge[r]({type:"negotiationneeded",target:D[r],timestamp:new Date().toISOString(),signalingState:D[r].signalingState,connectionState:D[r].iceConnectionState,gatheringState:D[r].iceGatheringState});},o({target:D[r],channels:G[r],hangup:()=>ue.bind(this)({cid:r}),media:this.__mediaStream});}).bind(this);})}}function rs(e){return async(t,r)=>{t=t||{},t=$(t).data;let n=e.sender_cid,i=await this.__socket;if(!pe[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 D?.[n]||(D[n]=new RTCPeerConnection({iceServers:[{urls:s}]})),t?.media&&(this.__mediaStream=await es(t.media),this.__mediaStream.getTracks().forEach(o=>{D[n].addTrack(o,this.__mediaStream);})),delete pe[n],ge[n]=r,G[n]||(G[n]={}),D[n].ondatachannel=o=>{this.log("ondatachannel",`received data channel "${o.channel.label}".`);let a=o.channel;G[n][a.label]=a,is.bind(this)(n,a);},ns.bind(this)(n,["onnegotiationneeded"]),await Cr.bind(this)(null,n),await Or.bind(this)(null,n),i.send(JSON.stringify({action:"rtc",uid:n,content:{pickup:this.user.user_id},token:this.session.accessToken.jwtToken})),{target:D[n],channels:G[n],hangup:()=>ue.bind(this)({cid:n}),media:this.__mediaStream}}}async function Ur(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 D[e].createOffer();await D[e].setLocalDescription(r);let n=D[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 Xa(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=ge[t]||(()=>{}),i=e.candidate;this.log("ice gathering state set to",D[t].iceGatheringState),n({type:"icecandidate",target:D[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:D[t].iceGatheringState,connectionState:D[t].iceConnectionState}),r.send(JSON.stringify({action:"rtc",uid:t,content:{candidate:i},token:this.session.accessToken.jwtToken}));}function ns(e,t){let r=new Set(t),n=ge[e]||(o=>{}),i=D[e],s={ontrack:o=>{n({type:"track",target:i,timeStamp:o.timeStamp,streams:o.streams,track:o.track});},onicecandidate:o=>{Xa.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:()=>{Ur.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 is(e,t,r){let n=new Set(r),i=ge[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),G[e]&&(delete G[e][t.label],Object.keys(G[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 we;function ss(){return we}var Re=null,at=true,qe=0;async function Za(){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 Lr=null;async function Ft(){if(typeof window>"u"||window._runningInNodeJS)throw new l("WebSocket is not supported in Node.js environment.",{code:"NOT_SUPPORTED"});at=true;let e=this.__socket?await this.__socket:this.__socket;ue.bind(this)({close_all:true}),we&&je.bind(this)({group:null}),qe=0,Re&&(Re.terminate(),Re=null);try{e&&e.close();}catch{}return window.removeEventListener("visibilitychange",Lr),this.__socket=null,null}async function Ve(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(at&&(Lr=()=>{!document.hidden&&!at&&Ve.bind(this)(e,0,"reconnect");},this.__socket instanceof Promise))return this.__socket;Re&&(Re.terminate(),Re=null);let n={value:null};return this.__socket=new Promise(async(i,s)=>{let o=a=>{this.__socket===n.value&&(this.__socket=null),s(a);};try{await Oe.bind(this)();}catch(a){o(a);return}setTimeout(async()=>{try{let a=await Za.bind(this)();a.onopen=()=>{at=!1,qe=0,r!=="reconnect"&&window.addEventListener("visibilitychange",Lr),this.log("realtime onopen","Connected to WebSocket server."),e({type:"success",message:"Connected to WebSocket server."}),we&&a.send(JSON.stringify({action:"joinRoom",rid:we,token:this.session.accessToken.jwtToken}));let d=`
|
|
207
207
|
let interval = 15000; // Set interval time 15 seconds
|
|
208
208
|
|
|
209
209
|
function runInterval() {
|
|
@@ -224,7 +224,7 @@ ${n}`;}}}function dl(e,t){let r=globalThis.process,n=ve("readline");return new P
|
|
|
224
224
|
This process remembers the ID until it exits. To stop being asked, replace "${e}" in your code with the ID.
|
|
225
225
|
`),d();})}async function to(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 S.bind(this)("block-account",t,{auth:true})}async function ro(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 S.bind(this)("block-account",t,{auth:true})}async function no(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 S.bind(this)("remove-account",t,{auth:true})}async function io(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 S.bind(this)("admin-signup",n,{auth:true})}async function so(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 S.bind(this)("admin-signup",n,{auth:true})}async function oo(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 S.bind(this)("grant-access",e,{auth:true})}async function ao(e,t){if(e=y.Params(e,{email:"string"}),!await Q.bind(this)()){if(!this.__user)throw new 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 S.bind(this)("invitation-list",Object.assign({mode:"search"},e),{fetchOptions:t,auth:true});return n.list=n.list.map(i=>Ke(i.user)),n}async function lo(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 S.bind(this)("invitation-list",Object.assign({mode:"cancel"},e),{auth:true})}async function co(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 S.bind(this)("invitation-list",Object.assign({mode:"resend"},e),{auth:true})}async function uo(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,await this.__connection,this.__user?.user_id&&t.user_id===this.__user.user_id)throw new l("Cannot modify attributes of the current user.",{code:"INVALID_REQUEST"});if(Object.keys(t).filter(o=>o!=="user_id"&&t[o]!==void 0).length===0)throw new l("At least one attribute to update is required.",{code:"INVALID_PARAMETER"});if(!await 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 s={attributes:t};return r&&n&&(s.service=r,s.owner=n),await S.bind(this)("admin-edit-profile",s,{auth:true})}async function fo(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 S.bind(this)("store-subscription",{endpoint:e.endpoint,keys:e.keys},{auth:true}),"SUCCESS: Subscribed to receive notifications."}async function go(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 S.bind(this)("delete-subscription",{endpoint:e.endpoint,keys:e.keys},{auth:true}),"SUCCESS: Unsubscribed from notifications."}async function po(){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 S.bind(this)("get-vapid-public-key",null,{auth:true})}}async function ho(e,t){if(typeof window>"u"||window._runningInNodeJS)throw new l("Push Notifications are not supported in Node.js environment.",{code:"NOT_SUPPORTED"});await this.__connection;let{title:r,body:n}=$(e||{},{nullIfEmpty:true}).data;if(!r)throw new l("Missing parameter: message title",{code:"INVALID_PARAMETER"});if(!n)throw new l("Missing parameter: message body",{code:"INVALID_PARAMETER"});let i={title:r,body:n};return t?(typeof t=="string"&&(t=[t]),i.user_ids=t):i.user_ids="all_users",await S.bind(this)("push-notification",i,{auth:true}),"SUCCESS: Notification sent."}async function mo(e){await this.__connection,e=y.Params(e,{spell:"string",name:"string",magic:r=>r},["spell","name"]);await S.bind(this)("castspell",e);return `The spell "${e.spell}" has been cast.`}async function yo(e){return await this.__connection,e=y.Params(e||{},{search:["spell","name",()=>"spell"],value:"string"}),await S.bind(this)("getspell",e)}async function bo(e){await this.__connection,e=y.Params(e,{message:"string",name:"string"},["message","name"]);let t=await S.bind(this)("dopamine",e,{auth:true}),r=t?.previous_message?.message,n=t?.previous_message?.name;if(H())r&&n&&window.alert(`${n} said: ${r}`),window.location.href=t.video;else return r&&n?`${n} said: ${r}
|
|
226
226
|
Watch the video here: ${t.video}`:`Your message has been uploaded for future generations to receive.
|
|
227
|
-
Watch the video here: ${t.video}`}var I=class{constructor(t,r,n,i){this.__version="2.2.
|
|
227
|
+
Watch the video here: ${t.video}`}var I=class{constructor(t,r,n,i){this.__version="2.2.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=50;this.__disabledAccount=null;this.__cached_requests={};this.__startKeyHistory={};this.__request_signup_confirmation=null;this.__private_access_key={};this.__class_properties_has_been_cached=false;this.__user=null;this._userProfileListeners=[];this._onLoginListeners=[];this._onBatchProcessListeners=[];this.validate={userId(t){try{return y.UserId(t),!0}catch{return false}},url(t){try{return y.Url(t),!0}catch{return false}},phoneNumber(t){try{return y.PhoneNumber(t),!0}catch{return false}},birthdate(t){try{return y.Birthdate(t),!0}catch{return false}},email(t){try{return y.Email(t),!0}catch{return false}},params(t,r,n){return y.Params(t,r,n)}};this.util={MD5:Z,generateRandom:Ie,toBase62:Xr,fromBase62:se,decodeProjectId:Jt,formatServiceId:Yt,extractFormData:$,terminatePendingRequests:Ti,request:(t,r,n)=>S.bind(this)(t,r,n,{ignoreService:true})};this.__projectIdInput=null;this.__network_logs=false;this.__endpoint_version="v2";this.__public_identifier="";this.bearerToken="";this.registerTicket=ii.bind(this);this.unregisterTicket=si.bind(this);if(!t||typeof t!="string")throw this._alert("Service ID is required."),new l("Service ID is required.",{code:"INVALID_PARAMETER"});if(zs(t)){let o=Js(),a=null;if(o)try{a=this._resolveProject(o,r,n,i);}catch{$t(o);}if(a)H()&&console.info(`Skapi: "${t}" was replaced with the Project ID entered earlier in this tab (${o}). It is kept in sessionStorage under "${$e}"; delete that entry to enter a different one.`),this._start(a),this.__connection.catch(()=>$t(o));else if(Xs())this._startAfterProjectIdInput(t,r,n,i);else throw this._alert(`Replace "${t}" with your actual Project ID.`),new l("Project ID is required.",{code:"INVALID_PARAMETER"});return}let s;try{s=this._resolveProject(t,r,n,i);}catch(o){throw this._alert(o.message),o}this._start(s);}get user(){return this.__user&&Object.keys(this.__user).length?JSON.parse(JSON.stringify(this.__user)):null}set user(t){}get onLogin(){return this._onLoginListeners}set onLogin(t){typeof t=="function"&&this._onLoginListeners.push(t);}get onUserUpdate(){return this._userProfileListeners}set onUserUpdate(t){typeof t=="function"&&this._userProfileListeners.push(t);}_runOnUserUpdateListeners(t){for(let r of this._userProfileListeners)typeof r=="function"&&r(t);}_runOnLoginListeners(t){for(let r of this._onLoginListeners)typeof r=="function"&&r(t);}get onBatchProcess(){return this._onBatchProcessListeners}set onBatchProcess(t){typeof t=="function"&&this._onBatchProcessListeners.push(t);}_alert(t){H()&&typeof window.alert=="function"&&window.alert(t);}_resolveProject(t,r,n,i){let s=t.split("-").length;if(s===2||s===7)try{let d=Jt(t);n&&typeof n=="object"&&(i=n),r&&typeof r=="object"&&(n=r),r=d.owner,t=d.service;}catch{throw new l("Service ID is invalid.",{code:"INVALID_PARAMETER"})}if(!r||typeof r!="string")throw new l("Owner ID is invalid.",{code:"INVALID_PARAMETER"});if(r!==this.host)try{y.UserId(r,'"owner"');}catch{throw new l("Owner ID is invalid.",{code:"INVALID_PARAMETER"})}return {service:t,owner:r,options:n,__etc:i}}_startAfterProjectIdInput(t,r,n,i){let s=eo(t,o=>{this._resolveProject(o,r,n,i);}).then(o=>{Ys(o),this._start(this._resolveProject(o,r,n,i)),this.__connection.catch(()=>$t(o));});this.__projectIdInput=s,this.admin_endpoint=s.then(()=>this.admin_endpoint),this.record_endpoint=s.then(()=>this.record_endpoint),this.__authConnection=s.then(()=>this.__authConnection),this.__connection=s.then(()=>this.__connection);for(let o of [s,this.admin_endpoint,this.record_endpoint,this.__authConnection,this.__connection])o.catch(()=>{});}_start({service:t,owner:r,options:n,__etc:i}){this.service=t,this.owner=r;try{this.project_id=Yt(t,r);}catch{this.project_id="";}let s=true,o=false,a=null;if(n&&(typeof n.refetchServiceInfo=="boolean"&&(o=n.refetchServiceInfo),typeof n.autoLogin=="boolean"&&(s=n.autoLogin),n.encryption&&(a=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`,c=t.substring(0,4);this.admin_endpoint=fetch(`${d}/${c}/admin-${this.__endpoint_version}.json`).then(h=>h.blob()).then(h=>new Promise((m,_)=>{let b=new FileReader;b.onloadend=()=>m(b.result),b.onerror=_,b.readAsDataURL(h);})).then(h=>{try{return typeof h=="string"?JSON.parse(atob(h.split(",")[1])):null}catch{throw new l("Service does not exist. Create your service from skapi.com",{code:"NOT_EXISTS"})}}),this.record_endpoint=fetch(`${d}/${c}/record-${this.__endpoint_version}.json`).then(h=>h.blob()).then(h=>new Promise((m,_)=>{let b=new FileReader;b.onloadend=()=>m(b.result),b.onerror=_,b.readAsDataURL(h);})).then(h=>{try{return typeof h=="string"?JSON.parse(atob(h.split(",")[1])):null}catch{throw new l("Service does not exist. Create your service from skapi.com",{code:"NOT_EXISTS"})}});let g=H();if(g&&!window.sessionStorage)throw this._alert("This browser is not supported."),new Error("This browser is not supported.");let f=g?JSON.parse(window.sessionStorage.getItem(`${t}#${r}`)||"null"):null;if(this.log("constructor:restore",f),f?.connection){for(let h in f)this[h]=f[h];f.__public_identifier||(this.__public_identifier=`${this.service}:${this.owner}:${Ie(16)}`);}Rn.bind(this)(a),this.__authConnection=(async()=>{let h=await this.admin_endpoint,m={UserPoolId:h.userpool_id,ClientId:h.userpool_client};zt()&&(m.Storage=window.localStorage),this.userPool=new CognitoUserPool(m);try{this.user||await W.bind(this)().getSession({skipUserUpdateEventTrigger:!0}),this.user&&(!f?.connection&&!s?be.bind(this)():(a&&$n.bind(this)(),this._runOnLoginListeners(this.user),this._runOnUserUpdateListeners(this.user)));}catch{}})();let u=`${this.service}/${this.owner}`,p=g?window.sessionStorage.getItem(`${u}:uniqueids`):null;if(p)try{let h=JSON.parse(p);this.__my_unique_ids=h&&typeof h=="object"&&!Array.isArray(h)?{[u]:h}:{};}catch{this.__my_unique_ids={};}this.__connection=(async()=>{let h=null;await this.record_endpoint,f?.connection||(h=this._updateConnection({refresh:o}));let m=()=>{if(this.__class_properties_has_been_cached)return;let _=()=>{let b={},A=["__startKeyHistory","__disabledAccount","__cached_requests","__request_signup_confirmation","__public_identifier","connection"];if(this.connection){for(let w of A)b[w]=this[w];if(a&&(b.__cached_requests={},b.__startKeyHistory={}),g){let w=`${t}#${r}`;try{window.sessionStorage.setItem(w,JSON.stringify(b));}catch{try{let E=Object.assign({},b,{__cached_requests:{},__startKeyHistory:{}});window.sessionStorage.setItem(w,JSON.stringify(E));}catch{try{window.sessionStorage.removeItem(w);}catch{}}}}this.__class_properties_has_been_cached=true;}};return h instanceof Promise?h.then(()=>_()):_()};return g&&(window.addEventListener("beforeunload",()=>{this.closeRealtime(),m();}),window.addEventListener("visibilitychange",()=>{m();})),await h,await this.__authConnection,this.connection})(),this.__connection.then(h=>{((h?.group||0)<3||this.__network_logs)&&this.version();}).catch(()=>{});}async getConnectionInfo(t){t?.refresh&&(this.__connection instanceof Promise&&await this.__connection,this.__connection=this._updateConnection({refresh:true}));let n=await this.__connection,i=n?.user_agent||(H()&&typeof window.navigator?.userAgent=="string"?window.navigator.userAgent:`skapi-node/${globalThis?.process?.versions?.node||"unknown"}`);return {project_id:this.project_id,user_ip:n.ip,user_agent:i,user_location:n.locale,service_name:n.service_name,version:this.__version,service_description:n?.service_description||"",ai_agent:n?.ai_agent||"",conf:n?.opt}}async _updateConnection(t){let r=t?.refresh||false;try{this.connection=await S.bind(this)("service",{service:this.service,owner:this.owner,refresh:r},{bypassAwaitConnection:!0,method:"get"});}catch(n){throw this.log("connection fail",n),this._alert("Service is not available: "+(n.message||n.toString())),this.connection=null,n}return this.connection}async version(){if(await this.__connection,H()){let r=`Built with:
|
|
228
228
|
%c\r
|
|
229
229
|
##\\ ##\\ \r
|
|
230
230
|
## | \\__|\r
|