skapi-js 1.5.0-beta.3 → 1.5.0-beta.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/skapi.cjs CHANGED
@@ -214,7 +214,7 @@ var Mn=Object.defineProperty;var Vn=Object.getOwnPropertyDescriptor;var te=(n=>t
214
214
  runInterval(); // Start interval
215
215
  `,o=new Blob([s],{type:"application/javascript"});Z=new Worker(URL.createObjectURL(o)),Z.onmessage=c=>{r.readyState===1&&r.send(JSON.stringify({action:"keepAlive"}));},i(r);},r.onmessage=async s=>{let o="";try{o=JSON.parse(decodeURI(s.data)),this.log("socket onmessage",o);}catch{return}let c;switch(true){case !!o?.["#message"]:c="message";break;case !!o?.["#private"]:c="private";break;case !!o?.["#notice"]:c="notice";break;case !!o?.["#rtc"]:c="rtc";break;case !!o?.["#error"]:c="error";break}if(!c)return;let u={type:c,message:o?.["#rtc"]||o?.["#message"]||o?.["#private"]||o?.["#notice"]||o?.["#error"]||null,sender:o?.["#user_id"]||null,sender_cid:o?.["#scid"]?"cid:"+o["#scid"]:null,sender_rid:o?.["#srid"]||null,code:o?.["#code"]||null};if(c==="notice")n(u);else if(c==="rtc"){if(u.sender!==this.user.user_id){let d=u.message;if(d.hungup){K[u.sender_cid]&&(K[u.sender_cid](false),delete K[u.sender_cid]),H[u.sender_cid]&&delete H[u.sender_cid],I?.[u.sender_cid]&&Q.bind(this)({cid:u.sender_cid}),u.type="rtc:closed",n(u);return}if(d.candidate&&je.bind(this)(d.candidate,u.sender_cid),d.sdpoffer&&(qe.bind(this)(d.sdpoffer,u.sender_cid),H[u.sender_cid]||(H[u.sender_cid]=u.sender_cid,delete u.message,u.connectRTC=en.bind(this)(u),u.type="rtc:incoming",u.hangup=(()=>{I[u.sender_cid]?Q.bind(this)({cid:u.sender_cid}):H[u.sender_cid]&&(delete H[u.sender_cid],r.send(JSON.stringify({action:"rtc",uid:u.sender_cid,content:{hungup:this.user.user_id},token:this.session.accessToken.jwtToken})));}).bind(this),n(u))),d.pickup&&K[u.sender_cid]&&(K[u.sender_cid](true),delete K[u.sender_cid]),d.sdpanswer&&I[u.sender_cid])if(I[u.sender_cid].signalingState==="have-local-offer")await I[u.sender_cid].setRemoteDescription(new RTCSessionDescription(d.sdpanswer));else throw new a("Invalid signaling state.",{code:"INVALID_REQUEST"})}}else n(u);},r.onclose=()=>{fe?(this.log("realtime onclose","WebSocket connection closed."),n({type:"close",message:"WebSocket connection closed."})):(this.log("realtime onclose","WebSocket unexpected close."),n({type:"error",message:"Skapi: WebSocket unexpected close."}),oe++,oe<3?(this.log("realtime onclose","Reconnecting to WebSocket server..."+oe),n({type:"reconnect",message:"Reconnecting to WebSocket server..."+oe}),xe.bind(this)(n,3e3,"reconnect")):(this.log("realtime onclose","Max reconnection attempts reached."),n({type:"error",message:"Skapi: Max reconnection attempts reached."})));},r.onerror=()=>{this.log("realtime onerror","WebSocket connection error."),n({type:"error",message:"Skapi: WebSocket connection error."});};},e);});}async function sn(n,e,t){if(typeof window>"u"||window._runningInNodeJS)throw new a("WebSocket is not supported in Node.js environment.",{code:"NOT_SUPPORTED"});let i=this.__socket?await this.__socket:this.__socket;if(!i)throw new a("No realtime connection. Execute connectRealtime() before this method.",{code:"INVALID_REQUEST"});if(!e)throw new a("No recipient.",{code:"INVALID_REQUEST"});await ie.bind(this)(),n=D(n).data;let r="";if(t&&(t=g.Params(t,{config:{always:"boolean"},title:"string",body:"string"},["title","body"]),r=JSON.stringify({title:t.title,body:t.body}),new Blob([r]).size>3072))throw new a("Notification size exceeds 3kb.",{code:"INVALID_PARAMETER"});if(i.readyState===1){try{g.UserId(e),i.send(JSON.stringify({action:"sendMessage",uid:e,content:n,notification:r,notificationConfig:t?.config||{},token:`IdT:${this.service}:${this.owner}:`+(this.bearerToken||this.session?.idToken?.jwtToken||"null")}));}catch(s){if(this.log("postRealtime:err",{err:s}),Y!==e)throw new a(`User has not joined to the recipient group. Run joinRealtime({ group: "${e}" })`,{code:"INVALID_REQUEST"});i.send(JSON.stringify({action:"broadcast",rid:e,content:n,notification:r,notificationConfig:t?.config||{},token:`IdT:${this.service}:${this.owner}:`+(this.bearerToken||this.session?.idToken?.jwtToken||"null")}));}return {type:"success",message:"Message sent."}}throw new a("Realtime connection is not open. Try reconnecting with connectRealtime().",{code:"INVALID_REQUEST"})}async function Ke(n){if(typeof window>"u"||window._runningInNodeJS)throw new a("WebSocket is not supported in Node.js environment.",{code:"NOT_SUPPORTED"});let e=this.__socket?await this.__socket:this.__socket;if(!e)throw new a("No realtime connection. Execute connectRealtime() before this method.",{code:"INVALID_REQUEST"});await ie.bind(this)(),n=D(n,{nullIfEmpty:true}).data;let{group:t=null}=n;if(!t&&!Y)return {type:"success",message:"Left realtime message group."};if(t!==null&&typeof t!="string")throw new a('"group" must be a string | null.',{code:"INVALID_PARAMETER"});return e.send(JSON.stringify({action:"joinRoom",rid:t,token:this.session.accessToken.jwtToken})),Y=t,{type:"success",message:t?`Joined realtime message group: "${t}".`:"Left realtime message group."}}async function on(n,e){n=g.Params(n,{user_id:i=>g.UserId(i,'User ID in "user_id"'),group:["string",()=>{if(!Y)throw new a('No group has been joined. Otherwise "group" is required.',{code:"INVALID_REQUEST"});return Y}]});let t=await w.bind(this)("get-ws-group",n,{fetchOptions:e,auth:true,method:"post"});return t.list=t.list.map(i=>({user_id:i.uid.split("#")[1],cid:"cid:"+i.cid})),t}async function an(n,e){if(await this.__connection,n||(n={searchFor:"group",value:" ",condition:">"}),n=g.Params(n,{searchFor:["group","number_of_users",()=>"group"],value:["string","number",()=>n?.searchFor&&n?.searchFor==="number_of_users"?0:" "],condition:[">",">=","=","<","<=","!=","gt","gte","eq","lt","lte","ne"],range:["string","number"]}),n.condition||(n.value===" "||!n.value?n.condition=">":n.condition="="),n.range&&n.condition&&delete n.condition,n.searchFor==="number_of_users"&&typeof n.value!="number")throw new a('"value" must be a number.',{code:"INVALID_PARAMETER"});if(n.searchFor==="group"&&typeof n.value!="string")throw new a('"value" must be a string.',{code:"INVALID_PARAMETER"});if(n.hasOwnProperty("range")&&typeof n.range!=typeof n.value)throw new a(`"range" must be a ${typeof n.value}.`,{code:"INVALID_PARAMETER"});let t=await w.bind(this)("get-ws-group",n,{fetchOptions:e,auth:true,method:"post"});return t.list=t.list.map(i=>({group:i.rid.split("#")[1],number_of_users:i.cnt})),t}var Tr=typeof FormData<"u",kr=typeof HTMLFormElement<"u",xr=typeof SubmitEvent<"u";async function cn(n){let e=false,t=r=>{for(let s in r)if(typeof r[s]=="string"&&r[s].includes("$CLIENT_SECRET")){e=true;break}};if(n=g.Params(n,{url:r=>{if(!r||typeof r!="string")throw new a('"url" should be type: <string>.',{code:"INVALID_PARAMETER"});return g.Url(r),r.includes("$CLIENT_SECRET")&&(e=true),r},clientSecretName:"string",method:r=>{if(r&&typeof r!="string")throw new a('"method" should be either "GET" or "POST" or "DELETE" or "PUT".',{code:"INVALID_PARAMETER"});let s=r.toLowerCase();if(s!=="get"&&s!=="post"&&s!=="delete"&&s!=="put")throw new a('"method" should be either "GET" or "POST" or "DELETE" or "PUT".',{code:"INVALID_PARAMETER"});return s},headers:r=>{if(r&&typeof r!="object")throw new a('"headers" should be type: <object>.',{code:"INVALID_PARAMETER"});return t(r),r},data:r=>{if(r&&typeof r!="object")throw new a('"data" should be type: <object>.',{code:"INVALID_PARAMETER"});return t(r),r},params:r=>{if(r&&typeof r!="object")throw new a('"params" should be type: <object>.',{code:"INVALID_PARAMETER"});return t(r),r}},["clientSecretName","method","url"]),!e)throw new a(`At least one parameter value should include "$CLIENT_SECRET" in ${n.method.toLowerCase()==="post"?'"data"':'"params"'} or "headers".`,{code:"INVALID_PARAMETER"});await this.__connection;let i=!!this.__user;return w.bind(this)("csr",n,{auth:i})}async function ln(n){await this.__connection;let e={name:"string",email:t=>(g.Email(t),t),subject:"string",message:"string"};return n=g.Params(n,e,["name","email","subject","message"]),await w.bind(this)("send-inquiry",n),"SUCCESS: Inquiry has been sent."}async function un(n,e){if(await this.__connection,Tr&&n instanceof FormData||kr&&n instanceof HTMLFormElement||xr&&n instanceof SubmitEvent){if(!e)throw new a("Url string as a second argument is required when form is passed.",{code:"INVALID_PARAMETER"});let i=D(n);n={url:e,data:i.data,sync:true};}let t={url:i=>g.Url(i),data:i=>i,sync:["boolean",()=>true]};if(Array.isArray(n))for(let i of n)i=g.Params(i,t);else n=g.Params(n,t);return w.bind(this)("post-secure",n,{auth:true})}async function dn(n,e){await this.__connection;let{auth:t=false,method:i="POST",bypassAwaitConnection:r=false,responseType:s,contentType:o,progress:c}=e||{};if(e=Object.assign({auth:t,method:i,bypassAwaitConnection:r,responseType:s,contentType:o},{fetchOptions:{progress:c}}),typeof n!="object"&&(o==="application/json"||o===void 0))throw new a('"data" should be type: <object>.',{code:"INVALID_PARAMETER"});return w.bind(this)("mock",n,e)}async function gn(n,e){await this.__connection,n=g.Params(n||{},{access_group:i=>{if(i==="authorized"&&(i=1),i==="public"&&(i=0),typeof i!="number")throw new a('"access_group" should be type number.',{code:"INVALID_PARAMETER"});if(i<0)throw new a('"access_group" should be zero or a positive number.',{code:"INVALID_PARAMETER"});if(i>this.__user.access_group)throw new a("User has no access.",{code:"INVALID_REQUEST"});return i}});let t=await w.bind(this)("get-feed",n,{auth:true,fetchOptions:e});for(let i in t.list)t.list[i]=await se.bind(this)(t.list[i]);return t}function he(n){if(n===this.__user.user_id)throw new a(`"user_id" cannot be the user's own ID.`,{code:"INVALID_PARAMETER"});return g.UserId(n,'"user_id"')}async function fn(n,e){if(n=D(n,{ignoreEmpty:true}).data,n=g.Params(n,{subscriber:i=>g.UserId(i,'User ID in "subscriber"'),subscription:he.bind(this),blocked:"boolean"}),!n.subscriber&&!n.subscription)throw new a('At least either "subscriber" or "subscription" should have a value.',{code:"INVALID_PARAMETER"});let t=await w.bind(this)("get-subscription",n,Object.assign({auth:true},{fetchOptions:e}));return t.list=t.list.map((i=>{let r={};if(i.sub){let s=i.sub.split("#");r.subscriber=s[2],r.subscription=s[0];}else r.subscriber=i.subscriber,r.subscription=i.subscription;return r.timestamp=i?.timestamp||i.stmp,r.blocked=i?.blocked||i.grp.substring(0,1)==="N",Object.assign(r,i.opt),r})),t}async function hn(n){await this.__connection,n=g.Params(n,{user_id:he.bind(this),get_feed:["boolean",()=>false],get_notified:["boolean",()=>false],get_email:i=>{if(i&&!this.__user.email||!this.__user.email_verified)throw new a("User has no verified email address.",{code:"INVALID_REQUEST"});return !!i}},["user_id"]);let e=await w.bind(this)("subscription",{subscribe:n.user_id,option:{get_feed:n.get_feed,get_notified:n.get_notified,get_email:n.get_email||false}},{auth:true}),t={};if(e.sub){let i=e.sub.split("#");t.subscriber=i[2],t.subscription=i[0];}else t.subscriber=e.subscriber,t.subscription=e.subscription;return t.timestamp=e?.timestamp||e.stmp,t.blocked=e?.blocked||e.grp.substring(0,1)==="N",Object.assign(t,e.opt),t}async function pn(n){await this.__connection;let{user_id:e}=g.Params(n,{user_id:he.bind(this)},["user_id"]);return await w.bind(this)("subscription",{unsubscribe:e},{auth:true})}async function mn(n){await this.__connection;let{user_id:e}=g.Params(n,{user_id:he.bind(this)},["user_id"]);return await w.bind(this)("subscription",{block:e},{auth:true})}async function bn(n){await this.__connection;let{user_id:e}=g.Params(n,{user_id:he.bind(this)},["user_id"]);return await w.bind(this)("subscription",{unblock:e},{auth:true})}async function _n(n,e){await this.__connection;let t=await M.bind(this)();n=g.Params(n,{user_id:o=>{if(o!==this.__user.user_id&&!t)throw new a("No access.",{code:"INVALID_REQUEST"});return o},group:o=>{if(o==="public"&&(o=0),o==="authorized"&&(o=1),typeof o!="number")throw new a('"group" should be type number | "public" | "authorized".',{code:"INVALID_PARAMETER"});return o}});let i=await w.bind(this)("get-newsletter-subscription",n,{auth:true,fetchOptions:e||null}),r=i?.list||i,s=[];Array.isArray(r)||(r=[]);for(let o of r){let c=o.subt.split("#"),u=true;c[0].charAt(0)==="@"&&(u=false,c[0]=c[0].substring(1));let d=parseInt(c[0]);s.push({timestamp:o.stmp,group:d,subscribed_email:c[1],active:u});}return i?.list?(i.list=s,i):s}async function yn(n){await this.__connection;let e=g.Params(n||{},{email:t=>Array.isArray(t)&&t.length>0?t.length===1?g.Email(t[0]):t.map(i=>g.Email(i)):g.Email(t),group:["number","public","authorized","admin",t=>{if(typeof t!="string"||t.length>20||!/^[a-zA-Z0-9]+$/.test(t))throw new a('"group" should be an alphanumeric string without spaces and less than 20 characters.',{code:"INVALID_PARAMETER"});return t}],redirect:t=>g.Url(t)},this.__user?["group"]:["email","group"]);return w.bind(this)(`subscribe-${this.__user?"":"public-"}newsletter`,e,{auth:!!this.__user})}async function wn(n){await this.__connection,n=g.Params(n,{group:["number","public","authorized","admin"]},["group"]);let e=Object.assign({action:"unsubscribe"},n);return w.bind(this)("subscribe-newsletter",e,{auth:true})}async function En(n,e){let t=await M.bind(this)(),i={message_id:"string",timestamp:"number",read:"number",complaint:"number",subject:"string",bounced:"number"};n||(e=Object.assign({ascending:false},e||{})),n=D(n).data,n=n||{searchFor:"timestamp",value:Date.now(),condition:"<",group:"public"},n=g.Params(n,{searchFor:["message_id","timestamp","subject","complaint","read","bounced"],value:u=>{if(typeof u!==i[n.searchFor])throw new a(`"value" type does not match the type of "${n.searchFor}" index.`,{code:"INVALID_PARAMETER"});if(typeof u=="string"&&!u)throw new a('"value" should not be empty string.',{code:"INVALID_PARAMETER"});return u},range:u=>{if(!n.hasOwnProperty("value")||typeof u!=typeof n.value)throw new a('"range" should match type of "value".',{code:"INVALID_PARAMETER"});return u},condition:[">",">=","=","<","<=","gt","gte","eq","lt","lte",()=>"="],group:u=>{if(u==="public")return 0;if(!this.session)throw new a("User should be logged in.",{code:"INVALID_REQUEST"});if(u==="authorized")return 1;if(typeof u=="number"){if(!t&&u>parseInt(this.user?.access_group||this.session?.idToken?.payload?.access_group))throw new a("User has no access.",{code:"INVALID_REQUEST"});return u}throw new a('"group" should be type: number | "public" | "authorized".',{code:"INVALID_PARAMETER"})}},["searchFor","value","group"]);let r=n.group===0?"get-public-newsletters":"get-newsletters",s=await w.bind(this)(r,n,Object.assign({method:"get",auth:r==="get-public-newsletters"?!!this.__user:true},{fetchOptions:e})),o={message_id:"mid",timestamp:"stmp",complaint:"cmpl",read:"read",subject:"subj",bounced:"bnce",url:"url",delivered:"delv"},c={message_id:"",timestamp:0,complaint:0,read:0,subject:"",bounced:"",url:"",delivered:0};return s.list=s.list.map(u=>{let d={};for(let f in o)d[f]=u[o[f]]||c[f];return d.bounced=String(d.bounced),d}),s}async function Rn(n){let e=g.Params(n,{user_id:i=>g.UserId(i,'"user_id"')},["user_id"]);if(e?.service&&e?.owner?e={service:e?.service,owner:e?.owner,block:e.user_id}:e={block:e.user_id},!await M.bind(this)()){if(!this.__user)throw new a("User needs to login.",{code:"INVALID_REQUEST"});if(this.__user.access_group<90)throw new a("Invalid access.",{code:"INVALID_REQUEST"})}return await w.bind(this)("block-account",e,{auth:true})}async function An(n){let e=g.Params(n,{user_id:i=>g.UserId(i,'"user_id"')},["user_id"]);if(e?.service&&e?.owner?e={service:e?.service,owner:e?.owner,unblock:e.user_id}:e={unblock:e.user_id},!await M.bind(this)()){if(!this.__user)throw new a("User needs to login.",{code:"INVALID_REQUEST"});if(this.__user.access_group<90)throw new a("Invalid access.",{code:"INVALID_REQUEST"})}return await w.bind(this)("block-account",e,{auth:true})}async function In(n){let e=g.Params(n,{user_id:i=>g.UserId(i,'"user_id"')},["user_id"]);if(e?.service&&e?.owner?e={service:e?.service,owner:e?.owner,delete:e.user_id}:e={delete:e.user_id},!await M.bind(this)()){if(!this.__user)throw new a("User needs to login.",{code:"INVALID_REQUEST"});if(this.__user.access_group<90)throw new a("Invalid access.",{code:"INVALID_REQUEST"})}return await w.bind(this)("remove-account",e,{auth:true})}async function Sn(n,e){let t={email:s=>g.Email(s),password:s=>g.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=>g.Birthdate(s),phone_number:s=>g.PhoneNumber(s),picture:s=>{if(s)return g.Url(s)},profile:s=>{if(s)return g.Url(s)},website:s=>{if(s)return g.Url(s)},nickname:"string",misc:"string",email_public:["boolean",()=>false],gender_public:["boolean",()=>false],address_public:["boolean",()=>false],birthdate_public:["boolean",()=>false],phone_number_public:["boolean",()=>false],openid_id:"string",access_group:s=>{try{typeof s=="string"&&(s=s==="admin"?99:parseInt(s));}catch{throw new a('"access_group" is invalid. Should be type <number>.',{code:"INVALID_PARAMETER"})}if(typeof s!="number"||s<1||s>100)throw new a('"access_group" is invalid. Should be type <number> of range 1~99',{code:"INVALID_PARAMETER"});return s}},i=g.Params(n,t,["email"]);if(e=g.Params(e,{confirmation_url:s=>{let o=s;if(typeof s=="string")o=g.Url(s);else throw new a('"options.confirmation_url" should be type: <string>.',{code:"INVALID_PARAMETER"});if(o&&!i.email)throw new a('"email" is required for signup confirmation.',{code:"INVALID_PARAMETER"});return o},email_subscription:s=>{if(typeof s!="boolean")throw new a('"options.email_subscription" should be type: <boolean>.',{code:"INVALID_PARAMETER"});if(!e?.confirmation_url)throw new a('"options.confirmation_url" is required for email subscription.',{code:"INVALID_PARAMETER"});return s},template:s=>{if(typeof s!="object"||!s.url||!s.subject)throw new a('"options.template" should be type: <object> with "url" and "subject".',{code:"INVALID_PARAMETER"});return {url:g.Url(s.url),subject:s.subject}}}),i.signup_confirmation=e?.confirmation_url||true,i.email_subscription=e?.email_subscription||false,i.template=e?.template||{},!await M.bind(this)()){if(!this.__user)throw new a("User needs to login.",{code:"INVALID_REQUEST"});if(this.__user.access_group<90)throw new a("Invalid access.",{code:"INVALID_REQUEST"})}return await w.bind(this)("admin-signup",i,{auth:true})}async function Pn(n){let e={email:r=>g.Email(r),password:r=>g.Password(r),openid_id:"string",name:"string",username:"string",gender:"string",address:r=>{if(!r)return "";if(typeof r=="string")return r;if(typeof r=="object")return JSON.stringify(r)},birthdate:r=>g.Birthdate(r),phone_number:r=>g.PhoneNumber(r),picture:r=>r?g.Url(r):"",profile:r=>r?g.Url(r):"",website:r=>r?g.Url(r):"",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:r=>{try{typeof r=="string"&&(r=parseInt(r));}catch{throw new a('"access_group" is invalid. Should be type <number>.',{code:"INVALID_PARAMETER"})}if(typeof r!="number"||r<1||r>100)throw new a('"access_group" is invalid. Should be type <number> of range 1~99',{code:"INVALID_PARAMETER"});return r}},t=g.Params(n,e,["email","password"]);if(!await M.bind(this)()){if(!this.__user)throw new a("User needs to login.",{code:"INVALID_REQUEST"});if(this.__user.access_group<90)throw new a("Invalid access.",{code:"INVALID_REQUEST"})}return await w.bind(this)("admin-signup",t,{auth:true})}async function Tn(n){if(n=g.Params(n,{user_id:t=>g.UserId(t,'"user_id"'),access_group:t=>{try{typeof t=="string"&&(t=parseInt(t));}catch{throw new a('"access_group" is invalid. Should be type <number>.',{code:"INVALID_PARAMETER"})}if(typeof t=="number"&&t>0&&t<100)return t;throw new a('"access_group" is invalid. Should be type <number> of range 1~99',{code:"INVALID_PARAMETER"})}},["user_id","access_group"]),!await M.bind(this)()){if(!this.__user)throw new a("User needs to login.",{code:"INVALID_REQUEST"});if(this.__user.access_group<90)throw new a("Invalid access.",{code:"INVALID_REQUEST"})}return await w.bind(this)("grant-access",n,{auth:true})}async function kn(n,e){if(n=g.Params(n,{email:"string"}),!await M.bind(this)()){if(!this.__user)throw new a("User needs to login.",{code:"INVALID_REQUEST"});if(this.__user.access_group<90)throw new a("Invalid access.",{code:"INVALID_REQUEST"})}let i=await w.bind(this)("invitation-list",Object.assign({mode:"search"},n),{fetchOptions:e,auth:true});return i.list=i.list.map(r=>ce(r.user)),i}async function xn(n){if(n=g.Params(n,{email:t=>g.Email(t)},["email"]),!await M.bind(this)()){if(!this.__user)throw new a("User needs to login.",{code:"INVALID_REQUEST"});if(this.__user.access_group<90)throw new a("Invalid access.",{code:"INVALID_REQUEST"})}return await w.bind(this)("invitation-list",Object.assign({mode:"cancel"},n),{auth:true})}async function vn(n){if(n=g.Params(n,{email:t=>g.Email(t)},["email"]),!await M.bind(this)()){if(!this.__user)throw new a("User needs to login.",{code:"INVALID_REQUEST"});if(this.__user.access_group<90)throw new a("Invalid access.",{code:"INVALID_REQUEST"})}return await w.bind(this)("invitation-list",Object.assign({mode:"resend"},n),{auth:true})}async function Dn(n){if(typeof window>"u"||window._runningInNodeJS)throw new a("Push Notifications are not supported in Node.js environment.",{code:"NOT_SUPPORTED"});if(await this.__connection,!n.endpoint)throw new a("Missing parameter: endpoint",{code:"INVALID_PARAMETER"});if(!n.keys||!n.keys.p256dh||!n.keys.auth)throw new a("Missing parameter: keys.p256dh or keys.auth",{code:"INVALID_PARAMETER"});return await w.bind(this)("store-subscription",{endpoint:n.endpoint,keys:n.keys},{auth:true}),"SUCCESS: Subscribed to receive notifications."}async function Nn(n){if(typeof window>"u"||window._runningInNodeJS)throw new a("Push Notifications are not supported in Node.js environment.",{code:"NOT_SUPPORTED"});if(await this.__connection,!n.endpoint)throw new a("Missing parameter: endpoint",{code:"INVALID_PARAMETER"});if(!n.keys||!n.keys.p256dh||!n.keys.auth)throw new a("Missing parameter: keys.p256dh or keys.auth",{code:"INVALID_PARAMETER"});return await w.bind(this)("delete-subscription",{endpoint:n.endpoint,keys:n.keys},{auth:true}),"SUCCESS: Unsubscribed from notifications."}async function Un(){if(typeof window>"u"||window._runningInNodeJS)throw new a("Push Notifications are not supported in Node.js environment.",{code:"NOT_SUPPORTED"});return await this.__connection,{VAPIDPublicKey:await w.bind(this)("get-vapid-public-key",null,{auth:true})}}async function Cn(n,e){if(typeof window>"u"||window._runningInNodeJS)throw new a("Push Notifications are not supported in Node.js environment.",{code:"NOT_SUPPORTED"});await this.__connection;let{title:t,body:i}=D(n||{},{nullIfEmpty:true}).data;if(!t)throw new a("Missing parameter: message title",{code:"INVALID_PARAMETER"});if(!i)throw new a("Missing parameter: message body",{code:"INVALID_PARAMETER"});let r={title:t,body:i};return e?(typeof e=="string"&&(e=[e]),r.user_ids=e):r.user_ids="all_users",await w.bind(this)("push-notification",r,{auth:true}),"SUCCESS: Notification sent."}async function Ln(n){await this.__connection,n=g.Params(n,{spell:"string",name:"string",magic:t=>t},["spell","name"]);await w.bind(this)("castspell",n);return `The spell "${n.spell}" has been cast.`}async function On(n){return await this.__connection,n=g.Params(n||{},{search:["spell","name",()=>"spell"],value:"string"}),await w.bind(this)("getspell",n)}async function Fn(n){await this.__connection,n=g.Params(n,{message:"string",name:"string"},["message","name"]);let e=await w.bind(this)("dopamine",n,{auth:true}),t=e?.previous_message?.message,i=e?.previous_message?.name;if(q())t&&i&&window.alert(`${i} said: ${t}`),window.location.href=e.video;else return t&&i?`${i} said: ${t}
216
216
  Watch the video here: ${e.video}`:`Your message has been uploaded for future generations to receive.
217
- Watch the video here: ${e.video}`}var b=class{constructor(e,t,i,r){this.__version="1.5.0-beta.3";this.session=null;this.connection=null;this.__my_unique_ids={};this.userPool=null;this.__socket=null;this.__mediaStream=null;this.host="skapi";this.hostDomain="skapi.com";this.target_cdn="d3e9syvbtso631";this.customApiDomain="skapi.dev";this.requestBatchSize=30;this.__disabledAccount=null;this.__cached_requests={};this.__startKeyHistory={};this.__request_signup_confirmation=null;this.__private_access_key={};this.__class_properties_has_been_cached=false;this.__user=null;this._userProfileListeners=[];this._onLoginListeners=[];this._onBatchProcessListeners=[];this.validate={userId(e){try{return g.UserId(e),!0}catch{return false}},url(e){try{return g.Url(e),!0}catch{return false}},phoneNumber(e){try{return g.PhoneNumber(e),!0}catch{return false}},birthdate(e){try{return g.Birthdate(e),!0}catch{return false}},email(e){try{return g.Email(e),!0}catch{return false}},params(e,t,i){return g.Params(e,t,i)}};this.util={MD5:V,generateRandom:ae,toBase62:et,fromBase62:B,decodeServiceId:Ne,formatServiceId:tt,extractFormData:D,terminatePendingRequests:xt,request:(e,t,i)=>w.bind(this)(e,t,i,{ignoreService:true})};this.__network_logs=false;this.__endpoint_version="v1";this.__public_identifier="";this.bearerToken="";this.registerTicket=ot.bind(this);this.unregisterTicket=at.bind(this);if(!e||typeof e!="string")throw this._alert("Service ID is required."),new a("Service ID is required.",{code:"INVALID_PARAMETER"});if(e.startsWith("s1_")||e.split("-").length===7)try{let l=Ne(e);i&&typeof i=="object"&&(r=i),t&&typeof t=="object"&&(i=t),t=l.owner,e=l.service;}catch{throw this._alert("Service ID is invalid."),new a("Service ID is invalid.",{code:"INVALID_PARAMETER"})}if(!t||typeof t!="string")throw this._alert("Owner ID is invalid."),new a("Owner ID is invalid.",{code:"INVALID_PARAMETER"});if(e.toLowerCase()==="service_id")throw this._alert('Replace "service_id" with your actual Service ID.'),new a("Service ID is required.",{code:"INVALID_PARAMETER"});if(t!==this.host)try{g.UserId(t,'"owner"');}catch{throw this._alert("Owner ID is invalid."),new a("Owner ID is invalid.",{code:"INVALID_PARAMETER"})}this.service=e,this.owner=t;let s=true;if(i&&(typeof i.autoLogin=="boolean"&&(s=i.autoLogin),typeof i.requestBatchSize=="number")){if(i.requestBatchSize<1)throw new a('"requestBatchSize" must be greater than 0.',{code:"INVALID_PARAMETER"});this.requestBatchSize=i.requestBatchSize;}i?.eventListener&&typeof i.eventListener=="object"&&(i.eventListener?.onLogin&&typeof i.eventListener.onLogin=="function"&&(this.onLogin=i.eventListener.onLogin),i.eventListener?.onUserUpdate&&typeof i.eventListener.onUserUpdate=="function"&&(this.onUserUpdate=i.eventListener.onUserUpdate),i.eventListener?.onBatchProcess&&typeof i.eventListener.onBatchProcess=="function"&&(this.onBatchProcess=i.eventListener.onBatchProcess)),this.target_cdn=r?.target_cdn||this.target_cdn,this.hostDomain=r?.hostDomain||this.hostDomain,this.customApiDomain=r?.customApiDomain||this.customApiDomain,this.__network_logs=!!r?.network_logs;let o=`https://${this.target_cdn}.cloudfront.net`,c=e.substring(0,4);this.admin_endpoint=fetch(`${o}/${c}/admin-${this.__endpoint_version}.json`).then(l=>l.blob()).then(l=>new Promise((h,R)=>{let p=new FileReader;p.onloadend=()=>h(p.result),p.onerror=R,p.readAsDataURL(l);})).then(l=>{try{return typeof l=="string"?JSON.parse(atob(l.split(",")[1])):null}catch{throw new a("Service does not exist. Create your service from skapi.com",{code:"NOT_EXISTS"})}}),this.record_endpoint=fetch(`${o}/${c}/record-${this.__endpoint_version}.json`).then(l=>l.blob()).then(l=>new Promise((h,R)=>{let p=new FileReader;p.onloadend=()=>h(p.result),p.onerror=R,p.readAsDataURL(l);})).then(l=>{try{return typeof l=="string"?JSON.parse(atob(l.split(",")[1])):null}catch{throw new a("Service does not exist. Create your service from skapi.com",{code:"NOT_EXISTS"})}});let u=q();if(u&&!window.sessionStorage)throw this._alert("This browser is not supported."),new Error("This browser is not supported.");let d=u?JSON.parse(window.sessionStorage.getItem(`${e}#${t}`)||"null"):null;if(this.log("constructor:restore",d),d?.connection){for(let l in d)this[l]=d[l];d.__public_identifier||(this.__public_identifier=`${this.service}:${this.owner}:${ae(16)}`);}this.__authConnection=(async()=>{let l=await this.admin_endpoint,h={UserPoolId:l.userpool_id,ClientId:l.userpool_client};De()&&(h.Storage=window.localStorage),this.userPool=new amazonCognitoIdentityJs.CognitoUserPool(h);try{this.user||await F.bind(this)().getSession({skipUserUpdateEventTrigger:!0}),this.user&&(!d?.connection&&!s?z.bind(this)():(this._runOnLoginListeners(this.user),this._runOnUserUpdateListeners(this.user)));}catch{}})();let f=u?window.sessionStorage.getItem(`${this.service}:uniqueids`):null;if(f)try{this.__my_unique_ids=JSON.parse(f);}catch{this.__my_unique_ids={};}this.__connection=(async()=>{let l=null;await this.record_endpoint,d?.connection||(l=this._updateConnection());let h=()=>{if(this.__class_properties_has_been_cached)return;let R=()=>{let p={},A=["__startKeyHistory","__disabledAccount","__cached_requests","__request_signup_confirmation","__public_identifier","connection"];if(this.connection){for(let S of A)p[S]=this[S];u&&window.sessionStorage.setItem(`${e}#${t}`,JSON.stringify(p)),this.__class_properties_has_been_cached=true;}};return l instanceof Promise?l.then(()=>R()):R()};return u&&(window.addEventListener("beforeunload",()=>{this.closeRealtime(),h();}),window.addEventListener("visibilitychange",()=>{h();})),await l,await this.__authConnection,this.connection})(),this.__connection.then(l=>{((l?.group||0)<3||this.__network_logs)&&this.version();});}get user(){return this.__user&&Object.keys(this.__user).length?JSON.parse(JSON.stringify(this.__user)):null}set user(e){}get onLogin(){return this._onLoginListeners}set onLogin(e){typeof e=="function"&&this._onLoginListeners.push(e);}get onUserUpdate(){return this._userProfileListeners}set onUserUpdate(e){typeof e=="function"&&this._userProfileListeners.push(e);}_runOnUserUpdateListeners(e){for(let t of this._userProfileListeners)typeof t=="function"&&t(e);}_runOnLoginListeners(e){for(let t of this._onLoginListeners)typeof t=="function"&&t(e);}get onBatchProcess(){return this._onBatchProcessListeners}set onBatchProcess(e){typeof e=="function"&&this._onBatchProcessListeners.push(e);}_alert(e){q()&&typeof window.alert=="function"&&window.alert(e);}async getConnectionInfo(){let e=await this.__connection,t=e?.user_agent||(q()&&typeof window.navigator?.userAgent=="string"?window.navigator.userAgent:`skapi-node/${globalThis?.process?.versions?.node||"unknown"}`);return {user_ip:e.ip,user_agent:t,user_location:e.locale,service_name:e.service_name,version:this.__version}}async _updateConnection(){try{this.connection=await w.bind(this)("service",{service:this.service,owner:this.owner},{bypassAwaitConnection:!0,method:"get"});}catch(e){throw this.log("connection fail",e),this._alert("Service is not available: "+(e.message||e.toString())),this.connection=null,e}return this.connection}async version(){if(await this.__connection,q()){let t=`Built with:
217
+ Watch the video here: ${e.video}`}var b=class{constructor(e,t,i,r){this.__version="1.5.0-beta.5";this.session=null;this.connection=null;this.__my_unique_ids={};this.userPool=null;this.__socket=null;this.__mediaStream=null;this.host="skapi";this.hostDomain="skapi.com";this.target_cdn="d3e9syvbtso631";this.customApiDomain="skapi.dev";this.requestBatchSize=30;this.__disabledAccount=null;this.__cached_requests={};this.__startKeyHistory={};this.__request_signup_confirmation=null;this.__private_access_key={};this.__class_properties_has_been_cached=false;this.__user=null;this._userProfileListeners=[];this._onLoginListeners=[];this._onBatchProcessListeners=[];this.validate={userId(e){try{return g.UserId(e),!0}catch{return false}},url(e){try{return g.Url(e),!0}catch{return false}},phoneNumber(e){try{return g.PhoneNumber(e),!0}catch{return false}},birthdate(e){try{return g.Birthdate(e),!0}catch{return false}},email(e){try{return g.Email(e),!0}catch{return false}},params(e,t,i){return g.Params(e,t,i)}};this.util={MD5:V,generateRandom:ae,toBase62:et,fromBase62:B,decodeServiceId:Ne,formatServiceId:tt,extractFormData:D,terminatePendingRequests:xt,request:(e,t,i)=>w.bind(this)(e,t,i,{ignoreService:true})};this.__network_logs=false;this.__endpoint_version="v1";this.__public_identifier="";this.bearerToken="";this.registerTicket=ot.bind(this);this.unregisterTicket=at.bind(this);if(!e||typeof e!="string")throw this._alert("Service ID is required."),new a("Service ID is required.",{code:"INVALID_PARAMETER"});if(e.startsWith("s1_")||e.split("-").length===7)try{let l=Ne(e);i&&typeof i=="object"&&(r=i),t&&typeof t=="object"&&(i=t),t=l.owner,e=l.service;}catch{throw this._alert("Service ID is invalid."),new a("Service ID is invalid.",{code:"INVALID_PARAMETER"})}if(!t||typeof t!="string")throw this._alert("Owner ID is invalid."),new a("Owner ID is invalid.",{code:"INVALID_PARAMETER"});if(e.toLowerCase()==="service_id")throw this._alert('Replace "service_id" with your actual Service ID.'),new a("Service ID is required.",{code:"INVALID_PARAMETER"});if(t!==this.host)try{g.UserId(t,'"owner"');}catch{throw this._alert("Owner ID is invalid."),new a("Owner ID is invalid.",{code:"INVALID_PARAMETER"})}this.service=e,this.owner=t;let s=true;if(i&&(typeof i.autoLogin=="boolean"&&(s=i.autoLogin),typeof i.requestBatchSize=="number")){if(i.requestBatchSize<1)throw new a('"requestBatchSize" must be greater than 0.',{code:"INVALID_PARAMETER"});this.requestBatchSize=i.requestBatchSize;}i?.eventListener&&typeof i.eventListener=="object"&&(i.eventListener?.onLogin&&typeof i.eventListener.onLogin=="function"&&(this.onLogin=i.eventListener.onLogin),i.eventListener?.onUserUpdate&&typeof i.eventListener.onUserUpdate=="function"&&(this.onUserUpdate=i.eventListener.onUserUpdate),i.eventListener?.onBatchProcess&&typeof i.eventListener.onBatchProcess=="function"&&(this.onBatchProcess=i.eventListener.onBatchProcess)),this.target_cdn=r?.target_cdn||this.target_cdn,this.hostDomain=r?.hostDomain||this.hostDomain,this.customApiDomain=r?.customApiDomain||this.customApiDomain,this.__network_logs=!!r?.network_logs;let o=`https://${this.target_cdn}.cloudfront.net`,c=e.substring(0,4);this.admin_endpoint=fetch(`${o}/${c}/admin-${this.__endpoint_version}.json`).then(l=>l.blob()).then(l=>new Promise((h,R)=>{let p=new FileReader;p.onloadend=()=>h(p.result),p.onerror=R,p.readAsDataURL(l);})).then(l=>{try{return typeof l=="string"?JSON.parse(atob(l.split(",")[1])):null}catch{throw new a("Service does not exist. Create your service from skapi.com",{code:"NOT_EXISTS"})}}),this.record_endpoint=fetch(`${o}/${c}/record-${this.__endpoint_version}.json`).then(l=>l.blob()).then(l=>new Promise((h,R)=>{let p=new FileReader;p.onloadend=()=>h(p.result),p.onerror=R,p.readAsDataURL(l);})).then(l=>{try{return typeof l=="string"?JSON.parse(atob(l.split(",")[1])):null}catch{throw new a("Service does not exist. Create your service from skapi.com",{code:"NOT_EXISTS"})}});let u=q();if(u&&!window.sessionStorage)throw this._alert("This browser is not supported."),new Error("This browser is not supported.");let d=u?JSON.parse(window.sessionStorage.getItem(`${e}#${t}`)||"null"):null;if(this.log("constructor:restore",d),d?.connection){for(let l in d)this[l]=d[l];d.__public_identifier||(this.__public_identifier=`${this.service}:${this.owner}:${ae(16)}`);}this.__authConnection=(async()=>{let l=await this.admin_endpoint,h={UserPoolId:l.userpool_id,ClientId:l.userpool_client};De()&&(h.Storage=window.localStorage),this.userPool=new amazonCognitoIdentityJs.CognitoUserPool(h);try{this.user||await F.bind(this)().getSession({skipUserUpdateEventTrigger:!0}),this.user&&(!d?.connection&&!s?z.bind(this)():(this._runOnLoginListeners(this.user),this._runOnUserUpdateListeners(this.user)));}catch{}})();let f=u?window.sessionStorage.getItem(`${this.service}:uniqueids`):null;if(f)try{this.__my_unique_ids=JSON.parse(f);}catch{this.__my_unique_ids={};}this.__connection=(async()=>{let l=null;await this.record_endpoint,d?.connection||(l=this._updateConnection());let h=()=>{if(this.__class_properties_has_been_cached)return;let R=()=>{let p={},A=["__startKeyHistory","__disabledAccount","__cached_requests","__request_signup_confirmation","__public_identifier","connection"];if(this.connection){for(let S of A)p[S]=this[S];u&&window.sessionStorage.setItem(`${e}#${t}`,JSON.stringify(p)),this.__class_properties_has_been_cached=true;}};return l instanceof Promise?l.then(()=>R()):R()};return u&&(window.addEventListener("beforeunload",()=>{this.closeRealtime(),h();}),window.addEventListener("visibilitychange",()=>{h();})),await l,await this.__authConnection,this.connection})(),this.__connection.then(l=>{((l?.group||0)<3||this.__network_logs)&&this.version();});}get user(){return this.__user&&Object.keys(this.__user).length?JSON.parse(JSON.stringify(this.__user)):null}set user(e){}get onLogin(){return this._onLoginListeners}set onLogin(e){typeof e=="function"&&this._onLoginListeners.push(e);}get onUserUpdate(){return this._userProfileListeners}set onUserUpdate(e){typeof e=="function"&&this._userProfileListeners.push(e);}_runOnUserUpdateListeners(e){for(let t of this._userProfileListeners)typeof t=="function"&&t(e);}_runOnLoginListeners(e){for(let t of this._onLoginListeners)typeof t=="function"&&t(e);}get onBatchProcess(){return this._onBatchProcessListeners}set onBatchProcess(e){typeof e=="function"&&this._onBatchProcessListeners.push(e);}_alert(e){q()&&typeof window.alert=="function"&&window.alert(e);}async getConnectionInfo(){let e=await this.__connection,t=e?.user_agent||(q()&&typeof window.navigator?.userAgent=="string"?window.navigator.userAgent:`skapi-node/${globalThis?.process?.versions?.node||"unknown"}`);return {user_ip:e.ip,user_agent:t,user_location:e.locale,service_name:e.service_name,version:this.__version}}async _updateConnection(){try{this.connection=await w.bind(this)("service",{service:this.service,owner:this.owner},{bypassAwaitConnection:!0,method:"get"});}catch(e){throw this.log("connection fail",e),this._alert("Service is not available: "+(e.message||e.toString())),this.connection=null,e}return this.connection}async version(){if(await this.__connection,q()){let t=`Built with:
218
218
  %c\r
219
219
  $$\\ $$\\ \r
220
220
  $$ | \\__|\r
package/dist/skapi.js CHANGED
@@ -215,7 +215,7 @@ var Ds=Object.create;var Ue=Object.defineProperty;var Or=Object.getOwnPropertyDe
215
215
  runInterval(); // Start interval
216
216
  `,o=new Blob([s],{type:"application/javascript"});Ae=new Worker(URL.createObjectURL(o)),Ae.onmessage=a=>{i.readyState===1&&i.send(JSON.stringify({action:"keepAlive"}));},n(i);},i.onmessage=async s=>{let o="";try{o=JSON.parse(decodeURI(s.data)),this.log("socket onmessage",o);}catch{return}let a;switch(true){case !!o?.["#message"]:a="message";break;case !!o?.["#private"]:a="private";break;case !!o?.["#notice"]:a="notice";break;case !!o?.["#rtc"]:a="rtc";break;case !!o?.["#error"]:a="error";break}if(!a)return;let u={type:a,message:o?.["#rtc"]||o?.["#message"]||o?.["#private"]||o?.["#notice"]||o?.["#error"]||null,sender:o?.["#user_id"]||null,sender_cid:o?.["#scid"]?"cid:"+o["#scid"]:null,sender_rid:o?.["#srid"]||null,code:o?.["#code"]||null};if(a==="notice")r(u);else if(a==="rtc"){if(u.sender!==this.user.user_id){let c=u.message;if(c.hungup){ie[u.sender_cid]&&(ie[u.sender_cid](false),delete ie[u.sender_cid]),de[u.sender_cid]&&delete de[u.sender_cid],I?.[u.sender_cid]&&se.bind(this)({cid:u.sender_cid}),u.type="rtc:closed",r(u);return}if(c.candidate&&Dr.bind(this)(c.candidate,u.sender_cid),c.sdpoffer&&(Cr.bind(this)(c.sdpoffer,u.sender_cid),de[u.sender_cid]||(de[u.sender_cid]=u.sender_cid,delete u.message,u.connectRTC=Gi.bind(this)(u),u.type="rtc:incoming",u.hangup=(()=>{I[u.sender_cid]?se.bind(this)({cid:u.sender_cid}):de[u.sender_cid]&&(delete de[u.sender_cid],i.send(JSON.stringify({action:"rtc",uid:u.sender_cid,content:{hungup:this.user.user_id},token:this.session.accessToken.jwtToken})));}).bind(this),r(u))),c.pickup&&ie[u.sender_cid]&&(ie[u.sender_cid](true),delete ie[u.sender_cid]),c.sdpanswer&&I[u.sender_cid])if(I[u.sender_cid].signalingState==="have-local-offer")await I[u.sender_cid].setRemoteDescription(new RTCSessionDescription(c.sdpanswer));else throw new f("Invalid signaling state.",{code:"INVALID_REQUEST"})}}else r(u);},i.onclose=()=>{et?(this.log("realtime onclose","WebSocket connection closed."),r({type:"close",message:"WebSocket connection closed."})):(this.log("realtime onclose","WebSocket unexpected close."),r({type:"error",message:"Skapi: WebSocket unexpected close."}),Ke++,Ke<3?(this.log("realtime onclose","Reconnecting to WebSocket server..."+Ke),r({type:"reconnect",message:"Reconnecting to WebSocket server..."+Ke}),Mt.bind(this)(r,3e3,"reconnect")):(this.log("realtime onclose","Max reconnection attempts reached."),r({type:"error",message:"Skapi: Max reconnection attempts reached."})));},i.onerror=()=>{this.log("realtime onerror","WebSocket connection error."),r({type:"error",message:"Skapi: WebSocket connection error."});};},e);});}async function Xi(r,e,t){if(typeof window>"u"||window._runningInNodeJS)throw new f("WebSocket is not supported in Node.js environment.",{code:"NOT_SUPPORTED"});let n=this.__socket?await this.__socket:this.__socket;if(!n)throw new f("No realtime connection. Execute connectRealtime() before this method.",{code:"INVALID_REQUEST"});if(!e)throw new f("No recipient.",{code:"INVALID_REQUEST"});await $e.bind(this)(),r=L(r).data;let i="";if(t&&(t=m.Params(t,{config:{always:"boolean"},title:"string",body:"string"},["title","body"]),i=JSON.stringify({title:t.title,body:t.body}),new Blob([i]).size>3072))throw new f("Notification size exceeds 3kb.",{code:"INVALID_PARAMETER"});if(n.readyState===1){try{m.UserId(e),n.send(JSON.stringify({action:"sendMessage",uid:e,content:r,notification:i,notificationConfig:t?.config||{},token:`IdT:${this.service}:${this.owner}:`+(this.bearerToken||this.session?.idToken?.jwtToken||"null")}));}catch(s){if(this.log("postRealtime:err",{err:s}),Ee!==e)throw new f(`User has not joined to the recipient group. Run joinRealtime({ group: "${e}" })`,{code:"INVALID_REQUEST"});n.send(JSON.stringify({action:"broadcast",rid:e,content:r,notification:i,notificationConfig:t?.config||{},token:`IdT:${this.service}:${this.owner}:`+(this.bearerToken||this.session?.idToken?.jwtToken||"null")}));}return {type:"success",message:"Message sent."}}throw new f("Realtime connection is not open. Try reconnecting with connectRealtime().",{code:"INVALID_REQUEST"})}async function Nr(r){if(typeof window>"u"||window._runningInNodeJS)throw new f("WebSocket is not supported in Node.js environment.",{code:"NOT_SUPPORTED"});let e=this.__socket?await this.__socket:this.__socket;if(!e)throw new f("No realtime connection. Execute connectRealtime() before this method.",{code:"INVALID_REQUEST"});await $e.bind(this)(),r=L(r,{nullIfEmpty:true}).data;let{group:t=null}=r;if(!t&&!Ee)return {type:"success",message:"Left realtime message group."};if(t!==null&&typeof t!="string")throw new f('"group" must be a string | null.',{code:"INVALID_PARAMETER"});return e.send(JSON.stringify({action:"joinRoom",rid:t,token:this.session.accessToken.jwtToken})),Ee=t,{type:"success",message:t?`Joined realtime message group: "${t}".`:"Left realtime message group."}}async function Zi(r,e){r=m.Params(r,{user_id:n=>m.UserId(n,'User ID in "user_id"'),group:["string",()=>{if(!Ee)throw new f('No group has been joined. Otherwise "group" is required.',{code:"INVALID_REQUEST"});return Ee}]});let t=await T.bind(this)("get-ws-group",r,{fetchOptions:e,auth:true,method:"post"});return t.list=t.list.map(n=>({user_id:n.uid.split("#")[1],cid:"cid:"+n.cid})),t}async function es(r,e){if(await this.__connection,r||(r={searchFor:"group",value:" ",condition:">"}),r=m.Params(r,{searchFor:["group","number_of_users",()=>"group"],value:["string","number",()=>r?.searchFor&&r?.searchFor==="number_of_users"?0:" "],condition:[">",">=","=","<","<=","!=","gt","gte","eq","lt","lte","ne"],range:["string","number"]}),r.condition||(r.value===" "||!r.value?r.condition=">":r.condition="="),r.range&&r.condition&&delete r.condition,r.searchFor==="number_of_users"&&typeof r.value!="number")throw new f('"value" must be a number.',{code:"INVALID_PARAMETER"});if(r.searchFor==="group"&&typeof r.value!="string")throw new f('"value" must be a string.',{code:"INVALID_PARAMETER"});if(r.hasOwnProperty("range")&&typeof r.range!=typeof r.value)throw new f(`"range" must be a ${typeof r.value}.`,{code:"INVALID_PARAMETER"});let t=await T.bind(this)("get-ws-group",r,{fetchOptions:e,auth:true,method:"post"});return t.list=t.list.map(n=>({group:n.rid.split("#")[1],number_of_users:n.cnt})),t}var qu=typeof FormData<"u",$u=typeof HTMLFormElement<"u",ju=typeof SubmitEvent<"u";async function ts(r){let e=false,t=i=>{for(let s in i)if(typeof i[s]=="string"&&i[s].includes("$CLIENT_SECRET")){e=true;break}};if(r=m.Params(r,{url:i=>{if(!i||typeof i!="string")throw new f('"url" should be type: <string>.',{code:"INVALID_PARAMETER"});return m.Url(i),i.includes("$CLIENT_SECRET")&&(e=true),i},clientSecretName:"string",method:i=>{if(i&&typeof i!="string")throw new f('"method" should be either "GET" or "POST" or "DELETE" or "PUT".',{code:"INVALID_PARAMETER"});let s=i.toLowerCase();if(s!=="get"&&s!=="post"&&s!=="delete"&&s!=="put")throw new f('"method" should be either "GET" or "POST" or "DELETE" or "PUT".',{code:"INVALID_PARAMETER"});return s},headers:i=>{if(i&&typeof i!="object")throw new f('"headers" should be type: <object>.',{code:"INVALID_PARAMETER"});return t(i),i},data:i=>{if(i&&typeof i!="object")throw new f('"data" should be type: <object>.',{code:"INVALID_PARAMETER"});return t(i),i},params:i=>{if(i&&typeof i!="object")throw new f('"params" should be type: <object>.',{code:"INVALID_PARAMETER"});return t(i),i}},["clientSecretName","method","url"]),!e)throw new f(`At least one parameter value should include "$CLIENT_SECRET" in ${r.method.toLowerCase()==="post"?'"data"':'"params"'} or "headers".`,{code:"INVALID_PARAMETER"});await this.__connection;let n=!!this.__user;return T.bind(this)("csr",r,{auth:n})}async function rs(r){await this.__connection;let e={name:"string",email:t=>(m.Email(t),t),subject:"string",message:"string"};return r=m.Params(r,e,["name","email","subject","message"]),await T.bind(this)("send-inquiry",r),"SUCCESS: Inquiry has been sent."}async function ns(r,e){if(await this.__connection,qu&&r instanceof FormData||$u&&r instanceof HTMLFormElement||ju&&r instanceof SubmitEvent){if(!e)throw new f("Url string as a second argument is required when form is passed.",{code:"INVALID_PARAMETER"});let n=L(r);r={url:e,data:n.data,sync:true};}let t={url:n=>m.Url(n),data:n=>n,sync:["boolean",()=>true]};if(Array.isArray(r))for(let n of r)n=m.Params(n,t);else r=m.Params(r,t);return T.bind(this)("post-secure",r,{auth:true})}async function is(r,e){await this.__connection;let{auth:t=false,method:n="POST",bypassAwaitConnection:i=false,responseType:s,contentType:o,progress:a}=e||{};if(e=Object.assign({auth:t,method:n,bypassAwaitConnection:i,responseType:s,contentType:o},{fetchOptions:{progress:a}}),typeof r!="object"&&(o==="application/json"||o===void 0))throw new f('"data" should be type: <object>.',{code:"INVALID_PARAMETER"});return T.bind(this)("mock",r,e)}async function ss(r,e){await this.__connection,r=m.Params(r||{},{access_group:n=>{if(n==="authorized"&&(n=1),n==="public"&&(n=0),typeof n!="number")throw new f('"access_group" should be type number.',{code:"INVALID_PARAMETER"});if(n<0)throw new f('"access_group" should be zero or a positive number.',{code:"INVALID_PARAMETER"});if(n>this.__user.access_group)throw new f("User has no access.",{code:"INVALID_REQUEST"});return n}});let t=await T.bind(this)("get-feed",r,{auth:true,fetchOptions:e});for(let n in t.list)t.list[n]=await je.bind(this)(t.list[n]);return t}function tt(r){if(r===this.__user.user_id)throw new f(`"user_id" cannot be the user's own ID.`,{code:"INVALID_PARAMETER"});return m.UserId(r,'"user_id"')}async function os(r,e){if(r=L(r,{ignoreEmpty:true}).data,r=m.Params(r,{subscriber:n=>m.UserId(n,'User ID in "subscriber"'),subscription:tt.bind(this),blocked:"boolean"}),!r.subscriber&&!r.subscription)throw new f('At least either "subscriber" or "subscription" should have a value.',{code:"INVALID_PARAMETER"});let t=await T.bind(this)("get-subscription",r,Object.assign({auth:true},{fetchOptions:e}));return t.list=t.list.map((n=>{let i={};if(n.sub){let s=n.sub.split("#");i.subscriber=s[2],i.subscription=s[0];}else i.subscriber=n.subscriber,i.subscription=n.subscription;return i.timestamp=n?.timestamp||n.stmp,i.blocked=n?.blocked||n.grp.substring(0,1)==="N",Object.assign(i,n.opt),i})),t}async function as(r){await this.__connection,r=m.Params(r,{user_id:tt.bind(this),get_feed:["boolean",()=>false],get_notified:["boolean",()=>false],get_email:n=>{if(n&&!this.__user.email||!this.__user.email_verified)throw new f("User has no verified email address.",{code:"INVALID_REQUEST"});return !!n}},["user_id"]);let e=await T.bind(this)("subscription",{subscribe:r.user_id,option:{get_feed:r.get_feed,get_notified:r.get_notified,get_email:r.get_email||false}},{auth:true}),t={};if(e.sub){let n=e.sub.split("#");t.subscriber=n[2],t.subscription=n[0];}else t.subscriber=e.subscriber,t.subscription=e.subscription;return t.timestamp=e?.timestamp||e.stmp,t.blocked=e?.blocked||e.grp.substring(0,1)==="N",Object.assign(t,e.opt),t}async function us(r){await this.__connection;let{user_id:e}=m.Params(r,{user_id:tt.bind(this)},["user_id"]);return await T.bind(this)("subscription",{unsubscribe:e},{auth:true})}async function cs(r){await this.__connection;let{user_id:e}=m.Params(r,{user_id:tt.bind(this)},["user_id"]);return await T.bind(this)("subscription",{block:e},{auth:true})}async function ls(r){await this.__connection;let{user_id:e}=m.Params(r,{user_id:tt.bind(this)},["user_id"]);return await T.bind(this)("subscription",{unblock:e},{auth:true})}async function ds(r,e){await this.__connection;let t=await J.bind(this)();r=m.Params(r,{user_id:o=>{if(o!==this.__user.user_id&&!t)throw new f("No access.",{code:"INVALID_REQUEST"});return o},group:o=>{if(o==="public"&&(o=0),o==="authorized"&&(o=1),typeof o!="number")throw new f('"group" should be type number | "public" | "authorized".',{code:"INVALID_PARAMETER"});return o}});let n=await T.bind(this)("get-newsletter-subscription",r,{auth:true,fetchOptions:e||null}),i=n?.list||n,s=[];Array.isArray(i)||(i=[]);for(let o of i){let a=o.subt.split("#"),u=true;a[0].charAt(0)==="@"&&(u=false,a[0]=a[0].substring(1));let c=parseInt(a[0]);s.push({timestamp:o.stmp,group:c,subscribed_email:a[1],active:u});}return n?.list?(n.list=s,n):s}async function fs(r){await this.__connection;let e=m.Params(r||{},{email:t=>Array.isArray(t)&&t.length>0?t.length===1?m.Email(t[0]):t.map(n=>m.Email(n)):m.Email(t),group:["number","public","authorized","admin",t=>{if(typeof t!="string"||t.length>20||!/^[a-zA-Z0-9]+$/.test(t))throw new f('"group" should be an alphanumeric string without spaces and less than 20 characters.',{code:"INVALID_PARAMETER"});return t}],redirect:t=>m.Url(t)},this.__user?["group"]:["email","group"]);return T.bind(this)(`subscribe-${this.__user?"":"public-"}newsletter`,e,{auth:!!this.__user})}async function hs(r){await this.__connection,r=m.Params(r,{group:["number","public","authorized","admin"]},["group"]);let e=Object.assign({action:"unsubscribe"},r);return T.bind(this)("subscribe-newsletter",e,{auth:true})}async function gs(r,e){let t=await J.bind(this)(),n={message_id:"string",timestamp:"number",read:"number",complaint:"number",subject:"string",bounced:"number"};r||(e=Object.assign({ascending:false},e||{})),r=L(r).data,r=r||{searchFor:"timestamp",value:Date.now(),condition:"<",group:"public"},r=m.Params(r,{searchFor:["message_id","timestamp","subject","complaint","read","bounced"],value:u=>{if(typeof u!==n[r.searchFor])throw new f(`"value" type does not match the type of "${r.searchFor}" index.`,{code:"INVALID_PARAMETER"});if(typeof u=="string"&&!u)throw new f('"value" should not be empty string.',{code:"INVALID_PARAMETER"});return u},range:u=>{if(!r.hasOwnProperty("value")||typeof u!=typeof r.value)throw new f('"range" should match type of "value".',{code:"INVALID_PARAMETER"});return u},condition:[">",">=","=","<","<=","gt","gte","eq","lt","lte",()=>"="],group:u=>{if(u==="public")return 0;if(!this.session)throw new f("User should be logged in.",{code:"INVALID_REQUEST"});if(u==="authorized")return 1;if(typeof u=="number"){if(!t&&u>parseInt(this.user?.access_group||this.session?.idToken?.payload?.access_group))throw new f("User has no access.",{code:"INVALID_REQUEST"});return u}throw new f('"group" should be type: number | "public" | "authorized".',{code:"INVALID_PARAMETER"})}},["searchFor","value","group"]);let i=r.group===0?"get-public-newsletters":"get-newsletters",s=await T.bind(this)(i,r,Object.assign({method:"get",auth:i==="get-public-newsletters"?!!this.__user:true},{fetchOptions:e})),o={message_id:"mid",timestamp:"stmp",complaint:"cmpl",read:"read",subject:"subj",bounced:"bnce",url:"url",delivered:"delv"},a={message_id:"",timestamp:0,complaint:0,read:0,subject:"",bounced:"",url:"",delivered:0};return s.list=s.list.map(u=>{let c={};for(let d in o)c[d]=u[o[d]]||a[d];return c.bounced=String(c.bounced),c}),s}async function ps(r){let e=m.Params(r,{user_id:n=>m.UserId(n,'"user_id"')},["user_id"]);if(e?.service&&e?.owner?e={service:e?.service,owner:e?.owner,block:e.user_id}:e={block:e.user_id},!await J.bind(this)()){if(!this.__user)throw new f("User needs to login.",{code:"INVALID_REQUEST"});if(this.__user.access_group<90)throw new f("Invalid access.",{code:"INVALID_REQUEST"})}return await T.bind(this)("block-account",e,{auth:true})}async function ms(r){let e=m.Params(r,{user_id:n=>m.UserId(n,'"user_id"')},["user_id"]);if(e?.service&&e?.owner?e={service:e?.service,owner:e?.owner,unblock:e.user_id}:e={unblock:e.user_id},!await J.bind(this)()){if(!this.__user)throw new f("User needs to login.",{code:"INVALID_REQUEST"});if(this.__user.access_group<90)throw new f("Invalid access.",{code:"INVALID_REQUEST"})}return await T.bind(this)("block-account",e,{auth:true})}async function _s(r){let e=m.Params(r,{user_id:n=>m.UserId(n,'"user_id"')},["user_id"]);if(e?.service&&e?.owner?e={service:e?.service,owner:e?.owner,delete:e.user_id}:e={delete:e.user_id},!await J.bind(this)()){if(!this.__user)throw new f("User needs to login.",{code:"INVALID_REQUEST"});if(this.__user.access_group<90)throw new f("Invalid access.",{code:"INVALID_REQUEST"})}return await T.bind(this)("remove-account",e,{auth:true})}async function bs(r,e){let t={email:s=>m.Email(s),password:s=>m.Password(s),name:"string",username:"string",gender:"string",address:s=>{if(!s)return "";if(typeof s=="string")return s;if(typeof s=="object")return JSON.stringify(s)},birthdate:s=>m.Birthdate(s),phone_number:s=>m.PhoneNumber(s),picture:s=>{if(s)return m.Url(s)},profile:s=>{if(s)return m.Url(s)},website:s=>{if(s)return m.Url(s)},nickname:"string",misc:"string",email_public:["boolean",()=>false],gender_public:["boolean",()=>false],address_public:["boolean",()=>false],birthdate_public:["boolean",()=>false],phone_number_public:["boolean",()=>false],openid_id:"string",access_group:s=>{try{typeof s=="string"&&(s=s==="admin"?99:parseInt(s));}catch{throw new f('"access_group" is invalid. Should be type <number>.',{code:"INVALID_PARAMETER"})}if(typeof s!="number"||s<1||s>100)throw new f('"access_group" is invalid. Should be type <number> of range 1~99',{code:"INVALID_PARAMETER"});return s}},n=m.Params(r,t,["email"]);if(e=m.Params(e,{confirmation_url:s=>{let o=s;if(typeof s=="string")o=m.Url(s);else throw new f('"options.confirmation_url" should be type: <string>.',{code:"INVALID_PARAMETER"});if(o&&!n.email)throw new f('"email" is required for signup confirmation.',{code:"INVALID_PARAMETER"});return o},email_subscription:s=>{if(typeof s!="boolean")throw new f('"options.email_subscription" should be type: <boolean>.',{code:"INVALID_PARAMETER"});if(!e?.confirmation_url)throw new f('"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 f('"options.template" should be type: <object> with "url" and "subject".',{code:"INVALID_PARAMETER"});return {url:m.Url(s.url),subject:s.subject}}}),n.signup_confirmation=e?.confirmation_url||true,n.email_subscription=e?.email_subscription||false,n.template=e?.template||{},!await J.bind(this)()){if(!this.__user)throw new f("User needs to login.",{code:"INVALID_REQUEST"});if(this.__user.access_group<90)throw new f("Invalid access.",{code:"INVALID_REQUEST"})}return await T.bind(this)("admin-signup",n,{auth:true})}async function ys(r){let e={email:i=>m.Email(i),password:i=>m.Password(i),openid_id:"string",name:"string",username:"string",gender:"string",address:i=>{if(!i)return "";if(typeof i=="string")return i;if(typeof i=="object")return JSON.stringify(i)},birthdate:i=>m.Birthdate(i),phone_number:i=>m.PhoneNumber(i),picture:i=>i?m.Url(i):"",profile:i=>i?m.Url(i):"",website:i=>i?m.Url(i):"",nickname:"string",misc:"string",email_public:["boolean",()=>false],gender_public:["boolean",()=>false],address_public:["boolean",()=>false],birthdate_public:["boolean",()=>false],phone_number_public:["boolean",()=>false],access_group:i=>{try{typeof i=="string"&&(i=parseInt(i));}catch{throw new f('"access_group" is invalid. Should be type <number>.',{code:"INVALID_PARAMETER"})}if(typeof i!="number"||i<1||i>100)throw new f('"access_group" is invalid. Should be type <number> of range 1~99',{code:"INVALID_PARAMETER"});return i}},t=m.Params(r,e,["email","password"]);if(!await J.bind(this)()){if(!this.__user)throw new f("User needs to login.",{code:"INVALID_REQUEST"});if(this.__user.access_group<90)throw new f("Invalid access.",{code:"INVALID_REQUEST"})}return await T.bind(this)("admin-signup",t,{auth:true})}async function ws(r){if(r=m.Params(r,{user_id:t=>m.UserId(t,'"user_id"'),access_group:t=>{try{typeof t=="string"&&(t=parseInt(t));}catch{throw new f('"access_group" is invalid. Should be type <number>.',{code:"INVALID_PARAMETER"})}if(typeof t=="number"&&t>0&&t<100)return t;throw new f('"access_group" is invalid. Should be type <number> of range 1~99',{code:"INVALID_PARAMETER"})}},["user_id","access_group"]),!await J.bind(this)()){if(!this.__user)throw new f("User needs to login.",{code:"INVALID_REQUEST"});if(this.__user.access_group<90)throw new f("Invalid access.",{code:"INVALID_REQUEST"})}return await T.bind(this)("grant-access",r,{auth:true})}async function Ss(r,e){if(r=m.Params(r,{email:"string"}),!await J.bind(this)()){if(!this.__user)throw new f("User needs to login.",{code:"INVALID_REQUEST"});if(this.__user.access_group<90)throw new f("Invalid access.",{code:"INVALID_REQUEST"})}let n=await T.bind(this)("invitation-list",Object.assign({mode:"search"},r),{fetchOptions:e,auth:true});return n.list=n.list.map(i=>Ge(i.user)),n}async function As(r){if(r=m.Params(r,{email:t=>m.Email(t)},["email"]),!await J.bind(this)()){if(!this.__user)throw new f("User needs to login.",{code:"INVALID_REQUEST"});if(this.__user.access_group<90)throw new f("Invalid access.",{code:"INVALID_REQUEST"})}return await T.bind(this)("invitation-list",Object.assign({mode:"cancel"},r),{auth:true})}async function Es(r){if(r=m.Params(r,{email:t=>m.Email(t)},["email"]),!await J.bind(this)()){if(!this.__user)throw new f("User needs to login.",{code:"INVALID_REQUEST"});if(this.__user.access_group<90)throw new f("Invalid access.",{code:"INVALID_REQUEST"})}return await T.bind(this)("invitation-list",Object.assign({mode:"resend"},r),{auth:true})}async function vs(r){if(typeof window>"u"||window._runningInNodeJS)throw new f("Push Notifications are not supported in Node.js environment.",{code:"NOT_SUPPORTED"});if(await this.__connection,!r.endpoint)throw new f("Missing parameter: endpoint",{code:"INVALID_PARAMETER"});if(!r.keys||!r.keys.p256dh||!r.keys.auth)throw new f("Missing parameter: keys.p256dh or keys.auth",{code:"INVALID_PARAMETER"});return await T.bind(this)("store-subscription",{endpoint:r.endpoint,keys:r.keys},{auth:true}),"SUCCESS: Subscribed to receive notifications."}async function Ts(r){if(typeof window>"u"||window._runningInNodeJS)throw new f("Push Notifications are not supported in Node.js environment.",{code:"NOT_SUPPORTED"});if(await this.__connection,!r.endpoint)throw new f("Missing parameter: endpoint",{code:"INVALID_PARAMETER"});if(!r.keys||!r.keys.p256dh||!r.keys.auth)throw new f("Missing parameter: keys.p256dh or keys.auth",{code:"INVALID_PARAMETER"});return await T.bind(this)("delete-subscription",{endpoint:r.endpoint,keys:r.keys},{auth:true}),"SUCCESS: Unsubscribed from notifications."}async function Rs(){if(typeof window>"u"||window._runningInNodeJS)throw new f("Push Notifications are not supported in Node.js environment.",{code:"NOT_SUPPORTED"});return await this.__connection,{VAPIDPublicKey:await T.bind(this)("get-vapid-public-key",null,{auth:true})}}async function Is(r,e){if(typeof window>"u"||window._runningInNodeJS)throw new f("Push Notifications are not supported in Node.js environment.",{code:"NOT_SUPPORTED"});await this.__connection;let{title:t,body:n}=L(r||{},{nullIfEmpty:true}).data;if(!t)throw new f("Missing parameter: message title",{code:"INVALID_PARAMETER"});if(!n)throw new f("Missing parameter: message body",{code:"INVALID_PARAMETER"});let i={title:t,body:n};return e?(typeof e=="string"&&(e=[e]),i.user_ids=e):i.user_ids="all_users",await T.bind(this)("push-notification",i,{auth:true}),"SUCCESS: Notification sent."}async function Ps(r){await this.__connection,r=m.Params(r,{spell:"string",name:"string",magic:t=>t},["spell","name"]);await T.bind(this)("castspell",r);return `The spell "${r.spell}" has been cast.`}async function xs(r){return await this.__connection,r=m.Params(r||{},{search:["spell","name",()=>"spell"],value:"string"}),await T.bind(this)("getspell",r)}async function Us(r){await this.__connection,r=m.Params(r,{message:"string",name:"string"},["message","name"]);let e=await T.bind(this)("dopamine",r,{auth:true}),t=e?.previous_message?.message,n=e?.previous_message?.name;if(te())t&&n&&window.alert(`${n} said: ${t}`),window.location.href=e.video;else return t&&n?`${n} said: ${t}
217
217
  Watch the video here: ${e.video}`:`Your message has been uploaded for future generations to receive.
218
- Watch the video here: ${e.video}`}var A=class{constructor(e,t,n,i){this.__version="1.5.0-beta.3";this.session=null;this.connection=null;this.__my_unique_ids={};this.userPool=null;this.__socket=null;this.__mediaStream=null;this.host="skapi";this.hostDomain="skapi.com";this.target_cdn="d3e9syvbtso631";this.customApiDomain="skapi.dev";this.requestBatchSize=30;this.__disabledAccount=null;this.__cached_requests={};this.__startKeyHistory={};this.__request_signup_confirmation=null;this.__private_access_key={};this.__class_properties_has_been_cached=false;this.__user=null;this._userProfileListeners=[];this._onLoginListeners=[];this._onBatchProcessListeners=[];this.validate={userId(e){try{return m.UserId(e),!0}catch{return false}},url(e){try{return m.Url(e),!0}catch{return false}},phoneNumber(e){try{return m.PhoneNumber(e),!0}catch{return false}},birthdate(e){try{return m.Birthdate(e),!0}catch{return false}},email(e){try{return m.Email(e),!0}catch{return false}},params(e,t,n){return m.Params(e,t,n)}};this.util={MD5:Q,generateRandom:Je,toBase62:Qn,fromBase62:ne,decodeServiceId:Sr,formatServiceId:zn,extractFormData:L,terminatePendingRequests:Ei,request:(e,t,n)=>T.bind(this)(e,t,n,{ignoreService:true})};this.__network_logs=false;this.__endpoint_version="v1";this.__public_identifier="";this.bearerToken="";this.registerTicket=ti.bind(this);this.unregisterTicket=ri.bind(this);if(!e||typeof e!="string")throw this._alert("Service ID is required."),new f("Service ID is required.",{code:"INVALID_PARAMETER"});if(e.startsWith("s1_")||e.split("-").length===7)try{let l=Sr(e);n&&typeof n=="object"&&(i=n),t&&typeof t=="object"&&(n=t),t=l.owner,e=l.service;}catch{throw this._alert("Service ID is invalid."),new f("Service ID is invalid.",{code:"INVALID_PARAMETER"})}if(!t||typeof t!="string")throw this._alert("Owner ID is invalid."),new f("Owner ID is invalid.",{code:"INVALID_PARAMETER"});if(e.toLowerCase()==="service_id")throw this._alert('Replace "service_id" with your actual Service ID.'),new f("Service ID is required.",{code:"INVALID_PARAMETER"});if(t!==this.host)try{m.UserId(t,'"owner"');}catch{throw this._alert("Owner ID is invalid."),new f("Owner ID is invalid.",{code:"INVALID_PARAMETER"})}this.service=e,this.owner=t;let s=true;if(n&&(typeof n.autoLogin=="boolean"&&(s=n.autoLogin),typeof n.requestBatchSize=="number")){if(n.requestBatchSize<1)throw new f('"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 o=`https://${this.target_cdn}.cloudfront.net`,a=e.substring(0,4);this.admin_endpoint=fetch(`${o}/${a}/admin-${this.__endpoint_version}.json`).then(l=>l.blob()).then(l=>new Promise((h,p)=>{let g=new FileReader;g.onloadend=()=>h(g.result),g.onerror=p,g.readAsDataURL(l);})).then(l=>{try{return typeof l=="string"?JSON.parse(atob(l.split(",")[1])):null}catch{throw new f("Service does not exist. Create your service from skapi.com",{code:"NOT_EXISTS"})}}),this.record_endpoint=fetch(`${o}/${a}/record-${this.__endpoint_version}.json`).then(l=>l.blob()).then(l=>new Promise((h,p)=>{let g=new FileReader;g.onloadend=()=>h(g.result),g.onerror=p,g.readAsDataURL(l);})).then(l=>{try{return typeof l=="string"?JSON.parse(atob(l.split(",")[1])):null}catch{throw new f("Service does not exist. Create your service from skapi.com",{code:"NOT_EXISTS"})}});let u=te();if(u&&!window.sessionStorage)throw this._alert("This browser is not supported."),new Error("This browser is not supported.");let c=u?JSON.parse(window.sessionStorage.getItem(`${e}#${t}`)||"null"):null;if(this.log("constructor:restore",c),c?.connection){for(let l in c)this[l]=c[l];c.__public_identifier||(this.__public_identifier=`${this.service}:${this.owner}:${Je(16)}`);}this.__authConnection=(async()=>{let l=await this.admin_endpoint,h={UserPoolId:l.userpool_id,ClientId:l.userpool_client};wr()&&(h.Storage=window.localStorage),this.userPool=new _r(h);try{this.user||await W.bind(this)().getSession({skipUserUpdateEventTrigger:!0}),this.user&&(!c?.connection&&!s?_e.bind(this)():(this._runOnLoginListeners(this.user),this._runOnUserUpdateListeners(this.user)));}catch{}})();let d=u?window.sessionStorage.getItem(`${this.service}:uniqueids`):null;if(d)try{this.__my_unique_ids=JSON.parse(d);}catch{this.__my_unique_ids={};}this.__connection=(async()=>{let l=null;await this.record_endpoint,c?.connection||(l=this._updateConnection());let h=()=>{if(this.__class_properties_has_been_cached)return;let p=()=>{let g={},_=["__startKeyHistory","__disabledAccount","__cached_requests","__request_signup_confirmation","__public_identifier","connection"];if(this.connection){for(let w of _)g[w]=this[w];u&&window.sessionStorage.setItem(`${e}#${t}`,JSON.stringify(g)),this.__class_properties_has_been_cached=true;}};return l instanceof Promise?l.then(()=>p()):p()};return u&&(window.addEventListener("beforeunload",()=>{this.closeRealtime(),h();}),window.addEventListener("visibilitychange",()=>{h();})),await l,await this.__authConnection,this.connection})(),this.__connection.then(l=>{((l?.group||0)<3||this.__network_logs)&&this.version();});}get user(){return this.__user&&Object.keys(this.__user).length?JSON.parse(JSON.stringify(this.__user)):null}set user(e){}get onLogin(){return this._onLoginListeners}set onLogin(e){typeof e=="function"&&this._onLoginListeners.push(e);}get onUserUpdate(){return this._userProfileListeners}set onUserUpdate(e){typeof e=="function"&&this._userProfileListeners.push(e);}_runOnUserUpdateListeners(e){for(let t of this._userProfileListeners)typeof t=="function"&&t(e);}_runOnLoginListeners(e){for(let t of this._onLoginListeners)typeof t=="function"&&t(e);}get onBatchProcess(){return this._onBatchProcessListeners}set onBatchProcess(e){typeof e=="function"&&this._onBatchProcessListeners.push(e);}_alert(e){te()&&typeof window.alert=="function"&&window.alert(e);}async getConnectionInfo(){let e=await this.__connection,t=e?.user_agent||(te()&&typeof window.navigator?.userAgent=="string"?window.navigator.userAgent:`skapi-node/${globalThis?.process?.versions?.node||"unknown"}`);return {user_ip:e.ip,user_agent:t,user_location:e.locale,service_name:e.service_name,version:this.__version}}async _updateConnection(){try{this.connection=await T.bind(this)("service",{service:this.service,owner:this.owner},{bypassAwaitConnection:!0,method:"get"});}catch(e){throw this.log("connection fail",e),this._alert("Service is not available: "+(e.message||e.toString())),this.connection=null,e}return this.connection}async version(){if(await this.__connection,te()){let t=`Built with:
218
+ Watch the video here: ${e.video}`}var A=class{constructor(e,t,n,i){this.__version="1.5.0-beta.5";this.session=null;this.connection=null;this.__my_unique_ids={};this.userPool=null;this.__socket=null;this.__mediaStream=null;this.host="skapi";this.hostDomain="skapi.com";this.target_cdn="d3e9syvbtso631";this.customApiDomain="skapi.dev";this.requestBatchSize=30;this.__disabledAccount=null;this.__cached_requests={};this.__startKeyHistory={};this.__request_signup_confirmation=null;this.__private_access_key={};this.__class_properties_has_been_cached=false;this.__user=null;this._userProfileListeners=[];this._onLoginListeners=[];this._onBatchProcessListeners=[];this.validate={userId(e){try{return m.UserId(e),!0}catch{return false}},url(e){try{return m.Url(e),!0}catch{return false}},phoneNumber(e){try{return m.PhoneNumber(e),!0}catch{return false}},birthdate(e){try{return m.Birthdate(e),!0}catch{return false}},email(e){try{return m.Email(e),!0}catch{return false}},params(e,t,n){return m.Params(e,t,n)}};this.util={MD5:Q,generateRandom:Je,toBase62:Qn,fromBase62:ne,decodeServiceId:Sr,formatServiceId:zn,extractFormData:L,terminatePendingRequests:Ei,request:(e,t,n)=>T.bind(this)(e,t,n,{ignoreService:true})};this.__network_logs=false;this.__endpoint_version="v1";this.__public_identifier="";this.bearerToken="";this.registerTicket=ti.bind(this);this.unregisterTicket=ri.bind(this);if(!e||typeof e!="string")throw this._alert("Service ID is required."),new f("Service ID is required.",{code:"INVALID_PARAMETER"});if(e.startsWith("s1_")||e.split("-").length===7)try{let l=Sr(e);n&&typeof n=="object"&&(i=n),t&&typeof t=="object"&&(n=t),t=l.owner,e=l.service;}catch{throw this._alert("Service ID is invalid."),new f("Service ID is invalid.",{code:"INVALID_PARAMETER"})}if(!t||typeof t!="string")throw this._alert("Owner ID is invalid."),new f("Owner ID is invalid.",{code:"INVALID_PARAMETER"});if(e.toLowerCase()==="service_id")throw this._alert('Replace "service_id" with your actual Service ID.'),new f("Service ID is required.",{code:"INVALID_PARAMETER"});if(t!==this.host)try{m.UserId(t,'"owner"');}catch{throw this._alert("Owner ID is invalid."),new f("Owner ID is invalid.",{code:"INVALID_PARAMETER"})}this.service=e,this.owner=t;let s=true;if(n&&(typeof n.autoLogin=="boolean"&&(s=n.autoLogin),typeof n.requestBatchSize=="number")){if(n.requestBatchSize<1)throw new f('"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 o=`https://${this.target_cdn}.cloudfront.net`,a=e.substring(0,4);this.admin_endpoint=fetch(`${o}/${a}/admin-${this.__endpoint_version}.json`).then(l=>l.blob()).then(l=>new Promise((h,p)=>{let g=new FileReader;g.onloadend=()=>h(g.result),g.onerror=p,g.readAsDataURL(l);})).then(l=>{try{return typeof l=="string"?JSON.parse(atob(l.split(",")[1])):null}catch{throw new f("Service does not exist. Create your service from skapi.com",{code:"NOT_EXISTS"})}}),this.record_endpoint=fetch(`${o}/${a}/record-${this.__endpoint_version}.json`).then(l=>l.blob()).then(l=>new Promise((h,p)=>{let g=new FileReader;g.onloadend=()=>h(g.result),g.onerror=p,g.readAsDataURL(l);})).then(l=>{try{return typeof l=="string"?JSON.parse(atob(l.split(",")[1])):null}catch{throw new f("Service does not exist. Create your service from skapi.com",{code:"NOT_EXISTS"})}});let u=te();if(u&&!window.sessionStorage)throw this._alert("This browser is not supported."),new Error("This browser is not supported.");let c=u?JSON.parse(window.sessionStorage.getItem(`${e}#${t}`)||"null"):null;if(this.log("constructor:restore",c),c?.connection){for(let l in c)this[l]=c[l];c.__public_identifier||(this.__public_identifier=`${this.service}:${this.owner}:${Je(16)}`);}this.__authConnection=(async()=>{let l=await this.admin_endpoint,h={UserPoolId:l.userpool_id,ClientId:l.userpool_client};wr()&&(h.Storage=window.localStorage),this.userPool=new _r(h);try{this.user||await W.bind(this)().getSession({skipUserUpdateEventTrigger:!0}),this.user&&(!c?.connection&&!s?_e.bind(this)():(this._runOnLoginListeners(this.user),this._runOnUserUpdateListeners(this.user)));}catch{}})();let d=u?window.sessionStorage.getItem(`${this.service}:uniqueids`):null;if(d)try{this.__my_unique_ids=JSON.parse(d);}catch{this.__my_unique_ids={};}this.__connection=(async()=>{let l=null;await this.record_endpoint,c?.connection||(l=this._updateConnection());let h=()=>{if(this.__class_properties_has_been_cached)return;let p=()=>{let g={},_=["__startKeyHistory","__disabledAccount","__cached_requests","__request_signup_confirmation","__public_identifier","connection"];if(this.connection){for(let w of _)g[w]=this[w];u&&window.sessionStorage.setItem(`${e}#${t}`,JSON.stringify(g)),this.__class_properties_has_been_cached=true;}};return l instanceof Promise?l.then(()=>p()):p()};return u&&(window.addEventListener("beforeunload",()=>{this.closeRealtime(),h();}),window.addEventListener("visibilitychange",()=>{h();})),await l,await this.__authConnection,this.connection})(),this.__connection.then(l=>{((l?.group||0)<3||this.__network_logs)&&this.version();});}get user(){return this.__user&&Object.keys(this.__user).length?JSON.parse(JSON.stringify(this.__user)):null}set user(e){}get onLogin(){return this._onLoginListeners}set onLogin(e){typeof e=="function"&&this._onLoginListeners.push(e);}get onUserUpdate(){return this._userProfileListeners}set onUserUpdate(e){typeof e=="function"&&this._userProfileListeners.push(e);}_runOnUserUpdateListeners(e){for(let t of this._userProfileListeners)typeof t=="function"&&t(e);}_runOnLoginListeners(e){for(let t of this._onLoginListeners)typeof t=="function"&&t(e);}get onBatchProcess(){return this._onBatchProcessListeners}set onBatchProcess(e){typeof e=="function"&&this._onBatchProcessListeners.push(e);}_alert(e){te()&&typeof window.alert=="function"&&window.alert(e);}async getConnectionInfo(){let e=await this.__connection,t=e?.user_agent||(te()&&typeof window.navigator?.userAgent=="string"?window.navigator.userAgent:`skapi-node/${globalThis?.process?.versions?.node||"unknown"}`);return {user_ip:e.ip,user_agent:t,user_location:e.locale,service_name:e.service_name,version:this.__version}}async _updateConnection(){try{this.connection=await T.bind(this)("service",{service:this.service,owner:this.owner},{bypassAwaitConnection:!0,method:"get"});}catch(e){throw this.log("connection fail",e),this._alert("Service is not available: "+(e.message||e.toString())),this.connection=null,e}return this.connection}async version(){if(await this.__connection,te()){let t=`Built with:
219
219
  %c\r
220
220
  $$\\ $$\\ \r
221
221
  $$ | \\__|\r
package/dist/skapi.mjs CHANGED
@@ -214,7 +214,7 @@ var Mn=Object.defineProperty;var Vn=Object.getOwnPropertyDescriptor;var te=(n=>t
214
214
  runInterval(); // Start interval
215
215
  `,o=new Blob([s],{type:"application/javascript"});Z=new Worker(URL.createObjectURL(o)),Z.onmessage=c=>{r.readyState===1&&r.send(JSON.stringify({action:"keepAlive"}));},i(r);},r.onmessage=async s=>{let o="";try{o=JSON.parse(decodeURI(s.data)),this.log("socket onmessage",o);}catch{return}let c;switch(true){case !!o?.["#message"]:c="message";break;case !!o?.["#private"]:c="private";break;case !!o?.["#notice"]:c="notice";break;case !!o?.["#rtc"]:c="rtc";break;case !!o?.["#error"]:c="error";break}if(!c)return;let u={type:c,message:o?.["#rtc"]||o?.["#message"]||o?.["#private"]||o?.["#notice"]||o?.["#error"]||null,sender:o?.["#user_id"]||null,sender_cid:o?.["#scid"]?"cid:"+o["#scid"]:null,sender_rid:o?.["#srid"]||null,code:o?.["#code"]||null};if(c==="notice")n(u);else if(c==="rtc"){if(u.sender!==this.user.user_id){let d=u.message;if(d.hungup){K[u.sender_cid]&&(K[u.sender_cid](false),delete K[u.sender_cid]),H[u.sender_cid]&&delete H[u.sender_cid],I?.[u.sender_cid]&&Q.bind(this)({cid:u.sender_cid}),u.type="rtc:closed",n(u);return}if(d.candidate&&je.bind(this)(d.candidate,u.sender_cid),d.sdpoffer&&(qe.bind(this)(d.sdpoffer,u.sender_cid),H[u.sender_cid]||(H[u.sender_cid]=u.sender_cid,delete u.message,u.connectRTC=en.bind(this)(u),u.type="rtc:incoming",u.hangup=(()=>{I[u.sender_cid]?Q.bind(this)({cid:u.sender_cid}):H[u.sender_cid]&&(delete H[u.sender_cid],r.send(JSON.stringify({action:"rtc",uid:u.sender_cid,content:{hungup:this.user.user_id},token:this.session.accessToken.jwtToken})));}).bind(this),n(u))),d.pickup&&K[u.sender_cid]&&(K[u.sender_cid](true),delete K[u.sender_cid]),d.sdpanswer&&I[u.sender_cid])if(I[u.sender_cid].signalingState==="have-local-offer")await I[u.sender_cid].setRemoteDescription(new RTCSessionDescription(d.sdpanswer));else throw new a("Invalid signaling state.",{code:"INVALID_REQUEST"})}}else n(u);},r.onclose=()=>{fe?(this.log("realtime onclose","WebSocket connection closed."),n({type:"close",message:"WebSocket connection closed."})):(this.log("realtime onclose","WebSocket unexpected close."),n({type:"error",message:"Skapi: WebSocket unexpected close."}),oe++,oe<3?(this.log("realtime onclose","Reconnecting to WebSocket server..."+oe),n({type:"reconnect",message:"Reconnecting to WebSocket server..."+oe}),xe.bind(this)(n,3e3,"reconnect")):(this.log("realtime onclose","Max reconnection attempts reached."),n({type:"error",message:"Skapi: Max reconnection attempts reached."})));},r.onerror=()=>{this.log("realtime onerror","WebSocket connection error."),n({type:"error",message:"Skapi: WebSocket connection error."});};},e);});}async function sn(n,e,t){if(typeof window>"u"||window._runningInNodeJS)throw new a("WebSocket is not supported in Node.js environment.",{code:"NOT_SUPPORTED"});let i=this.__socket?await this.__socket:this.__socket;if(!i)throw new a("No realtime connection. Execute connectRealtime() before this method.",{code:"INVALID_REQUEST"});if(!e)throw new a("No recipient.",{code:"INVALID_REQUEST"});await ie.bind(this)(),n=D(n).data;let r="";if(t&&(t=g.Params(t,{config:{always:"boolean"},title:"string",body:"string"},["title","body"]),r=JSON.stringify({title:t.title,body:t.body}),new Blob([r]).size>3072))throw new a("Notification size exceeds 3kb.",{code:"INVALID_PARAMETER"});if(i.readyState===1){try{g.UserId(e),i.send(JSON.stringify({action:"sendMessage",uid:e,content:n,notification:r,notificationConfig:t?.config||{},token:`IdT:${this.service}:${this.owner}:`+(this.bearerToken||this.session?.idToken?.jwtToken||"null")}));}catch(s){if(this.log("postRealtime:err",{err:s}),Y!==e)throw new a(`User has not joined to the recipient group. Run joinRealtime({ group: "${e}" })`,{code:"INVALID_REQUEST"});i.send(JSON.stringify({action:"broadcast",rid:e,content:n,notification:r,notificationConfig:t?.config||{},token:`IdT:${this.service}:${this.owner}:`+(this.bearerToken||this.session?.idToken?.jwtToken||"null")}));}return {type:"success",message:"Message sent."}}throw new a("Realtime connection is not open. Try reconnecting with connectRealtime().",{code:"INVALID_REQUEST"})}async function Ke(n){if(typeof window>"u"||window._runningInNodeJS)throw new a("WebSocket is not supported in Node.js environment.",{code:"NOT_SUPPORTED"});let e=this.__socket?await this.__socket:this.__socket;if(!e)throw new a("No realtime connection. Execute connectRealtime() before this method.",{code:"INVALID_REQUEST"});await ie.bind(this)(),n=D(n,{nullIfEmpty:true}).data;let{group:t=null}=n;if(!t&&!Y)return {type:"success",message:"Left realtime message group."};if(t!==null&&typeof t!="string")throw new a('"group" must be a string | null.',{code:"INVALID_PARAMETER"});return e.send(JSON.stringify({action:"joinRoom",rid:t,token:this.session.accessToken.jwtToken})),Y=t,{type:"success",message:t?`Joined realtime message group: "${t}".`:"Left realtime message group."}}async function on(n,e){n=g.Params(n,{user_id:i=>g.UserId(i,'User ID in "user_id"'),group:["string",()=>{if(!Y)throw new a('No group has been joined. Otherwise "group" is required.',{code:"INVALID_REQUEST"});return Y}]});let t=await w.bind(this)("get-ws-group",n,{fetchOptions:e,auth:true,method:"post"});return t.list=t.list.map(i=>({user_id:i.uid.split("#")[1],cid:"cid:"+i.cid})),t}async function an(n,e){if(await this.__connection,n||(n={searchFor:"group",value:" ",condition:">"}),n=g.Params(n,{searchFor:["group","number_of_users",()=>"group"],value:["string","number",()=>n?.searchFor&&n?.searchFor==="number_of_users"?0:" "],condition:[">",">=","=","<","<=","!=","gt","gte","eq","lt","lte","ne"],range:["string","number"]}),n.condition||(n.value===" "||!n.value?n.condition=">":n.condition="="),n.range&&n.condition&&delete n.condition,n.searchFor==="number_of_users"&&typeof n.value!="number")throw new a('"value" must be a number.',{code:"INVALID_PARAMETER"});if(n.searchFor==="group"&&typeof n.value!="string")throw new a('"value" must be a string.',{code:"INVALID_PARAMETER"});if(n.hasOwnProperty("range")&&typeof n.range!=typeof n.value)throw new a(`"range" must be a ${typeof n.value}.`,{code:"INVALID_PARAMETER"});let t=await w.bind(this)("get-ws-group",n,{fetchOptions:e,auth:true,method:"post"});return t.list=t.list.map(i=>({group:i.rid.split("#")[1],number_of_users:i.cnt})),t}var Tr=typeof FormData<"u",kr=typeof HTMLFormElement<"u",xr=typeof SubmitEvent<"u";async function cn(n){let e=false,t=r=>{for(let s in r)if(typeof r[s]=="string"&&r[s].includes("$CLIENT_SECRET")){e=true;break}};if(n=g.Params(n,{url:r=>{if(!r||typeof r!="string")throw new a('"url" should be type: <string>.',{code:"INVALID_PARAMETER"});return g.Url(r),r.includes("$CLIENT_SECRET")&&(e=true),r},clientSecretName:"string",method:r=>{if(r&&typeof r!="string")throw new a('"method" should be either "GET" or "POST" or "DELETE" or "PUT".',{code:"INVALID_PARAMETER"});let s=r.toLowerCase();if(s!=="get"&&s!=="post"&&s!=="delete"&&s!=="put")throw new a('"method" should be either "GET" or "POST" or "DELETE" or "PUT".',{code:"INVALID_PARAMETER"});return s},headers:r=>{if(r&&typeof r!="object")throw new a('"headers" should be type: <object>.',{code:"INVALID_PARAMETER"});return t(r),r},data:r=>{if(r&&typeof r!="object")throw new a('"data" should be type: <object>.',{code:"INVALID_PARAMETER"});return t(r),r},params:r=>{if(r&&typeof r!="object")throw new a('"params" should be type: <object>.',{code:"INVALID_PARAMETER"});return t(r),r}},["clientSecretName","method","url"]),!e)throw new a(`At least one parameter value should include "$CLIENT_SECRET" in ${n.method.toLowerCase()==="post"?'"data"':'"params"'} or "headers".`,{code:"INVALID_PARAMETER"});await this.__connection;let i=!!this.__user;return w.bind(this)("csr",n,{auth:i})}async function ln(n){await this.__connection;let e={name:"string",email:t=>(g.Email(t),t),subject:"string",message:"string"};return n=g.Params(n,e,["name","email","subject","message"]),await w.bind(this)("send-inquiry",n),"SUCCESS: Inquiry has been sent."}async function un(n,e){if(await this.__connection,Tr&&n instanceof FormData||kr&&n instanceof HTMLFormElement||xr&&n instanceof SubmitEvent){if(!e)throw new a("Url string as a second argument is required when form is passed.",{code:"INVALID_PARAMETER"});let i=D(n);n={url:e,data:i.data,sync:true};}let t={url:i=>g.Url(i),data:i=>i,sync:["boolean",()=>true]};if(Array.isArray(n))for(let i of n)i=g.Params(i,t);else n=g.Params(n,t);return w.bind(this)("post-secure",n,{auth:true})}async function dn(n,e){await this.__connection;let{auth:t=false,method:i="POST",bypassAwaitConnection:r=false,responseType:s,contentType:o,progress:c}=e||{};if(e=Object.assign({auth:t,method:i,bypassAwaitConnection:r,responseType:s,contentType:o},{fetchOptions:{progress:c}}),typeof n!="object"&&(o==="application/json"||o===void 0))throw new a('"data" should be type: <object>.',{code:"INVALID_PARAMETER"});return w.bind(this)("mock",n,e)}async function gn(n,e){await this.__connection,n=g.Params(n||{},{access_group:i=>{if(i==="authorized"&&(i=1),i==="public"&&(i=0),typeof i!="number")throw new a('"access_group" should be type number.',{code:"INVALID_PARAMETER"});if(i<0)throw new a('"access_group" should be zero or a positive number.',{code:"INVALID_PARAMETER"});if(i>this.__user.access_group)throw new a("User has no access.",{code:"INVALID_REQUEST"});return i}});let t=await w.bind(this)("get-feed",n,{auth:true,fetchOptions:e});for(let i in t.list)t.list[i]=await se.bind(this)(t.list[i]);return t}function he(n){if(n===this.__user.user_id)throw new a(`"user_id" cannot be the user's own ID.`,{code:"INVALID_PARAMETER"});return g.UserId(n,'"user_id"')}async function fn(n,e){if(n=D(n,{ignoreEmpty:true}).data,n=g.Params(n,{subscriber:i=>g.UserId(i,'User ID in "subscriber"'),subscription:he.bind(this),blocked:"boolean"}),!n.subscriber&&!n.subscription)throw new a('At least either "subscriber" or "subscription" should have a value.',{code:"INVALID_PARAMETER"});let t=await w.bind(this)("get-subscription",n,Object.assign({auth:true},{fetchOptions:e}));return t.list=t.list.map((i=>{let r={};if(i.sub){let s=i.sub.split("#");r.subscriber=s[2],r.subscription=s[0];}else r.subscriber=i.subscriber,r.subscription=i.subscription;return r.timestamp=i?.timestamp||i.stmp,r.blocked=i?.blocked||i.grp.substring(0,1)==="N",Object.assign(r,i.opt),r})),t}async function hn(n){await this.__connection,n=g.Params(n,{user_id:he.bind(this),get_feed:["boolean",()=>false],get_notified:["boolean",()=>false],get_email:i=>{if(i&&!this.__user.email||!this.__user.email_verified)throw new a("User has no verified email address.",{code:"INVALID_REQUEST"});return !!i}},["user_id"]);let e=await w.bind(this)("subscription",{subscribe:n.user_id,option:{get_feed:n.get_feed,get_notified:n.get_notified,get_email:n.get_email||false}},{auth:true}),t={};if(e.sub){let i=e.sub.split("#");t.subscriber=i[2],t.subscription=i[0];}else t.subscriber=e.subscriber,t.subscription=e.subscription;return t.timestamp=e?.timestamp||e.stmp,t.blocked=e?.blocked||e.grp.substring(0,1)==="N",Object.assign(t,e.opt),t}async function pn(n){await this.__connection;let{user_id:e}=g.Params(n,{user_id:he.bind(this)},["user_id"]);return await w.bind(this)("subscription",{unsubscribe:e},{auth:true})}async function mn(n){await this.__connection;let{user_id:e}=g.Params(n,{user_id:he.bind(this)},["user_id"]);return await w.bind(this)("subscription",{block:e},{auth:true})}async function bn(n){await this.__connection;let{user_id:e}=g.Params(n,{user_id:he.bind(this)},["user_id"]);return await w.bind(this)("subscription",{unblock:e},{auth:true})}async function _n(n,e){await this.__connection;let t=await M.bind(this)();n=g.Params(n,{user_id:o=>{if(o!==this.__user.user_id&&!t)throw new a("No access.",{code:"INVALID_REQUEST"});return o},group:o=>{if(o==="public"&&(o=0),o==="authorized"&&(o=1),typeof o!="number")throw new a('"group" should be type number | "public" | "authorized".',{code:"INVALID_PARAMETER"});return o}});let i=await w.bind(this)("get-newsletter-subscription",n,{auth:true,fetchOptions:e||null}),r=i?.list||i,s=[];Array.isArray(r)||(r=[]);for(let o of r){let c=o.subt.split("#"),u=true;c[0].charAt(0)==="@"&&(u=false,c[0]=c[0].substring(1));let d=parseInt(c[0]);s.push({timestamp:o.stmp,group:d,subscribed_email:c[1],active:u});}return i?.list?(i.list=s,i):s}async function yn(n){await this.__connection;let e=g.Params(n||{},{email:t=>Array.isArray(t)&&t.length>0?t.length===1?g.Email(t[0]):t.map(i=>g.Email(i)):g.Email(t),group:["number","public","authorized","admin",t=>{if(typeof t!="string"||t.length>20||!/^[a-zA-Z0-9]+$/.test(t))throw new a('"group" should be an alphanumeric string without spaces and less than 20 characters.',{code:"INVALID_PARAMETER"});return t}],redirect:t=>g.Url(t)},this.__user?["group"]:["email","group"]);return w.bind(this)(`subscribe-${this.__user?"":"public-"}newsletter`,e,{auth:!!this.__user})}async function wn(n){await this.__connection,n=g.Params(n,{group:["number","public","authorized","admin"]},["group"]);let e=Object.assign({action:"unsubscribe"},n);return w.bind(this)("subscribe-newsletter",e,{auth:true})}async function En(n,e){let t=await M.bind(this)(),i={message_id:"string",timestamp:"number",read:"number",complaint:"number",subject:"string",bounced:"number"};n||(e=Object.assign({ascending:false},e||{})),n=D(n).data,n=n||{searchFor:"timestamp",value:Date.now(),condition:"<",group:"public"},n=g.Params(n,{searchFor:["message_id","timestamp","subject","complaint","read","bounced"],value:u=>{if(typeof u!==i[n.searchFor])throw new a(`"value" type does not match the type of "${n.searchFor}" index.`,{code:"INVALID_PARAMETER"});if(typeof u=="string"&&!u)throw new a('"value" should not be empty string.',{code:"INVALID_PARAMETER"});return u},range:u=>{if(!n.hasOwnProperty("value")||typeof u!=typeof n.value)throw new a('"range" should match type of "value".',{code:"INVALID_PARAMETER"});return u},condition:[">",">=","=","<","<=","gt","gte","eq","lt","lte",()=>"="],group:u=>{if(u==="public")return 0;if(!this.session)throw new a("User should be logged in.",{code:"INVALID_REQUEST"});if(u==="authorized")return 1;if(typeof u=="number"){if(!t&&u>parseInt(this.user?.access_group||this.session?.idToken?.payload?.access_group))throw new a("User has no access.",{code:"INVALID_REQUEST"});return u}throw new a('"group" should be type: number | "public" | "authorized".',{code:"INVALID_PARAMETER"})}},["searchFor","value","group"]);let r=n.group===0?"get-public-newsletters":"get-newsletters",s=await w.bind(this)(r,n,Object.assign({method:"get",auth:r==="get-public-newsletters"?!!this.__user:true},{fetchOptions:e})),o={message_id:"mid",timestamp:"stmp",complaint:"cmpl",read:"read",subject:"subj",bounced:"bnce",url:"url",delivered:"delv"},c={message_id:"",timestamp:0,complaint:0,read:0,subject:"",bounced:"",url:"",delivered:0};return s.list=s.list.map(u=>{let d={};for(let f in o)d[f]=u[o[f]]||c[f];return d.bounced=String(d.bounced),d}),s}async function Rn(n){let e=g.Params(n,{user_id:i=>g.UserId(i,'"user_id"')},["user_id"]);if(e?.service&&e?.owner?e={service:e?.service,owner:e?.owner,block:e.user_id}:e={block:e.user_id},!await M.bind(this)()){if(!this.__user)throw new a("User needs to login.",{code:"INVALID_REQUEST"});if(this.__user.access_group<90)throw new a("Invalid access.",{code:"INVALID_REQUEST"})}return await w.bind(this)("block-account",e,{auth:true})}async function An(n){let e=g.Params(n,{user_id:i=>g.UserId(i,'"user_id"')},["user_id"]);if(e?.service&&e?.owner?e={service:e?.service,owner:e?.owner,unblock:e.user_id}:e={unblock:e.user_id},!await M.bind(this)()){if(!this.__user)throw new a("User needs to login.",{code:"INVALID_REQUEST"});if(this.__user.access_group<90)throw new a("Invalid access.",{code:"INVALID_REQUEST"})}return await w.bind(this)("block-account",e,{auth:true})}async function In(n){let e=g.Params(n,{user_id:i=>g.UserId(i,'"user_id"')},["user_id"]);if(e?.service&&e?.owner?e={service:e?.service,owner:e?.owner,delete:e.user_id}:e={delete:e.user_id},!await M.bind(this)()){if(!this.__user)throw new a("User needs to login.",{code:"INVALID_REQUEST"});if(this.__user.access_group<90)throw new a("Invalid access.",{code:"INVALID_REQUEST"})}return await w.bind(this)("remove-account",e,{auth:true})}async function Sn(n,e){let t={email:s=>g.Email(s),password:s=>g.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=>g.Birthdate(s),phone_number:s=>g.PhoneNumber(s),picture:s=>{if(s)return g.Url(s)},profile:s=>{if(s)return g.Url(s)},website:s=>{if(s)return g.Url(s)},nickname:"string",misc:"string",email_public:["boolean",()=>false],gender_public:["boolean",()=>false],address_public:["boolean",()=>false],birthdate_public:["boolean",()=>false],phone_number_public:["boolean",()=>false],openid_id:"string",access_group:s=>{try{typeof s=="string"&&(s=s==="admin"?99:parseInt(s));}catch{throw new a('"access_group" is invalid. Should be type <number>.',{code:"INVALID_PARAMETER"})}if(typeof s!="number"||s<1||s>100)throw new a('"access_group" is invalid. Should be type <number> of range 1~99',{code:"INVALID_PARAMETER"});return s}},i=g.Params(n,t,["email"]);if(e=g.Params(e,{confirmation_url:s=>{let o=s;if(typeof s=="string")o=g.Url(s);else throw new a('"options.confirmation_url" should be type: <string>.',{code:"INVALID_PARAMETER"});if(o&&!i.email)throw new a('"email" is required for signup confirmation.',{code:"INVALID_PARAMETER"});return o},email_subscription:s=>{if(typeof s!="boolean")throw new a('"options.email_subscription" should be type: <boolean>.',{code:"INVALID_PARAMETER"});if(!e?.confirmation_url)throw new a('"options.confirmation_url" is required for email subscription.',{code:"INVALID_PARAMETER"});return s},template:s=>{if(typeof s!="object"||!s.url||!s.subject)throw new a('"options.template" should be type: <object> with "url" and "subject".',{code:"INVALID_PARAMETER"});return {url:g.Url(s.url),subject:s.subject}}}),i.signup_confirmation=e?.confirmation_url||true,i.email_subscription=e?.email_subscription||false,i.template=e?.template||{},!await M.bind(this)()){if(!this.__user)throw new a("User needs to login.",{code:"INVALID_REQUEST"});if(this.__user.access_group<90)throw new a("Invalid access.",{code:"INVALID_REQUEST"})}return await w.bind(this)("admin-signup",i,{auth:true})}async function Pn(n){let e={email:r=>g.Email(r),password:r=>g.Password(r),openid_id:"string",name:"string",username:"string",gender:"string",address:r=>{if(!r)return "";if(typeof r=="string")return r;if(typeof r=="object")return JSON.stringify(r)},birthdate:r=>g.Birthdate(r),phone_number:r=>g.PhoneNumber(r),picture:r=>r?g.Url(r):"",profile:r=>r?g.Url(r):"",website:r=>r?g.Url(r):"",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:r=>{try{typeof r=="string"&&(r=parseInt(r));}catch{throw new a('"access_group" is invalid. Should be type <number>.',{code:"INVALID_PARAMETER"})}if(typeof r!="number"||r<1||r>100)throw new a('"access_group" is invalid. Should be type <number> of range 1~99',{code:"INVALID_PARAMETER"});return r}},t=g.Params(n,e,["email","password"]);if(!await M.bind(this)()){if(!this.__user)throw new a("User needs to login.",{code:"INVALID_REQUEST"});if(this.__user.access_group<90)throw new a("Invalid access.",{code:"INVALID_REQUEST"})}return await w.bind(this)("admin-signup",t,{auth:true})}async function Tn(n){if(n=g.Params(n,{user_id:t=>g.UserId(t,'"user_id"'),access_group:t=>{try{typeof t=="string"&&(t=parseInt(t));}catch{throw new a('"access_group" is invalid. Should be type <number>.',{code:"INVALID_PARAMETER"})}if(typeof t=="number"&&t>0&&t<100)return t;throw new a('"access_group" is invalid. Should be type <number> of range 1~99',{code:"INVALID_PARAMETER"})}},["user_id","access_group"]),!await M.bind(this)()){if(!this.__user)throw new a("User needs to login.",{code:"INVALID_REQUEST"});if(this.__user.access_group<90)throw new a("Invalid access.",{code:"INVALID_REQUEST"})}return await w.bind(this)("grant-access",n,{auth:true})}async function kn(n,e){if(n=g.Params(n,{email:"string"}),!await M.bind(this)()){if(!this.__user)throw new a("User needs to login.",{code:"INVALID_REQUEST"});if(this.__user.access_group<90)throw new a("Invalid access.",{code:"INVALID_REQUEST"})}let i=await w.bind(this)("invitation-list",Object.assign({mode:"search"},n),{fetchOptions:e,auth:true});return i.list=i.list.map(r=>ce(r.user)),i}async function xn(n){if(n=g.Params(n,{email:t=>g.Email(t)},["email"]),!await M.bind(this)()){if(!this.__user)throw new a("User needs to login.",{code:"INVALID_REQUEST"});if(this.__user.access_group<90)throw new a("Invalid access.",{code:"INVALID_REQUEST"})}return await w.bind(this)("invitation-list",Object.assign({mode:"cancel"},n),{auth:true})}async function vn(n){if(n=g.Params(n,{email:t=>g.Email(t)},["email"]),!await M.bind(this)()){if(!this.__user)throw new a("User needs to login.",{code:"INVALID_REQUEST"});if(this.__user.access_group<90)throw new a("Invalid access.",{code:"INVALID_REQUEST"})}return await w.bind(this)("invitation-list",Object.assign({mode:"resend"},n),{auth:true})}async function Dn(n){if(typeof window>"u"||window._runningInNodeJS)throw new a("Push Notifications are not supported in Node.js environment.",{code:"NOT_SUPPORTED"});if(await this.__connection,!n.endpoint)throw new a("Missing parameter: endpoint",{code:"INVALID_PARAMETER"});if(!n.keys||!n.keys.p256dh||!n.keys.auth)throw new a("Missing parameter: keys.p256dh or keys.auth",{code:"INVALID_PARAMETER"});return await w.bind(this)("store-subscription",{endpoint:n.endpoint,keys:n.keys},{auth:true}),"SUCCESS: Subscribed to receive notifications."}async function Nn(n){if(typeof window>"u"||window._runningInNodeJS)throw new a("Push Notifications are not supported in Node.js environment.",{code:"NOT_SUPPORTED"});if(await this.__connection,!n.endpoint)throw new a("Missing parameter: endpoint",{code:"INVALID_PARAMETER"});if(!n.keys||!n.keys.p256dh||!n.keys.auth)throw new a("Missing parameter: keys.p256dh or keys.auth",{code:"INVALID_PARAMETER"});return await w.bind(this)("delete-subscription",{endpoint:n.endpoint,keys:n.keys},{auth:true}),"SUCCESS: Unsubscribed from notifications."}async function Un(){if(typeof window>"u"||window._runningInNodeJS)throw new a("Push Notifications are not supported in Node.js environment.",{code:"NOT_SUPPORTED"});return await this.__connection,{VAPIDPublicKey:await w.bind(this)("get-vapid-public-key",null,{auth:true})}}async function Cn(n,e){if(typeof window>"u"||window._runningInNodeJS)throw new a("Push Notifications are not supported in Node.js environment.",{code:"NOT_SUPPORTED"});await this.__connection;let{title:t,body:i}=D(n||{},{nullIfEmpty:true}).data;if(!t)throw new a("Missing parameter: message title",{code:"INVALID_PARAMETER"});if(!i)throw new a("Missing parameter: message body",{code:"INVALID_PARAMETER"});let r={title:t,body:i};return e?(typeof e=="string"&&(e=[e]),r.user_ids=e):r.user_ids="all_users",await w.bind(this)("push-notification",r,{auth:true}),"SUCCESS: Notification sent."}async function Ln(n){await this.__connection,n=g.Params(n,{spell:"string",name:"string",magic:t=>t},["spell","name"]);await w.bind(this)("castspell",n);return `The spell "${n.spell}" has been cast.`}async function On(n){return await this.__connection,n=g.Params(n||{},{search:["spell","name",()=>"spell"],value:"string"}),await w.bind(this)("getspell",n)}async function Fn(n){await this.__connection,n=g.Params(n,{message:"string",name:"string"},["message","name"]);let e=await w.bind(this)("dopamine",n,{auth:true}),t=e?.previous_message?.message,i=e?.previous_message?.name;if(q())t&&i&&window.alert(`${i} said: ${t}`),window.location.href=e.video;else return t&&i?`${i} said: ${t}
216
216
  Watch the video here: ${e.video}`:`Your message has been uploaded for future generations to receive.
217
- Watch the video here: ${e.video}`}var b=class{constructor(e,t,i,r){this.__version="1.5.0-beta.3";this.session=null;this.connection=null;this.__my_unique_ids={};this.userPool=null;this.__socket=null;this.__mediaStream=null;this.host="skapi";this.hostDomain="skapi.com";this.target_cdn="d3e9syvbtso631";this.customApiDomain="skapi.dev";this.requestBatchSize=30;this.__disabledAccount=null;this.__cached_requests={};this.__startKeyHistory={};this.__request_signup_confirmation=null;this.__private_access_key={};this.__class_properties_has_been_cached=false;this.__user=null;this._userProfileListeners=[];this._onLoginListeners=[];this._onBatchProcessListeners=[];this.validate={userId(e){try{return g.UserId(e),!0}catch{return false}},url(e){try{return g.Url(e),!0}catch{return false}},phoneNumber(e){try{return g.PhoneNumber(e),!0}catch{return false}},birthdate(e){try{return g.Birthdate(e),!0}catch{return false}},email(e){try{return g.Email(e),!0}catch{return false}},params(e,t,i){return g.Params(e,t,i)}};this.util={MD5:V,generateRandom:ae,toBase62:et,fromBase62:B,decodeServiceId:Ne,formatServiceId:tt,extractFormData:D,terminatePendingRequests:xt,request:(e,t,i)=>w.bind(this)(e,t,i,{ignoreService:true})};this.__network_logs=false;this.__endpoint_version="v1";this.__public_identifier="";this.bearerToken="";this.registerTicket=ot.bind(this);this.unregisterTicket=at.bind(this);if(!e||typeof e!="string")throw this._alert("Service ID is required."),new a("Service ID is required.",{code:"INVALID_PARAMETER"});if(e.startsWith("s1_")||e.split("-").length===7)try{let l=Ne(e);i&&typeof i=="object"&&(r=i),t&&typeof t=="object"&&(i=t),t=l.owner,e=l.service;}catch{throw this._alert("Service ID is invalid."),new a("Service ID is invalid.",{code:"INVALID_PARAMETER"})}if(!t||typeof t!="string")throw this._alert("Owner ID is invalid."),new a("Owner ID is invalid.",{code:"INVALID_PARAMETER"});if(e.toLowerCase()==="service_id")throw this._alert('Replace "service_id" with your actual Service ID.'),new a("Service ID is required.",{code:"INVALID_PARAMETER"});if(t!==this.host)try{g.UserId(t,'"owner"');}catch{throw this._alert("Owner ID is invalid."),new a("Owner ID is invalid.",{code:"INVALID_PARAMETER"})}this.service=e,this.owner=t;let s=true;if(i&&(typeof i.autoLogin=="boolean"&&(s=i.autoLogin),typeof i.requestBatchSize=="number")){if(i.requestBatchSize<1)throw new a('"requestBatchSize" must be greater than 0.',{code:"INVALID_PARAMETER"});this.requestBatchSize=i.requestBatchSize;}i?.eventListener&&typeof i.eventListener=="object"&&(i.eventListener?.onLogin&&typeof i.eventListener.onLogin=="function"&&(this.onLogin=i.eventListener.onLogin),i.eventListener?.onUserUpdate&&typeof i.eventListener.onUserUpdate=="function"&&(this.onUserUpdate=i.eventListener.onUserUpdate),i.eventListener?.onBatchProcess&&typeof i.eventListener.onBatchProcess=="function"&&(this.onBatchProcess=i.eventListener.onBatchProcess)),this.target_cdn=r?.target_cdn||this.target_cdn,this.hostDomain=r?.hostDomain||this.hostDomain,this.customApiDomain=r?.customApiDomain||this.customApiDomain,this.__network_logs=!!r?.network_logs;let o=`https://${this.target_cdn}.cloudfront.net`,c=e.substring(0,4);this.admin_endpoint=fetch(`${o}/${c}/admin-${this.__endpoint_version}.json`).then(l=>l.blob()).then(l=>new Promise((h,R)=>{let p=new FileReader;p.onloadend=()=>h(p.result),p.onerror=R,p.readAsDataURL(l);})).then(l=>{try{return typeof l=="string"?JSON.parse(atob(l.split(",")[1])):null}catch{throw new a("Service does not exist. Create your service from skapi.com",{code:"NOT_EXISTS"})}}),this.record_endpoint=fetch(`${o}/${c}/record-${this.__endpoint_version}.json`).then(l=>l.blob()).then(l=>new Promise((h,R)=>{let p=new FileReader;p.onloadend=()=>h(p.result),p.onerror=R,p.readAsDataURL(l);})).then(l=>{try{return typeof l=="string"?JSON.parse(atob(l.split(",")[1])):null}catch{throw new a("Service does not exist. Create your service from skapi.com",{code:"NOT_EXISTS"})}});let u=q();if(u&&!window.sessionStorage)throw this._alert("This browser is not supported."),new Error("This browser is not supported.");let d=u?JSON.parse(window.sessionStorage.getItem(`${e}#${t}`)||"null"):null;if(this.log("constructor:restore",d),d?.connection){for(let l in d)this[l]=d[l];d.__public_identifier||(this.__public_identifier=`${this.service}:${this.owner}:${ae(16)}`);}this.__authConnection=(async()=>{let l=await this.admin_endpoint,h={UserPoolId:l.userpool_id,ClientId:l.userpool_client};De()&&(h.Storage=window.localStorage),this.userPool=new CognitoUserPool(h);try{this.user||await F.bind(this)().getSession({skipUserUpdateEventTrigger:!0}),this.user&&(!d?.connection&&!s?z.bind(this)():(this._runOnLoginListeners(this.user),this._runOnUserUpdateListeners(this.user)));}catch{}})();let f=u?window.sessionStorage.getItem(`${this.service}:uniqueids`):null;if(f)try{this.__my_unique_ids=JSON.parse(f);}catch{this.__my_unique_ids={};}this.__connection=(async()=>{let l=null;await this.record_endpoint,d?.connection||(l=this._updateConnection());let h=()=>{if(this.__class_properties_has_been_cached)return;let R=()=>{let p={},A=["__startKeyHistory","__disabledAccount","__cached_requests","__request_signup_confirmation","__public_identifier","connection"];if(this.connection){for(let S of A)p[S]=this[S];u&&window.sessionStorage.setItem(`${e}#${t}`,JSON.stringify(p)),this.__class_properties_has_been_cached=true;}};return l instanceof Promise?l.then(()=>R()):R()};return u&&(window.addEventListener("beforeunload",()=>{this.closeRealtime(),h();}),window.addEventListener("visibilitychange",()=>{h();})),await l,await this.__authConnection,this.connection})(),this.__connection.then(l=>{((l?.group||0)<3||this.__network_logs)&&this.version();});}get user(){return this.__user&&Object.keys(this.__user).length?JSON.parse(JSON.stringify(this.__user)):null}set user(e){}get onLogin(){return this._onLoginListeners}set onLogin(e){typeof e=="function"&&this._onLoginListeners.push(e);}get onUserUpdate(){return this._userProfileListeners}set onUserUpdate(e){typeof e=="function"&&this._userProfileListeners.push(e);}_runOnUserUpdateListeners(e){for(let t of this._userProfileListeners)typeof t=="function"&&t(e);}_runOnLoginListeners(e){for(let t of this._onLoginListeners)typeof t=="function"&&t(e);}get onBatchProcess(){return this._onBatchProcessListeners}set onBatchProcess(e){typeof e=="function"&&this._onBatchProcessListeners.push(e);}_alert(e){q()&&typeof window.alert=="function"&&window.alert(e);}async getConnectionInfo(){let e=await this.__connection,t=e?.user_agent||(q()&&typeof window.navigator?.userAgent=="string"?window.navigator.userAgent:`skapi-node/${globalThis?.process?.versions?.node||"unknown"}`);return {user_ip:e.ip,user_agent:t,user_location:e.locale,service_name:e.service_name,version:this.__version}}async _updateConnection(){try{this.connection=await w.bind(this)("service",{service:this.service,owner:this.owner},{bypassAwaitConnection:!0,method:"get"});}catch(e){throw this.log("connection fail",e),this._alert("Service is not available: "+(e.message||e.toString())),this.connection=null,e}return this.connection}async version(){if(await this.__connection,q()){let t=`Built with:
217
+ Watch the video here: ${e.video}`}var b=class{constructor(e,t,i,r){this.__version="1.5.0-beta.5";this.session=null;this.connection=null;this.__my_unique_ids={};this.userPool=null;this.__socket=null;this.__mediaStream=null;this.host="skapi";this.hostDomain="skapi.com";this.target_cdn="d3e9syvbtso631";this.customApiDomain="skapi.dev";this.requestBatchSize=30;this.__disabledAccount=null;this.__cached_requests={};this.__startKeyHistory={};this.__request_signup_confirmation=null;this.__private_access_key={};this.__class_properties_has_been_cached=false;this.__user=null;this._userProfileListeners=[];this._onLoginListeners=[];this._onBatchProcessListeners=[];this.validate={userId(e){try{return g.UserId(e),!0}catch{return false}},url(e){try{return g.Url(e),!0}catch{return false}},phoneNumber(e){try{return g.PhoneNumber(e),!0}catch{return false}},birthdate(e){try{return g.Birthdate(e),!0}catch{return false}},email(e){try{return g.Email(e),!0}catch{return false}},params(e,t,i){return g.Params(e,t,i)}};this.util={MD5:V,generateRandom:ae,toBase62:et,fromBase62:B,decodeServiceId:Ne,formatServiceId:tt,extractFormData:D,terminatePendingRequests:xt,request:(e,t,i)=>w.bind(this)(e,t,i,{ignoreService:true})};this.__network_logs=false;this.__endpoint_version="v1";this.__public_identifier="";this.bearerToken="";this.registerTicket=ot.bind(this);this.unregisterTicket=at.bind(this);if(!e||typeof e!="string")throw this._alert("Service ID is required."),new a("Service ID is required.",{code:"INVALID_PARAMETER"});if(e.startsWith("s1_")||e.split("-").length===7)try{let l=Ne(e);i&&typeof i=="object"&&(r=i),t&&typeof t=="object"&&(i=t),t=l.owner,e=l.service;}catch{throw this._alert("Service ID is invalid."),new a("Service ID is invalid.",{code:"INVALID_PARAMETER"})}if(!t||typeof t!="string")throw this._alert("Owner ID is invalid."),new a("Owner ID is invalid.",{code:"INVALID_PARAMETER"});if(e.toLowerCase()==="service_id")throw this._alert('Replace "service_id" with your actual Service ID.'),new a("Service ID is required.",{code:"INVALID_PARAMETER"});if(t!==this.host)try{g.UserId(t,'"owner"');}catch{throw this._alert("Owner ID is invalid."),new a("Owner ID is invalid.",{code:"INVALID_PARAMETER"})}this.service=e,this.owner=t;let s=true;if(i&&(typeof i.autoLogin=="boolean"&&(s=i.autoLogin),typeof i.requestBatchSize=="number")){if(i.requestBatchSize<1)throw new a('"requestBatchSize" must be greater than 0.',{code:"INVALID_PARAMETER"});this.requestBatchSize=i.requestBatchSize;}i?.eventListener&&typeof i.eventListener=="object"&&(i.eventListener?.onLogin&&typeof i.eventListener.onLogin=="function"&&(this.onLogin=i.eventListener.onLogin),i.eventListener?.onUserUpdate&&typeof i.eventListener.onUserUpdate=="function"&&(this.onUserUpdate=i.eventListener.onUserUpdate),i.eventListener?.onBatchProcess&&typeof i.eventListener.onBatchProcess=="function"&&(this.onBatchProcess=i.eventListener.onBatchProcess)),this.target_cdn=r?.target_cdn||this.target_cdn,this.hostDomain=r?.hostDomain||this.hostDomain,this.customApiDomain=r?.customApiDomain||this.customApiDomain,this.__network_logs=!!r?.network_logs;let o=`https://${this.target_cdn}.cloudfront.net`,c=e.substring(0,4);this.admin_endpoint=fetch(`${o}/${c}/admin-${this.__endpoint_version}.json`).then(l=>l.blob()).then(l=>new Promise((h,R)=>{let p=new FileReader;p.onloadend=()=>h(p.result),p.onerror=R,p.readAsDataURL(l);})).then(l=>{try{return typeof l=="string"?JSON.parse(atob(l.split(",")[1])):null}catch{throw new a("Service does not exist. Create your service from skapi.com",{code:"NOT_EXISTS"})}}),this.record_endpoint=fetch(`${o}/${c}/record-${this.__endpoint_version}.json`).then(l=>l.blob()).then(l=>new Promise((h,R)=>{let p=new FileReader;p.onloadend=()=>h(p.result),p.onerror=R,p.readAsDataURL(l);})).then(l=>{try{return typeof l=="string"?JSON.parse(atob(l.split(",")[1])):null}catch{throw new a("Service does not exist. Create your service from skapi.com",{code:"NOT_EXISTS"})}});let u=q();if(u&&!window.sessionStorage)throw this._alert("This browser is not supported."),new Error("This browser is not supported.");let d=u?JSON.parse(window.sessionStorage.getItem(`${e}#${t}`)||"null"):null;if(this.log("constructor:restore",d),d?.connection){for(let l in d)this[l]=d[l];d.__public_identifier||(this.__public_identifier=`${this.service}:${this.owner}:${ae(16)}`);}this.__authConnection=(async()=>{let l=await this.admin_endpoint,h={UserPoolId:l.userpool_id,ClientId:l.userpool_client};De()&&(h.Storage=window.localStorage),this.userPool=new CognitoUserPool(h);try{this.user||await F.bind(this)().getSession({skipUserUpdateEventTrigger:!0}),this.user&&(!d?.connection&&!s?z.bind(this)():(this._runOnLoginListeners(this.user),this._runOnUserUpdateListeners(this.user)));}catch{}})();let f=u?window.sessionStorage.getItem(`${this.service}:uniqueids`):null;if(f)try{this.__my_unique_ids=JSON.parse(f);}catch{this.__my_unique_ids={};}this.__connection=(async()=>{let l=null;await this.record_endpoint,d?.connection||(l=this._updateConnection());let h=()=>{if(this.__class_properties_has_been_cached)return;let R=()=>{let p={},A=["__startKeyHistory","__disabledAccount","__cached_requests","__request_signup_confirmation","__public_identifier","connection"];if(this.connection){for(let S of A)p[S]=this[S];u&&window.sessionStorage.setItem(`${e}#${t}`,JSON.stringify(p)),this.__class_properties_has_been_cached=true;}};return l instanceof Promise?l.then(()=>R()):R()};return u&&(window.addEventListener("beforeunload",()=>{this.closeRealtime(),h();}),window.addEventListener("visibilitychange",()=>{h();})),await l,await this.__authConnection,this.connection})(),this.__connection.then(l=>{((l?.group||0)<3||this.__network_logs)&&this.version();});}get user(){return this.__user&&Object.keys(this.__user).length?JSON.parse(JSON.stringify(this.__user)):null}set user(e){}get onLogin(){return this._onLoginListeners}set onLogin(e){typeof e=="function"&&this._onLoginListeners.push(e);}get onUserUpdate(){return this._userProfileListeners}set onUserUpdate(e){typeof e=="function"&&this._userProfileListeners.push(e);}_runOnUserUpdateListeners(e){for(let t of this._userProfileListeners)typeof t=="function"&&t(e);}_runOnLoginListeners(e){for(let t of this._onLoginListeners)typeof t=="function"&&t(e);}get onBatchProcess(){return this._onBatchProcessListeners}set onBatchProcess(e){typeof e=="function"&&this._onBatchProcessListeners.push(e);}_alert(e){q()&&typeof window.alert=="function"&&window.alert(e);}async getConnectionInfo(){let e=await this.__connection,t=e?.user_agent||(q()&&typeof window.navigator?.userAgent=="string"?window.navigator.userAgent:`skapi-node/${globalThis?.process?.versions?.node||"unknown"}`);return {user_ip:e.ip,user_agent:t,user_location:e.locale,service_name:e.service_name,version:this.__version}}async _updateConnection(){try{this.connection=await w.bind(this)("service",{service:this.service,owner:this.owner},{bypassAwaitConnection:!0,method:"get"});}catch(e){throw this.log("connection fail",e),this._alert("Service is not available: "+(e.message||e.toString())),this.connection=null,e}return this.connection}async version(){if(await this.__connection,q()){let t=`Built with:
218
218
  %c\r
219
219
  $$\\ $$\\ \r
220
220
  $$ | \\__|\r
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "skapi-js",
3
- "version": "1.5.0-beta.3",
3
+ "version": "1.5.0-beta.5",
4
4
  "description": "Serverless Backend API for AI Agents.",
5
5
  "main": "dist/skapi.cjs",
6
6
  "browser": "dist/skapi.mjs",