@synnaxlabs/client 0.17.0 → 0.17.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,5 +1,5 @@
1
1
 
2
- > @synnaxlabs/client@0.17.0 build /home/runner/work/synnax/synnax/client/ts
2
+ > @synnaxlabs/client@0.17.1 build /home/runner/work/synnax/synnax/client/ts
3
3
  > tsc --noEmit && vite build
4
4
 
5
5
  vite v5.1.2 building for production...
@@ -9,8 +9,8 @@ rendering chunks...
9
9
  
10
10
  [vite:dts] Start generate declaration files...
11
11
  computing gzip size...
12
- dist/client.js 531.40 kB │ gzip: 116.81 kB │ map: 1,194.37 kB
13
- [vite:dts] Declaration files built in 3700ms.
12
+ dist/client.js 531.66 kB │ gzip: 116.90 kB │ map: 1,195.36 kB
13
+ [vite:dts] Declaration files built in 3719ms.
14
14
  
15
- dist/client.cjs 350.50 kB │ gzip: 92.44 kB │ map: 1,139.49 kB
16
- ✓ built in 5.25s
15
+ dist/client.cjs 350.69 kB │ gzip: 92.51 kB │ map: 1,140.46 kB
16
+ ✓ built in 5.28s
@@ -4,6 +4,9 @@ import { type Creator } from './creator';
4
4
  import { type Key, type KeyOrName, type Params, type Payload, type NewPayload } from './payload';
5
5
  import { type Retriever } from './retriever';
6
6
  import { type framer } from '../framer';
7
+ interface CreateOptions {
8
+ retrieveIfNameExists?: boolean;
9
+ }
7
10
  /**
8
11
  * Represents a Channel in a Synnax database. Typically, channels should not be
9
12
  * instantiated directly, but instead created via the `.channels.create` or retrieved
@@ -125,7 +128,7 @@ export declare class Client implements AsyncTermSearcher<string, Key, Channel> {
125
128
  * });
126
129
  * ```
127
130
  */
128
- create(channel: NewPayload): Promise<Channel>;
131
+ create(channel: NewPayload, options?: CreateOptions): Promise<Channel>;
129
132
  /**
130
133
  * Creates multiple channels with the given properties. The order of the channels
131
134
  * returned is guaranteed to match the order of the channels passed in.
@@ -149,7 +152,7 @@ export declare class Client implements AsyncTermSearcher<string, Key, Channel> {
149
152
  *
150
153
  * @param channels
151
154
  */
152
- create(channels: NewPayload[]): Promise<Channel[]>;
155
+ create(channels: NewPayload[], options?: CreateOptions): Promise<Channel[]>;
153
156
  /**
154
157
  * Retrieves a channel from the database using the given key or name.
155
158
  *
@@ -192,3 +195,4 @@ export declare class Client implements AsyncTermSearcher<string, Key, Channel> {
192
195
  createDebouncedBatchRetriever(deb?: number): Retriever;
193
196
  private sugar;
194
197
  }
198
+ export {};
package/dist/client.cjs CHANGED
@@ -11,7 +11,7 @@
11
11
  ${e}
12
12
 
13
13
  Please report this to the Synnax team.
14
- `)}}class tr extends Hr{}class Sw extends tr{}class Nw extends tr{}class fh extends Hr{constructor(t,n){super(t);h(this,"path");this.path=n}}class Ew extends Hr{}const Aw=r=>{if(!r.type.startsWith(wr))return null;switch(r.type){case Ir.General:return new hh(r.data);case Ir.Parse:return new ph(r.data);case Ir.Auth:return new Ac(r.data);case Ir.Unexpected:return new wn(r.data);case Ir.Validation:return new jt(r.data);case Ir.Query:return new tr(r.data);case Ir.Route:return new fh(r.data,r.data);default:return new wn(r.data)}},Iw=()=>{throw new Error("Not implemented")};oh({encode:Iw,decode:Aw});const Zw=async(r,e)=>{const[t,n]=await e(r);return n==null?[t,n]:n instanceof qs?[t,new qs({message:`Cannot reach cluster at ${n.url.host}:${n.url.port}`,url:n.url})]:[t,n]};class Ic{constructor({dataType:e,rate:t,name:n,leaseholder:s=0,key:a=0,isIndex:i=!1,index:o=0,frameClient:c,alias:l}){h(this,"_frameClient");h(this,"key");h(this,"name");h(this,"rate");h(this,"dataType");h(this,"leaseholder");h(this,"index");h(this,"isIndex");h(this,"alias");this.key=a,this.name=n,this.rate=new xi(t??0),this.dataType=new rt(e),this.leaseholder=s,this.index=o,this.isIndex=i,this.alias=l,this._frameClient=c??null}get framer(){if(this._frameClient==null)throw new jt("cannot read from a channel that has not been created");return this._frameClient}get payload(){return Gs.parse({key:this.key,name:this.name,rate:this.rate.valueOf(),dataType:this.dataType.valueOf(),leaseholder:this.leaseholder,index:this.index,isIndex:this.isIndex})}async read(e){return await this.framer.read(e,this.key)}async write(e,t){return await this.framer.write(this.key,e,t)}}let mh=class{constructor(e,t,n,s){h(this,"frameClient");h(this,"retriever");h(this,"creator");h(this,"client");this.frameClient=e,this.retriever=t,this.client=n,this.creator=s}async create(e){const t=!Array.isArray(e),n=await this.creator.create(Ne(e)),s=this.sugar(n);return t?s[0]:s}async retrieve(e,t){const{single:n,actual:s,normalized:a}=Gr(e);if(a.length===0)return[];const i=this.sugar(await this.retriever.retrieve(e,t));if(!n)return i;if(i.length===0)throw new Sw(`channel matching ${s} not found`);if(i.length>1)throw new Nw(`multiple channels matching ${s} found`);return i[0]}async search(e,t){return this.sugar(await this.retriever.search(e,t))}newSearcherUnderRange(e){return new $w(this,e)}async page(e,t,n){return this.sugar(await this.retriever.page(e,t,n))}createDebouncedBatchRetriever(e=10){return new dc(new td(new vs(this.client),e))}sugar(e){const{frameClient:t}=this;return e.map(n=>new Ic({...n,frameClient:t}))}};class $w{constructor(e,t){h(this,"client");h(this,"rangeKey");this.client=e,this.rangeKey=t}async search(e){return await this.client.search(e,this.rangeKey)}async page(e,t){return await this.client.page(e,t,this.rangeKey)}async retrieve(e){return await this.client.retrieve(e,this.rangeKey)}}const Cw=Object.freeze(Object.defineProperty({__proto__:null,CacheRetriever:dc,Channel:Ic,Client:mh,ClusterRetriever:vs,Creator:Ga,DebouncedBatchRetriever:td,analyzeParams:Gr,keyZ:Js,newPayload:Ql,parseChannels:ed,payload:Gs},Symbol.toStringTag,{value:"Module"})),jw=u.z.object({key:u.z.string(),username:u.z.string()}),Rw=r=>async(e,t)=>{try{const n=await r();e.params.Authorization=`Bearer ${n}`}catch(n){return[e,n]}return await t(e)},zw=u.z.object({username:u.z.string(),password:u.z.string()}),Pw=u.z.object({token:u.z.string(),user:jw}),Uw="/auth/login";let Dw=class{constructor(e,t){h(this,"token");h(this,"client");h(this,"authenticating");h(this,"authenticated");h(this,"user");this.client=e,this.authenticated=!1,this.authenticate(t)}authenticate(e){this.authenticating=new Promise((t,n)=>{this.client.send(Uw,e,zw,Pw).then(([s,a])=>{if(a!=null)return n(a);this.token=s==null?void 0:s.token,this.user=s==null?void 0:s.user,this.authenticated=!0,t()}).catch(n)})}middleware(){return Rw(async()=>{if(this.authenticated||await this.authenticating,this.token==null)throw new Ac("[auth] - attempting to authenticate without a token");return this.token})}};const Mw=["disconnected","connecting","connected","failed"],yh=u.z.enum(Mw),gh=u.z.object({status:yh,error:u.z.instanceof(Error).optional(),message:u.z.string().optional(),clusterKey:u.z.string()}),Lw=u.z.object({clusterKey:u.z.string()}),Du={clusterKey:"",status:"disconnected",error:void 0,message:"Disconnected"},An=class An{constructor(e,t=Pe.seconds(30),n){h(this,"_state");h(this,"pollFrequency",Pe.seconds(30));h(this,"client");h(this,"name");h(this,"interval");h(this,"onChangeHandlers",[]);this._state={...Du},this.client=e,this.pollFrequency=t,this.name=n,this.check(),this.startChecking()}stopChecking(){this.interval!=null&&clearInterval(this.interval)}async check(){var t;const e=this._state.status;try{const[n,s]=await this.client.send(An.ENDPOINT,{},u.z.object({}),Lw);if(s!=null)throw s;this._state.status="connected",this._state.message=`Connected to ${this.name??"cluster"}`,this._state.clusterKey=n.clusterKey}catch(n){this._state.status="failed",this._state.error=n,this._state.message=(t=this.state.error)==null?void 0:t.message}return this.onChangeHandlers.length>0&&e!==this._state.status&&this.onChangeHandlers.forEach(n=>n(this.state)),this.state}get state(){return{...this._state}}onChange(e){this.onChangeHandlers.push(e)}startChecking(){this.interval=setInterval(()=>{this.check()},this.pollFrequency.milliseconds)}};h(An,"ENDPOINT","/connectivity/check"),h(An,"DEFAULT",Du),h(An,"connectionStateZ",gh);let Fs=An;const Bw=Object.freeze(Object.defineProperty({__proto__:null,Checker:Fs,state:gh,status:yh},Symbol.toStringTag,{value:"Module"})),Zr=class Zr extends Number{};h(Zr,"Absolute",255),h(Zr,"Default",1),h(Zr,"z",u.z.union([u.z.instanceof(Zr),u.z.number().int().min(0).max(255).transform(e=>new Zr(e)),u.z.instanceof(Number).transform(e=>new Zr(e))]));let Jr=Zr;const Mu=r=>{const e=Ne(r);return e.length===0?null:typeof e[0]=="number"?"key":"name"},Lu=(r,e)=>{const t=Ne(r);if(t.length===e.length)return;const n=Mu(r);throw Mu===null?new jt("[Frame] - channel keys or names must be provided when constructing a frame."):new jt(`[Frame] - ${n}s and arrays must be the same length.
14
+ `)}}class tr extends Hr{}class Sw extends tr{}class Nw extends tr{}class fh extends Hr{constructor(t,n){super(t);h(this,"path");this.path=n}}class Ew extends Hr{}const Aw=r=>{if(!r.type.startsWith(wr))return null;switch(r.type){case Ir.General:return new hh(r.data);case Ir.Parse:return new ph(r.data);case Ir.Auth:return new Ac(r.data);case Ir.Unexpected:return new wn(r.data);case Ir.Validation:return new jt(r.data);case Ir.Query:return new tr(r.data);case Ir.Route:return new fh(r.data,r.data);default:return new wn(r.data)}},Iw=()=>{throw new Error("Not implemented")};oh({encode:Iw,decode:Aw});const Zw=async(r,e)=>{const[t,n]=await e(r);return n==null?[t,n]:n instanceof qs?[t,new qs({message:`Cannot reach cluster at ${n.url.host}:${n.url.port}`,url:n.url})]:[t,n]};class Ic{constructor({dataType:e,rate:t,name:n,leaseholder:s=0,key:a=0,isIndex:i=!1,index:o=0,frameClient:c,alias:l}){h(this,"_frameClient");h(this,"key");h(this,"name");h(this,"rate");h(this,"dataType");h(this,"leaseholder");h(this,"index");h(this,"isIndex");h(this,"alias");this.key=a,this.name=n,this.rate=new xi(t??0),this.dataType=new rt(e),this.leaseholder=s,this.index=o,this.isIndex=i,this.alias=l,this._frameClient=c??null}get framer(){if(this._frameClient==null)throw new jt("cannot read from a channel that has not been created");return this._frameClient}get payload(){return Gs.parse({key:this.key,name:this.name,rate:this.rate.valueOf(),dataType:this.dataType.valueOf(),leaseholder:this.leaseholder,index:this.index,isIndex:this.isIndex})}async read(e){return await this.framer.read(e,this.key)}async write(e,t){return await this.framer.write(this.key,e,t)}}let mh=class{constructor(e,t,n,s){h(this,"frameClient");h(this,"retriever");h(this,"creator");h(this,"client");this.frameClient=e,this.retriever=t,this.client=n,this.creator=s}async create(e,t={}){const{retrieveIfNameExists:n=!1}=t,s=!Array.isArray(e);let a=Ne(e),i=[];if(n){const o=await this.retriever.retrieve(a.map(l=>l.name)),c=new Set(o.map(l=>l.name));a=a.filter(l=>!c.has(l.name)),i=this.sugar(o)}return i=i.concat(this.sugar(await this.creator.create(a))),s?i[0]:i}async retrieve(e,t){const{single:n,actual:s,normalized:a}=Gr(e);if(a.length===0)return[];const i=this.sugar(await this.retriever.retrieve(e,t));if(!n)return i;if(i.length===0)throw new Sw(`channel matching ${s} not found`);if(i.length>1)throw new Nw(`multiple channels matching ${s} found`);return i[0]}async search(e,t){return this.sugar(await this.retriever.search(e,t))}newSearcherUnderRange(e){return new $w(this,e)}async page(e,t,n){return this.sugar(await this.retriever.page(e,t,n))}createDebouncedBatchRetriever(e=10){return new dc(new td(new vs(this.client),e))}sugar(e){const{frameClient:t}=this;return e.map(n=>new Ic({...n,frameClient:t}))}};class $w{constructor(e,t){h(this,"client");h(this,"rangeKey");this.client=e,this.rangeKey=t}async search(e){return await this.client.search(e,this.rangeKey)}async page(e,t){return await this.client.page(e,t,this.rangeKey)}async retrieve(e){return await this.client.retrieve(e,this.rangeKey)}}const Cw=Object.freeze(Object.defineProperty({__proto__:null,CacheRetriever:dc,Channel:Ic,Client:mh,ClusterRetriever:vs,Creator:Ga,DebouncedBatchRetriever:td,analyzeParams:Gr,keyZ:Js,newPayload:Ql,parseChannels:ed,payload:Gs},Symbol.toStringTag,{value:"Module"})),jw=u.z.object({key:u.z.string(),username:u.z.string()}),Rw=r=>async(e,t)=>{try{const n=await r();e.params.Authorization=`Bearer ${n}`}catch(n){return[e,n]}return await t(e)},zw=u.z.object({username:u.z.string(),password:u.z.string()}),Pw=u.z.object({token:u.z.string(),user:jw}),Uw="/auth/login";let Dw=class{constructor(e,t){h(this,"token");h(this,"client");h(this,"authenticating");h(this,"authenticated");h(this,"user");this.client=e,this.authenticated=!1,this.authenticate(t)}authenticate(e){this.authenticating=new Promise((t,n)=>{this.client.send(Uw,e,zw,Pw).then(([s,a])=>{if(a!=null)return n(a);this.token=s==null?void 0:s.token,this.user=s==null?void 0:s.user,this.authenticated=!0,t()}).catch(n)})}middleware(){return Rw(async()=>{if(this.authenticated||await this.authenticating,this.token==null)throw new Ac("[auth] - attempting to authenticate without a token");return this.token})}};const Mw=["disconnected","connecting","connected","failed"],yh=u.z.enum(Mw),gh=u.z.object({status:yh,error:u.z.instanceof(Error).optional(),message:u.z.string().optional(),clusterKey:u.z.string()}),Lw=u.z.object({clusterKey:u.z.string()}),Du={clusterKey:"",status:"disconnected",error:void 0,message:"Disconnected"},An=class An{constructor(e,t=Pe.seconds(30),n){h(this,"_state");h(this,"pollFrequency",Pe.seconds(30));h(this,"client");h(this,"name");h(this,"interval");h(this,"onChangeHandlers",[]);this._state={...Du},this.client=e,this.pollFrequency=t,this.name=n,this.check(),this.startChecking()}stopChecking(){this.interval!=null&&clearInterval(this.interval)}async check(){var t;const e=this._state.status;try{const[n,s]=await this.client.send(An.ENDPOINT,{},u.z.object({}),Lw);if(s!=null)throw s;this._state.status="connected",this._state.message=`Connected to ${this.name??"cluster"}`,this._state.clusterKey=n.clusterKey}catch(n){this._state.status="failed",this._state.error=n,this._state.message=(t=this.state.error)==null?void 0:t.message}return this.onChangeHandlers.length>0&&e!==this._state.status&&this.onChangeHandlers.forEach(n=>n(this.state)),this.state}get state(){return{...this._state}}onChange(e){this.onChangeHandlers.push(e)}startChecking(){this.interval=setInterval(()=>{this.check()},this.pollFrequency.milliseconds)}};h(An,"ENDPOINT","/connectivity/check"),h(An,"DEFAULT",Du),h(An,"connectionStateZ",gh);let Fs=An;const Bw=Object.freeze(Object.defineProperty({__proto__:null,Checker:Fs,state:gh,status:yh},Symbol.toStringTag,{value:"Module"})),Zr=class Zr extends Number{};h(Zr,"Absolute",255),h(Zr,"Default",1),h(Zr,"z",u.z.union([u.z.instanceof(Zr),u.z.number().int().min(0).max(255).transform(e=>new Zr(e)),u.z.instanceof(Number).transform(e=>new Zr(e))]));let Jr=Zr;const Mu=r=>{const e=Ne(r);return e.length===0?null:typeof e[0]=="number"?"key":"name"},Lu=(r,e)=>{const t=Ne(r);if(t.length===e.length)return;const n=Mu(r);throw Mu===null?new jt("[Frame] - channel keys or names must be provided when constructing a frame."):new jt(`[Frame] - ${n}s and arrays must be the same length.
15
15
  Got ${t.length} ${n}s and ${e.length} arrays.`)};class yt{constructor(e=[],t=[]){h(this,"columns",[]);h(this,"series",[]);if(e instanceof yt){this.columns=e.columns,this.series=e.series;return}if(e instanceof Map){e.forEach((s,a)=>this.push(a,...Ne(s)));return}if(typeof e=="object"&&!Array.isArray(e)){if("keys"in e&&"series"in e){const s=e,a=s.series.map(i=>wh(i));Lu(s.keys,a),s.keys.forEach((i,o)=>this.push(i,a[o]))}else Object.entries(e).forEach(([s,a])=>this.push(s,...Ne(a)));return}if(Array.isArray(e)||["string","number"].includes(typeof e)){const s=Ne(t),a=Ne(e);Lu(a,s),s.forEach((i,o)=>this.push(a[o],i));return}throw new jt(`[Frame] - invalid frame construction parameters. data parameter ust be a frame
16
16
  payload, a list of lazy arrays, a lazy array, a map, or a record keyed by channel
17
17
  name. keys parameter must be a set of channel keys or channel names.`)}get colType(){return this.columns.length===0?null:typeof this.columns[0]=="string"?"name":"key"}get keys(){if(this.colType==="name")throw new wn("colType is not key");return this.columns??[]}get uniqueKeys(){return eu(this.keys)}get names(){if(this.colType==="key")throw new wn("colType is not name");return this.columns??[]}get uniqueNames(){return eu(this.names)}get uniqueColumns(){return this.colType==="key"?this.uniqueKeys:this.uniqueNames}toPayload(){return{series:this.series.map(e=>bh(e)),keys:this.keys}}get isVertical(){return this.uniqueColumns.length===this.columns.length}get isHorizontal(){return this.uniqueColumns.length===1}get isSquare(){return this.isHorizontal&&this.isVertical}get isWeaklyAligned(){if(this.columns.length<=1)return!0;const e=this.timeRanges;return e.every(t=>t.equals(e[0]))}timeRange(e){if(e==null){if(this.columns.length===0)return Zt.ZERO;const n=je.min(...this.series.map(a=>a.timeRange.start)),s=je.max(...this.series.map(a=>a.timeRange.end));return new Zt(n,s)}const t=this.get(e);return t==null?Zt.ZERO:new Zt(t[0].timeRange.start,t[t.length-1].timeRange.end)}get timeRanges(){return this.uniqueColumns.map(e=>this.timeRange(e))}get(e){return Array.isArray(e)?this.filter(t=>e.includes(t)):this.series.filter((t,n)=>this.columns[n]===e)}push(e,...t){if(e instanceof yt){if(this.colType!==null&&e.colType!==this.colType)throw new jt("keyVariant must match");this.series.push(...e.series),this.columns.push(...e.columns)}else{if(this.series.push(...t),typeof e=="string"&&this.colType==="key")throw new jt("keyVariant must match");if(typeof e!="string"&&this.colType==="name")throw new jt("keyVariant must match");this.columns.push(...Array.from({length:t.length},()=>e))}}concat(e){return new yt([...this.columns,...e.columns],[...this.series,...e.series])}has(e){return typeof e=="string"&&this.colType==="key"||typeof e=="number"&&this.colType==="name"?!1:this.columns.includes(e)}map(e){const t=new yt;return this.forEach((n,s,a)=>t.push(...e(n,s,a))),t}forEach(e){this.columns.forEach((t,n)=>{const s=this.series[n];e(t,s,n)})}filter(e){const t=new yt;return this.columns.forEach((n,s)=>{const a=this.series[s];e(n,a,s)&&t.push(n,a)}),t}get byteLength(){return new Ya(this.series.reduce((e,t)=>e.add(t.byteLength),Ya.ZERO))}get length(){return this.series.reduce((e,t)=>e+t.length,0)}}const vh=u.z.object({timeRange:Zt.z.optional(),alignment:u.z.number().optional(),dataType:rt.z,data:u.z.string().transform(r=>new Uint8Array(atob(r).split("").map(e=>e.charCodeAt(0))).buffer)}),Pi=u.z.object({keys:u.z.union([u.z.null().transform(()=>[]),u.z.number().array().optional().default([])]),series:u.z.union([u.z.null().transform(()=>[]),vh.array().optional().default([])])}),wh=r=>{const{dataType:e,data:t,timeRange:n,alignment:s}=r;return new ic({data:t,dataType:e,timeRange:n,glBufferUsage:"static",alignment:s})},bh=r=>({timeRange:r._timeRange,dataType:r.dataType,data:new Uint8Array(r.data.buffer),alignment:r.alignment});class Ui{constructor(e){h(this,"adapter");h(this,"retriever");h(this,"keys");this.retriever=e,this.adapter=null,this.keys=[]}static async open(e,t){const n=new Ui(e);return await n.update(t),n}async update(e){const{variant:t,normalized:n}=Gr(e);if(t==="keys"){this.adapter=null,this.keys=n;return}const s=await this.retriever.retrieve(n),a=new Map;this.adapter=a,n.forEach(i=>{const o=s.find(c=>c.name===i);if(o==null)throw new Error(`Channel ${i} not found`);a.set(o.key,o.name)}),this.keys=Array.from(this.adapter.keys())}adapt(e){if(this.adapter==null)return e;const t=this.adapter;return e.map((n,s)=>{if(typeof n=="number"){const a=t.get(n);if(a==null)throw new Error(`Channel ${n} not found`);return[a,s]}return[n,s]})}}class Zc{constructor(e){h(this,"adapter");h(this,"retriever");h(this,"keys");this.retriever=e,this.adapter=null,this.keys=[]}static async open(e,t){const n=new Zc(e);return await n.update(t),n}async update(e){const{variant:t,normalized:n}=Gr(e);if(t==="keys"){this.adapter=null,this.keys=n;return}const s=await this.retriever.retrieve(n),a=new Map;this.adapter=a,n.forEach(i=>{const o=s.find(c=>c.name===i);if(o==null)throw new jt(`Channel ${i} was not provided in the list of channels when opening the writer`);a.set(o.name,o.key)}),this.keys=s.map(i=>i.key)}adapt(e){if(this.adapter==null)return e.columns.forEach(n=>{if(typeof n!="number")throw new jt(`Channel ${n} was not provided in the list of channels when opening the writer`)}),e;const t=this.adapter;return e.map((n,s)=>{if(typeof n=="string"){const a=t.get(n);if(a==null)throw new Error(`Channel ${n} not found`);return[a,s]}return[n,s]})}}class $c{constructor(e,t){h(this,"name");h(this,"stream");this.stream=t,this.name=e}async receive(){const[e,t]=await this.stream.receive();if(t!=null)throw t;return e}received(){return this.stream.received()}async closeAndAck(){this.stream.closeSend();const[e,t]=await this.stream.receive();if(e!=null)throw new wn(`${this.name} received unexpected response on closure.