@based/client
Advanced tools
Comparing version 2.4.0 to 2.5.0
import { Connection } from './websocket/types'; | ||
import { GenericObject, RequestMessage, SubscriptionMessage, FunctionCallMessage, Configuration, TrackMessage, SendTokenOptions } from '@based/types'; | ||
import { Based } from './'; | ||
export * from './types'; | ||
export * from '@based/types'; | ||
export declare class BasedClient { | ||
@@ -6,0 +6,0 @@ based: Based; |
@@ -26,3 +26,3 @@ "use strict"; | ||
const token_1 = __importDefault(require("./token")); | ||
__exportStar(require("./types"), exports); | ||
__exportStar(require("@based/types"), exports); | ||
class BasedClient { | ||
@@ -94,3 +94,5 @@ constructor(based) { | ||
data[0] === types_1.RequestTypes.Copy || | ||
data[0] === types_1.RequestTypes.Digest) { | ||
data[0] === types_1.RequestTypes.Digest || | ||
data[0] === types_1.RequestTypes.RemoveType || | ||
data[0] === types_1.RequestTypes.RemoveField) { | ||
(0, request_1.incomingRequest)(this, data); | ||
@@ -97,0 +99,0 @@ } |
@@ -87,2 +87,8 @@ import Emitter from './Emitter'; | ||
schema(): Promise<Configuration>; | ||
removeType(type: string, db?: string): Promise<{ | ||
removed: boolean; | ||
}>; | ||
removeField(type: string, path: string | string[], db?: string): Promise<{ | ||
removed: boolean; | ||
}>; | ||
updateSchema(configuration: { | ||
@@ -89,0 +95,0 @@ schema?: GenericObject; |
@@ -1,5 +0,5 @@ | ||
var Le=Object.create;var R=Object.defineProperty;var He=Object.getOwnPropertyDescriptor;var _e=Object.getOwnPropertyNames,he=Object.getOwnPropertySymbols,ze=Object.getPrototypeOf,ye=Object.prototype.hasOwnProperty,Je=Object.prototype.propertyIsEnumerable;var ge=(t,s,e)=>s in t?R(t,s,{enumerable:!0,configurable:!0,writable:!0,value:e}):t[s]=e,ve=(t,s)=>{for(var e in s||(s={}))ye.call(s,e)&&ge(t,e,s[e]);if(he)for(var e of he(s))Je.call(s,e)&&ge(t,e,s[e]);return t};var Ke=(t,s)=>{for(var e in s)R(t,e,{get:s[e],enumerable:!0})},j=(t,s,e,i)=>{if(s&&typeof s=="object"||typeof s=="function")for(let r of _e(s))!ye.call(t,r)&&r!==e&&R(t,r,{get:()=>s[r],enumerable:!(i=He(s,r))||i.enumerable});return t},b=(t,s,e)=>(j(t,s,"default"),e&&j(e,s,"default")),N=(t,s,e)=>(e=t!=null?Le(ze(t)):{},j(s||!t||!t.__esModule?R(e,"default",{value:t,enumerable:!0}):e,t)),We=t=>j(R({},"__esModule",{value:!0}),t);var f={};Ke(f,{Based:()=>Z,BasedClient:()=>A,BasedGraphQL:()=>y.BasedGraphQL,Observable:()=>T,addGetSubscriber:()=>L,addRequest:()=>O,addSubscriber:()=>B,createGraphqlOperations:()=>y.createOperations,default:()=>ct,generateSubscriptionId:()=>C,generateTrackingKey:()=>ue,handleGraphqlVariables:()=>y.handleGraphqlVariables,parseGraphql:()=>y.parseGraphql,removeSubscriber:()=>g});module.exports=We(f);var te=class{constructor(){this.listeners={};Object.defineProperty(this,"listeners",{enumerable:!1,writable:!0})}emit(s,e){this.listeners[s]&&this.listeners[s].forEach(i=>i(e))}on(s,e){this.listeners[s]||(this.listeners[s]=[]),this.listeners[s].push(e)}removeAllListeners(){this.listeners={}}once(s,e){this.on(s,i=>{e(i),this.removeListener(s,e)})}removeListener(s,e){let i=this.listeners[s];if(i){if(!e)delete this.listeners[s];else for(let r=0,n=i.length;r<n;r++)if(i[r]===e){i.splice(r,1);break}}}},Se=te;var ke=(t,s)=>{typeof t=="function"?t().then(e=>{s(e)}):s(t)};var Te=N(require("isomorphic-ws")),U=new Map,Oe;typeof window!="undefined"&&document.addEventListener("visibilitychange",function(t){clearTimeout(Oe),document.hidden?Oe=setTimeout(()=>{U.forEach(s=>{s(!1)})},3e4):U.forEach(s=>{s(!0)})});var se=(t,s,e={destroy:()=>{U.delete(e)}},i=0,r=!1)=>(ke(s,n=>{setTimeout(()=>{if(e.disconnected)return;let o=!0;U.set(e,a=>{e.disconnected||(!a&&o?(console.warn("Send to background - close connection"),o=!1,t.onClose(),c.close()):!o&&a&&(U.delete(e),se(t,s,e,0,!0)))});let c=e.ws=new Te.default(n);c.onerror=()=>{},c.onmessage=a=>t.onData(a),c.onopen=()=>{if(o){if(e.disconnected)return;i=100,r&&t.onReconnect(),t.onOpen()}},c.onclose=()=>{if(o){if(e.disconnected)return;t.onClose(),se(t,s,e,Math.min(1250,Math.min(i+500)),!0)}}},i)}),e),re=se;var k=require("@based/types");var E=require("@based/types");var x=require("@based/types");var Ve=t=>{clearTimeout(t.idlePing),t.idlePing=setTimeout(()=>{t.connection&&t.connected&&!t.connection.disconnected&&t.connection.ws.send("1")},6e4)},M=Ve;var m=(t,s)=>{s[0]===x.RequestTypes.Unsubscribe||s[0]===x.RequestTypes.Subscription||s[0]===x.RequestTypes.SendSubscriptionData||s[0]===x.RequestTypes.GetSubscription?t.subscriptionQueue.push(s):t.queue.push(s),t.connected&&!t.drainInProgress&&ie(t)},ie=t=>{t.connected&&!t.drainInProgress&&(t.queue.length||t.subscriptionQueue.length)&&(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.connection.ws.send(JSON.stringify(s)),M(t)}},0))},Ce=t=>{t.drainInProgress&&(clearTimeout(t.drainTimeout),t.drainInProgress=!1)};var ne=require("@saulx/hash"),C=(t,s)=>s?(0,ne.hashObjectIgnoreKeyOrder)([s,t]):(0,ne.hashObjectIgnoreKeyOrder)(t);var L=(t,s,e,i,r)=>{i||(i=C(s,r));let n=t.subscriptions[i],o=t.cache[i];if(n)if(n.authError)if(!t.beingAuth)e(n.authError.error,i,0);else{let c=++n.cnt;n.subscribers[c]={onInitial:e}}else if(o)e(null,i,0,o.value);else{let c=++n.cnt;n.subscribers[c]={onInitial:e}}else{n=t.subscriptions[i]={query:s,cnt:1,name:r,subscribers:{1:{onInitial:e}}};let c;for(let a=0;a<t.subscriptionQueue.length;a++){let[u,l,,p]=t.subscriptionQueue[a];(u===E.RequestTypes.Unsubscribe||u===E.RequestTypes.SendSubscriptionData)&&l===i?(t.subscriptionQueue.splice(a,1),a--):(u===E.RequestTypes.Subscription||u===E.RequestTypes.GetSubscription)&&l===i&&(c=!0,u===E.RequestTypes.Subscription&&(p!==o.checksum&&(t.subscriptionQueue[a][3]=o.checksum),t.subscriptionQueue[a][4]=2))}if(!c){let a=[E.RequestTypes.GetSubscription,i,s];o&&a.push(o.checksum),r&&(o||a.push(0),a.push(r)),m(t,a)}}};var w=require("@based/types");var B=(t,s,e,i,r,n,o)=>{n||(n=C(s,o));let c=t.subscriptions[n],a=t.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:e,onInitial:i},l){for(let d=0;d<t.subscriptionQueue.length;d++){let[h,v]=t.subscriptionQueue[d];h===w.RequestTypes.GetSubscription&&v===n&&(t.subscriptionQueue.splice(d,1),d--)}let p=[w.RequestTypes.Subscription,n,s];a&&(p.push(a.checksum),p.push(2)),o&&(a||p.push(0,2),p.push(o)),m(t,p)}}else{u=1,c=t.subscriptions[n]={query:s,cnt:1,name:o,subscribers:{1:{onError:r,onData:e,onInitial:i}}};let l=!1,p=!1,d;for(let h=0;h<t.subscriptionQueue.length;h++){let[v,P,,F]=t.subscriptionQueue[h];(v===w.RequestTypes.Unsubscribe||v===w.RequestTypes.SendSubscriptionData||v===w.RequestTypes.GetSubscription)&&P===n?(v===w.RequestTypes.GetSubscription&&(p=!0),d&&(d[4]=2),t.subscriptionQueue.splice(h,1),h--):v===w.RequestTypes.Subscription&&P===n&&(l=!0,d=t.subscriptionQueue[h],F!==a.checksum&&(d[3]=a.checksum),!d[4]&&p&&(d[4]=2))}if(!l){let h=[w.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)),m(t,h)}}return a&&(i&&(i(null,n,u),delete c.subscribers[u].onInitial),e&&e(a.value,a.checksum)),[n,u]};var D=require("@based/types");var g=(t,s,e)=>{let i=t.subscriptions[s];if(i){let r=!1;if(e?i.subscribers[e]&&(delete i.subscribers[e],i.cnt--,i.cnt===0&&(r=!0)):r=!0,r){delete t.subscriptions[s];let n=!1;for(let o=0;o<t.subscriptionQueue.length;o++){let[c,a]=t.subscriptionQueue[o];c===D.RequestTypes.Unsubscribe&&a===s?n=!0:(c===D.RequestTypes.Subscription||c===D.RequestTypes.SendSubscriptionData)&&a===s&&(t.subscriptionQueue.splice(o,1),o--)}n||m(t,[D.RequestTypes.Unsubscribe,s])}}};var we=require("@based/types"),Pe=t=>{for(let s=0;s<t.subscriptionQueue.length;s++)t.subscriptionQueue[s][0]===we.RequestTypes.Unsubscribe&&(t.subscriptionQueue.splice(s,1),s--)};var Be=require("@based/types"),qe=t=>{for(let s=0;s<t.subscriptionQueue.length;s++)t.subscriptionQueue[s][0]===Be.RequestTypes.SendSubscriptionData&&(t.subscriptionQueue.splice(s,1),s--)};var H=(t,s=!1)=>{for(let e in t.subscriptions){let i=Number(e),r=t.subscriptions[e];if(s&&!r.authError)continue;let n,o,c;for(let l=0;l<t.subscriptionQueue.length;l++){let[p,d]=t.subscriptionQueue[l];d===i&&(p===10?(c=l,n=t.subscriptionQueue[l]):p===1&&(o=t.subscriptionQueue[l]))}n&&o&&console.error("GET IN Q AND SUB IN Q SHOULD BE IMPOSSIBLE");let a=t.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"),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:p}=t.subscriptions[i];l?a?m(t,[1,i,p,a.checksum,n?2:0,l]):m(t,[1,i,p,0,n?2:0,l]):a?m(t,[1,i,p,a.checksum,n?2:0]):m(t,[1,i,p,0,n?2:0])}}};var _=(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}`},oe=(t,s=0,e=!1,i="",r=!1)=>{let n="";for(let a=0;a<s;a++)n+=" ";let o=e?[]:i?[n+`${_(i,r?"brightRed":"white")} {`]:[n+"{"],c=!1;e||(n+=" ",s+=1);for(let a in t){let u=t[a],l=a[0]==="$"?_(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 d=u[p];o.push(...d&&typeof d=="object"?oe(d,s+4):[`${n} ${d}`]),p!==u.length-1&&(o[o.length-1]+=",")}o.push(`${n} ]`)}else u&&typeof u=="object"?(o.push(`${n} ${l}: {`),o.push(...oe(u,s+2,!0)),o.push(`${n} }`)):o.push(`${n} ${l}: ${u}`);c=!0}return e||o.push(n.slice(0,-1)+"}"),o},z=oe;var q=t=>{let s=new Error(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(` | ||
var ze=Object.create;var D=Object.defineProperty;var Je=Object.getOwnPropertyDescriptor;var Ke=Object.getOwnPropertyNames,ye=Object.getOwnPropertySymbols,We=Object.getPrototypeOf,Se=Object.prototype.hasOwnProperty,Ve=Object.prototype.propertyIsEnumerable;var ve=(t,s,e)=>s in t?D(t,s,{enumerable:!0,configurable:!0,writable:!0,value:e}):t[s]=e,ke=(t,s)=>{for(var e in s||(s={}))Se.call(s,e)&&ve(t,e,s[e]);if(ye)for(var e of ye(s))Ve.call(s,e)&&ve(t,e,s[e]);return t};var Te=(t,s)=>{for(var e in s)D(t,e,{get:s[e],enumerable:!0})},M=(t,s,e,i)=>{if(s&&typeof s=="object"||typeof s=="function")for(let r of Ke(s))!Se.call(t,r)&&r!==e&&D(t,r,{get:()=>s[r],enumerable:!(i=Je(s,r))||i.enumerable});return t},d=(t,s,e)=>(M(t,s,"default"),e&&M(e,s,"default")),L=(t,s,e)=>(e=t!=null?ze(We(t)):{},M(s||!t||!t.__esModule?D(e,"default",{value:t,enumerable:!0}):e,t)),Xe=t=>M(D({},"__esModule",{value:!0}),t);var b={};Te(b,{Based:()=>te,BasedClient:()=>U,BasedGraphQL:()=>S.BasedGraphQL,Observable:()=>C,addGetSubscriber:()=>_,addRequest:()=>T,addSubscriber:()=>F,createGraphqlOperations:()=>S.createOperations,default:()=>lt,generateSubscriptionId:()=>w,generateTrackingKey:()=>pe,handleGraphqlVariables:()=>S.handleGraphqlVariables,parseGraphql:()=>S.parseGraphql,removeSubscriber:()=>g});module.exports=Xe(b);var re=class{constructor(){this.listeners={};Object.defineProperty(this,"listeners",{enumerable:!1,writable:!0})}emit(s,e){this.listeners[s]&&this.listeners[s].forEach(i=>i(e))}on(s,e){this.listeners[s]||(this.listeners[s]=[]),this.listeners[s].push(e)}removeAllListeners(){this.listeners={}}once(s,e){this.on(s,i=>{e(i),this.removeListener(s,e)})}removeListener(s,e){let i=this.listeners[s];if(i){if(!e)delete this.listeners[s];else for(let r=0,n=i.length;r<n;r++)if(i[r]===e){i.splice(r,1);break}}}},Oe=re;var Ce=(t,s)=>{typeof t=="function"?t().then(e=>{s(e)}):s(t)};var Pe=L(require("isomorphic-ws")),I=new Map,we;typeof window!="undefined"&&document.addEventListener("visibilitychange",function(){clearTimeout(we),document.hidden?we=setTimeout(()=>{I.forEach(t=>{t(!1)})},3e4):I.forEach(t=>{t(!0)})});var ie=(t,s,e={destroy:()=>{I.delete(e)}},i=0,r=!1)=>(Ce(s,n=>{setTimeout(()=>{if(e.disconnected)return;let o=!0;I.set(e,a=>{e.disconnected||(!a&&o?(console.warn("Send to background - close connection"),o=!1,t.onClose(),c.close()):!o&&a&&(I.delete(e),ie(t,s,e,0,!0)))});let c=e.ws=new Pe.default(n);c.onerror=()=>{},c.onmessage=a=>t.onData(a),c.onopen=()=>{if(o){if(e.disconnected)return;i=100,r&&t.onReconnect(),t.onOpen()}},c.onclose=()=>{if(o){if(e.disconnected)return;t.onClose(),ie(t,s,e,Math.min(1250,Math.min(i+500)),!0)}}},i)}),e),ne=ie;var v=require("@based/types");var E=require("@based/types");var A=require("@based/types");var Ye=t=>{clearTimeout(t.idlePing),t.idlePing=setTimeout(()=>{t.connection&&t.connected&&!t.connection.disconnected&&t.connection.ws.send("1")},6e4)},H=Ye;var m=(t,s)=>{s[0]===A.RequestTypes.Unsubscribe||s[0]===A.RequestTypes.Subscription||s[0]===A.RequestTypes.SendSubscriptionData||s[0]===A.RequestTypes.GetSubscription?t.subscriptionQueue.push(s):t.queue.push(s),t.connected&&!t.drainInProgress&&oe(t)},oe=t=>{t.connected&&!t.drainInProgress&&(t.queue.length||t.subscriptionQueue.length)&&(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.connection.ws.send(JSON.stringify(s)),H(t)}},0))},Be=t=>{t.drainInProgress&&(clearTimeout(t.drainTimeout),t.drainInProgress=!1)};var ae=require("@saulx/hash"),w=(t,s)=>s?(0,ae.hashObjectIgnoreKeyOrder)([s,t]):(0,ae.hashObjectIgnoreKeyOrder)(t);var _=(t,s,e,i,r)=>{i||(i=w(s,r));let n=t.subscriptions[i],o=t.cache[i];if(n)if(n.authError)if(!t.beingAuth)e(n.authError.error,i,0);else{let c=++n.cnt;n.subscribers[c]={onInitial:e}}else if(o)e(null,i,0,o.value);else{let c=++n.cnt;n.subscribers[c]={onInitial:e}}else{n=t.subscriptions[i]={query:s,cnt:1,name:r,subscribers:{1:{onInitial:e}}};let c;for(let a=0;a<t.subscriptionQueue.length;a++){let[u,l,,p]=t.subscriptionQueue[a];(u===E.RequestTypes.Unsubscribe||u===E.RequestTypes.SendSubscriptionData)&&l===i?(t.subscriptionQueue.splice(a,1),a--):(u===E.RequestTypes.Subscription||u===E.RequestTypes.GetSubscription)&&l===i&&(c=!0,u===E.RequestTypes.Subscription&&(p!==o.checksum&&(t.subscriptionQueue[a][3]=o.checksum),t.subscriptionQueue[a][4]=2))}if(!c){let a=[E.RequestTypes.GetSubscription,i,s];o&&a.push(o.checksum),r&&(o||a.push(0),a.push(r)),m(t,a)}}};var P=require("@based/types");var F=(t,s,e,i,r,n,o)=>{n||(n=w(s,o));let c=t.subscriptions[n],a=t.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:e,onInitial:i},l){for(let f=0;f<t.subscriptionQueue.length;f++){let[h,k]=t.subscriptionQueue[f];h===P.RequestTypes.GetSubscription&&k===n&&(t.subscriptionQueue.splice(f,1),f--)}let p=[P.RequestTypes.Subscription,n,s];a&&(p.push(a.checksum),p.push(2)),o&&(a||p.push(0,2),p.push(o)),m(t,p)}}else{u=1,c=t.subscriptions[n]={query:s,cnt:1,name:o,subscribers:{1:{onError:r,onData:e,onInitial:i}}};let l=!1,p=!1,f;for(let h=0;h<t.subscriptionQueue.length;h++){let[k,B,,R]=t.subscriptionQueue[h];(k===P.RequestTypes.Unsubscribe||k===P.RequestTypes.SendSubscriptionData||k===P.RequestTypes.GetSubscription)&&B===n?(k===P.RequestTypes.GetSubscription&&(p=!0),f&&(f[4]=2),t.subscriptionQueue.splice(h,1),h--):k===P.RequestTypes.Subscription&&B===n&&(l=!0,f=t.subscriptionQueue[h],R!==a.checksum&&(f[3]=a.checksum),!f[4]&&p&&(f[4]=2))}if(!l){let h=[P.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)),m(t,h)}}return a&&(i&&(i(null,n,u),delete c.subscribers[u].onInitial),e&&e(a.value,a.checksum)),[n,u]};var G=require("@based/types");var g=(t,s,e)=>{let i=t.subscriptions[s];if(i){let r=!1;if(e?i.subscribers[e]&&(delete i.subscribers[e],i.cnt--,i.cnt===0&&(r=!0)):r=!0,r){delete t.subscriptions[s];let n=!1;for(let o=0;o<t.subscriptionQueue.length;o++){let[c,a]=t.subscriptionQueue[o];c===G.RequestTypes.Unsubscribe&&a===s?n=!0:(c===G.RequestTypes.Subscription||c===G.RequestTypes.SendSubscriptionData)&&a===s&&(t.subscriptionQueue.splice(o,1),o--)}n||m(t,[G.RequestTypes.Unsubscribe,s])}}};var Fe=require("@based/types"),qe=t=>{for(let s=0;s<t.subscriptionQueue.length;s++)t.subscriptionQueue[s][0]===Fe.RequestTypes.Unsubscribe&&(t.subscriptionQueue.splice(s,1),s--)};var Ee=require("@based/types"),Qe=t=>{for(let s=0;s<t.subscriptionQueue.length;s++)t.subscriptionQueue[s][0]===Ee.RequestTypes.SendSubscriptionData&&(t.subscriptionQueue.splice(s,1),s--)};var Q=require("@based/types");var z=(t,s=!1)=>{for(let e in t.subscriptions){let i=Number(e),r=t.subscriptions[e];if(s&&!r.authError)continue;let n,o,c;for(let l=0;l<t.subscriptionQueue.length;l++){let[p,f]=t.subscriptionQueue[l];f===i&&(p===Q.RequestTypes.GetSubscription?(c=l,n=t.subscriptionQueue[l]):p===Q.RequestTypes.Subscription&&(o=t.subscriptionQueue[l]))}n&&o&&console.error("GET IN Q AND SUB IN Q SHOULD BE IMPOSSIBLE");let a=t.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"),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:p}=t.subscriptions[i];l?a?m(t,[Q.RequestTypes.Subscription,i,p,a.checksum,n?2:0,l]):m(t,[Q.RequestTypes.Subscription,i,p,0,n?2:0,l]):a?m(t,[Q.RequestTypes.Subscription,i,p,a.checksum,n?2:0]):m(t,[Q.RequestTypes.Subscription,i,p,0,n?2:0])}}};var J=(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}`},ce=(t,s=0,e=!1,i="",r=!1)=>{let n="";for(let a=0;a<s;a++)n+=" ";let o=e?[]:i?[n+`${J(i,r?"brightRed":"white")} {`]:[n+"{"],c=!1;e||(n+=" ",s+=1);for(let a in t){let u=t[a],l=a[0]==="$"?J(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 f=u[p];o.push(...f&&typeof f=="object"?ce(f,s+4):[`${n} ${f}`]),p!==u.length-1&&(o[o.length-1]+=",")}o.push(`${n} ]`)}else u&&typeof u=="object"?(o.push(`${n} ${l}: {`),o.push(...ce(u,s+2,!0)),o.push(`${n} }`)):o.push(`${n} ${l}: ${u}`);c=!0}return e||o.push(n.slice(0,-1)+"}"),o},K=ce;var q=t=>{let s=new Error(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(` | ||
`),i=0;e[0]===""&&e.shift();let r=e[0];for(let n=0;n<r.length;n++)if(r[n]!==" "){i=n-2;break}i>0?e=e.map(n=>n.slice(i)):e=e.map(n=>" "+n),t.code&&(s.code=t.code),s.message=` | ||
`+(t.payload&&typeof t.payload!="object"?` ${_("Payload","brightRed")} ${t.payload}`:z(t.payload||t.query,0,!1,t.payload?"Payload":"Query",!0).map(n=>" "+n).join(` | ||
`+(t.payload&&typeof t.payload!="object"?` ${J("Payload","brightRed")} ${t.payload}`:K(t.payload||t.query,0,!1,t.payload?"Payload":"Query",!0).map(n=>" "+n).join(` | ||
`))+` | ||
@@ -10,7 +10,7 @@ | ||
`}return s};var Ee=(t,s)=>{let[,e,i,r,n]=s,o=t.subscriptions[e];if(o){let c=t.cache[e]&&t.cache[e].checksum;if(n){let a=q(n);n.auth&&(o.authError={token:t.token,error:a});for(let u in o.subscribers){let l=o.subscribers[u];l.onInitial?n.auth?(l.onError&&l.onError(a),l.onInitial(a,Number(e),Number(u),void 0,!0),delete l.onInitial):(l.onInitial(a,Number(e),Number(u)),delete l.onInitial,g(t,e,Number(u))):l.onError&&l.onError(a)}}else if(c===r){o.authError&&delete o.authError;for(let a in o.subscribers){let u=o.subscribers[a];u.onInitial&&(u.onInitial(null,Number(e),Number(a),t.cache[e].value),delete u.onInitial,u.onData||g(t,e,Number(a)))}}else{o.authError&&delete o.authError,t.cache[e]={value:i,checksum:r};for(let a in o.subscribers){let u=o.subscribers[a];u.onInitial&&(u.onInitial(null,Number(e),Number(a),i),delete u.onInitial,u.onData||g(t,e,Number(a))),u.onData&&u.onData(i,r)}}}};var Fe=require("@saulx/diff"),J=require("@based/types");var Qe=(t,s)=>{let[,e,i,[r,n]]=s,o=t.subscriptions[e];if(o){let c=t.cache[e];if(!c||c.checksum!==r)if(c)if(c.checksum===n)for(let a in o.subscribers){let u=o.subscribers[a];u.onInitial&&(u.onInitial(null,Number(e),Number(a),c.value),delete u.onInitial,u.onData||g(t,e,Number(a)))}else m(t,[J.RequestTypes.SendSubscriptionData,e]);else m(t,[J.RequestTypes.SendSubscriptionData,e]);else{let a=!1;try{c.value=(0,Fe.applyPatch)(c.value,i),c.value===null&&(a=!0)}catch(u){a=!0}if(a)console.warn(` | ||
`}return s};var Re=(t,s)=>{let[,e,i,r,n]=s,o=t.subscriptions[e];if(o){let c=t.cache[e]&&t.cache[e].checksum;if(n){let a=q(n);n.auth&&(o.authError={token:t.token,error:a});for(let u in o.subscribers){let l=o.subscribers[u];l.onInitial?n.auth?(l.onError&&l.onError(a),l.onInitial(a,Number(e),Number(u),void 0,!0),delete l.onInitial):(l.onInitial(a,Number(e),Number(u)),delete l.onInitial,g(t,e,Number(u))):l.onError&&l.onError(a)}}else if(c===r){o.authError&&delete o.authError;for(let a in o.subscribers){let u=o.subscribers[a];u.onInitial&&(u.onInitial(null,Number(e),Number(a),t.cache[e].value),delete u.onInitial,u.onData||g(t,e,Number(a)))}}else{o.authError&&delete o.authError,t.cache[e]={value:i,checksum:r};for(let a in o.subscribers){let u=o.subscribers[a];u.onInitial&&(u.onInitial(null,Number(e),Number(a),i),delete u.onInitial,u.onData||g(t,e,Number(a))),u.onData&&u.onData(i,r)}}}};var Ue=require("@saulx/diff"),W=require("@based/types");var xe=(t,s)=>{let[,e,i,[r,n]]=s,o=t.subscriptions[e];if(o){let c=t.cache[e];if(!c||c.checksum!==r)if(c)if(c.checksum===n)for(let a in o.subscribers){let u=o.subscribers[a];u.onInitial&&(u.onInitial(null,Number(e),Number(a),c.value),delete u.onInitial,u.onData||g(t,e,Number(a)))}else m(t,[W.RequestTypes.SendSubscriptionData,e]);else m(t,[W.RequestTypes.SendSubscriptionData,e]);else{let a=!1;try{c.value=(0,Ue.applyPatch)(c.value,i),c.value===null&&(a=!0)}catch(u){a=!0}if(a)console.warn(` | ||
Found corrupt data while applying diff to subscription need to re-fetch | ||
`),console.warn(z(o.query,2,!1,"Query").join(` | ||
`),console.warn(K(o.query,2,!1,"Query").join(` | ||
`)+` | ||
`),delete t.cache[e],m(t,[J.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||g(t,e,Number(u))),l.onData&&l.onData(c.value,c.checksum)}}}}};var Re=(t,s)=>{for(let e of s[1]){delete t.cache[e];let i=t.subscriptions[e];if(i){let r={type:"AuthorizationError",name:i.name?`observe "${i.name}"`:"observe",message:"Unauthorized request",payload:i.query,auth:!0},n=q(r);i.authError={token:t.token,error:n};for(let o in i.subscribers){let c=i.subscribers[o];c.onError&&c.onError(n)}}}};var Ue=require("@based/types");var Xe=0,O=(t,s,e,i,r,n)=>{let o=++Xe;t.requestCallbacks[o]={resolve:i,reject:r},s===Ue.RequestTypes.Call?m(t,[s,n,o,e]):m(t,[s,o,e])};var xe=(t,s)=>{let[,e,i,r]=s,n=t.requestCallbacks[e];n&&(delete t.requestCallbacks[e],r?n.reject(q(r)):n.resolve(i))};var S=require("@based/types");var ae=require("@based/types");var Ye=t=>typeof t!="undefined"&&t!==null,Ze=(t,s,e)=>{if(t.beingAuth=!0,s)t.token=s,t.sendTokenOptions=e;else{for(let i in t.cache)t.subscriptions[i]||delete t.cache[i];delete t.token,delete t.sendTokenOptions}if(t.connected){let i=s?[ae.RequestTypes.Token,s,e].filter(Ye):[ae.RequestTypes.Token];t.connection.ws.send(JSON.stringify(i)),M(t),H(t,!0)}},I=Ze;var A=class{constructor(s){this.auth=[];this.subscriptions={};this.cache={};this.requestCallbacks={};this.connected=!1;this.subscriptionQueue=[];this.queue=[];this.drainInProgress=!1;this.based=s}onClose(){this.connected=!1,Ce(this),Pe(this),qe(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)m(this,[S.RequestTypes.Track,{t:s}])}onOpen(){this.connected=!0,this.based.listeners.connect&&this.based.listeners.connect.forEach(s=>s()),this.token&&I(this,this.token,this.sendTokenOptions),H(this),ie(this)}onData(s){try{let e=JSON.parse(s.data);if(e[0]===S.RequestTypes.Token){e[1].length&&Re(this,e);for(let i of this.auth)i(!e[2]);this.beingAuth=!1,this.auth=[]}else e[0]===S.RequestTypes.Set||e[0]===S.RequestTypes.Get||e[0]===S.RequestTypes.Configuration||e[0]===S.RequestTypes.GetConfiguration||e[0]===S.RequestTypes.Call||e[0]===S.RequestTypes.Delete||e[0]===S.RequestTypes.Copy||e[0]===S.RequestTypes.Digest?xe(this,e):e[0]===S.RequestTypes.Subscription?Ee(this,e):e[0]===S.RequestTypes.SubscriptionDiff&&Qe(this,e)}catch(e){console.error("Received incorrect data ",s)}}};var ce=(t,s)=>{let e;if(t.configuration&&t.configuration.schema)for(let i in t.configuration.schema){let r=t.configuration.schema[i];if(r.prefixToTypeMapping){for(let n in r.prefixToTypeMapping)if(r.prefixToTypeMapping[n]===s){e=n;break}}}return e};var fe=require("@saulx/hash");var Ie=require("@based/types"),Ae=require("@saulx/hash"),De=new Set,et=t=>{if(typeof window!="undefined"){if(De.has(t))return!1;De.add(t);try{let s="_ba:"+(0,Ae.hashCompact)(t);return localStorage.getItem(s)?!1:(localStorage.setItem(s,"1"),!0)}catch(s){return!1}}return!1},ue=(t,s)=>{if(s){let e=`${t}`,i=Object.keys(s).sort();for(let r of i)e+="_"+r+"_"+s[r];return e}else return t},G=(t,s,e,i,r,n,o)=>{let c=ue(s,e),a={t:c};o&&(a.r=1),r&&(a.e=1,n&&(a.o=n)),i?(a.s=1,t.tracking.delete(c)):o||(r||(t.tracking||(t.tracking=new Set),t.tracking.add(c)),et(c)&&(a.u=1)),m(t,[Ie.RequestTypes.Track,a])};var le=class{constructor(s,e,i){this.closed=!1;this.client=s,this.subId=i,this.subscriberId=e}unsubscribe(){this.closed=!0,g(this.client,this.subId,this.subscriberId)}},pe=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()}}},K=class{constructor(s,e){this.client=s,this.components=e}subscribe(s,e,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)},e);n.push(a)}return new pe(this.client,n)}},T=class{constructor(s,e,i){this.client=s,this.subId=typeof e=="string"?C(i,e):C(e),this.name=typeof e=="string"?e:null,this.payload=typeof e=="string"?i:e}subscribe(s,e,i){let[,r]=B(this.client,this.payload,s,n=>{n&&(console.error(n),e&&e(n))},e,this.subId,this.name);return new le(this.client,r,this.subId)}};var de={},$={},tt=(t,s)=>{de[t]||(de[t]=!0,setTimeout(()=>{console.info("Drain file q"),de[t]=!1;let e=$[t];$[t]=[];let i=new global.FormData;for(let r of e){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",t+"/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))},Ge=async(t,s,e,i,r,n,o)=>{$[e]||($[e]=[]),$[e].push({file:s,id:i,url:e,raw:r,name:n,functionName:o}),tt(e,t.getToken())};var $e=N(require("@based/get-service")),W={},V={},st=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:i,org:r}=t.opts,n=e+"/"+i+"/"+r+"/"+t.opts.cluster;if(W[n])return W[n];if(V[n])return(await V[n]).url;let o=await(V[n]=(0,$e.default)({env:e,project:i,org:r,name:"@based/hub",key:"file-upload",optionalKey:!0},0,t.opts.cluster));return delete V[n],setTimeout(()=>{delete W[n]},2e3),W[n]=o.url},je=st;var Ne=N(require("cross-fetch")),X=(t,s,e)=>((0,Ne.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(i=>{}).catch(i=>{console.error("Error while uploading file",i)}),{id:e.id});var Q=require("./file/stream"),Y=typeof window!="undefined",rt=t=>"src"in t&&typeof t.src=="string",it=t=>"path"in t&&typeof t.path=="string",nt=t=>"contents"in t&&(0,Q.isStream)(t.contents),Me=async(t,s)=>{if(rt(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 t.set(r)):void 0}let e=s.id;if(!e){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),e=(await t.set(r)).id}s.id=e;let i=(await je(t,s)).replace(/^ws/,"http");if(it(s))return(0,Q.uploadFilePath)(t,i,s),{id:e};if(nt(s))return(0,Q.uploadFileStream)(t,i,s),{id:e};if(s.contents instanceof ArrayBuffer)return s.contents=Y?new global.Blob([s.contents],{type:s.mimeType||"text/plain"}):global.Buffer.from(s.contents),X(t,i+"/file",s);if(Y&&s.contents instanceof global.Blob)return s.mimeType||(s.mimeType=s.contents.type),X(t,i+"/file",s);if(typeof s.contents=="string"||!Y&&s.contents instanceof global.Buffer)return X(t,i+"/file",s);if(Y&&s.contents instanceof File)return Ge(t,s.contents,i,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 ee=N(require("@based/get-service")),be=require("@saulx/utils"),y=require("@based/graphql");b(f,require("@based/types"),module.exports);var Z=class extends Se{constructor(e){super();this.client=new A(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=re(this.client,this._url)):(this._url=e,this.client.connection=re(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,i,r){return new Promise((n,o)=>{let c,a=!1;this.observe(e,(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(e,...i){typeof e=="string"&&(e=[e]);let r=e[0];return i.forEach((n,o)=>{n&&n.kind==="Document"?r+=n.loc.source.body:r+=n,r+=e[o+1]}),(0,y.createOperations)({schemas:this.client.configuration.schema},(0,y.parseGraphql)(r))}gqlDb(e="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,y.createOperations)({schemas:this.client.configuration.schema,db:e},(0,y.parseGraphql)(n))}}observe(e,i,r,n){return typeof e=="string"?new Promise((o,c)=>{let a=typeof i=="function",u=a?i:r,l=a?r:n;B(this.client,a?void 0:i,u,(p,d,h,v,P)=>{p&&!P?c(p):o(()=>{g(this.client,d,h)})},l,void 0,e)}):new Promise((o,c)=>{B(this.client,e,i,(a,u,l,p,d)=>{a&&!d?c(a):o(()=>{g(this.client,u,l)})},r)})}createObservable(e,i){return typeof e=="string"?new T(this.client,e,i):new T(this.client,e)}observeSchema(e,i,r){return new Promise((n,o)=>{let c=typeof e=="string"?e:"default",a=typeof e=="string"?i:e,u=typeof e=="string"?r:i;B(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,d,h,v)=>{l&&!v?o(l):n(()=>{g(this.client,p,d)})},u)})}get(e,i){return typeof e=="string"?new Promise((r,n)=>{L(this.client,i,(o,c,a,u)=>{o?n(o):r(u)},0,e)}):new Promise((r,n)=>{O(this.client,k.RequestTypes.Get,e,r,n)})}file(e){return global.File&&e instanceof File&&(e={contents:e}),Me(this,e)}call(e,i){return new Promise((r,n)=>{O(this.client,k.RequestTypes.Call,i,r,n,e)})}async id(e,i){let r=ce(this.client,e);if(r||(await this.schema(),r=ce(this.client,e)),!r)throw q({message:`Type does not exist ${e}`,type:"Invalid type",payload:i?{type:e,opts:i}:{type:e}});if(i){let n=(0,fe.hashCompact)(i,8,!0);return r+n}else return r+(0,fe.hashCompact)(Math.floor(Math.random()*99999999999)+""+Date.now())}digest(e){return new Promise((i,r)=>{O(this.client,k.RequestTypes.Digest,e,i,r)})}set(e){return new Promise((i,r)=>{O(this.client,k.RequestTypes.Set,e,i,r)})}copy(e){return new Promise((i,r)=>{O(this.client,k.RequestTypes.Copy,e,i,r)})}async gqlQuery(e,i={}){let r;typeof e=="string"?r=this.gql(e):r=e;try{if(r=(0,y.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,d,h,v,P;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 F={};F.id=a;let me=(P=(v=(h=(d=(p=this.client)==null?void 0:p.configuration)==null?void 0:d.schema)==null?void 0:h[r.db])==null?void 0:v.prefixToTypeMapping)==null?void 0:P[a.slice(0,2)];me&&(F.type=me),n[o]=F;return}let u=(0,be.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,i={}){let r;if(typeof e=="string"?r=this.gql(e):r=e,r=(0,y.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 T(this.client,l.fn.name,l.fn.payload),key:l.key})),u=new T(this.client,ve({$db:r.db},c));return a.push({key:"",obs:u}),new K(this.client,a)}return new T(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,be.deepCopy)(c.get);u.$id=a,n[o]=u})),new T(this.client,{$db:r.db,data:n})}analytics(e,i){return new Promise((r,n)=>{i?B(this.client,e,i,(o,c,a,u,l)=>{o&&!l?n(o):r(()=>{g(this.client,c,a)})},o=>console.error(o),void 0,"analytics"):L(this.client,e,(o,c,a,u)=>{o?n(o):((0,k.isAnalyticsHistoryOpts)(e)||(0,k.isAnalyticsTypesOpts)(e),r(u))},0,"analytics")})}track(e,i){G(this.client,e,i)}clearAnalytics(e,i){G(this.client,e,i,!1,!1,void 0,!0)}untrack(e,i){G(this.client,e,i,!0)}event(e,i,r){G(this.client,e,i,!1,!0,r)}delete(e){return new Promise((i,r)=>{O(this.client,k.RequestTypes.Delete,e,i,r)})}schema(){return new Promise((e,i)=>{let r=n=>{this.client.configuration=n,e(n)};O(this.client,k.RequestTypes.GetConfiguration,0,r,i)})}updateSchema(e){return new Promise((i,r)=>{O(this.client,k.RequestTypes.Configuration,e,i,r)})}getToken(){return this.client.token}auth(e,i){return new Promise(r=>{this.client.auth.push(r),(e&&e!==this.client.token||e===!1&&this.client.token)&&(typeof e=="string"?I(this.client,e,i):I(this.client),this.emit("auth",e))})}},ot=(t,s)=>{if(s){let e;t+=/\?/.test(t)?"&":"?";for(let i in s){let r=s[i];t+=e?`&${i}=${r}`:`${i}=${r}`,e=!0}}return t},at=(t,s=Z)=>{let{env:e,project:i,org:r,url:n,key:o,name:c="@based/hub",cluster:a,params:u}=t;if(n||(a=t.cluster=(0,ee.getClusterUrl)(a),n=async()=>{let{url:l}=await(0,ee.default)({env:e,project:i,org:r,key:o,name:c},0,a);return ot(l,u)}),n){let l=new s;return l.opts=t,l.connect(n),l}},ct=at;0&&(module.exports={Based,BasedClient,BasedGraphQL,Observable,addGetSubscriber,addRequest,addSubscriber,createGraphqlOperations,generateSubscriptionId,generateTrackingKey,handleGraphqlVariables,parseGraphql,removeSubscriber}); | ||
`),delete t.cache[e],m(t,[W.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||g(t,e,Number(u))),l.onData&&l.onData(c.value,c.checksum)}}}}};var De=(t,s)=>{for(let e of s[1]){delete t.cache[e];let i=t.subscriptions[e];if(i){let r={type:"AuthorizationError",name:i.name?`observe "${i.name}"`:"observe",message:"Unauthorized request",payload:i.query,auth:!0},n=q(r);i.authError={token:t.token,error:n};for(let o in i.subscribers){let c=i.subscribers[o];c.onError&&c.onError(n)}}}};var Ie=require("@based/types");var Ze=0,T=(t,s,e,i,r,n)=>{let o=++Ze;t.requestCallbacks[o]={resolve:i,reject:r},s===Ie.RequestTypes.Call?m(t,[s,n,o,e]):m(t,[s,o,e])};var Ae=(t,s)=>{let[,e,i,r]=s,n=t.requestCallbacks[e];n&&(delete t.requestCallbacks[e],r?n.reject(q(r)):n.resolve(i))};var O={};Te(O,{BasedClient:()=>U});var y=require("@based/types");var ue=require("@based/types");var et=t=>typeof t!="undefined"&&t!==null,tt=(t,s,e)=>{if(t.beingAuth=!0,s)t.token=s,t.sendTokenOptions=e;else{for(let i in t.cache)t.subscriptions[i]||delete t.cache[i];delete t.token,delete t.sendTokenOptions}if(t.connected){let i=s?[ue.RequestTypes.Token,s,e].filter(et):[ue.RequestTypes.Token];t.connection.ws.send(JSON.stringify(i)),H(t),z(t,!0)}},$=tt;d(O,require("@based/types"));var U=class{constructor(s){this.auth=[];this.subscriptions={};this.cache={};this.requestCallbacks={};this.connected=!1;this.subscriptionQueue=[];this.queue=[];this.drainInProgress=!1;this.based=s}onClose(){this.connected=!1,Be(this),qe(this),Qe(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)m(this,[y.RequestTypes.Track,{t:s}])}onOpen(){this.connected=!0,this.based.listeners.connect&&this.based.listeners.connect.forEach(s=>s()),this.token&&$(this,this.token,this.sendTokenOptions),z(this),oe(this)}onData(s){try{let e=JSON.parse(s.data);if(e[0]===y.RequestTypes.Token){e[1].length&&De(this,e);for(let i of this.auth)i(!e[2]);this.beingAuth=!1,this.auth=[]}else e[0]===y.RequestTypes.Set||e[0]===y.RequestTypes.Get||e[0]===y.RequestTypes.Configuration||e[0]===y.RequestTypes.GetConfiguration||e[0]===y.RequestTypes.Call||e[0]===y.RequestTypes.Delete||e[0]===y.RequestTypes.Copy||e[0]===y.RequestTypes.Digest||e[0]===y.RequestTypes.RemoveType||e[0]===y.RequestTypes.RemoveField?Ae(this,e):e[0]===y.RequestTypes.Subscription?Re(this,e):e[0]===y.RequestTypes.SubscriptionDiff&&xe(this,e)}catch(e){console.error("Received incorrect data ",s)}}};var le=(t,s)=>{let e;if(t.configuration&&t.configuration.schema)for(let i in t.configuration.schema){let r=t.configuration.schema[i];if(r.prefixToTypeMapping){for(let n in r.prefixToTypeMapping)if(r.prefixToTypeMapping[n]===s){e=n;break}}}return e};var me=require("@saulx/hash");var $e=require("@based/types"),je=require("@saulx/hash"),Ge=new Set,st=t=>{if(typeof window!="undefined"){if(Ge.has(t))return!1;Ge.add(t);try{let s="_ba:"+(0,je.hashCompact)(t);return localStorage.getItem(s)?!1:(localStorage.setItem(s,"1"),!0)}catch(s){return!1}}return!1},pe=(t,s)=>{if(s){let e=`${t}`,i=Object.keys(s).sort();for(let r of i)e+="_"+r+"_"+s[r];return e}else return t},j=(t,s,e,i,r,n,o)=>{let c=pe(s,e),a={t:c};o&&(a.r=1),r&&(a.e=1,n&&(a.o=n)),i?(a.s=1,t.tracking.delete(c)):o||(r||(t.tracking||(t.tracking=new Set),t.tracking.add(c)),st(c)&&(a.u=1)),m(t,[$e.RequestTypes.Track,a])};var de=class{constructor(s,e,i){this.closed=!1;this.client=s,this.subId=i,this.subscriberId=e}unsubscribe(){this.closed=!0,g(this.client,this.subId,this.subscriberId)}},fe=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()}}},V=class{constructor(s,e){this.client=s,this.components=e}subscribe(s,e,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)},e);n.push(a)}return new fe(this.client,n)}},C=class{constructor(s,e,i){this.client=s,this.subId=typeof e=="string"?w(i,e):w(e),this.name=typeof e=="string"?e:null,this.payload=typeof e=="string"?i:e}subscribe(s,e,i){let[,r]=F(this.client,this.payload,s,n=>{n&&(console.error(n),e&&e(n))},e,this.subId,this.name);return new de(this.client,r,this.subId)}};var be={},N={},rt=(t,s)=>{be[t]||(be[t]=!0,setTimeout(()=>{console.info("Drain file q"),be[t]=!1;let e=N[t];N[t]=[];let i=new global.FormData;for(let r of e){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",t+"/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))},Ne=async(t,s,e,i,r,n,o)=>{N[e]||(N[e]=[]),N[e].push({file:s,id:i,url:e,raw:r,name:n,functionName:o}),rt(e,t.getToken())};var Me=L(require("@based/get-service")),X={},Y={},it=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:i,org:r}=t.opts,n=e+"/"+i+"/"+r+"/"+t.opts.cluster;if(X[n])return X[n];if(Y[n])return(await Y[n]).url;let o=await(Y[n]=(0,Me.default)({env:e,project:i,org:r,name:"@based/hub",key:"file-upload",optionalKey:!0},0,t.opts.cluster));return delete Y[n],setTimeout(()=>{delete X[n]},2e3),X[n]=o.url},Le=it;var He=L(require("cross-fetch")),Z=(t,s,e)=>((0,He.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(i=>{}).catch(i=>{console.error("Error while uploading file",i)}),{id:e.id});var x=require("./file/stream"),ee=typeof window!="undefined",nt=t=>"src"in t&&typeof t.src=="string",ot=t=>"path"in t&&typeof t.path=="string",at=t=>"contents"in t&&(0,x.isStream)(t.contents),_e=async(t,s)=>{if(nt(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 t.set(r)):void 0}let e=s.id;if(!e){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),e=(await t.set(r)).id}s.id=e;let i=(await Le(t,s)).replace(/^ws/,"http");if(ot(s))return(0,x.uploadFilePath)(t,i,s),{id:e};if(at(s))return(0,x.uploadFileStream)(t,i,s),{id:e};if(s.contents instanceof ArrayBuffer)return s.contents=ee?new global.Blob([s.contents],{type:s.mimeType||"text/plain"}):global.Buffer.from(s.contents),Z(t,i+"/file",s);if(ee&&s.contents instanceof global.Blob)return s.mimeType||(s.mimeType=s.contents.type),Z(t,i+"/file",s);if(typeof s.contents=="string"||!ee&&s.contents instanceof global.Buffer)return Z(t,i+"/file",s);if(ee&&s.contents instanceof File)return Ne(t,s.contents,i,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 se=L(require("@based/get-service")),he=require("@saulx/utils"),S=require("@based/graphql");d(b,require("@based/types"),module.exports);var te=class extends Oe{constructor(e){super();this.client=new U(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=ne(this.client,this._url)):(this._url=e,this.client.connection=ne(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,i,r){return new Promise((n,o)=>{let c,a=!1;this.observe(e,(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(e,...i){typeof e=="string"&&(e=[e]);let r=e[0];return i.forEach((n,o)=>{n&&n.kind==="Document"?r+=n.loc.source.body:r+=n,r+=e[o+1]}),(0,S.createOperations)({schemas:this.client.configuration.schema},(0,S.parseGraphql)(r))}gqlDb(e="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:e},(0,S.parseGraphql)(n))}}observe(e,i,r,n){return typeof e=="string"?new Promise((o,c)=>{let a=typeof i=="function",u=a?i:r,l=a?r:n;F(this.client,a?void 0:i,u,(p,f,h,k,B)=>{p&&!B?c(p):o(()=>{g(this.client,f,h)})},l,void 0,e)}):new Promise((o,c)=>{F(this.client,e,i,(a,u,l,p,f)=>{a&&!f?c(a):o(()=>{g(this.client,u,l)})},r)})}createObservable(e,i){return typeof e=="string"?new C(this.client,e,i):new C(this.client,e)}observeSchema(e,i,r){return new Promise((n,o)=>{let c=typeof e=="string"?e:"default",a=typeof e=="string"?i:e,u=typeof e=="string"?r:i;F(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,f,h,k)=>{l&&!k?o(l):n(()=>{g(this.client,p,f)})},u)})}get(e,i){return typeof e=="string"?new Promise((r,n)=>{_(this.client,i,(o,c,a,u)=>{o?n(o):r(u)},0,e)}):new Promise((r,n)=>{T(this.client,v.RequestTypes.Get,e,r,n)})}file(e){return global.File&&e instanceof File&&(e={contents:e}),_e(this,e)}call(e,i){return new Promise((r,n)=>{T(this.client,v.RequestTypes.Call,i,r,n,e)})}async id(e,i){let r=le(this.client,e);if(r||(await this.schema(),r=le(this.client,e)),!r)throw q({message:`Type does not exist ${e}`,type:"Invalid type",payload:i?{type:e,opts:i}:{type:e}});if(i){let n=(0,me.hashCompact)(i,8,!0);return r+n}else return r+(0,me.hashCompact)(Math.floor(Math.random()*99999999999)+""+Date.now())}digest(e){return new Promise((i,r)=>{T(this.client,v.RequestTypes.Digest,e,i,r)})}set(e){return new Promise((i,r)=>{T(this.client,v.RequestTypes.Set,e,i,r)})}copy(e){return new Promise((i,r)=>{T(this.client,v.RequestTypes.Copy,e,i,r)})}async gqlQuery(e,i={}){let r;typeof e=="string"?r=this.gql(e):r=e;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,f,h,k,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 R={};R.id=a;let ge=(B=(k=(h=(f=(p=this.client)==null?void 0:p.configuration)==null?void 0:f.schema)==null?void 0:h[r.db])==null?void 0:k.prefixToTypeMapping)==null?void 0:B[a.slice(0,2)];ge&&(R.type=ge),n[o]=R;return}let u=(0,he.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,i={}){let r;if(typeof e=="string"?r=this.gql(e):r=e,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 C(this.client,l.fn.name,l.fn.payload),key:l.key})),u=new C(this.client,ke({$db:r.db},c));return a.push({key:"",obs:u}),new V(this.client,a)}return new C(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,he.deepCopy)(c.get);u.$id=a,n[o]=u})),new C(this.client,{$db:r.db,data:n})}analytics(e,i){return new Promise((r,n)=>{i?F(this.client,e,i,(o,c,a,u,l)=>{o&&!l?n(o):r(()=>{g(this.client,c,a)})},o=>console.error(o),void 0,"analytics"):_(this.client,e,(o,c,a,u)=>{o?n(o):((0,v.isAnalyticsHistoryOpts)(e)||(0,v.isAnalyticsTypesOpts)(e),r(u))},0,"analytics")})}track(e,i){j(this.client,e,i)}clearAnalytics(e,i){j(this.client,e,i,!1,!1,void 0,!0)}untrack(e,i){j(this.client,e,i,!0)}event(e,i,r){j(this.client,e,i,!1,!0,r)}delete(e){return new Promise((i,r)=>{T(this.client,v.RequestTypes.Delete,e,i,r)})}schema(){return new Promise((e,i)=>{let r=n=>{this.client.configuration=n,e(n)};T(this.client,v.RequestTypes.GetConfiguration,0,r,i)})}removeType(e,i="default"){return new Promise((r,n)=>{T(this.client,v.RequestTypes.RemoveType,{type:e,db:i},r,n)})}removeField(e,i,r="default"){return new Promise((n,o)=>{!i||i.length===0?o(new Error("Path cannot be empty")):(Array.isArray(i)||(i=[i]),T(this.client,v.RequestTypes.RemoveField,{type:e,db:r,path:i},n,o))})}updateSchema(e){return new Promise((i,r)=>{T(this.client,v.RequestTypes.Configuration,e,i,r)})}getToken(){return this.client.token}auth(e,i){return new Promise(r=>{this.client.auth.push(r),(e&&e!==this.client.token||e===!1&&this.client.token)&&(typeof e=="string"?$(this.client,e,i):$(this.client),this.emit("auth",e))})}},ct=(t,s)=>{if(s){let e;t+=/\?/.test(t)?"&":"?";for(let i in s){let r=s[i];t+=e?`&${i}=${r}`:`${i}=${r}`,e=!0}}return t},ut=(t,s=te)=>{let{env:e,project:i,org:r,url:n,key:o,name:c="@based/hub",cluster:a,params:u}=t;if(n||(a=t.cluster=(0,se.getClusterUrl)(a),n=async()=>{let{url:l}=await(0,se.default)({env:e,project:i,org:r,key:o,name:c},0,a);return ct(l,u)}),n){let l=new s;return l.opts=t,l.connect(n),l}},lt=ut;0&&(module.exports={Based,BasedClient,BasedGraphQL,Observable,addGetSubscriber,addRequest,addSubscriber,createGraphqlOperations,generateSubscriptionId,generateTrackingKey,handleGraphqlVariables,parseGraphql,removeSubscriber}); |
import { BasedClient } from '.'; | ||
import { RequestData, RequestTypes } from '@based/types'; | ||
export declare const addRequest: (client: BasedClient, type: RequestTypes.Set | RequestTypes.Get | RequestTypes.Configuration | RequestTypes.GetConfiguration | RequestTypes.Delete | RequestTypes.Copy | RequestTypes.Digest | RequestTypes.Call, payload: any, resolve: (val?: any) => void, reject: (err: Error) => void, name?: string) => void; | ||
export declare const addRequest: (client: BasedClient, type: RequestTypes.Set | RequestTypes.Get | RequestTypes.Configuration | RequestTypes.GetConfiguration | RequestTypes.Delete | RequestTypes.Copy | RequestTypes.Digest | RequestTypes.Call | RequestTypes.RemoveType | RequestTypes.RemoveField, payload: any, resolve: (val?: any) => void, reject: (err: Error) => void, name?: string) => void; | ||
export declare const abortRequest: () => void; | ||
export declare const cleanUpRequests: () => void; | ||
export declare const incomingRequest: (client: BasedClient, data: RequestData) => void; |
"use strict"; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
exports.sendAllSubscriptions = void 0; | ||
const types_1 = require("../types"); | ||
const types_1 = require("@based/types"); | ||
const queue_1 = require("../queue"); | ||
@@ -6,0 +6,0 @@ const sendAllSubscriptions = (client, reAuth = false) => { |
@@ -11,3 +11,3 @@ "use strict"; | ||
if (typeof window !== 'undefined') { | ||
document.addEventListener('visibilitychange', function (event) { | ||
document.addEventListener('visibilitychange', function () { | ||
clearTimeout(activeTimer); | ||
@@ -14,0 +14,0 @@ if (document.hidden) { |
{ | ||
"name": "@based/client", | ||
"version": "2.4.0", | ||
"version": "2.5.0", | ||
"license": "MIT", | ||
@@ -31,5 +31,5 @@ "main": "dist/index.js", | ||
"dependencies": { | ||
"@based/get-service": "2.3.5", | ||
"@based/graphql": "2.3.5", | ||
"@based/types": "2.3.5", | ||
"@based/get-service": "2.4.1", | ||
"@based/graphql": "2.4.1", | ||
"@based/types": "2.4.3", | ||
"@saulx/diff": "^1.1.3", | ||
@@ -45,4 +45,5 @@ "@saulx/hash": "^1.1.0", | ||
"@saulx/hash": "^1.1.0", | ||
"@saulx/selva": "10.6.2", | ||
"@saulx/selva": "10.6.3", | ||
"@saulx/utils": "^2.2.1", | ||
"@saulx/selva-server": "10.6.3", | ||
"@types/jsonwebtoken": "^8.5.6", | ||
@@ -49,0 +50,0 @@ "@types/node": "^17.0.23", |
@@ -1,2 +0,2 @@ | ||
# based-client | ||
# @based/client | ||
@@ -3,0 +3,0 @@ ## 🔗 Links |
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
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
184055
13
108
2389
+ Added@based/get-service@2.4.1(transitive)
+ Added@based/graphql@2.4.1(transitive)
+ Added@based/types@2.4.3(transitive)
- Removed@based/get-service@2.3.5(transitive)
- Removed@based/graphql@2.3.5(transitive)
- Removed@based/types@2.3.5(transitive)
Updated@based/get-service@2.4.1
Updated@based/graphql@2.4.1
Updated@based/types@2.4.3