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