@based/client
Advanced tools
Comparing version 3.0.0 to 3.0.1
@@ -189,3 +189,2 @@ "use strict"; | ||
if (type === types_1.RequestTypes.Token) { | ||
console.info(err); | ||
this.retryingRenewToken = false; | ||
@@ -192,0 +191,0 @@ // means stomething got de-auth wrong |
@@ -15,2 +15,2 @@ var nt=Object.create;var D=Object.defineProperty,ot=Object.defineProperties,at=Object.getOwnPropertyDescriptor,ct=Object.getOwnPropertyDescriptors,ut=Object.getOwnPropertyNames,_=Object.getOwnPropertySymbols,lt=Object.getPrototypeOf,ae=Object.prototype.hasOwnProperty,Pe=Object.prototype.propertyIsEnumerable;var Ce=(t,s,e)=>s in t?D(t,s,{enumerable:!0,configurable:!0,writable:!0,value:e}):t[s]=e,G=(t,s)=>{for(var e in s||(s={}))ae.call(s,e)&&Ce(t,e,s[e]);if(_)for(var e of _(s))Pe.call(s,e)&&Ce(t,e,s[e]);return t},J=(t,s)=>ot(t,ct(s));var qe=(t,s)=>{var e={};for(var r in t)ae.call(t,r)&&s.indexOf(r)<0&&(e[r]=t[r]);if(t!=null&&_)for(var r of _(t))s.indexOf(r)<0&&Pe.call(t,r)&&(e[r]=t[r]);return e};var Re=(t,s)=>{for(var e in s)D(t,e,{get:s[e],enumerable:!0})},z=(t,s,e,r)=>{if(s&&typeof s=="object"||typeof s=="function")for(let i of ut(s))!ae.call(t,i)&&i!==e&&D(t,i,{get:()=>s[i],enumerable:!(r=at(s,i))||r.enumerable});return t},p=(t,s,e)=>(z(t,s,"default"),e&&z(e,s,"default")),K=(t,s,e)=>(e=t!=null?nt(lt(t)):{},z(s||!t||!t.__esModule?D(e,"default",{value:t,enumerable:!0}):e,t)),dt=t=>z(D({},"__esModule",{value:!0}),t);var m={};Re(m,{Based:()=>ne,BasedClient:()=>x,BasedGraphQL:()=>T.BasedGraphQL,Observable:()=>C,addGetSubscriber:()=>V,addRequest:()=>y,addSubscriber:()=>I,createGraphqlOperations:()=>T.createOperations,default:()=>wt,generateSubscriptionId:()=>P,generateTrackingKey:()=>ye,handleGraphqlVariables:()=>T.handleGraphqlVariables,parseGraphql:()=>T.parseGraphql,removeSubscriber:()=>v});module.exports=dt(m);var ce=class{constructor(){this.listeners={};Object.defineProperty(this,"listeners",{enumerable:!1,writable:!0})}emit(s,e){this.listeners[s]&&this.listeners[s].forEach(r=>r(e))}on(s,e){this.listeners[s]||(this.listeners[s]=[]),this.listeners[s].push(e)}removeAllListeners(){this.listeners={}}once(s,e){this.on(s,r=>{e(r),this.removeListener(s,e)})}removeListener(s,e){let r=this.listeners[s];if(r){if(!e)delete this.listeners[s];else for(let i=0,n=r.length;i<n;i++)if(r[i]===e){r.splice(i,1);break}}}},Be=ce;var Ie=(t,s)=>{typeof t=="function"?t().then(e=>{s(e)}):s(t)};var Fe=K(require("isomorphic-ws")),j=new Map,Ee;typeof window!="undefined"&&document.addEventListener("visibilitychange",function(){clearTimeout(Ee),document.hidden?Ee=setTimeout(()=>{j.forEach(t=>{t(!1)})},3e4):j.forEach(t=>{t(!0)})});var ue=(t,s,e={destroy:()=>{j.delete(e)}},r=0,i=!1)=>(Ie(s,n=>{setTimeout(()=>{if(e.disconnected)return;let o=!0;j.set(e,a=>{e.disconnected||(!a&&o?(console.warn("Send to background - close connection"),o=!1,t.onClose(),c.close()):!o&&a&&(j.delete(e),ue(t,s,e,0,!0)))});let c=e.ws=new Fe.default(n);c.onerror=()=>{},c.onmessage=a=>t.onData(a),c.onopen=()=>{if(o){if(e.disconnected)return;r=100,i&&t.onReconnect(),t.onOpen()}},c.onclose=()=>{if(o){if(e.disconnected)return;t.onClose(),ue(t,s,e,Math.min(1250,Math.min(r+500)),!0)}}},r)}),e),le=ue;var k=require("@based/types");var F=require("@based/types");var $=require("@based/types");var pt=t=>{clearTimeout(t.idlePing),t.idlePing=setTimeout(()=>{t.connection&&t.connected&&!t.connection.disconnected&&t.connection.ws.send("1")},6e4)},W=pt;var b=(t,s)=>{s[0]===$.RequestTypes.Unsubscribe||s[0]===$.RequestTypes.Subscription||s[0]===$.RequestTypes.SendSubscriptionData||s[0]===$.RequestTypes.GetSubscription?t.subscriptionQueue.push(s):t.queue.push(s),t.connected&&!t.drainInProgress&&de(t)},de=t=>{t.connected&&!t.drainInProgress&&(t.queue.length||t.subscriptionQueue.length)&&!t.isLogginIn&&(t.drainInProgress=!0,t.drainTimeout=setTimeout(()=>{if(t.drainInProgress=!1,t.queue.length||t.subscriptionQueue.length){let s=[...t.queue,...t.subscriptionQueue];t.queue=[],t.subscriptionQueue=[],t.debugInternal&&t.debugInternal(s,"outgoing"),t.connection.ws.send(JSON.stringify(s)),W(t)}},0))},Ue=t=>{t.drainInProgress&&(clearTimeout(t.drainTimeout),t.drainInProgress=!1)};var pe=require("@saulx/hash"),P=(t,s)=>s?(0,pe.hashObjectIgnoreKeyOrder)([s,t]):(0,pe.hashObjectIgnoreKeyOrder)(t);var V=(t,s,e,r,i)=>{r||(r=P(s,i));let n=t.subscriptions[r],o=t.cache[r];if(n)if(n.authError)if(!t.beingAuth)e(n.authError.error,r,0);else{let c=++n.cnt;n.subscribers[c]={onInitial:e}}else if(o)e(null,r,0,o.value);else{let c=++n.cnt;n.subscribers[c]={onInitial:e}}else{n=t.subscriptions[r]={query:s,cnt:1,name:i,subscribers:{1:{onInitial:e}}};let c;for(let a=0;a<t.subscriptionQueue.length;a++){let[u,l,,d]=t.subscriptionQueue[a];(u===F.RequestTypes.Unsubscribe||u===F.RequestTypes.SendSubscriptionData)&&l===r?(t.subscriptionQueue.splice(a,1),a--):(u===F.RequestTypes.Subscription||u===F.RequestTypes.GetSubscription)&&l===r&&(c=!0,u===F.RequestTypes.Subscription&&(d!==o.checksum&&(t.subscriptionQueue[a][3]=o.checksum),t.subscriptionQueue[a][4]=2))}if(!c){let a=[F.RequestTypes.GetSubscription,r,s];o&&a.push(o.checksum),i&&(o||a.push(0),a.push(i)),b(t,a)}}};var q=require("@based/types");var I=(t,s,e,r,i,n,o)=>{n||(n=P(s,o));let c=t.subscriptions[n],a=t.cache[n],u;if(c){u=++c.cnt;let l=!0;for(let d in c.subscribers)if(c.subscribers[d].onData){l=!1;break}if(c.subscribers[u]={onError:i,onData:e,onInitial:r},l){for(let f=0;f<t.subscriptionQueue.length;f++){let[h,O]=t.subscriptionQueue[f];h===q.RequestTypes.GetSubscription&&O===n&&(t.subscriptionQueue.splice(f,1),f--)}let d=[q.RequestTypes.Subscription,n,s];a&&(d.push(a.checksum),d.push(2)),o&&(a||d.push(0,2),d.push(o)),b(t,d)}}else{u=1,c=t.subscriptions[n]={query:s,cnt:1,name:o,subscribers:{1:{onError:i,onData:e,onInitial:r}}};let l=!1,d=!1,f;for(let h=0;h<t.subscriptionQueue.length;h++){let[O,B,,Q]=t.subscriptionQueue[h];(O===q.RequestTypes.Unsubscribe||O===q.RequestTypes.SendSubscriptionData||O===q.RequestTypes.GetSubscription)&&B===n?(O===q.RequestTypes.GetSubscription&&(d=!0),f&&(f[4]=2),t.subscriptionQueue.splice(h,1),h--):O===q.RequestTypes.Subscription&&B===n&&(l=!0,f=t.subscriptionQueue[h],Q!==a.checksum&&(f[3]=a.checksum),!f[4]&&d&&(f[4]=2))}if(!l){let h=[q.RequestTypes.Subscription,n,s];a&&(h.push(a.checksum),d&&h.push(2)),o&&(a?!d&&a&&h.push(2):h.push(0,0),h.push(o)),b(t,h)}}return a&&(r&&(r(null,n,u),delete c.subscribers[u].onInitial),e&&e(a.value,a.checksum)),[n,u]};var L=require("@based/types");var v=(t,s,e)=>{let r=t.subscriptions[s];if(r){let i=!1;if(e?r.subscribers[e]&&(delete r.subscribers[e],r.cnt--,r.cnt===0&&(i=!0)):i=!0,i){delete t.subscriptions[s];let n=!1;for(let o=0;o<t.subscriptionQueue.length;o++){let[c,a]=t.subscriptionQueue[o];c===L.RequestTypes.Unsubscribe&&a===s?n=!0:(c===L.RequestTypes.Subscription||c===L.RequestTypes.SendSubscriptionData)&&a===s&&(t.subscriptionQueue.splice(o,1),o--)}n||b(t,[L.RequestTypes.Unsubscribe,s])}}};var Qe=require("@based/types"),xe=t=>{for(let s=0;s<t.subscriptionQueue.length;s++)t.subscriptionQueue[s][0]===Qe.RequestTypes.Unsubscribe&&(t.subscriptionQueue.splice(s,1),s--)};var Ae=require("@based/types"),De=t=>{for(let s=0;s<t.subscriptionQueue.length;s++)t.subscriptionQueue[s][0]===Ae.RequestTypes.SendSubscriptionData&&(t.subscriptionQueue.splice(s,1),s--)};var U=require("@based/types");var M=(t,s=!1)=>{for(let e in t.subscriptions){let r=Number(e),i=t.subscriptions[e];if(s&&!i.authError)continue;let n,o,c;for(let l=0;l<t.subscriptionQueue.length;l++){let[d,f]=t.subscriptionQueue[l];f===r&&(d===U.RequestTypes.GetSubscription?(c=l,n=t.subscriptionQueue[l]):d===U.RequestTypes.Subscription&&(o=t.subscriptionQueue[l]))}n&&o&&console.error("GET IN Q AND SUB IN Q SHOULD BE IMPOSSIBLE");let a=t.cache[r],u=!1;if(n){let l=!0;for(let d in i.subscribers)if(i.subscribers[d].onData){l=!1;break}l?u=!0:(console.info("not only gets remove get"),t.subscriptionQueue.splice(c,1)),a&&n[3]!==a.checksum&&(n[3]=a.checksum)}if(!u)if(o)a&&o[3]!==a.checksum&&(o[3]=a.checksum,n&&(o[4]=2));else{let{name:l,query:d}=t.subscriptions[r];l?a?b(t,[U.RequestTypes.Subscription,r,d,a.checksum,n?2:0,l]):b(t,[U.RequestTypes.Subscription,r,d,0,n?2:0,l]):a?b(t,[U.RequestTypes.Subscription,r,d,a.checksum,n?2:0]):b(t,[U.RequestTypes.Subscription,r,d,0,n?2:0])}}};var Ge=require("@based/types");var X=(t,s)=>{if(typeof window!="undefined")return t;let e={white:"\x1B[37;1m",reset:"\x1B[0m",blue:"\x1B[34m",red:"\x1B[31m",green:"\x1B[32m",brightBlue:"\x1B[34;1m",brightRed:"\x1B[31;1m"};return`${e[s]}${t}${e.reset}`},fe=(t,s=0,e=!1,r="",i=!1)=>{let n="";for(let a=0;a<s;a++)n+=" ";let o=e?[]:r?[n+`${X(r,i?"brightRed":"white")} {`]:[n+"{"],c=!1;e||(n+=" ",s+=1);for(let a in t){let u=t[a],l=a[0]==="$"?X(a,"white"):a;if(c&&(o[o.length-1]+=","),Array.isArray(u)){o.push(`${n} ${l}: [`);for(let d=0;d<u.length;d++){let f=u[d];o.push(...f&&typeof f=="object"?fe(f,s+4):[`${n} ${f}`]),d!==u.length-1&&(o[o.length-1]+=",")}o.push(`${n} ]`)}else u&&typeof u=="object"?(o.push(`${n} ${l}: {`),o.push(...fe(u,s+2,!0)),o.push(`${n} }`)):o.push(`${n} ${l}: ${u}`);c=!0}return e||o.push(n.slice(0,-1)+"}"),o},Y=fe;var w=t=>{let s=new Ge.BasedError(t.message);if(s.name=t.name?`${t.type} from ${t.name}`:t.type,s.stack=null,t.query||t.payload){let e=s.message.split(` | ||
`),delete t.cache[e],b(t,[Z.RequestTypes.SendSubscriptionData,e]);else{c.checksum=n;for(let u in o.subscribers){let l=o.subscribers[u];l.onInitial&&(l.onInitial(null,Number(e),Number(u),c.value),delete l.onInitial,l.onData||v(t,e,Number(u))),l.onData&&l.onData(c.value,c.checksum)}}}}};var Me=(t,s)=>{for(let e of s[1]){delete t.cache[e];let r=t.subscriptions[e];if(r){let i={type:"AuthorizationError",name:r.name?`observe "${r.name}"`:"observe",message:"Unauthorized request",payload:r.query,auth:!0},n=w(i);r.authError={token:t.token,error:n};for(let o in r.subscribers){let c=r.subscribers[o];c.onError&&c.onError(n)}}}};var Ne=require("@based/types");var ft=0,y=(t,s,e,r,i,n,o)=>{let c=++ft;t.requestCallbacks[c]={resolve:r,reject:i,type:s,payload:e,name:n,isRetry:o},s===Ne.RequestTypes.Call?b(t,[s,n,c,e]):b(t,[s,c,e])};var He=(t,s)=>{let[,e,r,i]=s,n=t.requestCallbacks[e];n&&(delete t.requestCallbacks[e],i?n.reject(w(i)):n.resolve(r))};var S={};Re(S,{BasedClient:()=>x});var g=require("@based/types");var be=require("@based/types");var bt=t=>typeof t!="undefined"&&t!==null,mt=(t,s,e)=>{if(t.beingAuth=!0,s)t.token=s,t.sendTokenOptions=e;else{for(let r in t.cache)t.subscriptions[r]||delete t.cache[r];delete t.token,delete t.sendTokenOptions}if(t.connected){let r=s?[be.RequestTypes.Token,s,e].filter(bt):[be.RequestTypes.Token];t.connection.ws.send(JSON.stringify(r)),W(t),M(t,!0)}},E=mt;var R=require("@based/types");var me=0,_e=(t,s)=>{let e=++me;return b(t,[R.RequestTypes.Auth,R.AuthRequestTypes.Login,e,s]),new Promise((r,i)=>{t.authCallbacks[e]={resolve:n=>{n.id&&n.token?t.updateUserState(n.id,n.token,n.refreshToken):t.updateUserState(!1),r(n)},reject:i}})},ze=(t,s)=>new Promise((e,r)=>{y(t,R.RequestTypes.Call,s,i=>{i.id&&i.token?t.updateUserState(i.id,i.token,i.refreshToken):t.updateUserState(!1),e(i)},r,"registerUser")}),Je=(t,s)=>{let e=++me;return b(t,[R.RequestTypes.Auth,R.AuthRequestTypes.RenewToken,e,s]),new Promise((r,i)=>{t.authCallbacks[e]={resolve:r,reject:i}})},Ke=(t,s)=>{let[,e,r,i]=s,n=t.authCallbacks[e];n&&(delete t.authCallbacks[e],i?n.reject(w(i)):n.resolve(r))},We=t=>{let s=++me;return b(t,[R.RequestTypes.Auth,R.AuthRequestTypes.Logout,s]),new Promise((e,r)=>{t.authCallbacks[s]={resolve:i=>{t.updateUserState(!1),e(i)},reject:r}})};var Ve=(t,s)=>{let e=new Date,r=e.getHours()+":"+e.getMinutes()+":"+e.getSeconds()+":"+e.getMilliseconds();if(s==="incoming"){let i=`\u25BC ${r} -- `;console.info(i,t)}else{let i=`\u25B2 ${r} -- `;console.info(i,t)}};var he=require("@saulx/hash");p(S,require("@based/types"));var x=class{constructor(s){this.tokenToLocalStorage=!1;this.auth=[];this.subscriptions={};this.cache={};this.requestCallbacks={};this.authCallbacks={};this.connected=!1;this.subscriptionQueue=[];this.queue=[];this.drainInProgress=!1;this.based=s}get debug(){return this.debugInternal}set debug(s){s===!0?this.debugInternal=Ve:this.debugInternal=s}initUserState(){if(typeof window!="undefined"){if(this.based.opts){let s=(0,he.hash)({cluster:this.based.opts.cluster,project:this.based.opts.project,env:this.based.opts.project,org:this.based.opts.org});this.optsId=s}else this.optsId=(0,he.hash)("un-specified-env");try{let s=global.localStorage.getItem("based-"+this.optsId+"-uid");if(s){this.tokenToLocalStorage=!0;try{let[e,r,i]=JSON.parse(s);r&&e&&this.updateUserState(e,r,i)}catch(e){global.localStorage.removeItem("based-"+this.optsId+"-uid")}}}catch(s){}}}updateUserState(s,e,r){if(this.user=s,!this.tokenToLocalStorage&&typeof window!="undefined")try{global.localStorage.removeItem("based-"+this.optsId+"-uid")}catch(i){}if(e)r&&(this.renewOptions={refreshToken:r}),r&&(this.renewOptions=J(G({},this.renewOptions),{refreshToken:r})),E(this,e,{refreshToken:r}),this.auth.push(i=>{if(i){if(typeof window!="undefined")try{this.tokenToLocalStorage&&global.localStorage.setItem("based-"+this.optsId+"-uid",JSON.stringify([s,e,r]))}catch(n){}this.based.emit("auth",e)}else{if(typeof window!="undefined")try{this.tokenToLocalStorage&&global.localStorage.removeItem("based-"+this.optsId+"-uid")}catch(n){}this.based.emit("auth",!1)}});else{if(typeof window!="undefined"){this.user=!1;try{this.tokenToLocalStorage&&global.localStorage.removeItem("based-"+this.optsId+"-uid")}catch(i){}}E(this),this.based.emit("auth",!1)}}onClose(){this.connected=!1,Ue(this),xe(this),De(this),this.based.listeners.disconnect&&this.based.listeners.disconnect.forEach(s=>s())}onReconnect(){if(this.based.listeners.reconnect&&this.based.listeners.reconnect.forEach(s=>s()),this.tracking)for(let s of this.tracking)b(this,[g.RequestTypes.Track,{t:s}])}onOpen(){this.connected=!0,this.based.listeners.connect&&this.based.listeners.connect.forEach(s=>s()),this.token&&E(this,this.token,this.sendTokenOptions),M(this),de(this)}onData(s){var e,r;try{let i=JSON.parse(s.data);this.debugInternal&&this.debugInternal(i,"incoming");let[n,o,c,a,u]=i;if(n===g.RequestTypes.Token){console.info(a),this.retryingRenewToken=!1,o.length&&Me(this,i),!c&&typeof a=="string"&&this.user&&this.renewOptions.refreshToken&&(this.token=a);for(let l of this.auth)l(!c);this.beingAuth=!1,this.auth=[]}else if(n===g.RequestTypes.Auth)Ke(this,i);else if((((e=u||a)==null?void 0:e.code)===g.BasedErrorCodes.TokenExpired||((r=u||a)==null?void 0:r.message)==="Token expired")&&!this.retryingRenewToken){this.retryingRenewToken=!0;let l=this.user;Je(this,this.renewOptions).then(d=>{E(this,d.token,this.sendTokenOptions),n===g.RequestTypes.Subscription||n===g.RequestTypes.SubscriptionDiff?M(this):y(this,n,a==null?void 0:a.payload,this.requestCallbacks[o].resolve,this.requestCallbacks[o].reject),this.based.emit("renewToken",d),d&&this.updateUserState(l,d.token,this.renewOptions.refreshToken)}).catch(d=>{var f;(f=this.requestCallbacks[o])==null||f.reject(d)})}else n===g.RequestTypes.Set||n===g.RequestTypes.Get||n===g.RequestTypes.Configuration||n===g.RequestTypes.GetConfiguration||n===g.RequestTypes.Call||n===g.RequestTypes.Delete||n===g.RequestTypes.Copy||n===g.RequestTypes.Digest||n===g.RequestTypes.RemoveType||n===g.RequestTypes.RemoveField?He(this,i):n===g.RequestTypes.Subscription?je(this,i):n===g.RequestTypes.SubscriptionDiff&&Le(this,i)}catch(i){console.error("Received incorrect data ",s.data)}}};var ge=(t,s)=>{let e;if(t.configuration&&t.configuration.schema)for(let r in t.configuration.schema){let i=t.configuration.schema[r];if(i.prefixToTypeMapping){for(let n in i.prefixToTypeMapping)if(i.prefixToTypeMapping[n]===s){e=n;break}}}return e};var Te=require("@saulx/hash");var Ye=require("@based/types"),Ze=require("@saulx/hash"),Xe=new Set,ht=t=>{if(typeof window!="undefined"){if(Xe.has(t))return!1;Xe.add(t);try{let s="_ba:"+(0,Ze.hashCompact)(t);return localStorage.getItem(s)?!1:(localStorage.setItem(s,"1"),!0)}catch(s){return!1}}return!1},ye=(t,s)=>{if(s){let e=`${t}`,r=Object.keys(s).sort();for(let i of r)e+="_"+i+"_"+s[i];return e}else return t},N=(t,s,e,r,i,n,o)=>{let c=ye(s,e),a={t:c};o&&(a.r=1),i&&(a.e=1,n&&(a.o=n)),r?(a.s=1,t.tracking.delete(c)):o||(i||(t.tracking||(t.tracking=new Set),t.tracking.add(c)),ht(c)&&(a.u=1)),b(t,[Ye.RequestTypes.Track,a])};var ve=class{constructor(s,e,r){this.closed=!1;this.client=s,this.subId=r,this.subscriberId=e}unsubscribe(){this.closed=!0,v(this.client,this.subId,this.subscriberId)}},ke=class{constructor(s,e){this.closed=!1;this.client=s,this.subs=e}unsubscribe(){if(!this.closed){this.closed=!0;for(let s of this.subs)s.unsubscribe()}}},ee=class{constructor(s,e){this.client=s,this.components=e}subscribe(s,e,r){let i={data:{}},n=[];for(let{key:o,obs:c}of this.components){let a=c.subscribe(u=>{if(o===""){Object.assign(i.data,u),s(i);return}i.data[o]=u,s(i)},e);n.push(a)}return new ke(this.client,n)}},C=class{constructor(s,e,r){this.client=s,this.subId=typeof e=="string"?P(r,e):P(e),this.name=typeof e=="string"?e:null,this.payload=typeof e=="string"?r:e}subscribe(s,e,r){let[,i]=I(this.client,this.payload,s,n=>{n&&(console.error(n),e&&e(n))},e,this.subId,this.name);return new ve(this.client,i,this.subId)}};var Se={},H={},gt=(t,s)=>{Se[t]||(Se[t]=!0,setTimeout(()=>{console.info("Drain file q"),Se[t]=!1;let e=H[t];H[t]=[];let r=new global.FormData;for(let i of e){let{raw:n,name:o,id:c,file:a,functionName:u}=i,l=`${u||""}|${n?1:0}|${c}|${a.size}${o?`|${o}`:""}`;r.append(l,a)}try{let i=new global.XMLHttpRequest;i.upload.onprogress=n=>{let o=100*(n.loaded||n.position)/(n.totalSize||n.total);console.info(o,"upload...")},i.onerror=n=>{console.error("error!",n,"flap",i.responseText)},i.timeout=1e3*60*60*24,i.onabort=n=>{console.error("abort",n)},i.ontimeout=n=>{console.error("on timeout",n)},i.onload=()=>{try{JSON.parse(i.response)}catch(n){console.error("something wrong with file upload",n)}},i.open("POST",t+"/file"),i.setRequestHeader("Content-Type","multipart/form-data"),i.setRequestHeader("Authorization",s),i.send(r)}catch(i){console.error("Something wrong with xhr upload",i)}},500))},et=async(t,s,e,r,i,n,o)=>{H[e]||(H[e]=[]),H[e].push({file:s,id:r,url:e,raw:i,name:n,functionName:o}),gt(e,t.getToken())};var tt=K(require("@based/get-service")),te={},se={},yt=async(t,s)=>{if(s.url)return typeof s.url=="string"?s.url:await s.url();if(!t.opts.env&&t.opts.url)return typeof t.opts.url=="string"?t.opts.url:await t.opts.url();let{env:e,project:r,org:i}=t.opts,n=e+"/"+r+"/"+i+"/"+t.opts.cluster;if(te[n])return te[n];if(se[n])return(await se[n]).url;let o=await(se[n]=(0,tt.default)({env:e,project:r,org:i,name:"@based/hub",key:"file-upload",optionalKey:!0},0,t.opts.cluster));return delete se[n],setTimeout(()=>{delete te[n]},2e3),te[n]=o.url},st=yt;var it=K(require("cross-fetch")),ie=(t,s,e)=>((0,it.default)(s,{method:"POST",cache:"no-cache",headers:{"Content-Type":e.mimeType||"text/plain","File-Id":e.id,"File-Is-Raw":e.raw?"1":"0","File-Name":e.name||"","Function-Name":e.functionName||"",Authorization:t.getToken()},body:e.contents}).then(r=>{}).catch(r=>{console.error("Error while uploading file",r)}),{id:e.id});var A=require("./file/stream"),re=typeof window!="undefined",vt=t=>"src"in t&&typeof t.src=="string",kt=t=>"path"in t&&typeof t.path=="string",St=t=>"contents"in t&&(0,A.isStream)(t.contents),rt=async(t,s)=>{if(vt(s)){let i=s.id?{$id:s.id}:{type:"file"};return s.src?(i.src=s.src,i.origin=s.src,s.size&&(i.size=s.size),s.name&&(i.name=s.name),s.parents&&(i.parents=s.parents),await t.set(i)):void 0}let e=s.id;if(!e){let i={type:"file",progress:0};s.name?i.name=s.name:global.File&&"contents"in s&&s.contents instanceof global.File&&(i.name=s.contents.name),s.parents&&(i.parents=s.parents),e=(await t.set(i)).id}s.id=e;let r=(await st(t,s)).replace(/^ws/,"http");if(kt(s))return(0,A.uploadFilePath)(t,r,s),{id:e};if(St(s))return(0,A.uploadFileStream)(t,r,s),{id:e};if(s.contents instanceof ArrayBuffer)return s.contents=re?new global.Blob([s.contents],{type:s.mimeType||"text/plain"}):global.Buffer.from(s.contents),ie(t,r+"/file",s);if(re&&s.contents instanceof global.Blob)return s.mimeType||(s.mimeType=s.contents.type),ie(t,r+"/file",s);if(typeof s.contents=="string"||!re&&s.contents instanceof global.Buffer)return ie(t,r+"/file",s);if(re&&s.contents instanceof File)return et(t,s.contents,r,s.id,s.raw||!1,s.name,s.functionName),{id:e};throw s.id||await t.delete({$id:e}),new Error(`Invalid contents for file api ${JSON.stringify(s,null,2)}`)};var oe=K(require("@based/get-service")),Oe=require("@saulx/utils"),T=require("@based/graphql");p(m,require("@based/types"),module.exports);var ne=class extends Be{constructor(e){super();this.client=new x(this),Object.defineProperty(this,"client",{enumerable:!1,writable:!0}),e&&e.url&&this.connect(e.url),this.graphql={query:this.gqlQuery.bind(this),live:this.gqlLive.bind(this)}}connect(e){!e&&this._url?this.client.connection||(this.client.connection=le(this.client,this._url)):(this._url=e,this.client.connection=le(this.client,e))}disconnect(){this.client.connection&&(this.client.connection.disconnected=!0,this.client.connection.destroy(),this.client.connection.ws&&this.client.connection.ws.close(),this.client.connected&&this.client.onClose(),delete this.client.connection),this.client.connected=!1}observeUntil(e,r,i){return new Promise((n,o)=>{let c,a=!1;this.observe(e,(u,l)=>{i&&i(u,l),r(u,l)&&(a=!0,c&&c(),n(u))}).then(u=>{a?c():c=u}).catch(u=>{o(u)})})}gql(e,...r){typeof e=="string"&&(e=[e]);let i=e[0];return r.forEach((n,o)=>{n&&n.kind==="Document"?i+=n.loc.source.body:i+=n,i+=e[o+1]}),(0,T.createOperations)({schemas:this.client.configuration.schema},(0,T.parseGraphql)(i))}gqlDb(e="default"){return(r,...i)=>{typeof r=="string"&&(r=[r]);let n=r[0];return i.forEach((o,c)=>{o&&o.kind==="Document"?n+=o.loc.source.body:n+=o,n+=r[c+1]}),(0,T.createOperations)({schemas:this.client.configuration.schema,db:e},(0,T.parseGraphql)(n))}}observe(e,r,i,n){return typeof e=="string"?new Promise((o,c)=>{let a=typeof r=="function",u=a?r:i,l=a?i:n;I(this.client,a?void 0:r,u,(d,f,h,O,B)=>{d&&!B?c(d):o(()=>{v(this.client,f,h)})},l,void 0,e)}):new Promise((o,c)=>{I(this.client,e,r,(a,u,l,d,f)=>{a&&!f?c(a):o(()=>{v(this.client,u,l)})},i)})}createObservable(e,r){return typeof e=="string"?new C(this.client,e,r):new C(this.client,e)}observeSchema(e,r,i){return new Promise((n,o)=>{let c=typeof e=="string"?e:"default",a=typeof e=="string"?r:e,u=typeof e=="string"?i:r;I(this.client,{$subscribe_schema:c},(l,d)=>{this.client.configuration||(this.client.configuration={dbs:[],schema:{},functions:{}}),this.client.configuration.schema[c]=l,a(l,d)},(l,d,f,h,O)=>{l&&!O?o(l):n(()=>{v(this.client,d,f)})},u)})}get(e,r){return typeof e=="string"?new Promise((i,n)=>{V(this.client,r,(o,c,a,u)=>{o?n(o):i(u)},0,e)}):new Promise((i,n)=>{y(this.client,k.RequestTypes.Get,e,i,n)})}file(e){return global.File&&e instanceof File&&(e={contents:e}),rt(this,e)}call(e,r){return new Promise((i,n)=>{y(this.client,k.RequestTypes.Call,r,i,n,e)})}async id(e,r){let i=ge(this.client,e);if(i||(await this.schema(),i=ge(this.client,e)),!i)throw w({message:`Type does not exist ${e}`,type:"Invalid type",payload:r?{type:e,opts:r}:{type:e}});if(r){let n=(0,Te.hashCompact)(r,8,!0);return i+n}else return i+(0,Te.hashCompact)(Math.floor(Math.random()*99999999999)+""+Date.now())}digest(e){return new Promise((r,i)=>{y(this.client,k.RequestTypes.Digest,e,r,i)})}set(e){return new Promise((r,i)=>{y(this.client,k.RequestTypes.Set,e,r,i)})}copy(e){return new Promise((r,i)=>{y(this.client,k.RequestTypes.Copy,e,r,i)})}async gqlQuery(e,r={}){let i;typeof e=="string"?i=this.gql(e):i=e;try{if(i=(0,T.handleGraphqlVariables)(i,i,r),i.opType==="GET"){let o={$db:i.db},c=[];for(let u in i.ops){if(i.ops[u].fnObserve){let l=await this.get(i.ops[u].fnObserve.name,i.ops[u].fnObserve.payload);c.push({key:u,reply:l});continue}i.ops[u].get&&(o[u]=i.ops[u].get)}let a=await this.get(o);for(let{key:u,reply:l}of c)a[u]=l;return{data:a}}let n={};return await Promise.all(Object.entries(i.ops).map(async([o,c])=>{var d,f,h,O,B;if(c.delete){n[o]=await this.delete(c.delete);return}else if(c.fnCall){n[o]=await this.call(c.fnCall.name,c.fnCall.payload);return}let{id:a}=await this.set(c.set);if(!c.get){let Q={};Q.id=a;let we=(B=(O=(h=(f=(d=this.client)==null?void 0:d.configuration)==null?void 0:f.schema)==null?void 0:h[i.db])==null?void 0:O.prefixToTypeMapping)==null?void 0:B[a.slice(0,2)];we&&(Q.type=we),n[o]=Q;return}let u=(0,Oe.deepCopy)(c.get);u.$id=a;let l=await this.get(u);n[o]=l})),{data:n}}catch(n){return{errors:[{message:n.message,locations:n.locations}]}}}async gqlLive(e,r={}){let i;if(typeof e=="string"?i=this.gql(e):i=e,i=(0,T.handleGraphqlVariables)(i,i,r),i.opType==="GET"){let o=[],c={};for(let a in i.ops){if(i.ops[a].fnObserve){let{name:u,payload:l}=i.ops[a].fnObserve;o.push({key:a,fn:{name:u,payload:l}});continue}c[a]=i.ops[a].get}if(o!=null&&o.length){let a=o.map(l=>({obs:new C(this.client,l.fn.name,l.fn.payload),key:l.key})),u=new C(this.client,G({$db:i.db},c));return a.push({key:"",obs:u}),new ee(this.client,a)}return new C(this.client,{$db:i.db,data:c})}let n={};return await Promise.all(Object.entries(i.ops).map(async([o,c])=>{if(c.delete){n[o]=await this.delete(c.delete);return}else if(c.fnCall){n[o]=await this.call(c.fnCall.name,c.fnCall.payload);return}let{id:a}=await this.set(c.set),u=(0,Oe.deepCopy)(c.get);u.$id=a,n[o]=u})),new C(this.client,{$db:i.db,data:n})}analytics(e,r){return new Promise((i,n)=>{r?I(this.client,e,r,(o,c,a,u,l)=>{o&&!l?n(o):i(()=>{v(this.client,c,a)})},o=>console.error(o),void 0,"analytics"):V(this.client,e,(o,c,a,u)=>{o?n(o):((0,k.isAnalyticsHistoryOpts)(e)||(0,k.isAnalyticsTypesOpts)(e),i(u))},0,"analytics")})}track(e,r){N(this.client,e,r)}clearAnalytics(e,r){N(this.client,e,r,!1,!1,void 0,!0)}untrack(e,r){N(this.client,e,r,!0)}event(e,r,i){N(this.client,e,r,!1,!0,i)}delete(e){return new Promise((r,i)=>{y(this.client,k.RequestTypes.Delete,e,r,i)})}schema(){return new Promise((e,r)=>{let i=n=>{this.client.configuration=n,e(n)};y(this.client,k.RequestTypes.GetConfiguration,0,i,r)})}removeType(e,r="default"){return new Promise((i,n)=>{y(this.client,k.RequestTypes.RemoveType,{type:e,db:r},i,n)})}removeField(e,r,i="default"){return new Promise((n,o)=>{!r||r.length===0?o(new Error("Path cannot be empty")):(Array.isArray(r)||(r=[r]),y(this.client,k.RequestTypes.RemoveField,{type:e,db:i,path:r},n,o))})}updateSchema(e){return new Promise((r,i)=>{y(this.client,k.RequestTypes.Configuration,e,r,i)})}getToken(){return this.client.token}auth(e,r){return new Promise(i=>{if(this.client.auth.push(i),e&&e!==this.client.token||e===!1&&this.client.token){if(typeof e=="string"){let n=r||{},{renewOptions:o,refreshToken:c}=n,a=qe(n,["renewOptions","refreshToken"]);o&&(this.client.renewOptions=o),c&&(this.client.renewOptions=J(G({},this.client.renewOptions),{refreshToken:c})),E(this.client,e,a)}else E(this.client);this.emit("auth",e)}})}async login(e){return e.localStorage===!1?this.client.tokenToLocalStorage=!1:this.client.tokenToLocalStorage=!0,_e(this.client,e)}async register(e){return e.localStorage===!1?this.client.tokenToLocalStorage=!1:this.client.tokenToLocalStorage=!0,ze(this.client,e)}logout(){return We(this.client)}observeAuth(e){return new Promise(r=>{this.client.user&&this.client.token?e({id:this.client.user,token:this.client.token}):e(!1);let i=n=>{n&&this.client.user&&this.client.token?e({id:this.client.user,token:this.client.token}):e(!1)};this.on("auth",i),r(()=>{this.removeListener("auth",i)})})}},Tt=(t,s)=>{if(s){let e;t+=/\?/.test(t)?"&":"?";for(let r in s){let i=s[r];t+=e?`&${r}=${i}`:`${r}=${i}`,e=!0}}return t},Ot=(t,s=ne)=>{let{env:e,project:r,org:i,url:n,key:o,name:c="@based/hub",cluster:a,params:u}=t;if(n||(a=t.cluster=(0,oe.getClusterUrl)(a),n=async()=>{let{url:l}=await(0,oe.default)({env:e,project:r,org:i,key:o,name:c},0,a);return Tt(l,u)}),n){let l=new s;return l.opts=t,l.client.initUserState(),l.connect(n),l}},wt=Ot;0&&(module.exports={Based,BasedClient,BasedGraphQL,Observable,addGetSubscriber,addRequest,addSubscriber,createGraphqlOperations,generateSubscriptionId,generateTrackingKey,handleGraphqlVariables,parseGraphql,removeSubscriber}); | ||
`),delete t.cache[e],b(t,[Z.RequestTypes.SendSubscriptionData,e]);else{c.checksum=n;for(let u in o.subscribers){let l=o.subscribers[u];l.onInitial&&(l.onInitial(null,Number(e),Number(u),c.value),delete l.onInitial,l.onData||v(t,e,Number(u))),l.onData&&l.onData(c.value,c.checksum)}}}}};var Me=(t,s)=>{for(let e of s[1]){delete t.cache[e];let r=t.subscriptions[e];if(r){let i={type:"AuthorizationError",name:r.name?`observe "${r.name}"`:"observe",message:"Unauthorized request",payload:r.query,auth:!0},n=w(i);r.authError={token:t.token,error:n};for(let o in r.subscribers){let c=r.subscribers[o];c.onError&&c.onError(n)}}}};var Ne=require("@based/types");var ft=0,y=(t,s,e,r,i,n,o)=>{let c=++ft;t.requestCallbacks[c]={resolve:r,reject:i,type:s,payload:e,name:n,isRetry:o},s===Ne.RequestTypes.Call?b(t,[s,n,c,e]):b(t,[s,c,e])};var He=(t,s)=>{let[,e,r,i]=s,n=t.requestCallbacks[e];n&&(delete t.requestCallbacks[e],i?n.reject(w(i)):n.resolve(r))};var S={};Re(S,{BasedClient:()=>x});var g=require("@based/types");var be=require("@based/types");var bt=t=>typeof t!="undefined"&&t!==null,mt=(t,s,e)=>{if(t.beingAuth=!0,s)t.token=s,t.sendTokenOptions=e;else{for(let r in t.cache)t.subscriptions[r]||delete t.cache[r];delete t.token,delete t.sendTokenOptions}if(t.connected){let r=s?[be.RequestTypes.Token,s,e].filter(bt):[be.RequestTypes.Token];t.connection.ws.send(JSON.stringify(r)),W(t),M(t,!0)}},E=mt;var R=require("@based/types");var me=0,_e=(t,s)=>{let e=++me;return b(t,[R.RequestTypes.Auth,R.AuthRequestTypes.Login,e,s]),new Promise((r,i)=>{t.authCallbacks[e]={resolve:n=>{n.id&&n.token?t.updateUserState(n.id,n.token,n.refreshToken):t.updateUserState(!1),r(n)},reject:i}})},ze=(t,s)=>new Promise((e,r)=>{y(t,R.RequestTypes.Call,s,i=>{i.id&&i.token?t.updateUserState(i.id,i.token,i.refreshToken):t.updateUserState(!1),e(i)},r,"registerUser")}),Je=(t,s)=>{let e=++me;return b(t,[R.RequestTypes.Auth,R.AuthRequestTypes.RenewToken,e,s]),new Promise((r,i)=>{t.authCallbacks[e]={resolve:r,reject:i}})},Ke=(t,s)=>{let[,e,r,i]=s,n=t.authCallbacks[e];n&&(delete t.authCallbacks[e],i?n.reject(w(i)):n.resolve(r))},We=t=>{let s=++me;return b(t,[R.RequestTypes.Auth,R.AuthRequestTypes.Logout,s]),new Promise((e,r)=>{t.authCallbacks[s]={resolve:i=>{t.updateUserState(!1),e(i)},reject:r}})};var Ve=(t,s)=>{let e=new Date,r=e.getHours()+":"+e.getMinutes()+":"+e.getSeconds()+":"+e.getMilliseconds();if(s==="incoming"){let i=`\u25BC ${r} -- `;console.info(i,t)}else{let i=`\u25B2 ${r} -- `;console.info(i,t)}};var he=require("@saulx/hash");p(S,require("@based/types"));var x=class{constructor(s){this.tokenToLocalStorage=!1;this.auth=[];this.subscriptions={};this.cache={};this.requestCallbacks={};this.authCallbacks={};this.connected=!1;this.subscriptionQueue=[];this.queue=[];this.drainInProgress=!1;this.based=s}get debug(){return this.debugInternal}set debug(s){s===!0?this.debugInternal=Ve:this.debugInternal=s}initUserState(){if(typeof window!="undefined"){if(this.based.opts){let s=(0,he.hash)({cluster:this.based.opts.cluster,project:this.based.opts.project,env:this.based.opts.project,org:this.based.opts.org});this.optsId=s}else this.optsId=(0,he.hash)("un-specified-env");try{let s=global.localStorage.getItem("based-"+this.optsId+"-uid");if(s){this.tokenToLocalStorage=!0;try{let[e,r,i]=JSON.parse(s);r&&e&&this.updateUserState(e,r,i)}catch(e){global.localStorage.removeItem("based-"+this.optsId+"-uid")}}}catch(s){}}}updateUserState(s,e,r){if(this.user=s,!this.tokenToLocalStorage&&typeof window!="undefined")try{global.localStorage.removeItem("based-"+this.optsId+"-uid")}catch(i){}if(e)r&&(this.renewOptions={refreshToken:r}),r&&(this.renewOptions=J(G({},this.renewOptions),{refreshToken:r})),E(this,e,{refreshToken:r}),this.auth.push(i=>{if(i){if(typeof window!="undefined")try{this.tokenToLocalStorage&&global.localStorage.setItem("based-"+this.optsId+"-uid",JSON.stringify([s,e,r]))}catch(n){}this.based.emit("auth",e)}else{if(typeof window!="undefined")try{this.tokenToLocalStorage&&global.localStorage.removeItem("based-"+this.optsId+"-uid")}catch(n){}this.based.emit("auth",!1)}});else{if(typeof window!="undefined"){this.user=!1;try{this.tokenToLocalStorage&&global.localStorage.removeItem("based-"+this.optsId+"-uid")}catch(i){}}E(this),this.based.emit("auth",!1)}}onClose(){this.connected=!1,Ue(this),xe(this),De(this),this.based.listeners.disconnect&&this.based.listeners.disconnect.forEach(s=>s())}onReconnect(){if(this.based.listeners.reconnect&&this.based.listeners.reconnect.forEach(s=>s()),this.tracking)for(let s of this.tracking)b(this,[g.RequestTypes.Track,{t:s}])}onOpen(){this.connected=!0,this.based.listeners.connect&&this.based.listeners.connect.forEach(s=>s()),this.token&&E(this,this.token,this.sendTokenOptions),M(this),de(this)}onData(s){var e,r;try{let i=JSON.parse(s.data);this.debugInternal&&this.debugInternal(i,"incoming");let[n,o,c,a,u]=i;if(n===g.RequestTypes.Token){this.retryingRenewToken=!1,o.length&&Me(this,i),!c&&typeof a=="string"&&this.user&&this.renewOptions.refreshToken&&(this.token=a);for(let l of this.auth)l(!c);this.beingAuth=!1,this.auth=[]}else if(n===g.RequestTypes.Auth)Ke(this,i);else if((((e=u||a)==null?void 0:e.code)===g.BasedErrorCodes.TokenExpired||((r=u||a)==null?void 0:r.message)==="Token expired")&&!this.retryingRenewToken){this.retryingRenewToken=!0;let l=this.user;Je(this,this.renewOptions).then(d=>{E(this,d.token,this.sendTokenOptions),n===g.RequestTypes.Subscription||n===g.RequestTypes.SubscriptionDiff?M(this):y(this,n,a==null?void 0:a.payload,this.requestCallbacks[o].resolve,this.requestCallbacks[o].reject),this.based.emit("renewToken",d),d&&this.updateUserState(l,d.token,this.renewOptions.refreshToken)}).catch(d=>{var f;(f=this.requestCallbacks[o])==null||f.reject(d)})}else n===g.RequestTypes.Set||n===g.RequestTypes.Get||n===g.RequestTypes.Configuration||n===g.RequestTypes.GetConfiguration||n===g.RequestTypes.Call||n===g.RequestTypes.Delete||n===g.RequestTypes.Copy||n===g.RequestTypes.Digest||n===g.RequestTypes.RemoveType||n===g.RequestTypes.RemoveField?He(this,i):n===g.RequestTypes.Subscription?je(this,i):n===g.RequestTypes.SubscriptionDiff&&Le(this,i)}catch(i){console.error("Received incorrect data ",s.data)}}};var ge=(t,s)=>{let e;if(t.configuration&&t.configuration.schema)for(let r in t.configuration.schema){let i=t.configuration.schema[r];if(i.prefixToTypeMapping){for(let n in i.prefixToTypeMapping)if(i.prefixToTypeMapping[n]===s){e=n;break}}}return e};var Te=require("@saulx/hash");var Ye=require("@based/types"),Ze=require("@saulx/hash"),Xe=new Set,ht=t=>{if(typeof window!="undefined"){if(Xe.has(t))return!1;Xe.add(t);try{let s="_ba:"+(0,Ze.hashCompact)(t);return localStorage.getItem(s)?!1:(localStorage.setItem(s,"1"),!0)}catch(s){return!1}}return!1},ye=(t,s)=>{if(s){let e=`${t}`,r=Object.keys(s).sort();for(let i of r)e+="_"+i+"_"+s[i];return e}else return t},N=(t,s,e,r,i,n,o)=>{let c=ye(s,e),a={t:c};o&&(a.r=1),i&&(a.e=1,n&&(a.o=n)),r?(a.s=1,t.tracking.delete(c)):o||(i||(t.tracking||(t.tracking=new Set),t.tracking.add(c)),ht(c)&&(a.u=1)),b(t,[Ye.RequestTypes.Track,a])};var ve=class{constructor(s,e,r){this.closed=!1;this.client=s,this.subId=r,this.subscriberId=e}unsubscribe(){this.closed=!0,v(this.client,this.subId,this.subscriberId)}},ke=class{constructor(s,e){this.closed=!1;this.client=s,this.subs=e}unsubscribe(){if(!this.closed){this.closed=!0;for(let s of this.subs)s.unsubscribe()}}},ee=class{constructor(s,e){this.client=s,this.components=e}subscribe(s,e,r){let i={data:{}},n=[];for(let{key:o,obs:c}of this.components){let a=c.subscribe(u=>{if(o===""){Object.assign(i.data,u),s(i);return}i.data[o]=u,s(i)},e);n.push(a)}return new ke(this.client,n)}},C=class{constructor(s,e,r){this.client=s,this.subId=typeof e=="string"?P(r,e):P(e),this.name=typeof e=="string"?e:null,this.payload=typeof e=="string"?r:e}subscribe(s,e,r){let[,i]=I(this.client,this.payload,s,n=>{n&&(console.error(n),e&&e(n))},e,this.subId,this.name);return new ve(this.client,i,this.subId)}};var Se={},H={},gt=(t,s)=>{Se[t]||(Se[t]=!0,setTimeout(()=>{console.info("Drain file q"),Se[t]=!1;let e=H[t];H[t]=[];let r=new global.FormData;for(let i of e){let{raw:n,name:o,id:c,file:a,functionName:u}=i,l=`${u||""}|${n?1:0}|${c}|${a.size}${o?`|${o}`:""}`;r.append(l,a)}try{let i=new global.XMLHttpRequest;i.upload.onprogress=n=>{let o=100*(n.loaded||n.position)/(n.totalSize||n.total);console.info(o,"upload...")},i.onerror=n=>{console.error("error!",n,"flap",i.responseText)},i.timeout=1e3*60*60*24,i.onabort=n=>{console.error("abort",n)},i.ontimeout=n=>{console.error("on timeout",n)},i.onload=()=>{try{JSON.parse(i.response)}catch(n){console.error("something wrong with file upload",n)}},i.open("POST",t+"/file"),i.setRequestHeader("Content-Type","multipart/form-data"),i.setRequestHeader("Authorization",s),i.send(r)}catch(i){console.error("Something wrong with xhr upload",i)}},500))},et=async(t,s,e,r,i,n,o)=>{H[e]||(H[e]=[]),H[e].push({file:s,id:r,url:e,raw:i,name:n,functionName:o}),gt(e,t.getToken())};var tt=K(require("@based/get-service")),te={},se={},yt=async(t,s)=>{if(s.url)return typeof s.url=="string"?s.url:await s.url();if(!t.opts.env&&t.opts.url)return typeof t.opts.url=="string"?t.opts.url:await t.opts.url();let{env:e,project:r,org:i}=t.opts,n=e+"/"+r+"/"+i+"/"+t.opts.cluster;if(te[n])return te[n];if(se[n])return(await se[n]).url;let o=await(se[n]=(0,tt.default)({env:e,project:r,org:i,name:"@based/hub",key:"file-upload",optionalKey:!0},0,t.opts.cluster));return delete se[n],setTimeout(()=>{delete te[n]},2e3),te[n]=o.url},st=yt;var it=K(require("cross-fetch")),ie=(t,s,e)=>((0,it.default)(s,{method:"POST",cache:"no-cache",headers:{"Content-Type":e.mimeType||"text/plain","File-Id":e.id,"File-Is-Raw":e.raw?"1":"0","File-Name":e.name||"","Function-Name":e.functionName||"",Authorization:t.getToken()},body:e.contents}).then(r=>{}).catch(r=>{console.error("Error while uploading file",r)}),{id:e.id});var A=require("./file/stream"),re=typeof window!="undefined",vt=t=>"src"in t&&typeof t.src=="string",kt=t=>"path"in t&&typeof t.path=="string",St=t=>"contents"in t&&(0,A.isStream)(t.contents),rt=async(t,s)=>{if(vt(s)){let i=s.id?{$id:s.id}:{type:"file"};return s.src?(i.src=s.src,i.origin=s.src,s.size&&(i.size=s.size),s.name&&(i.name=s.name),s.parents&&(i.parents=s.parents),await t.set(i)):void 0}let e=s.id;if(!e){let i={type:"file",progress:0};s.name?i.name=s.name:global.File&&"contents"in s&&s.contents instanceof global.File&&(i.name=s.contents.name),s.parents&&(i.parents=s.parents),e=(await t.set(i)).id}s.id=e;let r=(await st(t,s)).replace(/^ws/,"http");if(kt(s))return(0,A.uploadFilePath)(t,r,s),{id:e};if(St(s))return(0,A.uploadFileStream)(t,r,s),{id:e};if(s.contents instanceof ArrayBuffer)return s.contents=re?new global.Blob([s.contents],{type:s.mimeType||"text/plain"}):global.Buffer.from(s.contents),ie(t,r+"/file",s);if(re&&s.contents instanceof global.Blob)return s.mimeType||(s.mimeType=s.contents.type),ie(t,r+"/file",s);if(typeof s.contents=="string"||!re&&s.contents instanceof global.Buffer)return ie(t,r+"/file",s);if(re&&s.contents instanceof File)return et(t,s.contents,r,s.id,s.raw||!1,s.name,s.functionName),{id:e};throw s.id||await t.delete({$id:e}),new Error(`Invalid contents for file api ${JSON.stringify(s,null,2)}`)};var oe=K(require("@based/get-service")),Oe=require("@saulx/utils"),T=require("@based/graphql");p(m,require("@based/types"),module.exports);var ne=class extends Be{constructor(e){super();this.client=new x(this),Object.defineProperty(this,"client",{enumerable:!1,writable:!0}),e&&e.url&&this.connect(e.url),this.graphql={query:this.gqlQuery.bind(this),live:this.gqlLive.bind(this)}}connect(e){!e&&this._url?this.client.connection||(this.client.connection=le(this.client,this._url)):(this._url=e,this.client.connection=le(this.client,e))}disconnect(){this.client.connection&&(this.client.connection.disconnected=!0,this.client.connection.destroy(),this.client.connection.ws&&this.client.connection.ws.close(),this.client.connected&&this.client.onClose(),delete this.client.connection),this.client.connected=!1}observeUntil(e,r,i){return new Promise((n,o)=>{let c,a=!1;this.observe(e,(u,l)=>{i&&i(u,l),r(u,l)&&(a=!0,c&&c(),n(u))}).then(u=>{a?c():c=u}).catch(u=>{o(u)})})}gql(e,...r){typeof e=="string"&&(e=[e]);let i=e[0];return r.forEach((n,o)=>{n&&n.kind==="Document"?i+=n.loc.source.body:i+=n,i+=e[o+1]}),(0,T.createOperations)({schemas:this.client.configuration.schema},(0,T.parseGraphql)(i))}gqlDb(e="default"){return(r,...i)=>{typeof r=="string"&&(r=[r]);let n=r[0];return i.forEach((o,c)=>{o&&o.kind==="Document"?n+=o.loc.source.body:n+=o,n+=r[c+1]}),(0,T.createOperations)({schemas:this.client.configuration.schema,db:e},(0,T.parseGraphql)(n))}}observe(e,r,i,n){return typeof e=="string"?new Promise((o,c)=>{let a=typeof r=="function",u=a?r:i,l=a?i:n;I(this.client,a?void 0:r,u,(d,f,h,O,B)=>{d&&!B?c(d):o(()=>{v(this.client,f,h)})},l,void 0,e)}):new Promise((o,c)=>{I(this.client,e,r,(a,u,l,d,f)=>{a&&!f?c(a):o(()=>{v(this.client,u,l)})},i)})}createObservable(e,r){return typeof e=="string"?new C(this.client,e,r):new C(this.client,e)}observeSchema(e,r,i){return new Promise((n,o)=>{let c=typeof e=="string"?e:"default",a=typeof e=="string"?r:e,u=typeof e=="string"?i:r;I(this.client,{$subscribe_schema:c},(l,d)=>{this.client.configuration||(this.client.configuration={dbs:[],schema:{},functions:{}}),this.client.configuration.schema[c]=l,a(l,d)},(l,d,f,h,O)=>{l&&!O?o(l):n(()=>{v(this.client,d,f)})},u)})}get(e,r){return typeof e=="string"?new Promise((i,n)=>{V(this.client,r,(o,c,a,u)=>{o?n(o):i(u)},0,e)}):new Promise((i,n)=>{y(this.client,k.RequestTypes.Get,e,i,n)})}file(e){return global.File&&e instanceof File&&(e={contents:e}),rt(this,e)}call(e,r){return new Promise((i,n)=>{y(this.client,k.RequestTypes.Call,r,i,n,e)})}async id(e,r){let i=ge(this.client,e);if(i||(await this.schema(),i=ge(this.client,e)),!i)throw w({message:`Type does not exist ${e}`,type:"Invalid type",payload:r?{type:e,opts:r}:{type:e}});if(r){let n=(0,Te.hashCompact)(r,8,!0);return i+n}else return i+(0,Te.hashCompact)(Math.floor(Math.random()*99999999999)+""+Date.now())}digest(e){return new Promise((r,i)=>{y(this.client,k.RequestTypes.Digest,e,r,i)})}set(e){return new Promise((r,i)=>{y(this.client,k.RequestTypes.Set,e,r,i)})}copy(e){return new Promise((r,i)=>{y(this.client,k.RequestTypes.Copy,e,r,i)})}async gqlQuery(e,r={}){let i;typeof e=="string"?i=this.gql(e):i=e;try{if(i=(0,T.handleGraphqlVariables)(i,i,r),i.opType==="GET"){let o={$db:i.db},c=[];for(let u in i.ops){if(i.ops[u].fnObserve){let l=await this.get(i.ops[u].fnObserve.name,i.ops[u].fnObserve.payload);c.push({key:u,reply:l});continue}i.ops[u].get&&(o[u]=i.ops[u].get)}let a=await this.get(o);for(let{key:u,reply:l}of c)a[u]=l;return{data:a}}let n={};return await Promise.all(Object.entries(i.ops).map(async([o,c])=>{var d,f,h,O,B;if(c.delete){n[o]=await this.delete(c.delete);return}else if(c.fnCall){n[o]=await this.call(c.fnCall.name,c.fnCall.payload);return}let{id:a}=await this.set(c.set);if(!c.get){let Q={};Q.id=a;let we=(B=(O=(h=(f=(d=this.client)==null?void 0:d.configuration)==null?void 0:f.schema)==null?void 0:h[i.db])==null?void 0:O.prefixToTypeMapping)==null?void 0:B[a.slice(0,2)];we&&(Q.type=we),n[o]=Q;return}let u=(0,Oe.deepCopy)(c.get);u.$id=a;let l=await this.get(u);n[o]=l})),{data:n}}catch(n){return{errors:[{message:n.message,locations:n.locations}]}}}async gqlLive(e,r={}){let i;if(typeof e=="string"?i=this.gql(e):i=e,i=(0,T.handleGraphqlVariables)(i,i,r),i.opType==="GET"){let o=[],c={};for(let a in i.ops){if(i.ops[a].fnObserve){let{name:u,payload:l}=i.ops[a].fnObserve;o.push({key:a,fn:{name:u,payload:l}});continue}c[a]=i.ops[a].get}if(o!=null&&o.length){let a=o.map(l=>({obs:new C(this.client,l.fn.name,l.fn.payload),key:l.key})),u=new C(this.client,G({$db:i.db},c));return a.push({key:"",obs:u}),new ee(this.client,a)}return new C(this.client,{$db:i.db,data:c})}let n={};return await Promise.all(Object.entries(i.ops).map(async([o,c])=>{if(c.delete){n[o]=await this.delete(c.delete);return}else if(c.fnCall){n[o]=await this.call(c.fnCall.name,c.fnCall.payload);return}let{id:a}=await this.set(c.set),u=(0,Oe.deepCopy)(c.get);u.$id=a,n[o]=u})),new C(this.client,{$db:i.db,data:n})}analytics(e,r){return new Promise((i,n)=>{r?I(this.client,e,r,(o,c,a,u,l)=>{o&&!l?n(o):i(()=>{v(this.client,c,a)})},o=>console.error(o),void 0,"analytics"):V(this.client,e,(o,c,a,u)=>{o?n(o):((0,k.isAnalyticsHistoryOpts)(e)||(0,k.isAnalyticsTypesOpts)(e),i(u))},0,"analytics")})}track(e,r){N(this.client,e,r)}clearAnalytics(e,r){N(this.client,e,r,!1,!1,void 0,!0)}untrack(e,r){N(this.client,e,r,!0)}event(e,r,i){N(this.client,e,r,!1,!0,i)}delete(e){return new Promise((r,i)=>{y(this.client,k.RequestTypes.Delete,e,r,i)})}schema(){return new Promise((e,r)=>{let i=n=>{this.client.configuration=n,e(n)};y(this.client,k.RequestTypes.GetConfiguration,0,i,r)})}removeType(e,r="default"){return new Promise((i,n)=>{y(this.client,k.RequestTypes.RemoveType,{type:e,db:r},i,n)})}removeField(e,r,i="default"){return new Promise((n,o)=>{!r||r.length===0?o(new Error("Path cannot be empty")):(Array.isArray(r)||(r=[r]),y(this.client,k.RequestTypes.RemoveField,{type:e,db:i,path:r},n,o))})}updateSchema(e){return new Promise((r,i)=>{y(this.client,k.RequestTypes.Configuration,e,r,i)})}getToken(){return this.client.token}auth(e,r){return new Promise(i=>{if(this.client.auth.push(i),e&&e!==this.client.token||e===!1&&this.client.token){if(typeof e=="string"){let n=r||{},{renewOptions:o,refreshToken:c}=n,a=qe(n,["renewOptions","refreshToken"]);o&&(this.client.renewOptions=o),c&&(this.client.renewOptions=J(G({},this.client.renewOptions),{refreshToken:c})),E(this.client,e,a)}else E(this.client);this.emit("auth",e)}})}async login(e){return e.localStorage===!1?this.client.tokenToLocalStorage=!1:this.client.tokenToLocalStorage=!0,_e(this.client,e)}async register(e){return e.localStorage===!1?this.client.tokenToLocalStorage=!1:this.client.tokenToLocalStorage=!0,ze(this.client,e)}logout(){return We(this.client)}observeAuth(e){return new Promise(r=>{this.client.user&&this.client.token?e({id:this.client.user,token:this.client.token}):e(!1);let i=n=>{n&&this.client.user&&this.client.token?e({id:this.client.user,token:this.client.token}):e(!1)};this.on("auth",i),r(()=>{this.removeListener("auth",i)})})}},Tt=(t,s)=>{if(s){let e;t+=/\?/.test(t)?"&":"?";for(let r in s){let i=s[r];t+=e?`&${r}=${i}`:`${r}=${i}`,e=!0}}return t},Ot=(t,s=ne)=>{let{env:e,project:r,org:i,url:n,key:o,name:c="@based/hub",cluster:a,params:u}=t;if(n||(a=t.cluster=(0,oe.getClusterUrl)(a),n=async()=>{let{url:l}=await(0,oe.default)({env:e,project:r,org:i,key:o,name:c},0,a);return Tt(l,u)}),n){let l=new s;return l.opts=t,l.client.initUserState(),l.connect(n),l}},wt=Ot;0&&(module.exports={Based,BasedClient,BasedGraphQL,Observable,addGetSubscriber,addRequest,addSubscriber,createGraphqlOperations,generateSubscriptionId,generateTrackingKey,handleGraphqlVariables,parseGraphql,removeSubscriber}); |
@@ -38,3 +38,5 @@ "use strict"; | ||
} | ||
subscribe(onNext, onError, onComplete) { | ||
subscribe(onNext, onError, | ||
// eslint-disable-next-line | ||
onComplete) { | ||
const sharedResult = { data: {} }; | ||
@@ -68,3 +70,5 @@ const subs = []; | ||
} | ||
subscribe(onNext, onError, onComplete) { | ||
subscribe(onNext, onError, | ||
// eslint-disable-next-line | ||
onComplete) { | ||
const [, subscriberId] = (0, subscriptions_1.addSubscriber)(this.client, this.payload, onNext, (err) => { | ||
@@ -71,0 +75,0 @@ if (err) { |
{ | ||
"name": "@based/client", | ||
"version": "3.0.0", | ||
"version": "3.0.1", | ||
"license": "MIT", | ||
@@ -5,0 +5,0 @@ "main": "dist/index.js", |
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
286956
2751