@synnaxlabs/client 0.31.1 → 0.32.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/.turbo/turbo-build.log +5 -5
- package/dist/client.cjs +15 -15
- package/dist/client.js +185 -172
- package/dist/hardware/task/client.d.ts +1 -1
- package/dist/hardware/task/client.d.ts.map +1 -1
- package/dist/user/payload.d.ts +6 -6
- package/dist/user/payload.d.ts.map +1 -1
- package/package.json +5 -5
- package/src/hardware/task/client.ts +1 -1
- package/src/user/payload.ts +6 -3
package/dist/client.cjs
CHANGED
|
@@ -1,36 +1,36 @@
|
|
|
1
|
-
"use strict";var za=Object.defineProperty;var Ea=(r,e,t)=>e in r?za(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t;var o=(r,e,t)=>Ea(r,typeof e!="symbol"?e+"":e,t);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const s=require("zod"),T=r=>Array.isArray(r)?r:[r];var Sa=Object.defineProperty,Na=(r,e,t)=>e in r?Sa(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,k=(r,e,t)=>Na(r,typeof e!="symbol"?e+"":e,t);const Ia=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:e[0].toLowerCase()+e.slice(1)},ps=r=>{const e=(t,n=Vr)=>{if(typeof t=="string")return r(t);if(Array.isArray(t))return t.map(c=>e(c,n));if(!$r(t))return t;n=$a(n);const i={},a=t;return Object.keys(a).forEach(c=>{let l=a[c];const u=r(c);n.recursive&&($r(l)?Sn(l,n.keepTypesOnRecursion)||(l=e(l,n)):n.recursiveInArray&&En(l)&&(l=[...l].map(
|
|
1
|
+
"use strict";var za=Object.defineProperty;var Ea=(r,e,t)=>e in r?za(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t;var o=(r,e,t)=>Ea(r,typeof e!="symbol"?e+"":e,t);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const s=require("zod"),T=r=>Array.isArray(r)?r:[r];var Sa=Object.defineProperty,Na=(r,e,t)=>e in r?Sa(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,k=(r,e,t)=>Na(r,typeof e!="symbol"?e+"":e,t);const Ia=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:e[0].toLowerCase()+e.slice(1)},ps=r=>{const e=(t,n=Vr)=>{if(typeof t=="string")return r(t);if(Array.isArray(t))return t.map(c=>e(c,n));if(!$r(t))return t;n=$a(n);const i={},a=t;return Object.keys(a).forEach(c=>{let l=a[c];const u=r(c);n.recursive&&($r(l)?Sn(l,n.keepTypesOnRecursion)||(l=e(l,n)):n.recursiveInArray&&En(l)&&(l=[...l].map(h=>{let d=h;return $r(h)?Sn(d,n.keepTypesOnRecursion)||(d=e(h,n)):En(h)&&(d=e({key:h},n).key),d}))),i[u]=l}),i};return e},gs=ps(Ia),ka=r=>r.replace(/([a-z0-9])([A-Z])/g,(e,t,n)=>`${t}_${n.toLowerCase()}`),Aa=ps(ka),Vr={recursive:!0,recursiveInArray:!0,keepTypesOnRecursion:[Number,String,Uint8Array]},$a=(r=Vr)=>(r.recursive==null?r=Vr:r.recursiveInArray==null&&(r.recursiveInArray=!1),r),En=r=>r!=null&&Array.isArray(r),$r=r=>r!=null&&typeof r=="object"&&!Array.isArray(r),Sn=(r,e)=>(e||[]).some(t=>r instanceof t),ms=r=>r!=null&&typeof r=="object"&&!Array.isArray(r);var Ra=Object.defineProperty,xa=(r,e,t)=>e in r?Ra(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,wt=(r,e,t)=>xa(r,typeof e!="symbol"?e+"":e,t);let Ca=class{constructor(){wt(this,"contentType","application/json"),wt(this,"decoder"),wt(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=gs(t);return e!=null?e.parse(n):n}encodeString(r){const e=Aa(r);return JSON.stringify(e,(t,n)=>ArrayBuffer.isView(n)?Array.from(n):ms(n)&&"encode_value"in n?typeof n.value=="bigint"?n.value.toString():n.value:typeof n=="bigint"?n.toString():n)}static registerCustomType(){}},Pa=class{constructor(){wt(this,"contentType","text/csv")}encode(r){const e=this.encodeString(r);return new TextEncoder().encode(e).buffer}decode(r,e){const t=new TextDecoder().decode(r);return this.decodeString(t,e)}encodeString(r){if(!Array.isArray(r)||r.length===0||!ms(r[0]))throw new Error("Payload must be an array of objects");const e=Object.keys(r[0]),t=[e.join(",")];return r.forEach(n=>{const i=e.map(a=>JSON.stringify(n[a]??""));t.push(i.join(","))}),t.join(`
|
|
2
2
|
`)}decodeString(r,e){const[t,...n]=r.trim().split(`
|
|
3
|
-
`).map(c=>c.trim());if(t.length===0)return e!=null?e.parse({}):{};const i=t.split(",").map(c=>c.trim()),a={};return i.forEach(c=>{a[c]=[]}),n.forEach(c=>{const l=c.split(",").map(u=>u.trim());i.forEach((u,y)=>{const d=this.parseValue(l[y]);d!=null&&a[u].push(d)})}),e!=null?e.parse(a):a}parseValue(r){if(r==null||r.length===0)return null;const e=Number(r);return isNaN(e)?r.startsWith('"')&&r.endsWith('"')?r.slice(1,-1):r:e}static registerCustomType(){}},Da=class{constructor(){wt(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 Vt=new Ca;new Pa;new Da;const dr=s.z.tuple([s.z.number(),s.z.number()]);s.z.tuple([s.z.bigint(),s.z.bigint()]);const ws=s.z.object({width:s.z.number(),height:s.z.number()}),ja=s.z.object({signedWidth:s.z.number(),signedHeight:s.z.number()}),Ma=["width","height"];s.z.enum(Ma);const Ba=["start","center","end"],Ua=["signedWidth","signedHeight"];s.z.enum(Ua);const ar=s.z.object({x:s.z.number(),y:s.z.number()}),Za=s.z.object({clientX:s.z.number(),clientY:s.z.number()}),La=["x","y"],bs=s.z.enum(La),Ts=["top","right","bottom","left"];s.z.enum(Ts);const _a=["left","right"],vs=s.z.enum(_a),Ya=["top","bottom"],Os=s.z.enum(Ya),zs=["center"],Nn=s.z.enum(zs),qa=[...Ts,...zs],Es=s.z.enum(qa);s.z.enum(Ba);const Wa=["first","last"];s.z.enum(Wa);const Ga=s.z.object({lower:s.z.number(),upper:s.z.number()}),Fa=s.z.object({lower:s.z.bigint(),upper:s.z.bigint()});s.z.union([Ga,dr]);s.z.union([Fa,dr]);s.z.union([bs,Es]);s.z.union([bs,Es,s.z.instanceof(String)]);const bt=(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 In(r);return In(t)},In=r=>r.lower>r.upper?{lower:r.upper,upper:r.lower}:r;s.z.object({x:vs.or(Nn),y:Os.or(Nn)});const Va=s.z.object({x:vs,y:Os}),Ka=Object.freeze({x:"left",y:"top"}),Ja=(r,e)=>r.x===e.x&&r.y===e.y,kn=s.z.union([s.z.number(),ar,dr,ws,ja,Za]),Ha=(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}},An=Object.freeze({x:0,y:0}),qt=s.z.union([s.z.number(),s.z.string()]);s.z.object({top:qt,left:qt,width:qt,height:qt});s.z.object({left:s.z.number(),top:s.z.number(),right:s.z.number(),bottom:s.z.number()});s.z.object({one:ar,two:ar,root:Va});const cn=(r,e,t=0,n=0,i)=>{const a={one:{...An},two:{...An},root:i??Ka};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))},Rr=r=>{const e=cn(r);return{lower:e.one.x,upper:e.two.x}},xr=r=>{const e=cn(r);return{lower:e.one.y,upper:e.two.y}},Xa=r=>typeof r!="object"||r==null?!1:"one"in r&&"two"in r&&"root"in r;var Qa=Object.defineProperty,eo=(r,e,t)=>e in r?Qa(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,de=(r,e,t)=>eo(r,typeof e!="symbol"?e+"":e,t);const to=(r,e,t)=>e!==void 0&&r<e?e:t!==void 0&&r>t?t:r;s.z.object({offset:kn,scale:kn});const ro=r=>(e,t,n,i)=>t==="dimension"?[e,n]:[e,i?n-r:n+r],no=r=>(e,t,n,i)=>[e,i?n/r:n*r],so=r=>(e,t,n)=>{if(e===null)return[r,n];const{lower:i,upper:a}=e,{lower:c,upper:l}=r,u=a-i,y=l-c;if(t==="dimension")return[r,n*(y/u)];const d=(n-i)*(y/u)+c;return[r,d]},io=r=>(e,t,n)=>[r,n],ao=()=>(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)]},oo=r=>(e,t,n)=>{const{lower:i,upper:a}=r;return n=to(n,i,a),[e,n]},Kr=class ot{constructor(){de(this,"ops",[]),de(this,"currBounds",null),de(this,"currType",null),de(this,"reversed",!1),this.ops=[]}static translate(e){return new ot().translate(e)}static magnify(e){return new ot().magnify(e)}static scale(e,t){return new ot().scale(e,t)}translate(e){const t=this.new(),n=ro(e);return n.type="translate",t.ops.push(n),t}magnify(e){const t=this.new(),n=no(e);return n.type="magnify",t.ops.push(n),t}scale(e,t){const n=bt(e,t),i=this.new(),a=so(n);return a.type="scale",i.ops.push(a),i}clamp(e,t){const n=bt(e,t),i=this.new(),a=oo(n);return a.type="clamp",i.ops.push(a),i}reBound(e,t){const n=bt(e,t),i=this.new(),a=io(n);return a.type="re-bound",i.ops.push(a),i}invert(){const e=ao();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 ot;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(([c,l])=>i>=c&&i<=l))return;const a=e.ops.findIndex((c,l)=>c.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}};de(Kr,"IDENTITY",new Kr);let $n=Kr;const Rn=class le{constructor(e=new $n,t=new $n,n=null){de(this,"x"),de(this,"y"),de(this,"currRoot"),this.x=e,this.y=t,this.currRoot=n}static translate(e,t){return new le().translate(e,t)}static translateX(e){return new le().translateX(e)}static translateY(e){return new le().translateY(e)}static clamp(e){return new le().clamp(e)}static magnify(e){return new le().magnify(e)}static scale(e){return new le().scale(e)}static reBound(e){return new le().reBound(e)}translate(e,t){const n=Ha(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(Xa(e)){const n=this.currRoot;return t.currRoot=e.root,n!=null&&!Ja(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(Rr(e)),t.y=t.y.scale(xr(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(Rr(e)),t.y=this.y.reBound(xr(e)),t}clamp(e){const t=this.copy();return t.x=this.x.clamp(Rr(e)),t.y=this.y.clamp(xr(e)),t}copy(){const e=new le;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)}}box(e){return cn(this.pos(e.one),this.pos(e.two),0,0,this.currRoot??e.root)}};de(Rn,"IDENTITY",new Rn);const co=r=>r!=null&&typeof r=="object"&&"toString"in r,lo=(r,e=!1)=>{const t=co(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?uo(n):n},uo=r=>(e,t)=>r(t,e),ho=s.z.object({signedWidth:s.z.number(),signedHeight:s.z.number()});s.z.union([ws,ho,ar,dr]);const yo=s.z.bigint().or(s.z.string().transform(BigInt));var fo=Object.defineProperty,po=(r,e,t)=>e in r?fo(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,m=(r,e,t)=>po(r,typeof e!="symbol"?e+"":e,t);let go=(r,e=21)=>(t=e)=>{let n="",i=t;for(;i--;)n+=r[Math.random()*r.length|0];return n};const mo="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",wo=go(mo,11),bo=s.z.enum(["static","dynamic"]),Ss=(r,e)=>{const t=new j(e);if(![L.DAY,L.HOUR,L.MINUTE,L.SECOND,L.MILLISECOND,L.MICROSECOND,L.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 j?new j(n):new L(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 c="00",l="00";a!=null&&([c,l]=a.split("."));let u=v.hours(parseInt(n??"00",10)).add(v.minutes(parseInt(i??"00",10))).add(v.seconds(parseInt(c??"00",10))).add(v.milliseconds(parseInt(l??"00",10)));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 L(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 ln(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()))}milliseconds(){return Number(this.valueOf())/Number(v.MILLISECOND.valueOf())}toString(){return this.date().toISOString()}remainder(e){return Ss(this,e)}get isToday(){return this.truncate(L.DAY).equals(v.now().truncate(L.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 j=A;const $=class N{constructor(e){m(this,"value"),m(this,"encodeValue",!0),typeof e=="number"&&(e=Math.trunc(e.valueOf())),this.value=BigInt(e.valueOf())}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 Ss(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),c=this.truncate(N.MICROSECOND),l=this.truncate(N.NANOSECOND),u=e,y=t.sub(e),d=n.sub(t),h=i.sub(n),D=a.sub(i),P=c.sub(a),Q=l.sub(c);let B="";return u.isZero||(B+=`${u.days}d `),y.isZero||(B+=`${y.hours}h `),d.isZero||(B+=`${d.minutes}m `),h.isZero||(B+=`${h.seconds}s `),D.isZero||(B+=`${D.milliseconds}ms `),P.isZero||(B+=`${P.microseconds}µs `),Q.isZero||(B+=`${Q.nanoseconds}ns`),B.trim()}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(e*1e3)}static milliseconds(e=1){return N.microseconds(e*1e3)}static seconds(e=1){return N.milliseconds(e*1e3)}static minutes(e){return N.seconds(e.valueOf()*60)}static hours(e){return N.minutes(e*60)}static days(e){return N.hours(e*24)}};m($,"NANOSECOND",$.nanoseconds(1)),m($,"MICROSECOND",$.microseconds(1)),m($,"MILLISECOND",$.milliseconds(1)),m($,"SECOND",$.seconds(1)),m($,"MINUTE",$.minutes(1)),m($,"HOUR",$.hours(1)),m($,"DAY",$.days(1)),m($,"MAX",new $((1n<<63n)-1n)),m($,"MIN",new $(0)),m($,"ZERO",new $(0)),m($,"z",s.z.union([s.z.object({value:s.z.bigint()}).transform(r=>new $(r.value)),s.z.string().transform(r=>new $(BigInt(r))),s.z.instanceof(Number).transform(r=>new $(r)),s.z.number().transform(r=>new $(r)),s.z.instanceof($)]));let L=$;const Wt=class Kt extends Number{constructor(e){e instanceof Number?super(e.valueOf()):super(e)}toString(){return`${this.valueOf()} Hz`}equals(e){return this.valueOf()===new Kt(e).valueOf()}get period(){return L.seconds(1/this.valueOf())}sampleCount(e){return new L(e).seconds*this.valueOf()}byteCount(e,t){return this.sampleCount(e)*new K(t).valueOf()}span(e){return L.seconds(e/this.valueOf())}byteSpan(e,t){return this.span(e.valueOf()/t.valueOf())}static hz(e){return new Kt(e)}static khz(e){return Kt.hz(e*1e3)}};m(Wt,"z",s.z.union([s.z.number().transform(r=>new Wt(r)),s.z.instanceof(Number).transform(r=>new Wt(r)),s.z.instanceof(Wt)]));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 Ns(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 K=Y;const se=class Jt{constructor(e,t){m(this,"start"),m(this,"end"),typeof e=="object"&&"start"in e?(this.start=new j(e.start),this.end=new j(e.end)):(this.start=new j(e),this.end=new j(t))}get span(){return new L(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 Jt(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=L.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=j.max(n.start,e.start),a=j.min(n.end,e.end);return a.before(i)?!1:new L(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 Jt?this.contains(e.start)&&this.contains(e.end):this.start.beforeEq(e)&&this.end.after(e)}boundBy(e){const t=new Jt(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(se,"MAX",new se(j.MIN,j.MAX)),m(se,"MIN",new se(j.MAX,j.MIN)),m(se,"ZERO",new se(j.ZERO,j.ZERO)),m(se,"z",s.z.union([s.z.object({start:j.z,end:j.z}).transform(r=>new se(r.start,r.end)),s.z.instanceof(se)]));let ln=se;const f=class ie extends String{constructor(e){if(e instanceof ie||typeof e=="string"||typeof e.valueOf()=="string"){super(e.valueOf());return}else{const t=ie.ARRAY_CONSTRUCTOR_DATA_TYPES.get(e.constructor.name);if(t!=null){super(t.valueOf());return}}throw super(ie.UNKNOWN.valueOf()),new Error(`unable to find data type for ${e.toString()}`)}get Array(){const e=ie.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(ie.JSON)||this.equals(ie.STRING)}get isNumeric(){return!this.isVariable&&!this.equals(ie.UUID)}get isInteger(){return this.toString().startsWith("int")}get isFloat(){return this.toString().startsWith("float")}get density(){const e=ie.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 ie.BIG_INT_TYPES.some(e=>e.equals(this))}};m(f,"UNKNOWN",new f("unknown")),m(f,"FLOAT64",new f("float64")),m(f,"FLOAT32",new f("float32")),m(f,"INT64",new f("int64")),m(f,"INT32",new f("int32")),m(f,"INT16",new f("int16")),m(f,"INT8",new f("int8")),m(f,"UINT64",new f("uint64")),m(f,"UINT32",new f("uint32")),m(f,"UINT16",new f("uint16")),m(f,"UINT8",new f("uint8")),m(f,"BOOLEAN",f.UINT8),m(f,"TIMESTAMP",new f("timestamp")),m(f,"UUID",new f("uuid")),m(f,"STRING",new f("string")),m(f,"JSON",new f("json")),m(f,"ARRAY_CONSTRUCTORS",new Map([[f.UINT8.toString(),Uint8Array],[f.UINT16.toString(),Uint16Array],[f.UINT32.toString(),Uint32Array],[f.UINT64.toString(),BigUint64Array],[f.FLOAT32.toString(),Float32Array],[f.FLOAT64.toString(),Float64Array],[f.INT8.toString(),Int8Array],[f.INT16.toString(),Int16Array],[f.INT32.toString(),Int32Array],[f.INT64.toString(),BigInt64Array],[f.TIMESTAMP.toString(),BigInt64Array],[f.STRING.toString(),Uint8Array],[f.JSON.toString(),Uint8Array],[f.UUID.toString(),Uint8Array]])),m(f,"ARRAY_CONSTRUCTOR_DATA_TYPES",new Map([[Uint8Array.name,f.UINT8],[Uint16Array.name,f.UINT16],[Uint32Array.name,f.UINT32],[BigUint64Array.name,f.UINT64],[Float32Array.name,f.FLOAT32],[Float64Array.name,f.FLOAT64],[Int8Array.name,f.INT8],[Int16Array.name,f.INT16],[Int32Array.name,f.INT32],[BigInt64Array.name,f.INT64]])),m(f,"DENSITIES",new Map([[f.UINT8.toString(),K.BIT8],[f.UINT16.toString(),K.BIT16],[f.UINT32.toString(),K.BIT32],[f.UINT64.toString(),K.BIT64],[f.FLOAT32.toString(),K.BIT32],[f.FLOAT64.toString(),K.BIT64],[f.INT8.toString(),K.BIT8],[f.INT16.toString(),K.BIT16],[f.INT32.toString(),K.BIT32],[f.INT64.toString(),K.BIT64],[f.TIMESTAMP.toString(),K.BIT64],[f.STRING.toString(),K.UNKNOWN],[f.JSON.toString(),K.UNKNOWN],[f.UUID.toString(),K.BIT128]])),m(f,"ALL",[f.UNKNOWN,f.FLOAT64,f.FLOAT32,f.INT64,f.INT32,f.INT16,f.INT8,f.UINT64,f.UINT32,f.UINT16,f.UINT8,f.TIMESTAMP,f.UUID,f.STRING,f.JSON]),m(f,"BIG_INT_TYPES",[f.INT64,f.UINT64,f.TIMESTAMP]),m(f,"z",s.z.union([s.z.string().transform(r=>new f(r)),s.z.instanceof(f)]));let R=f;const G=class U extends Number{constructor(e){super(e.valueOf())}largerThan(e){return this.valueOf()>e.valueOf()}smallerThan(e){return this.valueOf()<e.valueOf()}add(e){return U.bytes(this.valueOf()+e.valueOf())}sub(e){return U.bytes(this.valueOf()-e.valueOf())}truncate(e){return new U(Math.trunc(this.valueOf()/e.valueOf())*e.valueOf())}remainder(e){return U.bytes(this.valueOf()%e.valueOf())}get gigabytes(){return this.valueOf()/U.GIGABYTE.valueOf()}get megabytes(){return this.valueOf()/U.MEGABYTE.valueOf()}get kilobytes(){return this.valueOf()/U.KILOBYTE.valueOf()}get terabytes(){return this.valueOf()/U.TERABYTE.valueOf()}toString(){const e=this.truncate(U.TERABYTE),t=this.truncate(U.GIGABYTE),n=this.truncate(U.MEGABYTE),i=this.truncate(U.KILOBYTE),a=this.truncate(U.BYTE),c=e,l=t.sub(e),u=n.sub(t),y=i.sub(n),d=a.sub(i);let h="";return c.isZero||(h+=`${c.terabytes}TB `),l.isZero||(h+=`${l.gigabytes}GB `),u.isZero||(h+=`${u.megabytes}MB `),y.isZero||(h+=`${y.kilobytes}KB `),(!d.isZero||h==="")&&(h+=`${d.valueOf()}B`),h.trim()}static bytes(e=1){return new U(e)}static kilobytes(e=1){return U.bytes(e.valueOf()*1e3)}static megabytes(e=1){return U.kilobytes(e.valueOf()*1e3)}static gigabytes(e=1){return U.megabytes(e.valueOf()*1e3)}static terabytes(e){return U.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 Ns=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 Is=r=>{const e=typeof r;return e==="string"||e==="number"||e==="boolean"||e==="bigint"||r instanceof j||r instanceof L||r instanceof Date},To=(r,e,t,n=0)=>r.usesBigInt&&!e.usesBigInt?Number(t)-Number(n):!r.usesBigInt&&e.usesBigInt?BigInt(t)-BigInt(n):lt(t,-n),vo=r=>r==null?!1:Array.isArray(r)||r instanceof ArrayBuffer||ArrayBuffer.isView(r)&&!(r instanceof DataView)||r instanceof Eo?!0:Is(r),Ne=-1,Oo=s.z.string().transform(r=>new Uint8Array(atob(r).split("").map(e=>e.charCodeAt(0))).buffer),zo=s.z.union([s.z.null(),s.z.undefined()]).transform(()=>new Uint8Array().buffer),ct=class ue{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",Ne),m(this,"_refCount",0),m(this,"_cachedLength"),vo(e)&&(e={data:e});const{dataType:t,timeRange:n,sampleOffset:i=0,glBufferUsage:a="static",alignment:c=0n,key:l=wo()}=e,u=e.data??[];if(u instanceof ue||typeof u=="object"&&"isSynnaxSeries"in u&&u.isSynnaxSeries===!0){const h=u;this.key=h.key,this.dataType=h.dataType,this.sampleOffset=h.sampleOffset,this.gl=h.gl,this._data=h._data,this._timeRange=h._timeRange,this.alignment=h.alignment,this._cachedMin=h._cachedMin,this._cachedMax=h._cachedMax,this.writePos=h.writePos,this._refCount=h._refCount,this._cachedLength=h._cachedLength;return}const y=Is(u),d=Array.isArray(u);if(t!=null)this.dataType=new R(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(d||y){let h=u;if(!y){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.");h=u[0]}if(typeof h=="string")this.dataType=R.STRING;else if(typeof h=="number")this.dataType=R.FLOAT64;else if(typeof h=="bigint")this.dataType=R.INT64;else if(typeof h=="boolean")this.dataType=R.BOOLEAN;else if(h instanceof j||h instanceof Date||h instanceof j)this.dataType=R.TIMESTAMP;else if(typeof h=="object")this.dataType=R.JSON;else throw new Error(`cannot infer data type of ${typeof h} when constructing a Series from a JS array`)}else this.dataType=new R(u)}if(!d&&!y)this._data=u;else{let h=y?[u]:u;const D=h[0];(D instanceof j||D instanceof Date||D instanceof L)&&(h=h.map(P=>new j(P).valueOf())),this.dataType.equals(R.STRING)?(this._cachedLength=h.length,this._data=new TextEncoder().encode(h.join(`
|
|
3
|
+
`).map(c=>c.trim());if(t.length===0)return e!=null?e.parse({}):{};const i=t.split(",").map(c=>c.trim()),a={};return i.forEach(c=>{a[c]=[]}),n.forEach(c=>{const l=c.split(",").map(u=>u.trim());i.forEach((u,h)=>{const d=this.parseValue(l[h]);d!=null&&a[u].push(d)})}),e!=null?e.parse(a):a}parseValue(r){if(r==null||r.length===0)return null;const e=Number(r);return isNaN(e)?r.startsWith('"')&&r.endsWith('"')?r.slice(1,-1):r:e}static registerCustomType(){}},Da=class{constructor(){wt(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 Vt=new Ca;new Pa;new Da;const dr=s.z.tuple([s.z.number(),s.z.number()]);s.z.tuple([s.z.bigint(),s.z.bigint()]);const ws=s.z.object({width:s.z.number(),height:s.z.number()}),ja=s.z.object({signedWidth:s.z.number(),signedHeight:s.z.number()}),Ma=["width","height"];s.z.enum(Ma);const Ba=["start","center","end"],Ua=["signedWidth","signedHeight"];s.z.enum(Ua);const ar=s.z.object({x:s.z.number(),y:s.z.number()}),Za=s.z.object({clientX:s.z.number(),clientY:s.z.number()}),La=["x","y"],bs=s.z.enum(La),Ts=["top","right","bottom","left"];s.z.enum(Ts);const _a=["left","right"],vs=s.z.enum(_a),Ya=["top","bottom"],Os=s.z.enum(Ya),zs=["center"],Nn=s.z.enum(zs),qa=[...Ts,...zs],Es=s.z.enum(qa);s.z.enum(Ba);const Wa=["first","last"];s.z.enum(Wa);const Ga=s.z.object({lower:s.z.number(),upper:s.z.number()}),Fa=s.z.object({lower:s.z.bigint(),upper:s.z.bigint()});s.z.union([Ga,dr]);s.z.union([Fa,dr]);s.z.union([bs,Es]);s.z.union([bs,Es,s.z.instanceof(String)]);const bt=(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 In(r);return In(t)},In=r=>r.lower>r.upper?{lower:r.upper,upper:r.lower}:r;s.z.object({x:vs.or(Nn),y:Os.or(Nn)});const Va=s.z.object({x:vs,y:Os}),Ka=Object.freeze({x:"left",y:"top"}),Ja=(r,e)=>r.x===e.x&&r.y===e.y,kn=s.z.union([s.z.number(),ar,dr,ws,ja,Za]),Ha=(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}},An=Object.freeze({x:0,y:0}),qt=s.z.union([s.z.number(),s.z.string()]);s.z.object({top:qt,left:qt,width:qt,height:qt});s.z.object({left:s.z.number(),top:s.z.number(),right:s.z.number(),bottom:s.z.number()});s.z.object({one:ar,two:ar,root:Va});const cn=(r,e,t=0,n=0,i)=>{const a={one:{...An},two:{...An},root:i??Ka};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))},Rr=r=>{const e=cn(r);return{lower:e.one.x,upper:e.two.x}},xr=r=>{const e=cn(r);return{lower:e.one.y,upper:e.two.y}},Xa=r=>typeof r!="object"||r==null?!1:"one"in r&&"two"in r&&"root"in r;var Qa=Object.defineProperty,eo=(r,e,t)=>e in r?Qa(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,de=(r,e,t)=>eo(r,typeof e!="symbol"?e+"":e,t);const to=(r,e,t)=>e!==void 0&&r<e?e:t!==void 0&&r>t?t:r;s.z.object({offset:kn,scale:kn});const ro=r=>(e,t,n,i)=>t==="dimension"?[e,n]:[e,i?n-r:n+r],no=r=>(e,t,n,i)=>[e,i?n/r:n*r],so=r=>(e,t,n)=>{if(e===null)return[r,n];const{lower:i,upper:a}=e,{lower:c,upper:l}=r,u=a-i,h=l-c;if(t==="dimension")return[r,n*(h/u)];const d=(n-i)*(h/u)+c;return[r,d]},io=r=>(e,t,n)=>[r,n],ao=()=>(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)]},oo=r=>(e,t,n)=>{const{lower:i,upper:a}=r;return n=to(n,i,a),[e,n]},Kr=class ot{constructor(){de(this,"ops",[]),de(this,"currBounds",null),de(this,"currType",null),de(this,"reversed",!1),this.ops=[]}static translate(e){return new ot().translate(e)}static magnify(e){return new ot().magnify(e)}static scale(e,t){return new ot().scale(e,t)}translate(e){const t=this.new(),n=ro(e);return n.type="translate",t.ops.push(n),t}magnify(e){const t=this.new(),n=no(e);return n.type="magnify",t.ops.push(n),t}scale(e,t){const n=bt(e,t),i=this.new(),a=so(n);return a.type="scale",i.ops.push(a),i}clamp(e,t){const n=bt(e,t),i=this.new(),a=oo(n);return a.type="clamp",i.ops.push(a),i}reBound(e,t){const n=bt(e,t),i=this.new(),a=io(n);return a.type="re-bound",i.ops.push(a),i}invert(){const e=ao();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 ot;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(([c,l])=>i>=c&&i<=l))return;const a=e.ops.findIndex((c,l)=>c.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}};de(Kr,"IDENTITY",new Kr);let $n=Kr;const Rn=class le{constructor(e=new $n,t=new $n,n=null){de(this,"x"),de(this,"y"),de(this,"currRoot"),this.x=e,this.y=t,this.currRoot=n}static translate(e,t){return new le().translate(e,t)}static translateX(e){return new le().translateX(e)}static translateY(e){return new le().translateY(e)}static clamp(e){return new le().clamp(e)}static magnify(e){return new le().magnify(e)}static scale(e){return new le().scale(e)}static reBound(e){return new le().reBound(e)}translate(e,t){const n=Ha(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(Xa(e)){const n=this.currRoot;return t.currRoot=e.root,n!=null&&!Ja(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(Rr(e)),t.y=t.y.scale(xr(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(Rr(e)),t.y=this.y.reBound(xr(e)),t}clamp(e){const t=this.copy();return t.x=this.x.clamp(Rr(e)),t.y=this.y.clamp(xr(e)),t}copy(){const e=new le;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)}}box(e){return cn(this.pos(e.one),this.pos(e.two),0,0,this.currRoot??e.root)}};de(Rn,"IDENTITY",new Rn);const co=r=>r!=null&&typeof r=="object"&&"toString"in r,lo=(r,e=!1)=>{const t=co(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?uo(n):n},uo=r=>(e,t)=>r(t,e),ho=s.z.object({signedWidth:s.z.number(),signedHeight:s.z.number()});s.z.union([ws,ho,ar,dr]);const yo=s.z.bigint().or(s.z.string().transform(BigInt));var fo=Object.defineProperty,po=(r,e,t)=>e in r?fo(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,m=(r,e,t)=>po(r,typeof e!="symbol"?e+"":e,t);let go=(r,e=21)=>(t=e)=>{let n="",i=t;for(;i--;)n+=r[Math.random()*r.length|0];return n};const mo="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",wo=go(mo,11),bo=s.z.enum(["static","dynamic"]),Ss=(r,e)=>{const t=new j(e);if(![L.DAY,L.HOUR,L.MINUTE,L.SECOND,L.MILLISECOND,L.MICROSECOND,L.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 j?new j(n):new L(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 c="00",l="00";a!=null&&([c,l]=a.split("."));let u=v.hours(parseInt(n??"00",10)).add(v.minutes(parseInt(i??"00",10))).add(v.seconds(parseInt(c??"00",10))).add(v.milliseconds(parseInt(l??"00",10)));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 L(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 ln(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()))}milliseconds(){return Number(this.valueOf())/Number(v.MILLISECOND.valueOf())}toString(){return this.date().toISOString()}remainder(e){return Ss(this,e)}get isToday(){return this.truncate(L.DAY).equals(v.now().truncate(L.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 j=A;const $=class N{constructor(e){m(this,"value"),m(this,"encodeValue",!0),typeof e=="number"&&(e=Math.trunc(e.valueOf())),this.value=BigInt(e.valueOf())}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 Ss(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),c=this.truncate(N.MICROSECOND),l=this.truncate(N.NANOSECOND),u=e,h=t.sub(e),d=n.sub(t),y=i.sub(n),P=a.sub(i),D=c.sub(a),Q=l.sub(c);let B="";return u.isZero||(B+=`${u.days}d `),h.isZero||(B+=`${h.hours}h `),d.isZero||(B+=`${d.minutes}m `),y.isZero||(B+=`${y.seconds}s `),P.isZero||(B+=`${P.milliseconds}ms `),D.isZero||(B+=`${D.microseconds}µs `),Q.isZero||(B+=`${Q.nanoseconds}ns`),B.trim()}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(e*1e3)}static milliseconds(e=1){return N.microseconds(e*1e3)}static seconds(e=1){return N.milliseconds(e*1e3)}static minutes(e){return N.seconds(e.valueOf()*60)}static hours(e){return N.minutes(e*60)}static days(e){return N.hours(e*24)}};m($,"NANOSECOND",$.nanoseconds(1)),m($,"MICROSECOND",$.microseconds(1)),m($,"MILLISECOND",$.milliseconds(1)),m($,"SECOND",$.seconds(1)),m($,"MINUTE",$.minutes(1)),m($,"HOUR",$.hours(1)),m($,"DAY",$.days(1)),m($,"MAX",new $((1n<<63n)-1n)),m($,"MIN",new $(0)),m($,"ZERO",new $(0)),m($,"z",s.z.union([s.z.object({value:s.z.bigint()}).transform(r=>new $(r.value)),s.z.string().transform(r=>new $(BigInt(r))),s.z.instanceof(Number).transform(r=>new $(r)),s.z.number().transform(r=>new $(r)),s.z.instanceof($)]));let L=$;const Wt=class Kt extends Number{constructor(e){e instanceof Number?super(e.valueOf()):super(e)}toString(){return`${this.valueOf()} Hz`}equals(e){return this.valueOf()===new Kt(e).valueOf()}get period(){return L.seconds(1/this.valueOf())}sampleCount(e){return new L(e).seconds*this.valueOf()}byteCount(e,t){return this.sampleCount(e)*new K(t).valueOf()}span(e){return L.seconds(e/this.valueOf())}byteSpan(e,t){return this.span(e.valueOf()/t.valueOf())}static hz(e){return new Kt(e)}static khz(e){return Kt.hz(e*1e3)}};m(Wt,"z",s.z.union([s.z.number().transform(r=>new Wt(r)),s.z.instanceof(Number).transform(r=>new Wt(r)),s.z.instanceof(Wt)]));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 Ns(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 K=Y;const se=class Jt{constructor(e,t){m(this,"start"),m(this,"end"),typeof e=="object"&&"start"in e?(this.start=new j(e.start),this.end=new j(e.end)):(this.start=new j(e),this.end=new j(t))}get span(){return new L(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 Jt(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=L.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=j.max(n.start,e.start),a=j.min(n.end,e.end);return a.before(i)?!1:new L(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 Jt?this.contains(e.start)&&this.contains(e.end):this.start.beforeEq(e)&&this.end.after(e)}boundBy(e){const t=new Jt(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(se,"MAX",new se(j.MIN,j.MAX)),m(se,"MIN",new se(j.MAX,j.MIN)),m(se,"ZERO",new se(j.ZERO,j.ZERO)),m(se,"z",s.z.union([s.z.object({start:j.z,end:j.z}).transform(r=>new se(r.start,r.end)),s.z.instanceof(se)]));let ln=se;const f=class ie extends String{constructor(e){if(e instanceof ie||typeof e=="string"||typeof e.valueOf()=="string"){super(e.valueOf());return}else{const t=ie.ARRAY_CONSTRUCTOR_DATA_TYPES.get(e.constructor.name);if(t!=null){super(t.valueOf());return}}throw super(ie.UNKNOWN.valueOf()),new Error(`unable to find data type for ${e.toString()}`)}get Array(){const e=ie.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(ie.JSON)||this.equals(ie.STRING)}get isNumeric(){return!this.isVariable&&!this.equals(ie.UUID)}get isInteger(){return this.toString().startsWith("int")}get isFloat(){return this.toString().startsWith("float")}get density(){const e=ie.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 ie.BIG_INT_TYPES.some(e=>e.equals(this))}};m(f,"UNKNOWN",new f("unknown")),m(f,"FLOAT64",new f("float64")),m(f,"FLOAT32",new f("float32")),m(f,"INT64",new f("int64")),m(f,"INT32",new f("int32")),m(f,"INT16",new f("int16")),m(f,"INT8",new f("int8")),m(f,"UINT64",new f("uint64")),m(f,"UINT32",new f("uint32")),m(f,"UINT16",new f("uint16")),m(f,"UINT8",new f("uint8")),m(f,"BOOLEAN",f.UINT8),m(f,"TIMESTAMP",new f("timestamp")),m(f,"UUID",new f("uuid")),m(f,"STRING",new f("string")),m(f,"JSON",new f("json")),m(f,"ARRAY_CONSTRUCTORS",new Map([[f.UINT8.toString(),Uint8Array],[f.UINT16.toString(),Uint16Array],[f.UINT32.toString(),Uint32Array],[f.UINT64.toString(),BigUint64Array],[f.FLOAT32.toString(),Float32Array],[f.FLOAT64.toString(),Float64Array],[f.INT8.toString(),Int8Array],[f.INT16.toString(),Int16Array],[f.INT32.toString(),Int32Array],[f.INT64.toString(),BigInt64Array],[f.TIMESTAMP.toString(),BigInt64Array],[f.STRING.toString(),Uint8Array],[f.JSON.toString(),Uint8Array],[f.UUID.toString(),Uint8Array]])),m(f,"ARRAY_CONSTRUCTOR_DATA_TYPES",new Map([[Uint8Array.name,f.UINT8],[Uint16Array.name,f.UINT16],[Uint32Array.name,f.UINT32],[BigUint64Array.name,f.UINT64],[Float32Array.name,f.FLOAT32],[Float64Array.name,f.FLOAT64],[Int8Array.name,f.INT8],[Int16Array.name,f.INT16],[Int32Array.name,f.INT32],[BigInt64Array.name,f.INT64]])),m(f,"DENSITIES",new Map([[f.UINT8.toString(),K.BIT8],[f.UINT16.toString(),K.BIT16],[f.UINT32.toString(),K.BIT32],[f.UINT64.toString(),K.BIT64],[f.FLOAT32.toString(),K.BIT32],[f.FLOAT64.toString(),K.BIT64],[f.INT8.toString(),K.BIT8],[f.INT16.toString(),K.BIT16],[f.INT32.toString(),K.BIT32],[f.INT64.toString(),K.BIT64],[f.TIMESTAMP.toString(),K.BIT64],[f.STRING.toString(),K.UNKNOWN],[f.JSON.toString(),K.UNKNOWN],[f.UUID.toString(),K.BIT128]])),m(f,"ALL",[f.UNKNOWN,f.FLOAT64,f.FLOAT32,f.INT64,f.INT32,f.INT16,f.INT8,f.UINT64,f.UINT32,f.UINT16,f.UINT8,f.TIMESTAMP,f.UUID,f.STRING,f.JSON]),m(f,"BIG_INT_TYPES",[f.INT64,f.UINT64,f.TIMESTAMP]),m(f,"z",s.z.union([s.z.string().transform(r=>new f(r)),s.z.instanceof(f)]));let R=f;const G=class U extends Number{constructor(e){super(e.valueOf())}largerThan(e){return this.valueOf()>e.valueOf()}smallerThan(e){return this.valueOf()<e.valueOf()}add(e){return U.bytes(this.valueOf()+e.valueOf())}sub(e){return U.bytes(this.valueOf()-e.valueOf())}truncate(e){return new U(Math.trunc(this.valueOf()/e.valueOf())*e.valueOf())}remainder(e){return U.bytes(this.valueOf()%e.valueOf())}get gigabytes(){return this.valueOf()/U.GIGABYTE.valueOf()}get megabytes(){return this.valueOf()/U.MEGABYTE.valueOf()}get kilobytes(){return this.valueOf()/U.KILOBYTE.valueOf()}get terabytes(){return this.valueOf()/U.TERABYTE.valueOf()}toString(){const e=this.truncate(U.TERABYTE),t=this.truncate(U.GIGABYTE),n=this.truncate(U.MEGABYTE),i=this.truncate(U.KILOBYTE),a=this.truncate(U.BYTE),c=e,l=t.sub(e),u=n.sub(t),h=i.sub(n),d=a.sub(i);let y="";return c.isZero||(y+=`${c.terabytes}TB `),l.isZero||(y+=`${l.gigabytes}GB `),u.isZero||(y+=`${u.megabytes}MB `),h.isZero||(y+=`${h.kilobytes}KB `),(!d.isZero||y==="")&&(y+=`${d.valueOf()}B`),y.trim()}static bytes(e=1){return new U(e)}static kilobytes(e=1){return U.bytes(e.valueOf()*1e3)}static megabytes(e=1){return U.kilobytes(e.valueOf()*1e3)}static gigabytes(e=1){return U.megabytes(e.valueOf()*1e3)}static terabytes(e){return U.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 Ns=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 Is=r=>{const e=typeof r;return e==="string"||e==="number"||e==="boolean"||e==="bigint"||r instanceof j||r instanceof L||r instanceof Date},To=(r,e,t,n=0)=>r.usesBigInt&&!e.usesBigInt?Number(t)-Number(n):!r.usesBigInt&&e.usesBigInt?BigInt(t)-BigInt(n):lt(t,-n),vo=r=>r==null?!1:Array.isArray(r)||r instanceof ArrayBuffer||ArrayBuffer.isView(r)&&!(r instanceof DataView)||r instanceof Eo?!0:Is(r),Ne=-1,Oo=s.z.string().transform(r=>new Uint8Array(atob(r).split("").map(e=>e.charCodeAt(0))).buffer),zo=s.z.union([s.z.null(),s.z.undefined()]).transform(()=>new Uint8Array().buffer),ct=class ue{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",Ne),m(this,"_refCount",0),m(this,"_cachedLength"),vo(e)&&(e={data:e});const{dataType:t,timeRange:n,sampleOffset:i=0,glBufferUsage:a="static",alignment:c=0n,key:l=wo()}=e,u=e.data??[];if(u instanceof ue||typeof u=="object"&&"isSynnaxSeries"in u&&u.isSynnaxSeries===!0){const y=u;this.key=y.key,this.dataType=y.dataType,this.sampleOffset=y.sampleOffset,this.gl=y.gl,this._data=y._data,this._timeRange=y._timeRange,this.alignment=y.alignment,this._cachedMin=y._cachedMin,this._cachedMax=y._cachedMax,this.writePos=y.writePos,this._refCount=y._refCount,this._cachedLength=y._cachedLength;return}const h=Is(u),d=Array.isArray(u);if(t!=null)this.dataType=new R(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(d||h){let y=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.");y=u[0]}if(typeof y=="string")this.dataType=R.STRING;else if(typeof y=="number")this.dataType=R.FLOAT64;else if(typeof y=="bigint")this.dataType=R.INT64;else if(typeof y=="boolean")this.dataType=R.BOOLEAN;else if(y instanceof j||y instanceof Date||y instanceof j)this.dataType=R.TIMESTAMP;else if(typeof y=="object")this.dataType=R.JSON;else throw new Error(`cannot infer data type of ${typeof y} when constructing a Series from a JS array`)}else this.dataType=new R(u)}if(!d&&!h)this._data=u;else{let y=h?[u]:u;const P=y[0];(P instanceof j||P instanceof Date||P instanceof L)&&(y=y.map(D=>new j(D).valueOf())),this.dataType.equals(R.STRING)?(this._cachedLength=y.length,this._data=new TextEncoder().encode(y.join(`
|
|
4
4
|
`)+`
|
|
5
|
-
`)):this.dataType.equals(R.JSON)?(this._cachedLength=
|
|
5
|
+
`)):this.dataType.equals(R.JSON)?(this._cachedLength=y.length,this._data=new TextEncoder().encode(y.map(D=>Vt.encodeString(D)).join(`
|
|
6
6
|
`)+`
|
|
7
|
-
`)):this._data=new this.dataType.Array(
|
|
7
|
+
`)):this._data=new this.dataType.Array(y).buffer}this.key=l,this.alignment=c,this.sampleOffset=i??0,this._timeRange=n,this.gl={control:null,buffer:null,prevBuffer:0,bufferUsage:a}}static alloc({capacity:e,dataType:t,...n}){if(e===0)throw new Error("[Series] - cannot allocate an array of length 0");const i=new new R(t).Array(e),a=new ue({data:i.buffer,dataType:t,...n});return a.writePos=0,a}static generateTimestamps(e,t,n){const i=n.spanRange(t.span(e)),a=new BigInt64Array(e);for(let c=0;c<e;c++)a[c]=BigInt(n.add(t.span(c)).valueOf());return new ue({data:a,dataType:R.TIMESTAMP,timeRange:i})}get refCount(){return this._refCount}static fromStrings(e,t){const n=new TextEncoder().encode(e.join(`
|
|
8
8
|
`)+`
|
|
9
9
|
`);return new ue({data:n,dataType:R.STRING,timeRange:t})}static fromJSON(e,t){const n=new TextEncoder().encode(e.map(i=>Vt.encodeString(i)).join(`
|
|
10
10
|
`)+`
|
|
11
11
|
`);return new ue({data:n,dataType:R.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");if(this.writePos===Ne)return 0;const t=this.capacity-this.writePos,n=t<e.length?e.slice(0,t):e;return this.underlyingData.set(n.data,this.writePos),this.maybeRecomputeMinMax(n),this._cachedLength=void 0,this.writePos+=n.length,n.length}get buffer(){return this._data}get underlyingData(){return new this.dataType.Array(this._data)}get data(){return this.writePos===Ne?this.underlyingData:new this.dataType.Array(this._data,0,this.writePos)}toStrings(){if(!this.dataType.matches(R.STRING,R.UUID))throw new Error("cannot convert non-string series to strings");return new TextDecoder().decode(this.buffer).split(`
|
|
12
12
|
`).slice(0,-1)}toUUIDs(){if(!this.dataType.equals(R.UUID))throw new Error("cannot convert non-uuid series to uuids");const e=R.UUID.density.valueOf(),t=Array(this.length);for(let n=0;n<this.length;n++){const i=this.buffer.slice(n*e,(n+1)*e),a=Array.from(new Uint8Array(i),c=>c.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(R.JSON))throw new Error("cannot convert non-string series to strings");return new TextDecoder().decode(this.buffer).split(`
|
|
13
|
-
`).slice(0,-1).map(t=>e.parse(Vt.decodeString(t)))}get timeRange(){if(this._timeRange==null)throw new Error("time range not set on series");return this._timeRange}get byteCapacity(){return new Ns(this.buffer.byteLength)}get capacity(){return this.dataType.density.length(this.byteCapacity)}get byteLength(){return this.writePos===Ne?this.byteCapacity:this.dataType.density.size(this.writePos)}get length(){return this._cachedLength!=null?this._cachedLength:this.dataType.isVariable?this.calculateCachedLength():this.writePos===Ne?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;return this.data.forEach(t=>{t===10&&e++}),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]=To(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(R.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==null&&(this._cachedMax=this.calcRawMax()),lt(this._cachedMax,this.sampleOffset))}calcRawMin(){if(this.length===0)return 1/0;if(this.dataType.equals(R.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==null&&(this._cachedMin=this.calcRawMin()),lt(this._cachedMin,this.sampleOffset))}get bounds(){return bt(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 lt(this.max,-this.min)}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 lt(n,this.sampleOffset)}atVariable(e,t){e<0&&(e=this.length+e);let n=0,i=0;for(let c=0;c<this.data.length;c++)if(this.data[c]===10){if(e===0){i=c;break}n=c+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(R.STRING)?new TextDecoder().decode(a):gs(JSON.parse(new TextDecoder().decode(a)))}binarySearch(e){let t=0,n=this.length-1;const i=lo(e);for(;t<=n;){const a=Math.floor((t+n)/2),c=i(this.at(a,!0),e);if(c===0)return a;c<0?t=a+1:n=a-1}return t}updateGLBuffer(e){if(this.gl.control=e,!this.dataType.equals(R.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!==Ne){i===0&&e.bufferData(e.ARRAY_BUFFER,this.byteCapacity.valueOf(),e.STATIC_DRAW);const a=this.dataType.density.size(i).valueOf(),c=this.underlyingData.slice(this.gl.prevBuffer,this.writePos);e.bufferSubData(e.ARRAY_BUFFER,a,c.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=Ne}as(e){if(e==="string"){if(!this.dataType.equals(R.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(R.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:this.alignmentBounds,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 bt(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 So(this);return this.dataType.equals(R.JSON)?new No(e):e}return new Io(this)}slice(e,t){if(e<=0&&(t==null||t>=this.length))return this;const n=this.data.slice(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)})}reAlign(e){return new ue({data:this.buffer,dataType:this.dataType,timeRange:ln.ZERO,sampleOffset:this.sampleOffset,glBufferUsage:"static",alignment:e})}};m(ct,"crudeZ",s.z.object({timeRange:ln.z.optional(),dataType:R.z,alignment:yo.optional(),data:s.z.union([Oo,zo,s.z.instanceof(ArrayBuffer)]),glBufferUsage:bo.optional().default("static").optional()})),m(ct,"z",ct.crudeZ.transform(r=>new ct(r)));let Eo=ct;class So{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]!==10;)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 xn,Cn;class No{constructor(e){m(this,"wrapped"),m(this,xn,"JSONSeriesIterator"),this.wrapped=e}next(){const e=this.wrapped.next();return e.done===!0?{done:!0,value:void 0}:{done:!1,value:Vt.decodeString(e.value)}}[(Cn=Symbol.iterator,xn=Symbol.toStringTag,Cn)](){return this}}var Pn,Dn;class Io{constructor(e){m(this,"series"),m(this,"index"),m(this,Pn,"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)}}[(Dn=Symbol.iterator,Pn=Symbol.toStringTag,Dn)](){return this}}const lt=(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);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 ks=()=>typeof process<"u"&&process.versions!=null&&process.versions.node!=null?"node":typeof window>"u"||window.document===void 0?"webworker":"browser",ko=ks(),As=["MacOS","Windows","Linux","Docker"],Ao=s.z.enum(As);let Cr;const $o=()=>{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"},Ro=(r={})=>{const{force:e,default:t}=r;return e??Cr??(Cr=$o(),Cr??t)},$s=Object.freeze(Object.defineProperty({__proto__:null,OPERATING_SYSTEMS:As,RUNTIME:ko,detect:ks,getOS:Ro,osZ:Ao},Symbol.toStringTag,{value:"Module"}));var xo=Object.defineProperty,Co=(r,e,t)=>e in r?xo(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,ut=(r,e,t)=>Co(r,typeof e!="symbol"?e+"":e,t);const Po=(...r)=>r.map(Rs).join(""),Rs=r=>(r.endsWith("/")||(r+="/"),r.startsWith("/")&&(r=r.slice(1)),r),Do=r=>r.endsWith("/")?r.slice(0,-1):r,jo=(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("&"),Jr=class Hr{constructor({host:e,port:t,protocol:n="",pathPrefix:i=""}){ut(this,"protocol"),ut(this,"host"),ut(this,"port"),ut(this,"path"),this.protocol=n,this.host=e,this.port=t,this.path=Rs(i)}replace(e){return new Hr({host:e.host??this.host,port:e.port??this.port,protocol:e.protocol??this.protocol,pathPrefix:e.pathPrefix??this.path})}child(e){return new Hr({...this,pathPrefix:Po(this.path,e)})}toString(){return Do(`${this.protocol}://${this.host}:${this.port}/${this.path}`)}};ut(Jr,"UNKNOWN",new Jr({host:"unknown",port:0}));let Mo=Jr;var Bo=Object.defineProperty,Uo=(r,e,t)=>e in r?Bo(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,Ht=(r,e,t)=>Uo(r,typeof e!="symbol"?e+"":e,t);const je=class extends Number{};Ht(je,"Absolute",255),Ht(je,"Default",1),Ht(je,"z",s.z.union([s.z.instanceof(je),s.z.number().int().min(0).max(255).transform(r=>new je(r)),s.z.instanceof(Number).transform(r=>new je(r))]));s.z.object({name:s.z.string(),key:s.z.string()});const xs=class ht extends Error{constructor(){super(ht.MESSAGE)}matches(e){return typeof e=="string"?e.includes(ht.MESSAGE):e instanceof ht||e.message.includes(ht.MESSAGE)}};Ht(xs,"MESSAGE","canceled");let Zo=xs;new Zo;s.z.string().regex(/^\d+\.\d+\.\d+$/);const H=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 ne extends Error{constructor(e){super(e),k(this,"discriminator","FreighterError"),k(this,"type","")}}const Lo=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},jn="unknown",Mn="nil",_o="freighter",Rt=s.z.object({type:s.z.string(),data:s.z.string()});class Yo{constructor(){k(this,"providers",[])}register(e){this.providers.push(e)}encode(e){if(e==null)return{type:Mn,data:""};if(Lo(e))for(const t of this.providers){const n=t.encode(e);if(n!=null)return n}return{type:jn,data:JSON.stringify(e)}}decode(e){if(e==null||e.type===Mn)return null;if(e.type===jn)return new Bn(e.data);for(const t of this.providers){const n=t.decode(e);if(n!=null)return n}return new Bn(e.data)}}const Cs=new Yo,Ps=({encode:r,decode:e})=>Cs.register({encode:r,decode:e}),un=r=>Cs.decode(r);class Bn extends ne{constructor(e){super(e),k(this,"type","unknown")}}const fr="freighter.",Xt=class Ds extends ne{constructor(){super("EOF"),k(this,"type",Ds.TYPE)}};k(Xt,"TYPE",fr+"eof"),k(Xt,"matches",H(Xt.TYPE));let Oe=Xt;const Qt=class js extends ne{constructor(){super("StreamClosed"),k(this,"type",js.TYPE)}};k(Qt,"TYPE",fr+"stream_closed"),k(Qt,"matches",H(Qt.TYPE));let Qe=Qt;const er=class Ms extends ne{constructor(e={}){const{message:t="Unreachable",url:n=Mo.UNKNOWN}=e;super(t),k(this,"type",Ms.TYPE),k(this,"url"),this.url=n}};k(er,"TYPE",fr+"unreachable"),k(er,"matches",H(er.TYPE));let Re=er;const qo=r=>{if(!r.type.startsWith(_o))return null;if(Oe.matches(r))return{type:Oe.TYPE,data:"EOF"};if(Qe.matches(r))return{type:Qe.TYPE,data:"StreamClosed"};if(Re.matches(r))return{type:Re.TYPE,data:"Unreachable"};throw new Error(`Unknown error type: ${r.type}: ${r.message}`)},Wo=r=>{if(!r.type.startsWith(fr))return null;switch(r.type){case Oe.TYPE:return new Oe;case Qe.TYPE:return new Qe;case Re.TYPE:return new Re;default:throw new Error(`Unknown error type: ${r.data}`)}};Ps({encode:qo,decode:Wo});let Bs=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 c=this.middleware[n];return n++,await c(a,i)};return await i(e)}};const Us="Content-Type",Un=r=>{if($s.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 Go extends Bs{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=Un(this.endpoint.protocol),new Proxy(this,{get:(i,a,c)=>a==="endpoint"?this.endpoint:Reflect.get(i,a,c)})}get headers(){return{[Us]:this.encoder.contentType}}async send(e,t,n,i){t=n==null?void 0:n.parse(t);let a=null;const c=this.endpoint.child(e),l={};l.method="POST",l.body=this.encoder.encode(t??{});const[,u]=await this.executeMiddleware({target:c.toString(),protocol:this.endpoint.protocol,params:{},role:"client"},async y=>{const d={...y,params:{}};l.headers={...this.headers,...y.params};let h;try{h=await Un(y.protocol)(y.target,l)}catch(P){let Q=P;return Q.message==="Load failed"&&(Q=new Re({url:c})),[d,Q]}const D=await h.arrayBuffer();if(h!=null&&h.ok)return i!=null&&(a=this.encoder.decode(D,i)),[d,null];try{if(h.status!==400)return[d,new Error(h.statusText)];const P=this.encoder.decode(D,Rt),Q=un(P);return[d,Q]}catch(P){return[d,new Error(`[freighter] - failed to decode error: ${h.statusText}: ${P.message}`)]}});return[a,u]}}const w=async(r,e,t,n,i)=>{const[a,c]=await r.send(e,t,n,i);if(c!=null)throw c;return a},Fo=()=>$s.RUNTIME!=="node"?r=>new WebSocket(r):r=>new(require("ws")).WebSocket(r,{rejectUnauthorized:!1}),Vo=s.z.object({type:s.z.union([s.z.literal("data"),s.z.literal("close")]),payload:s.z.unknown().optional(),error:s.z.optional(Rt)});class Ko{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()}send(e){if(this.serverClosed!=null)return new Oe;if(this.sendClosed)throw new Qe;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=un(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,Vo)),this.ws.onclose=e=>this.addMessage({type:"close",error:{type:ec(e)?Oe.TYPE:Qe.TYPE,data:""}})}}const Jo="freighterctx",Ho=1e3,Xo=1001,Qo=[Ho,Xo],ec=r=>Qo.includes(r.code),Zs=class Ls extends Bs{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=Fo();let a;const[,c]=await this.executeMiddleware({target:e,protocol:"websocket",params:{},role:"client"},async l=>{const u=i(this.buildURL(e,l)),y={...l,params:{}};u.binaryType=Ls.MESSAGE_TYPE;const d=await this.wrapSocket(u,t,n);return d instanceof Error?[y,d]:(a=d,[y,null])});if(c!=null)throw c;return a}buildURL(e,t){const n=jo({[Us]:this.encoder.contentType,...t.params},Jo);return this.baseUrl.child(e).toString()+n}async wrapSocket(e,t,n){return await new Promise(i=>{e.onopen=()=>{i(new Ko(e,this.encoder,t,n))},e.onerror=a=>{const c=a;i(new Error(c.message))}})}};k(Zs,"MESSAGE_TYPE","arraybuffer");let tc=Zs;const or=s.z.union([s.z.literal("all"),s.z.literal("create"),s.z.literal("delete"),s.z.literal("retrieve"),s.z.literal("update")]),rc="all",nc="create",sc="delete",ic="retrieve",ac="update",oc=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:e[0].toLowerCase()+e.slice(1)},_s=r=>{const e=(t,n=Xr)=>{if(typeof t=="string")return r(t);if(Array.isArray(t))return t.map(c=>e(c,n));if(!Pr(t))return t;n=uc(n);const i={},a=t;return Object.keys(a).forEach(c=>{let l=a[c];const u=r(c);n.recursive&&(Pr(l)?Ln(l,n.keepTypesOnRecursion)||(l=e(l,n)):n.recursiveInArray&&Zn(l)&&(l=[...l].map(y=>{let d=y;return Pr(y)?Ln(d,n.keepTypesOnRecursion)||(d=e(y,n)):Zn(y)&&(d=e({key:y},n).key),d}))),i[u]=l}),i};return e},Ys=_s(oc),cc=r=>r.replace(/([a-z0-9])([A-Z])/g,(e,t,n)=>`${t}_${n.toLowerCase()}`),lc=_s(cc),Xr={recursive:!0,recursiveInArray:!0,keepTypesOnRecursion:[Number,String,Uint8Array]},uc=(r=Xr)=>(r.recursive==null?r=Xr:r.recursiveInArray==null&&(r.recursiveInArray=!1),r),Zn=r=>r!=null&&Array.isArray(r),Pr=r=>r!=null&&typeof r=="object"&&!Array.isArray(r),Ln=(r,e)=>(e||[]).some(t=>r instanceof t),hn=r=>r!=null&&typeof r=="object"&&!Array.isArray(r);var hc=Object.defineProperty,yc=(r,e,t)=>e in r?hc(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,Tt=(r,e,t)=>yc(r,typeof e!="symbol"?e+"":e,t);let qs=class{constructor(){Tt(this,"contentType","application/json"),Tt(this,"decoder"),Tt(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=Ys(n);return t!=null?t.parse(i):i}encodeString(e){const t=lc(e);return JSON.stringify(t,(n,i)=>ArrayBuffer.isView(i)?Array.from(i):hn(i)&&"encode_value"in i?typeof i.value=="bigint"?i.value.toString():i.value:typeof i=="bigint"?i.toString():i)}static registerCustomType(){}},Ws=class{constructor(){Tt(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||!hn(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(c=>JSON.stringify(i[c]??""));n.push(a.join(","))}),n.join(`
|
|
13
|
+
`).slice(0,-1).map(t=>e.parse(Vt.decodeString(t)))}get timeRange(){if(this._timeRange==null)throw new Error("time range not set on series");return this._timeRange}get byteCapacity(){return new Ns(this.buffer.byteLength)}get capacity(){return this.dataType.density.length(this.byteCapacity)}get byteLength(){return this.writePos===Ne?this.byteCapacity:this.dataType.density.size(this.writePos)}get length(){return this._cachedLength!=null?this._cachedLength:this.dataType.isVariable?this.calculateCachedLength():this.writePos===Ne?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;return this.data.forEach(t=>{t===10&&e++}),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]=To(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(R.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==null&&(this._cachedMax=this.calcRawMax()),lt(this._cachedMax,this.sampleOffset))}calcRawMin(){if(this.length===0)return 1/0;if(this.dataType.equals(R.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==null&&(this._cachedMin=this.calcRawMin()),lt(this._cachedMin,this.sampleOffset))}get bounds(){return bt(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 lt(this.max,-this.min)}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 lt(n,this.sampleOffset)}atVariable(e,t){e<0&&(e=this.length+e);let n=0,i=0;for(let c=0;c<this.data.length;c++)if(this.data[c]===10){if(e===0){i=c;break}n=c+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(R.STRING)?new TextDecoder().decode(a):gs(JSON.parse(new TextDecoder().decode(a)))}binarySearch(e){let t=0,n=this.length-1;const i=lo(e);for(;t<=n;){const a=Math.floor((t+n)/2),c=i(this.at(a,!0),e);if(c===0)return a;c<0?t=a+1:n=a-1}return t}updateGLBuffer(e){if(this.gl.control=e,!this.dataType.equals(R.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!==Ne){i===0&&e.bufferData(e.ARRAY_BUFFER,this.byteCapacity.valueOf(),e.STATIC_DRAW);const a=this.dataType.density.size(i).valueOf(),c=this.underlyingData.slice(this.gl.prevBuffer,this.writePos);e.bufferSubData(e.ARRAY_BUFFER,a,c.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=Ne}as(e){if(e==="string"){if(!this.dataType.equals(R.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(R.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:this.alignmentBounds,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 bt(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 So(this);return this.dataType.equals(R.JSON)?new No(e):e}return new Io(this)}slice(e,t){if(e<=0&&(t==null||t>=this.length))return this;const n=this.data.slice(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)})}reAlign(e){return new ue({data:this.buffer,dataType:this.dataType,timeRange:ln.ZERO,sampleOffset:this.sampleOffset,glBufferUsage:"static",alignment:e})}};m(ct,"crudeZ",s.z.object({timeRange:ln.z.optional(),dataType:R.z,alignment:yo.optional(),data:s.z.union([Oo,zo,s.z.instanceof(ArrayBuffer)]),glBufferUsage:bo.optional().default("static").optional()})),m(ct,"z",ct.crudeZ.transform(r=>new ct(r)));let Eo=ct;class So{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]!==10;)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 xn,Cn;class No{constructor(e){m(this,"wrapped"),m(this,xn,"JSONSeriesIterator"),this.wrapped=e}next(){const e=this.wrapped.next();return e.done===!0?{done:!0,value:void 0}:{done:!1,value:Vt.decodeString(e.value)}}[(Cn=Symbol.iterator,xn=Symbol.toStringTag,Cn)](){return this}}var Pn,Dn;class Io{constructor(e){m(this,"series"),m(this,"index"),m(this,Pn,"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)}}[(Dn=Symbol.iterator,Pn=Symbol.toStringTag,Dn)](){return this}}const lt=(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);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 ks=()=>typeof process<"u"&&process.versions!=null&&process.versions.node!=null?"node":typeof window>"u"||window.document===void 0?"webworker":"browser",ko=ks(),As=["MacOS","Windows","Linux","Docker"],Ao=s.z.enum(As);let Cr;const $o=()=>{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"},Ro=(r={})=>{const{force:e,default:t}=r;return e??Cr??(Cr=$o(),Cr??t)},$s=Object.freeze(Object.defineProperty({__proto__:null,OPERATING_SYSTEMS:As,RUNTIME:ko,detect:ks,getOS:Ro,osZ:Ao},Symbol.toStringTag,{value:"Module"}));var xo=Object.defineProperty,Co=(r,e,t)=>e in r?xo(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,ut=(r,e,t)=>Co(r,typeof e!="symbol"?e+"":e,t);const Po=(...r)=>r.map(Rs).join(""),Rs=r=>(r.endsWith("/")||(r+="/"),r.startsWith("/")&&(r=r.slice(1)),r),Do=r=>r.endsWith("/")?r.slice(0,-1):r,jo=(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("&"),Jr=class Hr{constructor({host:e,port:t,protocol:n="",pathPrefix:i=""}){ut(this,"protocol"),ut(this,"host"),ut(this,"port"),ut(this,"path"),this.protocol=n,this.host=e,this.port=t,this.path=Rs(i)}replace(e){return new Hr({host:e.host??this.host,port:e.port??this.port,protocol:e.protocol??this.protocol,pathPrefix:e.pathPrefix??this.path})}child(e){return new Hr({...this,pathPrefix:Po(this.path,e)})}toString(){return Do(`${this.protocol}://${this.host}:${this.port}/${this.path}`)}};ut(Jr,"UNKNOWN",new Jr({host:"unknown",port:0}));let Mo=Jr;var Bo=Object.defineProperty,Uo=(r,e,t)=>e in r?Bo(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,Ht=(r,e,t)=>Uo(r,typeof e!="symbol"?e+"":e,t);const je=class extends Number{};Ht(je,"Absolute",255),Ht(je,"Default",1),Ht(je,"z",s.z.union([s.z.instanceof(je),s.z.number().int().min(0).max(255).transform(r=>new je(r)),s.z.instanceof(Number).transform(r=>new je(r))]));s.z.object({name:s.z.string(),key:s.z.string()});const xs=class ht extends Error{constructor(){super(ht.MESSAGE)}matches(e){return typeof e=="string"?e.includes(ht.MESSAGE):e instanceof ht||e.message.includes(ht.MESSAGE)}};Ht(xs,"MESSAGE","canceled");let Zo=xs;new Zo;s.z.string().regex(/^\d+\.\d+\.\d+$/);const H=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 ne extends Error{constructor(e){super(e),k(this,"discriminator","FreighterError"),k(this,"type","")}}const Lo=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},jn="unknown",Mn="nil",_o="freighter",Rt=s.z.object({type:s.z.string(),data:s.z.string()});class Yo{constructor(){k(this,"providers",[])}register(e){this.providers.push(e)}encode(e){if(e==null)return{type:Mn,data:""};if(Lo(e))for(const t of this.providers){const n=t.encode(e);if(n!=null)return n}return{type:jn,data:JSON.stringify(e)}}decode(e){if(e==null||e.type===Mn)return null;if(e.type===jn)return new Bn(e.data);for(const t of this.providers){const n=t.decode(e);if(n!=null)return n}return new Bn(e.data)}}const Cs=new Yo,Ps=({encode:r,decode:e})=>Cs.register({encode:r,decode:e}),un=r=>Cs.decode(r);class Bn extends ne{constructor(e){super(e),k(this,"type","unknown")}}const fr="freighter.",Xt=class Ds extends ne{constructor(){super("EOF"),k(this,"type",Ds.TYPE)}};k(Xt,"TYPE",fr+"eof"),k(Xt,"matches",H(Xt.TYPE));let Oe=Xt;const Qt=class js extends ne{constructor(){super("StreamClosed"),k(this,"type",js.TYPE)}};k(Qt,"TYPE",fr+"stream_closed"),k(Qt,"matches",H(Qt.TYPE));let Qe=Qt;const er=class Ms extends ne{constructor(e={}){const{message:t="Unreachable",url:n=Mo.UNKNOWN}=e;super(t),k(this,"type",Ms.TYPE),k(this,"url"),this.url=n}};k(er,"TYPE",fr+"unreachable"),k(er,"matches",H(er.TYPE));let Re=er;const qo=r=>{if(!r.type.startsWith(_o))return null;if(Oe.matches(r))return{type:Oe.TYPE,data:"EOF"};if(Qe.matches(r))return{type:Qe.TYPE,data:"StreamClosed"};if(Re.matches(r))return{type:Re.TYPE,data:"Unreachable"};throw new Error(`Unknown error type: ${r.type}: ${r.message}`)},Wo=r=>{if(!r.type.startsWith(fr))return null;switch(r.type){case Oe.TYPE:return new Oe;case Qe.TYPE:return new Qe;case Re.TYPE:return new Re;default:throw new Error(`Unknown error type: ${r.data}`)}};Ps({encode:qo,decode:Wo});let Bs=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 c=this.middleware[n];return n++,await c(a,i)};return await i(e)}};const Us="Content-Type",Un=r=>{if($s.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 Go extends Bs{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=Un(this.endpoint.protocol),new Proxy(this,{get:(i,a,c)=>a==="endpoint"?this.endpoint:Reflect.get(i,a,c)})}get headers(){return{[Us]:this.encoder.contentType}}async send(e,t,n,i){t=n==null?void 0:n.parse(t);let a=null;const c=this.endpoint.child(e),l={};l.method="POST",l.body=this.encoder.encode(t??{});const[,u]=await this.executeMiddleware({target:c.toString(),protocol:this.endpoint.protocol,params:{},role:"client"},async h=>{const d={...h,params:{}};l.headers={...this.headers,...h.params};let y;try{y=await Un(h.protocol)(h.target,l)}catch(D){let Q=D;return Q.message==="Load failed"&&(Q=new Re({url:c})),[d,Q]}const P=await y.arrayBuffer();if(y!=null&&y.ok)return i!=null&&(a=this.encoder.decode(P,i)),[d,null];try{if(y.status!==400)return[d,new Error(y.statusText)];const D=this.encoder.decode(P,Rt),Q=un(D);return[d,Q]}catch(D){return[d,new Error(`[freighter] - failed to decode error: ${y.statusText}: ${D.message}`)]}});return[a,u]}}const w=async(r,e,t,n,i)=>{const[a,c]=await r.send(e,t,n,i);if(c!=null)throw c;return a},Fo=()=>$s.RUNTIME!=="node"?r=>new WebSocket(r):r=>new(require("ws")).WebSocket(r,{rejectUnauthorized:!1}),Vo=s.z.object({type:s.z.union([s.z.literal("data"),s.z.literal("close")]),payload:s.z.unknown().optional(),error:s.z.optional(Rt)});class Ko{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()}send(e){if(this.serverClosed!=null)return new Oe;if(this.sendClosed)throw new Qe;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=un(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,Vo)),this.ws.onclose=e=>this.addMessage({type:"close",error:{type:ec(e)?Oe.TYPE:Qe.TYPE,data:""}})}}const Jo="freighterctx",Ho=1e3,Xo=1001,Qo=[Ho,Xo],ec=r=>Qo.includes(r.code),Zs=class Ls extends Bs{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=Fo();let a;const[,c]=await this.executeMiddleware({target:e,protocol:"websocket",params:{},role:"client"},async l=>{const u=i(this.buildURL(e,l)),h={...l,params:{}};u.binaryType=Ls.MESSAGE_TYPE;const d=await this.wrapSocket(u,t,n);return d instanceof Error?[h,d]:(a=d,[h,null])});if(c!=null)throw c;return a}buildURL(e,t){const n=jo({[Us]:this.encoder.contentType,...t.params},Jo);return this.baseUrl.child(e).toString()+n}async wrapSocket(e,t,n){return await new Promise(i=>{e.onopen=()=>{i(new Ko(e,this.encoder,t,n))},e.onerror=a=>{const c=a;i(new Error(c.message))}})}};k(Zs,"MESSAGE_TYPE","arraybuffer");let tc=Zs;const or=s.z.union([s.z.literal("all"),s.z.literal("create"),s.z.literal("delete"),s.z.literal("retrieve"),s.z.literal("update")]),rc="all",nc="create",sc="delete",ic="retrieve",ac="update",oc=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:e[0].toLowerCase()+e.slice(1)},_s=r=>{const e=(t,n=Xr)=>{if(typeof t=="string")return r(t);if(Array.isArray(t))return t.map(c=>e(c,n));if(!Pr(t))return t;n=uc(n);const i={},a=t;return Object.keys(a).forEach(c=>{let l=a[c];const u=r(c);n.recursive&&(Pr(l)?Ln(l,n.keepTypesOnRecursion)||(l=e(l,n)):n.recursiveInArray&&Zn(l)&&(l=[...l].map(h=>{let d=h;return Pr(h)?Ln(d,n.keepTypesOnRecursion)||(d=e(h,n)):Zn(h)&&(d=e({key:h},n).key),d}))),i[u]=l}),i};return e},Ys=_s(oc),cc=r=>r.replace(/([a-z0-9])([A-Z])/g,(e,t,n)=>`${t}_${n.toLowerCase()}`),lc=_s(cc),Xr={recursive:!0,recursiveInArray:!0,keepTypesOnRecursion:[Number,String,Uint8Array]},uc=(r=Xr)=>(r.recursive==null?r=Xr:r.recursiveInArray==null&&(r.recursiveInArray=!1),r),Zn=r=>r!=null&&Array.isArray(r),Pr=r=>r!=null&&typeof r=="object"&&!Array.isArray(r),Ln=(r,e)=>(e||[]).some(t=>r instanceof t),hn=r=>r!=null&&typeof r=="object"&&!Array.isArray(r);var hc=Object.defineProperty,yc=(r,e,t)=>e in r?hc(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,Tt=(r,e,t)=>yc(r,typeof e!="symbol"?e+"":e,t);let qs=class{constructor(){Tt(this,"contentType","application/json"),Tt(this,"decoder"),Tt(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=Ys(n);return t!=null?t.parse(i):i}encodeString(e){const t=lc(e);return JSON.stringify(t,(n,i)=>ArrayBuffer.isView(i)?Array.from(i):hn(i)&&"encode_value"in i?typeof i.value=="bigint"?i.value.toString():i.value:typeof i=="bigint"?i.toString():i)}static registerCustomType(){}},Ws=class{constructor(){Tt(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||!hn(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(c=>JSON.stringify(i[c]??""));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()),c={};return a.forEach(l=>{c[l]=[]}),i.forEach(l=>{const u=l.split(",").map(y=>y.trim());a.forEach((y,d)=>{const h=this.parseValue(u[d]);h!=null&&c[y].push(h)})}),t!=null?t.parse(c):c}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(){}},Gs=class{constructor(){Tt(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 Xe=new qs,dc=new Ws,fc=new Gs,pc=[Xe],nt=Object.freeze(Object.defineProperty({__proto__:null,CSVCodec:Ws,CSV_CODEC:dc,ENCODERS:pc,JSONCodec:qs,JSON_CODEC:Xe,TEXT_CODEC:fc,TextCodec:Gs},Symbol.toStringTag,{value:"Module"})),pr=s.z.tuple([s.z.number(),s.z.number()]);s.z.tuple([s.z.bigint(),s.z.bigint()]);const Fs=s.z.object({width:s.z.number(),height:s.z.number()}),gc=s.z.object({signedWidth:s.z.number(),signedHeight:s.z.number()}),mc=["width","height"];s.z.enum(mc);const wc=["start","center","end"],bc=["signedWidth","signedHeight"];s.z.enum(bc);const cr=s.z.object({x:s.z.number(),y:s.z.number()}),Tc=s.z.object({clientX:s.z.number(),clientY:s.z.number()}),vc=["x","y"],Vs=s.z.enum(vc),Ks=["top","right","bottom","left"];s.z.enum(Ks);const Oc=["left","right"],Js=s.z.enum(Oc),zc=["top","bottom"],Hs=s.z.enum(zc),Xs=["center"],_n=s.z.enum(Xs),Ec=[...Ks,...Xs],Qs=s.z.enum(Ec);s.z.enum(wc);const Sc=["first","last"];s.z.enum(Sc);const Nc=s.z.object({lower:s.z.number(),upper:s.z.number()}),Ic=s.z.object({lower:s.z.bigint(),upper:s.z.bigint()});s.z.union([Nc,pr]);s.z.union([Ic,pr]);s.z.union([Vs,Qs]);s.z.union([Vs,Qs,s.z.instanceof(String)]);const vt=(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 Yn(r);return Yn(t)},Yn=r=>r.lower>r.upper?{lower:r.upper,upper:r.lower}:r;s.z.object({x:Js.or(_n),y:Hs.or(_n)});const kc=s.z.object({x:Js,y:Hs}),Ac=Object.freeze({x:"left",y:"top"}),$c=(r,e)=>r.x===e.x&&r.y===e.y,qn=s.z.union([s.z.number(),cr,pr,Fs,gc,Tc]),Rc=(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}},Wn=Object.freeze({x:0,y:0}),Gt=s.z.union([s.z.number(),s.z.string()]);s.z.object({top:Gt,left:Gt,width:Gt,height:Gt});s.z.object({left:s.z.number(),top:s.z.number(),right:s.z.number(),bottom:s.z.number()});s.z.object({one:cr,two:cr,root:kc});const yn=(r,e,t=0,n=0,i)=>{const a={one:{...Wn},two:{...Wn},root:i??Ac};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))},Dr=r=>{const e=yn(r);return{lower:e.one.x,upper:e.two.x}},jr=r=>{const e=yn(r);return{lower:e.one.y,upper:e.two.y}},xc=r=>typeof r!="object"||r==null?!1:"one"in r&&"two"in r&&"root"in r;var Cc=Object.defineProperty,Pc=(r,e,t)=>e in r?Cc(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,fe=(r,e,t)=>Pc(r,typeof e!="symbol"?e+"":e,t);const Dc=(r,e,t)=>e!==void 0&&r<e?e:t!==void 0&&r>t?t:r;s.z.object({offset:qn,scale:qn});const jc=r=>(e,t,n,i)=>t==="dimension"?[e,n]:[e,i?n-r:n+r],Mc=r=>(e,t,n,i)=>[e,i?n/r:n*r],Bc=r=>(e,t,n)=>{if(e===null)return[r,n];const{lower:i,upper:a}=e,{lower:c,upper:l}=r,u=a-i,y=l-c;if(t==="dimension")return[r,n*(y/u)];const d=(n-i)*(y/u)+c;return[r,d]},Uc=r=>(e,t,n)=>[r,n],Zc=()=>(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)]},Lc=r=>(e,t,n)=>{const{lower:i,upper:a}=r;return n=Dc(n,i,a),[e,n]},Qr=class yt{constructor(){fe(this,"ops",[]),fe(this,"currBounds",null),fe(this,"currType",null),fe(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=jc(e);return n.type="translate",t.ops.push(n),t}magnify(e){const t=this.new(),n=Mc(e);return n.type="magnify",t.ops.push(n),t}scale(e,t){const n=vt(e,t),i=this.new(),a=Bc(n);return a.type="scale",i.ops.push(a),i}clamp(e,t){const n=vt(e,t),i=this.new(),a=Lc(n);return a.type="clamp",i.ops.push(a),i}reBound(e,t){const n=vt(e,t),i=this.new(),a=Uc(n);return a.type="re-bound",i.ops.push(a),i}invert(){const e=Zc();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(([c,l])=>i>=c&&i<=l))return;const a=e.ops.findIndex((c,l)=>c.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}};fe(Qr,"IDENTITY",new Qr);let Gn=Qr;const Fn=class he{constructor(e=new Gn,t=new Gn,n=null){fe(this,"x"),fe(this,"y"),fe(this,"currRoot"),this.x=e,this.y=t,this.currRoot=n}static translate(e,t){return new he().translate(e,t)}static translateX(e){return new he().translateX(e)}static translateY(e){return new he().translateY(e)}static clamp(e){return new he().clamp(e)}static magnify(e){return new he().magnify(e)}static scale(e){return new he().scale(e)}static reBound(e){return new he().reBound(e)}translate(e,t){const n=Rc(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(xc(e)){const n=this.currRoot;return t.currRoot=e.root,n!=null&&!$c(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(Dr(e)),t.y=t.y.scale(jr(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(Dr(e)),t.y=this.y.reBound(jr(e)),t}clamp(e){const t=this.copy();return t.x=this.x.clamp(Dr(e)),t.y=this.y.clamp(jr(e)),t}copy(){const e=new he;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)}}box(e){return yn(this.pos(e.one),this.pos(e.two),0,0,this.currRoot??e.root)}};fe(Fn,"IDENTITY",new Fn);const Vn=r=>[...new Set(r)],_c=r=>r!=null&&typeof r=="object"&&"toString"in r,Yc=(r,e=!1)=>{const t=_c(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?qc(n):n},qc=r=>(e,t)=>r(t,e),gr=0,Mr=-1,Br=1,Wc=r=>r<gr,Gc=r=>r>gr,Fc=r=>r===gr,Vc=(r,e)=>{let t=null;return e===0?r:(...n)=>{t!==null&&(clearTimeout(t),t=null),t=setTimeout(()=>r(...n),e)}},Kc=s.z.object({signedWidth:s.z.number(),signedHeight:s.z.number()});s.z.union([Fs,Kc,cr,pr]);const Jc=s.z.bigint().or(s.z.string().transform(BigInt));var Hc=Object.defineProperty,Xc=(r,e,t)=>e in r?Hc(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,g=(r,e,t)=>Xc(r,typeof e!="symbol"?e+"":e,t);let Qc=(r,e=21)=>(t=e)=>{let n="",i=t;for(;i--;)n+=r[Math.random()*r.length|0];return n};const el="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",ei=Qc(el,11),tl=Object.freeze(Object.defineProperty({__proto__:null,id:ei},Symbol.toStringTag,{value:"Module"})),rl=s.z.enum(["static","dynamic"]),ti=(r,e)=>{const t=new S(e);if(![E.DAY,E.HOUR,E.MINUTE,E.SECOND,E.MILLISECOND,E.MICROSECOND,E.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 S?new S(n):new E(n)},x=class O{constructor(e,t="UTC"){if(g(this,"value"),g(this,"encodeValue",!0),e==null)this.value=O.now().valueOf();else if(e instanceof Date)this.value=BigInt(e.getTime())*O.MILLISECOND.valueOf();else if(typeof e=="string")this.value=O.parseDateTimeString(e,t).valueOf();else if(Array.isArray(e))this.value=O.parseDate(e);else{let n=BigInt(0);e instanceof Number&&(e=e.valueOf()),t==="local"&&(n=O.utcOffset.valueOf()),typeof e=="number"&&(isFinite(e)?e=Math.trunc(e):(isNaN(e)&&(e=0),e===1/0?e=O.MAX:e=O.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 O(BigInt(i.getTime())*O.MILLISECOND.valueOf()).truncate(O.DAY).valueOf()}encode(){return this.value.toString()}valueOf(){return this.value}static parseTimeString(e,t="UTC"){const[n,i,a]=e.split(":");let c="00",l="00";a!=null&&([c,l]=a.split("."));let u=O.hours(parseInt(n??"00",10)).add(O.minutes(parseInt(i??"00",10))).add(O.seconds(parseInt(c??"00",10))).add(O.milliseconds(parseInt(l??"00",10)));return t==="local"&&(u=u.add(O.utcOffset)),u.valueOf()}static parseDateTimeString(e,t="UTC"){if(!e.includes("/")&&!e.includes("-"))return O.parseTimeString(e,t);const n=new Date(e);return e.includes(":")||n.setUTCHours(0,0,0,0),new O(BigInt(n.getTime())*O.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(O.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 E(BigInt(new Date().getTimezoneOffset())*O.MINUTE.valueOf())}static since(e){return new O().span(e)}date(){return new Date(this.milliseconds())}equals(e){return this.valueOf()===new O(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 O(e).valueOf()}afterEq(e){return this.valueOf()>=new O(e).valueOf()}before(e){return this.valueOf()<new O(e).valueOf()}beforeEq(e){return this.valueOf()<=new O(e).valueOf()}add(e){return new O(this.valueOf()+BigInt(e.valueOf()))}sub(e){return new O(this.valueOf()-BigInt(e.valueOf()))}milliseconds(){return Number(this.valueOf())/Number(O.MILLISECOND.valueOf())}toString(){return this.date().toISOString()}remainder(e){return ti(this,e)}get isToday(){return this.truncate(E.DAY).equals(O.now().truncate(E.DAY))}truncate(e){return this.sub(this.remainder(e))}static now(){return new O(new Date)}static max(...e){let t=O.MIN;for(const n of e){const i=new O(n);i.after(t)&&(t=i)}return t}static min(...e){let t=O.MAX;for(const n of e){const i=new O(n);i.before(t)&&(t=i)}return t}static nanoseconds(e){return new O(e)}static microseconds(e){return O.nanoseconds(e*1e3)}static milliseconds(e){return O.microseconds(e*1e3)}static seconds(e){return O.milliseconds(e*1e3)}static minutes(e){return O.seconds(e*60)}static hours(e){return O.minutes(e*60)}static days(e){return O.hours(e*24)}};g(x,"NANOSECOND",x.nanoseconds(1)),g(x,"MICROSECOND",x.microseconds(1)),g(x,"MILLISECOND",x.milliseconds(1)),g(x,"SECOND",x.seconds(1)),g(x,"MINUTE",x.minutes(1)),g(x,"HOUR",x.hours(1)),g(x,"DAY",x.days(1)),g(x,"MAX",new x((1n<<63n)-1n)),g(x,"MIN",new x(0)),g(x,"ZERO",new x(0)),g(x,"z",s.z.union([s.z.object({value:s.z.bigint()}).transform(r=>new x(r.value)),s.z.string().transform(r=>new x(BigInt(r))),s.z.instanceof(Number).transform(r=>new x(r)),s.z.number().transform(r=>new x(r)),s.z.instanceof(x)]));let S=x;const C=class I{constructor(e){g(this,"value"),g(this,"encodeValue",!0),typeof e=="number"&&(e=Math.trunc(e.valueOf())),this.value=BigInt(e.valueOf())}encode(){return this.value.toString()}valueOf(){return this.value}lessThan(e){return this.valueOf()<new I(e).valueOf()}greaterThan(e){return this.valueOf()>new I(e).valueOf()}lessThanOrEqual(e){return this.valueOf()<=new I(e).valueOf()}greaterThanOrEqual(e){return this.valueOf()>=new I(e).valueOf()}remainder(e){return ti(this,e)}truncate(e){return new I(BigInt(Math.trunc(Number(this.valueOf()/e.valueOf())))*e.valueOf())}toString(){const e=this.truncate(I.DAY),t=this.truncate(I.HOUR),n=this.truncate(I.MINUTE),i=this.truncate(I.SECOND),a=this.truncate(I.MILLISECOND),c=this.truncate(I.MICROSECOND),l=this.truncate(I.NANOSECOND),u=e,y=t.sub(e),d=n.sub(t),h=i.sub(n),D=a.sub(i),P=c.sub(a),Q=l.sub(c);let B="";return u.isZero||(B+=`${u.days}d `),y.isZero||(B+=`${y.hours}h `),d.isZero||(B+=`${d.minutes}m `),h.isZero||(B+=`${h.seconds}s `),D.isZero||(B+=`${D.milliseconds}ms `),P.isZero||(B+=`${P.microseconds}µs `),Q.isZero||(B+=`${Q.nanoseconds}ns`),B.trim()}get days(){return Number(this.valueOf())/Number(I.DAY.valueOf())}get hours(){return Number(this.valueOf())/Number(I.HOUR.valueOf())}get minutes(){return Number(this.valueOf())/Number(I.MINUTE.valueOf())}get seconds(){return Number(this.valueOf())/Number(I.SECOND.valueOf())}get milliseconds(){return Number(this.valueOf())/Number(I.MILLISECOND.valueOf())}get microseconds(){return Number(this.valueOf())/Number(I.MICROSECOND.valueOf())}get nanoseconds(){return Number(this.valueOf())}get isZero(){return this.valueOf()===BigInt(0)}equals(e){return this.valueOf()===new I(e).valueOf()}add(e){return new I(this.valueOf()+new I(e).valueOf())}sub(e){return new I(this.valueOf()-new I(e).valueOf())}static nanoseconds(e=1){return new I(e)}static microseconds(e=1){return I.nanoseconds(e*1e3)}static milliseconds(e=1){return I.microseconds(e*1e3)}static seconds(e=1){return I.milliseconds(e*1e3)}static minutes(e){return I.seconds(e.valueOf()*60)}static hours(e){return I.minutes(e*60)}static days(e){return I.hours(e*24)}};g(C,"NANOSECOND",C.nanoseconds(1)),g(C,"MICROSECOND",C.microseconds(1)),g(C,"MILLISECOND",C.milliseconds(1)),g(C,"SECOND",C.seconds(1)),g(C,"MINUTE",C.minutes(1)),g(C,"HOUR",C.hours(1)),g(C,"DAY",C.days(1)),g(C,"MAX",new C((1n<<63n)-1n)),g(C,"MIN",new C(0)),g(C,"ZERO",new C(0)),g(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 E=C;const dt=class tr extends Number{constructor(e){e instanceof Number?super(e.valueOf()):super(e)}toString(){return`${this.valueOf()} Hz`}equals(e){return this.valueOf()===new tr(e).valueOf()}get period(){return E.seconds(1/this.valueOf())}sampleCount(e){return new E(e).seconds*this.valueOf()}byteCount(e,t){return this.sampleCount(e)*new V(t).valueOf()}span(e){return E.seconds(e/this.valueOf())}byteSpan(e,t){return this.span(e.valueOf()/t.valueOf())}static hz(e){return new tr(e)}static khz(e){return tr.hz(e*1e3)}};g(dt,"z",s.z.union([s.z.number().transform(r=>new dt(r)),s.z.instanceof(Number).transform(r=>new dt(r)),s.z.instanceof(dt)]));let mr=dt;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 Et(e*this.valueOf())}};g(q,"UNKNOWN",new q(0)),g(q,"BIT128",new q(16)),g(q,"BIT64",new q(8)),g(q,"BIT32",new q(4)),g(q,"BIT16",new q(2)),g(q,"BIT8",new q(1)),g(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 V=q;const ae=class rr{constructor(e,t){g(this,"start"),g(this,"end"),typeof e=="object"&&"start"in e?(this.start=new S(e.start),this.end=new S(e.end)):(this.start=new S(e),this.end=new S(t))}get span(){return new E(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 rr(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=E.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=S.max(n.start,e.start),a=S.min(n.end,e.end);return a.before(i)?!1:new E(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 rr?this.contains(e.start)&&this.contains(e.end):this.start.beforeEq(e)&&this.end.after(e)}boundBy(e){const t=new rr(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}};g(ae,"MAX",new ae(S.MIN,S.MAX)),g(ae,"MIN",new ae(S.MAX,S.MIN)),g(ae,"ZERO",new ae(S.ZERO,S.ZERO)),g(ae,"z",s.z.union([s.z.object({start:S.z,end:S.z}).transform(r=>new ae(r.start,r.end)),s.z.instanceof(ae)]));let W=ae;const p=class oe extends String{constructor(e){if(e instanceof oe||typeof e=="string"||typeof e.valueOf()=="string"){super(e.valueOf());return}else{const t=oe.ARRAY_CONSTRUCTOR_DATA_TYPES.get(e.constructor.name);if(t!=null){super(t.valueOf());return}}throw super(oe.UNKNOWN.valueOf()),new Error(`unable to find data type for ${e.toString()}`)}get Array(){const e=oe.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(oe.JSON)||this.equals(oe.STRING)}get isNumeric(){return!this.isVariable&&!this.equals(oe.UUID)}get isInteger(){return this.toString().startsWith("int")}get isFloat(){return this.toString().startsWith("float")}get density(){const e=oe.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 oe.BIG_INT_TYPES.some(e=>e.equals(this))}};g(p,"UNKNOWN",new p("unknown")),g(p,"FLOAT64",new p("float64")),g(p,"FLOAT32",new p("float32")),g(p,"INT64",new p("int64")),g(p,"INT32",new p("int32")),g(p,"INT16",new p("int16")),g(p,"INT8",new p("int8")),g(p,"UINT64",new p("uint64")),g(p,"UINT32",new p("uint32")),g(p,"UINT16",new p("uint16")),g(p,"UINT8",new p("uint8")),g(p,"BOOLEAN",p.UINT8),g(p,"TIMESTAMP",new p("timestamp")),g(p,"UUID",new p("uuid")),g(p,"STRING",new p("string")),g(p,"JSON",new p("json")),g(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]])),g(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]])),g(p,"DENSITIES",new Map([[p.UINT8.toString(),V.BIT8],[p.UINT16.toString(),V.BIT16],[p.UINT32.toString(),V.BIT32],[p.UINT64.toString(),V.BIT64],[p.FLOAT32.toString(),V.BIT32],[p.FLOAT64.toString(),V.BIT64],[p.INT8.toString(),V.BIT8],[p.INT16.toString(),V.BIT16],[p.INT32.toString(),V.BIT32],[p.INT64.toString(),V.BIT64],[p.TIMESTAMP.toString(),V.BIT64],[p.STRING.toString(),V.UNKNOWN],[p.JSON.toString(),V.UNKNOWN],[p.UUID.toString(),V.BIT128]])),g(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]),g(p,"BIG_INT_TYPES",[p.INT64,p.UINT64,p.TIMESTAMP]),g(p,"z",s.z.union([s.z.string().transform(r=>new p(r)),s.z.instanceof(p)]));let z=p;const F=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),c=e,l=t.sub(e),u=n.sub(t),y=i.sub(n),d=a.sub(i);let h="";return c.isZero||(h+=`${c.terabytes}TB `),l.isZero||(h+=`${l.gigabytes}GB `),u.isZero||(h+=`${u.megabytes}MB `),y.isZero||(h+=`${y.kilobytes}KB `),(!d.isZero||h==="")&&(h+=`${d.valueOf()}B`),h.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}};g(F,"BYTE",new F(1)),g(F,"KILOBYTE",F.kilobytes(1)),g(F,"MEGABYTE",F.megabytes(1)),g(F,"GIGABYTE",F.gigabytes(1)),g(F,"TERABYTE",F.terabytes(1)),g(F,"ZERO",new F(0)),g(F,"z",s.z.union([s.z.number().transform(r=>new F(r)),s.z.instanceof(F)]));let Et=F;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 ri=r=>{const e=typeof r;return e==="string"||e==="number"||e==="boolean"||e==="bigint"||r instanceof S||r instanceof E||r instanceof Date},nl=(r,e,t,n=0)=>r.usesBigInt&&!e.usesBigInt?Number(t)-Number(n):!r.usesBigInt&&e.usesBigInt?BigInt(t)-BigInt(n):pt(t,-n),sl=r=>r==null?!1:Array.isArray(r)||r instanceof ArrayBuffer||ArrayBuffer.isView(r)&&!(r instanceof DataView)||r instanceof be?!0:ri(r),Ie=-1,il=s.z.string().transform(r=>new Uint8Array(atob(r).split("").map(e=>e.charCodeAt(0))).buffer),al=s.z.union([s.z.null(),s.z.undefined()]).transform(()=>new Uint8Array().buffer),ft=class ye{constructor(e){g(this,"key",""),g(this,"isSynnaxSeries",!0),g(this,"dataType"),g(this,"sampleOffset"),g(this,"gl"),g(this,"_data"),g(this,"_timeRange"),g(this,"alignment",0n),g(this,"_cachedMin"),g(this,"_cachedMax"),g(this,"writePos",Ie),g(this,"_refCount",0),g(this,"_cachedLength"),sl(e)&&(e={data:e});const{dataType:t,timeRange:n,sampleOffset:i=0,glBufferUsage:a="static",alignment:c=0n,key:l=ei()}=e,u=e.data??[];if(u instanceof ye||typeof u=="object"&&"isSynnaxSeries"in u&&u.isSynnaxSeries===!0){const h=u;this.key=h.key,this.dataType=h.dataType,this.sampleOffset=h.sampleOffset,this.gl=h.gl,this._data=h._data,this._timeRange=h._timeRange,this.alignment=h.alignment,this._cachedMin=h._cachedMin,this._cachedMax=h._cachedMax,this.writePos=h.writePos,this._refCount=h._refCount,this._cachedLength=h._cachedLength;return}const y=ri(u),d=Array.isArray(u);if(t!=null)this.dataType=new z(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(d||y){let h=u;if(!y){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.");h=u[0]}if(typeof h=="string")this.dataType=z.STRING;else if(typeof h=="number")this.dataType=z.FLOAT64;else if(typeof h=="bigint")this.dataType=z.INT64;else if(typeof h=="boolean")this.dataType=z.BOOLEAN;else if(h instanceof S||h instanceof Date||h instanceof S)this.dataType=z.TIMESTAMP;else if(typeof h=="object")this.dataType=z.JSON;else throw new Error(`cannot infer data type of ${typeof h} when constructing a Series from a JS array`)}else this.dataType=new z(u)}if(!d&&!y)this._data=u;else{let h=y?[u]:u;const D=h[0];(D instanceof S||D instanceof Date||D instanceof E)&&(h=h.map(P=>new S(P).valueOf())),this.dataType.equals(z.STRING)?(this._cachedLength=h.length,this._data=new TextEncoder().encode(h.join(`
|
|
15
|
+
`).map(l=>l.trim());if(n.length===0)return t!=null?t.parse({}):{};const a=n.split(",").map(l=>l.trim()),c={};return a.forEach(l=>{c[l]=[]}),i.forEach(l=>{const u=l.split(",").map(h=>h.trim());a.forEach((h,d)=>{const y=this.parseValue(u[d]);y!=null&&c[h].push(y)})}),t!=null?t.parse(c):c}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(){}},Gs=class{constructor(){Tt(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 Xe=new qs,dc=new Ws,fc=new Gs,pc=[Xe],nt=Object.freeze(Object.defineProperty({__proto__:null,CSVCodec:Ws,CSV_CODEC:dc,ENCODERS:pc,JSONCodec:qs,JSON_CODEC:Xe,TEXT_CODEC:fc,TextCodec:Gs},Symbol.toStringTag,{value:"Module"})),pr=s.z.tuple([s.z.number(),s.z.number()]);s.z.tuple([s.z.bigint(),s.z.bigint()]);const Fs=s.z.object({width:s.z.number(),height:s.z.number()}),gc=s.z.object({signedWidth:s.z.number(),signedHeight:s.z.number()}),mc=["width","height"];s.z.enum(mc);const wc=["start","center","end"],bc=["signedWidth","signedHeight"];s.z.enum(bc);const cr=s.z.object({x:s.z.number(),y:s.z.number()}),Tc=s.z.object({clientX:s.z.number(),clientY:s.z.number()}),vc=["x","y"],Vs=s.z.enum(vc),Ks=["top","right","bottom","left"];s.z.enum(Ks);const Oc=["left","right"],Js=s.z.enum(Oc),zc=["top","bottom"],Hs=s.z.enum(zc),Xs=["center"],_n=s.z.enum(Xs),Ec=[...Ks,...Xs],Qs=s.z.enum(Ec);s.z.enum(wc);const Sc=["first","last"];s.z.enum(Sc);const Nc=s.z.object({lower:s.z.number(),upper:s.z.number()}),Ic=s.z.object({lower:s.z.bigint(),upper:s.z.bigint()});s.z.union([Nc,pr]);s.z.union([Ic,pr]);s.z.union([Vs,Qs]);s.z.union([Vs,Qs,s.z.instanceof(String)]);const vt=(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 Yn(r);return Yn(t)},Yn=r=>r.lower>r.upper?{lower:r.upper,upper:r.lower}:r;s.z.object({x:Js.or(_n),y:Hs.or(_n)});const kc=s.z.object({x:Js,y:Hs}),Ac=Object.freeze({x:"left",y:"top"}),$c=(r,e)=>r.x===e.x&&r.y===e.y,qn=s.z.union([s.z.number(),cr,pr,Fs,gc,Tc]),Rc=(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}},Wn=Object.freeze({x:0,y:0}),Gt=s.z.union([s.z.number(),s.z.string()]);s.z.object({top:Gt,left:Gt,width:Gt,height:Gt});s.z.object({left:s.z.number(),top:s.z.number(),right:s.z.number(),bottom:s.z.number()});s.z.object({one:cr,two:cr,root:kc});const yn=(r,e,t=0,n=0,i)=>{const a={one:{...Wn},two:{...Wn},root:i??Ac};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))},Dr=r=>{const e=yn(r);return{lower:e.one.x,upper:e.two.x}},jr=r=>{const e=yn(r);return{lower:e.one.y,upper:e.two.y}},xc=r=>typeof r!="object"||r==null?!1:"one"in r&&"two"in r&&"root"in r;var Cc=Object.defineProperty,Pc=(r,e,t)=>e in r?Cc(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,fe=(r,e,t)=>Pc(r,typeof e!="symbol"?e+"":e,t);const Dc=(r,e,t)=>e!==void 0&&r<e?e:t!==void 0&&r>t?t:r;s.z.object({offset:qn,scale:qn});const jc=r=>(e,t,n,i)=>t==="dimension"?[e,n]:[e,i?n-r:n+r],Mc=r=>(e,t,n,i)=>[e,i?n/r:n*r],Bc=r=>(e,t,n)=>{if(e===null)return[r,n];const{lower:i,upper:a}=e,{lower:c,upper:l}=r,u=a-i,h=l-c;if(t==="dimension")return[r,n*(h/u)];const d=(n-i)*(h/u)+c;return[r,d]},Uc=r=>(e,t,n)=>[r,n],Zc=()=>(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)]},Lc=r=>(e,t,n)=>{const{lower:i,upper:a}=r;return n=Dc(n,i,a),[e,n]},Qr=class yt{constructor(){fe(this,"ops",[]),fe(this,"currBounds",null),fe(this,"currType",null),fe(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=jc(e);return n.type="translate",t.ops.push(n),t}magnify(e){const t=this.new(),n=Mc(e);return n.type="magnify",t.ops.push(n),t}scale(e,t){const n=vt(e,t),i=this.new(),a=Bc(n);return a.type="scale",i.ops.push(a),i}clamp(e,t){const n=vt(e,t),i=this.new(),a=Lc(n);return a.type="clamp",i.ops.push(a),i}reBound(e,t){const n=vt(e,t),i=this.new(),a=Uc(n);return a.type="re-bound",i.ops.push(a),i}invert(){const e=Zc();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(([c,l])=>i>=c&&i<=l))return;const a=e.ops.findIndex((c,l)=>c.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}};fe(Qr,"IDENTITY",new Qr);let Gn=Qr;const Fn=class he{constructor(e=new Gn,t=new Gn,n=null){fe(this,"x"),fe(this,"y"),fe(this,"currRoot"),this.x=e,this.y=t,this.currRoot=n}static translate(e,t){return new he().translate(e,t)}static translateX(e){return new he().translateX(e)}static translateY(e){return new he().translateY(e)}static clamp(e){return new he().clamp(e)}static magnify(e){return new he().magnify(e)}static scale(e){return new he().scale(e)}static reBound(e){return new he().reBound(e)}translate(e,t){const n=Rc(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(xc(e)){const n=this.currRoot;return t.currRoot=e.root,n!=null&&!$c(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(Dr(e)),t.y=t.y.scale(jr(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(Dr(e)),t.y=this.y.reBound(jr(e)),t}clamp(e){const t=this.copy();return t.x=this.x.clamp(Dr(e)),t.y=this.y.clamp(jr(e)),t}copy(){const e=new he;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)}}box(e){return yn(this.pos(e.one),this.pos(e.two),0,0,this.currRoot??e.root)}};fe(Fn,"IDENTITY",new Fn);const Vn=r=>[...new Set(r)],_c=r=>r!=null&&typeof r=="object"&&"toString"in r,Yc=(r,e=!1)=>{const t=_c(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?qc(n):n},qc=r=>(e,t)=>r(t,e),gr=0,Mr=-1,Br=1,Wc=r=>r<gr,Gc=r=>r>gr,Fc=r=>r===gr,Vc=(r,e)=>{let t=null;return e===0?r:(...n)=>{t!==null&&(clearTimeout(t),t=null),t=setTimeout(()=>r(...n),e)}},Kc=s.z.object({signedWidth:s.z.number(),signedHeight:s.z.number()});s.z.union([Fs,Kc,cr,pr]);const Jc=s.z.bigint().or(s.z.string().transform(BigInt));var Hc=Object.defineProperty,Xc=(r,e,t)=>e in r?Hc(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,g=(r,e,t)=>Xc(r,typeof e!="symbol"?e+"":e,t);let Qc=(r,e=21)=>(t=e)=>{let n="",i=t;for(;i--;)n+=r[Math.random()*r.length|0];return n};const el="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",ei=Qc(el,11),tl=Object.freeze(Object.defineProperty({__proto__:null,id:ei},Symbol.toStringTag,{value:"Module"})),rl=s.z.enum(["static","dynamic"]),ti=(r,e)=>{const t=new S(e);if(![E.DAY,E.HOUR,E.MINUTE,E.SECOND,E.MILLISECOND,E.MICROSECOND,E.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 S?new S(n):new E(n)},x=class O{constructor(e,t="UTC"){if(g(this,"value"),g(this,"encodeValue",!0),e==null)this.value=O.now().valueOf();else if(e instanceof Date)this.value=BigInt(e.getTime())*O.MILLISECOND.valueOf();else if(typeof e=="string")this.value=O.parseDateTimeString(e,t).valueOf();else if(Array.isArray(e))this.value=O.parseDate(e);else{let n=BigInt(0);e instanceof Number&&(e=e.valueOf()),t==="local"&&(n=O.utcOffset.valueOf()),typeof e=="number"&&(isFinite(e)?e=Math.trunc(e):(isNaN(e)&&(e=0),e===1/0?e=O.MAX:e=O.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 O(BigInt(i.getTime())*O.MILLISECOND.valueOf()).truncate(O.DAY).valueOf()}encode(){return this.value.toString()}valueOf(){return this.value}static parseTimeString(e,t="UTC"){const[n,i,a]=e.split(":");let c="00",l="00";a!=null&&([c,l]=a.split("."));let u=O.hours(parseInt(n??"00",10)).add(O.minutes(parseInt(i??"00",10))).add(O.seconds(parseInt(c??"00",10))).add(O.milliseconds(parseInt(l??"00",10)));return t==="local"&&(u=u.add(O.utcOffset)),u.valueOf()}static parseDateTimeString(e,t="UTC"){if(!e.includes("/")&&!e.includes("-"))return O.parseTimeString(e,t);const n=new Date(e);return e.includes(":")||n.setUTCHours(0,0,0,0),new O(BigInt(n.getTime())*O.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(O.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 E(BigInt(new Date().getTimezoneOffset())*O.MINUTE.valueOf())}static since(e){return new O().span(e)}date(){return new Date(this.milliseconds())}equals(e){return this.valueOf()===new O(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 O(e).valueOf()}afterEq(e){return this.valueOf()>=new O(e).valueOf()}before(e){return this.valueOf()<new O(e).valueOf()}beforeEq(e){return this.valueOf()<=new O(e).valueOf()}add(e){return new O(this.valueOf()+BigInt(e.valueOf()))}sub(e){return new O(this.valueOf()-BigInt(e.valueOf()))}milliseconds(){return Number(this.valueOf())/Number(O.MILLISECOND.valueOf())}toString(){return this.date().toISOString()}remainder(e){return ti(this,e)}get isToday(){return this.truncate(E.DAY).equals(O.now().truncate(E.DAY))}truncate(e){return this.sub(this.remainder(e))}static now(){return new O(new Date)}static max(...e){let t=O.MIN;for(const n of e){const i=new O(n);i.after(t)&&(t=i)}return t}static min(...e){let t=O.MAX;for(const n of e){const i=new O(n);i.before(t)&&(t=i)}return t}static nanoseconds(e){return new O(e)}static microseconds(e){return O.nanoseconds(e*1e3)}static milliseconds(e){return O.microseconds(e*1e3)}static seconds(e){return O.milliseconds(e*1e3)}static minutes(e){return O.seconds(e*60)}static hours(e){return O.minutes(e*60)}static days(e){return O.hours(e*24)}};g(x,"NANOSECOND",x.nanoseconds(1)),g(x,"MICROSECOND",x.microseconds(1)),g(x,"MILLISECOND",x.milliseconds(1)),g(x,"SECOND",x.seconds(1)),g(x,"MINUTE",x.minutes(1)),g(x,"HOUR",x.hours(1)),g(x,"DAY",x.days(1)),g(x,"MAX",new x((1n<<63n)-1n)),g(x,"MIN",new x(0)),g(x,"ZERO",new x(0)),g(x,"z",s.z.union([s.z.object({value:s.z.bigint()}).transform(r=>new x(r.value)),s.z.string().transform(r=>new x(BigInt(r))),s.z.instanceof(Number).transform(r=>new x(r)),s.z.number().transform(r=>new x(r)),s.z.instanceof(x)]));let S=x;const C=class I{constructor(e){g(this,"value"),g(this,"encodeValue",!0),typeof e=="number"&&(e=Math.trunc(e.valueOf())),this.value=BigInt(e.valueOf())}encode(){return this.value.toString()}valueOf(){return this.value}lessThan(e){return this.valueOf()<new I(e).valueOf()}greaterThan(e){return this.valueOf()>new I(e).valueOf()}lessThanOrEqual(e){return this.valueOf()<=new I(e).valueOf()}greaterThanOrEqual(e){return this.valueOf()>=new I(e).valueOf()}remainder(e){return ti(this,e)}truncate(e){return new I(BigInt(Math.trunc(Number(this.valueOf()/e.valueOf())))*e.valueOf())}toString(){const e=this.truncate(I.DAY),t=this.truncate(I.HOUR),n=this.truncate(I.MINUTE),i=this.truncate(I.SECOND),a=this.truncate(I.MILLISECOND),c=this.truncate(I.MICROSECOND),l=this.truncate(I.NANOSECOND),u=e,h=t.sub(e),d=n.sub(t),y=i.sub(n),P=a.sub(i),D=c.sub(a),Q=l.sub(c);let B="";return u.isZero||(B+=`${u.days}d `),h.isZero||(B+=`${h.hours}h `),d.isZero||(B+=`${d.minutes}m `),y.isZero||(B+=`${y.seconds}s `),P.isZero||(B+=`${P.milliseconds}ms `),D.isZero||(B+=`${D.microseconds}µs `),Q.isZero||(B+=`${Q.nanoseconds}ns`),B.trim()}get days(){return Number(this.valueOf())/Number(I.DAY.valueOf())}get hours(){return Number(this.valueOf())/Number(I.HOUR.valueOf())}get minutes(){return Number(this.valueOf())/Number(I.MINUTE.valueOf())}get seconds(){return Number(this.valueOf())/Number(I.SECOND.valueOf())}get milliseconds(){return Number(this.valueOf())/Number(I.MILLISECOND.valueOf())}get microseconds(){return Number(this.valueOf())/Number(I.MICROSECOND.valueOf())}get nanoseconds(){return Number(this.valueOf())}get isZero(){return this.valueOf()===BigInt(0)}equals(e){return this.valueOf()===new I(e).valueOf()}add(e){return new I(this.valueOf()+new I(e).valueOf())}sub(e){return new I(this.valueOf()-new I(e).valueOf())}static nanoseconds(e=1){return new I(e)}static microseconds(e=1){return I.nanoseconds(e*1e3)}static milliseconds(e=1){return I.microseconds(e*1e3)}static seconds(e=1){return I.milliseconds(e*1e3)}static minutes(e){return I.seconds(e.valueOf()*60)}static hours(e){return I.minutes(e*60)}static days(e){return I.hours(e*24)}};g(C,"NANOSECOND",C.nanoseconds(1)),g(C,"MICROSECOND",C.microseconds(1)),g(C,"MILLISECOND",C.milliseconds(1)),g(C,"SECOND",C.seconds(1)),g(C,"MINUTE",C.minutes(1)),g(C,"HOUR",C.hours(1)),g(C,"DAY",C.days(1)),g(C,"MAX",new C((1n<<63n)-1n)),g(C,"MIN",new C(0)),g(C,"ZERO",new C(0)),g(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 E=C;const dt=class tr extends Number{constructor(e){e instanceof Number?super(e.valueOf()):super(e)}toString(){return`${this.valueOf()} Hz`}equals(e){return this.valueOf()===new tr(e).valueOf()}get period(){return E.seconds(1/this.valueOf())}sampleCount(e){return new E(e).seconds*this.valueOf()}byteCount(e,t){return this.sampleCount(e)*new V(t).valueOf()}span(e){return E.seconds(e/this.valueOf())}byteSpan(e,t){return this.span(e.valueOf()/t.valueOf())}static hz(e){return new tr(e)}static khz(e){return tr.hz(e*1e3)}};g(dt,"z",s.z.union([s.z.number().transform(r=>new dt(r)),s.z.instanceof(Number).transform(r=>new dt(r)),s.z.instanceof(dt)]));let mr=dt;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 Et(e*this.valueOf())}};g(q,"UNKNOWN",new q(0)),g(q,"BIT128",new q(16)),g(q,"BIT64",new q(8)),g(q,"BIT32",new q(4)),g(q,"BIT16",new q(2)),g(q,"BIT8",new q(1)),g(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 V=q;const ae=class rr{constructor(e,t){g(this,"start"),g(this,"end"),typeof e=="object"&&"start"in e?(this.start=new S(e.start),this.end=new S(e.end)):(this.start=new S(e),this.end=new S(t))}get span(){return new E(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 rr(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=E.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=S.max(n.start,e.start),a=S.min(n.end,e.end);return a.before(i)?!1:new E(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 rr?this.contains(e.start)&&this.contains(e.end):this.start.beforeEq(e)&&this.end.after(e)}boundBy(e){const t=new rr(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}};g(ae,"MAX",new ae(S.MIN,S.MAX)),g(ae,"MIN",new ae(S.MAX,S.MIN)),g(ae,"ZERO",new ae(S.ZERO,S.ZERO)),g(ae,"z",s.z.union([s.z.object({start:S.z,end:S.z}).transform(r=>new ae(r.start,r.end)),s.z.instanceof(ae)]));let W=ae;const p=class oe extends String{constructor(e){if(e instanceof oe||typeof e=="string"||typeof e.valueOf()=="string"){super(e.valueOf());return}else{const t=oe.ARRAY_CONSTRUCTOR_DATA_TYPES.get(e.constructor.name);if(t!=null){super(t.valueOf());return}}throw super(oe.UNKNOWN.valueOf()),new Error(`unable to find data type for ${e.toString()}`)}get Array(){const e=oe.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(oe.JSON)||this.equals(oe.STRING)}get isNumeric(){return!this.isVariable&&!this.equals(oe.UUID)}get isInteger(){return this.toString().startsWith("int")}get isFloat(){return this.toString().startsWith("float")}get density(){const e=oe.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 oe.BIG_INT_TYPES.some(e=>e.equals(this))}};g(p,"UNKNOWN",new p("unknown")),g(p,"FLOAT64",new p("float64")),g(p,"FLOAT32",new p("float32")),g(p,"INT64",new p("int64")),g(p,"INT32",new p("int32")),g(p,"INT16",new p("int16")),g(p,"INT8",new p("int8")),g(p,"UINT64",new p("uint64")),g(p,"UINT32",new p("uint32")),g(p,"UINT16",new p("uint16")),g(p,"UINT8",new p("uint8")),g(p,"BOOLEAN",p.UINT8),g(p,"TIMESTAMP",new p("timestamp")),g(p,"UUID",new p("uuid")),g(p,"STRING",new p("string")),g(p,"JSON",new p("json")),g(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]])),g(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]])),g(p,"DENSITIES",new Map([[p.UINT8.toString(),V.BIT8],[p.UINT16.toString(),V.BIT16],[p.UINT32.toString(),V.BIT32],[p.UINT64.toString(),V.BIT64],[p.FLOAT32.toString(),V.BIT32],[p.FLOAT64.toString(),V.BIT64],[p.INT8.toString(),V.BIT8],[p.INT16.toString(),V.BIT16],[p.INT32.toString(),V.BIT32],[p.INT64.toString(),V.BIT64],[p.TIMESTAMP.toString(),V.BIT64],[p.STRING.toString(),V.UNKNOWN],[p.JSON.toString(),V.UNKNOWN],[p.UUID.toString(),V.BIT128]])),g(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]),g(p,"BIG_INT_TYPES",[p.INT64,p.UINT64,p.TIMESTAMP]),g(p,"z",s.z.union([s.z.string().transform(r=>new p(r)),s.z.instanceof(p)]));let z=p;const F=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),c=e,l=t.sub(e),u=n.sub(t),h=i.sub(n),d=a.sub(i);let y="";return c.isZero||(y+=`${c.terabytes}TB `),l.isZero||(y+=`${l.gigabytes}GB `),u.isZero||(y+=`${u.megabytes}MB `),h.isZero||(y+=`${h.kilobytes}KB `),(!d.isZero||y==="")&&(y+=`${d.valueOf()}B`),y.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}};g(F,"BYTE",new F(1)),g(F,"KILOBYTE",F.kilobytes(1)),g(F,"MEGABYTE",F.megabytes(1)),g(F,"GIGABYTE",F.gigabytes(1)),g(F,"TERABYTE",F.terabytes(1)),g(F,"ZERO",new F(0)),g(F,"z",s.z.union([s.z.number().transform(r=>new F(r)),s.z.instanceof(F)]));let Et=F;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 ri=r=>{const e=typeof r;return e==="string"||e==="number"||e==="boolean"||e==="bigint"||r instanceof S||r instanceof E||r instanceof Date},nl=(r,e,t,n=0)=>r.usesBigInt&&!e.usesBigInt?Number(t)-Number(n):!r.usesBigInt&&e.usesBigInt?BigInt(t)-BigInt(n):pt(t,-n),sl=r=>r==null?!1:Array.isArray(r)||r instanceof ArrayBuffer||ArrayBuffer.isView(r)&&!(r instanceof DataView)||r instanceof be?!0:ri(r),Ie=-1,il=s.z.string().transform(r=>new Uint8Array(atob(r).split("").map(e=>e.charCodeAt(0))).buffer),al=s.z.union([s.z.null(),s.z.undefined()]).transform(()=>new Uint8Array().buffer),ft=class ye{constructor(e){g(this,"key",""),g(this,"isSynnaxSeries",!0),g(this,"dataType"),g(this,"sampleOffset"),g(this,"gl"),g(this,"_data"),g(this,"_timeRange"),g(this,"alignment",0n),g(this,"_cachedMin"),g(this,"_cachedMax"),g(this,"writePos",Ie),g(this,"_refCount",0),g(this,"_cachedLength"),sl(e)&&(e={data:e});const{dataType:t,timeRange:n,sampleOffset:i=0,glBufferUsage:a="static",alignment:c=0n,key:l=ei()}=e,u=e.data??[];if(u instanceof ye||typeof u=="object"&&"isSynnaxSeries"in u&&u.isSynnaxSeries===!0){const y=u;this.key=y.key,this.dataType=y.dataType,this.sampleOffset=y.sampleOffset,this.gl=y.gl,this._data=y._data,this._timeRange=y._timeRange,this.alignment=y.alignment,this._cachedMin=y._cachedMin,this._cachedMax=y._cachedMax,this.writePos=y.writePos,this._refCount=y._refCount,this._cachedLength=y._cachedLength;return}const h=ri(u),d=Array.isArray(u);if(t!=null)this.dataType=new z(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(d||h){let y=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.");y=u[0]}if(typeof y=="string")this.dataType=z.STRING;else if(typeof y=="number")this.dataType=z.FLOAT64;else if(typeof y=="bigint")this.dataType=z.INT64;else if(typeof y=="boolean")this.dataType=z.BOOLEAN;else if(y instanceof S||y instanceof Date||y instanceof S)this.dataType=z.TIMESTAMP;else if(typeof y=="object")this.dataType=z.JSON;else throw new Error(`cannot infer data type of ${typeof y} when constructing a Series from a JS array`)}else this.dataType=new z(u)}if(!d&&!h)this._data=u;else{let y=h?[u]:u;const P=y[0];(P instanceof S||P instanceof Date||P instanceof E)&&(y=y.map(D=>new S(D).valueOf())),this.dataType.equals(z.STRING)?(this._cachedLength=y.length,this._data=new TextEncoder().encode(y.join(`
|
|
16
16
|
`)+`
|
|
17
|
-
`)):this.dataType.equals(z.JSON)?(this._cachedLength=
|
|
17
|
+
`)):this.dataType.equals(z.JSON)?(this._cachedLength=y.length,this._data=new TextEncoder().encode(y.map(D=>Xe.encodeString(D)).join(`
|
|
18
18
|
`)+`
|
|
19
|
-
`)):this._data=new this.dataType.Array(
|
|
19
|
+
`)):this._data=new this.dataType.Array(y).buffer}this.key=l,this.alignment=c,this.sampleOffset=i??0,this._timeRange=n,this.gl={control:null,buffer:null,prevBuffer:0,bufferUsage:a}}static alloc({capacity:e,dataType:t,...n}){if(e===0)throw new Error("[Series] - cannot allocate an array of length 0");const i=new new z(t).Array(e),a=new ye({data:i.buffer,dataType:t,...n});return a.writePos=0,a}static generateTimestamps(e,t,n){const i=n.spanRange(t.span(e)),a=new BigInt64Array(e);for(let c=0;c<e;c++)a[c]=BigInt(n.add(t.span(c)).valueOf());return new ye({data:a,dataType:z.TIMESTAMP,timeRange:i})}get refCount(){return this._refCount}static fromStrings(e,t){const n=new TextEncoder().encode(e.join(`
|
|
20
20
|
`)+`
|
|
21
21
|
`);return new ye({data:n,dataType:z.STRING,timeRange:t})}static fromJSON(e,t){const n=new TextEncoder().encode(e.map(i=>Xe.encodeString(i)).join(`
|
|
22
22
|
`)+`
|
|
23
23
|
`);return new ye({data:n,dataType:z.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");if(this.writePos===Ie)return 0;const t=this.capacity-this.writePos,n=t<e.length?e.slice(0,t):e;return this.underlyingData.set(n.data,this.writePos),this.maybeRecomputeMinMax(n),this._cachedLength=void 0,this.writePos+=n.length,n.length}get buffer(){return this._data}get underlyingData(){return new this.dataType.Array(this._data)}get data(){return this.writePos===Ie?this.underlyingData:new this.dataType.Array(this._data,0,this.writePos)}toStrings(){if(!this.dataType.matches(z.STRING,z.UUID))throw new Error("cannot convert non-string series to strings");return new TextDecoder().decode(this.buffer).split(`
|
|
24
24
|
`).slice(0,-1)}toUUIDs(){if(!this.dataType.equals(z.UUID))throw new Error("cannot convert non-uuid series to uuids");const e=z.UUID.density.valueOf(),t=Array(this.length);for(let n=0;n<this.length;n++){const i=this.buffer.slice(n*e,(n+1)*e),a=Array.from(new Uint8Array(i),c=>c.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(z.JSON))throw new Error("cannot convert non-string series to strings");return new TextDecoder().decode(this.buffer).split(`
|
|
25
|
-
`).slice(0,-1).map(t=>e.parse(Xe.decodeString(t)))}get timeRange(){if(this._timeRange==null)throw new Error("time range not set on series");return this._timeRange}get byteCapacity(){return new Et(this.buffer.byteLength)}get capacity(){return this.dataType.density.length(this.byteCapacity)}get byteLength(){return this.writePos===Ie?this.byteCapacity:this.dataType.density.size(this.writePos)}get length(){return this._cachedLength!=null?this._cachedLength:this.dataType.isVariable?this.calculateCachedLength():this.writePos===Ie?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;return this.data.forEach(t=>{t===10&&e++}),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]=nl(this.dataType,e,this.data[i],t);return new ye({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(z.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==null&&(this._cachedMax=this.calcRawMax()),pt(this._cachedMax,this.sampleOffset))}calcRawMin(){if(this.length===0)return 1/0;if(this.dataType.equals(z.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==null&&(this._cachedMin=this.calcRawMin()),pt(this._cachedMin,this.sampleOffset))}get bounds(){return vt(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 pt(this.max,-this.min)}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 pt(n,this.sampleOffset)}atVariable(e,t){e<0&&(e=this.length+e);let n=0,i=0;for(let c=0;c<this.data.length;c++)if(this.data[c]===10){if(e===0){i=c;break}n=c+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(z.STRING)?new TextDecoder().decode(a):Ys(JSON.parse(new TextDecoder().decode(a)))}binarySearch(e){let t=0,n=this.length-1;const i=Yc(e);for(;t<=n;){const a=Math.floor((t+n)/2),c=i(this.at(a,!0),e);if(c===0)return a;c<0?t=a+1:n=a-1}return t}updateGLBuffer(e){if(this.gl.control=e,!this.dataType.equals(z.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!==Ie){i===0&&e.bufferData(e.ARRAY_BUFFER,this.byteCapacity.valueOf(),e.STATIC_DRAW);const a=this.dataType.density.size(i).valueOf(),c=this.underlyingData.slice(this.gl.prevBuffer,this.writePos);e.bufferSubData(e.ARRAY_BUFFER,a,c.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=Ie}as(e){if(e==="string"){if(!this.dataType.equals(z.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(z.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:this.alignmentBounds,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 vt(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 ol(this);return this.dataType.equals(z.JSON)?new cl(e):e}return new ll(this)}slice(e,t){if(e<=0&&(t==null||t>=this.length))return this;const n=this.data.slice(e,t);return new ye({data:n,dataType:this.dataType,timeRange:this._timeRange,sampleOffset:this.sampleOffset,glBufferUsage:this.gl.bufferUsage,alignment:this.alignment+BigInt(e)})}reAlign(e){return new ye({data:this.buffer,dataType:this.dataType,timeRange:W.ZERO,sampleOffset:this.sampleOffset,glBufferUsage:"static",alignment:e})}};g(ft,"crudeZ",s.z.object({timeRange:W.z.optional(),dataType:z.z,alignment:Jc.optional(),data:s.z.union([il,al,s.z.instanceof(ArrayBuffer)]),glBufferUsage:rl.optional().default("static").optional()})),g(ft,"z",ft.crudeZ.transform(r=>new ft(r)));let be=ft;class ol{constructor(e){if(g(this,"series"),g(this,"index"),g(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]!==10;)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 Kn,Jn;class cl{constructor(e){g(this,"wrapped"),g(this,Kn,"JSONSeriesIterator"),this.wrapped=e}next(){const e=this.wrapped.next();return e.done===!0?{done:!0,value:void 0}:{done:!1,value:Xe.decodeString(e.value)}}[(Jn=Symbol.iterator,Kn=Symbol.toStringTag,Jn)](){return this}}var Hn,Xn;class ll{constructor(e){g(this,"series"),g(this,"index"),g(this,Hn,"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)}}[(Xn=Symbol.iterator,Hn=Symbol.toStringTag,Xn)](){return this}}const pt=(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 ni{constructor(e){if(g(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 z(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?z.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)}push(e){this.series.push(e)}get length(){return this.series.reduce((e,t)=>e+t.length,0)}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}`)}get byteLength(){return new Et(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)}[Symbol.iterator](){return this.series.length===0?{next(){return{done:!0,value:void 0}}}:new ul(this.series)}}var Qn,es;class ul{constructor(e){g(this,"series"),g(this,"seriesIndex"),g(this,"internal"),g(this,Qn,"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())}[(es=Symbol.iterator,Qn=Symbol.toStringTag,es)](){return this}}s.z.object({key:s.z.string(),value:s.z.string()});var hl=Object.defineProperty,yl=(r,e,t)=>e in r?hl(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,nr=(r,e,t)=>yl(r,typeof e!="symbol"?e+"":e,t);let dl=class{constructor(e,t){nr(this,"handlers"),nr(this,"transform"),nr(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))}},fl=class{constructor(e){nr(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 xe=Object.freeze(Object.defineProperty({__proto__:null,BaseObserver:fl,Observer:dl},Symbol.toStringTag,{value:"Module"})),dn=s.z.record(s.z.union([s.z.number(),s.z.string(),s.z.symbol()]),s.z.unknown()),pl=()=>typeof process<"u"&&process.versions!=null&&process.versions.node!=null?"node":typeof window>"u"||window.document===void 0?"webworker":"browser";pl();const gl=["MacOS","Windows","Linux","Docker"];s.z.enum(gl);var ml=Object.defineProperty,wl=(r,e,t)=>e in r?ml(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,gt=(r,e,t)=>wl(r,typeof e!="symbol"?e+"":e,t);const bl=(...r)=>r.map(si).join(""),si=r=>(r.endsWith("/")||(r+="/"),r.startsWith("/")&&(r=r.slice(1)),r),Tl=r=>r.endsWith("/")?r.slice(0,-1):r,en=class tn{constructor({host:e,port:t,protocol:n="",pathPrefix:i=""}){gt(this,"protocol"),gt(this,"host"),gt(this,"port"),gt(this,"path"),this.protocol=n,this.host=e,this.port=t,this.path=si(i)}replace(e){return new tn({host:e.host??this.host,port:e.port??this.port,protocol:e.protocol??this.protocol,pathPrefix:e.pathPrefix??this.path})}child(e){return new tn({...this,pathPrefix:bl(this.path,e)})}toString(){return Tl(`${this.protocol}://${this.host}:${this.port}/${this.path}`)}};gt(en,"UNKNOWN",new en({host:"unknown",port:0}));let vl=en;var Ol=Object.defineProperty,zl=(r,e,t)=>e in r?Ol(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,sr=(r,e,t)=>zl(r,typeof e!="symbol"?e+"":e,t);const ke=class extends Number{};sr(ke,"Absolute",255),sr(ke,"Default",1),sr(ke,"z",s.z.union([s.z.instanceof(ke),s.z.number().int().min(0).max(255).transform(r=>new ke(r)),s.z.instanceof(Number).transform(r=>new ke(r))]));let ii=ke;const ai=s.z.object({name:s.z.string(),key:s.z.string()}),El=r=>s.z.object({subject:ai,resource:r,authority:ii.z}),Sl=(...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}),et=Object.freeze(Object.defineProperty({__proto__:null,Authority:ii,filterTransfersByChannelKey:Sl,stateZ:El,subjectZ:ai},Symbol.toStringTag,{value:"Module"})),oi=class mt extends Error{constructor(){super(mt.MESSAGE)}matches(e){return typeof e=="string"?e.includes(mt.MESSAGE):e instanceof mt||e.message.includes(mt.MESSAGE)}};sr(oi,"MESSAGE","canceled");let Nl=oi;new Nl;const rn=s.z.string().regex(/^\d+\.\d+\.\d+$/),xt=(r,e,t={})=>{t.checkMajor??(t.checkMajor=!0),t.checkMinor??(t.checkMinor=!0),t.checkPatch??(t.checkPatch=!0);const n=rn.parse(r),i=rn.parse(e),[a,c,l]=n.split(".").map(Number),[u,y,d]=i.split(".").map(Number);if(t.checkMajor){if(a<u)return Mr;if(a>u)return Br}if(t.checkMinor){if(c<y)return Mr;if(c>y)return Br}if(t.checkPatch){if(l<d)return Mr;if(l>d)return Br}return gr},Il=(r,e,t={})=>Fc(xt(r,e,t)),ci=(r,e,t={})=>Gc(xt(r,e,t)),kl=(r,e,t={})=>Wc(xt(r,e,t)),Al=({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}},$l=({name:r,migrations:e,targetSchema:t,def:n})=>{const i=Object.keys(e).sort(xt).pop();if(i==null)return u=>{if(u.version!==n.version)return console.log(`${r} version ${u.version} is newer than latest version of ${n.version}.
|
|
25
|
+
`).slice(0,-1).map(t=>e.parse(Xe.decodeString(t)))}get timeRange(){if(this._timeRange==null)throw new Error("time range not set on series");return this._timeRange}get byteCapacity(){return new Et(this.buffer.byteLength)}get capacity(){return this.dataType.density.length(this.byteCapacity)}get byteLength(){return this.writePos===Ie?this.byteCapacity:this.dataType.density.size(this.writePos)}get length(){return this._cachedLength!=null?this._cachedLength:this.dataType.isVariable?this.calculateCachedLength():this.writePos===Ie?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;return this.data.forEach(t=>{t===10&&e++}),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]=nl(this.dataType,e,this.data[i],t);return new ye({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(z.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==null&&(this._cachedMax=this.calcRawMax()),pt(this._cachedMax,this.sampleOffset))}calcRawMin(){if(this.length===0)return 1/0;if(this.dataType.equals(z.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==null&&(this._cachedMin=this.calcRawMin()),pt(this._cachedMin,this.sampleOffset))}get bounds(){return vt(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 pt(this.max,-this.min)}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 pt(n,this.sampleOffset)}atVariable(e,t){e<0&&(e=this.length+e);let n=0,i=0;for(let c=0;c<this.data.length;c++)if(this.data[c]===10){if(e===0){i=c;break}n=c+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(z.STRING)?new TextDecoder().decode(a):Ys(JSON.parse(new TextDecoder().decode(a)))}binarySearch(e){let t=0,n=this.length-1;const i=Yc(e);for(;t<=n;){const a=Math.floor((t+n)/2),c=i(this.at(a,!0),e);if(c===0)return a;c<0?t=a+1:n=a-1}return t}updateGLBuffer(e){if(this.gl.control=e,!this.dataType.equals(z.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!==Ie){i===0&&e.bufferData(e.ARRAY_BUFFER,this.byteCapacity.valueOf(),e.STATIC_DRAW);const a=this.dataType.density.size(i).valueOf(),c=this.underlyingData.slice(this.gl.prevBuffer,this.writePos);e.bufferSubData(e.ARRAY_BUFFER,a,c.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=Ie}as(e){if(e==="string"){if(!this.dataType.equals(z.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(z.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:this.alignmentBounds,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 vt(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 ol(this);return this.dataType.equals(z.JSON)?new cl(e):e}return new ll(this)}slice(e,t){if(e<=0&&(t==null||t>=this.length))return this;const n=this.data.slice(e,t);return new ye({data:n,dataType:this.dataType,timeRange:this._timeRange,sampleOffset:this.sampleOffset,glBufferUsage:this.gl.bufferUsage,alignment:this.alignment+BigInt(e)})}reAlign(e){return new ye({data:this.buffer,dataType:this.dataType,timeRange:W.ZERO,sampleOffset:this.sampleOffset,glBufferUsage:"static",alignment:e})}};g(ft,"crudeZ",s.z.object({timeRange:W.z.optional(),dataType:z.z,alignment:Jc.optional(),data:s.z.union([il,al,s.z.instanceof(ArrayBuffer)]),glBufferUsage:rl.optional().default("static").optional()})),g(ft,"z",ft.crudeZ.transform(r=>new ft(r)));let be=ft;class ol{constructor(e){if(g(this,"series"),g(this,"index"),g(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]!==10;)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 Kn,Jn;class cl{constructor(e){g(this,"wrapped"),g(this,Kn,"JSONSeriesIterator"),this.wrapped=e}next(){const e=this.wrapped.next();return e.done===!0?{done:!0,value:void 0}:{done:!1,value:Xe.decodeString(e.value)}}[(Jn=Symbol.iterator,Kn=Symbol.toStringTag,Jn)](){return this}}var Hn,Xn;class ll{constructor(e){g(this,"series"),g(this,"index"),g(this,Hn,"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)}}[(Xn=Symbol.iterator,Hn=Symbol.toStringTag,Xn)](){return this}}const pt=(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 ni{constructor(e){if(g(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 z(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?z.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)}push(e){this.series.push(e)}get length(){return this.series.reduce((e,t)=>e+t.length,0)}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}`)}get byteLength(){return new Et(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)}[Symbol.iterator](){return this.series.length===0?{next(){return{done:!0,value:void 0}}}:new ul(this.series)}}var Qn,es;class ul{constructor(e){g(this,"series"),g(this,"seriesIndex"),g(this,"internal"),g(this,Qn,"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())}[(es=Symbol.iterator,Qn=Symbol.toStringTag,es)](){return this}}s.z.object({key:s.z.string(),value:s.z.string()});var hl=Object.defineProperty,yl=(r,e,t)=>e in r?hl(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,nr=(r,e,t)=>yl(r,typeof e!="symbol"?e+"":e,t);let dl=class{constructor(e,t){nr(this,"handlers"),nr(this,"transform"),nr(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))}},fl=class{constructor(e){nr(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 xe=Object.freeze(Object.defineProperty({__proto__:null,BaseObserver:fl,Observer:dl},Symbol.toStringTag,{value:"Module"})),dn=s.z.record(s.z.union([s.z.number(),s.z.string(),s.z.symbol()]),s.z.unknown()),pl=()=>typeof process<"u"&&process.versions!=null&&process.versions.node!=null?"node":typeof window>"u"||window.document===void 0?"webworker":"browser";pl();const gl=["MacOS","Windows","Linux","Docker"];s.z.enum(gl);var ml=Object.defineProperty,wl=(r,e,t)=>e in r?ml(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,gt=(r,e,t)=>wl(r,typeof e!="symbol"?e+"":e,t);const bl=(...r)=>r.map(si).join(""),si=r=>(r.endsWith("/")||(r+="/"),r.startsWith("/")&&(r=r.slice(1)),r),Tl=r=>r.endsWith("/")?r.slice(0,-1):r,en=class tn{constructor({host:e,port:t,protocol:n="",pathPrefix:i=""}){gt(this,"protocol"),gt(this,"host"),gt(this,"port"),gt(this,"path"),this.protocol=n,this.host=e,this.port=t,this.path=si(i)}replace(e){return new tn({host:e.host??this.host,port:e.port??this.port,protocol:e.protocol??this.protocol,pathPrefix:e.pathPrefix??this.path})}child(e){return new tn({...this,pathPrefix:bl(this.path,e)})}toString(){return Tl(`${this.protocol}://${this.host}:${this.port}/${this.path}`)}};gt(en,"UNKNOWN",new en({host:"unknown",port:0}));let vl=en;var Ol=Object.defineProperty,zl=(r,e,t)=>e in r?Ol(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,sr=(r,e,t)=>zl(r,typeof e!="symbol"?e+"":e,t);const ke=class extends Number{};sr(ke,"Absolute",255),sr(ke,"Default",1),sr(ke,"z",s.z.union([s.z.instanceof(ke),s.z.number().int().min(0).max(255).transform(r=>new ke(r)),s.z.instanceof(Number).transform(r=>new ke(r))]));let ii=ke;const ai=s.z.object({name:s.z.string(),key:s.z.string()}),El=r=>s.z.object({subject:ai,resource:r,authority:ii.z}),Sl=(...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}),et=Object.freeze(Object.defineProperty({__proto__:null,Authority:ii,filterTransfersByChannelKey:Sl,stateZ:El,subjectZ:ai},Symbol.toStringTag,{value:"Module"})),oi=class mt extends Error{constructor(){super(mt.MESSAGE)}matches(e){return typeof e=="string"?e.includes(mt.MESSAGE):e instanceof mt||e.message.includes(mt.MESSAGE)}};sr(oi,"MESSAGE","canceled");let Nl=oi;new Nl;const rn=s.z.string().regex(/^\d+\.\d+\.\d+$/),xt=(r,e,t={})=>{t.checkMajor??(t.checkMajor=!0),t.checkMinor??(t.checkMinor=!0),t.checkPatch??(t.checkPatch=!0);const n=rn.parse(r),i=rn.parse(e),[a,c,l]=n.split(".").map(Number),[u,h,d]=i.split(".").map(Number);if(t.checkMajor){if(a<u)return Mr;if(a>u)return Br}if(t.checkMinor){if(c<h)return Mr;if(c>h)return Br}if(t.checkPatch){if(l<d)return Mr;if(l>d)return Br}return gr},Il=(r,e,t={})=>Fc(xt(r,e,t)),ci=(r,e,t={})=>Gc(xt(r,e,t)),kl=(r,e,t={})=>Wc(xt(r,e,t)),Al=({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}},$l=({name:r,migrations:e,targetSchema:t,defaultVersion:n,def:i})=>{const a=Object.keys(e).sort(xt).pop();if(a==null)return h=>{if(h.version==null&&(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
|
-
`),
|
|
27
|
+
`),i;try{return t!=null?t.parse(h):h}catch(d){return console.log(`${r} failed to parse default. Exiting with default`),console.error(d),i}};const c=Object.keys(e).length;let l=!1;const u=h=>{try{if(c===0||ci(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 d=h.version,y=e[d],P=y(h);return l=!0,u(P)}catch(d){return console.log(`${r} failed to migrate from ${h.version} to ${a}`),console.error(d),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(d){return console.log(`${r} failed to parse final result. Exiting with default`),console.error(d),i}}},ts=Object.freeze(Object.defineProperty({__proto__:null,compareSemVer:xt,createMigration:Al,migrator:$l,semVerNewer:ci,semVerOlder:kl,semVerZ:rn,versionsEqual:Il},Symbol.toStringTag,{value:"Module"})),ze="sy.",Be=class Be extends ne{constructor(){super(...arguments);o(this,"type",Be.TYPE)}};o(Be,"TYPE",ze+"validation"),o(Be,"matches",H(Be.TYPE));let M=Be;const Ue=class Ue extends M{constructor(t,n){super(t+": "+n);o(this,"type",Ue.TYPE);o(this,"field");o(this,"message");this.field=t,this.message=n}};o(Ue,"TYPE",M.TYPE+".field"),o(Ue,"matches",H(Ue.TYPE));let lr=Ue;const Ze=class Ze extends ne{constructor(){super(...arguments);o(this,"type",Ze.TYPE)}};o(Ze,"TYPE",ze+"auth"),o(Ze,"matches",H(Ze.TYPE));let Ce=Ze;const Le=class Le extends Ce{constructor(){super(...arguments);o(this,"type",Le.TYPE)}};o(Le,"TYPE",Ce.TYPE+".invalid-token"),o(Le,"matches",H(Le.TYPE));let St=Le;const _e=class _e extends ne{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
|
-
`);o(this,"type",_e.TYPE)}};o(_e,"TYPE",ze+"unexpected"),o(_e,"matches",H(_e.TYPE));let ve=_e;const Ye=class Ye extends ne{constructor(){super(...arguments);o(this,"type",Ye.TYPE)}};o(Ye,"TYPE",ze+"query"),o(Ye,"matches",H(Ye.TYPE));let te=Ye;const qe=class qe extends te{constructor(){super(...arguments);o(this,"type",qe.TYPE)}};o(qe,"TYPE",te.TYPE+".not_found"),o(qe,"matches",H(qe.TYPE));let pe=qe;const We=class We extends te{constructor(){super(...arguments);o(this,"type",We.TYPE)}};o(We,"TYPE",te.TYPE+".multiple_results"),o(We,"matches",H(We.TYPE));let ge=We;const Ge=class Ge extends ne{constructor(t,n){super(t);o(this,"type",Ge.TYPE);o(this,"path");this.path=n}};o(Ge,"TYPE",ze+"route"),o(Ge,"matches",H(Ge.TYPE));let Nt=Ge;const Fe=class Fe extends ne{constructor(){super(...arguments);o(this,"type",Fe.TYPE)}};o(Fe,"TYPE",ze+"control"),o(Fe,"matches",H(Fe.TYPE));let tt=Fe;const Ve=class Ve extends tt{constructor(){super(...arguments);o(this,"type",Ve.TYPE)}};o(Ve,"TYPE",tt.TYPE+".unauthorized"),o(Ve,"matches",H(Ve.TYPE));let ur=Ve;const Ke=class Ke extends ne{constructor(){super(...arguments);o(this,"type",Ke.TYPE)}};o(Ke,"TYPE",ze+"contiguity"),o(Ke,"matches",H(Ke.TYPE));let nn=Ke;const Rl=r=>{if(!r.type.startsWith(ze))return null;if(r.type.startsWith(M.TYPE)){if(r.type===lr.TYPE){const e=r.data.split(": ");return e.length<2?new M(r.data):new lr(e[0],e[1])}return new M(r.data)}return r.type.startsWith(Ce.TYPE)?r.type.startsWith(St.TYPE)?new St(r.data):new Ce(r.data):r.type.startsWith(ve.TYPE)?new ve(r.data):r.type.startsWith(te.TYPE)?r.type.startsWith(pe.TYPE)?new pe(r.data):r.type.startsWith(ge.TYPE)?new ge(r.data):new te(r.data):r.type.startsWith(tt.TYPE)?r.type.startsWith(ur.TYPE)?new ur(r.data):new tt(r.data):r.type.startsWith(Nt.TYPE)?new Nt(r.data,r.data):new ve(r.data)},xl=()=>{throw new Error("Not implemented")};Ps({encode:xl,decode:Rl});const Cl=async(r,e)=>{const[t,n]=await e(r);return n==null?[t,n]:n instanceof Re?[t,new Re({message:`Cannot reach cluster at ${n.url.host}:${n.url.port}`,url:n.url})]:[t,n]};class li{constructor(e,t){o(this,"key");o(this,"name");this.key=t,this.name=e}get ontologyID(){return new b({type:"group",key:this.key})}}const Pl=s.z.string().uuid(),ui=s.z.object({key:Pl,name:s.z.string()}),Ct=s.z.union([s.z.literal("label"),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")]),Dl="builtin",jl="cluster",Ml="node",J=s.z.object({type:Ct,key:s.z.string()}),hi=s.z.string().transform(r=>{const[e,t]=r.split(":");return{type:Ct.parse(e),key:t??""}}),Me=s.z.union([hi,J]),Je=class Je{constructor(e){o(this,"type");o(this,"key");if(e instanceof Je){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}}};o(Je,"z",s.z.union([s.z.instanceof(Je),Me.transform(e=>new Je(e))]));let b=Je;const Bl=new b({type:"builtin",key:"root"}),yi=s.z.object({type:s.z.number()}),di=s.z.object({type:Ct,fields:s.z.record(yi)}),fi=s.z.object({id:b.z,name:s.z.string(),schema:di.optional().nullable(),data:s.z.record(s.z.unknown()).optional().nullable()}).transform(r=>({key:r.id.toString(),...r})),Ul=s.z.object({from:b.z,type:s.z.string(),to:b.z}),sn=r=>{const[e,t,n]=r.split("->");return{from:new b(e),type:t,to:new b(n)}},Zl=s.z.object({group:ui}),Ll=s.z.object({parent:J,key:s.z.string().uuid().optional(),name:s.z.string()}),_l=s.z.object({key:s.z.string(),name:s.z.string()}),Yl=s.z.object({keys:s.z.array(s.z.string())});var re;let ql=(re=class{constructor(e){o(this,"client");this.client=e}async create(e,t,n){return(await w(this.client,re.ENDPOINT,{parent:e,name:t,key:n},Ll,Zl)).group}async rename(e,t){await w(this.client,re.ENDPOINT_RENAME,{key:e,name:t},_l,s.z.object({}))}async delete(e){await w(this.client,re.ENDPOINT_DELETE,{keys:e},Yl,s.z.object({}))}},o(re,"ENDPOINT","/ontology/create-group"),o(re,"ENDPOINT_RENAME","/ontology/rename-group"),o(re,"ENDPOINT_DELETE","/ontology/delete-group"),re),Wl=class{constructor(e){o(this,"creator");this.creator=new ql(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 li(e.name,e.key)}};const Ur={ADD_CHILDREN:"/ontology/add-children",REMOVE_CHILDREN:"/ontology/remove-children",MOVE_CHILDREN:"/ontology/move-children"},rs=s.z.object({id:J,children:J.array()}),Gl=s.z.object({from:J,to:J,children:J.array()});let Fl=class{constructor(e){o(this,"client");this.client=e}async addChildren(e,...t){await w(this.client,Ur.ADD_CHILDREN,{id:new b(e).payload,children:t.map(n=>new b(n).payload)},rs,s.z.object({}))}async removeChildren(e,...t){await w(this.client,Ur.REMOVE_CHILDREN,{id:new b(e).payload,children:t.map(n=>new b(n).payload)},rs,s.z.object({}))}async moveChildren(e,t,...n){const i={from:new b(e).payload,to:new b(t).payload,children:n.map(a=>new b(a).payload)};await w(this.client,Ur.MOVE_CHILDREN,i,Gl,s.z.object({}))}};const Vl="/ontology/retrieve",Kl=s.z.object({ids:J.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:Ct.array().optional()}),Jl=s.z.object({resources:fi.array()}),ir=r=>T(r).map(e=>new b(e).payload);let pi=class{constructor(e,t){o(this,"type","ontology");o(this,"groups");o(this,"client");o(this,"writer");o(this,"framer");this.client=e,this.writer=new Fl(e),this.groups=new Wl(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:ir(e),...t});if(Array.isArray(e))return n;if(n.length===0)throw new te(`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:ir(e),children:!0,...t})}async retrieveParents(e,t){return await this.execRetrieve({ids:ir(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 Pt.open(this.framer,this)}async openDependentTracker(e){return await wr.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,Vl,e,Kl,Jl);return t}};const ns="sy_ontology_resource_set",ss="sy_ontology_resource_delete",is="sy_ontology_relationship_set",as="sy_ontology_relationship_delete";class Pt{constructor(e,t){o(this,"relationships");o(this,"resources");o(this,"resourceObs");o(this,"relationshipObs");o(this,"streamer");o(this,"client");o(this,"closePromise");this.relationshipObs=new xe.Observer,this.relationships=this.relationshipObs,this.resourceObs=new xe.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),c=this.parseRelationshipDeletes(e);a.concat(c).length>0&&this.relationshipObs.notify(a.concat(c))}parseRelationshipSets(e){const t=e.get(is);return t.length===0?[]:Array.from(t.as("string")).map(n=>({variant:"set",key:sn(n),value:void 0}))}parseRelationshipDeletes(e){const t=e.get(as);return t.length===0?[]:Array.from(t.as("string")).map(n=>({variant:"delete",key:sn(n)}))}async parseResourceSets(e){const t=e.get(ns);if(t.length===0)return[];const n=Array.from(t.as("string")).map(i=>new b(i));try{return(await this.client.retrieve(n)).map(a=>({variant:"set",key:a.id,value:a}))}catch(i){if(i instanceof te)return[];throw i}}parseResourceDeletes(e){const t=e.get(ss);return t.length===0?[]:Array.from(t.as("string")).map(n=>({variant:"delete",key:new b(n)}))}static async open(e,t){const n=await e.openStreamer([ns,ss,is,as]);return new Pt(n,t)}}const os=r=>r==="from"?"to":"from";class wr extends xe.Observer{constructor({target:t,dependents:n,relationshipType:i="parent",relationshipDirection:a="from",resourceType:c},l,u){super();o(this,"internal");o(this,"target");o(this,"relDir");o(this,"resourceType");o(this,"dependents");o(this,"client");o(this,"relType");o(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)});o(this,"handleRelationshipChange",t=>{const n=t.filter(a=>a.variant==="delete"&&a.key[this.relDir].toString()===this.target.toString()&&(this.resourceType==null||a.key[os(this.relDir)].type===this.resourceType));this.dependents=this.dependents.filter(a=>!n.some(c=>c.key.to.toString()===a.id.toString()&&c.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[os(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=c,this.internal=l,this.target=t,this.dependents=n,this.resourceType!=null&&(this.dependents=this.dependents.filter(y=>y.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 Pt.open(n,i);return new wr(t,a,i)}async close(){await this.internal.close()}}const Hl=Object.freeze(Object.defineProperty({__proto__:null,BUILTIN_TYPE:Dl,CLUSTER_TYPE:jl,ChangeTracker:Pt,Client:pi,DependentTracker:wr,ID:b,NODE_TYPE:Ml,Root:Bl,crudeIDZ:Me,idZ:J,parseIDs:ir,parseRelationship:sn,relationshipSchemaZ:Ul,resourceSchemaZ:fi,resourceTypeZ:Ct,schemaFieldZ:yi,schemaZ:di,stringIDZ:hi},Symbol.toStringTag,{value:"Module"})),ee=r=>s.z.union([s.z.null().transform(()=>[]),r.array()]),Dt=s.z.string().uuid(),gi=s.z.object({key:Dt.optional(),subjects:Me.array().or(Me),objects:Me.array().or(Me),actions:or.array().or(or)}),br=s.z.object({key:Dt,subjects:ee(J),objects:ee(J),actions:ee(or)}),mi="policy",Xl=r=>new b({type:mi,key:r}),wi="allow_all",Ql=new b({type:wi,key:""}),eu=s.z.object({keys:Dt.array().optional(),subjects:J.array().optional()}),tu=s.z.object({policies:ee(br)}),ru="/access/policy/retrieve";let nu=class{constructor(e){o(this,"client");this.client=e}async retrieve(e){return(await w(this.client,ru,e,eu,tu)).policies}};const su=s.z.object({policies:br.partial({key:!0}).array()}),iu=s.z.object({policies:br.array()}),au=s.z.object({keys:Dt.array()}),ou=s.z.object({}),cu="/access/policy/create",lu="/access/policy/delete";let uu=class{constructor(e){o(this,"client");this.client=e}async create(e){const n=gi.array().parse(T(e)).map(a=>({objects:T(a.objects),actions:T(a.actions),subjects:T(a.subjects)}));return(await w(this.client,cu,{policies:n},su,iu)).policies}async delete(e){await w(this.client,lu,{keys:T(e)},au,ou)}},bi=class{constructor(e){o(this,"retriever");o(this,"writer");this.retriever=new nu(e),this.writer=new uu(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:T(e)});return t?n:n[0]}async retrieveFor(e){const t=T(e).map(n=>new b(n).payload);return await this.retriever.retrieve({subjects:t})}async delete(e){await this.writer.delete(e)}};const hu=Object.freeze(Object.defineProperty({__proto__:null,ALLOW_ALL_ONTOLOGY_ID:Ql,ALLOW_ALL_ONTOLOGY_TYPE:wi,Client:bi,ONTOLOGY_TYPE:mi,keyZ:Dt,newPolicyZ:gi,ontologyID:Xl,policyZ:br},Symbol.toStringTag,{value:"Module"}));let Ti=class{constructor(e){o(this,"policy");this.policy=new bi(e)}};const yu=Object.freeze(Object.defineProperty({__proto__:null,ALL_ACTION:rc,CREATE_ACTION:nc,Client:Ti,DELETE_ACTION:sc,RETRIEVE_ACTION:ic,UPDATE_ACTION:ac,actionZ:or},Symbol.toStringTag,{value:"Module"})),Ee=s.z.number(),jt=s.z.object({name:s.z.string(),key:s.z.number(),rate:mr.z,dataType:z.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()}),vi=jt.extend({key:s.z.number().optional(),leaseholder:s.z.number().optional(),index:s.z.number().optional(),rate:mr.z.optional().default(0),isIndex:s.z.boolean().optional(),internal:s.z.boolean().optional().default(!1),virtual:s.z.boolean().optional().default(!1)}),Oi="channel",du=r=>new b({type:Oi,key:r.toString()}),fu=new Error("request for lock canceled");var pu=function(r,e,t,n){function i(a){return a instanceof t?a:new t(function(c){c(a)})}return new(t||(t=Promise))(function(a,c){function l(d){try{y(n.next(d))}catch(h){c(h)}}function u(d){try{y(n.throw(d))}catch(h){c(h)}}function y(d){d.done?a(d.value):i(d.value).then(l,u)}y((n=n.apply(r,e||[])).next())})};class gu{constructor(e,t=fu){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},c=zi(this._queue,l=>t<=l.priority);c===-1&&e<=this._value?this._dispatchItem(a):this._queue.splice(c+1,0,a)})}runExclusive(e){return pu(this,arguments,void 0,function*(t,n=1,i=0){const[a,c]=yield this.acquire(n,i);try{return yield t(a)}finally{c()}})}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]=[]),mu(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 mu(r,e){const t=zi(r,n=>e.priority<=n.priority);r.splice(t+1,0,e)}function zi(r,e){for(let t=r.length-1;t>=0;t--)if(e(r[t]))return t;return-1}var wu=function(r,e,t,n){function i(a){return a instanceof t?a:new t(function(c){c(a)})}return new(t||(t=Promise))(function(a,c){function l(d){try{y(n.next(d))}catch(h){c(h)}}function u(d){try{y(n.throw(d))}catch(h){c(h)}}function y(d){d.done?a(d.value):i(d.value).then(l,u)}y((n=n.apply(r,e||[])).next())})};class bu{constructor(e){this._semaphore=new gu(1,e)}acquire(){return wu(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 Tr=(r,e,{convertNumericStrings:t=!0}={})=>{const n=!Array.isArray(r);let i=T(r);const a=i[0],c=typeof a;let l;return c==="string"&&t&&!isNaN(parseInt(a))&&"number"in e?(l=e.number,i=i.map(u=>parseInt(u))):l=e[c],{single:n,variant:l,normalized:i,actual:r}},vr=(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 ge(`Expected one ${r} matching ${JSON.stringify(e)}, but found ${t.length}`)}},Tu=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:z.z.array().optional(),notDataTypes:z.z.array().optional(),virtual:s.z.boolean().optional(),isIndex:s.z.boolean().optional(),internal:s.z.boolean().optional()}),vu=s.z.object({channels:ee(jt)}),me=r=>Tr(r,{number:"keys",string:"names"}),yr=class yr{constructor(e){o(this,"client");this.client=e}async search(e,t){return await this.execute({search:e,...t})}async retrieve(e,t){const n=me(e),{variant:i}=n;let{normalized:a}=n;return i==="keys"&&a.indexOf(0)!==-1&&(a=a.filter(c=>c!==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(yr.ENDPOINT,e,Tu,vu);if(n!=null)throw n;return t.channels}};o(yr,"ENDPOINT","/channel/retrieve");let It=yr;class fn{constructor(e){o(this,"cache");o(this,"namesToKeys");o(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}=Tr(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 c=await this.wrapped.retrieve(a,t);return this.set(c),i.concat(c)}delete(e){const{variant:t,normalized:n}=me(e);t==="names"?n.forEach(i=>{const a=this.namesToKeys.get(i);a!=null&&(a.forEach(c=>this.cache.delete(c)),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],c=this.cache.get(n);if(c==null)return;this.cache.delete(n);const l=this.namesToKeys.get(c.name);l!=null&&(l.delete(n),l.size===0&&this.namesToKeys.delete(c.name)),c.name=a,this.cache.set(n,c);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 Ei{constructor(e,t){o(this,"mu",new bu);o(this,"requests",new Map);o(this,"wrapped");o(this,"debouncedRun");this.wrapped=e,this.debouncedRun=Vc(()=>{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}=me(e);return n==="names"?await this.wrapped.retrieve(t):await new Promise((a,c)=>{this.mu.runExclusive(()=>{this.requests.set(t,{resolve:a,reject:c}),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 Si=async(r,e)=>{const{normalized:t}=me(e),n=await r.retrieve(t),i=[];if(t.forEach(a=>{n.find(c=>c.name===a||c.key===a)==null&&i.push(a)}),i.length>0)throw new te(`Could not find channels: ${JSON.stringify(i)}`);return n};class pn{constructor({dataType:e,rate:t,name:n,leaseholder:i=0,key:a=0,isIndex:c=!1,index:l=0,internal:u=!1,virtual:y=!1,frameClient:d,alias:h}){o(this,"_frameClient");o(this,"key");o(this,"name");o(this,"rate");o(this,"dataType");o(this,"leaseholder");o(this,"index");o(this,"isIndex");o(this,"internal");o(this,"alias");o(this,"virtual");this.key=a,this.name=n,this.rate=new mr(t??0),this.dataType=new z(e),this.leaseholder=i,this.index=l,this.isIndex=c,this.internal=u,this.alias=h,this.virtual=y,this._frameClient=d??null}get framer(){if(this._frameClient==null)throw new M("cannot read from a channel that has not been created");return this._frameClient}get payload(){return jt.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 b({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 Ou="/channel/retrieve-group",zu=s.z.object({}),Eu=s.z.object({group:ui});let Ni=class{constructor(e,t,n,i){o(this,"type","channel");o(this,"frameClient");o(this,"client");o(this,"retriever");o(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=T(e),c=[];if(n){const l=await this.retriever.retrieve(a.map(y=>y.name)),u=new Set(l.map(y=>y.name));a=a.filter(y=>!u.has(y.name)),c=this.sugar(l)}return c=c.concat(this.sugar(await this.writer.create(a))),i?c[0]:c}async retrieve(e,t){const n=!Array.isArray(e),i=this.sugar(await this.retriever.retrieve(e,t));return vr("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}=me(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(T(e),T(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 fn(new Ei(new It(this.client),e))}sugar(e){const{frameClient:t}=this;return e.map(n=>new pn({...n,frameClient:t}))}async retrieveGroup(){const e=await w(this.client,Ou,{},zu,Eu);return new li(e.group.name,e.group.key)}};const Su=s.z.object({channels:vi.array()}),Nu=s.z.object({channels:jt.array()}),Iu=s.z.object({keys:Ee.array().optional(),names:s.z.string().array().optional()}),ku=s.z.object({}),Au=s.z.object({keys:Ee.array(),names:s.z.string().array()}),$u=s.z.object({}),Ru="/channel/create",xu="/channel/delete",Cu="/channel/rename";let Ii=class{constructor(e,t){o(this,"client");o(this,"cache");this.client=e,this.cache=t}async create(e){const{channels:t}=await w(this.client,Ru,{channels:e},Su,Nu);return this.cache.set(t),t}async delete(e){await w(this.client,xu,e,Iu,ku),e.keys!=null&&this.cache.delete(e.keys),e.names!=null&&this.cache.delete(e.names)}async rename(e,t){await w(this.client,Cu,{keys:e,names:t},Au,$u),this.cache.rename(e,t)}};const Pu=Object.freeze(Object.defineProperty({__proto__:null,CacheRetriever:fn,Channel:pn,Client:Ni,ClusterRetriever:It,DebouncedBatchRetriever:Ei,ONTOLOGY_TYPE:Oi,Writer:Ii,analyzeChannelParams:me,keyZ:Ee,newPayload:vi,ontologyID:du,payload:jt,retrieveRequired:Si},Symbol.toStringTag,{value:"Module"})),st=s.z.string().uuid(),Mt=s.z.object({key:st,username:s.z.string().min(1),firstName:s.z.string().optional().default(""),lastName:s.z.string().optional().default(""),rootUser:s.z.boolean().optional().default(!0)}),ki=Mt.partial({key:!0,firstName:!0,lastName:!0}).omit({rootUser:!0}).extend({password:s.z.string().min(1)}),Ai="user",Du=r=>new b({type:Ai,key:r}),ju=s.z.object({keys:st.array().optional(),usernames:s.z.string().array().optional()}),Mu=s.z.object({users:ee(Mt)}),Bu="/user/retrieve";let Uu=class{constructor(e){o(this,"client");this.client=e}async retrieve(e){return(await w(this.client,Bu,e,ju,Mu)).users}};const Zu=s.z.object({users:ki.array()}),Lu=s.z.object({users:Mt.array()}),_u=s.z.object({key:st,username:s.z.string().min(1)}),Yu=s.z.object({}),qu=s.z.object({key:st,firstName:s.z.string().optional(),lastName:s.z.string().optional()}),Wu=s.z.object({}),Gu=s.z.object({keys:st.array()}),Fu=s.z.object({}),Vu="/user/create",Ku="/user/change-username",Ju="/user/rename",Hu="/user/delete";let Xu=class{constructor(e){o(this,"client");this.client=e}async create(e){return(await w(this.client,Vu,{users:T(e)},Zu,Lu)).users}async changeUsername(e,t){await w(this.client,Ku,{key:e,username:t},_u,Yu)}async rename(e,t,n){await w(this.client,Ju,{key:e,firstName:t,lastName:n},qu,Wu)}async delete(e){await w(this.client,Hu,{keys:T(e)},Gu,Fu)}},$i=class{constructor(e){o(this,"reader");o(this,"writer");this.writer=new Xu(e),this.reader=new Uu(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:T(e)});if(t)return n;if(n.length===0)throw new pe(`No user with key ${e} found`);if(n.length>1)throw new ge(`Multiple users found with key ${e}`);return n[0]}async retrieveByName(e){const t=Array.isArray(e),n=await this.reader.retrieve({usernames:T(e)});if(t)return n;if(n.length===0)throw new pe(`No user with username ${e} found`);if(n.length>1)throw new ge(`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 Qu=Object.freeze(Object.defineProperty({__proto__:null,Client:$i,ONTOLOGY_TYPE:Ai,keyZ:st,newUserZ:ki,ontologyID:Du,userZ:Mt},Symbol.toStringTag,{value:"Module"})),eh=s.z.object({username:s.z.string(),password:s.z.string()}),th=s.z.object({token:s.z.string(),user:Mt}),cs="/auth/login",rh=3,nh="/auth/change-password",sh=s.z.object({username:s.z.string(),password:s.z.string(),newPassword:s.z.string().min(1)}),ih=s.z.object({});let ah=class{constructor(e,t){o(this,"token");o(this,"client");o(this,"credentials");o(this,"authenticating");o(this,"authenticated");o(this,"user");o(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,nh,{username:this.credentials.username,password:this.credentials.password,newPassword:e},sh,ih),this.credentials.password=e}middleware(){const e=async(t,n)=>{if(!this.authenticated&&!t.target.endsWith(cs)){this.authenticating==null&&(this.authenticating=new Promise((l,u)=>{this.client.send(cs,this.credentials,eh,th).then(([y,d])=>{if(d!=null)return l(d);this.token=y==null?void 0:y.token,this.user=y==null?void 0:y.user,this.authenticated=!0,l(null)}).catch(u)}));const c=await this.authenticating;if(c!=null)return[t,c]}t.params.Authorization=`Bearer ${this.token}`;const[i,a]=await n(t);return St.matches(a)&&this.retryCount<rh?(this.authenticated=!1,this.authenticating=void 0,this.retryCount+=1,e(t,n)):(this.retryCount=0,[i,a])};return e}};const oh=["disconnected","connecting","connected","failed"],Ri=s.z.enum(oh),xi=s.z.object({status:Ri,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()}),ch=s.z.object({clusterKey:s.z.string(),nodeVersion:s.z.string().optional()}),ls={clusterKey:"",status:"disconnected",error:void 0,message:"Disconnected",clientServerCompatible:!1,clientVersion:"0.31.1"},us=(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
|
+
`);o(this,"type",_e.TYPE)}};o(_e,"TYPE",ze+"unexpected"),o(_e,"matches",H(_e.TYPE));let ve=_e;const Ye=class Ye extends ne{constructor(){super(...arguments);o(this,"type",Ye.TYPE)}};o(Ye,"TYPE",ze+"query"),o(Ye,"matches",H(Ye.TYPE));let te=Ye;const qe=class qe extends te{constructor(){super(...arguments);o(this,"type",qe.TYPE)}};o(qe,"TYPE",te.TYPE+".not_found"),o(qe,"matches",H(qe.TYPE));let pe=qe;const We=class We extends te{constructor(){super(...arguments);o(this,"type",We.TYPE)}};o(We,"TYPE",te.TYPE+".multiple_results"),o(We,"matches",H(We.TYPE));let ge=We;const Ge=class Ge extends ne{constructor(t,n){super(t);o(this,"type",Ge.TYPE);o(this,"path");this.path=n}};o(Ge,"TYPE",ze+"route"),o(Ge,"matches",H(Ge.TYPE));let Nt=Ge;const Fe=class Fe extends ne{constructor(){super(...arguments);o(this,"type",Fe.TYPE)}};o(Fe,"TYPE",ze+"control"),o(Fe,"matches",H(Fe.TYPE));let tt=Fe;const Ve=class Ve extends tt{constructor(){super(...arguments);o(this,"type",Ve.TYPE)}};o(Ve,"TYPE",tt.TYPE+".unauthorized"),o(Ve,"matches",H(Ve.TYPE));let ur=Ve;const Ke=class Ke extends ne{constructor(){super(...arguments);o(this,"type",Ke.TYPE)}};o(Ke,"TYPE",ze+"contiguity"),o(Ke,"matches",H(Ke.TYPE));let nn=Ke;const Rl=r=>{if(!r.type.startsWith(ze))return null;if(r.type.startsWith(M.TYPE)){if(r.type===lr.TYPE){const e=r.data.split(": ");return e.length<2?new M(r.data):new lr(e[0],e[1])}return new M(r.data)}return r.type.startsWith(Ce.TYPE)?r.type.startsWith(St.TYPE)?new St(r.data):new Ce(r.data):r.type.startsWith(ve.TYPE)?new ve(r.data):r.type.startsWith(te.TYPE)?r.type.startsWith(pe.TYPE)?new pe(r.data):r.type.startsWith(ge.TYPE)?new ge(r.data):new te(r.data):r.type.startsWith(tt.TYPE)?r.type.startsWith(ur.TYPE)?new ur(r.data):new tt(r.data):r.type.startsWith(Nt.TYPE)?new Nt(r.data,r.data):new ve(r.data)},xl=()=>{throw new Error("Not implemented")};Ps({encode:xl,decode:Rl});const Cl=async(r,e)=>{const[t,n]=await e(r);return n==null?[t,n]:n instanceof Re?[t,new Re({message:`Cannot reach cluster at ${n.url.host}:${n.url.port}`,url:n.url})]:[t,n]};class li{constructor(e,t){o(this,"key");o(this,"name");this.key=t,this.name=e}get ontologyID(){return new b({type:"group",key:this.key})}}const Pl=s.z.string().uuid(),ui=s.z.object({key:Pl,name:s.z.string()}),Ct=s.z.union([s.z.literal("label"),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")]),Dl="builtin",jl="cluster",Ml="node",J=s.z.object({type:Ct,key:s.z.string()}),hi=s.z.string().transform(r=>{const[e,t]=r.split(":");return{type:Ct.parse(e),key:t??""}}),Me=s.z.union([hi,J]),Je=class Je{constructor(e){o(this,"type");o(this,"key");if(e instanceof Je){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}}};o(Je,"z",s.z.union([s.z.instanceof(Je),Me.transform(e=>new Je(e))]));let b=Je;const Bl=new b({type:"builtin",key:"root"}),yi=s.z.object({type:s.z.number()}),di=s.z.object({type:Ct,fields:s.z.record(yi)}),fi=s.z.object({id:b.z,name:s.z.string(),schema:di.optional().nullable(),data:s.z.record(s.z.unknown()).optional().nullable()}).transform(r=>({key:r.id.toString(),...r})),Ul=s.z.object({from:b.z,type:s.z.string(),to:b.z}),sn=r=>{const[e,t,n]=r.split("->");return{from:new b(e),type:t,to:new b(n)}},Zl=s.z.object({group:ui}),Ll=s.z.object({parent:J,key:s.z.string().uuid().optional(),name:s.z.string()}),_l=s.z.object({key:s.z.string(),name:s.z.string()}),Yl=s.z.object({keys:s.z.array(s.z.string())});var re;let ql=(re=class{constructor(e){o(this,"client");this.client=e}async create(e,t,n){return(await w(this.client,re.ENDPOINT,{parent:e,name:t,key:n},Ll,Zl)).group}async rename(e,t){await w(this.client,re.ENDPOINT_RENAME,{key:e,name:t},_l,s.z.object({}))}async delete(e){await w(this.client,re.ENDPOINT_DELETE,{keys:e},Yl,s.z.object({}))}},o(re,"ENDPOINT","/ontology/create-group"),o(re,"ENDPOINT_RENAME","/ontology/rename-group"),o(re,"ENDPOINT_DELETE","/ontology/delete-group"),re),Wl=class{constructor(e){o(this,"creator");this.creator=new ql(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 li(e.name,e.key)}};const Ur={ADD_CHILDREN:"/ontology/add-children",REMOVE_CHILDREN:"/ontology/remove-children",MOVE_CHILDREN:"/ontology/move-children"},rs=s.z.object({id:J,children:J.array()}),Gl=s.z.object({from:J,to:J,children:J.array()});let Fl=class{constructor(e){o(this,"client");this.client=e}async addChildren(e,...t){await w(this.client,Ur.ADD_CHILDREN,{id:new b(e).payload,children:t.map(n=>new b(n).payload)},rs,s.z.object({}))}async removeChildren(e,...t){await w(this.client,Ur.REMOVE_CHILDREN,{id:new b(e).payload,children:t.map(n=>new b(n).payload)},rs,s.z.object({}))}async moveChildren(e,t,...n){const i={from:new b(e).payload,to:new b(t).payload,children:n.map(a=>new b(a).payload)};await w(this.client,Ur.MOVE_CHILDREN,i,Gl,s.z.object({}))}};const Vl="/ontology/retrieve",Kl=s.z.object({ids:J.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:Ct.array().optional()}),Jl=s.z.object({resources:fi.array()}),ir=r=>T(r).map(e=>new b(e).payload);let pi=class{constructor(e,t){o(this,"type","ontology");o(this,"groups");o(this,"client");o(this,"writer");o(this,"framer");this.client=e,this.writer=new Fl(e),this.groups=new Wl(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:ir(e),...t});if(Array.isArray(e))return n;if(n.length===0)throw new te(`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:ir(e),children:!0,...t})}async retrieveParents(e,t){return await this.execRetrieve({ids:ir(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 Pt.open(this.framer,this)}async openDependentTracker(e){return await wr.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,Vl,e,Kl,Jl);return t}};const ns="sy_ontology_resource_set",ss="sy_ontology_resource_delete",is="sy_ontology_relationship_set",as="sy_ontology_relationship_delete";class Pt{constructor(e,t){o(this,"relationships");o(this,"resources");o(this,"resourceObs");o(this,"relationshipObs");o(this,"streamer");o(this,"client");o(this,"closePromise");this.relationshipObs=new xe.Observer,this.relationships=this.relationshipObs,this.resourceObs=new xe.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),c=this.parseRelationshipDeletes(e);a.concat(c).length>0&&this.relationshipObs.notify(a.concat(c))}parseRelationshipSets(e){const t=e.get(is);return t.length===0?[]:Array.from(t.as("string")).map(n=>({variant:"set",key:sn(n),value:void 0}))}parseRelationshipDeletes(e){const t=e.get(as);return t.length===0?[]:Array.from(t.as("string")).map(n=>({variant:"delete",key:sn(n)}))}async parseResourceSets(e){const t=e.get(ns);if(t.length===0)return[];const n=Array.from(t.as("string")).map(i=>new b(i));try{return(await this.client.retrieve(n)).map(a=>({variant:"set",key:a.id,value:a}))}catch(i){if(i instanceof te)return[];throw i}}parseResourceDeletes(e){const t=e.get(ss);return t.length===0?[]:Array.from(t.as("string")).map(n=>({variant:"delete",key:new b(n)}))}static async open(e,t){const n=await e.openStreamer([ns,ss,is,as]);return new Pt(n,t)}}const os=r=>r==="from"?"to":"from";class wr extends xe.Observer{constructor({target:t,dependents:n,relationshipType:i="parent",relationshipDirection:a="from",resourceType:c},l,u){super();o(this,"internal");o(this,"target");o(this,"relDir");o(this,"resourceType");o(this,"dependents");o(this,"client");o(this,"relType");o(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)});o(this,"handleRelationshipChange",t=>{const n=t.filter(a=>a.variant==="delete"&&a.key[this.relDir].toString()===this.target.toString()&&(this.resourceType==null||a.key[os(this.relDir)].type===this.resourceType));this.dependents=this.dependents.filter(a=>!n.some(c=>c.key.to.toString()===a.id.toString()&&c.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[os(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=c,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 Pt.open(n,i);return new wr(t,a,i)}async close(){await this.internal.close()}}const Hl=Object.freeze(Object.defineProperty({__proto__:null,BUILTIN_TYPE:Dl,CLUSTER_TYPE:jl,ChangeTracker:Pt,Client:pi,DependentTracker:wr,ID:b,NODE_TYPE:Ml,Root:Bl,crudeIDZ:Me,idZ:J,parseIDs:ir,parseRelationship:sn,relationshipSchemaZ:Ul,resourceSchemaZ:fi,resourceTypeZ:Ct,schemaFieldZ:yi,schemaZ:di,stringIDZ:hi},Symbol.toStringTag,{value:"Module"})),ee=r=>s.z.union([s.z.null().transform(()=>[]),r.array()]),Dt=s.z.string().uuid(),gi=s.z.object({key:Dt.optional(),subjects:Me.array().or(Me),objects:Me.array().or(Me),actions:or.array().or(or)}),br=s.z.object({key:Dt,subjects:ee(J),objects:ee(J),actions:ee(or)}),mi="policy",Xl=r=>new b({type:mi,key:r}),wi="allow_all",Ql=new b({type:wi,key:""}),eu=s.z.object({keys:Dt.array().optional(),subjects:J.array().optional()}),tu=s.z.object({policies:ee(br)}),ru="/access/policy/retrieve";let nu=class{constructor(e){o(this,"client");this.client=e}async retrieve(e){return(await w(this.client,ru,e,eu,tu)).policies}};const su=s.z.object({policies:br.partial({key:!0}).array()}),iu=s.z.object({policies:br.array()}),au=s.z.object({keys:Dt.array()}),ou=s.z.object({}),cu="/access/policy/create",lu="/access/policy/delete";let uu=class{constructor(e){o(this,"client");this.client=e}async create(e){const n=gi.array().parse(T(e)).map(a=>({objects:T(a.objects),actions:T(a.actions),subjects:T(a.subjects)}));return(await w(this.client,cu,{policies:n},su,iu)).policies}async delete(e){await w(this.client,lu,{keys:T(e)},au,ou)}},bi=class{constructor(e){o(this,"retriever");o(this,"writer");this.retriever=new nu(e),this.writer=new uu(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:T(e)});return t?n:n[0]}async retrieveFor(e){const t=T(e).map(n=>new b(n).payload);return await this.retriever.retrieve({subjects:t})}async delete(e){await this.writer.delete(e)}};const hu=Object.freeze(Object.defineProperty({__proto__:null,ALLOW_ALL_ONTOLOGY_ID:Ql,ALLOW_ALL_ONTOLOGY_TYPE:wi,Client:bi,ONTOLOGY_TYPE:mi,keyZ:Dt,newPolicyZ:gi,ontologyID:Xl,policyZ:br},Symbol.toStringTag,{value:"Module"}));let Ti=class{constructor(e){o(this,"policy");this.policy=new bi(e)}};const yu=Object.freeze(Object.defineProperty({__proto__:null,ALL_ACTION:rc,CREATE_ACTION:nc,Client:Ti,DELETE_ACTION:sc,RETRIEVE_ACTION:ic,UPDATE_ACTION:ac,actionZ:or},Symbol.toStringTag,{value:"Module"})),Ee=s.z.number(),jt=s.z.object({name:s.z.string(),key:s.z.number(),rate:mr.z,dataType:z.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()}),vi=jt.extend({key:s.z.number().optional(),leaseholder:s.z.number().optional(),index:s.z.number().optional(),rate:mr.z.optional().default(0),isIndex:s.z.boolean().optional(),internal:s.z.boolean().optional().default(!1),virtual:s.z.boolean().optional().default(!1)}),Oi="channel",du=r=>new b({type:Oi,key:r.toString()}),fu=new Error("request for lock canceled");var pu=function(r,e,t,n){function i(a){return a instanceof t?a:new t(function(c){c(a)})}return new(t||(t=Promise))(function(a,c){function l(d){try{h(n.next(d))}catch(y){c(y)}}function u(d){try{h(n.throw(d))}catch(y){c(y)}}function h(d){d.done?a(d.value):i(d.value).then(l,u)}h((n=n.apply(r,e||[])).next())})};class gu{constructor(e,t=fu){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},c=zi(this._queue,l=>t<=l.priority);c===-1&&e<=this._value?this._dispatchItem(a):this._queue.splice(c+1,0,a)})}runExclusive(e){return pu(this,arguments,void 0,function*(t,n=1,i=0){const[a,c]=yield this.acquire(n,i);try{return yield t(a)}finally{c()}})}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]=[]),mu(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 mu(r,e){const t=zi(r,n=>e.priority<=n.priority);r.splice(t+1,0,e)}function zi(r,e){for(let t=r.length-1;t>=0;t--)if(e(r[t]))return t;return-1}var wu=function(r,e,t,n){function i(a){return a instanceof t?a:new t(function(c){c(a)})}return new(t||(t=Promise))(function(a,c){function l(d){try{h(n.next(d))}catch(y){c(y)}}function u(d){try{h(n.throw(d))}catch(y){c(y)}}function h(d){d.done?a(d.value):i(d.value).then(l,u)}h((n=n.apply(r,e||[])).next())})};class bu{constructor(e){this._semaphore=new gu(1,e)}acquire(){return wu(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 Tr=(r,e,{convertNumericStrings:t=!0}={})=>{const n=!Array.isArray(r);let i=T(r);const a=i[0],c=typeof a;let l;return c==="string"&&t&&!isNaN(parseInt(a))&&"number"in e?(l=e.number,i=i.map(u=>parseInt(u))):l=e[c],{single:n,variant:l,normalized:i,actual:r}},vr=(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 ge(`Expected one ${r} matching ${JSON.stringify(e)}, but found ${t.length}`)}},Tu=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:z.z.array().optional(),notDataTypes:z.z.array().optional(),virtual:s.z.boolean().optional(),isIndex:s.z.boolean().optional(),internal:s.z.boolean().optional()}),vu=s.z.object({channels:ee(jt)}),me=r=>Tr(r,{number:"keys",string:"names"}),yr=class yr{constructor(e){o(this,"client");this.client=e}async search(e,t){return await this.execute({search:e,...t})}async retrieve(e,t){const n=me(e),{variant:i}=n;let{normalized:a}=n;return i==="keys"&&a.indexOf(0)!==-1&&(a=a.filter(c=>c!==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(yr.ENDPOINT,e,Tu,vu);if(n!=null)throw n;return t.channels}};o(yr,"ENDPOINT","/channel/retrieve");let It=yr;class fn{constructor(e){o(this,"cache");o(this,"namesToKeys");o(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}=Tr(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 c=await this.wrapped.retrieve(a,t);return this.set(c),i.concat(c)}delete(e){const{variant:t,normalized:n}=me(e);t==="names"?n.forEach(i=>{const a=this.namesToKeys.get(i);a!=null&&(a.forEach(c=>this.cache.delete(c)),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],c=this.cache.get(n);if(c==null)return;this.cache.delete(n);const l=this.namesToKeys.get(c.name);l!=null&&(l.delete(n),l.size===0&&this.namesToKeys.delete(c.name)),c.name=a,this.cache.set(n,c);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 Ei{constructor(e,t){o(this,"mu",new bu);o(this,"requests",new Map);o(this,"wrapped");o(this,"debouncedRun");this.wrapped=e,this.debouncedRun=Vc(()=>{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}=me(e);return n==="names"?await this.wrapped.retrieve(t):await new Promise((a,c)=>{this.mu.runExclusive(()=>{this.requests.set(t,{resolve:a,reject:c}),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 Si=async(r,e)=>{const{normalized:t}=me(e),n=await r.retrieve(t),i=[];if(t.forEach(a=>{n.find(c=>c.name===a||c.key===a)==null&&i.push(a)}),i.length>0)throw new te(`Could not find channels: ${JSON.stringify(i)}`);return n};class pn{constructor({dataType:e,rate:t,name:n,leaseholder:i=0,key:a=0,isIndex:c=!1,index:l=0,internal:u=!1,virtual:h=!1,frameClient:d,alias:y}){o(this,"_frameClient");o(this,"key");o(this,"name");o(this,"rate");o(this,"dataType");o(this,"leaseholder");o(this,"index");o(this,"isIndex");o(this,"internal");o(this,"alias");o(this,"virtual");this.key=a,this.name=n,this.rate=new mr(t??0),this.dataType=new z(e),this.leaseholder=i,this.index=l,this.isIndex=c,this.internal=u,this.alias=y,this.virtual=h,this._frameClient=d??null}get framer(){if(this._frameClient==null)throw new M("cannot read from a channel that has not been created");return this._frameClient}get payload(){return jt.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 b({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 Ou="/channel/retrieve-group",zu=s.z.object({}),Eu=s.z.object({group:ui});let Ni=class{constructor(e,t,n,i){o(this,"type","channel");o(this,"frameClient");o(this,"client");o(this,"retriever");o(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=T(e),c=[];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)),c=this.sugar(l)}return c=c.concat(this.sugar(await this.writer.create(a))),i?c[0]:c}async retrieve(e,t){const n=!Array.isArray(e),i=this.sugar(await this.retriever.retrieve(e,t));return vr("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}=me(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(T(e),T(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 fn(new Ei(new It(this.client),e))}sugar(e){const{frameClient:t}=this;return e.map(n=>new pn({...n,frameClient:t}))}async retrieveGroup(){const e=await w(this.client,Ou,{},zu,Eu);return new li(e.group.name,e.group.key)}};const Su=s.z.object({channels:vi.array()}),Nu=s.z.object({channels:jt.array()}),Iu=s.z.object({keys:Ee.array().optional(),names:s.z.string().array().optional()}),ku=s.z.object({}),Au=s.z.object({keys:Ee.array(),names:s.z.string().array()}),$u=s.z.object({}),Ru="/channel/create",xu="/channel/delete",Cu="/channel/rename";let Ii=class{constructor(e,t){o(this,"client");o(this,"cache");this.client=e,this.cache=t}async create(e){const{channels:t}=await w(this.client,Ru,{channels:e},Su,Nu);return this.cache.set(t),t}async delete(e){await w(this.client,xu,e,Iu,ku),e.keys!=null&&this.cache.delete(e.keys),e.names!=null&&this.cache.delete(e.names)}async rename(e,t){await w(this.client,Cu,{keys:e,names:t},Au,$u),this.cache.rename(e,t)}};const Pu=Object.freeze(Object.defineProperty({__proto__:null,CacheRetriever:fn,Channel:pn,Client:Ni,ClusterRetriever:It,DebouncedBatchRetriever:Ei,ONTOLOGY_TYPE:Oi,Writer:Ii,analyzeChannelParams:me,keyZ:Ee,newPayload:vi,ontologyID:du,payload:jt,retrieveRequired:Si},Symbol.toStringTag,{value:"Module"})),st=s.z.string().uuid(),Mt=s.z.object({key:st,username:s.z.string().min(1),firstName:s.z.string().default(""),lastName:s.z.string().default(""),rootUser:s.z.boolean().default(!0)}),ki=Mt.partial({key:!0,firstName:!0,lastName:!0}).omit({rootUser:!0}).extend({password:s.z.string().min(1)}),Ai="user",Du=r=>new b({type:Ai,key:r}),ju=s.z.object({keys:st.array().optional(),usernames:s.z.string().array().optional()}),Mu=s.z.object({users:ee(Mt)}),Bu="/user/retrieve";let Uu=class{constructor(e){o(this,"client");this.client=e}async retrieve(e){return(await w(this.client,Bu,e,ju,Mu)).users}};const Zu=s.z.object({users:ki.array()}),Lu=s.z.object({users:Mt.array()}),_u=s.z.object({key:st,username:s.z.string().min(1)}),Yu=s.z.object({}),qu=s.z.object({key:st,firstName:s.z.string().optional(),lastName:s.z.string().optional()}),Wu=s.z.object({}),Gu=s.z.object({keys:st.array()}),Fu=s.z.object({}),Vu="/user/create",Ku="/user/change-username",Ju="/user/rename",Hu="/user/delete";let Xu=class{constructor(e){o(this,"client");this.client=e}async create(e){return(await w(this.client,Vu,{users:T(e)},Zu,Lu)).users}async changeUsername(e,t){await w(this.client,Ku,{key:e,username:t},_u,Yu)}async rename(e,t,n){await w(this.client,Ju,{key:e,firstName:t,lastName:n},qu,Wu)}async delete(e){await w(this.client,Hu,{keys:T(e)},Gu,Fu)}},$i=class{constructor(e){o(this,"reader");o(this,"writer");this.writer=new Xu(e),this.reader=new Uu(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:T(e)});if(t)return n;if(n.length===0)throw new pe(`No user with key ${e} found`);if(n.length>1)throw new ge(`Multiple users found with key ${e}`);return n[0]}async retrieveByName(e){const t=Array.isArray(e),n=await this.reader.retrieve({usernames:T(e)});if(t)return n;if(n.length===0)throw new pe(`No user with username ${e} found`);if(n.length>1)throw new ge(`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 Qu=Object.freeze(Object.defineProperty({__proto__:null,Client:$i,ONTOLOGY_TYPE:Ai,keyZ:st,newUserZ:ki,ontologyID:Du,userZ:Mt},Symbol.toStringTag,{value:"Module"})),eh=s.z.object({username:s.z.string(),password:s.z.string()}),th=s.z.object({token:s.z.string(),user:Mt}),cs="/auth/login",rh=3,nh="/auth/change-password",sh=s.z.object({username:s.z.string(),password:s.z.string(),newPassword:s.z.string().min(1)}),ih=s.z.object({});let ah=class{constructor(e,t){o(this,"token");o(this,"client");o(this,"credentials");o(this,"authenticating");o(this,"authenticated");o(this,"user");o(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,nh,{username:this.credentials.username,password:this.credentials.password,newPassword:e},sh,ih),this.credentials.password=e}middleware(){const e=async(t,n)=>{if(!this.authenticated&&!t.target.endsWith(cs)){this.authenticating==null&&(this.authenticating=new Promise((l,u)=>{this.client.send(cs,this.credentials,eh,th).then(([h,d])=>{if(d!=null)return l(d);this.token=h==null?void 0:h.token,this.user=h==null?void 0:h.user,this.authenticated=!0,l(null)}).catch(u)}));const c=await this.authenticating;if(c!=null)return[t,c]}t.params.Authorization=`Bearer ${this.token}`;const[i,a]=await n(t);return St.matches(a)&&this.retryCount<rh?(this.authenticated=!1,this.authenticating=void 0,this.retryCount+=1,e(t,n)):(this.retryCount=0,[i,a])};return e}};const oh=["disconnected","connecting","connected","failed"],Ri=s.z.enum(oh),xi=s.z.object({status:Ri,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()}),ch=s.z.object({clusterKey:s.z.string(),nodeVersion:s.z.string().optional()}),ls={clusterKey:"",status:"disconnected",error:void 0,message:"Disconnected",clientServerCompatible:!1,clientVersion:"0.32.0"},us=(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
35
|
https://docs.synnaxlabs.com/reference/typescript-client/troubleshooting#old-${n}-version`},He=class He{constructor(e,t=E.seconds(30),n,i){o(this,"_state");o(this,"pollFrequency",E.seconds(30));o(this,"client");o(this,"name");o(this,"interval");o(this,"clientVersion");o(this,"onChangeHandlers",[]);o(this,"versionWarned",!1);this._state={...ls},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(He.ENDPOINT,{},s.z.object({}),ch);if(i!=null)throw i;const a=n.nodeVersion,c=this.clientVersion,l=this.versionWarned;a==null?(this._state.clientServerCompatible=!1,l||(console.warn(us(null,c,!0)),this.versionWarned=!0)):ts.versionsEqual(c,a,{checkMajor:!0,checkMinor:!0,checkPatch:!1})?this._state.clientServerCompatible=!0:(this._state.clientServerCompatible=!1,l||(console.warn(us(a,c,ts.semVerNewer(c,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)}};o(He,"ENDPOINT","/connectivity/check"),o(He,"DEFAULT",ls),o(He,"connectionStateZ",xi);let kt=He;const lh=Object.freeze(Object.defineProperty({__proto__:null,Checker:kt,state:xi,status:Ri},Symbol.toStringTag,{value:"Module"})),uh=s.z.object({keys:Ee.array().optional(),bounds:W.z,names:s.z.string().array().optional()}),hh=s.z.object({}),yh="/frame/delete";class dh{constructor(e){o(this,"client");this.client=e}async delete(e){await w(this.client,yh,e,uh,hh)}}const hs=r=>{const e=T(r);return e.length===0?null:typeof e[0]=="number"||!isNaN(parseInt(e[0]))?"key":"name"},ys=(r,e)=>{const t=T(r);if(t.length===e.length)return;const n=hs(r);throw hs===null?new M("[Frame] - channel keys or names must be provided when constructing a frame."):new M(`[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=[]){o(this,"columns",[]);o(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,...T(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(c=>Ci(c));ys(i.keys,a),i.keys.forEach((c,l)=>this.push(c,a[l]))}else Object.entries(e).forEach(([i,a])=>{const c=parseInt(i);if(isNaN(c))this.push(i,...T(a));else return this.push(c,...T(a))});return}if(Array.isArray(e)||["string","number"].includes(typeof e)){const i=T(t),a=T(e);ys(a,i),i.forEach((c,l)=>this.push(a[l],c));return}throw new M(`[Frame] - invalid frame construction parameters. data parameter ust be a frame
|
|
@@ -43,9 +43,9 @@
|
|
|
43
43
|
Received an array of channel names or keys but no series.
|
|
44
44
|
`);if(!Array.isArray(t))throw new M(`
|
|
45
45
|
Received an array of channel names or keys but no array of series.
|
|
46
|
-
`);const c=[],l=[];for(let u=0;u<e.length;u++){const
|
|
46
|
+
`);const c=[],l=[];for(let u=0;u<e.length;u++){const h=await this.fetchChannel(e[u]);if(u>=t.length)throw new M(`
|
|
47
47
|
Received an array of channel names or keys but not enough series.
|
|
48
|
-
`);const d=new be({data:t[u],dataType:
|
|
48
|
+
`);const d=new be({data:t[u],dataType:h.dataType});c.push(h.key),l.push(d)}return new _(c,l)}if(e instanceof _||e instanceof Map){const c=new _(e);if(this.adapter==null)return c;let l=[];return l=c.columns.map(u=>{var d;const h=typeof u=="string"?(d=this.adapter)==null?void 0:d.get(u):u;if(h==null)throw new M(`
|
|
49
49
|
Channel ${u} was not provided in the list of channels when opening the writer
|
|
50
|
-
`);return
|
|
51
|
-
Please report this error to the Synnax team. ${JSON.stringify(e)}`),t!=null){if(Oe.matches(t))return;throw t}}}closeSend(){this.stream.closeSend()}send(e){const t=this.stream.send(e);if(t!=null)throw t}}const an=new E(-1);var wn=(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))(wn||{}),Di=(r=>(r[r.None=0]="None",r[r.Ack=1]="Ack",r[r.Data=2]="Data",r))(Di||{});const fh=s.z.object({command:s.z.nativeEnum(wn),span:E.z.optional(),bounds:W.z.optional(),stamp:S.z.optional(),keys:s.z.number().array().optional(),chunkSize:s.z.number().optional()}),ph=s.z.object({variant:s.z.nativeEnum(Di),ack:s.z.boolean(),command:s.z.nativeEnum(wn),error:Rt.optional().nullable(),frame:Or.optional()}),zt=class zt{constructor(e,t){o(this,"stream");o(this,"adapter");o(this,"value");this.stream=new mn("Iterator",e),this.value=new _,this.adapter=t}static async _open(e,t,n,i,a={}){const c=await zr.open(n,t),l=await i.stream(zt.ENDPOINT,fh,ph),u=new zt(l,c);return await u.execute({command:0,keys:c.keys,bounds:new W(e),chunkSize:a.chunkSize??1e5}),u}async next(e=an){return await this.execute({command:1,span:new E(e)})}async prev(e=an){return await this.execute({command:2,span:new E(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 S(e)})}async seekGE(e){return await this.execute({command:6,stamp:new S(e)})}async valid(){return await this.execute({command:7})}async close(){await this.stream.closeAndAck()}[Symbol.asyncIterator](){return new gh(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)))}}};o(zt,"ENDPOINT","/frame/iterate");let hr=zt;class gh{constructor(e){o(this,"iter");o(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 mh=s.z.object({keys:s.z.number().array(),downsampleFactor:s.z.number()}),wh=s.z.object({frame:Or,error:Rt.optional().nullable()}),bh="/frame/stream";class Er{constructor(e,t){o(this,"stream");o(this,"adapter");o(this,"downsampleFactor");this.stream=new mn("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 zr.open(e,n),c=await t.stream(bh,mh,wh),l=new Er(c,a);c.send({keys:a.keys,downsampleFactor:i??1});const[,u]=await c.receive();if(u!=null)throw u;return l}async next(){try{return{done:!1,value:await this.read()}}catch(e){if(Oe.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 Bt extends xe.Observer{constructor(t,n){super(n);o(this,"streamer");o(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 bn=(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))(bn||{}),rt=(r=>(r[r.PersistStream=1]="PersistStream",r[r.Persist=2]="Persist",r[r.Stream=3]="Stream",r))(rt||{});const Th=r=>{switch(r){case"persist":return 2;case"stream":return 3;case"persistStream":return 1;default:if(typeof r=="number"&&r in rt)return r;throw new Error(`invalid writer mode: ${r}`)}},vh=new E(-1),Oh=s.z.object({start:S.z.optional(),controlSubject:et.subjectZ.optional(),keys:s.z.number().array().optional(),authorities:et.Authority.z.array().optional(),mode:s.z.nativeEnum(rt).optional(),errOnUnauthorized:s.z.boolean().optional(),enableAutoCommit:s.z.boolean().optional(),autoIndexPersistInterval:E.z.optional()}),zh=s.z.object({command:s.z.nativeEnum(bn),config:Oh.optional(),frame:Or.optional()}),Eh=s.z.object({ack:s.z.boolean(),command:s.z.nativeEnum(bn),error:Rt.optional().nullable()});var Te;let ji=(Te=class{constructor(e,t){o(this,"stream");o(this,"adapter");this.stream=new mn("Writer",e),this.adapter=t}static async _open(e,t,{channels:n,start:i=S.now(),authorities:a=et.Authority.Absolute,controlSubject:c,mode:l=1,errOnUnauthorized:u=!1,enableAutoCommit:y=!1,autoIndexPersistInterval:d=E.SECOND}){const h=await gn.open(e,n),D=await t.stream(Te.ENDPOINT,zh,Eh),P=new Te(D,h);return await P.execute({command:0,config:{start:new S(i),keys:h.keys,controlSubject:c,authorities:T(a),mode:Th(l),errOnUnauthorized:u,enableAutoCommit:y,autoIndexPersistInterval:d}}),P}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={keys:[],authorities:[]};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(c=>Number(c)),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?un(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()}},o(Te,"ENDPOINT","/frame/write"),Te);const Mi="framer",Sh=r=>new b({type:Mi,key:r.toString()});let Bi=class{constructor(e,t,n){o(this,"streamClient");o(this,"retriever");o(this,"deleter");this.streamClient=e,this.retriever=n,this.deleter=new dh(t)}async openIterator(e,t,n){return await hr._open(e,t,this.retriever,this.streamClient,n)}async openWriter(e){return(Array.isArray(e)||typeof e!="object")&&(e={channels:e}),await ji._open(this.retriever,this.streamClient,e)}async openStreamer(e){return(Array.isArray(e)||typeof e!="object")&&(e={channels:e,downsampleFactor:1}),await Er._open(this.retriever,this.streamClient,e)}async write(e,t,n){if(n==null){const a=t,c=await this.openWriter({start:e,channels:Object.keys(a),mode:rt.Persist});try{await c.write(a),await c.commit()}finally{await c.close()}return}const i=await this.openWriter({start:e,channels:t,mode:rt.Persist,errOnUnauthorized:!0,enableAutoCommit:!0,autoIndexPersistInterval:E.MAX});try{await i.write(t,n)}finally{await i.close()}}async read(e,t){const{single:n}=me(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}=me(e);return i==="keys"?await this.deleter.delete({keys:n,bounds:t}):await this.deleter.delete({names:n,bounds:t})}};const Nh=Object.freeze(Object.defineProperty({__proto__:null,ALWAYS_INDEX_PERSIST_ON_AUTO_COMMIT:vh,AUTO_SPAN:an,Client:Bi,Frame:_,Iterator:hr,ONTOLOGY_TYPE:Mi,ObservableStreamer:Bt,Streamer:Er,Writer:ji,WriterMode:rt,frameZ:Or,ontologyID:Sh,seriesFromPayload:Ci,seriesToPayload:Pi},Symbol.toStringTag,{value:"Module"})),Ih=et.Authority,kh=et.stateZ(s.z.number()),Ah=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 Ui extends Bt{constructor(t){super(t,n=>{const i=this.codec.decode(n.series[0].buffer);return this.merge(i),[i.transfers,!0]});o(this,"states");o(this,"codec");this.states=new Map,this.codec=new nt.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 $h="sy_node_1_control";let Zi=class{constructor(e){o(this,"framer");this.framer=e}async openStateTracker(){const e=await this.framer.openStreamer($h);return new Ui(e)}};const Rh=Object.freeze(Object.defineProperty({__proto__:null,Authority:Ih,Client:Zi,StateTracker:Ui,stateZ:kh,transferString:Ah},Symbol.toStringTag,{value:"Module"}));let Li=class{constructor(e,t,n){o(this,"tasks");o(this,"racks");o(this,"devices");this.tasks=e,this.racks=t,this.devices=n}};const xh=Object.freeze(Object.defineProperty({__proto__:null,Client:Li},Symbol.toStringTag,{value:"Module"})),it=s.z.number(),Sr=s.z.object({key:it,name:s.z.string()}),_i=Sr.partial({key:!0}),Yi="rack",Ch=r=>new b({type:Yi,key:r.toString()}),Nr=s.z.string(),Ut=s.z.object({key:Nr,rack:it,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===""?{}:nt.JSON_CODEC.decodeString(r)))}),qi=Ut.extend({properties:s.z.unknown().transform(r=>nt.JSON_CODEC.encodeString(r))}),Wi="device",Ph=r=>new b({type:Wi,key:r.toString()}),Pe=async(r,e,t,n)=>{const i=await r.openStreamer([e,t]),a=c=>{const l=[];return t!=null&&l.push(...c.get(t).series.flatMap(u=>n("delete",u))),e!=null&&l.push(...c.get(e).series.flatMap(u=>n("set",u))),[l,l.length>0]};return new Bt(i,a)},Dh=Object.freeze(Object.defineProperty({__proto__:null,openObservable:Pe},Symbol.toStringTag,{value:"Module"})),jh="sy_device_set",Mh="sy_device_delete",Zr="/hardware/device/retrieve",Bh="/hardware/device/create",Uh="/hardware/device/delete",Zh=s.z.object({devices:qi.array()}),Lh=s.z.object({devices:Ut.array()}),_h=s.z.object({keys:Nr.array()}),Yh=s.z.object({}),Lr=s.z.object({search:s.z.string().optional(),limit:s.z.number().optional(),offset:s.z.number().optional(),keys:Nr.array().optional(),names:s.z.string().array().optional(),makes:s.z.string().array().optional()}),_r=s.z.object({devices:ee(Ut)});let Gi=class{constructor(e,t){o(this,"type","device");o(this,"client");o(this,"frameClient");this.client=e,this.frameClient=t}async retrieve(e,t){const n=!Array.isArray(e),i=await w(this.client,Zr,{keys:T(e),...t},Lr,_r);return vr("Device",e,i.devices,n),n?i.devices[0]:i.devices}async search(e,t){return(await w(this.client,Zr,{search:e,...t},Lr,_r)).devices}async page(e,t,n){return(await w(this.client,Zr,{offset:e,limit:t,...n},Lr,_r)).devices}async create(e){const t=!Array.isArray(e),n=await w(this.client,Bh,{devices:T(e)},Zh,Lh);return t?n.devices[0]:n.devices}async delete(e){await w(this.client,Uh,{keys:T(e)},_h,Yh)}async openDeviceTracker(){return await Pe(this.frameClient,jh,Mh,qh)}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 qh=(r,e)=>r==="delete"?e.toStrings().map(t=>({variant:r,key:t,value:void 0})):e.parseJSON(Ut).map(t=>({variant:r,key:t.key,value:t})),Wh=Object.freeze(Object.defineProperty({__proto__:null,Client:Gi,ONTOLOGY_TYPE:Wi,deviceKeyZ:Nr,deviceZ:Ut,newDeviceZ:qi,ontologyID:Ph},Symbol.toStringTag,{value:"Module"})),Yr="/hardware/rack/retrieve",Gh="/hardware/rack/create",Fh="/hardware/rack/delete",qr=s.z.object({keys:it.array().optional(),names:s.z.string().array().optional(),search:s.z.string().optional(),offset:s.z.number().optional(),limit:s.z.number().optional()}),Wr=s.z.object({racks:ee(Sr)}),Vh=s.z.object({racks:_i.array()}),Kh=s.z.object({racks:Sr.array()}),Jh=s.z.object({keys:it.array()}),Hh=s.z.object({});let Fi=class{constructor(e,t,n){o(this,"type","rack");o(this,"client");o(this,"frameClient");o(this,"tasks");this.client=e,this.frameClient=t,this.tasks=n}async delete(e){await w(this.client,Fh,{keys:T(e)},Jh,Hh)}async create(e){const t=!Array.isArray(e),n=await w(this.client,Gh,{racks:T(e)},Vh,Kh),i=this.sugar(n.racks);return t?i[0]:i}async search(e){const t=await w(this.client,Yr,{search:e},qr,Wr);return this.sugar(t.racks)}async page(e,t){const n=await w(this.client,Yr,{offset:e,limit:t},qr,Wr);return this.sugar(n.racks)}async retrieve(e){const{variant:t,normalized:n,single:i}=Tr(e,{string:"names",number:"keys"}),a=await w(this.client,Yr,{[t]:n},qr,Wr),c=this.sugar(a.racks);return vr("Rack",e,c,i),i?c[0]:c}sugar(e){return e.map(({key:t,name:n})=>new Vi(t,n,this.tasks))}};class Vi{constructor(e,t,n){o(this,"key");o(this,"name");o(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 Xh=Object.freeze(Object.defineProperty({__proto__:null,Client:Fi,ONTOLOGY_TYPE:Yi,Rack:Vi,newRackZ:_i,ontologyID:Ch,rackKeyZ:it,rackZ:Sr},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())]),At=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())}),Zt=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===""?{}:nt.JSON_CODEC.decodeString(r))),state:At.optional().nullable(),snapshot:s.z.boolean().optional()}),Ki=Zt.omit({key:!0}).extend({key:De.transform(r=>r.toString()).optional(),config:s.z.unknown().transform(r=>nt.JSON_CODEC.encodeString(r))}),Qh=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)))}),Ji="task",ey=r=>new b({type:Ji,key:r.toString()}),Ot="sy_task_state",ds="sy_task_cmd",Ft=new Error("Task not created");class Hi{constructor(e,t,n,i,a=!1,c=!1,l,u=null,y=null,d=null){o(this,"key");o(this,"name");o(this,"internal");o(this,"type");o(this,"config");o(this,"snapshot");o(this,"state");o(this,"frameClient");o(this,"ontologyClient");o(this,"rangeClient");this.key=e,this.name=t,this.type=n,this.config=i,this.internal=a,this.snapshot=c,l!==null&&(this.state=l),this.frameClient=u,this.ontologyClient=y,this.rangeClient=d}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 b({type:"task",key:this.key})}async executeCommand(e,t){if(this.frameClient==null)throw Ft;const n=await this.frameClient.openWriter(ds),i=tl.id();return await n.write(ds,[{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(Ot),a=await this.executeCommand(e,t);let c;const l=new Promise(u=>setTimeout(()=>u(!1),new E(n).milliseconds));for(;;){const u=await Promise.any([i.read(),l]);if(u===!1)throw new Error("Command timed out");const y=At.safeParse(u.at(-1).sy_task_state);if(y.success){if(c=y.data,c.key===a)break}else console.error(y.error)}return i.close(),c}async openStateObserver(){if(this.frameClient==null)throw Ft;return new Bt(await this.frameClient.openStreamer(Ot),e=>{const t=e.get(Ot);if(t.length===0)return[null,!1];const n=At.safeParse(t.at(-1));if(!n.success)return[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 ty=s.z.object({rack:it.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()}),ry=s.z.object({tasks:ee(Zt)}),ny="/hardware/task/retrieve",sy="/hardware/task/create",iy="/hardware/task/delete",ay="/hardware/task/copy",oy=s.z.object({tasks:Ki.array()}),cy=s.z.object({tasks:Zt.array()}),ly=s.z.object({keys:De.array()}),uy=s.z.object({}),hy=s.z.object({key:De,name:s.z.string(),snapshot:s.z.boolean()}),yy=s.z.object({task:Zt});let Xi=class{constructor(e,t,n,i){o(this,"type","task");o(this,"client");o(this,"frameClient");o(this,"ontologyClient");o(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,sy,{tasks:T(e)},oy,cy),i=this.sugar(n.tasks);return t?i[0]:i}async delete(e){await w(this.client,iy,{keys:T(e)},ly,uy)}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}=Tr(e,{number:"rack",string:"keys"},{convertNumericStrings:!1}),c={...t};a==="rack"?c.rack=e:c.keys=i;const l=await this.execRetrieve(c),u=this.sugar(l);return n&&a!=="rack"?u[0]:u}async copy(e,t,n){const i=await w(this.client,ay,{key:e,name:t,snapshot:n},hy,yy);return this.sugar([i.task])[0]}async retrieveByName(e,t){const n=await this.execRetrieve({names:[e],rack:t});return vr("Task",e,n,!0),this.sugar(n)[0]}async execRetrieve(e){return(await w(this.client,ny,e,ty,ry)).tasks}sugar(e){return e.map(({key:t,name:n,type:i,config:a,state:c,internal:l,snapshot:u})=>new Hi(t,n,i,a,l,u,c,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 Bt(await this.frameClient.openStreamer(Ot),e=>{const t=e.get(Ot);if(t.length===0)return[null,!1];const n=At.safeParse(t.at(-1));return n.success?[n.data,!0]:[null,!1]})}};const dy=Object.freeze(Object.defineProperty({__proto__:null,Client:Xi,ONTOLOGY_TYPE:Ji,Task:Hi,commandZ:Qh,newTaskZ:Ki,ontologyID:ey,stateZ:At,taskKeyZ:De,taskZ:Zt},Symbol.toStringTag,{value:"Module"})),at=s.z.string().uuid(),Lt=s.z.object({key:at,name:s.z.string().min(1),color:s.z.string()}),Qi="label",fy=r=>new b({type:Qi,key:r}),py=s.z.object({keys:at.array().optional(),for:J.optional(),search:s.z.string().optional(),offset:s.z.number().optional(),limit:s.z.number().optional()}),gy=s.z.object({labels:ee(Lt)});var Ae;let ea=(Ae=class{constructor(e){o(this,"client");this.client=e}async retrieve(e){const t=T(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(Ae.ENDPOINT,e,py,gy);if(n!=null)throw n;return t.labels}},o(Ae,"ENDPOINT","/label/retrieve"),Ae);const ta=Lt.extend({key:at.optional()}),my=s.z.object({labels:ta.array()}),wy=s.z.object({labels:Lt.array()}),by=s.z.object({keys:at.array()}),ra=s.z.object({id:J,labels:at.array(),replace:s.z.boolean().optional()}),Ty=ra.omit({replace:!0}),Gr=s.z.object({}),vy="/label/create",Oy="/label/delete",zy="/label/set",Ey="/label/remove";let na=class{constructor(e){o(this,"client");this.client=e}async create(e){return(await w(this.client,vy,{labels:T(e)},my,wy)).labels}async delete(e){await w(this.client,Oy,{keys:T(e)},by,Gr)}async set(e,t,{replace:n}={}){await w(this.client,zy,{id:e,labels:t,replace:n},ra,Gr)}async remove(e,t){await w(this.client,Ey,{id:e,labels:t},Ty,Gr)}};const Sy="sy_label_set",Ny="sy_label_delete";let sa=class{constructor(e,t,n){o(this,"type","label");o(this,"retriever");o(this,"writer");o(this,"frameClient");o(this,"ontology");this.writer=new na(e),this.retriever=new ea(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 b(e))}async label(e,t,n={}){await this.writer.set(new b(e),t,n)}async removeLabels(e,t){await this.writer.remove(new b(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,Sy,Ny,Iy)}async trackLabelsOf(e){const t=new xe.Observer,n=(await this.retrieveFor(e)).map(a=>({id:new b({key:a.key,type:"label"}),key:a.key,name:a.name,data:a}));return(await this.ontology.openDependentTracker({target:new b(e),dependents:n,relationshipType:"labeled_by"})).onChange(a=>t.notify(a.map(c=>{var l,u;return{key:c.id.key,color:(l=c.data)==null?void 0:l.color,name:(u=c.data)==null?void 0:u.name}}))),t}};const Iy=(r,e)=>r==="delete"?e.toUUIDs().map(t=>({variant:r,key:t})):e.parseJSON(Lt).map(t=>({variant:r,key:t.key,value:t})),ky=Object.freeze(Object.defineProperty({__proto__:null,Client:sa,ONTOLOGY_TYPE:Qi,Retriever:ea,Writer:na,keyZ:at,labelZ:Lt,newLabelPayloadZ:ta,ontologyID:fy},Symbol.toStringTag,{value:"Module"})),X=s.z.string().uuid(),_t=s.z.object({key:X,name:s.z.string().min(1),timeRange:W.z,color:s.z.string().optional()}),ia=_t.extend({key:s.z.string().uuid().optional()}),aa=r=>{const e=T(r),t=e.length===0;let n=!1;return t||(n=X.safeParse(e[0]).success),{single:!Array.isArray(r),variant:n?"keys":"names",normalized:e,actual:r,empty:t}},oa="range",ca="range-alias",Ay=r=>new b({type:oa,key:r}),$y=r=>new b({type:ca,key:r}),Ry="sy_range_alias_set",xy="sy_range_alias_delete",Cy=s.z.object({range:X,aliases:s.z.string().array()}),Py=s.z.object({aliases:s.z.record(s.z.string(),Ee)}),Dy=s.z.object({range:X,aliases:s.z.record(Ee.or(s.z.string()),s.z.string())}),jy=s.z.unknown(),My=s.z.object({range:X,channels:Ee.array()}),By=s.z.unknown(),Uy=s.z.object({range:X}),Zy=s.z.object({aliases:s.z.record(s.z.string(),s.z.string())}),ce=class ce{constructor(e,t,n){o(this,"frameClient");o(this,"cache",new Map);o(this,"client");o(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 c=this.cache.get(e);if(c!=null)return c;t.push(e)}else e.forEach(c=>{const l=this.cache.get(c);l!=null?i[c]=l:t.push(c)});if(t.length===0)return i;const a=await w(this.client,ce.RESOLVE_ENDPOINT,{range:this.rangeKey,aliases:t},Cy,Py);return Object.entries(a.aliases).forEach(([c,l])=>this.cache.set(c,l)),n?a.aliases[t[0]]:{...i,...a.aliases}}async set(e){await w(this.client,ce.SET_ENDPOINT,{range:this.rangeKey,aliases:e},Dy,jy)}async list(){return(await w(this.client,ce.LIST_ENDPOINT,{range:this.rangeKey},Uy,Zy)).aliases}async delete(e){await w(this.client,ce.DELETE_ENDPOINT,{range:this.rangeKey,channels:e},My,By)}async openChangeTracker(){return await Pe(this.frameClient,Ry,xy,Yy(this.rangeKey))}};o(ce,"SET_ENDPOINT","/range/alias/set"),o(ce,"RESOLVE_ENDPOINT","/range/alias/resolve"),o(ce,"LIST_ENDPOINT","/range/alias/list"),o(ce,"DELETE_ENDPOINT","/range/alias/delete");let on=ce;const Ly=s.z.object({range:X,channel:Ee,alias:s.z.string()}),_y="---",Yy=r=>(e,t)=>e==="delete"?t.toStrings().filter(n=>n.split(_y)[0]===r).map(n=>({variant:e,key:n,value:void 0})):t.parseJSON(Ly).map(n=>({variant:e,key:n.alias,value:n})),qy=s.z.object({range:X,keys:s.z.string().array()}),Tn=s.z.object({range:X,key:s.z.string(),value:s.z.string()}),Wy=s.z.object({pairs:ee(Tn)}),Gy=s.z.object({range:X,pairs:Tn.array()}),Fy=s.z.object({range:X,keys:s.z.string().array()}),we=class we{constructor(e,t,n){o(this,"rangeKey");o(this,"client");o(this,"frameClient");this.rangeKey=e,this.client=t,this.frameClient=n}async get(e){const t=await w(this.client,we.GET_ENDPOINT,{range:this.rangeKey,keys:T(e)},qy,Wy);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;hn(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,we.SET_ENDPOINT,{range:this.rangeKey,pairs:n},Gy,s.z.unknown())}async delete(e){await w(this.client,we.DELETE_ENDPOINT,{range:this.rangeKey,keys:T(e)},Fy,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(Tn).map(n=>({variant:e,key:`${n.range}${n.key}`,value:n})))}};o(we,"GET_ENDPOINT","/range/kv/get"),o(we,"SET_ENDPOINT","/range/kv/set"),o(we,"DELETE_ENDPOINT","/range/kv/delete");let $t=we;const Fr=r=>new b({type:"range",key:r});class la{constructor(e,t=W.ZERO,n,i,a,c,l,u,y,d,h){o(this,"key");o(this,"name");o(this,"kv");o(this,"timeRange");o(this,"color");o(this,"channels");o(this,"aliaser");o(this,"frameClient");o(this,"labelClient");o(this,"ontologyClient");o(this,"rangeClient");this.key=n,this.name=e,this.timeRange=t,this.frameClient=a,this.color=i,this.kv=c,this.aliaser=l,this.channels=u,this.labelClient=y,this.ontologyClient=d,this.rangeClient=h}get ontologyID(){return new b({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 te(`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(Fr(this.key))}async addLabel(...e){await this.labelClient.label(Fr(this.key),e)}async removeLabel(...e){await this.labelClient.removeLabels(Fr(this.key),e)}async openChildRangeTracker(){const e=new xe.Observer,t=(await this.retrieveChildren()).map(i=>{const a=new b({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 xe.Observer,t=await this.retrieveParent();if(t==null)return null;const n=new b({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(c=>{const l=this.rangeClient.resourcesToRanges(c);if(l.length===0)return;const u=l[0];e.notify(u)}),e.setCloser(async()=>await a.close()),e}}const Vy=s.z.object({keys:X.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()}),Ky="/range/retrieve",Jy=s.z.object({ranges:ee(_t)});let ua=class{constructor(e,t,n,i,a,c){o(this,"type","range");o(this,"frameClient");o(this,"writer");o(this,"unaryClient");o(this,"channels");o(this,"labelClient");o(this,"ontologyClient");this.frameClient=e,this.writer=t,this.unaryClient=n,this.channels=i,this.labelClient=a,this.ontologyClient=c}async create(e,t){const n=!Array.isArray(e),i=this.sugarMany(await this.writer.create(T(e),t));return n?i[0]:i}async rename(e,t){await this.writer.rename(e,t)}async delete(e){await this.writer.delete(T(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:c}=aa(e);if(c)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 ge(`multiple ranges matching ${n} found`);return l[0]}getKV(e){return new $t(e,this.unaryClient,this.frameClient)}async execRetrieve(e){const{ranges:t}=await w(this.unaryClient,Ky,e,Vy,Jy);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 la(e.name,e.timeRange,e.key,e.color,this.frameClient,new $t(e.key,this.unaryClient,this.frameClient),new on(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(_t)).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 Hy=s.z.object({ranges:_t.array()}),Xy=s.z.object({parent:J.optional(),ranges:ia.array()}),Qy=s.z.object({keys:X.array()}),ed=s.z.object({}),td=s.z.object({key:X,name:s.z.string()}),rd=s.z.object({}),nd="/range/create",sd="/range/delete",id="/range/rename";let ha=class{constructor(e){o(this,"client");this.client=e}async rename(e,t){await w(this.client,id,{key:e,name:t},td,rd)}async create(e,t){return(await w(this.client,nd,{ranges:e,...t},Xy,Hy)).ranges}async delete(e){await w(this.client,sd,{keys:e},Qy,ed)}};const ad=Object.freeze(Object.defineProperty({__proto__:null,ALIAS_ONTOLOGY_TYPE:ca,Client:ua,KV:$t,ONTOLOGY_TYPE:oa,Range:la,Writer:ha,analyzeParams:aa,keyZ:X,newPayloadZ:ia,payloadZ:_t,rangeAliasOntologyID:$y,rangeOntologyID:Ay},Symbol.toStringTag,{value:"Module"})),od="/api/v1/";class cd{constructor(e,t=!1){o(this,"url");o(this,"unary");o(this,"stream");o(this,"secure");this.secure=t,this.url=e.child(od);const n=new nt.JSONCodec;this.unary=new Go(this.url,n,this.secure),this.stream=new tc(this.url,n,this.secure)}use(...e){this.unary.use(...e),this.stream.use(...e)}}const Ir=s.z.string().uuid(),kr=s.z.object({key:s.z.string(),name:s.z.string(),data:dn.or(s.z.string().transform(r=>JSON.parse(r)))}),ya="lineplot",ld=r=>new b({type:ya,key:r}),ud=s.z.object({keys:s.z.string().array()}),hd=s.z.object({linePlots:kr.array()});let yd=class{constructor(e){o(this,"ENDPOINT","/workspace/lineplot/retrieve");o(this,"client");this.client=e}async retrieve(e){const t=T(e);return(await w(this.client,this.ENDPOINT,{keys:t},ud,hd)).linePlots}};const Se=s.z.string().uuid(),da=r=>JSON.parse(r),vn=s.z.object({name:s.z.string(),key:Se,layout:dn.or(s.z.string().transform(r=>da(r)))}),On=vn.omit({layout:!0}).extend({layout:s.z.string().transform(r=>da(r))}),fa="workspace",dd=r=>new b({type:fa,key:r}),fd=kr.partial({key:!0}).transform(r=>({...r,data:JSON.stringify(r.data)})),pd=s.z.object({workspace:Se,linePlots:fd.array()}),gd=s.z.object({linePlots:kr.array()}),md=s.z.object({keys:Ir.array()}),wd=s.z.object({}),bd=s.z.object({key:Ir,name:s.z.string()}),Td=s.z.object({}),vd=s.z.object({key:Ir,data:s.z.string()}),Od=s.z.object({}),zd="/workspace/lineplot/create",Ed="/workspace/lineplot/delete",Sd="/workspace/lineplot/rename",Nd="/workspace/lineplot/set-data";let Id=class{constructor(e){o(this,"client");this.client=e}async create(e,t){const n={...t,data:JSON.stringify(t.data)};return(await w(this.client,zd,{workspace:e,linePlots:[n]},pd,gd)).linePlots[0]}async delete(e){const t=T(e);await w(this.client,Ed,{keys:t},md,wd)}async rename(e,t){await w(this.client,Sd,{key:e,name:t},bd,Td)}async setData(e,t){await w(this.client,Nd,{key:e,data:JSON.stringify(t)},vd,Od)}},pa=class{constructor(e){o(this,"writer");o(this,"retriever");this.writer=new Id(e),this.retriever=new yd(e)}async create(e,t){return await this.writer.create(e,t)}async rename(e,t){await this.writer.rename(e,t)}async setData(e,t){await this.writer.setData(e,t)}async retrieve(e){const t=Array.isArray(e),n=await this.retriever.retrieve(e);return t?n:n[0]}async delete(e){await this.writer.delete(e)}};const kd=Object.freeze(Object.defineProperty({__proto__:null,Client:pa,ONTOLOGY_TYPE:ya,keyZ:Ir,linePlotZ:kr,ontologyID:ld},Symbol.toStringTag,{value:"Module"})),Ad=s.z.object({keys:Se.array().optional(),search:s.z.string().optional(),author:s.z.string().uuid().optional(),offset:s.z.number().optional(),limit:s.z.number().optional()}),$d=s.z.object({workspaces:ee(On)});var $e;let Rd=($e=class{constructor(e){o(this,"client");this.client=e}async retrieve(e){const t=T(e);return await this.execute({keys:t})}async retrieveByAuthor(e){return await this.execute({author: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){return(await w(this.client,$e.ENDPOINT,e,Ad,$d)).workspaces}},o($e,"ENDPOINT","/workspace/retrieve"),$e);const Yt=s.z.string().uuid(),ga=s.z.object({key:s.z.string(),name:s.z.string(),data:dn.or(s.z.string().transform(r=>JSON.parse(r))),snapshot:s.z.boolean()}),Ar=s.z.object({key:s.z.string(),name:s.z.string(),snapshot:s.z.boolean(),data:s.z.string().transform(r=>JSON.parse(r))}),ma="schematic",xd=r=>new b({type:ma,key:r}),Cd=s.z.object({keys:s.z.string().array()}),Pd=s.z.object({schematics:Ar.array()});class Dd{constructor(e){o(this,"ENDPOINT","/workspace/schematic/retrieve");o(this,"client");this.client=e}async retrieve(e){return(await w(this.client,this.ENDPOINT,{keys:T(e)},Cd,Pd)).schematics}}const jd=ga.partial({key:!0,snapshot:!0}).transform(r=>({...r,data:JSON.stringify(r.data)})),Md=s.z.object({workspace:Se,schematics:jd.array()}),Bd=s.z.object({schematics:Ar.array()}),Ud=s.z.object({keys:Yt.array()}),Zd=s.z.object({}),Ld=s.z.object({key:Yt,name:s.z.string()}),fs=s.z.object({}),_d=s.z.object({key:Yt,data:s.z.string()});s.z.object({});const Yd=s.z.object({key:Yt,name:s.z.string(),snapshot:s.z.boolean()}),qd=s.z.object({schematic:Ar}),Wd="/workspace/schematic/create",Gd="/workspace/schematic/delete",Fd="/workspace/schematic/rename",Vd="/workspace/schematic/set-data",Kd="/workspace/schematic/copy";let Jd=class{constructor(e){o(this,"client");this.client=e}async create(e,t){const n={...t,data:JSON.stringify(t.data)};return(await w(this.client,Wd,{workspace:e,schematics:[n]},Md,Bd)).schematics[0]}async copy(e,t,n){return(await w(this.client,Kd,{key:e,name:t,snapshot:n},Yd,qd)).schematic}async delete(e){const t=T(e);await w(this.client,Gd,{keys:t},Ud,Zd)}async rename(e,t){await w(this.client,Fd,{key:e,name:t},Ld,fs)}async setData(e,t){await w(this.client,Vd,{key:e,data:JSON.stringify(t)},_d,fs)}},wa=class{constructor(e){o(this,"writer");o(this,"retriever");this.writer=new Jd(e),this.retriever=new Dd(e)}async create(e,t){return await this.writer.create(e,t)}async rename(e,t){await this.writer.rename(e,t)}async setData(e,t){await this.writer.setData(e,t)}async retrieve(e){const t=Array.isArray(e),n=await this.retriever.retrieve(e);return t?n:n[0]}async delete(e){await this.writer.delete(e)}async copy(e,t,n){return await this.writer.copy(e,t,n)}};const Hd=Object.freeze(Object.defineProperty({__proto__:null,Client:wa,ONTOLOGY_TYPE:ma,keyZ:Yt,ontologyID:xd,schematicRemoteZ:Ar,schematicZ:ga},Symbol.toStringTag,{value:"Module"})),Xd=vn.partial({key:!0}).transform(r=>({...r,layout:JSON.stringify(r.layout)})),Qd=s.z.object({workspaces:Xd.array()}),ef=s.z.object({workspaces:On.array()}),tf=s.z.object({keys:Se.array()}),rf=s.z.object({}),nf=s.z.object({key:Se,name:s.z.string()}),sf=s.z.object({}),af=s.z.object({key:Se,layout:s.z.string()}),of=s.z.object({}),cf="/workspace/create",lf="/workspace/delete",uf="/workspace/rename",hf="/workspace/set-layout";class yf{constructor(e){o(this,"client");this.client=e}async create(e){return(await w(this.client,cf,{workspaces:T(e)},Qd,ef)).workspaces}async delete(e){await w(this.client,lf,{keys:T(e)},tf,rf)}async rename(e,t){await w(this.client,uf,{key:e,name:t},nf,sf)}async setLayout(e,t){await w(this.client,hf,{key:e,layout:JSON.stringify(t)},af,of)}}class ba{constructor(e){o(this,"type","workspace");o(this,"schematic");o(this,"linePlot");o(this,"retriever");o(this,"writer");this.schematic=new wa(e),this.linePlot=new pa(e),this.retriever=new Rd(e),this.writer=new yf(e)}async search(e){return await this.retriever.search(e)}async retrieveByAuthor(e){return await this.retriever.retrieveByAuthor(e)}async retrieve(e){const t=Array.isArray(e),n=await this.retriever.retrieve(e);return t?n:n[0]}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 rename(e,t){await this.writer.rename(e,t)}async setLayout(e,t){await this.writer.setLayout(e,t)}async delete(...e){await this.writer.delete(e)}}const df=Object.freeze(Object.defineProperty({__proto__:null,Client:ba,ONTOLOGY_TYPE:fa,keyZ:Se,ontologyID:dd,workspaceRemoteZ:On,workspaceZ:vn},Symbol.toStringTag,{value:"Module"})),Ta=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:E.z.default(E.seconds(30)),secure:s.z.boolean().optional().default(!1),name:s.z.string().optional()});class va extends Bi{constructor(t){const n=Ta.parse(t),{host:i,port:a,username:c,password:l,connectivityPollFrequency:u,secure:y}=n,d=new cd(new vl({host:i,port:Number(a)}),y);d.use(Cl);let h;c!=null&&l!=null&&(h=new ah(d.unary,{username:c,password:l}),d.use(h.middleware()));const D=new fn(new It(d.unary)),P=new Ii(d.unary,D);super(d.stream,d.unary,D);o(this,"createdAt");o(this,"props");o(this,"ranges");o(this,"channels");o(this,"auth");o(this,"user");o(this,"access");o(this,"connectivity");o(this,"ontology");o(this,"workspaces");o(this,"labels");o(this,"hardware");o(this,"control");o(this,"transport");o(this,"clientVersion","0.31.1");this.createdAt=S.now(),this.props=n,this.auth=h,this.transport=d,this.channels=new Ni(this,D,d.unary,P),this.connectivity=new kt(d.unary,u,this.clientVersion,n.name),this.control=new Zi(this),this.ontology=new pi(d.unary,this);const Q=new ha(this.transport.unary);this.labels=new sa(this.transport.unary,this,this.ontology),this.ranges=new ua(this,Q,this.transport.unary,D,this.labels,this.ontology),this.access=new Ti(this.transport.unary),this.user=new $i(this.transport.unary),this.workspaces=new ba(this.transport.unary);const B=new Gi(this.transport.unary,this),zn=new Xi(this.transport.unary,this,this.ontology,this.ranges),Oa=new Fi(this.transport.unary,this,zn);this.hardware=new Li(zn,Oa,B)}get key(){return this.createdAt.valueOf().toString()}close(){this.connectivity.stopChecking()}}o(va,"connectivity",kt);const ff=et.Authority;exports.AuthError=Ce;exports.Authority=ff;exports.Channel=pn;exports.ContiguityError=nn;exports.DataType=z;exports.Density=V;exports.Frame=_;exports.MultiSeries=ni;exports.MultipleFoundError=ge;exports.NotFoundError=pe;exports.QueryError=te;exports.Rate=mr;exports.RouteError=Nt;exports.Series=be;exports.Synnax=va;exports.TimeRange=W;exports.TimeSpan=E;exports.TimeStamp=S;exports.UnexpectedError=ve;exports.ValidationError=M;exports.access=yu;exports.channel=Pu;exports.connection=lh;exports.control=Rh;exports.device=Wh;exports.framer=Nh;exports.hardware=xh;exports.label=ky;exports.linePlot=kd;exports.ontology=Hl;exports.policy=hu;exports.rack=Xh;exports.ranger=ad;exports.schematic=Hd;exports.signals=Dh;exports.synnaxPropsZ=Ta;exports.task=dy;exports.user=Qu;exports.workspace=df;
|
|
50
|
+
`);return h}),new _(l,c.series)}const n=[],i=[],a=Object.entries(e);for(let c=0;c<a.length;c++){const[l,u]=a[c],h=await this.fetchChannel(l),d=new be({data:u,dataType:h.dataType});n.push(h.key),i.push(d)}return new _(n,i)}}class mn{constructor(e,t){o(this,"name");o(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(Oe.matches(t))return;throw t}}}closeSend(){this.stream.closeSend()}send(e){const t=this.stream.send(e);if(t!=null)throw t}}const an=new E(-1);var wn=(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))(wn||{}),Di=(r=>(r[r.None=0]="None",r[r.Ack=1]="Ack",r[r.Data=2]="Data",r))(Di||{});const fh=s.z.object({command:s.z.nativeEnum(wn),span:E.z.optional(),bounds:W.z.optional(),stamp:S.z.optional(),keys:s.z.number().array().optional(),chunkSize:s.z.number().optional()}),ph=s.z.object({variant:s.z.nativeEnum(Di),ack:s.z.boolean(),command:s.z.nativeEnum(wn),error:Rt.optional().nullable(),frame:Or.optional()}),zt=class zt{constructor(e,t){o(this,"stream");o(this,"adapter");o(this,"value");this.stream=new mn("Iterator",e),this.value=new _,this.adapter=t}static async _open(e,t,n,i,a={}){const c=await zr.open(n,t),l=await i.stream(zt.ENDPOINT,fh,ph),u=new zt(l,c);return await u.execute({command:0,keys:c.keys,bounds:new W(e),chunkSize:a.chunkSize??1e5}),u}async next(e=an){return await this.execute({command:1,span:new E(e)})}async prev(e=an){return await this.execute({command:2,span:new E(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 S(e)})}async seekGE(e){return await this.execute({command:6,stamp:new S(e)})}async valid(){return await this.execute({command:7})}async close(){await this.stream.closeAndAck()}[Symbol.asyncIterator](){return new gh(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)))}}};o(zt,"ENDPOINT","/frame/iterate");let hr=zt;class gh{constructor(e){o(this,"iter");o(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 mh=s.z.object({keys:s.z.number().array(),downsampleFactor:s.z.number()}),wh=s.z.object({frame:Or,error:Rt.optional().nullable()}),bh="/frame/stream";class Er{constructor(e,t){o(this,"stream");o(this,"adapter");o(this,"downsampleFactor");this.stream=new mn("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 zr.open(e,n),c=await t.stream(bh,mh,wh),l=new Er(c,a);c.send({keys:a.keys,downsampleFactor:i??1});const[,u]=await c.receive();if(u!=null)throw u;return l}async next(){try{return{done:!1,value:await this.read()}}catch(e){if(Oe.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 Bt extends xe.Observer{constructor(t,n){super(n);o(this,"streamer");o(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 bn=(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))(bn||{}),rt=(r=>(r[r.PersistStream=1]="PersistStream",r[r.Persist=2]="Persist",r[r.Stream=3]="Stream",r))(rt||{});const Th=r=>{switch(r){case"persist":return 2;case"stream":return 3;case"persistStream":return 1;default:if(typeof r=="number"&&r in rt)return r;throw new Error(`invalid writer mode: ${r}`)}},vh=new E(-1),Oh=s.z.object({start:S.z.optional(),controlSubject:et.subjectZ.optional(),keys:s.z.number().array().optional(),authorities:et.Authority.z.array().optional(),mode:s.z.nativeEnum(rt).optional(),errOnUnauthorized:s.z.boolean().optional(),enableAutoCommit:s.z.boolean().optional(),autoIndexPersistInterval:E.z.optional()}),zh=s.z.object({command:s.z.nativeEnum(bn),config:Oh.optional(),frame:Or.optional()}),Eh=s.z.object({ack:s.z.boolean(),command:s.z.nativeEnum(bn),error:Rt.optional().nullable()});var Te;let ji=(Te=class{constructor(e,t){o(this,"stream");o(this,"adapter");this.stream=new mn("Writer",e),this.adapter=t}static async _open(e,t,{channels:n,start:i=S.now(),authorities:a=et.Authority.Absolute,controlSubject:c,mode:l=1,errOnUnauthorized:u=!1,enableAutoCommit:h=!1,autoIndexPersistInterval:d=E.SECOND}){const y=await gn.open(e,n),P=await t.stream(Te.ENDPOINT,zh,Eh),D=new Te(P,y);return await D.execute({command:0,config:{start:new S(i),keys:y.keys,controlSubject:c,authorities:T(a),mode:Th(l),errOnUnauthorized:u,enableAutoCommit:h,autoIndexPersistInterval:d}}),D}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={keys:[],authorities:[]};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(c=>Number(c)),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?un(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()}},o(Te,"ENDPOINT","/frame/write"),Te);const Mi="framer",Sh=r=>new b({type:Mi,key:r.toString()});let Bi=class{constructor(e,t,n){o(this,"streamClient");o(this,"retriever");o(this,"deleter");this.streamClient=e,this.retriever=n,this.deleter=new dh(t)}async openIterator(e,t,n){return await hr._open(e,t,this.retriever,this.streamClient,n)}async openWriter(e){return(Array.isArray(e)||typeof e!="object")&&(e={channels:e}),await ji._open(this.retriever,this.streamClient,e)}async openStreamer(e){return(Array.isArray(e)||typeof e!="object")&&(e={channels:e,downsampleFactor:1}),await Er._open(this.retriever,this.streamClient,e)}async write(e,t,n){if(n==null){const a=t,c=await this.openWriter({start:e,channels:Object.keys(a),mode:rt.Persist});try{await c.write(a),await c.commit()}finally{await c.close()}return}const i=await this.openWriter({start:e,channels:t,mode:rt.Persist,errOnUnauthorized:!0,enableAutoCommit:!0,autoIndexPersistInterval:E.MAX});try{await i.write(t,n)}finally{await i.close()}}async read(e,t){const{single:n}=me(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}=me(e);return i==="keys"?await this.deleter.delete({keys:n,bounds:t}):await this.deleter.delete({names:n,bounds:t})}};const Nh=Object.freeze(Object.defineProperty({__proto__:null,ALWAYS_INDEX_PERSIST_ON_AUTO_COMMIT:vh,AUTO_SPAN:an,Client:Bi,Frame:_,Iterator:hr,ONTOLOGY_TYPE:Mi,ObservableStreamer:Bt,Streamer:Er,Writer:ji,WriterMode:rt,frameZ:Or,ontologyID:Sh,seriesFromPayload:Ci,seriesToPayload:Pi},Symbol.toStringTag,{value:"Module"})),Ih=et.Authority,kh=et.stateZ(s.z.number()),Ah=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 Ui extends Bt{constructor(t){super(t,n=>{const i=this.codec.decode(n.series[0].buffer);return this.merge(i),[i.transfers,!0]});o(this,"states");o(this,"codec");this.states=new Map,this.codec=new nt.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 $h="sy_node_1_control";let Zi=class{constructor(e){o(this,"framer");this.framer=e}async openStateTracker(){const e=await this.framer.openStreamer($h);return new Ui(e)}};const Rh=Object.freeze(Object.defineProperty({__proto__:null,Authority:Ih,Client:Zi,StateTracker:Ui,stateZ:kh,transferString:Ah},Symbol.toStringTag,{value:"Module"}));let Li=class{constructor(e,t,n){o(this,"tasks");o(this,"racks");o(this,"devices");this.tasks=e,this.racks=t,this.devices=n}};const xh=Object.freeze(Object.defineProperty({__proto__:null,Client:Li},Symbol.toStringTag,{value:"Module"})),it=s.z.number(),Sr=s.z.object({key:it,name:s.z.string()}),_i=Sr.partial({key:!0}),Yi="rack",Ch=r=>new b({type:Yi,key:r.toString()}),Nr=s.z.string(),Ut=s.z.object({key:Nr,rack:it,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===""?{}:nt.JSON_CODEC.decodeString(r)))}),qi=Ut.extend({properties:s.z.unknown().transform(r=>nt.JSON_CODEC.encodeString(r))}),Wi="device",Ph=r=>new b({type:Wi,key:r.toString()}),Pe=async(r,e,t,n)=>{const i=await r.openStreamer([e,t]),a=c=>{const l=[];return t!=null&&l.push(...c.get(t).series.flatMap(u=>n("delete",u))),e!=null&&l.push(...c.get(e).series.flatMap(u=>n("set",u))),[l,l.length>0]};return new Bt(i,a)},Dh=Object.freeze(Object.defineProperty({__proto__:null,openObservable:Pe},Symbol.toStringTag,{value:"Module"})),jh="sy_device_set",Mh="sy_device_delete",Zr="/hardware/device/retrieve",Bh="/hardware/device/create",Uh="/hardware/device/delete",Zh=s.z.object({devices:qi.array()}),Lh=s.z.object({devices:Ut.array()}),_h=s.z.object({keys:Nr.array()}),Yh=s.z.object({}),Lr=s.z.object({search:s.z.string().optional(),limit:s.z.number().optional(),offset:s.z.number().optional(),keys:Nr.array().optional(),names:s.z.string().array().optional(),makes:s.z.string().array().optional()}),_r=s.z.object({devices:ee(Ut)});let Gi=class{constructor(e,t){o(this,"type","device");o(this,"client");o(this,"frameClient");this.client=e,this.frameClient=t}async retrieve(e,t){const n=!Array.isArray(e),i=await w(this.client,Zr,{keys:T(e),...t},Lr,_r);return vr("Device",e,i.devices,n),n?i.devices[0]:i.devices}async search(e,t){return(await w(this.client,Zr,{search:e,...t},Lr,_r)).devices}async page(e,t,n){return(await w(this.client,Zr,{offset:e,limit:t,...n},Lr,_r)).devices}async create(e){const t=!Array.isArray(e),n=await w(this.client,Bh,{devices:T(e)},Zh,Lh);return t?n.devices[0]:n.devices}async delete(e){await w(this.client,Uh,{keys:T(e)},_h,Yh)}async openDeviceTracker(){return await Pe(this.frameClient,jh,Mh,qh)}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 qh=(r,e)=>r==="delete"?e.toStrings().map(t=>({variant:r,key:t,value:void 0})):e.parseJSON(Ut).map(t=>({variant:r,key:t.key,value:t})),Wh=Object.freeze(Object.defineProperty({__proto__:null,Client:Gi,ONTOLOGY_TYPE:Wi,deviceKeyZ:Nr,deviceZ:Ut,newDeviceZ:qi,ontologyID:Ph},Symbol.toStringTag,{value:"Module"})),Yr="/hardware/rack/retrieve",Gh="/hardware/rack/create",Fh="/hardware/rack/delete",qr=s.z.object({keys:it.array().optional(),names:s.z.string().array().optional(),search:s.z.string().optional(),offset:s.z.number().optional(),limit:s.z.number().optional()}),Wr=s.z.object({racks:ee(Sr)}),Vh=s.z.object({racks:_i.array()}),Kh=s.z.object({racks:Sr.array()}),Jh=s.z.object({keys:it.array()}),Hh=s.z.object({});let Fi=class{constructor(e,t,n){o(this,"type","rack");o(this,"client");o(this,"frameClient");o(this,"tasks");this.client=e,this.frameClient=t,this.tasks=n}async delete(e){await w(this.client,Fh,{keys:T(e)},Jh,Hh)}async create(e){const t=!Array.isArray(e),n=await w(this.client,Gh,{racks:T(e)},Vh,Kh),i=this.sugar(n.racks);return t?i[0]:i}async search(e){const t=await w(this.client,Yr,{search:e},qr,Wr);return this.sugar(t.racks)}async page(e,t){const n=await w(this.client,Yr,{offset:e,limit:t},qr,Wr);return this.sugar(n.racks)}async retrieve(e){const{variant:t,normalized:n,single:i}=Tr(e,{string:"names",number:"keys"}),a=await w(this.client,Yr,{[t]:n},qr,Wr),c=this.sugar(a.racks);return vr("Rack",e,c,i),i?c[0]:c}sugar(e){return e.map(({key:t,name:n})=>new Vi(t,n,this.tasks))}};class Vi{constructor(e,t,n){o(this,"key");o(this,"name");o(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 Xh=Object.freeze(Object.defineProperty({__proto__:null,Client:Fi,ONTOLOGY_TYPE:Yi,Rack:Vi,newRackZ:_i,ontologyID:Ch,rackKeyZ:it,rackZ:Sr},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())]),At=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())}),Zt=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===""?{}:nt.JSON_CODEC.decodeString(r))),state:At.optional().nullable(),snapshot:s.z.boolean().optional()}),Ki=Zt.omit({key:!0}).extend({key:De.transform(r=>r.toString()).optional(),config:s.z.unknown().transform(r=>nt.JSON_CODEC.encodeString(r))}),Qh=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)))}),Ji="task",ey=r=>new b({type:Ji,key:r.toString()}),Ot="sy_task_state",ds="sy_task_cmd",Ft=new Error("Task not created");class Hi{constructor(e,t,n,i,a=!1,c=!1,l,u=null,h=null,d=null){o(this,"key");o(this,"name");o(this,"internal");o(this,"type");o(this,"config");o(this,"snapshot");o(this,"state");o(this,"frameClient");o(this,"ontologyClient");o(this,"rangeClient");this.key=e,this.name=t,this.type=n,this.config=i,this.internal=a,this.snapshot=c,l!==null&&(this.state=l),this.frameClient=u,this.ontologyClient=h,this.rangeClient=d}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 b({type:"task",key:this.key})}async executeCommand(e,t){if(this.frameClient==null)throw Ft;const n=await this.frameClient.openWriter(ds),i=tl.id();return await n.write(ds,[{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(Ot),a=await this.executeCommand(e,t);let c;const l=new Promise(u=>setTimeout(()=>u(!1),new E(n).milliseconds));for(;;){const u=await Promise.any([i.read(),l]);if(u===!1)throw new Error("Command timed out");const h=At.safeParse(u.at(-1).sy_task_state);if(h.success){if(c=h.data,c.key===a)break}else console.error(h.error)}return i.close(),c}async openStateObserver(){if(this.frameClient==null)throw Ft;return new Bt(await this.frameClient.openStreamer(Ot),e=>{const t=e.get(Ot);if(t.length===0)return[null,!1];const n=At.safeParse(t.at(-1));if(!n.success)return[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 ty=s.z.object({rack:it.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()}),ry=s.z.object({tasks:ee(Zt)}),ny="/hardware/task/retrieve",sy="/hardware/task/create",iy="/hardware/task/delete",ay="/hardware/task/copy",oy=s.z.object({tasks:Ki.array()}),cy=s.z.object({tasks:Zt.array()}),ly=s.z.object({keys:De.array()}),uy=s.z.object({}),hy=s.z.object({key:De,name:s.z.string(),snapshot:s.z.boolean()}),yy=s.z.object({task:Zt});let Xi=class{constructor(e,t,n,i){o(this,"type","task");o(this,"client");o(this,"frameClient");o(this,"ontologyClient");o(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,sy,{tasks:T(e)},oy,cy),i=this.sugar(n.tasks);return t?i[0]:i}async delete(e){await w(this.client,iy,{keys:T(e)},ly,uy)}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}=Tr(e,{number:"rack",string:"keys"},{convertNumericStrings:!1}),c={...t};a==="rack"?c.rack=e:c.keys=i;const l=await this.execRetrieve(c),u=this.sugar(l);return n&&a!=="rack"?u[0]:u}async copy(e,t,n){const i=await w(this.client,ay,{key:e,name:t,snapshot:n},hy,yy);return this.sugar([i.task])[0]}async retrieveByName(e,t){const n=await this.execRetrieve({names:[e],rack:t});return vr("Task",e,n,!0),this.sugar(n)[0]}async execRetrieve(e){return(await w(this.client,ny,e,ty,ry)).tasks}sugar(e){return e.map(({key:t,name:n,type:i,config:a,state:c,internal:l,snapshot:u})=>new Hi(t,n,i,a,l,u,c,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 Bt(await this.frameClient.openStreamer(Ot),e=>{const t=e.get(Ot);if(t.length===0)return[null,!1];const n=At.safeParse(t.at(-1));return n.success?[n.data,!0]:[null,!1]})}};const dy=Object.freeze(Object.defineProperty({__proto__:null,Client:Xi,ONTOLOGY_TYPE:Ji,Task:Hi,commandZ:Qh,newTaskZ:Ki,ontologyID:ey,stateZ:At,taskKeyZ:De,taskZ:Zt},Symbol.toStringTag,{value:"Module"})),at=s.z.string().uuid(),Lt=s.z.object({key:at,name:s.z.string().min(1),color:s.z.string()}),Qi="label",fy=r=>new b({type:Qi,key:r}),py=s.z.object({keys:at.array().optional(),for:J.optional(),search:s.z.string().optional(),offset:s.z.number().optional(),limit:s.z.number().optional()}),gy=s.z.object({labels:ee(Lt)});var Ae;let ea=(Ae=class{constructor(e){o(this,"client");this.client=e}async retrieve(e){const t=T(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(Ae.ENDPOINT,e,py,gy);if(n!=null)throw n;return t.labels}},o(Ae,"ENDPOINT","/label/retrieve"),Ae);const ta=Lt.extend({key:at.optional()}),my=s.z.object({labels:ta.array()}),wy=s.z.object({labels:Lt.array()}),by=s.z.object({keys:at.array()}),ra=s.z.object({id:J,labels:at.array(),replace:s.z.boolean().optional()}),Ty=ra.omit({replace:!0}),Gr=s.z.object({}),vy="/label/create",Oy="/label/delete",zy="/label/set",Ey="/label/remove";let na=class{constructor(e){o(this,"client");this.client=e}async create(e){return(await w(this.client,vy,{labels:T(e)},my,wy)).labels}async delete(e){await w(this.client,Oy,{keys:T(e)},by,Gr)}async set(e,t,{replace:n}={}){await w(this.client,zy,{id:e,labels:t,replace:n},ra,Gr)}async remove(e,t){await w(this.client,Ey,{id:e,labels:t},Ty,Gr)}};const Sy="sy_label_set",Ny="sy_label_delete";let sa=class{constructor(e,t,n){o(this,"type","label");o(this,"retriever");o(this,"writer");o(this,"frameClient");o(this,"ontology");this.writer=new na(e),this.retriever=new ea(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 b(e))}async label(e,t,n={}){await this.writer.set(new b(e),t,n)}async removeLabels(e,t){await this.writer.remove(new b(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,Sy,Ny,Iy)}async trackLabelsOf(e){const t=new xe.Observer,n=(await this.retrieveFor(e)).map(a=>({id:new b({key:a.key,type:"label"}),key:a.key,name:a.name,data:a}));return(await this.ontology.openDependentTracker({target:new b(e),dependents:n,relationshipType:"labeled_by"})).onChange(a=>t.notify(a.map(c=>{var l,u;return{key:c.id.key,color:(l=c.data)==null?void 0:l.color,name:(u=c.data)==null?void 0:u.name}}))),t}};const Iy=(r,e)=>r==="delete"?e.toUUIDs().map(t=>({variant:r,key:t})):e.parseJSON(Lt).map(t=>({variant:r,key:t.key,value:t})),ky=Object.freeze(Object.defineProperty({__proto__:null,Client:sa,ONTOLOGY_TYPE:Qi,Retriever:ea,Writer:na,keyZ:at,labelZ:Lt,newLabelPayloadZ:ta,ontologyID:fy},Symbol.toStringTag,{value:"Module"})),X=s.z.string().uuid(),_t=s.z.object({key:X,name:s.z.string().min(1),timeRange:W.z,color:s.z.string().optional()}),ia=_t.extend({key:s.z.string().uuid().optional()}),aa=r=>{const e=T(r),t=e.length===0;let n=!1;return t||(n=X.safeParse(e[0]).success),{single:!Array.isArray(r),variant:n?"keys":"names",normalized:e,actual:r,empty:t}},oa="range",ca="range-alias",Ay=r=>new b({type:oa,key:r}),$y=r=>new b({type:ca,key:r}),Ry="sy_range_alias_set",xy="sy_range_alias_delete",Cy=s.z.object({range:X,aliases:s.z.string().array()}),Py=s.z.object({aliases:s.z.record(s.z.string(),Ee)}),Dy=s.z.object({range:X,aliases:s.z.record(Ee.or(s.z.string()),s.z.string())}),jy=s.z.unknown(),My=s.z.object({range:X,channels:Ee.array()}),By=s.z.unknown(),Uy=s.z.object({range:X}),Zy=s.z.object({aliases:s.z.record(s.z.string(),s.z.string())}),ce=class ce{constructor(e,t,n){o(this,"frameClient");o(this,"cache",new Map);o(this,"client");o(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 c=this.cache.get(e);if(c!=null)return c;t.push(e)}else e.forEach(c=>{const l=this.cache.get(c);l!=null?i[c]=l:t.push(c)});if(t.length===0)return i;const a=await w(this.client,ce.RESOLVE_ENDPOINT,{range:this.rangeKey,aliases:t},Cy,Py);return Object.entries(a.aliases).forEach(([c,l])=>this.cache.set(c,l)),n?a.aliases[t[0]]:{...i,...a.aliases}}async set(e){await w(this.client,ce.SET_ENDPOINT,{range:this.rangeKey,aliases:e},Dy,jy)}async list(){return(await w(this.client,ce.LIST_ENDPOINT,{range:this.rangeKey},Uy,Zy)).aliases}async delete(e){await w(this.client,ce.DELETE_ENDPOINT,{range:this.rangeKey,channels:e},My,By)}async openChangeTracker(){return await Pe(this.frameClient,Ry,xy,Yy(this.rangeKey))}};o(ce,"SET_ENDPOINT","/range/alias/set"),o(ce,"RESOLVE_ENDPOINT","/range/alias/resolve"),o(ce,"LIST_ENDPOINT","/range/alias/list"),o(ce,"DELETE_ENDPOINT","/range/alias/delete");let on=ce;const Ly=s.z.object({range:X,channel:Ee,alias:s.z.string()}),_y="---",Yy=r=>(e,t)=>e==="delete"?t.toStrings().filter(n=>n.split(_y)[0]===r).map(n=>({variant:e,key:n,value:void 0})):t.parseJSON(Ly).map(n=>({variant:e,key:n.alias,value:n})),qy=s.z.object({range:X,keys:s.z.string().array()}),Tn=s.z.object({range:X,key:s.z.string(),value:s.z.string()}),Wy=s.z.object({pairs:ee(Tn)}),Gy=s.z.object({range:X,pairs:Tn.array()}),Fy=s.z.object({range:X,keys:s.z.string().array()}),we=class we{constructor(e,t,n){o(this,"rangeKey");o(this,"client");o(this,"frameClient");this.rangeKey=e,this.client=t,this.frameClient=n}async get(e){const t=await w(this.client,we.GET_ENDPOINT,{range:this.rangeKey,keys:T(e)},qy,Wy);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;hn(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,we.SET_ENDPOINT,{range:this.rangeKey,pairs:n},Gy,s.z.unknown())}async delete(e){await w(this.client,we.DELETE_ENDPOINT,{range:this.rangeKey,keys:T(e)},Fy,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(Tn).map(n=>({variant:e,key:`${n.range}${n.key}`,value:n})))}};o(we,"GET_ENDPOINT","/range/kv/get"),o(we,"SET_ENDPOINT","/range/kv/set"),o(we,"DELETE_ENDPOINT","/range/kv/delete");let $t=we;const Fr=r=>new b({type:"range",key:r});class la{constructor(e,t=W.ZERO,n,i,a,c,l,u,h,d,y){o(this,"key");o(this,"name");o(this,"kv");o(this,"timeRange");o(this,"color");o(this,"channels");o(this,"aliaser");o(this,"frameClient");o(this,"labelClient");o(this,"ontologyClient");o(this,"rangeClient");this.key=n,this.name=e,this.timeRange=t,this.frameClient=a,this.color=i,this.kv=c,this.aliaser=l,this.channels=u,this.labelClient=h,this.ontologyClient=d,this.rangeClient=y}get ontologyID(){return new b({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 te(`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(Fr(this.key))}async addLabel(...e){await this.labelClient.label(Fr(this.key),e)}async removeLabel(...e){await this.labelClient.removeLabels(Fr(this.key),e)}async openChildRangeTracker(){const e=new xe.Observer,t=(await this.retrieveChildren()).map(i=>{const a=new b({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 xe.Observer,t=await this.retrieveParent();if(t==null)return null;const n=new b({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(c=>{const l=this.rangeClient.resourcesToRanges(c);if(l.length===0)return;const u=l[0];e.notify(u)}),e.setCloser(async()=>await a.close()),e}}const Vy=s.z.object({keys:X.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()}),Ky="/range/retrieve",Jy=s.z.object({ranges:ee(_t)});let ua=class{constructor(e,t,n,i,a,c){o(this,"type","range");o(this,"frameClient");o(this,"writer");o(this,"unaryClient");o(this,"channels");o(this,"labelClient");o(this,"ontologyClient");this.frameClient=e,this.writer=t,this.unaryClient=n,this.channels=i,this.labelClient=a,this.ontologyClient=c}async create(e,t){const n=!Array.isArray(e),i=this.sugarMany(await this.writer.create(T(e),t));return n?i[0]:i}async rename(e,t){await this.writer.rename(e,t)}async delete(e){await this.writer.delete(T(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:c}=aa(e);if(c)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 ge(`multiple ranges matching ${n} found`);return l[0]}getKV(e){return new $t(e,this.unaryClient,this.frameClient)}async execRetrieve(e){const{ranges:t}=await w(this.unaryClient,Ky,e,Vy,Jy);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 la(e.name,e.timeRange,e.key,e.color,this.frameClient,new $t(e.key,this.unaryClient,this.frameClient),new on(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(_t)).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 Hy=s.z.object({ranges:_t.array()}),Xy=s.z.object({parent:J.optional(),ranges:ia.array()}),Qy=s.z.object({keys:X.array()}),ed=s.z.object({}),td=s.z.object({key:X,name:s.z.string()}),rd=s.z.object({}),nd="/range/create",sd="/range/delete",id="/range/rename";let ha=class{constructor(e){o(this,"client");this.client=e}async rename(e,t){await w(this.client,id,{key:e,name:t},td,rd)}async create(e,t){return(await w(this.client,nd,{ranges:e,...t},Xy,Hy)).ranges}async delete(e){await w(this.client,sd,{keys:e},Qy,ed)}};const ad=Object.freeze(Object.defineProperty({__proto__:null,ALIAS_ONTOLOGY_TYPE:ca,Client:ua,KV:$t,ONTOLOGY_TYPE:oa,Range:la,Writer:ha,analyzeParams:aa,keyZ:X,newPayloadZ:ia,payloadZ:_t,rangeAliasOntologyID:$y,rangeOntologyID:Ay},Symbol.toStringTag,{value:"Module"})),od="/api/v1/";class cd{constructor(e,t=!1){o(this,"url");o(this,"unary");o(this,"stream");o(this,"secure");this.secure=t,this.url=e.child(od);const n=new nt.JSONCodec;this.unary=new Go(this.url,n,this.secure),this.stream=new tc(this.url,n,this.secure)}use(...e){this.unary.use(...e),this.stream.use(...e)}}const Ir=s.z.string().uuid(),kr=s.z.object({key:s.z.string(),name:s.z.string(),data:dn.or(s.z.string().transform(r=>JSON.parse(r)))}),ya="lineplot",ld=r=>new b({type:ya,key:r}),ud=s.z.object({keys:s.z.string().array()}),hd=s.z.object({linePlots:kr.array()});let yd=class{constructor(e){o(this,"ENDPOINT","/workspace/lineplot/retrieve");o(this,"client");this.client=e}async retrieve(e){const t=T(e);return(await w(this.client,this.ENDPOINT,{keys:t},ud,hd)).linePlots}};const Se=s.z.string().uuid(),da=r=>JSON.parse(r),vn=s.z.object({name:s.z.string(),key:Se,layout:dn.or(s.z.string().transform(r=>da(r)))}),On=vn.omit({layout:!0}).extend({layout:s.z.string().transform(r=>da(r))}),fa="workspace",dd=r=>new b({type:fa,key:r}),fd=kr.partial({key:!0}).transform(r=>({...r,data:JSON.stringify(r.data)})),pd=s.z.object({workspace:Se,linePlots:fd.array()}),gd=s.z.object({linePlots:kr.array()}),md=s.z.object({keys:Ir.array()}),wd=s.z.object({}),bd=s.z.object({key:Ir,name:s.z.string()}),Td=s.z.object({}),vd=s.z.object({key:Ir,data:s.z.string()}),Od=s.z.object({}),zd="/workspace/lineplot/create",Ed="/workspace/lineplot/delete",Sd="/workspace/lineplot/rename",Nd="/workspace/lineplot/set-data";let Id=class{constructor(e){o(this,"client");this.client=e}async create(e,t){const n={...t,data:JSON.stringify(t.data)};return(await w(this.client,zd,{workspace:e,linePlots:[n]},pd,gd)).linePlots[0]}async delete(e){const t=T(e);await w(this.client,Ed,{keys:t},md,wd)}async rename(e,t){await w(this.client,Sd,{key:e,name:t},bd,Td)}async setData(e,t){await w(this.client,Nd,{key:e,data:JSON.stringify(t)},vd,Od)}},pa=class{constructor(e){o(this,"writer");o(this,"retriever");this.writer=new Id(e),this.retriever=new yd(e)}async create(e,t){return await this.writer.create(e,t)}async rename(e,t){await this.writer.rename(e,t)}async setData(e,t){await this.writer.setData(e,t)}async retrieve(e){const t=Array.isArray(e),n=await this.retriever.retrieve(e);return t?n:n[0]}async delete(e){await this.writer.delete(e)}};const kd=Object.freeze(Object.defineProperty({__proto__:null,Client:pa,ONTOLOGY_TYPE:ya,keyZ:Ir,linePlotZ:kr,ontologyID:ld},Symbol.toStringTag,{value:"Module"})),Ad=s.z.object({keys:Se.array().optional(),search:s.z.string().optional(),author:s.z.string().uuid().optional(),offset:s.z.number().optional(),limit:s.z.number().optional()}),$d=s.z.object({workspaces:ee(On)});var $e;let Rd=($e=class{constructor(e){o(this,"client");this.client=e}async retrieve(e){const t=T(e);return await this.execute({keys:t})}async retrieveByAuthor(e){return await this.execute({author: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){return(await w(this.client,$e.ENDPOINT,e,Ad,$d)).workspaces}},o($e,"ENDPOINT","/workspace/retrieve"),$e);const Yt=s.z.string().uuid(),ga=s.z.object({key:s.z.string(),name:s.z.string(),data:dn.or(s.z.string().transform(r=>JSON.parse(r))),snapshot:s.z.boolean()}),Ar=s.z.object({key:s.z.string(),name:s.z.string(),snapshot:s.z.boolean(),data:s.z.string().transform(r=>JSON.parse(r))}),ma="schematic",xd=r=>new b({type:ma,key:r}),Cd=s.z.object({keys:s.z.string().array()}),Pd=s.z.object({schematics:Ar.array()});class Dd{constructor(e){o(this,"ENDPOINT","/workspace/schematic/retrieve");o(this,"client");this.client=e}async retrieve(e){return(await w(this.client,this.ENDPOINT,{keys:T(e)},Cd,Pd)).schematics}}const jd=ga.partial({key:!0,snapshot:!0}).transform(r=>({...r,data:JSON.stringify(r.data)})),Md=s.z.object({workspace:Se,schematics:jd.array()}),Bd=s.z.object({schematics:Ar.array()}),Ud=s.z.object({keys:Yt.array()}),Zd=s.z.object({}),Ld=s.z.object({key:Yt,name:s.z.string()}),fs=s.z.object({}),_d=s.z.object({key:Yt,data:s.z.string()});s.z.object({});const Yd=s.z.object({key:Yt,name:s.z.string(),snapshot:s.z.boolean()}),qd=s.z.object({schematic:Ar}),Wd="/workspace/schematic/create",Gd="/workspace/schematic/delete",Fd="/workspace/schematic/rename",Vd="/workspace/schematic/set-data",Kd="/workspace/schematic/copy";let Jd=class{constructor(e){o(this,"client");this.client=e}async create(e,t){const n={...t,data:JSON.stringify(t.data)};return(await w(this.client,Wd,{workspace:e,schematics:[n]},Md,Bd)).schematics[0]}async copy(e,t,n){return(await w(this.client,Kd,{key:e,name:t,snapshot:n},Yd,qd)).schematic}async delete(e){const t=T(e);await w(this.client,Gd,{keys:t},Ud,Zd)}async rename(e,t){await w(this.client,Fd,{key:e,name:t},Ld,fs)}async setData(e,t){await w(this.client,Vd,{key:e,data:JSON.stringify(t)},_d,fs)}},wa=class{constructor(e){o(this,"writer");o(this,"retriever");this.writer=new Jd(e),this.retriever=new Dd(e)}async create(e,t){return await this.writer.create(e,t)}async rename(e,t){await this.writer.rename(e,t)}async setData(e,t){await this.writer.setData(e,t)}async retrieve(e){const t=Array.isArray(e),n=await this.retriever.retrieve(e);return t?n:n[0]}async delete(e){await this.writer.delete(e)}async copy(e,t,n){return await this.writer.copy(e,t,n)}};const Hd=Object.freeze(Object.defineProperty({__proto__:null,Client:wa,ONTOLOGY_TYPE:ma,keyZ:Yt,ontologyID:xd,schematicRemoteZ:Ar,schematicZ:ga},Symbol.toStringTag,{value:"Module"})),Xd=vn.partial({key:!0}).transform(r=>({...r,layout:JSON.stringify(r.layout)})),Qd=s.z.object({workspaces:Xd.array()}),ef=s.z.object({workspaces:On.array()}),tf=s.z.object({keys:Se.array()}),rf=s.z.object({}),nf=s.z.object({key:Se,name:s.z.string()}),sf=s.z.object({}),af=s.z.object({key:Se,layout:s.z.string()}),of=s.z.object({}),cf="/workspace/create",lf="/workspace/delete",uf="/workspace/rename",hf="/workspace/set-layout";class yf{constructor(e){o(this,"client");this.client=e}async create(e){return(await w(this.client,cf,{workspaces:T(e)},Qd,ef)).workspaces}async delete(e){await w(this.client,lf,{keys:T(e)},tf,rf)}async rename(e,t){await w(this.client,uf,{key:e,name:t},nf,sf)}async setLayout(e,t){await w(this.client,hf,{key:e,layout:JSON.stringify(t)},af,of)}}class ba{constructor(e){o(this,"type","workspace");o(this,"schematic");o(this,"linePlot");o(this,"retriever");o(this,"writer");this.schematic=new wa(e),this.linePlot=new pa(e),this.retriever=new Rd(e),this.writer=new yf(e)}async search(e){return await this.retriever.search(e)}async retrieveByAuthor(e){return await this.retriever.retrieveByAuthor(e)}async retrieve(e){const t=Array.isArray(e),n=await this.retriever.retrieve(e);return t?n:n[0]}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 rename(e,t){await this.writer.rename(e,t)}async setLayout(e,t){await this.writer.setLayout(e,t)}async delete(...e){await this.writer.delete(e)}}const df=Object.freeze(Object.defineProperty({__proto__:null,Client:ba,ONTOLOGY_TYPE:fa,keyZ:Se,ontologyID:dd,workspaceRemoteZ:On,workspaceZ:vn},Symbol.toStringTag,{value:"Module"})),Ta=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:E.z.default(E.seconds(30)),secure:s.z.boolean().optional().default(!1),name:s.z.string().optional()});class va extends Bi{constructor(t){const n=Ta.parse(t),{host:i,port:a,username:c,password:l,connectivityPollFrequency:u,secure:h}=n,d=new cd(new vl({host:i,port:Number(a)}),h);d.use(Cl);let y;c!=null&&l!=null&&(y=new ah(d.unary,{username:c,password:l}),d.use(y.middleware()));const P=new fn(new It(d.unary)),D=new Ii(d.unary,P);super(d.stream,d.unary,P);o(this,"createdAt");o(this,"props");o(this,"ranges");o(this,"channels");o(this,"auth");o(this,"user");o(this,"access");o(this,"connectivity");o(this,"ontology");o(this,"workspaces");o(this,"labels");o(this,"hardware");o(this,"control");o(this,"transport");o(this,"clientVersion","0.32.0");this.createdAt=S.now(),this.props=n,this.auth=y,this.transport=d,this.channels=new Ni(this,P,d.unary,D),this.connectivity=new kt(d.unary,u,this.clientVersion,n.name),this.control=new Zi(this),this.ontology=new pi(d.unary,this);const Q=new ha(this.transport.unary);this.labels=new sa(this.transport.unary,this,this.ontology),this.ranges=new ua(this,Q,this.transport.unary,P,this.labels,this.ontology),this.access=new Ti(this.transport.unary),this.user=new $i(this.transport.unary),this.workspaces=new ba(this.transport.unary);const B=new Gi(this.transport.unary,this),zn=new Xi(this.transport.unary,this,this.ontology,this.ranges),Oa=new Fi(this.transport.unary,this,zn);this.hardware=new Li(zn,Oa,B)}get key(){return this.createdAt.valueOf().toString()}close(){this.connectivity.stopChecking()}}o(va,"connectivity",kt);const ff=et.Authority;exports.AuthError=Ce;exports.Authority=ff;exports.Channel=pn;exports.ContiguityError=nn;exports.DataType=z;exports.Density=V;exports.Frame=_;exports.MultiSeries=ni;exports.MultipleFoundError=ge;exports.NotFoundError=pe;exports.QueryError=te;exports.Rate=mr;exports.RouteError=Nt;exports.Series=be;exports.Synnax=va;exports.TimeRange=W;exports.TimeSpan=E;exports.TimeStamp=S;exports.UnexpectedError=ve;exports.ValidationError=M;exports.access=yu;exports.channel=Pu;exports.connection=lh;exports.control=Rh;exports.device=Wh;exports.framer=Nh;exports.hardware=xh;exports.label=ky;exports.linePlot=kd;exports.ontology=Hl;exports.policy=hu;exports.rack=Xh;exports.ranger=ad;exports.schematic=Hd;exports.signals=Dh;exports.synnaxPropsZ=Ta;exports.task=dy;exports.user=Qu;exports.workspace=df;
|