skapi-js 2.2.6-beta.0 → 2.2.6-beta.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/skapi.browser.mjs +2 -2
- package/dist/skapi.browser.mjs.map +1 -1
- package/dist/skapi.cjs +2 -2
- package/dist/skapi.cjs.map +1 -1
- package/dist/skapi.d.mts +59 -18
- package/dist/skapi.d.ts +59 -18
- package/dist/skapi.js +2 -2
- package/dist/skapi.js.map +1 -1
- package/dist/skapi.mjs +2 -2
- package/dist/skapi.mjs.map +1 -1
- package/package.json +1 -1
package/dist/skapi.cjs
CHANGED
|
@@ -212,7 +212,7 @@ var wo=Object.defineProperty;var Eo=Object.getOwnPropertyDescriptor;var Se=(e=>t
|
|
|
212
212
|
}
|
|
213
213
|
|
|
214
214
|
runInterval(); // Start interval
|
|
215
|
-
`,c=new Blob([d],{type:"application/javascript"});Re=new Worker(URL.createObjectURL(c)),Re.onmessage=g=>{a.readyState===1&&a.send(JSON.stringify({action:"keepAlive"}));},i(a);},a.onmessage=async d=>{let c="";try{c=JSON.parse(decodeURI(d.data)),this.log("socket onmessage",c);}catch{return}let g;switch(!0){case !!c?.["#message"]:g="message";break;case !!c?.["#private"]:g="private";break;case !!c?.["#notice"]:g="notice";break;case !!c?.["#rtc"]:g="rtc";break;case !!c?.["#error"]:g="error";break}if(!g)return;let f={type:g,message:c?.["#rtc"]||c?.["#message"]||c?.["#private"]||c?.["#notice"]||c?.["#error"]||null,sender:c?.["#user_id"]||null,sender_cid:c?.["#scid"]?"cid:"+c["#scid"]:null,sender_rid:c?.["#srid"]||null,code:c?.["#code"]||null};if(g==="notice")e(f);else if(g==="rtc"){if(f.sender!==this.user.user_id){let u=f.message;if(u.hungup){ce[f.sender_cid]&&(ce[f.sender_cid](!1),delete ce[f.sender_cid]),pe[f.sender_cid]&&delete pe[f.sender_cid],D?.[f.sender_cid]&&ue.bind(this)({cid:f.sender_cid}),f.type="rtc:closed",e(f);return}if(u.candidate&&Or.bind(this)(u.candidate,f.sender_cid),u.sdpoffer&&(Cr.bind(this)(u.sdpoffer,f.sender_cid),pe[f.sender_cid]||(pe[f.sender_cid]=f.sender_cid,delete f.message,f.connectRTC=ns.bind(this)(f),f.type="rtc:incoming",f.hangup=(()=>{D[f.sender_cid]?ue.bind(this)({cid:f.sender_cid}):pe[f.sender_cid]&&(delete pe[f.sender_cid],a.send(JSON.stringify({action:"rtc",uid:f.sender_cid,content:{hungup:this.user.user_id},token:this.session.accessToken.jwtToken})));}).bind(this),e(f))),u.pickup&&ce[f.sender_cid]&&(ce[f.sender_cid](!0),delete ce[f.sender_cid]),u.sdpanswer&&D[f.sender_cid])if(D[f.sender_cid].signalingState==="have-local-offer")await D[f.sender_cid].setRemoteDescription(new RTCSessionDescription(u.sdpanswer));else throw new l("Invalid signaling state.",{code:"INVALID_REQUEST"})}}else e(f);},a.onclose=()=>{at?(this.log("realtime onclose","WebSocket connection closed."),e({type:"close",message:"WebSocket connection closed."})):(this.log("realtime onclose","WebSocket unexpected close."),e({type:"error",message:"Skapi: WebSocket unexpected close."}),qe++,qe<3?(this.log("realtime onclose","Reconnecting to WebSocket server..."+qe),e({type:"reconnect",message:"Reconnecting to WebSocket server..."+qe}),Ve.bind(this)(e,3e3,"reconnect")):(this.log("realtime onclose","Max reconnection attempts reached."),e({type:"error",message:"Skapi: Max reconnection attempts reached."})));},a.onerror=()=>{this.log("realtime onerror","WebSocket connection error."),e({type:"error",message:"Skapi: WebSocket connection error."});};}catch(a){o(a);}},t);}),n.value=this.__socket,this.__socket}async function as(e,t,r){if(typeof window>"u"||window._runningInNodeJS)throw new l("WebSocket is not supported in Node.js environment.",{code:"NOT_SUPPORTED"});let n=this.__socket?await this.__socket:this.__socket;if(!n)throw new l("No realtime connection. Execute connectRealtime() before this method.",{code:"INVALID_REQUEST"});if(!t)throw new l("No recipient.",{code:"INVALID_REQUEST"});await Oe.bind(this)(),e=$(e).data;let i="";if(r&&(r=y.Params(r,{config:{always:"boolean"},title:"string",body:"string"},["title","body"]),i=JSON.stringify({title:r.title,body:r.body}),new Blob([i]).size>3072))throw new l("Notification size exceeds 3kb.",{code:"INVALID_PARAMETER"});if(n.readyState===1){try{y.UserId(t),n.send(JSON.stringify({action:"sendMessage",uid:t,content:e,notification:i,notificationConfig:r?.config||{},token:`IdT:${this.service}:${this.owner}:`+(this.bearerToken||this.session?.idToken?.jwtToken||"null")}));}catch(s){if(this.log("postRealtime:err",{err:s}),we!==t)throw new l(`User has not joined to the recipient group. Run joinRealtime({ group: "${t}" })`,{code:"INVALID_REQUEST"});n.send(JSON.stringify({action:"broadcast",rid:t,content:e,notification:i,notificationConfig:r?.config||{},token:`IdT:${this.service}:${this.owner}:`+(this.bearerToken||this.session?.idToken?.jwtToken||"null")}));}return {type:"success",message:"Message sent."}}throw new l("Realtime connection is not open. Try reconnecting with connectRealtime().",{code:"INVALID_REQUEST"})}async function je(e){if(typeof window>"u"||window._runningInNodeJS)throw new l("WebSocket is not supported in Node.js environment.",{code:"NOT_SUPPORTED"});let t=this.__socket?await this.__socket:this.__socket;if(!t)throw new l("No realtime connection. Execute connectRealtime() before this method.",{code:"INVALID_REQUEST"});await Oe.bind(this)(),e=$(e,{nullIfEmpty:true}).data;let{group:r=null}=e;if(!r&&!we)return {type:"success",message:"Left realtime message group."};if(r!==null&&typeof r!="string")throw new l('"group" must be a string | null.',{code:"INVALID_PARAMETER"});return t.readyState===1&&t.send(JSON.stringify({action:"joinRoom",rid:r,token:this.session.accessToken.jwtToken})),we=r,{type:"success",message:r?`Joined realtime message group: "${r}".`:"Left realtime message group."}}async function ls(e,t){e=y.Params(e,{user_id:n=>y.UserId(n,'User ID in "user_id"'),group:["string",()=>{if(!we)throw new l('No group has been joined. Otherwise "group" is required.',{code:"INVALID_REQUEST"});return we}]});let r=await k.bind(this)("get-ws-group",e,{fetchOptions:t,auth:true,method:"post"});return r.list=r.list.map(n=>({user_id:n.uid.split("#")[1],cid:"cid:"+n.cid})),r}async function cs(e,t){if(await this.__connection,e||(e={searchFor:"group",value:" ",condition:">"}),e=y.Params(e,{searchFor:["group","number_of_users",()=>"group"],value:["string","number",()=>e?.searchFor&&e?.searchFor==="number_of_users"?0:" "],condition:[">",">=","=","<","<=","!=","gt","gte","eq","lt","lte","ne"],range:["string","number"]}),e.condition||(e.value===" "||!e.value?e.condition=">":e.condition="="),e.range&&e.condition&&delete e.condition,e.searchFor==="number_of_users"&&typeof e.value!="number")throw new l('"value" must be a number.',{code:"INVALID_PARAMETER"});if(e.searchFor==="group"&&typeof e.value!="string")throw new l('"value" must be a string.',{code:"INVALID_PARAMETER"});if(e.hasOwnProperty("range")&&typeof e.range!=typeof e.value)throw new l(`"range" must be a ${typeof e.value}.`,{code:"INVALID_PARAMETER"});let r=await k.bind(this)("get-ws-group",e,{fetchOptions:t,auth:true,method:"post"});return r.list=r.list.map(n=>({group:n.rid.split("#")[1],number_of_users:n.cnt})),r}var tl=typeof FormData<"u",fs=typeof HTMLFormElement<"u",gs=typeof SubmitEvent<"u",he={},lt={},te={};function ct(e){return Object.freeze({id:e,status:"stopped"})}function Fr(e){return !!e&&typeof e=="object"&&e.status==="stopped"}var ps=3;function hs(e,t,r){let n=false,i=Array.isArray(e?.chunks)?e.chunks.slice():[];i.sort((s,o)=>(s?.seq||0)-(o?.seq||0));for(let s of i)if(!(!s||typeof s.seq!="number"||s.seq<=t.seq)&&(t.seq=s.seq,n=true,r&&typeof s.txt=="string"&&s.txt!==""))try{r(s.txt,s.seq,"poll");}catch(o){console.error(o);}return typeof e?.last_seq=="number"&&e.last_seq>t.seq&&(t.seq=e.last_seq,n=true),n}var rl=2e3,ms=5e3,nl=2e3,il=5,sl=1500,qt=null;function ys(e,t,r){let n=new Map,i=false,s=false,o=0,a={socket:0,poll:0},d=(u,p,h)=>{if(e.seq=u,!(!t||typeof p!="string"||p===""))try{t(p,u,h);}catch(m){console.error(m);}},c=()=>{for(let u of Array.from(n.keys()))u<=e.seq&&n.delete(u);for(;;){let u=e.seq+1;if(!n.has(u))break;let p=n.get(u);n.delete(u),d(u,p.txt,p.via);}};return {cursor:e,open:()=>{i||s||(i=true,c());},fromPoll:u=>{if(s)return false;let p=e.seq,h=e.seq,m=Array.isArray(u?.chunks)?u.chunks:[];for(let b of m){if(!b||typeof b.seq!="number"||b.seq<=e.seq)continue;let A=!n.has(b.seq);A&&(a.poll++,r&&a.poll===1&&r("poll",b.seq)),n.set(b.seq,{txt:typeof b.txt=="string"?b.txt:"",via:A?"poll":n.get(b.seq).via}),b.seq>h&&(h=b.seq);}typeof u?.last_seq=="number"&&u.last_seq>h&&(h=u.last_seq);let _=Array.from(n.keys()).sort((b,A)=>b-A);for(let b of _){if(b<=e.seq){n.delete(b);continue}if(b>h)break;let A=n.get(b);n.delete(b),d(b,A.txt,A.via);}return h>e.seq&&(e.seq=h),c(),e.seq>p},fromSocket:(u,p)=>{s||typeof u!="number"||!Number.isFinite(u)||(o=Date.now(),!(u<=e.seq)&&(!n.has(u)&&n.size>=nl||(n.has(u)||(a.socket++,r&&a.socket===1&&r("socket",u)),n.set(u,{txt:typeof p=="string"?p:"",via:n.has(u)?n.get(u).via:"socket"}),i&&c())));},warm:()=>o!==0&&Date.now()-o<rl,stats:()=>({socket:a.socket,poll:a.poll}),close:()=>{s=true,n.clear();}}}function bs(e){if(!this||!this.__network_logs)return {onTransport:void 0,done:()=>{}};let t=Date.now(),r=false;return {onTransport:(n,i)=>{console.log(`%cSKAPI: stream chunk arrived over ${n==="socket"?"WEBSOCKET":"POLL"}`,`color: ${n==="socket"?"green":"orange"};`,{id:e,first_seq:i,after_ms:Date.now()-t});},done:n=>{if(r||!n)return;r=true;let i=n.stats();console.log("%cSKAPI: stream transport","color: blue;",{id:e,over_websocket:i.socket,over_poll:i.poll,took_ms:Date.now()-t});}}}function _s(e,t){let r={stop:()=>{}};if(typeof window>"u"||window._runningInNodeJS||qt)return r;let n={stopped:false,socket:null,opened:null,joined:false,attempts:0,unavailable:false};qt=n;let i=c=>{if(n.stopped)return;let g=c?.data;if(typeof g!="string")return;let f=null;try{f=JSON.parse(g);}catch{try{f=JSON.parse(decodeURI(g));}catch{return}}let u=f?.["#message"];if(u==null)return;if(typeof u=="string")try{u=JSON.parse(u);}catch{return}if(typeof u!="object")return;let p=f?.["#srid"];if(typeof p=="string"&&p!==e)return;let h=u.seq;typeof h=="string"&&h!==""&&(h=Number(h)),t.fromSocket(h,u.txt);},s=()=>{if(n.socket){try{n.socket.removeEventListener("message",i);}catch{}try{n.socket.removeEventListener("close",a);}catch{}n.socket=null;}},o=async()=>{let c=n.opened,g=n.joined;if(n.opened=null,n.joined=false,s(),!(!g&&!c))try{let f=this.__socket?await this.__socket:null;if(c&&f===c){await Ft.bind(this)();return}g&&f&&os()===room&&await je.bind(this)({group:null});}catch{}},a=()=>{n.stopped||(s(),!n.unavailable&&(n.attempts>=il||(n.attempts+=1,setTimeout(()=>{n.stopped||d();},sl))));},d=async()=>{try{let c=this.__socket?await this.__socket:null;if(n.stopped){o();return}if(!c){if(!this.session){n.unavailable=!0,o();return}if(await Ve.bind(this)(()=>{},0),c=this.__socket?await this.__socket:null,n.stopped){o();return}c&&!n.opened&&(n.opened=c);}if(!c||c.readyState!==1)return;if(c.addEventListener("message",i),c.addEventListener("close",a),n.socket=c,!n.joined&&(await je.bind(this)({group:e}),n.joined=!0,n.stopped)){o();return}}catch{}};return d(),{stop:()=>{n.stopped||(n.stopped=true,qt===n&&(qt=null),o());}}}function ws(e){return e?.status==="running"||e?.status==="pending"}function Es(e){return !!e&&typeof e=="object"&&!Array.isArray(e)&&typeof e.status=="string"&&typeof e.id=="string"&&"in_queue"in e}function As(e,t,r,n){if(!e||typeof e!="string")throw new l('"requestId" should be type: <string>.',{code:"INVALID_PARAMETER"});if(e.includes("#"))return e;if(!t||typeof t!="string"||!r||typeof r!="string")throw new l('"url" and "method" are required to address a request by its short id.',{code:"INVALID_PARAMETER"});return y.Url(t),`[${r.toUpperCase()}]${t.toLowerCase()}#${n}:${e}`}function Rs({id:e,auth:t,service:r,owner:n,latency:i=1e3,queue:s,seedExecuted:o,onResponse:a,onError:d,onStream:c,realtimeGroup:g}){if(typeof i!="number")throw new l('"latency" should be a number.',{code:"INVALID_PARAMETER"});if(i<0)throw new l('"latency" should be a non-negative number.',{code:"INVALID_PARAMETER"});s&&!he?.[s]&&(he[s]=new ds__default.default({breakWhenError:false,batchSize:1}));let f={stop:null,aborted:false,queue:s};te[e]=f;let u=null,p=()=>{te[e]===f&&delete te[e];},h=()=>new Promise((_,b)=>{let A=false;if(f.aborted){p(),_(ct(e));return}let w={seq:0},S=bs.call(this,e),E=c&&g?ys(w,c,S.onTransport):null,N=E?_s.call(this,g,E):null,U=()=>{S.done(E),N&&N.stop(),E&&E.close();};u=U;let C=0,v=false,x=0,O=typeof o=="number"&&o>0?o:void 0,V=async()=>{if(!(A||v)&&!(E&&E.warm()&&Date.now()-C<ms)){v=true;try{for(;;){let ie={id:e,service:r,owner:n};c&&(ie.since=w.seq),C=Date.now();let M=await k.bind(this)("csr-poll",ie,{auth:t});if(A)return;let J=E?E.fromPoll(M):c?hs(M,w,c):!1;E&&E.open();let ft=ws(M);if(typeof M?.executed=="number"&&M.executed>0&&(O=M.executed),M?.more&&J){x=0;continue}if(ft){x=0;return}if(x=M?.more?x+1:0,M?.more&&x<ps)return;A=!0,a&&a(M,O!==void 0?{executed:O}:void 0),clearInterval(de),U(),p(),_(M);return}}catch(ie){if(A)return;A=true,d&&d(ie),clearInterval(de),U(),p(),b(ie);}finally{v=false;}}},de=setInterval(V,i);E&&V(),f.stop=()=>{A||(A=true,clearInterval(de),U(),p(),_(ct(e)));};}),m=()=>{let _=te[e];_&&(_.stop?_.stop():(_.aborted=true,delete te[e]));};if(s){let _=new Promise((b,A)=>{let w=false,S=he[s].add([async()=>{try{let E=await h();return w||(w=!0,b(E)),E}catch(E){throw w||(w=true,A(E)),E}}])[0];lt[e]=S,f.stop=()=>{if(!w){f.aborted=true,u&&u();try{he[s]&&he[s].remove(lt[e]);}catch{}delete lt[e],p(),w=true,b(ct(e));}};});return Object.assign(_,{stop:m})}else return Object.assign(h(),{stop:m})}function jt(e){let t=0,r=[];if(e?.id){if(e.url&&e.method){let n=e.service||this.service;r.push(`[${e.method.toUpperCase()}]${e.url.toLowerCase()}#${n}:${e.id}`);}r.push(e.id);}else if(e?.queue)for(let n in te)te[n]?.queue===e.queue&&r.push(n);else for(let n in te)r.push(n);for(let n of r){let i=te[n];i&&(i.stop?i.stop():(i.aborted=true,delete te[n]),t+=1);}return t}function qr(e,t){if(!e.queue)throw new l('"queue" is required.',{code:"INVALID_PARAMETER"});let r=()=>k.bind(this)("csr-poll",{service:e.service||this.service,owner:e.owner||this.owner,queue:e.queue+":"},{auth:true});return this.__projectIdInput?this.__projectIdInput.then(r):r()}function ol(e){if(typeof Buffer<"u"&&typeof Buffer.from=="function")return Buffer.from(e).toString("base64");if(typeof btoa=="function"){let t="";for(let n=0;n<e.length;n+=32768)t+=String.fromCharCode.apply(null,Array.from(e.subarray(n,n+32768)));return btoa(t)}throw new l("No base64 encoder available in this environment.",{code:"NOT_SUPPORTED"})}var us=2*1024*1024-64*1024;function Vt(e){return typeof File<"u"&&e instanceof File||typeof Blob<"u"&&e instanceof Blob}function Mr(e){if(Array.isArray(e)){let t=[];for(let r of e)Vt(r)||t.push(Mr(r));return t}if(e&&typeof e=="object"&&!Vt(e)){let t=Object.getPrototypeOf(e);if(t!==Object.prototype&&t!==null)return e;let r={};for(let n in e)Vt(e[n])||(r[n]=Mr(e[n]));return r}return e}function al(e){if(e==null)return null;let t=$(e)?.data;return !t||typeof t!="object"||Array.isArray(t)?null:Mr(t)}function Ts(e,t,r){if(r!==void 0){if(Array.isArray(r)){for(let n of r)Ts(e,t,n);return}if(Vt(r)){e.append(t,r);return}if(r===null){e.append(t,"");return}if(typeof r=="object"){e.append(t,JSON.stringify(r));return}e.append(t,String(r));}}async function ll(e){if(e==null)throw new l('"multipart": true needs a form body in the first argument.',{code:"INVALID_PARAMETER"});if(typeof FormData>"u"||typeof Response>"u")throw new l('"multipart": true is not available in this environment.',{code:"NOT_SUPPORTED"});let t;if(gs&&e instanceof SubmitEvent)t=new FormData(e.target);else if(fs&&e instanceof HTMLFormElement)t=new FormData(e);else if(e instanceof FormData)t=e;else if(typeof e=="object"&&!Array.isArray(e)){t=new FormData;for(let s in e)Ts(t,s,e[s]);}else throw new l('"form" should be a submit event, a form element, FormData, or an object.',{code:"INVALID_PARAMETER"});let r=new Response(t),n=r.headers.get("content-type"),i=ol(new Uint8Array(await r.arrayBuffer()));if(i.length>us)throw new l(`Multipart body is too large: ${i.length} bytes once base64 encoded, and the limit is ${us}. Upload the file first and send its url instead.`,{code:"INVALID_PARAMETER"});return {body_b64:i,body_content_type:n}}function cl(e){if(e!=null){if(typeof e=="boolean")return e;if(typeof e=="object"&&!Array.isArray(e))return {user:!!e.user,service:!!e.service};throw new l('"skapiHeaders" should be type: <boolean> or { user?: boolean; service?: boolean }.',{code:"INVALID_PARAMETER"})}}function ul(e){if(!(!e||typeof e!="object")){for(let t in e)if(typeof t=="string"&&t.toLowerCase().indexOf("x-skapi-")===0)throw new l(`"headers" cannot set "${t}": the "x-skapi-" prefix is reserved. Use "skapiHeaders" to tell the destination who the caller is.`,{code:"INVALID_PARAMETER"})}}async function Is(e,t){let r=false,n=!!(e?.secretName||e?.clientSecretName),i=t?.signal;if(i?.aborted)throw new l('"signal" was already aborted.',{code:"INVALID_REQUEST"});if(typeof e.poll=="number"&&e.poll<0)throw new l('"poll" should be a non-negative number.',{code:"INVALID_PARAMETER"});let s=e?.onResponse,o=e?.onError,a=e?.onStream,d=typeof e.poll=="number"?e.poll:e.poll?1e3:0;delete e.poll,(d||e.stream)&&!e.queue&&(e.queue=(this.__user?.user_id||"anonymous")+"-"+Te());let c=(u,p=new WeakSet)=>{if(!(r||!u||typeof u!="object"||p.has(u))){p.add(u);for(let h in u){let m=u[h];if(typeof m=="string"){if(m.includes("$CLIENT_SECRET")){r=true;return}}else m&&typeof m=="object"&&c(m,p);}}};if(e=y.Params(e,{url:u=>{if(!u||typeof u!="string")throw new l('"url" should be type: <string>.',{code:"INVALID_PARAMETER"});return y.Url(u),u.includes("$CLIENT_SECRET")&&(r=true),u},secretName:"string",clientSecretName:"string",method:u=>{if(u&&typeof u!="string")throw new l('"method" should be one of "GET", "POST", "PUT", "PATCH", "DELETE" or "HEAD".',{code:"INVALID_PARAMETER"});let p=u.toLowerCase();if(p!=="get"&&p!=="post"&&p!=="delete"&&p!=="put"&&p!=="patch"&&p!=="head")throw new l('"method" should be one of "GET", "POST", "PUT", "PATCH", "DELETE" or "HEAD".',{code:"INVALID_PARAMETER"});return p},stream:u=>{if(u!=null&&typeof u!="boolean")throw new l('"stream" should be type: <boolean>.',{code:"INVALID_PARAMETER"});return !!u},realtime:u=>{if(u!=null&&typeof u!="boolean")throw new l('"realtime" should be type: <boolean>.',{code:"INVALID_PARAMETER"});return !!u},headers:u=>{if(u&&typeof u!="object")throw new l('"headers" should be type: <object>.',{code:"INVALID_PARAMETER"});return ul(u),c(u),u},skapiHeaders:u=>cl(u),data:u=>{if(u&&typeof u!="object")throw new l('"data" should be type: <object>.',{code:"INVALID_PARAMETER"});return c(u),u},params:u=>{if(u&&typeof u!="object")throw new l('"params" should be type: <object>.',{code:"INVALID_PARAMETER"});return c(u),u},body_b64:"string",body_content_type:"string",expires:"number",queue:"string"},t?.requireSecretName?["clientSecretName","method","url"]:["method","url"]),e.realtime&&!e.stream)throw new l('"realtime" requires "stream": true.',{code:"INVALID_PARAMETER"});if(e.body_b64&&e.data)throw new l('"data" cannot be sent with "multipart": true.',{code:"INVALID_PARAMETER"});n&&!r&&(delete e.secretName,delete e.clientSecretName),await this.__connection;let g=!!this.__user,f=()=>k.bind(this)("csr",e,{auth:g,tokenHeaders:{accessToken:!!g}}).then(u=>{if(u.status==="running"||u.status==="pending"){let p=`[${e.method.toUpperCase()}]${e.url.toLowerCase()}`,h=e.service||this.service,m=e.owner||this.owner,_=`${p}#${h}:${u.id}`;if(i){let b=()=>{jt.call(this,{id:_});};i.aborted?b():i.addEventListener("abort",b,{once:true});}Object.assign(u,{poll:b=>Rs.call(this,{id:_,auth:g,service:h,owner:m,latency:b?.latency||1e3,queue:e?.queue,onResponse:s,onError:o,onStream:b?.onStream||a,realtimeGroup:u?.realtime_group})});}return s?s(u):u}).catch(u=>{if(o)return o(u);throw u});if(e?.queue){let u="base:"+e.queue;return he?.[u]||(he[u]=new ds__default.default({breakWhenError:false,batchSize:1})),new Promise((p,h)=>{he[u].add([async()=>{try{let m=await f();if(d>0){let _=m.poll({latency:d});return i&&(i.aborted?_.stop():i.addEventListener("abort",()=>_.stop(),{once:!0})),p(_),_}return p(m),m}catch(m){throw h(m),m}}]);})}else return f()}async function Ps(e,t){if(!t||typeof t!="object")throw new l('"options" is required in the second argument.',{code:"INVALID_PARAMETER"});if(t.apiKeyHeader!==void 0||t.apiKeyScheme!==void 0)throw new l('"apiKeyHeader" and "apiKeyScheme" are no longer supported. Store the key as a client secret, name it with "secretName", and put "$CLIENT_SECRET" where the key goes.',{code:"INVALID_PARAMETER"});if(t.multipart!==void 0&&t.multipart!==null&&typeof t.multipart!="boolean")throw new l('"multipart" should be type: <boolean>.',{code:"INVALID_PARAMETER"});let r=t.responseType;if(r!=null){if(r==="response")throw new l(`"responseType": "response" is not available here. The request is relayed from the server and what comes back is the stored answer, not a live Response; the destination's status code is the "status_code" of the row forwardRequestHistory lists.`,{code:"INVALID_PARAMETER"});if(r!=="json"&&r!=="text")throw new l('"responseType" should be either "json" or "text".',{code:"INVALID_PARAMETER"})}let n=t.method||"POST",i=typeof n=="string"?n.toLowerCase():"",s=i==="get"||i==="delete"||i==="head"?"params":"data",o={url:t.url,method:n};if(t.secretName!==void 0&&(o.secretName=t.secretName),t.headers!==void 0&&(o.headers=t.headers),t.data!==void 0&&(o.data=t.data),t.params!==void 0&&(o.params=t.params),t.skapiHeaders!==void 0&&(o.skapiHeaders=t.skapiHeaders),t.service!==void 0&&(o.service=t.service),t.owner!==void 0&&(o.owner=t.owner),t.queue!==void 0&&(o.queue=t.queue),t.expires!==void 0&&(o.expires=t.expires),t.stream!==void 0&&(o.stream=t.stream),t.realtime!==void 0&&(o.realtime=t.realtime),t.poll!==void 0&&(o.poll=t.poll),t.onStream!==void 0&&(o.onStream=t.onStream),t.onResponse!==void 0&&(o.onResponse=t.onResponse),t.onError!==void 0&&(o.onError=t.onError),t.multipart){if(t.data!==void 0&&t.data!==null)throw new l('"data" cannot be sent with "multipart": true. The form itself is the body.',{code:"INVALID_PARAMETER"});let d=await ll(e);o.body_b64=d.body_b64,o.body_content_type=d.body_content_type;}else {let d=al(e);d&&Object.keys(d).length&&(o[s]=Object.assign({},d,o[s]||{}));}let a=Is.call(this,o,{signal:t.signal});return r?a.then(d=>{if(Es(d)||Fr(d))return d;if(r==="text")return typeof d=="string"?d:JSON.stringify(d);if(typeof d=="string")try{return JSON.parse(d)}catch{return d}return d}):a}async function ks(e){return Is.call(this,e,{requireSecretName:true})}async function Vr(e,t){await this.__connection;let r=e.service||this.service,n=e.owner||this.owner;e=y.Params(e,{url:"string",method:["GET","POST","PUT","PATCH","DELETE","HEAD"],queue:"string",status:["pending","running","resolved","failed"],compact:"boolean",queue_exact:"boolean",queue_exclude:"string"},["url","method"]);let i=!!this.__user,s=`[${e.method.toUpperCase()}]${e.url.toLowerCase()}#${r}:`,o={id:s,queue:e?.queue,status:e?.status,service:r,owner:n};e?.compact&&(o.compact=true),e?.queue_exact&&(o.queue_exact=true),e?.queue_exclude&&(o.queue_exclude=e.queue_exclude),Object.keys(o).forEach(d=>{o[d]||delete o[d];}),o.queue&&(o.id_prefix=o.id,delete o.id);let a=await k.bind(this)("csr-poll",o,{auth:i,fetchOptions:t});return a.list=a.list.map(d=>{let c={id:d.id,status_code:d.rslv?.status_code||null,response_body:d.rslv?.body||d.rslv?.truncated||null,error:d?.err,created:d?.stmp,updated:d?.utmp,executed:typeof d?.att=="number"?d.att*1e3:void 0,responded:typeof d?.rtmp=="number"?d.rtmp:void 0,request_body:d?.reqbdy,expires:d?.expt,status:d.stts,queue_name:d?.qid,request_text:d?.reqtxt,response_text:d?.rslvtxt,response_complete_marker:d?.rslvmk!=null?!!d.rslvmk:void 0,compact:d?.cmpct?true:void 0};for(let g in c)c[g]===void 0&&delete c[g];return (c.status==="running"||c.status==="pending")&&(c.poll=g=>Rs.call(this,{id:s+c.id,auth:i,service:r,owner:n,latency:g?.latency||1e3,queue:d?.qid,seedExecuted:c.executed,onResponse:g?.onResponse,onError:g?.onError,onStream:g?.onStream})),c}),a}async function jr(e){await this.__connection,e=y.Params(e,{url:"string",method:["GET","POST","PUT","PATCH","DELETE","HEAD"],id:"string",queue:"string"},["url","method","id"]);let t=e?.service||this.service,r=e?.owner||this.owner,n=!!this.__user,i=`[${e.method.toUpperCase()}]${e.url.toLowerCase()}#${t}`,s=e.id,o=`${i}:${s}`,a=e?.queue;return a&&he?.[a]&&(he[a].remove(lt[o]),delete lt[o]),k.bind(this)("csr-cancel",{id:o,service:t,owner:r},{auth:n})}function $r(e,t){let r=typeof t?.poll=="number"?t.poll:1e3;if(!Number.isFinite(r)||r<0)throw new l('"poll" should be a non-negative number.',{code:"INVALID_PARAMETER"});if(!e||typeof e!="string")throw new l('"requestId" should be type: <string>.',{code:"INVALID_PARAMETER"});if(t?.since!==void 0&&typeof t.since!="number")throw new l('"since" should be a number.',{code:"INVALID_PARAMETER"});if(t?.realtimeGroup!==void 0&&t.realtimeGroup!==null&&typeof t.realtimeGroup!="string")throw new l('"realtimeGroup" should be type: <string>.',{code:"INVALID_PARAMETER"});let n=typeof t?.since=="number"&&t.since>0?t.since:0,i=t?.onStream,s=t?.onResponse,o=t?.onError,a={stopped:false,fullId:e,resolve:null},d=null,c={stop:null,aborted:false},g=()=>{te[a.fullId]===c&&delete te[a.fullId];},f=()=>{a.stopped||(a.stopped=true,d&&d(),g(),a.resolve&&a.resolve(ct(a.fullId)));};c.stop=f;let u=new Promise(async(p,h)=>{a.resolve=p;try{await this.__connection;let m=!!this.__user,_=t?.service||this.service,b=t?.owner||this.owner;if(a.fullId=As(e,t?.url,t?.method,_),a.stopped){p(ct(a.fullId));return}te[a.fullId]=c;let A={seq:n},w=0,S=bs.call(this,a.fullId),E=i&&t?.realtimeGroup?ys(A,i,S.onTransport):null,N=E?_s.call(this,t.realtimeGroup,E):null,U=()=>{S.done(E),N&&N.stop(),E&&E.close();};for(d=U;;){let C=await k.bind(this)("csr-poll",{id:a.fullId,service:_,owner:b,since:A.seq},{auth:m});if(a.stopped)return;if(!Es(C)){U(),g(),s&&s(C),p(C);return}let v=E?E.fromPoll(C):hs(C,A,i);E&&E.open();let x=ws(C);if(C.more&&v){w=0;continue}if(w=C.more?w+1:0,!x&&(!C.more||w>=ps)){U(),g(),s&&s(C),p(C);return}if(await new Promise(O=>setTimeout(O,E&&E.warm()?Math.max(r,ms):r)),a.stopped)return}}catch(m){if(a.stopped)return;d&&d(),g(),o&&o(m),h(m);}});return Object.assign(u,{stop:f})}async function Br(e,t,r){await this.__connection;let n=r?.service||this.service,i=r?.owner||this.owner,s=!!this.__user,o=As(e,r?.url,r?.method,n);return k.bind(this)("csr-finalize",{id:o,data:t,service:n,owner:i},{auth:s})}var Ss=$r,vs=Br,Ns=Vr,Ds=jr,xs=jt,Us=qr;async function Cs(e){await this.__connection;let t={name:"string",email:r=>(y.Email(r),r),subject:"string",message:"string"};return e=y.Params(e,t,["name","email","subject","message"]),await k.bind(this)("send-inquiry",e),"SUCCESS: Inquiry has been sent."}async function Os(e,t){if(await this.__connection,tl&&e instanceof FormData||fs&&e instanceof HTMLFormElement||gs&&e instanceof SubmitEvent){if(!t)throw new l("Url string as a second argument is required when form is passed.",{code:"INVALID_PARAMETER"});let n=$(e);e={url:t,data:n.data,sync:true};}let r={url:n=>y.Url(n),data:n=>n,sync:["boolean",()=>true]};if(Array.isArray(e))for(let n of e)n=y.Params(n,r);else e=y.Params(e,r);return k.bind(this)("post-secure",e,{auth:true})}async function Ls(e,t){await this.__connection;let{auth:r=false,method:n="POST",bypassAwaitConnection:i=false,responseType:s,contentType:o,tokenHeaders:a,progress:d}=t||{};if(t=Object.assign({auth:r,method:n,bypassAwaitConnection:i,responseType:s,contentType:o,tokenHeaders:a},{fetchOptions:{progress:d}}),typeof e!="object"&&(o==="application/json"||o===void 0))throw new l('"data" should be type: <object>.',{code:"INVALID_PARAMETER"});return k.bind(this)("mock",e,t)}async function Ms(e,t){await this.__connection,e=y.Params(e||{},{access_group:n=>{if(n==="authorized"&&(n=1),n==="public"&&(n=0),typeof n!="number")throw new l('"access_group" should be type number.',{code:"INVALID_PARAMETER"});if(n<0)throw new l('"access_group" should be zero or a positive number.',{code:"INVALID_PARAMETER"});if(n>this.__user.access_group)throw new l("User has no access.",{code:"INVALID_REQUEST"});return n}});let r=await k.bind(this)("get-feed",e,{auth:true,fetchOptions:t});return Array.isArray(r?.list)&&(r.list=await Promise.all(r.list.map(n=>ke.bind(this)(n)))),r}function ut(e){if(e===this.__user.user_id)throw new l(`"user_id" cannot be the user's own ID.`,{code:"INVALID_PARAMETER"});return y.UserId(e,'"user_id"')}async function Fs(e,t){if(e=$(e,{ignoreEmpty:true}).data,e=y.Params(e,{subscriber:n=>y.UserId(n,'User ID in "subscriber"'),subscription:ut.bind(this),blocked:"boolean"}),!e.subscriber&&!e.subscription)throw new l('At least either "subscriber" or "subscription" should have a value.',{code:"INVALID_PARAMETER"});let r=await k.bind(this)("get-subscription",e,Object.assign({auth:true},{fetchOptions:t}));return r.list=r.list.map((n=>{let i={};if(n.sub){let s=n.sub.split("#");i.subscriber=s[2],i.subscription=s[0];}else i.subscriber=n.subscriber,i.subscription=n.subscription;return i.timestamp=n?.timestamp||n.stmp,i.blocked=n?.blocked||n.grp.substring(0,1)==="N",Object.assign(i,n.opt),i})),r}async function qs(e){await this.__connection,e=y.Params(e,{user_id:ut.bind(this),get_feed:"boolean",get_notified:"boolean",get_email:i=>{if(i&&(!this.__user.email||!this.__user.email_verified))throw new l("User has no verified email address.",{code:"INVALID_REQUEST"});return !!i}},["user_id"]);let t={};for(let i of ["get_feed","get_notified","get_email"])typeof e[i]=="boolean"&&(t[i]=e[i]);let r=await k.bind(this)("subscription",{subscribe:e.user_id,option:t},{auth:true}),n={};if(r.sub){let i=r.sub.split("#");n.subscriber=i[2],n.subscription=i[0];}else n.subscriber=r.subscriber,n.subscription=r.subscription;return n.timestamp=r?.timestamp||r.stmp,n.blocked=r?.blocked||r.grp.substring(0,1)==="N",Object.assign(n,r.opt),n}async function Vs(e){await this.__connection;let{user_id:t}=y.Params(e,{user_id:ut.bind(this)},["user_id"]);return await k.bind(this)("subscription",{unsubscribe:t},{auth:true})}async function js(e){await this.__connection;let{user_id:t}=y.Params(e,{user_id:ut.bind(this)},["user_id"]);return await k.bind(this)("subscription",{block:t},{auth:true})}async function $s(e){await this.__connection;let{user_id:t}=y.Params(e,{user_id:ut.bind(this)},["user_id"]);return await k.bind(this)("subscription",{unblock:t},{auth:true})}async function Bs(e,t){await this.__connection;let r=await Q.bind(this)();if(e=y.Params(e||{},{user_id:o=>{if(o!==this.__user.user_id&&!r)throw new l("No access.",{code:"INVALID_REQUEST"});return o},group:o=>y.newsletterGroup(o,{allowNull:true}),email:o=>{if(typeof o!="string"||!o.trim())throw new l('"email" should be a non-empty string.',{code:"INVALID_PARAMETER"});if(o.trim().length>255)throw new l('"email" should be at most 255 characters.',{code:"INVALID_PARAMETER"});return o.trim().toLowerCase()}}),e.email!==void 0){if(e.user_id!==void 0&&e.user_id!==null)throw new l('"email" cannot be used with "user_id".',{code:"INVALID_PARAMETER"});if(e.group===void 0||e.group===null)throw new l('"group" is required to search by "email".',{code:"INVALID_PARAMETER"})}let n=await k.bind(this)("get-newsletter-subscription",e,{auth:true,fetchOptions:t||null}),i=n?.list||n,s=[];Array.isArray(i)||(i=[]);for(let o of i){let a=o.subt.split("#"),d=true;a[0].charAt(0)==="@"&&(d=false,a[0]=a[0].substring(1));let c=/^\d+$/.test(a[0])?parseInt(a[0]):a[0],g={timestamp:o.stmp,group:c,subscribed_email:a[1],active:d};typeof o.email_token=="string"&&o.email_token&&(g.subscriber_token=o.email_token),s.push(g);}return n?.list?(n.list=s,n):s}async function Ks(e){await this.__connection;let t=y.Params(e||{},{email:r=>Array.isArray(r)&&r.length>0?r.length===1?y.Email(r[0]):r.map(n=>y.Email(n)):y.Email(r),group:r=>y.newsletterGroup(r),redirect:r=>y.Url(r)},this.__user?["group"]:["email","group"]);return k.bind(this)(`subscribe-${this.__user?"":"public-"}newsletter`,t,{auth:!!this.__user})}async function Hs(e){await this.__connection;let t=y.Params(e||{},{group:r=>y.newsletterGroup(r,{nameOnly:true}),restriction:r=>{if(typeof r!="number"||!Number.isInteger(r)||r<0||r>99)throw new l('"restriction" should be a number between 0 and 99.',{code:"INVALID_PARAMETER"});return r},name:r=>{if(typeof r!="string"||r.length>60)throw new l('"name" should be a string of 60 characters or less.',{code:"INVALID_PARAMETER"});return r}},["group"]);return k.bind(this)("register-newsletter-group",t,{auth:true})}async function Gs(e){await this.__connection;let t=y.Params(e||{},{group:r=>y.newsletterGroup(r,{nameOnly:true})},["group"]);return k.bind(this)("delete-newsletter-group",t,{auth:true})}async function Ws(){return await this.__connection,k.bind(this)("newsletter-group-endpoint",null,{auth:true})}async function Qs(e){await this.__connection,e=y.Params(e,{group:r=>y.newsletterGroup(r,{allowNull:true})},["group"]);let t=Object.assign({action:"unsubscribe"},e);return k.bind(this)("subscribe-newsletter",t,{auth:true})}async function zs(e,t){let r=await Q.bind(this)(),n={message_id:"string",timestamp:"number",read:"number",complaint:"number",subject:"string",bounced:"number"};e||(t=Object.assign({ascending:false},t||{})),e=$(e).data,e=e||{searchFor:"timestamp",value:Date.now(),condition:"<",group:"public"},e=y.Params(e,{searchFor:["message_id","timestamp","subject","complaint","read","bounced"],value:d=>{if(typeof d!==n[e.searchFor])throw new l(`"value" type does not match the type of "${e.searchFor}" index.`,{code:"INVALID_PARAMETER"});if(typeof d=="string"&&!d)throw new l('"value" should not be empty string.',{code:"INVALID_PARAMETER"});return d},range:d=>{if(!e.hasOwnProperty("value")||typeof d!=typeof e.value)throw new l('"range" should match type of "value".',{code:"INVALID_PARAMETER"});return d},condition:[">",">=","=","<","<=","gt","gte","eq","lt","lte",()=>"="],group:d=>{let c=y.newsletterGroup(d);if(c===0)return 0;if(typeof c=="string")return c;if(!this.session)throw new l("User should be logged in.",{code:"INVALID_REQUEST"});if(d==="authorized")return 1;if(!r&&c>parseInt(this.user?.access_group||this.session?.idToken?.payload?.access_group))throw new l("User has no access.",{code:"INVALID_REQUEST"});return c}},["searchFor","value","group"]);let i=e.group===0||typeof e.group=="string"&&!this.__user?"get-public-newsletters":"get-newsletters",s=await k.bind(this)(i,e,Object.assign({method:"get",auth:i==="get-public-newsletters"?!!this.__user:true},{fetchOptions:t})),o={message_id:"mid",timestamp:"stmp",complaint:"cmpl",read:"read",subject:"subj",bounced:"bnce",url:"url",delivered:"delv",group:"grp"},a={message_id:"",timestamp:0,complaint:0,read:0,subject:"",bounced:"",url:"",delivered:0,group:e.group};return s.list=s.list.map(d=>{let c={};for(let g in o)c[g]=d[o[g]]||a[g];return c.bounced=String(c.bounced),c}),s}var $e="skapi:project_id";function Js(e){let t=e.trim().toLowerCase().replace(/^<|>$/g,"").replace(/[\s_\-.]+/g,"");return t==="serviceid"||t==="projectid"}function Ys(){try{return window.sessionStorage.getItem($e)||null}catch{return null}}function Xs(e){try{window.sessionStorage.setItem($e,e);}catch{}}function $t(e){try{window.sessionStorage.getItem($e)===e&&window.sessionStorage.removeItem($e);}catch{}}function Zs(){if(H())return typeof window.prompt=="function";let e=ve("tty");return !!(e&&ve("readline")&&e.isatty(0)&&e.isatty(2))}function eo(){return new l("Project ID is required.",{code:"INVALID_PARAMETER"})}var dt=null;function to(e,t){if(!dt){dt=H()?dl(e,t):fl(e,t);let r=()=>{dt=null;};dt.then(r,r);}return dt}async function dl(e,t){await new Promise(o=>setTimeout(o,0));let r=`new Skapi() was given the placeholder "${e}" instead of your Project ID.`,n=`Enter your Project ID to continue. This browser tab remembers it until the tab is closed. To stop being asked, replace "${e}" in your code with the ID.`,i=`${r}
|
|
215
|
+
`,c=new Blob([d],{type:"application/javascript"});Re=new Worker(URL.createObjectURL(c)),Re.onmessage=g=>{a.readyState===1&&a.send(JSON.stringify({action:"keepAlive"}));},i(a);},a.onmessage=async d=>{let c="";try{c=JSON.parse(decodeURI(d.data)),this.log("socket onmessage",c);}catch{return}let g;switch(!0){case !!c?.["#message"]:g="message";break;case !!c?.["#private"]:g="private";break;case !!c?.["#notice"]:g="notice";break;case !!c?.["#rtc"]:g="rtc";break;case !!c?.["#error"]:g="error";break}if(!g)return;let f={type:g,message:c?.["#rtc"]||c?.["#message"]||c?.["#private"]||c?.["#notice"]||c?.["#error"]||null,sender:c?.["#user_id"]||null,sender_cid:c?.["#scid"]?"cid:"+c["#scid"]:null,sender_rid:c?.["#srid"]||null,code:c?.["#code"]||null};if(g==="notice")e(f);else if(g==="rtc"){if(f.sender!==this.user.user_id){let u=f.message;if(u.hungup){ce[f.sender_cid]&&(ce[f.sender_cid](!1),delete ce[f.sender_cid]),pe[f.sender_cid]&&delete pe[f.sender_cid],D?.[f.sender_cid]&&ue.bind(this)({cid:f.sender_cid}),f.type="rtc:closed",e(f);return}if(u.candidate&&Or.bind(this)(u.candidate,f.sender_cid),u.sdpoffer&&(Cr.bind(this)(u.sdpoffer,f.sender_cid),pe[f.sender_cid]||(pe[f.sender_cid]=f.sender_cid,delete f.message,f.connectRTC=ns.bind(this)(f),f.type="rtc:incoming",f.hangup=(()=>{D[f.sender_cid]?ue.bind(this)({cid:f.sender_cid}):pe[f.sender_cid]&&(delete pe[f.sender_cid],a.send(JSON.stringify({action:"rtc",uid:f.sender_cid,content:{hungup:this.user.user_id},token:this.session.accessToken.jwtToken})));}).bind(this),e(f))),u.pickup&&ce[f.sender_cid]&&(ce[f.sender_cid](!0),delete ce[f.sender_cid]),u.sdpanswer&&D[f.sender_cid])if(D[f.sender_cid].signalingState==="have-local-offer")await D[f.sender_cid].setRemoteDescription(new RTCSessionDescription(u.sdpanswer));else throw new l("Invalid signaling state.",{code:"INVALID_REQUEST"})}}else e(f);},a.onclose=()=>{at?(this.log("realtime onclose","WebSocket connection closed."),e({type:"close",message:"WebSocket connection closed."})):(this.log("realtime onclose","WebSocket unexpected close."),e({type:"error",message:"Skapi: WebSocket unexpected close."}),qe++,qe<3?(this.log("realtime onclose","Reconnecting to WebSocket server..."+qe),e({type:"reconnect",message:"Reconnecting to WebSocket server..."+qe}),Ve.bind(this)(e,3e3,"reconnect")):(this.log("realtime onclose","Max reconnection attempts reached."),e({type:"error",message:"Skapi: Max reconnection attempts reached."})));},a.onerror=()=>{this.log("realtime onerror","WebSocket connection error."),e({type:"error",message:"Skapi: WebSocket connection error."});};}catch(a){o(a);}},t);}),n.value=this.__socket,this.__socket}async function as(e,t,r){if(typeof window>"u"||window._runningInNodeJS)throw new l("WebSocket is not supported in Node.js environment.",{code:"NOT_SUPPORTED"});let n=this.__socket?await this.__socket:this.__socket;if(!n)throw new l("No realtime connection. Execute connectRealtime() before this method.",{code:"INVALID_REQUEST"});if(!t)throw new l("No recipient.",{code:"INVALID_REQUEST"});await Oe.bind(this)(),e=$(e).data;let i="";if(r&&(r=y.Params(r,{config:{always:"boolean"},title:"string",body:"string"},["title","body"]),i=JSON.stringify({title:r.title,body:r.body}),new Blob([i]).size>3072))throw new l("Notification size exceeds 3kb.",{code:"INVALID_PARAMETER"});if(n.readyState===1){try{y.UserId(t),n.send(JSON.stringify({action:"sendMessage",uid:t,content:e,notification:i,notificationConfig:r?.config||{},token:`IdT:${this.service}:${this.owner}:`+(this.bearerToken||this.session?.idToken?.jwtToken||"null")}));}catch(s){if(this.log("postRealtime:err",{err:s}),we!==t)throw new l(`User has not joined to the recipient group. Run joinRealtime({ group: "${t}" })`,{code:"INVALID_REQUEST"});n.send(JSON.stringify({action:"broadcast",rid:t,content:e,notification:i,notificationConfig:r?.config||{},token:`IdT:${this.service}:${this.owner}:`+(this.bearerToken||this.session?.idToken?.jwtToken||"null")}));}return {type:"success",message:"Message sent."}}throw new l("Realtime connection is not open. Try reconnecting with connectRealtime().",{code:"INVALID_REQUEST"})}async function je(e){if(typeof window>"u"||window._runningInNodeJS)throw new l("WebSocket is not supported in Node.js environment.",{code:"NOT_SUPPORTED"});let t=this.__socket?await this.__socket:this.__socket;if(!t)throw new l("No realtime connection. Execute connectRealtime() before this method.",{code:"INVALID_REQUEST"});await Oe.bind(this)(),e=$(e,{nullIfEmpty:true}).data;let{group:r=null}=e;if(!r&&!we)return {type:"success",message:"Left realtime message group."};if(r!==null&&typeof r!="string")throw new l('"group" must be a string | null.',{code:"INVALID_PARAMETER"});return t.readyState===1&&t.send(JSON.stringify({action:"joinRoom",rid:r,token:this.session.accessToken.jwtToken})),we=r,{type:"success",message:r?`Joined realtime message group: "${r}".`:"Left realtime message group."}}async function ls(e,t){e=y.Params(e,{user_id:n=>y.UserId(n,'User ID in "user_id"'),group:["string",()=>{if(!we)throw new l('No group has been joined. Otherwise "group" is required.',{code:"INVALID_REQUEST"});return we}]});let r=await k.bind(this)("get-ws-group",e,{fetchOptions:t,auth:true,method:"post"});return r.list=r.list.map(n=>({user_id:n.uid.split("#")[1],cid:"cid:"+n.cid})),r}async function cs(e,t){if(await this.__connection,e||(e={searchFor:"group",value:" ",condition:">"}),e=y.Params(e,{searchFor:["group","number_of_users",()=>"group"],value:["string","number",()=>e?.searchFor&&e?.searchFor==="number_of_users"?0:" "],condition:[">",">=","=","<","<=","!=","gt","gte","eq","lt","lte","ne"],range:["string","number"]}),e.condition||(e.value===" "||!e.value?e.condition=">":e.condition="="),e.range&&e.condition&&delete e.condition,e.searchFor==="number_of_users"&&typeof e.value!="number")throw new l('"value" must be a number.',{code:"INVALID_PARAMETER"});if(e.searchFor==="group"&&typeof e.value!="string")throw new l('"value" must be a string.',{code:"INVALID_PARAMETER"});if(e.hasOwnProperty("range")&&typeof e.range!=typeof e.value)throw new l(`"range" must be a ${typeof e.value}.`,{code:"INVALID_PARAMETER"});let r=await k.bind(this)("get-ws-group",e,{fetchOptions:t,auth:true,method:"post"});return r.list=r.list.map(n=>({group:n.rid.split("#")[1],number_of_users:n.cnt})),r}var tl=typeof FormData<"u",fs=typeof HTMLFormElement<"u",gs=typeof SubmitEvent<"u",he={},lt={},te={};function ct(e){return Object.freeze({id:e,status:"stopped"})}function Fr(e){return !!e&&typeof e=="object"&&e.status==="stopped"}var ps=3;function hs(e,t,r){let n=false,i=Array.isArray(e?.chunks)?e.chunks.slice():[];i.sort((s,o)=>(s?.seq||0)-(o?.seq||0));for(let s of i)if(!(!s||typeof s.seq!="number"||s.seq<=t.seq)&&(t.seq=s.seq,n=true,r&&typeof s.txt=="string"&&s.txt!==""))try{r(s.txt,s.seq,"poll");}catch(o){console.error(o);}return typeof e?.last_seq=="number"&&e.last_seq>t.seq&&(t.seq=e.last_seq,n=true),n}var rl=2e3,ms=5e3,nl=2e3,il=5,sl=1500,qt=null;function ys(e,t,r){let n=new Map,i=false,s=false,o=0,a={socket:0,poll:0},d=(u,p,h)=>{if(e.seq=u,!(!t||typeof p!="string"||p===""))try{t(p,u,h);}catch(m){console.error(m);}},c=()=>{for(let u of Array.from(n.keys()))u<=e.seq&&n.delete(u);for(;;){let u=e.seq+1;if(!n.has(u))break;let p=n.get(u);n.delete(u),d(u,p.txt,p.via);}};return {cursor:e,open:()=>{i||s||(i=true,c());},fromPoll:u=>{if(s)return false;let p=e.seq,h=e.seq,m=Array.isArray(u?.chunks)?u.chunks:[];for(let b of m){if(!b||typeof b.seq!="number"||b.seq<=e.seq)continue;let A=!n.has(b.seq);A&&(a.poll++,r&&a.poll===1&&r("poll",b.seq)),n.set(b.seq,{txt:typeof b.txt=="string"?b.txt:"",via:A?"poll":n.get(b.seq).via}),b.seq>h&&(h=b.seq);}typeof u?.last_seq=="number"&&u.last_seq>h&&(h=u.last_seq);let _=Array.from(n.keys()).sort((b,A)=>b-A);for(let b of _){if(b<=e.seq){n.delete(b);continue}if(b>h)break;let A=n.get(b);n.delete(b),d(b,A.txt,A.via);}return h>e.seq&&(e.seq=h),c(),e.seq>p},fromSocket:(u,p)=>{s||typeof u!="number"||!Number.isFinite(u)||(o=Date.now(),!(u<=e.seq)&&(!n.has(u)&&n.size>=nl||(n.has(u)||(a.socket++,r&&a.socket===1&&r("socket",u)),n.set(u,{txt:typeof p=="string"?p:"",via:n.has(u)?n.get(u).via:"socket"}),i&&c())));},warm:()=>o!==0&&Date.now()-o<rl,stats:()=>({socket:a.socket,poll:a.poll}),close:()=>{s=true,n.clear();}}}function bs(e){if(!this||!this.__network_logs)return {onTransport:void 0,done:()=>{}};let t=Date.now(),r=false;return {onTransport:(n,i)=>{console.log(`%cSKAPI: stream chunk arrived over ${n==="socket"?"WEBSOCKET":"POLL"}`,`color: ${n==="socket"?"green":"orange"};`,{id:e,first_seq:i,after_ms:Date.now()-t});},done:n=>{if(r||!n)return;r=true;let i=n.stats();console.log("%cSKAPI: stream transport","color: blue;",{id:e,over_websocket:i.socket,over_poll:i.poll,took_ms:Date.now()-t});}}}function _s(e,t){let r={stop:()=>{}};if(typeof window>"u"||window._runningInNodeJS||qt)return r;let n={stopped:false,socket:null,opened:null,joined:false,attempts:0,unavailable:false};qt=n;let i=c=>{if(n.stopped)return;let g=c?.data;if(typeof g!="string")return;let f=null;try{f=JSON.parse(g);}catch{try{f=JSON.parse(decodeURI(g));}catch{return}}let u=f?.["#message"];if(u==null)return;if(typeof u=="string")try{u=JSON.parse(u);}catch{return}if(typeof u!="object")return;let p=f?.["#srid"];if(typeof p=="string"&&p!==e)return;let h=u.seq;typeof h=="string"&&h!==""&&(h=Number(h)),t.fromSocket(h,u.txt);},s=()=>{if(n.socket){try{n.socket.removeEventListener("message",i);}catch{}try{n.socket.removeEventListener("close",a);}catch{}n.socket=null;}},o=async()=>{let c=n.opened,g=n.joined;if(n.opened=null,n.joined=false,s(),!(!g&&!c))try{let f=this.__socket?await this.__socket:null;if(c&&f===c){await Ft.bind(this)();return}g&&f&&os()===room&&await je.bind(this)({group:null});}catch{}},a=()=>{n.stopped||(s(),!n.unavailable&&(n.attempts>=il||(n.attempts+=1,setTimeout(()=>{n.stopped||d();},sl))));},d=async()=>{try{let c=this.__socket?await this.__socket:null;if(n.stopped){o();return}if(!c){if(!this.session){n.unavailable=!0,o();return}if(await Ve.bind(this)(()=>{},0),c=this.__socket?await this.__socket:null,n.stopped){o();return}c&&!n.opened&&(n.opened=c);}if(!c||c.readyState!==1)return;if(c.addEventListener("message",i),c.addEventListener("close",a),n.socket=c,!n.joined&&(await je.bind(this)({group:e}),n.joined=!0,n.stopped)){o();return}}catch{}};return d(),{stop:()=>{n.stopped||(n.stopped=true,qt===n&&(qt=null),o());}}}function ws(e){return e?.status==="running"||e?.status==="pending"}function Es(e){return !!e&&typeof e=="object"&&!Array.isArray(e)&&typeof e.status=="string"&&typeof e.id=="string"&&"in_queue"in e}function As(e,t,r,n){if(!e||typeof e!="string")throw new l('"requestId" should be type: <string>.',{code:"INVALID_PARAMETER"});if(e.includes("#"))return e;if(!t||typeof t!="string"||!r||typeof r!="string")throw new l('"url" and "method" are required to address a request by its short id.',{code:"INVALID_PARAMETER"});return y.Url(t),`[${r.toUpperCase()}]${t.toLowerCase()}#${n}:${e}`}function Rs({id:e,auth:t,service:r,owner:n,latency:i=1e3,queue:s,seedExecuted:o,onResponse:a,onError:d,onStream:c,realtimeGroup:g}){if(typeof i!="number")throw new l('"latency" should be a number.',{code:"INVALID_PARAMETER"});if(i<0)throw new l('"latency" should be a non-negative number.',{code:"INVALID_PARAMETER"});s&&!he?.[s]&&(he[s]=new ds__default.default({breakWhenError:false,batchSize:1}));let f={stop:null,aborted:false,queue:s};te[e]=f;let u=null,p=()=>{te[e]===f&&delete te[e];},h=()=>new Promise((_,b)=>{let A=false;if(f.aborted){p(),_(ct(e));return}let w={seq:0},S=bs.call(this,e),E=c&&g?ys(w,c,S.onTransport):null,N=E?_s.call(this,g,E):null,U=()=>{S.done(E),N&&N.stop(),E&&E.close();};u=U;let C=0,v=false,x=0,O=typeof o=="number"&&o>0?o:void 0,V=async()=>{if(!(A||v)&&!(E&&E.warm()&&Date.now()-C<ms)){v=true;try{for(;;){let ie={id:e,service:r,owner:n};c&&(ie.since=w.seq),C=Date.now();let M=await k.bind(this)("csr-poll",ie,{auth:t});if(A)return;let J=E?E.fromPoll(M):c?hs(M,w,c):!1;E&&E.open();let ft=ws(M);if(typeof M?.executed=="number"&&M.executed>0&&(O=M.executed),M?.more&&J){x=0;continue}if(ft){x=0;return}if(x=M?.more?x+1:0,M?.more&&x<ps)return;A=!0,a&&a(M,O!==void 0?{executed:O}:void 0),clearInterval(de),U(),p(),_(M);return}}catch(ie){if(A)return;A=true,d&&d(ie),clearInterval(de),U(),p(),b(ie);}finally{v=false;}}},de=setInterval(V,i);E&&V(),f.stop=()=>{A||(A=true,clearInterval(de),U(),p(),_(ct(e)));};}),m=()=>{let _=te[e];_&&(_.stop?_.stop():(_.aborted=true,delete te[e]));};if(s){let _=new Promise((b,A)=>{let w=false,S=he[s].add([async()=>{try{let E=await h();return w||(w=!0,b(E)),E}catch(E){throw w||(w=true,A(E)),E}}])[0];lt[e]=S,f.stop=()=>{if(!w){f.aborted=true,u&&u();try{he[s]&&he[s].remove(lt[e]);}catch{}delete lt[e],p(),w=true,b(ct(e));}};});return Object.assign(_,{stop:m})}else return Object.assign(h(),{stop:m})}function jt(e){let t=0,r=[];if(e?.id){if(e.url&&e.method){let n=e.service||this.service;r.push(`[${e.method.toUpperCase()}]${e.url.toLowerCase()}#${n}:${e.id}`);}r.push(e.id);}else if(e?.queue)for(let n in te)te[n]?.queue===e.queue&&r.push(n);else for(let n in te)r.push(n);for(let n of r){let i=te[n];i&&(i.stop?i.stop():(i.aborted=true,delete te[n]),t+=1);}return t}function qr(e,t){if(!e.queue)throw new l('"queue" is required.',{code:"INVALID_PARAMETER"});let r=()=>k.bind(this)("csr-poll",{service:e.service||this.service,owner:e.owner||this.owner,queue:e.queue+":"},{auth:true});return this.__projectIdInput?this.__projectIdInput.then(r):r()}function ol(e){if(typeof Buffer<"u"&&typeof Buffer.from=="function")return Buffer.from(e).toString("base64");if(typeof btoa=="function"){let t="";for(let n=0;n<e.length;n+=32768)t+=String.fromCharCode.apply(null,Array.from(e.subarray(n,n+32768)));return btoa(t)}throw new l("No base64 encoder available in this environment.",{code:"NOT_SUPPORTED"})}var us=2*1024*1024-64*1024;function Vt(e){return typeof File<"u"&&e instanceof File||typeof Blob<"u"&&e instanceof Blob}function Mr(e){if(Array.isArray(e)){let t=[];for(let r of e)Vt(r)||t.push(Mr(r));return t}if(e&&typeof e=="object"&&!Vt(e)){let t=Object.getPrototypeOf(e);if(t!==Object.prototype&&t!==null)return e;let r={};for(let n in e)Vt(e[n])||(r[n]=Mr(e[n]));return r}return e}function al(e){if(e==null)return null;let t=$(e)?.data;return !t||typeof t!="object"||Array.isArray(t)?null:Mr(t)}function Ts(e,t,r){if(r!==void 0){if(Array.isArray(r)){for(let n of r)Ts(e,t,n);return}if(Vt(r)){e.append(t,r);return}if(r===null){e.append(t,"");return}if(typeof r=="object"){e.append(t,JSON.stringify(r));return}e.append(t,String(r));}}async function ll(e){if(e==null)throw new l('"multipart": true needs a form body in the first argument.',{code:"INVALID_PARAMETER"});if(typeof FormData>"u"||typeof Response>"u")throw new l('"multipart": true is not available in this environment.',{code:"NOT_SUPPORTED"});let t;if(gs&&e instanceof SubmitEvent)t=new FormData(e.target);else if(fs&&e instanceof HTMLFormElement)t=new FormData(e);else if(e instanceof FormData)t=e;else if(typeof e=="object"&&!Array.isArray(e)){t=new FormData;for(let s in e)Ts(t,s,e[s]);}else throw new l('"form" should be a submit event, a form element, FormData, or an object.',{code:"INVALID_PARAMETER"});let r=new Response(t),n=r.headers.get("content-type"),i=ol(new Uint8Array(await r.arrayBuffer()));if(i.length>us)throw new l(`Multipart body is too large: ${i.length} bytes once base64 encoded, and the limit is ${us}. Upload the file first and send its url instead.`,{code:"INVALID_PARAMETER"});return {body_b64:i,body_content_type:n}}function cl(e){if(e!=null){if(typeof e=="boolean")return e;if(typeof e=="object"&&!Array.isArray(e))return {user:!!e.user,service:!!e.service};throw new l('"skapiHeaders" should be type: <boolean> or { user?: boolean; service?: boolean }.',{code:"INVALID_PARAMETER"})}}function ul(e){if(!(!e||typeof e!="object")){for(let t in e)if(typeof t=="string"&&t.toLowerCase().indexOf("x-skapi-")===0)throw new l(`"headers" cannot set "${t}": the "x-skapi-" prefix is reserved. Use "skapiHeaders" to tell the destination who the caller is.`,{code:"INVALID_PARAMETER"})}}async function Is(e,t){let r=false,n=!!(e?.secretName||e?.clientSecretName),i=t?.signal;if(i?.aborted)throw new l('"signal" was already aborted.',{code:"INVALID_REQUEST"});if(typeof e.poll=="number"&&e.poll<0)throw new l('"poll" should be a non-negative number.',{code:"INVALID_PARAMETER"});let s=e?.onResponse,o=e?.onError,a=e?.onStream,d=typeof e.poll=="number"?e.poll:e.poll?1e3:0;delete e.poll,(d||e.stream)&&!e.queue&&(e.queue=(this.__user?.user_id||"anonymous")+"-"+Te());let c=(u,p=new WeakSet)=>{if(!(r||!u||typeof u!="object"||p.has(u))){p.add(u);for(let h in u){let m=u[h];if(typeof m=="string"){if(m.includes("$CLIENT_SECRET")){r=true;return}}else m&&typeof m=="object"&&c(m,p);}}};if(e=y.Params(e,{url:u=>{if(!u||typeof u!="string")throw new l('"url" should be type: <string>.',{code:"INVALID_PARAMETER"});return y.Url(u),u.includes("$CLIENT_SECRET")&&(r=true),u},secretName:"string",clientSecretName:"string",method:u=>{if(u&&typeof u!="string")throw new l('"method" should be one of "GET", "POST", "PUT", "PATCH", "DELETE" or "HEAD".',{code:"INVALID_PARAMETER"});let p=u.toLowerCase();if(p!=="get"&&p!=="post"&&p!=="delete"&&p!=="put"&&p!=="patch"&&p!=="head")throw new l('"method" should be one of "GET", "POST", "PUT", "PATCH", "DELETE" or "HEAD".',{code:"INVALID_PARAMETER"});return p},stream:u=>{if(u!=null&&typeof u!="boolean")throw new l('"stream" should be type: <boolean>.',{code:"INVALID_PARAMETER"});return !!u},realtime:u=>{if(u!=null&&typeof u!="boolean")throw new l('"realtime" should be type: <boolean>.',{code:"INVALID_PARAMETER"});return !!u},headers:u=>{if(u&&typeof u!="object")throw new l('"headers" should be type: <object>.',{code:"INVALID_PARAMETER"});return ul(u),c(u),u},skapiHeaders:u=>cl(u),data:u=>{if(u&&typeof u!="object")throw new l('"data" should be type: <object>.',{code:"INVALID_PARAMETER"});return c(u),u},params:u=>{if(u&&typeof u!="object")throw new l('"params" should be type: <object>.',{code:"INVALID_PARAMETER"});return c(u),u},body_b64:"string",body_content_type:"string",expires:"number",queue:"string"},t?.requireSecretName?["clientSecretName","method","url"]:["method","url"]),e.realtime&&!e.stream)throw new l('"realtime" requires "stream": true.',{code:"INVALID_PARAMETER"});if(e.body_b64&&e.data)throw new l('"data" cannot be sent with "multipart": true.',{code:"INVALID_PARAMETER"});n&&!r&&(delete e.secretName,delete e.clientSecretName),await this.__connection;let g=!!this.__user,f=()=>k.bind(this)("csr",e,{auth:g,tokenHeaders:{accessToken:!!g}}).then(u=>{if(u.status==="running"||u.status==="pending"){let p=`[${e.method.toUpperCase()}]${e.url.toLowerCase()}`,h=e.service||this.service,m=e.owner||this.owner,_=`${p}#${h}:${u.id}`;if(i){let b=()=>{jt.call(this,{id:_});};i.aborted?b():i.addEventListener("abort",b,{once:true});}Object.assign(u,{poll:b=>Rs.call(this,{id:_,auth:g,service:h,owner:m,latency:b?.latency||1e3,queue:e?.queue,onResponse:s,onError:o,onStream:b?.onStream||a,realtimeGroup:u?.realtime_group})});}return s?s(u):u}).catch(u=>{if(o)return o(u);throw u});if(e?.queue){let u="base:"+e.queue;return he?.[u]||(he[u]=new ds__default.default({breakWhenError:false,batchSize:1})),new Promise((p,h)=>{he[u].add([async()=>{try{let m=await f();if(d>0){let _=m.poll({latency:d});return i&&(i.aborted?_.stop():i.addEventListener("abort",()=>_.stop(),{once:!0})),p(_),_}return p(m),m}catch(m){throw h(m),m}}]);})}else return f()}async function Ps(e,t){if(!t||typeof t!="object")throw new l('"options" is required in the second argument.',{code:"INVALID_PARAMETER"});if(t.apiKeyHeader!==void 0||t.apiKeyScheme!==void 0)throw new l('"apiKeyHeader" and "apiKeyScheme" are no longer supported. Store the key as a client secret, name it with "secretName", and put "$CLIENT_SECRET" where the key goes.',{code:"INVALID_PARAMETER"});if(t.multipart!==void 0&&t.multipart!==null&&typeof t.multipart!="boolean")throw new l('"multipart" should be type: <boolean>.',{code:"INVALID_PARAMETER"});let r=t.responseType;if(r!=null){if(r==="response")throw new l(`"responseType": "response" is not available here. The request is relayed from the server and what comes back is the stored answer, not a live Response; the destination's status code is the "status_code" of the row forwardRequestHistory lists.`,{code:"INVALID_PARAMETER"});if(r!=="json"&&r!=="text")throw new l('"responseType" should be either "json" or "text".',{code:"INVALID_PARAMETER"})}let n=t.method||"POST",i=typeof n=="string"?n.toLowerCase():"",s=i==="get"||i==="delete"||i==="head"?"params":"data",o={url:t.url,method:n};if(t.secretName!==void 0&&(o.secretName=t.secretName),t.headers!==void 0&&(o.headers=t.headers),t.data!==void 0&&(o.data=t.data),t.params!==void 0&&(o.params=t.params),t.skapiHeaders!==void 0&&(o.skapiHeaders=t.skapiHeaders),t.service!==void 0&&(o.service=t.service),t.owner!==void 0&&(o.owner=t.owner),t.queue!==void 0&&(o.queue=t.queue),t.expires!==void 0&&(o.expires=t.expires),t.stream!==void 0&&(o.stream=t.stream),t.realtime!==void 0&&(o.realtime=t.realtime),t.poll!==void 0&&(o.poll=t.poll),t.onStream!==void 0&&(o.onStream=t.onStream),t.onResponse!==void 0&&(o.onResponse=t.onResponse),t.onError!==void 0&&(o.onError=t.onError),t.multipart){if(t.data!==void 0&&t.data!==null)throw new l('"data" cannot be sent with "multipart": true. The form itself is the body.',{code:"INVALID_PARAMETER"});let d=await ll(e);o.body_b64=d.body_b64,o.body_content_type=d.body_content_type;}else {let d=al(e);d&&Object.keys(d).length&&(o[s]=Object.assign({},d,o[s]||{}));}let a=Is.call(this,o,{signal:t.signal});return r?a.then(d=>{if(Es(d)||Fr(d))return d;if(r==="text")return typeof d=="string"?d:JSON.stringify(d);if(typeof d=="string")try{return JSON.parse(d)}catch{return d}return d}):a}async function ks(e){return Is.call(this,e,{requireSecretName:true})}async function Vr(e,t){await this.__connection;let r=e.service||this.service,n=e.owner||this.owner;e=y.Params(e,{url:"string",method:["GET","POST","PUT","PATCH","DELETE","HEAD"],queue:"string",status:["pending","running","resolved","failed"],compact:"boolean",queue_exact:"boolean",queue_exclude:"string"},["url","method"]);let i=!!this.__user,s=`[${e.method.toUpperCase()}]${e.url.toLowerCase()}#${r}:`,o={id:s,queue:e?.queue,status:e?.status,service:r,owner:n};e?.compact&&(o.compact=true),e?.queue_exact&&(o.queue_exact=true),e?.queue_exclude&&(o.queue_exclude=e.queue_exclude),Object.keys(o).forEach(d=>{o[d]||delete o[d];}),o.queue&&(o.id_prefix=o.id,delete o.id);let a=await k.bind(this)("csr-poll",o,{auth:i,fetchOptions:t});return a.list=a.list.map(d=>{let c={id:d.id,status_code:d.rslv?.status_code||null,response_body:d.rslv?.body||d.rslv?.truncated||null,error:d?.err,created:d?.stmp,updated:d?.utmp,executed:typeof d?.att=="number"?d.att*1e3:void 0,responded:typeof d?.rtmp=="number"?d.rtmp:void 0,request_body:d?.reqbdy,expires:d?.expt,status:d.stts,queue_name:d?.qid,request_text:d?.reqtxt,response_text:d?.rslvtxt,response_complete_marker:d?.rslvmk!=null?!!d.rslvmk:void 0,compact:d?.cmpct?true:void 0};for(let g in c)c[g]===void 0&&delete c[g];return (c.status==="running"||c.status==="pending")&&(c.poll=g=>Rs.call(this,{id:s+c.id,auth:i,service:r,owner:n,latency:g?.latency||1e3,queue:d?.qid,seedExecuted:c.executed,onResponse:g?.onResponse,onError:g?.onError,onStream:g?.onStream})),c}),a}async function jr(e){await this.__connection,e=y.Params(e,{url:"string",method:["GET","POST","PUT","PATCH","DELETE","HEAD"],id:"string",queue:"string"},["url","method","id"]);let t=e?.service||this.service,r=e?.owner||this.owner,n=!!this.__user,i=`[${e.method.toUpperCase()}]${e.url.toLowerCase()}#${t}`,s=e.id,o=`${i}:${s}`,a=e?.queue;return a&&he?.[a]&&(he[a].remove(lt[o]),delete lt[o]),k.bind(this)("csr-cancel",{id:o,service:t,owner:r},{auth:n})}function $r(e,t){let r=typeof t?.poll=="number"?t.poll:1e3;if(!Number.isFinite(r)||r<0)throw new l('"poll" should be a non-negative number.',{code:"INVALID_PARAMETER"});if(!e||typeof e!="string")throw new l('"requestId" should be type: <string>.',{code:"INVALID_PARAMETER"});if(t?.since!==void 0&&typeof t.since!="number")throw new l('"since" should be a number.',{code:"INVALID_PARAMETER"});if(t?.realtimeGroup!==void 0&&t.realtimeGroup!==null&&typeof t.realtimeGroup!="string")throw new l('"realtimeGroup" should be type: <string>.',{code:"INVALID_PARAMETER"});let n=typeof t?.since=="number"&&t.since>0?t.since:0,i=t?.onStream,s=t?.onResponse,o=t?.onError,a={stopped:false,fullId:e,resolve:null},d=null,c={stop:null,aborted:false},g=()=>{te[a.fullId]===c&&delete te[a.fullId];},f=()=>{a.stopped||(a.stopped=true,d&&d(),g(),a.resolve&&a.resolve(ct(a.fullId)));};c.stop=f;let u=new Promise(async(p,h)=>{a.resolve=p;try{await this.__connection;let m=!!this.__user,_=t?.service||this.service,b=t?.owner||this.owner;if(a.fullId=As(e,t?.url,t?.method,_),a.stopped){p(ct(a.fullId));return}te[a.fullId]=c;let A={seq:n},w=0,S=bs.call(this,a.fullId),E=i&&t?.realtimeGroup?ys(A,i,S.onTransport):null,N=E?_s.call(this,t.realtimeGroup,E):null,U=()=>{S.done(E),N&&N.stop(),E&&E.close();};for(d=U;;){let C=await k.bind(this)("csr-poll",{id:a.fullId,service:_,owner:b,since:A.seq},{auth:m});if(a.stopped)return;if(!Es(C)){U(),g(),s&&s(C),p(C);return}let v=E?E.fromPoll(C):hs(C,A,i);E&&E.open();let x=ws(C);if(C.more&&v){w=0;continue}if(w=C.more?w+1:0,!x&&(!C.more||w>=ps)){U(),g(),s&&s(C),p(C);return}if(await new Promise(O=>setTimeout(O,E&&E.warm()?Math.max(r,ms):r)),a.stopped)return}}catch(m){if(a.stopped)return;d&&d(),g(),o&&o(m),h(m);}});return Object.assign(u,{stop:f})}async function Br(e,t,r){await this.__connection;let n=r?.service||this.service,i=r?.owner||this.owner,s=!!this.__user,o=As(e,r?.url,r?.method,n);return k.bind(this)("csr-finalize",{id:o,data:t,service:n,owner:i},{auth:s})}var Ss=$r,vs=Br,Ns=Vr,Ds=jr,xs=jt,Us=qr;async function Cs(e){await this.__connection;let t={name:"string",email:r=>(y.Email(r),r),subject:"string",message:"string"};return e=y.Params(e,t,["name","email","subject","message"]),await k.bind(this)("send-inquiry",e),"SUCCESS: Inquiry has been sent."}async function Os(e,t){if(await this.__connection,tl&&e instanceof FormData||fs&&e instanceof HTMLFormElement||gs&&e instanceof SubmitEvent){if(!t)throw new l("Url string as a second argument is required when form is passed.",{code:"INVALID_PARAMETER"});let n=$(e);e={url:t,data:n.data,sync:true};}let r={url:n=>y.Url(n),data:n=>n,sync:["boolean",()=>true]};if(Array.isArray(e))for(let n of e)n=y.Params(n,r);else e=y.Params(e,r);return k.bind(this)("post-secure",e,{auth:true})}async function Ls(e,t){await this.__connection;let{auth:r=false,method:n="POST",bypassAwaitConnection:i=false,responseType:s,contentType:o,tokenHeaders:a,progress:d}=t||{};if(t=Object.assign({auth:r,method:n,bypassAwaitConnection:i,responseType:s,contentType:o,tokenHeaders:a},{fetchOptions:{progress:d}}),typeof e!="object"&&(o==="application/json"||o===void 0))throw new l('"data" should be type: <object>.',{code:"INVALID_PARAMETER"});return k.bind(this)("mock",e,t)}async function Ms(e,t){await this.__connection,e=y.Params(e||{},{access_group:n=>{if(n==="authorized"&&(n=1),n==="public"&&(n=0),typeof n!="number")throw new l('"access_group" should be type number.',{code:"INVALID_PARAMETER"});if(n<0)throw new l('"access_group" should be zero or a positive number.',{code:"INVALID_PARAMETER"});if(n>this.__user.access_group)throw new l("User has no access.",{code:"INVALID_REQUEST"});return n}});let r=await k.bind(this)("get-feed",e,{auth:true,fetchOptions:t});return Array.isArray(r?.list)&&(r.list=await Promise.all(r.list.map(n=>ke.bind(this)(n)))),r}function ut(e){if(e===this.__user.user_id)throw new l(`"user_id" cannot be the user's own ID.`,{code:"INVALID_PARAMETER"});return y.UserId(e,'"user_id"')}async function Fs(e,t){if(e=$(e,{ignoreEmpty:true}).data,e=y.Params(e,{subscriber:n=>y.UserId(n,'User ID in "subscriber"'),subscription:ut.bind(this),blocked:"boolean"}),!e.subscriber&&!e.subscription)throw new l('At least either "subscriber" or "subscription" should have a value.',{code:"INVALID_PARAMETER"});let r=await k.bind(this)("get-subscription",e,Object.assign({auth:true},{fetchOptions:t}));return r.list=r.list.map((n=>{let i={};if(n.sub){let s=n.sub.split("#");i.subscriber=s[2],i.subscription=s[0];}else i.subscriber=n.subscriber,i.subscription=n.subscription;return i.timestamp=n?.timestamp||n.stmp,i.blocked=n?.blocked||n.grp.substring(0,1)==="N",Object.assign(i,n.opt),i})),r}async function qs(e){await this.__connection,e=y.Params(e,{user_id:ut.bind(this),get_feed:"boolean",get_notified:"boolean",get_email:i=>{if(i&&(!this.__user.email||!this.__user.email_verified))throw new l("User has no verified email address.",{code:"INVALID_REQUEST"});return !!i}},["user_id"]);let t={};for(let i of ["get_feed","get_notified","get_email"])typeof e[i]=="boolean"&&(t[i]=e[i]);let r=await k.bind(this)("subscription",{subscribe:e.user_id,option:t},{auth:true}),n={};if(r.sub){let i=r.sub.split("#");n.subscriber=i[2],n.subscription=i[0];}else n.subscriber=r.subscriber,n.subscription=r.subscription;return n.timestamp=r?.timestamp||r.stmp,n.blocked=r?.blocked||r.grp.substring(0,1)==="N",Object.assign(n,r.opt),n}async function Vs(e){await this.__connection;let{user_id:t}=y.Params(e,{user_id:ut.bind(this)},["user_id"]);return await k.bind(this)("subscription",{unsubscribe:t},{auth:true})}async function js(e){await this.__connection;let{user_id:t}=y.Params(e,{user_id:ut.bind(this)},["user_id"]);return await k.bind(this)("subscription",{block:t},{auth:true})}async function $s(e){await this.__connection;let{user_id:t}=y.Params(e,{user_id:ut.bind(this)},["user_id"]);return await k.bind(this)("subscription",{unblock:t},{auth:true})}async function Bs(e,t){await this.__connection;let r=await Q.bind(this)();if(e=y.Params(e||{},{user_id:o=>{if(o!==this.__user.user_id&&!r)throw new l("No access.",{code:"INVALID_REQUEST"});return o},group:o=>y.newsletterGroup(o,{allowNull:true}),email:o=>{if(typeof o!="string"||!o.trim())throw new l('"email" should be a non-empty string.',{code:"INVALID_PARAMETER"});if(o.trim().length>255)throw new l('"email" should be at most 255 characters.',{code:"INVALID_PARAMETER"});return o.trim().toLowerCase()}}),e.email!==void 0){if(e.user_id!==void 0&&e.user_id!==null)throw new l('"email" cannot be used with "user_id".',{code:"INVALID_PARAMETER"});if(e.group===void 0||e.group===null)throw new l('"group" is required to search by "email".',{code:"INVALID_PARAMETER"})}let n=await k.bind(this)("get-newsletter-subscription",e,{auth:true,fetchOptions:t||null}),i=n?.list||n,s=[];Array.isArray(i)||(i=[]);for(let o of i){let a=o.subt.split("#"),d=true;a[0].charAt(0)==="@"&&(d=false,a[0]=a[0].substring(1));let c=/^\d+$/.test(a[0])?parseInt(a[0]):a[0],g={timestamp:o.stmp,group:c,subscribed_email:a[1],active:d};typeof o.email_token=="string"&&o.email_token&&(g.subscriber_token=o.email_token),s.push(g);}return n?.list?(n.list=s,n):s}async function Ks(e){await this.__connection;let t=y.Params(e||{},{email:r=>Array.isArray(r)&&r.length>0?r.length===1?y.Email(r[0]):r.map(n=>y.Email(n)):y.Email(r),group:r=>y.newsletterGroup(r),redirect:r=>y.Url(r)},this.__user?["group"]:["email","group"]);return k.bind(this)(`subscribe-${this.__user?"":"public-"}newsletter`,t,{auth:!!this.__user})}async function Hs(e){await this.__connection;let t=y.Params(e||{},{group:r=>y.newsletterGroup(r,{nameOnly:true}),restriction:r=>{if(typeof r!="number"||!Number.isInteger(r)||r<0||r>99)throw new l('"restriction" should be a number between 0 and 99.',{code:"INVALID_PARAMETER"});return r},name:r=>{if(typeof r!="string"||r.length>60)throw new l('"name" should be a string of 60 characters or less.',{code:"INVALID_PARAMETER"});return r}},["group"]);return k.bind(this)("register-newsletter-group",t,{auth:true})}async function Gs(e){await this.__connection;let t=y.Params(e||{},{group:r=>y.newsletterGroup(r,{nameOnly:true})},["group"]);return k.bind(this)("delete-newsletter-group",t,{auth:true})}async function Ws(){return await this.__connection,k.bind(this)("newsletter-group-endpoint",null,{auth:true})}async function Qs(e){await this.__connection,e=y.Params(e,{group:r=>y.newsletterGroup(r,{allowNull:true})},["group"]);let t=Object.assign({action:"unsubscribe"},e);return k.bind(this)("subscribe-newsletter",t,{auth:true})}async function zs(e,t){let r=await Q.bind(this)(),n={message_id:"string",timestamp:"number",read:"number",complaint:"number",subject:"string",bounced:"number"};e||(t=Object.assign({ascending:false},t||{})),e=$(e).data,e=e||{searchFor:"timestamp",value:Date.now(),condition:"<",group:"public"},e=y.Params(e,{searchFor:["message_id","timestamp","subject","complaint","read","bounced"],value:d=>{if(typeof d!==n[e.searchFor])throw new l(`"value" type does not match the type of "${e.searchFor}" index.`,{code:"INVALID_PARAMETER"});if(typeof d=="string"&&!d)throw new l('"value" should not be empty string.',{code:"INVALID_PARAMETER"});return d},range:d=>{if(!e.hasOwnProperty("value")||typeof d!=typeof e.value)throw new l('"range" should match type of "value".',{code:"INVALID_PARAMETER"});return d},condition:[">",">=","=","<","<=","gt","gte","eq","lt","lte",()=>"="],group:d=>{let c=y.newsletterGroup(d);if(c===0)return 0;if(typeof c=="string")return c;if(!this.session)throw new l("User should be logged in.",{code:"INVALID_REQUEST"});if(d==="authorized")return 1;if(!r&&c>parseInt(this.user?.access_group||this.session?.idToken?.payload?.access_group))throw new l("User has no access.",{code:"INVALID_REQUEST"});return c}},["searchFor","value","group"]);let i=e.group===0||typeof e.group=="string"&&!this.__user?"get-public-newsletters":"get-newsletters",s=await k.bind(this)(i,e,Object.assign({method:"get",auth:i==="get-public-newsletters"?!!this.__user:true},{fetchOptions:t})),o={message_id:"mid",timestamp:"stmp",complaint:"cmpl",read:"read",subject:"subj",bounced:"bnce",url:"url",delivered:"delv",group:"grp",dry:"dry",sent:"sent"},a={message_id:"",timestamp:0,complaint:0,read:0,subject:"",bounced:"",url:"",delivered:0,group:e.group,dry:false,sent:0};return s.list=s.list.map(d=>{let c={};for(let g in o)c[g]=d[o[g]]||a[g];return c.bounced=String(c.bounced),c.dry=!!c.dry,c.sent||delete c.sent,c}),s}var $e="skapi:project_id";function Js(e){let t=e.trim().toLowerCase().replace(/^<|>$/g,"").replace(/[\s_\-.]+/g,"");return t==="serviceid"||t==="projectid"}function Ys(){try{return window.sessionStorage.getItem($e)||null}catch{return null}}function Xs(e){try{window.sessionStorage.setItem($e,e);}catch{}}function $t(e){try{window.sessionStorage.getItem($e)===e&&window.sessionStorage.removeItem($e);}catch{}}function Zs(){if(H())return typeof window.prompt=="function";let e=ve("tty");return !!(e&&ve("readline")&&e.isatty(0)&&e.isatty(2))}function eo(){return new l("Project ID is required.",{code:"INVALID_PARAMETER"})}var dt=null;function to(e,t){if(!dt){dt=H()?dl(e,t):fl(e,t);let r=()=>{dt=null;};dt.then(r,r);}return dt}async function dl(e,t){await new Promise(o=>setTimeout(o,0));let r=`new Skapi() was given the placeholder "${e}" instead of your Project ID.`,n=`Enter your Project ID to continue. This browser tab remembers it until the tab is closed. To stop being asked, replace "${e}" in your code with the ID.`,i=`${r}
|
|
216
216
|
|
|
217
217
|
${n}`,s="";for(;;){let o=window.prompt(i,s);if(o===null)throw eo();if(s=o.trim(),!s){i=`${r}
|
|
218
218
|
|
|
@@ -224,7 +224,7 @@ ${n}`;}}}function fl(e,t){let r=globalThis.process,n=ve("readline");return new P
|
|
|
224
224
|
This process remembers the ID until it exits. To stop being asked, replace "${e}" in your code with the ID.
|
|
225
225
|
`),d();})}async function ro(e){let t=y.Params(e,{user_id:n=>y.UserId(n,'"user_id"')},["user_id"]);if(t?.service&&t?.owner?t={service:t?.service,owner:t?.owner,block:t.user_id}:t={block:t.user_id},!await Q.bind(this)()){if(!this.__user)throw new l("User needs to login.",{code:"INVALID_REQUEST"});if(this.__user.access_group<90)throw new l("Invalid access.",{code:"INVALID_REQUEST"})}return await k.bind(this)("block-account",t,{auth:true})}async function no(e){let t=y.Params(e,{user_id:n=>y.UserId(n,'"user_id"')},["user_id"]);if(t?.service&&t?.owner?t={service:t?.service,owner:t?.owner,unblock:t.user_id}:t={unblock:t.user_id},!await Q.bind(this)()){if(!this.__user)throw new l("User needs to login.",{code:"INVALID_REQUEST"});if(this.__user.access_group<90)throw new l("Invalid access.",{code:"INVALID_REQUEST"})}return await k.bind(this)("block-account",t,{auth:true})}async function io(e){let t=y.Params(e,{user_id:n=>y.UserId(n,'"user_id"')},["user_id"]);if(t?.service&&t?.owner?t={service:t?.service,owner:t?.owner,delete:t.user_id}:t={delete:t.user_id},!await Q.bind(this)()){if(!this.__user)throw new l("User needs to login.",{code:"INVALID_REQUEST"});if(this.__user.access_group<90)throw new l("Invalid access.",{code:"INVALID_REQUEST"})}return await k.bind(this)("remove-account",t,{auth:true})}async function so(e,t){let r={email:s=>y.Email(s),password:s=>y.Password(s),name:"string",username:"string",gender:"string",address:s=>{if(!s)return "";if(typeof s=="string")return s;if(typeof s=="object")return JSON.stringify(s)},birthdate:s=>y.Birthdate(s),phone_number:s=>y.PhoneNumber(s),picture:s=>{if(s)return y.Url(s)},profile:s=>{if(s)return y.Url(s)},website:s=>{if(s)return y.Url(s)},nickname:"string",misc:"string",email_public:["boolean",()=>false],gender_public:["boolean",()=>false],address_public:["boolean",()=>false],birthdate_public:["boolean",()=>false],phone_number_public:["boolean",()=>false],openid_id:"string",access_group:s=>{try{typeof s=="string"&&(s=s==="admin"?99:parseInt(s));}catch{throw new l('"access_group" is invalid. Should be type <number>.',{code:"INVALID_PARAMETER"})}if(typeof s!="number"||s<1||s>100)throw new l('"access_group" is invalid. Should be type <number> of range 1~99',{code:"INVALID_PARAMETER"});return s}},n=y.Params(e,r,["email"]);if(t=y.Params(t,{confirmation_url:s=>{let o=s;if(typeof s=="string")o=y.Url(s);else throw new l('"options.confirmation_url" should be type: <string>.',{code:"INVALID_PARAMETER"});if(o&&!n.email)throw new l('"email" is required for signup confirmation.',{code:"INVALID_PARAMETER"});return o},email_subscription:s=>{if(typeof s!="boolean")throw new l('"options.email_subscription" should be type: <boolean>.',{code:"INVALID_PARAMETER"});if(!t?.confirmation_url)throw new l('"options.confirmation_url" is required for email subscription.',{code:"INVALID_PARAMETER"});return s},template:s=>{if(typeof s!="object"||!s.url||!s.subject)throw new l('"options.template" should be type: <object> with "url" and "subject".',{code:"INVALID_PARAMETER"});return {url:y.Url(s.url),subject:s.subject}}}),n.signup_confirmation=t?.confirmation_url||true,n.email_subscription=t?.email_subscription||false,n.template=t?.template||{},!await Q.bind(this)()){if(!this.__user)throw new l("User needs to login.",{code:"INVALID_REQUEST"});if(this.__user.access_group<90)throw new l("Invalid access.",{code:"INVALID_REQUEST"})}return await k.bind(this)("admin-signup",n,{auth:true})}async function oo(e){let t={email:s=>y.Email(s),password:s=>y.Password(s),openid_id:"string",name:"string",username:"string",gender:"string",address:s=>{if(!s)return "";if(typeof s=="string")return s;if(typeof s=="object")return JSON.stringify(s)},birthdate:s=>y.Birthdate(s),phone_number:s=>y.PhoneNumber(s),picture:s=>s?y.Url(s):"",profile:s=>s?y.Url(s):"",website:s=>s?y.Url(s):"",nickname:"string",misc:"string",email_public:["boolean",()=>false],gender_public:["boolean",()=>false],address_public:["boolean",()=>false],birthdate_public:["boolean",()=>false],phone_number_public:["boolean",()=>false],access_group:s=>{try{typeof s=="string"&&(s=parseInt(s));}catch{throw new l('"access_group" is invalid. Should be type <number>.',{code:"INVALID_PARAMETER"})}if(typeof s!="number"||s<1||s>100)throw new l('"access_group" is invalid. Should be type <number> of range 1~99',{code:"INVALID_PARAMETER"});return s}},r=["email","password"],n=y.Params(e,t,r);if(!await Q.bind(this)()){if(!this.__user)throw new l("User needs to login.",{code:"INVALID_REQUEST"});if(this.__user.access_group<90)throw new l("Invalid access.",{code:"INVALID_REQUEST"})}return await k.bind(this)("admin-signup",n,{auth:true})}async function ao(e){if(e=y.Params(e,{user_id:r=>y.UserId(r,'"user_id"'),access_group:r=>{try{typeof r=="string"&&(r=parseInt(r));}catch{throw new l('"access_group" is invalid. Should be type <number>.',{code:"INVALID_PARAMETER"})}if(typeof r=="number"&&r>0&&r<100)return r;throw new l('"access_group" is invalid. Should be type <number> of range 1~99',{code:"INVALID_PARAMETER"})}},["user_id","access_group"]),!await Q.bind(this)()){if(!this.__user)throw new l("User needs to login.",{code:"INVALID_REQUEST"});if(this.__user.access_group<90)throw new l("Invalid access.",{code:"INVALID_REQUEST"})}return await k.bind(this)("grant-access",e,{auth:true})}async function lo(e,t){if(e=y.Params(e,{email:"string"}),!await Q.bind(this)()){if(!this.__user)throw new l("User needs to login.",{code:"INVALID_REQUEST"});if(this.__user.access_group<90)throw new l("Invalid access.",{code:"INVALID_REQUEST"})}let n=await k.bind(this)("invitation-list",Object.assign({mode:"search"},e),{fetchOptions:t,auth:true});return n.list=n.list.map(i=>Ke(i.user)),n}async function co(e){if(e=y.Params(e,{email:r=>y.Email(r)},["email"]),!await Q.bind(this)()){if(!this.__user)throw new l("User needs to login.",{code:"INVALID_REQUEST"});if(this.__user.access_group<90)throw new l("Invalid access.",{code:"INVALID_REQUEST"})}return await k.bind(this)("invitation-list",Object.assign({mode:"cancel"},e),{auth:true})}async function uo(e){if(e=y.Params(e,{email:r=>y.Email(r)},["email"]),!await Q.bind(this)()){if(!this.__user)throw new l("User needs to login.",{code:"INVALID_REQUEST"});if(this.__user.access_group<90)throw new l("Invalid access.",{code:"INVALID_REQUEST"})}return await k.bind(this)("invitation-list",Object.assign({mode:"resend"},e),{auth:true})}async function fo(e){let t=y.Params(e,{user_id:o=>y.UserId(o,'"user_id"'),email:o=>y.Email(o),address:o=>{if(!o)return "";if(typeof o=="string")return o;if(typeof o=="object")return JSON.stringify(o)},name:"string",gender:"string",birthdate:o=>o?y.Birthdate(o):"",phone_number:o=>o?y.PhoneNumber(o):"",email_public:"boolean",phone_number_public:"boolean",address_public:"boolean",gender_public:"boolean",birthdate_public:"boolean",misc:"string",picture:o=>o?y.Url(o):"",profile:o=>o?y.Url(o):"",nickname:"string",website:o=>o?y.Url(o):""},["user_id"]),r=t.service,n=t.owner;if(delete t.service,delete t.owner,await this.__connection,this.__user?.user_id&&t.user_id===this.__user.user_id)throw new l("Cannot modify attributes of the current user.",{code:"INVALID_REQUEST"});if(Object.keys(t).filter(o=>o!=="user_id"&&t[o]!==void 0).length===0)throw new l("At least one attribute to update is required.",{code:"INVALID_PARAMETER"});if(!await Q.bind(this)()){if(!this.__user)throw new l("User needs to login.",{code:"INVALID_REQUEST"});if(this.__user.access_group<90)throw new l("Invalid access.",{code:"INVALID_REQUEST"})}let s={attributes:t};return r&&n&&(s.service=r,s.owner=n),await k.bind(this)("admin-edit-profile",s,{auth:true})}async function go(e){if(typeof window>"u"||window._runningInNodeJS)throw new l("Push Notifications are not supported in Node.js environment.",{code:"NOT_SUPPORTED"});if(await this.__connection,!e.endpoint)throw new l("Missing parameter: endpoint",{code:"INVALID_PARAMETER"});if(!e.keys||!e.keys.p256dh||!e.keys.auth)throw new l("Missing parameter: keys.p256dh or keys.auth",{code:"INVALID_PARAMETER"});return await k.bind(this)("store-subscription",{endpoint:e.endpoint,keys:e.keys},{auth:true}),"SUCCESS: Subscribed to receive notifications."}async function po(e){if(typeof window>"u"||window._runningInNodeJS)throw new l("Push Notifications are not supported in Node.js environment.",{code:"NOT_SUPPORTED"});if(await this.__connection,!e.endpoint)throw new l("Missing parameter: endpoint",{code:"INVALID_PARAMETER"});if(!e.keys||!e.keys.p256dh||!e.keys.auth)throw new l("Missing parameter: keys.p256dh or keys.auth",{code:"INVALID_PARAMETER"});return await k.bind(this)("delete-subscription",{endpoint:e.endpoint,keys:e.keys},{auth:true}),"SUCCESS: Unsubscribed from notifications."}async function ho(){if(typeof window>"u"||window._runningInNodeJS)throw new l("Push Notifications are not supported in Node.js environment.",{code:"NOT_SUPPORTED"});return await this.__connection,{VAPIDPublicKey:await k.bind(this)("get-vapid-public-key",null,{auth:true})}}async function mo(e,t){if(typeof window>"u"||window._runningInNodeJS)throw new l("Push Notifications are not supported in Node.js environment.",{code:"NOT_SUPPORTED"});await this.__connection;let{title:r,body:n}=$(e||{},{nullIfEmpty:true}).data;if(!r)throw new l("Missing parameter: message title",{code:"INVALID_PARAMETER"});if(!n)throw new l("Missing parameter: message body",{code:"INVALID_PARAMETER"});let i={title:r,body:n};return t?(typeof t=="string"&&(t=[t]),i.user_ids=t):i.user_ids="all_users",await k.bind(this)("push-notification",i,{auth:true}),"SUCCESS: Notification sent."}async function yo(e){await this.__connection,e=y.Params(e,{spell:"string",name:"string",magic:r=>r},["spell","name"]);await k.bind(this)("castspell",e);return `The spell "${e.spell}" has been cast.`}async function bo(e){return await this.__connection,e=y.Params(e||{},{search:["spell","name",()=>"spell"],value:"string"}),await k.bind(this)("getspell",e)}async function _o(e){await this.__connection,e=y.Params(e,{message:"string",name:"string"},["message","name"]);let t=await k.bind(this)("dopamine",e,{auth:true}),r=t?.previous_message?.message,n=t?.previous_message?.name;if(H())r&&n&&window.alert(`${n} said: ${r}`),window.location.href=t.video;else return r&&n?`${n} said: ${r}
|
|
226
226
|
Watch the video here: ${t.video}`:`Your message has been uploaded for future generations to receive.
|
|
227
|
-
Watch the video here: ${t.video}`}var T=class{constructor(t,r,n,i){this.__version="2.2.6-beta.
|
|
227
|
+
Watch the video here: ${t.video}`}var T=class{constructor(t,r,n,i){this.__version="2.2.6-beta.1";this.project_id="";this.session=null;this.connection=null;this.__my_unique_ids={};this.__uniqueIdsPersistTimer=null;this.userPool=null;this.__socket=null;this.__mediaStream=null;this.host="skapi";this.hostDomain="skapi.com";this.target_cdn="d3e9syvbtso631";this.customApiDomain="skapi.dev";this.requestBatchSize=50;this.__disabledAccount=null;this.__cached_requests={};this.__startKeyHistory={};this.__request_signup_confirmation=null;this.__private_access_key={};this.__class_properties_has_been_cached=false;this.__user=null;this._userProfileListeners=[];this._onLoginListeners=[];this._onBatchProcessListeners=[];this.validate={userId(t){try{return y.UserId(t),!0}catch{return false}},url(t){try{return y.Url(t),!0}catch{return false}},phoneNumber(t){try{return y.PhoneNumber(t),!0}catch{return false}},birthdate(t){try{return y.Birthdate(t),!0}catch{return false}},email(t){try{return y.Email(t),!0}catch{return false}},params(t,r,n){return y.Params(t,r,n)}};this.util={MD5:Z,generateRandom:Te,toBase62:Xr,fromBase62:se,decodeProjectId:Jt,formatServiceId:Yt,extractFormData:$,terminatePendingRequests:Pi,request:(t,r,n)=>k.bind(this)(t,r,n,{ignoreService:true})};this.__projectIdInput=null;this.__network_logs=false;this.__endpoint_version="v2";this.__public_identifier="";this.bearerToken="";this.registerTicket=si.bind(this);this.unregisterTicket=oi.bind(this);if(!t||typeof t!="string")throw this._alert("Service ID is required."),new l("Service ID is required.",{code:"INVALID_PARAMETER"});if(Js(t)){let o=Ys(),a=null;if(o)try{a=this._resolveProject(o,r,n,i);}catch{$t(o);}if(a)H()&&console.info(`Skapi: "${t}" was replaced with the Project ID entered earlier in this tab (${o}). It is kept in sessionStorage under "${$e}"; delete that entry to enter a different one.`),this._start(a),this.__connection.catch(()=>$t(o));else if(Zs())this._startAfterProjectIdInput(t,r,n,i);else throw this._alert(`Replace "${t}" with your actual Project ID.`),new l("Project ID is required.",{code:"INVALID_PARAMETER"});return}let s;try{s=this._resolveProject(t,r,n,i);}catch(o){throw this._alert(o.message),o}this._start(s);}get user(){return this.__user&&Object.keys(this.__user).length?JSON.parse(JSON.stringify(this.__user)):null}set user(t){}get onLogin(){return this._onLoginListeners}set onLogin(t){typeof t=="function"&&this._onLoginListeners.push(t);}get onUserUpdate(){return this._userProfileListeners}set onUserUpdate(t){typeof t=="function"&&this._userProfileListeners.push(t);}_runOnUserUpdateListeners(t){for(let r of this._userProfileListeners)typeof r=="function"&&r(t);}_runOnLoginListeners(t){for(let r of this._onLoginListeners)typeof r=="function"&&r(t);}get onBatchProcess(){return this._onBatchProcessListeners}set onBatchProcess(t){typeof t=="function"&&this._onBatchProcessListeners.push(t);}_alert(t){H()&&typeof window.alert=="function"&&window.alert(t);}_resolveProject(t,r,n,i){let s=t.split("-").length;if(s===2||s===7)try{let d=Jt(t);n&&typeof n=="object"&&(i=n),r&&typeof r=="object"&&(n=r),r=d.owner,t=d.service;}catch{throw new l("Service ID is invalid.",{code:"INVALID_PARAMETER"})}if(!r||typeof r!="string")throw new l("Owner ID is invalid.",{code:"INVALID_PARAMETER"});if(r!==this.host)try{y.UserId(r,'"owner"');}catch{throw new l("Owner ID is invalid.",{code:"INVALID_PARAMETER"})}return {service:t,owner:r,options:n,__etc:i}}_startAfterProjectIdInput(t,r,n,i){let s=to(t,o=>{this._resolveProject(o,r,n,i);}).then(o=>{Xs(o),this._start(this._resolveProject(o,r,n,i)),this.__connection.catch(()=>$t(o));});this.__projectIdInput=s,this.admin_endpoint=s.then(()=>this.admin_endpoint),this.record_endpoint=s.then(()=>this.record_endpoint),this.__authConnection=s.then(()=>this.__authConnection),this.__connection=s.then(()=>this.__connection);for(let o of [s,this.admin_endpoint,this.record_endpoint,this.__authConnection,this.__connection])o.catch(()=>{});}_start({service:t,owner:r,options:n,__etc:i}){this.service=t,this.owner=r;try{this.project_id=Yt(t,r);}catch{this.project_id="";}let s=true,o=false,a=null;if(n&&(typeof n.refetchServiceInfo=="boolean"&&(o=n.refetchServiceInfo),typeof n.autoLogin=="boolean"&&(s=n.autoLogin),n.encryption&&(a=An(n.encryption)),typeof n.requestBatchSize=="number")){if(n.requestBatchSize<1)throw new l('"requestBatchSize" must be greater than 0.',{code:"INVALID_PARAMETER"});this.requestBatchSize=n.requestBatchSize;}n?.eventListener&&typeof n.eventListener=="object"&&(n.eventListener?.onLogin&&typeof n.eventListener.onLogin=="function"&&(this.onLogin=n.eventListener.onLogin),n.eventListener?.onUserUpdate&&typeof n.eventListener.onUserUpdate=="function"&&(this.onUserUpdate=n.eventListener.onUserUpdate),n.eventListener?.onBatchProcess&&typeof n.eventListener.onBatchProcess=="function"&&(this.onBatchProcess=n.eventListener.onBatchProcess)),this.target_cdn=i?.target_cdn||this.target_cdn,this.hostDomain=i?.hostDomain||this.hostDomain,this.customApiDomain=i?.customApiDomain||this.customApiDomain,this.__network_logs=!!i?.network_logs;let d=`https://${this.target_cdn}.cloudfront.net`,c=t.substring(0,4);this.admin_endpoint=fetch(`${d}/${c}/admin-${this.__endpoint_version}.json`).then(h=>h.blob()).then(h=>new Promise((m,_)=>{let b=new FileReader;b.onloadend=()=>m(b.result),b.onerror=_,b.readAsDataURL(h);})).then(h=>{try{return typeof h=="string"?JSON.parse(atob(h.split(",")[1])):null}catch{throw new l("Service does not exist. Create your service from skapi.com",{code:"NOT_EXISTS"})}}),this.record_endpoint=fetch(`${d}/${c}/record-${this.__endpoint_version}.json`).then(h=>h.blob()).then(h=>new Promise((m,_)=>{let b=new FileReader;b.onloadend=()=>m(b.result),b.onerror=_,b.readAsDataURL(h);})).then(h=>{try{return typeof h=="string"?JSON.parse(atob(h.split(",")[1])):null}catch{throw new l("Service does not exist. Create your service from skapi.com",{code:"NOT_EXISTS"})}});let g=H();if(g&&!window.sessionStorage)throw this._alert("This browser is not supported."),new Error("This browser is not supported.");let f=g?JSON.parse(window.sessionStorage.getItem(`${t}#${r}`)||"null"):null;if(this.log("constructor:restore",f),f?.connection){for(let h in f)this[h]=f[h];f.__public_identifier||(this.__public_identifier=`${this.service}:${this.owner}:${Te(16)}`);}Rn.bind(this)(a),this.__authConnection=(async()=>{let h=await this.admin_endpoint,m={UserPoolId:h.userpool_id,ClientId:h.userpool_client};zt()&&(m.Storage=window.localStorage),this.userPool=new amazonCognitoIdentityJs.CognitoUserPool(m);try{this.user||await W.bind(this)().getSession({skipUserUpdateEventTrigger:!0}),this.user&&(!f?.connection&&!s?be.bind(this)():(a&&$n.bind(this)(),this._runOnLoginListeners(this.user),this._runOnUserUpdateListeners(this.user)));}catch{}})();let u=`${this.service}/${this.owner}`,p=g?window.sessionStorage.getItem(`${u}:uniqueids`):null;if(p)try{let h=JSON.parse(p);this.__my_unique_ids=h&&typeof h=="object"&&!Array.isArray(h)?{[u]:h}:{};}catch{this.__my_unique_ids={};}this.__connection=(async()=>{let h=null;await this.record_endpoint,f?.connection||(h=this._updateConnection({refresh:o}));let m=()=>{if(this.__class_properties_has_been_cached)return;let _=()=>{let b={},A=["__startKeyHistory","__disabledAccount","__cached_requests","__request_signup_confirmation","__public_identifier","connection"];if(this.connection){for(let w of A)b[w]=this[w];if(a&&(b.__cached_requests={},b.__startKeyHistory={}),g){let w=`${t}#${r}`;try{window.sessionStorage.setItem(w,JSON.stringify(b));}catch{try{let E=Object.assign({},b,{__cached_requests:{},__startKeyHistory:{}});window.sessionStorage.setItem(w,JSON.stringify(E));}catch{try{window.sessionStorage.removeItem(w);}catch{}}}}this.__class_properties_has_been_cached=true;}};return h instanceof Promise?h.then(()=>_()):_()};return g&&(window.addEventListener("beforeunload",()=>{this.closeRealtime(),m();}),window.addEventListener("visibilitychange",()=>{m();})),await h,await this.__authConnection,this.connection})(),this.__connection.then(h=>{((h?.group||0)<3||this.__network_logs)&&this.version();}).catch(()=>{});}async getConnectionInfo(t){t?.refresh&&(this.__connection instanceof Promise&&await this.__connection,this.__connection=this._updateConnection({refresh:true}));let n=await this.__connection,i=n?.user_agent||(H()&&typeof window.navigator?.userAgent=="string"?window.navigator.userAgent:`skapi-node/${globalThis?.process?.versions?.node||"unknown"}`);return {project_id:this.project_id,user_ip:n.ip,user_agent:i,user_location:n.locale,service_name:n.service_name,version:this.__version,service_description:n?.service_description||"",ai_agent:n?.ai_agent||"",conf:n?.opt}}async _updateConnection(t){let r=t?.refresh||false;try{this.connection=await k.bind(this)("service",{service:this.service,owner:this.owner,refresh:r},{bypassAwaitConnection:!0,method:"get"});}catch(n){throw this.log("connection fail",n),this._alert("Service is not available: "+(n.message||n.toString())),this.connection=null,n}return this.connection}async version(){if(await this.__connection,H()){let r=`Built with:
|
|
228
228
|
%c\r
|
|
229
229
|
##\\ ##\\ \r
|
|
230
230
|
## | \\__|\r
|