@synnaxlabs/client 0.36.0 → 0.37.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/client.cjs CHANGED
@@ -1,6 +1,6 @@
1
1
  "use strict";var oo=Object.defineProperty;var co=(r,e,t)=>e in r?oo(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t;var c=(r,e,t)=>co(r,typeof e!="symbol"?e+"":e,t);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const s=require("zod"),b=r=>Array.isArray(r)?r:[r];var lo=Object.defineProperty,uo=(r,e,t)=>e in r?lo(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,k=(r,e,t)=>uo(r,typeof e!="symbol"?e+"":e,t);const ho=r=>{const e=r.replace(/_[a-z]/g,t=>t[1].toUpperCase());return e.length>1&&e[0]===e[0].toUpperCase()&&e[1]===e[1].toUpperCase()||e.length===0?e:e[0].toLowerCase()+e.slice(1)},qs=r=>{const e=(t,n=hn)=>{if(typeof t=="string")return r(t);if(Array.isArray(t))return t.map(o=>e(o,n));if(!Ur(t))return t;n=go(n);const i={},a=t;return Object.keys(a).forEach(o=>{let l=a[o];const u=r(o);n.recursive&&(Ur(l)?Fn(l,n.keepTypesOnRecursion)||(l=e(l,n)):n.recursiveInArray&&Vn(l)&&(l=[...l].map(h=>{let y=h;return Ur(h)?Fn(y,n.keepTypesOnRecursion)||(y=e(h,n)):Vn(h)&&(y=e({key:h},n).key),y}))),i[u]=l}),i};return e},Ws=qs(ho),fo=r=>r.replace(/([a-z0-9])([A-Z])/g,(e,t,n)=>`${t}_${n.toLowerCase()}`),yo=qs(fo),hn={recursive:!0,recursiveInArray:!0,keepTypesOnRecursion:[Number,String,Uint8Array]},go=(r=hn)=>(r.recursive==null?r=hn:r.recursiveInArray??(r.recursiveInArray=!1),r),Vn=r=>r!=null&&Array.isArray(r),Ur=r=>r!=null&&typeof r=="object"&&!Array.isArray(r),Fn=(r,e)=>(e||[]).some(t=>r instanceof t),Gs=r=>r!=null&&typeof r=="object"&&!Array.isArray(r);var po=Object.defineProperty,mo=(r,e,t)=>e in r?po(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,St=(r,e,t)=>mo(r,typeof e!="symbol"?e+"":e,t);let wo=class{constructor(){St(this,"contentType","application/json"),St(this,"decoder"),St(this,"encoder"),this.decoder=new TextDecoder,this.encoder=new TextEncoder}encode(r){return this.encoder.encode(this.encodeString(r)).buffer}decode(r,e){return this.decodeString(this.decoder.decode(r),e)}decodeString(r,e){const t=JSON.parse(r),n=Ws(t);return e!=null?e.parse(n):n}encodeString(r){const e=yo(r);return JSON.stringify(e,(t,n)=>ArrayBuffer.isView(n)?Array.from(n):Gs(n)&&"encode_value"in n?typeof n.value=="bigint"?n.value.toString():n.value:typeof n=="bigint"?n.toString():n)}static registerCustomType(){}},bo=class{constructor(){St(this,"contentType","text/csv")}encode(e){const t=this.encodeString(e);return new TextEncoder().encode(t).buffer}decode(e,t){const n=new TextDecoder().decode(e);return this.decodeString(n,t)}encodeString(e){if(!Array.isArray(e)||e.length===0||!Gs(e[0]))throw new Error("Payload must be an array of objects");const t=Object.keys(e[0]),n=[t.join(",")];return e.forEach(i=>{const a=t.map(o=>JSON.stringify(i[o]??""));n.push(a.join(","))}),n.join(`
2
2
  `)}decodeString(e,t){const[n,...i]=e.trim().split(`
3
- `).map(l=>l.trim());if(n.length===0)return t!=null?t.parse({}):{};const a=n.split(",").map(l=>l.trim()),o={};return a.forEach(l=>{o[l]=[]}),i.forEach(l=>{const u=l.split(",").map(h=>h.trim());a.forEach((h,y)=>{const d=this.parseValue(u[y]);d!=null&&o[h].push(d)})}),t!=null?t.parse(o):o}parseValue(e){if(e==null||e.length===0)return null;const t=Number(e);return isNaN(t)?e.startsWith('"')&&e.endsWith('"')?e.slice(1,-1):e:t}static registerCustomType(){}},vo=class{constructor(){St(this,"contentType","text/plain")}encode(r){return new TextEncoder().encode(r).buffer}decode(r,e){const t=new TextDecoder().decode(r);return e!=null?e.parse(t):t}};const tr=new wo;new bo;new vo;const zr=s.z.tuple([s.z.number(),s.z.number()]);s.z.tuple([s.z.bigint(),s.z.bigint()]);const Vs=s.z.object({width:s.z.number(),height:s.z.number()}),To=s.z.object({signedWidth:s.z.number(),signedHeight:s.z.number()}),Oo=["width","height"];s.z.enum(Oo);const zo=["start","center","end"],Eo=["signedWidth","signedHeight"];s.z.enum(Eo);const fr=s.z.object({x:s.z.number(),y:s.z.number()}),No=s.z.object({clientX:s.z.number(),clientY:s.z.number()}),So=["x","y"],Fs=s.z.enum(So),Js=["top","right","bottom","left"];s.z.enum(Js);const Io=["left","right"],Ks=s.z.enum(Io),ko=["top","bottom"],Hs=s.z.enum(ko),Xs=["center"],Jn=s.z.enum(Xs),$o=[...Js,...Xs],Qs=s.z.enum($o);s.z.enum(zo);const Ao=["first","last"];s.z.enum(Ao);const Ro=s.z.object({lower:s.z.number(),upper:s.z.number()}),xo=s.z.object({lower:s.z.bigint(),upper:s.z.bigint()});s.z.union([Ro,zr]);s.z.union([xo,zr]);s.z.union([Fs,Qs]);s.z.union([Fs,Qs,s.z.instanceof(String)]);const Co=r=>typeof r=="bigint"||r instanceof BigInt,je=(r,e)=>Co(r)?r.valueOf()*BigInt(e.valueOf()):r.valueOf()*Number(e.valueOf()),Ae=(r,e)=>{const t={};if(typeof r=="number"||typeof r=="bigint")e!=null?(t.lower=r,t.upper=e):(t.lower=typeof r=="bigint"?0n:0,t.upper=r);else if(Array.isArray(r)){if(r.length!==2)throw new Error("bounds: expected array of length 2");[t.lower,t.upper]=r}else return Kn(r);return Kn(t)},Kn=r=>r.lower>r.upper?{lower:r.upper,upper:r.lower}:r,Hn=(r,e)=>{const t=Ae(r);return e<t.lower?t.lower:e>=t.upper?t.upper-(typeof t.upper=="number"?1:1n):e};s.z.object({x:Ks.or(Jn),y:Hs.or(Jn)});const Po=s.z.object({x:Ks,y:Hs}),Do=Object.freeze({x:"left",y:"top"}),jo=(r,e)=>r.x===e.x&&r.y===e.y,Xn=s.z.union([s.z.number(),fr,zr,Vs,To,No]),Mo=(r,e)=>{if(typeof r=="string"){if(e===void 0)throw new Error("The y coordinate must be given.");return r==="x"?{x:e,y:0}:{x:0,y:e}}return typeof r=="number"?{x:r,y:e??r}:Array.isArray(r)?{x:r[0],y:r[1]}:"signedWidth"in r?{x:r.signedWidth,y:r.signedHeight}:"clientX"in r?{x:r.clientX,y:r.clientY}:"width"in r?{x:r.width,y:r.height}:{x:r.x,y:r.y}},Qn=Object.freeze({x:0,y:0}),Jt=s.z.union([s.z.number(),s.z.string()]);s.z.object({top:Jt,left:Jt,width:Jt,height:Jt});s.z.object({left:s.z.number(),top:s.z.number(),right:s.z.number(),bottom:s.z.number()});s.z.object({one:fr,two:fr,root:Po});const kn=(r,e,t=0,n=0,i)=>{const a={one:{...Qn},two:{...Qn},root:i??Do};if(typeof r=="number"){if(typeof e!="number")throw new Error("Box constructor called with invalid arguments");return a.one={x:r,y:e},a.two={x:a.one.x+t,y:a.one.y+n},a}return"one"in r&&"two"in r&&"root"in r?{...r,root:i??r.root}:("getBoundingClientRect"in r&&(r=r.getBoundingClientRect()),"left"in r?(a.one={x:r.left,y:r.top},a.two={x:r.right,y:r.bottom},a):(a.one=r,e==null?a.two={x:a.one.x+t,y:a.one.y+n}:typeof e=="number"?a.two={x:a.one.x+e,y:a.one.y+t}:"width"in e?a.two={x:a.one.x+e.width,y:a.one.y+e.height}:"signedWidth"in e?a.two={x:a.one.x+e.signedWidth,y:a.one.y+e.signedHeight}:a.two=e,a))},Zr=r=>{const e=kn(r);return{lower:e.one.x,upper:e.two.x}},Lr=r=>{const e=kn(r);return{lower:e.one.y,upper:e.two.y}},Bo=r=>typeof r!="object"||r==null?!1:"one"in r&&"two"in r&&"root"in r;var Uo=Object.defineProperty,Zo=(r,e,t)=>e in r?Uo(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,ye=(r,e,t)=>Zo(r,typeof e!="symbol"?e+"":e,t);const Lo=(r,e,t)=>e!==void 0&&r<e?e:t!==void 0&&r>t?t:r;s.z.object({offset:Xn,scale:Xn});s.z.object({offset:s.z.number(),scale:s.z.number()});const _o=r=>(e,t,n,i)=>t==="dimension"?[e,n]:[e,i?n-r:n+r],Yo=r=>(e,t,n,i)=>[e,i?n/r:n*r],qo=r=>(e,t,n)=>{if(e===null)return[r,n];const{lower:i,upper:a}=e,{lower:o,upper:l}=r,u=a-i,h=l-o;if(t==="dimension")return[r,n*(h/u)];const y=(n-i)*(h/u)+o;return[r,y]},Wo=r=>(e,t,n)=>[r,n],Go=()=>(r,e,t)=>{if(r===null)throw new Error("cannot invert without bounds");if(e==="dimension")return[r,t];const{lower:n,upper:i}=r;return[r,i-(t-n)]},Vo=r=>(e,t,n)=>{const{lower:i,upper:a}=r;return n=Lo(n,i,a),[e,n]},dn=class yt{constructor(){ye(this,"ops",[]),ye(this,"currBounds",null),ye(this,"currType",null),ye(this,"reversed",!1),this.ops=[]}static translate(e){return new yt().translate(e)}static magnify(e){return new yt().magnify(e)}static scale(e,t){return new yt().scale(e,t)}translate(e){const t=this.new(),n=_o(e);return n.type="translate",t.ops.push(n),t}magnify(e){const t=this.new(),n=Yo(e);return n.type="magnify",t.ops.push(n),t}scale(e,t){const n=Ae(e,t),i=this.new(),a=qo(n);return a.type="scale",i.ops.push(a),i}clamp(e,t){const n=Ae(e,t),i=this.new(),a=Vo(n);return a.type="clamp",i.ops.push(a),i}reBound(e,t){const n=Ae(e,t),i=this.new(),a=Wo(n);return a.type="re-bound",i.ops.push(a),i}invert(){const e=Go();e.type="invert";const t=this.new();return t.ops.push(e),t}pos(e){return this.exec("position",e)}dim(e){return this.exec("dimension",e)}new(){const e=new yt;return e.ops=this.ops.slice(),e.reversed=this.reversed,e}exec(e,t){return this.currBounds=null,this.ops.reduce(([n,i],a)=>a(n,e,i,this.reversed),[null,t])[1]}reverse(){const e=this.new();e.ops.reverse();const t=[];return e.ops.forEach((n,i)=>{if(n.type==="scale"||t.some(([o,l])=>i>=o&&i<=l))return;const a=e.ops.findIndex((o,l)=>o.type==="scale"&&l>i);a!==-1&&t.push([i,a])}),t.forEach(([n,i])=>{const a=e.ops.slice(n,i);a.unshift(e.ops[i]),e.ops.splice(n,i-n+1,...a)}),e.reversed=!e.reversed,e}get transform(){return{scale:this.dim(1),offset:this.pos(0)}}};ye(dn,"IDENTITY",new dn);let es=dn;const ts=class de{constructor(e=new es,t=new es,n=null){ye(this,"x"),ye(this,"y"),ye(this,"currRoot"),this.x=e,this.y=t,this.currRoot=n}static translate(e,t){return new de().translate(e,t)}static translateX(e){return new de().translateX(e)}static translateY(e){return new de().translateY(e)}static clamp(e){return new de().clamp(e)}static magnify(e){return new de().magnify(e)}static scale(e){return new de().scale(e)}static reBound(e){return new de().reBound(e)}translate(e,t){const n=Mo(e,t),i=this.copy();return i.x=this.x.translate(n.x),i.y=this.y.translate(n.y),i}translateX(e){const t=this.copy();return t.x=this.x.translate(e),t}translateY(e){const t=this.copy();return t.y=this.y.translate(e),t}magnify(e){const t=this.copy();return t.x=this.x.magnify(e.x),t.y=this.y.magnify(e.y),t}scale(e){const t=this.copy();if(Bo(e)){const n=this.currRoot;return t.currRoot=e.root,n!=null&&!jo(n,e.root)&&(n.x!==e.root.x&&(t.x=t.x.invert()),n.y!==e.root.y&&(t.y=t.y.invert())),t.x=t.x.scale(Zr(e)),t.y=t.y.scale(Lr(e)),t}return t.x=t.x.scale(e.width),t.y=t.y.scale(e.height),t}reBound(e){const t=this.copy();return t.x=this.x.reBound(Zr(e)),t.y=this.y.reBound(Lr(e)),t}clamp(e){const t=this.copy();return t.x=this.x.clamp(Zr(e)),t.y=this.y.clamp(Lr(e)),t}copy(){const e=new de;return e.currRoot=this.currRoot,e.x=this.x,e.y=this.y,e}reverse(){const e=this.copy();return e.x=this.x.reverse(),e.y=this.y.reverse(),e}pos(e){return{x:this.x.pos(e.x),y:this.y.pos(e.y)}}dim(e){return{x:this.x.dim(e.x),y:this.y.dim(e.y)}}box(e){return kn(this.pos(e.one),this.pos(e.two),0,0,this.currRoot??e.root)}get transform(){return{scale:this.dim({x:1,y:1}),offset:this.pos({x:0,y:0})}}};ye(ts,"IDENTITY",new ts);const Fo=r=>r!=null&&typeof r=="object"&&"toString"in r,Jo=(r,e=!1)=>{const t=Fo(r)?"stringer":typeof r;let n;switch(t){case"string":n=(i,a)=>i.localeCompare(a);break;case"stringer":n=(i,a)=>i.toString().localeCompare(a.toString());break;case"number":n=(i,a)=>Number(i)-Number(a);break;case"bigint":n=(i,a)=>BigInt(i)-BigInt(a)>0n?1:-1;break;case"boolean":n=(i,a)=>Number(i)-Number(a);break;case"undefined":n=()=>0;break;default:return console.warn(`sortFunc: unknown type ${t}`),()=>-1}return e?Ko(n):n},Ko=r=>(e,t)=>r(t,e),Ho=s.z.object({signedWidth:s.z.number(),signedHeight:s.z.number()});s.z.union([Vs,Ho,fr,zr]);const Xo=s.z.bigint().or(s.z.string().transform(BigInt));var Qo=Object.defineProperty,ec=(r,e,t)=>e in r?Qo(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,m=(r,e,t)=>ec(r,typeof e!="symbol"?e+"":e,t);let tc=(r,e=21)=>(t=e)=>{let n="",i=t;for(;i--;)n+=r[Math.random()*r.length|0];return n};const rc="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",nc=tc(rc,11),sc=s.z.enum(["static","dynamic"]),ei=(r,e)=>{const t=new M(e);if(![D.DAY,D.HOUR,D.MINUTE,D.SECOND,D.MILLISECOND,D.MICROSECOND,D.NANOSECOND].some(i=>i.equals(t)))throw new Error("Invalid argument for remainder. Must be an even TimeSpan or Timestamp");const n=r.valueOf()%t.valueOf();return r instanceof M?new M(n):new D(n)},A=class v{constructor(e,t="UTC"){if(m(this,"value"),m(this,"encodeValue",!0),e==null)this.value=v.now().valueOf();else if(e instanceof Date)this.value=BigInt(e.getTime())*v.MILLISECOND.valueOf();else if(typeof e=="string")this.value=v.parseDateTimeString(e,t).valueOf();else if(Array.isArray(e))this.value=v.parseDate(e);else{let n=BigInt(0);e instanceof Number&&(e=e.valueOf()),t==="local"&&(n=v.utcOffset.valueOf()),typeof e=="number"&&(isFinite(e)?e=Math.trunc(e):(isNaN(e)&&(e=0),e===1/0?e=v.MAX:e=v.MIN)),this.value=BigInt(e.valueOf())+n}}static parseDate([e=1970,t=1,n=1]){const i=new Date(e,t-1,n,0,0,0,0);return new v(BigInt(i.getTime())*v.MILLISECOND.valueOf()).truncate(v.DAY).valueOf()}encode(){return this.value.toString()}valueOf(){return this.value}static parseTimeString(e,t="UTC"){const[n,i,a]=e.split(":");let o="00",l="00";a!=null&&([o,l]=a.split("."));let u=v.hours(parseInt(n??"00")).add(v.minutes(parseInt(i??"00"))).add(v.seconds(parseInt(o??"00"))).add(v.milliseconds(parseInt(l??"00")));return t==="local"&&(u=u.add(v.utcOffset)),u.valueOf()}static parseDateTimeString(e,t="UTC"){if(!e.includes("/")&&!e.includes("-"))return v.parseTimeString(e,t);const n=new Date(e);return e.includes(":")||n.setUTCHours(0,0,0,0),new v(BigInt(n.getTime())*v.MILLISECOND.valueOf(),t).valueOf()}fString(e="ISO",t="UTC"){switch(e){case"ISODate":return this.toISOString(t).slice(0,10);case"ISOTime":return this.toISOString(t).slice(11,23);case"time":return this.timeString(!1,t);case"preciseTime":return this.timeString(!0,t);case"date":return this.dateString();case"preciseDate":return`${this.dateString()} ${this.timeString(!0,t)}`;case"dateTime":return`${this.dateString()} ${this.timeString(!1,t)}`;default:return this.toISOString(t)}}toISOString(e="UTC"){return e==="UTC"?this.date().toISOString():this.sub(v.utcOffset).date().toISOString()}timeString(e=!1,t="UTC"){const n=this.toISOString(t);return e?n.slice(11,23):n.slice(11,19)}dateString(){const e=this.date(),t=e.toLocaleString("default",{month:"short"}),n=e.toLocaleString("default",{day:"numeric"});return`${t} ${n}`}static get utcOffset(){return new D(BigInt(new Date().getTimezoneOffset())*v.MINUTE.valueOf())}static since(e){return new v().span(e)}date(){return new Date(this.milliseconds)}equals(e){return this.valueOf()===new v(e).valueOf()}span(e){return this.range(e).span}range(e){return new $n(this,e).makeValid()}spanRange(e){return this.range(this.add(e)).makeValid()}get isZero(){return this.valueOf()===BigInt(0)}after(e){return this.valueOf()>new v(e).valueOf()}afterEq(e){return this.valueOf()>=new v(e).valueOf()}before(e){return this.valueOf()<new v(e).valueOf()}beforeEq(e){return this.valueOf()<=new v(e).valueOf()}add(e){return new v(this.valueOf()+BigInt(e.valueOf()))}sub(e){return new v(this.valueOf()-BigInt(e.valueOf()))}get hours(){return Number(this.valueOf())/Number(D.HOUR.valueOf())}get minutes(){return Number(this.valueOf())/Number(D.MINUTE.valueOf())}get days(){return Number(this.valueOf())/Number(D.DAY.valueOf())}get seconds(){return Number(this.valueOf())/Number(D.SECOND.valueOf())}get milliseconds(){return Number(this.valueOf())/Number(v.MILLISECOND.valueOf())}get year(){return this.date().getFullYear()}setYear(e){const t=this.date();return t.setFullYear(e),new v(t)}get month(){return this.date().getMonth()}setMonth(e){const t=this.date();return t.setMonth(e),new v(t)}get day(){return this.date().getDate()}setDay(e){const t=this.date();return t.setDate(e),new v(t)}get hour(){return this.date().getHours()}setHour(e){const t=this.date();return t.setHours(e),new v(t)}get minute(){return this.date().getMinutes()}setMinute(e){const t=this.date();return t.setMinutes(e),new v(t)}get second(){return this.date().getSeconds()}setSecond(e){const t=this.date();return t.setSeconds(e),new v(t)}get millisecond(){return this.date().getMilliseconds()}setMillisecond(e){const t=this.date();return t.setMilliseconds(e),new v(t)}toString(){return this.date().toISOString()}remainder(e){return ei(this,e)}get isToday(){return this.truncate(D.DAY).equals(v.now().truncate(D.DAY))}truncate(e){return this.sub(this.remainder(e))}static now(){return new v(new Date)}static max(...e){let t=v.MIN;for(const n of e){const i=new v(n);i.after(t)&&(t=i)}return t}static min(...e){let t=v.MAX;for(const n of e){const i=new v(n);i.before(t)&&(t=i)}return t}static nanoseconds(e){return new v(e)}static microseconds(e){return v.nanoseconds(e*1e3)}static milliseconds(e){return v.microseconds(e*1e3)}static seconds(e){return v.milliseconds(e*1e3)}static minutes(e){return v.seconds(e*60)}static hours(e){return v.minutes(e*60)}static days(e){return v.hours(e*24)}};m(A,"NANOSECOND",A.nanoseconds(1)),m(A,"MICROSECOND",A.microseconds(1)),m(A,"MILLISECOND",A.milliseconds(1)),m(A,"SECOND",A.seconds(1)),m(A,"MINUTE",A.minutes(1)),m(A,"HOUR",A.hours(1)),m(A,"DAY",A.days(1)),m(A,"MAX",new A((1n<<63n)-1n)),m(A,"MIN",new A(0)),m(A,"ZERO",new A(0)),m(A,"z",s.z.union([s.z.object({value:s.z.bigint()}).transform(r=>new A(r.value)),s.z.string().transform(r=>new A(BigInt(r))),s.z.instanceof(Number).transform(r=>new A(r)),s.z.number().transform(r=>new A(r)),s.z.instanceof(A)]));let M=A;const R=class E{constructor(e){m(this,"value"),m(this,"encodeValue",!0),typeof e=="number"&&(e=Math.trunc(e.valueOf())),this.value=BigInt(e.valueOf())}static fromSeconds(e){return e instanceof E?e:e instanceof rs?e.period:e instanceof M?new E(e):["number","bigint"].includes(typeof e)?E.seconds(e):new E(e)}static fromMilliseconds(e){return e instanceof E?e:e instanceof rs?e.period:e instanceof M?new E(e):["number","bigint"].includes(typeof e)?E.milliseconds(e):new E(e)}encode(){return this.value.toString()}valueOf(){return this.value}lessThan(e){return this.valueOf()<new E(e).valueOf()}greaterThan(e){return this.valueOf()>new E(e).valueOf()}lessThanOrEqual(e){return this.valueOf()<=new E(e).valueOf()}greaterThanOrEqual(e){return this.valueOf()>=new E(e).valueOf()}remainder(e){return ei(this,e)}truncate(e){return new E(BigInt(Math.trunc(Number(this.valueOf()/e.valueOf())))*e.valueOf())}toString(){const e=this.truncate(E.DAY),t=this.truncate(E.HOUR),n=this.truncate(E.MINUTE),i=this.truncate(E.SECOND),a=this.truncate(E.MILLISECOND),o=this.truncate(E.MICROSECOND),l=this.truncate(E.NANOSECOND),u=e,h=t.sub(e),y=n.sub(t),d=i.sub(n),j=a.sub(i),$=o.sub(a),te=l.sub(o);let U="";return u.isZero||(U+=`${u.days}d `),h.isZero||(U+=`${h.hours}h `),y.isZero||(U+=`${y.minutes}m `),d.isZero||(U+=`${d.seconds}s `),j.isZero||(U+=`${j.milliseconds}ms `),$.isZero||(U+=`${$.microseconds}µs `),te.isZero||(U+=`${te.nanoseconds}ns`),U.trim()}mult(e){return new E(this.valueOf()*BigInt(e))}get days(){return Number(this.valueOf())/Number(E.DAY.valueOf())}get hours(){return Number(this.valueOf())/Number(E.HOUR.valueOf())}get minutes(){return Number(this.valueOf())/Number(E.MINUTE.valueOf())}get seconds(){return Number(this.valueOf())/Number(E.SECOND.valueOf())}get milliseconds(){return Number(this.valueOf())/Number(E.MILLISECOND.valueOf())}get microseconds(){return Number(this.valueOf())/Number(E.MICROSECOND.valueOf())}get nanoseconds(){return Number(this.valueOf())}get isZero(){return this.valueOf()===BigInt(0)}equals(e){return this.valueOf()===new E(e).valueOf()}add(e){return new E(this.valueOf()+new E(e).valueOf())}sub(e){return new E(this.valueOf()-new E(e).valueOf())}static nanoseconds(e=1){return new E(e)}static microseconds(e=1){return E.nanoseconds(je(e,1e3))}static milliseconds(e=1){return E.microseconds(je(e,1e3))}static seconds(e=1){return E.milliseconds(je(e,1e3))}static minutes(e=1){return E.seconds(je(e,60))}static hours(e){return E.minutes(je(e,60))}static days(e){return E.hours(je(e,24))}};m(R,"NANOSECOND",R.nanoseconds(1)),m(R,"MICROSECOND",R.microseconds(1)),m(R,"MILLISECOND",R.milliseconds(1)),m(R,"SECOND",R.seconds(1)),m(R,"MINUTE",R.minutes(1)),m(R,"HOUR",R.hours(1)),m(R,"DAY",R.days(1)),m(R,"MAX",new R((1n<<63n)-1n)),m(R,"MIN",new R(0)),m(R,"ZERO",new R(0)),m(R,"z",s.z.union([s.z.object({value:s.z.bigint()}).transform(r=>new R(r.value)),s.z.string().transform(r=>new R(BigInt(r))),s.z.instanceof(Number).transform(r=>new R(r)),s.z.number().transform(r=>new R(r)),s.z.instanceof(R)]));let D=R;const gt=class rr extends Number{constructor(e){e instanceof Number?super(e.valueOf()):super(e)}toString(){return`${this.valueOf()} Hz`}equals(e){return this.valueOf()===new rr(e).valueOf()}get period(){return D.seconds(1/this.valueOf())}sampleCount(e){return new D(e).seconds*this.valueOf()}byteCount(e,t){return this.sampleCount(e)*new J(t).valueOf()}span(e){return D.seconds(e/this.valueOf())}byteSpan(e,t){return this.span(e.valueOf()/t.valueOf())}static hz(e){return new rr(e)}static khz(e){return rr.hz(e*1e3)}};m(gt,"z",s.z.union([s.z.number().transform(r=>new gt(r)),s.z.instanceof(Number).transform(r=>new gt(r)),s.z.instanceof(gt)]));let rs=gt;const Y=class extends Number{constructor(e){e instanceof Number?super(e.valueOf()):super(e)}length(e){return e.valueOf()/this.valueOf()}size(e){return new fn(e*this.valueOf())}};m(Y,"UNKNOWN",new Y(0)),m(Y,"BIT128",new Y(16)),m(Y,"BIT64",new Y(8)),m(Y,"BIT32",new Y(4)),m(Y,"BIT16",new Y(2)),m(Y,"BIT8",new Y(1)),m(Y,"z",s.z.union([s.z.number().transform(r=>new Y(r)),s.z.instanceof(Number).transform(r=>new Y(r)),s.z.instanceof(Y)]));let J=Y;const ie=class nr{constructor(e,t){m(this,"start"),m(this,"end"),typeof e=="object"&&"start"in e?(this.start=new M(e.start),this.end=new M(e.end)):(this.start=new M(e),this.end=new M(t))}get span(){return new D(this.end.valueOf()-this.start.valueOf())}get isValid(){return this.start.valueOf()<=this.end.valueOf()}makeValid(){return this.isValid?this:this.swap()}get isZero(){return this.span.isZero}get numeric(){return{start:Number(this.start.valueOf()),end:Number(this.end.valueOf())}}swap(){return new nr(this.end,this.start)}equals(e){return this.start.equals(e.start)&&this.end.equals(e.end)}toString(){return`${this.start.toString()} - ${this.end.toString()}`}toPrettyString(){return`${this.start.fString("preciseDate")} - ${this.span.toString()}`}overlapsWith(e,t=D.ZERO){e=e.makeValid();const n=this.makeValid();if(this.equals(e))return!0;if(e.end.equals(n.start)||n.end.equals(e.start))return!1;const i=M.max(n.start,e.start),a=M.min(n.end,e.end);return a.before(i)?!1:new D(a.sub(i)).greaterThanOrEqual(t)}roughlyEquals(e,t){let n=this.start.sub(e.start).valueOf(),i=this.end.sub(e.end).valueOf();return n<0&&(n=-n),i<0&&(i=-i),n<=t.valueOf()&&i<=t.valueOf()}contains(e){return e instanceof nr?this.contains(e.start)&&this.contains(e.end):this.start.beforeEq(e)&&this.end.after(e)}boundBy(e){const t=new nr(this.start,this.end);return e.start.after(this.start)&&(t.start=e.start),e.start.after(this.end)&&(t.end=e.start),e.end.before(this.end)&&(t.end=e.end),e.end.before(this.start)&&(t.start=e.end),t}};m(ie,"MAX",new ie(M.MIN,M.MAX)),m(ie,"MIN",new ie(M.MAX,M.MIN)),m(ie,"ZERO",new ie(M.ZERO,M.ZERO)),m(ie,"z",s.z.union([s.z.object({start:M.z,end:M.z}).transform(r=>new ie(r.start,r.end)),s.z.instanceof(ie)]));let $n=ie;const g=class ae extends String{constructor(e){if(e instanceof ae||typeof e=="string"||typeof e.valueOf()=="string"){super(e.valueOf());return}const t=ae.ARRAY_CONSTRUCTOR_DATA_TYPES.get(e.constructor.name);if(t!=null){super(t.valueOf());return}throw super(ae.UNKNOWN.valueOf()),new Error(`unable to find data type for ${e.toString()}`)}get Array(){const e=ae.ARRAY_CONSTRUCTORS.get(this.toString());if(e==null)throw new Error(`unable to find array constructor for ${this.valueOf()}`);return e}equals(e){return this.valueOf()===e.valueOf()}matches(...e){return e.some(t=>this.equals(t))}toString(){return this.valueOf()}get isVariable(){return this.equals(ae.JSON)||this.equals(ae.STRING)}get isNumeric(){return!this.isVariable&&!this.equals(ae.UUID)}get isInteger(){return this.toString().startsWith("int")}get isFloat(){return this.toString().startsWith("float")}get density(){const e=ae.DENSITIES.get(this.toString());if(e==null)throw new Error(`unable to find density for ${this.valueOf()}`);return e}canSafelyCastTo(e){return this.equals(e)?!0:this.isVariable&&!e.isVariable||!this.isVariable&&e.isVariable?!1:this.isFloat&&e.isInteger||this.isInteger&&e.isFloat?this.density.valueOf()<e.density.valueOf():this.isFloat&&e.isFloat||this.isInteger&&e.isInteger?this.density.valueOf()<=e.density.valueOf():!1}canCastTo(e){return this.isNumeric&&e.isNumeric?!0:this.equals(e)}checkArray(e){return e.constructor===this.Array}toJSON(){return this.toString()}get usesBigInt(){return ae.BIG_INT_TYPES.some(e=>e.equals(this))}};m(g,"UNKNOWN",new g("unknown")),m(g,"FLOAT64",new g("float64")),m(g,"FLOAT32",new g("float32")),m(g,"INT64",new g("int64")),m(g,"INT32",new g("int32")),m(g,"INT16",new g("int16")),m(g,"INT8",new g("int8")),m(g,"UINT64",new g("uint64")),m(g,"UINT32",new g("uint32")),m(g,"UINT16",new g("uint16")),m(g,"UINT8",new g("uint8")),m(g,"BOOLEAN",g.UINT8),m(g,"TIMESTAMP",new g("timestamp")),m(g,"UUID",new g("uuid")),m(g,"STRING",new g("string")),m(g,"JSON",new g("json")),m(g,"ARRAY_CONSTRUCTORS",new Map([[g.UINT8.toString(),Uint8Array],[g.UINT16.toString(),Uint16Array],[g.UINT32.toString(),Uint32Array],[g.UINT64.toString(),BigUint64Array],[g.FLOAT32.toString(),Float32Array],[g.FLOAT64.toString(),Float64Array],[g.INT8.toString(),Int8Array],[g.INT16.toString(),Int16Array],[g.INT32.toString(),Int32Array],[g.INT64.toString(),BigInt64Array],[g.TIMESTAMP.toString(),BigInt64Array],[g.STRING.toString(),Uint8Array],[g.JSON.toString(),Uint8Array],[g.UUID.toString(),Uint8Array]])),m(g,"ARRAY_CONSTRUCTOR_DATA_TYPES",new Map([[Uint8Array.name,g.UINT8],[Uint16Array.name,g.UINT16],[Uint32Array.name,g.UINT32],[BigUint64Array.name,g.UINT64],[Float32Array.name,g.FLOAT32],[Float64Array.name,g.FLOAT64],[Int8Array.name,g.INT8],[Int16Array.name,g.INT16],[Int32Array.name,g.INT32],[BigInt64Array.name,g.INT64]])),m(g,"DENSITIES",new Map([[g.UINT8.toString(),J.BIT8],[g.UINT16.toString(),J.BIT16],[g.UINT32.toString(),J.BIT32],[g.UINT64.toString(),J.BIT64],[g.FLOAT32.toString(),J.BIT32],[g.FLOAT64.toString(),J.BIT64],[g.INT8.toString(),J.BIT8],[g.INT16.toString(),J.BIT16],[g.INT32.toString(),J.BIT32],[g.INT64.toString(),J.BIT64],[g.TIMESTAMP.toString(),J.BIT64],[g.STRING.toString(),J.UNKNOWN],[g.JSON.toString(),J.UNKNOWN],[g.UUID.toString(),J.BIT128]])),m(g,"ALL",[g.UNKNOWN,g.FLOAT64,g.FLOAT32,g.INT64,g.INT32,g.INT16,g.INT8,g.UINT64,g.UINT32,g.UINT16,g.UINT8,g.TIMESTAMP,g.UUID,g.STRING,g.JSON]),m(g,"BIG_INT_TYPES",[g.INT64,g.UINT64,g.TIMESTAMP]),m(g,"z",s.z.union([s.z.string().transform(r=>new g(r)),s.z.instanceof(g)]));let x=g;const G=class Z extends Number{constructor(e){super(e.valueOf())}largerThan(e){return this.valueOf()>e.valueOf()}smallerThan(e){return this.valueOf()<e.valueOf()}add(e){return Z.bytes(this.valueOf()+e.valueOf())}sub(e){return Z.bytes(this.valueOf()-e.valueOf())}truncate(e){return new Z(Math.trunc(this.valueOf()/e.valueOf())*e.valueOf())}remainder(e){return Z.bytes(this.valueOf()%e.valueOf())}get gigabytes(){return this.valueOf()/Z.GIGABYTE.valueOf()}get megabytes(){return this.valueOf()/Z.MEGABYTE.valueOf()}get kilobytes(){return this.valueOf()/Z.KILOBYTE.valueOf()}get terabytes(){return this.valueOf()/Z.TERABYTE.valueOf()}toString(){const e=this.truncate(Z.TERABYTE),t=this.truncate(Z.GIGABYTE),n=this.truncate(Z.MEGABYTE),i=this.truncate(Z.KILOBYTE),a=this.truncate(Z.BYTE),o=e,l=t.sub(e),u=n.sub(t),h=i.sub(n),y=a.sub(i);let d="";return o.isZero||(d+=`${o.terabytes}TB `),l.isZero||(d+=`${l.gigabytes}GB `),u.isZero||(d+=`${u.megabytes}MB `),h.isZero||(d+=`${h.kilobytes}KB `),(!y.isZero||d==="")&&(d+=`${y.valueOf()}B`),d.trim()}static bytes(e=1){return new Z(e)}static kilobytes(e=1){return Z.bytes(e.valueOf()*1e3)}static megabytes(e=1){return Z.kilobytes(e.valueOf()*1e3)}static gigabytes(e=1){return Z.megabytes(e.valueOf()*1e3)}static terabytes(e){return Z.gigabytes(e.valueOf()*1e3)}get isZero(){return this.valueOf()===0}};m(G,"BYTE",new G(1)),m(G,"KILOBYTE",G.kilobytes(1)),m(G,"MEGABYTE",G.megabytes(1)),m(G,"GIGABYTE",G.gigabytes(1)),m(G,"TERABYTE",G.terabytes(1)),m(G,"ZERO",new G(0)),m(G,"z",s.z.union([s.z.number().transform(r=>new G(r)),s.z.instanceof(G)]));let fn=G;s.z.union([s.z.instanceof(Uint8Array),s.z.instanceof(Uint16Array),s.z.instanceof(Uint32Array),s.z.instanceof(BigUint64Array),s.z.instanceof(Float32Array),s.z.instanceof(Float64Array),s.z.instanceof(Int8Array),s.z.instanceof(Int16Array),s.z.instanceof(Int32Array),s.z.instanceof(BigInt64Array)]);const ti=r=>{const e=typeof r;return e==="string"||e==="number"||e==="boolean"||e==="bigint"||r instanceof M||r instanceof D||r instanceof Date},ic=(r,e,t,n=0)=>r.usesBigInt&&!e.usesBigInt?Number(t)-Number(n):!r.usesBigInt&&e.usesBigInt?BigInt(t.valueOf())-BigInt(n.valueOf()):mt(t,-n).valueOf(),ac=r=>r==null?!1:Array.isArray(r)||r instanceof ArrayBuffer||ArrayBuffer.isView(r)&&!(r instanceof DataView)||r instanceof lc?!0:ti(r),be=-1,oc=s.z.string().transform(r=>new Uint8Array(atob(r).split("").map(e=>e.charCodeAt(0))).buffer),cc=s.z.union([s.z.null(),s.z.undefined()]).transform(()=>new Uint8Array().buffer),yn=10,pt=class oe{constructor(e){m(this,"key",""),m(this,"isSynnaxSeries",!0),m(this,"dataType"),m(this,"sampleOffset"),m(this,"gl"),m(this,"_data"),m(this,"_timeRange"),m(this,"alignment",0n),m(this,"_cachedMin"),m(this,"_cachedMax"),m(this,"writePos",be),m(this,"_refCount",0),m(this,"_cachedLength"),m(this,"_cachedIndexes"),ac(e)&&(e={data:e});const{dataType:t,timeRange:n,sampleOffset:i=0,glBufferUsage:a="static",alignment:o=0n,key:l=nc()}=e,u=e.data??[];if(u instanceof oe||typeof u=="object"&&"isSynnaxSeries"in u&&u.isSynnaxSeries===!0){const d=u;this.key=d.key,this.dataType=d.dataType,this.sampleOffset=d.sampleOffset,this.gl=d.gl,this._data=d._data,this._timeRange=d._timeRange,this.alignment=d.alignment,this._cachedMin=d._cachedMin,this._cachedMax=d._cachedMax,this.writePos=d.writePos,this._refCount=d._refCount,this._cachedLength=d._cachedLength;return}const h=ti(u),y=Array.isArray(u);if(t!=null)this.dataType=new x(t);else{if(u instanceof ArrayBuffer)throw new Error("cannot infer data type from an ArrayBuffer instance when constructing a Series. Please provide a data type.");if(y||h){let d=u;if(!h){if(u.length===0)throw new Error("cannot infer data type from a zero length JS array when constructing a Series. Please provide a data type.");d=u[0]}if(typeof d=="string")this.dataType=x.STRING;else if(typeof d=="number")this.dataType=x.FLOAT64;else if(typeof d=="bigint")this.dataType=x.INT64;else if(typeof d=="boolean")this.dataType=x.BOOLEAN;else if(d instanceof M||d instanceof Date||d instanceof M)this.dataType=x.TIMESTAMP;else if(typeof d=="object")this.dataType=x.JSON;else throw new Error(`cannot infer data type of ${typeof d} when constructing a Series from a JS array`)}else this.dataType=new x(u)}if(!y&&!h)this._data=u;else{let d=h?[u]:u;const j=d[0];(j instanceof M||j instanceof Date||j instanceof D)&&(d=d.map($=>new M($).valueOf())),this.dataType.equals(x.STRING)?(this._cachedLength=d.length,this._data=new TextEncoder().encode(`${d.join(`
3
+ `).map(l=>l.trim());if(n.length===0)return t!=null?t.parse({}):{};const a=n.split(",").map(l=>l.trim()),o={};return a.forEach(l=>{o[l]=[]}),i.forEach(l=>{const u=l.split(",").map(h=>h.trim());a.forEach((h,y)=>{const d=this.parseValue(u[y]);d!=null&&o[h].push(d)})}),t!=null?t.parse(o):o}parseValue(e){if(e==null||e.length===0)return null;const t=Number(e);return isNaN(t)?e.startsWith('"')&&e.endsWith('"')?e.slice(1,-1):e:t}static registerCustomType(){}},vo=class{constructor(){St(this,"contentType","text/plain")}encode(r){return new TextEncoder().encode(r).buffer}decode(r,e){const t=new TextDecoder().decode(r);return e!=null?e.parse(t):t}};const tr=new wo;new bo;new vo;const To=r=>r!=null&&typeof r=="object"&&"toString"in r,Oo=(r,e=!1)=>{const t=To(r)?"stringer":typeof r;let n;switch(t){case"string":n=(i,a)=>i.localeCompare(a);break;case"stringer":n=(i,a)=>i.toString().localeCompare(a.toString());break;case"number":n=(i,a)=>Number(i)-Number(a);break;case"bigint":n=(i,a)=>BigInt(i)-BigInt(a)>0n?1:-1;break;case"boolean":n=(i,a)=>Number(i)-Number(a);break;case"undefined":n=()=>0;break;default:return console.warn(`sortFunc: unknown type ${t}`),()=>-1}return e?zo(n):n},zo=r=>(e,t)=>r(t,e),zr=s.z.tuple([s.z.number(),s.z.number()]);s.z.tuple([s.z.bigint(),s.z.bigint()]);const Vs=s.z.object({width:s.z.number(),height:s.z.number()}),Eo=s.z.object({signedWidth:s.z.number(),signedHeight:s.z.number()}),No=["width","height"];s.z.enum(No);const So=["start","center","end"],Io=["signedWidth","signedHeight"];s.z.enum(Io);const fr=s.z.object({x:s.z.number(),y:s.z.number()}),ko=s.z.object({clientX:s.z.number(),clientY:s.z.number()}),$o=["x","y"],Fs=s.z.enum($o),Js=["top","right","bottom","left"];s.z.enum(Js);const Ao=["left","right"],Ks=s.z.enum(Ao),Ro=["top","bottom"],Hs=s.z.enum(Ro),Xs=["center"],Jn=s.z.enum(Xs),xo=[...Js,...Xs],Qs=s.z.enum(xo);s.z.enum(So);const Co=["first","last"];s.z.enum(Co);const Po=s.z.object({lower:s.z.number(),upper:s.z.number()}),Do=s.z.object({lower:s.z.bigint(),upper:s.z.bigint()});s.z.union([Po,zr]);s.z.union([Do,zr]);s.z.union([Fs,Qs]);s.z.union([Fs,Qs,s.z.instanceof(String)]);const jo=r=>typeof r=="bigint"||r instanceof BigInt,je=(r,e)=>jo(r)?r.valueOf()*BigInt(e.valueOf()):r.valueOf()*Number(e.valueOf()),Ae=(r,e)=>{const t={};if(typeof r=="number"||typeof r=="bigint")e!=null?(t.lower=r,t.upper=e):(t.lower=typeof r=="bigint"?0n:0,t.upper=r);else if(Array.isArray(r)){if(r.length!==2)throw new Error("bounds: expected array of length 2");[t.lower,t.upper]=r}else return Kn(r);return Kn(t)},Kn=r=>r.lower>r.upper?{lower:r.upper,upper:r.lower}:r,Hn=(r,e)=>{const t=Ae(r);return e<t.lower?t.lower:e>=t.upper?t.upper-(typeof t.upper=="number"?1:1n):e};s.z.object({x:Ks.or(Jn),y:Hs.or(Jn)});const Mo=s.z.object({x:Ks,y:Hs}),Bo=Object.freeze({x:"left",y:"top"}),Uo=(r,e)=>r.x===e.x&&r.y===e.y,Xn=s.z.union([s.z.number(),fr,zr,Vs,Eo,ko]),Zo=(r,e)=>{if(typeof r=="string"){if(e===void 0)throw new Error("The y coordinate must be given.");return r==="x"?{x:e,y:0}:{x:0,y:e}}return typeof r=="number"?{x:r,y:e??r}:Array.isArray(r)?{x:r[0],y:r[1]}:"signedWidth"in r?{x:r.signedWidth,y:r.signedHeight}:"clientX"in r?{x:r.clientX,y:r.clientY}:"width"in r?{x:r.width,y:r.height}:{x:r.x,y:r.y}},Qn=Object.freeze({x:0,y:0}),Jt=s.z.union([s.z.number(),s.z.string()]);s.z.object({top:Jt,left:Jt,width:Jt,height:Jt});s.z.object({left:s.z.number(),top:s.z.number(),right:s.z.number(),bottom:s.z.number()});s.z.object({one:fr,two:fr,root:Mo});const kn=(r,e,t=0,n=0,i)=>{const a={one:{...Qn},two:{...Qn},root:i??Bo};if(typeof r=="number"){if(typeof e!="number")throw new Error("Box constructor called with invalid arguments");return a.one={x:r,y:e},a.two={x:a.one.x+t,y:a.one.y+n},a}return"one"in r&&"two"in r&&"root"in r?{...r,root:i??r.root}:("getBoundingClientRect"in r&&(r=r.getBoundingClientRect()),"left"in r?(a.one={x:r.left,y:r.top},a.two={x:r.right,y:r.bottom},a):(a.one=r,e==null?a.two={x:a.one.x+t,y:a.one.y+n}:typeof e=="number"?a.two={x:a.one.x+e,y:a.one.y+t}:"width"in e?a.two={x:a.one.x+e.width,y:a.one.y+e.height}:"signedWidth"in e?a.two={x:a.one.x+e.signedWidth,y:a.one.y+e.signedHeight}:a.two=e,a))},Zr=r=>{const e=kn(r);return{lower:e.one.x,upper:e.two.x}},Lr=r=>{const e=kn(r);return{lower:e.one.y,upper:e.two.y}},Lo=r=>typeof r!="object"||r==null?!1:"one"in r&&"two"in r&&"root"in r,_o=s.z.object({signedWidth:s.z.number(),signedHeight:s.z.number()});s.z.union([Vs,_o,fr,zr]);var Yo=Object.defineProperty,qo=(r,e,t)=>e in r?Yo(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,ye=(r,e,t)=>qo(r,typeof e!="symbol"?e+"":e,t);const Wo=(r,e,t)=>e!==void 0&&r<e?e:t!==void 0&&r>t?t:r;s.z.object({offset:Xn,scale:Xn});s.z.object({offset:s.z.number(),scale:s.z.number()});const Go=r=>(e,t,n,i)=>t==="dimension"?[e,n]:[e,i?n-r:n+r],Vo=r=>(e,t,n,i)=>[e,i?n/r:n*r],Fo=r=>(e,t,n)=>{if(e===null)return[r,n];const{lower:i,upper:a}=e,{lower:o,upper:l}=r,u=a-i,h=l-o;if(t==="dimension")return[r,n*(h/u)];const y=(n-i)*(h/u)+o;return[r,y]},Jo=r=>(e,t,n)=>[r,n],Ko=()=>(r,e,t)=>{if(r===null)throw new Error("cannot invert without bounds");if(e==="dimension")return[r,t];const{lower:n,upper:i}=r;return[r,i-(t-n)]},Ho=r=>(e,t,n)=>{const{lower:i,upper:a}=r;return n=Wo(n,i,a),[e,n]},dn=class yt{constructor(){ye(this,"ops",[]),ye(this,"currBounds",null),ye(this,"currType",null),ye(this,"reversed",!1),this.ops=[]}static translate(e){return new yt().translate(e)}static magnify(e){return new yt().magnify(e)}static scale(e,t){return new yt().scale(e,t)}translate(e){const t=this.new(),n=Go(e);return n.type="translate",t.ops.push(n),t}magnify(e){const t=this.new(),n=Vo(e);return n.type="magnify",t.ops.push(n),t}scale(e,t){const n=Ae(e,t),i=this.new(),a=Fo(n);return a.type="scale",i.ops.push(a),i}clamp(e,t){const n=Ae(e,t),i=this.new(),a=Ho(n);return a.type="clamp",i.ops.push(a),i}reBound(e,t){const n=Ae(e,t),i=this.new(),a=Jo(n);return a.type="re-bound",i.ops.push(a),i}invert(){const e=Ko();e.type="invert";const t=this.new();return t.ops.push(e),t}pos(e){return this.exec("position",e)}dim(e){return this.exec("dimension",e)}new(){const e=new yt;return e.ops=this.ops.slice(),e.reversed=this.reversed,e}exec(e,t){return this.currBounds=null,this.ops.reduce(([n,i],a)=>a(n,e,i,this.reversed),[null,t])[1]}reverse(){const e=this.new();e.ops.reverse();const t=[];return e.ops.forEach((n,i)=>{if(n.type==="scale"||t.some(([o,l])=>i>=o&&i<=l))return;const a=e.ops.findIndex((o,l)=>o.type==="scale"&&l>i);a!==-1&&t.push([i,a])}),t.forEach(([n,i])=>{const a=e.ops.slice(n,i);a.unshift(e.ops[i]),e.ops.splice(n,i-n+1,...a)}),e.reversed=!e.reversed,e}get transform(){return{scale:this.dim(1),offset:this.pos(0)}}};ye(dn,"IDENTITY",new dn);let es=dn;const ts=class de{constructor(e=new es,t=new es,n=null){ye(this,"x"),ye(this,"y"),ye(this,"currRoot"),this.x=e,this.y=t,this.currRoot=n}static translate(e,t){return new de().translate(e,t)}static translateX(e){return new de().translateX(e)}static translateY(e){return new de().translateY(e)}static clamp(e){return new de().clamp(e)}static magnify(e){return new de().magnify(e)}static scale(e){return new de().scale(e)}static reBound(e){return new de().reBound(e)}translate(e,t){const n=Zo(e,t),i=this.copy();return i.x=this.x.translate(n.x),i.y=this.y.translate(n.y),i}translateX(e){const t=this.copy();return t.x=this.x.translate(e),t}translateY(e){const t=this.copy();return t.y=this.y.translate(e),t}magnify(e){const t=this.copy();return t.x=this.x.magnify(e.x),t.y=this.y.magnify(e.y),t}scale(e){const t=this.copy();if(Lo(e)){const n=this.currRoot;return t.currRoot=e.root,n!=null&&!Uo(n,e.root)&&(n.x!==e.root.x&&(t.x=t.x.invert()),n.y!==e.root.y&&(t.y=t.y.invert())),t.x=t.x.scale(Zr(e)),t.y=t.y.scale(Lr(e)),t}return t.x=t.x.scale(e.width),t.y=t.y.scale(e.height),t}reBound(e){const t=this.copy();return t.x=this.x.reBound(Zr(e)),t.y=this.y.reBound(Lr(e)),t}clamp(e){const t=this.copy();return t.x=this.x.clamp(Zr(e)),t.y=this.y.clamp(Lr(e)),t}copy(){const e=new de;return e.currRoot=this.currRoot,e.x=this.x,e.y=this.y,e}reverse(){const e=this.copy();return e.x=this.x.reverse(),e.y=this.y.reverse(),e}pos(e){return{x:this.x.pos(e.x),y:this.y.pos(e.y)}}dim(e){return{x:this.x.dim(e.x),y:this.y.dim(e.y)}}box(e){return kn(this.pos(e.one),this.pos(e.two),0,0,this.currRoot??e.root)}get transform(){return{scale:this.dim({x:1,y:1}),offset:this.pos({x:0,y:0})}}};ye(ts,"IDENTITY",new ts);const Xo=s.z.bigint().or(s.z.string().transform(BigInt));var Qo=Object.defineProperty,ec=(r,e,t)=>e in r?Qo(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,m=(r,e,t)=>ec(r,typeof e!="symbol"?e+"":e,t);let tc=(r,e=21)=>(t=e)=>{let n="",i=t|0;for(;i--;)n+=r[Math.random()*r.length|0];return n};const rc="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",nc=tc(rc,11),sc=s.z.enum(["static","dynamic"]),ei=(r,e)=>{const t=new M(e);if(![D.DAY,D.HOUR,D.MINUTE,D.SECOND,D.MILLISECOND,D.MICROSECOND,D.NANOSECOND].some(i=>i.equals(t)))throw new Error("Invalid argument for remainder. Must be an even TimeSpan or Timestamp");const n=r.valueOf()%t.valueOf();return r instanceof M?new M(n):new D(n)},A=class v{constructor(e,t="UTC"){if(m(this,"value"),m(this,"encodeValue",!0),e==null)this.value=v.now().valueOf();else if(e instanceof Date)this.value=BigInt(e.getTime())*v.MILLISECOND.valueOf();else if(typeof e=="string")this.value=v.parseDateTimeString(e,t).valueOf();else if(Array.isArray(e))this.value=v.parseDate(e);else{let n=BigInt(0);e instanceof Number&&(e=e.valueOf()),t==="local"&&(n=v.utcOffset.valueOf()),typeof e=="number"&&(isFinite(e)?e=Math.trunc(e):(isNaN(e)&&(e=0),e===1/0?e=v.MAX:e=v.MIN)),this.value=BigInt(e.valueOf())+n}}static parseDate([e=1970,t=1,n=1]){const i=new Date(e,t-1,n,0,0,0,0);return new v(BigInt(i.getTime())*v.MILLISECOND.valueOf()).truncate(v.DAY).valueOf()}encode(){return this.value.toString()}valueOf(){return this.value}static parseTimeString(e,t="UTC"){const[n,i,a]=e.split(":");let o="00",l="00";a!=null&&([o,l]=a.split("."));let u=v.hours(parseInt(n??"00")).add(v.minutes(parseInt(i??"00"))).add(v.seconds(parseInt(o??"00"))).add(v.milliseconds(parseInt(l??"00")));return t==="local"&&(u=u.add(v.utcOffset)),u.valueOf()}static parseDateTimeString(e,t="UTC"){if(!e.includes("/")&&!e.includes("-"))return v.parseTimeString(e,t);const n=new Date(e);return e.includes(":")||n.setUTCHours(0,0,0,0),new v(BigInt(n.getTime())*v.MILLISECOND.valueOf(),t).valueOf()}fString(e="ISO",t="UTC"){switch(e){case"ISODate":return this.toISOString(t).slice(0,10);case"ISOTime":return this.toISOString(t).slice(11,23);case"time":return this.timeString(!1,t);case"preciseTime":return this.timeString(!0,t);case"date":return this.dateString();case"preciseDate":return`${this.dateString()} ${this.timeString(!0,t)}`;case"dateTime":return`${this.dateString()} ${this.timeString(!1,t)}`;default:return this.toISOString(t)}}toISOString(e="UTC"){return e==="UTC"?this.date().toISOString():this.sub(v.utcOffset).date().toISOString()}timeString(e=!1,t="UTC"){const n=this.toISOString(t);return e?n.slice(11,23):n.slice(11,19)}dateString(){const e=this.date(),t=e.toLocaleString("default",{month:"short"}),n=e.toLocaleString("default",{day:"numeric"});return`${t} ${n}`}static get utcOffset(){return new D(BigInt(new Date().getTimezoneOffset())*v.MINUTE.valueOf())}static since(e){return new v().span(e)}date(){return new Date(this.milliseconds)}equals(e){return this.valueOf()===new v(e).valueOf()}span(e){return this.range(e).span}range(e){return new $n(this,e).makeValid()}spanRange(e){return this.range(this.add(e)).makeValid()}get isZero(){return this.valueOf()===BigInt(0)}after(e){return this.valueOf()>new v(e).valueOf()}afterEq(e){return this.valueOf()>=new v(e).valueOf()}before(e){return this.valueOf()<new v(e).valueOf()}beforeEq(e){return this.valueOf()<=new v(e).valueOf()}add(e){return new v(this.valueOf()+BigInt(e.valueOf()))}sub(e){return new v(this.valueOf()-BigInt(e.valueOf()))}get hours(){return Number(this.valueOf())/Number(D.HOUR.valueOf())}get minutes(){return Number(this.valueOf())/Number(D.MINUTE.valueOf())}get days(){return Number(this.valueOf())/Number(D.DAY.valueOf())}get seconds(){return Number(this.valueOf())/Number(D.SECOND.valueOf())}get milliseconds(){return Number(this.valueOf())/Number(v.MILLISECOND.valueOf())}get year(){return this.date().getFullYear()}setYear(e){const t=this.date();return t.setFullYear(e),new v(t)}get month(){return this.date().getMonth()}setMonth(e){const t=this.date();return t.setMonth(e),new v(t)}get day(){return this.date().getDate()}setDay(e){const t=this.date();return t.setDate(e),new v(t)}get hour(){return this.date().getHours()}setHour(e){const t=this.date();return t.setHours(e),new v(t)}get minute(){return this.date().getMinutes()}setMinute(e){const t=this.date();return t.setMinutes(e),new v(t)}get second(){return this.date().getSeconds()}setSecond(e){const t=this.date();return t.setSeconds(e),new v(t)}get millisecond(){return this.date().getMilliseconds()}setMillisecond(e){const t=this.date();return t.setMilliseconds(e),new v(t)}toString(){return this.date().toISOString()}remainder(e){return ei(this,e)}get isToday(){return this.truncate(D.DAY).equals(v.now().truncate(D.DAY))}truncate(e){return this.sub(this.remainder(e))}static now(){return new v(new Date)}static max(...e){let t=v.MIN;for(const n of e){const i=new v(n);i.after(t)&&(t=i)}return t}static min(...e){let t=v.MAX;for(const n of e){const i=new v(n);i.before(t)&&(t=i)}return t}static nanoseconds(e){return new v(e)}static microseconds(e){return v.nanoseconds(e*1e3)}static milliseconds(e){return v.microseconds(e*1e3)}static seconds(e){return v.milliseconds(e*1e3)}static minutes(e){return v.seconds(e*60)}static hours(e){return v.minutes(e*60)}static days(e){return v.hours(e*24)}};m(A,"NANOSECOND",A.nanoseconds(1)),m(A,"MICROSECOND",A.microseconds(1)),m(A,"MILLISECOND",A.milliseconds(1)),m(A,"SECOND",A.seconds(1)),m(A,"MINUTE",A.minutes(1)),m(A,"HOUR",A.hours(1)),m(A,"DAY",A.days(1)),m(A,"MAX",new A((1n<<63n)-1n)),m(A,"MIN",new A(0)),m(A,"ZERO",new A(0)),m(A,"z",s.z.union([s.z.object({value:s.z.bigint()}).transform(r=>new A(r.value)),s.z.string().transform(r=>new A(BigInt(r))),s.z.instanceof(Number).transform(r=>new A(r)),s.z.number().transform(r=>new A(r)),s.z.instanceof(A)]));let M=A;const R=class E{constructor(e){m(this,"value"),m(this,"encodeValue",!0),typeof e=="number"&&(e=Math.trunc(e.valueOf())),this.value=BigInt(e.valueOf())}static fromSeconds(e){return e instanceof E?e:e instanceof rs?e.period:e instanceof M?new E(e):["number","bigint"].includes(typeof e)?E.seconds(e):new E(e)}static fromMilliseconds(e){return e instanceof E?e:e instanceof rs?e.period:e instanceof M?new E(e):["number","bigint"].includes(typeof e)?E.milliseconds(e):new E(e)}encode(){return this.value.toString()}valueOf(){return this.value}lessThan(e){return this.valueOf()<new E(e).valueOf()}greaterThan(e){return this.valueOf()>new E(e).valueOf()}lessThanOrEqual(e){return this.valueOf()<=new E(e).valueOf()}greaterThanOrEqual(e){return this.valueOf()>=new E(e).valueOf()}remainder(e){return ei(this,e)}truncate(e){return new E(BigInt(Math.trunc(Number(this.valueOf()/e.valueOf())))*e.valueOf())}toString(){const e=this.truncate(E.DAY),t=this.truncate(E.HOUR),n=this.truncate(E.MINUTE),i=this.truncate(E.SECOND),a=this.truncate(E.MILLISECOND),o=this.truncate(E.MICROSECOND),l=this.truncate(E.NANOSECOND),u=e,h=t.sub(e),y=n.sub(t),d=i.sub(n),j=a.sub(i),$=o.sub(a),te=l.sub(o);let U="";return u.isZero||(U+=`${u.days}d `),h.isZero||(U+=`${h.hours}h `),y.isZero||(U+=`${y.minutes}m `),d.isZero||(U+=`${d.seconds}s `),j.isZero||(U+=`${j.milliseconds}ms `),$.isZero||(U+=`${$.microseconds}µs `),te.isZero||(U+=`${te.nanoseconds}ns`),U.trim()}mult(e){return new E(this.valueOf()*BigInt(e))}get days(){return Number(this.valueOf())/Number(E.DAY.valueOf())}get hours(){return Number(this.valueOf())/Number(E.HOUR.valueOf())}get minutes(){return Number(this.valueOf())/Number(E.MINUTE.valueOf())}get seconds(){return Number(this.valueOf())/Number(E.SECOND.valueOf())}get milliseconds(){return Number(this.valueOf())/Number(E.MILLISECOND.valueOf())}get microseconds(){return Number(this.valueOf())/Number(E.MICROSECOND.valueOf())}get nanoseconds(){return Number(this.valueOf())}get isZero(){return this.valueOf()===BigInt(0)}equals(e){return this.valueOf()===new E(e).valueOf()}add(e){return new E(this.valueOf()+new E(e).valueOf())}sub(e){return new E(this.valueOf()-new E(e).valueOf())}static nanoseconds(e=1){return new E(e)}static microseconds(e=1){return E.nanoseconds(je(e,1e3))}static milliseconds(e=1){return E.microseconds(je(e,1e3))}static seconds(e=1){return E.milliseconds(je(e,1e3))}static minutes(e=1){return E.seconds(je(e,60))}static hours(e){return E.minutes(je(e,60))}static days(e){return E.hours(je(e,24))}};m(R,"NANOSECOND",R.nanoseconds(1)),m(R,"MICROSECOND",R.microseconds(1)),m(R,"MILLISECOND",R.milliseconds(1)),m(R,"SECOND",R.seconds(1)),m(R,"MINUTE",R.minutes(1)),m(R,"HOUR",R.hours(1)),m(R,"DAY",R.days(1)),m(R,"MAX",new R((1n<<63n)-1n)),m(R,"MIN",new R(0)),m(R,"ZERO",new R(0)),m(R,"z",s.z.union([s.z.object({value:s.z.bigint()}).transform(r=>new R(r.value)),s.z.string().transform(r=>new R(BigInt(r))),s.z.instanceof(Number).transform(r=>new R(r)),s.z.number().transform(r=>new R(r)),s.z.instanceof(R)]));let D=R;const gt=class rr extends Number{constructor(e){e instanceof Number?super(e.valueOf()):super(e)}toString(){return`${this.valueOf()} Hz`}equals(e){return this.valueOf()===new rr(e).valueOf()}get period(){return D.seconds(1/this.valueOf())}sampleCount(e){return new D(e).seconds*this.valueOf()}byteCount(e,t){return this.sampleCount(e)*new J(t).valueOf()}span(e){return D.seconds(e/this.valueOf())}byteSpan(e,t){return this.span(e.valueOf()/t.valueOf())}static hz(e){return new rr(e)}static khz(e){return rr.hz(e*1e3)}};m(gt,"z",s.z.union([s.z.number().transform(r=>new gt(r)),s.z.instanceof(Number).transform(r=>new gt(r)),s.z.instanceof(gt)]));let rs=gt;const Y=class extends Number{constructor(e){e instanceof Number?super(e.valueOf()):super(e)}length(e){return e.valueOf()/this.valueOf()}size(e){return new fn(e*this.valueOf())}};m(Y,"UNKNOWN",new Y(0)),m(Y,"BIT128",new Y(16)),m(Y,"BIT64",new Y(8)),m(Y,"BIT32",new Y(4)),m(Y,"BIT16",new Y(2)),m(Y,"BIT8",new Y(1)),m(Y,"z",s.z.union([s.z.number().transform(r=>new Y(r)),s.z.instanceof(Number).transform(r=>new Y(r)),s.z.instanceof(Y)]));let J=Y;const ie=class nr{constructor(e,t){m(this,"start"),m(this,"end"),typeof e=="object"&&"start"in e?(this.start=new M(e.start),this.end=new M(e.end)):(this.start=new M(e),this.end=new M(t))}get span(){return new D(this.end.valueOf()-this.start.valueOf())}get isValid(){return this.start.valueOf()<=this.end.valueOf()}makeValid(){return this.isValid?this:this.swap()}get isZero(){return this.span.isZero}get numeric(){return{start:Number(this.start.valueOf()),end:Number(this.end.valueOf())}}swap(){return new nr(this.end,this.start)}equals(e){return this.start.equals(e.start)&&this.end.equals(e.end)}toString(){return`${this.start.toString()} - ${this.end.toString()}`}toPrettyString(){return`${this.start.fString("preciseDate")} - ${this.span.toString()}`}overlapsWith(e,t=D.ZERO){e=e.makeValid();const n=this.makeValid();if(this.equals(e))return!0;if(e.end.equals(n.start)||n.end.equals(e.start))return!1;const i=M.max(n.start,e.start),a=M.min(n.end,e.end);return a.before(i)?!1:new D(a.sub(i)).greaterThanOrEqual(t)}roughlyEquals(e,t){let n=this.start.sub(e.start).valueOf(),i=this.end.sub(e.end).valueOf();return n<0&&(n=-n),i<0&&(i=-i),n<=t.valueOf()&&i<=t.valueOf()}contains(e){return e instanceof nr?this.contains(e.start)&&this.contains(e.end):this.start.beforeEq(e)&&this.end.after(e)}boundBy(e){const t=new nr(this.start,this.end);return e.start.after(this.start)&&(t.start=e.start),e.start.after(this.end)&&(t.end=e.start),e.end.before(this.end)&&(t.end=e.end),e.end.before(this.start)&&(t.start=e.end),t}};m(ie,"MAX",new ie(M.MIN,M.MAX)),m(ie,"MIN",new ie(M.MAX,M.MIN)),m(ie,"ZERO",new ie(M.ZERO,M.ZERO)),m(ie,"z",s.z.union([s.z.object({start:M.z,end:M.z}).transform(r=>new ie(r.start,r.end)),s.z.instanceof(ie)]));let $n=ie;const g=class ae extends String{constructor(e){if(e instanceof ae||typeof e=="string"||typeof e.valueOf()=="string"){super(e.valueOf());return}const t=ae.ARRAY_CONSTRUCTOR_DATA_TYPES.get(e.constructor.name);if(t!=null){super(t.valueOf());return}throw super(ae.UNKNOWN.valueOf()),new Error(`unable to find data type for ${e.toString()}`)}get Array(){const e=ae.ARRAY_CONSTRUCTORS.get(this.toString());if(e==null)throw new Error(`unable to find array constructor for ${this.valueOf()}`);return e}equals(e){return this.valueOf()===e.valueOf()}matches(...e){return e.some(t=>this.equals(t))}toString(){return this.valueOf()}get isVariable(){return this.equals(ae.JSON)||this.equals(ae.STRING)}get isNumeric(){return!this.isVariable&&!this.equals(ae.UUID)}get isInteger(){return this.toString().startsWith("int")}get isFloat(){return this.toString().startsWith("float")}get density(){const e=ae.DENSITIES.get(this.toString());if(e==null)throw new Error(`unable to find density for ${this.valueOf()}`);return e}canSafelyCastTo(e){return this.equals(e)?!0:this.isVariable&&!e.isVariable||!this.isVariable&&e.isVariable?!1:this.isFloat&&e.isInteger||this.isInteger&&e.isFloat?this.density.valueOf()<e.density.valueOf():this.isFloat&&e.isFloat||this.isInteger&&e.isInteger?this.density.valueOf()<=e.density.valueOf():!1}canCastTo(e){return this.isNumeric&&e.isNumeric?!0:this.equals(e)}checkArray(e){return e.constructor===this.Array}toJSON(){return this.toString()}get usesBigInt(){return ae.BIG_INT_TYPES.some(e=>e.equals(this))}};m(g,"UNKNOWN",new g("unknown")),m(g,"FLOAT64",new g("float64")),m(g,"FLOAT32",new g("float32")),m(g,"INT64",new g("int64")),m(g,"INT32",new g("int32")),m(g,"INT16",new g("int16")),m(g,"INT8",new g("int8")),m(g,"UINT64",new g("uint64")),m(g,"UINT32",new g("uint32")),m(g,"UINT16",new g("uint16")),m(g,"UINT8",new g("uint8")),m(g,"BOOLEAN",g.UINT8),m(g,"TIMESTAMP",new g("timestamp")),m(g,"UUID",new g("uuid")),m(g,"STRING",new g("string")),m(g,"JSON",new g("json")),m(g,"ARRAY_CONSTRUCTORS",new Map([[g.UINT8.toString(),Uint8Array],[g.UINT16.toString(),Uint16Array],[g.UINT32.toString(),Uint32Array],[g.UINT64.toString(),BigUint64Array],[g.FLOAT32.toString(),Float32Array],[g.FLOAT64.toString(),Float64Array],[g.INT8.toString(),Int8Array],[g.INT16.toString(),Int16Array],[g.INT32.toString(),Int32Array],[g.INT64.toString(),BigInt64Array],[g.TIMESTAMP.toString(),BigInt64Array],[g.STRING.toString(),Uint8Array],[g.JSON.toString(),Uint8Array],[g.UUID.toString(),Uint8Array]])),m(g,"ARRAY_CONSTRUCTOR_DATA_TYPES",new Map([[Uint8Array.name,g.UINT8],[Uint16Array.name,g.UINT16],[Uint32Array.name,g.UINT32],[BigUint64Array.name,g.UINT64],[Float32Array.name,g.FLOAT32],[Float64Array.name,g.FLOAT64],[Int8Array.name,g.INT8],[Int16Array.name,g.INT16],[Int32Array.name,g.INT32],[BigInt64Array.name,g.INT64]])),m(g,"DENSITIES",new Map([[g.UINT8.toString(),J.BIT8],[g.UINT16.toString(),J.BIT16],[g.UINT32.toString(),J.BIT32],[g.UINT64.toString(),J.BIT64],[g.FLOAT32.toString(),J.BIT32],[g.FLOAT64.toString(),J.BIT64],[g.INT8.toString(),J.BIT8],[g.INT16.toString(),J.BIT16],[g.INT32.toString(),J.BIT32],[g.INT64.toString(),J.BIT64],[g.TIMESTAMP.toString(),J.BIT64],[g.STRING.toString(),J.UNKNOWN],[g.JSON.toString(),J.UNKNOWN],[g.UUID.toString(),J.BIT128]])),m(g,"ALL",[g.UNKNOWN,g.FLOAT64,g.FLOAT32,g.INT64,g.INT32,g.INT16,g.INT8,g.UINT64,g.UINT32,g.UINT16,g.UINT8,g.TIMESTAMP,g.UUID,g.STRING,g.JSON]),m(g,"BIG_INT_TYPES",[g.INT64,g.UINT64,g.TIMESTAMP]),m(g,"z",s.z.union([s.z.string().transform(r=>new g(r)),s.z.instanceof(g)]));let x=g;const G=class Z extends Number{constructor(e){super(e.valueOf())}largerThan(e){return this.valueOf()>e.valueOf()}smallerThan(e){return this.valueOf()<e.valueOf()}add(e){return Z.bytes(this.valueOf()+e.valueOf())}sub(e){return Z.bytes(this.valueOf()-e.valueOf())}truncate(e){return new Z(Math.trunc(this.valueOf()/e.valueOf())*e.valueOf())}remainder(e){return Z.bytes(this.valueOf()%e.valueOf())}get gigabytes(){return this.valueOf()/Z.GIGABYTE.valueOf()}get megabytes(){return this.valueOf()/Z.MEGABYTE.valueOf()}get kilobytes(){return this.valueOf()/Z.KILOBYTE.valueOf()}get terabytes(){return this.valueOf()/Z.TERABYTE.valueOf()}toString(){const e=this.truncate(Z.TERABYTE),t=this.truncate(Z.GIGABYTE),n=this.truncate(Z.MEGABYTE),i=this.truncate(Z.KILOBYTE),a=this.truncate(Z.BYTE),o=e,l=t.sub(e),u=n.sub(t),h=i.sub(n),y=a.sub(i);let d="";return o.isZero||(d+=`${o.terabytes}TB `),l.isZero||(d+=`${l.gigabytes}GB `),u.isZero||(d+=`${u.megabytes}MB `),h.isZero||(d+=`${h.kilobytes}KB `),(!y.isZero||d==="")&&(d+=`${y.valueOf()}B`),d.trim()}static bytes(e=1){return new Z(e)}static kilobytes(e=1){return Z.bytes(e.valueOf()*1e3)}static megabytes(e=1){return Z.kilobytes(e.valueOf()*1e3)}static gigabytes(e=1){return Z.megabytes(e.valueOf()*1e3)}static terabytes(e){return Z.gigabytes(e.valueOf()*1e3)}get isZero(){return this.valueOf()===0}};m(G,"BYTE",new G(1)),m(G,"KILOBYTE",G.kilobytes(1)),m(G,"MEGABYTE",G.megabytes(1)),m(G,"GIGABYTE",G.gigabytes(1)),m(G,"TERABYTE",G.terabytes(1)),m(G,"ZERO",new G(0)),m(G,"z",s.z.union([s.z.number().transform(r=>new G(r)),s.z.instanceof(G)]));let fn=G;s.z.union([s.z.instanceof(Uint8Array),s.z.instanceof(Uint16Array),s.z.instanceof(Uint32Array),s.z.instanceof(BigUint64Array),s.z.instanceof(Float32Array),s.z.instanceof(Float64Array),s.z.instanceof(Int8Array),s.z.instanceof(Int16Array),s.z.instanceof(Int32Array),s.z.instanceof(BigInt64Array)]);const ti=r=>{const e=typeof r;return e==="string"||e==="number"||e==="boolean"||e==="bigint"||r instanceof M||r instanceof D||r instanceof Date},ic=(r,e,t,n=0)=>r.usesBigInt&&!e.usesBigInt?Number(t)-Number(n):!r.usesBigInt&&e.usesBigInt?BigInt(t.valueOf())-BigInt(n.valueOf()):mt(t,-n).valueOf(),ac=r=>r==null?!1:Array.isArray(r)||r instanceof ArrayBuffer||ArrayBuffer.isView(r)&&!(r instanceof DataView)||r instanceof lc?!0:ti(r),be=-1,oc=s.z.string().transform(r=>new Uint8Array(atob(r).split("").map(e=>e.charCodeAt(0))).buffer),cc=s.z.union([s.z.null(),s.z.undefined()]).transform(()=>new Uint8Array().buffer),yn=10,pt=class oe{constructor(e){m(this,"key",""),m(this,"isSynnaxSeries",!0),m(this,"dataType"),m(this,"sampleOffset"),m(this,"gl"),m(this,"_data"),m(this,"_timeRange"),m(this,"alignment",0n),m(this,"_cachedMin"),m(this,"_cachedMax"),m(this,"writePos",be),m(this,"_refCount",0),m(this,"_cachedLength"),m(this,"_cachedIndexes"),ac(e)&&(e={data:e});const{dataType:t,timeRange:n,sampleOffset:i=0,glBufferUsage:a="static",alignment:o=0n,key:l=nc()}=e,u=e.data??[];if(u instanceof oe||typeof u=="object"&&"isSynnaxSeries"in u&&u.isSynnaxSeries===!0){const d=u;this.key=d.key,this.dataType=d.dataType,this.sampleOffset=d.sampleOffset,this.gl=d.gl,this._data=d._data,this._timeRange=d._timeRange,this.alignment=d.alignment,this._cachedMin=d._cachedMin,this._cachedMax=d._cachedMax,this.writePos=d.writePos,this._refCount=d._refCount,this._cachedLength=d._cachedLength;return}const h=ti(u),y=Array.isArray(u);if(t!=null)this.dataType=new x(t);else{if(u instanceof ArrayBuffer)throw new Error("cannot infer data type from an ArrayBuffer instance when constructing a Series. Please provide a data type.");if(y||h){let d=u;if(!h){if(u.length===0)throw new Error("cannot infer data type from a zero length JS array when constructing a Series. Please provide a data type.");d=u[0]}if(typeof d=="string")this.dataType=x.STRING;else if(typeof d=="number")this.dataType=x.FLOAT64;else if(typeof d=="bigint")this.dataType=x.INT64;else if(typeof d=="boolean")this.dataType=x.BOOLEAN;else if(d instanceof M||d instanceof Date||d instanceof M)this.dataType=x.TIMESTAMP;else if(typeof d=="object")this.dataType=x.JSON;else throw new Error(`cannot infer data type of ${typeof d} when constructing a Series from a JS array`)}else this.dataType=new x(u)}if(!y&&!h)this._data=u;else{let d=h?[u]:u;const j=d[0];(j instanceof M||j instanceof Date||j instanceof D)&&(d=d.map($=>new M($).valueOf())),this.dataType.equals(x.STRING)?(this._cachedLength=d.length,this._data=new TextEncoder().encode(`${d.join(`
4
4
  `)}
5
5
  `).buffer):this.dataType.equals(x.JSON)?(this._cachedLength=d.length,this._data=new TextEncoder().encode(`${d.map($=>tr.encodeString($)).join(`
6
6
  `)}
@@ -10,9 +10,9 @@
10
10
  `)}
11
11
  `);return new oe({data:n,dataType:x.JSON,timeRange:t})}acquire(e){this._refCount++,e!=null&&this.updateGLBuffer(e)}release(){if(this._refCount--,this._refCount===0&&this.gl.control!=null)this.maybeGarbageCollectGLBuffer(this.gl.control);else if(this._refCount<0)throw new Error("cannot release an array with a negative reference count")}write(e){if(!e.dataType.equals(this.dataType))throw new Error("buffer must be of the same type as this array");return this.dataType.isVariable?this.writeVariable(e):this.writeFixed(e)}writeVariable(e){if(this.writePos===be)return 0;const t=this.byteCapacity.valueOf()-this.writePos,n=e.subBytes(0,t);return this.writeToUnderlyingData(n),this.writePos+=n.byteLength.valueOf(),this._cachedLength!=null&&(this._cachedLength+=n.length,this.calculateCachedLength()),n.length}writeFixed(e){if(this.writePos===be)return 0;const t=this.capacity-this.writePos,n=e.sub(0,t);return this.writeToUnderlyingData(n),this._cachedLength=void 0,this.maybeRecomputeMinMax(n),this.writePos+=n.length,n.length}writeToUnderlyingData(e){this.underlyingData.set(e.data,this.writePos)}get buffer(){return typeof this._data=="object"&&"buffer"in this._data?this._data.buffer:this._data}get underlyingData(){return new this.dataType.Array(this._data)}get data(){return this.writePos===be?this.underlyingData:new this.dataType.Array(this._data,0,this.writePos)}toStrings(){if(!this.dataType.matches(x.STRING,x.UUID))throw new Error("cannot convert non-string series to strings");return new TextDecoder().decode(this.underlyingData).split(`
12
12
  `).slice(0,-1)}toUUIDs(){if(!this.dataType.equals(x.UUID))throw new Error("cannot convert non-uuid series to uuids");const e=x.UUID.density.valueOf(),t=Array(this.length);for(let n=0;n<this.length;n++){const i=this.underlyingData.slice(n*e,(n+1)*e),a=Array.from(new Uint8Array(i.buffer),o=>o.toString(16).padStart(2,"0")).join("").replace(/(.{8})(.{4})(.{4})(.{4})(.{12})/,"$1-$2-$3-$4-$5");t[n]=a}return t}parseJSON(e){if(!this.dataType.equals(x.JSON))throw new Error("cannot convert non-string series to strings");return new TextDecoder().decode(this.underlyingData).split(`
13
- `).slice(0,-1).map(t=>e.parse(tr.decodeString(t)))}get timeRange(){if(this._timeRange==null)throw new Error("time range not set on series");return this._timeRange}get byteCapacity(){return new fn(this.underlyingData.byteLength)}get capacity(){return this.dataType.isVariable?this.byteCapacity.valueOf():this.dataType.density.length(this.byteCapacity)}get byteLength(){return this.writePos===be?this.byteCapacity:this.dataType.isVariable?new fn(this.writePos):this.dataType.density.size(this.writePos)}get length(){return this._cachedLength!=null?this._cachedLength:this.dataType.isVariable?this.calculateCachedLength():this.writePos===be?this.data.length:this.writePos}calculateCachedLength(){if(!this.dataType.isVariable)throw new Error("cannot calculate length of a non-variable length data type");let e=0;const t=[0];return this.data.forEach((n,i)=>{n===yn&&(e++,t.push(i+1))}),this._cachedIndexes=t,this._cachedLength=e,e}convert(e,t=0){if(this.dataType.equals(e))return this;const n=new e.Array(this.length);for(let i=0;i<this.length;i++)n[i]=ic(this.dataType,e,this.data[i],t);return new oe({data:n.buffer,dataType:e,timeRange:this._timeRange,sampleOffset:t,glBufferUsage:this.gl.bufferUsage,alignment:this.alignment})}calcRawMax(){if(this.length===0)return-1/0;if(this.dataType.equals(x.TIMESTAMP))this._cachedMax=this.data[this.data.length-1];else if(this.dataType.usesBigInt){const e=this.data;this._cachedMax=e.reduce((t,n)=>t>n?t:n)}else{const e=this.data;this._cachedMax=e.reduce((t,n)=>t>n?t:n)}return this._cachedMax}get max(){if(this.dataType.isVariable)throw new Error("cannot calculate maximum on a variable length data type");return this.writePos===0?-1/0:(this._cachedMax??(this._cachedMax=this.calcRawMax()),mt(this._cachedMax,this.sampleOffset))}calcRawMin(){if(this.length===0)return 1/0;if(this.dataType.equals(x.TIMESTAMP))this._cachedMin=this.data[0];else if(this.dataType.usesBigInt){const e=this.data;this._cachedMin=e.reduce((t,n)=>t<n?t:n)}else{const e=this.data;this._cachedMin=e.reduce((t,n)=>t<n?t:n)}return this._cachedMin}get min(){if(this.dataType.isVariable)throw new Error("cannot calculate minimum on a variable length data type");return this.writePos===0?1/0:(this._cachedMin??(this._cachedMin=this.calcRawMin()),mt(this._cachedMin,this.sampleOffset))}get bounds(){return Ae(Number(this.min),Number(this.max))}maybeRecomputeMinMax(e){if(this._cachedMin!=null){const t=e._cachedMin??e.calcRawMin();t<this._cachedMin&&(this._cachedMin=t)}if(this._cachedMax!=null){const t=e._cachedMax??e.calcRawMax();t>this._cachedMax&&(this._cachedMax=t)}}enrich(){this.max,this.min}get range(){return mt(this.max,-this.min)}atAlignment(e,t){const n=Number(e-this.alignment);if(n<0||n>=this.length){if(t===!0)throw new Error(`[series] - no value at index ${n}`);return}return this.at(n,t)}at(e,t){if(this.dataType.isVariable)return this.atVariable(e,t??!1);e<0&&(e=this.length+e);const n=this.data[e];if(n==null){if(t===!0)throw new Error(`[series] - no value at index ${e}`);return}return mt(n,this.sampleOffset)}atVariable(e,t){let n=0,i=0;if(this._cachedIndexes!=null)n=this._cachedIndexes[e],i=this._cachedIndexes[e+1]-1;else{e<0&&(e=this.length+e);for(let o=0;o<this.data.length;o++)if(this.data[o]===yn){if(e===0){i=o;break}n=o+1,e--}if(i===0&&(i=this.data.length),n>=i||e>0){if(t)throw new Error(`[series] - no value at index ${e}`);return}}const a=this.data.slice(n,i);return this.dataType.equals(x.STRING)?new TextDecoder().decode(a):Ws(JSON.parse(new TextDecoder().decode(a)))}binarySearch(e){let t=0,n=this.length-1;const i=Jo(e);for(;t<=n;){const a=Math.floor((t+n)/2),o=i(this.at(a,!0),e);if(o===0)return a;o<0?t=a+1:n=a-1}return t}updateGLBuffer(e){if(this.gl.control=e,!this.dataType.equals(x.FLOAT32))throw new Error("Only FLOAT32 arrays can be used in WebGL");const{buffer:t,bufferUsage:n,prevBuffer:i}=this.gl;if(t==null&&(this.gl.buffer=e.createBuffer()),this.writePos!==i)if(e.bindBuffer(e.ARRAY_BUFFER,this.gl.buffer),this.writePos!==be){i===0&&e.bufferData(e.ARRAY_BUFFER,this.byteCapacity.valueOf(),e.STATIC_DRAW);const a=this.dataType.density.size(i).valueOf(),o=this.underlyingData.slice(this.gl.prevBuffer,this.writePos);e.bufferSubData(e.ARRAY_BUFFER,a,o.buffer),this.gl.prevBuffer=this.writePos}else e.bufferData(e.ARRAY_BUFFER,this.buffer,n==="static"?e.STATIC_DRAW:e.DYNAMIC_DRAW),this.gl.prevBuffer=be}as(e){if(e==="string"){if(!this.dataType.equals(x.STRING))throw new Error(`cannot convert series of type ${this.dataType.toString()} to string`);return this}if(e==="number"){if(!this.dataType.isNumeric)throw new Error(`cannot convert series of type ${this.dataType.toString()} to number`);return this}if(e==="bigint"){if(!this.dataType.equals(x.INT64))throw new Error(`cannot convert series of type ${this.dataType.toString()} to bigint`);return this}throw new Error(`cannot convert series to ${e}`)}get digest(){var e;return{key:this.key,dataType:this.dataType.toString(),sampleOffset:this.sampleOffset,alignment:{lower:cs(this.alignmentBounds.lower),upper:cs(this.alignmentBounds.upper)},timeRange:(e=this._timeRange)==null?void 0:e.toString(),length:this.length,capacity:this.capacity}}get memInfo(){return{key:this.key,length:this.length,byteLength:this.byteLength,glBuffer:this.gl.buffer!=null}}get alignmentBounds(){return Ae(this.alignment,this.alignment+BigInt(this.length))}maybeGarbageCollectGLBuffer(e){this.gl.buffer!=null&&(e.deleteBuffer(this.gl.buffer),this.gl.buffer=null,this.gl.prevBuffer=0,this.gl.control=null)}get glBuffer(){if(this.gl.buffer==null)throw new Error("gl buffer not initialized");return this.gl.prevBuffer!==this.writePos&&console.warn("buffer not updated"),this.gl.buffer}[Symbol.iterator](){if(this.dataType.isVariable){const e=new uc(this);return this.dataType.equals(x.JSON)?new hc(e):e}return new dc(this)}slice(e,t){return this.sliceSub(!1,e,t)}sub(e,t){return this.sliceSub(!0,e,t)}subIterator(e,t){return new ns(this,e,t??this.length)}subAlignmentIterator(e,t){return new ns(this,Number(e-this.alignment),Number(t-this.alignment))}subBytes(e,t){if(e>=0&&(t==null||t>=this.byteLength.valueOf()))return this;const n=this.data.subarray(e,t);return new oe({data:n,dataType:this.dataType,timeRange:this._timeRange,sampleOffset:this.sampleOffset,glBufferUsage:this.gl.bufferUsage,alignment:this.alignment+BigInt(e)})}sliceSub(e,t,n){if(t<=0&&(n==null||n>=this.length))return this;let i;return e?i=this.data.subarray(t,n):i=this.data.slice(t,n),new oe({data:i,dataType:this.dataType,timeRange:this._timeRange,sampleOffset:this.sampleOffset,glBufferUsage:this.gl.bufferUsage,alignment:this.alignment+BigInt(t)})}reAlign(e){return new oe({data:this.buffer,dataType:this.dataType,timeRange:$n.ZERO,sampleOffset:this.sampleOffset,glBufferUsage:"static",alignment:e})}};m(pt,"crudeZ",s.z.object({timeRange:$n.z.optional(),dataType:x.z,alignment:Xo.optional(),data:s.z.union([oc,cc,s.z.instanceof(ArrayBuffer),s.z.instanceof(Uint8Array)]),glBufferUsage:sc.optional().default("static").optional()})),m(pt,"z",pt.crudeZ.transform(r=>new pt(r)));let lc=pt;class ns{constructor(e,t,n){m(this,"series"),m(this,"end"),m(this,"index"),this.series=e;const i=Ae(0,e.length);this.end=Hn(i,n),this.index=Hn(i,t)}next(){return this.index>=this.end?{done:!0,value:void 0}:{done:!1,value:this.series.at(this.index++,!0)}}[Symbol.iterator](){return this}}class uc{constructor(e){if(m(this,"series"),m(this,"index"),m(this,"decoder"),!e.dataType.isVariable)throw new Error("cannot create a variable series iterator for a non-variable series");this.series=e,this.index=0,this.decoder=new TextDecoder}next(){const e=this.index,t=this.series.data;for(;this.index<t.length&&t[this.index]!==yn;)this.index++;const n=this.index;return e===n?{done:!0,value:void 0}:(this.index++,{done:!1,value:this.decoder.decode(this.series.buffer.slice(e,n))})}[Symbol.iterator](){return this}}var ss,is;class hc{constructor(e){m(this,"wrapped"),m(this,ss,"JSONSeriesIterator"),this.wrapped=e}next(){const e=this.wrapped.next();return e.done===!0?{done:!0,value:void 0}:{done:!1,value:tr.decodeString(e.value)}}[(is=Symbol.iterator,ss=Symbol.toStringTag,is)](){return this}}var as,os;class dc{constructor(e){m(this,"series"),m(this,"index"),m(this,as,"SeriesIterator"),this.series=e,this.index=0}next(){return this.index>=this.series.length?{done:!0,value:void 0}:{done:!1,value:this.series.at(this.index++,!0)}}[(os=Symbol.iterator,as=Symbol.toStringTag,os)](){return this}}const mt=(r,e)=>typeof r=="bigint"&&typeof e=="bigint"||typeof r=="number"&&typeof e=="number"?r+e:e===0?r:r===0?e:Number(r)+Number(e),cs=r=>{const e=r>>32n,t=r&0xffffffffn;return{domain:e,sample:t}};s.z.object({key:s.z.string(),value:s.z.string()});s.z.record(s.z.union([s.z.number(),s.z.string(),s.z.symbol()]),s.z.unknown());const ri=()=>typeof process<"u"&&process.versions!=null&&process.versions.node!=null?"node":typeof window>"u"||window.document===void 0?"webworker":"browser",fc=ri(),ni=["MacOS","Windows","Linux","Docker"],yc=s.z.enum(ni);let _r;const gc=()=>{if(typeof window>"u")return;const r=window.navigator.userAgent.toLowerCase();if(r.includes("mac"))return"MacOS";if(r.includes("win"))return"Windows";if(r.includes("linux"))return"Linux"},pc=(r={})=>{const{force:e,default:t}=r;return e??_r??(_r=gc(),_r??t)},si=Object.freeze(Object.defineProperty({__proto__:null,OPERATING_SYSTEMS:ni,RUNTIME:fc,detect:ri,getOS:pc,osZ:yc},Symbol.toStringTag,{value:"Module"}));var mc=Object.defineProperty,wc=(r,e,t)=>e in r?mc(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,wt=(r,e,t)=>wc(r,typeof e!="symbol"?e+"":e,t);const bc=(...r)=>r.map(ii).join(""),ii=r=>(r.endsWith("/")||(r+="/"),r.startsWith("/")&&(r=r.slice(1)),r),vc=r=>r.endsWith("/")?r.slice(0,-1):r,Tc=(r,e="")=>r===null?"":`?${Object.entries(r).filter(([,t])=>t==null?!1:Array.isArray(t)?t.length>0:!0).map(([t,n])=>`${e}${t}=${n}`).join("&")}`,gn=class pn{constructor({host:e,port:t,protocol:n="",pathPrefix:i=""}){wt(this,"protocol"),wt(this,"host"),wt(this,"port"),wt(this,"path"),this.protocol=n,this.host=e,this.port=t,this.path=ii(i)}replace(e){return new pn({host:e.host??this.host,port:e.port??this.port,protocol:e.protocol??this.protocol,pathPrefix:e.pathPrefix??this.path})}child(e){return new pn({...this,pathPrefix:bc(this.path,e)})}toString(){return vc(`${this.protocol}://${this.host}:${this.port}/${this.path}`)}};wt(gn,"UNKNOWN",new gn({host:"unknown",port:0}));let Oc=gn;var zc=Object.defineProperty,Ec=(r,e,t)=>e in r?zc(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,sr=(r,e,t)=>Ec(r,typeof e!="symbol"?e+"":e,t);const Me=class extends Number{};sr(Me,"Absolute",255),sr(Me,"Default",1),sr(Me,"z",s.z.union([s.z.instanceof(Me),s.z.number().int().min(0).max(255).transform(r=>new Me(r)),s.z.instanceof(Number).transform(r=>new Me(r))]));s.z.object({name:s.z.string(),key:s.z.string()});const ai=class bt extends Error{constructor(){super(bt.MESSAGE)}matches(e){return typeof e=="string"?e.includes(bt.MESSAGE):e instanceof bt||e.message.includes(bt.MESSAGE)}};sr(ai,"MESSAGE","canceled");let Nc=ai;new Nc;s.z.string().regex(/^\d+\.\d+\.\d+$/);const Sc=async r=>await new Promise(e=>setTimeout(e,D.fromMilliseconds(r).milliseconds)),Ic=s.z.object({interval:D.z.optional(),maxRetries:s.z.number().optional(),scale:s.z.number().optional()}),kc=(r={})=>{const e=r.sleepFn||Sc,t=r.maxRetries??5,n=r.scale??1;let i=0,a=new D(r.interval??D.milliseconds(1));return async()=>i>=t?!1:(await e(a),a=a.mult(n),i++,!0)},$c=Object.freeze(Object.defineProperty({__proto__:null,breakerConfig:Ic,create:kc},Symbol.toStringTag,{value:"Module"})),Q=r=>e=>e!=null&&typeof e=="object"&&"type"in e&&typeof e.type=="string"?e.type.includes(r):e instanceof Error?e.message.includes(r):typeof e!="string"?!1:e.includes(r);class se extends Error{constructor(){super(...arguments),k(this,"discriminator","FreighterError"),k(this,"type","")}}const Ac=r=>{if(r==null||typeof r!="object")return!1;const e=r;if(e.discriminator!=="FreighterError")return!1;if(!("type"in e))throw new Error(`Freighter error is missing its type property: ${JSON.stringify(e)}`);return!0},ls="unknown",us="nil",Rc="freighter",jt=s.z.object({type:s.z.string(),data:s.z.string()});class xc{constructor(){k(this,"providers",[])}register(e){this.providers.push(e)}encode(e){if(e==null)return{type:us,data:""};if(Ac(e))for(const t of this.providers){const n=t.encode(e);if(n!=null)return n}return{type:ls,data:JSON.stringify(e)}}decode(e){if(e==null||e.type===us)return null;if(e.type===ls)return new hs(e.data);for(const t of this.providers){const n=t.decode(e);if(n!=null)return n}return new hs(e.data)}}const oi=new xc,ci=({encode:r,decode:e})=>oi.register({encode:r,decode:e}),yr=r=>oi.decode(r);class hs extends se{constructor(){super(...arguments),k(this,"type","unknown")}}const Er="freighter.",ir=class li extends se{constructor(){super("EOF"),k(this,"type",li.TYPE)}};k(ir,"TYPE",`${Er}eof`),k(ir,"matches",Q(ir.TYPE));let Ne=ir;const ar=class ui extends se{constructor(){super("StreamClosed"),k(this,"type",ui.TYPE)}};k(ar,"TYPE",`${Er}stream_closed`),k(ar,"matches",Q(ar.TYPE));let rt=ar;const or=class hi extends se{constructor(e={}){const{message:t="Unreachable",url:n=Oc.UNKNOWN}=e;super(t),k(this,"type",hi.TYPE),k(this,"url"),this.url=n}};k(or,"TYPE",`${Er}unreachable`),k(or,"matches",Q(or.TYPE));let Se=or;const Cc=r=>{if(!r.type.startsWith(Rc))return null;if(Ne.matches(r))return{type:Ne.TYPE,data:"EOF"};if(rt.matches(r))return{type:rt.TYPE,data:"StreamClosed"};if(Se.matches(r))return{type:Se.TYPE,data:"Unreachable"};throw new Error(`Unknown error type: ${r.type}: ${r.message}`)},Pc=r=>{if(!r.type.startsWith(Er))return null;switch(r.type){case Ne.TYPE:return new Ne;case rt.TYPE:return new rt;case Se.TYPE:return new Se;default:throw new Error(`Unknown error type: ${r.data}`)}};ci({encode:Cc,decode:Pc});let di=class{constructor(){k(this,"middleware",[])}use(...e){this.middleware.push(...e)}async executeMiddleware(e,t){let n=0;const i=async a=>{if(n===this.middleware.length)return await t(a);const o=this.middleware[n];return n++,await o(a,i)};return await i(e)}};const fi="Content-Type",ds=r=>{if(si.RUNTIME!=="node")return fetch;const e=require("node-fetch");if(r==="http")return e;const t=require("https"),n=new t.Agent({rejectUnauthorized:!1});return async(i,a)=>await e(i,{...a,agent:n})};class Dc extends di{constructor(e,t,n=!1){return super(),k(this,"endpoint"),k(this,"encoder"),k(this,"fetch"),this.endpoint=e.replace({protocol:n?"https":"http"}),this.encoder=t,this.fetch=ds(this.endpoint.protocol),new Proxy(this,{get:(i,a,o)=>a==="endpoint"?this.endpoint:Reflect.get(i,a,o)})}get headers(){return{[fi]:this.encoder.contentType}}async send(e,t,n,i){t=n==null?void 0:n.parse(t);let a=null;const o=this.endpoint.child(e),l={};l.method="POST",l.body=this.encoder.encode(t??{});const[,u]=await this.executeMiddleware({target:o.toString(),protocol:this.endpoint.protocol,params:{},role:"client"},async h=>{const y={...h,params:{}};l.headers={...this.headers,...h.params};let d;try{d=await ds(h.protocol)(h.target,l)}catch($){let te=$;return te.message==="Load failed"&&(te=new Se({url:o})),[y,te]}const j=await d.arrayBuffer();if(d!=null&&d.ok)return i!=null&&(a=this.encoder.decode(j,i)),[y,null];try{if(d.status!==400)return[y,new Error(d.statusText)];const $=this.encoder.decode(j,jt),te=yr($);return[y,te]}catch($){return[y,new Error(`[freighter] - failed to decode error: ${d.statusText}: ${$.message}`)]}});return[a,u]}}const jc=(r,e)=>{class t{constructor(i){k(this,"wrapped"),this.wrapped=i}use(...i){this.wrapped.use(...i)}async send(i,a,o,l){const u=$c.create(e);do{const[h,y]=await this.wrapped.send(i,a,o,l);if(y==null||!Se.matches(y))return[h,y];if(!await u())return[h,y]}while(!0)}}return new t(r)},w=async(r,e,t,n,i)=>{const[a,o]=await r.send(e,t,n,i);if(o!=null)throw o;return a},Mc=()=>si.RUNTIME!=="node"?r=>new WebSocket(r):r=>new(require("ws")).WebSocket(r,{rejectUnauthorized:!1}),Bc=s.z.object({type:s.z.union([s.z.literal("data"),s.z.literal("close"),s.z.literal("open")]),payload:s.z.unknown().optional(),error:s.z.optional(jt)});class Uc{constructor(e,t,n,i){k(this,"encoder"),k(this,"reqSchema"),k(this,"resSchema"),k(this,"ws"),k(this,"serverClosed"),k(this,"sendClosed"),k(this,"receiveDataQueue",[]),k(this,"receiveCallbacksQueue",[]),this.encoder=t,this.reqSchema=n,this.resSchema=i,this.ws=e,this.sendClosed=!1,this.serverClosed=null,this.listenForMessages()}async receiveOpenAck(){const e=await this.receiveMsg();if(e.type!=="open"){if(e.error==null)throw new Error("Message error must be defined");return yr(e.error)}return null}send(e){if(this.serverClosed!=null)return new Ne;if(this.sendClosed)throw new rt;return this.ws.send(this.encoder.encode({type:"data",payload:e})),null}async receive(){if(this.serverClosed!=null)return[null,this.serverClosed];const e=await this.receiveMsg();if(e.type==="close"){if(e.error==null)throw new Error("Message error must be defined");return this.serverClosed=yr(e.error),[null,this.serverClosed]}return[this.resSchema.parse(e.payload),null]}received(){return this.receiveDataQueue.length!==0}closeSend(){if(this.sendClosed||this.serverClosed!=null)return;const e={type:"close"};try{this.ws.send(this.encoder.encode(e))}finally{this.sendClosed=!0}}async receiveMsg(){return this.receiveDataQueue.shift()??await new Promise((t,n)=>this.receiveCallbacksQueue.push({resolve:t,reject:n}))}addMessage(e){const t=this.receiveCallbacksQueue.shift();t!=null?t.resolve(e):this.receiveDataQueue.push(e)}listenForMessages(){this.ws.onmessage=e=>this.addMessage(this.encoder.decode(e.data,Bc)),this.ws.onclose=e=>this.addMessage({type:"close",error:{type:qc(e)?Ne.TYPE:rt.TYPE,data:""}})}}const Zc="freighterctx",Lc=1e3,_c=1001,Yc=[Lc,_c],qc=r=>Yc.includes(r.code),yi=class gi extends di{constructor(e,t,n=!1){super(),k(this,"baseUrl"),k(this,"encoder"),this.baseUrl=e.replace({protocol:n?"wss":"ws"}),this.encoder=t}async stream(e,t,n){const i=Mc();let a;const[,o]=await this.executeMiddleware({target:e,protocol:"websocket",params:{},role:"client"},async l=>{const u=i(this.buildURL(e,l)),h={...l,params:{}};u.binaryType=gi.MESSAGE_TYPE;const y=await this.wrapSocket(u,t,n);return y instanceof Error?[h,y]:(a=y,[h,null])});if(o!=null)throw o;return a}buildURL(e,t){const n=Tc({[fi]:this.encoder.contentType,...t.params},Zc);return this.baseUrl.child(e).toString()+n}async wrapSocket(e,t,n){return await new Promise(i=>{e.onopen=()=>{const a=new Uc(e,this.encoder,t,n);a.receiveOpenAck().then(o=>{o!=null?i(o):i(a)}).catch(o=>i(o))},e.onerror=a=>{const o=a;i(new Error(o.message))}})}};k(yi,"MESSAGE_TYPE","arraybuffer");let Wc=yi;const gr=s.z.union([s.z.literal("all"),s.z.literal("create"),s.z.literal("delete"),s.z.literal("retrieve"),s.z.literal("update")]),Gc="all",Vc="create",Fc="delete",Jc="retrieve",Kc="update",Hc=r=>{const e=r.replace(/_[a-z]/g,t=>t[1].toUpperCase());return e.length>1&&e[0]===e[0].toUpperCase()&&e[1]===e[1].toUpperCase()||e.length===0?e:e[0].toLowerCase()+e.slice(1)},pi=r=>{const e=(t,n=mn)=>{if(typeof t=="string")return r(t);if(Array.isArray(t))return t.map(o=>e(o,n));if(!Yr(t))return t;n=el(n);const i={},a=t;return Object.keys(a).forEach(o=>{let l=a[o];const u=r(o);n.recursive&&(Yr(l)?ys(l,n.keepTypesOnRecursion)||(l=e(l,n)):n.recursiveInArray&&fs(l)&&(l=[...l].map(h=>{let y=h;return Yr(h)?ys(y,n.keepTypesOnRecursion)||(y=e(h,n)):fs(h)&&(y=e({key:h},n).key),y}))),i[u]=l}),i};return e},mi=pi(Hc),Xc=r=>r.replace(/([a-z0-9])([A-Z])/g,(e,t,n)=>`${t}_${n.toLowerCase()}`),Qc=pi(Xc),mn={recursive:!0,recursiveInArray:!0,keepTypesOnRecursion:[Number,String,Uint8Array]},el=(r=mn)=>(r.recursive==null?r=mn:r.recursiveInArray??(r.recursiveInArray=!1),r),fs=r=>r!=null&&Array.isArray(r),Yr=r=>r!=null&&typeof r=="object"&&!Array.isArray(r),ys=(r,e)=>(e||[]).some(t=>r instanceof t),An=r=>r!=null&&typeof r=="object"&&!Array.isArray(r);var tl=Object.defineProperty,rl=(r,e,t)=>e in r?tl(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,It=(r,e,t)=>rl(r,typeof e!="symbol"?e+"":e,t);let wi=class{constructor(){It(this,"contentType","application/json"),It(this,"decoder"),It(this,"encoder"),this.decoder=new TextDecoder,this.encoder=new TextEncoder}encode(e){return this.encoder.encode(this.encodeString(e)).buffer}decode(e,t){return this.decodeString(this.decoder.decode(e),t)}decodeString(e,t){const n=JSON.parse(e),i=mi(n);return t!=null?t.parse(i):i}encodeString(e){const t=Qc(e);return JSON.stringify(t,(n,i)=>ArrayBuffer.isView(i)?Array.from(i):An(i)&&"encode_value"in i?typeof i.value=="bigint"?i.value.toString():i.value:typeof i=="bigint"?i.toString():i)}static registerCustomType(){}},bi=class{constructor(){It(this,"contentType","text/csv")}encode(e){const t=this.encodeString(e);return new TextEncoder().encode(t).buffer}decode(e,t){const n=new TextDecoder().decode(e);return this.decodeString(n,t)}encodeString(e){if(!Array.isArray(e)||e.length===0||!An(e[0]))throw new Error("Payload must be an array of objects");const t=Object.keys(e[0]),n=[t.join(",")];return e.forEach(i=>{const a=t.map(o=>JSON.stringify(i[o]??""));n.push(a.join(","))}),n.join(`
13
+ `).slice(0,-1).map(t=>e.parse(tr.decodeString(t)))}get timeRange(){if(this._timeRange==null)throw new Error("time range not set on series");return this._timeRange}get byteCapacity(){return new fn(this.underlyingData.byteLength)}get capacity(){return this.dataType.isVariable?this.byteCapacity.valueOf():this.dataType.density.length(this.byteCapacity)}get byteLength(){return this.writePos===be?this.byteCapacity:this.dataType.isVariable?new fn(this.writePos):this.dataType.density.size(this.writePos)}get length(){return this._cachedLength!=null?this._cachedLength:this.dataType.isVariable?this.calculateCachedLength():this.writePos===be?this.data.length:this.writePos}calculateCachedLength(){if(!this.dataType.isVariable)throw new Error("cannot calculate length of a non-variable length data type");let e=0;const t=[0];return this.data.forEach((n,i)=>{n===yn&&(e++,t.push(i+1))}),this._cachedIndexes=t,this._cachedLength=e,e}convert(e,t=0){if(this.dataType.equals(e))return this;const n=new e.Array(this.length);for(let i=0;i<this.length;i++)n[i]=ic(this.dataType,e,this.data[i],t);return new oe({data:n.buffer,dataType:e,timeRange:this._timeRange,sampleOffset:t,glBufferUsage:this.gl.bufferUsage,alignment:this.alignment})}calcRawMax(){if(this.length===0)return-1/0;if(this.dataType.equals(x.TIMESTAMP))this._cachedMax=this.data[this.data.length-1];else if(this.dataType.usesBigInt){const e=this.data;this._cachedMax=e.reduce((t,n)=>t>n?t:n)}else{const e=this.data;this._cachedMax=e.reduce((t,n)=>t>n?t:n)}return this._cachedMax}get max(){if(this.dataType.isVariable)throw new Error("cannot calculate maximum on a variable length data type");return this.writePos===0?-1/0:(this._cachedMax??(this._cachedMax=this.calcRawMax()),mt(this._cachedMax,this.sampleOffset))}calcRawMin(){if(this.length===0)return 1/0;if(this.dataType.equals(x.TIMESTAMP))this._cachedMin=this.data[0];else if(this.dataType.usesBigInt){const e=this.data;this._cachedMin=e.reduce((t,n)=>t<n?t:n)}else{const e=this.data;this._cachedMin=e.reduce((t,n)=>t<n?t:n)}return this._cachedMin}get min(){if(this.dataType.isVariable)throw new Error("cannot calculate minimum on a variable length data type");return this.writePos===0?1/0:(this._cachedMin??(this._cachedMin=this.calcRawMin()),mt(this._cachedMin,this.sampleOffset))}get bounds(){return Ae(Number(this.min),Number(this.max))}maybeRecomputeMinMax(e){if(this._cachedMin!=null){const t=e._cachedMin??e.calcRawMin();t<this._cachedMin&&(this._cachedMin=t)}if(this._cachedMax!=null){const t=e._cachedMax??e.calcRawMax();t>this._cachedMax&&(this._cachedMax=t)}}enrich(){this.max,this.min}get range(){return mt(this.max,-this.min)}atAlignment(e,t){const n=Number(e-this.alignment);if(n<0||n>=this.length){if(t===!0)throw new Error(`[series] - no value at index ${n}`);return}return this.at(n,t)}at(e,t){if(this.dataType.isVariable)return this.atVariable(e,t??!1);e<0&&(e=this.length+e);const n=this.data[e];if(n==null){if(t===!0)throw new Error(`[series] - no value at index ${e}`);return}return mt(n,this.sampleOffset)}atVariable(e,t){let n=0,i=0;if(this._cachedIndexes!=null)n=this._cachedIndexes[e],i=this._cachedIndexes[e+1]-1;else{e<0&&(e=this.length+e);for(let o=0;o<this.data.length;o++)if(this.data[o]===yn){if(e===0){i=o;break}n=o+1,e--}if(i===0&&(i=this.data.length),n>=i||e>0){if(t)throw new Error(`[series] - no value at index ${e}`);return}}const a=this.data.slice(n,i);return this.dataType.equals(x.STRING)?new TextDecoder().decode(a):Ws(JSON.parse(new TextDecoder().decode(a)))}binarySearch(e){let t=0,n=this.length-1;const i=Oo(e);for(;t<=n;){const a=Math.floor((t+n)/2),o=i(this.at(a,!0),e);if(o===0)return a;o<0?t=a+1:n=a-1}return t}updateGLBuffer(e){if(this.gl.control=e,!this.dataType.equals(x.FLOAT32))throw new Error("Only FLOAT32 arrays can be used in WebGL");const{buffer:t,bufferUsage:n,prevBuffer:i}=this.gl;if(t==null&&(this.gl.buffer=e.createBuffer()),this.writePos!==i)if(e.bindBuffer(e.ARRAY_BUFFER,this.gl.buffer),this.writePos!==be){i===0&&e.bufferData(e.ARRAY_BUFFER,this.byteCapacity.valueOf(),e.STATIC_DRAW);const a=this.dataType.density.size(i).valueOf(),o=this.underlyingData.slice(this.gl.prevBuffer,this.writePos);e.bufferSubData(e.ARRAY_BUFFER,a,o.buffer),this.gl.prevBuffer=this.writePos}else e.bufferData(e.ARRAY_BUFFER,this.buffer,n==="static"?e.STATIC_DRAW:e.DYNAMIC_DRAW),this.gl.prevBuffer=be}as(e){if(e==="string"){if(!this.dataType.equals(x.STRING))throw new Error(`cannot convert series of type ${this.dataType.toString()} to string`);return this}if(e==="number"){if(!this.dataType.isNumeric)throw new Error(`cannot convert series of type ${this.dataType.toString()} to number`);return this}if(e==="bigint"){if(!this.dataType.equals(x.INT64))throw new Error(`cannot convert series of type ${this.dataType.toString()} to bigint`);return this}throw new Error(`cannot convert series to ${e}`)}get digest(){var e;return{key:this.key,dataType:this.dataType.toString(),sampleOffset:this.sampleOffset,alignment:{lower:cs(this.alignmentBounds.lower),upper:cs(this.alignmentBounds.upper)},timeRange:(e=this._timeRange)==null?void 0:e.toString(),length:this.length,capacity:this.capacity}}get memInfo(){return{key:this.key,length:this.length,byteLength:this.byteLength,glBuffer:this.gl.buffer!=null}}get alignmentBounds(){return Ae(this.alignment,this.alignment+BigInt(this.length))}maybeGarbageCollectGLBuffer(e){this.gl.buffer!=null&&(e.deleteBuffer(this.gl.buffer),this.gl.buffer=null,this.gl.prevBuffer=0,this.gl.control=null)}get glBuffer(){if(this.gl.buffer==null)throw new Error("gl buffer not initialized");return this.gl.prevBuffer!==this.writePos&&console.warn("buffer not updated"),this.gl.buffer}[Symbol.iterator](){if(this.dataType.isVariable){const e=new uc(this);return this.dataType.equals(x.JSON)?new hc(e):e}return new dc(this)}slice(e,t){return this.sliceSub(!1,e,t)}sub(e,t){return this.sliceSub(!0,e,t)}subIterator(e,t){return new ns(this,e,t??this.length)}subAlignmentIterator(e,t){return new ns(this,Number(e-this.alignment),Number(t-this.alignment))}subBytes(e,t){if(e>=0&&(t==null||t>=this.byteLength.valueOf()))return this;const n=this.data.subarray(e,t);return new oe({data:n,dataType:this.dataType,timeRange:this._timeRange,sampleOffset:this.sampleOffset,glBufferUsage:this.gl.bufferUsage,alignment:this.alignment+BigInt(e)})}sliceSub(e,t,n){if(t<=0&&(n==null||n>=this.length))return this;let i;return e?i=this.data.subarray(t,n):i=this.data.slice(t,n),new oe({data:i,dataType:this.dataType,timeRange:this._timeRange,sampleOffset:this.sampleOffset,glBufferUsage:this.gl.bufferUsage,alignment:this.alignment+BigInt(t)})}reAlign(e){return new oe({data:this.buffer,dataType:this.dataType,timeRange:$n.ZERO,sampleOffset:this.sampleOffset,glBufferUsage:"static",alignment:e})}};m(pt,"crudeZ",s.z.object({timeRange:$n.z.optional(),dataType:x.z,alignment:Xo.optional(),data:s.z.union([oc,cc,s.z.instanceof(ArrayBuffer),s.z.instanceof(Uint8Array)]),glBufferUsage:sc.optional().default("static").optional()})),m(pt,"z",pt.crudeZ.transform(r=>new pt(r)));let lc=pt;class ns{constructor(e,t,n){m(this,"series"),m(this,"end"),m(this,"index"),this.series=e;const i=Ae(0,e.length);this.end=Hn(i,n),this.index=Hn(i,t)}next(){return this.index>=this.end?{done:!0,value:void 0}:{done:!1,value:this.series.at(this.index++,!0)}}[Symbol.iterator](){return this}}class uc{constructor(e){if(m(this,"series"),m(this,"index"),m(this,"decoder"),!e.dataType.isVariable)throw new Error("cannot create a variable series iterator for a non-variable series");this.series=e,this.index=0,this.decoder=new TextDecoder}next(){const e=this.index,t=this.series.data;for(;this.index<t.length&&t[this.index]!==yn;)this.index++;const n=this.index;return e===n?{done:!0,value:void 0}:(this.index++,{done:!1,value:this.decoder.decode(this.series.buffer.slice(e,n))})}[Symbol.iterator](){return this}}var ss,is;class hc{constructor(e){m(this,"wrapped"),m(this,ss,"JSONSeriesIterator"),this.wrapped=e}next(){const e=this.wrapped.next();return e.done===!0?{done:!0,value:void 0}:{done:!1,value:tr.decodeString(e.value)}}[(is=Symbol.iterator,ss=Symbol.toStringTag,is)](){return this}}var as,os;class dc{constructor(e){m(this,"series"),m(this,"index"),m(this,as,"SeriesIterator"),this.series=e,this.index=0}next(){return this.index>=this.series.length?{done:!0,value:void 0}:{done:!1,value:this.series.at(this.index++,!0)}}[(os=Symbol.iterator,as=Symbol.toStringTag,os)](){return this}}const mt=(r,e)=>typeof r=="bigint"&&typeof e=="bigint"||typeof r=="number"&&typeof e=="number"?r+e:e===0?r:r===0?e:Number(r)+Number(e),cs=r=>{const e=r>>32n,t=r&0xffffffffn;return{domain:e,sample:t}};s.z.object({key:s.z.string(),value:s.z.string()});s.z.record(s.z.union([s.z.number(),s.z.string(),s.z.symbol()]),s.z.unknown());const ri=()=>typeof process<"u"&&process.versions!=null&&process.versions.node!=null?"node":typeof window>"u"||window.document===void 0?"webworker":"browser",fc=ri(),ni=["MacOS","Windows","Linux","Docker"],yc=["macos","windows","linux","docker"],gc={macos:"MacOS",windows:"Windows",linux:"Linux",docker:"Docker"},pc=s.z.enum(ni).or(s.z.enum(yc).transform(r=>gc[r]));let _r;const mc=()=>{if(typeof window>"u")return;const r=window.navigator.userAgent.toLowerCase();if(r.includes("mac"))return"MacOS";if(r.includes("win"))return"Windows";if(r.includes("linux"))return"Linux"},wc=(r={})=>{const{force:e,default:t}=r;return e??_r??(_r=mc(),_r??t)},si=Object.freeze(Object.defineProperty({__proto__:null,OPERATING_SYSTEMS:ni,RUNTIME:fc,detect:ri,getOS:wc,osZ:pc},Symbol.toStringTag,{value:"Module"}));var bc=Object.defineProperty,vc=(r,e,t)=>e in r?bc(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,wt=(r,e,t)=>vc(r,typeof e!="symbol"?e+"":e,t);const Tc=(...r)=>r.map(ii).join(""),ii=r=>(r.endsWith("/")||(r+="/"),r.startsWith("/")&&(r=r.slice(1)),r),Oc=r=>r.endsWith("/")?r.slice(0,-1):r,zc=(r,e="")=>r===null?"":`?${Object.entries(r).filter(([,t])=>t==null?!1:Array.isArray(t)?t.length>0:!0).map(([t,n])=>`${e}${t}=${n}`).join("&")}`,gn=class pn{constructor({host:e,port:t,protocol:n="",pathPrefix:i=""}){wt(this,"protocol"),wt(this,"host"),wt(this,"port"),wt(this,"path"),this.protocol=n,this.host=e,this.port=t,this.path=ii(i)}replace(e){return new pn({host:e.host??this.host,port:e.port??this.port,protocol:e.protocol??this.protocol,pathPrefix:e.pathPrefix??this.path})}child(e){return new pn({...this,pathPrefix:Tc(this.path,e)})}toString(){return Oc(`${this.protocol}://${this.host}:${this.port}/${this.path}`)}};wt(gn,"UNKNOWN",new gn({host:"unknown",port:0}));let Ec=gn;var Nc=Object.defineProperty,Sc=(r,e,t)=>e in r?Nc(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,sr=(r,e,t)=>Sc(r,typeof e!="symbol"?e+"":e,t);const Ic=async r=>await new Promise(e=>setTimeout(e,D.fromMilliseconds(r).milliseconds)),kc=s.z.object({interval:D.z.optional(),maxRetries:s.z.number().optional(),scale:s.z.number().optional()}),$c=(r={})=>{const e=r.sleepFn||Ic,t=r.maxRetries??5,n=r.scale??1;let i=0,a=new D(r.interval??D.milliseconds(1));return async()=>i>=t?!1:(await e(a),a=a.mult(n),i++,!0)},Ac=Object.freeze(Object.defineProperty({__proto__:null,breakerConfig:kc,create:$c},Symbol.toStringTag,{value:"Module"})),Me=class extends Number{};sr(Me,"Absolute",255),sr(Me,"Default",1),sr(Me,"z",s.z.union([s.z.instanceof(Me),s.z.number().int().min(0).max(255).transform(r=>new Me(r)),s.z.instanceof(Number).transform(r=>new Me(r))]));s.z.object({name:s.z.string(),key:s.z.string()});const ai=class bt extends Error{constructor(){super(bt.MESSAGE)}matches(e){return typeof e=="string"?e.includes(bt.MESSAGE):e instanceof bt||e.message.includes(bt.MESSAGE)}};sr(ai,"MESSAGE","canceled");let Rc=ai;new Rc;s.z.string().regex(/^\d+\.\d+\.\d+$/);const Q=r=>e=>e!=null&&typeof e=="object"&&"type"in e&&typeof e.type=="string"?e.type.includes(r):e instanceof Error?e.message.includes(r):typeof e!="string"?!1:e.includes(r);class se extends Error{constructor(){super(...arguments),k(this,"discriminator","FreighterError"),k(this,"type","")}}const xc=r=>{if(r==null||typeof r!="object")return!1;const e=r;if(e.discriminator!=="FreighterError")return!1;if(!("type"in e))throw new Error(`Freighter error is missing its type property: ${JSON.stringify(e)}`);return!0},ls="unknown",us="nil",Cc="freighter",jt=s.z.object({type:s.z.string(),data:s.z.string()});class Pc{constructor(){k(this,"providers",[])}register(e){this.providers.push(e)}encode(e){if(e==null)return{type:us,data:""};if(xc(e))for(const t of this.providers){const n=t.encode(e);if(n!=null)return n}return{type:ls,data:JSON.stringify(e)}}decode(e){if(e==null||e.type===us)return null;if(e.type===ls)return new hs(e.data);for(const t of this.providers){const n=t.decode(e);if(n!=null)return n}return new hs(e.data)}}const oi=new Pc,ci=({encode:r,decode:e})=>oi.register({encode:r,decode:e}),yr=r=>oi.decode(r);class hs extends se{constructor(){super(...arguments),k(this,"type","unknown")}}const Er="freighter.",ir=class li extends se{constructor(){super("EOF"),k(this,"type",li.TYPE)}};k(ir,"TYPE",`${Er}eof`),k(ir,"matches",Q(ir.TYPE));let Ne=ir;const ar=class ui extends se{constructor(){super("StreamClosed"),k(this,"type",ui.TYPE)}};k(ar,"TYPE",`${Er}stream_closed`),k(ar,"matches",Q(ar.TYPE));let rt=ar;const or=class hi extends se{constructor(e={}){const{message:t="Unreachable",url:n=Ec.UNKNOWN}=e;super(t),k(this,"type",hi.TYPE),k(this,"url"),this.url=n}};k(or,"TYPE",`${Er}unreachable`),k(or,"matches",Q(or.TYPE));let Se=or;const Dc=r=>{if(!r.type.startsWith(Cc))return null;if(Ne.matches(r))return{type:Ne.TYPE,data:"EOF"};if(rt.matches(r))return{type:rt.TYPE,data:"StreamClosed"};if(Se.matches(r))return{type:Se.TYPE,data:"Unreachable"};throw new Error(`Unknown error type: ${r.type}: ${r.message}`)},jc=r=>{if(!r.type.startsWith(Er))return null;switch(r.type){case Ne.TYPE:return new Ne;case rt.TYPE:return new rt;case Se.TYPE:return new Se;default:throw new Error(`Unknown error type: ${r.data}`)}};ci({encode:Dc,decode:jc});let di=class{constructor(){k(this,"middleware",[])}use(...e){this.middleware.push(...e)}async executeMiddleware(e,t){let n=0;const i=async a=>{if(n===this.middleware.length)return await t(a);const o=this.middleware[n];return n++,await o(a,i)};return await i(e)}};const fi="Content-Type",ds=r=>{if(si.RUNTIME!=="node")return fetch;const e=require("node-fetch");if(r==="http")return e;const t=require("https"),n=new t.Agent({rejectUnauthorized:!1});return async(i,a)=>await e(i,{...a,agent:n})};class Mc extends di{constructor(e,t,n=!1){return super(),k(this,"endpoint"),k(this,"encoder"),k(this,"fetch"),this.endpoint=e.replace({protocol:n?"https":"http"}),this.encoder=t,this.fetch=ds(this.endpoint.protocol),new Proxy(this,{get:(i,a,o)=>a==="endpoint"?this.endpoint:Reflect.get(i,a,o)})}get headers(){return{[fi]:this.encoder.contentType}}async send(e,t,n,i){t=n==null?void 0:n.parse(t);let a=null;const o=this.endpoint.child(e),l={};l.method="POST",l.body=this.encoder.encode(t??{});const[,u]=await this.executeMiddleware({target:o.toString(),protocol:this.endpoint.protocol,params:{},role:"client"},async h=>{const y={...h,params:{}};l.headers={...this.headers,...h.params};let d;try{d=await ds(h.protocol)(h.target,l)}catch($){let te=$;return te.message==="Load failed"&&(te=new Se({url:o})),[y,te]}const j=await d.arrayBuffer();if(d!=null&&d.ok)return i!=null&&(a=this.encoder.decode(j,i)),[y,null];try{if(d.status!==400)return[y,new Error(d.statusText)];const $=this.encoder.decode(j,jt),te=yr($);return[y,te]}catch($){return[y,new Error(`[freighter] - failed to decode error: ${d.statusText}: ${$.message}`)]}});return[a,u]}}const Bc=(r,e)=>{class t{constructor(i){k(this,"wrapped"),this.wrapped=i}use(...i){this.wrapped.use(...i)}async send(i,a,o,l){const u=Ac.create(e);do{const[h,y]=await this.wrapped.send(i,a,o,l);if(y==null||!Se.matches(y))return[h,y];if(!await u())return[h,y]}while(!0)}}return new t(r)},w=async(r,e,t,n,i)=>{const[a,o]=await r.send(e,t,n,i);if(o!=null)throw o;return a},Uc=()=>si.RUNTIME!=="node"?r=>new WebSocket(r):r=>new(require("ws")).WebSocket(r,{rejectUnauthorized:!1}),Zc=s.z.object({type:s.z.union([s.z.literal("data"),s.z.literal("close"),s.z.literal("open")]),payload:s.z.unknown().optional(),error:s.z.optional(jt)});class Lc{constructor(e,t,n,i){k(this,"encoder"),k(this,"reqSchema"),k(this,"resSchema"),k(this,"ws"),k(this,"serverClosed"),k(this,"sendClosed"),k(this,"receiveDataQueue",[]),k(this,"receiveCallbacksQueue",[]),this.encoder=t,this.reqSchema=n,this.resSchema=i,this.ws=e,this.sendClosed=!1,this.serverClosed=null,this.listenForMessages()}async receiveOpenAck(){const e=await this.receiveMsg();if(e.type!=="open"){if(e.error==null)throw new Error("Message error must be defined");return yr(e.error)}return null}send(e){if(this.serverClosed!=null)return new Ne;if(this.sendClosed)throw new rt;return this.ws.send(this.encoder.encode({type:"data",payload:e})),null}async receive(){if(this.serverClosed!=null)return[null,this.serverClosed];const e=await this.receiveMsg();if(e.type==="close"){if(e.error==null)throw new Error("Message error must be defined");return this.serverClosed=yr(e.error),[null,this.serverClosed]}return[this.resSchema.parse(e.payload),null]}received(){return this.receiveDataQueue.length!==0}closeSend(){if(this.sendClosed||this.serverClosed!=null)return;const e={type:"close"};try{this.ws.send(this.encoder.encode(e))}finally{this.sendClosed=!0}}async receiveMsg(){return this.receiveDataQueue.shift()??await new Promise((t,n)=>this.receiveCallbacksQueue.push({resolve:t,reject:n}))}addMessage(e){const t=this.receiveCallbacksQueue.shift();t!=null?t.resolve(e):this.receiveDataQueue.push(e)}listenForMessages(){this.ws.onmessage=e=>this.addMessage(this.encoder.decode(e.data,Zc)),this.ws.onclose=e=>this.addMessage({type:"close",error:{type:Gc(e)?Ne.TYPE:rt.TYPE,data:""}})}}const _c="freighterctx",Yc=1e3,qc=1001,Wc=[Yc,qc],Gc=r=>Wc.includes(r.code),yi=class gi extends di{constructor(e,t,n=!1){super(),k(this,"baseUrl"),k(this,"encoder"),this.baseUrl=e.replace({protocol:n?"wss":"ws"}),this.encoder=t}async stream(e,t,n){const i=Uc();let a;const[,o]=await this.executeMiddleware({target:e,protocol:"websocket",params:{},role:"client"},async l=>{const u=i(this.buildURL(e,l)),h={...l,params:{}};u.binaryType=gi.MESSAGE_TYPE;const y=await this.wrapSocket(u,t,n);return y instanceof Error?[h,y]:(a=y,[h,null])});if(o!=null)throw o;return a}buildURL(e,t){const n=zc({[fi]:this.encoder.contentType,...t.params},_c);return this.baseUrl.child(e).toString()+n}async wrapSocket(e,t,n){return await new Promise(i=>{e.onopen=()=>{const a=new Lc(e,this.encoder,t,n);a.receiveOpenAck().then(o=>{o!=null?i(o):i(a)}).catch(o=>i(o))},e.onerror=a=>{const o=a;i(new Error(o.message))}})}};k(yi,"MESSAGE_TYPE","arraybuffer");let Vc=yi;const gr=s.z.union([s.z.literal("all"),s.z.literal("create"),s.z.literal("delete"),s.z.literal("retrieve"),s.z.literal("update")]),Fc="all",Jc="create",Kc="delete",Hc="retrieve",Xc="update",Qc=r=>{const e=r.replace(/_[a-z]/g,t=>t[1].toUpperCase());return e.length>1&&e[0]===e[0].toUpperCase()&&e[1]===e[1].toUpperCase()||e.length===0?e:e[0].toLowerCase()+e.slice(1)},pi=r=>{const e=(t,n=mn)=>{if(typeof t=="string")return r(t);if(Array.isArray(t))return t.map(o=>e(o,n));if(!Yr(t))return t;n=rl(n);const i={},a=t;return Object.keys(a).forEach(o=>{let l=a[o];const u=r(o);n.recursive&&(Yr(l)?ys(l,n.keepTypesOnRecursion)||(l=e(l,n)):n.recursiveInArray&&fs(l)&&(l=[...l].map(h=>{let y=h;return Yr(h)?ys(y,n.keepTypesOnRecursion)||(y=e(h,n)):fs(h)&&(y=e({key:h},n).key),y}))),i[u]=l}),i};return e},mi=pi(Qc),el=r=>r.replace(/([a-z0-9])([A-Z])/g,(e,t,n)=>`${t}_${n.toLowerCase()}`),tl=pi(el),mn={recursive:!0,recursiveInArray:!0,keepTypesOnRecursion:[Number,String,Uint8Array]},rl=(r=mn)=>(r.recursive==null?r=mn:r.recursiveInArray??(r.recursiveInArray=!1),r),fs=r=>r!=null&&Array.isArray(r),Yr=r=>r!=null&&typeof r=="object"&&!Array.isArray(r),ys=(r,e)=>(e||[]).some(t=>r instanceof t),An=r=>r!=null&&typeof r=="object"&&!Array.isArray(r);var nl=Object.defineProperty,sl=(r,e,t)=>e in r?nl(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,It=(r,e,t)=>sl(r,typeof e!="symbol"?e+"":e,t);let wi=class{constructor(){It(this,"contentType","application/json"),It(this,"decoder"),It(this,"encoder"),this.decoder=new TextDecoder,this.encoder=new TextEncoder}encode(e){return this.encoder.encode(this.encodeString(e)).buffer}decode(e,t){return this.decodeString(this.decoder.decode(e),t)}decodeString(e,t){const n=JSON.parse(e),i=mi(n);return t!=null?t.parse(i):i}encodeString(e){const t=tl(e);return JSON.stringify(t,(n,i)=>ArrayBuffer.isView(i)?Array.from(i):An(i)&&"encode_value"in i?typeof i.value=="bigint"?i.value.toString():i.value:typeof i=="bigint"?i.toString():i)}static registerCustomType(){}},bi=class{constructor(){It(this,"contentType","text/csv")}encode(e){const t=this.encodeString(e);return new TextEncoder().encode(t).buffer}decode(e,t){const n=new TextDecoder().decode(e);return this.decodeString(n,t)}encodeString(e){if(!Array.isArray(e)||e.length===0||!An(e[0]))throw new Error("Payload must be an array of objects");const t=Object.keys(e[0]),n=[t.join(",")];return e.forEach(i=>{const a=t.map(o=>JSON.stringify(i[o]??""));n.push(a.join(","))}),n.join(`
14
14
  `)}decodeString(e,t){const[n,...i]=e.trim().split(`
15
- `).map(l=>l.trim());if(n.length===0)return t!=null?t.parse({}):{};const a=n.split(",").map(l=>l.trim()),o={};return a.forEach(l=>{o[l]=[]}),i.forEach(l=>{const u=l.split(",").map(h=>h.trim());a.forEach((h,y)=>{const d=this.parseValue(u[y]);d!=null&&o[h].push(d)})}),t!=null?t.parse(o):o}parseValue(e){if(e==null||e.length===0)return null;const t=Number(e);return isNaN(t)?e.startsWith('"')&&e.endsWith('"')?e.slice(1,-1):e:t}static registerCustomType(){}},vi=class{constructor(){It(this,"contentType","text/plain")}encode(e){return new TextEncoder().encode(e).buffer}decode(e,t){const n=new TextDecoder().decode(e);return t!=null?t.parse(n):n}};const tt=new wi,nl=new bi,sl=new vi,il=[tt],ct=Object.freeze(Object.defineProperty({__proto__:null,CSVCodec:bi,CSV_CODEC:nl,ENCODERS:il,JSONCodec:wi,JSON_CODEC:tt,TEXT_CODEC:sl,TextCodec:vi},Symbol.toStringTag,{value:"Module"})),Nr=s.z.tuple([s.z.number(),s.z.number()]);s.z.tuple([s.z.bigint(),s.z.bigint()]);const Ti=s.z.object({width:s.z.number(),height:s.z.number()}),al=s.z.object({signedWidth:s.z.number(),signedHeight:s.z.number()}),ol=["width","height"];s.z.enum(ol);const cl=["start","center","end"],ll=["signedWidth","signedHeight"];s.z.enum(ll);const pr=s.z.object({x:s.z.number(),y:s.z.number()}),ul=s.z.object({clientX:s.z.number(),clientY:s.z.number()}),hl=["x","y"],Oi=s.z.enum(hl),zi=["top","right","bottom","left"];s.z.enum(zi);const dl=["left","right"],Ei=s.z.enum(dl),fl=["top","bottom"],Ni=s.z.enum(fl),Si=["center"],gs=s.z.enum(Si),yl=[...zi,...Si],Ii=s.z.enum(yl);s.z.enum(cl);const gl=["first","last"];s.z.enum(gl);const pl=s.z.object({lower:s.z.number(),upper:s.z.number()}),ml=s.z.object({lower:s.z.bigint(),upper:s.z.bigint()});s.z.union([pl,Nr]);s.z.union([ml,Nr]);s.z.union([Oi,Ii]);s.z.union([Oi,Ii,s.z.instanceof(String)]);const lt=r=>typeof r=="bigint"||r instanceof BigInt,qr=(r,e)=>lt(r)?r.valueOf()-BigInt(e.valueOf().valueOf()):r.valueOf()-Number(e.valueOf()),wl=(r,e)=>lt(r)?r.valueOf()+BigInt(e.valueOf().valueOf()):r+Number(e.valueOf()),ps=(r,e)=>lt(r)?r===BigInt(e.valueOf().valueOf()):r===Number(e.valueOf()),bl=(r,e)=>lt(r)?r.valueOf()<BigInt(e.valueOf())?r:BigInt(e.valueOf()):r.valueOf()<Number(e.valueOf())?r:Number(e.valueOf()),vl=r=>lt(r)||r instanceof BigInt?r.valueOf()<0n?-r:r:r.valueOf()<0?-r:r,Be=(r,e)=>lt(r)?r.valueOf()*BigInt(e.valueOf()):r.valueOf()*Number(e.valueOf()),K=(r,e)=>{const t={};if(typeof r=="number"||typeof r=="bigint")e!=null?(t.lower=r,t.upper=e):(t.lower=typeof r=="bigint"?0n:0,t.upper=r);else if(Array.isArray(r)){if(r.length!==2)throw new Error("bounds: expected array of length 2");[t.lower,t.upper]=r}else return ms(r);return ms(t)},ms=r=>r.lower>r.upper?{lower:r.upper,upper:r.lower}:r,ws=(r,e)=>{const t=K(r);return e<t.lower?t.lower:e>=t.upper?t.upper-(typeof t.upper=="number"?1:1n):e},Kt=(r,e)=>{const t=K(r);if(typeof e=="number"||typeof e=="bigint")return e>=t.lower&&e<t.upper;const n=K(e);return n.lower>=t.lower&&n.upper<=t.upper},Tl=(r,e,t)=>{const n=r.map(l=>K(l)),i=t>0?1:t<0?-1:0;if(i===0)return e;let a=t,o=e;for(;ps(a,0)===!1;){const l=n.findIndex(u=>i>0?o>=u.lower&&o<u.upper:o>u.lower&&o<=u.upper);if(l!==-1){const u=n[l];let h;if(i>0?h=qr(u.upper,o):h=qr(o,u.lower),h>0){const y=bl(vl(a),h);if(o=wl(o,i>0?y:-y),a=qr(a,i>0?y:-y),ps(a,0))return o;continue}}if(i>0){const u=n.filter(h=>h.lower>o);if(u.length>0)o=u[0].lower;else return o}else{const u=n.filter(h=>h.upper<o);if(u.length>0)o=u[u.length-1].upper;else return o}}return o},Ol=(r,e,t)=>{const n=r.map(o=>K(o));if(e===t)return typeof e=="bigint"?0n:0;const i=e<t?K([e,t]):K([t,e]);let a=typeof e=="bigint"?0n:0;for(const o of n){const l=o.lower>i.lower?o.lower:i.lower,u=o.upper<i.upper?o.upper:i.upper;if(l<u){const h=u-l;a=a+h}}return a};s.z.object({x:Ei.or(gs),y:Ni.or(gs)});const zl=s.z.object({x:Ei,y:Ni}),El=Object.freeze({x:"left",y:"top"}),Nl=(r,e)=>r.x===e.x&&r.y===e.y,bs=s.z.union([s.z.number(),pr,Nr,Ti,al,ul]),Sl=(r,e)=>{if(typeof r=="string"){if(e===void 0)throw new Error("The y coordinate must be given.");return r==="x"?{x:e,y:0}:{x:0,y:e}}return typeof r=="number"?{x:r,y:e??r}:Array.isArray(r)?{x:r[0],y:r[1]}:"signedWidth"in r?{x:r.signedWidth,y:r.signedHeight}:"clientX"in r?{x:r.clientX,y:r.clientY}:"width"in r?{x:r.width,y:r.height}:{x:r.x,y:r.y}},vs=Object.freeze({x:0,y:0}),Ht=s.z.union([s.z.number(),s.z.string()]);s.z.object({top:Ht,left:Ht,width:Ht,height:Ht});s.z.object({left:s.z.number(),top:s.z.number(),right:s.z.number(),bottom:s.z.number()});s.z.object({one:pr,two:pr,root:zl});const Rn=(r,e,t=0,n=0,i)=>{const a={one:{...vs},two:{...vs},root:i??El};if(typeof r=="number"){if(typeof e!="number")throw new Error("Box constructor called with invalid arguments");return a.one={x:r,y:e},a.two={x:a.one.x+t,y:a.one.y+n},a}return"one"in r&&"two"in r&&"root"in r?{...r,root:i??r.root}:("getBoundingClientRect"in r&&(r=r.getBoundingClientRect()),"left"in r?(a.one={x:r.left,y:r.top},a.two={x:r.right,y:r.bottom},a):(a.one=r,e==null?a.two={x:a.one.x+t,y:a.one.y+n}:typeof e=="number"?a.two={x:a.one.x+e,y:a.one.y+t}:"width"in e?a.two={x:a.one.x+e.width,y:a.one.y+e.height}:"signedWidth"in e?a.two={x:a.one.x+e.signedWidth,y:a.one.y+e.signedHeight}:a.two=e,a))},Wr=r=>{const e=Rn(r);return{lower:e.one.x,upper:e.two.x}},Gr=r=>{const e=Rn(r);return{lower:e.one.y,upper:e.two.y}},Il=r=>typeof r!="object"||r==null?!1:"one"in r&&"two"in r&&"root"in r;var kl=Object.defineProperty,$l=(r,e,t)=>e in r?kl(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,ge=(r,e,t)=>$l(r,typeof e!="symbol"?e+"":e,t);const Al=(r,e,t)=>e!==void 0&&r<e?e:t!==void 0&&r>t?t:r;s.z.object({offset:bs,scale:bs});s.z.object({offset:s.z.number(),scale:s.z.number()});const Rl=r=>(e,t,n,i)=>t==="dimension"?[e,n]:[e,i?n-r:n+r],xl=r=>(e,t,n,i)=>[e,i?n/r:n*r],Cl=r=>(e,t,n)=>{if(e===null)return[r,n];const{lower:i,upper:a}=e,{lower:o,upper:l}=r,u=a-i,h=l-o;if(t==="dimension")return[r,n*(h/u)];const y=(n-i)*(h/u)+o;return[r,y]},Pl=r=>(e,t,n)=>[r,n],Dl=()=>(r,e,t)=>{if(r===null)throw new Error("cannot invert without bounds");if(e==="dimension")return[r,t];const{lower:n,upper:i}=r;return[r,i-(t-n)]},jl=r=>(e,t,n)=>{const{lower:i,upper:a}=r;return n=Al(n,i,a),[e,n]},wn=class vt{constructor(){ge(this,"ops",[]),ge(this,"currBounds",null),ge(this,"currType",null),ge(this,"reversed",!1),this.ops=[]}static translate(e){return new vt().translate(e)}static magnify(e){return new vt().magnify(e)}static scale(e,t){return new vt().scale(e,t)}translate(e){const t=this.new(),n=Rl(e);return n.type="translate",t.ops.push(n),t}magnify(e){const t=this.new(),n=xl(e);return n.type="magnify",t.ops.push(n),t}scale(e,t){const n=K(e,t),i=this.new(),a=Cl(n);return a.type="scale",i.ops.push(a),i}clamp(e,t){const n=K(e,t),i=this.new(),a=jl(n);return a.type="clamp",i.ops.push(a),i}reBound(e,t){const n=K(e,t),i=this.new(),a=Pl(n);return a.type="re-bound",i.ops.push(a),i}invert(){const e=Dl();e.type="invert";const t=this.new();return t.ops.push(e),t}pos(e){return this.exec("position",e)}dim(e){return this.exec("dimension",e)}new(){const e=new vt;return e.ops=this.ops.slice(),e.reversed=this.reversed,e}exec(e,t){return this.currBounds=null,this.ops.reduce(([n,i],a)=>a(n,e,i,this.reversed),[null,t])[1]}reverse(){const e=this.new();e.ops.reverse();const t=[];return e.ops.forEach((n,i)=>{if(n.type==="scale"||t.some(([o,l])=>i>=o&&i<=l))return;const a=e.ops.findIndex((o,l)=>o.type==="scale"&&l>i);a!==-1&&t.push([i,a])}),t.forEach(([n,i])=>{const a=e.ops.slice(n,i);a.unshift(e.ops[i]),e.ops.splice(n,i-n+1,...a)}),e.reversed=!e.reversed,e}get transform(){return{scale:this.dim(1),offset:this.pos(0)}}};ge(wn,"IDENTITY",new wn);let Ts=wn;const Os=class fe{constructor(e=new Ts,t=new Ts,n=null){ge(this,"x"),ge(this,"y"),ge(this,"currRoot"),this.x=e,this.y=t,this.currRoot=n}static translate(e,t){return new fe().translate(e,t)}static translateX(e){return new fe().translateX(e)}static translateY(e){return new fe().translateY(e)}static clamp(e){return new fe().clamp(e)}static magnify(e){return new fe().magnify(e)}static scale(e){return new fe().scale(e)}static reBound(e){return new fe().reBound(e)}translate(e,t){const n=Sl(e,t),i=this.copy();return i.x=this.x.translate(n.x),i.y=this.y.translate(n.y),i}translateX(e){const t=this.copy();return t.x=this.x.translate(e),t}translateY(e){const t=this.copy();return t.y=this.y.translate(e),t}magnify(e){const t=this.copy();return t.x=this.x.magnify(e.x),t.y=this.y.magnify(e.y),t}scale(e){const t=this.copy();if(Il(e)){const n=this.currRoot;return t.currRoot=e.root,n!=null&&!Nl(n,e.root)&&(n.x!==e.root.x&&(t.x=t.x.invert()),n.y!==e.root.y&&(t.y=t.y.invert())),t.x=t.x.scale(Wr(e)),t.y=t.y.scale(Gr(e)),t}return t.x=t.x.scale(e.width),t.y=t.y.scale(e.height),t}reBound(e){const t=this.copy();return t.x=this.x.reBound(Wr(e)),t.y=this.y.reBound(Gr(e)),t}clamp(e){const t=this.copy();return t.x=this.x.clamp(Wr(e)),t.y=this.y.clamp(Gr(e)),t}copy(){const e=new fe;return e.currRoot=this.currRoot,e.x=this.x,e.y=this.y,e}reverse(){const e=this.copy();return e.x=this.x.reverse(),e.y=this.y.reverse(),e}pos(e){return{x:this.x.pos(e.x),y:this.y.pos(e.y)}}dim(e){return{x:this.x.dim(e.x),y:this.y.dim(e.y)}}box(e){return Rn(this.pos(e.one),this.pos(e.two),0,0,this.currRoot??e.root)}get transform(){return{scale:this.dim({x:1,y:1}),offset:this.pos({x:0,y:0})}}};ge(Os,"IDENTITY",new Os);const zs=r=>[...new Set(r)],Ml=r=>r!=null&&typeof r=="object"&&"toString"in r,Bl=(r,e=!1)=>{const t=Ml(r)?"stringer":typeof r;let n;switch(t){case"string":n=(i,a)=>i.localeCompare(a);break;case"stringer":n=(i,a)=>i.toString().localeCompare(a.toString());break;case"number":n=(i,a)=>Number(i)-Number(a);break;case"bigint":n=(i,a)=>BigInt(i)-BigInt(a)>0n?1:-1;break;case"boolean":n=(i,a)=>Number(i)-Number(a);break;case"undefined":n=()=>0;break;default:return console.warn(`sortFunc: unknown type ${t}`),()=>-1}return e?Ul(n):n},Ul=r=>(e,t)=>r(t,e),Sr=0,Vr=-1,Fr=1,Zl=r=>r<Sr,Ll=r=>r>Sr,_l=r=>r===Sr,Yl=(r,e)=>{let t=null;return e===0?r:(...n)=>{t!==null&&(clearTimeout(t),t=null),t=setTimeout(()=>r(...n),e)}},ql=s.z.object({signedWidth:s.z.number(),signedHeight:s.z.number()});s.z.union([Ti,ql,pr,Nr]);const Wl=s.z.bigint().or(s.z.string().transform(BigInt));var Gl=Object.defineProperty,Vl=(r,e,t)=>e in r?Gl(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,f=(r,e,t)=>Vl(r,typeof e!="symbol"?e+"":e,t);let Fl=(r,e=21)=>(t=e)=>{let n="",i=t;for(;i--;)n+=r[Math.random()*r.length|0];return n};const Jl="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",ki=Fl(Jl,11),Kl=Object.freeze(Object.defineProperty({__proto__:null,id:ki},Symbol.toStringTag,{value:"Module"})),Hl=s.z.enum(["static","dynamic"]),$i=(r,e)=>{const t=new I(e);if(![z.DAY,z.HOUR,z.MINUTE,z.SECOND,z.MILLISECOND,z.MICROSECOND,z.NANOSECOND].some(i=>i.equals(t)))throw new Error("Invalid argument for remainder. Must be an even TimeSpan or Timestamp");const n=r.valueOf()%t.valueOf();return r instanceof I?new I(n):new z(n)},C=class T{constructor(e,t="UTC"){if(f(this,"value"),f(this,"encodeValue",!0),e==null)this.value=T.now().valueOf();else if(e instanceof Date)this.value=BigInt(e.getTime())*T.MILLISECOND.valueOf();else if(typeof e=="string")this.value=T.parseDateTimeString(e,t).valueOf();else if(Array.isArray(e))this.value=T.parseDate(e);else{let n=BigInt(0);e instanceof Number&&(e=e.valueOf()),t==="local"&&(n=T.utcOffset.valueOf()),typeof e=="number"&&(isFinite(e)?e=Math.trunc(e):(isNaN(e)&&(e=0),e===1/0?e=T.MAX:e=T.MIN)),this.value=BigInt(e.valueOf())+n}}static parseDate([e=1970,t=1,n=1]){const i=new Date(e,t-1,n,0,0,0,0);return new T(BigInt(i.getTime())*T.MILLISECOND.valueOf()).truncate(T.DAY).valueOf()}encode(){return this.value.toString()}valueOf(){return this.value}static parseTimeString(e,t="UTC"){const[n,i,a]=e.split(":");let o="00",l="00";a!=null&&([o,l]=a.split("."));let u=T.hours(parseInt(n??"00")).add(T.minutes(parseInt(i??"00"))).add(T.seconds(parseInt(o??"00"))).add(T.milliseconds(parseInt(l??"00")));return t==="local"&&(u=u.add(T.utcOffset)),u.valueOf()}static parseDateTimeString(e,t="UTC"){if(!e.includes("/")&&!e.includes("-"))return T.parseTimeString(e,t);const n=new Date(e);return e.includes(":")||n.setUTCHours(0,0,0,0),new T(BigInt(n.getTime())*T.MILLISECOND.valueOf(),t).valueOf()}fString(e="ISO",t="UTC"){switch(e){case"ISODate":return this.toISOString(t).slice(0,10);case"ISOTime":return this.toISOString(t).slice(11,23);case"time":return this.timeString(!1,t);case"preciseTime":return this.timeString(!0,t);case"date":return this.dateString();case"preciseDate":return`${this.dateString()} ${this.timeString(!0,t)}`;case"dateTime":return`${this.dateString()} ${this.timeString(!1,t)}`;default:return this.toISOString(t)}}toISOString(e="UTC"){return e==="UTC"?this.date().toISOString():this.sub(T.utcOffset).date().toISOString()}timeString(e=!1,t="UTC"){const n=this.toISOString(t);return e?n.slice(11,23):n.slice(11,19)}dateString(){const e=this.date(),t=e.toLocaleString("default",{month:"short"}),n=e.toLocaleString("default",{day:"numeric"});return`${t} ${n}`}static get utcOffset(){return new z(BigInt(new Date().getTimezoneOffset())*T.MINUTE.valueOf())}static since(e){return new T().span(e)}date(){return new Date(this.milliseconds)}equals(e){return this.valueOf()===new T(e).valueOf()}span(e){return this.range(e).span}range(e){return new W(this,e).makeValid()}spanRange(e){return this.range(this.add(e)).makeValid()}get isZero(){return this.valueOf()===BigInt(0)}after(e){return this.valueOf()>new T(e).valueOf()}afterEq(e){return this.valueOf()>=new T(e).valueOf()}before(e){return this.valueOf()<new T(e).valueOf()}beforeEq(e){return this.valueOf()<=new T(e).valueOf()}add(e){return new T(this.valueOf()+BigInt(e.valueOf()))}sub(e){return new T(this.valueOf()-BigInt(e.valueOf()))}get hours(){return Number(this.valueOf())/Number(z.HOUR.valueOf())}get minutes(){return Number(this.valueOf())/Number(z.MINUTE.valueOf())}get days(){return Number(this.valueOf())/Number(z.DAY.valueOf())}get seconds(){return Number(this.valueOf())/Number(z.SECOND.valueOf())}get milliseconds(){return Number(this.valueOf())/Number(T.MILLISECOND.valueOf())}get year(){return this.date().getFullYear()}setYear(e){const t=this.date();return t.setFullYear(e),new T(t)}get month(){return this.date().getMonth()}setMonth(e){const t=this.date();return t.setMonth(e),new T(t)}get day(){return this.date().getDate()}setDay(e){const t=this.date();return t.setDate(e),new T(t)}get hour(){return this.date().getHours()}setHour(e){const t=this.date();return t.setHours(e),new T(t)}get minute(){return this.date().getMinutes()}setMinute(e){const t=this.date();return t.setMinutes(e),new T(t)}get second(){return this.date().getSeconds()}setSecond(e){const t=this.date();return t.setSeconds(e),new T(t)}get millisecond(){return this.date().getMilliseconds()}setMillisecond(e){const t=this.date();return t.setMilliseconds(e),new T(t)}toString(){return this.date().toISOString()}remainder(e){return $i(this,e)}get isToday(){return this.truncate(z.DAY).equals(T.now().truncate(z.DAY))}truncate(e){return this.sub(this.remainder(e))}static now(){return new T(new Date)}static max(...e){let t=T.MIN;for(const n of e){const i=new T(n);i.after(t)&&(t=i)}return t}static min(...e){let t=T.MAX;for(const n of e){const i=new T(n);i.before(t)&&(t=i)}return t}static nanoseconds(e){return new T(e)}static microseconds(e){return T.nanoseconds(e*1e3)}static milliseconds(e){return T.microseconds(e*1e3)}static seconds(e){return T.milliseconds(e*1e3)}static minutes(e){return T.seconds(e*60)}static hours(e){return T.minutes(e*60)}static days(e){return T.hours(e*24)}};f(C,"NANOSECOND",C.nanoseconds(1)),f(C,"MICROSECOND",C.microseconds(1)),f(C,"MILLISECOND",C.milliseconds(1)),f(C,"SECOND",C.seconds(1)),f(C,"MINUTE",C.minutes(1)),f(C,"HOUR",C.hours(1)),f(C,"DAY",C.days(1)),f(C,"MAX",new C((1n<<63n)-1n)),f(C,"MIN",new C(0)),f(C,"ZERO",new C(0)),f(C,"z",s.z.union([s.z.object({value:s.z.bigint()}).transform(r=>new C(r.value)),s.z.string().transform(r=>new C(BigInt(r))),s.z.instanceof(Number).transform(r=>new C(r)),s.z.number().transform(r=>new C(r)),s.z.instanceof(C)]));let I=C;const P=class N{constructor(e){f(this,"value"),f(this,"encodeValue",!0),typeof e=="number"&&(e=Math.trunc(e.valueOf())),this.value=BigInt(e.valueOf())}static fromSeconds(e){return e instanceof N?e:e instanceof nt?e.period:e instanceof I?new N(e):["number","bigint"].includes(typeof e)?N.seconds(e):new N(e)}static fromMilliseconds(e){return e instanceof N?e:e instanceof nt?e.period:e instanceof I?new N(e):["number","bigint"].includes(typeof e)?N.milliseconds(e):new N(e)}encode(){return this.value.toString()}valueOf(){return this.value}lessThan(e){return this.valueOf()<new N(e).valueOf()}greaterThan(e){return this.valueOf()>new N(e).valueOf()}lessThanOrEqual(e){return this.valueOf()<=new N(e).valueOf()}greaterThanOrEqual(e){return this.valueOf()>=new N(e).valueOf()}remainder(e){return $i(this,e)}truncate(e){return new N(BigInt(Math.trunc(Number(this.valueOf()/e.valueOf())))*e.valueOf())}toString(){const e=this.truncate(N.DAY),t=this.truncate(N.HOUR),n=this.truncate(N.MINUTE),i=this.truncate(N.SECOND),a=this.truncate(N.MILLISECOND),o=this.truncate(N.MICROSECOND),l=this.truncate(N.NANOSECOND),u=e,h=t.sub(e),y=n.sub(t),d=i.sub(n),j=a.sub(i),$=o.sub(a),te=l.sub(o);let U="";return u.isZero||(U+=`${u.days}d `),h.isZero||(U+=`${h.hours}h `),y.isZero||(U+=`${y.minutes}m `),d.isZero||(U+=`${d.seconds}s `),j.isZero||(U+=`${j.milliseconds}ms `),$.isZero||(U+=`${$.microseconds}µs `),te.isZero||(U+=`${te.nanoseconds}ns`),U.trim()}mult(e){return new N(this.valueOf()*BigInt(e))}get days(){return Number(this.valueOf())/Number(N.DAY.valueOf())}get hours(){return Number(this.valueOf())/Number(N.HOUR.valueOf())}get minutes(){return Number(this.valueOf())/Number(N.MINUTE.valueOf())}get seconds(){return Number(this.valueOf())/Number(N.SECOND.valueOf())}get milliseconds(){return Number(this.valueOf())/Number(N.MILLISECOND.valueOf())}get microseconds(){return Number(this.valueOf())/Number(N.MICROSECOND.valueOf())}get nanoseconds(){return Number(this.valueOf())}get isZero(){return this.valueOf()===BigInt(0)}equals(e){return this.valueOf()===new N(e).valueOf()}add(e){return new N(this.valueOf()+new N(e).valueOf())}sub(e){return new N(this.valueOf()-new N(e).valueOf())}static nanoseconds(e=1){return new N(e)}static microseconds(e=1){return N.nanoseconds(Be(e,1e3))}static milliseconds(e=1){return N.microseconds(Be(e,1e3))}static seconds(e=1){return N.milliseconds(Be(e,1e3))}static minutes(e=1){return N.seconds(Be(e,60))}static hours(e){return N.minutes(Be(e,60))}static days(e){return N.hours(Be(e,24))}};f(P,"NANOSECOND",P.nanoseconds(1)),f(P,"MICROSECOND",P.microseconds(1)),f(P,"MILLISECOND",P.milliseconds(1)),f(P,"SECOND",P.seconds(1)),f(P,"MINUTE",P.minutes(1)),f(P,"HOUR",P.hours(1)),f(P,"DAY",P.days(1)),f(P,"MAX",new P((1n<<63n)-1n)),f(P,"MIN",new P(0)),f(P,"ZERO",new P(0)),f(P,"z",s.z.union([s.z.object({value:s.z.bigint()}).transform(r=>new P(r.value)),s.z.string().transform(r=>new P(BigInt(r))),s.z.instanceof(Number).transform(r=>new P(r)),s.z.number().transform(r=>new P(r)),s.z.instanceof(P)]));let z=P;const Tt=class cr extends Number{constructor(e){e instanceof Number?super(e.valueOf()):super(e)}toString(){return`${this.valueOf()} Hz`}equals(e){return this.valueOf()===new cr(e).valueOf()}get period(){return z.seconds(1/this.valueOf())}sampleCount(e){return new z(e).seconds*this.valueOf()}byteCount(e,t){return this.sampleCount(e)*new F(t).valueOf()}span(e){return z.seconds(e/this.valueOf())}byteSpan(e,t){return this.span(e.valueOf()/t.valueOf())}static hz(e){return new cr(e)}static khz(e){return cr.hz(e*1e3)}};f(Tt,"z",s.z.union([s.z.number().transform(r=>new Tt(r)),s.z.instanceof(Number).transform(r=>new Tt(r)),s.z.instanceof(Tt)]));let nt=Tt;const q=class extends Number{constructor(e){e instanceof Number?super(e.valueOf()):super(e)}length(e){return e.valueOf()/this.valueOf()}size(e){return new st(e*this.valueOf())}};f(q,"UNKNOWN",new q(0)),f(q,"BIT128",new q(16)),f(q,"BIT64",new q(8)),f(q,"BIT32",new q(4)),f(q,"BIT16",new q(2)),f(q,"BIT8",new q(1)),f(q,"z",s.z.union([s.z.number().transform(r=>new q(r)),s.z.instanceof(Number).transform(r=>new q(r)),s.z.instanceof(q)]));let F=q;const ce=class lr{constructor(e,t){f(this,"start"),f(this,"end"),typeof e=="object"&&"start"in e?(this.start=new I(e.start),this.end=new I(e.end)):(this.start=new I(e),this.end=new I(t))}get span(){return new z(this.end.valueOf()-this.start.valueOf())}get isValid(){return this.start.valueOf()<=this.end.valueOf()}makeValid(){return this.isValid?this:this.swap()}get isZero(){return this.span.isZero}get numeric(){return{start:Number(this.start.valueOf()),end:Number(this.end.valueOf())}}swap(){return new lr(this.end,this.start)}equals(e){return this.start.equals(e.start)&&this.end.equals(e.end)}toString(){return`${this.start.toString()} - ${this.end.toString()}`}toPrettyString(){return`${this.start.fString("preciseDate")} - ${this.span.toString()}`}overlapsWith(e,t=z.ZERO){e=e.makeValid();const n=this.makeValid();if(this.equals(e))return!0;if(e.end.equals(n.start)||n.end.equals(e.start))return!1;const i=I.max(n.start,e.start),a=I.min(n.end,e.end);return a.before(i)?!1:new z(a.sub(i)).greaterThanOrEqual(t)}roughlyEquals(e,t){let n=this.start.sub(e.start).valueOf(),i=this.end.sub(e.end).valueOf();return n<0&&(n=-n),i<0&&(i=-i),n<=t.valueOf()&&i<=t.valueOf()}contains(e){return e instanceof lr?this.contains(e.start)&&this.contains(e.end):this.start.beforeEq(e)&&this.end.after(e)}boundBy(e){const t=new lr(this.start,this.end);return e.start.after(this.start)&&(t.start=e.start),e.start.after(this.end)&&(t.end=e.start),e.end.before(this.end)&&(t.end=e.end),e.end.before(this.start)&&(t.start=e.end),t}};f(ce,"MAX",new ce(I.MIN,I.MAX)),f(ce,"MIN",new ce(I.MAX,I.MIN)),f(ce,"ZERO",new ce(I.ZERO,I.ZERO)),f(ce,"z",s.z.union([s.z.object({start:I.z,end:I.z}).transform(r=>new ce(r.start,r.end)),s.z.instanceof(ce)]));let W=ce;const Xl=(r,e)=>r.start.before(e.start)?-1:r.start.after(e.start)?1:r.end.before(e.end)?-1:r.end.after(e.end)?1:0,p=class le extends String{constructor(e){if(e instanceof le||typeof e=="string"||typeof e.valueOf()=="string"){super(e.valueOf());return}const t=le.ARRAY_CONSTRUCTOR_DATA_TYPES.get(e.constructor.name);if(t!=null){super(t.valueOf());return}throw super(le.UNKNOWN.valueOf()),new Error(`unable to find data type for ${e.toString()}`)}get Array(){const e=le.ARRAY_CONSTRUCTORS.get(this.toString());if(e==null)throw new Error(`unable to find array constructor for ${this.valueOf()}`);return e}equals(e){return this.valueOf()===e.valueOf()}matches(...e){return e.some(t=>this.equals(t))}toString(){return this.valueOf()}get isVariable(){return this.equals(le.JSON)||this.equals(le.STRING)}get isNumeric(){return!this.isVariable&&!this.equals(le.UUID)}get isInteger(){return this.toString().startsWith("int")}get isFloat(){return this.toString().startsWith("float")}get density(){const e=le.DENSITIES.get(this.toString());if(e==null)throw new Error(`unable to find density for ${this.valueOf()}`);return e}canSafelyCastTo(e){return this.equals(e)?!0:this.isVariable&&!e.isVariable||!this.isVariable&&e.isVariable?!1:this.isFloat&&e.isInteger||this.isInteger&&e.isFloat?this.density.valueOf()<e.density.valueOf():this.isFloat&&e.isFloat||this.isInteger&&e.isInteger?this.density.valueOf()<=e.density.valueOf():!1}canCastTo(e){return this.isNumeric&&e.isNumeric?!0:this.equals(e)}checkArray(e){return e.constructor===this.Array}toJSON(){return this.toString()}get usesBigInt(){return le.BIG_INT_TYPES.some(e=>e.equals(this))}};f(p,"UNKNOWN",new p("unknown")),f(p,"FLOAT64",new p("float64")),f(p,"FLOAT32",new p("float32")),f(p,"INT64",new p("int64")),f(p,"INT32",new p("int32")),f(p,"INT16",new p("int16")),f(p,"INT8",new p("int8")),f(p,"UINT64",new p("uint64")),f(p,"UINT32",new p("uint32")),f(p,"UINT16",new p("uint16")),f(p,"UINT8",new p("uint8")),f(p,"BOOLEAN",p.UINT8),f(p,"TIMESTAMP",new p("timestamp")),f(p,"UUID",new p("uuid")),f(p,"STRING",new p("string")),f(p,"JSON",new p("json")),f(p,"ARRAY_CONSTRUCTORS",new Map([[p.UINT8.toString(),Uint8Array],[p.UINT16.toString(),Uint16Array],[p.UINT32.toString(),Uint32Array],[p.UINT64.toString(),BigUint64Array],[p.FLOAT32.toString(),Float32Array],[p.FLOAT64.toString(),Float64Array],[p.INT8.toString(),Int8Array],[p.INT16.toString(),Int16Array],[p.INT32.toString(),Int32Array],[p.INT64.toString(),BigInt64Array],[p.TIMESTAMP.toString(),BigInt64Array],[p.STRING.toString(),Uint8Array],[p.JSON.toString(),Uint8Array],[p.UUID.toString(),Uint8Array]])),f(p,"ARRAY_CONSTRUCTOR_DATA_TYPES",new Map([[Uint8Array.name,p.UINT8],[Uint16Array.name,p.UINT16],[Uint32Array.name,p.UINT32],[BigUint64Array.name,p.UINT64],[Float32Array.name,p.FLOAT32],[Float64Array.name,p.FLOAT64],[Int8Array.name,p.INT8],[Int16Array.name,p.INT16],[Int32Array.name,p.INT32],[BigInt64Array.name,p.INT64]])),f(p,"DENSITIES",new Map([[p.UINT8.toString(),F.BIT8],[p.UINT16.toString(),F.BIT16],[p.UINT32.toString(),F.BIT32],[p.UINT64.toString(),F.BIT64],[p.FLOAT32.toString(),F.BIT32],[p.FLOAT64.toString(),F.BIT64],[p.INT8.toString(),F.BIT8],[p.INT16.toString(),F.BIT16],[p.INT32.toString(),F.BIT32],[p.INT64.toString(),F.BIT64],[p.TIMESTAMP.toString(),F.BIT64],[p.STRING.toString(),F.UNKNOWN],[p.JSON.toString(),F.UNKNOWN],[p.UUID.toString(),F.BIT128]])),f(p,"ALL",[p.UNKNOWN,p.FLOAT64,p.FLOAT32,p.INT64,p.INT32,p.INT16,p.INT8,p.UINT64,p.UINT32,p.UINT16,p.UINT8,p.TIMESTAMP,p.UUID,p.STRING,p.JSON]),f(p,"BIG_INT_TYPES",[p.INT64,p.UINT64,p.TIMESTAMP]),f(p,"z",s.z.union([s.z.string().transform(r=>new p(r)),s.z.instanceof(p)]));let S=p;const V=class L extends Number{constructor(e){super(e.valueOf())}largerThan(e){return this.valueOf()>e.valueOf()}smallerThan(e){return this.valueOf()<e.valueOf()}add(e){return L.bytes(this.valueOf()+e.valueOf())}sub(e){return L.bytes(this.valueOf()-e.valueOf())}truncate(e){return new L(Math.trunc(this.valueOf()/e.valueOf())*e.valueOf())}remainder(e){return L.bytes(this.valueOf()%e.valueOf())}get gigabytes(){return this.valueOf()/L.GIGABYTE.valueOf()}get megabytes(){return this.valueOf()/L.MEGABYTE.valueOf()}get kilobytes(){return this.valueOf()/L.KILOBYTE.valueOf()}get terabytes(){return this.valueOf()/L.TERABYTE.valueOf()}toString(){const e=this.truncate(L.TERABYTE),t=this.truncate(L.GIGABYTE),n=this.truncate(L.MEGABYTE),i=this.truncate(L.KILOBYTE),a=this.truncate(L.BYTE),o=e,l=t.sub(e),u=n.sub(t),h=i.sub(n),y=a.sub(i);let d="";return o.isZero||(d+=`${o.terabytes}TB `),l.isZero||(d+=`${l.gigabytes}GB `),u.isZero||(d+=`${u.megabytes}MB `),h.isZero||(d+=`${h.kilobytes}KB `),(!y.isZero||d==="")&&(d+=`${y.valueOf()}B`),d.trim()}static bytes(e=1){return new L(e)}static kilobytes(e=1){return L.bytes(e.valueOf()*1e3)}static megabytes(e=1){return L.kilobytes(e.valueOf()*1e3)}static gigabytes(e=1){return L.megabytes(e.valueOf()*1e3)}static terabytes(e){return L.gigabytes(e.valueOf()*1e3)}get isZero(){return this.valueOf()===0}};f(V,"BYTE",new V(1)),f(V,"KILOBYTE",V.kilobytes(1)),f(V,"MEGABYTE",V.megabytes(1)),f(V,"GIGABYTE",V.gigabytes(1)),f(V,"TERABYTE",V.terabytes(1)),f(V,"ZERO",new V(0)),f(V,"z",s.z.union([s.z.number().transform(r=>new V(r)),s.z.instanceof(V)]));let st=V;s.z.union([s.z.instanceof(Uint8Array),s.z.instanceof(Uint16Array),s.z.instanceof(Uint32Array),s.z.instanceof(BigUint64Array),s.z.instanceof(Float32Array),s.z.instanceof(Float64Array),s.z.instanceof(Int8Array),s.z.instanceof(Int16Array),s.z.instanceof(Int32Array),s.z.instanceof(BigInt64Array)]);const Ai=r=>{const e=typeof r;return e==="string"||e==="number"||e==="boolean"||e==="bigint"||r instanceof I||r instanceof z||r instanceof Date},Ql=(r,e,t,n=0)=>r.usesBigInt&&!e.usesBigInt?Number(t)-Number(n):!r.usesBigInt&&e.usesBigInt?BigInt(t.valueOf())-BigInt(n.valueOf()):zt(t,-n).valueOf(),eu=r=>r==null?!1:Array.isArray(r)||r instanceof ArrayBuffer||ArrayBuffer.isView(r)&&!(r instanceof DataView)||r instanceof Oe?!0:Ai(r),ve=-1,bn={[Symbol.iterator]:()=>bn,next:()=>({done:!0,value:void 0})},tu=s.z.string().transform(r=>new Uint8Array(atob(r).split("").map(e=>e.charCodeAt(0))).buffer),ru=s.z.union([s.z.null(),s.z.undefined()]).transform(()=>new Uint8Array().buffer),vn=10,Ot=class ue{constructor(e){f(this,"key",""),f(this,"isSynnaxSeries",!0),f(this,"dataType"),f(this,"sampleOffset"),f(this,"gl"),f(this,"_data"),f(this,"_timeRange"),f(this,"alignment",0n),f(this,"_cachedMin"),f(this,"_cachedMax"),f(this,"writePos",ve),f(this,"_refCount",0),f(this,"_cachedLength"),f(this,"_cachedIndexes"),eu(e)&&(e={data:e});const{dataType:t,timeRange:n,sampleOffset:i=0,glBufferUsage:a="static",alignment:o=0n,key:l=ki()}=e,u=e.data??[];if(u instanceof ue||typeof u=="object"&&"isSynnaxSeries"in u&&u.isSynnaxSeries===!0){const d=u;this.key=d.key,this.dataType=d.dataType,this.sampleOffset=d.sampleOffset,this.gl=d.gl,this._data=d._data,this._timeRange=d._timeRange,this.alignment=d.alignment,this._cachedMin=d._cachedMin,this._cachedMax=d._cachedMax,this.writePos=d.writePos,this._refCount=d._refCount,this._cachedLength=d._cachedLength;return}const h=Ai(u),y=Array.isArray(u);if(t!=null)this.dataType=new S(t);else{if(u instanceof ArrayBuffer)throw new Error("cannot infer data type from an ArrayBuffer instance when constructing a Series. Please provide a data type.");if(y||h){let d=u;if(!h){if(u.length===0)throw new Error("cannot infer data type from a zero length JS array when constructing a Series. Please provide a data type.");d=u[0]}if(typeof d=="string")this.dataType=S.STRING;else if(typeof d=="number")this.dataType=S.FLOAT64;else if(typeof d=="bigint")this.dataType=S.INT64;else if(typeof d=="boolean")this.dataType=S.BOOLEAN;else if(d instanceof I||d instanceof Date||d instanceof I)this.dataType=S.TIMESTAMP;else if(typeof d=="object")this.dataType=S.JSON;else throw new Error(`cannot infer data type of ${typeof d} when constructing a Series from a JS array`)}else this.dataType=new S(u)}if(!y&&!h)this._data=u;else{let d=h?[u]:u;const j=d[0];(j instanceof I||j instanceof Date||j instanceof z)&&(d=d.map($=>new I($).valueOf())),this.dataType.equals(S.STRING)?(this._cachedLength=d.length,this._data=new TextEncoder().encode(`${d.join(`
15
+ `).map(l=>l.trim());if(n.length===0)return t!=null?t.parse({}):{};const a=n.split(",").map(l=>l.trim()),o={};return a.forEach(l=>{o[l]=[]}),i.forEach(l=>{const u=l.split(",").map(h=>h.trim());a.forEach((h,y)=>{const d=this.parseValue(u[y]);d!=null&&o[h].push(d)})}),t!=null?t.parse(o):o}parseValue(e){if(e==null||e.length===0)return null;const t=Number(e);return isNaN(t)?e.startsWith('"')&&e.endsWith('"')?e.slice(1,-1):e:t}static registerCustomType(){}},vi=class{constructor(){It(this,"contentType","text/plain")}encode(e){return new TextEncoder().encode(e).buffer}decode(e,t){const n=new TextDecoder().decode(e);return t!=null?t.parse(n):n}};const tt=new wi,il=new bi,al=new vi,ol=[tt],ct=Object.freeze(Object.defineProperty({__proto__:null,CSVCodec:bi,CSV_CODEC:il,ENCODERS:ol,JSONCodec:wi,JSON_CODEC:tt,TEXT_CODEC:al,TextCodec:vi},Symbol.toStringTag,{value:"Module"})),gs=r=>[...new Set(r)],cl=r=>r!=null&&typeof r=="object"&&"toString"in r,ll=(r,e=!1)=>{const t=cl(r)?"stringer":typeof r;let n;switch(t){case"string":n=(i,a)=>i.localeCompare(a);break;case"stringer":n=(i,a)=>i.toString().localeCompare(a.toString());break;case"number":n=(i,a)=>Number(i)-Number(a);break;case"bigint":n=(i,a)=>BigInt(i)-BigInt(a)>0n?1:-1;break;case"boolean":n=(i,a)=>Number(i)-Number(a);break;case"undefined":n=()=>0;break;default:return console.warn(`sortFunc: unknown type ${t}`),()=>-1}return e?ul(n):n},ul=r=>(e,t)=>r(t,e),Nr=0,qr=-1,Wr=1,hl=r=>r<Nr,dl=r=>r>Nr,fl=r=>r===Nr,Sr=s.z.tuple([s.z.number(),s.z.number()]);s.z.tuple([s.z.bigint(),s.z.bigint()]);const Ti=s.z.object({width:s.z.number(),height:s.z.number()}),yl=s.z.object({signedWidth:s.z.number(),signedHeight:s.z.number()}),gl=["width","height"];s.z.enum(gl);const pl=["start","center","end"],ml=["signedWidth","signedHeight"];s.z.enum(ml);const pr=s.z.object({x:s.z.number(),y:s.z.number()}),wl=s.z.object({clientX:s.z.number(),clientY:s.z.number()}),bl=["x","y"],Oi=s.z.enum(bl),zi=["top","right","bottom","left"];s.z.enum(zi);const vl=["left","right"],Ei=s.z.enum(vl),Tl=["top","bottom"],Ni=s.z.enum(Tl),Si=["center"],ps=s.z.enum(Si),Ol=[...zi,...Si],Ii=s.z.enum(Ol);s.z.enum(pl);const zl=["first","last"];s.z.enum(zl);const El=s.z.object({lower:s.z.number(),upper:s.z.number()}),Nl=s.z.object({lower:s.z.bigint(),upper:s.z.bigint()});s.z.union([El,Sr]);s.z.union([Nl,Sr]);s.z.union([Oi,Ii]);s.z.union([Oi,Ii,s.z.instanceof(String)]);const lt=r=>typeof r=="bigint"||r instanceof BigInt,Gr=(r,e)=>lt(r)?r.valueOf()-BigInt(e.valueOf().valueOf()):r.valueOf()-Number(e.valueOf()),Sl=(r,e)=>lt(r)?r.valueOf()+BigInt(e.valueOf().valueOf()):r+Number(e.valueOf()),ms=(r,e)=>lt(r)?r===BigInt(e.valueOf().valueOf()):r===Number(e.valueOf()),Il=(r,e)=>lt(r)?r.valueOf()<BigInt(e.valueOf())?r:BigInt(e.valueOf()):r.valueOf()<Number(e.valueOf())?r:Number(e.valueOf()),kl=r=>lt(r)||r instanceof BigInt?r.valueOf()<0n?-r:r:r.valueOf()<0?-r:r,Be=(r,e)=>lt(r)?r.valueOf()*BigInt(e.valueOf()):r.valueOf()*Number(e.valueOf()),K=(r,e)=>{const t={};if(typeof r=="number"||typeof r=="bigint")e!=null?(t.lower=r,t.upper=e):(t.lower=typeof r=="bigint"?0n:0,t.upper=r);else if(Array.isArray(r)){if(r.length!==2)throw new Error("bounds: expected array of length 2");[t.lower,t.upper]=r}else return ws(r);return ws(t)},ws=r=>r.lower>r.upper?{lower:r.upper,upper:r.lower}:r,bs=(r,e)=>{const t=K(r);return e<t.lower?t.lower:e>=t.upper?t.upper-(typeof t.upper=="number"?1:1n):e},Kt=(r,e)=>{const t=K(r);if(typeof e=="number"||typeof e=="bigint")return e>=t.lower&&e<t.upper;const n=K(e);return n.lower>=t.lower&&n.upper<=t.upper},$l=(r,e,t)=>{const n=r.map(l=>K(l)),i=t>0?1:t<0?-1:0;if(i===0)return e;let a=t,o=e;for(;ms(a,0)===!1;){const l=n.findIndex(u=>i>0?o>=u.lower&&o<u.upper:o>u.lower&&o<=u.upper);if(l!==-1){const u=n[l];let h;if(i>0?h=Gr(u.upper,o):h=Gr(o,u.lower),h>0){const y=Il(kl(a),h);if(o=Sl(o,i>0?y:-y),a=Gr(a,i>0?y:-y),ms(a,0))return o;continue}}if(i>0){const u=n.filter(h=>h.lower>o);if(u.length>0)o=u[0].lower;else return o}else{const u=n.filter(h=>h.upper<o);if(u.length>0)o=u[u.length-1].upper;else return o}}return o},Al=(r,e,t)=>{const n=r.map(o=>K(o));if(e===t)return typeof e=="bigint"?0n:0;const i=e<t?K([e,t]):K([t,e]);let a=typeof e=="bigint"?0n:0;for(const o of n){const l=o.lower>i.lower?o.lower:i.lower,u=o.upper<i.upper?o.upper:i.upper;if(l<u){const h=u-l;a=a+h}}return a};s.z.object({x:Ei.or(ps),y:Ni.or(ps)});const Rl=s.z.object({x:Ei,y:Ni}),xl=Object.freeze({x:"left",y:"top"}),Cl=(r,e)=>r.x===e.x&&r.y===e.y,vs=s.z.union([s.z.number(),pr,Sr,Ti,yl,wl]),Pl=(r,e)=>{if(typeof r=="string"){if(e===void 0)throw new Error("The y coordinate must be given.");return r==="x"?{x:e,y:0}:{x:0,y:e}}return typeof r=="number"?{x:r,y:e??r}:Array.isArray(r)?{x:r[0],y:r[1]}:"signedWidth"in r?{x:r.signedWidth,y:r.signedHeight}:"clientX"in r?{x:r.clientX,y:r.clientY}:"width"in r?{x:r.width,y:r.height}:{x:r.x,y:r.y}},Ts=Object.freeze({x:0,y:0}),Ht=s.z.union([s.z.number(),s.z.string()]);s.z.object({top:Ht,left:Ht,width:Ht,height:Ht});s.z.object({left:s.z.number(),top:s.z.number(),right:s.z.number(),bottom:s.z.number()});s.z.object({one:pr,two:pr,root:Rl});const Rn=(r,e,t=0,n=0,i)=>{const a={one:{...Ts},two:{...Ts},root:i??xl};if(typeof r=="number"){if(typeof e!="number")throw new Error("Box constructor called with invalid arguments");return a.one={x:r,y:e},a.two={x:a.one.x+t,y:a.one.y+n},a}return"one"in r&&"two"in r&&"root"in r?{...r,root:i??r.root}:("getBoundingClientRect"in r&&(r=r.getBoundingClientRect()),"left"in r?(a.one={x:r.left,y:r.top},a.two={x:r.right,y:r.bottom},a):(a.one=r,e==null?a.two={x:a.one.x+t,y:a.one.y+n}:typeof e=="number"?a.two={x:a.one.x+e,y:a.one.y+t}:"width"in e?a.two={x:a.one.x+e.width,y:a.one.y+e.height}:"signedWidth"in e?a.two={x:a.one.x+e.signedWidth,y:a.one.y+e.signedHeight}:a.two=e,a))},Vr=r=>{const e=Rn(r);return{lower:e.one.x,upper:e.two.x}},Fr=r=>{const e=Rn(r);return{lower:e.one.y,upper:e.two.y}},Dl=r=>typeof r!="object"||r==null?!1:"one"in r&&"two"in r&&"root"in r,jl=s.z.object({signedWidth:s.z.number(),signedHeight:s.z.number()});s.z.union([Ti,jl,pr,Sr]);var Ml=Object.defineProperty,Bl=(r,e,t)=>e in r?Ml(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,ge=(r,e,t)=>Bl(r,typeof e!="symbol"?e+"":e,t);const Ul=(r,e,t)=>e!==void 0&&r<e?e:t!==void 0&&r>t?t:r;s.z.object({offset:vs,scale:vs});s.z.object({offset:s.z.number(),scale:s.z.number()});const Zl=r=>(e,t,n,i)=>t==="dimension"?[e,n]:[e,i?n-r:n+r],Ll=r=>(e,t,n,i)=>[e,i?n/r:n*r],_l=r=>(e,t,n)=>{if(e===null)return[r,n];const{lower:i,upper:a}=e,{lower:o,upper:l}=r,u=a-i,h=l-o;if(t==="dimension")return[r,n*(h/u)];const y=(n-i)*(h/u)+o;return[r,y]},Yl=r=>(e,t,n)=>[r,n],ql=()=>(r,e,t)=>{if(r===null)throw new Error("cannot invert without bounds");if(e==="dimension")return[r,t];const{lower:n,upper:i}=r;return[r,i-(t-n)]},Wl=r=>(e,t,n)=>{const{lower:i,upper:a}=r;return n=Ul(n,i,a),[e,n]},wn=class vt{constructor(){ge(this,"ops",[]),ge(this,"currBounds",null),ge(this,"currType",null),ge(this,"reversed",!1),this.ops=[]}static translate(e){return new vt().translate(e)}static magnify(e){return new vt().magnify(e)}static scale(e,t){return new vt().scale(e,t)}translate(e){const t=this.new(),n=Zl(e);return n.type="translate",t.ops.push(n),t}magnify(e){const t=this.new(),n=Ll(e);return n.type="magnify",t.ops.push(n),t}scale(e,t){const n=K(e,t),i=this.new(),a=_l(n);return a.type="scale",i.ops.push(a),i}clamp(e,t){const n=K(e,t),i=this.new(),a=Wl(n);return a.type="clamp",i.ops.push(a),i}reBound(e,t){const n=K(e,t),i=this.new(),a=Yl(n);return a.type="re-bound",i.ops.push(a),i}invert(){const e=ql();e.type="invert";const t=this.new();return t.ops.push(e),t}pos(e){return this.exec("position",e)}dim(e){return this.exec("dimension",e)}new(){const e=new vt;return e.ops=this.ops.slice(),e.reversed=this.reversed,e}exec(e,t){return this.currBounds=null,this.ops.reduce(([n,i],a)=>a(n,e,i,this.reversed),[null,t])[1]}reverse(){const e=this.new();e.ops.reverse();const t=[];return e.ops.forEach((n,i)=>{if(n.type==="scale"||t.some(([o,l])=>i>=o&&i<=l))return;const a=e.ops.findIndex((o,l)=>o.type==="scale"&&l>i);a!==-1&&t.push([i,a])}),t.forEach(([n,i])=>{const a=e.ops.slice(n,i);a.unshift(e.ops[i]),e.ops.splice(n,i-n+1,...a)}),e.reversed=!e.reversed,e}get transform(){return{scale:this.dim(1),offset:this.pos(0)}}};ge(wn,"IDENTITY",new wn);let Os=wn;const zs=class fe{constructor(e=new Os,t=new Os,n=null){ge(this,"x"),ge(this,"y"),ge(this,"currRoot"),this.x=e,this.y=t,this.currRoot=n}static translate(e,t){return new fe().translate(e,t)}static translateX(e){return new fe().translateX(e)}static translateY(e){return new fe().translateY(e)}static clamp(e){return new fe().clamp(e)}static magnify(e){return new fe().magnify(e)}static scale(e){return new fe().scale(e)}static reBound(e){return new fe().reBound(e)}translate(e,t){const n=Pl(e,t),i=this.copy();return i.x=this.x.translate(n.x),i.y=this.y.translate(n.y),i}translateX(e){const t=this.copy();return t.x=this.x.translate(e),t}translateY(e){const t=this.copy();return t.y=this.y.translate(e),t}magnify(e){const t=this.copy();return t.x=this.x.magnify(e.x),t.y=this.y.magnify(e.y),t}scale(e){const t=this.copy();if(Dl(e)){const n=this.currRoot;return t.currRoot=e.root,n!=null&&!Cl(n,e.root)&&(n.x!==e.root.x&&(t.x=t.x.invert()),n.y!==e.root.y&&(t.y=t.y.invert())),t.x=t.x.scale(Vr(e)),t.y=t.y.scale(Fr(e)),t}return t.x=t.x.scale(e.width),t.y=t.y.scale(e.height),t}reBound(e){const t=this.copy();return t.x=this.x.reBound(Vr(e)),t.y=this.y.reBound(Fr(e)),t}clamp(e){const t=this.copy();return t.x=this.x.clamp(Vr(e)),t.y=this.y.clamp(Fr(e)),t}copy(){const e=new fe;return e.currRoot=this.currRoot,e.x=this.x,e.y=this.y,e}reverse(){const e=this.copy();return e.x=this.x.reverse(),e.y=this.y.reverse(),e}pos(e){return{x:this.x.pos(e.x),y:this.y.pos(e.y)}}dim(e){return{x:this.x.dim(e.x),y:this.y.dim(e.y)}}box(e){return Rn(this.pos(e.one),this.pos(e.two),0,0,this.currRoot??e.root)}get transform(){return{scale:this.dim({x:1,y:1}),offset:this.pos({x:0,y:0})}}};ge(zs,"IDENTITY",new zs);const Gl=s.z.bigint().or(s.z.string().transform(BigInt));var Vl=Object.defineProperty,Fl=(r,e,t)=>e in r?Vl(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,f=(r,e,t)=>Fl(r,typeof e!="symbol"?e+"":e,t);let Jl=(r,e=21)=>(t=e)=>{let n="",i=t|0;for(;i--;)n+=r[Math.random()*r.length|0];return n};const Kl="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",ki=Jl(Kl,11),Hl=Object.freeze(Object.defineProperty({__proto__:null,id:ki},Symbol.toStringTag,{value:"Module"})),Xl=s.z.enum(["static","dynamic"]),$i=(r,e)=>{const t=new I(e);if(![z.DAY,z.HOUR,z.MINUTE,z.SECOND,z.MILLISECOND,z.MICROSECOND,z.NANOSECOND].some(i=>i.equals(t)))throw new Error("Invalid argument for remainder. Must be an even TimeSpan or Timestamp");const n=r.valueOf()%t.valueOf();return r instanceof I?new I(n):new z(n)},C=class T{constructor(e,t="UTC"){if(f(this,"value"),f(this,"encodeValue",!0),e==null)this.value=T.now().valueOf();else if(e instanceof Date)this.value=BigInt(e.getTime())*T.MILLISECOND.valueOf();else if(typeof e=="string")this.value=T.parseDateTimeString(e,t).valueOf();else if(Array.isArray(e))this.value=T.parseDate(e);else{let n=BigInt(0);e instanceof Number&&(e=e.valueOf()),t==="local"&&(n=T.utcOffset.valueOf()),typeof e=="number"&&(isFinite(e)?e=Math.trunc(e):(isNaN(e)&&(e=0),e===1/0?e=T.MAX:e=T.MIN)),this.value=BigInt(e.valueOf())+n}}static parseDate([e=1970,t=1,n=1]){const i=new Date(e,t-1,n,0,0,0,0);return new T(BigInt(i.getTime())*T.MILLISECOND.valueOf()).truncate(T.DAY).valueOf()}encode(){return this.value.toString()}valueOf(){return this.value}static parseTimeString(e,t="UTC"){const[n,i,a]=e.split(":");let o="00",l="00";a!=null&&([o,l]=a.split("."));let u=T.hours(parseInt(n??"00")).add(T.minutes(parseInt(i??"00"))).add(T.seconds(parseInt(o??"00"))).add(T.milliseconds(parseInt(l??"00")));return t==="local"&&(u=u.add(T.utcOffset)),u.valueOf()}static parseDateTimeString(e,t="UTC"){if(!e.includes("/")&&!e.includes("-"))return T.parseTimeString(e,t);const n=new Date(e);return e.includes(":")||n.setUTCHours(0,0,0,0),new T(BigInt(n.getTime())*T.MILLISECOND.valueOf(),t).valueOf()}fString(e="ISO",t="UTC"){switch(e){case"ISODate":return this.toISOString(t).slice(0,10);case"ISOTime":return this.toISOString(t).slice(11,23);case"time":return this.timeString(!1,t);case"preciseTime":return this.timeString(!0,t);case"date":return this.dateString();case"preciseDate":return`${this.dateString()} ${this.timeString(!0,t)}`;case"dateTime":return`${this.dateString()} ${this.timeString(!1,t)}`;default:return this.toISOString(t)}}toISOString(e="UTC"){return e==="UTC"?this.date().toISOString():this.sub(T.utcOffset).date().toISOString()}timeString(e=!1,t="UTC"){const n=this.toISOString(t);return e?n.slice(11,23):n.slice(11,19)}dateString(){const e=this.date(),t=e.toLocaleString("default",{month:"short"}),n=e.toLocaleString("default",{day:"numeric"});return`${t} ${n}`}static get utcOffset(){return new z(BigInt(new Date().getTimezoneOffset())*T.MINUTE.valueOf())}static since(e){return new T().span(e)}date(){return new Date(this.milliseconds)}equals(e){return this.valueOf()===new T(e).valueOf()}span(e){return this.range(e).span}range(e){return new W(this,e).makeValid()}spanRange(e){return this.range(this.add(e)).makeValid()}get isZero(){return this.valueOf()===BigInt(0)}after(e){return this.valueOf()>new T(e).valueOf()}afterEq(e){return this.valueOf()>=new T(e).valueOf()}before(e){return this.valueOf()<new T(e).valueOf()}beforeEq(e){return this.valueOf()<=new T(e).valueOf()}add(e){return new T(this.valueOf()+BigInt(e.valueOf()))}sub(e){return new T(this.valueOf()-BigInt(e.valueOf()))}get hours(){return Number(this.valueOf())/Number(z.HOUR.valueOf())}get minutes(){return Number(this.valueOf())/Number(z.MINUTE.valueOf())}get days(){return Number(this.valueOf())/Number(z.DAY.valueOf())}get seconds(){return Number(this.valueOf())/Number(z.SECOND.valueOf())}get milliseconds(){return Number(this.valueOf())/Number(T.MILLISECOND.valueOf())}get year(){return this.date().getFullYear()}setYear(e){const t=this.date();return t.setFullYear(e),new T(t)}get month(){return this.date().getMonth()}setMonth(e){const t=this.date();return t.setMonth(e),new T(t)}get day(){return this.date().getDate()}setDay(e){const t=this.date();return t.setDate(e),new T(t)}get hour(){return this.date().getHours()}setHour(e){const t=this.date();return t.setHours(e),new T(t)}get minute(){return this.date().getMinutes()}setMinute(e){const t=this.date();return t.setMinutes(e),new T(t)}get second(){return this.date().getSeconds()}setSecond(e){const t=this.date();return t.setSeconds(e),new T(t)}get millisecond(){return this.date().getMilliseconds()}setMillisecond(e){const t=this.date();return t.setMilliseconds(e),new T(t)}toString(){return this.date().toISOString()}remainder(e){return $i(this,e)}get isToday(){return this.truncate(z.DAY).equals(T.now().truncate(z.DAY))}truncate(e){return this.sub(this.remainder(e))}static now(){return new T(new Date)}static max(...e){let t=T.MIN;for(const n of e){const i=new T(n);i.after(t)&&(t=i)}return t}static min(...e){let t=T.MAX;for(const n of e){const i=new T(n);i.before(t)&&(t=i)}return t}static nanoseconds(e){return new T(e)}static microseconds(e){return T.nanoseconds(e*1e3)}static milliseconds(e){return T.microseconds(e*1e3)}static seconds(e){return T.milliseconds(e*1e3)}static minutes(e){return T.seconds(e*60)}static hours(e){return T.minutes(e*60)}static days(e){return T.hours(e*24)}};f(C,"NANOSECOND",C.nanoseconds(1)),f(C,"MICROSECOND",C.microseconds(1)),f(C,"MILLISECOND",C.milliseconds(1)),f(C,"SECOND",C.seconds(1)),f(C,"MINUTE",C.minutes(1)),f(C,"HOUR",C.hours(1)),f(C,"DAY",C.days(1)),f(C,"MAX",new C((1n<<63n)-1n)),f(C,"MIN",new C(0)),f(C,"ZERO",new C(0)),f(C,"z",s.z.union([s.z.object({value:s.z.bigint()}).transform(r=>new C(r.value)),s.z.string().transform(r=>new C(BigInt(r))),s.z.instanceof(Number).transform(r=>new C(r)),s.z.number().transform(r=>new C(r)),s.z.instanceof(C)]));let I=C;const P=class N{constructor(e){f(this,"value"),f(this,"encodeValue",!0),typeof e=="number"&&(e=Math.trunc(e.valueOf())),this.value=BigInt(e.valueOf())}static fromSeconds(e){return e instanceof N?e:e instanceof nt?e.period:e instanceof I?new N(e):["number","bigint"].includes(typeof e)?N.seconds(e):new N(e)}static fromMilliseconds(e){return e instanceof N?e:e instanceof nt?e.period:e instanceof I?new N(e):["number","bigint"].includes(typeof e)?N.milliseconds(e):new N(e)}encode(){return this.value.toString()}valueOf(){return this.value}lessThan(e){return this.valueOf()<new N(e).valueOf()}greaterThan(e){return this.valueOf()>new N(e).valueOf()}lessThanOrEqual(e){return this.valueOf()<=new N(e).valueOf()}greaterThanOrEqual(e){return this.valueOf()>=new N(e).valueOf()}remainder(e){return $i(this,e)}truncate(e){return new N(BigInt(Math.trunc(Number(this.valueOf()/e.valueOf())))*e.valueOf())}toString(){const e=this.truncate(N.DAY),t=this.truncate(N.HOUR),n=this.truncate(N.MINUTE),i=this.truncate(N.SECOND),a=this.truncate(N.MILLISECOND),o=this.truncate(N.MICROSECOND),l=this.truncate(N.NANOSECOND),u=e,h=t.sub(e),y=n.sub(t),d=i.sub(n),j=a.sub(i),$=o.sub(a),te=l.sub(o);let U="";return u.isZero||(U+=`${u.days}d `),h.isZero||(U+=`${h.hours}h `),y.isZero||(U+=`${y.minutes}m `),d.isZero||(U+=`${d.seconds}s `),j.isZero||(U+=`${j.milliseconds}ms `),$.isZero||(U+=`${$.microseconds}µs `),te.isZero||(U+=`${te.nanoseconds}ns`),U.trim()}mult(e){return new N(this.valueOf()*BigInt(e))}get days(){return Number(this.valueOf())/Number(N.DAY.valueOf())}get hours(){return Number(this.valueOf())/Number(N.HOUR.valueOf())}get minutes(){return Number(this.valueOf())/Number(N.MINUTE.valueOf())}get seconds(){return Number(this.valueOf())/Number(N.SECOND.valueOf())}get milliseconds(){return Number(this.valueOf())/Number(N.MILLISECOND.valueOf())}get microseconds(){return Number(this.valueOf())/Number(N.MICROSECOND.valueOf())}get nanoseconds(){return Number(this.valueOf())}get isZero(){return this.valueOf()===BigInt(0)}equals(e){return this.valueOf()===new N(e).valueOf()}add(e){return new N(this.valueOf()+new N(e).valueOf())}sub(e){return new N(this.valueOf()-new N(e).valueOf())}static nanoseconds(e=1){return new N(e)}static microseconds(e=1){return N.nanoseconds(Be(e,1e3))}static milliseconds(e=1){return N.microseconds(Be(e,1e3))}static seconds(e=1){return N.milliseconds(Be(e,1e3))}static minutes(e=1){return N.seconds(Be(e,60))}static hours(e){return N.minutes(Be(e,60))}static days(e){return N.hours(Be(e,24))}};f(P,"NANOSECOND",P.nanoseconds(1)),f(P,"MICROSECOND",P.microseconds(1)),f(P,"MILLISECOND",P.milliseconds(1)),f(P,"SECOND",P.seconds(1)),f(P,"MINUTE",P.minutes(1)),f(P,"HOUR",P.hours(1)),f(P,"DAY",P.days(1)),f(P,"MAX",new P((1n<<63n)-1n)),f(P,"MIN",new P(0)),f(P,"ZERO",new P(0)),f(P,"z",s.z.union([s.z.object({value:s.z.bigint()}).transform(r=>new P(r.value)),s.z.string().transform(r=>new P(BigInt(r))),s.z.instanceof(Number).transform(r=>new P(r)),s.z.number().transform(r=>new P(r)),s.z.instanceof(P)]));let z=P;const Tt=class cr extends Number{constructor(e){e instanceof Number?super(e.valueOf()):super(e)}toString(){return`${this.valueOf()} Hz`}equals(e){return this.valueOf()===new cr(e).valueOf()}get period(){return z.seconds(1/this.valueOf())}sampleCount(e){return new z(e).seconds*this.valueOf()}byteCount(e,t){return this.sampleCount(e)*new F(t).valueOf()}span(e){return z.seconds(e/this.valueOf())}byteSpan(e,t){return this.span(e.valueOf()/t.valueOf())}static hz(e){return new cr(e)}static khz(e){return cr.hz(e*1e3)}};f(Tt,"z",s.z.union([s.z.number().transform(r=>new Tt(r)),s.z.instanceof(Number).transform(r=>new Tt(r)),s.z.instanceof(Tt)]));let nt=Tt;const q=class extends Number{constructor(e){e instanceof Number?super(e.valueOf()):super(e)}length(e){return e.valueOf()/this.valueOf()}size(e){return new st(e*this.valueOf())}};f(q,"UNKNOWN",new q(0)),f(q,"BIT128",new q(16)),f(q,"BIT64",new q(8)),f(q,"BIT32",new q(4)),f(q,"BIT16",new q(2)),f(q,"BIT8",new q(1)),f(q,"z",s.z.union([s.z.number().transform(r=>new q(r)),s.z.instanceof(Number).transform(r=>new q(r)),s.z.instanceof(q)]));let F=q;const ce=class lr{constructor(e,t){f(this,"start"),f(this,"end"),typeof e=="object"&&"start"in e?(this.start=new I(e.start),this.end=new I(e.end)):(this.start=new I(e),this.end=new I(t))}get span(){return new z(this.end.valueOf()-this.start.valueOf())}get isValid(){return this.start.valueOf()<=this.end.valueOf()}makeValid(){return this.isValid?this:this.swap()}get isZero(){return this.span.isZero}get numeric(){return{start:Number(this.start.valueOf()),end:Number(this.end.valueOf())}}swap(){return new lr(this.end,this.start)}equals(e){return this.start.equals(e.start)&&this.end.equals(e.end)}toString(){return`${this.start.toString()} - ${this.end.toString()}`}toPrettyString(){return`${this.start.fString("preciseDate")} - ${this.span.toString()}`}overlapsWith(e,t=z.ZERO){e=e.makeValid();const n=this.makeValid();if(this.equals(e))return!0;if(e.end.equals(n.start)||n.end.equals(e.start))return!1;const i=I.max(n.start,e.start),a=I.min(n.end,e.end);return a.before(i)?!1:new z(a.sub(i)).greaterThanOrEqual(t)}roughlyEquals(e,t){let n=this.start.sub(e.start).valueOf(),i=this.end.sub(e.end).valueOf();return n<0&&(n=-n),i<0&&(i=-i),n<=t.valueOf()&&i<=t.valueOf()}contains(e){return e instanceof lr?this.contains(e.start)&&this.contains(e.end):this.start.beforeEq(e)&&this.end.after(e)}boundBy(e){const t=new lr(this.start,this.end);return e.start.after(this.start)&&(t.start=e.start),e.start.after(this.end)&&(t.end=e.start),e.end.before(this.end)&&(t.end=e.end),e.end.before(this.start)&&(t.start=e.end),t}};f(ce,"MAX",new ce(I.MIN,I.MAX)),f(ce,"MIN",new ce(I.MAX,I.MIN)),f(ce,"ZERO",new ce(I.ZERO,I.ZERO)),f(ce,"z",s.z.union([s.z.object({start:I.z,end:I.z}).transform(r=>new ce(r.start,r.end)),s.z.instanceof(ce)]));let W=ce;const Ql=(r,e)=>r.start.before(e.start)?-1:r.start.after(e.start)?1:r.end.before(e.end)?-1:r.end.after(e.end)?1:0,p=class le extends String{constructor(e){if(e instanceof le||typeof e=="string"||typeof e.valueOf()=="string"){super(e.valueOf());return}const t=le.ARRAY_CONSTRUCTOR_DATA_TYPES.get(e.constructor.name);if(t!=null){super(t.valueOf());return}throw super(le.UNKNOWN.valueOf()),new Error(`unable to find data type for ${e.toString()}`)}get Array(){const e=le.ARRAY_CONSTRUCTORS.get(this.toString());if(e==null)throw new Error(`unable to find array constructor for ${this.valueOf()}`);return e}equals(e){return this.valueOf()===e.valueOf()}matches(...e){return e.some(t=>this.equals(t))}toString(){return this.valueOf()}get isVariable(){return this.equals(le.JSON)||this.equals(le.STRING)}get isNumeric(){return!this.isVariable&&!this.equals(le.UUID)}get isInteger(){return this.toString().startsWith("int")}get isFloat(){return this.toString().startsWith("float")}get density(){const e=le.DENSITIES.get(this.toString());if(e==null)throw new Error(`unable to find density for ${this.valueOf()}`);return e}canSafelyCastTo(e){return this.equals(e)?!0:this.isVariable&&!e.isVariable||!this.isVariable&&e.isVariable?!1:this.isFloat&&e.isInteger||this.isInteger&&e.isFloat?this.density.valueOf()<e.density.valueOf():this.isFloat&&e.isFloat||this.isInteger&&e.isInteger?this.density.valueOf()<=e.density.valueOf():!1}canCastTo(e){return this.isNumeric&&e.isNumeric?!0:this.equals(e)}checkArray(e){return e.constructor===this.Array}toJSON(){return this.toString()}get usesBigInt(){return le.BIG_INT_TYPES.some(e=>e.equals(this))}};f(p,"UNKNOWN",new p("unknown")),f(p,"FLOAT64",new p("float64")),f(p,"FLOAT32",new p("float32")),f(p,"INT64",new p("int64")),f(p,"INT32",new p("int32")),f(p,"INT16",new p("int16")),f(p,"INT8",new p("int8")),f(p,"UINT64",new p("uint64")),f(p,"UINT32",new p("uint32")),f(p,"UINT16",new p("uint16")),f(p,"UINT8",new p("uint8")),f(p,"BOOLEAN",p.UINT8),f(p,"TIMESTAMP",new p("timestamp")),f(p,"UUID",new p("uuid")),f(p,"STRING",new p("string")),f(p,"JSON",new p("json")),f(p,"ARRAY_CONSTRUCTORS",new Map([[p.UINT8.toString(),Uint8Array],[p.UINT16.toString(),Uint16Array],[p.UINT32.toString(),Uint32Array],[p.UINT64.toString(),BigUint64Array],[p.FLOAT32.toString(),Float32Array],[p.FLOAT64.toString(),Float64Array],[p.INT8.toString(),Int8Array],[p.INT16.toString(),Int16Array],[p.INT32.toString(),Int32Array],[p.INT64.toString(),BigInt64Array],[p.TIMESTAMP.toString(),BigInt64Array],[p.STRING.toString(),Uint8Array],[p.JSON.toString(),Uint8Array],[p.UUID.toString(),Uint8Array]])),f(p,"ARRAY_CONSTRUCTOR_DATA_TYPES",new Map([[Uint8Array.name,p.UINT8],[Uint16Array.name,p.UINT16],[Uint32Array.name,p.UINT32],[BigUint64Array.name,p.UINT64],[Float32Array.name,p.FLOAT32],[Float64Array.name,p.FLOAT64],[Int8Array.name,p.INT8],[Int16Array.name,p.INT16],[Int32Array.name,p.INT32],[BigInt64Array.name,p.INT64]])),f(p,"DENSITIES",new Map([[p.UINT8.toString(),F.BIT8],[p.UINT16.toString(),F.BIT16],[p.UINT32.toString(),F.BIT32],[p.UINT64.toString(),F.BIT64],[p.FLOAT32.toString(),F.BIT32],[p.FLOAT64.toString(),F.BIT64],[p.INT8.toString(),F.BIT8],[p.INT16.toString(),F.BIT16],[p.INT32.toString(),F.BIT32],[p.INT64.toString(),F.BIT64],[p.TIMESTAMP.toString(),F.BIT64],[p.STRING.toString(),F.UNKNOWN],[p.JSON.toString(),F.UNKNOWN],[p.UUID.toString(),F.BIT128]])),f(p,"ALL",[p.UNKNOWN,p.FLOAT64,p.FLOAT32,p.INT64,p.INT32,p.INT16,p.INT8,p.UINT64,p.UINT32,p.UINT16,p.UINT8,p.TIMESTAMP,p.UUID,p.STRING,p.JSON]),f(p,"BIG_INT_TYPES",[p.INT64,p.UINT64,p.TIMESTAMP]),f(p,"z",s.z.union([s.z.string().transform(r=>new p(r)),s.z.instanceof(p)]));let S=p;const V=class L extends Number{constructor(e){super(e.valueOf())}largerThan(e){return this.valueOf()>e.valueOf()}smallerThan(e){return this.valueOf()<e.valueOf()}add(e){return L.bytes(this.valueOf()+e.valueOf())}sub(e){return L.bytes(this.valueOf()-e.valueOf())}truncate(e){return new L(Math.trunc(this.valueOf()/e.valueOf())*e.valueOf())}remainder(e){return L.bytes(this.valueOf()%e.valueOf())}get gigabytes(){return this.valueOf()/L.GIGABYTE.valueOf()}get megabytes(){return this.valueOf()/L.MEGABYTE.valueOf()}get kilobytes(){return this.valueOf()/L.KILOBYTE.valueOf()}get terabytes(){return this.valueOf()/L.TERABYTE.valueOf()}toString(){const e=this.truncate(L.TERABYTE),t=this.truncate(L.GIGABYTE),n=this.truncate(L.MEGABYTE),i=this.truncate(L.KILOBYTE),a=this.truncate(L.BYTE),o=e,l=t.sub(e),u=n.sub(t),h=i.sub(n),y=a.sub(i);let d="";return o.isZero||(d+=`${o.terabytes}TB `),l.isZero||(d+=`${l.gigabytes}GB `),u.isZero||(d+=`${u.megabytes}MB `),h.isZero||(d+=`${h.kilobytes}KB `),(!y.isZero||d==="")&&(d+=`${y.valueOf()}B`),d.trim()}static bytes(e=1){return new L(e)}static kilobytes(e=1){return L.bytes(e.valueOf()*1e3)}static megabytes(e=1){return L.kilobytes(e.valueOf()*1e3)}static gigabytes(e=1){return L.megabytes(e.valueOf()*1e3)}static terabytes(e){return L.gigabytes(e.valueOf()*1e3)}get isZero(){return this.valueOf()===0}};f(V,"BYTE",new V(1)),f(V,"KILOBYTE",V.kilobytes(1)),f(V,"MEGABYTE",V.megabytes(1)),f(V,"GIGABYTE",V.gigabytes(1)),f(V,"TERABYTE",V.terabytes(1)),f(V,"ZERO",new V(0)),f(V,"z",s.z.union([s.z.number().transform(r=>new V(r)),s.z.instanceof(V)]));let st=V;s.z.union([s.z.instanceof(Uint8Array),s.z.instanceof(Uint16Array),s.z.instanceof(Uint32Array),s.z.instanceof(BigUint64Array),s.z.instanceof(Float32Array),s.z.instanceof(Float64Array),s.z.instanceof(Int8Array),s.z.instanceof(Int16Array),s.z.instanceof(Int32Array),s.z.instanceof(BigInt64Array)]);const Ai=r=>{const e=typeof r;return e==="string"||e==="number"||e==="boolean"||e==="bigint"||r instanceof I||r instanceof z||r instanceof Date},eu=(r,e,t,n=0)=>r.usesBigInt&&!e.usesBigInt?Number(t)-Number(n):!r.usesBigInt&&e.usesBigInt?BigInt(t.valueOf())-BigInt(n.valueOf()):zt(t,-n).valueOf(),tu=r=>r==null?!1:Array.isArray(r)||r instanceof ArrayBuffer||ArrayBuffer.isView(r)&&!(r instanceof DataView)||r instanceof Oe?!0:Ai(r),ve=-1,bn={[Symbol.iterator]:()=>bn,next:()=>({done:!0,value:void 0})},ru=s.z.string().transform(r=>new Uint8Array(atob(r).split("").map(e=>e.charCodeAt(0))).buffer),nu=s.z.union([s.z.null(),s.z.undefined()]).transform(()=>new Uint8Array().buffer),vn=10,Ot=class ue{constructor(e){f(this,"key",""),f(this,"isSynnaxSeries",!0),f(this,"dataType"),f(this,"sampleOffset"),f(this,"gl"),f(this,"_data"),f(this,"_timeRange"),f(this,"alignment",0n),f(this,"_cachedMin"),f(this,"_cachedMax"),f(this,"writePos",ve),f(this,"_refCount",0),f(this,"_cachedLength"),f(this,"_cachedIndexes"),tu(e)&&(e={data:e});const{dataType:t,timeRange:n,sampleOffset:i=0,glBufferUsage:a="static",alignment:o=0n,key:l=ki()}=e,u=e.data??[];if(u instanceof ue||typeof u=="object"&&"isSynnaxSeries"in u&&u.isSynnaxSeries===!0){const d=u;this.key=d.key,this.dataType=d.dataType,this.sampleOffset=d.sampleOffset,this.gl=d.gl,this._data=d._data,this._timeRange=d._timeRange,this.alignment=d.alignment,this._cachedMin=d._cachedMin,this._cachedMax=d._cachedMax,this.writePos=d.writePos,this._refCount=d._refCount,this._cachedLength=d._cachedLength;return}const h=Ai(u),y=Array.isArray(u);if(t!=null)this.dataType=new S(t);else{if(u instanceof ArrayBuffer)throw new Error("cannot infer data type from an ArrayBuffer instance when constructing a Series. Please provide a data type.");if(y||h){let d=u;if(!h){if(u.length===0)throw new Error("cannot infer data type from a zero length JS array when constructing a Series. Please provide a data type.");d=u[0]}if(typeof d=="string")this.dataType=S.STRING;else if(typeof d=="number")this.dataType=S.FLOAT64;else if(typeof d=="bigint")this.dataType=S.INT64;else if(typeof d=="boolean")this.dataType=S.BOOLEAN;else if(d instanceof I||d instanceof Date||d instanceof I)this.dataType=S.TIMESTAMP;else if(typeof d=="object")this.dataType=S.JSON;else throw new Error(`cannot infer data type of ${typeof d} when constructing a Series from a JS array`)}else this.dataType=new S(u)}if(!y&&!h)this._data=u;else{let d=h?[u]:u;const j=d[0];(j instanceof I||j instanceof Date||j instanceof z)&&(d=d.map($=>new I($).valueOf())),this.dataType.equals(S.STRING)?(this._cachedLength=d.length,this._data=new TextEncoder().encode(`${d.join(`
16
16
  `)}
17
17
  `).buffer):this.dataType.equals(S.JSON)?(this._cachedLength=d.length,this._data=new TextEncoder().encode(`${d.map($=>tt.encodeString($)).join(`
18
18
  `)}
@@ -22,20 +22,20 @@
22
22
  `)}
23
23
  `);return new ue({data:n,dataType:S.JSON,timeRange:t})}acquire(e){this._refCount++,e!=null&&this.updateGLBuffer(e)}release(){if(this._refCount--,this._refCount===0&&this.gl.control!=null)this.maybeGarbageCollectGLBuffer(this.gl.control);else if(this._refCount<0)throw new Error("cannot release an array with a negative reference count")}write(e){if(!e.dataType.equals(this.dataType))throw new Error("buffer must be of the same type as this array");return this.dataType.isVariable?this.writeVariable(e):this.writeFixed(e)}writeVariable(e){if(this.writePos===ve)return 0;const t=this.byteCapacity.valueOf()-this.writePos,n=e.subBytes(0,t);return this.writeToUnderlyingData(n),this.writePos+=n.byteLength.valueOf(),this._cachedLength!=null&&(this._cachedLength+=n.length,this.calculateCachedLength()),n.length}writeFixed(e){if(this.writePos===ve)return 0;const t=this.capacity-this.writePos,n=e.sub(0,t);return this.writeToUnderlyingData(n),this._cachedLength=void 0,this.maybeRecomputeMinMax(n),this.writePos+=n.length,n.length}writeToUnderlyingData(e){this.underlyingData.set(e.data,this.writePos)}get buffer(){return typeof this._data=="object"&&"buffer"in this._data?this._data.buffer:this._data}get underlyingData(){return new this.dataType.Array(this._data)}get data(){return this.writePos===ve?this.underlyingData:new this.dataType.Array(this._data,0,this.writePos)}toStrings(){if(!this.dataType.matches(S.STRING,S.UUID))throw new Error("cannot convert non-string series to strings");return new TextDecoder().decode(this.underlyingData).split(`
24
24
  `).slice(0,-1)}toUUIDs(){if(!this.dataType.equals(S.UUID))throw new Error("cannot convert non-uuid series to uuids");const e=S.UUID.density.valueOf(),t=Array(this.length);for(let n=0;n<this.length;n++){const i=this.underlyingData.slice(n*e,(n+1)*e),a=Array.from(new Uint8Array(i.buffer),o=>o.toString(16).padStart(2,"0")).join("").replace(/(.{8})(.{4})(.{4})(.{4})(.{12})/,"$1-$2-$3-$4-$5");t[n]=a}return t}parseJSON(e){if(!this.dataType.equals(S.JSON))throw new Error("cannot convert non-string series to strings");return new TextDecoder().decode(this.underlyingData).split(`
25
- `).slice(0,-1).map(t=>e.parse(tt.decodeString(t)))}get timeRange(){if(this._timeRange==null)throw new Error("time range not set on series");return this._timeRange}get byteCapacity(){return new st(this.underlyingData.byteLength)}get capacity(){return this.dataType.isVariable?this.byteCapacity.valueOf():this.dataType.density.length(this.byteCapacity)}get byteLength(){return this.writePos===ve?this.byteCapacity:this.dataType.isVariable?new st(this.writePos):this.dataType.density.size(this.writePos)}get length(){return this._cachedLength!=null?this._cachedLength:this.dataType.isVariable?this.calculateCachedLength():this.writePos===ve?this.data.length:this.writePos}calculateCachedLength(){if(!this.dataType.isVariable)throw new Error("cannot calculate length of a non-variable length data type");let e=0;const t=[0];return this.data.forEach((n,i)=>{n===vn&&(e++,t.push(i+1))}),this._cachedIndexes=t,this._cachedLength=e,e}convert(e,t=0){if(this.dataType.equals(e))return this;const n=new e.Array(this.length);for(let i=0;i<this.length;i++)n[i]=Ql(this.dataType,e,this.data[i],t);return new ue({data:n.buffer,dataType:e,timeRange:this._timeRange,sampleOffset:t,glBufferUsage:this.gl.bufferUsage,alignment:this.alignment})}calcRawMax(){if(this.length===0)return-1/0;if(this.dataType.equals(S.TIMESTAMP))this._cachedMax=this.data[this.data.length-1];else if(this.dataType.usesBigInt){const e=this.data;this._cachedMax=e.reduce((t,n)=>t>n?t:n)}else{const e=this.data;this._cachedMax=e.reduce((t,n)=>t>n?t:n)}return this._cachedMax}get max(){if(this.dataType.isVariable)throw new Error("cannot calculate maximum on a variable length data type");return this.writePos===0?-1/0:(this._cachedMax??(this._cachedMax=this.calcRawMax()),zt(this._cachedMax,this.sampleOffset))}calcRawMin(){if(this.length===0)return 1/0;if(this.dataType.equals(S.TIMESTAMP))this._cachedMin=this.data[0];else if(this.dataType.usesBigInt){const e=this.data;this._cachedMin=e.reduce((t,n)=>t<n?t:n)}else{const e=this.data;this._cachedMin=e.reduce((t,n)=>t<n?t:n)}return this._cachedMin}get min(){if(this.dataType.isVariable)throw new Error("cannot calculate minimum on a variable length data type");return this.writePos===0?1/0:(this._cachedMin??(this._cachedMin=this.calcRawMin()),zt(this._cachedMin,this.sampleOffset))}get bounds(){return K(Number(this.min),Number(this.max))}maybeRecomputeMinMax(e){if(this._cachedMin!=null){const t=e._cachedMin??e.calcRawMin();t<this._cachedMin&&(this._cachedMin=t)}if(this._cachedMax!=null){const t=e._cachedMax??e.calcRawMax();t>this._cachedMax&&(this._cachedMax=t)}}enrich(){this.max,this.min}get range(){return zt(this.max,-this.min)}atAlignment(e,t){const n=Number(e-this.alignment);if(n<0||n>=this.length){if(t===!0)throw new Error(`[series] - no value at index ${n}`);return}return this.at(n,t)}at(e,t){if(this.dataType.isVariable)return this.atVariable(e,t??!1);e<0&&(e=this.length+e);const n=this.data[e];if(n==null){if(t===!0)throw new Error(`[series] - no value at index ${e}`);return}return zt(n,this.sampleOffset)}atVariable(e,t){let n=0,i=0;if(this._cachedIndexes!=null)n=this._cachedIndexes[e],i=this._cachedIndexes[e+1]-1;else{e<0&&(e=this.length+e);for(let o=0;o<this.data.length;o++)if(this.data[o]===vn){if(e===0){i=o;break}n=o+1,e--}if(i===0&&(i=this.data.length),n>=i||e>0){if(t)throw new Error(`[series] - no value at index ${e}`);return}}const a=this.data.slice(n,i);return this.dataType.equals(S.STRING)?new TextDecoder().decode(a):mi(JSON.parse(new TextDecoder().decode(a)))}binarySearch(e){let t=0,n=this.length-1;const i=Bl(e);for(;t<=n;){const a=Math.floor((t+n)/2),o=i(this.at(a,!0),e);if(o===0)return a;o<0?t=a+1:n=a-1}return t}updateGLBuffer(e){if(this.gl.control=e,!this.dataType.equals(S.FLOAT32))throw new Error("Only FLOAT32 arrays can be used in WebGL");const{buffer:t,bufferUsage:n,prevBuffer:i}=this.gl;if(t==null&&(this.gl.buffer=e.createBuffer()),this.writePos!==i)if(e.bindBuffer(e.ARRAY_BUFFER,this.gl.buffer),this.writePos!==ve){i===0&&e.bufferData(e.ARRAY_BUFFER,this.byteCapacity.valueOf(),e.STATIC_DRAW);const a=this.dataType.density.size(i).valueOf(),o=this.underlyingData.slice(this.gl.prevBuffer,this.writePos);e.bufferSubData(e.ARRAY_BUFFER,a,o.buffer),this.gl.prevBuffer=this.writePos}else e.bufferData(e.ARRAY_BUFFER,this.buffer,n==="static"?e.STATIC_DRAW:e.DYNAMIC_DRAW),this.gl.prevBuffer=ve}as(e){if(e==="string"){if(!this.dataType.equals(S.STRING))throw new Error(`cannot convert series of type ${this.dataType.toString()} to string`);return this}if(e==="number"){if(!this.dataType.isNumeric)throw new Error(`cannot convert series of type ${this.dataType.toString()} to number`);return this}if(e==="bigint"){if(!this.dataType.equals(S.INT64))throw new Error(`cannot convert series of type ${this.dataType.toString()} to bigint`);return this}throw new Error(`cannot convert series to ${e}`)}get digest(){var e;return{key:this.key,dataType:this.dataType.toString(),sampleOffset:this.sampleOffset,alignment:{lower:Rs(this.alignmentBounds.lower),upper:Rs(this.alignmentBounds.upper)},timeRange:(e=this._timeRange)==null?void 0:e.toString(),length:this.length,capacity:this.capacity}}get memInfo(){return{key:this.key,length:this.length,byteLength:this.byteLength,glBuffer:this.gl.buffer!=null}}get alignmentBounds(){return K(this.alignment,this.alignment+BigInt(this.length))}maybeGarbageCollectGLBuffer(e){this.gl.buffer!=null&&(e.deleteBuffer(this.gl.buffer),this.gl.buffer=null,this.gl.prevBuffer=0,this.gl.control=null)}get glBuffer(){if(this.gl.buffer==null)throw new Error("gl buffer not initialized");return this.gl.prevBuffer!==this.writePos&&console.warn("buffer not updated"),this.gl.buffer}[Symbol.iterator](){if(this.dataType.isVariable){const e=new nu(this);return this.dataType.equals(S.JSON)?new su(e):e}return new iu(this)}slice(e,t){return this.sliceSub(!1,e,t)}sub(e,t){return this.sliceSub(!0,e,t)}subIterator(e,t){return new Es(this,e,t??this.length)}subAlignmentIterator(e,t){return new Es(this,Number(e-this.alignment),Number(t-this.alignment))}subBytes(e,t){if(e>=0&&(t==null||t>=this.byteLength.valueOf()))return this;const n=this.data.subarray(e,t);return new ue({data:n,dataType:this.dataType,timeRange:this._timeRange,sampleOffset:this.sampleOffset,glBufferUsage:this.gl.bufferUsage,alignment:this.alignment+BigInt(e)})}sliceSub(e,t,n){if(t<=0&&(n==null||n>=this.length))return this;let i;return e?i=this.data.subarray(t,n):i=this.data.slice(t,n),new ue({data:i,dataType:this.dataType,timeRange:this._timeRange,sampleOffset:this.sampleOffset,glBufferUsage:this.gl.bufferUsage,alignment:this.alignment+BigInt(t)})}reAlign(e){return new ue({data:this.buffer,dataType:this.dataType,timeRange:W.ZERO,sampleOffset:this.sampleOffset,glBufferUsage:"static",alignment:e})}};f(Ot,"crudeZ",s.z.object({timeRange:W.z.optional(),dataType:S.z,alignment:Wl.optional(),data:s.z.union([tu,ru,s.z.instanceof(ArrayBuffer),s.z.instanceof(Uint8Array)]),glBufferUsage:Hl.optional().default("static").optional()})),f(Ot,"z",Ot.crudeZ.transform(r=>new Ot(r)));let Oe=Ot,Es=class{constructor(e,t,n){f(this,"series"),f(this,"end"),f(this,"index"),this.series=e;const i=K(0,e.length);this.end=ws(i,n),this.index=ws(i,t)}next(){return this.index>=this.end?{done:!0,value:void 0}:{done:!1,value:this.series.at(this.index++,!0)}}[Symbol.iterator](){return this}};class nu{constructor(e){if(f(this,"series"),f(this,"index"),f(this,"decoder"),!e.dataType.isVariable)throw new Error("cannot create a variable series iterator for a non-variable series");this.series=e,this.index=0,this.decoder=new TextDecoder}next(){const e=this.index,t=this.series.data;for(;this.index<t.length&&t[this.index]!==vn;)this.index++;const n=this.index;return e===n?{done:!0,value:void 0}:(this.index++,{done:!1,value:this.decoder.decode(this.series.buffer.slice(e,n))})}[Symbol.iterator](){return this}}var Ns,Ss;class su{constructor(e){f(this,"wrapped"),f(this,Ns,"JSONSeriesIterator"),this.wrapped=e}next(){const e=this.wrapped.next();return e.done===!0?{done:!0,value:void 0}:{done:!1,value:tt.decodeString(e.value)}}[(Ss=Symbol.iterator,Ns=Symbol.toStringTag,Ss)](){return this}}var Is,ks;class iu{constructor(e){f(this,"series"),f(this,"index"),f(this,Is,"SeriesIterator"),this.series=e,this.index=0}next(){return this.index>=this.series.length?{done:!0,value:void 0}:{done:!1,value:this.series.at(this.index++,!0)}}[(ks=Symbol.iterator,Is=Symbol.toStringTag,ks)](){return this}}const zt=(r,e)=>typeof r=="bigint"&&typeof e=="bigint"||typeof r=="number"&&typeof e=="number"?r+e:e===0?r:r===0?e:Number(r)+Number(e);class Ri{constructor(e){if(f(this,"series"),e.length!==0){const t=e[0].dataType;for(let n=1;n<e.length;n++)if(!e[n].dataType.equals(t))throw new Error("[multi-series] - series must have the same data type")}this.series=e}as(e){if(!new S(e).equals(this.dataType))throw new Error(`cannot convert series of type ${this.dataType.toString()} to ${e.toString()}`);return this}get dataType(){return this.series.length===0?S.UNKNOWN:this.series[0].dataType}get timeRange(){return this.series.length===0?W.ZERO:new W(this.series[0].timeRange.start,this.series[this.series.length-1].timeRange.end)}get alignment(){return this.series.length===0?0n:this.series[0].alignment}get alignmentBounds(){return this.series.length===0?K(0n,0n):K(this.series[0].alignmentBounds.lower,this.series[this.series.length-1].alignmentBounds.upper)}push(e){this.series.push(e)}get length(){return this.series.reduce((e,t)=>e+t.length,0)}atAlignment(e,t){if(this.series.length===0){if(t)throw new Error(`[series] - no value at alignment ${e}`);return}for(const n of this.series)if(Kt(n.alignmentBounds,e))return n.atAlignment(e,t);if(t)throw new Error(`[series] - no value at alignment ${e}`)}at(e,t=!1){e<0&&(e=this.length+e);for(const n of this.series){if(e<n.length)return n.at(e,t);e-=n.length}if(t)throw new Error(`[series] - no value at index ${e}`)}subIterator(e,t){return new Jr(this,e,t??this.length)}subAlignmentIterator(e,t){if(e>=this.alignmentBounds.upper||t<=this.alignmentBounds.lower)return bn;let n=0;for(let a=0;a<this.series.length;a++){const o=this.series[a];if(e<o.alignment)break;if(e>=o.alignmentBounds.upper)n+=o.length;else if(Kt(o.alignmentBounds,e)){n+=Number(e-o.alignment);break}}let i=0;for(let a=0;a<this.series.length;a++){const o=this.series[a];if(t<o.alignment)break;if(t>=o.alignmentBounds.upper)i+=o.length;else if(Kt(o.alignmentBounds,t)){i+=Number(t-o.alignment);break}}return new Jr(this,n,i)}subAlignmentSpanIterator(e,t){if(e>=this.alignmentBounds.upper)return bn;let n=0;for(let i=0;i<this.series.length;i++){const a=this.series[i];if(e<a.alignment)break;if(e>=a.alignmentBounds.upper)n+=a.length;else if(Kt(a.alignmentBounds,e)){n+=Number(e-a.alignment);break}}return new Jr(this,n,n+t)}get byteLength(){return new st(this.series.reduce((e,t)=>e+t.byteLength.valueOf(),0))}get data(){const e=new this.dataType.Array(this.length);let t=0;for(const n of this.series)e.set(n.data,t),t+=n.length;return new this.dataType.Array(e.buffer)}traverseAlignment(e,t){const n=this.series.map(i=>i.alignmentBounds);return Tl(n,e,t)}distance(e,t){const n=this.series.map(i=>i.alignmentBounds);return Ol(n,e,t)}[Symbol.iterator](){return this.series.length===0?{next(){return{done:!0,value:void 0}}}:new au(this.series)}}var $s,As;class au{constructor(e){f(this,"series"),f(this,"seriesIndex"),f(this,"internal"),f(this,$s,"MultiSeriesIterator"),this.series=e,this.seriesIndex=0,this.internal=e[0][Symbol.iterator]()}next(){const e=this.internal.next();return e.done===!1?e:this.seriesIndex===this.series.length-1?{done:!0,value:void 0}:(this.internal=this.series[++this.seriesIndex][Symbol.iterator](),this.next())}[(As=Symbol.iterator,$s=Symbol.toStringTag,As)](){return this}}let Jr=class{constructor(e,t,n){f(this,"series"),f(this,"index"),f(this,"end"),this.series=e,this.end=n,this.index=t}next(){return this.index>=this.end?{done:!0,value:void 0}:{done:!1,value:this.series.at(this.index++,!0)}}[Symbol.iterator](){return this}};const Rs=r=>{const e=r>>32n,t=r&0xffffffffn;return{domain:e,sample:t}};s.z.object({key:s.z.string(),value:s.z.string()});var ou=Object.defineProperty,cu=(r,e,t)=>e in r?ou(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,ur=(r,e,t)=>cu(r,typeof e!="symbol"?e+"":e,t);let lu=class{constructor(e,t){ur(this,"handlers"),ur(this,"transform"),ur(this,"closer"),this.transform=e,this.handlers=t??new Map}onChange(e){return this.handlers.set(e,null),()=>this.handlers.delete(e)}notify(e){let t=e;if(this.transform!=null){const[n,i]=this.transform(e);if(!i)return;t=n}this.handlers.forEach((n,i)=>i(t))}setCloser(e){this.closer=e}async close(){var e;return await((e=this.closer)==null?void 0:e.call(this))}},uu=class{constructor(e){ur(this,"handlers"),this.handlers=e??new Map}onChange(e){return this.handlers.set(e,null),()=>this.handlers.delete(e)}notify(e){this.handlers.forEach((t,n)=>n(e))}};const Re=Object.freeze(Object.defineProperty({__proto__:null,BaseObserver:uu,Observer:lu},Symbol.toStringTag,{value:"Module"})),Mt=s.z.record(s.z.union([s.z.number(),s.z.string(),s.z.symbol()]),s.z.unknown()),hu=()=>typeof process<"u"&&process.versions!=null&&process.versions.node!=null?"node":typeof window>"u"||window.document===void 0?"webworker":"browser";hu();const du=["MacOS","Windows","Linux","Docker"];s.z.enum(du);var fu=Object.defineProperty,yu=(r,e,t)=>e in r?fu(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,Et=(r,e,t)=>yu(r,typeof e!="symbol"?e+"":e,t);const gu=(...r)=>r.map(xi).join(""),xi=r=>(r.endsWith("/")||(r+="/"),r.startsWith("/")&&(r=r.slice(1)),r),pu=r=>r.endsWith("/")?r.slice(0,-1):r,Tn=class On{constructor({host:e,port:t,protocol:n="",pathPrefix:i=""}){Et(this,"protocol"),Et(this,"host"),Et(this,"port"),Et(this,"path"),this.protocol=n,this.host=e,this.port=t,this.path=xi(i)}replace(e){return new On({host:e.host??this.host,port:e.port??this.port,protocol:e.protocol??this.protocol,pathPrefix:e.pathPrefix??this.path})}child(e){return new On({...this,pathPrefix:gu(this.path,e)})}toString(){return pu(`${this.protocol}://${this.host}:${this.port}/${this.path}`)}};Et(Tn,"UNKNOWN",new Tn({host:"unknown",port:0}));let mu=Tn;var wu=Object.defineProperty,bu=(r,e,t)=>e in r?wu(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,hr=(r,e,t)=>bu(r,typeof e!="symbol"?e+"":e,t);const $e=class extends Number{};hr($e,"Absolute",255),hr($e,"Default",1),hr($e,"z",s.z.union([s.z.instanceof($e),s.z.number().int().min(0).max(255).transform(r=>new $e(r)),s.z.instanceof(Number).transform(r=>new $e(r))]));let Ci=$e;const Pi=s.z.object({name:s.z.string(),key:s.z.string()}),vu=r=>s.z.object({subject:Pi,resource:r,authority:Ci.z}),Tu=(...r)=>e=>e.filter(t=>{let n=!1;return t.to!=null&&(n=r.includes(t.to.resource)),t.from!=null&&!n&&(n=r.includes(t.from.resource)),n}),it=Object.freeze(Object.defineProperty({__proto__:null,Authority:Ci,filterTransfersByChannelKey:Tu,stateZ:vu,subjectZ:Pi},Symbol.toStringTag,{value:"Module"})),Di=class Nt extends Error{constructor(){super(Nt.MESSAGE)}matches(e){return typeof e=="string"?e.includes(Nt.MESSAGE):e instanceof Nt||e.message.includes(Nt.MESSAGE)}};hr(Di,"MESSAGE","canceled");let Ou=Di;new Ou;const zn=s.z.string().regex(/^\d+\.\d+\.\d+$/),Bt=(r,e,t={})=>{t.checkMajor??(t.checkMajor=!0),t.checkMinor??(t.checkMinor=!0),t.checkPatch??(t.checkPatch=!0);const n=zn.parse(r),i=zn.parse(e),[a,o,l]=n.split(".").map(Number),[u,h,y]=i.split(".").map(Number);if(t.checkMajor){if(a<u)return Vr;if(a>u)return Fr}if(t.checkMinor){if(o<h)return Vr;if(o>h)return Fr}if(t.checkPatch){if(l<y)return Vr;if(l>y)return Fr}return Sr},zu=(r,e,t={})=>_l(Bt(r,e,t)),ji=(r,e,t={})=>Ll(Bt(r,e,t)),Eu=(r,e,t={})=>Zl(Bt(r,e,t)),Nu=({name:r,migrate:e})=>t=>{try{const n=e(t);return console.log(`${r} migrated: ${t.version} -> ${n.version}`),n}catch(n){throw console.log(`${r} failed to migrate from ${t.version}`),console.error(n),n}},Su=({name:r,migrations:e,targetSchema:t,defaultVersion:n,def:i})=>{const a=Object.keys(e).sort(Bt).pop();if(a==null)return h=>{if(h.version??(h.version=n),h.version!==i.version)return console.log(`${r} version ${h.version} is newer than latest version of ${i.version}.
25
+ `).slice(0,-1).map(t=>e.parse(tt.decodeString(t)))}get timeRange(){if(this._timeRange==null)throw new Error("time range not set on series");return this._timeRange}get byteCapacity(){return new st(this.underlyingData.byteLength)}get capacity(){return this.dataType.isVariable?this.byteCapacity.valueOf():this.dataType.density.length(this.byteCapacity)}get byteLength(){return this.writePos===ve?this.byteCapacity:this.dataType.isVariable?new st(this.writePos):this.dataType.density.size(this.writePos)}get length(){return this._cachedLength!=null?this._cachedLength:this.dataType.isVariable?this.calculateCachedLength():this.writePos===ve?this.data.length:this.writePos}calculateCachedLength(){if(!this.dataType.isVariable)throw new Error("cannot calculate length of a non-variable length data type");let e=0;const t=[0];return this.data.forEach((n,i)=>{n===vn&&(e++,t.push(i+1))}),this._cachedIndexes=t,this._cachedLength=e,e}convert(e,t=0){if(this.dataType.equals(e))return this;const n=new e.Array(this.length);for(let i=0;i<this.length;i++)n[i]=eu(this.dataType,e,this.data[i],t);return new ue({data:n.buffer,dataType:e,timeRange:this._timeRange,sampleOffset:t,glBufferUsage:this.gl.bufferUsage,alignment:this.alignment})}calcRawMax(){if(this.length===0)return-1/0;if(this.dataType.equals(S.TIMESTAMP))this._cachedMax=this.data[this.data.length-1];else if(this.dataType.usesBigInt){const e=this.data;this._cachedMax=e.reduce((t,n)=>t>n?t:n)}else{const e=this.data;this._cachedMax=e.reduce((t,n)=>t>n?t:n)}return this._cachedMax}get max(){if(this.dataType.isVariable)throw new Error("cannot calculate maximum on a variable length data type");return this.writePos===0?-1/0:(this._cachedMax??(this._cachedMax=this.calcRawMax()),zt(this._cachedMax,this.sampleOffset))}calcRawMin(){if(this.length===0)return 1/0;if(this.dataType.equals(S.TIMESTAMP))this._cachedMin=this.data[0];else if(this.dataType.usesBigInt){const e=this.data;this._cachedMin=e.reduce((t,n)=>t<n?t:n)}else{const e=this.data;this._cachedMin=e.reduce((t,n)=>t<n?t:n)}return this._cachedMin}get min(){if(this.dataType.isVariable)throw new Error("cannot calculate minimum on a variable length data type");return this.writePos===0?1/0:(this._cachedMin??(this._cachedMin=this.calcRawMin()),zt(this._cachedMin,this.sampleOffset))}get bounds(){return K(Number(this.min),Number(this.max))}maybeRecomputeMinMax(e){if(this._cachedMin!=null){const t=e._cachedMin??e.calcRawMin();t<this._cachedMin&&(this._cachedMin=t)}if(this._cachedMax!=null){const t=e._cachedMax??e.calcRawMax();t>this._cachedMax&&(this._cachedMax=t)}}enrich(){this.max,this.min}get range(){return zt(this.max,-this.min)}atAlignment(e,t){const n=Number(e-this.alignment);if(n<0||n>=this.length){if(t===!0)throw new Error(`[series] - no value at index ${n}`);return}return this.at(n,t)}at(e,t){if(this.dataType.isVariable)return this.atVariable(e,t??!1);e<0&&(e=this.length+e);const n=this.data[e];if(n==null){if(t===!0)throw new Error(`[series] - no value at index ${e}`);return}return zt(n,this.sampleOffset)}atVariable(e,t){let n=0,i=0;if(this._cachedIndexes!=null)n=this._cachedIndexes[e],i=this._cachedIndexes[e+1]-1;else{e<0&&(e=this.length+e);for(let o=0;o<this.data.length;o++)if(this.data[o]===vn){if(e===0){i=o;break}n=o+1,e--}if(i===0&&(i=this.data.length),n>=i||e>0){if(t)throw new Error(`[series] - no value at index ${e}`);return}}const a=this.data.slice(n,i);return this.dataType.equals(S.STRING)?new TextDecoder().decode(a):mi(JSON.parse(new TextDecoder().decode(a)))}binarySearch(e){let t=0,n=this.length-1;const i=ll(e);for(;t<=n;){const a=Math.floor((t+n)/2),o=i(this.at(a,!0),e);if(o===0)return a;o<0?t=a+1:n=a-1}return t}updateGLBuffer(e){if(this.gl.control=e,!this.dataType.equals(S.FLOAT32))throw new Error("Only FLOAT32 arrays can be used in WebGL");const{buffer:t,bufferUsage:n,prevBuffer:i}=this.gl;if(t==null&&(this.gl.buffer=e.createBuffer()),this.writePos!==i)if(e.bindBuffer(e.ARRAY_BUFFER,this.gl.buffer),this.writePos!==ve){i===0&&e.bufferData(e.ARRAY_BUFFER,this.byteCapacity.valueOf(),e.STATIC_DRAW);const a=this.dataType.density.size(i).valueOf(),o=this.underlyingData.slice(this.gl.prevBuffer,this.writePos);e.bufferSubData(e.ARRAY_BUFFER,a,o.buffer),this.gl.prevBuffer=this.writePos}else e.bufferData(e.ARRAY_BUFFER,this.buffer,n==="static"?e.STATIC_DRAW:e.DYNAMIC_DRAW),this.gl.prevBuffer=ve}as(e){if(e==="string"){if(!this.dataType.equals(S.STRING))throw new Error(`cannot convert series of type ${this.dataType.toString()} to string`);return this}if(e==="number"){if(!this.dataType.isNumeric)throw new Error(`cannot convert series of type ${this.dataType.toString()} to number`);return this}if(e==="bigint"){if(!this.dataType.equals(S.INT64))throw new Error(`cannot convert series of type ${this.dataType.toString()} to bigint`);return this}throw new Error(`cannot convert series to ${e}`)}get digest(){var e;return{key:this.key,dataType:this.dataType.toString(),sampleOffset:this.sampleOffset,alignment:{lower:Rs(this.alignmentBounds.lower),upper:Rs(this.alignmentBounds.upper)},timeRange:(e=this._timeRange)==null?void 0:e.toString(),length:this.length,capacity:this.capacity}}get memInfo(){return{key:this.key,length:this.length,byteLength:this.byteLength,glBuffer:this.gl.buffer!=null}}get alignmentBounds(){return K(this.alignment,this.alignment+BigInt(this.length))}maybeGarbageCollectGLBuffer(e){this.gl.buffer!=null&&(e.deleteBuffer(this.gl.buffer),this.gl.buffer=null,this.gl.prevBuffer=0,this.gl.control=null)}get glBuffer(){if(this.gl.buffer==null)throw new Error("gl buffer not initialized");return this.gl.prevBuffer!==this.writePos&&console.warn("buffer not updated"),this.gl.buffer}[Symbol.iterator](){if(this.dataType.isVariable){const e=new su(this);return this.dataType.equals(S.JSON)?new iu(e):e}return new au(this)}slice(e,t){return this.sliceSub(!1,e,t)}sub(e,t){return this.sliceSub(!0,e,t)}subIterator(e,t){return new Es(this,e,t??this.length)}subAlignmentIterator(e,t){return new Es(this,Number(e-this.alignment),Number(t-this.alignment))}subBytes(e,t){if(e>=0&&(t==null||t>=this.byteLength.valueOf()))return this;const n=this.data.subarray(e,t);return new ue({data:n,dataType:this.dataType,timeRange:this._timeRange,sampleOffset:this.sampleOffset,glBufferUsage:this.gl.bufferUsage,alignment:this.alignment+BigInt(e)})}sliceSub(e,t,n){if(t<=0&&(n==null||n>=this.length))return this;let i;return e?i=this.data.subarray(t,n):i=this.data.slice(t,n),new ue({data:i,dataType:this.dataType,timeRange:this._timeRange,sampleOffset:this.sampleOffset,glBufferUsage:this.gl.bufferUsage,alignment:this.alignment+BigInt(t)})}reAlign(e){return new ue({data:this.buffer,dataType:this.dataType,timeRange:W.ZERO,sampleOffset:this.sampleOffset,glBufferUsage:"static",alignment:e})}};f(Ot,"crudeZ",s.z.object({timeRange:W.z.optional(),dataType:S.z,alignment:Gl.optional(),data:s.z.union([ru,nu,s.z.instanceof(ArrayBuffer),s.z.instanceof(Uint8Array)]),glBufferUsage:Xl.optional().default("static").optional()})),f(Ot,"z",Ot.crudeZ.transform(r=>new Ot(r)));let Oe=Ot,Es=class{constructor(e,t,n){f(this,"series"),f(this,"end"),f(this,"index"),this.series=e;const i=K(0,e.length);this.end=bs(i,n),this.index=bs(i,t)}next(){return this.index>=this.end?{done:!0,value:void 0}:{done:!1,value:this.series.at(this.index++,!0)}}[Symbol.iterator](){return this}};class su{constructor(e){if(f(this,"series"),f(this,"index"),f(this,"decoder"),!e.dataType.isVariable)throw new Error("cannot create a variable series iterator for a non-variable series");this.series=e,this.index=0,this.decoder=new TextDecoder}next(){const e=this.index,t=this.series.data;for(;this.index<t.length&&t[this.index]!==vn;)this.index++;const n=this.index;return e===n?{done:!0,value:void 0}:(this.index++,{done:!1,value:this.decoder.decode(this.series.buffer.slice(e,n))})}[Symbol.iterator](){return this}}var Ns,Ss;class iu{constructor(e){f(this,"wrapped"),f(this,Ns,"JSONSeriesIterator"),this.wrapped=e}next(){const e=this.wrapped.next();return e.done===!0?{done:!0,value:void 0}:{done:!1,value:tt.decodeString(e.value)}}[(Ss=Symbol.iterator,Ns=Symbol.toStringTag,Ss)](){return this}}var Is,ks;class au{constructor(e){f(this,"series"),f(this,"index"),f(this,Is,"SeriesIterator"),this.series=e,this.index=0}next(){return this.index>=this.series.length?{done:!0,value:void 0}:{done:!1,value:this.series.at(this.index++,!0)}}[(ks=Symbol.iterator,Is=Symbol.toStringTag,ks)](){return this}}const zt=(r,e)=>typeof r=="bigint"&&typeof e=="bigint"||typeof r=="number"&&typeof e=="number"?r+e:e===0?r:r===0?e:Number(r)+Number(e);class Ri{constructor(e){if(f(this,"series"),e.length!==0){const t=e[0].dataType;for(let n=1;n<e.length;n++)if(!e[n].dataType.equals(t))throw new Error("[multi-series] - series must have the same data type")}this.series=e}as(e){if(!new S(e).equals(this.dataType))throw new Error(`cannot convert series of type ${this.dataType.toString()} to ${e.toString()}`);return this}get dataType(){return this.series.length===0?S.UNKNOWN:this.series[0].dataType}get timeRange(){return this.series.length===0?W.ZERO:new W(this.series[0].timeRange.start,this.series[this.series.length-1].timeRange.end)}get alignment(){return this.series.length===0?0n:this.series[0].alignment}get alignmentBounds(){return this.series.length===0?K(0n,0n):K(this.series[0].alignmentBounds.lower,this.series[this.series.length-1].alignmentBounds.upper)}push(e){this.series.push(e)}get length(){return this.series.reduce((e,t)=>e+t.length,0)}atAlignment(e,t){if(this.series.length===0){if(t)throw new Error(`[series] - no value at alignment ${e}`);return}for(const n of this.series)if(Kt(n.alignmentBounds,e))return n.atAlignment(e,t);if(t)throw new Error(`[series] - no value at alignment ${e}`)}at(e,t=!1){e<0&&(e=this.length+e);for(const n of this.series){if(e<n.length)return n.at(e,t);e-=n.length}if(t)throw new Error(`[series] - no value at index ${e}`)}subIterator(e,t){return new Jr(this,e,t??this.length)}subAlignmentIterator(e,t){if(e>=this.alignmentBounds.upper||t<=this.alignmentBounds.lower)return bn;let n=0;for(let a=0;a<this.series.length;a++){const o=this.series[a];if(e<o.alignment)break;if(e>=o.alignmentBounds.upper)n+=o.length;else if(Kt(o.alignmentBounds,e)){n+=Number(e-o.alignment);break}}let i=0;for(let a=0;a<this.series.length;a++){const o=this.series[a];if(t<o.alignment)break;if(t>=o.alignmentBounds.upper)i+=o.length;else if(Kt(o.alignmentBounds,t)){i+=Number(t-o.alignment);break}}return new Jr(this,n,i)}subAlignmentSpanIterator(e,t){if(e>=this.alignmentBounds.upper)return bn;let n=0;for(let i=0;i<this.series.length;i++){const a=this.series[i];if(e<a.alignment)break;if(e>=a.alignmentBounds.upper)n+=a.length;else if(Kt(a.alignmentBounds,e)){n+=Number(e-a.alignment);break}}return new Jr(this,n,n+t)}get byteLength(){return new st(this.series.reduce((e,t)=>e+t.byteLength.valueOf(),0))}get data(){const e=new this.dataType.Array(this.length);let t=0;for(const n of this.series)e.set(n.data,t),t+=n.length;return new this.dataType.Array(e.buffer)}traverseAlignment(e,t){const n=this.series.map(i=>i.alignmentBounds);return $l(n,e,t)}distance(e,t){const n=this.series.map(i=>i.alignmentBounds);return Al(n,e,t)}[Symbol.iterator](){return this.series.length===0?{next(){return{done:!0,value:void 0}}}:new ou(this.series)}}var $s,As;class ou{constructor(e){f(this,"series"),f(this,"seriesIndex"),f(this,"internal"),f(this,$s,"MultiSeriesIterator"),this.series=e,this.seriesIndex=0,this.internal=e[0][Symbol.iterator]()}next(){const e=this.internal.next();return e.done===!1?e:this.seriesIndex===this.series.length-1?{done:!0,value:void 0}:(this.internal=this.series[++this.seriesIndex][Symbol.iterator](),this.next())}[(As=Symbol.iterator,$s=Symbol.toStringTag,As)](){return this}}let Jr=class{constructor(e,t,n){f(this,"series"),f(this,"index"),f(this,"end"),this.series=e,this.end=n,this.index=t}next(){return this.index>=this.end?{done:!0,value:void 0}:{done:!1,value:this.series.at(this.index++,!0)}}[Symbol.iterator](){return this}};const Rs=r=>{const e=r>>32n,t=r&0xffffffffn;return{domain:e,sample:t}},cu=(r,e)=>{let t=null;return e===0?r:(...n)=>{t!==null&&(clearTimeout(t),t=null),t=setTimeout(()=>r(...n),e)}};s.z.object({key:s.z.string(),value:s.z.string()});var lu=Object.defineProperty,uu=(r,e,t)=>e in r?lu(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,ur=(r,e,t)=>uu(r,typeof e!="symbol"?e+"":e,t);let hu=class{constructor(e,t){ur(this,"handlers"),ur(this,"transform"),ur(this,"closer"),this.transform=e,this.handlers=t??new Map}onChange(e){return this.handlers.set(e,null),()=>this.handlers.delete(e)}notify(e){let t=e;if(this.transform!=null){const[n,i]=this.transform(e);if(!i)return;t=n}this.handlers.forEach((n,i)=>i(t))}setCloser(e){this.closer=e}async close(){var e;return await((e=this.closer)==null?void 0:e.call(this))}},du=class{constructor(e){ur(this,"handlers"),this.handlers=e??new Map}onChange(e){return this.handlers.set(e,null),()=>this.handlers.delete(e)}notify(e){this.handlers.forEach((t,n)=>n(e))}};const Re=Object.freeze(Object.defineProperty({__proto__:null,BaseObserver:du,Observer:hu},Symbol.toStringTag,{value:"Module"})),Mt=s.z.record(s.z.union([s.z.number(),s.z.string(),s.z.symbol()]),s.z.unknown()),fu=()=>typeof process<"u"&&process.versions!=null&&process.versions.node!=null?"node":typeof window>"u"||window.document===void 0?"webworker":"browser";fu();const yu=["MacOS","Windows","Linux","Docker"],gu=["macos","windows","linux","docker"],pu={macos:"MacOS",windows:"Windows",linux:"Linux",docker:"Docker"};s.z.enum(yu).or(s.z.enum(gu).transform(r=>pu[r]));var mu=Object.defineProperty,wu=(r,e,t)=>e in r?mu(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,Et=(r,e,t)=>wu(r,typeof e!="symbol"?e+"":e,t);const bu=(...r)=>r.map(xi).join(""),xi=r=>(r.endsWith("/")||(r+="/"),r.startsWith("/")&&(r=r.slice(1)),r),vu=r=>r.endsWith("/")?r.slice(0,-1):r,Tn=class On{constructor({host:e,port:t,protocol:n="",pathPrefix:i=""}){Et(this,"protocol"),Et(this,"host"),Et(this,"port"),Et(this,"path"),this.protocol=n,this.host=e,this.port=t,this.path=xi(i)}replace(e){return new On({host:e.host??this.host,port:e.port??this.port,protocol:e.protocol??this.protocol,pathPrefix:e.pathPrefix??this.path})}child(e){return new On({...this,pathPrefix:bu(this.path,e)})}toString(){return vu(`${this.protocol}://${this.host}:${this.port}/${this.path}`)}};Et(Tn,"UNKNOWN",new Tn({host:"unknown",port:0}));let Tu=Tn;var Ou=Object.defineProperty,zu=(r,e,t)=>e in r?Ou(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,hr=(r,e,t)=>zu(r,typeof e!="symbol"?e+"":e,t);const Eu=async r=>await new Promise(e=>setTimeout(e,z.fromMilliseconds(r).milliseconds)),Nu=s.z.object({interval:z.z.optional(),maxRetries:s.z.number().optional(),scale:s.z.number().optional()}),Su=(r={})=>{const e=r.sleepFn||Eu,t=r.maxRetries??5,n=r.scale??1;let i=0,a=new z(r.interval??z.milliseconds(1));return async()=>i>=t?!1:(await e(a),a=a.mult(n),i++,!0)},Iu=Object.freeze(Object.defineProperty({__proto__:null,breakerConfig:Nu,create:Su},Symbol.toStringTag,{value:"Module"})),$e=class extends Number{};hr($e,"Absolute",255),hr($e,"Default",1),hr($e,"z",s.z.union([s.z.instanceof($e),s.z.number().int().min(0).max(255).transform(r=>new $e(r)),s.z.instanceof(Number).transform(r=>new $e(r))]));let Ci=$e;const Pi=s.z.object({name:s.z.string(),key:s.z.string()}),ku=r=>s.z.object({subject:Pi,resource:r,authority:Ci.z}),$u=(...r)=>e=>e.filter(t=>{let n=!1;return t.to!=null&&(n=r.includes(t.to.resource)),t.from!=null&&!n&&(n=r.includes(t.from.resource)),n}),it=Object.freeze(Object.defineProperty({__proto__:null,Authority:Ci,filterTransfersByChannelKey:$u,stateZ:ku,subjectZ:Pi},Symbol.toStringTag,{value:"Module"})),Di=class Nt extends Error{constructor(){super(Nt.MESSAGE)}matches(e){return typeof e=="string"?e.includes(Nt.MESSAGE):e instanceof Nt||e.message.includes(Nt.MESSAGE)}};hr(Di,"MESSAGE","canceled");let Au=Di;new Au;const zn=s.z.string().regex(/^\d+\.\d+\.\d+$/),Bt=(r,e,t={})=>{t.checkMajor??(t.checkMajor=!0),t.checkMinor??(t.checkMinor=!0),t.checkPatch??(t.checkPatch=!0);const n=zn.parse(r),i=zn.parse(e),[a,o,l]=n.split(".").map(Number),[u,h,y]=i.split(".").map(Number);if(t.checkMajor){if(a<u)return qr;if(a>u)return Wr}if(t.checkMinor){if(o<h)return qr;if(o>h)return Wr}if(t.checkPatch){if(l<y)return qr;if(l>y)return Wr}return Nr},Ru=(r,e,t={})=>fl(Bt(r,e,t)),ji=(r,e,t={})=>dl(Bt(r,e,t)),xu=(r,e,t={})=>hl(Bt(r,e,t)),Cu=({name:r,migrate:e})=>t=>{try{const n=e(t);return console.log(`${r} migrated: ${t.version} -> ${n.version}`),n}catch(n){throw console.log(`${r} failed to migrate from ${t.version}`),console.error(n),n}},Pu=({name:r,migrations:e,targetSchema:t,defaultVersion:n,def:i})=>{const a=Object.keys(e).sort(Bt).pop();if(a==null)return h=>{if(h.version??(h.version=n),h.version!==i.version)return console.log(`${r} version ${h.version} is newer than latest version of ${i.version}.
26
26
  Returning default instead.
27
- `),i;try{return t!=null?t.parse(h):h}catch(y){return console.log(`${r} failed to parse default. Exiting with default`),console.error(y),i}};const o=Object.keys(e).length;let l=!1;const u=h=>{try{if(o===0||ji(h.version,a))return console.log(l?`${r} ${h.version} now up to date`:`${r} version ${h.version} is up to date with target version ${i.version}`),h;const y=h.version,d=e[y],j=d(h);return l=!0,u(j)}catch(y){return console.log(`${r} failed to migrate from ${h.version} to ${a}`),console.error(y),i}};return h=>{try{if(h.version==null)if(n!=null)console.log(`${r} version is null. Setting version to default of ${n}`),h.version=n;else return console.log(`${r} version is null and no default version set. Exiting with default`),i;return u(h)}catch(y){return console.log(`${r} failed to parse final result. Exiting with default`),console.error(y),i}}},xs=Object.freeze(Object.defineProperty({__proto__:null,compareSemVer:Bt,createMigration:Nu,migrator:Su,semVerNewer:ji,semVerOlder:Eu,semVerZ:zn,versionsEqual:zu},Symbol.toStringTag,{value:"Module"})),Iu=async r=>await new Promise(e=>setTimeout(e,z.fromMilliseconds(r).milliseconds)),ku=s.z.object({interval:z.z.optional(),maxRetries:s.z.number().optional(),scale:s.z.number().optional()}),$u=(r={})=>{const e=r.sleepFn||Iu,t=r.maxRetries??5,n=r.scale??1;let i=0,a=new z(r.interval??z.milliseconds(1));return async()=>i>=t?!1:(await e(a),a=a.mult(n),i++,!0)},Au=Object.freeze(Object.defineProperty({__proto__:null,breakerConfig:ku,create:$u},Symbol.toStringTag,{value:"Module"})),Ie="sy.",Le=class Le extends se{constructor(){super(...arguments);c(this,"type",Le.TYPE)}};c(Le,"TYPE",`${Ie}validation`),c(Le,"matches",Q(Le.TYPE));let B=Le;const _e=class _e extends B{constructor(t,n){super(`${t}: ${n}`);c(this,"type",_e.TYPE);c(this,"field");c(this,"message");this.field=t,this.message=n}};c(_e,"TYPE",`${B.TYPE}.field`),c(_e,"matches",Q(_e.TYPE));let mr=_e;const Ye=class Ye extends se{constructor(){super(...arguments);c(this,"type",Ye.TYPE)}};c(Ye,"TYPE",`${Ie}auth`),c(Ye,"matches",Q(Ye.TYPE));let xe=Ye;const qe=class qe extends xe{constructor(){super(...arguments);c(this,"type",qe.TYPE)}};c(qe,"TYPE",`${xe.TYPE}.invalid-token`),c(qe,"matches",Q(qe.TYPE));let At=qe;const We=class We extends se{constructor(t){super(`
27
+ `),i;try{return t!=null?t.parse(h):h}catch(y){return console.log(`${r} failed to parse default. Exiting with default`),console.error(y),i}};const o=Object.keys(e).length;let l=!1;const u=h=>{try{if(o===0||ji(h.version,a))return console.log(l?`${r} ${h.version} now up to date`:`${r} version ${h.version} is up to date with target version ${i.version}`),h;const y=h.version,d=e[y],j=d(h);return l=!0,u(j)}catch(y){return console.log(`${r} failed to migrate from ${h.version} to ${a}`),console.error(y),i}};return h=>{try{if(h.version==null)if(n!=null)console.log(`${r} version is null. Setting version to default of ${n}`),h.version=n;else return console.log(`${r} version is null and no default version set. Exiting with default`),i;return u(h)}catch(y){return console.log(`${r} failed to parse final result. Exiting with default`),console.error(y),i}}},xs=Object.freeze(Object.defineProperty({__proto__:null,compareSemVer:Bt,createMigration:Cu,migrator:Pu,semVerNewer:ji,semVerOlder:xu,semVerZ:zn,versionsEqual:Ru},Symbol.toStringTag,{value:"Module"})),Ie="sy.",Le=class Le extends se{constructor(){super(...arguments);c(this,"type",Le.TYPE)}};c(Le,"TYPE",`${Ie}validation`),c(Le,"matches",Q(Le.TYPE));let B=Le;const _e=class _e extends B{constructor(t,n){super(`${t}: ${n}`);c(this,"type",_e.TYPE);c(this,"field");c(this,"message");this.field=t,this.message=n}};c(_e,"TYPE",`${B.TYPE}.field`),c(_e,"matches",Q(_e.TYPE));let mr=_e;const Ye=class Ye extends se{constructor(){super(...arguments);c(this,"type",Ye.TYPE)}};c(Ye,"TYPE",`${Ie}auth`),c(Ye,"matches",Q(Ye.TYPE));let xe=Ye;const qe=class qe extends xe{constructor(){super(...arguments);c(this,"type",qe.TYPE)}};c(qe,"TYPE",`${xe.TYPE}.invalid-token`),c(qe,"matches",Q(qe.TYPE));let At=qe;const We=class We extends se{constructor(t){super(`
28
28
  Unexpected error encountered:
29
29
 
30
30
  ${t}
31
31
 
32
32
  Please report this to the Synnax team.
33
- `);c(this,"type",We.TYPE)}};c(We,"TYPE",`${Ie}unexpected`),c(We,"matches",Q(We.TYPE));let Ee=We;const Ge=class Ge extends se{constructor(){super(...arguments);c(this,"type",Ge.TYPE)}};c(Ge,"TYPE",`${Ie}query`),c(Ge,"matches",Q(Ge.TYPE));let re=Ge;const Ve=class Ve extends re{constructor(){super(...arguments);c(this,"type",Ve.TYPE)}};c(Ve,"TYPE",`${re.TYPE}.not_found`),c(Ve,"matches",Q(Ve.TYPE));let pe=Ve;const Fe=class Fe extends re{constructor(){super(...arguments);c(this,"type",Fe.TYPE)}};c(Fe,"TYPE",`${re.TYPE}.multiple_results`),c(Fe,"matches",Q(Fe.TYPE));let me=Fe;const Je=class Je extends se{constructor(t,n){super(t);c(this,"type",Je.TYPE);c(this,"path");this.path=n}};c(Je,"TYPE",`${Ie}route`),c(Je,"matches",Q(Je.TYPE));let Rt=Je;const Ke=class Ke extends se{constructor(){super(...arguments);c(this,"type",Ke.TYPE)}};c(Ke,"TYPE",`${Ie}control`),c(Ke,"matches",Q(Ke.TYPE));let at=Ke;const He=class He extends at{constructor(){super(...arguments);c(this,"type",He.TYPE)}};c(He,"TYPE",`${at.TYPE}.unauthorized`),c(He,"matches",Q(He.TYPE));let wr=He;const Xe=class Xe extends se{constructor(){super(...arguments);c(this,"type",Xe.TYPE)}};c(Xe,"TYPE",`${Ie}contiguity`),c(Xe,"matches",Q(Xe.TYPE));let En=Xe;const Ru=r=>{if(!r.type.startsWith(Ie))return null;if(r.type.startsWith(B.TYPE)){if(r.type===mr.TYPE){const e=r.data.split(": ");return e.length<2?new B(r.data):new mr(e[0],e[1])}return new B(r.data)}return r.type.startsWith(xe.TYPE)?r.type.startsWith(At.TYPE)?new At(r.data):new xe(r.data):r.type.startsWith(Ee.TYPE)?new Ee(r.data):r.type.startsWith(re.TYPE)?r.type.startsWith(pe.TYPE)?new pe(r.data):r.type.startsWith(me.TYPE)?new me(r.data):new re(r.data):r.type.startsWith(at.TYPE)?r.type.startsWith(wr.TYPE)?new wr(r.data):new at(r.data):r.type.startsWith(Rt.TYPE)?new Rt(r.data,r.data):new Ee(r.data)},xu=()=>{throw new Error("Not implemented")};ci({encode:xu,decode:Ru});const Cu=async(r,e)=>{const[t,n]=await e(r);return n==null?[t,n]:n instanceof Se?[t,new Se({message:`Cannot reach cluster at ${n.url.host}:${n.url.port}`,url:n.url})]:[t,n]};class xn{constructor(e,t){c(this,"key");c(this,"name");this.key=t,this.name=e}get ontologyID(){return new O({type:"group",key:this.key})}}const Cn=s.z.string().uuid(),Pn=s.z.object({key:Cn,name:s.z.string()}),Pu=r=>{const e=b(r);if(e.length===0)throw new Error("No groups specified");const t=Cn.safeParse(e[0]).success;return{single:!Array.isArray(r),variant:t?"keys":"names",normalized:e,actual:r}},Mi="group",Du=r=>new O({type:Mi,key:r}),Ut=s.z.union([s.z.literal("label"),s.z.literal("log"),s.z.literal("allow_all"),s.z.literal("builtin"),s.z.literal("cluster"),s.z.literal("channel"),s.z.literal("node"),s.z.literal("group"),s.z.literal("range"),s.z.literal("framer"),s.z.literal("range-alias"),s.z.literal("user"),s.z.literal("workspace"),s.z.literal("schematic"),s.z.literal("lineplot"),s.z.literal("rack"),s.z.literal("device"),s.z.literal("task"),s.z.literal("policy"),s.z.literal("table")]),ju="builtin",Mu="cluster",Bu="node",H=s.z.object({type:Ut,key:s.z.string()}),Bi=s.z.string().transform(r=>{const[e,t]=r.split(":");return{type:Ut.parse(e),key:t??""}}),Ue=s.z.union([Bi,H]),Qe=class Qe{constructor(e){c(this,"type");c(this,"key");if(e instanceof Qe){this.type=e.type,this.key=e.key;return}if(typeof e=="string"){const[t,n]=e.split(":");this.type=t,this.key=n??"";return}this.type=e.type,this.key=e.key}toString(){return`${this.type}:${this.key}`}isType(){return this.key===""}matchesType(e){return this.type===e&&this.isType()}get payload(){return{type:this.type,key:this.key}}};c(Qe,"z",s.z.union([s.z.instanceof(Qe),Ue.transform(e=>new Qe(e))]));let O=Qe;const Uu=new O({type:"builtin",key:"root"}),Ui=s.z.object({type:s.z.number()}),Zi=s.z.object({type:Ut,fields:s.z.record(Ui)}),Li=s.z.object({id:O.z,name:s.z.string(),schema:Zi.optional().nullable(),data:s.z.record(s.z.unknown()).optional().nullable()}).transform(r=>({key:r.id.toString(),...r})),Zu=s.z.object({from:O.z,type:s.z.string(),to:O.z}),Nn=r=>{const[e,t,n]=r.split("->");return{from:new O(e),type:t,to:new O(n)}},Lu=s.z.object({group:Pn}),_u=s.z.object({parent:H,key:s.z.string().uuid().optional(),name:s.z.string()}),Yu=s.z.object({key:s.z.string(),name:s.z.string()}),qu=s.z.object({keys:s.z.array(s.z.string())});var ne;let Wu=(ne=class{constructor(e){c(this,"client");this.client=e}async create(e,t,n){return(await w(this.client,ne.ENDPOINT,{parent:e,name:t,key:n},_u,Lu)).group}async rename(e,t){await w(this.client,ne.ENDPOINT_RENAME,{key:e,name:t},Yu,s.z.object({}))}async delete(e){await w(this.client,ne.ENDPOINT_DELETE,{keys:e},qu,s.z.object({}))}},c(ne,"ENDPOINT","/ontology/create-group"),c(ne,"ENDPOINT_RENAME","/ontology/rename-group"),c(ne,"ENDPOINT_DELETE","/ontology/delete-group"),ne),_i=class{constructor(e){c(this,"creator");this.creator=new Wu(e)}async create(e,t,n){return this.sugar(await this.creator.create(e,t,n))}async rename(e,t){return await this.creator.rename(e,t)}async delete(...e){return await this.creator.delete(e)}sugar(e){return new xn(e.name,e.key)}};const Gu=Object.freeze(Object.defineProperty({__proto__:null,Client:_i,Group:xn,ONTOLOGY_TYPE:Mi,analyzeParams:Pu,groupZ:Pn,keyZ:Cn,ontologyID:Du},Symbol.toStringTag,{value:"Module"})),Kr={ADD_CHILDREN:"/ontology/add-children",REMOVE_CHILDREN:"/ontology/remove-children",MOVE_CHILDREN:"/ontology/move-children"},Cs=s.z.object({id:H,children:H.array()}),Vu=s.z.object({from:H,to:H,children:H.array()});let Fu=class{constructor(e){c(this,"client");this.client=e}async addChildren(e,...t){await w(this.client,Kr.ADD_CHILDREN,{id:new O(e).payload,children:t.map(n=>new O(n).payload)},Cs,s.z.object({}))}async removeChildren(e,...t){await w(this.client,Kr.REMOVE_CHILDREN,{id:new O(e).payload,children:t.map(n=>new O(n).payload)},Cs,s.z.object({}))}async moveChildren(e,t,...n){const i={from:new O(e).payload,to:new O(t).payload,children:n.map(a=>new O(a).payload)};await w(this.client,Kr.MOVE_CHILDREN,i,Vu,s.z.object({}))}};const Ju="/ontology/retrieve",Ku=s.z.object({ids:H.array().optional(),children:s.z.boolean().optional(),parents:s.z.boolean().optional(),includeSchema:s.z.boolean().optional(),excludeFieldData:s.z.boolean().optional(),term:s.z.string().optional(),limit:s.z.number().optional(),offset:s.z.number().optional(),types:Ut.array().optional()}),Hu=s.z.object({resources:Li.array()}),dr=r=>b(r).map(e=>new O(e).payload);let Yi=class{constructor(e,t){c(this,"type","ontology");c(this,"groups");c(this,"client");c(this,"writer");c(this,"framer");this.client=e,this.writer=new Fu(e),this.groups=new _i(e),this.framer=t}async search(e,t){return await this.execRetrieve({term:e,...t})}async retrieve(e,t){const n=await this.execRetrieve({ids:dr(e),...t});if(Array.isArray(e))return n;if(n.length===0)throw new re(`No resource found with ID ${e.toString()}`);return n[0]}async page(e,t,n){return await this.execRetrieve({offset:e,limit:t,...n})}async retrieveChildren(e,t){return await this.execRetrieve({ids:dr(e),children:!0,...t})}async retrieveParents(e,t){return await this.execRetrieve({ids:dr(e),parents:!0,...t})}async addChildren(e,...t){return await this.writer.addChildren(e,...t)}async removeChildren(e,...t){return await this.writer.removeChildren(e,...t)}async moveChildren(e,t,...n){return await this.writer.moveChildren(e,t,...n)}async openChangeTracker(){return await Zt.open(this.framer,this)}async openDependentTracker(e){return await Ir.open(e,this.framer,this)}newSearcherWithOptions(e){return{type:this.type,search:t=>this.search(t,e),retrieve:t=>this.retrieve(t,e),page:(t,n)=>this.page(t,n,e)}}async execRetrieve(e){const{resources:t}=await w(this.client,Ju,e,Ku,Hu);return t}};const Ps="sy_ontology_resource_set",Ds="sy_ontology_resource_delete",js="sy_ontology_relationship_set",Ms="sy_ontology_relationship_delete";class Zt{constructor(e,t){c(this,"relationships");c(this,"resources");c(this,"resourceObs");c(this,"relationshipObs");c(this,"streamer");c(this,"client");c(this,"closePromise");this.relationshipObs=new Re.Observer,this.relationships=this.relationshipObs,this.resourceObs=new Re.Observer,this.resources=this.resourceObs,this.client=t,this.streamer=e,this.closePromise=this.start()}async close(){this.streamer.close(),await this.closePromise}async start(){for await(const e of this.streamer)await this.update(e)}async update(e){const t=await this.parseResourceSets(e),n=this.parseResourceDeletes(e);t.concat(n).length>0&&this.resourceObs.notify(t.concat(n));const a=this.parseRelationshipSets(e),o=this.parseRelationshipDeletes(e);a.concat(o).length>0&&this.relationshipObs.notify(a.concat(o))}parseRelationshipSets(e){const t=e.get(js);return t.length===0?[]:Array.from(t.as("string")).map(n=>({variant:"set",key:Nn(n),value:void 0}))}parseRelationshipDeletes(e){const t=e.get(Ms);return t.length===0?[]:Array.from(t.as("string")).map(n=>({variant:"delete",key:Nn(n)}))}async parseResourceSets(e){const t=e.get(Ps);if(t.length===0)return[];const n=Array.from(t.as("string")).map(i=>new O(i));try{return(await this.client.retrieve(n)).map(a=>({variant:"set",key:a.id,value:a}))}catch(i){if(i instanceof re)return[];throw i}}parseResourceDeletes(e){const t=e.get(Ds);return t.length===0?[]:Array.from(t.as("string")).map(n=>({variant:"delete",key:new O(n)}))}static async open(e,t){const n=await e.openStreamer([Ps,Ds,js,Ms]);return new Zt(n,t)}}const Bs=r=>r==="from"?"to":"from";class Ir extends Re.Observer{constructor({target:t,dependents:n,relationshipType:i="parent",relationshipDirection:a="from",resourceType:o},l,u){super();c(this,"internal");c(this,"target");c(this,"relDir");c(this,"resourceType");c(this,"dependents");c(this,"client");c(this,"relType");c(this,"handleResourceChange",t=>{this.dependents=this.dependents.map(n=>{const i=t.find(a=>a.key.toString()==n.id.toString());return i==null||i.variant==="delete"?n:i.value}),this.notify(this.dependents)});c(this,"handleRelationshipChange",t=>{const n=t.filter(a=>a.variant==="delete"&&a.key[this.relDir].toString()===this.target.toString()&&(this.resourceType==null||a.key[Bs(this.relDir)].type===this.resourceType));this.dependents=this.dependents.filter(a=>!n.some(o=>o.key.to.toString()===a.id.toString()&&o.key.type===this.relType));const i=t.filter(a=>a.variant==="set"&&a.key.type===this.relType&&a.key[this.relDir].toString()===this.target.toString()&&(this.resourceType==null||a.key[Bs(this.relDir)].type===this.resourceType));if(i.length===0)return this.notify(this.dependents);this.client.retrieve(i.map(a=>a.key.to)).then(a=>{this.dependents=this.dependents.concat(a),this.notify(this.dependents)})});this.resourceType=o,this.internal=l,this.target=t,this.dependents=n,this.resourceType!=null&&(this.dependents=this.dependents.filter(h=>h.id.type===this.resourceType)),this.client=u,this.relType=i,this.relDir=a,this.internal.resources.onChange(this.handleResourceChange),this.internal.relationships.onChange(this.handleRelationshipChange)}static async open(t,n,i){const a=await Zt.open(n,i);return new Ir(t,a,i)}async close(){await this.internal.close()}}const Xu=Object.freeze(Object.defineProperty({__proto__:null,BUILTIN_TYPE:ju,CLUSTER_TYPE:Mu,ChangeTracker:Zt,Client:Yi,DependentTracker:Ir,ID:O,NODE_TYPE:Bu,Root:Uu,crudeIDZ:Ue,idZ:H,parseIDs:dr,parseRelationship:Nn,relationshipSchemaZ:Zu,resourceSchemaZ:Li,resourceTypeZ:Ut,schemaFieldZ:Ui,schemaZ:Zi,stringIDZ:Bi},Symbol.toStringTag,{value:"Module"})),X=r=>s.z.union([s.z.null().transform(()=>[]),r.array()]),Lt=s.z.string().uuid(),qi=s.z.object({key:Lt.optional(),subjects:Ue.array().or(Ue),objects:Ue.array().or(Ue),actions:gr.array().or(gr)}),kr=s.z.object({key:Lt,subjects:X(H),objects:X(H),actions:X(gr)}),Wi="policy",Qu=r=>new O({type:Wi,key:r}),Gi="allow_all",eh=new O({type:Gi,key:""}),th=s.z.object({keys:Lt.array().optional(),subjects:H.array().optional()}),rh=s.z.object({policies:X(kr)}),nh="/access/policy/retrieve";let sh=class{constructor(e){c(this,"client");this.client=e}async retrieve(e){return(await w(this.client,nh,e,th,rh)).policies}};const ih=s.z.object({policies:kr.partial({key:!0}).array()}),ah=s.z.object({policies:kr.array()}),oh=s.z.object({keys:Lt.array()}),ch=s.z.object({}),lh="/access/policy/create",uh="/access/policy/delete";let hh=class{constructor(e){c(this,"client");this.client=e}async create(e){const n=qi.array().parse(b(e)).map(a=>({objects:b(a.objects),actions:b(a.actions),subjects:b(a.subjects)}));return(await w(this.client,lh,{policies:n},ih,ah)).policies}async delete(e){await w(this.client,uh,{keys:b(e)},oh,ch)}},Vi=class{constructor(e){c(this,"retriever");c(this,"writer");this.retriever=new sh(e),this.writer=new hh(e)}async create(e){const t=Array.isArray(e),n=await this.writer.create(e);return t?n:n[0]}async retrieve(e){const t=Array.isArray(e),n=await this.retriever.retrieve({keys:b(e)});return t?n:n[0]}async retrieveFor(e){const t=b(e).map(n=>new O(n).payload);return await this.retriever.retrieve({subjects:t})}async delete(e){await this.writer.delete(e)}};const dh=Object.freeze(Object.defineProperty({__proto__:null,ALLOW_ALL_ONTOLOGY_ID:eh,ALLOW_ALL_ONTOLOGY_TYPE:Gi,Client:Vi,ONTOLOGY_TYPE:Wi,keyZ:Lt,newPolicyZ:qi,ontologyID:Qu,policyZ:kr},Symbol.toStringTag,{value:"Module"}));let Fi=class{constructor(e){c(this,"policy");this.policy=new Vi(e)}};const fh=Object.freeze(Object.defineProperty({__proto__:null,ALL_ACTION:Gc,CREATE_ACTION:Vc,Client:Fi,DELETE_ACTION:Fc,RETRIEVE_ACTION:Jc,UPDATE_ACTION:Kc,actionZ:gr},Symbol.toStringTag,{value:"Module"})),ke=s.z.number(),_t=s.z.object({name:s.z.string(),key:s.z.number(),rate:nt.z,dataType:S.z,leaseholder:s.z.number(),index:s.z.number(),isIndex:s.z.boolean(),internal:s.z.boolean(),virtual:s.z.boolean(),alias:s.z.string().optional()}),Ji=_t.extend({key:s.z.number().optional(),leaseholder:s.z.number().optional(),index:s.z.number().optional(),rate:nt.z.optional().default(0),isIndex:s.z.boolean().optional(),internal:s.z.boolean().optional().default(!1),virtual:s.z.boolean().optional().default(!1)}),Ki="channel",yh=r=>new O({type:Ki,key:r.toString()}),gh=new Error("request for lock canceled");var ph=function(r,e,t,n){function i(a){return a instanceof t?a:new t(function(o){o(a)})}return new(t||(t=Promise))(function(a,o){function l(y){try{h(n.next(y))}catch(d){o(d)}}function u(y){try{h(n.throw(y))}catch(d){o(d)}}function h(y){y.done?a(y.value):i(y.value).then(l,u)}h((n=n.apply(r,e||[])).next())})};class mh{constructor(e,t=gh){this._value=e,this._cancelError=t,this._queue=[],this._weightedWaiters=[]}acquire(e=1,t=0){if(e<=0)throw new Error(`invalid weight ${e}: must be positive`);return new Promise((n,i)=>{const a={resolve:n,reject:i,weight:e,priority:t},o=Hi(this._queue,l=>t<=l.priority);o===-1&&e<=this._value?this._dispatchItem(a):this._queue.splice(o+1,0,a)})}runExclusive(e){return ph(this,arguments,void 0,function*(t,n=1,i=0){const[a,o]=yield this.acquire(n,i);try{return yield t(a)}finally{o()}})}waitForUnlock(e=1,t=0){if(e<=0)throw new Error(`invalid weight ${e}: must be positive`);return this._couldLockImmediately(e,t)?Promise.resolve():new Promise(n=>{this._weightedWaiters[e-1]||(this._weightedWaiters[e-1]=[]),wh(this._weightedWaiters[e-1],{resolve:n,priority:t})})}isLocked(){return this._value<=0}getValue(){return this._value}setValue(e){this._value=e,this._dispatchQueue()}release(e=1){if(e<=0)throw new Error(`invalid weight ${e}: must be positive`);this._value+=e,this._dispatchQueue()}cancel(){this._queue.forEach(e=>e.reject(this._cancelError)),this._queue=[]}_dispatchQueue(){for(this._drainUnlockWaiters();this._queue.length>0&&this._queue[0].weight<=this._value;)this._dispatchItem(this._queue.shift()),this._drainUnlockWaiters()}_dispatchItem(e){const t=this._value;this._value-=e.weight,e.resolve([t,this._newReleaser(e.weight)])}_newReleaser(e){let t=!1;return()=>{t||(t=!0,this.release(e))}}_drainUnlockWaiters(){if(this._queue.length===0)for(let e=this._value;e>0;e--){const t=this._weightedWaiters[e-1];t&&(t.forEach(n=>n.resolve()),this._weightedWaiters[e-1]=[])}else{const e=this._queue[0].priority;for(let t=this._value;t>0;t--){const n=this._weightedWaiters[t-1];if(!n)continue;const i=n.findIndex(a=>a.priority<=e);(i===-1?n:n.splice(0,i)).forEach(a=>a.resolve())}}}_couldLockImmediately(e,t){return(this._queue.length===0||this._queue[0].priority<t)&&e<=this._value}}function wh(r,e){const t=Hi(r,n=>e.priority<=n.priority);r.splice(t+1,0,e)}function Hi(r,e){for(let t=r.length-1;t>=0;t--)if(e(r[t]))return t;return-1}var bh=function(r,e,t,n){function i(a){return a instanceof t?a:new t(function(o){o(a)})}return new(t||(t=Promise))(function(a,o){function l(y){try{h(n.next(y))}catch(d){o(d)}}function u(y){try{h(n.throw(y))}catch(d){o(d)}}function h(y){y.done?a(y.value):i(y.value).then(l,u)}h((n=n.apply(r,e||[])).next())})};class vh{constructor(e){this._semaphore=new mh(1,e)}acquire(){return bh(this,arguments,void 0,function*(e=0){const[,t]=yield this._semaphore.acquire(1,e);return t})}runExclusive(e,t=0){return this._semaphore.runExclusive(()=>e(),1,t)}isLocked(){return this._semaphore.isLocked()}waitForUnlock(e=0){return this._semaphore.waitForUnlock(1,e)}release(){this._semaphore.isLocked()&&this._semaphore.release()}cancel(){return this._semaphore.cancel()}}const $r=(r,e,{convertNumericStrings:t=!0}={})=>{const n=!Array.isArray(r);let i=b(r);const a=i[0],o=typeof a;let l;return o==="string"&&t&&!isNaN(parseInt(a))&&"number"in e?(l=e.number,i=i.map(u=>parseInt(u))):l=e[o],{single:n,variant:l,normalized:i,actual:r}},Ar=(r,e,t,n)=>{if(n){if(t.length===0)throw new pe(`${r} not found matching ${JSON.stringify(e)}`);if(t.length>1)throw new me(`Expected one ${r} matching ${JSON.stringify(e)}, but found ${t.length}`)}},Th=s.z.object({leaseholder:s.z.number().optional(),keys:s.z.number().array().optional(),names:s.z.string().array().optional(),search:s.z.string().optional(),rangeKey:s.z.string().optional(),limit:s.z.number().optional(),offset:s.z.number().optional(),dataTypes:S.z.array().optional(),notDataTypes:S.z.array().optional(),virtual:s.z.boolean().optional(),isIndex:s.z.boolean().optional(),internal:s.z.boolean().optional()}),Oh=s.z.object({channels:X(_t)}),we=r=>$r(r,{number:"keys",string:"names"}),Tr=class Tr{constructor(e){c(this,"client");this.client=e}async search(e,t){return await this.execute({search:e,...t})}async retrieve(e,t){const n=we(e),{variant:i}=n;let{normalized:a}=n;return i==="keys"&&a.indexOf(0)!==-1&&(a=a.filter(o=>o!==0)),a.length===0?[]:await this.execute({[i]:a,...t})}async page(e,t,n){return await this.execute({offset:e,limit:t,...n})}async execute(e){const[t,n]=await this.client.send(Tr.ENDPOINT,e,Th,Oh);if(n!=null)throw n;return t.channels}};c(Tr,"ENDPOINT","/channel/retrieve");let xt=Tr;class Dn{constructor(e){c(this,"cache");c(this,"namesToKeys");c(this,"wrapped");this.cache=new Map,this.namesToKeys=new Map,this.wrapped=e}async search(e,t){return await this.wrapped.search(e,t)}async page(e,t,n){return await this.wrapped.page(e,t,n)}async retrieve(e,t){const{normalized:n}=$r(e,{string:"names",number:"keys"}),i=[],a=[];if(n.forEach(l=>{const u=this.get(l);u!=null?i.push(...u):a.push(l)}),a.length===0)return i;const o=await this.wrapped.retrieve(a,t);return this.set(o),i.concat(o)}delete(e){const{variant:t,normalized:n}=we(e);t==="names"?n.forEach(i=>{const a=this.namesToKeys.get(i);a!=null&&(a.forEach(o=>this.cache.delete(o)),this.namesToKeys.delete(i))}):n.forEach(i=>{const a=this.cache.get(i);a!=null&&(this.cache.delete(i),this.namesToKeys.delete(a.name))})}rename(e,t){e.forEach((n,i)=>{const a=t[i],o=this.cache.get(n);if(o==null)return;this.cache.delete(n);const l=this.namesToKeys.get(o.name);l!=null&&(l.delete(n),l.size===0&&this.namesToKeys.delete(o.name)),o.name=a,this.cache.set(n,o);const u=this.namesToKeys.get(a);u==null?this.namesToKeys.set(a,new Set([n])):u.add(n)})}set(e){e.forEach(t=>{this.cache.set(t.key,t);const n=this.namesToKeys.get(t.name);n==null?this.namesToKeys.set(t.name,new Set([t.key])):n.add(t.key)})}get(e){if(typeof e=="number"){const i=this.cache.get(e);return i==null?void 0:[i]}const t=this.namesToKeys.get(e);if(t==null)return;const n=[];if(t.forEach(i=>{const a=this.cache.get(i);a!=null&&n.push(a)}),n.length!==0)return n}}class Xi{constructor(e,t){c(this,"mu",new vh);c(this,"requests",new Map);c(this,"wrapped");c(this,"debouncedRun");this.wrapped=e,this.debouncedRun=Yl(()=>{this.run()},t)}async search(e,t){return await this.wrapped.search(e,t)}async page(e,t,n){return await this.wrapped.page(e,t,n)}async retrieve(e){const{normalized:t,variant:n}=we(e);return n==="names"?await this.wrapped.retrieve(t):await new Promise((a,o)=>{this.mu.runExclusive(()=>{this.requests.set(t,{resolve:a,reject:o}),this.debouncedRun()})})}async run(){await this.mu.runExclusive(async()=>{const e=new Set;this.requests.forEach((t,n)=>n.forEach(i=>e.add(i)));try{const t=await this.wrapped.retrieve(Array.from(e));this.requests.forEach((n,i)=>n.resolve(t.filter(a=>i.includes(a.key))))}catch(t){this.requests.forEach(n=>n.reject(t))}finally{this.requests.clear()}})}}const Qi=async(r,e)=>{const{normalized:t}=we(e),n=await r.retrieve(t),i=[];if(t.forEach(a=>{n.find(o=>o.name===a||o.key===a)==null&&i.push(a)}),i.length>0)throw new re(`Could not find channels: ${JSON.stringify(i)}`);return n};class jn{constructor({dataType:e,rate:t,name:n,leaseholder:i=0,key:a=0,isIndex:o=!1,index:l=0,internal:u=!1,virtual:h=!1,frameClient:y,alias:d}){c(this,"_frameClient");c(this,"key");c(this,"name");c(this,"rate");c(this,"dataType");c(this,"leaseholder");c(this,"index");c(this,"isIndex");c(this,"internal");c(this,"alias");c(this,"virtual");this.key=a,this.name=n,this.rate=new nt(t??0),this.dataType=new S(e),this.leaseholder=i,this.index=l,this.isIndex=o,this.internal=u,this.alias=d,this.virtual=h,this._frameClient=y??null}get framer(){if(this._frameClient==null)throw new B("cannot read from a channel that has not been created");return this._frameClient}get payload(){return _t.parse({key:this.key,name:this.name,rate:this.rate.valueOf(),dataType:this.dataType.valueOf(),leaseholder:this.leaseholder,index:this.index,isIndex:this.isIndex,internal:this.internal})}get ontologyID(){return new O({type:"channel",key:this.key.toString()})}async read(e){return await this.framer.read(e,this.key)}async write(e,t){return await this.framer.write(e,this.key,t)}}const zh="/channel/retrieve-group",Eh=s.z.object({}),Nh=s.z.object({group:Pn});let ea=class{constructor(e,t,n,i){c(this,"type","channel");c(this,"frameClient");c(this,"client");c(this,"retriever");c(this,"writer");this.frameClient=e,this.retriever=t,this.client=n,this.writer=i}async create(e,t={}){const{retrieveIfNameExists:n=!1}=t,i=!Array.isArray(e);let a=b(e),o=[];if(n){const l=await this.retriever.retrieve(a.map(h=>h.name)),u=new Set(l.map(h=>h.name));a=a.filter(h=>!u.has(h.name)),o=this.sugar(l)}return o=o.concat(this.sugar(await this.writer.create(a))),i?o[0]:o}async retrieve(e,t){const n=!Array.isArray(e),i=this.sugar(await this.retriever.retrieve(e,t));return Ar("channel",e,i,n),n?i[0]:i}async search(e,t){return this.sugar(await this.retriever.search(e,t))}async delete(e){const{normalized:t,variant:n}=we(e);return n==="keys"?await this.writer.delete({keys:t}):await this.writer.delete({names:t})}async rename(e,t){return await this.writer.rename(b(e),b(t))}newSearcherWithOptions(e){return{type:this.type,search:async t=>await this.search(t,e),retrieve:async t=>await this.retrieve(t,e),page:async(t,n)=>await this.page(t,n,e)}}async page(e,t,n){return this.sugar(await this.retriever.page(e,t,n))}createDebouncedBatchRetriever(e=10){return new Dn(new Xi(new xt(this.client),e))}sugar(e){const{frameClient:t}=this;return e.map(n=>new jn({...n,frameClient:t}))}async retrieveGroup(){const e=await w(this.client,zh,{},Eh,Nh);return new xn(e.group.name,e.group.key)}};const Sh=s.z.object({channels:Ji.array()}),Ih=s.z.object({channels:_t.array()}),kh=s.z.object({keys:ke.array().optional(),names:s.z.string().array().optional()}),$h=s.z.object({}),Ah=s.z.object({keys:ke.array(),names:s.z.string().array()}),Rh=s.z.object({}),xh="/channel/create",Ch="/channel/delete",Ph="/channel/rename";let ta=class{constructor(e,t){c(this,"client");c(this,"cache");this.client=e,this.cache=t}async create(e){const{channels:t}=await w(this.client,xh,{channels:e},Sh,Ih);return this.cache.set(t),t}async delete(e){await w(this.client,Ch,e,kh,$h),e.keys!=null&&this.cache.delete(e.keys),e.names!=null&&this.cache.delete(e.names)}async rename(e,t){await w(this.client,Ph,{keys:e,names:t},Ah,Rh),this.cache.rename(e,t)}};const Dh=Object.freeze(Object.defineProperty({__proto__:null,CacheRetriever:Dn,Channel:jn,Client:ea,ClusterRetriever:xt,DebouncedBatchRetriever:Xi,ONTOLOGY_TYPE:Ki,Writer:ta,analyzeChannelParams:we,keyZ:ke,newPayload:Ji,ontologyID:yh,payload:_t,retrieveRequired:Qi},Symbol.toStringTag,{value:"Module"})),ut=s.z.string().uuid(),Yt=s.z.object({key:ut,username:s.z.string().min(1),firstName:s.z.string().default(""),lastName:s.z.string().default(""),rootUser:s.z.boolean().default(!0)}),ra=Yt.partial({key:!0,firstName:!0,lastName:!0}).omit({rootUser:!0}).extend({password:s.z.string().min(1)}),na="user",jh=r=>new O({type:na,key:r}),Mh=s.z.object({keys:ut.array().optional(),usernames:s.z.string().array().optional()}),Bh=s.z.object({users:X(Yt)}),Uh="/user/retrieve";let Zh=class{constructor(e){c(this,"client");this.client=e}async retrieve(e){return(await w(this.client,Uh,e,Mh,Bh)).users}};const Lh=s.z.object({users:ra.array()}),_h=s.z.object({users:Yt.array()}),Yh=s.z.object({key:ut,username:s.z.string().min(1)}),qh=s.z.object({}),Wh=s.z.object({key:ut,firstName:s.z.string().optional(),lastName:s.z.string().optional()}),Gh=s.z.object({}),Vh=s.z.object({keys:ut.array()}),Fh=s.z.object({}),Jh="/user/create",Kh="/user/change-username",Hh="/user/rename",Xh="/user/delete";let Qh=class{constructor(e){c(this,"client");this.client=e}async create(e){return(await w(this.client,Jh,{users:b(e)},Lh,_h)).users}async changeUsername(e,t){await w(this.client,Kh,{key:e,username:t},Yh,qh)}async rename(e,t,n){await w(this.client,Hh,{key:e,firstName:t,lastName:n},Wh,Gh)}async delete(e){await w(this.client,Xh,{keys:b(e)},Vh,Fh)}},sa=class{constructor(e){c(this,"reader");c(this,"writer");this.writer=new Qh(e),this.reader=new Zh(e)}async create(e){const t=Array.isArray(e),n=await this.writer.create(e);return t?n:n[0]}async changeUsername(e,t){await this.writer.changeUsername(e,t)}async retrieve(e){const t=Array.isArray(e),n=await this.reader.retrieve({keys:b(e)});if(t)return n;if(n.length===0)throw new pe(`No user with key ${e} found`);if(n.length>1)throw new me(`Multiple users found with key ${e}`);return n[0]}async retrieveByName(e){const t=Array.isArray(e),n=await this.reader.retrieve({usernames:b(e)});if(t)return n;if(n.length===0)throw new pe(`No user with username ${e} found`);if(n.length>1)throw new me(`Multiple users found with username ${e}`);return n[0]}async rename(e,t,n){await this.writer.rename(e,t,n)}async delete(e){await this.writer.delete(e)}};const ed=Object.freeze(Object.defineProperty({__proto__:null,Client:sa,ONTOLOGY_TYPE:na,keyZ:ut,newUserZ:ra,ontologyID:jh,userZ:Yt},Symbol.toStringTag,{value:"Module"})),td=s.z.object({username:s.z.string(),password:s.z.string()}),rd=s.z.object({token:s.z.string(),user:Yt}),Us="/auth/login",nd=3,sd="/auth/change-password",id=s.z.object({username:s.z.string(),password:s.z.string(),newPassword:s.z.string().min(1)}),ad=s.z.object({});let od=class{constructor(e,t){c(this,"token");c(this,"client");c(this,"credentials");c(this,"authenticating");c(this,"authenticated");c(this,"user");c(this,"retryCount");this.client=e,this.authenticated=!1,this.credentials=t,this.retryCount=0}async changePassword(e){if(!this.authenticated)throw new Error("Not authenticated");await w(this.client,sd,{username:this.credentials.username,password:this.credentials.password,newPassword:e},id,ad),this.credentials.password=e}middleware(){const e=async(t,n)=>{if(!this.authenticated&&!t.target.endsWith(Us)){this.authenticating??(this.authenticating=new Promise((l,u)=>{this.client.send(Us,this.credentials,td,rd).then(([h,y])=>{if(y!=null)return l(y);this.token=h==null?void 0:h.token,this.user=h==null?void 0:h.user,this.authenticated=!0,l(null)}).catch(u)}));const o=await this.authenticating;if(o!=null)return[t,o]}t.params.Authorization=`Bearer ${this.token}`;const[i,a]=await n(t);return At.matches(a)&&this.retryCount<nd?(this.authenticated=!1,this.authenticating=void 0,this.retryCount+=1,e(t,n)):(this.retryCount=0,[i,a])};return e}};const cd=["disconnected","connecting","connected","failed"],ia=s.z.enum(cd),aa=s.z.object({status:ia,error:s.z.instanceof(Error).optional(),message:s.z.string().optional(),clusterKey:s.z.string(),clientVersion:s.z.string(),clientServerCompatible:s.z.boolean(),nodeVersion:s.z.string().optional()}),ld=s.z.object({clusterKey:s.z.string(),nodeVersion:s.z.string().optional()}),Zs={clusterKey:"",status:"disconnected",error:void 0,message:"Disconnected",clientServerCompatible:!1,clientVersion:"0.36.0"},Ls=(r,e,t)=>{const n=t?"cluster":"client";return`Synnax cluster node version ${r!=null?`${r} `:""}is too ${t?"old":"new"} for client version ${e}.
33
+ `);c(this,"type",We.TYPE)}};c(We,"TYPE",`${Ie}unexpected`),c(We,"matches",Q(We.TYPE));let Ee=We;const Ge=class Ge extends se{constructor(){super(...arguments);c(this,"type",Ge.TYPE)}};c(Ge,"TYPE",`${Ie}query`),c(Ge,"matches",Q(Ge.TYPE));let re=Ge;const Ve=class Ve extends re{constructor(){super(...arguments);c(this,"type",Ve.TYPE)}};c(Ve,"TYPE",`${re.TYPE}.not_found`),c(Ve,"matches",Q(Ve.TYPE));let pe=Ve;const Fe=class Fe extends re{constructor(){super(...arguments);c(this,"type",Fe.TYPE)}};c(Fe,"TYPE",`${re.TYPE}.multiple_results`),c(Fe,"matches",Q(Fe.TYPE));let me=Fe;const Je=class Je extends se{constructor(t,n){super(t);c(this,"type",Je.TYPE);c(this,"path");this.path=n}};c(Je,"TYPE",`${Ie}route`),c(Je,"matches",Q(Je.TYPE));let Rt=Je;const Ke=class Ke extends se{constructor(){super(...arguments);c(this,"type",Ke.TYPE)}};c(Ke,"TYPE",`${Ie}control`),c(Ke,"matches",Q(Ke.TYPE));let at=Ke;const He=class He extends at{constructor(){super(...arguments);c(this,"type",He.TYPE)}};c(He,"TYPE",`${at.TYPE}.unauthorized`),c(He,"matches",Q(He.TYPE));let wr=He;const Xe=class Xe extends se{constructor(){super(...arguments);c(this,"type",Xe.TYPE)}};c(Xe,"TYPE",`${Ie}contiguity`),c(Xe,"matches",Q(Xe.TYPE));let En=Xe;const Du=r=>{if(!r.type.startsWith(Ie))return null;if(r.type.startsWith(B.TYPE)){if(r.type===mr.TYPE){const e=r.data.split(": ");return e.length<2?new B(r.data):new mr(e[0],e[1])}return new B(r.data)}return r.type.startsWith(xe.TYPE)?r.type.startsWith(At.TYPE)?new At(r.data):new xe(r.data):r.type.startsWith(Ee.TYPE)?new Ee(r.data):r.type.startsWith(re.TYPE)?r.type.startsWith(pe.TYPE)?new pe(r.data):r.type.startsWith(me.TYPE)?new me(r.data):new re(r.data):r.type.startsWith(at.TYPE)?r.type.startsWith(wr.TYPE)?new wr(r.data):new at(r.data):r.type.startsWith(Rt.TYPE)?new Rt(r.data,r.data):new Ee(r.data)},ju=()=>{throw new Error("Not implemented")};ci({encode:ju,decode:Du});const Mu=async(r,e)=>{const[t,n]=await e(r);return n==null?[t,n]:n instanceof Se?[t,new Se({message:`Cannot reach cluster at ${n.url.host}:${n.url.port}`,url:n.url})]:[t,n]};class xn{constructor(e,t){c(this,"key");c(this,"name");this.key=t,this.name=e}get ontologyID(){return new O({type:"group",key:this.key})}}const Cn=s.z.string().uuid(),Pn=s.z.object({key:Cn,name:s.z.string()}),Bu=r=>{const e=b(r);if(e.length===0)throw new Error("No groups specified");const t=Cn.safeParse(e[0]).success;return{single:!Array.isArray(r),variant:t?"keys":"names",normalized:e,actual:r}},Mi="group",Uu=r=>new O({type:Mi,key:r}),Ut=s.z.union([s.z.literal("label"),s.z.literal("log"),s.z.literal("allow_all"),s.z.literal("builtin"),s.z.literal("cluster"),s.z.literal("channel"),s.z.literal("node"),s.z.literal("group"),s.z.literal("range"),s.z.literal("framer"),s.z.literal("range-alias"),s.z.literal("user"),s.z.literal("workspace"),s.z.literal("schematic"),s.z.literal("lineplot"),s.z.literal("rack"),s.z.literal("device"),s.z.literal("task"),s.z.literal("policy"),s.z.literal("table")]),Zu="builtin",Lu="cluster",_u="node",H=s.z.object({type:Ut,key:s.z.string()}),Bi=s.z.string().transform(r=>{const[e,t]=r.split(":");return{type:Ut.parse(e),key:t??""}}),Ue=s.z.union([Bi,H]),Qe=class Qe{constructor(e){c(this,"type");c(this,"key");if(e instanceof Qe){this.type=e.type,this.key=e.key;return}if(typeof e=="string"){const[t,n]=e.split(":");this.type=t,this.key=n??"";return}this.type=e.type,this.key=e.key}toString(){return`${this.type}:${this.key}`}isType(){return this.key===""}matchesType(e){return this.type===e&&this.isType()}get payload(){return{type:this.type,key:this.key}}};c(Qe,"z",s.z.union([s.z.instanceof(Qe),Ue.transform(e=>new Qe(e))]));let O=Qe;const Yu=new O({type:"builtin",key:"root"}),Ui=s.z.object({type:s.z.number()}),Zi=s.z.object({type:Ut,fields:s.z.record(Ui)}),Li=s.z.object({id:O.z,name:s.z.string(),schema:Zi.optional().nullable(),data:s.z.record(s.z.unknown()).optional().nullable()}).transform(r=>({key:r.id.toString(),...r})),qu=s.z.object({from:O.z,type:s.z.string(),to:O.z}),Nn=r=>{const[e,t,n]=r.split("->");return{from:new O(e),type:t,to:new O(n)}},Wu=s.z.object({group:Pn}),Gu=s.z.object({parent:H,key:s.z.string().uuid().optional(),name:s.z.string()}),Vu=s.z.object({key:s.z.string(),name:s.z.string()}),Fu=s.z.object({keys:s.z.array(s.z.string())});var ne;let Ju=(ne=class{constructor(e){c(this,"client");this.client=e}async create(e,t,n){return(await w(this.client,ne.ENDPOINT,{parent:e,name:t,key:n},Gu,Wu)).group}async rename(e,t){await w(this.client,ne.ENDPOINT_RENAME,{key:e,name:t},Vu,s.z.object({}))}async delete(e){await w(this.client,ne.ENDPOINT_DELETE,{keys:e},Fu,s.z.object({}))}},c(ne,"ENDPOINT","/ontology/create-group"),c(ne,"ENDPOINT_RENAME","/ontology/rename-group"),c(ne,"ENDPOINT_DELETE","/ontology/delete-group"),ne),_i=class{constructor(e){c(this,"creator");this.creator=new Ju(e)}async create(e,t,n){return this.sugar(await this.creator.create(e,t,n))}async rename(e,t){return await this.creator.rename(e,t)}async delete(...e){return await this.creator.delete(e)}sugar(e){return new xn(e.name,e.key)}};const Ku=Object.freeze(Object.defineProperty({__proto__:null,Client:_i,Group:xn,ONTOLOGY_TYPE:Mi,analyzeParams:Bu,groupZ:Pn,keyZ:Cn,ontologyID:Uu},Symbol.toStringTag,{value:"Module"})),Kr={ADD_CHILDREN:"/ontology/add-children",REMOVE_CHILDREN:"/ontology/remove-children",MOVE_CHILDREN:"/ontology/move-children"},Cs=s.z.object({id:H,children:H.array()}),Hu=s.z.object({from:H,to:H,children:H.array()});let Xu=class{constructor(e){c(this,"client");this.client=e}async addChildren(e,...t){await w(this.client,Kr.ADD_CHILDREN,{id:new O(e).payload,children:t.map(n=>new O(n).payload)},Cs,s.z.object({}))}async removeChildren(e,...t){await w(this.client,Kr.REMOVE_CHILDREN,{id:new O(e).payload,children:t.map(n=>new O(n).payload)},Cs,s.z.object({}))}async moveChildren(e,t,...n){const i={from:new O(e).payload,to:new O(t).payload,children:n.map(a=>new O(a).payload)};await w(this.client,Kr.MOVE_CHILDREN,i,Hu,s.z.object({}))}};const Qu="/ontology/retrieve",eh=s.z.object({ids:H.array().optional(),children:s.z.boolean().optional(),parents:s.z.boolean().optional(),includeSchema:s.z.boolean().optional(),excludeFieldData:s.z.boolean().optional(),term:s.z.string().optional(),limit:s.z.number().optional(),offset:s.z.number().optional(),types:Ut.array().optional()}),th=s.z.object({resources:Li.array()}),dr=r=>b(r).map(e=>new O(e).payload);let Yi=class{constructor(e,t){c(this,"type","ontology");c(this,"groups");c(this,"client");c(this,"writer");c(this,"framer");this.client=e,this.writer=new Xu(e),this.groups=new _i(e),this.framer=t}async search(e,t){return await this.execRetrieve({term:e,...t})}async retrieve(e,t){const n=await this.execRetrieve({ids:dr(e),...t});if(Array.isArray(e))return n;if(n.length===0)throw new re(`No resource found with ID ${e.toString()}`);return n[0]}async page(e,t,n){return await this.execRetrieve({offset:e,limit:t,...n})}async retrieveChildren(e,t){return await this.execRetrieve({ids:dr(e),children:!0,...t})}async retrieveParents(e,t){return await this.execRetrieve({ids:dr(e),parents:!0,...t})}async addChildren(e,...t){return await this.writer.addChildren(e,...t)}async removeChildren(e,...t){return await this.writer.removeChildren(e,...t)}async moveChildren(e,t,...n){return await this.writer.moveChildren(e,t,...n)}async openChangeTracker(){return await Zt.open(this.framer,this)}async openDependentTracker(e){return await Ir.open(e,this.framer,this)}newSearcherWithOptions(e){return{type:this.type,search:t=>this.search(t,e),retrieve:t=>this.retrieve(t,e),page:(t,n)=>this.page(t,n,e)}}async execRetrieve(e){const{resources:t}=await w(this.client,Qu,e,eh,th);return t}};const Ps="sy_ontology_resource_set",Ds="sy_ontology_resource_delete",js="sy_ontology_relationship_set",Ms="sy_ontology_relationship_delete";class Zt{constructor(e,t){c(this,"relationships");c(this,"resources");c(this,"resourceObs");c(this,"relationshipObs");c(this,"streamer");c(this,"client");c(this,"closePromise");this.relationshipObs=new Re.Observer,this.relationships=this.relationshipObs,this.resourceObs=new Re.Observer,this.resources=this.resourceObs,this.client=t,this.streamer=e,this.closePromise=this.start()}async close(){this.streamer.close(),await this.closePromise}async start(){for await(const e of this.streamer)await this.update(e)}async update(e){const t=await this.parseResourceSets(e),n=this.parseResourceDeletes(e);t.concat(n).length>0&&this.resourceObs.notify(t.concat(n));const a=this.parseRelationshipSets(e),o=this.parseRelationshipDeletes(e);a.concat(o).length>0&&this.relationshipObs.notify(a.concat(o))}parseRelationshipSets(e){const t=e.get(js);return t.length===0?[]:Array.from(t.as("string")).map(n=>({variant:"set",key:Nn(n),value:void 0}))}parseRelationshipDeletes(e){const t=e.get(Ms);return t.length===0?[]:Array.from(t.as("string")).map(n=>({variant:"delete",key:Nn(n)}))}async parseResourceSets(e){const t=e.get(Ps);if(t.length===0)return[];const n=Array.from(t.as("string")).map(i=>new O(i));try{return(await this.client.retrieve(n)).map(a=>({variant:"set",key:a.id,value:a}))}catch(i){if(i instanceof re)return[];throw i}}parseResourceDeletes(e){const t=e.get(Ds);return t.length===0?[]:Array.from(t.as("string")).map(n=>({variant:"delete",key:new O(n)}))}static async open(e,t){const n=await e.openStreamer([Ps,Ds,js,Ms]);return new Zt(n,t)}}const Bs=r=>r==="from"?"to":"from";class Ir extends Re.Observer{constructor({target:t,dependents:n,relationshipType:i="parent",relationshipDirection:a="from",resourceType:o},l,u){super();c(this,"internal");c(this,"target");c(this,"relDir");c(this,"resourceType");c(this,"dependents");c(this,"client");c(this,"relType");c(this,"handleResourceChange",t=>{this.dependents=this.dependents.map(n=>{const i=t.find(a=>a.key.toString()==n.id.toString());return i==null||i.variant==="delete"?n:i.value}),this.notify(this.dependents)});c(this,"handleRelationshipChange",t=>{const n=t.filter(a=>a.variant==="delete"&&a.key[this.relDir].toString()===this.target.toString()&&(this.resourceType==null||a.key[Bs(this.relDir)].type===this.resourceType));this.dependents=this.dependents.filter(a=>!n.some(o=>o.key.to.toString()===a.id.toString()&&o.key.type===this.relType));const i=t.filter(a=>a.variant==="set"&&a.key.type===this.relType&&a.key[this.relDir].toString()===this.target.toString()&&(this.resourceType==null||a.key[Bs(this.relDir)].type===this.resourceType));if(i.length===0)return this.notify(this.dependents);this.client.retrieve(i.map(a=>a.key.to)).then(a=>{this.dependents=this.dependents.concat(a),this.notify(this.dependents)})});this.resourceType=o,this.internal=l,this.target=t,this.dependents=n,this.resourceType!=null&&(this.dependents=this.dependents.filter(h=>h.id.type===this.resourceType)),this.client=u,this.relType=i,this.relDir=a,this.internal.resources.onChange(this.handleResourceChange),this.internal.relationships.onChange(this.handleRelationshipChange)}static async open(t,n,i){const a=await Zt.open(n,i);return new Ir(t,a,i)}async close(){await this.internal.close()}}const rh=Object.freeze(Object.defineProperty({__proto__:null,BUILTIN_TYPE:Zu,CLUSTER_TYPE:Lu,ChangeTracker:Zt,Client:Yi,DependentTracker:Ir,ID:O,NODE_TYPE:_u,Root:Yu,crudeIDZ:Ue,idZ:H,parseIDs:dr,parseRelationship:Nn,relationshipSchemaZ:qu,resourceSchemaZ:Li,resourceTypeZ:Ut,schemaFieldZ:Ui,schemaZ:Zi,stringIDZ:Bi},Symbol.toStringTag,{value:"Module"})),X=r=>s.z.union([s.z.null().transform(()=>[]),r.array()]),Lt=s.z.string().uuid(),qi=s.z.object({key:Lt.optional(),subjects:Ue.array().or(Ue),objects:Ue.array().or(Ue),actions:gr.array().or(gr)}),kr=s.z.object({key:Lt,subjects:X(H),objects:X(H),actions:X(gr)}),Wi="policy",nh=r=>new O({type:Wi,key:r}),Gi="allow_all",sh=new O({type:Gi,key:""}),ih=s.z.object({keys:Lt.array().optional(),subjects:H.array().optional()}),ah=s.z.object({policies:X(kr)}),oh="/access/policy/retrieve";let ch=class{constructor(e){c(this,"client");this.client=e}async retrieve(e){return(await w(this.client,oh,e,ih,ah)).policies}};const lh=s.z.object({policies:kr.partial({key:!0}).array()}),uh=s.z.object({policies:kr.array()}),hh=s.z.object({keys:Lt.array()}),dh=s.z.object({}),fh="/access/policy/create",yh="/access/policy/delete";let gh=class{constructor(e){c(this,"client");this.client=e}async create(e){const n=qi.array().parse(b(e)).map(a=>({objects:b(a.objects),actions:b(a.actions),subjects:b(a.subjects)}));return(await w(this.client,fh,{policies:n},lh,uh)).policies}async delete(e){await w(this.client,yh,{keys:b(e)},hh,dh)}},Vi=class{constructor(e){c(this,"retriever");c(this,"writer");this.retriever=new ch(e),this.writer=new gh(e)}async create(e){const t=Array.isArray(e),n=await this.writer.create(e);return t?n:n[0]}async retrieve(e){const t=Array.isArray(e),n=await this.retriever.retrieve({keys:b(e)});return t?n:n[0]}async retrieveFor(e){const t=b(e).map(n=>new O(n).payload);return await this.retriever.retrieve({subjects:t})}async delete(e){await this.writer.delete(e)}};const ph=Object.freeze(Object.defineProperty({__proto__:null,ALLOW_ALL_ONTOLOGY_ID:sh,ALLOW_ALL_ONTOLOGY_TYPE:Gi,Client:Vi,ONTOLOGY_TYPE:Wi,keyZ:Lt,newPolicyZ:qi,ontologyID:nh,policyZ:kr},Symbol.toStringTag,{value:"Module"}));let Fi=class{constructor(e){c(this,"policy");this.policy=new Vi(e)}};const mh=Object.freeze(Object.defineProperty({__proto__:null,ALL_ACTION:Fc,CREATE_ACTION:Jc,Client:Fi,DELETE_ACTION:Kc,RETRIEVE_ACTION:Hc,UPDATE_ACTION:Xc,actionZ:gr},Symbol.toStringTag,{value:"Module"})),ke=s.z.number(),_t=s.z.object({name:s.z.string(),key:s.z.number(),rate:nt.z,dataType:S.z,leaseholder:s.z.number(),index:s.z.number(),isIndex:s.z.boolean(),internal:s.z.boolean(),virtual:s.z.boolean(),alias:s.z.string().optional()}),Ji=_t.extend({key:s.z.number().optional(),leaseholder:s.z.number().optional(),index:s.z.number().optional(),rate:nt.z.optional().default(0),isIndex:s.z.boolean().optional(),internal:s.z.boolean().optional().default(!1),virtual:s.z.boolean().optional().default(!1)}),Ki="channel",wh=r=>new O({type:Ki,key:r.toString()}),bh=new Error("request for lock canceled");var vh=function(r,e,t,n){function i(a){return a instanceof t?a:new t(function(o){o(a)})}return new(t||(t=Promise))(function(a,o){function l(y){try{h(n.next(y))}catch(d){o(d)}}function u(y){try{h(n.throw(y))}catch(d){o(d)}}function h(y){y.done?a(y.value):i(y.value).then(l,u)}h((n=n.apply(r,e||[])).next())})};class Th{constructor(e,t=bh){this._value=e,this._cancelError=t,this._queue=[],this._weightedWaiters=[]}acquire(e=1,t=0){if(e<=0)throw new Error(`invalid weight ${e}: must be positive`);return new Promise((n,i)=>{const a={resolve:n,reject:i,weight:e,priority:t},o=Hi(this._queue,l=>t<=l.priority);o===-1&&e<=this._value?this._dispatchItem(a):this._queue.splice(o+1,0,a)})}runExclusive(e){return vh(this,arguments,void 0,function*(t,n=1,i=0){const[a,o]=yield this.acquire(n,i);try{return yield t(a)}finally{o()}})}waitForUnlock(e=1,t=0){if(e<=0)throw new Error(`invalid weight ${e}: must be positive`);return this._couldLockImmediately(e,t)?Promise.resolve():new Promise(n=>{this._weightedWaiters[e-1]||(this._weightedWaiters[e-1]=[]),Oh(this._weightedWaiters[e-1],{resolve:n,priority:t})})}isLocked(){return this._value<=0}getValue(){return this._value}setValue(e){this._value=e,this._dispatchQueue()}release(e=1){if(e<=0)throw new Error(`invalid weight ${e}: must be positive`);this._value+=e,this._dispatchQueue()}cancel(){this._queue.forEach(e=>e.reject(this._cancelError)),this._queue=[]}_dispatchQueue(){for(this._drainUnlockWaiters();this._queue.length>0&&this._queue[0].weight<=this._value;)this._dispatchItem(this._queue.shift()),this._drainUnlockWaiters()}_dispatchItem(e){const t=this._value;this._value-=e.weight,e.resolve([t,this._newReleaser(e.weight)])}_newReleaser(e){let t=!1;return()=>{t||(t=!0,this.release(e))}}_drainUnlockWaiters(){if(this._queue.length===0)for(let e=this._value;e>0;e--){const t=this._weightedWaiters[e-1];t&&(t.forEach(n=>n.resolve()),this._weightedWaiters[e-1]=[])}else{const e=this._queue[0].priority;for(let t=this._value;t>0;t--){const n=this._weightedWaiters[t-1];if(!n)continue;const i=n.findIndex(a=>a.priority<=e);(i===-1?n:n.splice(0,i)).forEach(a=>a.resolve())}}}_couldLockImmediately(e,t){return(this._queue.length===0||this._queue[0].priority<t)&&e<=this._value}}function Oh(r,e){const t=Hi(r,n=>e.priority<=n.priority);r.splice(t+1,0,e)}function Hi(r,e){for(let t=r.length-1;t>=0;t--)if(e(r[t]))return t;return-1}var zh=function(r,e,t,n){function i(a){return a instanceof t?a:new t(function(o){o(a)})}return new(t||(t=Promise))(function(a,o){function l(y){try{h(n.next(y))}catch(d){o(d)}}function u(y){try{h(n.throw(y))}catch(d){o(d)}}function h(y){y.done?a(y.value):i(y.value).then(l,u)}h((n=n.apply(r,e||[])).next())})};class Eh{constructor(e){this._semaphore=new Th(1,e)}acquire(){return zh(this,arguments,void 0,function*(e=0){const[,t]=yield this._semaphore.acquire(1,e);return t})}runExclusive(e,t=0){return this._semaphore.runExclusive(()=>e(),1,t)}isLocked(){return this._semaphore.isLocked()}waitForUnlock(e=0){return this._semaphore.waitForUnlock(1,e)}release(){this._semaphore.isLocked()&&this._semaphore.release()}cancel(){return this._semaphore.cancel()}}const $r=(r,e,{convertNumericStrings:t=!0}={})=>{const n=!Array.isArray(r);let i=b(r);const a=i[0],o=typeof a;let l;return o==="string"&&t&&!isNaN(parseInt(a))&&"number"in e?(l=e.number,i=i.map(u=>parseInt(u))):l=e[o],{single:n,variant:l,normalized:i,actual:r}},Ar=(r,e,t,n)=>{if(n){if(t.length===0)throw new pe(`${r} not found matching ${JSON.stringify(e)}`);if(t.length>1)throw new me(`Expected one ${r} matching ${JSON.stringify(e)}, but found ${t.length}`)}},Nh=s.z.object({leaseholder:s.z.number().optional(),keys:s.z.number().array().optional(),names:s.z.string().array().optional(),search:s.z.string().optional(),rangeKey:s.z.string().optional(),limit:s.z.number().optional(),offset:s.z.number().optional(),dataTypes:S.z.array().optional(),notDataTypes:S.z.array().optional(),virtual:s.z.boolean().optional(),isIndex:s.z.boolean().optional(),internal:s.z.boolean().optional()}),Sh=s.z.object({channels:X(_t)}),we=r=>$r(r,{number:"keys",string:"names"}),Tr=class Tr{constructor(e){c(this,"client");this.client=e}async search(e,t){return await this.execute({search:e,...t})}async retrieve(e,t){const n=we(e),{variant:i}=n;let{normalized:a}=n;return i==="keys"&&a.indexOf(0)!==-1&&(a=a.filter(o=>o!==0)),a.length===0?[]:await this.execute({[i]:a,...t})}async page(e,t,n){return await this.execute({offset:e,limit:t,...n})}async execute(e){const[t,n]=await this.client.send(Tr.ENDPOINT,e,Nh,Sh);if(n!=null)throw n;return t.channels}};c(Tr,"ENDPOINT","/channel/retrieve");let xt=Tr;class Dn{constructor(e){c(this,"cache");c(this,"namesToKeys");c(this,"wrapped");this.cache=new Map,this.namesToKeys=new Map,this.wrapped=e}async search(e,t){return await this.wrapped.search(e,t)}async page(e,t,n){return await this.wrapped.page(e,t,n)}async retrieve(e,t){const{normalized:n}=$r(e,{string:"names",number:"keys"}),i=[],a=[];if(n.forEach(l=>{const u=this.get(l);u!=null?i.push(...u):a.push(l)}),a.length===0)return i;const o=await this.wrapped.retrieve(a,t);return this.set(o),i.concat(o)}delete(e){const{variant:t,normalized:n}=we(e);t==="names"?n.forEach(i=>{const a=this.namesToKeys.get(i);a!=null&&(a.forEach(o=>this.cache.delete(o)),this.namesToKeys.delete(i))}):n.forEach(i=>{const a=this.cache.get(i);a!=null&&(this.cache.delete(i),this.namesToKeys.delete(a.name))})}rename(e,t){e.forEach((n,i)=>{const a=t[i],o=this.cache.get(n);if(o==null)return;this.cache.delete(n);const l=this.namesToKeys.get(o.name);l!=null&&(l.delete(n),l.size===0&&this.namesToKeys.delete(o.name)),o.name=a,this.cache.set(n,o);const u=this.namesToKeys.get(a);u==null?this.namesToKeys.set(a,new Set([n])):u.add(n)})}set(e){e.forEach(t=>{this.cache.set(t.key,t);const n=this.namesToKeys.get(t.name);n==null?this.namesToKeys.set(t.name,new Set([t.key])):n.add(t.key)})}get(e){if(typeof e=="number"){const i=this.cache.get(e);return i==null?void 0:[i]}const t=this.namesToKeys.get(e);if(t==null)return;const n=[];if(t.forEach(i=>{const a=this.cache.get(i);a!=null&&n.push(a)}),n.length!==0)return n}}class Xi{constructor(e,t){c(this,"mu",new Eh);c(this,"requests",new Map);c(this,"wrapped");c(this,"debouncedRun");this.wrapped=e,this.debouncedRun=cu(()=>{this.run()},t)}async search(e,t){return await this.wrapped.search(e,t)}async page(e,t,n){return await this.wrapped.page(e,t,n)}async retrieve(e){const{normalized:t,variant:n}=we(e);return n==="names"?await this.wrapped.retrieve(t):await new Promise((a,o)=>{this.mu.runExclusive(()=>{this.requests.set(t,{resolve:a,reject:o}),this.debouncedRun()})})}async run(){await this.mu.runExclusive(async()=>{const e=new Set;this.requests.forEach((t,n)=>n.forEach(i=>e.add(i)));try{const t=await this.wrapped.retrieve(Array.from(e));this.requests.forEach((n,i)=>n.resolve(t.filter(a=>i.includes(a.key))))}catch(t){this.requests.forEach(n=>n.reject(t))}finally{this.requests.clear()}})}}const Qi=async(r,e)=>{const{normalized:t}=we(e),n=await r.retrieve(t),i=[];if(t.forEach(a=>{n.find(o=>o.name===a||o.key===a)==null&&i.push(a)}),i.length>0)throw new re(`Could not find channels: ${JSON.stringify(i)}`);return n};class jn{constructor({dataType:e,rate:t,name:n,leaseholder:i=0,key:a=0,isIndex:o=!1,index:l=0,internal:u=!1,virtual:h=!1,frameClient:y,alias:d}){c(this,"_frameClient");c(this,"key");c(this,"name");c(this,"rate");c(this,"dataType");c(this,"leaseholder");c(this,"index");c(this,"isIndex");c(this,"internal");c(this,"alias");c(this,"virtual");this.key=a,this.name=n,this.rate=new nt(t??0),this.dataType=new S(e),this.leaseholder=i,this.index=l,this.isIndex=o,this.internal=u,this.alias=d,this.virtual=h,this._frameClient=y??null}get framer(){if(this._frameClient==null)throw new B("cannot read from a channel that has not been created");return this._frameClient}get payload(){return _t.parse({key:this.key,name:this.name,rate:this.rate.valueOf(),dataType:this.dataType.valueOf(),leaseholder:this.leaseholder,index:this.index,isIndex:this.isIndex,internal:this.internal})}get ontologyID(){return new O({type:"channel",key:this.key.toString()})}async read(e){return await this.framer.read(e,this.key)}async write(e,t){return await this.framer.write(e,this.key,t)}}const Ih="/channel/retrieve-group",kh=s.z.object({}),$h=s.z.object({group:Pn});let ea=class{constructor(e,t,n,i){c(this,"type","channel");c(this,"frameClient");c(this,"client");c(this,"retriever");c(this,"writer");this.frameClient=e,this.retriever=t,this.client=n,this.writer=i}async create(e,t={}){const{retrieveIfNameExists:n=!1}=t,i=!Array.isArray(e);let a=b(e),o=[];if(n){const l=await this.retriever.retrieve(a.map(h=>h.name)),u=new Set(l.map(h=>h.name));a=a.filter(h=>!u.has(h.name)),o=this.sugar(l)}return o=o.concat(this.sugar(await this.writer.create(a))),i?o[0]:o}async retrieve(e,t){const n=!Array.isArray(e),i=this.sugar(await this.retriever.retrieve(e,t));return Ar("channel",e,i,n),n?i[0]:i}async search(e,t){return this.sugar(await this.retriever.search(e,t))}async delete(e){const{normalized:t,variant:n}=we(e);return n==="keys"?await this.writer.delete({keys:t}):await this.writer.delete({names:t})}async rename(e,t){return await this.writer.rename(b(e),b(t))}newSearcherWithOptions(e){return{type:this.type,search:async t=>await this.search(t,e),retrieve:async t=>await this.retrieve(t,e),page:async(t,n)=>await this.page(t,n,e)}}async page(e,t,n){return this.sugar(await this.retriever.page(e,t,n))}createDebouncedBatchRetriever(e=10){return new Dn(new Xi(new xt(this.client),e))}sugar(e){const{frameClient:t}=this;return e.map(n=>new jn({...n,frameClient:t}))}async retrieveGroup(){const e=await w(this.client,Ih,{},kh,$h);return new xn(e.group.name,e.group.key)}};const Ah=s.z.object({channels:Ji.array()}),Rh=s.z.object({channels:_t.array()}),xh=s.z.object({keys:ke.array().optional(),names:s.z.string().array().optional()}),Ch=s.z.object({}),Ph=s.z.object({keys:ke.array(),names:s.z.string().array()}),Dh=s.z.object({}),jh="/channel/create",Mh="/channel/delete",Bh="/channel/rename";let ta=class{constructor(e,t){c(this,"client");c(this,"cache");this.client=e,this.cache=t}async create(e){const{channels:t}=await w(this.client,jh,{channels:e},Ah,Rh);return this.cache.set(t),t}async delete(e){await w(this.client,Mh,e,xh,Ch),e.keys!=null&&this.cache.delete(e.keys),e.names!=null&&this.cache.delete(e.names)}async rename(e,t){await w(this.client,Bh,{keys:e,names:t},Ph,Dh),this.cache.rename(e,t)}};const Uh=Object.freeze(Object.defineProperty({__proto__:null,CacheRetriever:Dn,Channel:jn,Client:ea,ClusterRetriever:xt,DebouncedBatchRetriever:Xi,ONTOLOGY_TYPE:Ki,Writer:ta,analyzeChannelParams:we,keyZ:ke,newPayload:Ji,ontologyID:wh,payload:_t,retrieveRequired:Qi},Symbol.toStringTag,{value:"Module"})),ut=s.z.string().uuid(),Yt=s.z.object({key:ut,username:s.z.string().min(1),firstName:s.z.string().default(""),lastName:s.z.string().default(""),rootUser:s.z.boolean().default(!0)}),ra=Yt.partial({key:!0,firstName:!0,lastName:!0}).omit({rootUser:!0}).extend({password:s.z.string().min(1)}),na="user",Zh=r=>new O({type:na,key:r}),Lh=s.z.object({keys:ut.array().optional(),usernames:s.z.string().array().optional()}),_h=s.z.object({users:X(Yt)}),Yh="/user/retrieve";let qh=class{constructor(e){c(this,"client");this.client=e}async retrieve(e){return(await w(this.client,Yh,e,Lh,_h)).users}};const Wh=s.z.object({users:ra.array()}),Gh=s.z.object({users:Yt.array()}),Vh=s.z.object({key:ut,username:s.z.string().min(1)}),Fh=s.z.object({}),Jh=s.z.object({key:ut,firstName:s.z.string().optional(),lastName:s.z.string().optional()}),Kh=s.z.object({}),Hh=s.z.object({keys:ut.array()}),Xh=s.z.object({}),Qh="/user/create",ed="/user/change-username",td="/user/rename",rd="/user/delete";let nd=class{constructor(e){c(this,"client");this.client=e}async create(e){return(await w(this.client,Qh,{users:b(e)},Wh,Gh)).users}async changeUsername(e,t){await w(this.client,ed,{key:e,username:t},Vh,Fh)}async rename(e,t,n){await w(this.client,td,{key:e,firstName:t,lastName:n},Jh,Kh)}async delete(e){await w(this.client,rd,{keys:b(e)},Hh,Xh)}},sa=class{constructor(e){c(this,"reader");c(this,"writer");this.writer=new nd(e),this.reader=new qh(e)}async create(e){const t=Array.isArray(e),n=await this.writer.create(e);return t?n:n[0]}async changeUsername(e,t){await this.writer.changeUsername(e,t)}async retrieve(e){const t=Array.isArray(e),n=await this.reader.retrieve({keys:b(e)});if(t)return n;if(n.length===0)throw new pe(`No user with key ${e} found`);if(n.length>1)throw new me(`Multiple users found with key ${e}`);return n[0]}async retrieveByName(e){const t=Array.isArray(e),n=await this.reader.retrieve({usernames:b(e)});if(t)return n;if(n.length===0)throw new pe(`No user with username ${e} found`);if(n.length>1)throw new me(`Multiple users found with username ${e}`);return n[0]}async rename(e,t,n){await this.writer.rename(e,t,n)}async delete(e){await this.writer.delete(e)}};const sd=Object.freeze(Object.defineProperty({__proto__:null,Client:sa,ONTOLOGY_TYPE:na,keyZ:ut,newUserZ:ra,ontologyID:Zh,userZ:Yt},Symbol.toStringTag,{value:"Module"})),id=s.z.object({username:s.z.string(),password:s.z.string()}),ad=s.z.object({token:s.z.string(),user:Yt}),Us="/auth/login",od=3,cd="/auth/change-password",ld=s.z.object({username:s.z.string(),password:s.z.string(),newPassword:s.z.string().min(1)}),ud=s.z.object({});let hd=class{constructor(e,t){c(this,"token");c(this,"client");c(this,"credentials");c(this,"authenticating");c(this,"authenticated");c(this,"user");c(this,"retryCount");this.client=e,this.authenticated=!1,this.credentials=t,this.retryCount=0}async changePassword(e){if(!this.authenticated)throw new Error("Not authenticated");await w(this.client,cd,{username:this.credentials.username,password:this.credentials.password,newPassword:e},ld,ud),this.credentials.password=e}middleware(){const e=async(t,n)=>{if(!this.authenticated&&!t.target.endsWith(Us)){this.authenticating??(this.authenticating=new Promise((l,u)=>{this.client.send(Us,this.credentials,id,ad).then(([h,y])=>{if(y!=null)return l(y);this.token=h==null?void 0:h.token,this.user=h==null?void 0:h.user,this.authenticated=!0,l(null)}).catch(u)}));const o=await this.authenticating;if(o!=null)return[t,o]}t.params.Authorization=`Bearer ${this.token}`;const[i,a]=await n(t);return At.matches(a)&&this.retryCount<od?(this.authenticated=!1,this.authenticating=void 0,this.retryCount+=1,e(t,n)):(this.retryCount=0,[i,a])};return e}};const dd=["disconnected","connecting","connected","failed"],ia=s.z.enum(dd),aa=s.z.object({status:ia,error:s.z.instanceof(Error).optional(),message:s.z.string().optional(),clusterKey:s.z.string(),clientVersion:s.z.string(),clientServerCompatible:s.z.boolean(),nodeVersion:s.z.string().optional()}),fd=s.z.object({clusterKey:s.z.string(),nodeVersion:s.z.string().optional()}),Zs={clusterKey:"",status:"disconnected",error:void 0,message:"Disconnected",clientServerCompatible:!1,clientVersion:"0.37.0"},Ls=(r,e,t)=>{const n=t?"cluster":"client";return`Synnax cluster node version ${r!=null?`${r} `:""}is too ${t?"old":"new"} for client version ${e}.
34
34
  This may cause compatibility issues. We recommend updating the ${n}. For more information, see
35
- https://docs.synnaxlabs.com/reference/typescript-client/troubleshooting#old-${n}-version`},et=class et{constructor(e,t=z.seconds(30),n,i){c(this,"_state");c(this,"pollFrequency",z.seconds(30));c(this,"client");c(this,"name");c(this,"interval");c(this,"clientVersion");c(this,"onChangeHandlers",[]);c(this,"versionWarned",!1);this._state={...Zs},this.client=e,this.pollFrequency=t,this.clientVersion=n,this.name=i,this.check(),this.startChecking()}stopChecking(){this.interval!=null&&clearInterval(this.interval)}async check(){var t;const e=this._state.status;try{const[n,i]=await this.client.send(et.ENDPOINT,{},s.z.object({}),ld);if(i!=null)throw i;const a=n.nodeVersion,o=this.clientVersion,l=this.versionWarned;a==null?(this._state.clientServerCompatible=!1,l||(console.warn(Ls(null,o,!0)),this.versionWarned=!0)):xs.versionsEqual(o,a,{checkMajor:!0,checkMinor:!0,checkPatch:!1})?this._state.clientServerCompatible=!0:(this._state.clientServerCompatible=!1,l||(console.warn(Ls(a,o,xs.semVerNewer(o,a))),this.versionWarned=!0)),this._state.status="connected",this._state.message=`Connected to ${this.name??"cluster"}`,this._state.clusterKey=n.clusterKey,this._state.nodeVersion=n.nodeVersion,this._state.clientVersion=this.clientVersion}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)}};c(et,"ENDPOINT","/connectivity/check"),c(et,"DEFAULT",Zs),c(et,"connectionStateZ",aa);let Ct=et;const ud=Object.freeze(Object.defineProperty({__proto__:null,Checker:Ct,state:aa,status:ia},Symbol.toStringTag,{value:"Module"})),hd=s.z.object({keys:ke.array().optional(),bounds:W.z,names:s.z.string().array().optional()}),dd=s.z.object({}),fd="/frame/delete";class yd{constructor(e){c(this,"client");this.client=e}async delete(e){await w(this.client,fd,e,hd,dd)}}const _s=r=>{const e=b(r);return e.length===0?null:typeof e[0]=="number"||!isNaN(parseInt(e[0]))?"key":"name"},Ys=(r,e)=>{const t=b(r);if(t.length===e.length)return;const n=_s(r);throw _s===null?new B("[Frame] - channel keys or names must be provided when constructing a frame."):new B(`[Frame] - ${n}s and series must be the same length.
35
+ https://docs.synnaxlabs.com/reference/typescript-client/troubleshooting#old-${n}-version`},et=class et{constructor(e,t=z.seconds(30),n,i){c(this,"_state");c(this,"pollFrequency",z.seconds(30));c(this,"client");c(this,"name");c(this,"interval");c(this,"clientVersion");c(this,"onChangeHandlers",[]);c(this,"versionWarned",!1);this._state={...Zs},this.client=e,this.pollFrequency=t,this.clientVersion=n,this.name=i,this.check(),this.startChecking()}stopChecking(){this.interval!=null&&clearInterval(this.interval)}async check(){var t;const e=this._state.status;try{const[n,i]=await this.client.send(et.ENDPOINT,{},s.z.object({}),fd);if(i!=null)throw i;const a=n.nodeVersion,o=this.clientVersion,l=this.versionWarned;a==null?(this._state.clientServerCompatible=!1,l||(console.warn(Ls(null,o,!0)),this.versionWarned=!0)):xs.versionsEqual(o,a,{checkMajor:!0,checkMinor:!0,checkPatch:!1})?this._state.clientServerCompatible=!0:(this._state.clientServerCompatible=!1,l||(console.warn(Ls(a,o,xs.semVerNewer(o,a))),this.versionWarned=!0)),this._state.status="connected",this._state.message=`Connected to ${this.name??"cluster"}`,this._state.clusterKey=n.clusterKey,this._state.nodeVersion=n.nodeVersion,this._state.clientVersion=this.clientVersion}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)}};c(et,"ENDPOINT","/connectivity/check"),c(et,"DEFAULT",Zs),c(et,"connectionStateZ",aa);let Ct=et;const yd=Object.freeze(Object.defineProperty({__proto__:null,Checker:Ct,state:aa,status:ia},Symbol.toStringTag,{value:"Module"})),gd=s.z.object({keys:ke.array().optional(),bounds:W.z,names:s.z.string().array().optional()}),pd=s.z.object({}),md="/frame/delete";class wd{constructor(e){c(this,"client");this.client=e}async delete(e){await w(this.client,md,e,gd,pd)}}const _s=r=>{const e=b(r);return e.length===0?null:typeof e[0]=="number"||!isNaN(parseInt(e[0]))?"key":"name"},Ys=(r,e)=>{const t=b(r);if(t.length===e.length)return;const n=_s(r);throw _s===null?new B("[Frame] - channel keys or names must be provided when constructing a frame."):new B(`[Frame] - ${n}s and series must be the same length.
36
36
  Got ${t.length} ${n}s and ${e.length} series.`)};class _{constructor(e=[],t=[]){c(this,"columns",[]);c(this,"series",[]);if(e instanceof _){this.columns=e.columns,this.series=e.series;return}if(e instanceof Map){e.forEach((i,a)=>this.push(a,...b(i)));return}if(typeof e=="object"&&!Array.isArray(e)){if("keys"in e&&"series"in e){const i=e;i.series??(i.series=[]),i.keys??(i.keys=[]);const a=i.series.map(o=>oa(o));Ys(i.keys,a),i.keys.forEach((o,l)=>this.push(o,a[l]))}else Object.entries(e).forEach(([i,a])=>{const o=parseInt(i);if(!isNaN(o))return this.push(o,...b(a));this.push(i,...b(a))});return}if(Array.isArray(e)||["string","number"].includes(typeof e)){const i=b(t),a=b(e);Ys(a,i),i.forEach((o,l)=>this.push(a[l],o));return}throw new B(`[Frame] - invalid frame construction parameters. data parameter ust be a frame
37
37
  payload, a list of lazy series, a lazy array, a map, or a record keyed by channel
38
- 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 Ee("colType is not key");return this.columns??[]}get uniqueKeys(){return zs(this.keys)}get names(){if(this.colType==="key")throw new Ee("colType is not name");return this.columns??[]}get uniqueNames(){return zs(this.names)}get uniqueColumns(){return this.colType==="key"?this.uniqueKeys:this.uniqueNames}toPayload(){return{series:this.series.map(e=>ca(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 W.ZERO;const n=I.min(...this.series.map(a=>a.timeRange.start)),i=I.max(...this.series.map(a=>a.timeRange.end));return new W(n,i)}const t=this.get(e);return t==null?W.ZERO:t.timeRange}latest(){return this.at(-1)}get timeRanges(){return this.uniqueColumns.map(e=>this.timeRange(e))}get(e){return Array.isArray(e)?this.filter(t=>e.includes(t)):new Ri(this.series.filter((t,n)=>this.columns[n]===e))}push(e,...t){if(e instanceof _){if(this.colType!==null&&e.colType!==this.colType)throw new B("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 B("keyVariant must match");if(typeof e!="string"&&this.colType==="name")throw new B("keyVariant must match");this.columns.push(...Array.from({length:t.length},()=>e))}}concat(e){return new _([...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 _;return this.forEach((n,i,a)=>t.push(...e(n,i,a))),t}forEach(e){this.columns.forEach((t,n)=>{const i=this.series[n];e(t,i,n)})}at(e,t=!1){const n={};return this.uniqueColumns.forEach(i=>{n[i]=this.get(i).at(e,t)}),n}filter(e){const t=new _;return this.columns.forEach((n,i)=>{const a=this.series[i];e(n,a,i)&&t.push(n,a)}),t}get byteLength(){return new st(this.series.reduce((e,t)=>e.add(t.byteLength),st.ZERO))}get digest(){const e={};return this.keys.forEach((t,n)=>{const i=this.series[n].digest;t in e?e[t].push(i):e[t]=[i]}),e}get length(){return this.series.reduce((e,t)=>e+t.length,0)}}const Rr=s.z.object({keys:s.z.union([s.z.null().transform(()=>[]),s.z.number().array().optional().default([])]),series:s.z.union([s.z.null().transform(()=>[]),Oe.crudeZ.array().optional().default([])])}),oa=r=>{const{dataType:e,data:t,timeRange:n,alignment:i}=r;return new Oe({data:t,dataType:e,timeRange:n,glBufferUsage:"static",alignment:i})},ca=r=>({timeRange:r._timeRange,dataType:r.dataType,data:new Uint8Array(r.data.buffer),alignment:r.alignment});class xr{constructor(e){c(this,"adapter");c(this,"retriever");c(this,"keys");this.retriever=e,this.adapter=null,this.keys=[]}static async open(e,t){const n=new xr(e);return await n.update(t),n}async update(e){const{variant:t,normalized:n}=we(e);if(t==="keys"){this.adapter=null,this.keys=n;return}const i=await this.retriever.retrieve(n),a=new Map;this.adapter=a,n.forEach(o=>{const l=i.find(u=>u.name===o);if(l==null)throw new Error(`Channel ${o} not found`);a.set(l.key,l.name)}),this.keys=Array.from(this.adapter.keys())}adapt(e){if(this.adapter==null)return e;const t=this.adapter;return e.map((n,i)=>{if(typeof n=="number"){const a=t.get(n);if(a==null)throw new Error(`Channel ${n} not found`);return[a,i]}return[n,i]})}}class Mn{constructor(e){c(this,"adapter");c(this,"retriever");c(this,"keys");this.retriever=e,this.adapter=null,this.keys=[]}static async open(e,t){const n=new Mn(e);return await n.update(t),n}async adaptObjectKeys(e){const t={};for(const[n,i]of Object.entries(e))t[await this.adaptToKey(n)]=i;return t}async update(e){const t=await Qi(this.retriever,e);this.adapter=new Map(t.map(n=>[n.name,n.key])),this.keys=t.map(n=>n.key)}async fetchChannel(e){const t=await this.retriever.retrieve(e);if(t.length===0)throw new Error(`Channel ${e} not found`);return t[0]}async adaptToKey(e){return typeof e=="number"?e:(await this.fetchChannel(e)).key}async adapt(e,t){if(typeof e=="string"||typeof e=="number"){if(t==null)throw new B(`
38
+ 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 Ee("colType is not key");return this.columns??[]}get uniqueKeys(){return gs(this.keys)}get names(){if(this.colType==="key")throw new Ee("colType is not name");return this.columns??[]}get uniqueNames(){return gs(this.names)}get uniqueColumns(){return this.colType==="key"?this.uniqueKeys:this.uniqueNames}toPayload(){return{series:this.series.map(e=>ca(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 W.ZERO;const n=I.min(...this.series.map(a=>a.timeRange.start)),i=I.max(...this.series.map(a=>a.timeRange.end));return new W(n,i)}const t=this.get(e);return t==null?W.ZERO:t.timeRange}latest(){return this.at(-1)}get timeRanges(){return this.uniqueColumns.map(e=>this.timeRange(e))}get(e){return Array.isArray(e)?this.filter(t=>e.includes(t)):new Ri(this.series.filter((t,n)=>this.columns[n]===e))}push(e,...t){if(e instanceof _){if(this.colType!==null&&e.colType!==this.colType)throw new B("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 B("keyVariant must match");if(typeof e!="string"&&this.colType==="name")throw new B("keyVariant must match");this.columns.push(...Array.from({length:t.length},()=>e))}}concat(e){return new _([...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 _;return this.forEach((n,i,a)=>t.push(...e(n,i,a))),t}forEach(e){this.columns.forEach((t,n)=>{const i=this.series[n];e(t,i,n)})}at(e,t=!1){const n={};return this.uniqueColumns.forEach(i=>{n[i]=this.get(i).at(e,t)}),n}filter(e){const t=new _;return this.columns.forEach((n,i)=>{const a=this.series[i];e(n,a,i)&&t.push(n,a)}),t}get byteLength(){return new st(this.series.reduce((e,t)=>e.add(t.byteLength),st.ZERO))}get digest(){const e={};return this.keys.forEach((t,n)=>{const i=this.series[n].digest;t in e?e[t].push(i):e[t]=[i]}),e}get length(){return this.series.reduce((e,t)=>e+t.length,0)}}const Rr=s.z.object({keys:s.z.union([s.z.null().transform(()=>[]),s.z.number().array().optional().default([])]),series:s.z.union([s.z.null().transform(()=>[]),Oe.crudeZ.array().optional().default([])])}),oa=r=>{const{dataType:e,data:t,timeRange:n,alignment:i}=r;return new Oe({data:t,dataType:e,timeRange:n,glBufferUsage:"static",alignment:i})},ca=r=>({timeRange:r._timeRange,dataType:r.dataType,data:new Uint8Array(r.data.buffer),alignment:r.alignment});class xr{constructor(e){c(this,"adapter");c(this,"retriever");c(this,"keys");this.retriever=e,this.adapter=null,this.keys=[]}static async open(e,t){const n=new xr(e);return await n.update(t),n}async update(e){const{variant:t,normalized:n}=we(e);if(t==="keys"){this.adapter=null,this.keys=n;return}const i=await this.retriever.retrieve(n),a=new Map;this.adapter=a,n.forEach(o=>{const l=i.find(u=>u.name===o);if(l==null)throw new Error(`Channel ${o} not found`);a.set(l.key,l.name)}),this.keys=Array.from(this.adapter.keys())}adapt(e){if(this.adapter==null)return e;const t=this.adapter;return e.map((n,i)=>{if(typeof n=="number"){const a=t.get(n);if(a==null)throw new Error(`Channel ${n} not found`);return[a,i]}return[n,i]})}}class Mn{constructor(e){c(this,"adapter");c(this,"retriever");c(this,"keys");this.retriever=e,this.adapter=null,this.keys=[]}static async open(e,t){const n=new Mn(e);return await n.update(t),n}async adaptObjectKeys(e){const t={};for(const[n,i]of Object.entries(e))t[await this.adaptToKey(n)]=i;return t}async update(e){const t=await Qi(this.retriever,e);this.adapter=new Map(t.map(n=>[n.name,n.key])),this.keys=t.map(n=>n.key)}async fetchChannel(e){const t=await this.retriever.retrieve(e);if(t.length===0)throw new Error(`Channel ${e} not found`);return t[0]}async adaptToKey(e){return typeof e=="number"?e:(await this.fetchChannel(e)).key}async adapt(e,t){if(typeof e=="string"||typeof e=="number"){if(t==null)throw new B(`
39
39
  Received a single channel name or key but no series.
40
40
  `);if(Array.isArray(t)){if(t.some(u=>u instanceof Oe||Array.isArray(u)))throw new B(`
41
41
  Received a single channel name or key but multiple series.
@@ -48,4 +48,4 @@
48
48
  `);const y=new Oe({data:t[u],dataType:h.dataType});o.push(h.key),l.push(y)}return new _(o,l)}if(e instanceof _||e instanceof Map){const o=new _(e);if(this.adapter==null)return o;const l=o.columns.map(u=>{var y;const h=typeof u=="string"?(y=this.adapter)==null?void 0:y.get(u):u;if(h==null)throw new B(`
49
49
  Channel ${u} was not provided in the list of channels when opening the writer
50
50
  `);return h});return new _(l,o.series)}const n=[],i=[],a=Object.entries(e);for(let o=0;o<a.length;o++){const[l,u]=a[o],h=await this.fetchChannel(l),y=new Oe({data:u,dataType:h.dataType});n.push(h.key),i.push(y)}return new _(n,i)}}class Bn{constructor(e,t){c(this,"name");c(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(){for(this.stream.closeSend();;){const[e,t]=await this.stream.receive();if(e!=null&&console.warn(`${this.name} received unexpected response on closure.
51
- Please report this error to the Synnax team. ${JSON.stringify(e)}`),t!=null){if(Ne.matches(t))return;throw t}}}closeSend(){this.stream.closeSend()}send(e){const t=this.stream.send(e);if(t!=null)throw t}}const Sn=new z(-1);var Un=(r=>(r[r.Open=0]="Open",r[r.Next=1]="Next",r[r.Prev=2]="Prev",r[r.SeekFirst=3]="SeekFirst",r[r.SeekLast=4]="SeekLast",r[r.SeekLE=5]="SeekLE",r[r.SeekGE=6]="SeekGE",r[r.Valid=7]="Valid",r[r.Error=8]="Error",r))(Un||{}),la=(r=>(r[r.None=0]="None",r[r.Ack=1]="Ack",r[r.Data=2]="Data",r))(la||{});const gd=s.z.object({command:s.z.nativeEnum(Un),span:z.z.optional(),bounds:W.z.optional(),stamp:I.z.optional(),keys:s.z.number().array().optional(),chunkSize:s.z.number().optional()}),pd=s.z.object({variant:s.z.nativeEnum(la),ack:s.z.boolean(),command:s.z.nativeEnum(Un),error:jt.optional().nullable(),frame:Rr.optional()}),$t=class $t{constructor(e,t){c(this,"stream");c(this,"adapter");c(this,"value");this.stream=new Bn("Iterator",e),this.value=new _,this.adapter=t}static async _open(e,t,n,i,a={}){const o=await xr.open(n,t),l=await i.stream($t.ENDPOINT,gd,pd),u=new $t(l,o);return await u.execute({command:0,keys:o.keys,bounds:new W(e),chunkSize:a.chunkSize??1e5}),u}async next(e=Sn){return await this.execute({command:1,span:new z(e)})}async prev(e=Sn){return await this.execute({command:2,span:new z(e)})}async seekFirst(){return await this.execute({command:3})}async seekLast(){return await this.execute({command:4})}async seekLE(e){return await this.execute({command:5,stamp:new I(e)})}async seekGE(e){return await this.execute({command:6,stamp:new I(e)})}async valid(){return await this.execute({command:7})}async close(){await this.stream.closeAndAck()}[Symbol.asyncIterator](){return new md(this)}async execute(e){for(this.stream.send(e),this.value=new _;;){const t=await this.stream.receive();if(t.variant===1)return t.ack;this.value.push(this.adapter.adapt(new _(t.frame)))}}};c($t,"ENDPOINT","/frame/iterate");let br=$t;class md{constructor(e){c(this,"iter");c(this,"open",!1);this.iter=e}async next(){try{let e=!0;return this.open||(await this.iter.seekFirst()||(e=!1),this.open=!0),await this.iter.next()||(e=!1),e||await this.iter.close(),{done:!e,value:this.iter.value}}catch(e){throw await this.iter.close(),e}}}const wd=s.z.object({keys:s.z.number().array(),downsampleFactor:s.z.number()}),bd=s.z.object({frame:Rr,error:jt.optional().nullable()}),vd="/frame/stream";class Cr{constructor(e,t){c(this,"stream");c(this,"adapter");c(this,"downsampleFactor");this.stream=new Bn("Streamer",e),this.adapter=t,this.downsampleFactor=1}get keys(){return this.adapter.keys}static async _open(e,t,{channels:n,downsampleFactor:i}){const a=await xr.open(e,n),o=await t.stream(vd,wd,bd),l=new Cr(o,a);o.send({keys:a.keys,downsampleFactor:i??1});const[,u]=await o.receive();if(u!=null)throw u;return l}async next(){try{return{done:!1,value:await this.read()}}catch(e){if(Ne.matches(e))return{done:!0,value:void 0};throw e}}async read(){return this.adapter.adapt(new _((await this.stream.receive()).frame))}async update(e){await this.adapter.update(e),this.stream.send({keys:this.adapter.keys,downsampleFactor:this.downsampleFactor})}close(){this.stream.closeSend()}[Symbol.asyncIterator](){return this}}class Ce extends Re.Observer{constructor(t,n){super(n);c(this,"streamer");c(this,"closePromise");this.streamer=t,this.closePromise=this.stream()}async close(){this.streamer.close(),await this.closePromise}async stream(){for await(const t of this.streamer)this.notify(t)}}var Zn=(r=>(r[r.Open=0]="Open",r[r.Write=1]="Write",r[r.Commit=2]="Commit",r[r.Error=3]="Error",r[r.SetAuthority=4]="SetAuthority",r))(Zn||{}),ot=(r=>(r[r.PersistStream=1]="PersistStream",r[r.Persist=2]="Persist",r[r.Stream=3]="Stream",r))(ot||{});const Td=r=>{switch(r){case"persist":return 2;case"stream":return 3;case"persistStream":return 1;default:if(typeof r=="number"&&r in ot)return r;throw new Error(`invalid writer mode: ${r}`)}},Od=new z(-1),zd=s.z.object({start:I.z.optional(),controlSubject:it.subjectZ.optional(),keys:s.z.number().array().optional(),authorities:it.Authority.z.array().optional(),mode:s.z.nativeEnum(ot).optional(),errOnUnauthorized:s.z.boolean().optional(),enableAutoCommit:s.z.boolean().optional(),autoIndexPersistInterval:z.z.optional()}),Ed=s.z.object({command:s.z.nativeEnum(Zn),config:zd.optional(),frame:Rr.optional()}),Nd=s.z.object({ack:s.z.boolean(),command:s.z.nativeEnum(Zn),error:jt.optional().nullable()});var ze;let ua=(ze=class{constructor(e,t){c(this,"stream");c(this,"adapter");this.stream=new Bn("Writer",e),this.adapter=t}static async _open(e,t,{channels:n,start:i=I.now(),authorities:a=it.Authority.Absolute,controlSubject:o,mode:l=1,errOnUnauthorized:u=!1,enableAutoCommit:h=!1,autoIndexPersistInterval:y=z.SECOND}){const d=await Mn.open(e,n),j=await t.stream(ze.ENDPOINT,Ed,Nd),$=new ze(j,d);return await $.execute({command:0,config:{start:new I(i),keys:d.keys,controlSubject:o,authorities:b(a),mode:Td(l),errOnUnauthorized:u,enableAutoCommit:h,autoIndexPersistInterval:y}}),$}async write(e,t){const n=await this.adapter.adapt(e,t);return this.stream.send({command:1,frame:n.toPayload()}),!0}async setAuthority(e,t){let n;if(typeof e=="number"&&t==null)n={keys:[],authorities:[e]};else{let a;typeof e=="string"||typeof e=="number"?a={[e]:t}:a=e,a=await this.adapter.adaptObjectKeys(a),n={keys:Object.keys(a).map(o=>Number(o)),authorities:Object.values(a)}}return(await this.execute({command:4,config:n})).ack}async commit(){return this.errorAccumulated?!1:(await this.execute({command:2})).ack}async error(){this.stream.send({command:3});const e=await this.execute({command:3});return e.error!=null?yr(e.error):null}async close(){await this.stream.closeAndAck()}async execute(e){for(this.stream.send(e);;){const t=await this.stream.receive();if(t.command===e.command)return t;console.warn("writer received unexpected response",t)}}get errorAccumulated(){return this.stream.received()}},c(ze,"ENDPOINT","/frame/write"),ze);const ha="framer",Sd=r=>new O({type:ha,key:r.toString()});let da=class{constructor(e,t,n){c(this,"streamClient");c(this,"retriever");c(this,"deleter");this.streamClient=e,this.retriever=n,this.deleter=new yd(t)}async openIterator(e,t,n){return await br._open(e,t,this.retriever,this.streamClient,n)}async openWriter(e){return(Array.isArray(e)||typeof e!="object")&&(e={channels:e}),await ua._open(this.retriever,this.streamClient,e)}async openStreamer(e){return(Array.isArray(e)||typeof e!="object")&&(e={channels:e,downsampleFactor:1}),await Cr._open(this.retriever,this.streamClient,e)}async write(e,t,n){if(n==null){const a=t,o=await this.openWriter({start:e,channels:Object.keys(a),mode:ot.Persist});try{await o.write(a),await o.commit()}finally{await o.close()}return}const i=await this.openWriter({start:e,channels:t,mode:ot.Persist,errOnUnauthorized:!0,enableAutoCommit:!0,autoIndexPersistInterval:z.MAX});try{await i.write(t,n)}finally{await i.close()}}async read(e,t){const{single:n}=we(t),i=await this.readFrame(e,t);return n?i.get(t):i}async readFrame(e,t){const n=await this.openIterator(e,t),i=new _;try{for await(const a of n)i.push(a)}finally{await n.close()}return i}async delete(e,t){const{normalized:n,variant:i}=we(e);return i==="keys"?await this.deleter.delete({keys:n,bounds:t}):await this.deleter.delete({names:n,bounds:t})}};const Id=Object.freeze(Object.defineProperty({__proto__:null,ALWAYS_INDEX_PERSIST_ON_AUTO_COMMIT:Od,AUTO_SPAN:Sn,Client:da,Frame:_,Iterator:br,ONTOLOGY_TYPE:ha,ObservableStreamer:Ce,Streamer:Cr,Writer:ua,WriterMode:ot,frameZ:Rr,ontologyID:Sd,seriesFromPayload:oa,seriesToPayload:ca},Symbol.toStringTag,{value:"Module"})),kd=it.Authority,$d=it.stateZ(s.z.number()),Ad=r=>{var e,t;return r.to==null?`${(e=r.from)==null?void 0:e.resource} - ${(t=r.from)==null?void 0:t.subject.name} -> released`:r.from==null?`${r.to.resource} - released -> ${r.to.subject.name} (${r.to.authority.toString()})`:`${r.to.resource} - ${r.from.subject.name} -> ${r.to.subject.name} (${r.to.authority.toString()})`};class fa extends Ce{constructor(t){super(t,n=>{const i=this.codec.decode(n.series[0].buffer);return this.merge(i),[i.transfers,!0]});c(this,"states");c(this,"codec");this.states=new Map,this.codec=new ct.JSONCodec}subjects(){const t=new Map;return this.states.forEach(n=>t.set(n.subject.key,n.subject)),Array.from(t.values())}merge(t){t.transfers.forEach(n=>{n.from==null&&n.to==null&&console.warn("Invalid transfer: ",n),n.to==null?this.states.delete(n.from.resource):this.states.set(n.to.resource,n.to)})}}const Rd="sy_node_1_control";let ya=class{constructor(e){c(this,"framer");this.framer=e}async openStateTracker(){const e=await this.framer.openStreamer(Rd);return new fa(e)}};const xd=Object.freeze(Object.defineProperty({__proto__:null,Authority:kd,Client:ya,StateTracker:fa,stateZ:$d,transferString:Ad},Symbol.toStringTag,{value:"Module"}));let ga=class{constructor(e,t,n){c(this,"tasks");c(this,"racks");c(this,"devices");this.tasks=e,this.racks=t,this.devices=n}};const Cd=Object.freeze(Object.defineProperty({__proto__:null,Client:ga},Symbol.toStringTag,{value:"Module"})),ht=s.z.number(),Pr=s.z.object({key:ht,name:s.z.string()}),pa=Pr.partial({key:!0}),ma="rack",Pd=r=>new O({type:ma,key:r.toString()}),Dr=s.z.string(),qt=s.z.object({key:Dr,rack:ht,name:s.z.string(),make:s.z.string(),model:s.z.string(),location:s.z.string(),configured:s.z.boolean().optional(),properties:s.z.record(s.z.unknown()).or(s.z.string().transform(r=>r===""?{}:ct.JSON_CODEC.decodeString(r)))}),wa=qt.extend({properties:s.z.unknown().transform(r=>ct.JSON_CODEC.encodeString(r))}),ba="device",Dd=r=>new O({type:ba,key:r.toString()}),Pe=async(r,e,t,n)=>{const i=await r.openStreamer([e,t]),a=o=>{const l=[];return t!=null&&l.push(...o.get(t).series.flatMap(u=>n("delete",u))),e!=null&&l.push(...o.get(e).series.flatMap(u=>n("set",u))),[l,l.length>0]};return new Ce(i,a)},jd=Object.freeze(Object.defineProperty({__proto__:null,openObservable:Pe},Symbol.toStringTag,{value:"Module"})),Md="sy_device_set",Bd="sy_device_delete",Hr="/hardware/device/retrieve",Ud="/hardware/device/create",Zd="/hardware/device/delete",Ld=s.z.object({devices:wa.array()}),_d=s.z.object({devices:qt.array()}),Yd=s.z.object({keys:Dr.array()}),qd=s.z.object({}),Xr=s.z.object({search:s.z.string().optional(),limit:s.z.number().optional(),offset:s.z.number().optional(),keys:Dr.array().optional(),names:s.z.string().array().optional(),makes:s.z.string().array().optional()}),Qr=s.z.object({devices:X(qt)});let va=class{constructor(e,t){c(this,"type","device");c(this,"client");c(this,"frameClient");this.client=e,this.frameClient=t}async retrieve(e,t){const n=!Array.isArray(e),i=await w(this.client,Hr,{keys:b(e),...t},Xr,Qr);return Ar("Device",e,i.devices,n),n?i.devices[0]:i.devices}async search(e,t){return(await w(this.client,Hr,{search:e,...t},Xr,Qr)).devices}async page(e,t,n){return(await w(this.client,Hr,{offset:e,limit:t,...n},Xr,Qr)).devices}async create(e){const t=!Array.isArray(e),n=await w(this.client,Ud,{devices:b(e)},Ld,_d);return t?n.devices[0]:n.devices}async delete(e){await w(this.client,Zd,{keys:b(e)},Yd,qd)}async openDeviceTracker(){return await Pe(this.frameClient,Md,Bd,Wd)}newSearcherWithOptions(e){return{type:this.type,search:async t=>await this.search(t,e),retrieve:async t=>await this.retrieve(t,e),page:async(t,n)=>await this.page(t,n,e)}}};const Wd=(r,e)=>r==="delete"?e.toStrings().map(t=>({variant:r,key:t,value:void 0})):e.parseJSON(qt).map(t=>({variant:r,key:t.key,value:t})),Gd=Object.freeze(Object.defineProperty({__proto__:null,Client:va,ONTOLOGY_TYPE:ba,deviceKeyZ:Dr,deviceZ:qt,newDeviceZ:wa,ontologyID:Dd},Symbol.toStringTag,{value:"Module"})),en="/hardware/rack/retrieve",Vd="/hardware/rack/create",Fd="/hardware/rack/delete",tn=s.z.object({keys:ht.array().optional(),names:s.z.string().array().optional(),search:s.z.string().optional(),offset:s.z.number().optional(),limit:s.z.number().optional()}),rn=s.z.object({racks:X(Pr)}),Jd=s.z.object({racks:pa.array()}),Kd=s.z.object({racks:Pr.array()}),Hd=s.z.object({keys:ht.array()}),Xd=s.z.object({});let Ta=class{constructor(e,t,n){c(this,"type","rack");c(this,"client");c(this,"frameClient");c(this,"tasks");this.client=e,this.frameClient=t,this.tasks=n}async delete(e){await w(this.client,Fd,{keys:b(e)},Hd,Xd)}async create(e){const t=!Array.isArray(e),n=await w(this.client,Vd,{racks:b(e)},Jd,Kd),i=this.sugar(n.racks);return t?i[0]:i}async search(e){const t=await w(this.client,en,{search:e},tn,rn);return this.sugar(t.racks)}async page(e,t){const n=await w(this.client,en,{offset:e,limit:t},tn,rn);return this.sugar(n.racks)}async retrieve(e){const{variant:t,normalized:n,single:i}=$r(e,{string:"names",number:"keys"}),a=await w(this.client,en,{[t]:n},tn,rn),o=this.sugar(a.racks);return Ar("Rack",e,o,i),i?o[0]:o}sugar(e){return e.map(({key:t,name:n})=>new Oa(t,n,this.tasks))}};class Oa{constructor(e,t,n){c(this,"key");c(this,"name");c(this,"tasks");this.key=e,this.name=t,this.tasks=n}async listTasks(){return await this.tasks.retrieve(this.key)}async retrieveTaskByName(e){return await this.tasks.retrieveByName(e,this.key)}async createTask(e){return e.key=((BigInt(this.key)<<32n)+(BigInt(e.key??0)&0xffffffffn)).toString(),await this.tasks.create(e)}async deleteTask(e){await this.tasks.delete([e])}}const Qd=Object.freeze(Object.defineProperty({__proto__:null,Client:Ta,ONTOLOGY_TYPE:ma,Rack:Oa,newRackZ:pa,ontologyID:Pd,rackKeyZ:ht,rackZ:Pr},Symbol.toStringTag,{value:"Module"})),De=s.z.union([s.z.string(),s.z.bigint().transform(r=>r.toString()),s.z.number().transform(r=>r.toString())]),Pt=s.z.object({task:De,variant:s.z.string(),key:s.z.string().optional(),details:s.z.record(s.z.unknown()).or(s.z.string().transform(r=>r===""?{}:JSON.parse(r))).or(s.z.array(s.z.unknown())).or(s.z.null())}),Wt=s.z.object({key:De,name:s.z.string(),type:s.z.string(),internal:s.z.boolean().optional(),config:s.z.record(s.z.unknown()).or(s.z.string().transform(r=>r===""?{}:ct.JSON_CODEC.decodeString(r))),state:Pt.optional().nullable(),snapshot:s.z.boolean().optional()}),za=Wt.omit({key:!0}).extend({key:De.transform(r=>r.toString()).optional(),config:s.z.unknown().transform(r=>ct.JSON_CODEC.encodeString(r))}),Ln=s.z.object({task:De,type:s.z.string(),key:s.z.string(),args:s.z.record(s.z.unknown()).or(s.z.string().transform(r=>r===""?{}:JSON.parse(r))).or(s.z.array(s.z.unknown())).or(s.z.null()).optional()}),Ea="task",ef=r=>new O({type:Ea,key:r.toString()}),kt="sy_task_state",Ze="sy_task_cmd",ft=new Error("Task not created");class Na{constructor(e,t,n,i,a=!1,o=!1,l,u=null,h=null,y=null){c(this,"key");c(this,"name");c(this,"internal");c(this,"type");c(this,"config");c(this,"snapshot");c(this,"state");c(this,"frameClient");c(this,"ontologyClient");c(this,"rangeClient");this.key=e,this.name=t,this.type=n,this.config=i,this.internal=a,this.snapshot=o,l!==null&&(this.state=l),this.frameClient=u,this.ontologyClient=h,this.rangeClient=y}get payload(){return{key:this.key,name:this.name,type:this.type,config:this.config,state:this.state,internal:this.internal}}get ontologyID(){return new O({type:"task",key:this.key})}async executeCommand(e,t){if(this.frameClient==null)throw ft;const n=await this.frameClient.openWriter(Ze),i=Kl.id();return await n.write(Ze,[{task:this.key,type:e,key:i,args:t}]),await n.close(),i}async executeCommandSync(e,t,n){if(this.frameClient==null)throw ft;const i=await this.frameClient.openStreamer(kt),a=await this.executeCommand(e,t);let o;const l=new Promise(u=>setTimeout(()=>u(!1),new z(n).milliseconds));for(;;){const u=await Promise.any([i.read(),l]);if(u===!1)throw new Error("Command timed out");const h=Pt.safeParse(u.at(-1).sy_task_state);if(h.success){if(o=h.data,o.key===a)break}else console.error(h.error)}return i.close(),o}async openStateObserver(){if(this.frameClient==null)throw ft;return new Ce(await this.frameClient.openStreamer(kt),e=>{const t=e.get(kt);if(t.length===0)return[null,!1];const n=Pt.safeParse(t.at(-1));if(!n.success)return console.error(n.error),[null,!1];const i=n.data;return i.task!==this.key?[null,!1]:[i,!0]})}async openCommandObserver(){if(this.frameClient==null)throw ft;return new Ce(await this.frameClient.openStreamer(Ze),e=>{const t=e.get(Ze);if(t.length===0)return[null,!1];const n=Ln.safeParse(t.at(-1));if(!n.success)return console.error(n.error),[null,!1];const i=n.data;return i.task!==this.key?[null,!1]:[i,!0]})}async snapshottedTo(){if(this.ontologyClient==null||this.rangeClient==null)throw ft;if(!this.snapshot)return null;const e=await this.ontologyClient.retrieveParents(this.ontologyID);return e.length==0?null:e[0]}}const tf=s.z.object({rack:ht.optional(),keys:s.z.string().array().optional(),names:s.z.string().array().optional(),offset:s.z.number().optional(),limit:s.z.number().optional(),includeState:s.z.boolean().optional()}),rf=s.z.object({tasks:X(Wt)}),nf="/hardware/task/retrieve",sf="/hardware/task/create",af="/hardware/task/delete",of="/hardware/task/copy",cf=s.z.object({tasks:za.array()}),lf=s.z.object({tasks:Wt.array()}),uf=s.z.object({keys:De.array()}),hf=s.z.object({}),df=s.z.object({key:De,name:s.z.string(),snapshot:s.z.boolean()}),ff=s.z.object({task:Wt});let Sa=class{constructor(e,t,n,i){c(this,"type","task");c(this,"client");c(this,"frameClient");c(this,"ontologyClient");c(this,"rangeClient");this.client=e,this.frameClient=t,this.ontologyClient=n,this.rangeClient=i}async create(e){const t=!Array.isArray(e),n=await w(this.client,sf,{tasks:b(e)},cf,lf),i=this.sugar(n.tasks);return t?i[0]:i}async delete(e){await w(this.client,af,{keys:b(e)},uf,hf)}async search(e){return await this.execRetrieve({keys:[e]})}async page(e,t){return await this.execRetrieve({offset:e,limit:t})}async list(e={}){return this.sugar(await this.execRetrieve(e))}async retrieve(e,t){const{single:n,normalized:i,variant:a}=$r(e,{number:"rack",string:"keys"},{convertNumericStrings:!1}),o={...t};a==="rack"?o.rack=e:o.keys=i;const l=await this.execRetrieve(o),u=this.sugar(l);return n&&a!=="rack"?u[0]:u}async copy(e,t,n){const i=await w(this.client,of,{key:e,name:t,snapshot:n},df,ff);return this.sugar([i.task])[0]}async retrieveByName(e,t){const n=await this.execRetrieve({names:[e],rack:t});return Ar("Task",e,n,!0),this.sugar(n)[0]}async execRetrieve(e){return(await w(this.client,nf,e,tf,rf)).tasks}sugar(e){return e.map(({key:t,name:n,type:i,config:a,state:o,internal:l,snapshot:u})=>new Na(t,n,i,a,l,u,o,this.frameClient,this.ontologyClient,this.rangeClient))}async openTracker(){return await Pe(this.frameClient,"sy_task_set","sy_task_delete",(e,t)=>Array.from(t).map(n=>({variant:e,key:n.toString(),value:n.toString()})))}async openStateObserver(){return new Ce(await this.frameClient.openStreamer(kt),e=>{const t=e.get(kt);if(t.length===0)return[null,!1];const n=Pt.safeParse(t.at(-1));return n.success?[n.data,!0]:(console.error(n.error),[null,!1])})}async openCommandObserver(){return new Ce(await this.frameClient.openStreamer(Ze),e=>{const t=e.get(Ze);if(t.length===0)return[null,!1];const n=Ln.safeParse(t.at(-1));return n.success?[n.data,!0]:(console.error(n.error),[null,!1])})}};const yf=Object.freeze(Object.defineProperty({__proto__:null,Client:Sa,ONTOLOGY_TYPE:Ea,Task:Na,commandZ:Ln,newTaskZ:za,ontologyID:ef,stateZ:Pt,taskKeyZ:De,taskZ:Wt},Symbol.toStringTag,{value:"Module"})),dt=s.z.string().uuid(),Gt=s.z.object({key:dt,name:s.z.string().min(1),color:s.z.string()}),Ia="label",gf=r=>new O({type:Ia,key:r}),pf=s.z.object({keys:dt.array().optional(),for:H.optional(),search:s.z.string().optional(),offset:s.z.number().optional(),limit:s.z.number().optional()}),mf=s.z.object({labels:X(Gt)}),Or=class Or{constructor(e){c(this,"client");this.client=e}async retrieve(e){const t=b(e);return await this.execute({keys:t})}async retrieveFor(e){return await this.execute({for:e})}async search(e){return await this.execute({search:e})}async page(e,t){return await this.execute({offset:e,limit:t})}async execute(e){const[t,n]=await this.client.send(Or.ENDPOINT,e,pf,mf);if(n!=null)throw n;return t.labels}};c(Or,"ENDPOINT","/label/retrieve");let vr=Or;const ka=Gt.extend({key:dt.optional()}),wf=s.z.object({labels:ka.array()}),bf=s.z.object({labels:Gt.array()}),vf=s.z.object({keys:dt.array()}),$a=s.z.object({id:H,labels:dt.array(),replace:s.z.boolean().optional()}),Tf=$a.omit({replace:!0}),nn=s.z.object({}),Of="/label/create",zf="/label/delete",Ef="/label/set",Nf="/label/remove";let Aa=class{constructor(e){c(this,"client");this.client=e}async create(e){return(await w(this.client,Of,{labels:b(e)},wf,bf)).labels}async delete(e){await w(this.client,zf,{keys:b(e)},vf,nn)}async set(e,t,{replace:n}={}){await w(this.client,Ef,{id:e,labels:t,replace:n},$a,nn)}async remove(e,t){await w(this.client,Nf,{id:e,labels:t},Tf,nn)}};const Sf="sy_label_set",If="sy_label_delete";let Ra=class{constructor(e,t,n){c(this,"type","label");c(this,"retriever");c(this,"writer");c(this,"frameClient");c(this,"ontology");this.writer=new Aa(e),this.retriever=new vr(e),this.frameClient=t,this.ontology=n}async search(e){return await this.retriever.search(e)}async retrieve(e){const t=Array.isArray(e),n=await this.retriever.retrieve(e);return t?n:n[0]}async retrieveFor(e){return await this.retriever.retrieveFor(new O(e))}async label(e,t,n={}){await this.writer.set(new O(e),t,n)}async removeLabels(e,t){await this.writer.remove(new O(e),t)}async page(e,t){return await this.retriever.page(e,t)}async create(e){const t=Array.isArray(e),n=await this.writer.create(e);return t?n:n[0]}async delete(e){await this.writer.delete(e)}async openChangeTracker(){return await Pe(this.frameClient,Sf,If,kf)}async trackLabelsOf(e){const t=new Re.Observer,n=(await this.retrieveFor(e)).map(a=>({id:new O({key:a.key,type:"label"}),key:a.key,name:a.name,data:a}));return(await this.ontology.openDependentTracker({target:new O(e),dependents:n,relationshipType:"labeled_by"})).onChange(a=>t.notify(a.map(o=>{var l,u;return{key:o.id.key,color:(l=o.data)==null?void 0:l.color,name:(u=o.data)==null?void 0:u.name}}))),t}};const kf=(r,e)=>r==="delete"?e.toUUIDs().map(t=>({variant:r,key:t})):e.parseJSON(Gt).map(t=>({variant:r,key:t.key,value:t})),$f=Object.freeze(Object.defineProperty({__proto__:null,Client:Ra,ONTOLOGY_TYPE:Ia,Retriever:vr,Writer:Aa,keyZ:dt,labelZ:Gt,newLabelPayloadZ:ka,ontologyID:gf},Symbol.toStringTag,{value:"Module"})),ee=s.z.string().uuid(),Vt=s.z.object({key:ee,name:s.z.string().min(1),timeRange:W.z,color:s.z.string().optional()}),xa=Vt.extend({key:s.z.string().uuid().optional()}),Ca=r=>{const e=b(r),t=e.length===0;let n=!1;return t||(n=ee.safeParse(e[0]).success),{single:!Array.isArray(r),variant:n?"keys":"names",normalized:e,actual:r,empty:t}},Pa="range",Da="range-alias",Af=r=>new O({type:Pa,key:r}),Rf=r=>new O({type:Da,key:r}),xf="sy_range_alias_set",Cf="sy_range_alias_delete",Pf=s.z.object({range:ee,aliases:s.z.string().array()}),Df=s.z.object({aliases:s.z.record(s.z.string(),ke)}),jf=s.z.object({range:ee,aliases:s.z.record(ke.or(s.z.string()),s.z.string())}),Mf=s.z.unknown(),Bf=s.z.object({range:ee,channels:ke.array()}),Uf=s.z.unknown(),Zf=s.z.object({range:ee}),Lf=s.z.object({aliases:s.z.record(s.z.string(),s.z.string())}),he=class he{constructor(e,t,n){c(this,"frameClient");c(this,"cache",new Map);c(this,"client");c(this,"rangeKey");this.rangeKey=e,this.cache=new Map,this.client=n,this.frameClient=t}async resolve(e){const t=[],n=typeof e=="string",i={};if(n){const o=this.cache.get(e);if(o!=null)return o;t.push(e)}else e.forEach(o=>{const l=this.cache.get(o);l!=null?i[o]=l:t.push(o)});if(t.length===0)return i;const a=await w(this.client,he.RESOLVE_ENDPOINT,{range:this.rangeKey,aliases:t},Pf,Df);return Object.entries(a.aliases).forEach(([o,l])=>this.cache.set(o,l)),n?a.aliases[t[0]]:{...i,...a.aliases}}async set(e){await w(this.client,he.SET_ENDPOINT,{range:this.rangeKey,aliases:e},jf,Mf)}async list(){return(await w(this.client,he.LIST_ENDPOINT,{range:this.rangeKey},Zf,Lf)).aliases}async delete(e){await w(this.client,he.DELETE_ENDPOINT,{range:this.rangeKey,channels:e},Bf,Uf)}async openChangeTracker(){return await Pe(this.frameClient,xf,Cf,qf(this.rangeKey))}};c(he,"SET_ENDPOINT","/range/alias/set"),c(he,"RESOLVE_ENDPOINT","/range/alias/resolve"),c(he,"LIST_ENDPOINT","/range/alias/list"),c(he,"DELETE_ENDPOINT","/range/alias/delete");let In=he;const _f=s.z.object({range:ee,channel:ke,alias:s.z.string()}),Yf="---",qf=r=>(e,t)=>e==="delete"?t.toStrings().filter(n=>n.split(Yf)[0]===r).map(n=>({variant:e,key:n,value:void 0})):t.parseJSON(_f).map(n=>({variant:e,key:n.alias,value:n})),Wf=s.z.object({range:ee,keys:s.z.string().array()}),_n=s.z.object({range:ee,key:s.z.string(),value:s.z.string()}),Gf=s.z.object({pairs:X(_n)}),Vf=s.z.object({range:ee,pairs:_n.array()}),Ff=s.z.object({range:ee,keys:s.z.string().array()}),Te=class Te{constructor(e,t,n){c(this,"rangeKey");c(this,"client");c(this,"frameClient");this.rangeKey=e,this.client=t,this.frameClient=n}async get(e){const t=await w(this.client,Te.GET_ENDPOINT,{range:this.rangeKey,keys:b(e)},Wf,Gf);return typeof e=="string"?t.pairs[0].value:Object.fromEntries(t.pairs.map(n=>[n.key,n.value]))}async list(){return this.get([])}async set(e,t=""){let n;An(e)?n=Object.entries(e).map(([i,a])=>({range:this.rangeKey,key:i,value:a})):n=[{range:this.rangeKey,key:e,value:t}],await w(this.client,Te.SET_ENDPOINT,{range:this.rangeKey,pairs:n},Vf,s.z.unknown())}async delete(e){await w(this.client,Te.DELETE_ENDPOINT,{range:this.rangeKey,keys:b(e)},Ff,s.z.unknown())}async openTracker(){return await Pe(this.frameClient,"sy_range_kv_set","sy_range_kv_delete",(e,t)=>e==="delete"?t.toStrings().map(n=>{const[i,a]=n.split("<--->",2);return{variant:e,key:n,value:{range:i,key:a,value:""}}}):t.parseJSON(_n).map(n=>({variant:e,key:`${n.range}${n.key}`,value:n})))}};c(Te,"GET_ENDPOINT","/range/kv/get"),c(Te,"SET_ENDPOINT","/range/kv/set"),c(Te,"DELETE_ENDPOINT","/range/kv/delete");let Dt=Te;const sn=r=>new O({type:"range",key:r});class ja{constructor(e,t=W.ZERO,n,i,a,o,l,u,h,y,d){c(this,"key");c(this,"name");c(this,"kv");c(this,"timeRange");c(this,"color");c(this,"channels");c(this,"aliaser");c(this,"frameClient");c(this,"labelClient");c(this,"ontologyClient");c(this,"rangeClient");this.key=n,this.name=e,this.timeRange=t,this.frameClient=a,this.color=i,this.kv=o,this.aliaser=l,this.channels=u,this.labelClient=h,this.ontologyClient=y,this.rangeClient=d}get ontologyID(){return new O({key:this.key,type:"range"})}get payload(){return{key:this.key,name:this.name,timeRange:this.timeRange,color:this.color}}async setAlias(e,t){const n=await this.channels.retrieve(e);if(n.length===0)throw new re(`Channel ${e} does not exist`);await this.aliaser.set({[n[0].key]:t})}async deleteAlias(...e){await this.aliaser.delete(e)}async listAliases(){return await this.aliaser.list()}async resolveAlias(e){return await this.aliaser.resolve(e)}async openAliasTracker(){return await this.aliaser.openChangeTracker()}async retrieveParent(){return this.rangeClient.retrieveParent(this.key)}async retrieveChildren(){const e=(await this.ontologyClient.retrieveChildren(this.ontologyID,{excludeFieldData:!0,types:["range"]})).map(t=>t.id.key);return await this.rangeClient.retrieve(e)}async read(e){return await this.frameClient.read(this.timeRange,e)}async labels(){return await this.labelClient.retrieveFor(sn(this.key))}async addLabel(...e){await this.labelClient.label(sn(this.key),e)}async removeLabel(...e){await this.labelClient.removeLabels(sn(this.key),e)}async openChildRangeTracker(){const e=new Re.Observer,t=(await this.retrieveChildren()).map(i=>{const a=new O({key:i.key,type:"range"});return{id:a,key:a.toString(),name:i.name,data:i.payload}}),n=await this.ontologyClient.openDependentTracker({target:this.ontologyID,dependents:t,resourceType:"range"});return n.onChange(i=>e.notify(this.rangeClient.resourcesToRanges(i))),e.setCloser(async()=>await n.close()),e}async openParentRangeTracker(){const e=new Re.Observer,t=await this.retrieveParent();if(t==null)return null;const n=new O({key:t.key,type:"range"}),i={id:n,key:n.toString(),name:t.name,data:t.payload},a=await this.ontologyClient.openDependentTracker({target:this.ontologyID,dependents:[i],relationshipDirection:"to"});return a.onChange(o=>{const l=this.rangeClient.resourcesToRanges(o);if(l.length===0)return;const u=l[0];e.notify(u)}),e.setCloser(async()=>await a.close()),e}}const Jf=(r,e)=>Xl(r.timeRange,e.timeRange),Kf=s.z.object({keys:ee.array().optional(),names:s.z.array(s.z.string()).optional(),term:s.z.string().optional(),overlapsWith:W.z.optional(),limit:s.z.number().int().optional(),offset:s.z.number().int().optional()}),Hf="/range/retrieve",Xf=s.z.object({ranges:X(Vt)});let Ma=class{constructor(e,t,n,i,a,o){c(this,"type","range");c(this,"frameClient");c(this,"writer");c(this,"unaryClient");c(this,"channels");c(this,"labelClient");c(this,"ontologyClient");this.frameClient=e,this.writer=t,this.unaryClient=n,this.channels=i,this.labelClient=a,this.ontologyClient=o}async create(e,t){const n=!Array.isArray(e),i=this.sugarMany(await this.writer.create(b(e),t));return n?i[0]:i}async rename(e,t){await this.writer.rename(e,t)}async delete(e){await this.writer.delete(b(e))}async search(e){return this.sugarMany(await this.execRetrieve({term:e}))}async page(e,t){return this.sugarMany(await this.execRetrieve({offset:e,limit:t}))}async retrieve(e){if(typeof e=="object"&&"start"in e)return await this.execRetrieve({overlapsWith:new W(e)});const{single:t,actual:n,variant:i,normalized:a,empty:o}=Ca(e);if(o)return[];const l=await this.execRetrieve({[i]:a});if(!t)return l;if(l.length===0)throw new pe(`range matching ${n} not found`);if(l.length>1)throw new me(`multiple ranges matching ${n} found`);return l[0]}getKV(e){return new Dt(e,this.unaryClient,this.frameClient)}async execRetrieve(e){const{ranges:t}=await w(this.unaryClient,Hf,e,Kf,Xf);return this.sugarMany(t)}async retrieveParent(e){const t=await this.ontologyClient.retrieveParents({key:e,type:"range"});if(t.length===0)return null;const n=t[0];return n.id.type!=="range"?null:await this.retrieve(n.id.key)}sugarOne(e){return new ja(e.name,e.timeRange,e.key,e.color,this.frameClient,new Dt(e.key,this.unaryClient,this.frameClient),new In(e.key,this.frameClient,this.unaryClient),this.channels,this.labelClient,this.ontologyClient,this)}sugarMany(e){return e.map(t=>this.sugarOne(t))}async openTracker(){return await Pe(this.frameClient,"sy_range_set","sy_range_delete",(e,t)=>e==="delete"?t.toStrings().map(i=>({variant:e,key:i,value:void 0})):this.sugarMany(t.parseJSON(Vt)).map(i=>({variant:e,key:i.key,value:i})))}resourcesToRanges(e){return e.map(t=>this.resourceToRange(t))}resourceToRange(e){var t,n,i;return this.sugarOne({key:e.id.key,name:(t=e.data)==null?void 0:t.name,timeRange:new W((n=e.data)==null?void 0:n.timeRange),color:(i=e.data)==null?void 0:i.color})}};const Qf=s.z.object({ranges:Vt.array()}),ey=s.z.object({parent:H.optional(),ranges:xa.array()}),ty=s.z.object({keys:ee.array()}),ry=s.z.object({}),ny=s.z.object({key:ee,name:s.z.string()}),sy=s.z.object({}),iy="/range/create",ay="/range/delete",oy="/range/rename";class Ba{constructor(e){c(this,"client");this.client=e}async rename(e,t){await w(this.client,oy,{key:e,name:t},ny,sy)}async create(e,t){return(await w(this.client,iy,{ranges:e,...t},ey,Qf)).ranges}async delete(e){await w(this.client,ay,{keys:e},ty,ry)}}const cy=Object.freeze(Object.defineProperty({__proto__:null,ALIAS_ONTOLOGY_TYPE:Da,Client:Ma,KV:Dt,ONTOLOGY_TYPE:Pa,Range:ja,Writer:Ba,analyzeParams:Ca,keyZ:ee,newPayloadZ:xa,payloadZ:Vt,rangeAliasOntologyID:Rf,rangeOntologyID:Af,sort:Jf},Symbol.toStringTag,{value:"Module"})),ly="/api/v1/";class uy{constructor(e,t={},n=!1){c(this,"url");c(this,"unary");c(this,"stream");c(this,"secure");this.secure=n,this.url=e.child(ly);const i=new ct.JSONCodec;this.unary=jc(new Dc(this.url,i,this.secure),t),this.stream=new Wc(this.url,i,this.secure)}use(...e){this.unary.use(...e),this.stream.use(...e)}}const Ft=s.z.string().uuid(),jr=s.z.object({key:s.z.string(),name:s.z.string(),data:Mt.or(s.z.string().transform(r=>JSON.parse(r)))}),Ua="lineplot",hy=r=>new O({type:Ua,key:r}),dy="/workspace/lineplot/retrieve",fy="/workspace/lineplot/create",yy="/workspace/lineplot/rename",gy="/workspace/lineplot/set-data",py="/workspace/lineplot/delete",Za=jr.partial({key:!0}).transform(r=>({...r,data:JSON.stringify(r.data)})),my=s.z.object({keys:Ft.array()}),wy=s.z.object({workspace:s.z.string(),linePlots:Za.array()}),by=s.z.object({key:Ft,name:s.z.string()}),vy=s.z.object({key:Ft,data:s.z.string()}),Ty=s.z.object({keys:Ft.array()}),Oy=s.z.object({linePlots:X(jr)}),zy=s.z.object({linePlots:jr.array()}),an=s.z.object({});let La=class{constructor(e){c(this,"client");this.client=e}async create(e,t){const n=Array.isArray(t),i=b(t),a=await w(this.client,fy,{workspace:e,linePlots:i},wy,zy);return n?a.linePlots:a.linePlots[0]}async rename(e,t){await w(this.client,yy,{key:e,name:t},by,an)}async setData(e,t){await w(this.client,gy,{key:e,data:JSON.stringify(t)},vy,an)}async retrieve(e){const t=Array.isArray(e),n=b(e),i=await w(this.client,dy,{keys:n},my,Oy);return t?i.linePlots:i.linePlots[0]}async delete(e){const t=b(e);await w(this.client,py,{keys:t},Ty,an)}};const Ey=Object.freeze(Object.defineProperty({__proto__:null,Client:La,ONTOLOGY_TYPE:Ua,keyZ:Ft,linePlotZ:jr,newLinePlotZ:Za,ontologyID:hy},Symbol.toStringTag,{value:"Module"})),Ny=s.z.string().uuid(),Mr=s.z.object({key:s.z.string(),name:s.z.string(),data:Mt.or(s.z.string().transform(r=>JSON.parse(r)))}),_a="log",Sy=r=>new O({type:_a,key:r}),Iy="/workspace/log/retrieve",ky="/workspace/log/create",$y="/workspace/log/rename",Ay="/workspace/log/set-data",Ry="/workspace/log/delete",Ya=Mr.partial({key:!0}).transform(r=>({...r,data:JSON.stringify(r.data)})),xy=s.z.object({keys:s.z.string().array()}),Cy=s.z.object({workspace:s.z.string(),logs:Ya.array()}),Py=s.z.object({key:s.z.string(),name:s.z.string()}),Dy=s.z.object({key:s.z.string(),data:s.z.string()}),jy=s.z.object({keys:s.z.string().array()}),My=s.z.object({logs:Mr.array()}),By=s.z.object({logs:Mr.array()}),on=s.z.object({});let qa=class{constructor(e){c(this,"client");this.client=e}async create(e,t){const n=Array.isArray(t),i=b(t),a=await w(this.client,ky,{workspace:e,logs:i},Cy,By);return n?a.logs:a.logs[0]}async rename(e,t){await w(this.client,$y,{key:e,name:t},Py,on)}async setData(e,t){await w(this.client,Ay,{key:e,data:JSON.stringify(t)},Dy,on)}async retrieve(e){const t=Array.isArray(e),n=b(e),i=await w(this.client,Iy,{keys:n},xy,My);return t?i.logs:i.logs[0]}async delete(e){const t=b(e);await w(this.client,Ry,{keys:t},jy,on)}};const Uy=Object.freeze(Object.defineProperty({__proto__:null,Client:qa,ONTOLOGY_TYPE:_a,keyZ:Ny,logZ:Mr,newLogZ:Ya,ontologyID:Sy},Symbol.toStringTag,{value:"Module"})),Zy=s.z.string().uuid(),Yn=s.z.object({key:s.z.string(),name:s.z.string(),data:Mt.or(s.z.string().transform(r=>JSON.parse(r))),snapshot:s.z.boolean()}),qn=s.z.object({key:s.z.string(),name:s.z.string(),snapshot:s.z.boolean(),data:s.z.string().transform(r=>JSON.parse(r))}),Wa="schematic",Ly=r=>new O({type:Wa,key:r}),_y="/workspace/schematic/retrieve",Yy="/workspace/schematic/create",qy="/workspace/schematic/rename",Wy="/workspace/schematic/set-data",Gy="/workspace/schematic/delete",Vy="/workspace/schematic/copy",Ga=Yn.partial({key:!0,snapshot:!0}).transform(r=>({...r,data:JSON.stringify(r.data)})),Fy=s.z.object({keys:s.z.string().array()}),Jy=s.z.object({workspace:s.z.string(),schematics:Ga.array()}),Ky=s.z.object({key:s.z.string(),name:s.z.string()}),Hy=s.z.object({key:s.z.string(),data:s.z.string()}),Xy=s.z.object({keys:s.z.string().array()}),Qy=s.z.object({key:s.z.string(),name:s.z.string(),snapshot:s.z.boolean()}),eg=s.z.object({schematics:X(qn)}),tg=s.z.object({schematics:qn.array()}),rg=s.z.object({schematic:Yn}),cn=s.z.object({});let Va=class{constructor(e){c(this,"client");this.client=e}async create(e,t){const n=Array.isArray(t),i=b(t),a=await w(this.client,Yy,{workspace:e,schematics:i},Jy,tg);return n?a.schematics:a.schematics[0]}async rename(e,t){await w(this.client,qy,{key:e,name:t},Ky,cn)}async setData(e,t){await w(this.client,Wy,{key:e,data:JSON.stringify(t)},Hy,cn)}async retrieve(e){const t=Array.isArray(e),n=b(e),i=await w(this.client,_y,{keys:n},Fy,eg);return t?i.schematics:i.schematics[0]}async delete(e){const t=b(e);await w(this.client,Gy,{keys:t},Xy,cn)}async copy(e,t,n){return(await w(this.client,Vy,{key:e,name:t,snapshot:n},Qy,rg)).schematic}};const ng=Object.freeze(Object.defineProperty({__proto__:null,Client:Va,ONTOLOGY_TYPE:Wa,keyZ:Zy,newSchematicZ:Ga,ontologyID:Ly,schematicRemoteZ:qn,schematicZ:Yn},Symbol.toStringTag,{value:"Module"})),sg=s.z.string().uuid(),Fa=s.z.object({key:s.z.string(),name:s.z.string(),data:Mt.or(s.z.string().transform(r=>JSON.parse(r)))}),Ja="table",ig=r=>new O({type:Ja,key:r}),ag="/workspace/table/retrieve",og="/workspace/table/create",cg="/workspace/table/rename",lg="/workspace/table/set-data",ug="/workspace/table/delete",Ka=Fa.partial({key:!0}).transform(r=>({...r,data:JSON.stringify(r.data)})),Wn=s.z.object({key:s.z.string(),name:s.z.string(),data:s.z.string().transform(r=>JSON.parse(r))}),hg=s.z.object({keys:s.z.string().array()}),dg=s.z.object({workspace:s.z.string(),tables:Ka.array()}),fg=s.z.object({key:s.z.string(),name:s.z.string()}),yg=s.z.object({key:s.z.string(),data:s.z.string()}),gg=s.z.object({keys:s.z.string().array()}),pg=s.z.object({tables:Wn.array()}),mg=s.z.object({tables:Wn.array()}),ln=s.z.object({});let Ha=class{constructor(e){c(this,"client");this.client=e}async create(e,t){const n=Array.isArray(t),i=b(t),a=await w(this.client,og,{workspace:e,tables:i},dg,mg);return n?a.tables:a.tables[0]}async rename(e,t){await w(this.client,cg,{key:e,name:t},fg,ln)}async setData(e,t){await w(this.client,lg,{key:e,data:JSON.stringify(t)},yg,ln)}async retrieve(e){const t=Array.isArray(e),n=b(e),i=await w(this.client,ag,{keys:n},hg,pg);return t?i.tables:i.tables[0]}async delete(e){const t=b(e);await w(this.client,ug,{keys:t},gg,ln)}};const wg=Object.freeze(Object.defineProperty({__proto__:null,Client:Ha,ONTOLOGY_TYPE:Ja,keyZ:sg,newTableZ:Ka,ontologyID:ig,tableRemoteZ:Wn,tableZ:Fa},Symbol.toStringTag,{value:"Module"})),bg=s.z.string().uuid(),Xa=r=>JSON.parse(r),Br=s.z.object({key:s.z.string(),name:s.z.string(),layout:Mt.or(s.z.string().transform(r=>Xa(r)))}),Qa="workspace",vg=r=>new O({type:Qa,key:r}),Xt="/workspace/retrieve",Tg="/workspace/create",Og="/workspace/rename",zg="/workspace/set-layout",Eg="/workspace/delete",eo=Br.partial({key:!0}).transform(r=>({...r,layout:JSON.stringify(r.layout)})),to=Br.omit({layout:!0}).extend({layout:s.z.string().transform(r=>Xa(r))}),Qt=s.z.object({keys:s.z.string().array().optional(),search:s.z.string().optional(),author:s.z.string().uuid().optional(),offset:s.z.number().optional(),limit:s.z.number().optional()}),Ng=s.z.object({workspaces:eo.array()}),Sg=s.z.object({key:s.z.string(),name:s.z.string()}),Ig=s.z.object({key:s.z.string(),layout:s.z.string()}),kg=s.z.object({keys:s.z.string().array()}),er=s.z.object({workspaces:X(Br)}),$g=s.z.object({workspaces:to.array()}),un=s.z.object({});class ro{constructor(e){c(this,"type","workspace");c(this,"schematic");c(this,"linePlot");c(this,"log");c(this,"table");c(this,"client");this.client=e,this.schematic=new Va(e),this.linePlot=new La(e),this.log=new qa(e),this.table=new Ha(e)}async create(e){const t=Array.isArray(e),n=b(e),i=await w(this.client,Tg,{workspaces:n},Ng,$g);return t?i.workspaces:i.workspaces[0]}async rename(e,t){await w(this.client,Og,{key:e,name:t},Sg,un)}async setLayout(e,t){await w(this.client,zg,{key:e,layout:JSON.stringify(t)},Ig,un)}async retrieve(e){const t=Array.isArray(e),n=b(e),i=await w(this.client,Xt,{keys:n},Qt,er);return t?i.workspaces:i.workspaces[0]}async retrieveByAuthor(e){return(await w(this.client,Xt,{author:e},Qt,er)).workspaces}async search(e){return(await w(this.client,Xt,{search:e},Qt,er)).workspaces}async page(e,t){return(await w(this.client,Xt,{offset:e,limit:t},Qt,er)).workspaces}async delete(e){const t=b(e);await w(this.client,Eg,{keys:t},kg,un)}}const Ag=Object.freeze(Object.defineProperty({__proto__:null,Client:ro,ONTOLOGY_TYPE:Qa,keyZ:bg,newWorkspaceZ:eo,ontologyID:vg,workspaceRemoteZ:to,workspaceZ:Br},Symbol.toStringTag,{value:"Module"})),no=s.z.object({host:s.z.string({required_error:"Host is required"}).min(1,"Host is required"),port:s.z.number({required_error:"Port is required"}).or(s.z.string({required_error:"Port is required"})),username:s.z.string().min(1,"Username is required"),password:s.z.string().min(1,"Password is required"),connectivityPollFrequency:z.z.default(z.seconds(30)),secure:s.z.boolean().optional().default(!1),name:s.z.string().optional(),retry:Au.breakerConfig.optional()});class so extends da{constructor(t){const n=no.parse(t),{host:i,port:a,username:o,password:l,connectivityPollFrequency:u,secure:h,retry:y}=n,d=new uy(new mu({host:i,port:Number(a)}),y,h);d.use(Cu);let j;o!=null&&l!=null&&(j=new od(d.unary,{username:o,password:l}),d.use(j.middleware()));const $=new Dn(new xt(d.unary)),te=new ta(d.unary,$);super(d.stream,d.unary,$);c(this,"createdAt");c(this,"props");c(this,"ranges");c(this,"channels");c(this,"auth");c(this,"user");c(this,"access");c(this,"connectivity");c(this,"ontology");c(this,"workspaces");c(this,"labels");c(this,"hardware");c(this,"control");c(this,"transport");c(this,"clientVersion","0.36.0");this.createdAt=I.now(),this.props=n,this.auth=j,this.transport=d,this.channels=new ea(this,$,d.unary,te),this.connectivity=new Ct(d.unary,u,this.clientVersion,n.name),this.control=new ya(this),this.ontology=new Yi(d.unary,this);const U=new Ba(this.transport.unary);this.labels=new Ra(this.transport.unary,this,this.ontology),this.ranges=new Ma(this,U,this.transport.unary,$,this.labels,this.ontology),this.access=new Fi(this.transport.unary),this.user=new sa(this.transport.unary),this.workspaces=new ro(this.transport.unary);const io=new va(this.transport.unary,this),Gn=new Sa(this.transport.unary,this,this.ontology,this.ranges),ao=new Ta(this.transport.unary,this,Gn);this.hardware=new ga(Gn,ao,io)}get key(){return this.createdAt.valueOf().toString()}close(){this.connectivity.stopChecking()}}c(so,"connectivity",Ct);const Rg=it.Authority;exports.AuthError=xe;exports.Authority=Rg;exports.Channel=jn;exports.ContiguityError=En;exports.DataType=S;exports.Density=F;exports.Frame=_;exports.MultiSeries=Ri;exports.MultipleFoundError=me;exports.NotFoundError=pe;exports.QueryError=re;exports.Rate=nt;exports.RouteError=Rt;exports.Series=Oe;exports.Synnax=so;exports.TimeRange=W;exports.TimeSpan=z;exports.TimeStamp=I;exports.UnexpectedError=Ee;exports.ValidationError=B;exports.access=fh;exports.channel=Dh;exports.connection=ud;exports.control=xd;exports.device=Gd;exports.framer=Id;exports.group=Gu;exports.hardware=Cd;exports.label=$f;exports.linePlot=Ey;exports.log=Uy;exports.ontology=Xu;exports.policy=dh;exports.rack=Qd;exports.ranger=cy;exports.schematic=ng;exports.signals=jd;exports.synnaxPropsZ=no;exports.table=wg;exports.task=yf;exports.user=ed;exports.workspace=Ag;
51
+ Please report this error to the Synnax team. ${JSON.stringify(e)}`),t!=null){if(Ne.matches(t))return;throw t}}}closeSend(){this.stream.closeSend()}send(e){const t=this.stream.send(e);if(t!=null)throw t}}const Sn=new z(-1);var Un=(r=>(r[r.Open=0]="Open",r[r.Next=1]="Next",r[r.Prev=2]="Prev",r[r.SeekFirst=3]="SeekFirst",r[r.SeekLast=4]="SeekLast",r[r.SeekLE=5]="SeekLE",r[r.SeekGE=6]="SeekGE",r[r.Valid=7]="Valid",r[r.Error=8]="Error",r))(Un||{}),la=(r=>(r[r.None=0]="None",r[r.Ack=1]="Ack",r[r.Data=2]="Data",r))(la||{});const bd=s.z.object({command:s.z.nativeEnum(Un),span:z.z.optional(),bounds:W.z.optional(),stamp:I.z.optional(),keys:s.z.number().array().optional(),chunkSize:s.z.number().optional()}),vd=s.z.object({variant:s.z.nativeEnum(la),ack:s.z.boolean(),command:s.z.nativeEnum(Un),error:jt.optional().nullable(),frame:Rr.optional()}),$t=class $t{constructor(e,t){c(this,"stream");c(this,"adapter");c(this,"value");this.stream=new Bn("Iterator",e),this.value=new _,this.adapter=t}static async _open(e,t,n,i,a={}){const o=await xr.open(n,t),l=await i.stream($t.ENDPOINT,bd,vd),u=new $t(l,o);return await u.execute({command:0,keys:o.keys,bounds:new W(e),chunkSize:a.chunkSize??1e5}),u}async next(e=Sn){return await this.execute({command:1,span:new z(e)})}async prev(e=Sn){return await this.execute({command:2,span:new z(e)})}async seekFirst(){return await this.execute({command:3})}async seekLast(){return await this.execute({command:4})}async seekLE(e){return await this.execute({command:5,stamp:new I(e)})}async seekGE(e){return await this.execute({command:6,stamp:new I(e)})}async valid(){return await this.execute({command:7})}async close(){await this.stream.closeAndAck()}[Symbol.asyncIterator](){return new Td(this)}async execute(e){for(this.stream.send(e),this.value=new _;;){const t=await this.stream.receive();if(t.variant===1)return t.ack;this.value.push(this.adapter.adapt(new _(t.frame)))}}};c($t,"ENDPOINT","/frame/iterate");let br=$t;class Td{constructor(e){c(this,"iter");c(this,"open",!1);this.iter=e}async next(){try{let e=!0;return this.open||(await this.iter.seekFirst()||(e=!1),this.open=!0),await this.iter.next()||(e=!1),e||await this.iter.close(),{done:!e,value:this.iter.value}}catch(e){throw await this.iter.close(),e}}}const Od=s.z.object({keys:s.z.number().array(),downsampleFactor:s.z.number()}),zd=s.z.object({frame:Rr,error:jt.optional().nullable()}),Ed="/frame/stream";class Cr{constructor(e,t){c(this,"stream");c(this,"adapter");c(this,"downsampleFactor");this.stream=new Bn("Streamer",e),this.adapter=t,this.downsampleFactor=1}get keys(){return this.adapter.keys}static async _open(e,t,{channels:n,downsampleFactor:i}){const a=await xr.open(e,n),o=await t.stream(Ed,Od,zd),l=new Cr(o,a);o.send({keys:a.keys,downsampleFactor:i??1});const[,u]=await o.receive();if(u!=null)throw u;return l}async next(){try{return{done:!1,value:await this.read()}}catch(e){if(Ne.matches(e))return{done:!0,value:void 0};throw e}}async read(){return this.adapter.adapt(new _((await this.stream.receive()).frame))}async update(e){await this.adapter.update(e),this.stream.send({keys:this.adapter.keys,downsampleFactor:this.downsampleFactor})}close(){this.stream.closeSend()}[Symbol.asyncIterator](){return this}}class Ce extends Re.Observer{constructor(t,n){super(n);c(this,"streamer");c(this,"closePromise");this.streamer=t,this.closePromise=this.stream()}async close(){this.streamer.close(),await this.closePromise}async stream(){for await(const t of this.streamer)this.notify(t)}}var Zn=(r=>(r[r.Open=0]="Open",r[r.Write=1]="Write",r[r.Commit=2]="Commit",r[r.Error=3]="Error",r[r.SetAuthority=4]="SetAuthority",r))(Zn||{}),ot=(r=>(r[r.PersistStream=1]="PersistStream",r[r.Persist=2]="Persist",r[r.Stream=3]="Stream",r))(ot||{});const Nd=r=>{switch(r){case"persist":return 2;case"stream":return 3;case"persistStream":return 1;default:if(typeof r=="number"&&r in ot)return r;throw new Error(`invalid writer mode: ${r}`)}},Sd=new z(-1),Id=s.z.object({start:I.z.optional(),controlSubject:it.subjectZ.optional(),keys:s.z.number().array().optional(),authorities:it.Authority.z.array().optional(),mode:s.z.nativeEnum(ot).optional(),errOnUnauthorized:s.z.boolean().optional(),enableAutoCommit:s.z.boolean().optional(),autoIndexPersistInterval:z.z.optional()}),kd=s.z.object({command:s.z.nativeEnum(Zn),config:Id.optional(),frame:Rr.optional()}),$d=s.z.object({ack:s.z.boolean(),command:s.z.nativeEnum(Zn),error:jt.optional().nullable()});var ze;let ua=(ze=class{constructor(e,t){c(this,"stream");c(this,"adapter");this.stream=new Bn("Writer",e),this.adapter=t}static async _open(e,t,{channels:n,start:i=I.now(),authorities:a=it.Authority.Absolute,controlSubject:o,mode:l=1,errOnUnauthorized:u=!1,enableAutoCommit:h=!1,autoIndexPersistInterval:y=z.SECOND}){const d=await Mn.open(e,n),j=await t.stream(ze.ENDPOINT,kd,$d),$=new ze(j,d);return await $.execute({command:0,config:{start:new I(i),keys:d.keys,controlSubject:o,authorities:b(a),mode:Nd(l),errOnUnauthorized:u,enableAutoCommit:h,autoIndexPersistInterval:y}}),$}async write(e,t){const n=await this.adapter.adapt(e,t);return this.stream.send({command:1,frame:n.toPayload()}),!0}async setAuthority(e,t){let n;if(typeof e=="number"&&t==null)n={keys:[],authorities:[e]};else{let a;typeof e=="string"||typeof e=="number"?a={[e]:t}:a=e,a=await this.adapter.adaptObjectKeys(a),n={keys:Object.keys(a).map(o=>Number(o)),authorities:Object.values(a)}}return(await this.execute({command:4,config:n})).ack}async commit(){return this.errorAccumulated?!1:(await this.execute({command:2})).ack}async error(){this.stream.send({command:3});const e=await this.execute({command:3});return e.error!=null?yr(e.error):null}async close(){await this.stream.closeAndAck()}async execute(e){for(this.stream.send(e);;){const t=await this.stream.receive();if(t.command===e.command)return t;console.warn("writer received unexpected response",t)}}get errorAccumulated(){return this.stream.received()}},c(ze,"ENDPOINT","/frame/write"),ze);const ha="framer",Ad=r=>new O({type:ha,key:r.toString()});let da=class{constructor(e,t,n){c(this,"streamClient");c(this,"retriever");c(this,"deleter");this.streamClient=e,this.retriever=n,this.deleter=new wd(t)}async openIterator(e,t,n){return await br._open(e,t,this.retriever,this.streamClient,n)}async openWriter(e){return(Array.isArray(e)||typeof e!="object")&&(e={channels:e}),await ua._open(this.retriever,this.streamClient,e)}async openStreamer(e){return(Array.isArray(e)||typeof e!="object")&&(e={channels:e,downsampleFactor:1}),await Cr._open(this.retriever,this.streamClient,e)}async write(e,t,n){if(n==null){const a=t,o=await this.openWriter({start:e,channels:Object.keys(a),mode:ot.Persist});try{await o.write(a),await o.commit()}finally{await o.close()}return}const i=await this.openWriter({start:e,channels:t,mode:ot.Persist,errOnUnauthorized:!0,enableAutoCommit:!0,autoIndexPersistInterval:z.MAX});try{await i.write(t,n)}finally{await i.close()}}async read(e,t){const{single:n}=we(t),i=await this.readFrame(e,t);return n?i.get(t):i}async readFrame(e,t){const n=await this.openIterator(e,t),i=new _;try{for await(const a of n)i.push(a)}finally{await n.close()}return i}async delete(e,t){const{normalized:n,variant:i}=we(e);return i==="keys"?await this.deleter.delete({keys:n,bounds:t}):await this.deleter.delete({names:n,bounds:t})}};const Rd=Object.freeze(Object.defineProperty({__proto__:null,ALWAYS_INDEX_PERSIST_ON_AUTO_COMMIT:Sd,AUTO_SPAN:Sn,Client:da,Frame:_,Iterator:br,ONTOLOGY_TYPE:ha,ObservableStreamer:Ce,Streamer:Cr,Writer:ua,WriterMode:ot,frameZ:Rr,ontologyID:Ad,seriesFromPayload:oa,seriesToPayload:ca},Symbol.toStringTag,{value:"Module"})),xd=it.Authority,Cd=it.stateZ(s.z.number()),Pd=r=>{var e,t;return r.to==null?`${(e=r.from)==null?void 0:e.resource} - ${(t=r.from)==null?void 0:t.subject.name} -> released`:r.from==null?`${r.to.resource} - released -> ${r.to.subject.name} (${r.to.authority.toString()})`:`${r.to.resource} - ${r.from.subject.name} -> ${r.to.subject.name} (${r.to.authority.toString()})`};class fa extends Ce{constructor(t){super(t,n=>{const i=this.codec.decode(n.series[0].buffer);return this.merge(i),[i.transfers,!0]});c(this,"states");c(this,"codec");this.states=new Map,this.codec=new ct.JSONCodec}subjects(){const t=new Map;return this.states.forEach(n=>t.set(n.subject.key,n.subject)),Array.from(t.values())}merge(t){t.transfers.forEach(n=>{n.from==null&&n.to==null&&console.warn("Invalid transfer: ",n),n.to==null?this.states.delete(n.from.resource):this.states.set(n.to.resource,n.to)})}}const Dd="sy_node_1_control";let ya=class{constructor(e){c(this,"framer");this.framer=e}async openStateTracker(){const e=await this.framer.openStreamer(Dd);return new fa(e)}};const jd=Object.freeze(Object.defineProperty({__proto__:null,Authority:xd,Client:ya,StateTracker:fa,stateZ:Cd,transferString:Pd},Symbol.toStringTag,{value:"Module"}));let ga=class{constructor(e,t,n){c(this,"tasks");c(this,"racks");c(this,"devices");this.tasks=e,this.racks=t,this.devices=n}};const Md=Object.freeze(Object.defineProperty({__proto__:null,Client:ga},Symbol.toStringTag,{value:"Module"})),ht=s.z.number(),Pr=s.z.object({key:ht,name:s.z.string()}),pa=Pr.partial({key:!0}),ma="rack",Bd=r=>new O({type:ma,key:r.toString()}),Dr=s.z.string(),qt=s.z.object({key:Dr,rack:ht,name:s.z.string(),make:s.z.string(),model:s.z.string(),location:s.z.string(),configured:s.z.boolean().optional(),properties:s.z.record(s.z.unknown()).or(s.z.string().transform(r=>r===""?{}:ct.JSON_CODEC.decodeString(r)))}),wa=qt.extend({properties:s.z.unknown().transform(r=>ct.JSON_CODEC.encodeString(r))}),ba="device",Ud=r=>new O({type:ba,key:r.toString()}),Pe=async(r,e,t,n)=>{const i=await r.openStreamer([e,t]),a=o=>{const l=[];return t!=null&&l.push(...o.get(t).series.flatMap(u=>n("delete",u))),e!=null&&l.push(...o.get(e).series.flatMap(u=>n("set",u))),[l,l.length>0]};return new Ce(i,a)},Zd=Object.freeze(Object.defineProperty({__proto__:null,openObservable:Pe},Symbol.toStringTag,{value:"Module"})),Ld="sy_device_set",_d="sy_device_delete",Hr="/hardware/device/retrieve",Yd="/hardware/device/create",qd="/hardware/device/delete",Wd=s.z.object({devices:wa.array()}),Gd=s.z.object({devices:qt.array()}),Vd=s.z.object({keys:Dr.array()}),Fd=s.z.object({}),Xr=s.z.object({search:s.z.string().optional(),limit:s.z.number().optional(),offset:s.z.number().optional(),keys:Dr.array().optional(),names:s.z.string().array().optional(),makes:s.z.string().array().optional()}),Qr=s.z.object({devices:X(qt)});let va=class{constructor(e,t){c(this,"type","device");c(this,"client");c(this,"frameClient");this.client=e,this.frameClient=t}async retrieve(e,t){const n=!Array.isArray(e),i=await w(this.client,Hr,{keys:b(e),...t},Xr,Qr);return Ar("Device",e,i.devices,n),n?i.devices[0]:i.devices}async search(e,t){return(await w(this.client,Hr,{search:e,...t},Xr,Qr)).devices}async page(e,t,n){return(await w(this.client,Hr,{offset:e,limit:t,...n},Xr,Qr)).devices}async create(e){const t=!Array.isArray(e),n=await w(this.client,Yd,{devices:b(e)},Wd,Gd);return t?n.devices[0]:n.devices}async delete(e){await w(this.client,qd,{keys:b(e)},Vd,Fd)}async openDeviceTracker(){return await Pe(this.frameClient,Ld,_d,Jd)}newSearcherWithOptions(e){return{type:this.type,search:async t=>await this.search(t,e),retrieve:async t=>await this.retrieve(t,e),page:async(t,n)=>await this.page(t,n,e)}}};const Jd=(r,e)=>r==="delete"?e.toStrings().map(t=>({variant:r,key:t,value:void 0})):e.parseJSON(qt).map(t=>({variant:r,key:t.key,value:t})),Kd=Object.freeze(Object.defineProperty({__proto__:null,Client:va,ONTOLOGY_TYPE:ba,deviceKeyZ:Dr,deviceZ:qt,newDeviceZ:wa,ontologyID:Ud},Symbol.toStringTag,{value:"Module"})),en="/hardware/rack/retrieve",Hd="/hardware/rack/create",Xd="/hardware/rack/delete",tn=s.z.object({keys:ht.array().optional(),names:s.z.string().array().optional(),search:s.z.string().optional(),offset:s.z.number().optional(),limit:s.z.number().optional()}),rn=s.z.object({racks:X(Pr)}),Qd=s.z.object({racks:pa.array()}),ef=s.z.object({racks:Pr.array()}),tf=s.z.object({keys:ht.array()}),rf=s.z.object({});let Ta=class{constructor(e,t,n){c(this,"type","rack");c(this,"client");c(this,"frameClient");c(this,"tasks");this.client=e,this.frameClient=t,this.tasks=n}async delete(e){await w(this.client,Xd,{keys:b(e)},tf,rf)}async create(e){const t=!Array.isArray(e),n=await w(this.client,Hd,{racks:b(e)},Qd,ef),i=this.sugar(n.racks);return t?i[0]:i}async search(e){const t=await w(this.client,en,{search:e},tn,rn);return this.sugar(t.racks)}async page(e,t){const n=await w(this.client,en,{offset:e,limit:t},tn,rn);return this.sugar(n.racks)}async retrieve(e){const{variant:t,normalized:n,single:i}=$r(e,{string:"names",number:"keys"}),a=await w(this.client,en,{[t]:n},tn,rn),o=this.sugar(a.racks);return Ar("Rack",e,o,i),i?o[0]:o}sugar(e){return e.map(({key:t,name:n})=>new Oa(t,n,this.tasks))}};class Oa{constructor(e,t,n){c(this,"key");c(this,"name");c(this,"tasks");this.key=e,this.name=t,this.tasks=n}async listTasks(){return await this.tasks.retrieve(this.key)}async retrieveTaskByName(e){return await this.tasks.retrieveByName(e,this.key)}async createTask(e){return e.key=((BigInt(this.key)<<32n)+(BigInt(e.key??0)&0xffffffffn)).toString(),await this.tasks.create(e)}async deleteTask(e){await this.tasks.delete([e])}}const nf=Object.freeze(Object.defineProperty({__proto__:null,Client:Ta,ONTOLOGY_TYPE:ma,Rack:Oa,newRackZ:pa,ontologyID:Bd,rackKeyZ:ht,rackZ:Pr},Symbol.toStringTag,{value:"Module"})),De=s.z.union([s.z.string(),s.z.bigint().transform(r=>r.toString()),s.z.number().transform(r=>r.toString())]),Pt=s.z.object({task:De,variant:s.z.string(),key:s.z.string().optional(),details:s.z.record(s.z.unknown()).or(s.z.string().transform(r=>r===""?{}:JSON.parse(r))).or(s.z.array(s.z.unknown())).or(s.z.null())}),Wt=s.z.object({key:De,name:s.z.string(),type:s.z.string(),internal:s.z.boolean().optional(),config:s.z.record(s.z.unknown()).or(s.z.string().transform(r=>r===""?{}:ct.JSON_CODEC.decodeString(r))),state:Pt.optional().nullable(),snapshot:s.z.boolean().optional()}),za=Wt.omit({key:!0}).extend({key:De.transform(r=>r.toString()).optional(),config:s.z.unknown().transform(r=>ct.JSON_CODEC.encodeString(r))}),Ln=s.z.object({task:De,type:s.z.string(),key:s.z.string(),args:s.z.record(s.z.unknown()).or(s.z.string().transform(r=>r===""?{}:JSON.parse(r))).or(s.z.array(s.z.unknown())).or(s.z.null()).optional()}),Ea="task",sf=r=>new O({type:Ea,key:r.toString()}),kt="sy_task_state",Ze="sy_task_cmd",ft=new Error("Task not created");class Na{constructor(e,t,n,i,a=!1,o=!1,l,u=null,h=null,y=null){c(this,"key");c(this,"name");c(this,"internal");c(this,"type");c(this,"config");c(this,"snapshot");c(this,"state");c(this,"frameClient");c(this,"ontologyClient");c(this,"rangeClient");this.key=e,this.name=t,this.type=n,this.config=i,this.internal=a,this.snapshot=o,l!==null&&(this.state=l),this.frameClient=u,this.ontologyClient=h,this.rangeClient=y}get payload(){return{key:this.key,name:this.name,type:this.type,config:this.config,state:this.state,internal:this.internal}}get ontologyID(){return new O({type:"task",key:this.key})}async executeCommand(e,t){if(this.frameClient==null)throw ft;const n=await this.frameClient.openWriter(Ze),i=Hl.id();return await n.write(Ze,[{task:this.key,type:e,key:i,args:t}]),await n.close(),i}async executeCommandSync(e,t,n){if(this.frameClient==null)throw ft;const i=await this.frameClient.openStreamer(kt),a=await this.executeCommand(e,t);let o;const l=new Promise(u=>setTimeout(()=>u(!1),new z(n).milliseconds));for(;;){const u=await Promise.any([i.read(),l]);if(u===!1)throw new Error("Command timed out");const h=Pt.safeParse(u.at(-1).sy_task_state);if(h.success){if(o=h.data,o.key===a)break}else console.error(h.error)}return i.close(),o}async openStateObserver(){if(this.frameClient==null)throw ft;return new Ce(await this.frameClient.openStreamer(kt),e=>{const t=e.get(kt);if(t.length===0)return[null,!1];const n=Pt.safeParse(t.at(-1));if(!n.success)return console.error(n.error),[null,!1];const i=n.data;return i.task!==this.key?[null,!1]:[i,!0]})}async openCommandObserver(){if(this.frameClient==null)throw ft;return new Ce(await this.frameClient.openStreamer(Ze),e=>{const t=e.get(Ze);if(t.length===0)return[null,!1];const n=Ln.safeParse(t.at(-1));if(!n.success)return console.error(n.error),[null,!1];const i=n.data;return i.task!==this.key?[null,!1]:[i,!0]})}async snapshottedTo(){if(this.ontologyClient==null||this.rangeClient==null)throw ft;if(!this.snapshot)return null;const e=await this.ontologyClient.retrieveParents(this.ontologyID);return e.length==0?null:e[0]}}const af=s.z.object({rack:ht.optional(),keys:s.z.string().array().optional(),names:s.z.string().array().optional(),offset:s.z.number().optional(),limit:s.z.number().optional(),includeState:s.z.boolean().optional()}),of=s.z.object({tasks:X(Wt)}),cf="/hardware/task/retrieve",lf="/hardware/task/create",uf="/hardware/task/delete",hf="/hardware/task/copy",df=s.z.object({tasks:za.array()}),ff=s.z.object({tasks:Wt.array()}),yf=s.z.object({keys:De.array()}),gf=s.z.object({}),pf=s.z.object({key:De,name:s.z.string(),snapshot:s.z.boolean()}),mf=s.z.object({task:Wt});let Sa=class{constructor(e,t,n,i){c(this,"type","task");c(this,"client");c(this,"frameClient");c(this,"ontologyClient");c(this,"rangeClient");this.client=e,this.frameClient=t,this.ontologyClient=n,this.rangeClient=i}async create(e){const t=!Array.isArray(e),n=await w(this.client,lf,{tasks:b(e)},df,ff),i=this.sugar(n.tasks);return t?i[0]:i}async delete(e){await w(this.client,uf,{keys:b(e)},yf,gf)}async search(e){return await this.execRetrieve({keys:[e]})}async page(e,t){return await this.execRetrieve({offset:e,limit:t})}async list(e={}){return this.sugar(await this.execRetrieve(e))}async retrieve(e,t){const{single:n,normalized:i,variant:a}=$r(e,{number:"rack",string:"keys"},{convertNumericStrings:!1}),o={...t};a==="rack"?o.rack=e:o.keys=i;const l=await this.execRetrieve(o),u=this.sugar(l);return n&&a!=="rack"?u[0]:u}async copy(e,t,n){const i=await w(this.client,hf,{key:e,name:t,snapshot:n},pf,mf);return this.sugar([i.task])[0]}async retrieveByName(e,t){const n=await this.execRetrieve({names:[e],rack:t});return Ar("Task",e,n,!0),this.sugar(n)[0]}async execRetrieve(e){return(await w(this.client,cf,e,af,of)).tasks}sugar(e){return e.map(({key:t,name:n,type:i,config:a,state:o,internal:l,snapshot:u})=>new Na(t,n,i,a,l,u,o,this.frameClient,this.ontologyClient,this.rangeClient))}async openTracker(){return await Pe(this.frameClient,"sy_task_set","sy_task_delete",(e,t)=>Array.from(t).map(n=>({variant:e,key:n.toString(),value:n.toString()})))}async openStateObserver(){return new Ce(await this.frameClient.openStreamer(kt),e=>{const t=e.get(kt);if(t.length===0)return[null,!1];const n=Pt.safeParse(t.at(-1));return n.success?[n.data,!0]:(console.error(n.error),[null,!1])})}async openCommandObserver(){return new Ce(await this.frameClient.openStreamer(Ze),e=>{const t=e.get(Ze);if(t.length===0)return[null,!1];const n=Ln.safeParse(t.at(-1));return n.success?[n.data,!0]:(console.error(n.error),[null,!1])})}};const wf=Object.freeze(Object.defineProperty({__proto__:null,Client:Sa,ONTOLOGY_TYPE:Ea,Task:Na,commandZ:Ln,newTaskZ:za,ontologyID:sf,stateZ:Pt,taskKeyZ:De,taskZ:Wt},Symbol.toStringTag,{value:"Module"})),dt=s.z.string().uuid(),Gt=s.z.object({key:dt,name:s.z.string().min(1),color:s.z.string()}),Ia="label",bf=r=>new O({type:Ia,key:r}),vf=s.z.object({keys:dt.array().optional(),for:H.optional(),search:s.z.string().optional(),offset:s.z.number().optional(),limit:s.z.number().optional()}),Tf=s.z.object({labels:X(Gt)}),Or=class Or{constructor(e){c(this,"client");this.client=e}async retrieve(e){const t=b(e);return await this.execute({keys:t})}async retrieveFor(e){return await this.execute({for:e})}async search(e){return await this.execute({search:e})}async page(e,t){return await this.execute({offset:e,limit:t})}async execute(e){const[t,n]=await this.client.send(Or.ENDPOINT,e,vf,Tf);if(n!=null)throw n;return t.labels}};c(Or,"ENDPOINT","/label/retrieve");let vr=Or;const ka=Gt.extend({key:dt.optional()}),Of=s.z.object({labels:ka.array()}),zf=s.z.object({labels:Gt.array()}),Ef=s.z.object({keys:dt.array()}),$a=s.z.object({id:H,labels:dt.array(),replace:s.z.boolean().optional()}),Nf=$a.omit({replace:!0}),nn=s.z.object({}),Sf="/label/create",If="/label/delete",kf="/label/set",$f="/label/remove";let Aa=class{constructor(e){c(this,"client");this.client=e}async create(e){return(await w(this.client,Sf,{labels:b(e)},Of,zf)).labels}async delete(e){await w(this.client,If,{keys:b(e)},Ef,nn)}async set(e,t,{replace:n}={}){await w(this.client,kf,{id:e,labels:t,replace:n},$a,nn)}async remove(e,t){await w(this.client,$f,{id:e,labels:t},Nf,nn)}};const Af="sy_label_set",Rf="sy_label_delete";let Ra=class{constructor(e,t,n){c(this,"type","label");c(this,"retriever");c(this,"writer");c(this,"frameClient");c(this,"ontology");this.writer=new Aa(e),this.retriever=new vr(e),this.frameClient=t,this.ontology=n}async search(e){return await this.retriever.search(e)}async retrieve(e){const t=Array.isArray(e),n=await this.retriever.retrieve(e);return t?n:n[0]}async retrieveFor(e){return await this.retriever.retrieveFor(new O(e))}async label(e,t,n={}){await this.writer.set(new O(e),t,n)}async removeLabels(e,t){await this.writer.remove(new O(e),t)}async page(e,t){return await this.retriever.page(e,t)}async create(e){const t=Array.isArray(e),n=await this.writer.create(e);return t?n:n[0]}async delete(e){await this.writer.delete(e)}async openChangeTracker(){return await Pe(this.frameClient,Af,Rf,xf)}async trackLabelsOf(e){const t=new Re.Observer,n=(await this.retrieveFor(e)).map(a=>({id:new O({key:a.key,type:"label"}),key:a.key,name:a.name,data:a}));return(await this.ontology.openDependentTracker({target:new O(e),dependents:n,relationshipType:"labeled_by"})).onChange(a=>t.notify(a.map(o=>{var l,u;return{key:o.id.key,color:(l=o.data)==null?void 0:l.color,name:(u=o.data)==null?void 0:u.name}}))),t}};const xf=(r,e)=>r==="delete"?e.toUUIDs().map(t=>({variant:r,key:t})):e.parseJSON(Gt).map(t=>({variant:r,key:t.key,value:t})),Cf=Object.freeze(Object.defineProperty({__proto__:null,Client:Ra,ONTOLOGY_TYPE:Ia,Retriever:vr,Writer:Aa,keyZ:dt,labelZ:Gt,newLabelPayloadZ:ka,ontologyID:bf},Symbol.toStringTag,{value:"Module"})),ee=s.z.string().uuid(),Vt=s.z.object({key:ee,name:s.z.string().min(1),timeRange:W.z,color:s.z.string().optional()}),xa=Vt.extend({key:s.z.string().uuid().optional()}),Ca=r=>{const e=b(r),t=e.length===0;let n=!1;return t||(n=ee.safeParse(e[0]).success),{single:!Array.isArray(r),variant:n?"keys":"names",normalized:e,actual:r,empty:t}},Pa="range",Da="range-alias",Pf=r=>new O({type:Pa,key:r}),Df=r=>new O({type:Da,key:r}),jf="sy_range_alias_set",Mf="sy_range_alias_delete",Bf=s.z.object({range:ee,aliases:s.z.string().array()}),Uf=s.z.object({aliases:s.z.record(s.z.string(),ke)}),Zf=s.z.object({range:ee,aliases:s.z.record(ke.or(s.z.string()),s.z.string())}),Lf=s.z.unknown(),_f=s.z.object({range:ee,channels:ke.array()}),Yf=s.z.unknown(),qf=s.z.object({range:ee}),Wf=s.z.object({aliases:s.z.record(s.z.string(),s.z.string())}),he=class he{constructor(e,t,n){c(this,"frameClient");c(this,"cache",new Map);c(this,"client");c(this,"rangeKey");this.rangeKey=e,this.cache=new Map,this.client=n,this.frameClient=t}async resolve(e){const t=[],n=typeof e=="string",i={};if(n){const o=this.cache.get(e);if(o!=null)return o;t.push(e)}else e.forEach(o=>{const l=this.cache.get(o);l!=null?i[o]=l:t.push(o)});if(t.length===0)return i;const a=await w(this.client,he.RESOLVE_ENDPOINT,{range:this.rangeKey,aliases:t},Bf,Uf);return Object.entries(a.aliases).forEach(([o,l])=>this.cache.set(o,l)),n?a.aliases[t[0]]:{...i,...a.aliases}}async set(e){await w(this.client,he.SET_ENDPOINT,{range:this.rangeKey,aliases:e},Zf,Lf)}async list(){return(await w(this.client,he.LIST_ENDPOINT,{range:this.rangeKey},qf,Wf)).aliases}async delete(e){await w(this.client,he.DELETE_ENDPOINT,{range:this.rangeKey,channels:e},_f,Yf)}async openChangeTracker(){return await Pe(this.frameClient,jf,Mf,Ff(this.rangeKey))}};c(he,"SET_ENDPOINT","/range/alias/set"),c(he,"RESOLVE_ENDPOINT","/range/alias/resolve"),c(he,"LIST_ENDPOINT","/range/alias/list"),c(he,"DELETE_ENDPOINT","/range/alias/delete");let In=he;const Gf=s.z.object({range:ee,channel:ke,alias:s.z.string()}),Vf="---",Ff=r=>(e,t)=>e==="delete"?t.toStrings().filter(n=>n.split(Vf)[0]===r).map(n=>({variant:e,key:n,value:void 0})):t.parseJSON(Gf).map(n=>({variant:e,key:n.alias,value:n})),Jf=s.z.object({range:ee,keys:s.z.string().array()}),_n=s.z.object({range:ee,key:s.z.string(),value:s.z.string()}),Kf=s.z.object({pairs:X(_n)}),Hf=s.z.object({range:ee,pairs:_n.array()}),Xf=s.z.object({range:ee,keys:s.z.string().array()}),Te=class Te{constructor(e,t,n){c(this,"rangeKey");c(this,"client");c(this,"frameClient");this.rangeKey=e,this.client=t,this.frameClient=n}async get(e){const t=await w(this.client,Te.GET_ENDPOINT,{range:this.rangeKey,keys:b(e)},Jf,Kf);return typeof e=="string"?t.pairs[0].value:Object.fromEntries(t.pairs.map(n=>[n.key,n.value]))}async list(){return this.get([])}async set(e,t=""){let n;An(e)?n=Object.entries(e).map(([i,a])=>({range:this.rangeKey,key:i,value:a})):n=[{range:this.rangeKey,key:e,value:t}],await w(this.client,Te.SET_ENDPOINT,{range:this.rangeKey,pairs:n},Hf,s.z.unknown())}async delete(e){await w(this.client,Te.DELETE_ENDPOINT,{range:this.rangeKey,keys:b(e)},Xf,s.z.unknown())}async openTracker(){return await Pe(this.frameClient,"sy_range_kv_set","sy_range_kv_delete",(e,t)=>e==="delete"?t.toStrings().map(n=>{const[i,a]=n.split("<--->",2);return{variant:e,key:n,value:{range:i,key:a,value:""}}}):t.parseJSON(_n).map(n=>({variant:e,key:`${n.range}${n.key}`,value:n})))}};c(Te,"GET_ENDPOINT","/range/kv/get"),c(Te,"SET_ENDPOINT","/range/kv/set"),c(Te,"DELETE_ENDPOINT","/range/kv/delete");let Dt=Te;const sn=r=>new O({type:"range",key:r});class ja{constructor(e,t=W.ZERO,n,i,a,o,l,u,h,y,d){c(this,"key");c(this,"name");c(this,"kv");c(this,"timeRange");c(this,"color");c(this,"channels");c(this,"aliaser");c(this,"frameClient");c(this,"labelClient");c(this,"ontologyClient");c(this,"rangeClient");this.key=n,this.name=e,this.timeRange=t,this.frameClient=a,this.color=i,this.kv=o,this.aliaser=l,this.channels=u,this.labelClient=h,this.ontologyClient=y,this.rangeClient=d}get ontologyID(){return new O({key:this.key,type:"range"})}get payload(){return{key:this.key,name:this.name,timeRange:this.timeRange,color:this.color}}async setAlias(e,t){const n=await this.channels.retrieve(e);if(n.length===0)throw new re(`Channel ${e} does not exist`);await this.aliaser.set({[n[0].key]:t})}async deleteAlias(...e){await this.aliaser.delete(e)}async listAliases(){return await this.aliaser.list()}async resolveAlias(e){return await this.aliaser.resolve(e)}async openAliasTracker(){return await this.aliaser.openChangeTracker()}async retrieveParent(){return this.rangeClient.retrieveParent(this.key)}async retrieveChildren(){const e=(await this.ontologyClient.retrieveChildren(this.ontologyID,{excludeFieldData:!0,types:["range"]})).map(t=>t.id.key);return await this.rangeClient.retrieve(e)}async read(e){return await this.frameClient.read(this.timeRange,e)}async labels(){return await this.labelClient.retrieveFor(sn(this.key))}async addLabel(...e){await this.labelClient.label(sn(this.key),e)}async removeLabel(...e){await this.labelClient.removeLabels(sn(this.key),e)}async openChildRangeTracker(){const e=new Re.Observer,t=(await this.retrieveChildren()).map(i=>{const a=new O({key:i.key,type:"range"});return{id:a,key:a.toString(),name:i.name,data:i.payload}}),n=await this.ontologyClient.openDependentTracker({target:this.ontologyID,dependents:t,resourceType:"range"});return n.onChange(i=>e.notify(this.rangeClient.resourcesToRanges(i))),e.setCloser(async()=>await n.close()),e}async openParentRangeTracker(){const e=new Re.Observer,t=await this.retrieveParent();if(t==null)return null;const n=new O({key:t.key,type:"range"}),i={id:n,key:n.toString(),name:t.name,data:t.payload},a=await this.ontologyClient.openDependentTracker({target:this.ontologyID,dependents:[i],relationshipDirection:"to"});return a.onChange(o=>{const l=this.rangeClient.resourcesToRanges(o);if(l.length===0)return;const u=l[0];e.notify(u)}),e.setCloser(async()=>await a.close()),e}}const Qf=(r,e)=>Ql(r.timeRange,e.timeRange),ey=s.z.object({keys:ee.array().optional(),names:s.z.array(s.z.string()).optional(),term:s.z.string().optional(),overlapsWith:W.z.optional(),limit:s.z.number().int().optional(),offset:s.z.number().int().optional()}),ty="/range/retrieve",ry=s.z.object({ranges:X(Vt)});let Ma=class{constructor(e,t,n,i,a,o){c(this,"type","range");c(this,"frameClient");c(this,"writer");c(this,"unaryClient");c(this,"channels");c(this,"labelClient");c(this,"ontologyClient");this.frameClient=e,this.writer=t,this.unaryClient=n,this.channels=i,this.labelClient=a,this.ontologyClient=o}async create(e,t){const n=!Array.isArray(e),i=this.sugarMany(await this.writer.create(b(e),t));return n?i[0]:i}async rename(e,t){await this.writer.rename(e,t)}async delete(e){await this.writer.delete(b(e))}async search(e){return this.sugarMany(await this.execRetrieve({term:e}))}async page(e,t){return this.sugarMany(await this.execRetrieve({offset:e,limit:t}))}async retrieve(e){if(typeof e=="object"&&"start"in e)return await this.execRetrieve({overlapsWith:new W(e)});const{single:t,actual:n,variant:i,normalized:a,empty:o}=Ca(e);if(o)return[];const l=await this.execRetrieve({[i]:a});if(!t)return l;if(l.length===0)throw new pe(`range matching ${n} not found`);if(l.length>1)throw new me(`multiple ranges matching ${n} found`);return l[0]}getKV(e){return new Dt(e,this.unaryClient,this.frameClient)}async execRetrieve(e){const{ranges:t}=await w(this.unaryClient,ty,e,ey,ry);return this.sugarMany(t)}async retrieveParent(e){const t=await this.ontologyClient.retrieveParents({key:e,type:"range"});if(t.length===0)return null;const n=t[0];return n.id.type!=="range"?null:await this.retrieve(n.id.key)}sugarOne(e){return new ja(e.name,e.timeRange,e.key,e.color,this.frameClient,new Dt(e.key,this.unaryClient,this.frameClient),new In(e.key,this.frameClient,this.unaryClient),this.channels,this.labelClient,this.ontologyClient,this)}sugarMany(e){return e.map(t=>this.sugarOne(t))}async openTracker(){return await Pe(this.frameClient,"sy_range_set","sy_range_delete",(e,t)=>e==="delete"?t.toStrings().map(i=>({variant:e,key:i,value:void 0})):this.sugarMany(t.parseJSON(Vt)).map(i=>({variant:e,key:i.key,value:i})))}resourcesToRanges(e){return e.map(t=>this.resourceToRange(t))}resourceToRange(e){var t,n,i;return this.sugarOne({key:e.id.key,name:(t=e.data)==null?void 0:t.name,timeRange:new W((n=e.data)==null?void 0:n.timeRange),color:(i=e.data)==null?void 0:i.color})}};const ny=s.z.object({ranges:Vt.array()}),sy=s.z.object({parent:H.optional(),ranges:xa.array()}),iy=s.z.object({keys:ee.array()}),ay=s.z.object({}),oy=s.z.object({key:ee,name:s.z.string()}),cy=s.z.object({}),ly="/range/create",uy="/range/delete",hy="/range/rename";class Ba{constructor(e){c(this,"client");this.client=e}async rename(e,t){await w(this.client,hy,{key:e,name:t},oy,cy)}async create(e,t){return(await w(this.client,ly,{ranges:e,...t},sy,ny)).ranges}async delete(e){await w(this.client,uy,{keys:e},iy,ay)}}const dy=Object.freeze(Object.defineProperty({__proto__:null,ALIAS_ONTOLOGY_TYPE:Da,Client:Ma,KV:Dt,ONTOLOGY_TYPE:Pa,Range:ja,Writer:Ba,analyzeParams:Ca,keyZ:ee,newPayloadZ:xa,payloadZ:Vt,rangeAliasOntologyID:Df,rangeOntologyID:Pf,sort:Qf},Symbol.toStringTag,{value:"Module"})),fy="/api/v1/";class yy{constructor(e,t={},n=!1){c(this,"url");c(this,"unary");c(this,"stream");c(this,"secure");this.secure=n,this.url=e.child(fy);const i=new ct.JSONCodec;this.unary=Bc(new Mc(this.url,i,this.secure),t),this.stream=new Vc(this.url,i,this.secure)}use(...e){this.unary.use(...e),this.stream.use(...e)}}const Ft=s.z.string().uuid(),jr=s.z.object({key:s.z.string(),name:s.z.string(),data:Mt.or(s.z.string().transform(r=>JSON.parse(r)))}),Ua="lineplot",gy=r=>new O({type:Ua,key:r}),py="/workspace/lineplot/retrieve",my="/workspace/lineplot/create",wy="/workspace/lineplot/rename",by="/workspace/lineplot/set-data",vy="/workspace/lineplot/delete",Za=jr.partial({key:!0}).transform(r=>({...r,data:JSON.stringify(r.data)})),Ty=s.z.object({keys:Ft.array()}),Oy=s.z.object({workspace:s.z.string(),linePlots:Za.array()}),zy=s.z.object({key:Ft,name:s.z.string()}),Ey=s.z.object({key:Ft,data:s.z.string()}),Ny=s.z.object({keys:Ft.array()}),Sy=s.z.object({linePlots:X(jr)}),Iy=s.z.object({linePlots:jr.array()}),an=s.z.object({});let La=class{constructor(e){c(this,"client");this.client=e}async create(e,t){const n=Array.isArray(t),i=b(t),a=await w(this.client,my,{workspace:e,linePlots:i},Oy,Iy);return n?a.linePlots:a.linePlots[0]}async rename(e,t){await w(this.client,wy,{key:e,name:t},zy,an)}async setData(e,t){await w(this.client,by,{key:e,data:JSON.stringify(t)},Ey,an)}async retrieve(e){const t=Array.isArray(e),n=b(e),i=await w(this.client,py,{keys:n},Ty,Sy);return t?i.linePlots:i.linePlots[0]}async delete(e){const t=b(e);await w(this.client,vy,{keys:t},Ny,an)}};const ky=Object.freeze(Object.defineProperty({__proto__:null,Client:La,ONTOLOGY_TYPE:Ua,keyZ:Ft,linePlotZ:jr,newLinePlotZ:Za,ontologyID:gy},Symbol.toStringTag,{value:"Module"})),$y=s.z.string().uuid(),Mr=s.z.object({key:s.z.string(),name:s.z.string(),data:Mt.or(s.z.string().transform(r=>JSON.parse(r)))}),_a="log",Ay=r=>new O({type:_a,key:r}),Ry="/workspace/log/retrieve",xy="/workspace/log/create",Cy="/workspace/log/rename",Py="/workspace/log/set-data",Dy="/workspace/log/delete",Ya=Mr.partial({key:!0}).transform(r=>({...r,data:JSON.stringify(r.data)})),jy=s.z.object({keys:s.z.string().array()}),My=s.z.object({workspace:s.z.string(),logs:Ya.array()}),By=s.z.object({key:s.z.string(),name:s.z.string()}),Uy=s.z.object({key:s.z.string(),data:s.z.string()}),Zy=s.z.object({keys:s.z.string().array()}),Ly=s.z.object({logs:Mr.array()}),_y=s.z.object({logs:Mr.array()}),on=s.z.object({});let qa=class{constructor(e){c(this,"client");this.client=e}async create(e,t){const n=Array.isArray(t),i=b(t),a=await w(this.client,xy,{workspace:e,logs:i},My,_y);return n?a.logs:a.logs[0]}async rename(e,t){await w(this.client,Cy,{key:e,name:t},By,on)}async setData(e,t){await w(this.client,Py,{key:e,data:JSON.stringify(t)},Uy,on)}async retrieve(e){const t=Array.isArray(e),n=b(e),i=await w(this.client,Ry,{keys:n},jy,Ly);return t?i.logs:i.logs[0]}async delete(e){const t=b(e);await w(this.client,Dy,{keys:t},Zy,on)}};const Yy=Object.freeze(Object.defineProperty({__proto__:null,Client:qa,ONTOLOGY_TYPE:_a,keyZ:$y,logZ:Mr,newLogZ:Ya,ontologyID:Ay},Symbol.toStringTag,{value:"Module"})),qy=s.z.string().uuid(),Yn=s.z.object({key:s.z.string(),name:s.z.string(),data:Mt.or(s.z.string().transform(r=>JSON.parse(r))),snapshot:s.z.boolean()}),qn=s.z.object({key:s.z.string(),name:s.z.string(),snapshot:s.z.boolean(),data:s.z.string().transform(r=>JSON.parse(r))}),Wa="schematic",Wy=r=>new O({type:Wa,key:r}),Gy="/workspace/schematic/retrieve",Vy="/workspace/schematic/create",Fy="/workspace/schematic/rename",Jy="/workspace/schematic/set-data",Ky="/workspace/schematic/delete",Hy="/workspace/schematic/copy",Ga=Yn.partial({key:!0,snapshot:!0}).transform(r=>({...r,data:JSON.stringify(r.data)})),Xy=s.z.object({keys:s.z.string().array()}),Qy=s.z.object({workspace:s.z.string(),schematics:Ga.array()}),eg=s.z.object({key:s.z.string(),name:s.z.string()}),tg=s.z.object({key:s.z.string(),data:s.z.string()}),rg=s.z.object({keys:s.z.string().array()}),ng=s.z.object({key:s.z.string(),name:s.z.string(),snapshot:s.z.boolean()}),sg=s.z.object({schematics:X(qn)}),ig=s.z.object({schematics:qn.array()}),ag=s.z.object({schematic:Yn}),cn=s.z.object({});let Va=class{constructor(e){c(this,"client");this.client=e}async create(e,t){const n=Array.isArray(t),i=b(t),a=await w(this.client,Vy,{workspace:e,schematics:i},Qy,ig);return n?a.schematics:a.schematics[0]}async rename(e,t){await w(this.client,Fy,{key:e,name:t},eg,cn)}async setData(e,t){await w(this.client,Jy,{key:e,data:JSON.stringify(t)},tg,cn)}async retrieve(e){const t=Array.isArray(e),n=b(e),i=await w(this.client,Gy,{keys:n},Xy,sg);return t?i.schematics:i.schematics[0]}async delete(e){const t=b(e);await w(this.client,Ky,{keys:t},rg,cn)}async copy(e,t,n){return(await w(this.client,Hy,{key:e,name:t,snapshot:n},ng,ag)).schematic}};const og=Object.freeze(Object.defineProperty({__proto__:null,Client:Va,ONTOLOGY_TYPE:Wa,keyZ:qy,newSchematicZ:Ga,ontologyID:Wy,schematicRemoteZ:qn,schematicZ:Yn},Symbol.toStringTag,{value:"Module"})),cg=s.z.string().uuid(),Fa=s.z.object({key:s.z.string(),name:s.z.string(),data:Mt.or(s.z.string().transform(r=>JSON.parse(r)))}),Ja="table",lg=r=>new O({type:Ja,key:r}),ug="/workspace/table/retrieve",hg="/workspace/table/create",dg="/workspace/table/rename",fg="/workspace/table/set-data",yg="/workspace/table/delete",Ka=Fa.partial({key:!0}).transform(r=>({...r,data:JSON.stringify(r.data)})),Wn=s.z.object({key:s.z.string(),name:s.z.string(),data:s.z.string().transform(r=>JSON.parse(r))}),gg=s.z.object({keys:s.z.string().array()}),pg=s.z.object({workspace:s.z.string(),tables:Ka.array()}),mg=s.z.object({key:s.z.string(),name:s.z.string()}),wg=s.z.object({key:s.z.string(),data:s.z.string()}),bg=s.z.object({keys:s.z.string().array()}),vg=s.z.object({tables:Wn.array()}),Tg=s.z.object({tables:Wn.array()}),ln=s.z.object({});let Ha=class{constructor(e){c(this,"client");this.client=e}async create(e,t){const n=Array.isArray(t),i=b(t),a=await w(this.client,hg,{workspace:e,tables:i},pg,Tg);return n?a.tables:a.tables[0]}async rename(e,t){await w(this.client,dg,{key:e,name:t},mg,ln)}async setData(e,t){await w(this.client,fg,{key:e,data:JSON.stringify(t)},wg,ln)}async retrieve(e){const t=Array.isArray(e),n=b(e),i=await w(this.client,ug,{keys:n},gg,vg);return t?i.tables:i.tables[0]}async delete(e){const t=b(e);await w(this.client,yg,{keys:t},bg,ln)}};const Og=Object.freeze(Object.defineProperty({__proto__:null,Client:Ha,ONTOLOGY_TYPE:Ja,keyZ:cg,newTableZ:Ka,ontologyID:lg,tableRemoteZ:Wn,tableZ:Fa},Symbol.toStringTag,{value:"Module"})),zg=s.z.string().uuid(),Xa=r=>JSON.parse(r),Br=s.z.object({key:s.z.string(),name:s.z.string(),layout:Mt.or(s.z.string().transform(r=>Xa(r)))}),Qa="workspace",Eg=r=>new O({type:Qa,key:r}),Xt="/workspace/retrieve",Ng="/workspace/create",Sg="/workspace/rename",Ig="/workspace/set-layout",kg="/workspace/delete",eo=Br.partial({key:!0}).transform(r=>({...r,layout:JSON.stringify(r.layout)})),to=Br.omit({layout:!0}).extend({layout:s.z.string().transform(r=>Xa(r))}),Qt=s.z.object({keys:s.z.string().array().optional(),search:s.z.string().optional(),author:s.z.string().uuid().optional(),offset:s.z.number().optional(),limit:s.z.number().optional()}),$g=s.z.object({workspaces:eo.array()}),Ag=s.z.object({key:s.z.string(),name:s.z.string()}),Rg=s.z.object({key:s.z.string(),layout:s.z.string()}),xg=s.z.object({keys:s.z.string().array()}),er=s.z.object({workspaces:X(Br)}),Cg=s.z.object({workspaces:to.array()}),un=s.z.object({});class ro{constructor(e){c(this,"type","workspace");c(this,"schematic");c(this,"linePlot");c(this,"log");c(this,"table");c(this,"client");this.client=e,this.schematic=new Va(e),this.linePlot=new La(e),this.log=new qa(e),this.table=new Ha(e)}async create(e){const t=Array.isArray(e),n=b(e),i=await w(this.client,Ng,{workspaces:n},$g,Cg);return t?i.workspaces:i.workspaces[0]}async rename(e,t){await w(this.client,Sg,{key:e,name:t},Ag,un)}async setLayout(e,t){await w(this.client,Ig,{key:e,layout:JSON.stringify(t)},Rg,un)}async retrieve(e){const t=Array.isArray(e),n=b(e),i=await w(this.client,Xt,{keys:n},Qt,er);return t?i.workspaces:i.workspaces[0]}async retrieveByAuthor(e){return(await w(this.client,Xt,{author:e},Qt,er)).workspaces}async search(e){return(await w(this.client,Xt,{search:e},Qt,er)).workspaces}async page(e,t){return(await w(this.client,Xt,{offset:e,limit:t},Qt,er)).workspaces}async delete(e){const t=b(e);await w(this.client,kg,{keys:t},xg,un)}}const Pg=Object.freeze(Object.defineProperty({__proto__:null,Client:ro,ONTOLOGY_TYPE:Qa,keyZ:zg,newWorkspaceZ:eo,ontologyID:Eg,workspaceRemoteZ:to,workspaceZ:Br},Symbol.toStringTag,{value:"Module"})),no=s.z.object({host:s.z.string({required_error:"Host is required"}).min(1,"Host is required"),port:s.z.number({required_error:"Port is required"}).or(s.z.string({required_error:"Port is required"})),username:s.z.string().min(1,"Username is required"),password:s.z.string().min(1,"Password is required"),connectivityPollFrequency:z.z.default(z.seconds(30)),secure:s.z.boolean().optional().default(!1),name:s.z.string().optional(),retry:Iu.breakerConfig.optional()});class so extends da{constructor(t){const n=no.parse(t),{host:i,port:a,username:o,password:l,connectivityPollFrequency:u,secure:h,retry:y}=n,d=new yy(new Tu({host:i,port:Number(a)}),y,h);d.use(Mu);let j;o!=null&&l!=null&&(j=new hd(d.unary,{username:o,password:l}),d.use(j.middleware()));const $=new Dn(new xt(d.unary)),te=new ta(d.unary,$);super(d.stream,d.unary,$);c(this,"createdAt");c(this,"props");c(this,"ranges");c(this,"channels");c(this,"auth");c(this,"user");c(this,"access");c(this,"connectivity");c(this,"ontology");c(this,"workspaces");c(this,"labels");c(this,"hardware");c(this,"control");c(this,"transport");c(this,"clientVersion","0.37.0");this.createdAt=I.now(),this.props=n,this.auth=j,this.transport=d,this.channels=new ea(this,$,d.unary,te),this.connectivity=new Ct(d.unary,u,this.clientVersion,n.name),this.control=new ya(this),this.ontology=new Yi(d.unary,this);const U=new Ba(this.transport.unary);this.labels=new Ra(this.transport.unary,this,this.ontology),this.ranges=new Ma(this,U,this.transport.unary,$,this.labels,this.ontology),this.access=new Fi(this.transport.unary),this.user=new sa(this.transport.unary),this.workspaces=new ro(this.transport.unary);const io=new va(this.transport.unary,this),Gn=new Sa(this.transport.unary,this,this.ontology,this.ranges),ao=new Ta(this.transport.unary,this,Gn);this.hardware=new ga(Gn,ao,io)}get key(){return this.createdAt.valueOf().toString()}close(){this.connectivity.stopChecking()}}c(so,"connectivity",Ct);const Dg=it.Authority;exports.AuthError=xe;exports.Authority=Dg;exports.Channel=jn;exports.ContiguityError=En;exports.DataType=S;exports.Density=F;exports.Frame=_;exports.MultiSeries=Ri;exports.MultipleFoundError=me;exports.NotFoundError=pe;exports.QueryError=re;exports.Rate=nt;exports.RouteError=Rt;exports.Series=Oe;exports.Synnax=so;exports.TimeRange=W;exports.TimeSpan=z;exports.TimeStamp=I;exports.UnexpectedError=Ee;exports.ValidationError=B;exports.access=mh;exports.channel=Uh;exports.connection=yd;exports.control=jd;exports.device=Kd;exports.framer=Rd;exports.group=Ku;exports.hardware=Md;exports.label=Cf;exports.linePlot=ky;exports.log=Yy;exports.ontology=rh;exports.policy=ph;exports.rack=nf;exports.ranger=dy;exports.schematic=og;exports.signals=Zd;exports.synnaxPropsZ=no;exports.table=Og;exports.task=wf;exports.user=sd;exports.workspace=Pg;