@synnaxlabs/pluto 0.31.0 → 0.32.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{Animated-CqxAz8yC.js → Animated-m1d-q2MY.js} +1 -1
- package/dist/{Animated-Bo0VMLXe.cjs → Animated-vgeFXXXh.cjs} +1 -1
- package/dist/{Item-Cr7Cee2t.js → Item-AKMko1DZ.js} +3 -3
- package/dist/{Item-s_R6czdE.cjs → Item-CzgByHQ2.cjs} +1 -1
- package/dist/{Keyboard-CIJ6C-6F.js → Keyboard-DWCElMA3.js} +1 -1
- package/dist/{Keyboard-D-9KUUCq.cjs → Keyboard-Dy7Q9I4w.cjs} +1 -1
- package/dist/{LinePlot-k6OxHynn.cjs → LinePlot-BcVyfdeK.cjs} +8 -8
- package/dist/{LinePlot-CVOH06qp.js → LinePlot-CCzgiKg5.js} +1 -1
- package/dist/Link-BLs4o2WZ.js +11 -0
- package/dist/Link-DAjbmQEI.cjs +1 -0
- package/dist/{List-DVMb5TAO.cjs → List-C8Cd_qEK.cjs} +1 -1
- package/dist/{List-L9yD_LRe.js → List-CVxaH1Gv.js} +2 -2
- package/dist/{Text-Vzb9NS0-.cjs → Text-DwK7WZwz.cjs} +1 -1
- package/dist/{Text-D9wOBnT3.js → Text-ZWBNDAJX.js} +3 -3
- package/dist/{Toggle-BrC3s3ox.js → Toggle-BQtgHKds.js} +3121 -3117
- package/dist/{Toggle-DdnBJm8D.cjs → Toggle-Cu_t9VPe.cjs} +24 -24
- package/dist/{aggregator-BNkkZ-Bc.js → aggregator-f5OfPmNc.js} +603 -580
- package/dist/{aggregator-LvZi4Kvh.cjs → aggregator-q0CY7-QS.cjs} +24 -24
- package/dist/button.cjs +1 -1
- package/dist/button.js +1 -1
- package/dist/color.cjs +1 -1
- package/dist/color.js +1 -1
- package/dist/dropdown.cjs +1 -1
- package/dist/dropdown.js +1 -1
- package/dist/ether.cjs +1 -1
- package/dist/ether.js +4 -4
- package/dist/{external-BwdvFk2R.js → external-0qSQW-rW.js} +2 -2
- package/dist/{external-BGcGef1R.cjs → external-1AgJfGUo.cjs} +1 -1
- package/dist/{external-D7bzFwDm.cjs → external-2HiPz4gN.cjs} +1 -1
- package/dist/{external-vf43rlmJ.js → external-B22Cd5L_.js} +2 -2
- package/dist/{external-BpWJNQQi.cjs → external-BAqZitjw.cjs} +1 -1
- package/dist/{external-DzY80h7T.js → external-BGO9o6o7.js} +6 -6
- package/dist/{external-EHAadzLe.js → external-BIcOl3QR.js} +2 -2
- package/dist/{external-ByGOTAK0.js → external-BSbQ1fB2.js} +3 -3
- package/dist/{external-ArTLjo1-.cjs → external-BVWCSwPk.cjs} +1 -1
- package/dist/{external-CzVXDUkp.cjs → external-Bcj4ayXg.cjs} +1 -1
- package/dist/{external-BaV5u1sJ.js → external-BiVAfJDo.js} +10 -10
- package/dist/{external-oW8IRqfk.js → external-BswSNc0P.js} +2 -2
- package/dist/{external-Cta1T9rO.js → external-BxSZ_pLZ.js} +2 -2
- package/dist/{external-BxX4TXgQ.cjs → external-CCY3TmGe.cjs} +1 -1
- package/dist/{external-CJt9nz9P.cjs → external-COZBfuIe.cjs} +1 -1
- package/dist/{external-MSpJvixc.cjs → external-CR7eRU7I.cjs} +1 -1
- package/dist/{external-CGdoEsew.cjs → external-CV8q9dy8.cjs} +1 -1
- package/dist/{external-B1KQRpm7.js → external-CWLnWzN8.js} +33 -33
- package/dist/{external-DAswAy_H.js → external-Co3i1qex.js} +25 -25
- package/dist/{external-DmH8EJ0I.cjs → external-Cqh9AY74.cjs} +1 -1
- package/dist/{external-qbHFNsHS.js → external-CyqJB_UP.js} +14 -14
- package/dist/{external-ZS0XGHuP.cjs → external-DNl6ut74.cjs} +1 -1
- package/dist/header.cjs +1 -1
- package/dist/header.js +1 -1
- package/dist/index.cjs +1 -1
- package/dist/index.js +191 -191
- package/dist/input.cjs +1 -1
- package/dist/input.js +1 -1
- package/dist/list.cjs +1 -1
- package/dist/list.js +1 -1
- package/dist/menu.cjs +1 -1
- package/dist/menu.js +1 -1
- package/dist/src/button/Link.d.ts +2 -1
- package/dist/src/button/Link.d.ts.map +1 -1
- package/dist/src/select/Direction.d.ts.map +1 -1
- package/dist/style.css +1 -1
- package/dist/tabs.cjs +1 -1
- package/dist/tabs.js +1 -1
- package/dist/text.cjs +1 -1
- package/dist/text.js +2 -2
- package/dist/theming.cjs +1 -1
- package/dist/theming.js +2 -2
- package/dist/tree.cjs +1 -1
- package/dist/tree.js +1 -1
- package/dist/triggers.cjs +1 -1
- package/dist/triggers.js +1 -1
- package/package.json +7 -7
- package/dist/Link-B1bLviPV.js +0 -10
- package/dist/Link-z1QKdW8G.cjs +0 -1
|
@@ -1,67 +1,67 @@
|
|
|
1
1
|
"use strict";var Bc=Object.defineProperty;var Uc=(t,e,r)=>e in t?Bc(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r;var B=(t,e,r)=>Uc(t,typeof e!="symbol"?e+"":e,r);const s=require("zod"),O=require("./css-LxkguM_s.cjs"),ps=require("react");var Lc=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function _c(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}function Yc(t){if(t.__esModule)return t;var e=t.default;if(typeof e=="function"){var r=function n(){return this instanceof n?Reflect.construct(e,arguments,this.constructor):e.apply(this,arguments)};r.prototype=e.prototype}else r={};return Object.defineProperty(r,"__esModule",{value:!0}),Object.keys(t).forEach(function(n){var i=Object.getOwnPropertyDescriptor(t,n);Object.defineProperty(r,n,i.get?i:{enumerable:!0,get:function(){return t[n]}})}),r}const Mt=t=>t!=null&&typeof t=="object"&&!Array.isArray(t);var qc=Object.defineProperty,Fc=(t,e,r)=>e in t?qc(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Dt=(t,e,r)=>Fc(t,typeof e!="symbol"?e+"":e,r);let Vc=class{constructor(){Dt(this,"contentType","application/json"),Dt(this,"decoder"),Dt(this,"encoder"),this.decoder=new TextDecoder,this.encoder=new TextEncoder}encode(e){return this.encoder.encode(this.encodeString(e)).buffer}decode(e,r){return this.decodeString(this.decoder.decode(e),r)}decodeString(e,r){const n=JSON.parse(e),i=O.T(n);return r!=null?r.parse(i):i}encodeString(e){const r=O.v(e);return JSON.stringify(r,(n,i)=>ArrayBuffer.isView(i)?Array.from(i):Mt(i)&&"encode_value"in i?typeof i.value=="bigint"?i.value.toString():i.value:typeof i=="bigint"?i.toString():i)}static registerCustomType(){}},Wc=class{constructor(){Dt(this,"contentType","text/csv")}encode(e){const r=this.encodeString(e);return new TextEncoder().encode(r).buffer}decode(e,r){const n=new TextDecoder().decode(e);return this.decodeString(n,r)}encodeString(e){if(!Array.isArray(e)||e.length===0||!Mt(e[0]))throw new Error("Payload must be an array of objects");const r=Object.keys(e[0]),n=[r.join(",")];return e.forEach(i=>{const a=r.map(o=>JSON.stringify(i[o]??""));n.push(a.join(","))}),n.join(`
|
|
2
2
|
`)}decodeString(e,r){const[n,...i]=e.trim().split(`
|
|
3
|
-
`).map(u=>u.trim());if(n.length===0)return r!=null?r.parse({}):{};const a=n.split(",").map(u=>u.trim()),o={};return a.forEach(u=>{o[u]=[]}),i.forEach(u=>{const c=u.split(",").map(d=>d.trim());a.forEach((d,f)=>{const h=this.parseValue(c[f]);h!=null&&o[d].push(h)})}),r!=null?r.parse(o):o}parseValue(e){if(e==null||e.length===0)return null;const r=Number(e);return isNaN(r)?e.startsWith('"')&&e.endsWith('"')?e.slice(1,-1):e:r}static registerCustomType(){}},Gc=class{constructor(){Dt(this,"contentType","text/plain")}encode(e){return new TextEncoder().encode(e).buffer}decode(e,r){const n=new TextDecoder().decode(e);return r!=null?r.parse(n):n}};const yr=new Vc;new Wc;new Gc;const Fn=t=>[...new Set(t)],ta=t=>t!=null&&typeof t=="object"&&"toString"in t,Zc=t=>{if(ta(t))return(t==null?void 0:t.toString().length)===0;switch(typeof t){case"string":return t.length===0;case"number":return t===0;case"bigint":return t===0n;case"boolean":return!t;case"undefined":return!0;case"object":return t===null}},en=(t,e=!1)=>{const r=ta(t)?"stringer":typeof t;let n;switch(r){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 ${r}`),()=>-1}return e?na(n):n},Kc=(t,e,r)=>{const n=en(e[t],r);return(i,a)=>n(i[t],a[t])},Jc=(t,e)=>t.length!==e.length?t.length-e.length:t.every((r,n)=>r===e[n])?0:-1,ra=(t,e)=>{if(t.length!==e.length)return t.length-e.length;if(t.length===0)return 0;const r=en(t[0]),n=[...t].sort(r),i=[...e].sort(r);return n.every((a,o)=>a===i[o])?0:-1},Hc=(t,e)=>{const r=Fn(t),n=Fn(e);return ra(r,n)},Xc=(t,e)=>t===e?0:t==="first"&&e==="last"?1:-1,na=t=>(e,r)=>t(r,e),at=0,gr=-1,pr=1,sa=t=>t<at,ia=t=>t>at,Qc=t=>t>=at,aa=t=>t===at,el=(t,e)=>{const r=/([a-zA-Z]+)|(\d+)/g,n=t.replace(/[\s_.-]+/g,"").match(r),i=e.replace(/[\s_.-]+/g,"").match(r);if(!n||!i)return 0;for(let a=0;a<Math.min(n.length,i.length);a++){const o=n[a],u=i[a];if(isNaN(Number(o))&&isNaN(Number(u))){const c=o.localeCompare(u);if(c!==0)return c}else if(!isNaN(Number(o))&&!isNaN(Number(u))){const c=Number(o)-Number(u);if(c!==0)return c}else return isNaN(Number(o))?-1:1}return n.length-i.length},tl=Object.freeze(Object.defineProperty({__proto__:null,EQUAL:at,GREATER_THAN:pr,LESS_THAN:gr,isEqualTo:aa,isGreaterThan:ia,isGreaterThanEqual:Qc,isLessThan:sa,newF:en,newFieldF:Kc,order:Xc,primitiveArrays:Jc,reverseF:na,stringsWithNumbers:el,uniqueUnorderedPrimitiveArrays:Hc,unorderedPrimitiveArrays:ra},Symbol.toStringTag,{value:"Module"})),rl=(t,e)=>{let r=null;return e===0?t:(...n)=>{r!==null&&(clearTimeout(r),r=null),r=setTimeout(()=>t(...n),e)}},nl=(t,e)=>{let r=null;return e===0?t:(...n)=>{r===null&&(r=setTimeout(()=>{t(...n),r=null},e))}},oa=(t,e,r=".")=>{const n=t.split(r);return n.map((i,a)=>{const o=e(i,a,n);return o==null?null:typeof o=="string"?o:o.join(r)}).filter(i=>i!=null).join(r)},ms=(t,e,r={optional:!1,separator:"."})=>{r.separator??(r.separator=".");const{optional:n,getter:i=(u,c)=>u[c]}=r,a=e.split(r.separator);if(a.length===1&&a[0]==="")return t;let o=t;for(const u of a){const c=i(o,u);if(c==null){if(n)return null;throw new Error(`Path ${e} does not exist. ${u} is null`)}o=c}return o},sl=(t,e,r)=>{const n=e.split(".");let i=t;for(let a=0;a<n.length-1;a++){const o=n[a];i[o]==null&&(i[o]={}),i=i[o]}i[n[n.length-1]]=r},il=(t,e)=>{const r=e.split(".");let n=t;for(let i=0;i<r.length-1;i++){const a=r[i];if(n[a]==null)return;n=n[a]}if(Array.isArray(n)){const i=parseInt(r[r.length-1],10);if(isNaN(i))return;n.splice(i,1);return}delete n[r[r.length-1]]},al=(t,e)=>{const r=t.split(".");return e<0?r[r.length+e]:r[e]},ol=(t,e)=>{try{return ms(t,e),!0}catch{return!1}},cl=(t,e)=>{if(e.length===0)return!0;const r=t.split("."),n=e.split(".");if(n.length>r.length)return!1;for(let i=0;i<n.length;i++){const a=r[i],o=n[i];if(o!=="*"&&a!==o)return!1}return!0},ll=t=>JSON.parse(JSON.stringify(t)),ul=(t,...e)=>(e.forEach(r=>{let n=t;const i=r.split(".");i.forEach((a,o)=>{o===i.length-1?delete n[a]:a in n&&(n=n[a])})}),t),hl=(t,e,r="")=>{const n={},i=(a,o,u)=>{if(typeof a!=typeof o||a===null||o===null){n[u]=[a,o];return}if(typeof a=="object"&&typeof o=="object")if(Array.isArray(a)&&Array.isArray(o)){if(a.length!==o.length){n[u]=[a,o];return}for(let c=0;c<a.length;c++)i(a[c],o[c],`${u}[${c}]`)}else new Set([...Object.keys(a),...Object.keys(o)]).forEach(c=>{i(a[c],o[c],u!==""?`${u}.${c}`:c)});else a!==o&&(n[u]=[a,o])};return i(t,e,r),n},Vn=(t,e)=>{const r=Array.isArray(t),n=Array.isArray(e);if(r!==n)return!1;if(r&&n){const o=t,u=e;if(o.length!==u.length)return!1;for(let c=0;c<o.length;c++)if(!Vn(o[c],u[c]))return!1;return!0}if(t==null||e==null||typeof t!="object"||typeof e!="object")return t===e;if("equals"in t)return t.equals(e);const i=Object.keys(t),a=Object.keys(e);if(i.length!==a.length)return!1;for(const o of i){const u=t[o],c=e[o];if(typeof u=="object"&&typeof c=="object"){if(!Vn(u,c))return!1}else if(u!==c)return!1}return!0},ca=(t,e)=>{if(typeof t!="object"||t==null)return t===e;const r=Object.keys(t),n=Object.keys(e);if(n.length>r.length)return!1;for(const i of n){const a=t[i],o=e[i];if(typeof a=="object"&&typeof o=="object"){if(!ca(a,o))return!1}else if(a!==o)return!1}return!0},Wn=(t,...e)=>{if(e.length===0)return t;const r=e.shift();if(Mt(t)&&Mt(r))for(const n in r)try{Mt(r[n])?(n in t||Object.assign(t,{[n]:{}}),Wn(t[n],r[n])):Object.assign(t,{[n]:r[n]})}catch(i){throw i instanceof TypeError?new TypeError(`.${n}: ${i.message}`):i}return Wn(t,...e)},dl=(t,e,r)=>{const n=(i,a,o)=>{for(const u in a){const c=a[u];if(o!=null&&o.shape[u]){const d=o.shape[u].safeParse(c);d.success&&(i[u]=d.data)}else typeof c=="object"&&!Array.isArray(c)&&c!==null&&o&&o.shape&&o.shape[u]&&(i[u]||(i[u]={}),n(i[u],c,o.shape[u]))}return i};return n({...t},e,r)},la=Object.freeze(Object.defineProperty({__proto__:null,copy:ll,deleteD:ul,difference:hl,element:al,equal:Vn,get:ms,has:ol,override:Wn,overrideValidItems:dl,partialEqual:ca,pathsMatch:cl,remove:il,set:sl,transformPath:oa},Symbol.toStringTag,{value:"Module"})),ua=t=>oa(t,(e,r,n)=>{const i=r===n.length-1,a=!isNaN(parseInt(e)),o=!isNaN(parseInt(n[r+1]));return a&&(e="element"),i||o?e:[e,"shape"]}),Js=(t,e)=>{if(t==null)return null;const r=t[e];return r==null&&typeof t=="object"&&"sourceType"in t?t.sourceType()[e]:r},fl=(t,e,r)=>ms(Js(t,"shape"),ua(e),{...r,getter:Js}),yl=(t,e)=>r=>{const n=e.find(i=>i.safeParse(r).success);return n==null?null:t(n.parse(r))},ha=s.z.bigint().or(s.z.string().transform(BigInt)),gl=Object.freeze(Object.defineProperty({__proto__:null,bigInt:ha,getFieldSchema:fl,getFieldSchemaPath:ua,transformer:yl},Symbol.toStringTag,{value:"Module"}));var pl=Object.defineProperty,ml=(t,e,r)=>e in t?pl(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,m=(t,e,r)=>ml(t,typeof e!="symbol"?e+"":e,r);let wl=(t,e=21)=>(r=e)=>{let n="",i=r;for(;i--;)n+=t[Math.random()*t.length|0];return n};const bl="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",da=wl(bl,11),fa=Object.freeze(Object.defineProperty({__proto__:null,id:da},Symbol.toStringTag,{value:"Module"})),vl=s.z.enum(["static","dynamic"]),ya=(t,e)=>{const r=new W(e);if(![Z.DAY,Z.HOUR,Z.MINUTE,Z.SECOND,Z.MILLISECOND,Z.MICROSECOND,Z.NANOSECOND].some(i=>i.equals(r)))throw new Error("Invalid argument for remainder. Must be an even TimeSpan or Timestamp");const n=t.valueOf()%r.valueOf();return t instanceof W?new W(n):new Z(n)},U=class S{constructor(e,r="UTC"){if(m(this,"value"),m(this,"encodeValue",!0),e==null)this.value=S.now().valueOf();else if(e instanceof Date)this.value=BigInt(e.getTime())*S.MILLISECOND.valueOf();else if(typeof e=="string")this.value=S.parseDateTimeString(e,r).valueOf();else if(Array.isArray(e))this.value=S.parseDate(e);else{let n=BigInt(0);e instanceof Number&&(e=e.valueOf()),r==="local"&&(n=S.utcOffset.valueOf()),typeof e=="number"&&(isFinite(e)?e=Math.trunc(e):(isNaN(e)&&(e=0),e===1/0?e=S.MAX:e=S.MIN)),this.value=BigInt(e.valueOf())+n}}static parseDate([e=1970,r=1,n=1]){const i=new Date(e,r-1,n,0,0,0,0);return new S(BigInt(i.getTime())*S.MILLISECOND.valueOf()).truncate(S.DAY).valueOf()}encode(){return this.value.toString()}valueOf(){return this.value}static parseTimeString(e,r="UTC"){const[n,i,a]=e.split(":");let o="00",u="00";a!=null&&([o,u]=a.split("."));let c=S.hours(parseInt(n??"00",10)).add(S.minutes(parseInt(i??"00",10))).add(S.seconds(parseInt(o??"00",10))).add(S.milliseconds(parseInt(u??"00",10)));return r==="local"&&(c=c.add(S.utcOffset)),c.valueOf()}static parseDateTimeString(e,r="UTC"){if(!e.includes("/")&&!e.includes("-"))return S.parseTimeString(e,r);const n=new Date(e);return e.includes(":")||n.setUTCHours(0,0,0,0),new S(BigInt(n.getTime())*S.MILLISECOND.valueOf(),r).valueOf()}fString(e="ISO",r="UTC"){switch(e){case"ISODate":return this.toISOString(r).slice(0,10);case"ISOTime":return this.toISOString(r).slice(11,23);case"time":return this.timeString(!1,r);case"preciseTime":return this.timeString(!0,r);case"date":return this.dateString();case"preciseDate":return`${this.dateString()} ${this.timeString(!0,r)}`;case"dateTime":return`${this.dateString()} ${this.timeString(!1,r)}`;default:return this.toISOString(r)}}toISOString(e="UTC"){return e==="UTC"?this.date().toISOString():this.sub(S.utcOffset).date().toISOString()}timeString(e=!1,r="UTC"){const n=this.toISOString(r);return e?n.slice(11,23):n.slice(11,19)}dateString(){const e=this.date(),r=e.toLocaleString("default",{month:"short"}),n=e.toLocaleString("default",{day:"numeric"});return`${r} ${n}`}static get utcOffset(){return new Z(BigInt(new Date().getTimezoneOffset())*S.MINUTE.valueOf())}static since(e){return new S().span(e)}date(){return new Date(this.milliseconds())}equals(e){return this.valueOf()===new S(e).valueOf()}span(e){return this.range(e).span}range(e){return new tt(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 S(e).valueOf()}afterEq(e){return this.valueOf()>=new S(e).valueOf()}before(e){return this.valueOf()<new S(e).valueOf()}beforeEq(e){return this.valueOf()<=new S(e).valueOf()}add(e){return new S(this.valueOf()+BigInt(e.valueOf()))}sub(e){return new S(this.valueOf()-BigInt(e.valueOf()))}milliseconds(){return Number(this.valueOf())/Number(S.MILLISECOND.valueOf())}toString(){return this.date().toISOString()}remainder(e){return ya(this,e)}get isToday(){return this.truncate(Z.DAY).equals(S.now().truncate(Z.DAY))}truncate(e){return this.sub(this.remainder(e))}static now(){return new S(new Date)}static max(...e){let r=S.MIN;for(const n of e){const i=new S(n);i.after(r)&&(r=i)}return r}static min(...e){let r=S.MAX;for(const n of e){const i=new S(n);i.before(r)&&(r=i)}return r}static nanoseconds(e){return new S(e)}static microseconds(e){return S.nanoseconds(e*1e3)}static milliseconds(e){return S.microseconds(e*1e3)}static seconds(e){return S.milliseconds(e*1e3)}static minutes(e){return S.seconds(e*60)}static hours(e){return S.minutes(e*60)}static days(e){return S.hours(e*24)}};m(U,"NANOSECOND",U.nanoseconds(1)),m(U,"MICROSECOND",U.microseconds(1)),m(U,"MILLISECOND",U.milliseconds(1)),m(U,"SECOND",U.seconds(1)),m(U,"MINUTE",U.minutes(1)),m(U,"HOUR",U.hours(1)),m(U,"DAY",U.days(1)),m(U,"MAX",new U((1n<<63n)-1n)),m(U,"MIN",new U(0)),m(U,"ZERO",new U(0)),m(U,"z",s.z.union([s.z.object({value:s.z.bigint()}).transform(t=>new U(t.value)),s.z.string().transform(t=>new U(BigInt(t))),s.z.instanceof(Number).transform(t=>new U(t)),s.z.number().transform(t=>new U(t)),s.z.instanceof(U)]));let W=U;const L=class C{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 C(e).valueOf()}greaterThan(e){return this.valueOf()>new C(e).valueOf()}lessThanOrEqual(e){return this.valueOf()<=new C(e).valueOf()}greaterThanOrEqual(e){return this.valueOf()>=new C(e).valueOf()}remainder(e){return ya(this,e)}truncate(e){return new C(BigInt(Math.trunc(Number(this.valueOf()/e.valueOf())))*e.valueOf())}toString(){const e=this.truncate(C.DAY),r=this.truncate(C.HOUR),n=this.truncate(C.MINUTE),i=this.truncate(C.SECOND),a=this.truncate(C.MILLISECOND),o=this.truncate(C.MICROSECOND),u=this.truncate(C.NANOSECOND),c=e,d=r.sub(e),f=n.sub(r),h=i.sub(n),E=a.sub(i),P=o.sub(a),ie=u.sub(o);let M="";return c.isZero||(M+=`${c.days}d `),d.isZero||(M+=`${d.hours}h `),f.isZero||(M+=`${f.minutes}m `),h.isZero||(M+=`${h.seconds}s `),E.isZero||(M+=`${E.milliseconds}ms `),P.isZero||(M+=`${P.microseconds}µs `),ie.isZero||(M+=`${ie.nanoseconds}ns`),M.trim()}get days(){return Number(this.valueOf())/Number(C.DAY.valueOf())}get hours(){return Number(this.valueOf())/Number(C.HOUR.valueOf())}get minutes(){return Number(this.valueOf())/Number(C.MINUTE.valueOf())}get seconds(){return Number(this.valueOf())/Number(C.SECOND.valueOf())}get milliseconds(){return Number(this.valueOf())/Number(C.MILLISECOND.valueOf())}get microseconds(){return Number(this.valueOf())/Number(C.MICROSECOND.valueOf())}get nanoseconds(){return Number(this.valueOf())}get isZero(){return this.valueOf()===BigInt(0)}equals(e){return this.valueOf()===new C(e).valueOf()}add(e){return new C(this.valueOf()+new C(e).valueOf())}sub(e){return new C(this.valueOf()-new C(e).valueOf())}static nanoseconds(e=1){return new C(e)}static microseconds(e=1){return C.nanoseconds(e*1e3)}static milliseconds(e=1){return C.microseconds(e*1e3)}static seconds(e=1){return C.milliseconds(e*1e3)}static minutes(e){return C.seconds(e.valueOf()*60)}static hours(e){return C.minutes(e*60)}static days(e){return C.hours(e*24)}};m(L,"NANOSECOND",L.nanoseconds(1)),m(L,"MICROSECOND",L.microseconds(1)),m(L,"MILLISECOND",L.milliseconds(1)),m(L,"SECOND",L.seconds(1)),m(L,"MINUTE",L.minutes(1)),m(L,"HOUR",L.hours(1)),m(L,"DAY",L.days(1)),m(L,"MAX",new L((1n<<63n)-1n)),m(L,"MIN",new L(0)),m(L,"ZERO",new L(0)),m(L,"z",s.z.union([s.z.object({value:s.z.bigint()}).transform(t=>new L(t.value)),s.z.string().transform(t=>new L(BigInt(t))),s.z.instanceof(Number).transform(t=>new L(t)),s.z.number().transform(t=>new L(t)),s.z.instanceof(L)]));let Z=L;const pt=class mr extends Number{constructor(e){e instanceof Number?super(e.valueOf()):super(e)}toString(){return`${this.valueOf()} Hz`}equals(e){return this.valueOf()===new mr(e).valueOf()}get period(){return Z.seconds(1/this.valueOf())}sampleCount(e){return new Z(e).seconds*this.valueOf()}byteCount(e,r){return this.sampleCount(e)*new le(r).valueOf()}span(e){return Z.seconds(e/this.valueOf())}byteSpan(e,r){return this.span(e.valueOf()/r.valueOf())}static hz(e){return new mr(e)}static khz(e){return mr.hz(e*1e3)}};m(pt,"z",s.z.union([s.z.number().transform(t=>new pt(t)),s.z.instanceof(Number).transform(t=>new pt(t)),s.z.instanceof(pt)]));let Ol=pt;const te=class extends Number{constructor(e){e instanceof Number?super(e.valueOf()):super(e)}length(e){return e.valueOf()/this.valueOf()}size(e){return new tn(e*this.valueOf())}};m(te,"UNKNOWN",new te(0)),m(te,"BIT128",new te(16)),m(te,"BIT64",new te(8)),m(te,"BIT32",new te(4)),m(te,"BIT16",new te(2)),m(te,"BIT8",new te(1)),m(te,"z",s.z.union([s.z.number().transform(t=>new te(t)),s.z.instanceof(Number).transform(t=>new te(t)),s.z.instanceof(te)]));let le=te;const Te=class wr{constructor(e,r){m(this,"start"),m(this,"end"),typeof e=="object"&&"start"in e?(this.start=new W(e.start),this.end=new W(e.end)):(this.start=new W(e),this.end=new W(r))}get span(){return new Z(this.end.valueOf()-this.start.valueOf())}get isValid(){return this.start.valueOf()<=this.end.valueOf()}makeValid(){return this.isValid?this:this.swap()}get isZero(){return this.span.isZero}get numeric(){return{start:Number(this.start.valueOf()),end:Number(this.end.valueOf())}}swap(){return new wr(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,r=Z.ZERO){e=e.makeValid();const n=this.makeValid();if(this.equals(e))return!0;if(e.end.equals(n.start)||n.end.equals(e.start))return!1;const i=W.max(n.start,e.start),a=W.min(n.end,e.end);return a.before(i)?!1:new Z(a.sub(i)).greaterThanOrEqual(r)}roughlyEquals(e,r){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<=r.valueOf()&&i<=r.valueOf()}contains(e){return e instanceof wr?this.contains(e.start)&&this.contains(e.end):this.start.beforeEq(e)&&this.end.after(e)}boundBy(e){const r=new wr(this.start,this.end);return e.start.after(this.start)&&(r.start=e.start),e.start.after(this.end)&&(r.end=e.start),e.end.before(this.end)&&(r.end=e.end),e.end.before(this.start)&&(r.start=e.end),r}};m(Te,"MAX",new Te(W.MIN,W.MAX)),m(Te,"MIN",new Te(W.MAX,W.MIN)),m(Te,"ZERO",new Te(W.ZERO,W.ZERO)),m(Te,"z",s.z.union([s.z.object({start:W.z,end:W.z}).transform(t=>new Te(t.start,t.end)),s.z.instanceof(Te)]));let tt=Te;const y=class Se extends String{constructor(e){if(e instanceof Se||typeof e=="string"||typeof e.valueOf()=="string"){super(e.valueOf());return}else{const r=Se.ARRAY_CONSTRUCTOR_DATA_TYPES.get(e.constructor.name);if(r!=null){super(r.valueOf());return}}throw super(Se.UNKNOWN.valueOf()),new Error(`unable to find data type for ${e.toString()}`)}get Array(){const e=Se.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(r=>this.equals(r))}toString(){return this.valueOf()}get isVariable(){return this.equals(Se.JSON)||this.equals(Se.STRING)}get isNumeric(){return!this.isVariable&&!this.equals(Se.UUID)}get isInteger(){return this.toString().startsWith("int")}get isFloat(){return this.toString().startsWith("float")}get density(){const e=Se.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 Se.BIG_INT_TYPES.some(e=>e.equals(this))}};m(y,"UNKNOWN",new y("unknown")),m(y,"FLOAT64",new y("float64")),m(y,"FLOAT32",new y("float32")),m(y,"INT64",new y("int64")),m(y,"INT32",new y("int32")),m(y,"INT16",new y("int16")),m(y,"INT8",new y("int8")),m(y,"UINT64",new y("uint64")),m(y,"UINT32",new y("uint32")),m(y,"UINT16",new y("uint16")),m(y,"UINT8",new y("uint8")),m(y,"BOOLEAN",y.UINT8),m(y,"TIMESTAMP",new y("timestamp")),m(y,"UUID",new y("uuid")),m(y,"STRING",new y("string")),m(y,"JSON",new y("json")),m(y,"ARRAY_CONSTRUCTORS",new Map([[y.UINT8.toString(),Uint8Array],[y.UINT16.toString(),Uint16Array],[y.UINT32.toString(),Uint32Array],[y.UINT64.toString(),BigUint64Array],[y.FLOAT32.toString(),Float32Array],[y.FLOAT64.toString(),Float64Array],[y.INT8.toString(),Int8Array],[y.INT16.toString(),Int16Array],[y.INT32.toString(),Int32Array],[y.INT64.toString(),BigInt64Array],[y.TIMESTAMP.toString(),BigInt64Array],[y.STRING.toString(),Uint8Array],[y.JSON.toString(),Uint8Array],[y.UUID.toString(),Uint8Array]])),m(y,"ARRAY_CONSTRUCTOR_DATA_TYPES",new Map([[Uint8Array.name,y.UINT8],[Uint16Array.name,y.UINT16],[Uint32Array.name,y.UINT32],[BigUint64Array.name,y.UINT64],[Float32Array.name,y.FLOAT32],[Float64Array.name,y.FLOAT64],[Int8Array.name,y.INT8],[Int16Array.name,y.INT16],[Int32Array.name,y.INT32],[BigInt64Array.name,y.INT64]])),m(y,"DENSITIES",new Map([[y.UINT8.toString(),le.BIT8],[y.UINT16.toString(),le.BIT16],[y.UINT32.toString(),le.BIT32],[y.UINT64.toString(),le.BIT64],[y.FLOAT32.toString(),le.BIT32],[y.FLOAT64.toString(),le.BIT64],[y.INT8.toString(),le.BIT8],[y.INT16.toString(),le.BIT16],[y.INT32.toString(),le.BIT32],[y.INT64.toString(),le.BIT64],[y.TIMESTAMP.toString(),le.BIT64],[y.STRING.toString(),le.UNKNOWN],[y.JSON.toString(),le.UNKNOWN],[y.UUID.toString(),le.BIT128]])),m(y,"ALL",[y.UNKNOWN,y.FLOAT64,y.FLOAT32,y.INT64,y.INT32,y.INT16,y.INT8,y.UINT64,y.UINT32,y.UINT16,y.UINT8,y.TIMESTAMP,y.UUID,y.STRING,y.JSON]),m(y,"BIG_INT_TYPES",[y.INT64,y.UINT64,y.TIMESTAMP]),m(y,"z",s.z.union([s.z.string().transform(t=>new y(t)),s.z.instanceof(y)]));let j=y;const ae=class J extends Number{constructor(e){super(e.valueOf())}largerThan(e){return this.valueOf()>e.valueOf()}smallerThan(e){return this.valueOf()<e.valueOf()}add(e){return J.bytes(this.valueOf()+e.valueOf())}sub(e){return J.bytes(this.valueOf()-e.valueOf())}truncate(e){return new J(Math.trunc(this.valueOf()/e.valueOf())*e.valueOf())}remainder(e){return J.bytes(this.valueOf()%e.valueOf())}get gigabytes(){return this.valueOf()/J.GIGABYTE.valueOf()}get megabytes(){return this.valueOf()/J.MEGABYTE.valueOf()}get kilobytes(){return this.valueOf()/J.KILOBYTE.valueOf()}get terabytes(){return this.valueOf()/J.TERABYTE.valueOf()}toString(){const e=this.truncate(J.TERABYTE),r=this.truncate(J.GIGABYTE),n=this.truncate(J.MEGABYTE),i=this.truncate(J.KILOBYTE),a=this.truncate(J.BYTE),o=e,u=r.sub(e),c=n.sub(r),d=i.sub(n),f=a.sub(i);let h="";return o.isZero||(h+=`${o.terabytes}TB `),u.isZero||(h+=`${u.gigabytes}GB `),c.isZero||(h+=`${c.megabytes}MB `),d.isZero||(h+=`${d.kilobytes}KB `),(!f.isZero||h==="")&&(h+=`${f.valueOf()}B`),h.trim()}static bytes(e=1){return new J(e)}static kilobytes(e=1){return J.bytes(e.valueOf()*1e3)}static megabytes(e=1){return J.kilobytes(e.valueOf()*1e3)}static gigabytes(e=1){return J.megabytes(e.valueOf()*1e3)}static terabytes(e){return J.gigabytes(e.valueOf()*1e3)}get isZero(){return this.valueOf()===0}};m(ae,"BYTE",new ae(1)),m(ae,"KILOBYTE",ae.kilobytes(1)),m(ae,"MEGABYTE",ae.megabytes(1)),m(ae,"GIGABYTE",ae.gigabytes(1)),m(ae,"TERABYTE",ae.terabytes(1)),m(ae,"ZERO",new ae(0)),m(ae,"z",s.z.union([s.z.number().transform(t=>new ae(t)),s.z.instanceof(ae)]));let tn=ae;const Tl=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)]),ga=t=>{const e=typeof t;return e==="string"||e==="number"||e==="boolean"||e==="bigint"||t instanceof W||t instanceof Z||t instanceof Date},Sl=(t,e,r,n=0)=>t.usesBigInt&&!e.usesBigInt?Number(r)-Number(n):!t.usesBigInt&&e.usesBigInt?BigInt(r)-BigInt(n):wt(r,-n),zl=t=>t==null?!1:Array.isArray(t)||t instanceof ArrayBuffer||ArrayBuffer.isView(t)&&!(t instanceof DataView)||t instanceof pa?!0:ga(t),Ye=-1,Nl=s.z.string().transform(t=>new Uint8Array(atob(t).split("").map(e=>e.charCodeAt(0))).buffer),El=s.z.union([s.z.null(),s.z.undefined()]).transform(()=>new Uint8Array().buffer),mt=class ke{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",Ye),m(this,"_refCount",0),m(this,"_cachedLength"),zl(e)&&(e={data:e});const{dataType:r,timeRange:n,sampleOffset:i=0,glBufferUsage:a="static",alignment:o=0n,key:u=da()}=e,c=e.data??[];if(c instanceof ke||typeof c=="object"&&"isSynnaxSeries"in c&&c.isSynnaxSeries===!0){const h=c;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 d=ga(c),f=Array.isArray(c);if(r!=null)this.dataType=new j(r);else{if(c instanceof ArrayBuffer)throw new Error("cannot infer data type from an ArrayBuffer instance when constructing a Series. Please provide a data type.");if(f||d){let h=c;if(!d){if(c.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=c[0]}if(typeof h=="string")this.dataType=j.STRING;else if(typeof h=="number")this.dataType=j.FLOAT64;else if(typeof h=="bigint")this.dataType=j.INT64;else if(typeof h=="boolean")this.dataType=j.BOOLEAN;else if(h instanceof W||h instanceof Date||h instanceof W)this.dataType=j.TIMESTAMP;else if(typeof h=="object")this.dataType=j.JSON;else throw new Error(`cannot infer data type of ${typeof h} when constructing a Series from a JS array`)}else this.dataType=new j(c)}if(!f&&!d)this._data=c;else{let h=d?[c]:c;const E=h[0];(E instanceof W||E instanceof Date||E instanceof Z)&&(h=h.map(P=>new W(P).valueOf())),this.dataType.equals(j.STRING)?(this._cachedLength=h.length,this._data=new TextEncoder().encode(h.join(`
|
|
3
|
+
`).map(l=>l.trim());if(n.length===0)return r!=null?r.parse({}):{};const a=n.split(",").map(l=>l.trim()),o={};return a.forEach(l=>{o[l]=[]}),i.forEach(l=>{const u=l.split(",").map(d=>d.trim());a.forEach((d,f)=>{const h=this.parseValue(u[f]);h!=null&&o[d].push(h)})}),r!=null?r.parse(o):o}parseValue(e){if(e==null||e.length===0)return null;const r=Number(e);return isNaN(r)?e.startsWith('"')&&e.endsWith('"')?e.slice(1,-1):e:r}static registerCustomType(){}},Gc=class{constructor(){Dt(this,"contentType","text/plain")}encode(e){return new TextEncoder().encode(e).buffer}decode(e,r){const n=new TextDecoder().decode(e);return r!=null?r.parse(n):n}};const yr=new Vc;new Wc;new Gc;const Fn=t=>[...new Set(t)],ta=t=>t!=null&&typeof t=="object"&&"toString"in t,Zc=t=>{if(ta(t))return(t==null?void 0:t.toString().length)===0;switch(typeof t){case"string":return t.length===0;case"number":return t===0;case"bigint":return t===0n;case"boolean":return!t;case"undefined":return!0;case"object":return t===null}},en=(t,e=!1)=>{const r=ta(t)?"stringer":typeof t;let n;switch(r){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 ${r}`),()=>-1}return e?na(n):n},Kc=(t,e,r)=>{const n=en(e[t],r);return(i,a)=>n(i[t],a[t])},Jc=(t,e)=>t.length!==e.length?t.length-e.length:t.every((r,n)=>r===e[n])?0:-1,ra=(t,e)=>{if(t.length!==e.length)return t.length-e.length;if(t.length===0)return 0;const r=en(t[0]),n=[...t].sort(r),i=[...e].sort(r);return n.every((a,o)=>a===i[o])?0:-1},Hc=(t,e)=>{const r=Fn(t),n=Fn(e);return ra(r,n)},Xc=(t,e)=>t===e?0:t==="first"&&e==="last"?1:-1,na=t=>(e,r)=>t(r,e),at=0,gr=-1,pr=1,sa=t=>t<at,ia=t=>t>at,Qc=t=>t>=at,aa=t=>t===at,el=(t,e)=>{const r=/([a-zA-Z]+)|(\d+)/g,n=t.replace(/[\s_.-]+/g,"").match(r),i=e.replace(/[\s_.-]+/g,"").match(r);if(!n||!i)return 0;for(let a=0;a<Math.min(n.length,i.length);a++){const o=n[a],l=i[a];if(isNaN(Number(o))&&isNaN(Number(l))){const u=o.localeCompare(l);if(u!==0)return u}else if(!isNaN(Number(o))&&!isNaN(Number(l))){const u=Number(o)-Number(l);if(u!==0)return u}else return isNaN(Number(o))?-1:1}return n.length-i.length},tl=Object.freeze(Object.defineProperty({__proto__:null,EQUAL:at,GREATER_THAN:pr,LESS_THAN:gr,isEqualTo:aa,isGreaterThan:ia,isGreaterThanEqual:Qc,isLessThan:sa,newF:en,newFieldF:Kc,order:Xc,primitiveArrays:Jc,reverseF:na,stringsWithNumbers:el,uniqueUnorderedPrimitiveArrays:Hc,unorderedPrimitiveArrays:ra},Symbol.toStringTag,{value:"Module"})),rl=(t,e)=>{let r=null;return e===0?t:(...n)=>{r!==null&&(clearTimeout(r),r=null),r=setTimeout(()=>t(...n),e)}},nl=(t,e)=>{let r=null;return e===0?t:(...n)=>{r===null&&(r=setTimeout(()=>{t(...n),r=null},e))}},oa=(t,e,r=".")=>{const n=t.split(r);return n.map((i,a)=>{const o=e(i,a,n);return o==null?null:typeof o=="string"?o:o.join(r)}).filter(i=>i!=null).join(r)},ms=(t,e,r={optional:!1,separator:"."})=>{r.separator??(r.separator=".");const{optional:n,getter:i=(l,u)=>l[u]}=r,a=e.split(r.separator);if(a.length===1&&a[0]==="")return t;let o=t;for(const l of a){const u=i(o,l);if(u==null){if(n)return null;throw new Error(`Path ${e} does not exist. ${l} is null`)}o=u}return o},sl=(t,e,r)=>{const n=e.split(".");let i=t;for(let a=0;a<n.length-1;a++){const o=n[a];i[o]==null&&(i[o]={}),i=i[o]}i[n[n.length-1]]=r},il=(t,e)=>{const r=e.split(".");let n=t;for(let i=0;i<r.length-1;i++){const a=r[i];if(n[a]==null)return;n=n[a]}if(Array.isArray(n)){const i=parseInt(r[r.length-1],10);if(isNaN(i))return;n.splice(i,1);return}delete n[r[r.length-1]]},al=(t,e)=>{const r=t.split(".");return e<0?r[r.length+e]:r[e]},ol=(t,e)=>{try{return ms(t,e),!0}catch{return!1}},cl=(t,e)=>{if(e.length===0)return!0;const r=t.split("."),n=e.split(".");if(n.length>r.length)return!1;for(let i=0;i<n.length;i++){const a=r[i],o=n[i];if(o!=="*"&&a!==o)return!1}return!0},ll=t=>JSON.parse(JSON.stringify(t)),ul=(t,...e)=>(e.forEach(r=>{let n=t;const i=r.split(".");i.forEach((a,o)=>{o===i.length-1?delete n[a]:a in n&&(n=n[a])})}),t),hl=(t,e,r="")=>{const n={},i=(a,o,l)=>{if(typeof a!=typeof o||a===null||o===null){n[l]=[a,o];return}if(typeof a=="object"&&typeof o=="object")if(Array.isArray(a)&&Array.isArray(o)){if(a.length!==o.length){n[l]=[a,o];return}for(let u=0;u<a.length;u++)i(a[u],o[u],`${l}[${u}]`)}else new Set([...Object.keys(a),...Object.keys(o)]).forEach(u=>{i(a[u],o[u],l!==""?`${l}.${u}`:u)});else a!==o&&(n[l]=[a,o])};return i(t,e,r),n},Vn=(t,e)=>{const r=Array.isArray(t),n=Array.isArray(e);if(r!==n)return!1;if(r&&n){const o=t,l=e;if(o.length!==l.length)return!1;for(let u=0;u<o.length;u++)if(!Vn(o[u],l[u]))return!1;return!0}if(t==null||e==null||typeof t!="object"||typeof e!="object")return t===e;if("equals"in t)return t.equals(e);const i=Object.keys(t),a=Object.keys(e);if(i.length!==a.length)return!1;for(const o of i){const l=t[o],u=e[o];if(typeof l=="object"&&typeof u=="object"){if(!Vn(l,u))return!1}else if(l!==u)return!1}return!0},ca=(t,e)=>{if(typeof t!="object"||t==null)return t===e;const r=Object.keys(t),n=Object.keys(e);if(n.length>r.length)return!1;for(const i of n){const a=t[i],o=e[i];if(typeof a=="object"&&typeof o=="object"){if(!ca(a,o))return!1}else if(a!==o)return!1}return!0},Wn=(t,...e)=>{if(e.length===0)return t;const r=e.shift();if(Mt(t)&&Mt(r))for(const n in r)try{Mt(r[n])?(n in t||Object.assign(t,{[n]:{}}),Wn(t[n],r[n])):Object.assign(t,{[n]:r[n]})}catch(i){throw i instanceof TypeError?new TypeError(`.${n}: ${i.message}`):i}return Wn(t,...e)},dl=(t,e,r)=>{const n=(i,a,o)=>{for(const l in a){const u=a[l];if(o!=null&&o.shape[l]){const d=o.shape[l].safeParse(u);d.success&&(i[l]=d.data)}else typeof u=="object"&&!Array.isArray(u)&&u!==null&&o&&o.shape&&o.shape[l]&&(i[l]||(i[l]={}),n(i[l],u,o.shape[l]))}return i};return n({...t},e,r)},la=Object.freeze(Object.defineProperty({__proto__:null,copy:ll,deleteD:ul,difference:hl,element:al,equal:Vn,get:ms,has:ol,override:Wn,overrideValidItems:dl,partialEqual:ca,pathsMatch:cl,remove:il,set:sl,transformPath:oa},Symbol.toStringTag,{value:"Module"})),ua=t=>oa(t,(e,r,n)=>{const i=r===n.length-1,a=!isNaN(parseInt(e)),o=!isNaN(parseInt(n[r+1]));return a&&(e="element"),i||o?e:[e,"shape"]}),Js=(t,e)=>{if(t==null)return null;const r=t[e];return r==null&&typeof t=="object"&&"sourceType"in t?t.sourceType()[e]:r},fl=(t,e,r)=>ms(Js(t,"shape"),ua(e),{...r,getter:Js}),yl=(t,e)=>r=>{const n=e.find(i=>i.safeParse(r).success);return n==null?null:t(n.parse(r))},ha=s.z.bigint().or(s.z.string().transform(BigInt)),gl=Object.freeze(Object.defineProperty({__proto__:null,bigInt:ha,getFieldSchema:fl,getFieldSchemaPath:ua,transformer:yl},Symbol.toStringTag,{value:"Module"}));var pl=Object.defineProperty,ml=(t,e,r)=>e in t?pl(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,m=(t,e,r)=>ml(t,typeof e!="symbol"?e+"":e,r);let wl=(t,e=21)=>(r=e)=>{let n="",i=r;for(;i--;)n+=t[Math.random()*t.length|0];return n};const bl="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",da=wl(bl,11),fa=Object.freeze(Object.defineProperty({__proto__:null,id:da},Symbol.toStringTag,{value:"Module"})),vl=s.z.enum(["static","dynamic"]),ya=(t,e)=>{const r=new W(e);if(![Z.DAY,Z.HOUR,Z.MINUTE,Z.SECOND,Z.MILLISECOND,Z.MICROSECOND,Z.NANOSECOND].some(i=>i.equals(r)))throw new Error("Invalid argument for remainder. Must be an even TimeSpan or Timestamp");const n=t.valueOf()%r.valueOf();return t instanceof W?new W(n):new Z(n)},U=class S{constructor(e,r="UTC"){if(m(this,"value"),m(this,"encodeValue",!0),e==null)this.value=S.now().valueOf();else if(e instanceof Date)this.value=BigInt(e.getTime())*S.MILLISECOND.valueOf();else if(typeof e=="string")this.value=S.parseDateTimeString(e,r).valueOf();else if(Array.isArray(e))this.value=S.parseDate(e);else{let n=BigInt(0);e instanceof Number&&(e=e.valueOf()),r==="local"&&(n=S.utcOffset.valueOf()),typeof e=="number"&&(isFinite(e)?e=Math.trunc(e):(isNaN(e)&&(e=0),e===1/0?e=S.MAX:e=S.MIN)),this.value=BigInt(e.valueOf())+n}}static parseDate([e=1970,r=1,n=1]){const i=new Date(e,r-1,n,0,0,0,0);return new S(BigInt(i.getTime())*S.MILLISECOND.valueOf()).truncate(S.DAY).valueOf()}encode(){return this.value.toString()}valueOf(){return this.value}static parseTimeString(e,r="UTC"){const[n,i,a]=e.split(":");let o="00",l="00";a!=null&&([o,l]=a.split("."));let u=S.hours(parseInt(n??"00",10)).add(S.minutes(parseInt(i??"00",10))).add(S.seconds(parseInt(o??"00",10))).add(S.milliseconds(parseInt(l??"00",10)));return r==="local"&&(u=u.add(S.utcOffset)),u.valueOf()}static parseDateTimeString(e,r="UTC"){if(!e.includes("/")&&!e.includes("-"))return S.parseTimeString(e,r);const n=new Date(e);return e.includes(":")||n.setUTCHours(0,0,0,0),new S(BigInt(n.getTime())*S.MILLISECOND.valueOf(),r).valueOf()}fString(e="ISO",r="UTC"){switch(e){case"ISODate":return this.toISOString(r).slice(0,10);case"ISOTime":return this.toISOString(r).slice(11,23);case"time":return this.timeString(!1,r);case"preciseTime":return this.timeString(!0,r);case"date":return this.dateString();case"preciseDate":return`${this.dateString()} ${this.timeString(!0,r)}`;case"dateTime":return`${this.dateString()} ${this.timeString(!1,r)}`;default:return this.toISOString(r)}}toISOString(e="UTC"){return e==="UTC"?this.date().toISOString():this.sub(S.utcOffset).date().toISOString()}timeString(e=!1,r="UTC"){const n=this.toISOString(r);return e?n.slice(11,23):n.slice(11,19)}dateString(){const e=this.date(),r=e.toLocaleString("default",{month:"short"}),n=e.toLocaleString("default",{day:"numeric"});return`${r} ${n}`}static get utcOffset(){return new Z(BigInt(new Date().getTimezoneOffset())*S.MINUTE.valueOf())}static since(e){return new S().span(e)}date(){return new Date(this.milliseconds())}equals(e){return this.valueOf()===new S(e).valueOf()}span(e){return this.range(e).span}range(e){return new tt(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 S(e).valueOf()}afterEq(e){return this.valueOf()>=new S(e).valueOf()}before(e){return this.valueOf()<new S(e).valueOf()}beforeEq(e){return this.valueOf()<=new S(e).valueOf()}add(e){return new S(this.valueOf()+BigInt(e.valueOf()))}sub(e){return new S(this.valueOf()-BigInt(e.valueOf()))}milliseconds(){return Number(this.valueOf())/Number(S.MILLISECOND.valueOf())}toString(){return this.date().toISOString()}remainder(e){return ya(this,e)}get isToday(){return this.truncate(Z.DAY).equals(S.now().truncate(Z.DAY))}truncate(e){return this.sub(this.remainder(e))}static now(){return new S(new Date)}static max(...e){let r=S.MIN;for(const n of e){const i=new S(n);i.after(r)&&(r=i)}return r}static min(...e){let r=S.MAX;for(const n of e){const i=new S(n);i.before(r)&&(r=i)}return r}static nanoseconds(e){return new S(e)}static microseconds(e){return S.nanoseconds(e*1e3)}static milliseconds(e){return S.microseconds(e*1e3)}static seconds(e){return S.milliseconds(e*1e3)}static minutes(e){return S.seconds(e*60)}static hours(e){return S.minutes(e*60)}static days(e){return S.hours(e*24)}};m(U,"NANOSECOND",U.nanoseconds(1)),m(U,"MICROSECOND",U.microseconds(1)),m(U,"MILLISECOND",U.milliseconds(1)),m(U,"SECOND",U.seconds(1)),m(U,"MINUTE",U.minutes(1)),m(U,"HOUR",U.hours(1)),m(U,"DAY",U.days(1)),m(U,"MAX",new U((1n<<63n)-1n)),m(U,"MIN",new U(0)),m(U,"ZERO",new U(0)),m(U,"z",s.z.union([s.z.object({value:s.z.bigint()}).transform(t=>new U(t.value)),s.z.string().transform(t=>new U(BigInt(t))),s.z.instanceof(Number).transform(t=>new U(t)),s.z.number().transform(t=>new U(t)),s.z.instanceof(U)]));let W=U;const L=class C{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 C(e).valueOf()}greaterThan(e){return this.valueOf()>new C(e).valueOf()}lessThanOrEqual(e){return this.valueOf()<=new C(e).valueOf()}greaterThanOrEqual(e){return this.valueOf()>=new C(e).valueOf()}remainder(e){return ya(this,e)}truncate(e){return new C(BigInt(Math.trunc(Number(this.valueOf()/e.valueOf())))*e.valueOf())}toString(){const e=this.truncate(C.DAY),r=this.truncate(C.HOUR),n=this.truncate(C.MINUTE),i=this.truncate(C.SECOND),a=this.truncate(C.MILLISECOND),o=this.truncate(C.MICROSECOND),l=this.truncate(C.NANOSECOND),u=e,d=r.sub(e),f=n.sub(r),h=i.sub(n),E=a.sub(i),P=o.sub(a),ie=l.sub(o);let M="";return u.isZero||(M+=`${u.days}d `),d.isZero||(M+=`${d.hours}h `),f.isZero||(M+=`${f.minutes}m `),h.isZero||(M+=`${h.seconds}s `),E.isZero||(M+=`${E.milliseconds}ms `),P.isZero||(M+=`${P.microseconds}µs `),ie.isZero||(M+=`${ie.nanoseconds}ns`),M.trim()}get days(){return Number(this.valueOf())/Number(C.DAY.valueOf())}get hours(){return Number(this.valueOf())/Number(C.HOUR.valueOf())}get minutes(){return Number(this.valueOf())/Number(C.MINUTE.valueOf())}get seconds(){return Number(this.valueOf())/Number(C.SECOND.valueOf())}get milliseconds(){return Number(this.valueOf())/Number(C.MILLISECOND.valueOf())}get microseconds(){return Number(this.valueOf())/Number(C.MICROSECOND.valueOf())}get nanoseconds(){return Number(this.valueOf())}get isZero(){return this.valueOf()===BigInt(0)}equals(e){return this.valueOf()===new C(e).valueOf()}add(e){return new C(this.valueOf()+new C(e).valueOf())}sub(e){return new C(this.valueOf()-new C(e).valueOf())}static nanoseconds(e=1){return new C(e)}static microseconds(e=1){return C.nanoseconds(e*1e3)}static milliseconds(e=1){return C.microseconds(e*1e3)}static seconds(e=1){return C.milliseconds(e*1e3)}static minutes(e){return C.seconds(e.valueOf()*60)}static hours(e){return C.minutes(e*60)}static days(e){return C.hours(e*24)}};m(L,"NANOSECOND",L.nanoseconds(1)),m(L,"MICROSECOND",L.microseconds(1)),m(L,"MILLISECOND",L.milliseconds(1)),m(L,"SECOND",L.seconds(1)),m(L,"MINUTE",L.minutes(1)),m(L,"HOUR",L.hours(1)),m(L,"DAY",L.days(1)),m(L,"MAX",new L((1n<<63n)-1n)),m(L,"MIN",new L(0)),m(L,"ZERO",new L(0)),m(L,"z",s.z.union([s.z.object({value:s.z.bigint()}).transform(t=>new L(t.value)),s.z.string().transform(t=>new L(BigInt(t))),s.z.instanceof(Number).transform(t=>new L(t)),s.z.number().transform(t=>new L(t)),s.z.instanceof(L)]));let Z=L;const pt=class mr extends Number{constructor(e){e instanceof Number?super(e.valueOf()):super(e)}toString(){return`${this.valueOf()} Hz`}equals(e){return this.valueOf()===new mr(e).valueOf()}get period(){return Z.seconds(1/this.valueOf())}sampleCount(e){return new Z(e).seconds*this.valueOf()}byteCount(e,r){return this.sampleCount(e)*new le(r).valueOf()}span(e){return Z.seconds(e/this.valueOf())}byteSpan(e,r){return this.span(e.valueOf()/r.valueOf())}static hz(e){return new mr(e)}static khz(e){return mr.hz(e*1e3)}};m(pt,"z",s.z.union([s.z.number().transform(t=>new pt(t)),s.z.instanceof(Number).transform(t=>new pt(t)),s.z.instanceof(pt)]));let Ol=pt;const te=class extends Number{constructor(e){e instanceof Number?super(e.valueOf()):super(e)}length(e){return e.valueOf()/this.valueOf()}size(e){return new tn(e*this.valueOf())}};m(te,"UNKNOWN",new te(0)),m(te,"BIT128",new te(16)),m(te,"BIT64",new te(8)),m(te,"BIT32",new te(4)),m(te,"BIT16",new te(2)),m(te,"BIT8",new te(1)),m(te,"z",s.z.union([s.z.number().transform(t=>new te(t)),s.z.instanceof(Number).transform(t=>new te(t)),s.z.instanceof(te)]));let le=te;const Te=class wr{constructor(e,r){m(this,"start"),m(this,"end"),typeof e=="object"&&"start"in e?(this.start=new W(e.start),this.end=new W(e.end)):(this.start=new W(e),this.end=new W(r))}get span(){return new Z(this.end.valueOf()-this.start.valueOf())}get isValid(){return this.start.valueOf()<=this.end.valueOf()}makeValid(){return this.isValid?this:this.swap()}get isZero(){return this.span.isZero}get numeric(){return{start:Number(this.start.valueOf()),end:Number(this.end.valueOf())}}swap(){return new wr(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,r=Z.ZERO){e=e.makeValid();const n=this.makeValid();if(this.equals(e))return!0;if(e.end.equals(n.start)||n.end.equals(e.start))return!1;const i=W.max(n.start,e.start),a=W.min(n.end,e.end);return a.before(i)?!1:new Z(a.sub(i)).greaterThanOrEqual(r)}roughlyEquals(e,r){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<=r.valueOf()&&i<=r.valueOf()}contains(e){return e instanceof wr?this.contains(e.start)&&this.contains(e.end):this.start.beforeEq(e)&&this.end.after(e)}boundBy(e){const r=new wr(this.start,this.end);return e.start.after(this.start)&&(r.start=e.start),e.start.after(this.end)&&(r.end=e.start),e.end.before(this.end)&&(r.end=e.end),e.end.before(this.start)&&(r.start=e.end),r}};m(Te,"MAX",new Te(W.MIN,W.MAX)),m(Te,"MIN",new Te(W.MAX,W.MIN)),m(Te,"ZERO",new Te(W.ZERO,W.ZERO)),m(Te,"z",s.z.union([s.z.object({start:W.z,end:W.z}).transform(t=>new Te(t.start,t.end)),s.z.instanceof(Te)]));let tt=Te;const y=class Se extends String{constructor(e){if(e instanceof Se||typeof e=="string"||typeof e.valueOf()=="string"){super(e.valueOf());return}else{const r=Se.ARRAY_CONSTRUCTOR_DATA_TYPES.get(e.constructor.name);if(r!=null){super(r.valueOf());return}}throw super(Se.UNKNOWN.valueOf()),new Error(`unable to find data type for ${e.toString()}`)}get Array(){const e=Se.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(r=>this.equals(r))}toString(){return this.valueOf()}get isVariable(){return this.equals(Se.JSON)||this.equals(Se.STRING)}get isNumeric(){return!this.isVariable&&!this.equals(Se.UUID)}get isInteger(){return this.toString().startsWith("int")}get isFloat(){return this.toString().startsWith("float")}get density(){const e=Se.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 Se.BIG_INT_TYPES.some(e=>e.equals(this))}};m(y,"UNKNOWN",new y("unknown")),m(y,"FLOAT64",new y("float64")),m(y,"FLOAT32",new y("float32")),m(y,"INT64",new y("int64")),m(y,"INT32",new y("int32")),m(y,"INT16",new y("int16")),m(y,"INT8",new y("int8")),m(y,"UINT64",new y("uint64")),m(y,"UINT32",new y("uint32")),m(y,"UINT16",new y("uint16")),m(y,"UINT8",new y("uint8")),m(y,"BOOLEAN",y.UINT8),m(y,"TIMESTAMP",new y("timestamp")),m(y,"UUID",new y("uuid")),m(y,"STRING",new y("string")),m(y,"JSON",new y("json")),m(y,"ARRAY_CONSTRUCTORS",new Map([[y.UINT8.toString(),Uint8Array],[y.UINT16.toString(),Uint16Array],[y.UINT32.toString(),Uint32Array],[y.UINT64.toString(),BigUint64Array],[y.FLOAT32.toString(),Float32Array],[y.FLOAT64.toString(),Float64Array],[y.INT8.toString(),Int8Array],[y.INT16.toString(),Int16Array],[y.INT32.toString(),Int32Array],[y.INT64.toString(),BigInt64Array],[y.TIMESTAMP.toString(),BigInt64Array],[y.STRING.toString(),Uint8Array],[y.JSON.toString(),Uint8Array],[y.UUID.toString(),Uint8Array]])),m(y,"ARRAY_CONSTRUCTOR_DATA_TYPES",new Map([[Uint8Array.name,y.UINT8],[Uint16Array.name,y.UINT16],[Uint32Array.name,y.UINT32],[BigUint64Array.name,y.UINT64],[Float32Array.name,y.FLOAT32],[Float64Array.name,y.FLOAT64],[Int8Array.name,y.INT8],[Int16Array.name,y.INT16],[Int32Array.name,y.INT32],[BigInt64Array.name,y.INT64]])),m(y,"DENSITIES",new Map([[y.UINT8.toString(),le.BIT8],[y.UINT16.toString(),le.BIT16],[y.UINT32.toString(),le.BIT32],[y.UINT64.toString(),le.BIT64],[y.FLOAT32.toString(),le.BIT32],[y.FLOAT64.toString(),le.BIT64],[y.INT8.toString(),le.BIT8],[y.INT16.toString(),le.BIT16],[y.INT32.toString(),le.BIT32],[y.INT64.toString(),le.BIT64],[y.TIMESTAMP.toString(),le.BIT64],[y.STRING.toString(),le.UNKNOWN],[y.JSON.toString(),le.UNKNOWN],[y.UUID.toString(),le.BIT128]])),m(y,"ALL",[y.UNKNOWN,y.FLOAT64,y.FLOAT32,y.INT64,y.INT32,y.INT16,y.INT8,y.UINT64,y.UINT32,y.UINT16,y.UINT8,y.TIMESTAMP,y.UUID,y.STRING,y.JSON]),m(y,"BIG_INT_TYPES",[y.INT64,y.UINT64,y.TIMESTAMP]),m(y,"z",s.z.union([s.z.string().transform(t=>new y(t)),s.z.instanceof(y)]));let j=y;const ae=class J extends Number{constructor(e){super(e.valueOf())}largerThan(e){return this.valueOf()>e.valueOf()}smallerThan(e){return this.valueOf()<e.valueOf()}add(e){return J.bytes(this.valueOf()+e.valueOf())}sub(e){return J.bytes(this.valueOf()-e.valueOf())}truncate(e){return new J(Math.trunc(this.valueOf()/e.valueOf())*e.valueOf())}remainder(e){return J.bytes(this.valueOf()%e.valueOf())}get gigabytes(){return this.valueOf()/J.GIGABYTE.valueOf()}get megabytes(){return this.valueOf()/J.MEGABYTE.valueOf()}get kilobytes(){return this.valueOf()/J.KILOBYTE.valueOf()}get terabytes(){return this.valueOf()/J.TERABYTE.valueOf()}toString(){const e=this.truncate(J.TERABYTE),r=this.truncate(J.GIGABYTE),n=this.truncate(J.MEGABYTE),i=this.truncate(J.KILOBYTE),a=this.truncate(J.BYTE),o=e,l=r.sub(e),u=n.sub(r),d=i.sub(n),f=a.sub(i);let h="";return o.isZero||(h+=`${o.terabytes}TB `),l.isZero||(h+=`${l.gigabytes}GB `),u.isZero||(h+=`${u.megabytes}MB `),d.isZero||(h+=`${d.kilobytes}KB `),(!f.isZero||h==="")&&(h+=`${f.valueOf()}B`),h.trim()}static bytes(e=1){return new J(e)}static kilobytes(e=1){return J.bytes(e.valueOf()*1e3)}static megabytes(e=1){return J.kilobytes(e.valueOf()*1e3)}static gigabytes(e=1){return J.megabytes(e.valueOf()*1e3)}static terabytes(e){return J.gigabytes(e.valueOf()*1e3)}get isZero(){return this.valueOf()===0}};m(ae,"BYTE",new ae(1)),m(ae,"KILOBYTE",ae.kilobytes(1)),m(ae,"MEGABYTE",ae.megabytes(1)),m(ae,"GIGABYTE",ae.gigabytes(1)),m(ae,"TERABYTE",ae.terabytes(1)),m(ae,"ZERO",new ae(0)),m(ae,"z",s.z.union([s.z.number().transform(t=>new ae(t)),s.z.instanceof(ae)]));let tn=ae;const Tl=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)]),ga=t=>{const e=typeof t;return e==="string"||e==="number"||e==="boolean"||e==="bigint"||t instanceof W||t instanceof Z||t instanceof Date},Sl=(t,e,r,n=0)=>t.usesBigInt&&!e.usesBigInt?Number(r)-Number(n):!t.usesBigInt&&e.usesBigInt?BigInt(r)-BigInt(n):wt(r,-n),zl=t=>t==null?!1:Array.isArray(t)||t instanceof ArrayBuffer||ArrayBuffer.isView(t)&&!(t instanceof DataView)||t instanceof pa?!0:ga(t),Ye=-1,Nl=s.z.string().transform(t=>new Uint8Array(atob(t).split("").map(e=>e.charCodeAt(0))).buffer),El=s.z.union([s.z.null(),s.z.undefined()]).transform(()=>new Uint8Array().buffer),mt=class ke{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",Ye),m(this,"_refCount",0),m(this,"_cachedLength"),zl(e)&&(e={data:e});const{dataType:r,timeRange:n,sampleOffset:i=0,glBufferUsage:a="static",alignment:o=0n,key:l=da()}=e,u=e.data??[];if(u instanceof ke||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 d=ga(u),f=Array.isArray(u);if(r!=null)this.dataType=new j(r);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(f||d){let h=u;if(!d){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=j.STRING;else if(typeof h=="number")this.dataType=j.FLOAT64;else if(typeof h=="bigint")this.dataType=j.INT64;else if(typeof h=="boolean")this.dataType=j.BOOLEAN;else if(h instanceof W||h instanceof Date||h instanceof W)this.dataType=j.TIMESTAMP;else if(typeof h=="object")this.dataType=j.JSON;else throw new Error(`cannot infer data type of ${typeof h} when constructing a Series from a JS array`)}else this.dataType=new j(u)}if(!f&&!d)this._data=u;else{let h=d?[u]:u;const E=h[0];(E instanceof W||E instanceof Date||E instanceof Z)&&(h=h.map(P=>new W(P).valueOf())),this.dataType.equals(j.STRING)?(this._cachedLength=h.length,this._data=new TextEncoder().encode(h.join(`
|
|
4
4
|
`)+`
|
|
5
5
|
`)):this.dataType.equals(j.JSON)?(this._cachedLength=h.length,this._data=new TextEncoder().encode(h.map(P=>yr.encodeString(P)).join(`
|
|
6
6
|
`)+`
|
|
7
|
-
`)):this._data=new this.dataType.Array(h).buffer}this.key=
|
|
7
|
+
`)):this._data=new this.dataType.Array(h).buffer}this.key=l,this.alignment=o,this.sampleOffset=i??0,this._timeRange=n,this.gl={control:null,buffer:null,prevBuffer:0,bufferUsage:a}}static alloc({capacity:e,dataType:r,...n}){if(e===0)throw new Error("[Series] - cannot allocate an array of length 0");const i=new new j(r).Array(e),a=new ke({data:i.buffer,dataType:r,...n});return a.writePos=0,a}static generateTimestamps(e,r,n){const i=n.spanRange(r.span(e)),a=new BigInt64Array(e);for(let o=0;o<e;o++)a[o]=BigInt(n.add(r.span(o)).valueOf());return new ke({data:a,dataType:j.TIMESTAMP,timeRange:i})}get refCount(){return this._refCount}static fromStrings(e,r){const n=new TextEncoder().encode(e.join(`
|
|
8
8
|
`)+`
|
|
9
9
|
`);return new ke({data:n,dataType:j.STRING,timeRange:r})}static fromJSON(e,r){const n=new TextEncoder().encode(e.map(i=>yr.encodeString(i)).join(`
|
|
10
10
|
`)+`
|
|
11
11
|
`);return new ke({data:n,dataType:j.JSON,timeRange:r})}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===Ye)return 0;const r=this.capacity-this.writePos,n=r<e.length?e.slice(0,r):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===Ye?this.underlyingData:new this.dataType.Array(this._data,0,this.writePos)}toStrings(){if(!this.dataType.matches(j.STRING,j.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(j.UUID))throw new Error("cannot convert non-uuid series to uuids");const e=j.UUID.density.valueOf(),r=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),o=>o.toString(16).padStart(2,"0")).join("").replace(/(.{8})(.{4})(.{4})(.{4})(.{12})/,"$1-$2-$3-$4-$5");r[n]=a}return r}parseJSON(e){if(!this.dataType.equals(j.JSON))throw new Error("cannot convert non-string series to strings");return new TextDecoder().decode(this.buffer).split(`
|
|
13
|
-
`).slice(0,-1).map(r=>e.parse(yr.decodeString(r)))}get timeRange(){if(this._timeRange==null)throw new Error("time range not set on series");return this._timeRange}get byteCapacity(){return new tn(this.buffer.byteLength)}get capacity(){return this.dataType.density.length(this.byteCapacity)}get byteLength(){return this.writePos===Ye?this.byteCapacity:this.dataType.density.size(this.writePos)}get length(){return this._cachedLength!=null?this._cachedLength:this.dataType.isVariable?this.calculateCachedLength():this.writePos===Ye?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(r=>{r===10&&e++}),this._cachedLength=e,e}convert(e,r=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]=Sl(this.dataType,e,this.data[i],r);return new ke({data:n.buffer,dataType:e,timeRange:this._timeRange,sampleOffset:r,glBufferUsage:this.gl.bufferUsage,alignment:this.alignment})}calcRawMax(){if(this.length===0)return-1/0;if(this.dataType.equals(j.TIMESTAMP))this._cachedMax=this.data[this.data.length-1];else if(this.dataType.usesBigInt){const e=this.data;this._cachedMax=e.reduce((r,n)=>r>n?r:n)}else{const e=this.data;this._cachedMax=e.reduce((r,n)=>r>n?r: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()),wt(this._cachedMax,this.sampleOffset))}calcRawMin(){if(this.length===0)return 1/0;if(this.dataType.equals(j.TIMESTAMP))this._cachedMin=this.data[0];else if(this.dataType.usesBigInt){const e=this.data;this._cachedMin=e.reduce((r,n)=>r<n?r:n)}else{const e=this.data;this._cachedMin=e.reduce((r,n)=>r<n?r: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()),wt(this._cachedMin,this.sampleOffset))}get bounds(){return O.o(Number(this.min),Number(this.max))}maybeRecomputeMinMax(e){if(this._cachedMin!=null){const r=e._cachedMin??e.calcRawMin();r<this._cachedMin&&(this._cachedMin=r)}if(this._cachedMax!=null){const r=e._cachedMax??e.calcRawMax();r>this._cachedMax&&(this._cachedMax=r)}}enrich(){this.max,this.min}get range(){return wt(this.max,-this.min)}at(e,r){if(this.dataType.isVariable)return this.atVariable(e,r??!1);e<0&&(e=this.length+e);const n=this.data[e];if(n==null){if(r===!0)throw new Error(`[series] - no value at index ${e}`);return}return wt(n,this.sampleOffset)}atVariable(e,r){e<0&&(e=this.length+e);let n=0,i=0;for(let o=0;o<this.data.length;o++)if(this.data[o]===10){if(e===0){i=o;break}n=o+1,e--}if(i===0&&(i=this.data.length),n>=i||e>0){if(r)throw new Error(`[series] - no value at index ${e}`);return}const a=this.data.slice(n,i);return this.dataType.equals(j.STRING)?new TextDecoder().decode(a):O.T(JSON.parse(new TextDecoder().decode(a)))}binarySearch(e){let r=0,n=this.length-1;const i=en(e);for(;r<=n;){const a=Math.floor((r+n)/2),o=i(this.at(a,!0),e);if(o===0)return a;o<0?r=a+1:n=a-1}return r}updateGLBuffer(e){if(this.gl.control=e,!this.dataType.equals(j.FLOAT32))throw new Error("Only FLOAT32 arrays can be used in WebGL");const{buffer:r,bufferUsage:n,prevBuffer:i}=this.gl;if(r==null&&(this.gl.buffer=e.createBuffer()),this.writePos!==i)if(e.bindBuffer(e.ARRAY_BUFFER,this.gl.buffer),this.writePos!==Ye){i===0&&e.bufferData(e.ARRAY_BUFFER,this.byteCapacity.valueOf(),e.STATIC_DRAW);const a=this.dataType.density.size(i).valueOf(),o=this.underlyingData.slice(this.gl.prevBuffer,this.writePos);e.bufferSubData(e.ARRAY_BUFFER,a,o.buffer),this.gl.prevBuffer=this.writePos}else e.bufferData(e.ARRAY_BUFFER,this.buffer,n==="static"?e.STATIC_DRAW:e.DYNAMIC_DRAW),this.gl.prevBuffer=Ye}as(e){if(e==="string"){if(!this.dataType.equals(j.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(j.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 O.o(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 Il(this);return this.dataType.equals(j.JSON)?new Al(e):e}return new kl(this)}slice(e,r){if(e<=0&&(r==null||r>=this.length))return this;const n=this.data.slice(e,r);return new ke({data:n,dataType:this.dataType,timeRange:this._timeRange,sampleOffset:this.sampleOffset,glBufferUsage:this.gl.bufferUsage,alignment:this.alignment+BigInt(e)})}reAlign(e){return new ke({data:this.buffer,dataType:this.dataType,timeRange:tt.ZERO,sampleOffset:this.sampleOffset,glBufferUsage:"static",alignment:e})}};m(mt,"crudeZ",s.z.object({timeRange:tt.z.optional(),dataType:j.z,alignment:ha.optional(),data:s.z.union([Nl,El,s.z.instanceof(ArrayBuffer)]),glBufferUsage:vl.optional().default("static").optional()})),m(mt,"z",mt.crudeZ.transform(t=>new mt(t)));let pa=mt,Il=class{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,r=this.series.data;for(;this.index<r.length&&r[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 Hs,Xs;let Al=class{constructor(e){m(this,"wrapped"),m(this,Hs,"JSONSeriesIterator"),this.wrapped=e}next(){const e=this.wrapped.next();return e.done===!0?{done:!0,value:void 0}:{done:!1,value:yr.decodeString(e.value)}}[(Xs=Symbol.iterator,Hs=Symbol.toStringTag,Xs)](){return this}};var Qs,ei;let kl=class{constructor(e){m(this,"series"),m(this,"index"),m(this,Qs,"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)}}[(ei=Symbol.iterator,Qs=Symbol.toStringTag,ei)](){return this}};const wt=(t,e)=>typeof t=="bigint"&&typeof e=="bigint"||typeof t=="number"&&typeof e=="number"?t+e:e===0?t:t===0?e:Number(t)+Number(e);let xl=class{constructor(e){if(m(this,"series"),e.length!==0){const r=e[0].dataType;for(let n=1;n<e.length;n++)if(!e[n].dataType.equals(r))throw new Error("[multi-series] - series must have the same data type")}this.series=e}as(e){if(!new j(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?j.UNKNOWN:this.series[0].dataType}get timeRange(){return this.series.length===0?tt.ZERO:new tt(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,r)=>e+r.length,0)}at(e,r=!1){e<0&&(e=this.length+e);for(const n of this.series){if(e<n.length)return n.at(e,r);e-=n.length}if(r)throw new Error(`[series] - no value at index ${e}`)}get byteLength(){return new tn(this.series.reduce((e,r)=>e+r.byteLength.valueOf(),0))}get data(){const e=new this.dataType.Array(this.length);let r=0;for(const n of this.series)e.set(n.data,r),r+=n.length;return new this.dataType.Array(e)}[Symbol.iterator](){return this.series.length===0?{next(){return{done:!0,value:void 0}}}:new Cl(this.series)}};var ti,ri;class Cl{constructor(e){m(this,"series"),m(this,"seriesIndex"),m(this,"internal"),m(this,ti,"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())}[(ri=Symbol.iterator,ti=Symbol.toStringTag,ri)](){return this}}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 ma=()=>typeof process<"u"&&process.versions!=null&&process.versions.node!=null?"node":typeof window>"u"||window.document===void 0?"webworker":"browser",$l=ma(),wa=["MacOS","Windows","Linux","Docker"],Rl=s.z.enum(wa);let vn;const jl=()=>{if(typeof window>"u")return;const t=window.navigator.userAgent.toLowerCase();if(t.includes("mac"))return"MacOS";if(t.includes("win"))return"Windows";if(t.includes("linux"))return"Linux"},Ml=(t={})=>{const{force:e,default:r}=t;return e??vn??(vn=jl(),vn??r)},ba=Object.freeze(Object.defineProperty({__proto__:null,OPERATING_SYSTEMS:wa,RUNTIME:$l,detect:ma,getOS:Ml,osZ:Rl},Symbol.toStringTag,{value:"Module"})),Dl=t=>Array.isArray(t)?t:[t],Pl=t=>Array.isArray(t)?t:t===null?[]:[t];var Bl=Object.defineProperty,Ul=(t,e,r)=>e in t?Bl(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,bt=(t,e,r)=>Ul(t,typeof e!="symbol"?e+"":e,r);const Ll=(...t)=>t.map(va).join(""),va=t=>(t.endsWith("/")||(t+="/"),t.startsWith("/")&&(t=t.slice(1)),t),_l=t=>t.endsWith("/")?t.slice(0,-1):t,ni=class Gn{constructor({host:e,port:r,protocol:n="",pathPrefix:i=""}){bt(this,"protocol"),bt(this,"host"),bt(this,"port"),bt(this,"path"),this.protocol=n,this.host=e,this.port=r,this.path=va(i)}replace(e){return new Gn({host:e.host??this.host,port:e.port??this.port,protocol:e.protocol??this.protocol,pathPrefix:e.pathPrefix??this.path})}child(e){return new Gn({...this,pathPrefix:Ll(this.path,e)})}toString(){return _l(`${this.protocol}://${this.host}:${this.port}/${this.path}`)}};bt(ni,"UNKNOWN",new ni({host:"unknown",port:0}));var Yl=Object.defineProperty,ql=(t,e,r)=>e in t?Yl(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Wr=(t,e,r)=>ql(t,typeof e!="symbol"?e+"":e,r);let Fl=class{constructor(e){Wr(this,"sender"),Wr(this,"handlers"),this.sender=e,this.handlers=new Map}handle({data:e}){var r;const n=(r=this.handlers.get(e.type))==null?void 0:r.handler;n==null?console.warn(`No handler for ${e.type}`):n(e.payload)}route(e){const r=Vl(e,this.sender),n=new Wl(r);return this.handlers.set(e,n),n}};const Vl=(t,e)=>(r,n)=>e({type:t,payload:r},n);let Wl=class{constructor(e){Wr(this,"_send"),Wr(this,"handler"),this._send=e,this.handler=null}send(e,r=[]){this._send(e,r)}handle(e){this.handler=e}};var Gl=Object.defineProperty,Zl=(t,e,r)=>e in t?Gl(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,br=(t,e,r)=>Zl(t,typeof e!="symbol"?e+"":e,r);const Ve=class extends Number{};br(Ve,"Absolute",255),br(Ve,"Default",1),br(Ve,"z",s.z.union([s.z.instanceof(Ve),s.z.number().int().min(0).max(255).transform(t=>new Ve(t)),s.z.instanceof(Number).transform(t=>new Ve(t))]));let Oa=Ve;const Ta=s.z.object({name:s.z.string(),key:s.z.string()}),Kl=t=>s.z.object({subject:Ta,resource:t,authority:Oa.z}),Jl=(...t)=>e=>e.filter(r=>{let n=!1;return r.to!=null&&(n=t.includes(r.to.resource)),r.from!=null&&!n&&(n=t.includes(r.from.resource)),n}),Hl=Object.freeze(Object.defineProperty({__proto__:null,Authority:Oa,filterTransfersByChannelKey:Jl,stateZ:Kl,subjectZ:Ta},Symbol.toStringTag,{value:"Module"})),Sa=class vt extends Error{constructor(){super(vt.MESSAGE)}matches(e){return typeof e=="string"?e.includes(vt.MESSAGE):e instanceof vt||e.message.includes(vt.MESSAGE)}};br(Sa,"MESSAGE","canceled");let Xl=Sa;new Xl;const Ql=t=>t?-1:1,Zn=s.z.string().regex(/^\d+\.\d+\.\d+$/),Jt=(t,e,r={})=>{r.checkMajor??(r.checkMajor=!0),r.checkMinor??(r.checkMinor=!0),r.checkPatch??(r.checkPatch=!0);const n=Zn.parse(t),i=Zn.parse(e),[a,o,u]=n.split(".").map(Number),[c,d,f]=i.split(".").map(Number);if(r.checkMajor){if(a<c)return gr;if(a>c)return pr}if(r.checkMinor){if(o<d)return gr;if(o>d)return pr}if(r.checkPatch){if(u<f)return gr;if(u>f)return pr}return at},eu=(t,e,r={})=>aa(Jt(t,e,r)),za=(t,e,r={})=>ia(Jt(t,e,r)),tu=(t,e,r={})=>sa(Jt(t,e,r)),ru=({name:t,migrate:e})=>r=>{try{const n=e(r);return console.log(`${t} migrated: ${r.version} -> ${n.version}`),n}catch(n){throw console.log(`${t} failed to migrate from ${r.version}`),console.error(n),n}},nu=({name:t,migrations:e,targetSchema:r,def:n})=>{const i=Object.keys(e).sort(Jt).pop();if(i==null)return c=>{if(c.version!==n.version)return console.log(`${t} version ${c.version} is newer than latest version of ${n.version}.
|
|
13
|
+
`).slice(0,-1).map(r=>e.parse(yr.decodeString(r)))}get timeRange(){if(this._timeRange==null)throw new Error("time range not set on series");return this._timeRange}get byteCapacity(){return new tn(this.buffer.byteLength)}get capacity(){return this.dataType.density.length(this.byteCapacity)}get byteLength(){return this.writePos===Ye?this.byteCapacity:this.dataType.density.size(this.writePos)}get length(){return this._cachedLength!=null?this._cachedLength:this.dataType.isVariable?this.calculateCachedLength():this.writePos===Ye?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(r=>{r===10&&e++}),this._cachedLength=e,e}convert(e,r=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]=Sl(this.dataType,e,this.data[i],r);return new ke({data:n.buffer,dataType:e,timeRange:this._timeRange,sampleOffset:r,glBufferUsage:this.gl.bufferUsage,alignment:this.alignment})}calcRawMax(){if(this.length===0)return-1/0;if(this.dataType.equals(j.TIMESTAMP))this._cachedMax=this.data[this.data.length-1];else if(this.dataType.usesBigInt){const e=this.data;this._cachedMax=e.reduce((r,n)=>r>n?r:n)}else{const e=this.data;this._cachedMax=e.reduce((r,n)=>r>n?r: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()),wt(this._cachedMax,this.sampleOffset))}calcRawMin(){if(this.length===0)return 1/0;if(this.dataType.equals(j.TIMESTAMP))this._cachedMin=this.data[0];else if(this.dataType.usesBigInt){const e=this.data;this._cachedMin=e.reduce((r,n)=>r<n?r:n)}else{const e=this.data;this._cachedMin=e.reduce((r,n)=>r<n?r: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()),wt(this._cachedMin,this.sampleOffset))}get bounds(){return O.o(Number(this.min),Number(this.max))}maybeRecomputeMinMax(e){if(this._cachedMin!=null){const r=e._cachedMin??e.calcRawMin();r<this._cachedMin&&(this._cachedMin=r)}if(this._cachedMax!=null){const r=e._cachedMax??e.calcRawMax();r>this._cachedMax&&(this._cachedMax=r)}}enrich(){this.max,this.min}get range(){return wt(this.max,-this.min)}at(e,r){if(this.dataType.isVariable)return this.atVariable(e,r??!1);e<0&&(e=this.length+e);const n=this.data[e];if(n==null){if(r===!0)throw new Error(`[series] - no value at index ${e}`);return}return wt(n,this.sampleOffset)}atVariable(e,r){e<0&&(e=this.length+e);let n=0,i=0;for(let o=0;o<this.data.length;o++)if(this.data[o]===10){if(e===0){i=o;break}n=o+1,e--}if(i===0&&(i=this.data.length),n>=i||e>0){if(r)throw new Error(`[series] - no value at index ${e}`);return}const a=this.data.slice(n,i);return this.dataType.equals(j.STRING)?new TextDecoder().decode(a):O.T(JSON.parse(new TextDecoder().decode(a)))}binarySearch(e){let r=0,n=this.length-1;const i=en(e);for(;r<=n;){const a=Math.floor((r+n)/2),o=i(this.at(a,!0),e);if(o===0)return a;o<0?r=a+1:n=a-1}return r}updateGLBuffer(e){if(this.gl.control=e,!this.dataType.equals(j.FLOAT32))throw new Error("Only FLOAT32 arrays can be used in WebGL");const{buffer:r,bufferUsage:n,prevBuffer:i}=this.gl;if(r==null&&(this.gl.buffer=e.createBuffer()),this.writePos!==i)if(e.bindBuffer(e.ARRAY_BUFFER,this.gl.buffer),this.writePos!==Ye){i===0&&e.bufferData(e.ARRAY_BUFFER,this.byteCapacity.valueOf(),e.STATIC_DRAW);const a=this.dataType.density.size(i).valueOf(),o=this.underlyingData.slice(this.gl.prevBuffer,this.writePos);e.bufferSubData(e.ARRAY_BUFFER,a,o.buffer),this.gl.prevBuffer=this.writePos}else e.bufferData(e.ARRAY_BUFFER,this.buffer,n==="static"?e.STATIC_DRAW:e.DYNAMIC_DRAW),this.gl.prevBuffer=Ye}as(e){if(e==="string"){if(!this.dataType.equals(j.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(j.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 O.o(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 Il(this);return this.dataType.equals(j.JSON)?new Al(e):e}return new kl(this)}slice(e,r){if(e<=0&&(r==null||r>=this.length))return this;const n=this.data.slice(e,r);return new ke({data:n,dataType:this.dataType,timeRange:this._timeRange,sampleOffset:this.sampleOffset,glBufferUsage:this.gl.bufferUsage,alignment:this.alignment+BigInt(e)})}reAlign(e){return new ke({data:this.buffer,dataType:this.dataType,timeRange:tt.ZERO,sampleOffset:this.sampleOffset,glBufferUsage:"static",alignment:e})}};m(mt,"crudeZ",s.z.object({timeRange:tt.z.optional(),dataType:j.z,alignment:ha.optional(),data:s.z.union([Nl,El,s.z.instanceof(ArrayBuffer)]),glBufferUsage:vl.optional().default("static").optional()})),m(mt,"z",mt.crudeZ.transform(t=>new mt(t)));let pa=mt,Il=class{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,r=this.series.data;for(;this.index<r.length&&r[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 Hs,Xs;let Al=class{constructor(e){m(this,"wrapped"),m(this,Hs,"JSONSeriesIterator"),this.wrapped=e}next(){const e=this.wrapped.next();return e.done===!0?{done:!0,value:void 0}:{done:!1,value:yr.decodeString(e.value)}}[(Xs=Symbol.iterator,Hs=Symbol.toStringTag,Xs)](){return this}};var Qs,ei;let kl=class{constructor(e){m(this,"series"),m(this,"index"),m(this,Qs,"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)}}[(ei=Symbol.iterator,Qs=Symbol.toStringTag,ei)](){return this}};const wt=(t,e)=>typeof t=="bigint"&&typeof e=="bigint"||typeof t=="number"&&typeof e=="number"?t+e:e===0?t:t===0?e:Number(t)+Number(e);let xl=class{constructor(e){if(m(this,"series"),e.length!==0){const r=e[0].dataType;for(let n=1;n<e.length;n++)if(!e[n].dataType.equals(r))throw new Error("[multi-series] - series must have the same data type")}this.series=e}as(e){if(!new j(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?j.UNKNOWN:this.series[0].dataType}get timeRange(){return this.series.length===0?tt.ZERO:new tt(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,r)=>e+r.length,0)}at(e,r=!1){e<0&&(e=this.length+e);for(const n of this.series){if(e<n.length)return n.at(e,r);e-=n.length}if(r)throw new Error(`[series] - no value at index ${e}`)}get byteLength(){return new tn(this.series.reduce((e,r)=>e+r.byteLength.valueOf(),0))}get data(){const e=new this.dataType.Array(this.length);let r=0;for(const n of this.series)e.set(n.data,r),r+=n.length;return new this.dataType.Array(e)}[Symbol.iterator](){return this.series.length===0?{next(){return{done:!0,value:void 0}}}:new Cl(this.series)}};var ti,ri;class Cl{constructor(e){m(this,"series"),m(this,"seriesIndex"),m(this,"internal"),m(this,ti,"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())}[(ri=Symbol.iterator,ti=Symbol.toStringTag,ri)](){return this}}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 ma=()=>typeof process<"u"&&process.versions!=null&&process.versions.node!=null?"node":typeof window>"u"||window.document===void 0?"webworker":"browser",$l=ma(),wa=["MacOS","Windows","Linux","Docker"],Rl=s.z.enum(wa);let vn;const jl=()=>{if(typeof window>"u")return;const t=window.navigator.userAgent.toLowerCase();if(t.includes("mac"))return"MacOS";if(t.includes("win"))return"Windows";if(t.includes("linux"))return"Linux"},Ml=(t={})=>{const{force:e,default:r}=t;return e??vn??(vn=jl(),vn??r)},ba=Object.freeze(Object.defineProperty({__proto__:null,OPERATING_SYSTEMS:wa,RUNTIME:$l,detect:ma,getOS:Ml,osZ:Rl},Symbol.toStringTag,{value:"Module"})),Dl=t=>Array.isArray(t)?t:[t],Pl=t=>Array.isArray(t)?t:t===null?[]:[t];var Bl=Object.defineProperty,Ul=(t,e,r)=>e in t?Bl(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,bt=(t,e,r)=>Ul(t,typeof e!="symbol"?e+"":e,r);const Ll=(...t)=>t.map(va).join(""),va=t=>(t.endsWith("/")||(t+="/"),t.startsWith("/")&&(t=t.slice(1)),t),_l=t=>t.endsWith("/")?t.slice(0,-1):t,ni=class Gn{constructor({host:e,port:r,protocol:n="",pathPrefix:i=""}){bt(this,"protocol"),bt(this,"host"),bt(this,"port"),bt(this,"path"),this.protocol=n,this.host=e,this.port=r,this.path=va(i)}replace(e){return new Gn({host:e.host??this.host,port:e.port??this.port,protocol:e.protocol??this.protocol,pathPrefix:e.pathPrefix??this.path})}child(e){return new Gn({...this,pathPrefix:Ll(this.path,e)})}toString(){return _l(`${this.protocol}://${this.host}:${this.port}/${this.path}`)}};bt(ni,"UNKNOWN",new ni({host:"unknown",port:0}));var Yl=Object.defineProperty,ql=(t,e,r)=>e in t?Yl(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Wr=(t,e,r)=>ql(t,typeof e!="symbol"?e+"":e,r);let Fl=class{constructor(e){Wr(this,"sender"),Wr(this,"handlers"),this.sender=e,this.handlers=new Map}handle({data:e}){var r;const n=(r=this.handlers.get(e.type))==null?void 0:r.handler;n==null?console.warn(`No handler for ${e.type}`):n(e.payload)}route(e){const r=Vl(e,this.sender),n=new Wl(r);return this.handlers.set(e,n),n}};const Vl=(t,e)=>(r,n)=>e({type:t,payload:r},n);let Wl=class{constructor(e){Wr(this,"_send"),Wr(this,"handler"),this._send=e,this.handler=null}send(e,r=[]){this._send(e,r)}handle(e){this.handler=e}};var Gl=Object.defineProperty,Zl=(t,e,r)=>e in t?Gl(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,br=(t,e,r)=>Zl(t,typeof e!="symbol"?e+"":e,r);const Ve=class extends Number{};br(Ve,"Absolute",255),br(Ve,"Default",1),br(Ve,"z",s.z.union([s.z.instanceof(Ve),s.z.number().int().min(0).max(255).transform(t=>new Ve(t)),s.z.instanceof(Number).transform(t=>new Ve(t))]));let Oa=Ve;const Ta=s.z.object({name:s.z.string(),key:s.z.string()}),Kl=t=>s.z.object({subject:Ta,resource:t,authority:Oa.z}),Jl=(...t)=>e=>e.filter(r=>{let n=!1;return r.to!=null&&(n=t.includes(r.to.resource)),r.from!=null&&!n&&(n=t.includes(r.from.resource)),n}),Hl=Object.freeze(Object.defineProperty({__proto__:null,Authority:Oa,filterTransfersByChannelKey:Jl,stateZ:Kl,subjectZ:Ta},Symbol.toStringTag,{value:"Module"})),Sa=class vt extends Error{constructor(){super(vt.MESSAGE)}matches(e){return typeof e=="string"?e.includes(vt.MESSAGE):e instanceof vt||e.message.includes(vt.MESSAGE)}};br(Sa,"MESSAGE","canceled");let Xl=Sa;new Xl;const Ql=t=>t?-1:1,Zn=s.z.string().regex(/^\d+\.\d+\.\d+$/),Jt=(t,e,r={})=>{r.checkMajor??(r.checkMajor=!0),r.checkMinor??(r.checkMinor=!0),r.checkPatch??(r.checkPatch=!0);const n=Zn.parse(t),i=Zn.parse(e),[a,o,l]=n.split(".").map(Number),[u,d,f]=i.split(".").map(Number);if(r.checkMajor){if(a<u)return gr;if(a>u)return pr}if(r.checkMinor){if(o<d)return gr;if(o>d)return pr}if(r.checkPatch){if(l<f)return gr;if(l>f)return pr}return at},eu=(t,e,r={})=>aa(Jt(t,e,r)),za=(t,e,r={})=>ia(Jt(t,e,r)),tu=(t,e,r={})=>sa(Jt(t,e,r)),ru=({name:t,migrate:e})=>r=>{try{const n=e(r);return console.log(`${t} migrated: ${r.version} -> ${n.version}`),n}catch(n){throw console.log(`${t} failed to migrate from ${r.version}`),console.error(n),n}},nu=({name:t,migrations:e,targetSchema:r,defaultVersion:n,def:i})=>{const a=Object.keys(e).sort(Jt).pop();if(a==null)return d=>{if(d.version==null&&(d.version=n),d.version!==i.version)return console.log(`${t} version ${d.version} is newer than latest version of ${i.version}.
|
|
14
14
|
Returning default instead.
|
|
15
|
-
`),
|
|
15
|
+
`),i;try{return r!=null?r.parse(d):d}catch(f){return console.log(`${t} failed to parse default. Exiting with default`),console.error(f),i}};const o=Object.keys(e).length;let l=!1;const u=d=>{try{if(o===0||za(d.version,a))return console.log(l?`${t} ${d.version} now up to date`:`${t} version ${d.version} is up to date with target version ${i.version}`),d;const f=d.version,h=e[f],E=h(d);return l=!0,u(E)}catch(f){return console.log(`${t} failed to migrate from ${d.version} to ${a}`),console.error(f),i}};return d=>{try{if(d.version==null)if(n!=null)console.log(`${t} version is null. Setting version to default of ${n}`),d.version=n;else return console.log(`${t} version is null and no default version set. Exiting with default`),i;return u(d)}catch(f){return console.log(`${t} failed to parse final result. Exiting with default`),console.error(f),i}}},su=Object.freeze(Object.defineProperty({__proto__:null,compareSemVer:Jt,createMigration:ru,migrator:nu,semVerNewer:za,semVerOlder:tu,semVerZ:Zn,versionsEqual:eu},Symbol.toStringTag,{value:"Module"})),iu=t=>{if(t===void 0||typeof t=="string"||typeof t=="number")return t;if(t.toString===void 0)throw new Error("invalid renderer");return t.toString()},au=t=>Array.isArray(t)?[...t]:typeof t=="object"&&t!==null?{...t}:t,ws=t=>typeof t=="function",bs=(t,e)=>ws(t)?t(e):t,Ht=t=>Na(t)?t():t,Na=t=>typeof t=="function",Ea=({initial:t,value:e,onChange:r})=>{const[n,i]=ps.useState(Ht(e??t));return e!=null&&r!=null?[e,r]:[n,i]},Ia=({initial:t,value:e,onChange:r})=>{const[n,i]=ps.useState(Ht(e??t));return e!=null&&r!=null?[e,r]:[n,i]},ou=(t,e)=>{const[r,n]=ps.useState(()=>{const i=localStorage.getItem(e);return i==null?Ht(t):JSON.parse(i)});return[r,i=>{n(i),localStorage.setItem(e,JSON.stringify(i))}]},cu=Object.freeze(Object.defineProperty({__proto__:null,executeInitialSetter:Ht,executeSetter:bs,isInitialSetter:Na,isSetter:ws,usePassthrough:Ea,usePersisted:ou,usePurePassthrough:Ia},Symbol.toStringTag,{value:"Module"})),Aa=["h1","h2","h3","h4","h5","p","small"],lu=s.z.enum(Aa),Be=s.z.object({size:s.z.number(),weight:s.z.union([s.z.number(),s.z.string()]),lineHeight:s.z.number(),textTransform:s.z.string().optional()}),ka={small:"small",medium:"p",large:"h5",huge:"h2"},uu={h1:"huge",h2:"huge",h3:"huge",h4:"large",h5:"small",p:"medium",small:"small"};let On=null;const hu=()=>(On==null&&(On=document.createElement("canvas")),On),du=(t,e,r)=>{if(ba.RUNTIME==="node")return{width:0,height:0};r==null&&(r=hu().getContext("2d")),r.font=e;const n=r.measureText(t);return{width:Math.trunc(Math.abs(n.actualBoundingBoxLeft)+Math.abs(n.actualBoundingBoxRight)),height:Math.trunc(Math.abs(n.actualBoundingBoxAscent)+Math.abs(n.actualBoundingBoxDescent))}},fu=s.z.object({l0:O.Color.z,l1:O.Color.z,l2:O.Color.z,l3:O.Color.z,l4:O.Color.z,l5:O.Color.z,l6:O.Color.z,l7:O.Color.z,l8:O.Color.z,l9:O.Color.z,l10:O.Color.z}),me=(t,e)=>[t[0],t[1],e,t[3]],yu=s.z.object({m2:O.Color.z,m1:O.Color.z,z:O.Color.z,p1:O.Color.z,p2:O.Color.z}),ar=yu.or(O.Color.z.transform(t=>{const e=t.hsla;return{m2:new O.Color(O.fromHSLA(me(e,40))),m1:new O.Color(O.fromHSLA(me(e,45))),z:t,p1:new O.Color(O.fromHSLA(me(e,55))),p2:new O.Color(O.fromHSLA(me(e,65)))}})),xa=s.z.object({name:s.z.string(),key:s.z.string(),colors:s.z.object({border:O.Color.z,primary:ar,gray:fu,error:ar,secondary:ar,warning:ar,visualization:s.z.object({palettes:s.z.record(s.z.array(O.Color.z))}).optional().default({palettes:{}}),white:O.Color.z,black:O.Color.z,text:O.Color.z,textInverted:O.Color.z,textOnPrimary:O.Color.z.optional().default(O.ZERO),logo:s.z.string()}),sizes:s.z.object({base:s.z.number(),border:s.z.object({radius:s.z.number(),width:s.z.number()}),schematic:s.z.object({elementStrokeWidth:s.z.number()})}),typography:s.z.object({family:s.z.string(),h1:Be,h2:Be,h3:Be,h4:Be,h5:Be,p:Be,small:Be})}).transform(t=>((t.colors.textOnPrimary==null||t.colors.textOnPrimary.isZero)&&(t.colors.textOnPrimary=t.colors.primary.z.pickByContrast(t.colors.text,t.colors.textInverted)),t)),gu="'Inter Variable', sans-serif",pu=6,ut=[357,91,55,1],ht=[58,100,50,1],mu=["#FDFDFD","#FAFAFA","#F3F3F3","#EAEAEA","#D8D8D8","#ADADAD","#878787","#616161","#404040","#1C1C1C","#050505"],dt=Object.fromEntries(mu.map((t,e)=>[`l${e}`,t])),Kn={key:"synnaxBase",name:"Synnax Base",colors:{primary:{m2:"#041B3D",m1:"#164FA0",z:"#3774D0",p1:"#5E94EE",p2:"#8AB8FF"},secondary:{m2:"#2D8F4E",m1:"#38B261",z:"#50C878",p1:"#73D393",p2:"#96DEAE"},gray:dt,border:dt.l3,error:{m2:O.fromHSLA(me(ut,30)),m1:O.fromHSLA(me(ut,40)),z:O.fromHSLA(ut),p1:O.fromHSLA(me(ut,65)),p2:O.fromHSLA(me(ut,77))},warning:{m2:O.fromHSLA(me(ht,30)),m1:O.fromHSLA(me(ht,40)),z:O.fromHSLA(ht),p1:O.fromHSLA(me(ht,65)),p2:O.fromHSLA(me(ht,75))},visualization:{palettes:{default:["#DC136C","#20A4F3","#7AC74F","#FFC43D","#FE5F55","#8075FF","#D90429","#f7aef8","#f18f01","#791e94","#279af1","#d9fff5","#ff6b6b","#52ffb8"]}},logo:"url(#synnax-linear-gradient)",white:"#FFFFFF",black:"#000000",text:dt.l9,textInverted:dt.l0,textOnPrimary:dt.l0},sizes:{base:pu,border:{radius:3,width:1},schematic:{elementStrokeWidth:2}},typography:{family:gu,h1:{size:7,weight:"500",lineHeight:7*1.5},h2:{size:4.5,weight:"medium",lineHeight:4.5*1.5},h3:{size:3.5,weight:"medium",lineHeight:3.5*1.5},h4:{size:2.6666,weight:"medium",lineHeight:2.6666*1.5},h5:{size:2.333333,weight:450,lineHeight:2.333333*1.5},p:{size:2.1666666666,weight:"regular",lineHeight:2*1.5},small:{size:1.916666,weight:"regular",lineHeight:1.9166666*1.5}}},Ca=Object.freeze({...Kn,key:"synnaxLight",name:"Synnax Light"}),wu=["#020202","#0A0A0A","#131313","#1E1E1E","#2E2E2E","#444444","#646464","#8A8A8A","#AFAFAF","#D5D5D5","#FDFDFD"],ft=Object.fromEntries(wu.map((t,e)=>[`l${e}`,t])),$a=Object.freeze({...Kn,key:"synnaxDark",name:"Synnax Dark",colors:{...Kn.colors,gray:ft,logo:"var(--pluto-text-color)",border:ft.l3,text:ft.l9,textInverted:ft.l0,textOnPrimary:ft.l10}}),bu={synnaxDark:$a,synnaxLight:Ca},vu=["small","medium","large","huge"],Ou=s.z.enum(vu),Tu=t=>Ou.safeParse(t).success,Su=(t,e,r)=>{const{typography:n,sizes:{base:i}}=t,a=n[Tu(e)?ka[e]:e].size,o=i*a,[l,u]=n.family.split(", ");return r!=null?` ${r} ${o}px ${l}, ${u}`:` ${o}px ${n.family}`};var zu=Object.defineProperty,Nu=(t,e,r)=>e in t?zu(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,c=(t,e,r)=>Nu(t,typeof e!="symbol"?e+"":e,r);const T=t=>Array.isArray(t)?t:[t];var Eu=Object.defineProperty,Iu=(t,e,r)=>e in t?Eu(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,D=(t,e,r)=>Iu(t,typeof e!="symbol"?e+"":e,r);const Au=t=>{const e=t.replace(/_[a-z]/g,r=>r[1].toUpperCase());return e.length>1&&e[0]===e[0].toUpperCase()&&e[1]===e[1].toUpperCase()?e:e[0].toLowerCase()+e.slice(1)},Ra=t=>{const e=(r,n=Jn)=>{if(typeof r=="string")return t(r);if(Array.isArray(r))return r.map(o=>e(o,n));if(!Tn(r))return r;n=Cu(n);const i={},a=r;return Object.keys(a).forEach(o=>{let l=a[o];const u=t(o);n.recursive&&(Tn(l)?ii(l,n.keepTypesOnRecursion)||(l=e(l,n)):n.recursiveInArray&&si(l)&&(l=[...l].map(d=>{let f=d;return Tn(d)?ii(f,n.keepTypesOnRecursion)||(f=e(d,n)):si(d)&&(f=e({key:d},n).key),f}))),i[u]=l}),i};return e},ja=Ra(Au),ku=t=>t.replace(/([a-z0-9])([A-Z])/g,(e,r,n)=>`${r}_${n.toLowerCase()}`),xu=Ra(ku),Jn={recursive:!0,recursiveInArray:!0,keepTypesOnRecursion:[Number,String,Uint8Array]},Cu=(t=Jn)=>(t.recursive==null?t=Jn:t.recursiveInArray==null&&(t.recursiveInArray=!1),t),si=t=>t!=null&&Array.isArray(t),Tn=t=>t!=null&&typeof t=="object"&&!Array.isArray(t),ii=(t,e)=>(e||[]).some(r=>t instanceof r),Ma=t=>t!=null&&typeof t=="object"&&!Array.isArray(t);var $u=Object.defineProperty,Ru=(t,e,r)=>e in t?$u(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Pt=(t,e,r)=>Ru(t,typeof e!="symbol"?e+"":e,r);let ju=class{constructor(){Pt(this,"contentType","application/json"),Pt(this,"decoder"),Pt(this,"encoder"),this.decoder=new TextDecoder,this.encoder=new TextEncoder}encode(t){return this.encoder.encode(this.encodeString(t)).buffer}decode(t,e){return this.decodeString(this.decoder.decode(t),e)}decodeString(t,e){const r=JSON.parse(t),n=ja(r);return e!=null?e.parse(n):n}encodeString(t){const e=xu(t);return JSON.stringify(e,(r,n)=>ArrayBuffer.isView(n)?Array.from(n):Ma(n)&&"encode_value"in n?typeof n.value=="bigint"?n.value.toString():n.value:typeof n=="bigint"?n.toString():n)}static registerCustomType(){}},Mu=class{constructor(){Pt(this,"contentType","text/csv")}encode(t){const e=this.encodeString(t);return new TextEncoder().encode(e).buffer}decode(t,e){const r=new TextDecoder().decode(t);return this.decodeString(r,e)}encodeString(t){if(!Array.isArray(t)||t.length===0||!Ma(t[0]))throw new Error("Payload must be an array of objects");const e=Object.keys(t[0]),r=[e.join(",")];return t.forEach(n=>{const i=e.map(a=>JSON.stringify(n[a]??""));r.push(i.join(","))}),r.join(`
|
|
16
16
|
`)}decodeString(t,e){const[r,...n]=t.trim().split(`
|
|
17
|
-
`).map(o=>o.trim());if(r.length===0)return e!=null?e.parse({}):{};const i=r.split(",").map(o=>o.trim()),a={};return i.forEach(o=>{a[o]=[]}),n.forEach(o=>{const u=o.split(",").map(c=>c.trim());i.forEach((c,d)=>{const f=this.parseValue(u[d]);f!=null&&a[c].push(f)})}),e!=null?e.parse(a):a}parseValue(t){if(t==null||t.length===0)return null;const e=Number(t);return isNaN(e)?t.startsWith('"')&&t.endsWith('"')?t.slice(1,-1):t:e}static registerCustomType(){}},Du=class{constructor(){Pt(this,"contentType","text/plain")}encode(t){return new TextEncoder().encode(t).buffer}decode(t,e){const r=new TextDecoder().decode(t);return e!=null?e.parse(r):r}};const vr=new ju;new Mu;new Du;const rn=s.z.tuple([s.z.number(),s.z.number()]);s.z.tuple([s.z.bigint(),s.z.bigint()]);const Da=s.z.object({width:s.z.number(),height:s.z.number()}),Pu=s.z.object({signedWidth:s.z.number(),signedHeight:s.z.number()}),Bu=["width","height"];s.z.enum(Bu);const Uu=["start","center","end"],Lu=["signedWidth","signedHeight"];s.z.enum(Lu);const Gr=s.z.object({x:s.z.number(),y:s.z.number()}),_u=s.z.object({clientX:s.z.number(),clientY:s.z.number()}),Yu=["x","y"],Pa=s.z.enum(Yu),Ba=["top","right","bottom","left"];s.z.enum(Ba);const qu=["left","right"],Ua=s.z.enum(qu),Fu=["top","bottom"],La=s.z.enum(Fu),_a=["center"],ai=s.z.enum(_a),Vu=[...Ba,..._a],Ya=s.z.enum(Vu);s.z.enum(Uu);const Wu=["first","last"];s.z.enum(Wu);const Gu=s.z.object({lower:s.z.number(),upper:s.z.number()}),Zu=s.z.object({lower:s.z.bigint(),upper:s.z.bigint()});s.z.union([Gu,rn]);s.z.union([Zu,rn]);s.z.union([Pa,Ya]);s.z.union([Pa,Ya,s.z.instanceof(String)]);const Bt=(t,e)=>{const r={};if(typeof t=="number"||typeof t=="bigint")e!=null?(r.lower=t,r.upper=e):(r.lower=typeof t=="bigint"?0n:0,r.upper=t);else if(Array.isArray(t)){if(t.length!==2)throw new Error("bounds: expected array of length 2");[r.lower,r.upper]=t}else return oi(t);return oi(r)},oi=t=>t.lower>t.upper?{lower:t.upper,upper:t.lower}:t;s.z.object({x:Ua.or(ai),y:La.or(ai)});const Ku=s.z.object({x:Ua,y:La}),Ju=Object.freeze({x:"left",y:"top"}),Hu=(t,e)=>t.x===e.x&&t.y===e.y,ci=s.z.union([s.z.number(),Gr,rn,Da,Pu,_u]),Xu=(t,e)=>{if(typeof t=="string"){if(e===void 0)throw new Error("The y coordinate must be given.");return t==="x"?{x:e,y:0}:{x:0,y:e}}return typeof t=="number"?{x:t,y:e??t}:Array.isArray(t)?{x:t[0],y:t[1]}:"signedWidth"in t?{x:t.signedWidth,y:t.signedHeight}:"clientX"in t?{x:t.clientX,y:t.clientY}:"width"in t?{x:t.width,y:t.height}:{x:t.x,y:t.y}},li=Object.freeze({x:0,y:0}),or=s.z.union([s.z.number(),s.z.string()]);s.z.object({top:or,left:or,width:or,height:or});s.z.object({left:s.z.number(),top:s.z.number(),right:s.z.number(),bottom:s.z.number()});s.z.object({one:Gr,two:Gr,root:Ku});const vs=(t,e,r=0,n=0,i)=>{const a={one:{...li},two:{...li},root:i??Ju};if(typeof t=="number"){if(typeof e!="number")throw new Error("Box constructor called with invalid arguments");return a.one={x:t,y:e},a.two={x:a.one.x+r,y:a.one.y+n},a}return"one"in t&&"two"in t&&"root"in t?{...t,root:i??t.root}:("getBoundingClientRect"in t&&(t=t.getBoundingClientRect()),"left"in t?(a.one={x:t.left,y:t.top},a.two={x:t.right,y:t.bottom},a):(a.one=t,e==null?a.two={x:a.one.x+r,y:a.one.y+n}:typeof e=="number"?a.two={x:a.one.x+e,y:a.one.y+r}:"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))},Sn=t=>{const e=vs(t);return{lower:e.one.x,upper:e.two.x}},zn=t=>{const e=vs(t);return{lower:e.one.y,upper:e.two.y}},Qu=t=>typeof t!="object"||t==null?!1:"one"in t&&"two"in t&&"root"in t;var eh=Object.defineProperty,th=(t,e,r)=>e in t?eh(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,je=(t,e,r)=>th(t,typeof e!="symbol"?e+"":e,r);const rh=(t,e,r)=>e!==void 0&&t<e?e:r!==void 0&&t>r?r:t;s.z.object({offset:ci,scale:ci});const nh=t=>(e,r,n,i)=>r==="dimension"?[e,n]:[e,i?n-t:n+t],sh=t=>(e,r,n,i)=>[e,i?n/t:n*t],ih=t=>(e,r,n)=>{if(e===null)return[t,n];const{lower:i,upper:a}=e,{lower:o,upper:u}=t,c=a-i,d=u-o;if(r==="dimension")return[t,n*(d/c)];const f=(n-i)*(d/c)+o;return[t,f]},ah=t=>(e,r,n)=>[t,n],oh=()=>(t,e,r)=>{if(t===null)throw new Error("cannot invert without bounds");if(e==="dimension")return[t,r];const{lower:n,upper:i}=t;return[t,i-(r-n)]},ch=t=>(e,r,n)=>{const{lower:i,upper:a}=t;return n=rh(n,i,a),[e,n]},Hn=class Ot{constructor(){je(this,"ops",[]),je(this,"currBounds",null),je(this,"currType",null),je(this,"reversed",!1),this.ops=[]}static translate(e){return new Ot().translate(e)}static magnify(e){return new Ot().magnify(e)}static scale(e,r){return new Ot().scale(e,r)}translate(e){const r=this.new(),n=nh(e);return n.type="translate",r.ops.push(n),r}magnify(e){const r=this.new(),n=sh(e);return n.type="magnify",r.ops.push(n),r}scale(e,r){const n=Bt(e,r),i=this.new(),a=ih(n);return a.type="scale",i.ops.push(a),i}clamp(e,r){const n=Bt(e,r),i=this.new(),a=ch(n);return a.type="clamp",i.ops.push(a),i}reBound(e,r){const n=Bt(e,r),i=this.new(),a=ah(n);return a.type="re-bound",i.ops.push(a),i}invert(){const e=oh();e.type="invert";const r=this.new();return r.ops.push(e),r}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,r){return this.currBounds=null,this.ops.reduce(([n,i],a)=>a(n,e,i,this.reversed),[null,r])[1]}reverse(){const e=this.new();e.ops.reverse();const r=[];return e.ops.forEach((n,i)=>{if(n.type==="scale"||r.some(([o,u])=>i>=o&&i<=u))return;const a=e.ops.findIndex((o,u)=>o.type==="scale"&&u>i);a!==-1&&r.push([i,a])}),r.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}};je(Hn,"IDENTITY",new Hn);let ui=Hn;const hi=class xe{constructor(e=new ui,r=new ui,n=null){je(this,"x"),je(this,"y"),je(this,"currRoot"),this.x=e,this.y=r,this.currRoot=n}static translate(e,r){return new xe().translate(e,r)}static translateX(e){return new xe().translateX(e)}static translateY(e){return new xe().translateY(e)}static clamp(e){return new xe().clamp(e)}static magnify(e){return new xe().magnify(e)}static scale(e){return new xe().scale(e)}static reBound(e){return new xe().reBound(e)}translate(e,r){const n=Xu(e,r),i=this.copy();return i.x=this.x.translate(n.x),i.y=this.y.translate(n.y),i}translateX(e){const r=this.copy();return r.x=this.x.translate(e),r}translateY(e){const r=this.copy();return r.y=this.y.translate(e),r}magnify(e){const r=this.copy();return r.x=this.x.magnify(e.x),r.y=this.y.magnify(e.y),r}scale(e){const r=this.copy();if(Qu(e)){const n=this.currRoot;return r.currRoot=e.root,n!=null&&!Hu(n,e.root)&&(n.x!==e.root.x&&(r.x=r.x.invert()),n.y!==e.root.y&&(r.y=r.y.invert())),r.x=r.x.scale(Sn(e)),r.y=r.y.scale(zn(e)),r}return r.x=r.x.scale(e.width),r.y=r.y.scale(e.height),r}reBound(e){const r=this.copy();return r.x=this.x.reBound(Sn(e)),r.y=this.y.reBound(zn(e)),r}clamp(e){const r=this.copy();return r.x=this.x.clamp(Sn(e)),r.y=this.y.clamp(zn(e)),r}copy(){const e=new xe;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 vs(this.pos(e.one),this.pos(e.two),0,0,this.currRoot??e.root)}};je(hi,"IDENTITY",new hi);const lh=t=>t!=null&&typeof t=="object"&&"toString"in t,uh=(t,e=!1)=>{const r=lh(t)?"stringer":typeof t;let n;switch(r){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 ${r}`),()=>-1}return e?hh(n):n},hh=t=>(e,r)=>t(r,e),dh=s.z.object({signedWidth:s.z.number(),signedHeight:s.z.number()});s.z.union([Da,dh,Gr,rn]);const fh=s.z.bigint().or(s.z.string().transform(BigInt));var yh=Object.defineProperty,gh=(t,e,r)=>e in t?yh(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,b=(t,e,r)=>gh(t,typeof e!="symbol"?e+"":e,r);let ph=(t,e=21)=>(r=e)=>{let n="",i=r;for(;i--;)n+=t[Math.random()*t.length|0];return n};const mh="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",wh=ph(mh,11),bh=s.z.enum(["static","dynamic"]),qa=(t,e)=>{const r=new G(e);if(![Q.DAY,Q.HOUR,Q.MINUTE,Q.SECOND,Q.MILLISECOND,Q.MICROSECOND,Q.NANOSECOND].some(i=>i.equals(r)))throw new Error("Invalid argument for remainder. Must be an even TimeSpan or Timestamp");const n=t.valueOf()%r.valueOf();return t instanceof G?new G(n):new Q(n)},_=class z{constructor(e,r="UTC"){if(b(this,"value"),b(this,"encodeValue",!0),e==null)this.value=z.now().valueOf();else if(e instanceof Date)this.value=BigInt(e.getTime())*z.MILLISECOND.valueOf();else if(typeof e=="string")this.value=z.parseDateTimeString(e,r).valueOf();else if(Array.isArray(e))this.value=z.parseDate(e);else{let n=BigInt(0);e instanceof Number&&(e=e.valueOf()),r==="local"&&(n=z.utcOffset.valueOf()),typeof e=="number"&&(isFinite(e)?e=Math.trunc(e):(isNaN(e)&&(e=0),e===1/0?e=z.MAX:e=z.MIN)),this.value=BigInt(e.valueOf())+n}}static parseDate([e=1970,r=1,n=1]){const i=new Date(e,r-1,n,0,0,0,0);return new z(BigInt(i.getTime())*z.MILLISECOND.valueOf()).truncate(z.DAY).valueOf()}encode(){return this.value.toString()}valueOf(){return this.value}static parseTimeString(e,r="UTC"){const[n,i,a]=e.split(":");let o="00",u="00";a!=null&&([o,u]=a.split("."));let c=z.hours(parseInt(n??"00",10)).add(z.minutes(parseInt(i??"00",10))).add(z.seconds(parseInt(o??"00",10))).add(z.milliseconds(parseInt(u??"00",10)));return r==="local"&&(c=c.add(z.utcOffset)),c.valueOf()}static parseDateTimeString(e,r="UTC"){if(!e.includes("/")&&!e.includes("-"))return z.parseTimeString(e,r);const n=new Date(e);return e.includes(":")||n.setUTCHours(0,0,0,0),new z(BigInt(n.getTime())*z.MILLISECOND.valueOf(),r).valueOf()}fString(e="ISO",r="UTC"){switch(e){case"ISODate":return this.toISOString(r).slice(0,10);case"ISOTime":return this.toISOString(r).slice(11,23);case"time":return this.timeString(!1,r);case"preciseTime":return this.timeString(!0,r);case"date":return this.dateString();case"preciseDate":return`${this.dateString()} ${this.timeString(!0,r)}`;case"dateTime":return`${this.dateString()} ${this.timeString(!1,r)}`;default:return this.toISOString(r)}}toISOString(e="UTC"){return e==="UTC"?this.date().toISOString():this.sub(z.utcOffset).date().toISOString()}timeString(e=!1,r="UTC"){const n=this.toISOString(r);return e?n.slice(11,23):n.slice(11,19)}dateString(){const e=this.date(),r=e.toLocaleString("default",{month:"short"}),n=e.toLocaleString("default",{day:"numeric"});return`${r} ${n}`}static get utcOffset(){return new Q(BigInt(new Date().getTimezoneOffset())*z.MINUTE.valueOf())}static since(e){return new z().span(e)}date(){return new Date(this.milliseconds())}equals(e){return this.valueOf()===new z(e).valueOf()}span(e){return this.range(e).span}range(e){return new Os(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 z(e).valueOf()}afterEq(e){return this.valueOf()>=new z(e).valueOf()}before(e){return this.valueOf()<new z(e).valueOf()}beforeEq(e){return this.valueOf()<=new z(e).valueOf()}add(e){return new z(this.valueOf()+BigInt(e.valueOf()))}sub(e){return new z(this.valueOf()-BigInt(e.valueOf()))}milliseconds(){return Number(this.valueOf())/Number(z.MILLISECOND.valueOf())}toString(){return this.date().toISOString()}remainder(e){return qa(this,e)}get isToday(){return this.truncate(Q.DAY).equals(z.now().truncate(Q.DAY))}truncate(e){return this.sub(this.remainder(e))}static now(){return new z(new Date)}static max(...e){let r=z.MIN;for(const n of e){const i=new z(n);i.after(r)&&(r=i)}return r}static min(...e){let r=z.MAX;for(const n of e){const i=new z(n);i.before(r)&&(r=i)}return r}static nanoseconds(e){return new z(e)}static microseconds(e){return z.nanoseconds(e*1e3)}static milliseconds(e){return z.microseconds(e*1e3)}static seconds(e){return z.milliseconds(e*1e3)}static minutes(e){return z.seconds(e*60)}static hours(e){return z.minutes(e*60)}static days(e){return z.hours(e*24)}};b(_,"NANOSECOND",_.nanoseconds(1)),b(_,"MICROSECOND",_.microseconds(1)),b(_,"MILLISECOND",_.milliseconds(1)),b(_,"SECOND",_.seconds(1)),b(_,"MINUTE",_.minutes(1)),b(_,"HOUR",_.hours(1)),b(_,"DAY",_.days(1)),b(_,"MAX",new _((1n<<63n)-1n)),b(_,"MIN",new _(0)),b(_,"ZERO",new _(0)),b(_,"z",s.z.union([s.z.object({value:s.z.bigint()}).transform(t=>new _(t.value)),s.z.string().transform(t=>new _(BigInt(t))),s.z.instanceof(Number).transform(t=>new _(t)),s.z.number().transform(t=>new _(t)),s.z.instanceof(_)]));let G=_;const Y=class ${constructor(e){b(this,"value"),b(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 $(e).valueOf()}greaterThan(e){return this.valueOf()>new $(e).valueOf()}lessThanOrEqual(e){return this.valueOf()<=new $(e).valueOf()}greaterThanOrEqual(e){return this.valueOf()>=new $(e).valueOf()}remainder(e){return qa(this,e)}truncate(e){return new $(BigInt(Math.trunc(Number(this.valueOf()/e.valueOf())))*e.valueOf())}toString(){const e=this.truncate($.DAY),r=this.truncate($.HOUR),n=this.truncate($.MINUTE),i=this.truncate($.SECOND),a=this.truncate($.MILLISECOND),o=this.truncate($.MICROSECOND),u=this.truncate($.NANOSECOND),c=e,d=r.sub(e),f=n.sub(r),h=i.sub(n),E=a.sub(i),P=o.sub(a),ie=u.sub(o);let M="";return c.isZero||(M+=`${c.days}d `),d.isZero||(M+=`${d.hours}h `),f.isZero||(M+=`${f.minutes}m `),h.isZero||(M+=`${h.seconds}s `),E.isZero||(M+=`${E.milliseconds}ms `),P.isZero||(M+=`${P.microseconds}µs `),ie.isZero||(M+=`${ie.nanoseconds}ns`),M.trim()}get days(){return Number(this.valueOf())/Number($.DAY.valueOf())}get hours(){return Number(this.valueOf())/Number($.HOUR.valueOf())}get minutes(){return Number(this.valueOf())/Number($.MINUTE.valueOf())}get seconds(){return Number(this.valueOf())/Number($.SECOND.valueOf())}get milliseconds(){return Number(this.valueOf())/Number($.MILLISECOND.valueOf())}get microseconds(){return Number(this.valueOf())/Number($.MICROSECOND.valueOf())}get nanoseconds(){return Number(this.valueOf())}get isZero(){return this.valueOf()===BigInt(0)}equals(e){return this.valueOf()===new $(e).valueOf()}add(e){return new $(this.valueOf()+new $(e).valueOf())}sub(e){return new $(this.valueOf()-new $(e).valueOf())}static nanoseconds(e=1){return new $(e)}static microseconds(e=1){return $.nanoseconds(e*1e3)}static milliseconds(e=1){return $.microseconds(e*1e3)}static seconds(e=1){return $.milliseconds(e*1e3)}static minutes(e){return $.seconds(e.valueOf()*60)}static hours(e){return $.minutes(e*60)}static days(e){return $.hours(e*24)}};b(Y,"NANOSECOND",Y.nanoseconds(1)),b(Y,"MICROSECOND",Y.microseconds(1)),b(Y,"MILLISECOND",Y.milliseconds(1)),b(Y,"SECOND",Y.seconds(1)),b(Y,"MINUTE",Y.minutes(1)),b(Y,"HOUR",Y.hours(1)),b(Y,"DAY",Y.days(1)),b(Y,"MAX",new Y((1n<<63n)-1n)),b(Y,"MIN",new Y(0)),b(Y,"ZERO",new Y(0)),b(Y,"z",s.z.union([s.z.object({value:s.z.bigint()}).transform(t=>new Y(t.value)),s.z.string().transform(t=>new Y(BigInt(t))),s.z.instanceof(Number).transform(t=>new Y(t)),s.z.number().transform(t=>new Y(t)),s.z.instanceof(Y)]));let Q=Y;const cr=class Or extends Number{constructor(e){e instanceof Number?super(e.valueOf()):super(e)}toString(){return`${this.valueOf()} Hz`}equals(e){return this.valueOf()===new Or(e).valueOf()}get period(){return Q.seconds(1/this.valueOf())}sampleCount(e){return new Q(e).seconds*this.valueOf()}byteCount(e,r){return this.sampleCount(e)*new ue(r).valueOf()}span(e){return Q.seconds(e/this.valueOf())}byteSpan(e,r){return this.span(e.valueOf()/r.valueOf())}static hz(e){return new Or(e)}static khz(e){return Or.hz(e*1e3)}};b(cr,"z",s.z.union([s.z.number().transform(t=>new cr(t)),s.z.instanceof(Number).transform(t=>new cr(t)),s.z.instanceof(cr)]));const re=class extends Number{constructor(e){e instanceof Number?super(e.valueOf()):super(e)}length(e){return e.valueOf()/this.valueOf()}size(e){return new Fa(e*this.valueOf())}};b(re,"UNKNOWN",new re(0)),b(re,"BIT128",new re(16)),b(re,"BIT64",new re(8)),b(re,"BIT32",new re(4)),b(re,"BIT16",new re(2)),b(re,"BIT8",new re(1)),b(re,"z",s.z.union([s.z.number().transform(t=>new re(t)),s.z.instanceof(Number).transform(t=>new re(t)),s.z.instanceof(re)]));let ue=re;const ze=class Tr{constructor(e,r){b(this,"start"),b(this,"end"),typeof e=="object"&&"start"in e?(this.start=new G(e.start),this.end=new G(e.end)):(this.start=new G(e),this.end=new G(r))}get span(){return new Q(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 Tr(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,r=Q.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=G.max(n.start,e.start),a=G.min(n.end,e.end);return a.before(i)?!1:new Q(a.sub(i)).greaterThanOrEqual(r)}roughlyEquals(e,r){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<=r.valueOf()&&i<=r.valueOf()}contains(e){return e instanceof Tr?this.contains(e.start)&&this.contains(e.end):this.start.beforeEq(e)&&this.end.after(e)}boundBy(e){const r=new Tr(this.start,this.end);return e.start.after(this.start)&&(r.start=e.start),e.start.after(this.end)&&(r.end=e.start),e.end.before(this.end)&&(r.end=e.end),e.end.before(this.start)&&(r.start=e.end),r}};b(ze,"MAX",new ze(G.MIN,G.MAX)),b(ze,"MIN",new ze(G.MAX,G.MIN)),b(ze,"ZERO",new ze(G.ZERO,G.ZERO)),b(ze,"z",s.z.union([s.z.object({start:G.z,end:G.z}).transform(t=>new ze(t.start,t.end)),s.z.instanceof(ze)]));let Os=ze;const g=class Ne extends String{constructor(e){if(e instanceof Ne||typeof e=="string"||typeof e.valueOf()=="string"){super(e.valueOf());return}else{const r=Ne.ARRAY_CONSTRUCTOR_DATA_TYPES.get(e.constructor.name);if(r!=null){super(r.valueOf());return}}throw super(Ne.UNKNOWN.valueOf()),new Error(`unable to find data type for ${e.toString()}`)}get Array(){const e=Ne.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(r=>this.equals(r))}toString(){return this.valueOf()}get isVariable(){return this.equals(Ne.JSON)||this.equals(Ne.STRING)}get isNumeric(){return!this.isVariable&&!this.equals(Ne.UUID)}get isInteger(){return this.toString().startsWith("int")}get isFloat(){return this.toString().startsWith("float")}get density(){const e=Ne.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 Ne.BIG_INT_TYPES.some(e=>e.equals(this))}};b(g,"UNKNOWN",new g("unknown")),b(g,"FLOAT64",new g("float64")),b(g,"FLOAT32",new g("float32")),b(g,"INT64",new g("int64")),b(g,"INT32",new g("int32")),b(g,"INT16",new g("int16")),b(g,"INT8",new g("int8")),b(g,"UINT64",new g("uint64")),b(g,"UINT32",new g("uint32")),b(g,"UINT16",new g("uint16")),b(g,"UINT8",new g("uint8")),b(g,"BOOLEAN",g.UINT8),b(g,"TIMESTAMP",new g("timestamp")),b(g,"UUID",new g("uuid")),b(g,"STRING",new g("string")),b(g,"JSON",new g("json")),b(g,"ARRAY_CONSTRUCTORS",new Map([[g.UINT8.toString(),Uint8Array],[g.UINT16.toString(),Uint16Array],[g.UINT32.toString(),Uint32Array],[g.UINT64.toString(),BigUint64Array],[g.FLOAT32.toString(),Float32Array],[g.FLOAT64.toString(),Float64Array],[g.INT8.toString(),Int8Array],[g.INT16.toString(),Int16Array],[g.INT32.toString(),Int32Array],[g.INT64.toString(),BigInt64Array],[g.TIMESTAMP.toString(),BigInt64Array],[g.STRING.toString(),Uint8Array],[g.JSON.toString(),Uint8Array],[g.UUID.toString(),Uint8Array]])),b(g,"ARRAY_CONSTRUCTOR_DATA_TYPES",new Map([[Uint8Array.name,g.UINT8],[Uint16Array.name,g.UINT16],[Uint32Array.name,g.UINT32],[BigUint64Array.name,g.UINT64],[Float32Array.name,g.FLOAT32],[Float64Array.name,g.FLOAT64],[Int8Array.name,g.INT8],[Int16Array.name,g.INT16],[Int32Array.name,g.INT32],[BigInt64Array.name,g.INT64]])),b(g,"DENSITIES",new Map([[g.UINT8.toString(),ue.BIT8],[g.UINT16.toString(),ue.BIT16],[g.UINT32.toString(),ue.BIT32],[g.UINT64.toString(),ue.BIT64],[g.FLOAT32.toString(),ue.BIT32],[g.FLOAT64.toString(),ue.BIT64],[g.INT8.toString(),ue.BIT8],[g.INT16.toString(),ue.BIT16],[g.INT32.toString(),ue.BIT32],[g.INT64.toString(),ue.BIT64],[g.TIMESTAMP.toString(),ue.BIT64],[g.STRING.toString(),ue.UNKNOWN],[g.JSON.toString(),ue.UNKNOWN],[g.UUID.toString(),ue.BIT128]])),b(g,"ALL",[g.UNKNOWN,g.FLOAT64,g.FLOAT32,g.INT64,g.INT32,g.INT16,g.INT8,g.UINT64,g.UINT32,g.UINT16,g.UINT8,g.TIMESTAMP,g.UUID,g.STRING,g.JSON]),b(g,"BIG_INT_TYPES",[g.INT64,g.UINT64,g.TIMESTAMP]),b(g,"z",s.z.union([s.z.string().transform(t=>new g(t)),s.z.instanceof(g)]));let q=g;const oe=class H extends Number{constructor(e){super(e.valueOf())}largerThan(e){return this.valueOf()>e.valueOf()}smallerThan(e){return this.valueOf()<e.valueOf()}add(e){return H.bytes(this.valueOf()+e.valueOf())}sub(e){return H.bytes(this.valueOf()-e.valueOf())}truncate(e){return new H(Math.trunc(this.valueOf()/e.valueOf())*e.valueOf())}remainder(e){return H.bytes(this.valueOf()%e.valueOf())}get gigabytes(){return this.valueOf()/H.GIGABYTE.valueOf()}get megabytes(){return this.valueOf()/H.MEGABYTE.valueOf()}get kilobytes(){return this.valueOf()/H.KILOBYTE.valueOf()}get terabytes(){return this.valueOf()/H.TERABYTE.valueOf()}toString(){const e=this.truncate(H.TERABYTE),r=this.truncate(H.GIGABYTE),n=this.truncate(H.MEGABYTE),i=this.truncate(H.KILOBYTE),a=this.truncate(H.BYTE),o=e,u=r.sub(e),c=n.sub(r),d=i.sub(n),f=a.sub(i);let h="";return o.isZero||(h+=`${o.terabytes}TB `),u.isZero||(h+=`${u.gigabytes}GB `),c.isZero||(h+=`${c.megabytes}MB `),d.isZero||(h+=`${d.kilobytes}KB `),(!f.isZero||h==="")&&(h+=`${f.valueOf()}B`),h.trim()}static bytes(e=1){return new H(e)}static kilobytes(e=1){return H.bytes(e.valueOf()*1e3)}static megabytes(e=1){return H.kilobytes(e.valueOf()*1e3)}static gigabytes(e=1){return H.megabytes(e.valueOf()*1e3)}static terabytes(e){return H.gigabytes(e.valueOf()*1e3)}get isZero(){return this.valueOf()===0}};b(oe,"BYTE",new oe(1)),b(oe,"KILOBYTE",oe.kilobytes(1)),b(oe,"MEGABYTE",oe.megabytes(1)),b(oe,"GIGABYTE",oe.gigabytes(1)),b(oe,"TERABYTE",oe.terabytes(1)),b(oe,"ZERO",new oe(0)),b(oe,"z",s.z.union([s.z.number().transform(t=>new oe(t)),s.z.instanceof(oe)]));let Fa=oe;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 Va=t=>{const e=typeof t;return e==="string"||e==="number"||e==="boolean"||e==="bigint"||t instanceof G||t instanceof Q||t instanceof Date},vh=(t,e,r,n=0)=>t.usesBigInt&&!e.usesBigInt?Number(r)-Number(n):!t.usesBigInt&&e.usesBigInt?BigInt(r)-BigInt(n):St(r,-n),Oh=t=>t==null?!1:Array.isArray(t)||t instanceof ArrayBuffer||ArrayBuffer.isView(t)&&!(t instanceof DataView)||t instanceof zh?!0:Va(t),qe=-1,Th=s.z.string().transform(t=>new Uint8Array(atob(t).split("").map(e=>e.charCodeAt(0))).buffer),Sh=s.z.union([s.z.null(),s.z.undefined()]).transform(()=>new Uint8Array().buffer),Tt=class Ce{constructor(e){b(this,"key",""),b(this,"isSynnaxSeries",!0),b(this,"dataType"),b(this,"sampleOffset"),b(this,"gl"),b(this,"_data"),b(this,"_timeRange"),b(this,"alignment",0n),b(this,"_cachedMin"),b(this,"_cachedMax"),b(this,"writePos",qe),b(this,"_refCount",0),b(this,"_cachedLength"),Oh(e)&&(e={data:e});const{dataType:r,timeRange:n,sampleOffset:i=0,glBufferUsage:a="static",alignment:o=0n,key:u=wh()}=e,c=e.data??[];if(c instanceof Ce||typeof c=="object"&&"isSynnaxSeries"in c&&c.isSynnaxSeries===!0){const h=c;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 d=Va(c),f=Array.isArray(c);if(r!=null)this.dataType=new q(r);else{if(c instanceof ArrayBuffer)throw new Error("cannot infer data type from an ArrayBuffer instance when constructing a Series. Please provide a data type.");if(f||d){let h=c;if(!d){if(c.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=c[0]}if(typeof h=="string")this.dataType=q.STRING;else if(typeof h=="number")this.dataType=q.FLOAT64;else if(typeof h=="bigint")this.dataType=q.INT64;else if(typeof h=="boolean")this.dataType=q.BOOLEAN;else if(h instanceof G||h instanceof Date||h instanceof G)this.dataType=q.TIMESTAMP;else if(typeof h=="object")this.dataType=q.JSON;else throw new Error(`cannot infer data type of ${typeof h} when constructing a Series from a JS array`)}else this.dataType=new q(c)}if(!f&&!d)this._data=c;else{let h=d?[c]:c;const E=h[0];(E instanceof G||E instanceof Date||E instanceof Q)&&(h=h.map(P=>new G(P).valueOf())),this.dataType.equals(q.STRING)?(this._cachedLength=h.length,this._data=new TextEncoder().encode(h.join(`
|
|
17
|
+
`).map(o=>o.trim());if(r.length===0)return e!=null?e.parse({}):{};const i=r.split(",").map(o=>o.trim()),a={};return i.forEach(o=>{a[o]=[]}),n.forEach(o=>{const l=o.split(",").map(u=>u.trim());i.forEach((u,d)=>{const f=this.parseValue(l[d]);f!=null&&a[u].push(f)})}),e!=null?e.parse(a):a}parseValue(t){if(t==null||t.length===0)return null;const e=Number(t);return isNaN(e)?t.startsWith('"')&&t.endsWith('"')?t.slice(1,-1):t:e}static registerCustomType(){}},Du=class{constructor(){Pt(this,"contentType","text/plain")}encode(t){return new TextEncoder().encode(t).buffer}decode(t,e){const r=new TextDecoder().decode(t);return e!=null?e.parse(r):r}};const vr=new ju;new Mu;new Du;const rn=s.z.tuple([s.z.number(),s.z.number()]);s.z.tuple([s.z.bigint(),s.z.bigint()]);const Da=s.z.object({width:s.z.number(),height:s.z.number()}),Pu=s.z.object({signedWidth:s.z.number(),signedHeight:s.z.number()}),Bu=["width","height"];s.z.enum(Bu);const Uu=["start","center","end"],Lu=["signedWidth","signedHeight"];s.z.enum(Lu);const Gr=s.z.object({x:s.z.number(),y:s.z.number()}),_u=s.z.object({clientX:s.z.number(),clientY:s.z.number()}),Yu=["x","y"],Pa=s.z.enum(Yu),Ba=["top","right","bottom","left"];s.z.enum(Ba);const qu=["left","right"],Ua=s.z.enum(qu),Fu=["top","bottom"],La=s.z.enum(Fu),_a=["center"],ai=s.z.enum(_a),Vu=[...Ba,..._a],Ya=s.z.enum(Vu);s.z.enum(Uu);const Wu=["first","last"];s.z.enum(Wu);const Gu=s.z.object({lower:s.z.number(),upper:s.z.number()}),Zu=s.z.object({lower:s.z.bigint(),upper:s.z.bigint()});s.z.union([Gu,rn]);s.z.union([Zu,rn]);s.z.union([Pa,Ya]);s.z.union([Pa,Ya,s.z.instanceof(String)]);const Bt=(t,e)=>{const r={};if(typeof t=="number"||typeof t=="bigint")e!=null?(r.lower=t,r.upper=e):(r.lower=typeof t=="bigint"?0n:0,r.upper=t);else if(Array.isArray(t)){if(t.length!==2)throw new Error("bounds: expected array of length 2");[r.lower,r.upper]=t}else return oi(t);return oi(r)},oi=t=>t.lower>t.upper?{lower:t.upper,upper:t.lower}:t;s.z.object({x:Ua.or(ai),y:La.or(ai)});const Ku=s.z.object({x:Ua,y:La}),Ju=Object.freeze({x:"left",y:"top"}),Hu=(t,e)=>t.x===e.x&&t.y===e.y,ci=s.z.union([s.z.number(),Gr,rn,Da,Pu,_u]),Xu=(t,e)=>{if(typeof t=="string"){if(e===void 0)throw new Error("The y coordinate must be given.");return t==="x"?{x:e,y:0}:{x:0,y:e}}return typeof t=="number"?{x:t,y:e??t}:Array.isArray(t)?{x:t[0],y:t[1]}:"signedWidth"in t?{x:t.signedWidth,y:t.signedHeight}:"clientX"in t?{x:t.clientX,y:t.clientY}:"width"in t?{x:t.width,y:t.height}:{x:t.x,y:t.y}},li=Object.freeze({x:0,y:0}),or=s.z.union([s.z.number(),s.z.string()]);s.z.object({top:or,left:or,width:or,height:or});s.z.object({left:s.z.number(),top:s.z.number(),right:s.z.number(),bottom:s.z.number()});s.z.object({one:Gr,two:Gr,root:Ku});const vs=(t,e,r=0,n=0,i)=>{const a={one:{...li},two:{...li},root:i??Ju};if(typeof t=="number"){if(typeof e!="number")throw new Error("Box constructor called with invalid arguments");return a.one={x:t,y:e},a.two={x:a.one.x+r,y:a.one.y+n},a}return"one"in t&&"two"in t&&"root"in t?{...t,root:i??t.root}:("getBoundingClientRect"in t&&(t=t.getBoundingClientRect()),"left"in t?(a.one={x:t.left,y:t.top},a.two={x:t.right,y:t.bottom},a):(a.one=t,e==null?a.two={x:a.one.x+r,y:a.one.y+n}:typeof e=="number"?a.two={x:a.one.x+e,y:a.one.y+r}:"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))},Sn=t=>{const e=vs(t);return{lower:e.one.x,upper:e.two.x}},zn=t=>{const e=vs(t);return{lower:e.one.y,upper:e.two.y}},Qu=t=>typeof t!="object"||t==null?!1:"one"in t&&"two"in t&&"root"in t;var eh=Object.defineProperty,th=(t,e,r)=>e in t?eh(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,je=(t,e,r)=>th(t,typeof e!="symbol"?e+"":e,r);const rh=(t,e,r)=>e!==void 0&&t<e?e:r!==void 0&&t>r?r:t;s.z.object({offset:ci,scale:ci});const nh=t=>(e,r,n,i)=>r==="dimension"?[e,n]:[e,i?n-t:n+t],sh=t=>(e,r,n,i)=>[e,i?n/t:n*t],ih=t=>(e,r,n)=>{if(e===null)return[t,n];const{lower:i,upper:a}=e,{lower:o,upper:l}=t,u=a-i,d=l-o;if(r==="dimension")return[t,n*(d/u)];const f=(n-i)*(d/u)+o;return[t,f]},ah=t=>(e,r,n)=>[t,n],oh=()=>(t,e,r)=>{if(t===null)throw new Error("cannot invert without bounds");if(e==="dimension")return[t,r];const{lower:n,upper:i}=t;return[t,i-(r-n)]},ch=t=>(e,r,n)=>{const{lower:i,upper:a}=t;return n=rh(n,i,a),[e,n]},Hn=class Ot{constructor(){je(this,"ops",[]),je(this,"currBounds",null),je(this,"currType",null),je(this,"reversed",!1),this.ops=[]}static translate(e){return new Ot().translate(e)}static magnify(e){return new Ot().magnify(e)}static scale(e,r){return new Ot().scale(e,r)}translate(e){const r=this.new(),n=nh(e);return n.type="translate",r.ops.push(n),r}magnify(e){const r=this.new(),n=sh(e);return n.type="magnify",r.ops.push(n),r}scale(e,r){const n=Bt(e,r),i=this.new(),a=ih(n);return a.type="scale",i.ops.push(a),i}clamp(e,r){const n=Bt(e,r),i=this.new(),a=ch(n);return a.type="clamp",i.ops.push(a),i}reBound(e,r){const n=Bt(e,r),i=this.new(),a=ah(n);return a.type="re-bound",i.ops.push(a),i}invert(){const e=oh();e.type="invert";const r=this.new();return r.ops.push(e),r}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,r){return this.currBounds=null,this.ops.reduce(([n,i],a)=>a(n,e,i,this.reversed),[null,r])[1]}reverse(){const e=this.new();e.ops.reverse();const r=[];return e.ops.forEach((n,i)=>{if(n.type==="scale"||r.some(([o,l])=>i>=o&&i<=l))return;const a=e.ops.findIndex((o,l)=>o.type==="scale"&&l>i);a!==-1&&r.push([i,a])}),r.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}};je(Hn,"IDENTITY",new Hn);let ui=Hn;const hi=class xe{constructor(e=new ui,r=new ui,n=null){je(this,"x"),je(this,"y"),je(this,"currRoot"),this.x=e,this.y=r,this.currRoot=n}static translate(e,r){return new xe().translate(e,r)}static translateX(e){return new xe().translateX(e)}static translateY(e){return new xe().translateY(e)}static clamp(e){return new xe().clamp(e)}static magnify(e){return new xe().magnify(e)}static scale(e){return new xe().scale(e)}static reBound(e){return new xe().reBound(e)}translate(e,r){const n=Xu(e,r),i=this.copy();return i.x=this.x.translate(n.x),i.y=this.y.translate(n.y),i}translateX(e){const r=this.copy();return r.x=this.x.translate(e),r}translateY(e){const r=this.copy();return r.y=this.y.translate(e),r}magnify(e){const r=this.copy();return r.x=this.x.magnify(e.x),r.y=this.y.magnify(e.y),r}scale(e){const r=this.copy();if(Qu(e)){const n=this.currRoot;return r.currRoot=e.root,n!=null&&!Hu(n,e.root)&&(n.x!==e.root.x&&(r.x=r.x.invert()),n.y!==e.root.y&&(r.y=r.y.invert())),r.x=r.x.scale(Sn(e)),r.y=r.y.scale(zn(e)),r}return r.x=r.x.scale(e.width),r.y=r.y.scale(e.height),r}reBound(e){const r=this.copy();return r.x=this.x.reBound(Sn(e)),r.y=this.y.reBound(zn(e)),r}clamp(e){const r=this.copy();return r.x=this.x.clamp(Sn(e)),r.y=this.y.clamp(zn(e)),r}copy(){const e=new xe;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 vs(this.pos(e.one),this.pos(e.two),0,0,this.currRoot??e.root)}};je(hi,"IDENTITY",new hi);const lh=t=>t!=null&&typeof t=="object"&&"toString"in t,uh=(t,e=!1)=>{const r=lh(t)?"stringer":typeof t;let n;switch(r){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 ${r}`),()=>-1}return e?hh(n):n},hh=t=>(e,r)=>t(r,e),dh=s.z.object({signedWidth:s.z.number(),signedHeight:s.z.number()});s.z.union([Da,dh,Gr,rn]);const fh=s.z.bigint().or(s.z.string().transform(BigInt));var yh=Object.defineProperty,gh=(t,e,r)=>e in t?yh(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,b=(t,e,r)=>gh(t,typeof e!="symbol"?e+"":e,r);let ph=(t,e=21)=>(r=e)=>{let n="",i=r;for(;i--;)n+=t[Math.random()*t.length|0];return n};const mh="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",wh=ph(mh,11),bh=s.z.enum(["static","dynamic"]),qa=(t,e)=>{const r=new G(e);if(![Q.DAY,Q.HOUR,Q.MINUTE,Q.SECOND,Q.MILLISECOND,Q.MICROSECOND,Q.NANOSECOND].some(i=>i.equals(r)))throw new Error("Invalid argument for remainder. Must be an even TimeSpan or Timestamp");const n=t.valueOf()%r.valueOf();return t instanceof G?new G(n):new Q(n)},_=class z{constructor(e,r="UTC"){if(b(this,"value"),b(this,"encodeValue",!0),e==null)this.value=z.now().valueOf();else if(e instanceof Date)this.value=BigInt(e.getTime())*z.MILLISECOND.valueOf();else if(typeof e=="string")this.value=z.parseDateTimeString(e,r).valueOf();else if(Array.isArray(e))this.value=z.parseDate(e);else{let n=BigInt(0);e instanceof Number&&(e=e.valueOf()),r==="local"&&(n=z.utcOffset.valueOf()),typeof e=="number"&&(isFinite(e)?e=Math.trunc(e):(isNaN(e)&&(e=0),e===1/0?e=z.MAX:e=z.MIN)),this.value=BigInt(e.valueOf())+n}}static parseDate([e=1970,r=1,n=1]){const i=new Date(e,r-1,n,0,0,0,0);return new z(BigInt(i.getTime())*z.MILLISECOND.valueOf()).truncate(z.DAY).valueOf()}encode(){return this.value.toString()}valueOf(){return this.value}static parseTimeString(e,r="UTC"){const[n,i,a]=e.split(":");let o="00",l="00";a!=null&&([o,l]=a.split("."));let u=z.hours(parseInt(n??"00",10)).add(z.minutes(parseInt(i??"00",10))).add(z.seconds(parseInt(o??"00",10))).add(z.milliseconds(parseInt(l??"00",10)));return r==="local"&&(u=u.add(z.utcOffset)),u.valueOf()}static parseDateTimeString(e,r="UTC"){if(!e.includes("/")&&!e.includes("-"))return z.parseTimeString(e,r);const n=new Date(e);return e.includes(":")||n.setUTCHours(0,0,0,0),new z(BigInt(n.getTime())*z.MILLISECOND.valueOf(),r).valueOf()}fString(e="ISO",r="UTC"){switch(e){case"ISODate":return this.toISOString(r).slice(0,10);case"ISOTime":return this.toISOString(r).slice(11,23);case"time":return this.timeString(!1,r);case"preciseTime":return this.timeString(!0,r);case"date":return this.dateString();case"preciseDate":return`${this.dateString()} ${this.timeString(!0,r)}`;case"dateTime":return`${this.dateString()} ${this.timeString(!1,r)}`;default:return this.toISOString(r)}}toISOString(e="UTC"){return e==="UTC"?this.date().toISOString():this.sub(z.utcOffset).date().toISOString()}timeString(e=!1,r="UTC"){const n=this.toISOString(r);return e?n.slice(11,23):n.slice(11,19)}dateString(){const e=this.date(),r=e.toLocaleString("default",{month:"short"}),n=e.toLocaleString("default",{day:"numeric"});return`${r} ${n}`}static get utcOffset(){return new Q(BigInt(new Date().getTimezoneOffset())*z.MINUTE.valueOf())}static since(e){return new z().span(e)}date(){return new Date(this.milliseconds())}equals(e){return this.valueOf()===new z(e).valueOf()}span(e){return this.range(e).span}range(e){return new Os(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 z(e).valueOf()}afterEq(e){return this.valueOf()>=new z(e).valueOf()}before(e){return this.valueOf()<new z(e).valueOf()}beforeEq(e){return this.valueOf()<=new z(e).valueOf()}add(e){return new z(this.valueOf()+BigInt(e.valueOf()))}sub(e){return new z(this.valueOf()-BigInt(e.valueOf()))}milliseconds(){return Number(this.valueOf())/Number(z.MILLISECOND.valueOf())}toString(){return this.date().toISOString()}remainder(e){return qa(this,e)}get isToday(){return this.truncate(Q.DAY).equals(z.now().truncate(Q.DAY))}truncate(e){return this.sub(this.remainder(e))}static now(){return new z(new Date)}static max(...e){let r=z.MIN;for(const n of e){const i=new z(n);i.after(r)&&(r=i)}return r}static min(...e){let r=z.MAX;for(const n of e){const i=new z(n);i.before(r)&&(r=i)}return r}static nanoseconds(e){return new z(e)}static microseconds(e){return z.nanoseconds(e*1e3)}static milliseconds(e){return z.microseconds(e*1e3)}static seconds(e){return z.milliseconds(e*1e3)}static minutes(e){return z.seconds(e*60)}static hours(e){return z.minutes(e*60)}static days(e){return z.hours(e*24)}};b(_,"NANOSECOND",_.nanoseconds(1)),b(_,"MICROSECOND",_.microseconds(1)),b(_,"MILLISECOND",_.milliseconds(1)),b(_,"SECOND",_.seconds(1)),b(_,"MINUTE",_.minutes(1)),b(_,"HOUR",_.hours(1)),b(_,"DAY",_.days(1)),b(_,"MAX",new _((1n<<63n)-1n)),b(_,"MIN",new _(0)),b(_,"ZERO",new _(0)),b(_,"z",s.z.union([s.z.object({value:s.z.bigint()}).transform(t=>new _(t.value)),s.z.string().transform(t=>new _(BigInt(t))),s.z.instanceof(Number).transform(t=>new _(t)),s.z.number().transform(t=>new _(t)),s.z.instanceof(_)]));let G=_;const Y=class ${constructor(e){b(this,"value"),b(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 $(e).valueOf()}greaterThan(e){return this.valueOf()>new $(e).valueOf()}lessThanOrEqual(e){return this.valueOf()<=new $(e).valueOf()}greaterThanOrEqual(e){return this.valueOf()>=new $(e).valueOf()}remainder(e){return qa(this,e)}truncate(e){return new $(BigInt(Math.trunc(Number(this.valueOf()/e.valueOf())))*e.valueOf())}toString(){const e=this.truncate($.DAY),r=this.truncate($.HOUR),n=this.truncate($.MINUTE),i=this.truncate($.SECOND),a=this.truncate($.MILLISECOND),o=this.truncate($.MICROSECOND),l=this.truncate($.NANOSECOND),u=e,d=r.sub(e),f=n.sub(r),h=i.sub(n),E=a.sub(i),P=o.sub(a),ie=l.sub(o);let M="";return u.isZero||(M+=`${u.days}d `),d.isZero||(M+=`${d.hours}h `),f.isZero||(M+=`${f.minutes}m `),h.isZero||(M+=`${h.seconds}s `),E.isZero||(M+=`${E.milliseconds}ms `),P.isZero||(M+=`${P.microseconds}µs `),ie.isZero||(M+=`${ie.nanoseconds}ns`),M.trim()}get days(){return Number(this.valueOf())/Number($.DAY.valueOf())}get hours(){return Number(this.valueOf())/Number($.HOUR.valueOf())}get minutes(){return Number(this.valueOf())/Number($.MINUTE.valueOf())}get seconds(){return Number(this.valueOf())/Number($.SECOND.valueOf())}get milliseconds(){return Number(this.valueOf())/Number($.MILLISECOND.valueOf())}get microseconds(){return Number(this.valueOf())/Number($.MICROSECOND.valueOf())}get nanoseconds(){return Number(this.valueOf())}get isZero(){return this.valueOf()===BigInt(0)}equals(e){return this.valueOf()===new $(e).valueOf()}add(e){return new $(this.valueOf()+new $(e).valueOf())}sub(e){return new $(this.valueOf()-new $(e).valueOf())}static nanoseconds(e=1){return new $(e)}static microseconds(e=1){return $.nanoseconds(e*1e3)}static milliseconds(e=1){return $.microseconds(e*1e3)}static seconds(e=1){return $.milliseconds(e*1e3)}static minutes(e){return $.seconds(e.valueOf()*60)}static hours(e){return $.minutes(e*60)}static days(e){return $.hours(e*24)}};b(Y,"NANOSECOND",Y.nanoseconds(1)),b(Y,"MICROSECOND",Y.microseconds(1)),b(Y,"MILLISECOND",Y.milliseconds(1)),b(Y,"SECOND",Y.seconds(1)),b(Y,"MINUTE",Y.minutes(1)),b(Y,"HOUR",Y.hours(1)),b(Y,"DAY",Y.days(1)),b(Y,"MAX",new Y((1n<<63n)-1n)),b(Y,"MIN",new Y(0)),b(Y,"ZERO",new Y(0)),b(Y,"z",s.z.union([s.z.object({value:s.z.bigint()}).transform(t=>new Y(t.value)),s.z.string().transform(t=>new Y(BigInt(t))),s.z.instanceof(Number).transform(t=>new Y(t)),s.z.number().transform(t=>new Y(t)),s.z.instanceof(Y)]));let Q=Y;const cr=class Or extends Number{constructor(e){e instanceof Number?super(e.valueOf()):super(e)}toString(){return`${this.valueOf()} Hz`}equals(e){return this.valueOf()===new Or(e).valueOf()}get period(){return Q.seconds(1/this.valueOf())}sampleCount(e){return new Q(e).seconds*this.valueOf()}byteCount(e,r){return this.sampleCount(e)*new ue(r).valueOf()}span(e){return Q.seconds(e/this.valueOf())}byteSpan(e,r){return this.span(e.valueOf()/r.valueOf())}static hz(e){return new Or(e)}static khz(e){return Or.hz(e*1e3)}};b(cr,"z",s.z.union([s.z.number().transform(t=>new cr(t)),s.z.instanceof(Number).transform(t=>new cr(t)),s.z.instanceof(cr)]));const re=class extends Number{constructor(e){e instanceof Number?super(e.valueOf()):super(e)}length(e){return e.valueOf()/this.valueOf()}size(e){return new Fa(e*this.valueOf())}};b(re,"UNKNOWN",new re(0)),b(re,"BIT128",new re(16)),b(re,"BIT64",new re(8)),b(re,"BIT32",new re(4)),b(re,"BIT16",new re(2)),b(re,"BIT8",new re(1)),b(re,"z",s.z.union([s.z.number().transform(t=>new re(t)),s.z.instanceof(Number).transform(t=>new re(t)),s.z.instanceof(re)]));let ue=re;const ze=class Tr{constructor(e,r){b(this,"start"),b(this,"end"),typeof e=="object"&&"start"in e?(this.start=new G(e.start),this.end=new G(e.end)):(this.start=new G(e),this.end=new G(r))}get span(){return new Q(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 Tr(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,r=Q.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=G.max(n.start,e.start),a=G.min(n.end,e.end);return a.before(i)?!1:new Q(a.sub(i)).greaterThanOrEqual(r)}roughlyEquals(e,r){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<=r.valueOf()&&i<=r.valueOf()}contains(e){return e instanceof Tr?this.contains(e.start)&&this.contains(e.end):this.start.beforeEq(e)&&this.end.after(e)}boundBy(e){const r=new Tr(this.start,this.end);return e.start.after(this.start)&&(r.start=e.start),e.start.after(this.end)&&(r.end=e.start),e.end.before(this.end)&&(r.end=e.end),e.end.before(this.start)&&(r.start=e.end),r}};b(ze,"MAX",new ze(G.MIN,G.MAX)),b(ze,"MIN",new ze(G.MAX,G.MIN)),b(ze,"ZERO",new ze(G.ZERO,G.ZERO)),b(ze,"z",s.z.union([s.z.object({start:G.z,end:G.z}).transform(t=>new ze(t.start,t.end)),s.z.instanceof(ze)]));let Os=ze;const g=class Ne extends String{constructor(e){if(e instanceof Ne||typeof e=="string"||typeof e.valueOf()=="string"){super(e.valueOf());return}else{const r=Ne.ARRAY_CONSTRUCTOR_DATA_TYPES.get(e.constructor.name);if(r!=null){super(r.valueOf());return}}throw super(Ne.UNKNOWN.valueOf()),new Error(`unable to find data type for ${e.toString()}`)}get Array(){const e=Ne.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(r=>this.equals(r))}toString(){return this.valueOf()}get isVariable(){return this.equals(Ne.JSON)||this.equals(Ne.STRING)}get isNumeric(){return!this.isVariable&&!this.equals(Ne.UUID)}get isInteger(){return this.toString().startsWith("int")}get isFloat(){return this.toString().startsWith("float")}get density(){const e=Ne.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 Ne.BIG_INT_TYPES.some(e=>e.equals(this))}};b(g,"UNKNOWN",new g("unknown")),b(g,"FLOAT64",new g("float64")),b(g,"FLOAT32",new g("float32")),b(g,"INT64",new g("int64")),b(g,"INT32",new g("int32")),b(g,"INT16",new g("int16")),b(g,"INT8",new g("int8")),b(g,"UINT64",new g("uint64")),b(g,"UINT32",new g("uint32")),b(g,"UINT16",new g("uint16")),b(g,"UINT8",new g("uint8")),b(g,"BOOLEAN",g.UINT8),b(g,"TIMESTAMP",new g("timestamp")),b(g,"UUID",new g("uuid")),b(g,"STRING",new g("string")),b(g,"JSON",new g("json")),b(g,"ARRAY_CONSTRUCTORS",new Map([[g.UINT8.toString(),Uint8Array],[g.UINT16.toString(),Uint16Array],[g.UINT32.toString(),Uint32Array],[g.UINT64.toString(),BigUint64Array],[g.FLOAT32.toString(),Float32Array],[g.FLOAT64.toString(),Float64Array],[g.INT8.toString(),Int8Array],[g.INT16.toString(),Int16Array],[g.INT32.toString(),Int32Array],[g.INT64.toString(),BigInt64Array],[g.TIMESTAMP.toString(),BigInt64Array],[g.STRING.toString(),Uint8Array],[g.JSON.toString(),Uint8Array],[g.UUID.toString(),Uint8Array]])),b(g,"ARRAY_CONSTRUCTOR_DATA_TYPES",new Map([[Uint8Array.name,g.UINT8],[Uint16Array.name,g.UINT16],[Uint32Array.name,g.UINT32],[BigUint64Array.name,g.UINT64],[Float32Array.name,g.FLOAT32],[Float64Array.name,g.FLOAT64],[Int8Array.name,g.INT8],[Int16Array.name,g.INT16],[Int32Array.name,g.INT32],[BigInt64Array.name,g.INT64]])),b(g,"DENSITIES",new Map([[g.UINT8.toString(),ue.BIT8],[g.UINT16.toString(),ue.BIT16],[g.UINT32.toString(),ue.BIT32],[g.UINT64.toString(),ue.BIT64],[g.FLOAT32.toString(),ue.BIT32],[g.FLOAT64.toString(),ue.BIT64],[g.INT8.toString(),ue.BIT8],[g.INT16.toString(),ue.BIT16],[g.INT32.toString(),ue.BIT32],[g.INT64.toString(),ue.BIT64],[g.TIMESTAMP.toString(),ue.BIT64],[g.STRING.toString(),ue.UNKNOWN],[g.JSON.toString(),ue.UNKNOWN],[g.UUID.toString(),ue.BIT128]])),b(g,"ALL",[g.UNKNOWN,g.FLOAT64,g.FLOAT32,g.INT64,g.INT32,g.INT16,g.INT8,g.UINT64,g.UINT32,g.UINT16,g.UINT8,g.TIMESTAMP,g.UUID,g.STRING,g.JSON]),b(g,"BIG_INT_TYPES",[g.INT64,g.UINT64,g.TIMESTAMP]),b(g,"z",s.z.union([s.z.string().transform(t=>new g(t)),s.z.instanceof(g)]));let q=g;const oe=class H extends Number{constructor(e){super(e.valueOf())}largerThan(e){return this.valueOf()>e.valueOf()}smallerThan(e){return this.valueOf()<e.valueOf()}add(e){return H.bytes(this.valueOf()+e.valueOf())}sub(e){return H.bytes(this.valueOf()-e.valueOf())}truncate(e){return new H(Math.trunc(this.valueOf()/e.valueOf())*e.valueOf())}remainder(e){return H.bytes(this.valueOf()%e.valueOf())}get gigabytes(){return this.valueOf()/H.GIGABYTE.valueOf()}get megabytes(){return this.valueOf()/H.MEGABYTE.valueOf()}get kilobytes(){return this.valueOf()/H.KILOBYTE.valueOf()}get terabytes(){return this.valueOf()/H.TERABYTE.valueOf()}toString(){const e=this.truncate(H.TERABYTE),r=this.truncate(H.GIGABYTE),n=this.truncate(H.MEGABYTE),i=this.truncate(H.KILOBYTE),a=this.truncate(H.BYTE),o=e,l=r.sub(e),u=n.sub(r),d=i.sub(n),f=a.sub(i);let h="";return o.isZero||(h+=`${o.terabytes}TB `),l.isZero||(h+=`${l.gigabytes}GB `),u.isZero||(h+=`${u.megabytes}MB `),d.isZero||(h+=`${d.kilobytes}KB `),(!f.isZero||h==="")&&(h+=`${f.valueOf()}B`),h.trim()}static bytes(e=1){return new H(e)}static kilobytes(e=1){return H.bytes(e.valueOf()*1e3)}static megabytes(e=1){return H.kilobytes(e.valueOf()*1e3)}static gigabytes(e=1){return H.megabytes(e.valueOf()*1e3)}static terabytes(e){return H.gigabytes(e.valueOf()*1e3)}get isZero(){return this.valueOf()===0}};b(oe,"BYTE",new oe(1)),b(oe,"KILOBYTE",oe.kilobytes(1)),b(oe,"MEGABYTE",oe.megabytes(1)),b(oe,"GIGABYTE",oe.gigabytes(1)),b(oe,"TERABYTE",oe.terabytes(1)),b(oe,"ZERO",new oe(0)),b(oe,"z",s.z.union([s.z.number().transform(t=>new oe(t)),s.z.instanceof(oe)]));let Fa=oe;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 Va=t=>{const e=typeof t;return e==="string"||e==="number"||e==="boolean"||e==="bigint"||t instanceof G||t instanceof Q||t instanceof Date},vh=(t,e,r,n=0)=>t.usesBigInt&&!e.usesBigInt?Number(r)-Number(n):!t.usesBigInt&&e.usesBigInt?BigInt(r)-BigInt(n):St(r,-n),Oh=t=>t==null?!1:Array.isArray(t)||t instanceof ArrayBuffer||ArrayBuffer.isView(t)&&!(t instanceof DataView)||t instanceof zh?!0:Va(t),qe=-1,Th=s.z.string().transform(t=>new Uint8Array(atob(t).split("").map(e=>e.charCodeAt(0))).buffer),Sh=s.z.union([s.z.null(),s.z.undefined()]).transform(()=>new Uint8Array().buffer),Tt=class Ce{constructor(e){b(this,"key",""),b(this,"isSynnaxSeries",!0),b(this,"dataType"),b(this,"sampleOffset"),b(this,"gl"),b(this,"_data"),b(this,"_timeRange"),b(this,"alignment",0n),b(this,"_cachedMin"),b(this,"_cachedMax"),b(this,"writePos",qe),b(this,"_refCount",0),b(this,"_cachedLength"),Oh(e)&&(e={data:e});const{dataType:r,timeRange:n,sampleOffset:i=0,glBufferUsage:a="static",alignment:o=0n,key:l=wh()}=e,u=e.data??[];if(u instanceof Ce||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 d=Va(u),f=Array.isArray(u);if(r!=null)this.dataType=new q(r);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(f||d){let h=u;if(!d){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=q.STRING;else if(typeof h=="number")this.dataType=q.FLOAT64;else if(typeof h=="bigint")this.dataType=q.INT64;else if(typeof h=="boolean")this.dataType=q.BOOLEAN;else if(h instanceof G||h instanceof Date||h instanceof G)this.dataType=q.TIMESTAMP;else if(typeof h=="object")this.dataType=q.JSON;else throw new Error(`cannot infer data type of ${typeof h} when constructing a Series from a JS array`)}else this.dataType=new q(u)}if(!f&&!d)this._data=u;else{let h=d?[u]:u;const E=h[0];(E instanceof G||E instanceof Date||E instanceof Q)&&(h=h.map(P=>new G(P).valueOf())),this.dataType.equals(q.STRING)?(this._cachedLength=h.length,this._data=new TextEncoder().encode(h.join(`
|
|
18
18
|
`)+`
|
|
19
19
|
`)):this.dataType.equals(q.JSON)?(this._cachedLength=h.length,this._data=new TextEncoder().encode(h.map(P=>vr.encodeString(P)).join(`
|
|
20
20
|
`)+`
|
|
21
|
-
`)):this._data=new this.dataType.Array(h).buffer}this.key=
|
|
21
|
+
`)):this._data=new this.dataType.Array(h).buffer}this.key=l,this.alignment=o,this.sampleOffset=i??0,this._timeRange=n,this.gl={control:null,buffer:null,prevBuffer:0,bufferUsage:a}}static alloc({capacity:e,dataType:r,...n}){if(e===0)throw new Error("[Series] - cannot allocate an array of length 0");const i=new new q(r).Array(e),a=new Ce({data:i.buffer,dataType:r,...n});return a.writePos=0,a}static generateTimestamps(e,r,n){const i=n.spanRange(r.span(e)),a=new BigInt64Array(e);for(let o=0;o<e;o++)a[o]=BigInt(n.add(r.span(o)).valueOf());return new Ce({data:a,dataType:q.TIMESTAMP,timeRange:i})}get refCount(){return this._refCount}static fromStrings(e,r){const n=new TextEncoder().encode(e.join(`
|
|
22
22
|
`)+`
|
|
23
23
|
`);return new Ce({data:n,dataType:q.STRING,timeRange:r})}static fromJSON(e,r){const n=new TextEncoder().encode(e.map(i=>vr.encodeString(i)).join(`
|
|
24
24
|
`)+`
|
|
25
25
|
`);return new Ce({data:n,dataType:q.JSON,timeRange:r})}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===qe)return 0;const r=this.capacity-this.writePos,n=r<e.length?e.slice(0,r):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===qe?this.underlyingData:new this.dataType.Array(this._data,0,this.writePos)}toStrings(){if(!this.dataType.matches(q.STRING,q.UUID))throw new Error("cannot convert non-string series to strings");return new TextDecoder().decode(this.buffer).split(`
|
|
26
26
|
`).slice(0,-1)}toUUIDs(){if(!this.dataType.equals(q.UUID))throw new Error("cannot convert non-uuid series to uuids");const e=q.UUID.density.valueOf(),r=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),o=>o.toString(16).padStart(2,"0")).join("").replace(/(.{8})(.{4})(.{4})(.{4})(.{12})/,"$1-$2-$3-$4-$5");r[n]=a}return r}parseJSON(e){if(!this.dataType.equals(q.JSON))throw new Error("cannot convert non-string series to strings");return new TextDecoder().decode(this.buffer).split(`
|
|
27
|
-
`).slice(0,-1).map(r=>e.parse(vr.decodeString(r)))}get timeRange(){if(this._timeRange==null)throw new Error("time range not set on series");return this._timeRange}get byteCapacity(){return new Fa(this.buffer.byteLength)}get capacity(){return this.dataType.density.length(this.byteCapacity)}get byteLength(){return this.writePos===qe?this.byteCapacity:this.dataType.density.size(this.writePos)}get length(){return this._cachedLength!=null?this._cachedLength:this.dataType.isVariable?this.calculateCachedLength():this.writePos===qe?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(r=>{r===10&&e++}),this._cachedLength=e,e}convert(e,r=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]=vh(this.dataType,e,this.data[i],r);return new Ce({data:n.buffer,dataType:e,timeRange:this._timeRange,sampleOffset:r,glBufferUsage:this.gl.bufferUsage,alignment:this.alignment})}calcRawMax(){if(this.length===0)return-1/0;if(this.dataType.equals(q.TIMESTAMP))this._cachedMax=this.data[this.data.length-1];else if(this.dataType.usesBigInt){const e=this.data;this._cachedMax=e.reduce((r,n)=>r>n?r:n)}else{const e=this.data;this._cachedMax=e.reduce((r,n)=>r>n?r: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()),St(this._cachedMax,this.sampleOffset))}calcRawMin(){if(this.length===0)return 1/0;if(this.dataType.equals(q.TIMESTAMP))this._cachedMin=this.data[0];else if(this.dataType.usesBigInt){const e=this.data;this._cachedMin=e.reduce((r,n)=>r<n?r:n)}else{const e=this.data;this._cachedMin=e.reduce((r,n)=>r<n?r: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()),St(this._cachedMin,this.sampleOffset))}get bounds(){return Bt(Number(this.min),Number(this.max))}maybeRecomputeMinMax(e){if(this._cachedMin!=null){const r=e._cachedMin??e.calcRawMin();r<this._cachedMin&&(this._cachedMin=r)}if(this._cachedMax!=null){const r=e._cachedMax??e.calcRawMax();r>this._cachedMax&&(this._cachedMax=r)}}enrich(){this.max,this.min}get range(){return St(this.max,-this.min)}at(e,r){if(this.dataType.isVariable)return this.atVariable(e,r??!1);e<0&&(e=this.length+e);const n=this.data[e];if(n==null){if(r===!0)throw new Error(`[series] - no value at index ${e}`);return}return St(n,this.sampleOffset)}atVariable(e,r){e<0&&(e=this.length+e);let n=0,i=0;for(let o=0;o<this.data.length;o++)if(this.data[o]===10){if(e===0){i=o;break}n=o+1,e--}if(i===0&&(i=this.data.length),n>=i||e>0){if(r)throw new Error(`[series] - no value at index ${e}`);return}const a=this.data.slice(n,i);return this.dataType.equals(q.STRING)?new TextDecoder().decode(a):ja(JSON.parse(new TextDecoder().decode(a)))}binarySearch(e){let r=0,n=this.length-1;const i=uh(e);for(;r<=n;){const a=Math.floor((r+n)/2),o=i(this.at(a,!0),e);if(o===0)return a;o<0?r=a+1:n=a-1}return r}updateGLBuffer(e){if(this.gl.control=e,!this.dataType.equals(q.FLOAT32))throw new Error("Only FLOAT32 arrays can be used in WebGL");const{buffer:r,bufferUsage:n,prevBuffer:i}=this.gl;if(r==null&&(this.gl.buffer=e.createBuffer()),this.writePos!==i)if(e.bindBuffer(e.ARRAY_BUFFER,this.gl.buffer),this.writePos!==qe){i===0&&e.bufferData(e.ARRAY_BUFFER,this.byteCapacity.valueOf(),e.STATIC_DRAW);const a=this.dataType.density.size(i).valueOf(),o=this.underlyingData.slice(this.gl.prevBuffer,this.writePos);e.bufferSubData(e.ARRAY_BUFFER,a,o.buffer),this.gl.prevBuffer=this.writePos}else e.bufferData(e.ARRAY_BUFFER,this.buffer,n==="static"?e.STATIC_DRAW:e.DYNAMIC_DRAW),this.gl.prevBuffer=qe}as(e){if(e==="string"){if(!this.dataType.equals(q.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(q.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 Nh(this);return this.dataType.equals(q.JSON)?new Eh(e):e}return new Ih(this)}slice(e,r){if(e<=0&&(r==null||r>=this.length))return this;const n=this.data.slice(e,r);return new Ce({data:n,dataType:this.dataType,timeRange:this._timeRange,sampleOffset:this.sampleOffset,glBufferUsage:this.gl.bufferUsage,alignment:this.alignment+BigInt(e)})}reAlign(e){return new Ce({data:this.buffer,dataType:this.dataType,timeRange:Os.ZERO,sampleOffset:this.sampleOffset,glBufferUsage:"static",alignment:e})}};b(Tt,"crudeZ",s.z.object({timeRange:Os.z.optional(),dataType:q.z,alignment:fh.optional(),data:s.z.union([Th,Sh,s.z.instanceof(ArrayBuffer)]),glBufferUsage:bh.optional().default("static").optional()})),b(Tt,"z",Tt.crudeZ.transform(t=>new Tt(t)));let zh=Tt;class Nh{constructor(e){if(b(this,"series"),b(this,"index"),b(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,r=this.series.data;for(;this.index<r.length&&r[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 di,fi;class Eh{constructor(e){b(this,"wrapped"),b(this,di,"JSONSeriesIterator"),this.wrapped=e}next(){const e=this.wrapped.next();return e.done===!0?{done:!0,value:void 0}:{done:!1,value:vr.decodeString(e.value)}}[(fi=Symbol.iterator,di=Symbol.toStringTag,fi)](){return this}}var yi,gi;class Ih{constructor(e){b(this,"series"),b(this,"index"),b(this,yi,"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)}}[(gi=Symbol.iterator,yi=Symbol.toStringTag,gi)](){return this}}const St=(t,e)=>typeof t=="bigint"&&typeof e=="bigint"||typeof t=="number"&&typeof e=="number"?t+e:e===0?t:t===0?e:Number(t)+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 Wa=()=>typeof process<"u"&&process.versions!=null&&process.versions.node!=null?"node":typeof window>"u"||window.document===void 0?"webworker":"browser",Ah=Wa(),Ga=["MacOS","Windows","Linux","Docker"],kh=s.z.enum(Ga);let Nn;const xh=()=>{if(typeof window>"u")return;const t=window.navigator.userAgent.toLowerCase();if(t.includes("mac"))return"MacOS";if(t.includes("win"))return"Windows";if(t.includes("linux"))return"Linux"},Ch=(t={})=>{const{force:e,default:r}=t;return e??Nn??(Nn=xh(),Nn??r)},Za=Object.freeze(Object.defineProperty({__proto__:null,OPERATING_SYSTEMS:Ga,RUNTIME:Ah,detect:Wa,getOS:Ch,osZ:kh},Symbol.toStringTag,{value:"Module"}));var $h=Object.defineProperty,Rh=(t,e,r)=>e in t?$h(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,zt=(t,e,r)=>Rh(t,typeof e!="symbol"?e+"":e,r);const jh=(...t)=>t.map(Ka).join(""),Ka=t=>(t.endsWith("/")||(t+="/"),t.startsWith("/")&&(t=t.slice(1)),t),Mh=t=>t.endsWith("/")?t.slice(0,-1):t,Dh=(t,e="")=>t===null?"":"?"+Object.entries(t).filter(([,r])=>r==null?!1:Array.isArray(r)?r.length>0:!0).map(([r,n])=>`${e}${r}=${n}`).join("&"),Xn=class Qn{constructor({host:e,port:r,protocol:n="",pathPrefix:i=""}){zt(this,"protocol"),zt(this,"host"),zt(this,"port"),zt(this,"path"),this.protocol=n,this.host=e,this.port=r,this.path=Ka(i)}replace(e){return new Qn({host:e.host??this.host,port:e.port??this.port,protocol:e.protocol??this.protocol,pathPrefix:e.pathPrefix??this.path})}child(e){return new Qn({...this,pathPrefix:jh(this.path,e)})}toString(){return Mh(`${this.protocol}://${this.host}:${this.port}/${this.path}`)}};zt(Xn,"UNKNOWN",new Xn({host:"unknown",port:0}));let Ph=Xn;var Bh=Object.defineProperty,Uh=(t,e,r)=>e in t?Bh(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Sr=(t,e,r)=>Uh(t,typeof e!="symbol"?e+"":e,r);const Xe=class extends Number{};Sr(Xe,"Absolute",255),Sr(Xe,"Default",1),Sr(Xe,"z",s.z.union([s.z.instanceof(Xe),s.z.number().int().min(0).max(255).transform(t=>new Xe(t)),s.z.instanceof(Number).transform(t=>new Xe(t))]));s.z.object({name:s.z.string(),key:s.z.string()});const Ja=class Nt extends Error{constructor(){super(Nt.MESSAGE)}matches(e){return typeof e=="string"?e.includes(Nt.MESSAGE):e instanceof Nt||e.message.includes(Nt.MESSAGE)}};Sr(Ja,"MESSAGE","canceled");let Lh=Ja;new Lh;s.z.string().regex(/^\d+\.\d+\.\d+$/);const de=t=>e=>e!=null&&typeof e=="object"&&"type"in e&&typeof e.type=="string"?e.type.includes(t):e instanceof Error?e.message.includes(t):typeof e!="string"?!1:e.includes(t);let Oe=class extends Error{constructor(e){super(e),D(this,"discriminator","FreighterError"),D(this,"type","")}};const _h=t=>{if(t==null||typeof t!="object")return!1;const e=t;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},pi="unknown",mi="nil",Yh="freighter",Xt=s.z.object({type:s.z.string(),data:s.z.string()});class qh{constructor(){D(this,"providers",[])}register(e){this.providers.push(e)}encode(e){if(e==null)return{type:mi,data:""};if(_h(e))for(const r of this.providers){const n=r.encode(e);if(n!=null)return n}return{type:pi,data:JSON.stringify(e)}}decode(e){if(e==null||e.type===mi)return null;if(e.type===pi)return new wi(e.data);for(const r of this.providers){const n=r.decode(e);if(n!=null)return n}return new wi(e.data)}}const Ha=new qh,Xa=({encode:t,decode:e})=>Ha.register({encode:t,decode:e}),Ts=t=>Ha.decode(t);class wi extends Oe{constructor(e){super(e),D(this,"type","unknown")}}const nn="freighter.",zr=class Qa extends Oe{constructor(){super("EOF"),D(this,"type",Qa.TYPE)}};D(zr,"TYPE",nn+"eof"),D(zr,"matches",de(zr.TYPE));let Ue=zr;const Nr=class eo extends Oe{constructor(){super("StreamClosed"),D(this,"type",eo.TYPE)}};D(Nr,"TYPE",nn+"stream_closed"),D(Nr,"matches",de(Nr.TYPE));let rt=Nr;const Er=class to extends Oe{constructor(e={}){const{message:r="Unreachable",url:n=Ph.UNKNOWN}=e;super(r),D(this,"type",to.TYPE),D(this,"url"),this.url=n}};D(Er,"TYPE",nn+"unreachable"),D(Er,"matches",de(Er.TYPE));let Ke=Er;const Fh=t=>{if(!t.type.startsWith(Yh))return null;if(Ue.matches(t))return{type:Ue.TYPE,data:"EOF"};if(rt.matches(t))return{type:rt.TYPE,data:"StreamClosed"};if(Ke.matches(t))return{type:Ke.TYPE,data:"Unreachable"};throw new Error(`Unknown error type: ${t.type}: ${t.message}`)},Vh=t=>{if(!t.type.startsWith(nn))return null;switch(t.type){case Ue.TYPE:return new Ue;case rt.TYPE:return new rt;case Ke.TYPE:return new Ke;default:throw new Error(`Unknown error type: ${t.data}`)}};Xa({encode:Fh,decode:Vh});let ro=class{constructor(){D(this,"middleware",[])}use(...t){this.middleware.push(...t)}async executeMiddleware(t,e){let r=0;const n=async i=>{if(r===this.middleware.length)return await e(i);const a=this.middleware[r];return r++,await a(i,n)};return await n(t)}};const no="Content-Type",bi=t=>{if(Za.RUNTIME!=="node")return fetch;const e=require("node-fetch");if(t==="http")return e;const r=require("https"),n=new r.Agent({rejectUnauthorized:!1});return async(i,a)=>await e(i,{...a,agent:n})};class Wh extends ro{constructor(e,r,n=!1){return super(),D(this,"endpoint"),D(this,"encoder"),D(this,"fetch"),this.endpoint=e.replace({protocol:n?"https":"http"}),this.encoder=r,this.fetch=bi(this.endpoint.protocol),new Proxy(this,{get:(i,a,o)=>a==="endpoint"?this.endpoint:Reflect.get(i,a,o)})}get headers(){return{[no]:this.encoder.contentType}}async send(e,r,n,i){r=n==null?void 0:n.parse(r);let a=null;const o=this.endpoint.child(e),u={};u.method="POST",u.body=this.encoder.encode(r??{});const[,c]=await this.executeMiddleware({target:o.toString(),protocol:this.endpoint.protocol,params:{},role:"client"},async d=>{const f={...d,params:{}};u.headers={...this.headers,...d.params};let h;try{h=await bi(d.protocol)(d.target,u)}catch(P){let ie=P;return ie.message==="Load failed"&&(ie=new Ke({url:o})),[f,ie]}const E=await h.arrayBuffer();if(h!=null&&h.ok)return i!=null&&(a=this.encoder.decode(E,i)),[f,null];try{if(h.status!==400)return[f,new Error(h.statusText)];const P=this.encoder.decode(E,Xt),ie=Ts(P);return[f,ie]}catch(P){return[f,new Error(`[freighter] - failed to decode error: ${h.statusText}: ${P.message}`)]}});return[a,c]}}const v=async(t,e,r,n,i)=>{const[a,o]=await t.send(e,r,n,i);if(o!=null)throw o;return a},Gh=()=>Za.RUNTIME!=="node"?t=>new WebSocket(t):t=>new(require("ws")).WebSocket(t,{rejectUnauthorized:!1}),Zh=s.z.object({type:s.z.union([s.z.literal("data"),s.z.literal("close")]),payload:s.z.unknown().optional(),error:s.z.optional(Xt)});class Kh{constructor(e,r,n,i){D(this,"encoder"),D(this,"reqSchema"),D(this,"resSchema"),D(this,"ws"),D(this,"serverClosed"),D(this,"sendClosed"),D(this,"receiveDataQueue",[]),D(this,"receiveCallbacksQueue",[]),this.encoder=r,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 Ue;if(this.sendClosed)throw new rt;return this.ws.send(this.encoder.encode({type:"data",payload:e})),null}async receive(){if(this.serverClosed!=null)return[null,this.serverClosed];const e=await this.receiveMsg();if(e.type==="close"){if(e.error==null)throw new Error("Message error must be defined");return this.serverClosed=Ts(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((e,r)=>this.receiveCallbacksQueue.push({resolve:e,reject:r}))}addMessage(e){const r=this.receiveCallbacksQueue.shift();r!=null?r.resolve(e):this.receiveDataQueue.push(e)}listenForMessages(){this.ws.onmessage=e=>this.addMessage(this.encoder.decode(e.data,Zh)),this.ws.onclose=e=>this.addMessage({type:"close",error:{type:ed(e)?Ue.TYPE:rt.TYPE,data:""}})}}const Jh="freighterctx",Hh=1e3,Xh=1001,Qh=[Hh,Xh],ed=t=>Qh.includes(t.code),so=class io extends ro{constructor(e,r,n=!1){super(),D(this,"baseUrl"),D(this,"encoder"),this.baseUrl=e.replace({protocol:n?"wss":"ws"}),this.encoder=r}async stream(e,r,n){const i=Gh();let a;const[,o]=await this.executeMiddleware({target:e,protocol:"websocket",params:{},role:"client"},async u=>{const c=i(this.buildURL(e,u)),d={...u,params:{}};c.binaryType=io.MESSAGE_TYPE;const f=await this.wrapSocket(c,r,n);return f instanceof Error?[d,f]:(a=f,[d,null])});if(o!=null)throw o;return a}buildURL(e,r){const n=Dh({[no]:this.encoder.contentType,...r.params},Jh);return this.baseUrl.child(e).toString()+n}async wrapSocket(e,r,n){return await new Promise(i=>{e.onopen=()=>{i(new Kh(e,this.encoder,r,n))},e.onerror=a=>{const o=a;i(new Error(o.message))}})}};D(so,"MESSAGE_TYPE","arraybuffer");let td=so;const es=s.z.union([s.z.literal("all"),s.z.literal("create"),s.z.literal("delete"),s.z.literal("retrieve"),s.z.literal("update")]),rd=t=>{const e=t.replace(/_[a-z]/g,r=>r[1].toUpperCase());return e.length>1&&e[0]===e[0].toUpperCase()&&e[1]===e[1].toUpperCase()?e:e[0].toLowerCase()+e.slice(1)},ao=t=>{const e=(r,n=ts)=>{if(typeof r=="string")return t(r);if(Array.isArray(r))return r.map(o=>e(o,n));if(!En(r))return r;n=id(n);const i={},a=r;return Object.keys(a).forEach(o=>{let u=a[o];const c=t(o);n.recursive&&(En(u)?Oi(u,n.keepTypesOnRecursion)||(u=e(u,n)):n.recursiveInArray&&vi(u)&&(u=[...u].map(d=>{let f=d;return En(d)?Oi(f,n.keepTypesOnRecursion)||(f=e(d,n)):vi(d)&&(f=e({key:d},n).key),f}))),i[c]=u}),i};return e},oo=ao(rd),nd=t=>t.replace(/([a-z0-9])([A-Z])/g,(e,r,n)=>`${r}_${n.toLowerCase()}`),sd=ao(nd),ts={recursive:!0,recursiveInArray:!0,keepTypesOnRecursion:[Number,String,Uint8Array]},id=(t=ts)=>(t.recursive==null?t=ts:t.recursiveInArray==null&&(t.recursiveInArray=!1),t),vi=t=>t!=null&&Array.isArray(t),En=t=>t!=null&&typeof t=="object"&&!Array.isArray(t),Oi=(t,e)=>(e||[]).some(r=>t instanceof r),Ss=t=>t!=null&&typeof t=="object"&&!Array.isArray(t);var ad=Object.defineProperty,od=(t,e,r)=>e in t?ad(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Ut=(t,e,r)=>od(t,typeof e!="symbol"?e+"":e,r);let co=class{constructor(){Ut(this,"contentType","application/json"),Ut(this,"decoder"),Ut(this,"encoder"),this.decoder=new TextDecoder,this.encoder=new TextEncoder}encode(t){return this.encoder.encode(this.encodeString(t)).buffer}decode(t,e){return this.decodeString(this.decoder.decode(t),e)}decodeString(t,e){const r=JSON.parse(t),n=oo(r);return e!=null?e.parse(n):n}encodeString(t){const e=sd(t);return JSON.stringify(e,(r,n)=>ArrayBuffer.isView(n)?Array.from(n):Ss(n)&&"encode_value"in n?typeof n.value=="bigint"?n.value.toString():n.value:typeof n=="bigint"?n.toString():n)}static registerCustomType(){}},lo=class{constructor(){Ut(this,"contentType","text/csv")}encode(t){const e=this.encodeString(t);return new TextEncoder().encode(e).buffer}decode(t,e){const r=new TextDecoder().decode(t);return this.decodeString(r,e)}encodeString(t){if(!Array.isArray(t)||t.length===0||!Ss(t[0]))throw new Error("Payload must be an array of objects");const e=Object.keys(t[0]),r=[e.join(",")];return t.forEach(n=>{const i=e.map(a=>JSON.stringify(n[a]??""));r.push(i.join(","))}),r.join(`
|
|
27
|
+
`).slice(0,-1).map(r=>e.parse(vr.decodeString(r)))}get timeRange(){if(this._timeRange==null)throw new Error("time range not set on series");return this._timeRange}get byteCapacity(){return new Fa(this.buffer.byteLength)}get capacity(){return this.dataType.density.length(this.byteCapacity)}get byteLength(){return this.writePos===qe?this.byteCapacity:this.dataType.density.size(this.writePos)}get length(){return this._cachedLength!=null?this._cachedLength:this.dataType.isVariable?this.calculateCachedLength():this.writePos===qe?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(r=>{r===10&&e++}),this._cachedLength=e,e}convert(e,r=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]=vh(this.dataType,e,this.data[i],r);return new Ce({data:n.buffer,dataType:e,timeRange:this._timeRange,sampleOffset:r,glBufferUsage:this.gl.bufferUsage,alignment:this.alignment})}calcRawMax(){if(this.length===0)return-1/0;if(this.dataType.equals(q.TIMESTAMP))this._cachedMax=this.data[this.data.length-1];else if(this.dataType.usesBigInt){const e=this.data;this._cachedMax=e.reduce((r,n)=>r>n?r:n)}else{const e=this.data;this._cachedMax=e.reduce((r,n)=>r>n?r: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()),St(this._cachedMax,this.sampleOffset))}calcRawMin(){if(this.length===0)return 1/0;if(this.dataType.equals(q.TIMESTAMP))this._cachedMin=this.data[0];else if(this.dataType.usesBigInt){const e=this.data;this._cachedMin=e.reduce((r,n)=>r<n?r:n)}else{const e=this.data;this._cachedMin=e.reduce((r,n)=>r<n?r: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()),St(this._cachedMin,this.sampleOffset))}get bounds(){return Bt(Number(this.min),Number(this.max))}maybeRecomputeMinMax(e){if(this._cachedMin!=null){const r=e._cachedMin??e.calcRawMin();r<this._cachedMin&&(this._cachedMin=r)}if(this._cachedMax!=null){const r=e._cachedMax??e.calcRawMax();r>this._cachedMax&&(this._cachedMax=r)}}enrich(){this.max,this.min}get range(){return St(this.max,-this.min)}at(e,r){if(this.dataType.isVariable)return this.atVariable(e,r??!1);e<0&&(e=this.length+e);const n=this.data[e];if(n==null){if(r===!0)throw new Error(`[series] - no value at index ${e}`);return}return St(n,this.sampleOffset)}atVariable(e,r){e<0&&(e=this.length+e);let n=0,i=0;for(let o=0;o<this.data.length;o++)if(this.data[o]===10){if(e===0){i=o;break}n=o+1,e--}if(i===0&&(i=this.data.length),n>=i||e>0){if(r)throw new Error(`[series] - no value at index ${e}`);return}const a=this.data.slice(n,i);return this.dataType.equals(q.STRING)?new TextDecoder().decode(a):ja(JSON.parse(new TextDecoder().decode(a)))}binarySearch(e){let r=0,n=this.length-1;const i=uh(e);for(;r<=n;){const a=Math.floor((r+n)/2),o=i(this.at(a,!0),e);if(o===0)return a;o<0?r=a+1:n=a-1}return r}updateGLBuffer(e){if(this.gl.control=e,!this.dataType.equals(q.FLOAT32))throw new Error("Only FLOAT32 arrays can be used in WebGL");const{buffer:r,bufferUsage:n,prevBuffer:i}=this.gl;if(r==null&&(this.gl.buffer=e.createBuffer()),this.writePos!==i)if(e.bindBuffer(e.ARRAY_BUFFER,this.gl.buffer),this.writePos!==qe){i===0&&e.bufferData(e.ARRAY_BUFFER,this.byteCapacity.valueOf(),e.STATIC_DRAW);const a=this.dataType.density.size(i).valueOf(),o=this.underlyingData.slice(this.gl.prevBuffer,this.writePos);e.bufferSubData(e.ARRAY_BUFFER,a,o.buffer),this.gl.prevBuffer=this.writePos}else e.bufferData(e.ARRAY_BUFFER,this.buffer,n==="static"?e.STATIC_DRAW:e.DYNAMIC_DRAW),this.gl.prevBuffer=qe}as(e){if(e==="string"){if(!this.dataType.equals(q.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(q.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 Nh(this);return this.dataType.equals(q.JSON)?new Eh(e):e}return new Ih(this)}slice(e,r){if(e<=0&&(r==null||r>=this.length))return this;const n=this.data.slice(e,r);return new Ce({data:n,dataType:this.dataType,timeRange:this._timeRange,sampleOffset:this.sampleOffset,glBufferUsage:this.gl.bufferUsage,alignment:this.alignment+BigInt(e)})}reAlign(e){return new Ce({data:this.buffer,dataType:this.dataType,timeRange:Os.ZERO,sampleOffset:this.sampleOffset,glBufferUsage:"static",alignment:e})}};b(Tt,"crudeZ",s.z.object({timeRange:Os.z.optional(),dataType:q.z,alignment:fh.optional(),data:s.z.union([Th,Sh,s.z.instanceof(ArrayBuffer)]),glBufferUsage:bh.optional().default("static").optional()})),b(Tt,"z",Tt.crudeZ.transform(t=>new Tt(t)));let zh=Tt;class Nh{constructor(e){if(b(this,"series"),b(this,"index"),b(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,r=this.series.data;for(;this.index<r.length&&r[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 di,fi;class Eh{constructor(e){b(this,"wrapped"),b(this,di,"JSONSeriesIterator"),this.wrapped=e}next(){const e=this.wrapped.next();return e.done===!0?{done:!0,value:void 0}:{done:!1,value:vr.decodeString(e.value)}}[(fi=Symbol.iterator,di=Symbol.toStringTag,fi)](){return this}}var yi,gi;class Ih{constructor(e){b(this,"series"),b(this,"index"),b(this,yi,"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)}}[(gi=Symbol.iterator,yi=Symbol.toStringTag,gi)](){return this}}const St=(t,e)=>typeof t=="bigint"&&typeof e=="bigint"||typeof t=="number"&&typeof e=="number"?t+e:e===0?t:t===0?e:Number(t)+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 Wa=()=>typeof process<"u"&&process.versions!=null&&process.versions.node!=null?"node":typeof window>"u"||window.document===void 0?"webworker":"browser",Ah=Wa(),Ga=["MacOS","Windows","Linux","Docker"],kh=s.z.enum(Ga);let Nn;const xh=()=>{if(typeof window>"u")return;const t=window.navigator.userAgent.toLowerCase();if(t.includes("mac"))return"MacOS";if(t.includes("win"))return"Windows";if(t.includes("linux"))return"Linux"},Ch=(t={})=>{const{force:e,default:r}=t;return e??Nn??(Nn=xh(),Nn??r)},Za=Object.freeze(Object.defineProperty({__proto__:null,OPERATING_SYSTEMS:Ga,RUNTIME:Ah,detect:Wa,getOS:Ch,osZ:kh},Symbol.toStringTag,{value:"Module"}));var $h=Object.defineProperty,Rh=(t,e,r)=>e in t?$h(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,zt=(t,e,r)=>Rh(t,typeof e!="symbol"?e+"":e,r);const jh=(...t)=>t.map(Ka).join(""),Ka=t=>(t.endsWith("/")||(t+="/"),t.startsWith("/")&&(t=t.slice(1)),t),Mh=t=>t.endsWith("/")?t.slice(0,-1):t,Dh=(t,e="")=>t===null?"":"?"+Object.entries(t).filter(([,r])=>r==null?!1:Array.isArray(r)?r.length>0:!0).map(([r,n])=>`${e}${r}=${n}`).join("&"),Xn=class Qn{constructor({host:e,port:r,protocol:n="",pathPrefix:i=""}){zt(this,"protocol"),zt(this,"host"),zt(this,"port"),zt(this,"path"),this.protocol=n,this.host=e,this.port=r,this.path=Ka(i)}replace(e){return new Qn({host:e.host??this.host,port:e.port??this.port,protocol:e.protocol??this.protocol,pathPrefix:e.pathPrefix??this.path})}child(e){return new Qn({...this,pathPrefix:jh(this.path,e)})}toString(){return Mh(`${this.protocol}://${this.host}:${this.port}/${this.path}`)}};zt(Xn,"UNKNOWN",new Xn({host:"unknown",port:0}));let Ph=Xn;var Bh=Object.defineProperty,Uh=(t,e,r)=>e in t?Bh(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Sr=(t,e,r)=>Uh(t,typeof e!="symbol"?e+"":e,r);const Xe=class extends Number{};Sr(Xe,"Absolute",255),Sr(Xe,"Default",1),Sr(Xe,"z",s.z.union([s.z.instanceof(Xe),s.z.number().int().min(0).max(255).transform(t=>new Xe(t)),s.z.instanceof(Number).transform(t=>new Xe(t))]));s.z.object({name:s.z.string(),key:s.z.string()});const Ja=class Nt extends Error{constructor(){super(Nt.MESSAGE)}matches(e){return typeof e=="string"?e.includes(Nt.MESSAGE):e instanceof Nt||e.message.includes(Nt.MESSAGE)}};Sr(Ja,"MESSAGE","canceled");let Lh=Ja;new Lh;s.z.string().regex(/^\d+\.\d+\.\d+$/);const de=t=>e=>e!=null&&typeof e=="object"&&"type"in e&&typeof e.type=="string"?e.type.includes(t):e instanceof Error?e.message.includes(t):typeof e!="string"?!1:e.includes(t);let Oe=class extends Error{constructor(e){super(e),D(this,"discriminator","FreighterError"),D(this,"type","")}};const _h=t=>{if(t==null||typeof t!="object")return!1;const e=t;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},pi="unknown",mi="nil",Yh="freighter",Xt=s.z.object({type:s.z.string(),data:s.z.string()});class qh{constructor(){D(this,"providers",[])}register(e){this.providers.push(e)}encode(e){if(e==null)return{type:mi,data:""};if(_h(e))for(const r of this.providers){const n=r.encode(e);if(n!=null)return n}return{type:pi,data:JSON.stringify(e)}}decode(e){if(e==null||e.type===mi)return null;if(e.type===pi)return new wi(e.data);for(const r of this.providers){const n=r.decode(e);if(n!=null)return n}return new wi(e.data)}}const Ha=new qh,Xa=({encode:t,decode:e})=>Ha.register({encode:t,decode:e}),Ts=t=>Ha.decode(t);class wi extends Oe{constructor(e){super(e),D(this,"type","unknown")}}const nn="freighter.",zr=class Qa extends Oe{constructor(){super("EOF"),D(this,"type",Qa.TYPE)}};D(zr,"TYPE",nn+"eof"),D(zr,"matches",de(zr.TYPE));let Ue=zr;const Nr=class eo extends Oe{constructor(){super("StreamClosed"),D(this,"type",eo.TYPE)}};D(Nr,"TYPE",nn+"stream_closed"),D(Nr,"matches",de(Nr.TYPE));let rt=Nr;const Er=class to extends Oe{constructor(e={}){const{message:r="Unreachable",url:n=Ph.UNKNOWN}=e;super(r),D(this,"type",to.TYPE),D(this,"url"),this.url=n}};D(Er,"TYPE",nn+"unreachable"),D(Er,"matches",de(Er.TYPE));let Ke=Er;const Fh=t=>{if(!t.type.startsWith(Yh))return null;if(Ue.matches(t))return{type:Ue.TYPE,data:"EOF"};if(rt.matches(t))return{type:rt.TYPE,data:"StreamClosed"};if(Ke.matches(t))return{type:Ke.TYPE,data:"Unreachable"};throw new Error(`Unknown error type: ${t.type}: ${t.message}`)},Vh=t=>{if(!t.type.startsWith(nn))return null;switch(t.type){case Ue.TYPE:return new Ue;case rt.TYPE:return new rt;case Ke.TYPE:return new Ke;default:throw new Error(`Unknown error type: ${t.data}`)}};Xa({encode:Fh,decode:Vh});let ro=class{constructor(){D(this,"middleware",[])}use(...t){this.middleware.push(...t)}async executeMiddleware(t,e){let r=0;const n=async i=>{if(r===this.middleware.length)return await e(i);const a=this.middleware[r];return r++,await a(i,n)};return await n(t)}};const no="Content-Type",bi=t=>{if(Za.RUNTIME!=="node")return fetch;const e=require("node-fetch");if(t==="http")return e;const r=require("https"),n=new r.Agent({rejectUnauthorized:!1});return async(i,a)=>await e(i,{...a,agent:n})};class Wh extends ro{constructor(e,r,n=!1){return super(),D(this,"endpoint"),D(this,"encoder"),D(this,"fetch"),this.endpoint=e.replace({protocol:n?"https":"http"}),this.encoder=r,this.fetch=bi(this.endpoint.protocol),new Proxy(this,{get:(i,a,o)=>a==="endpoint"?this.endpoint:Reflect.get(i,a,o)})}get headers(){return{[no]:this.encoder.contentType}}async send(e,r,n,i){r=n==null?void 0:n.parse(r);let a=null;const o=this.endpoint.child(e),l={};l.method="POST",l.body=this.encoder.encode(r??{});const[,u]=await this.executeMiddleware({target:o.toString(),protocol:this.endpoint.protocol,params:{},role:"client"},async d=>{const f={...d,params:{}};l.headers={...this.headers,...d.params};let h;try{h=await bi(d.protocol)(d.target,l)}catch(P){let ie=P;return ie.message==="Load failed"&&(ie=new Ke({url:o})),[f,ie]}const E=await h.arrayBuffer();if(h!=null&&h.ok)return i!=null&&(a=this.encoder.decode(E,i)),[f,null];try{if(h.status!==400)return[f,new Error(h.statusText)];const P=this.encoder.decode(E,Xt),ie=Ts(P);return[f,ie]}catch(P){return[f,new Error(`[freighter] - failed to decode error: ${h.statusText}: ${P.message}`)]}});return[a,u]}}const v=async(t,e,r,n,i)=>{const[a,o]=await t.send(e,r,n,i);if(o!=null)throw o;return a},Gh=()=>Za.RUNTIME!=="node"?t=>new WebSocket(t):t=>new(require("ws")).WebSocket(t,{rejectUnauthorized:!1}),Zh=s.z.object({type:s.z.union([s.z.literal("data"),s.z.literal("close")]),payload:s.z.unknown().optional(),error:s.z.optional(Xt)});class Kh{constructor(e,r,n,i){D(this,"encoder"),D(this,"reqSchema"),D(this,"resSchema"),D(this,"ws"),D(this,"serverClosed"),D(this,"sendClosed"),D(this,"receiveDataQueue",[]),D(this,"receiveCallbacksQueue",[]),this.encoder=r,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 Ue;if(this.sendClosed)throw new rt;return this.ws.send(this.encoder.encode({type:"data",payload:e})),null}async receive(){if(this.serverClosed!=null)return[null,this.serverClosed];const e=await this.receiveMsg();if(e.type==="close"){if(e.error==null)throw new Error("Message error must be defined");return this.serverClosed=Ts(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((e,r)=>this.receiveCallbacksQueue.push({resolve:e,reject:r}))}addMessage(e){const r=this.receiveCallbacksQueue.shift();r!=null?r.resolve(e):this.receiveDataQueue.push(e)}listenForMessages(){this.ws.onmessage=e=>this.addMessage(this.encoder.decode(e.data,Zh)),this.ws.onclose=e=>this.addMessage({type:"close",error:{type:ed(e)?Ue.TYPE:rt.TYPE,data:""}})}}const Jh="freighterctx",Hh=1e3,Xh=1001,Qh=[Hh,Xh],ed=t=>Qh.includes(t.code),so=class io extends ro{constructor(e,r,n=!1){super(),D(this,"baseUrl"),D(this,"encoder"),this.baseUrl=e.replace({protocol:n?"wss":"ws"}),this.encoder=r}async stream(e,r,n){const i=Gh();let a;const[,o]=await this.executeMiddleware({target:e,protocol:"websocket",params:{},role:"client"},async l=>{const u=i(this.buildURL(e,l)),d={...l,params:{}};u.binaryType=io.MESSAGE_TYPE;const f=await this.wrapSocket(u,r,n);return f instanceof Error?[d,f]:(a=f,[d,null])});if(o!=null)throw o;return a}buildURL(e,r){const n=Dh({[no]:this.encoder.contentType,...r.params},Jh);return this.baseUrl.child(e).toString()+n}async wrapSocket(e,r,n){return await new Promise(i=>{e.onopen=()=>{i(new Kh(e,this.encoder,r,n))},e.onerror=a=>{const o=a;i(new Error(o.message))}})}};D(so,"MESSAGE_TYPE","arraybuffer");let td=so;const es=s.z.union([s.z.literal("all"),s.z.literal("create"),s.z.literal("delete"),s.z.literal("retrieve"),s.z.literal("update")]),rd=t=>{const e=t.replace(/_[a-z]/g,r=>r[1].toUpperCase());return e.length>1&&e[0]===e[0].toUpperCase()&&e[1]===e[1].toUpperCase()?e:e[0].toLowerCase()+e.slice(1)},ao=t=>{const e=(r,n=ts)=>{if(typeof r=="string")return t(r);if(Array.isArray(r))return r.map(o=>e(o,n));if(!En(r))return r;n=id(n);const i={},a=r;return Object.keys(a).forEach(o=>{let l=a[o];const u=t(o);n.recursive&&(En(l)?Oi(l,n.keepTypesOnRecursion)||(l=e(l,n)):n.recursiveInArray&&vi(l)&&(l=[...l].map(d=>{let f=d;return En(d)?Oi(f,n.keepTypesOnRecursion)||(f=e(d,n)):vi(d)&&(f=e({key:d},n).key),f}))),i[u]=l}),i};return e},oo=ao(rd),nd=t=>t.replace(/([a-z0-9])([A-Z])/g,(e,r,n)=>`${r}_${n.toLowerCase()}`),sd=ao(nd),ts={recursive:!0,recursiveInArray:!0,keepTypesOnRecursion:[Number,String,Uint8Array]},id=(t=ts)=>(t.recursive==null?t=ts:t.recursiveInArray==null&&(t.recursiveInArray=!1),t),vi=t=>t!=null&&Array.isArray(t),En=t=>t!=null&&typeof t=="object"&&!Array.isArray(t),Oi=(t,e)=>(e||[]).some(r=>t instanceof r),Ss=t=>t!=null&&typeof t=="object"&&!Array.isArray(t);var ad=Object.defineProperty,od=(t,e,r)=>e in t?ad(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Ut=(t,e,r)=>od(t,typeof e!="symbol"?e+"":e,r);let co=class{constructor(){Ut(this,"contentType","application/json"),Ut(this,"decoder"),Ut(this,"encoder"),this.decoder=new TextDecoder,this.encoder=new TextEncoder}encode(t){return this.encoder.encode(this.encodeString(t)).buffer}decode(t,e){return this.decodeString(this.decoder.decode(t),e)}decodeString(t,e){const r=JSON.parse(t),n=oo(r);return e!=null?e.parse(n):n}encodeString(t){const e=sd(t);return JSON.stringify(e,(r,n)=>ArrayBuffer.isView(n)?Array.from(n):Ss(n)&&"encode_value"in n?typeof n.value=="bigint"?n.value.toString():n.value:typeof n=="bigint"?n.toString():n)}static registerCustomType(){}},lo=class{constructor(){Ut(this,"contentType","text/csv")}encode(t){const e=this.encodeString(t);return new TextEncoder().encode(e).buffer}decode(t,e){const r=new TextDecoder().decode(t);return this.decodeString(r,e)}encodeString(t){if(!Array.isArray(t)||t.length===0||!Ss(t[0]))throw new Error("Payload must be an array of objects");const e=Object.keys(t[0]),r=[e.join(",")];return t.forEach(n=>{const i=e.map(a=>JSON.stringify(n[a]??""));r.push(i.join(","))}),r.join(`
|
|
28
28
|
`)}decodeString(t,e){const[r,...n]=t.trim().split(`
|
|
29
|
-
`).map(o=>o.trim());if(r.length===0)return e!=null?e.parse({}):{};const i=r.split(",").map(o=>o.trim()),a={};return i.forEach(o=>{a[o]=[]}),n.forEach(o=>{const u=o.split(",").map(c=>c.trim());i.forEach((c,d)=>{const f=this.parseValue(u[d]);f!=null&&a[c].push(f)})}),e!=null?e.parse(a):a}parseValue(t){if(t==null||t.length===0)return null;const e=Number(t);return isNaN(e)?t.startsWith('"')&&t.endsWith('"')?t.slice(1,-1):t:e}static registerCustomType(){}},uo=class{constructor(){Ut(this,"contentType","text/plain")}encode(t){return new TextEncoder().encode(t).buffer}decode(t,e){const r=new TextDecoder().decode(t);return e!=null?e.parse(r):r}};const et=new co,cd=new lo,ld=new uo,ud=[et],ot=Object.freeze(Object.defineProperty({__proto__:null,CSVCodec:lo,CSV_CODEC:cd,ENCODERS:ud,JSONCodec:co,JSON_CODEC:et,TEXT_CODEC:ld,TextCodec:uo},Symbol.toStringTag,{value:"Module"})),sn=s.z.tuple([s.z.number(),s.z.number()]);s.z.tuple([s.z.bigint(),s.z.bigint()]);const ho=s.z.object({width:s.z.number(),height:s.z.number()}),hd=s.z.object({signedWidth:s.z.number(),signedHeight:s.z.number()}),dd=["width","height"];s.z.enum(dd);const fd=["start","center","end"],yd=["signedWidth","signedHeight"];s.z.enum(yd);const Zr=s.z.object({x:s.z.number(),y:s.z.number()}),gd=s.z.object({clientX:s.z.number(),clientY:s.z.number()}),pd=["x","y"],fo=s.z.enum(pd),yo=["top","right","bottom","left"];s.z.enum(yo);const md=["left","right"],go=s.z.enum(md),wd=["top","bottom"],po=s.z.enum(wd),mo=["center"],Ti=s.z.enum(mo),bd=[...yo,...mo],wo=s.z.enum(bd);s.z.enum(fd);const vd=["first","last"];s.z.enum(vd);const Od=s.z.object({lower:s.z.number(),upper:s.z.number()}),Td=s.z.object({lower:s.z.bigint(),upper:s.z.bigint()});s.z.union([Od,sn]);s.z.union([Td,sn]);s.z.union([fo,wo]);s.z.union([fo,wo,s.z.instanceof(String)]);const Lt=(t,e)=>{const r={};if(typeof t=="number"||typeof t=="bigint")e!=null?(r.lower=t,r.upper=e):(r.lower=typeof t=="bigint"?0n:0,r.upper=t);else if(Array.isArray(t)){if(t.length!==2)throw new Error("bounds: expected array of length 2");[r.lower,r.upper]=t}else return Si(t);return Si(r)},Si=t=>t.lower>t.upper?{lower:t.upper,upper:t.lower}:t;s.z.object({x:go.or(Ti),y:po.or(Ti)});const Sd=s.z.object({x:go,y:po}),zd=Object.freeze({x:"left",y:"top"}),Nd=(t,e)=>t.x===e.x&&t.y===e.y,zi=s.z.union([s.z.number(),Zr,sn,ho,hd,gd]),Ed=(t,e)=>{if(typeof t=="string"){if(e===void 0)throw new Error("The y coordinate must be given.");return t==="x"?{x:e,y:0}:{x:0,y:e}}return typeof t=="number"?{x:t,y:e??t}:Array.isArray(t)?{x:t[0],y:t[1]}:"signedWidth"in t?{x:t.signedWidth,y:t.signedHeight}:"clientX"in t?{x:t.clientX,y:t.clientY}:"width"in t?{x:t.width,y:t.height}:{x:t.x,y:t.y}},Ni=Object.freeze({x:0,y:0}),lr=s.z.union([s.z.number(),s.z.string()]);s.z.object({top:lr,left:lr,width:lr,height:lr});s.z.object({left:s.z.number(),top:s.z.number(),right:s.z.number(),bottom:s.z.number()});s.z.object({one:Zr,two:Zr,root:Sd});const zs=(t,e,r=0,n=0,i)=>{const a={one:{...Ni},two:{...Ni},root:i??zd};if(typeof t=="number"){if(typeof e!="number")throw new Error("Box constructor called with invalid arguments");return a.one={x:t,y:e},a.two={x:a.one.x+r,y:a.one.y+n},a}return"one"in t&&"two"in t&&"root"in t?{...t,root:i??t.root}:("getBoundingClientRect"in t&&(t=t.getBoundingClientRect()),"left"in t?(a.one={x:t.left,y:t.top},a.two={x:t.right,y:t.bottom},a):(a.one=t,e==null?a.two={x:a.one.x+r,y:a.one.y+n}:typeof e=="number"?a.two={x:a.one.x+e,y:a.one.y+r}:"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))},In=t=>{const e=zs(t);return{lower:e.one.x,upper:e.two.x}},An=t=>{const e=zs(t);return{lower:e.one.y,upper:e.two.y}},Id=t=>typeof t!="object"||t==null?!1:"one"in t&&"two"in t&&"root"in t;var Ad=Object.defineProperty,kd=(t,e,r)=>e in t?Ad(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Me=(t,e,r)=>kd(t,typeof e!="symbol"?e+"":e,r);const xd=(t,e,r)=>e!==void 0&&t<e?e:r!==void 0&&t>r?r:t;s.z.object({offset:zi,scale:zi});const Cd=t=>(e,r,n,i)=>r==="dimension"?[e,n]:[e,i?n-t:n+t],$d=t=>(e,r,n,i)=>[e,i?n/t:n*t],Rd=t=>(e,r,n)=>{if(e===null)return[t,n];const{lower:i,upper:a}=e,{lower:o,upper:u}=t,c=a-i,d=u-o;if(r==="dimension")return[t,n*(d/c)];const f=(n-i)*(d/c)+o;return[t,f]},jd=t=>(e,r,n)=>[t,n],Md=()=>(t,e,r)=>{if(t===null)throw new Error("cannot invert without bounds");if(e==="dimension")return[t,r];const{lower:n,upper:i}=t;return[t,i-(r-n)]},Dd=t=>(e,r,n)=>{const{lower:i,upper:a}=t;return n=xd(n,i,a),[e,n]},rs=class Et{constructor(){Me(this,"ops",[]),Me(this,"currBounds",null),Me(this,"currType",null),Me(this,"reversed",!1),this.ops=[]}static translate(e){return new Et().translate(e)}static magnify(e){return new Et().magnify(e)}static scale(e,r){return new Et().scale(e,r)}translate(e){const r=this.new(),n=Cd(e);return n.type="translate",r.ops.push(n),r}magnify(e){const r=this.new(),n=$d(e);return n.type="magnify",r.ops.push(n),r}scale(e,r){const n=Lt(e,r),i=this.new(),a=Rd(n);return a.type="scale",i.ops.push(a),i}clamp(e,r){const n=Lt(e,r),i=this.new(),a=Dd(n);return a.type="clamp",i.ops.push(a),i}reBound(e,r){const n=Lt(e,r),i=this.new(),a=jd(n);return a.type="re-bound",i.ops.push(a),i}invert(){const e=Md();e.type="invert";const r=this.new();return r.ops.push(e),r}pos(e){return this.exec("position",e)}dim(e){return this.exec("dimension",e)}new(){const e=new Et;return e.ops=this.ops.slice(),e.reversed=this.reversed,e}exec(e,r){return this.currBounds=null,this.ops.reduce(([n,i],a)=>a(n,e,i,this.reversed),[null,r])[1]}reverse(){const e=this.new();e.ops.reverse();const r=[];return e.ops.forEach((n,i)=>{if(n.type==="scale"||r.some(([o,u])=>i>=o&&i<=u))return;const a=e.ops.findIndex((o,u)=>o.type==="scale"&&u>i);a!==-1&&r.push([i,a])}),r.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}};Me(rs,"IDENTITY",new rs);let Ei=rs;const Ii=class $e{constructor(e=new Ei,r=new Ei,n=null){Me(this,"x"),Me(this,"y"),Me(this,"currRoot"),this.x=e,this.y=r,this.currRoot=n}static translate(e,r){return new $e().translate(e,r)}static translateX(e){return new $e().translateX(e)}static translateY(e){return new $e().translateY(e)}static clamp(e){return new $e().clamp(e)}static magnify(e){return new $e().magnify(e)}static scale(e){return new $e().scale(e)}static reBound(e){return new $e().reBound(e)}translate(e,r){const n=Ed(e,r),i=this.copy();return i.x=this.x.translate(n.x),i.y=this.y.translate(n.y),i}translateX(e){const r=this.copy();return r.x=this.x.translate(e),r}translateY(e){const r=this.copy();return r.y=this.y.translate(e),r}magnify(e){const r=this.copy();return r.x=this.x.magnify(e.x),r.y=this.y.magnify(e.y),r}scale(e){const r=this.copy();if(Id(e)){const n=this.currRoot;return r.currRoot=e.root,n!=null&&!Nd(n,e.root)&&(n.x!==e.root.x&&(r.x=r.x.invert()),n.y!==e.root.y&&(r.y=r.y.invert())),r.x=r.x.scale(In(e)),r.y=r.y.scale(An(e)),r}return r.x=r.x.scale(e.width),r.y=r.y.scale(e.height),r}reBound(e){const r=this.copy();return r.x=this.x.reBound(In(e)),r.y=this.y.reBound(An(e)),r}clamp(e){const r=this.copy();return r.x=this.x.clamp(In(e)),r.y=this.y.clamp(An(e)),r}copy(){const e=new $e;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 zs(this.pos(e.one),this.pos(e.two),0,0,this.currRoot??e.root)}};Me(Ii,"IDENTITY",new Ii);const Ai=t=>[...new Set(t)],Pd=t=>t!=null&&typeof t=="object"&&"toString"in t,Bd=(t,e=!1)=>{const r=Pd(t)?"stringer":typeof t;let n;switch(r){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 ${r}`),()=>-1}return e?Ud(n):n},Ud=t=>(e,r)=>t(r,e),an=0,kn=-1,xn=1,Ld=t=>t<an,_d=t=>t>an,Yd=t=>t===an,qd=(t,e)=>{let r=null;return e===0?t:(...n)=>{r!==null&&(clearTimeout(r),r=null),r=setTimeout(()=>t(...n),e)}},Fd=s.z.object({signedWidth:s.z.number(),signedHeight:s.z.number()});s.z.union([ho,Fd,Zr,sn]);const Vd=s.z.bigint().or(s.z.string().transform(BigInt));var Wd=Object.defineProperty,Gd=(t,e,r)=>e in t?Wd(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,w=(t,e,r)=>Gd(t,typeof e!="symbol"?e+"":e,r);let Zd=(t,e=21)=>(r=e)=>{let n="",i=r;for(;i--;)n+=t[Math.random()*t.length|0];return n};const Kd="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",bo=Zd(Kd,11),Jd=Object.freeze(Object.defineProperty({__proto__:null,id:bo},Symbol.toStringTag,{value:"Module"})),Hd=s.z.enum(["static","dynamic"]),vo=(t,e)=>{const r=new x(e);if(![A.DAY,A.HOUR,A.MINUTE,A.SECOND,A.MILLISECOND,A.MICROSECOND,A.NANOSECOND].some(i=>i.equals(r)))throw new Error("Invalid argument for remainder. Must be an even TimeSpan or Timestamp");const n=t.valueOf()%r.valueOf();return t instanceof x?new x(n):new A(n)},F=class N{constructor(e,r="UTC"){if(w(this,"value"),w(this,"encodeValue",!0),e==null)this.value=N.now().valueOf();else if(e instanceof Date)this.value=BigInt(e.getTime())*N.MILLISECOND.valueOf();else if(typeof e=="string")this.value=N.parseDateTimeString(e,r).valueOf();else if(Array.isArray(e))this.value=N.parseDate(e);else{let n=BigInt(0);e instanceof Number&&(e=e.valueOf()),r==="local"&&(n=N.utcOffset.valueOf()),typeof e=="number"&&(isFinite(e)?e=Math.trunc(e):(isNaN(e)&&(e=0),e===1/0?e=N.MAX:e=N.MIN)),this.value=BigInt(e.valueOf())+n}}static parseDate([e=1970,r=1,n=1]){const i=new Date(e,r-1,n,0,0,0,0);return new N(BigInt(i.getTime())*N.MILLISECOND.valueOf()).truncate(N.DAY).valueOf()}encode(){return this.value.toString()}valueOf(){return this.value}static parseTimeString(e,r="UTC"){const[n,i,a]=e.split(":");let o="00",u="00";a!=null&&([o,u]=a.split("."));let c=N.hours(parseInt(n??"00",10)).add(N.minutes(parseInt(i??"00",10))).add(N.seconds(parseInt(o??"00",10))).add(N.milliseconds(parseInt(u??"00",10)));return r==="local"&&(c=c.add(N.utcOffset)),c.valueOf()}static parseDateTimeString(e,r="UTC"){if(!e.includes("/")&&!e.includes("-"))return N.parseTimeString(e,r);const n=new Date(e);return e.includes(":")||n.setUTCHours(0,0,0,0),new N(BigInt(n.getTime())*N.MILLISECOND.valueOf(),r).valueOf()}fString(e="ISO",r="UTC"){switch(e){case"ISODate":return this.toISOString(r).slice(0,10);case"ISOTime":return this.toISOString(r).slice(11,23);case"time":return this.timeString(!1,r);case"preciseTime":return this.timeString(!0,r);case"date":return this.dateString();case"preciseDate":return`${this.dateString()} ${this.timeString(!0,r)}`;case"dateTime":return`${this.dateString()} ${this.timeString(!1,r)}`;default:return this.toISOString(r)}}toISOString(e="UTC"){return e==="UTC"?this.date().toISOString():this.sub(N.utcOffset).date().toISOString()}timeString(e=!1,r="UTC"){const n=this.toISOString(r);return e?n.slice(11,23):n.slice(11,19)}dateString(){const e=this.date(),r=e.toLocaleString("default",{month:"short"}),n=e.toLocaleString("default",{day:"numeric"});return`${r} ${n}`}static get utcOffset(){return new A(BigInt(new Date().getTimezoneOffset())*N.MINUTE.valueOf())}static since(e){return new N().span(e)}date(){return new Date(this.milliseconds())}equals(e){return this.valueOf()===new N(e).valueOf()}span(e){return this.range(e).span}range(e){return new se(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 N(e).valueOf()}afterEq(e){return this.valueOf()>=new N(e).valueOf()}before(e){return this.valueOf()<new N(e).valueOf()}beforeEq(e){return this.valueOf()<=new N(e).valueOf()}add(e){return new N(this.valueOf()+BigInt(e.valueOf()))}sub(e){return new N(this.valueOf()-BigInt(e.valueOf()))}milliseconds(){return Number(this.valueOf())/Number(N.MILLISECOND.valueOf())}toString(){return this.date().toISOString()}remainder(e){return vo(this,e)}get isToday(){return this.truncate(A.DAY).equals(N.now().truncate(A.DAY))}truncate(e){return this.sub(this.remainder(e))}static now(){return new N(new Date)}static max(...e){let r=N.MIN;for(const n of e){const i=new N(n);i.after(r)&&(r=i)}return r}static min(...e){let r=N.MAX;for(const n of e){const i=new N(n);i.before(r)&&(r=i)}return r}static nanoseconds(e){return new N(e)}static microseconds(e){return N.nanoseconds(e*1e3)}static milliseconds(e){return N.microseconds(e*1e3)}static seconds(e){return N.milliseconds(e*1e3)}static minutes(e){return N.seconds(e*60)}static hours(e){return N.minutes(e*60)}static days(e){return N.hours(e*24)}};w(F,"NANOSECOND",F.nanoseconds(1)),w(F,"MICROSECOND",F.microseconds(1)),w(F,"MILLISECOND",F.milliseconds(1)),w(F,"SECOND",F.seconds(1)),w(F,"MINUTE",F.minutes(1)),w(F,"HOUR",F.hours(1)),w(F,"DAY",F.days(1)),w(F,"MAX",new F((1n<<63n)-1n)),w(F,"MIN",new F(0)),w(F,"ZERO",new F(0)),w(F,"z",s.z.union([s.z.object({value:s.z.bigint()}).transform(t=>new F(t.value)),s.z.string().transform(t=>new F(BigInt(t))),s.z.instanceof(Number).transform(t=>new F(t)),s.z.number().transform(t=>new F(t)),s.z.instanceof(F)]));let x=F;const V=class R{constructor(e){w(this,"value"),w(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 R(e).valueOf()}greaterThan(e){return this.valueOf()>new R(e).valueOf()}lessThanOrEqual(e){return this.valueOf()<=new R(e).valueOf()}greaterThanOrEqual(e){return this.valueOf()>=new R(e).valueOf()}remainder(e){return vo(this,e)}truncate(e){return new R(BigInt(Math.trunc(Number(this.valueOf()/e.valueOf())))*e.valueOf())}toString(){const e=this.truncate(R.DAY),r=this.truncate(R.HOUR),n=this.truncate(R.MINUTE),i=this.truncate(R.SECOND),a=this.truncate(R.MILLISECOND),o=this.truncate(R.MICROSECOND),u=this.truncate(R.NANOSECOND),c=e,d=r.sub(e),f=n.sub(r),h=i.sub(n),E=a.sub(i),P=o.sub(a),ie=u.sub(o);let M="";return c.isZero||(M+=`${c.days}d `),d.isZero||(M+=`${d.hours}h `),f.isZero||(M+=`${f.minutes}m `),h.isZero||(M+=`${h.seconds}s `),E.isZero||(M+=`${E.milliseconds}ms `),P.isZero||(M+=`${P.microseconds}µs `),ie.isZero||(M+=`${ie.nanoseconds}ns`),M.trim()}get days(){return Number(this.valueOf())/Number(R.DAY.valueOf())}get hours(){return Number(this.valueOf())/Number(R.HOUR.valueOf())}get minutes(){return Number(this.valueOf())/Number(R.MINUTE.valueOf())}get seconds(){return Number(this.valueOf())/Number(R.SECOND.valueOf())}get milliseconds(){return Number(this.valueOf())/Number(R.MILLISECOND.valueOf())}get microseconds(){return Number(this.valueOf())/Number(R.MICROSECOND.valueOf())}get nanoseconds(){return Number(this.valueOf())}get isZero(){return this.valueOf()===BigInt(0)}equals(e){return this.valueOf()===new R(e).valueOf()}add(e){return new R(this.valueOf()+new R(e).valueOf())}sub(e){return new R(this.valueOf()-new R(e).valueOf())}static nanoseconds(e=1){return new R(e)}static microseconds(e=1){return R.nanoseconds(e*1e3)}static milliseconds(e=1){return R.microseconds(e*1e3)}static seconds(e=1){return R.milliseconds(e*1e3)}static minutes(e){return R.seconds(e.valueOf()*60)}static hours(e){return R.minutes(e*60)}static days(e){return R.hours(e*24)}};w(V,"NANOSECOND",V.nanoseconds(1)),w(V,"MICROSECOND",V.microseconds(1)),w(V,"MILLISECOND",V.milliseconds(1)),w(V,"SECOND",V.seconds(1)),w(V,"MINUTE",V.minutes(1)),w(V,"HOUR",V.hours(1)),w(V,"DAY",V.days(1)),w(V,"MAX",new V((1n<<63n)-1n)),w(V,"MIN",new V(0)),w(V,"ZERO",new V(0)),w(V,"z",s.z.union([s.z.object({value:s.z.bigint()}).transform(t=>new V(t.value)),s.z.string().transform(t=>new V(BigInt(t))),s.z.instanceof(Number).transform(t=>new V(t)),s.z.number().transform(t=>new V(t)),s.z.instanceof(V)]));let A=V;const It=class Ir extends Number{constructor(e){e instanceof Number?super(e.valueOf()):super(e)}toString(){return`${this.valueOf()} Hz`}equals(e){return this.valueOf()===new Ir(e).valueOf()}get period(){return A.seconds(1/this.valueOf())}sampleCount(e){return new A(e).seconds*this.valueOf()}byteCount(e,r){return this.sampleCount(e)*new he(r).valueOf()}span(e){return A.seconds(e/this.valueOf())}byteSpan(e,r){return this.span(e.valueOf()/r.valueOf())}static hz(e){return new Ir(e)}static khz(e){return Ir.hz(e*1e3)}};w(It,"z",s.z.union([s.z.number().transform(t=>new It(t)),s.z.instanceof(Number).transform(t=>new It(t)),s.z.instanceof(It)]));let Ns=It;const ne=class extends Number{constructor(e){e instanceof Number?super(e.valueOf()):super(e)}length(e){return e.valueOf()/this.valueOf()}size(e){return new qt(e*this.valueOf())}};w(ne,"UNKNOWN",new ne(0)),w(ne,"BIT128",new ne(16)),w(ne,"BIT64",new ne(8)),w(ne,"BIT32",new ne(4)),w(ne,"BIT16",new ne(2)),w(ne,"BIT8",new ne(1)),w(ne,"z",s.z.union([s.z.number().transform(t=>new ne(t)),s.z.instanceof(Number).transform(t=>new ne(t)),s.z.instanceof(ne)]));let he=ne;const Ee=class Ar{constructor(e,r){w(this,"start"),w(this,"end"),typeof e=="object"&&"start"in e?(this.start=new x(e.start),this.end=new x(e.end)):(this.start=new x(e),this.end=new x(r))}get span(){return new A(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 Ar(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,r=A.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=x.max(n.start,e.start),a=x.min(n.end,e.end);return a.before(i)?!1:new A(a.sub(i)).greaterThanOrEqual(r)}roughlyEquals(e,r){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<=r.valueOf()&&i<=r.valueOf()}contains(e){return e instanceof Ar?this.contains(e.start)&&this.contains(e.end):this.start.beforeEq(e)&&this.end.after(e)}boundBy(e){const r=new Ar(this.start,this.end);return e.start.after(this.start)&&(r.start=e.start),e.start.after(this.end)&&(r.end=e.start),e.end.before(this.end)&&(r.end=e.end),e.end.before(this.start)&&(r.start=e.end),r}};w(Ee,"MAX",new Ee(x.MIN,x.MAX)),w(Ee,"MIN",new Ee(x.MAX,x.MIN)),w(Ee,"ZERO",new Ee(x.ZERO,x.ZERO)),w(Ee,"z",s.z.union([s.z.object({start:x.z,end:x.z}).transform(t=>new Ee(t.start,t.end)),s.z.instanceof(Ee)]));let se=Ee;const p=class Ie extends String{constructor(e){if(e instanceof Ie||typeof e=="string"||typeof e.valueOf()=="string"){super(e.valueOf());return}else{const r=Ie.ARRAY_CONSTRUCTOR_DATA_TYPES.get(e.constructor.name);if(r!=null){super(r.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(r=>this.equals(r))}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))}};w(p,"UNKNOWN",new p("unknown")),w(p,"FLOAT64",new p("float64")),w(p,"FLOAT32",new p("float32")),w(p,"INT64",new p("int64")),w(p,"INT32",new p("int32")),w(p,"INT16",new p("int16")),w(p,"INT8",new p("int8")),w(p,"UINT64",new p("uint64")),w(p,"UINT32",new p("uint32")),w(p,"UINT16",new p("uint16")),w(p,"UINT8",new p("uint8")),w(p,"BOOLEAN",p.UINT8),w(p,"TIMESTAMP",new p("timestamp")),w(p,"UUID",new p("uuid")),w(p,"STRING",new p("string")),w(p,"JSON",new p("json")),w(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]])),w(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]])),w(p,"DENSITIES",new Map([[p.UINT8.toString(),he.BIT8],[p.UINT16.toString(),he.BIT16],[p.UINT32.toString(),he.BIT32],[p.UINT64.toString(),he.BIT64],[p.FLOAT32.toString(),he.BIT32],[p.FLOAT64.toString(),he.BIT64],[p.INT8.toString(),he.BIT8],[p.INT16.toString(),he.BIT16],[p.INT32.toString(),he.BIT32],[p.INT64.toString(),he.BIT64],[p.TIMESTAMP.toString(),he.BIT64],[p.STRING.toString(),he.UNKNOWN],[p.JSON.toString(),he.UNKNOWN],[p.UUID.toString(),he.BIT128]])),w(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]),w(p,"BIG_INT_TYPES",[p.INT64,p.UINT64,p.TIMESTAMP]),w(p,"z",s.z.union([s.z.string().transform(t=>new p(t)),s.z.instanceof(p)]));let I=p;const ce=class X extends Number{constructor(e){super(e.valueOf())}largerThan(e){return this.valueOf()>e.valueOf()}smallerThan(e){return this.valueOf()<e.valueOf()}add(e){return X.bytes(this.valueOf()+e.valueOf())}sub(e){return X.bytes(this.valueOf()-e.valueOf())}truncate(e){return new X(Math.trunc(this.valueOf()/e.valueOf())*e.valueOf())}remainder(e){return X.bytes(this.valueOf()%e.valueOf())}get gigabytes(){return this.valueOf()/X.GIGABYTE.valueOf()}get megabytes(){return this.valueOf()/X.MEGABYTE.valueOf()}get kilobytes(){return this.valueOf()/X.KILOBYTE.valueOf()}get terabytes(){return this.valueOf()/X.TERABYTE.valueOf()}toString(){const e=this.truncate(X.TERABYTE),r=this.truncate(X.GIGABYTE),n=this.truncate(X.MEGABYTE),i=this.truncate(X.KILOBYTE),a=this.truncate(X.BYTE),o=e,u=r.sub(e),c=n.sub(r),d=i.sub(n),f=a.sub(i);let h="";return o.isZero||(h+=`${o.terabytes}TB `),u.isZero||(h+=`${u.gigabytes}GB `),c.isZero||(h+=`${c.megabytes}MB `),d.isZero||(h+=`${d.kilobytes}KB `),(!f.isZero||h==="")&&(h+=`${f.valueOf()}B`),h.trim()}static bytes(e=1){return new X(e)}static kilobytes(e=1){return X.bytes(e.valueOf()*1e3)}static megabytes(e=1){return X.kilobytes(e.valueOf()*1e3)}static gigabytes(e=1){return X.megabytes(e.valueOf()*1e3)}static terabytes(e){return X.gigabytes(e.valueOf()*1e3)}get isZero(){return this.valueOf()===0}};w(ce,"BYTE",new ce(1)),w(ce,"KILOBYTE",ce.kilobytes(1)),w(ce,"MEGABYTE",ce.megabytes(1)),w(ce,"GIGABYTE",ce.gigabytes(1)),w(ce,"TERABYTE",ce.terabytes(1)),w(ce,"ZERO",new ce(0)),w(ce,"z",s.z.union([s.z.number().transform(t=>new ce(t)),s.z.instanceof(ce)]));let qt=ce;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 Oo=t=>{const e=typeof t;return e==="string"||e==="number"||e==="boolean"||e==="bigint"||t instanceof x||t instanceof A||t instanceof Date},Xd=(t,e,r,n=0)=>t.usesBigInt&&!e.usesBigInt?Number(r)-Number(n):!t.usesBigInt&&e.usesBigInt?BigInt(r)-BigInt(n):kt(r,-n),Qd=t=>t==null?!1:Array.isArray(t)||t instanceof ArrayBuffer||ArrayBuffer.isView(t)&&!(t instanceof DataView)||t instanceof Ge?!0:Oo(t),Fe=-1,ef=s.z.string().transform(t=>new Uint8Array(atob(t).split("").map(e=>e.charCodeAt(0))).buffer),tf=s.z.union([s.z.null(),s.z.undefined()]).transform(()=>new Uint8Array().buffer),At=class Re{constructor(e){w(this,"key",""),w(this,"isSynnaxSeries",!0),w(this,"dataType"),w(this,"sampleOffset"),w(this,"gl"),w(this,"_data"),w(this,"_timeRange"),w(this,"alignment",0n),w(this,"_cachedMin"),w(this,"_cachedMax"),w(this,"writePos",Fe),w(this,"_refCount",0),w(this,"_cachedLength"),Qd(e)&&(e={data:e});const{dataType:r,timeRange:n,sampleOffset:i=0,glBufferUsage:a="static",alignment:o=0n,key:u=bo()}=e,c=e.data??[];if(c instanceof Re||typeof c=="object"&&"isSynnaxSeries"in c&&c.isSynnaxSeries===!0){const h=c;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 d=Oo(c),f=Array.isArray(c);if(r!=null)this.dataType=new I(r);else{if(c instanceof ArrayBuffer)throw new Error("cannot infer data type from an ArrayBuffer instance when constructing a Series. Please provide a data type.");if(f||d){let h=c;if(!d){if(c.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=c[0]}if(typeof h=="string")this.dataType=I.STRING;else if(typeof h=="number")this.dataType=I.FLOAT64;else if(typeof h=="bigint")this.dataType=I.INT64;else if(typeof h=="boolean")this.dataType=I.BOOLEAN;else if(h instanceof x||h instanceof Date||h instanceof x)this.dataType=I.TIMESTAMP;else if(typeof h=="object")this.dataType=I.JSON;else throw new Error(`cannot infer data type of ${typeof h} when constructing a Series from a JS array`)}else this.dataType=new I(c)}if(!f&&!d)this._data=c;else{let h=d?[c]:c;const E=h[0];(E instanceof x||E instanceof Date||E instanceof A)&&(h=h.map(P=>new x(P).valueOf())),this.dataType.equals(I.STRING)?(this._cachedLength=h.length,this._data=new TextEncoder().encode(h.join(`
|
|
29
|
+
`).map(o=>o.trim());if(r.length===0)return e!=null?e.parse({}):{};const i=r.split(",").map(o=>o.trim()),a={};return i.forEach(o=>{a[o]=[]}),n.forEach(o=>{const l=o.split(",").map(u=>u.trim());i.forEach((u,d)=>{const f=this.parseValue(l[d]);f!=null&&a[u].push(f)})}),e!=null?e.parse(a):a}parseValue(t){if(t==null||t.length===0)return null;const e=Number(t);return isNaN(e)?t.startsWith('"')&&t.endsWith('"')?t.slice(1,-1):t:e}static registerCustomType(){}},uo=class{constructor(){Ut(this,"contentType","text/plain")}encode(t){return new TextEncoder().encode(t).buffer}decode(t,e){const r=new TextDecoder().decode(t);return e!=null?e.parse(r):r}};const et=new co,cd=new lo,ld=new uo,ud=[et],ot=Object.freeze(Object.defineProperty({__proto__:null,CSVCodec:lo,CSV_CODEC:cd,ENCODERS:ud,JSONCodec:co,JSON_CODEC:et,TEXT_CODEC:ld,TextCodec:uo},Symbol.toStringTag,{value:"Module"})),sn=s.z.tuple([s.z.number(),s.z.number()]);s.z.tuple([s.z.bigint(),s.z.bigint()]);const ho=s.z.object({width:s.z.number(),height:s.z.number()}),hd=s.z.object({signedWidth:s.z.number(),signedHeight:s.z.number()}),dd=["width","height"];s.z.enum(dd);const fd=["start","center","end"],yd=["signedWidth","signedHeight"];s.z.enum(yd);const Zr=s.z.object({x:s.z.number(),y:s.z.number()}),gd=s.z.object({clientX:s.z.number(),clientY:s.z.number()}),pd=["x","y"],fo=s.z.enum(pd),yo=["top","right","bottom","left"];s.z.enum(yo);const md=["left","right"],go=s.z.enum(md),wd=["top","bottom"],po=s.z.enum(wd),mo=["center"],Ti=s.z.enum(mo),bd=[...yo,...mo],wo=s.z.enum(bd);s.z.enum(fd);const vd=["first","last"];s.z.enum(vd);const Od=s.z.object({lower:s.z.number(),upper:s.z.number()}),Td=s.z.object({lower:s.z.bigint(),upper:s.z.bigint()});s.z.union([Od,sn]);s.z.union([Td,sn]);s.z.union([fo,wo]);s.z.union([fo,wo,s.z.instanceof(String)]);const Lt=(t,e)=>{const r={};if(typeof t=="number"||typeof t=="bigint")e!=null?(r.lower=t,r.upper=e):(r.lower=typeof t=="bigint"?0n:0,r.upper=t);else if(Array.isArray(t)){if(t.length!==2)throw new Error("bounds: expected array of length 2");[r.lower,r.upper]=t}else return Si(t);return Si(r)},Si=t=>t.lower>t.upper?{lower:t.upper,upper:t.lower}:t;s.z.object({x:go.or(Ti),y:po.or(Ti)});const Sd=s.z.object({x:go,y:po}),zd=Object.freeze({x:"left",y:"top"}),Nd=(t,e)=>t.x===e.x&&t.y===e.y,zi=s.z.union([s.z.number(),Zr,sn,ho,hd,gd]),Ed=(t,e)=>{if(typeof t=="string"){if(e===void 0)throw new Error("The y coordinate must be given.");return t==="x"?{x:e,y:0}:{x:0,y:e}}return typeof t=="number"?{x:t,y:e??t}:Array.isArray(t)?{x:t[0],y:t[1]}:"signedWidth"in t?{x:t.signedWidth,y:t.signedHeight}:"clientX"in t?{x:t.clientX,y:t.clientY}:"width"in t?{x:t.width,y:t.height}:{x:t.x,y:t.y}},Ni=Object.freeze({x:0,y:0}),lr=s.z.union([s.z.number(),s.z.string()]);s.z.object({top:lr,left:lr,width:lr,height:lr});s.z.object({left:s.z.number(),top:s.z.number(),right:s.z.number(),bottom:s.z.number()});s.z.object({one:Zr,two:Zr,root:Sd});const zs=(t,e,r=0,n=0,i)=>{const a={one:{...Ni},two:{...Ni},root:i??zd};if(typeof t=="number"){if(typeof e!="number")throw new Error("Box constructor called with invalid arguments");return a.one={x:t,y:e},a.two={x:a.one.x+r,y:a.one.y+n},a}return"one"in t&&"two"in t&&"root"in t?{...t,root:i??t.root}:("getBoundingClientRect"in t&&(t=t.getBoundingClientRect()),"left"in t?(a.one={x:t.left,y:t.top},a.two={x:t.right,y:t.bottom},a):(a.one=t,e==null?a.two={x:a.one.x+r,y:a.one.y+n}:typeof e=="number"?a.two={x:a.one.x+e,y:a.one.y+r}:"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))},In=t=>{const e=zs(t);return{lower:e.one.x,upper:e.two.x}},An=t=>{const e=zs(t);return{lower:e.one.y,upper:e.two.y}},Id=t=>typeof t!="object"||t==null?!1:"one"in t&&"two"in t&&"root"in t;var Ad=Object.defineProperty,kd=(t,e,r)=>e in t?Ad(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Me=(t,e,r)=>kd(t,typeof e!="symbol"?e+"":e,r);const xd=(t,e,r)=>e!==void 0&&t<e?e:r!==void 0&&t>r?r:t;s.z.object({offset:zi,scale:zi});const Cd=t=>(e,r,n,i)=>r==="dimension"?[e,n]:[e,i?n-t:n+t],$d=t=>(e,r,n,i)=>[e,i?n/t:n*t],Rd=t=>(e,r,n)=>{if(e===null)return[t,n];const{lower:i,upper:a}=e,{lower:o,upper:l}=t,u=a-i,d=l-o;if(r==="dimension")return[t,n*(d/u)];const f=(n-i)*(d/u)+o;return[t,f]},jd=t=>(e,r,n)=>[t,n],Md=()=>(t,e,r)=>{if(t===null)throw new Error("cannot invert without bounds");if(e==="dimension")return[t,r];const{lower:n,upper:i}=t;return[t,i-(r-n)]},Dd=t=>(e,r,n)=>{const{lower:i,upper:a}=t;return n=xd(n,i,a),[e,n]},rs=class Et{constructor(){Me(this,"ops",[]),Me(this,"currBounds",null),Me(this,"currType",null),Me(this,"reversed",!1),this.ops=[]}static translate(e){return new Et().translate(e)}static magnify(e){return new Et().magnify(e)}static scale(e,r){return new Et().scale(e,r)}translate(e){const r=this.new(),n=Cd(e);return n.type="translate",r.ops.push(n),r}magnify(e){const r=this.new(),n=$d(e);return n.type="magnify",r.ops.push(n),r}scale(e,r){const n=Lt(e,r),i=this.new(),a=Rd(n);return a.type="scale",i.ops.push(a),i}clamp(e,r){const n=Lt(e,r),i=this.new(),a=Dd(n);return a.type="clamp",i.ops.push(a),i}reBound(e,r){const n=Lt(e,r),i=this.new(),a=jd(n);return a.type="re-bound",i.ops.push(a),i}invert(){const e=Md();e.type="invert";const r=this.new();return r.ops.push(e),r}pos(e){return this.exec("position",e)}dim(e){return this.exec("dimension",e)}new(){const e=new Et;return e.ops=this.ops.slice(),e.reversed=this.reversed,e}exec(e,r){return this.currBounds=null,this.ops.reduce(([n,i],a)=>a(n,e,i,this.reversed),[null,r])[1]}reverse(){const e=this.new();e.ops.reverse();const r=[];return e.ops.forEach((n,i)=>{if(n.type==="scale"||r.some(([o,l])=>i>=o&&i<=l))return;const a=e.ops.findIndex((o,l)=>o.type==="scale"&&l>i);a!==-1&&r.push([i,a])}),r.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}};Me(rs,"IDENTITY",new rs);let Ei=rs;const Ii=class $e{constructor(e=new Ei,r=new Ei,n=null){Me(this,"x"),Me(this,"y"),Me(this,"currRoot"),this.x=e,this.y=r,this.currRoot=n}static translate(e,r){return new $e().translate(e,r)}static translateX(e){return new $e().translateX(e)}static translateY(e){return new $e().translateY(e)}static clamp(e){return new $e().clamp(e)}static magnify(e){return new $e().magnify(e)}static scale(e){return new $e().scale(e)}static reBound(e){return new $e().reBound(e)}translate(e,r){const n=Ed(e,r),i=this.copy();return i.x=this.x.translate(n.x),i.y=this.y.translate(n.y),i}translateX(e){const r=this.copy();return r.x=this.x.translate(e),r}translateY(e){const r=this.copy();return r.y=this.y.translate(e),r}magnify(e){const r=this.copy();return r.x=this.x.magnify(e.x),r.y=this.y.magnify(e.y),r}scale(e){const r=this.copy();if(Id(e)){const n=this.currRoot;return r.currRoot=e.root,n!=null&&!Nd(n,e.root)&&(n.x!==e.root.x&&(r.x=r.x.invert()),n.y!==e.root.y&&(r.y=r.y.invert())),r.x=r.x.scale(In(e)),r.y=r.y.scale(An(e)),r}return r.x=r.x.scale(e.width),r.y=r.y.scale(e.height),r}reBound(e){const r=this.copy();return r.x=this.x.reBound(In(e)),r.y=this.y.reBound(An(e)),r}clamp(e){const r=this.copy();return r.x=this.x.clamp(In(e)),r.y=this.y.clamp(An(e)),r}copy(){const e=new $e;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 zs(this.pos(e.one),this.pos(e.two),0,0,this.currRoot??e.root)}};Me(Ii,"IDENTITY",new Ii);const Ai=t=>[...new Set(t)],Pd=t=>t!=null&&typeof t=="object"&&"toString"in t,Bd=(t,e=!1)=>{const r=Pd(t)?"stringer":typeof t;let n;switch(r){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 ${r}`),()=>-1}return e?Ud(n):n},Ud=t=>(e,r)=>t(r,e),an=0,kn=-1,xn=1,Ld=t=>t<an,_d=t=>t>an,Yd=t=>t===an,qd=(t,e)=>{let r=null;return e===0?t:(...n)=>{r!==null&&(clearTimeout(r),r=null),r=setTimeout(()=>t(...n),e)}},Fd=s.z.object({signedWidth:s.z.number(),signedHeight:s.z.number()});s.z.union([ho,Fd,Zr,sn]);const Vd=s.z.bigint().or(s.z.string().transform(BigInt));var Wd=Object.defineProperty,Gd=(t,e,r)=>e in t?Wd(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,w=(t,e,r)=>Gd(t,typeof e!="symbol"?e+"":e,r);let Zd=(t,e=21)=>(r=e)=>{let n="",i=r;for(;i--;)n+=t[Math.random()*t.length|0];return n};const Kd="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",bo=Zd(Kd,11),Jd=Object.freeze(Object.defineProperty({__proto__:null,id:bo},Symbol.toStringTag,{value:"Module"})),Hd=s.z.enum(["static","dynamic"]),vo=(t,e)=>{const r=new x(e);if(![A.DAY,A.HOUR,A.MINUTE,A.SECOND,A.MILLISECOND,A.MICROSECOND,A.NANOSECOND].some(i=>i.equals(r)))throw new Error("Invalid argument for remainder. Must be an even TimeSpan or Timestamp");const n=t.valueOf()%r.valueOf();return t instanceof x?new x(n):new A(n)},F=class N{constructor(e,r="UTC"){if(w(this,"value"),w(this,"encodeValue",!0),e==null)this.value=N.now().valueOf();else if(e instanceof Date)this.value=BigInt(e.getTime())*N.MILLISECOND.valueOf();else if(typeof e=="string")this.value=N.parseDateTimeString(e,r).valueOf();else if(Array.isArray(e))this.value=N.parseDate(e);else{let n=BigInt(0);e instanceof Number&&(e=e.valueOf()),r==="local"&&(n=N.utcOffset.valueOf()),typeof e=="number"&&(isFinite(e)?e=Math.trunc(e):(isNaN(e)&&(e=0),e===1/0?e=N.MAX:e=N.MIN)),this.value=BigInt(e.valueOf())+n}}static parseDate([e=1970,r=1,n=1]){const i=new Date(e,r-1,n,0,0,0,0);return new N(BigInt(i.getTime())*N.MILLISECOND.valueOf()).truncate(N.DAY).valueOf()}encode(){return this.value.toString()}valueOf(){return this.value}static parseTimeString(e,r="UTC"){const[n,i,a]=e.split(":");let o="00",l="00";a!=null&&([o,l]=a.split("."));let u=N.hours(parseInt(n??"00",10)).add(N.minutes(parseInt(i??"00",10))).add(N.seconds(parseInt(o??"00",10))).add(N.milliseconds(parseInt(l??"00",10)));return r==="local"&&(u=u.add(N.utcOffset)),u.valueOf()}static parseDateTimeString(e,r="UTC"){if(!e.includes("/")&&!e.includes("-"))return N.parseTimeString(e,r);const n=new Date(e);return e.includes(":")||n.setUTCHours(0,0,0,0),new N(BigInt(n.getTime())*N.MILLISECOND.valueOf(),r).valueOf()}fString(e="ISO",r="UTC"){switch(e){case"ISODate":return this.toISOString(r).slice(0,10);case"ISOTime":return this.toISOString(r).slice(11,23);case"time":return this.timeString(!1,r);case"preciseTime":return this.timeString(!0,r);case"date":return this.dateString();case"preciseDate":return`${this.dateString()} ${this.timeString(!0,r)}`;case"dateTime":return`${this.dateString()} ${this.timeString(!1,r)}`;default:return this.toISOString(r)}}toISOString(e="UTC"){return e==="UTC"?this.date().toISOString():this.sub(N.utcOffset).date().toISOString()}timeString(e=!1,r="UTC"){const n=this.toISOString(r);return e?n.slice(11,23):n.slice(11,19)}dateString(){const e=this.date(),r=e.toLocaleString("default",{month:"short"}),n=e.toLocaleString("default",{day:"numeric"});return`${r} ${n}`}static get utcOffset(){return new A(BigInt(new Date().getTimezoneOffset())*N.MINUTE.valueOf())}static since(e){return new N().span(e)}date(){return new Date(this.milliseconds())}equals(e){return this.valueOf()===new N(e).valueOf()}span(e){return this.range(e).span}range(e){return new se(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 N(e).valueOf()}afterEq(e){return this.valueOf()>=new N(e).valueOf()}before(e){return this.valueOf()<new N(e).valueOf()}beforeEq(e){return this.valueOf()<=new N(e).valueOf()}add(e){return new N(this.valueOf()+BigInt(e.valueOf()))}sub(e){return new N(this.valueOf()-BigInt(e.valueOf()))}milliseconds(){return Number(this.valueOf())/Number(N.MILLISECOND.valueOf())}toString(){return this.date().toISOString()}remainder(e){return vo(this,e)}get isToday(){return this.truncate(A.DAY).equals(N.now().truncate(A.DAY))}truncate(e){return this.sub(this.remainder(e))}static now(){return new N(new Date)}static max(...e){let r=N.MIN;for(const n of e){const i=new N(n);i.after(r)&&(r=i)}return r}static min(...e){let r=N.MAX;for(const n of e){const i=new N(n);i.before(r)&&(r=i)}return r}static nanoseconds(e){return new N(e)}static microseconds(e){return N.nanoseconds(e*1e3)}static milliseconds(e){return N.microseconds(e*1e3)}static seconds(e){return N.milliseconds(e*1e3)}static minutes(e){return N.seconds(e*60)}static hours(e){return N.minutes(e*60)}static days(e){return N.hours(e*24)}};w(F,"NANOSECOND",F.nanoseconds(1)),w(F,"MICROSECOND",F.microseconds(1)),w(F,"MILLISECOND",F.milliseconds(1)),w(F,"SECOND",F.seconds(1)),w(F,"MINUTE",F.minutes(1)),w(F,"HOUR",F.hours(1)),w(F,"DAY",F.days(1)),w(F,"MAX",new F((1n<<63n)-1n)),w(F,"MIN",new F(0)),w(F,"ZERO",new F(0)),w(F,"z",s.z.union([s.z.object({value:s.z.bigint()}).transform(t=>new F(t.value)),s.z.string().transform(t=>new F(BigInt(t))),s.z.instanceof(Number).transform(t=>new F(t)),s.z.number().transform(t=>new F(t)),s.z.instanceof(F)]));let x=F;const V=class R{constructor(e){w(this,"value"),w(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 R(e).valueOf()}greaterThan(e){return this.valueOf()>new R(e).valueOf()}lessThanOrEqual(e){return this.valueOf()<=new R(e).valueOf()}greaterThanOrEqual(e){return this.valueOf()>=new R(e).valueOf()}remainder(e){return vo(this,e)}truncate(e){return new R(BigInt(Math.trunc(Number(this.valueOf()/e.valueOf())))*e.valueOf())}toString(){const e=this.truncate(R.DAY),r=this.truncate(R.HOUR),n=this.truncate(R.MINUTE),i=this.truncate(R.SECOND),a=this.truncate(R.MILLISECOND),o=this.truncate(R.MICROSECOND),l=this.truncate(R.NANOSECOND),u=e,d=r.sub(e),f=n.sub(r),h=i.sub(n),E=a.sub(i),P=o.sub(a),ie=l.sub(o);let M="";return u.isZero||(M+=`${u.days}d `),d.isZero||(M+=`${d.hours}h `),f.isZero||(M+=`${f.minutes}m `),h.isZero||(M+=`${h.seconds}s `),E.isZero||(M+=`${E.milliseconds}ms `),P.isZero||(M+=`${P.microseconds}µs `),ie.isZero||(M+=`${ie.nanoseconds}ns`),M.trim()}get days(){return Number(this.valueOf())/Number(R.DAY.valueOf())}get hours(){return Number(this.valueOf())/Number(R.HOUR.valueOf())}get minutes(){return Number(this.valueOf())/Number(R.MINUTE.valueOf())}get seconds(){return Number(this.valueOf())/Number(R.SECOND.valueOf())}get milliseconds(){return Number(this.valueOf())/Number(R.MILLISECOND.valueOf())}get microseconds(){return Number(this.valueOf())/Number(R.MICROSECOND.valueOf())}get nanoseconds(){return Number(this.valueOf())}get isZero(){return this.valueOf()===BigInt(0)}equals(e){return this.valueOf()===new R(e).valueOf()}add(e){return new R(this.valueOf()+new R(e).valueOf())}sub(e){return new R(this.valueOf()-new R(e).valueOf())}static nanoseconds(e=1){return new R(e)}static microseconds(e=1){return R.nanoseconds(e*1e3)}static milliseconds(e=1){return R.microseconds(e*1e3)}static seconds(e=1){return R.milliseconds(e*1e3)}static minutes(e){return R.seconds(e.valueOf()*60)}static hours(e){return R.minutes(e*60)}static days(e){return R.hours(e*24)}};w(V,"NANOSECOND",V.nanoseconds(1)),w(V,"MICROSECOND",V.microseconds(1)),w(V,"MILLISECOND",V.milliseconds(1)),w(V,"SECOND",V.seconds(1)),w(V,"MINUTE",V.minutes(1)),w(V,"HOUR",V.hours(1)),w(V,"DAY",V.days(1)),w(V,"MAX",new V((1n<<63n)-1n)),w(V,"MIN",new V(0)),w(V,"ZERO",new V(0)),w(V,"z",s.z.union([s.z.object({value:s.z.bigint()}).transform(t=>new V(t.value)),s.z.string().transform(t=>new V(BigInt(t))),s.z.instanceof(Number).transform(t=>new V(t)),s.z.number().transform(t=>new V(t)),s.z.instanceof(V)]));let A=V;const It=class Ir extends Number{constructor(e){e instanceof Number?super(e.valueOf()):super(e)}toString(){return`${this.valueOf()} Hz`}equals(e){return this.valueOf()===new Ir(e).valueOf()}get period(){return A.seconds(1/this.valueOf())}sampleCount(e){return new A(e).seconds*this.valueOf()}byteCount(e,r){return this.sampleCount(e)*new he(r).valueOf()}span(e){return A.seconds(e/this.valueOf())}byteSpan(e,r){return this.span(e.valueOf()/r.valueOf())}static hz(e){return new Ir(e)}static khz(e){return Ir.hz(e*1e3)}};w(It,"z",s.z.union([s.z.number().transform(t=>new It(t)),s.z.instanceof(Number).transform(t=>new It(t)),s.z.instanceof(It)]));let Ns=It;const ne=class extends Number{constructor(e){e instanceof Number?super(e.valueOf()):super(e)}length(e){return e.valueOf()/this.valueOf()}size(e){return new qt(e*this.valueOf())}};w(ne,"UNKNOWN",new ne(0)),w(ne,"BIT128",new ne(16)),w(ne,"BIT64",new ne(8)),w(ne,"BIT32",new ne(4)),w(ne,"BIT16",new ne(2)),w(ne,"BIT8",new ne(1)),w(ne,"z",s.z.union([s.z.number().transform(t=>new ne(t)),s.z.instanceof(Number).transform(t=>new ne(t)),s.z.instanceof(ne)]));let he=ne;const Ee=class Ar{constructor(e,r){w(this,"start"),w(this,"end"),typeof e=="object"&&"start"in e?(this.start=new x(e.start),this.end=new x(e.end)):(this.start=new x(e),this.end=new x(r))}get span(){return new A(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 Ar(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,r=A.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=x.max(n.start,e.start),a=x.min(n.end,e.end);return a.before(i)?!1:new A(a.sub(i)).greaterThanOrEqual(r)}roughlyEquals(e,r){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<=r.valueOf()&&i<=r.valueOf()}contains(e){return e instanceof Ar?this.contains(e.start)&&this.contains(e.end):this.start.beforeEq(e)&&this.end.after(e)}boundBy(e){const r=new Ar(this.start,this.end);return e.start.after(this.start)&&(r.start=e.start),e.start.after(this.end)&&(r.end=e.start),e.end.before(this.end)&&(r.end=e.end),e.end.before(this.start)&&(r.start=e.end),r}};w(Ee,"MAX",new Ee(x.MIN,x.MAX)),w(Ee,"MIN",new Ee(x.MAX,x.MIN)),w(Ee,"ZERO",new Ee(x.ZERO,x.ZERO)),w(Ee,"z",s.z.union([s.z.object({start:x.z,end:x.z}).transform(t=>new Ee(t.start,t.end)),s.z.instanceof(Ee)]));let se=Ee;const p=class Ie extends String{constructor(e){if(e instanceof Ie||typeof e=="string"||typeof e.valueOf()=="string"){super(e.valueOf());return}else{const r=Ie.ARRAY_CONSTRUCTOR_DATA_TYPES.get(e.constructor.name);if(r!=null){super(r.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(r=>this.equals(r))}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))}};w(p,"UNKNOWN",new p("unknown")),w(p,"FLOAT64",new p("float64")),w(p,"FLOAT32",new p("float32")),w(p,"INT64",new p("int64")),w(p,"INT32",new p("int32")),w(p,"INT16",new p("int16")),w(p,"INT8",new p("int8")),w(p,"UINT64",new p("uint64")),w(p,"UINT32",new p("uint32")),w(p,"UINT16",new p("uint16")),w(p,"UINT8",new p("uint8")),w(p,"BOOLEAN",p.UINT8),w(p,"TIMESTAMP",new p("timestamp")),w(p,"UUID",new p("uuid")),w(p,"STRING",new p("string")),w(p,"JSON",new p("json")),w(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]])),w(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]])),w(p,"DENSITIES",new Map([[p.UINT8.toString(),he.BIT8],[p.UINT16.toString(),he.BIT16],[p.UINT32.toString(),he.BIT32],[p.UINT64.toString(),he.BIT64],[p.FLOAT32.toString(),he.BIT32],[p.FLOAT64.toString(),he.BIT64],[p.INT8.toString(),he.BIT8],[p.INT16.toString(),he.BIT16],[p.INT32.toString(),he.BIT32],[p.INT64.toString(),he.BIT64],[p.TIMESTAMP.toString(),he.BIT64],[p.STRING.toString(),he.UNKNOWN],[p.JSON.toString(),he.UNKNOWN],[p.UUID.toString(),he.BIT128]])),w(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]),w(p,"BIG_INT_TYPES",[p.INT64,p.UINT64,p.TIMESTAMP]),w(p,"z",s.z.union([s.z.string().transform(t=>new p(t)),s.z.instanceof(p)]));let I=p;const ce=class X extends Number{constructor(e){super(e.valueOf())}largerThan(e){return this.valueOf()>e.valueOf()}smallerThan(e){return this.valueOf()<e.valueOf()}add(e){return X.bytes(this.valueOf()+e.valueOf())}sub(e){return X.bytes(this.valueOf()-e.valueOf())}truncate(e){return new X(Math.trunc(this.valueOf()/e.valueOf())*e.valueOf())}remainder(e){return X.bytes(this.valueOf()%e.valueOf())}get gigabytes(){return this.valueOf()/X.GIGABYTE.valueOf()}get megabytes(){return this.valueOf()/X.MEGABYTE.valueOf()}get kilobytes(){return this.valueOf()/X.KILOBYTE.valueOf()}get terabytes(){return this.valueOf()/X.TERABYTE.valueOf()}toString(){const e=this.truncate(X.TERABYTE),r=this.truncate(X.GIGABYTE),n=this.truncate(X.MEGABYTE),i=this.truncate(X.KILOBYTE),a=this.truncate(X.BYTE),o=e,l=r.sub(e),u=n.sub(r),d=i.sub(n),f=a.sub(i);let h="";return o.isZero||(h+=`${o.terabytes}TB `),l.isZero||(h+=`${l.gigabytes}GB `),u.isZero||(h+=`${u.megabytes}MB `),d.isZero||(h+=`${d.kilobytes}KB `),(!f.isZero||h==="")&&(h+=`${f.valueOf()}B`),h.trim()}static bytes(e=1){return new X(e)}static kilobytes(e=1){return X.bytes(e.valueOf()*1e3)}static megabytes(e=1){return X.kilobytes(e.valueOf()*1e3)}static gigabytes(e=1){return X.megabytes(e.valueOf()*1e3)}static terabytes(e){return X.gigabytes(e.valueOf()*1e3)}get isZero(){return this.valueOf()===0}};w(ce,"BYTE",new ce(1)),w(ce,"KILOBYTE",ce.kilobytes(1)),w(ce,"MEGABYTE",ce.megabytes(1)),w(ce,"GIGABYTE",ce.gigabytes(1)),w(ce,"TERABYTE",ce.terabytes(1)),w(ce,"ZERO",new ce(0)),w(ce,"z",s.z.union([s.z.number().transform(t=>new ce(t)),s.z.instanceof(ce)]));let qt=ce;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 Oo=t=>{const e=typeof t;return e==="string"||e==="number"||e==="boolean"||e==="bigint"||t instanceof x||t instanceof A||t instanceof Date},Xd=(t,e,r,n=0)=>t.usesBigInt&&!e.usesBigInt?Number(r)-Number(n):!t.usesBigInt&&e.usesBigInt?BigInt(r)-BigInt(n):kt(r,-n),Qd=t=>t==null?!1:Array.isArray(t)||t instanceof ArrayBuffer||ArrayBuffer.isView(t)&&!(t instanceof DataView)||t instanceof Ge?!0:Oo(t),Fe=-1,ef=s.z.string().transform(t=>new Uint8Array(atob(t).split("").map(e=>e.charCodeAt(0))).buffer),tf=s.z.union([s.z.null(),s.z.undefined()]).transform(()=>new Uint8Array().buffer),At=class Re{constructor(e){w(this,"key",""),w(this,"isSynnaxSeries",!0),w(this,"dataType"),w(this,"sampleOffset"),w(this,"gl"),w(this,"_data"),w(this,"_timeRange"),w(this,"alignment",0n),w(this,"_cachedMin"),w(this,"_cachedMax"),w(this,"writePos",Fe),w(this,"_refCount",0),w(this,"_cachedLength"),Qd(e)&&(e={data:e});const{dataType:r,timeRange:n,sampleOffset:i=0,glBufferUsage:a="static",alignment:o=0n,key:l=bo()}=e,u=e.data??[];if(u instanceof Re||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 d=Oo(u),f=Array.isArray(u);if(r!=null)this.dataType=new I(r);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(f||d){let h=u;if(!d){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=I.STRING;else if(typeof h=="number")this.dataType=I.FLOAT64;else if(typeof h=="bigint")this.dataType=I.INT64;else if(typeof h=="boolean")this.dataType=I.BOOLEAN;else if(h instanceof x||h instanceof Date||h instanceof x)this.dataType=I.TIMESTAMP;else if(typeof h=="object")this.dataType=I.JSON;else throw new Error(`cannot infer data type of ${typeof h} when constructing a Series from a JS array`)}else this.dataType=new I(u)}if(!f&&!d)this._data=u;else{let h=d?[u]:u;const E=h[0];(E instanceof x||E instanceof Date||E instanceof A)&&(h=h.map(P=>new x(P).valueOf())),this.dataType.equals(I.STRING)?(this._cachedLength=h.length,this._data=new TextEncoder().encode(h.join(`
|
|
30
30
|
`)+`
|
|
31
31
|
`)):this.dataType.equals(I.JSON)?(this._cachedLength=h.length,this._data=new TextEncoder().encode(h.map(P=>et.encodeString(P)).join(`
|
|
32
32
|
`)+`
|
|
33
|
-
`)):this._data=new this.dataType.Array(h).buffer}this.key=
|
|
33
|
+
`)):this._data=new this.dataType.Array(h).buffer}this.key=l,this.alignment=o,this.sampleOffset=i??0,this._timeRange=n,this.gl={control:null,buffer:null,prevBuffer:0,bufferUsage:a}}static alloc({capacity:e,dataType:r,...n}){if(e===0)throw new Error("[Series] - cannot allocate an array of length 0");const i=new new I(r).Array(e),a=new Re({data:i.buffer,dataType:r,...n});return a.writePos=0,a}static generateTimestamps(e,r,n){const i=n.spanRange(r.span(e)),a=new BigInt64Array(e);for(let o=0;o<e;o++)a[o]=BigInt(n.add(r.span(o)).valueOf());return new Re({data:a,dataType:I.TIMESTAMP,timeRange:i})}get refCount(){return this._refCount}static fromStrings(e,r){const n=new TextEncoder().encode(e.join(`
|
|
34
34
|
`)+`
|
|
35
35
|
`);return new Re({data:n,dataType:I.STRING,timeRange:r})}static fromJSON(e,r){const n=new TextEncoder().encode(e.map(i=>et.encodeString(i)).join(`
|
|
36
36
|
`)+`
|
|
37
37
|
`);return new Re({data:n,dataType:I.JSON,timeRange:r})}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===Fe)return 0;const r=this.capacity-this.writePos,n=r<e.length?e.slice(0,r):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===Fe?this.underlyingData:new this.dataType.Array(this._data,0,this.writePos)}toStrings(){if(!this.dataType.matches(I.STRING,I.UUID))throw new Error("cannot convert non-string series to strings");return new TextDecoder().decode(this.buffer).split(`
|
|
38
38
|
`).slice(0,-1)}toUUIDs(){if(!this.dataType.equals(I.UUID))throw new Error("cannot convert non-uuid series to uuids");const e=I.UUID.density.valueOf(),r=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),o=>o.toString(16).padStart(2,"0")).join("").replace(/(.{8})(.{4})(.{4})(.{4})(.{12})/,"$1-$2-$3-$4-$5");r[n]=a}return r}parseJSON(e){if(!this.dataType.equals(I.JSON))throw new Error("cannot convert non-string series to strings");return new TextDecoder().decode(this.buffer).split(`
|
|
39
|
-
`).slice(0,-1).map(r=>e.parse(et.decodeString(r)))}get timeRange(){if(this._timeRange==null)throw new Error("time range not set on series");return this._timeRange}get byteCapacity(){return new qt(this.buffer.byteLength)}get capacity(){return this.dataType.density.length(this.byteCapacity)}get byteLength(){return this.writePos===Fe?this.byteCapacity:this.dataType.density.size(this.writePos)}get length(){return this._cachedLength!=null?this._cachedLength:this.dataType.isVariable?this.calculateCachedLength():this.writePos===Fe?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(r=>{r===10&&e++}),this._cachedLength=e,e}convert(e,r=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]=Xd(this.dataType,e,this.data[i],r);return new Re({data:n.buffer,dataType:e,timeRange:this._timeRange,sampleOffset:r,glBufferUsage:this.gl.bufferUsage,alignment:this.alignment})}calcRawMax(){if(this.length===0)return-1/0;if(this.dataType.equals(I.TIMESTAMP))this._cachedMax=this.data[this.data.length-1];else if(this.dataType.usesBigInt){const e=this.data;this._cachedMax=e.reduce((r,n)=>r>n?r:n)}else{const e=this.data;this._cachedMax=e.reduce((r,n)=>r>n?r: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()),kt(this._cachedMax,this.sampleOffset))}calcRawMin(){if(this.length===0)return 1/0;if(this.dataType.equals(I.TIMESTAMP))this._cachedMin=this.data[0];else if(this.dataType.usesBigInt){const e=this.data;this._cachedMin=e.reduce((r,n)=>r<n?r:n)}else{const e=this.data;this._cachedMin=e.reduce((r,n)=>r<n?r: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()),kt(this._cachedMin,this.sampleOffset))}get bounds(){return Lt(Number(this.min),Number(this.max))}maybeRecomputeMinMax(e){if(this._cachedMin!=null){const r=e._cachedMin??e.calcRawMin();r<this._cachedMin&&(this._cachedMin=r)}if(this._cachedMax!=null){const r=e._cachedMax??e.calcRawMax();r>this._cachedMax&&(this._cachedMax=r)}}enrich(){this.max,this.min}get range(){return kt(this.max,-this.min)}at(e,r){if(this.dataType.isVariable)return this.atVariable(e,r??!1);e<0&&(e=this.length+e);const n=this.data[e];if(n==null){if(r===!0)throw new Error(`[series] - no value at index ${e}`);return}return kt(n,this.sampleOffset)}atVariable(e,r){e<0&&(e=this.length+e);let n=0,i=0;for(let o=0;o<this.data.length;o++)if(this.data[o]===10){if(e===0){i=o;break}n=o+1,e--}if(i===0&&(i=this.data.length),n>=i||e>0){if(r)throw new Error(`[series] - no value at index ${e}`);return}const a=this.data.slice(n,i);return this.dataType.equals(I.STRING)?new TextDecoder().decode(a):oo(JSON.parse(new TextDecoder().decode(a)))}binarySearch(e){let r=0,n=this.length-1;const i=Bd(e);for(;r<=n;){const a=Math.floor((r+n)/2),o=i(this.at(a,!0),e);if(o===0)return a;o<0?r=a+1:n=a-1}return r}updateGLBuffer(e){if(this.gl.control=e,!this.dataType.equals(I.FLOAT32))throw new Error("Only FLOAT32 arrays can be used in WebGL");const{buffer:r,bufferUsage:n,prevBuffer:i}=this.gl;if(r==null&&(this.gl.buffer=e.createBuffer()),this.writePos!==i)if(e.bindBuffer(e.ARRAY_BUFFER,this.gl.buffer),this.writePos!==Fe){i===0&&e.bufferData(e.ARRAY_BUFFER,this.byteCapacity.valueOf(),e.STATIC_DRAW);const a=this.dataType.density.size(i).valueOf(),o=this.underlyingData.slice(this.gl.prevBuffer,this.writePos);e.bufferSubData(e.ARRAY_BUFFER,a,o.buffer),this.gl.prevBuffer=this.writePos}else e.bufferData(e.ARRAY_BUFFER,this.buffer,n==="static"?e.STATIC_DRAW:e.DYNAMIC_DRAW),this.gl.prevBuffer=Fe}as(e){if(e==="string"){if(!this.dataType.equals(I.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(I.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 Lt(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 rf(this);return this.dataType.equals(I.JSON)?new nf(e):e}return new sf(this)}slice(e,r){if(e<=0&&(r==null||r>=this.length))return this;const n=this.data.slice(e,r);return new Re({data:n,dataType:this.dataType,timeRange:this._timeRange,sampleOffset:this.sampleOffset,glBufferUsage:this.gl.bufferUsage,alignment:this.alignment+BigInt(e)})}reAlign(e){return new Re({data:this.buffer,dataType:this.dataType,timeRange:se.ZERO,sampleOffset:this.sampleOffset,glBufferUsage:"static",alignment:e})}};w(At,"crudeZ",s.z.object({timeRange:se.z.optional(),dataType:I.z,alignment:Vd.optional(),data:s.z.union([ef,tf,s.z.instanceof(ArrayBuffer)]),glBufferUsage:Hd.optional().default("static").optional()})),w(At,"z",At.crudeZ.transform(t=>new At(t)));let Ge=At;class rf{constructor(e){if(w(this,"series"),w(this,"index"),w(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,r=this.series.data;for(;this.index<r.length&&r[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 ki,xi;class nf{constructor(e){w(this,"wrapped"),w(this,ki,"JSONSeriesIterator"),this.wrapped=e}next(){const e=this.wrapped.next();return e.done===!0?{done:!0,value:void 0}:{done:!1,value:et.decodeString(e.value)}}[(xi=Symbol.iterator,ki=Symbol.toStringTag,xi)](){return this}}var Ci,$i;class sf{constructor(e){w(this,"series"),w(this,"index"),w(this,Ci,"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)}}[($i=Symbol.iterator,Ci=Symbol.toStringTag,$i)](){return this}}const kt=(t,e)=>typeof t=="bigint"&&typeof e=="bigint"||typeof t=="number"&&typeof e=="number"?t+e:e===0?t:t===0?e:Number(t)+Number(e);class af{constructor(e){if(w(this,"series"),e.length!==0){const r=e[0].dataType;for(let n=1;n<e.length;n++)if(!e[n].dataType.equals(r))throw new Error("[multi-series] - series must have the same data type")}this.series=e}as(e){if(!new I(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?I.UNKNOWN:this.series[0].dataType}get timeRange(){return this.series.length===0?se.ZERO:new se(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,r)=>e+r.length,0)}at(e,r=!1){e<0&&(e=this.length+e);for(const n of this.series){if(e<n.length)return n.at(e,r);e-=n.length}if(r)throw new Error(`[series] - no value at index ${e}`)}get byteLength(){return new qt(this.series.reduce((e,r)=>e+r.byteLength.valueOf(),0))}get data(){const e=new this.dataType.Array(this.length);let r=0;for(const n of this.series)e.set(n.data,r),r+=n.length;return new this.dataType.Array(e)}[Symbol.iterator](){return this.series.length===0?{next(){return{done:!0,value:void 0}}}:new of(this.series)}}var Ri,ji;class of{constructor(e){w(this,"series"),w(this,"seriesIndex"),w(this,"internal"),w(this,Ri,"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())}[(ji=Symbol.iterator,Ri=Symbol.toStringTag,ji)](){return this}}s.z.object({key:s.z.string(),value:s.z.string()});var cf=Object.defineProperty,lf=(t,e,r)=>e in t?cf(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,kr=(t,e,r)=>lf(t,typeof e!="symbol"?e+"":e,r);let uf=class{constructor(t,e){kr(this,"handlers"),kr(this,"transform"),kr(this,"closer"),this.transform=t,this.handlers=e??new Map}onChange(t){return this.handlers.set(t,null),()=>this.handlers.delete(t)}notify(t){let e=t;if(this.transform!=null){const[r,n]=this.transform(t);if(!n)return;e=r}this.handlers.forEach((r,n)=>n(e))}setCloser(t){this.closer=t}async close(){var t;return await((t=this.closer)==null?void 0:t.call(this))}},hf=class{constructor(t){kr(this,"handlers"),this.handlers=t??new Map}onChange(t){return this.handlers.set(t,null),()=>this.handlers.delete(t)}notify(t){this.handlers.forEach((e,r)=>r(t))}};const Je=Object.freeze(Object.defineProperty({__proto__:null,BaseObserver:hf,Observer:uf},Symbol.toStringTag,{value:"Module"})),Es=s.z.record(s.z.union([s.z.number(),s.z.string(),s.z.symbol()]),s.z.unknown()),df=()=>typeof process<"u"&&process.versions!=null&&process.versions.node!=null?"node":typeof window>"u"||window.document===void 0?"webworker":"browser";df();const ff=["MacOS","Windows","Linux","Docker"];s.z.enum(ff);var yf=Object.defineProperty,gf=(t,e,r)=>e in t?yf(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,xt=(t,e,r)=>gf(t,typeof e!="symbol"?e+"":e,r);const pf=(...t)=>t.map(To).join(""),To=t=>(t.endsWith("/")||(t+="/"),t.startsWith("/")&&(t=t.slice(1)),t),mf=t=>t.endsWith("/")?t.slice(0,-1):t,ns=class ss{constructor({host:e,port:r,protocol:n="",pathPrefix:i=""}){xt(this,"protocol"),xt(this,"host"),xt(this,"port"),xt(this,"path"),this.protocol=n,this.host=e,this.port=r,this.path=To(i)}replace(e){return new ss({host:e.host??this.host,port:e.port??this.port,protocol:e.protocol??this.protocol,pathPrefix:e.pathPrefix??this.path})}child(e){return new ss({...this,pathPrefix:pf(this.path,e)})}toString(){return mf(`${this.protocol}://${this.host}:${this.port}/${this.path}`)}};xt(ns,"UNKNOWN",new ns({host:"unknown",port:0}));let wf=ns;var bf=Object.defineProperty,vf=(t,e,r)=>e in t?bf(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,xr=(t,e,r)=>vf(t,typeof e!="symbol"?e+"":e,r);const We=class extends Number{};xr(We,"Absolute",255),xr(We,"Default",1),xr(We,"z",s.z.union([s.z.instanceof(We),s.z.number().int().min(0).max(255).transform(t=>new We(t)),s.z.instanceof(Number).transform(t=>new We(t))]));let So=We;const zo=s.z.object({name:s.z.string(),key:s.z.string()}),Of=t=>s.z.object({subject:zo,resource:t,authority:So.z}),Tf=(...t)=>e=>e.filter(r=>{let n=!1;return r.to!=null&&(n=t.includes(r.to.resource)),r.from!=null&&!n&&(n=t.includes(r.from.resource)),n}),nt=Object.freeze(Object.defineProperty({__proto__:null,Authority:So,filterTransfersByChannelKey:Tf,stateZ:Of,subjectZ:zo},Symbol.toStringTag,{value:"Module"})),No=class Ct extends Error{constructor(){super(Ct.MESSAGE)}matches(e){return typeof e=="string"?e.includes(Ct.MESSAGE):e instanceof Ct||e.message.includes(Ct.MESSAGE)}};xr(No,"MESSAGE","canceled");let Sf=No;new Sf;const is=s.z.string().regex(/^\d+\.\d+\.\d+$/),Qt=(t,e,r={})=>{r.checkMajor??(r.checkMajor=!0),r.checkMinor??(r.checkMinor=!0),r.checkPatch??(r.checkPatch=!0);const n=is.parse(t),i=is.parse(e),[a,o,u]=n.split(".").map(Number),[c,d,f]=i.split(".").map(Number);if(r.checkMajor){if(a<c)return kn;if(a>c)return xn}if(r.checkMinor){if(o<d)return kn;if(o>d)return xn}if(r.checkPatch){if(u<f)return kn;if(u>f)return xn}return an},zf=(t,e,r={})=>Yd(Qt(t,e,r)),Eo=(t,e,r={})=>_d(Qt(t,e,r)),Nf=(t,e,r={})=>Ld(Qt(t,e,r)),Ef=({name:t,migrate:e})=>r=>{try{const n=e(r);return console.log(`${t} migrated: ${r.version} -> ${n.version}`),n}catch(n){throw console.log(`${t} failed to migrate from ${r.version}`),console.error(n),n}},If=({name:t,migrations:e,targetSchema:r,def:n})=>{const i=Object.keys(e).sort(Qt).pop();if(i==null)return c=>{if(c.version!==n.version)return console.log(`${t} version ${c.version} is newer than latest version of ${n.version}.
|
|
39
|
+
`).slice(0,-1).map(r=>e.parse(et.decodeString(r)))}get timeRange(){if(this._timeRange==null)throw new Error("time range not set on series");return this._timeRange}get byteCapacity(){return new qt(this.buffer.byteLength)}get capacity(){return this.dataType.density.length(this.byteCapacity)}get byteLength(){return this.writePos===Fe?this.byteCapacity:this.dataType.density.size(this.writePos)}get length(){return this._cachedLength!=null?this._cachedLength:this.dataType.isVariable?this.calculateCachedLength():this.writePos===Fe?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(r=>{r===10&&e++}),this._cachedLength=e,e}convert(e,r=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]=Xd(this.dataType,e,this.data[i],r);return new Re({data:n.buffer,dataType:e,timeRange:this._timeRange,sampleOffset:r,glBufferUsage:this.gl.bufferUsage,alignment:this.alignment})}calcRawMax(){if(this.length===0)return-1/0;if(this.dataType.equals(I.TIMESTAMP))this._cachedMax=this.data[this.data.length-1];else if(this.dataType.usesBigInt){const e=this.data;this._cachedMax=e.reduce((r,n)=>r>n?r:n)}else{const e=this.data;this._cachedMax=e.reduce((r,n)=>r>n?r: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()),kt(this._cachedMax,this.sampleOffset))}calcRawMin(){if(this.length===0)return 1/0;if(this.dataType.equals(I.TIMESTAMP))this._cachedMin=this.data[0];else if(this.dataType.usesBigInt){const e=this.data;this._cachedMin=e.reduce((r,n)=>r<n?r:n)}else{const e=this.data;this._cachedMin=e.reduce((r,n)=>r<n?r: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()),kt(this._cachedMin,this.sampleOffset))}get bounds(){return Lt(Number(this.min),Number(this.max))}maybeRecomputeMinMax(e){if(this._cachedMin!=null){const r=e._cachedMin??e.calcRawMin();r<this._cachedMin&&(this._cachedMin=r)}if(this._cachedMax!=null){const r=e._cachedMax??e.calcRawMax();r>this._cachedMax&&(this._cachedMax=r)}}enrich(){this.max,this.min}get range(){return kt(this.max,-this.min)}at(e,r){if(this.dataType.isVariable)return this.atVariable(e,r??!1);e<0&&(e=this.length+e);const n=this.data[e];if(n==null){if(r===!0)throw new Error(`[series] - no value at index ${e}`);return}return kt(n,this.sampleOffset)}atVariable(e,r){e<0&&(e=this.length+e);let n=0,i=0;for(let o=0;o<this.data.length;o++)if(this.data[o]===10){if(e===0){i=o;break}n=o+1,e--}if(i===0&&(i=this.data.length),n>=i||e>0){if(r)throw new Error(`[series] - no value at index ${e}`);return}const a=this.data.slice(n,i);return this.dataType.equals(I.STRING)?new TextDecoder().decode(a):oo(JSON.parse(new TextDecoder().decode(a)))}binarySearch(e){let r=0,n=this.length-1;const i=Bd(e);for(;r<=n;){const a=Math.floor((r+n)/2),o=i(this.at(a,!0),e);if(o===0)return a;o<0?r=a+1:n=a-1}return r}updateGLBuffer(e){if(this.gl.control=e,!this.dataType.equals(I.FLOAT32))throw new Error("Only FLOAT32 arrays can be used in WebGL");const{buffer:r,bufferUsage:n,prevBuffer:i}=this.gl;if(r==null&&(this.gl.buffer=e.createBuffer()),this.writePos!==i)if(e.bindBuffer(e.ARRAY_BUFFER,this.gl.buffer),this.writePos!==Fe){i===0&&e.bufferData(e.ARRAY_BUFFER,this.byteCapacity.valueOf(),e.STATIC_DRAW);const a=this.dataType.density.size(i).valueOf(),o=this.underlyingData.slice(this.gl.prevBuffer,this.writePos);e.bufferSubData(e.ARRAY_BUFFER,a,o.buffer),this.gl.prevBuffer=this.writePos}else e.bufferData(e.ARRAY_BUFFER,this.buffer,n==="static"?e.STATIC_DRAW:e.DYNAMIC_DRAW),this.gl.prevBuffer=Fe}as(e){if(e==="string"){if(!this.dataType.equals(I.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(I.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 Lt(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 rf(this);return this.dataType.equals(I.JSON)?new nf(e):e}return new sf(this)}slice(e,r){if(e<=0&&(r==null||r>=this.length))return this;const n=this.data.slice(e,r);return new Re({data:n,dataType:this.dataType,timeRange:this._timeRange,sampleOffset:this.sampleOffset,glBufferUsage:this.gl.bufferUsage,alignment:this.alignment+BigInt(e)})}reAlign(e){return new Re({data:this.buffer,dataType:this.dataType,timeRange:se.ZERO,sampleOffset:this.sampleOffset,glBufferUsage:"static",alignment:e})}};w(At,"crudeZ",s.z.object({timeRange:se.z.optional(),dataType:I.z,alignment:Vd.optional(),data:s.z.union([ef,tf,s.z.instanceof(ArrayBuffer)]),glBufferUsage:Hd.optional().default("static").optional()})),w(At,"z",At.crudeZ.transform(t=>new At(t)));let Ge=At;class rf{constructor(e){if(w(this,"series"),w(this,"index"),w(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,r=this.series.data;for(;this.index<r.length&&r[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 ki,xi;class nf{constructor(e){w(this,"wrapped"),w(this,ki,"JSONSeriesIterator"),this.wrapped=e}next(){const e=this.wrapped.next();return e.done===!0?{done:!0,value:void 0}:{done:!1,value:et.decodeString(e.value)}}[(xi=Symbol.iterator,ki=Symbol.toStringTag,xi)](){return this}}var Ci,$i;class sf{constructor(e){w(this,"series"),w(this,"index"),w(this,Ci,"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)}}[($i=Symbol.iterator,Ci=Symbol.toStringTag,$i)](){return this}}const kt=(t,e)=>typeof t=="bigint"&&typeof e=="bigint"||typeof t=="number"&&typeof e=="number"?t+e:e===0?t:t===0?e:Number(t)+Number(e);class af{constructor(e){if(w(this,"series"),e.length!==0){const r=e[0].dataType;for(let n=1;n<e.length;n++)if(!e[n].dataType.equals(r))throw new Error("[multi-series] - series must have the same data type")}this.series=e}as(e){if(!new I(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?I.UNKNOWN:this.series[0].dataType}get timeRange(){return this.series.length===0?se.ZERO:new se(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,r)=>e+r.length,0)}at(e,r=!1){e<0&&(e=this.length+e);for(const n of this.series){if(e<n.length)return n.at(e,r);e-=n.length}if(r)throw new Error(`[series] - no value at index ${e}`)}get byteLength(){return new qt(this.series.reduce((e,r)=>e+r.byteLength.valueOf(),0))}get data(){const e=new this.dataType.Array(this.length);let r=0;for(const n of this.series)e.set(n.data,r),r+=n.length;return new this.dataType.Array(e)}[Symbol.iterator](){return this.series.length===0?{next(){return{done:!0,value:void 0}}}:new of(this.series)}}var Ri,ji;class of{constructor(e){w(this,"series"),w(this,"seriesIndex"),w(this,"internal"),w(this,Ri,"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())}[(ji=Symbol.iterator,Ri=Symbol.toStringTag,ji)](){return this}}s.z.object({key:s.z.string(),value:s.z.string()});var cf=Object.defineProperty,lf=(t,e,r)=>e in t?cf(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,kr=(t,e,r)=>lf(t,typeof e!="symbol"?e+"":e,r);let uf=class{constructor(t,e){kr(this,"handlers"),kr(this,"transform"),kr(this,"closer"),this.transform=t,this.handlers=e??new Map}onChange(t){return this.handlers.set(t,null),()=>this.handlers.delete(t)}notify(t){let e=t;if(this.transform!=null){const[r,n]=this.transform(t);if(!n)return;e=r}this.handlers.forEach((r,n)=>n(e))}setCloser(t){this.closer=t}async close(){var t;return await((t=this.closer)==null?void 0:t.call(this))}},hf=class{constructor(t){kr(this,"handlers"),this.handlers=t??new Map}onChange(t){return this.handlers.set(t,null),()=>this.handlers.delete(t)}notify(t){this.handlers.forEach((e,r)=>r(t))}};const Je=Object.freeze(Object.defineProperty({__proto__:null,BaseObserver:hf,Observer:uf},Symbol.toStringTag,{value:"Module"})),Es=s.z.record(s.z.union([s.z.number(),s.z.string(),s.z.symbol()]),s.z.unknown()),df=()=>typeof process<"u"&&process.versions!=null&&process.versions.node!=null?"node":typeof window>"u"||window.document===void 0?"webworker":"browser";df();const ff=["MacOS","Windows","Linux","Docker"];s.z.enum(ff);var yf=Object.defineProperty,gf=(t,e,r)=>e in t?yf(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,xt=(t,e,r)=>gf(t,typeof e!="symbol"?e+"":e,r);const pf=(...t)=>t.map(To).join(""),To=t=>(t.endsWith("/")||(t+="/"),t.startsWith("/")&&(t=t.slice(1)),t),mf=t=>t.endsWith("/")?t.slice(0,-1):t,ns=class ss{constructor({host:e,port:r,protocol:n="",pathPrefix:i=""}){xt(this,"protocol"),xt(this,"host"),xt(this,"port"),xt(this,"path"),this.protocol=n,this.host=e,this.port=r,this.path=To(i)}replace(e){return new ss({host:e.host??this.host,port:e.port??this.port,protocol:e.protocol??this.protocol,pathPrefix:e.pathPrefix??this.path})}child(e){return new ss({...this,pathPrefix:pf(this.path,e)})}toString(){return mf(`${this.protocol}://${this.host}:${this.port}/${this.path}`)}};xt(ns,"UNKNOWN",new ns({host:"unknown",port:0}));let wf=ns;var bf=Object.defineProperty,vf=(t,e,r)=>e in t?bf(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,xr=(t,e,r)=>vf(t,typeof e!="symbol"?e+"":e,r);const We=class extends Number{};xr(We,"Absolute",255),xr(We,"Default",1),xr(We,"z",s.z.union([s.z.instanceof(We),s.z.number().int().min(0).max(255).transform(t=>new We(t)),s.z.instanceof(Number).transform(t=>new We(t))]));let So=We;const zo=s.z.object({name:s.z.string(),key:s.z.string()}),Of=t=>s.z.object({subject:zo,resource:t,authority:So.z}),Tf=(...t)=>e=>e.filter(r=>{let n=!1;return r.to!=null&&(n=t.includes(r.to.resource)),r.from!=null&&!n&&(n=t.includes(r.from.resource)),n}),nt=Object.freeze(Object.defineProperty({__proto__:null,Authority:So,filterTransfersByChannelKey:Tf,stateZ:Of,subjectZ:zo},Symbol.toStringTag,{value:"Module"})),No=class Ct extends Error{constructor(){super(Ct.MESSAGE)}matches(e){return typeof e=="string"?e.includes(Ct.MESSAGE):e instanceof Ct||e.message.includes(Ct.MESSAGE)}};xr(No,"MESSAGE","canceled");let Sf=No;new Sf;const is=s.z.string().regex(/^\d+\.\d+\.\d+$/),Qt=(t,e,r={})=>{r.checkMajor??(r.checkMajor=!0),r.checkMinor??(r.checkMinor=!0),r.checkPatch??(r.checkPatch=!0);const n=is.parse(t),i=is.parse(e),[a,o,l]=n.split(".").map(Number),[u,d,f]=i.split(".").map(Number);if(r.checkMajor){if(a<u)return kn;if(a>u)return xn}if(r.checkMinor){if(o<d)return kn;if(o>d)return xn}if(r.checkPatch){if(l<f)return kn;if(l>f)return xn}return an},zf=(t,e,r={})=>Yd(Qt(t,e,r)),Eo=(t,e,r={})=>_d(Qt(t,e,r)),Nf=(t,e,r={})=>Ld(Qt(t,e,r)),Ef=({name:t,migrate:e})=>r=>{try{const n=e(r);return console.log(`${t} migrated: ${r.version} -> ${n.version}`),n}catch(n){throw console.log(`${t} failed to migrate from ${r.version}`),console.error(n),n}},If=({name:t,migrations:e,targetSchema:r,defaultVersion:n,def:i})=>{const a=Object.keys(e).sort(Qt).pop();if(a==null)return d=>{if(d.version==null&&(d.version=n),d.version!==i.version)return console.log(`${t} version ${d.version} is newer than latest version of ${i.version}.
|
|
40
40
|
Returning default instead.
|
|
41
|
-
`),
|
|
41
|
+
`),i;try{return r!=null?r.parse(d):d}catch(f){return console.log(`${t} failed to parse default. Exiting with default`),console.error(f),i}};const o=Object.keys(e).length;let l=!1;const u=d=>{try{if(o===0||Eo(d.version,a))return console.log(l?`${t} ${d.version} now up to date`:`${t} version ${d.version} is up to date with target version ${i.version}`),d;const f=d.version,h=e[f],E=h(d);return l=!0,u(E)}catch(f){return console.log(`${t} failed to migrate from ${d.version} to ${a}`),console.error(f),i}};return d=>{try{if(d.version==null)if(n!=null)console.log(`${t} version is null. Setting version to default of ${n}`),d.version=n;else return console.log(`${t} version is null and no default version set. Exiting with default`),i;return u(d)}catch(f){return console.log(`${t} failed to parse final result. Exiting with default`),console.error(f),i}}},Mi=Object.freeze(Object.defineProperty({__proto__:null,compareSemVer:Qt,createMigration:Ef,migrator:If,semVerNewer:Eo,semVerOlder:Nf,semVerZ:is,versionsEqual:zf},Symbol.toStringTag,{value:"Module"})),Le="sy.",Cr=class Io extends Oe{constructor(){super(...arguments),c(this,"type",Io.TYPE)}};c(Cr,"TYPE",Le+"validation"),c(Cr,"matches",de(Cr.TYPE));let K=Cr;const $r=class Ao extends K{constructor(e,r){super(e+": "+r),c(this,"type",Ao.TYPE),c(this,"field"),c(this,"message"),this.field=e,this.message=r}};c($r,"TYPE",K.TYPE+".field"),c($r,"matches",de($r.TYPE));let Di=$r;const Rr=class ko extends Oe{constructor(){super(...arguments),c(this,"type",ko.TYPE)}};c(Rr,"TYPE",Le+"auth"),c(Rr,"matches",de(Rr.TYPE));let Kr=Rr;const jr=class xo extends Kr{constructor(){super(...arguments),c(this,"type",xo.TYPE)}};c(jr,"TYPE",Kr.TYPE+".invalid-token"),c(jr,"matches",de(jr.TYPE));let as=jr;const Mr=class Co extends Oe{constructor(e){super(`
|
|
42
42
|
Unexpected error encountered:
|
|
43
43
|
|
|
44
44
|
${e}
|
|
45
45
|
|
|
46
46
|
Please report this to the Synnax team.
|
|
47
|
-
`),l(this,"type",Co.TYPE)}};l(Mr,"TYPE",Le+"unexpected"),l(Mr,"matches",de(Mr.TYPE));let we=Mr;const Dr=class $o extends Oe{constructor(){super(...arguments),l(this,"type",$o.TYPE)}};l(Dr,"TYPE",Le+"query"),l(Dr,"matches",de(Dr.TYPE));let ve=Dr;const Pr=class Ro extends ve{constructor(){super(...arguments),l(this,"type",Ro.TYPE)}};l(Pr,"TYPE",ve.TYPE+".not_found"),l(Pr,"matches",de(Pr.TYPE));let st=Pr;const Br=class jo extends ve{constructor(){super(...arguments),l(this,"type",jo.TYPE)}};l(Br,"TYPE",ve.TYPE+".multiple_results"),l(Br,"matches",de(Br.TYPE));let it=Br;const Ur=class Mo extends Oe{constructor(e,r){super(e),l(this,"type",Mo.TYPE),l(this,"path"),this.path=r}};l(Ur,"TYPE",Le+"route"),l(Ur,"matches",de(Ur.TYPE));let Pi=Ur;const Lr=class Do extends Oe{constructor(){super(...arguments),l(this,"type",Do.TYPE)}};l(Lr,"TYPE",Le+"control"),l(Lr,"matches",de(Lr.TYPE));let Jr=Lr;const _r=class Po extends Jr{constructor(){super(...arguments),l(this,"type",Po.TYPE)}};l(_r,"TYPE",Jr.TYPE+".unauthorized"),l(_r,"matches",de(_r.TYPE));let Bi=_r;const Cn=class Bo extends Oe{constructor(){super(...arguments),l(this,"type",Bo.TYPE)}};l(Cn,"TYPE",Le+"contiguity"),l(Cn,"matches",de(Cn.TYPE));const Af=t=>{if(!t.type.startsWith(Le))return null;if(t.type.startsWith(K.TYPE)){if(t.type===Di.TYPE){const e=t.data.split(": ");return e.length<2?new K(t.data):new Di(e[0],e[1])}return new K(t.data)}return t.type.startsWith(Kr.TYPE)?t.type.startsWith(as.TYPE)?new as(t.data):new Kr(t.data):t.type.startsWith(we.TYPE)?new we(t.data):t.type.startsWith(ve.TYPE)?t.type.startsWith(st.TYPE)?new st(t.data):t.type.startsWith(it.TYPE)?new it(t.data):new ve(t.data):t.type.startsWith(Jr.TYPE)?t.type.startsWith(Bi.TYPE)?new Bi(t.data):new Jr(t.data):t.type.startsWith(Pi.TYPE)?new Pi(t.data,t.data):new we(t.data)},kf=()=>{throw new Error("Not implemented")};Xa({encode:kf,decode:Af});const xf=async(t,e)=>{const[r,n]=await e(t);return n==null?[r,n]:n instanceof Ke?[r,new Ke({message:`Cannot reach cluster at ${n.url.host}:${n.url.port}`,url:n.url})]:[r,n]};class Uo{constructor(e,r){l(this,"key"),l(this,"name"),this.key=r,this.name=e}get ontologyID(){return new k({type:"group",key:this.key})}}const Cf=s.z.string().uuid(),Lo=s.z.object({key:Cf,name:s.z.string()}),on=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")]),ye=s.z.object({type:on,key:s.z.string()}),$f=s.z.string().transform(t=>{const[e,r]=t.split(":");return{type:on.parse(e),key:r??""}}),$t=s.z.union([$f,ye]),Yr=class _o{constructor(e){if(l(this,"type"),l(this,"key"),e instanceof _o){this.type=e.type,this.key=e.key;return}if(typeof e=="string"){const[r,n]=e.split(":");this.type=r,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}}};l(Yr,"z",s.z.union([s.z.instanceof(Yr),$t.transform(t=>new Yr(t))]));let k=Yr;new k({type:"builtin",key:"root"});const Rf=s.z.object({type:s.z.number()}),jf=s.z.object({type:on,fields:s.z.record(Rf)}),Mf=s.z.object({id:k.z,name:s.z.string(),schema:jf.optional().nullable(),data:s.z.record(s.z.unknown()).optional().nullable()}).transform(t=>({key:t.id.toString(),...t}));s.z.object({from:k.z,type:s.z.string(),to:k.z});const Ui=t=>{const[e,r,n]=t.split("->");return{from:new k(e),type:r,to:new k(n)}},Df=s.z.object({group:Lo}),Pf=s.z.object({parent:ye,key:s.z.string().uuid().optional(),name:s.z.string()}),Bf=s.z.object({key:s.z.string(),name:s.z.string()}),Uf=s.z.object({keys:s.z.array(s.z.string())});var Pe;let Lf=(Pe=class{constructor(t){l(this,"client"),this.client=t}async create(t,e,r){return(await v(this.client,Pe.ENDPOINT,{parent:t,name:e,key:r},Pf,Df)).group}async rename(t,e){await v(this.client,Pe.ENDPOINT_RENAME,{key:t,name:e},Bf,s.z.object({}))}async delete(t){await v(this.client,Pe.ENDPOINT_DELETE,{keys:t},Uf,s.z.object({}))}},l(Pe,"ENDPOINT","/ontology/create-group"),l(Pe,"ENDPOINT_RENAME","/ontology/rename-group"),l(Pe,"ENDPOINT_DELETE","/ontology/delete-group"),Pe),_f=class{constructor(t){l(this,"creator"),this.creator=new Lf(t)}async create(t,e,r){return this.sugar(await this.creator.create(t,e,r))}async rename(t,e){return await this.creator.rename(t,e)}async delete(...t){return await this.creator.delete(t)}sugar(t){return new Uo(t.name,t.key)}};const $n={ADD_CHILDREN:"/ontology/add-children",REMOVE_CHILDREN:"/ontology/remove-children",MOVE_CHILDREN:"/ontology/move-children"},Li=s.z.object({id:ye,children:ye.array()}),Yf=s.z.object({from:ye,to:ye,children:ye.array()});let qf=class{constructor(t){l(this,"client"),this.client=t}async addChildren(t,...e){await v(this.client,$n.ADD_CHILDREN,{id:new k(t).payload,children:e.map(r=>new k(r).payload)},Li,s.z.object({}))}async removeChildren(t,...e){await v(this.client,$n.REMOVE_CHILDREN,{id:new k(t).payload,children:e.map(r=>new k(r).payload)},Li,s.z.object({}))}async moveChildren(t,e,...r){const n={from:new k(t).payload,to:new k(e).payload,children:r.map(i=>new k(i).payload)};await v(this.client,$n.MOVE_CHILDREN,n,Yf,s.z.object({}))}};const Ff="/ontology/retrieve",Vf=s.z.object({ids:ye.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:on.array().optional()}),Wf=s.z.object({resources:Mf.array()}),Rn=t=>T(t).map(e=>new k(e).payload);let Gf=class{constructor(t,e){l(this,"type","ontology"),l(this,"groups"),l(this,"client"),l(this,"writer"),l(this,"framer"),this.client=t,this.writer=new qf(t),this.groups=new _f(t),this.framer=e}async search(t,e){return await this.execRetrieve({term:t,...e})}async retrieve(t,e){const r=await this.execRetrieve({ids:Rn(t),...e});if(Array.isArray(t))return r;if(r.length===0)throw new ve(`No resource found with ID ${t.toString()}`);return r[0]}async page(t,e,r){return await this.execRetrieve({offset:t,limit:e,...r})}async retrieveChildren(t,e){return await this.execRetrieve({ids:Rn(t),children:!0,...e})}async retrieveParents(t,e){return await this.execRetrieve({ids:Rn(t),parents:!0,...e})}async addChildren(t,...e){return await this.writer.addChildren(t,...e)}async removeChildren(t,...e){return await this.writer.removeChildren(t,...e)}async moveChildren(t,e,...r){return await this.writer.moveChildren(t,e,...r)}async openChangeTracker(){return await cn.open(this.framer,this)}async openDependentTracker(t){return await Is.open(t,this.framer,this)}newSearcherWithOptions(t){return{type:this.type,search:e=>this.search(e,t),retrieve:e=>this.retrieve(e,t),page:(e,r)=>this.page(e,r,t)}}async execRetrieve(t){const{resources:e}=await v(this.client,Ff,t,Vf,Wf);return e}};const _i="sy_ontology_resource_set",Yi="sy_ontology_resource_delete",qi="sy_ontology_relationship_set",Fi="sy_ontology_relationship_delete";class cn{constructor(e,r){l(this,"relationships"),l(this,"resources"),l(this,"resourceObs"),l(this,"relationshipObs"),l(this,"streamer"),l(this,"client"),l(this,"closePromise"),this.relationshipObs=new Je.Observer,this.relationships=this.relationshipObs,this.resourceObs=new Je.Observer,this.resources=this.resourceObs,this.client=r,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 r=await this.parseResourceSets(e),n=this.parseResourceDeletes(e);r.concat(n).length>0&&this.resourceObs.notify(r.concat(n));const i=this.parseRelationshipSets(e),a=this.parseRelationshipDeletes(e);i.concat(a).length>0&&this.relationshipObs.notify(i.concat(a))}parseRelationshipSets(e){const r=e.get(qi);return r.length===0?[]:Array.from(r.as("string")).map(n=>({variant:"set",key:Ui(n),value:void 0}))}parseRelationshipDeletes(e){const r=e.get(Fi);return r.length===0?[]:Array.from(r.as("string")).map(n=>({variant:"delete",key:Ui(n)}))}async parseResourceSets(e){const r=e.get(_i);if(r.length===0)return[];const n=Array.from(r.as("string")).map(i=>new k(i));try{return(await this.client.retrieve(n)).map(i=>({variant:"set",key:i.id,value:i}))}catch(i){if(i instanceof ve)return[];throw i}}parseResourceDeletes(e){const r=e.get(Yi);return r.length===0?[]:Array.from(r.as("string")).map(n=>({variant:"delete",key:new k(n)}))}static async open(e,r){const n=await e.openStreamer([_i,Yi,qi,Fi]);return new cn(n,r)}}const Vi=t=>t==="from"?"to":"from";class Is extends Je.Observer{constructor({target:e,dependents:r,relationshipType:n="parent",relationshipDirection:i="from",resourceType:a},o,u){super(),l(this,"internal"),l(this,"target"),l(this,"relDir"),l(this,"resourceType"),l(this,"dependents"),l(this,"client"),l(this,"relType"),l(this,"handleResourceChange",c=>{this.dependents=this.dependents.map(d=>{const f=c.find(h=>h.key.toString()==d.id.toString());return f==null||f.variant==="delete"?d:f.value}),this.notify(this.dependents)}),l(this,"handleRelationshipChange",c=>{const d=c.filter(h=>h.variant==="delete"&&h.key[this.relDir].toString()===this.target.toString()&&(this.resourceType==null||h.key[Vi(this.relDir)].type===this.resourceType));this.dependents=this.dependents.filter(h=>!d.some(E=>E.key.to.toString()===h.id.toString()&&E.key.type===this.relType));const f=c.filter(h=>h.variant==="set"&&h.key.type===this.relType&&h.key[this.relDir].toString()===this.target.toString()&&(this.resourceType==null||h.key[Vi(this.relDir)].type===this.resourceType));if(f.length===0)return this.notify(this.dependents);this.client.retrieve(f.map(h=>h.key.to)).then(h=>{this.dependents=this.dependents.concat(h),this.notify(this.dependents)})}),this.resourceType=a,this.internal=o,this.target=e,this.dependents=r,this.resourceType!=null&&(this.dependents=this.dependents.filter(c=>c.id.type===this.resourceType)),this.client=u,this.relType=n,this.relDir=i,this.internal.resources.onChange(this.handleResourceChange),this.internal.relationships.onChange(this.handleRelationshipChange)}static async open(e,r,n){const i=await cn.open(r,n);return new Is(e,i,n)}async close(){await this.internal.close()}}const pe=t=>s.z.union([s.z.null().transform(()=>[]),t.array()]),ln=s.z.string().uuid(),Zf=s.z.object({key:ln.optional(),subjects:$t.array().or($t),objects:$t.array().or($t),actions:es.array().or(es)}),As=s.z.object({key:ln,subjects:pe(ye),objects:pe(ye),actions:pe(es)}),Kf="allow_all";new k({type:Kf,key:""});const Jf=s.z.object({keys:ln.array().optional(),subjects:ye.array().optional()}),Hf=s.z.object({policies:pe(As)}),Xf="/access/policy/retrieve";let Qf=class{constructor(t){l(this,"client"),this.client=t}async retrieve(t){return(await v(this.client,Xf,t,Jf,Hf)).policies}};const ey=s.z.object({policies:As.partial({key:!0}).array()}),ty=s.z.object({policies:As.array()}),ry=s.z.object({keys:ln.array()}),ny=s.z.object({}),sy="/access/policy/create",iy="/access/policy/delete";let ay=class{constructor(t){l(this,"client"),this.client=t}async create(t){const e=Zf.array().parse(T(t)).map(r=>({objects:T(r.objects),actions:T(r.actions),subjects:T(r.subjects)}));return(await v(this.client,sy,{policies:e},ey,ty)).policies}async delete(t){await v(this.client,iy,{keys:T(t)},ry,ny)}},oy=class{constructor(t){l(this,"retriever"),l(this,"writer"),this.retriever=new Qf(t),this.writer=new ay(t)}async create(t){const e=Array.isArray(t),r=await this.writer.create(t);return e?r:r[0]}async retrieve(t){const e=Array.isArray(t),r=await this.retriever.retrieve({keys:T(t)});return e?r:r[0]}async retrieveFor(t){const e=T(t).map(r=>new k(r).payload);return await this.retriever.retrieve({subjects:e})}async delete(t){await this.writer.delete(t)}},cy=class{constructor(t){l(this,"policy"),this.policy=new oy(t)}};const _e=s.z.number(),er=s.z.object({name:s.z.string(),key:s.z.number(),rate:Ns.z,dataType:I.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()}),Yo=er.extend({key:s.z.number().optional(),leaseholder:s.z.number().optional(),index:s.z.number().optional(),rate:Ns.z.optional().default(0),isIndex:s.z.boolean().optional(),internal:s.z.boolean().optional().default(!1),virtual:s.z.boolean().optional().default(!1)}),qo="channel",ly=t=>new k({type:qo,key:t.toString()}),uy=new Error("request for lock canceled");var hy=function(t,e,r,n){function i(a){return a instanceof r?a:new r(function(o){o(a)})}return new(r||(r=Promise))(function(a,o){function u(f){try{d(n.next(f))}catch(h){o(h)}}function c(f){try{d(n.throw(f))}catch(h){o(h)}}function d(f){f.done?a(f.value):i(f.value).then(u,c)}d((n=n.apply(t,e||[])).next())})};class dy{constructor(e,r=uy){this._value=e,this._cancelError=r,this._queue=[],this._weightedWaiters=[]}acquire(e=1,r=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:r},o=Fo(this._queue,u=>r<=u.priority);o===-1&&e<=this._value?this._dispatchItem(a):this._queue.splice(o+1,0,a)})}runExclusive(e){return hy(this,arguments,void 0,function*(r,n=1,i=0){const[a,o]=yield this.acquire(n,i);try{return yield r(a)}finally{o()}})}waitForUnlock(e=1,r=0){if(e<=0)throw new Error(`invalid weight ${e}: must be positive`);return this._couldLockImmediately(e,r)?Promise.resolve():new Promise(n=>{this._weightedWaiters[e-1]||(this._weightedWaiters[e-1]=[]),fy(this._weightedWaiters[e-1],{resolve:n,priority:r})})}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 r=this._value;this._value-=e.weight,e.resolve([r,this._newReleaser(e.weight)])}_newReleaser(e){let r=!1;return()=>{r||(r=!0,this.release(e))}}_drainUnlockWaiters(){if(this._queue.length===0)for(let e=this._value;e>0;e--){const r=this._weightedWaiters[e-1];r&&(r.forEach(n=>n.resolve()),this._weightedWaiters[e-1]=[])}else{const e=this._queue[0].priority;for(let r=this._value;r>0;r--){const n=this._weightedWaiters[r-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,r){return(this._queue.length===0||this._queue[0].priority<r)&&e<=this._value}}function fy(t,e){const r=Fo(t,n=>e.priority<=n.priority);t.splice(r+1,0,e)}function Fo(t,e){for(let r=t.length-1;r>=0;r--)if(e(t[r]))return r;return-1}var yy=function(t,e,r,n){function i(a){return a instanceof r?a:new r(function(o){o(a)})}return new(r||(r=Promise))(function(a,o){function u(f){try{d(n.next(f))}catch(h){o(h)}}function c(f){try{d(n.throw(f))}catch(h){o(h)}}function d(f){f.done?a(f.value):i(f.value).then(u,c)}d((n=n.apply(t,e||[])).next())})};class gy{constructor(e){this._semaphore=new dy(1,e)}acquire(){return yy(this,arguments,void 0,function*(e=0){const[,r]=yield this._semaphore.acquire(1,e);return r})}runExclusive(e,r=0){return this._semaphore.runExclusive(()=>e(),1,r)}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 un=(t,e,{convertNumericStrings:r=!0}={})=>{const n=!Array.isArray(t);let i=T(t);const a=i[0],o=typeof a;let u;return o==="string"&&r&&!isNaN(parseInt(a))&&"number"in e?(u=e.number,i=i.map(c=>parseInt(c))):u=e[o],{single:n,variant:u,normalized:i,actual:t}},hn=(t,e,r,n)=>{if(n){if(r.length===0)throw new st(`${t} not found matching ${JSON.stringify(e)}`);if(r.length>1)throw new it(`Expected one ${t} matching ${JSON.stringify(e)}, but found ${r.length}`)}},py=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:I.z.array().optional(),notDataTypes:I.z.array().optional(),virtual:s.z.boolean().optional(),isIndex:s.z.boolean().optional(),internal:s.z.boolean().optional()}),my=s.z.object({channels:pe(er)}),De=t=>un(t,{number:"keys",string:"names"}),Vo=class Wo{constructor(e){l(this,"client"),this.client=e}async search(e,r){return await this.execute({search:e,...r})}async retrieve(e,r){const n=De(e),{variant:i}=n;let{normalized:a}=n;return i==="keys"&&a.indexOf(0)!==-1&&(a=a.filter(o=>o!==0)),a.length===0?[]:await this.execute({[i]:a,...r})}async page(e,r,n){return await this.execute({offset:e,limit:r,...n})}async execute(e){const[r,n]=await this.client.send(Wo.ENDPOINT,e,py,my);if(n!=null)throw n;return r.channels}};l(Vo,"ENDPOINT","/channel/retrieve");let ks=Vo;class xs{constructor(e){l(this,"cache"),l(this,"namesToKeys"),l(this,"wrapped"),this.cache=new Map,this.namesToKeys=new Map,this.wrapped=e}async search(e,r){return await this.wrapped.search(e,r)}async page(e,r,n){return await this.wrapped.page(e,r,n)}async retrieve(e,r){const{normalized:n}=un(e,{string:"names",number:"keys"}),i=[],a=[];if(n.forEach(u=>{const c=this.get(u);c!=null?i.push(...c):a.push(u)}),a.length===0)return i;const o=await this.wrapped.retrieve(a,r);return this.set(o),i.concat(o)}delete(e){const{variant:r,normalized:n}=De(e);r==="names"?n.forEach(i=>{const a=this.namesToKeys.get(i);a!=null&&(a.forEach(o=>this.cache.delete(o)),this.namesToKeys.delete(i))}):n.forEach(i=>{const a=this.cache.get(i);a!=null&&(this.cache.delete(i),this.namesToKeys.delete(a.name))})}rename(e,r){e.forEach((n,i)=>{const a=r[i],o=this.cache.get(n);if(o==null)return;this.cache.delete(n);const u=this.namesToKeys.get(o.name);u!=null&&(u.delete(n),u.size===0&&this.namesToKeys.delete(o.name)),o.name=a,this.cache.set(n,o);const c=this.namesToKeys.get(a);c==null?this.namesToKeys.set(a,new Set([n])):c.add(n)})}set(e){e.forEach(r=>{this.cache.set(r.key,r);const n=this.namesToKeys.get(r.name);n==null?this.namesToKeys.set(r.name,new Set([r.key])):n.add(r.key)})}get(e){if(typeof e=="number"){const i=this.cache.get(e);return i==null?void 0:[i]}const r=this.namesToKeys.get(e);if(r==null)return;const n=[];if(r.forEach(i=>{const a=this.cache.get(i);a!=null&&n.push(a)}),n.length!==0)return n}}class Go{constructor(e,r){l(this,"mu",new gy),l(this,"requests",new Map),l(this,"wrapped"),l(this,"debouncedRun"),this.wrapped=e,this.debouncedRun=qd(()=>{this.run()},r)}async search(e,r){return await this.wrapped.search(e,r)}async page(e,r,n){return await this.wrapped.page(e,r,n)}async retrieve(e){const{normalized:r,variant:n}=De(e);return n==="names"?await this.wrapped.retrieve(r):await new Promise((i,a)=>{this.mu.runExclusive(()=>{this.requests.set(r,{resolve:i,reject:a}),this.debouncedRun()})})}async run(){await this.mu.runExclusive(async()=>{const e=new Set;this.requests.forEach((r,n)=>n.forEach(i=>e.add(i)));try{const r=await this.wrapped.retrieve(Array.from(e));this.requests.forEach((n,i)=>n.resolve(r.filter(a=>i.includes(a.key))))}catch(r){this.requests.forEach(n=>n.reject(r))}finally{this.requests.clear()}})}}const Zo=async(t,e)=>{const{normalized:r}=De(e),n=await t.retrieve(r),i=[];if(r.forEach(a=>{n.find(o=>o.name===a||o.key===a)==null&&i.push(a)}),i.length>0)throw new ve(`Could not find channels: ${JSON.stringify(i)}`);return n};class Ko{constructor({dataType:e,rate:r,name:n,leaseholder:i=0,key:a=0,isIndex:o=!1,index:u=0,internal:c=!1,virtual:d=!1,frameClient:f,alias:h}){l(this,"_frameClient"),l(this,"key"),l(this,"name"),l(this,"rate"),l(this,"dataType"),l(this,"leaseholder"),l(this,"index"),l(this,"isIndex"),l(this,"internal"),l(this,"alias"),l(this,"virtual"),this.key=a,this.name=n,this.rate=new Ns(r??0),this.dataType=new I(e),this.leaseholder=i,this.index=u,this.isIndex=o,this.internal=c,this.alias=h,this.virtual=d,this._frameClient=f??null}get framer(){if(this._frameClient==null)throw new K("cannot read from a channel that has not been created");return this._frameClient}get payload(){return er.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 k({type:"channel",key:this.key.toString()})}async read(e){return await this.framer.read(e,this.key)}async write(e,r){return await this.framer.write(e,this.key,r)}}const wy="/channel/retrieve-group",by=s.z.object({}),vy=s.z.object({group:Lo});let Jo=class{constructor(t,e,r,n){l(this,"type","channel"),l(this,"frameClient"),l(this,"client"),l(this,"retriever"),l(this,"writer"),this.frameClient=t,this.retriever=e,this.client=r,this.writer=n}async create(t,e={}){const{retrieveIfNameExists:r=!1}=e,n=!Array.isArray(t);let i=T(t),a=[];if(r){const o=await this.retriever.retrieve(i.map(c=>c.name)),u=new Set(o.map(c=>c.name));i=i.filter(c=>!u.has(c.name)),a=this.sugar(o)}return a=a.concat(this.sugar(await this.writer.create(i))),n?a[0]:a}async retrieve(t,e){const r=!Array.isArray(t),n=this.sugar(await this.retriever.retrieve(t,e));return hn("channel",t,n,r),r?n[0]:n}async search(t,e){return this.sugar(await this.retriever.search(t,e))}async delete(t){const{normalized:e,variant:r}=De(t);return r==="keys"?await this.writer.delete({keys:e}):await this.writer.delete({names:e})}async rename(t,e){return await this.writer.rename(T(t),T(e))}newSearcherWithOptions(t){return{type:this.type,search:async e=>await this.search(e,t),retrieve:async e=>await this.retrieve(e,t),page:async(e,r)=>await this.page(e,r,t)}}async page(t,e,r){return this.sugar(await this.retriever.page(t,e,r))}createDebouncedBatchRetriever(t=10){return new xs(new Go(new ks(this.client),t))}sugar(t){const{frameClient:e}=this;return t.map(r=>new Ko({...r,frameClient:e}))}async retrieveGroup(){const t=await v(this.client,wy,{},by,vy);return new Uo(t.group.name,t.group.key)}};const Oy=s.z.object({channels:Yo.array()}),Ty=s.z.object({channels:er.array()}),Sy=s.z.object({keys:_e.array().optional(),names:s.z.string().array().optional()}),zy=s.z.object({}),Ny=s.z.object({keys:_e.array(),names:s.z.string().array()}),Ey=s.z.object({}),Iy="/channel/create",Ay="/channel/delete",ky="/channel/rename";let Ho=class{constructor(t,e){l(this,"client"),l(this,"cache"),this.client=t,this.cache=e}async create(t){const{channels:e}=await v(this.client,Iy,{channels:t},Oy,Ty);return this.cache.set(e),e}async delete(t){await v(this.client,Ay,t,Sy,zy),t.keys!=null&&this.cache.delete(t.keys),t.names!=null&&this.cache.delete(t.names)}async rename(t,e){await v(this.client,ky,{keys:t,names:e},Ny,Ey),this.cache.rename(t,e)}};const xy=Object.freeze(Object.defineProperty({__proto__:null,CacheRetriever:xs,Channel:Ko,Client:Jo,ClusterRetriever:ks,DebouncedBatchRetriever:Go,ONTOLOGY_TYPE:qo,Writer:Ho,analyzeChannelParams:De,keyZ:_e,newPayload:Yo,ontologyID:ly,payload:er,retrieveRequired:Zo},Symbol.toStringTag,{value:"Module"})),tr=s.z.string().uuid(),dn=s.z.object({key:tr,username:s.z.string().min(1),firstName:s.z.string(),lastName:s.z.string(),rootUser:s.z.boolean()}),Cy=dn.partial({key:!0,firstName:!0,lastName:!0}).omit({rootUser:!0}).extend({password:s.z.string().min(1)}),$y=s.z.object({keys:tr.array().optional(),usernames:s.z.string().array().optional()}),Ry=s.z.object({users:pe(dn)}),jy="/user/retrieve";let My=class{constructor(t){l(this,"client"),this.client=t}async retrieve(t){return(await v(this.client,jy,t,$y,Ry)).users}};const Dy=s.z.object({users:Cy.array()}),Py=s.z.object({users:dn.array()}),By=s.z.object({key:tr,username:s.z.string().min(1)}),Uy=s.z.object({}),Ly=s.z.object({key:tr,firstName:s.z.string().optional(),lastName:s.z.string().optional()}),_y=s.z.object({}),Yy=s.z.object({keys:tr.array()}),qy=s.z.object({}),Fy="/user/create",Vy="/user/change-username",Wy="/user/rename",Gy="/user/delete";let Zy=class{constructor(t){l(this,"client"),this.client=t}async create(t){return(await v(this.client,Fy,{users:T(t)},Dy,Py)).users}async changeUsername(t,e){await v(this.client,Vy,{key:t,username:e},By,Uy)}async rename(t,e,r){await v(this.client,Wy,{key:t,firstName:e,lastName:r},Ly,_y)}async delete(t){await v(this.client,Gy,{keys:T(t)},Yy,qy)}},Ky=class{constructor(t){l(this,"reader"),l(this,"writer"),this.writer=new Zy(t),this.reader=new My(t)}async create(t){const e=Array.isArray(t),r=await this.writer.create(t);return e?r:r[0]}async changeUsername(t,e){await this.writer.changeUsername(t,e)}async retrieve(t){const e=Array.isArray(t),r=await this.reader.retrieve({keys:T(t)});if(e)return r;if(r.length===0)throw new st(`No user with key ${t} found`);if(r.length>1)throw new it(`Multiple users found with key ${t}`);return r[0]}async retrieveByName(t){const e=Array.isArray(t),r=await this.reader.retrieve({usernames:T(t)});if(e)return r;if(r.length===0)throw new st(`No user with username ${t} found`);if(r.length>1)throw new it(`Multiple users found with username ${t}`);return r[0]}async rename(t,e,r){await this.writer.rename(t,e,r)}async delete(t){await this.writer.delete(t)}};const Jy=s.z.object({username:s.z.string(),password:s.z.string()}),Hy=s.z.object({token:s.z.string(),user:dn}),Wi="/auth/login",Xy=3,Qy="/auth/change-password",eg=s.z.object({username:s.z.string(),password:s.z.string(),newPassword:s.z.string().min(1)}),tg=s.z.object({});let rg=class{constructor(t,e){l(this,"token"),l(this,"client"),l(this,"credentials"),l(this,"authenticating"),l(this,"authenticated"),l(this,"user"),l(this,"retryCount"),this.client=t,this.authenticated=!1,this.credentials=e,this.retryCount=0}async changePassword(t){if(!this.authenticated)throw new Error("Not authenticated");await v(this.client,Qy,{username:this.credentials.username,password:this.credentials.password,newPassword:t},eg,tg),this.credentials.password=t}middleware(){const t=async(e,r)=>{if(!this.authenticated&&!e.target.endsWith(Wi)){this.authenticating==null&&(this.authenticating=new Promise((o,u)=>{this.client.send(Wi,this.credentials,Jy,Hy).then(([c,d])=>{if(d!=null)return o(d);this.token=c==null?void 0:c.token,this.user=c==null?void 0:c.user,this.authenticated=!0,o(null)}).catch(u)}));const a=await this.authenticating;if(a!=null)return[e,a]}e.params.Authorization=`Bearer ${this.token}`;const[n,i]=await r(e);return as.matches(i)&&this.retryCount<Xy?(this.authenticated=!1,this.authenticating=void 0,this.retryCount+=1,t(e,r)):(this.retryCount=0,[n,i])};return t}};const ng=["disconnected","connecting","connected","failed"],sg=s.z.enum(ng),ig=s.z.object({status:sg,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()}),ag=s.z.object({clusterKey:s.z.string(),nodeVersion:s.z.string().optional()}),Xo={clusterKey:"",status:"disconnected",error:void 0,message:"Disconnected",clientServerCompatible:!1,clientVersion:"0.31.0"},Gi=(t,e,r)=>{const n=r?"cluster":"client";return`Synnax cluster node version ${t!=null?t+" ":""}is too ${r?"old":"new"} for client version ${e}.
|
|
47
|
+
`),c(this,"type",Co.TYPE)}};c(Mr,"TYPE",Le+"unexpected"),c(Mr,"matches",de(Mr.TYPE));let we=Mr;const Dr=class $o extends Oe{constructor(){super(...arguments),c(this,"type",$o.TYPE)}};c(Dr,"TYPE",Le+"query"),c(Dr,"matches",de(Dr.TYPE));let ve=Dr;const Pr=class Ro extends ve{constructor(){super(...arguments),c(this,"type",Ro.TYPE)}};c(Pr,"TYPE",ve.TYPE+".not_found"),c(Pr,"matches",de(Pr.TYPE));let st=Pr;const Br=class jo extends ve{constructor(){super(...arguments),c(this,"type",jo.TYPE)}};c(Br,"TYPE",ve.TYPE+".multiple_results"),c(Br,"matches",de(Br.TYPE));let it=Br;const Ur=class Mo extends Oe{constructor(e,r){super(e),c(this,"type",Mo.TYPE),c(this,"path"),this.path=r}};c(Ur,"TYPE",Le+"route"),c(Ur,"matches",de(Ur.TYPE));let Pi=Ur;const Lr=class Do extends Oe{constructor(){super(...arguments),c(this,"type",Do.TYPE)}};c(Lr,"TYPE",Le+"control"),c(Lr,"matches",de(Lr.TYPE));let Jr=Lr;const _r=class Po extends Jr{constructor(){super(...arguments),c(this,"type",Po.TYPE)}};c(_r,"TYPE",Jr.TYPE+".unauthorized"),c(_r,"matches",de(_r.TYPE));let Bi=_r;const Cn=class Bo extends Oe{constructor(){super(...arguments),c(this,"type",Bo.TYPE)}};c(Cn,"TYPE",Le+"contiguity"),c(Cn,"matches",de(Cn.TYPE));const Af=t=>{if(!t.type.startsWith(Le))return null;if(t.type.startsWith(K.TYPE)){if(t.type===Di.TYPE){const e=t.data.split(": ");return e.length<2?new K(t.data):new Di(e[0],e[1])}return new K(t.data)}return t.type.startsWith(Kr.TYPE)?t.type.startsWith(as.TYPE)?new as(t.data):new Kr(t.data):t.type.startsWith(we.TYPE)?new we(t.data):t.type.startsWith(ve.TYPE)?t.type.startsWith(st.TYPE)?new st(t.data):t.type.startsWith(it.TYPE)?new it(t.data):new ve(t.data):t.type.startsWith(Jr.TYPE)?t.type.startsWith(Bi.TYPE)?new Bi(t.data):new Jr(t.data):t.type.startsWith(Pi.TYPE)?new Pi(t.data,t.data):new we(t.data)},kf=()=>{throw new Error("Not implemented")};Xa({encode:kf,decode:Af});const xf=async(t,e)=>{const[r,n]=await e(t);return n==null?[r,n]:n instanceof Ke?[r,new Ke({message:`Cannot reach cluster at ${n.url.host}:${n.url.port}`,url:n.url})]:[r,n]};class Uo{constructor(e,r){c(this,"key"),c(this,"name"),this.key=r,this.name=e}get ontologyID(){return new k({type:"group",key:this.key})}}const Cf=s.z.string().uuid(),Lo=s.z.object({key:Cf,name:s.z.string()}),on=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")]),ye=s.z.object({type:on,key:s.z.string()}),$f=s.z.string().transform(t=>{const[e,r]=t.split(":");return{type:on.parse(e),key:r??""}}),$t=s.z.union([$f,ye]),Yr=class _o{constructor(e){if(c(this,"type"),c(this,"key"),e instanceof _o){this.type=e.type,this.key=e.key;return}if(typeof e=="string"){const[r,n]=e.split(":");this.type=r,this.key=n??"";return}this.type=e.type,this.key=e.key}toString(){return`${this.type}:${this.key}`}isType(){return this.key===""}matchesType(e){return this.type===e&&this.isType()}get payload(){return{type:this.type,key:this.key}}};c(Yr,"z",s.z.union([s.z.instanceof(Yr),$t.transform(t=>new Yr(t))]));let k=Yr;new k({type:"builtin",key:"root"});const Rf=s.z.object({type:s.z.number()}),jf=s.z.object({type:on,fields:s.z.record(Rf)}),Mf=s.z.object({id:k.z,name:s.z.string(),schema:jf.optional().nullable(),data:s.z.record(s.z.unknown()).optional().nullable()}).transform(t=>({key:t.id.toString(),...t}));s.z.object({from:k.z,type:s.z.string(),to:k.z});const Ui=t=>{const[e,r,n]=t.split("->");return{from:new k(e),type:r,to:new k(n)}},Df=s.z.object({group:Lo}),Pf=s.z.object({parent:ye,key:s.z.string().uuid().optional(),name:s.z.string()}),Bf=s.z.object({key:s.z.string(),name:s.z.string()}),Uf=s.z.object({keys:s.z.array(s.z.string())});var Pe;let Lf=(Pe=class{constructor(t){c(this,"client"),this.client=t}async create(t,e,r){return(await v(this.client,Pe.ENDPOINT,{parent:t,name:e,key:r},Pf,Df)).group}async rename(t,e){await v(this.client,Pe.ENDPOINT_RENAME,{key:t,name:e},Bf,s.z.object({}))}async delete(t){await v(this.client,Pe.ENDPOINT_DELETE,{keys:t},Uf,s.z.object({}))}},c(Pe,"ENDPOINT","/ontology/create-group"),c(Pe,"ENDPOINT_RENAME","/ontology/rename-group"),c(Pe,"ENDPOINT_DELETE","/ontology/delete-group"),Pe),_f=class{constructor(t){c(this,"creator"),this.creator=new Lf(t)}async create(t,e,r){return this.sugar(await this.creator.create(t,e,r))}async rename(t,e){return await this.creator.rename(t,e)}async delete(...t){return await this.creator.delete(t)}sugar(t){return new Uo(t.name,t.key)}};const $n={ADD_CHILDREN:"/ontology/add-children",REMOVE_CHILDREN:"/ontology/remove-children",MOVE_CHILDREN:"/ontology/move-children"},Li=s.z.object({id:ye,children:ye.array()}),Yf=s.z.object({from:ye,to:ye,children:ye.array()});let qf=class{constructor(t){c(this,"client"),this.client=t}async addChildren(t,...e){await v(this.client,$n.ADD_CHILDREN,{id:new k(t).payload,children:e.map(r=>new k(r).payload)},Li,s.z.object({}))}async removeChildren(t,...e){await v(this.client,$n.REMOVE_CHILDREN,{id:new k(t).payload,children:e.map(r=>new k(r).payload)},Li,s.z.object({}))}async moveChildren(t,e,...r){const n={from:new k(t).payload,to:new k(e).payload,children:r.map(i=>new k(i).payload)};await v(this.client,$n.MOVE_CHILDREN,n,Yf,s.z.object({}))}};const Ff="/ontology/retrieve",Vf=s.z.object({ids:ye.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:on.array().optional()}),Wf=s.z.object({resources:Mf.array()}),Rn=t=>T(t).map(e=>new k(e).payload);let Gf=class{constructor(t,e){c(this,"type","ontology"),c(this,"groups"),c(this,"client"),c(this,"writer"),c(this,"framer"),this.client=t,this.writer=new qf(t),this.groups=new _f(t),this.framer=e}async search(t,e){return await this.execRetrieve({term:t,...e})}async retrieve(t,e){const r=await this.execRetrieve({ids:Rn(t),...e});if(Array.isArray(t))return r;if(r.length===0)throw new ve(`No resource found with ID ${t.toString()}`);return r[0]}async page(t,e,r){return await this.execRetrieve({offset:t,limit:e,...r})}async retrieveChildren(t,e){return await this.execRetrieve({ids:Rn(t),children:!0,...e})}async retrieveParents(t,e){return await this.execRetrieve({ids:Rn(t),parents:!0,...e})}async addChildren(t,...e){return await this.writer.addChildren(t,...e)}async removeChildren(t,...e){return await this.writer.removeChildren(t,...e)}async moveChildren(t,e,...r){return await this.writer.moveChildren(t,e,...r)}async openChangeTracker(){return await cn.open(this.framer,this)}async openDependentTracker(t){return await Is.open(t,this.framer,this)}newSearcherWithOptions(t){return{type:this.type,search:e=>this.search(e,t),retrieve:e=>this.retrieve(e,t),page:(e,r)=>this.page(e,r,t)}}async execRetrieve(t){const{resources:e}=await v(this.client,Ff,t,Vf,Wf);return e}};const _i="sy_ontology_resource_set",Yi="sy_ontology_resource_delete",qi="sy_ontology_relationship_set",Fi="sy_ontology_relationship_delete";class cn{constructor(e,r){c(this,"relationships"),c(this,"resources"),c(this,"resourceObs"),c(this,"relationshipObs"),c(this,"streamer"),c(this,"client"),c(this,"closePromise"),this.relationshipObs=new Je.Observer,this.relationships=this.relationshipObs,this.resourceObs=new Je.Observer,this.resources=this.resourceObs,this.client=r,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 r=await this.parseResourceSets(e),n=this.parseResourceDeletes(e);r.concat(n).length>0&&this.resourceObs.notify(r.concat(n));const i=this.parseRelationshipSets(e),a=this.parseRelationshipDeletes(e);i.concat(a).length>0&&this.relationshipObs.notify(i.concat(a))}parseRelationshipSets(e){const r=e.get(qi);return r.length===0?[]:Array.from(r.as("string")).map(n=>({variant:"set",key:Ui(n),value:void 0}))}parseRelationshipDeletes(e){const r=e.get(Fi);return r.length===0?[]:Array.from(r.as("string")).map(n=>({variant:"delete",key:Ui(n)}))}async parseResourceSets(e){const r=e.get(_i);if(r.length===0)return[];const n=Array.from(r.as("string")).map(i=>new k(i));try{return(await this.client.retrieve(n)).map(i=>({variant:"set",key:i.id,value:i}))}catch(i){if(i instanceof ve)return[];throw i}}parseResourceDeletes(e){const r=e.get(Yi);return r.length===0?[]:Array.from(r.as("string")).map(n=>({variant:"delete",key:new k(n)}))}static async open(e,r){const n=await e.openStreamer([_i,Yi,qi,Fi]);return new cn(n,r)}}const Vi=t=>t==="from"?"to":"from";class Is extends Je.Observer{constructor({target:e,dependents:r,relationshipType:n="parent",relationshipDirection:i="from",resourceType:a},o,l){super(),c(this,"internal"),c(this,"target"),c(this,"relDir"),c(this,"resourceType"),c(this,"dependents"),c(this,"client"),c(this,"relType"),c(this,"handleResourceChange",u=>{this.dependents=this.dependents.map(d=>{const f=u.find(h=>h.key.toString()==d.id.toString());return f==null||f.variant==="delete"?d:f.value}),this.notify(this.dependents)}),c(this,"handleRelationshipChange",u=>{const d=u.filter(h=>h.variant==="delete"&&h.key[this.relDir].toString()===this.target.toString()&&(this.resourceType==null||h.key[Vi(this.relDir)].type===this.resourceType));this.dependents=this.dependents.filter(h=>!d.some(E=>E.key.to.toString()===h.id.toString()&&E.key.type===this.relType));const f=u.filter(h=>h.variant==="set"&&h.key.type===this.relType&&h.key[this.relDir].toString()===this.target.toString()&&(this.resourceType==null||h.key[Vi(this.relDir)].type===this.resourceType));if(f.length===0)return this.notify(this.dependents);this.client.retrieve(f.map(h=>h.key.to)).then(h=>{this.dependents=this.dependents.concat(h),this.notify(this.dependents)})}),this.resourceType=a,this.internal=o,this.target=e,this.dependents=r,this.resourceType!=null&&(this.dependents=this.dependents.filter(u=>u.id.type===this.resourceType)),this.client=l,this.relType=n,this.relDir=i,this.internal.resources.onChange(this.handleResourceChange),this.internal.relationships.onChange(this.handleRelationshipChange)}static async open(e,r,n){const i=await cn.open(r,n);return new Is(e,i,n)}async close(){await this.internal.close()}}const pe=t=>s.z.union([s.z.null().transform(()=>[]),t.array()]),ln=s.z.string().uuid(),Zf=s.z.object({key:ln.optional(),subjects:$t.array().or($t),objects:$t.array().or($t),actions:es.array().or(es)}),As=s.z.object({key:ln,subjects:pe(ye),objects:pe(ye),actions:pe(es)}),Kf="allow_all";new k({type:Kf,key:""});const Jf=s.z.object({keys:ln.array().optional(),subjects:ye.array().optional()}),Hf=s.z.object({policies:pe(As)}),Xf="/access/policy/retrieve";let Qf=class{constructor(t){c(this,"client"),this.client=t}async retrieve(t){return(await v(this.client,Xf,t,Jf,Hf)).policies}};const ey=s.z.object({policies:As.partial({key:!0}).array()}),ty=s.z.object({policies:As.array()}),ry=s.z.object({keys:ln.array()}),ny=s.z.object({}),sy="/access/policy/create",iy="/access/policy/delete";let ay=class{constructor(t){c(this,"client"),this.client=t}async create(t){const e=Zf.array().parse(T(t)).map(r=>({objects:T(r.objects),actions:T(r.actions),subjects:T(r.subjects)}));return(await v(this.client,sy,{policies:e},ey,ty)).policies}async delete(t){await v(this.client,iy,{keys:T(t)},ry,ny)}},oy=class{constructor(t){c(this,"retriever"),c(this,"writer"),this.retriever=new Qf(t),this.writer=new ay(t)}async create(t){const e=Array.isArray(t),r=await this.writer.create(t);return e?r:r[0]}async retrieve(t){const e=Array.isArray(t),r=await this.retriever.retrieve({keys:T(t)});return e?r:r[0]}async retrieveFor(t){const e=T(t).map(r=>new k(r).payload);return await this.retriever.retrieve({subjects:e})}async delete(t){await this.writer.delete(t)}},cy=class{constructor(t){c(this,"policy"),this.policy=new oy(t)}};const _e=s.z.number(),er=s.z.object({name:s.z.string(),key:s.z.number(),rate:Ns.z,dataType:I.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()}),Yo=er.extend({key:s.z.number().optional(),leaseholder:s.z.number().optional(),index:s.z.number().optional(),rate:Ns.z.optional().default(0),isIndex:s.z.boolean().optional(),internal:s.z.boolean().optional().default(!1),virtual:s.z.boolean().optional().default(!1)}),qo="channel",ly=t=>new k({type:qo,key:t.toString()}),uy=new Error("request for lock canceled");var hy=function(t,e,r,n){function i(a){return a instanceof r?a:new r(function(o){o(a)})}return new(r||(r=Promise))(function(a,o){function l(f){try{d(n.next(f))}catch(h){o(h)}}function u(f){try{d(n.throw(f))}catch(h){o(h)}}function d(f){f.done?a(f.value):i(f.value).then(l,u)}d((n=n.apply(t,e||[])).next())})};class dy{constructor(e,r=uy){this._value=e,this._cancelError=r,this._queue=[],this._weightedWaiters=[]}acquire(e=1,r=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:r},o=Fo(this._queue,l=>r<=l.priority);o===-1&&e<=this._value?this._dispatchItem(a):this._queue.splice(o+1,0,a)})}runExclusive(e){return hy(this,arguments,void 0,function*(r,n=1,i=0){const[a,o]=yield this.acquire(n,i);try{return yield r(a)}finally{o()}})}waitForUnlock(e=1,r=0){if(e<=0)throw new Error(`invalid weight ${e}: must be positive`);return this._couldLockImmediately(e,r)?Promise.resolve():new Promise(n=>{this._weightedWaiters[e-1]||(this._weightedWaiters[e-1]=[]),fy(this._weightedWaiters[e-1],{resolve:n,priority:r})})}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 r=this._value;this._value-=e.weight,e.resolve([r,this._newReleaser(e.weight)])}_newReleaser(e){let r=!1;return()=>{r||(r=!0,this.release(e))}}_drainUnlockWaiters(){if(this._queue.length===0)for(let e=this._value;e>0;e--){const r=this._weightedWaiters[e-1];r&&(r.forEach(n=>n.resolve()),this._weightedWaiters[e-1]=[])}else{const e=this._queue[0].priority;for(let r=this._value;r>0;r--){const n=this._weightedWaiters[r-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,r){return(this._queue.length===0||this._queue[0].priority<r)&&e<=this._value}}function fy(t,e){const r=Fo(t,n=>e.priority<=n.priority);t.splice(r+1,0,e)}function Fo(t,e){for(let r=t.length-1;r>=0;r--)if(e(t[r]))return r;return-1}var yy=function(t,e,r,n){function i(a){return a instanceof r?a:new r(function(o){o(a)})}return new(r||(r=Promise))(function(a,o){function l(f){try{d(n.next(f))}catch(h){o(h)}}function u(f){try{d(n.throw(f))}catch(h){o(h)}}function d(f){f.done?a(f.value):i(f.value).then(l,u)}d((n=n.apply(t,e||[])).next())})};class gy{constructor(e){this._semaphore=new dy(1,e)}acquire(){return yy(this,arguments,void 0,function*(e=0){const[,r]=yield this._semaphore.acquire(1,e);return r})}runExclusive(e,r=0){return this._semaphore.runExclusive(()=>e(),1,r)}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 un=(t,e,{convertNumericStrings:r=!0}={})=>{const n=!Array.isArray(t);let i=T(t);const a=i[0],o=typeof a;let l;return o==="string"&&r&&!isNaN(parseInt(a))&&"number"in e?(l=e.number,i=i.map(u=>parseInt(u))):l=e[o],{single:n,variant:l,normalized:i,actual:t}},hn=(t,e,r,n)=>{if(n){if(r.length===0)throw new st(`${t} not found matching ${JSON.stringify(e)}`);if(r.length>1)throw new it(`Expected one ${t} matching ${JSON.stringify(e)}, but found ${r.length}`)}},py=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:I.z.array().optional(),notDataTypes:I.z.array().optional(),virtual:s.z.boolean().optional(),isIndex:s.z.boolean().optional(),internal:s.z.boolean().optional()}),my=s.z.object({channels:pe(er)}),De=t=>un(t,{number:"keys",string:"names"}),Vo=class Wo{constructor(e){c(this,"client"),this.client=e}async search(e,r){return await this.execute({search:e,...r})}async retrieve(e,r){const n=De(e),{variant:i}=n;let{normalized:a}=n;return i==="keys"&&a.indexOf(0)!==-1&&(a=a.filter(o=>o!==0)),a.length===0?[]:await this.execute({[i]:a,...r})}async page(e,r,n){return await this.execute({offset:e,limit:r,...n})}async execute(e){const[r,n]=await this.client.send(Wo.ENDPOINT,e,py,my);if(n!=null)throw n;return r.channels}};c(Vo,"ENDPOINT","/channel/retrieve");let ks=Vo;class xs{constructor(e){c(this,"cache"),c(this,"namesToKeys"),c(this,"wrapped"),this.cache=new Map,this.namesToKeys=new Map,this.wrapped=e}async search(e,r){return await this.wrapped.search(e,r)}async page(e,r,n){return await this.wrapped.page(e,r,n)}async retrieve(e,r){const{normalized:n}=un(e,{string:"names",number:"keys"}),i=[],a=[];if(n.forEach(l=>{const u=this.get(l);u!=null?i.push(...u):a.push(l)}),a.length===0)return i;const o=await this.wrapped.retrieve(a,r);return this.set(o),i.concat(o)}delete(e){const{variant:r,normalized:n}=De(e);r==="names"?n.forEach(i=>{const a=this.namesToKeys.get(i);a!=null&&(a.forEach(o=>this.cache.delete(o)),this.namesToKeys.delete(i))}):n.forEach(i=>{const a=this.cache.get(i);a!=null&&(this.cache.delete(i),this.namesToKeys.delete(a.name))})}rename(e,r){e.forEach((n,i)=>{const a=r[i],o=this.cache.get(n);if(o==null)return;this.cache.delete(n);const l=this.namesToKeys.get(o.name);l!=null&&(l.delete(n),l.size===0&&this.namesToKeys.delete(o.name)),o.name=a,this.cache.set(n,o);const u=this.namesToKeys.get(a);u==null?this.namesToKeys.set(a,new Set([n])):u.add(n)})}set(e){e.forEach(r=>{this.cache.set(r.key,r);const n=this.namesToKeys.get(r.name);n==null?this.namesToKeys.set(r.name,new Set([r.key])):n.add(r.key)})}get(e){if(typeof e=="number"){const i=this.cache.get(e);return i==null?void 0:[i]}const r=this.namesToKeys.get(e);if(r==null)return;const n=[];if(r.forEach(i=>{const a=this.cache.get(i);a!=null&&n.push(a)}),n.length!==0)return n}}class Go{constructor(e,r){c(this,"mu",new gy),c(this,"requests",new Map),c(this,"wrapped"),c(this,"debouncedRun"),this.wrapped=e,this.debouncedRun=qd(()=>{this.run()},r)}async search(e,r){return await this.wrapped.search(e,r)}async page(e,r,n){return await this.wrapped.page(e,r,n)}async retrieve(e){const{normalized:r,variant:n}=De(e);return n==="names"?await this.wrapped.retrieve(r):await new Promise((i,a)=>{this.mu.runExclusive(()=>{this.requests.set(r,{resolve:i,reject:a}),this.debouncedRun()})})}async run(){await this.mu.runExclusive(async()=>{const e=new Set;this.requests.forEach((r,n)=>n.forEach(i=>e.add(i)));try{const r=await this.wrapped.retrieve(Array.from(e));this.requests.forEach((n,i)=>n.resolve(r.filter(a=>i.includes(a.key))))}catch(r){this.requests.forEach(n=>n.reject(r))}finally{this.requests.clear()}})}}const Zo=async(t,e)=>{const{normalized:r}=De(e),n=await t.retrieve(r),i=[];if(r.forEach(a=>{n.find(o=>o.name===a||o.key===a)==null&&i.push(a)}),i.length>0)throw new ve(`Could not find channels: ${JSON.stringify(i)}`);return n};class Ko{constructor({dataType:e,rate:r,name:n,leaseholder:i=0,key:a=0,isIndex:o=!1,index:l=0,internal:u=!1,virtual:d=!1,frameClient:f,alias:h}){c(this,"_frameClient"),c(this,"key"),c(this,"name"),c(this,"rate"),c(this,"dataType"),c(this,"leaseholder"),c(this,"index"),c(this,"isIndex"),c(this,"internal"),c(this,"alias"),c(this,"virtual"),this.key=a,this.name=n,this.rate=new Ns(r??0),this.dataType=new I(e),this.leaseholder=i,this.index=l,this.isIndex=o,this.internal=u,this.alias=h,this.virtual=d,this._frameClient=f??null}get framer(){if(this._frameClient==null)throw new K("cannot read from a channel that has not been created");return this._frameClient}get payload(){return er.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 k({type:"channel",key:this.key.toString()})}async read(e){return await this.framer.read(e,this.key)}async write(e,r){return await this.framer.write(e,this.key,r)}}const wy="/channel/retrieve-group",by=s.z.object({}),vy=s.z.object({group:Lo});let Jo=class{constructor(t,e,r,n){c(this,"type","channel"),c(this,"frameClient"),c(this,"client"),c(this,"retriever"),c(this,"writer"),this.frameClient=t,this.retriever=e,this.client=r,this.writer=n}async create(t,e={}){const{retrieveIfNameExists:r=!1}=e,n=!Array.isArray(t);let i=T(t),a=[];if(r){const o=await this.retriever.retrieve(i.map(u=>u.name)),l=new Set(o.map(u=>u.name));i=i.filter(u=>!l.has(u.name)),a=this.sugar(o)}return a=a.concat(this.sugar(await this.writer.create(i))),n?a[0]:a}async retrieve(t,e){const r=!Array.isArray(t),n=this.sugar(await this.retriever.retrieve(t,e));return hn("channel",t,n,r),r?n[0]:n}async search(t,e){return this.sugar(await this.retriever.search(t,e))}async delete(t){const{normalized:e,variant:r}=De(t);return r==="keys"?await this.writer.delete({keys:e}):await this.writer.delete({names:e})}async rename(t,e){return await this.writer.rename(T(t),T(e))}newSearcherWithOptions(t){return{type:this.type,search:async e=>await this.search(e,t),retrieve:async e=>await this.retrieve(e,t),page:async(e,r)=>await this.page(e,r,t)}}async page(t,e,r){return this.sugar(await this.retriever.page(t,e,r))}createDebouncedBatchRetriever(t=10){return new xs(new Go(new ks(this.client),t))}sugar(t){const{frameClient:e}=this;return t.map(r=>new Ko({...r,frameClient:e}))}async retrieveGroup(){const t=await v(this.client,wy,{},by,vy);return new Uo(t.group.name,t.group.key)}};const Oy=s.z.object({channels:Yo.array()}),Ty=s.z.object({channels:er.array()}),Sy=s.z.object({keys:_e.array().optional(),names:s.z.string().array().optional()}),zy=s.z.object({}),Ny=s.z.object({keys:_e.array(),names:s.z.string().array()}),Ey=s.z.object({}),Iy="/channel/create",Ay="/channel/delete",ky="/channel/rename";let Ho=class{constructor(t,e){c(this,"client"),c(this,"cache"),this.client=t,this.cache=e}async create(t){const{channels:e}=await v(this.client,Iy,{channels:t},Oy,Ty);return this.cache.set(e),e}async delete(t){await v(this.client,Ay,t,Sy,zy),t.keys!=null&&this.cache.delete(t.keys),t.names!=null&&this.cache.delete(t.names)}async rename(t,e){await v(this.client,ky,{keys:t,names:e},Ny,Ey),this.cache.rename(t,e)}};const xy=Object.freeze(Object.defineProperty({__proto__:null,CacheRetriever:xs,Channel:Ko,Client:Jo,ClusterRetriever:ks,DebouncedBatchRetriever:Go,ONTOLOGY_TYPE:qo,Writer:Ho,analyzeChannelParams:De,keyZ:_e,newPayload:Yo,ontologyID:ly,payload:er,retrieveRequired:Zo},Symbol.toStringTag,{value:"Module"})),tr=s.z.string().uuid(),dn=s.z.object({key:tr,username:s.z.string().min(1),firstName:s.z.string().default(""),lastName:s.z.string().default(""),rootUser:s.z.boolean().default(!0)}),Cy=dn.partial({key:!0,firstName:!0,lastName:!0}).omit({rootUser:!0}).extend({password:s.z.string().min(1)}),$y=s.z.object({keys:tr.array().optional(),usernames:s.z.string().array().optional()}),Ry=s.z.object({users:pe(dn)}),jy="/user/retrieve";let My=class{constructor(t){c(this,"client"),this.client=t}async retrieve(t){return(await v(this.client,jy,t,$y,Ry)).users}};const Dy=s.z.object({users:Cy.array()}),Py=s.z.object({users:dn.array()}),By=s.z.object({key:tr,username:s.z.string().min(1)}),Uy=s.z.object({}),Ly=s.z.object({key:tr,firstName:s.z.string().optional(),lastName:s.z.string().optional()}),_y=s.z.object({}),Yy=s.z.object({keys:tr.array()}),qy=s.z.object({}),Fy="/user/create",Vy="/user/change-username",Wy="/user/rename",Gy="/user/delete";let Zy=class{constructor(t){c(this,"client"),this.client=t}async create(t){return(await v(this.client,Fy,{users:T(t)},Dy,Py)).users}async changeUsername(t,e){await v(this.client,Vy,{key:t,username:e},By,Uy)}async rename(t,e,r){await v(this.client,Wy,{key:t,firstName:e,lastName:r},Ly,_y)}async delete(t){await v(this.client,Gy,{keys:T(t)},Yy,qy)}},Ky=class{constructor(t){c(this,"reader"),c(this,"writer"),this.writer=new Zy(t),this.reader=new My(t)}async create(t){const e=Array.isArray(t),r=await this.writer.create(t);return e?r:r[0]}async changeUsername(t,e){await this.writer.changeUsername(t,e)}async retrieve(t){const e=Array.isArray(t),r=await this.reader.retrieve({keys:T(t)});if(e)return r;if(r.length===0)throw new st(`No user with key ${t} found`);if(r.length>1)throw new it(`Multiple users found with key ${t}`);return r[0]}async retrieveByName(t){const e=Array.isArray(t),r=await this.reader.retrieve({usernames:T(t)});if(e)return r;if(r.length===0)throw new st(`No user with username ${t} found`);if(r.length>1)throw new it(`Multiple users found with username ${t}`);return r[0]}async rename(t,e,r){await this.writer.rename(t,e,r)}async delete(t){await this.writer.delete(t)}};const Jy=s.z.object({username:s.z.string(),password:s.z.string()}),Hy=s.z.object({token:s.z.string(),user:dn}),Wi="/auth/login",Xy=3,Qy="/auth/change-password",eg=s.z.object({username:s.z.string(),password:s.z.string(),newPassword:s.z.string().min(1)}),tg=s.z.object({});let rg=class{constructor(t,e){c(this,"token"),c(this,"client"),c(this,"credentials"),c(this,"authenticating"),c(this,"authenticated"),c(this,"user"),c(this,"retryCount"),this.client=t,this.authenticated=!1,this.credentials=e,this.retryCount=0}async changePassword(t){if(!this.authenticated)throw new Error("Not authenticated");await v(this.client,Qy,{username:this.credentials.username,password:this.credentials.password,newPassword:t},eg,tg),this.credentials.password=t}middleware(){const t=async(e,r)=>{if(!this.authenticated&&!e.target.endsWith(Wi)){this.authenticating==null&&(this.authenticating=new Promise((o,l)=>{this.client.send(Wi,this.credentials,Jy,Hy).then(([u,d])=>{if(d!=null)return o(d);this.token=u==null?void 0:u.token,this.user=u==null?void 0:u.user,this.authenticated=!0,o(null)}).catch(l)}));const a=await this.authenticating;if(a!=null)return[e,a]}e.params.Authorization=`Bearer ${this.token}`;const[n,i]=await r(e);return as.matches(i)&&this.retryCount<Xy?(this.authenticated=!1,this.authenticating=void 0,this.retryCount+=1,t(e,r)):(this.retryCount=0,[n,i])};return t}};const ng=["disconnected","connecting","connected","failed"],sg=s.z.enum(ng),ig=s.z.object({status:sg,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()}),ag=s.z.object({clusterKey:s.z.string(),nodeVersion:s.z.string().optional()}),Xo={clusterKey:"",status:"disconnected",error:void 0,message:"Disconnected",clientServerCompatible:!1,clientVersion:"0.32.0"},Gi=(t,e,r)=>{const n=r?"cluster":"client";return`Synnax cluster node version ${t!=null?t+" ":""}is too ${r?"old":"new"} for client version ${e}.
|
|
48
48
|
This may cause compatibility issues. We recommend updating the ${n}. For more information, see
|
|
49
|
-
https://docs.synnaxlabs.com/reference/typescript-client/troubleshooting#old-${n}-version`},qr=class Qo{constructor(e,r=A.seconds(30),n,i){
|
|
50
|
-
Got ${r.length} ${n}s and ${e.length} series.`)};let be=class Qe{constructor(e=[],r=[]){if(
|
|
49
|
+
https://docs.synnaxlabs.com/reference/typescript-client/troubleshooting#old-${n}-version`},qr=class Qo{constructor(e,r=A.seconds(30),n,i){c(this,"_state"),c(this,"pollFrequency",A.seconds(30)),c(this,"client"),c(this,"name"),c(this,"interval"),c(this,"clientVersion"),c(this,"onChangeHandlers",[]),c(this,"versionWarned",!1),this._state={...Xo},this.client=e,this.pollFrequency=r,this.clientVersion=n,this.name=i,this.check(),this.startChecking()}stopChecking(){this.interval!=null&&clearInterval(this.interval)}async check(){var e;const r=this._state.status;try{const[n,i]=await this.client.send(Qo.ENDPOINT,{},s.z.object({}),ag);if(i!=null)throw i;const a=n.nodeVersion,o=this.clientVersion,l=this.versionWarned;a==null?(this._state.clientServerCompatible=!1,l||(console.warn(Gi(null,o,!0)),this.versionWarned=!0)):Mi.versionsEqual(o,a,{checkMajor:!0,checkMinor:!0,checkPatch:!1})?this._state.clientServerCompatible=!0:(this._state.clientServerCompatible=!1,l||(console.warn(Gi(a,o,Mi.semVerNewer(o,a))),this.versionWarned=!0)),this._state.status="connected",this._state.message=`Connected to ${this.name??"cluster"}`,this._state.clusterKey=n.clusterKey,this._state.nodeVersion=n.nodeVersion,this._state.clientVersion=this.clientVersion}catch(n){this._state.status="failed",this._state.error=n,this._state.message=(e=this.state.error)==null?void 0:e.message}return this.onChangeHandlers.length>0&&r!==this._state.status&&this.onChangeHandlers.forEach(n=>n(this.state)),this.state}get state(){return{...this._state}}onChange(e){this.onChangeHandlers.push(e)}startChecking(){this.interval=setInterval(()=>{this.check()},this.pollFrequency.milliseconds)}};c(qr,"ENDPOINT","/connectivity/check"),c(qr,"DEFAULT",Xo),c(qr,"connectionStateZ",ig);let ec=qr;const og=s.z.object({keys:_e.array().optional(),bounds:se.z,names:s.z.string().array().optional()}),cg=s.z.object({}),lg="/frame/delete";class ug{constructor(e){c(this,"client"),this.client=e}async delete(e){await v(this.client,lg,e,og,cg)}}const Zi=t=>{const e=T(t);return e.length===0?null:typeof e[0]=="number"||!isNaN(parseInt(e[0]))?"key":"name"},Ki=(t,e)=>{const r=T(t);if(r.length===e.length)return;const n=Zi(t);throw Zi===null?new K("[Frame] - channel keys or names must be provided when constructing a frame."):new K(`[Frame] - ${n}s and series must be the same length.
|
|
50
|
+
Got ${r.length} ${n}s and ${e.length} series.`)};let be=class Qe{constructor(e=[],r=[]){if(c(this,"columns",[]),c(this,"series",[]),e instanceof Qe){this.columns=e.columns,this.series=e.series;return}if(e instanceof Map){e.forEach((n,i)=>this.push(i,...T(n)));return}if(typeof e=="object"&&!Array.isArray(e)){if("keys"in e&&"series"in e){const n=e;n.series??(n.series=[]),n.keys??(n.keys=[]);const i=n.series.map(a=>hg(a));Ki(n.keys,i),n.keys.forEach((a,o)=>this.push(a,i[o]))}else Object.entries(e).forEach(([n,i])=>{const a=parseInt(n);if(isNaN(a))this.push(n,...T(i));else return this.push(a,...T(i))});return}if(Array.isArray(e)||["string","number"].includes(typeof e)){const n=T(r),i=T(e);Ki(i,n),n.forEach((a,o)=>this.push(i[o],a));return}throw new K(`[Frame] - invalid frame construction parameters. data parameter ust be a frame
|
|
51
51
|
payload, a list of lazy series, a lazy array, a map, or a record keyed by channel
|
|
52
|
-
name. keys parameter must be a set of channel keys or channel names.`)}get colType(){return this.columns.length===0?null:typeof this.columns[0]=="string"?"name":"key"}get keys(){if(this.colType==="name")throw new we("colType is not key");return this.columns??[]}get uniqueKeys(){return Ai(this.keys)}get names(){if(this.colType==="key")throw new we("colType is not name");return this.columns??[]}get uniqueNames(){return Ai(this.names)}get uniqueColumns(){return this.colType==="key"?this.uniqueKeys:this.uniqueNames}toPayload(){return{series:this.series.map(e=>dg(e)),keys:this.keys}}get isVertical(){return this.uniqueColumns.length===this.columns.length}get isHorizontal(){return this.uniqueColumns.length===1}get isSquare(){return this.isHorizontal&&this.isVertical}get isWeaklyAligned(){if(this.columns.length<=1)return!0;const e=this.timeRanges;return e.every(r=>r.equals(e[0]))}timeRange(e){if(e==null){if(this.columns.length===0)return se.ZERO;const n=x.min(...this.series.map(a=>a.timeRange.start)),i=x.max(...this.series.map(a=>a.timeRange.end));return new se(n,i)}const r=this.get(e);return r==null?se.ZERO:r.timeRange}latest(){return this.at(-1)}get timeRanges(){return this.uniqueColumns.map(e=>this.timeRange(e))}get(e){return Array.isArray(e)?this.filter(r=>e.includes(r)):new af(this.series.filter((r,n)=>this.columns[n]===e))}push(e,...r){if(e instanceof Qe){if(this.colType!==null&&e.colType!==this.colType)throw new K("keyVariant must match");this.series.push(...e.series),this.columns.push(...e.columns)}else{if(this.series.push(...r),typeof e=="string"&&this.colType==="key")throw new K("keyVariant must match");if(typeof e!="string"&&this.colType==="name")throw new K("keyVariant must match");this.columns.push(...Array.from({length:r.length},()=>e))}}concat(e){return new Qe([...this.columns,...e.columns],[...this.series,...e.series])}has(e){return typeof e=="string"&&this.colType==="key"||typeof e=="number"&&this.colType==="name"?!1:this.columns.includes(e)}map(e){const r=new Qe;return this.forEach((n,i,a)=>r.push(...e(n,i,a))),r}forEach(e){this.columns.forEach((r,n)=>{const i=this.series[n];e(r,i,n)})}at(e,r=!1){const n={};return this.uniqueColumns.forEach(i=>{n[i]=this.get(i).at(e,r)}),n}filter(e){const r=new Qe;return this.columns.forEach((n,i)=>{const a=this.series[i];e(n,a,i)&&r.push(n,a)}),r}get byteLength(){return new qt(this.series.reduce((e,r)=>e.add(r.byteLength),qt.ZERO))}get length(){return this.series.reduce((e,r)=>e+r.length,0)}};const Cs=s.z.object({keys:s.z.union([s.z.null().transform(()=>[]),s.z.number().array().optional().default([])]),series:s.z.union([s.z.null().transform(()=>[]),Ge.crudeZ.array().optional().default([])])}),hg=t=>{const{dataType:e,data:r,timeRange:n,alignment:i}=t;return new Ge({data:r,dataType:e,timeRange:n,glBufferUsage:"static",alignment:i})},dg=t=>({timeRange:t._timeRange,dataType:t.dataType,data:new Uint8Array(t.data.buffer),alignment:t.alignment});class fn{constructor(e){
|
|
52
|
+
name. keys parameter must be a set of channel keys or channel names.`)}get colType(){return this.columns.length===0?null:typeof this.columns[0]=="string"?"name":"key"}get keys(){if(this.colType==="name")throw new we("colType is not key");return this.columns??[]}get uniqueKeys(){return Ai(this.keys)}get names(){if(this.colType==="key")throw new we("colType is not name");return this.columns??[]}get uniqueNames(){return Ai(this.names)}get uniqueColumns(){return this.colType==="key"?this.uniqueKeys:this.uniqueNames}toPayload(){return{series:this.series.map(e=>dg(e)),keys:this.keys}}get isVertical(){return this.uniqueColumns.length===this.columns.length}get isHorizontal(){return this.uniqueColumns.length===1}get isSquare(){return this.isHorizontal&&this.isVertical}get isWeaklyAligned(){if(this.columns.length<=1)return!0;const e=this.timeRanges;return e.every(r=>r.equals(e[0]))}timeRange(e){if(e==null){if(this.columns.length===0)return se.ZERO;const n=x.min(...this.series.map(a=>a.timeRange.start)),i=x.max(...this.series.map(a=>a.timeRange.end));return new se(n,i)}const r=this.get(e);return r==null?se.ZERO:r.timeRange}latest(){return this.at(-1)}get timeRanges(){return this.uniqueColumns.map(e=>this.timeRange(e))}get(e){return Array.isArray(e)?this.filter(r=>e.includes(r)):new af(this.series.filter((r,n)=>this.columns[n]===e))}push(e,...r){if(e instanceof Qe){if(this.colType!==null&&e.colType!==this.colType)throw new K("keyVariant must match");this.series.push(...e.series),this.columns.push(...e.columns)}else{if(this.series.push(...r),typeof e=="string"&&this.colType==="key")throw new K("keyVariant must match");if(typeof e!="string"&&this.colType==="name")throw new K("keyVariant must match");this.columns.push(...Array.from({length:r.length},()=>e))}}concat(e){return new Qe([...this.columns,...e.columns],[...this.series,...e.series])}has(e){return typeof e=="string"&&this.colType==="key"||typeof e=="number"&&this.colType==="name"?!1:this.columns.includes(e)}map(e){const r=new Qe;return this.forEach((n,i,a)=>r.push(...e(n,i,a))),r}forEach(e){this.columns.forEach((r,n)=>{const i=this.series[n];e(r,i,n)})}at(e,r=!1){const n={};return this.uniqueColumns.forEach(i=>{n[i]=this.get(i).at(e,r)}),n}filter(e){const r=new Qe;return this.columns.forEach((n,i)=>{const a=this.series[i];e(n,a,i)&&r.push(n,a)}),r}get byteLength(){return new qt(this.series.reduce((e,r)=>e.add(r.byteLength),qt.ZERO))}get length(){return this.series.reduce((e,r)=>e+r.length,0)}};const Cs=s.z.object({keys:s.z.union([s.z.null().transform(()=>[]),s.z.number().array().optional().default([])]),series:s.z.union([s.z.null().transform(()=>[]),Ge.crudeZ.array().optional().default([])])}),hg=t=>{const{dataType:e,data:r,timeRange:n,alignment:i}=t;return new Ge({data:r,dataType:e,timeRange:n,glBufferUsage:"static",alignment:i})},dg=t=>({timeRange:t._timeRange,dataType:t.dataType,data:new Uint8Array(t.data.buffer),alignment:t.alignment});class fn{constructor(e){c(this,"adapter"),c(this,"retriever"),c(this,"keys"),this.retriever=e,this.adapter=null,this.keys=[]}static async open(e,r){const n=new fn(e);return await n.update(r),n}async update(e){const{variant:r,normalized:n}=De(e);if(r==="keys"){this.adapter=null,this.keys=n;return}const i=await this.retriever.retrieve(n),a=new Map;this.adapter=a,n.forEach(o=>{const l=i.find(u=>u.name===o);if(l==null)throw new Error(`Channel ${o} not found`);a.set(l.key,l.name)}),this.keys=Array.from(this.adapter.keys())}adapt(e){if(this.adapter==null)return e;const r=this.adapter;return e.map((n,i)=>{if(typeof n=="number"){const a=r.get(n);if(a==null)throw new Error(`Channel ${n} not found`);return[a,i]}return[n,i]})}}class $s{constructor(e){c(this,"adapter"),c(this,"retriever"),c(this,"keys"),this.retriever=e,this.adapter=null,this.keys=[]}static async open(e,r){const n=new $s(e);return await n.update(r),n}async adaptObjectKeys(e){const r={};for(const[n,i]of Object.entries(e))r[await this.adaptToKey(n)]=i;return r}async update(e){const r=await Zo(this.retriever,e);this.adapter=new Map(r.map(n=>[n.name,n.key])),this.keys=r.map(n=>n.key)}async fetchChannel(e){const r=await this.retriever.retrieve(e);if(r.length===0)throw new Error(`Channel ${e} not found`);return r[0]}async adaptToKey(e){return typeof e=="number"?e:(await this.fetchChannel(e)).key}async adapt(e,r){if(typeof e=="string"||typeof e=="number"){if(r==null)throw new K(`
|
|
53
53
|
Received a single channel name or key but no series.
|
|
54
|
-
`);if(Array.isArray(r)){if(r.some(
|
|
54
|
+
`);if(Array.isArray(r)){if(r.some(u=>u instanceof Ge||Array.isArray(u)))throw new K(`
|
|
55
55
|
Received a single channel name or key but multiple series.
|
|
56
|
-
`);r=r}const o=await this.fetchChannel(e),
|
|
56
|
+
`);r=r}const o=await this.fetchChannel(e),l=new Ge({data:r,dataType:o.dataType});return new be(o.key,l)}if(Array.isArray(e)){if(r==null)throw new K(`
|
|
57
57
|
Received an array of channel names or keys but no series.
|
|
58
58
|
`);if(!Array.isArray(r))throw new K(`
|
|
59
59
|
Received an array of channel names or keys but no array of series.
|
|
60
|
-
`);const o=[],
|
|
60
|
+
`);const o=[],l=[];for(let u=0;u<e.length;u++){const d=await this.fetchChannel(e[u]);if(u>=r.length)throw new K(`
|
|
61
61
|
Received an array of channel names or keys but not enough series.
|
|
62
|
-
`);const f=new Ge({data:r[
|
|
63
|
-
Channel ${
|
|
64
|
-
`);return f}),new be(
|
|
65
|
-
Please report this error to the Synnax team. ${JSON.stringify(e)}`),r!=null){if(Ue.matches(r))return;throw r}}}closeSend(){this.stream.closeSend()}send(e){const r=this.stream.send(e);if(r!=null)throw r}}const Ji=new A(-1);var js=(t=>(t[t.Open=0]="Open",t[t.Next=1]="Next",t[t.Prev=2]="Prev",t[t.SeekFirst=3]="SeekFirst",t[t.SeekLast=4]="SeekLast",t[t.SeekLE=5]="SeekLE",t[t.SeekGE=6]="SeekGE",t[t.Valid=7]="Valid",t[t.Error=8]="Error",t))(js||{}),tc=(t=>(t[t.None=0]="None",t[t.Ack=1]="Ack",t[t.Data=2]="Data",t))(tc||{});const fg=s.z.object({command:s.z.nativeEnum(js),span:A.z.optional(),bounds:se.z.optional(),stamp:x.z.optional(),keys:s.z.number().array().optional(),chunkSize:s.z.number().optional()}),yg=s.z.object({variant:s.z.nativeEnum(tc),ack:s.z.boolean(),command:s.z.nativeEnum(js),error:Xt.optional().nullable(),frame:Cs.optional()}),rc=class os{constructor(e,r){l(this,"stream"),l(this,"adapter"),l(this,"value"),this.stream=new Rs("Iterator",e),this.value=new be,this.adapter=r}static async _open(e,r,n,i,a={}){const o=await fn.open(n,r),u=await i.stream(os.ENDPOINT,fg,yg),c=new os(u,o);return await c.execute({command:0,keys:o.keys,bounds:new se(e),chunkSize:a.chunkSize??1e5}),c}async next(e=Ji){return await this.execute({command:1,span:new A(e)})}async prev(e=Ji){return await this.execute({command:2,span:new A(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 x(e)})}async seekGE(e){return await this.execute({command:6,stamp:new x(e)})}async valid(){return await this.execute({command:7})}async close(){await this.stream.closeAndAck()}[Symbol.asyncIterator](){return new pg(this)}async execute(e){for(this.stream.send(e),this.value=new be;;){const r=await this.stream.receive();if(r.variant===1)return r.ack;this.value.push(this.adapter.adapt(new be(r.frame)))}}};l(rc,"ENDPOINT","/frame/iterate");let gg=rc;class pg{constructor(e){l(this,"iter"),l(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 mg=s.z.object({keys:s.z.number().array(),downsampleFactor:s.z.number()}),wg=s.z.object({frame:Cs,error:Xt.optional().nullable()}),bg="/frame/stream";class Ms{constructor(e,r){l(this,"stream"),l(this,"adapter"),l(this,"downsampleFactor"),this.stream=new Rs("Streamer",e),this.adapter=r,this.downsampleFactor=1}get keys(){return this.adapter.keys}static async _open(e,r,{channels:n,downsampleFactor:i}){const a=await fn.open(e,n),o=await r.stream(bg,mg,wg),u=new Ms(o,a);o.send({keys:a.keys,downsampleFactor:i??1});const[,c]=await o.receive();if(c!=null)throw c;return u}async next(){try{return{done:!1,value:await this.read()}}catch(e){if(Ue.matches(e))return{done:!0,value:void 0};throw e}}async read(){return this.adapter.adapt(new be((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 yn extends Je.Observer{constructor(e,r){super(r),l(this,"streamer"),l(this,"closePromise"),this.streamer=e,this.closePromise=this.stream()}async close(){this.streamer.close(),await this.closePromise}async stream(){for await(const e of this.streamer)this.notify(e)}}var Ds=(t=>(t[t.Open=0]="Open",t[t.Write=1]="Write",t[t.Commit=2]="Commit",t[t.Error=3]="Error",t[t.SetAuthority=4]="SetAuthority",t))(Ds||{}),Ft=(t=>(t[t.PersistStream=1]="PersistStream",t[t.Persist=2]="Persist",t[t.Stream=3]="Stream",t))(Ft||{});const vg=t=>{switch(t){case"persist":return 2;case"stream":return 3;case"persistStream":return 1;default:if(typeof t=="number"&&t in Ft)return t;throw new Error(`invalid writer mode: ${t}`)}};new A(-1);const Og=s.z.object({start:x.z.optional(),controlSubject:nt.subjectZ.optional(),keys:s.z.number().array().optional(),authorities:nt.Authority.z.array().optional(),mode:s.z.nativeEnum(Ft).optional(),errOnUnauthorized:s.z.boolean().optional(),enableAutoCommit:s.z.boolean().optional(),autoIndexPersistInterval:A.z.optional()}),Tg=s.z.object({command:s.z.nativeEnum(Ds),config:Og.optional(),frame:Cs.optional()}),Sg=s.z.object({ack:s.z.boolean(),command:s.z.nativeEnum(Ds),error:Xt.optional().nullable()});var yt;let zg=(yt=class{constructor(t,e){l(this,"stream"),l(this,"adapter"),this.stream=new Rs("Writer",t),this.adapter=e}static async _open(t,e,{channels:r,start:n=x.now(),authorities:i=nt.Authority.Absolute,controlSubject:a,mode:o=1,errOnUnauthorized:u=!1,enableAutoCommit:c=!1,autoIndexPersistInterval:d=A.SECOND}){const f=await $s.open(t,r),h=await e.stream(yt.ENDPOINT,Tg,Sg),E=new yt(h,f);return await E.execute({command:0,config:{start:new x(n),keys:f.keys,controlSubject:a,authorities:T(i),mode:vg(o),errOnUnauthorized:u,enableAutoCommit:c,autoIndexPersistInterval:d}}),E}async write(t,e){const r=await this.adapter.adapt(t,e);return this.stream.send({command:1,frame:r.toPayload()}),!0}async setAuthority(t,e){let r={keys:[],authorities:[]};if(typeof t=="number"&&e==null)r={keys:[],authorities:[t]};else{let n;typeof t=="string"||typeof t=="number"?n={[t]:e}:n=t,n=await this.adapter.adaptObjectKeys(n),r={keys:Object.keys(n).map(i=>Number(i)),authorities:Object.values(n)}}return(await this.execute({command:4,config:r})).ack}async commit(){return this.errorAccumulated?!1:(await this.execute({command:2})).ack}async error(){this.stream.send({command:3});const t=await this.execute({command:3});return t.error!=null?Ts(t.error):null}async close(){await this.stream.closeAndAck()}async execute(t){for(this.stream.send(t);;){const e=await this.stream.receive();if(e.command===t.command)return e;console.warn("writer received unexpected response",e)}}get errorAccumulated(){return this.stream.received()}},l(yt,"ENDPOINT","/frame/write"),yt),Ng=class{constructor(t,e,r){l(this,"streamClient"),l(this,"retriever"),l(this,"deleter"),this.streamClient=t,this.retriever=r,this.deleter=new ug(e)}async openIterator(t,e,r){return await gg._open(t,e,this.retriever,this.streamClient,r)}async openWriter(t){return(Array.isArray(t)||typeof t!="object")&&(t={channels:t}),await zg._open(this.retriever,this.streamClient,t)}async openStreamer(t){return(Array.isArray(t)||typeof t!="object")&&(t={channels:t,downsampleFactor:1}),await Ms._open(this.retriever,this.streamClient,t)}async write(t,e,r){if(r==null){const i=e,a=await this.openWriter({start:t,channels:Object.keys(i),mode:Ft.Persist});try{await a.write(i),await a.commit()}finally{await a.close()}return}const n=await this.openWriter({start:t,channels:e,mode:Ft.Persist,errOnUnauthorized:!0,enableAutoCommit:!0,autoIndexPersistInterval:A.MAX});try{await n.write(e,r)}finally{await n.close()}}async read(t,e){const{single:r}=De(e),n=await this.readFrame(t,e);return r?n.get(e):n}async readFrame(t,e){const r=await this.openIterator(t,e),n=new be;try{for await(const i of r)n.push(i)}finally{await r.close()}return n}async delete(t,e){const{normalized:r,variant:n}=De(t);return n==="keys"?await this.deleter.delete({keys:r,bounds:e}):await this.deleter.delete({names:r,bounds:e})}};const Eg=nt.Authority,Ig=nt.stateZ(s.z.number()),Ag=t=>{var e,r;return t.to==null?`${(e=t.from)==null?void 0:e.resource} - ${(r=t.from)==null?void 0:r.subject.name} -> released`:t.from==null?`${t.to.resource} - released -> ${t.to.subject.name} (${t.to.authority.toString()})`:`${t.to.resource} - ${t.from.subject.name} -> ${t.to.subject.name} (${t.to.authority.toString()})`};class nc extends yn{constructor(e){super(e,r=>{const n=this.codec.decode(r.series[0].buffer);return this.merge(n),[n.transfers,!0]}),l(this,"states"),l(this,"codec"),this.states=new Map,this.codec=new ot.JSONCodec}subjects(){const e=new Map;return this.states.forEach(r=>e.set(r.subject.key,r.subject)),Array.from(e.values())}merge(e){e.transfers.forEach(r=>{r.from==null&&r.to==null&&console.warn("Invalid transfer: ",r),r.to==null?this.states.delete(r.from.resource):this.states.set(r.to.resource,r.to)})}}const kg="sy_node_1_control";let sc=class{constructor(t){l(this,"framer"),this.framer=t}async openStateTracker(){const t=await this.framer.openStreamer(kg);return new nc(t)}};const xg=Object.freeze(Object.defineProperty({__proto__:null,Authority:Eg,Client:sc,StateTracker:nc,stateZ:Ig,transferString:Ag},Symbol.toStringTag,{value:"Module"}));let Cg=class{constructor(t,e,r){l(this,"tasks"),l(this,"racks"),l(this,"devices"),this.tasks=t,this.racks=e,this.devices=r}};const rr=s.z.number(),Ps=s.z.object({key:rr,name:s.z.string()}),$g=Ps.partial({key:!0}),Bs=s.z.string(),gn=s.z.object({key:Bs,rack:rr,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(t=>t===""?{}:ot.JSON_CODEC.decodeString(t)))}),Rg=gn.extend({properties:s.z.unknown().transform(t=>ot.JSON_CODEC.encodeString(t))}),ct=async(t,e,r,n)=>{const i=await t.openStreamer([e,r]),a=o=>{const u=[];return r!=null&&u.push(...o.get(r).series.flatMap(c=>n("delete",c))),e!=null&&u.push(...o.get(e).series.flatMap(c=>n("set",c))),[u,u.length>0]};return new yn(i,a)},jg="sy_device_set",Mg="sy_device_delete",jn="/hardware/device/retrieve",Dg="/hardware/device/create",Pg="/hardware/device/delete",Bg=s.z.object({devices:Rg.array()}),Ug=s.z.object({devices:gn.array()}),Lg=s.z.object({keys:Bs.array()}),_g=s.z.object({}),Mn=s.z.object({search:s.z.string().optional(),limit:s.z.number().optional(),offset:s.z.number().optional(),keys:Bs.array().optional(),names:s.z.string().array().optional(),makes:s.z.string().array().optional()}),Dn=s.z.object({devices:pe(gn)});let Yg=class{constructor(t,e){l(this,"type","device"),l(this,"client"),l(this,"frameClient"),this.client=t,this.frameClient=e}async retrieve(t,e){const r=!Array.isArray(t),n=await v(this.client,jn,{keys:T(t),...e},Mn,Dn);return hn("Device",t,n.devices,r),r?n.devices[0]:n.devices}async search(t,e){return(await v(this.client,jn,{search:t,...e},Mn,Dn)).devices}async page(t,e,r){return(await v(this.client,jn,{offset:t,limit:e,...r},Mn,Dn)).devices}async create(t){const e=!Array.isArray(t),r=await v(this.client,Dg,{devices:T(t)},Bg,Ug);return e?r.devices[0]:r.devices}async delete(t){await v(this.client,Pg,{keys:T(t)},Lg,_g)}async openDeviceTracker(){return await ct(this.frameClient,jg,Mg,qg)}newSearcherWithOptions(t){return{type:this.type,search:async e=>await this.search(e,t),retrieve:async e=>await this.retrieve(e,t),page:async(e,r)=>await this.page(e,r,t)}}};const qg=(t,e)=>t==="delete"?e.toStrings().map(r=>({variant:t,key:r,value:void 0})):e.parseJSON(gn).map(r=>({variant:t,key:r.key,value:r})),Pn="/hardware/rack/retrieve",Fg="/hardware/rack/create",Vg="/hardware/rack/delete",Bn=s.z.object({keys:rr.array().optional(),names:s.z.string().array().optional(),search:s.z.string().optional(),offset:s.z.number().optional(),limit:s.z.number().optional()}),Un=s.z.object({racks:pe(Ps)}),Wg=s.z.object({racks:$g.array()}),Gg=s.z.object({racks:Ps.array()}),Zg=s.z.object({keys:rr.array()}),Kg=s.z.object({});let Jg=class{constructor(t,e,r){l(this,"type","rack"),l(this,"client"),l(this,"frameClient"),l(this,"tasks"),this.client=t,this.frameClient=e,this.tasks=r}async delete(t){await v(this.client,Vg,{keys:T(t)},Zg,Kg)}async create(t){const e=!Array.isArray(t),r=await v(this.client,Fg,{racks:T(t)},Wg,Gg),n=this.sugar(r.racks);return e?n[0]:n}async search(t){const e=await v(this.client,Pn,{search:t},Bn,Un);return this.sugar(e.racks)}async page(t,e){const r=await v(this.client,Pn,{offset:t,limit:e},Bn,Un);return this.sugar(r.racks)}async retrieve(t){const{variant:e,normalized:r,single:n}=un(t,{string:"names",number:"keys"}),i=await v(this.client,Pn,{[e]:r},Bn,Un),a=this.sugar(i.racks);return hn("Rack",t,a,n),n?a[0]:a}sugar(t){return t.map(({key:e,name:r})=>new Hg(e,r,this.tasks))}};class Hg{constructor(e,r,n){l(this,"key"),l(this,"name"),l(this,"tasks"),this.key=e,this.name=r,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 lt=s.z.union([s.z.string(),s.z.bigint().transform(t=>t.toString()),s.z.number().transform(t=>t.toString())]),Hr=s.z.object({task:lt,variant:s.z.string(),key:s.z.string().optional(),details:s.z.record(s.z.unknown()).or(s.z.string().transform(t=>t===""?{}:JSON.parse(t))).or(s.z.array(s.z.unknown())).or(s.z.null())}),pn=s.z.object({key:lt,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(t=>t===""?{}:ot.JSON_CODEC.decodeString(t))),state:Hr.optional().nullable(),snapshot:s.z.boolean().optional()}),Xg=pn.omit({key:!0}).extend({key:lt.transform(t=>t.toString()).optional(),config:s.z.unknown().transform(t=>ot.JSON_CODEC.encodeString(t))});s.z.object({task:lt,type:s.z.string(),key:s.z.string(),args:s.z.record(s.z.unknown()).or(s.z.string().transform(t=>t===""?{}:JSON.parse(t)))});const _t="sy_task_state",Hi="sy_task_cmd",ur=new Error("Task not created");class Qg{constructor(e,r,n,i,a=!1,o=!1,u,c=null,d=null,f=null){l(this,"key"),l(this,"name"),l(this,"internal"),l(this,"type"),l(this,"config"),l(this,"snapshot"),l(this,"state"),l(this,"frameClient"),l(this,"ontologyClient"),l(this,"rangeClient"),this.key=e,this.name=r,this.type=n,this.config=i,this.internal=a,this.snapshot=o,u!==null&&(this.state=u),this.frameClient=c,this.ontologyClient=d,this.rangeClient=f}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 k({type:"task",key:this.key})}async executeCommand(e,r){if(this.frameClient==null)throw ur;const n=await this.frameClient.openWriter(Hi),i=Jd.id();return await n.write(Hi,[{task:this.key,type:e,key:i,args:r}]),await n.close(),i}async executeCommandSync(e,r,n){if(this.frameClient==null)throw ur;const i=await this.frameClient.openStreamer(_t),a=await this.executeCommand(e,r);let o;const u=new Promise(c=>setTimeout(()=>c(!1),new A(n).milliseconds));for(;;){const c=await Promise.any([i.read(),u]);if(c===!1)throw new Error("Command timed out");const d=Hr.safeParse(c.at(-1).sy_task_state);if(d.success){if(o=d.data,o.key===a)break}else console.error(d.error)}return i.close(),o}async openStateObserver(){if(this.frameClient==null)throw ur;return new yn(await this.frameClient.openStreamer(_t),e=>{const r=e.get(_t);if(r.length===0)return[null,!1];const n=Hr.safeParse(r.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 ur;if(!this.snapshot)return null;const e=await this.ontologyClient.retrieveParents(this.ontologyID);return e.length==0?null:e[0]}}const ep=s.z.object({rack:rr.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()}),tp=s.z.object({tasks:pe(pn)}),rp="/hardware/task/retrieve",np="/hardware/task/create",sp="/hardware/task/delete",ip="/hardware/task/copy",ap=s.z.object({tasks:Xg.array()}),op=s.z.object({tasks:pn.array()}),cp=s.z.object({keys:lt.array()}),lp=s.z.object({}),up=s.z.object({key:lt,name:s.z.string(),snapshot:s.z.boolean()}),hp=s.z.object({task:pn});let dp=class{constructor(t,e,r,n){l(this,"type","task"),l(this,"client"),l(this,"frameClient"),l(this,"ontologyClient"),l(this,"rangeClient"),this.client=t,this.frameClient=e,this.ontologyClient=r,this.rangeClient=n}async create(t){const e=!Array.isArray(t),r=await v(this.client,np,{tasks:T(t)},ap,op),n=this.sugar(r.tasks);return e?n[0]:n}async delete(t){await v(this.client,sp,{keys:T(t)},cp,lp)}async search(t){return await this.execRetrieve({keys:[t]})}async page(t,e){return await this.execRetrieve({offset:t,limit:e})}async list(t={}){return this.sugar(await this.execRetrieve(t))}async retrieve(t,e){const{single:r,normalized:n,variant:i}=un(t,{number:"rack",string:"keys"},{convertNumericStrings:!1}),a={...e};i==="rack"?a.rack=t:a.keys=n;const o=await this.execRetrieve(a),u=this.sugar(o);return r&&i!=="rack"?u[0]:u}async copy(t,e,r){const n=await v(this.client,ip,{key:t,name:e,snapshot:r},up,hp);return this.sugar([n.task])[0]}async retrieveByName(t,e){const r=await this.execRetrieve({names:[t],rack:e});return hn("Task",t,r,!0),this.sugar(r)[0]}async execRetrieve(t){return(await v(this.client,rp,t,ep,tp)).tasks}sugar(t){return t.map(({key:e,name:r,type:n,config:i,state:a,internal:o,snapshot:u})=>new Qg(e,r,n,i,o,u,a,this.frameClient,this.ontologyClient,this.rangeClient))}async openTracker(){return await ct(this.frameClient,"sy_task_set","sy_task_delete",(t,e)=>Array.from(e).map(r=>({variant:t,key:r.toString(),value:r.toString()})))}async openStateObserver(){return new yn(await this.frameClient.openStreamer(_t),t=>{const e=t.get(_t);if(e.length===0)return[null,!1];const r=Hr.safeParse(e.at(-1));return r.success?[r.data,!0]:[null,!1]})}};const nr=s.z.string().uuid(),mn=s.z.object({key:nr,name:s.z.string().min(1),color:s.z.string()}),fp=s.z.object({keys:nr.array().optional(),for:ye.optional(),search:s.z.string().optional(),offset:s.z.number().optional(),limit:s.z.number().optional()}),yp=s.z.object({labels:pe(mn)});var hr;let gp=(hr=class{constructor(t){l(this,"client"),this.client=t}async retrieve(t){const e=T(t);return await this.execute({keys:e})}async retrieveFor(t){return await this.execute({for:t})}async search(t){return await this.execute({search:t})}async page(t,e){return await this.execute({offset:t,limit:e})}async execute(t){const[e,r]=await this.client.send(hr.ENDPOINT,t,fp,yp);if(r!=null)throw r;return e.labels}},l(hr,"ENDPOINT","/label/retrieve"),hr);const pp=mn.extend({key:nr.optional()}),mp=s.z.object({labels:pp.array()}),wp=s.z.object({labels:mn.array()}),bp=s.z.object({keys:nr.array()}),ic=s.z.object({id:ye,labels:nr.array(),replace:s.z.boolean().optional()}),vp=ic.omit({replace:!0}),Ln=s.z.object({}),Op="/label/create",Tp="/label/delete",Sp="/label/set",zp="/label/remove";let Np=class{constructor(t){l(this,"client"),this.client=t}async create(t){return(await v(this.client,Op,{labels:T(t)},mp,wp)).labels}async delete(t){await v(this.client,Tp,{keys:T(t)},bp,Ln)}async set(t,e,{replace:r}={}){await v(this.client,Sp,{id:t,labels:e,replace:r},ic,Ln)}async remove(t,e){await v(this.client,zp,{id:t,labels:e},vp,Ln)}};const Ep="sy_label_set",Ip="sy_label_delete";let Ap=class{constructor(t,e,r){l(this,"type","label"),l(this,"retriever"),l(this,"writer"),l(this,"frameClient"),l(this,"ontology"),this.writer=new Np(t),this.retriever=new gp(t),this.frameClient=e,this.ontology=r}async search(t){return await this.retriever.search(t)}async retrieve(t){const e=Array.isArray(t),r=await this.retriever.retrieve(t);return e?r:r[0]}async retrieveFor(t){return await this.retriever.retrieveFor(new k(t))}async label(t,e,r={}){await this.writer.set(new k(t),e,r)}async removeLabels(t,e){await this.writer.remove(new k(t),e)}async page(t,e){return await this.retriever.page(t,e)}async create(t){const e=Array.isArray(t),r=await this.writer.create(t);return e?r:r[0]}async delete(t){await this.writer.delete(t)}async openChangeTracker(){return await ct(this.frameClient,Ep,Ip,kp)}async trackLabelsOf(t){const e=new Je.Observer,r=(await this.retrieveFor(t)).map(n=>({id:new k({key:n.key,type:"label"}),key:n.key,name:n.name,data:n}));return(await this.ontology.openDependentTracker({target:new k(t),dependents:r,relationshipType:"labeled_by"})).onChange(n=>e.notify(n.map(i=>{var a,o;return{key:i.id.key,color:(a=i.data)==null?void 0:a.color,name:(o=i.data)==null?void 0:o.name}}))),e}};const kp=(t,e)=>t==="delete"?e.toUUIDs().map(r=>({variant:t,key:r})):e.parseJSON(mn).map(r=>({variant:t,key:r.key,value:r})),fe=s.z.string().uuid(),sr=s.z.object({key:fe,name:s.z.string().min(1),timeRange:se.z,color:s.z.string().optional()}),ac=sr.extend({key:s.z.string().uuid().optional()}),oc=t=>{const e=T(t),r=e.length===0;let n=!1;return r||(n=fe.safeParse(e[0]).success),{single:!Array.isArray(t),variant:n?"keys":"names",normalized:e,actual:t,empty:r}},cc="range",lc="range-alias",xp=t=>new k({type:cc,key:t}),Cp=t=>new k({type:lc,key:t}),$p="sy_range_alias_set",Rp="sy_range_alias_delete",jp=s.z.object({range:fe,aliases:s.z.string().array()}),Mp=s.z.object({aliases:s.z.record(s.z.string(),_e)}),Dp=s.z.object({range:fe,aliases:s.z.record(_e.or(s.z.string()),s.z.string())}),Pp=s.z.unknown(),Bp=s.z.object({range:fe,channels:_e.array()}),Up=s.z.unknown(),Lp=s.z.object({range:fe}),_p=s.z.object({aliases:s.z.record(s.z.string(),s.z.string())}),Rt=class jt{constructor(e,r,n){l(this,"frameClient"),l(this,"cache",new Map),l(this,"client"),l(this,"rangeKey"),this.rangeKey=e,this.cache=new Map,this.client=n,this.frameClient=r}async resolve(e){const r=[],n=typeof e=="string",i={};if(n){const o=this.cache.get(e);if(o!=null)return o;r.push(e)}else e.forEach(o=>{const u=this.cache.get(o);u!=null?i[o]=u:r.push(o)});if(r.length===0)return i;const a=await v(this.client,jt.RESOLVE_ENDPOINT,{range:this.rangeKey,aliases:r},jp,Mp);return Object.entries(a.aliases).forEach(([o,u])=>this.cache.set(o,u)),n?a.aliases[r[0]]:{...i,...a.aliases}}async set(e){await v(this.client,jt.SET_ENDPOINT,{range:this.rangeKey,aliases:e},Dp,Pp)}async list(){return(await v(this.client,jt.LIST_ENDPOINT,{range:this.rangeKey},Lp,_p)).aliases}async delete(e){await v(this.client,jt.DELETE_ENDPOINT,{range:this.rangeKey,channels:e},Bp,Up)}async openChangeTracker(){return await ct(this.frameClient,$p,Rp,Vp(this.rangeKey))}};l(Rt,"SET_ENDPOINT","/range/alias/set"),l(Rt,"RESOLVE_ENDPOINT","/range/alias/resolve"),l(Rt,"LIST_ENDPOINT","/range/alias/list"),l(Rt,"DELETE_ENDPOINT","/range/alias/delete");let Yp=Rt;const qp=s.z.object({range:fe,channel:_e,alias:s.z.string()}),Fp="---",Vp=t=>(e,r)=>e==="delete"?r.toStrings().filter(n=>n.split(Fp)[0]===t).map(n=>({variant:e,key:n,value:void 0})):r.parseJSON(qp).map(n=>({variant:e,key:n.alias,value:n})),Wp=s.z.object({range:fe,keys:s.z.string().array()}),Us=s.z.object({range:fe,key:s.z.string(),value:s.z.string()}),Gp=s.z.object({pairs:pe(Us)}),Zp=s.z.object({range:fe,pairs:Us.array()}),Kp=s.z.object({range:fe,keys:s.z.string().array()}),Fr=class Vr{constructor(e,r,n){l(this,"rangeKey"),l(this,"client"),l(this,"frameClient"),this.rangeKey=e,this.client=r,this.frameClient=n}async get(e){const r=await v(this.client,Vr.GET_ENDPOINT,{range:this.rangeKey,keys:T(e)},Wp,Gp);return typeof e=="string"?r.pairs[0].value:Object.fromEntries(r.pairs.map(n=>[n.key,n.value]))}async list(){return this.get([])}async set(e,r=""){let n;Ss(e)?n=Object.entries(e).map(([i,a])=>({range:this.rangeKey,key:i,value:a})):n=[{range:this.rangeKey,key:e,value:r}],await v(this.client,Vr.SET_ENDPOINT,{range:this.rangeKey,pairs:n},Zp,s.z.unknown())}async delete(e){await v(this.client,Vr.DELETE_ENDPOINT,{range:this.rangeKey,keys:T(e)},Kp,s.z.unknown())}async openTracker(){return await ct(this.frameClient,"sy_range_kv_set","sy_range_kv_delete",(e,r)=>e==="delete"?r.toStrings().map(n=>{const[i,a]=n.split("<--->",2);return{variant:e,key:n,value:{range:i,key:a,value:""}}}):r.parseJSON(Us).map(n=>({variant:e,key:`${n.range}${n.key}`,value:n})))}};l(Fr,"GET_ENDPOINT","/range/kv/get"),l(Fr,"SET_ENDPOINT","/range/kv/set"),l(Fr,"DELETE_ENDPOINT","/range/kv/delete");let cs=Fr;const _n=t=>new k({type:"range",key:t});class uc{constructor(e,r=se.ZERO,n,i,a,o,u,c,d,f,h){l(this,"key"),l(this,"name"),l(this,"kv"),l(this,"timeRange"),l(this,"color"),l(this,"channels"),l(this,"aliaser"),l(this,"frameClient"),l(this,"labelClient"),l(this,"ontologyClient"),l(this,"rangeClient"),this.key=n,this.name=e,this.timeRange=r,this.frameClient=a,this.color=i,this.kv=o,this.aliaser=u,this.channels=c,this.labelClient=d,this.ontologyClient=f,this.rangeClient=h}get ontologyID(){return new k({key:this.key,type:"range"})}get payload(){return{key:this.key,name:this.name,timeRange:this.timeRange,color:this.color}}async setAlias(e,r){const n=await this.channels.retrieve(e);if(n.length===0)throw new ve(`Channel ${e} does not exist`);await this.aliaser.set({[n[0].key]:r})}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(r=>r.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(_n(this.key))}async addLabel(...e){await this.labelClient.label(_n(this.key),e)}async removeLabel(...e){await this.labelClient.removeLabels(_n(this.key),e)}async openChildRangeTracker(){const e=new Je.Observer,r=(await this.retrieveChildren()).map(i=>{const a=new k({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:r,resourceType:"range"});return n.onChange(i=>e.notify(this.rangeClient.resourcesToRanges(i))),e.setCloser(async()=>await n.close()),e}async openParentRangeTracker(){const e=new Je.Observer,r=await this.retrieveParent();if(r==null)return null;const n=new k({key:r.key,type:"range"}),i={id:n,key:n.toString(),name:r.name,data:r.payload},a=await this.ontologyClient.openDependentTracker({target:this.ontologyID,dependents:[i],relationshipDirection:"to"});return a.onChange(o=>{const u=this.rangeClient.resourcesToRanges(o);if(u.length===0)return;const c=u[0];e.notify(c)}),e.setCloser(async()=>await a.close()),e}}const Jp=s.z.object({keys:fe.array().optional(),names:s.z.array(s.z.string()).optional(),term:s.z.string().optional(),overlapsWith:se.z.optional(),limit:s.z.number().int().optional(),offset:s.z.number().int().optional()}),Hp="/range/retrieve",Xp=s.z.object({ranges:pe(sr)});let hc=class{constructor(t,e,r,n,i,a){l(this,"type","range"),l(this,"frameClient"),l(this,"writer"),l(this,"unaryClient"),l(this,"channels"),l(this,"labelClient"),l(this,"ontologyClient"),this.frameClient=t,this.writer=e,this.unaryClient=r,this.channels=n,this.labelClient=i,this.ontologyClient=a}async create(t,e){const r=!Array.isArray(t),n=this.sugarMany(await this.writer.create(T(t),e));return r?n[0]:n}async rename(t,e){await this.writer.rename(t,e)}async delete(t){await this.writer.delete(T(t))}async search(t){return this.sugarMany(await this.execRetrieve({term:t}))}async page(t,e){return this.sugarMany(await this.execRetrieve({offset:t,limit:e}))}async retrieve(t){if(typeof t=="object"&&"start"in t)return await this.execRetrieve({overlapsWith:new se(t)});const{single:e,actual:r,variant:n,normalized:i,empty:a}=oc(t);if(a)return[];const o=await this.execRetrieve({[n]:i});if(!e)return o;if(o.length===0)throw new st(`range matching ${r} not found`);if(o.length>1)throw new it(`multiple ranges matching ${r} found`);return o[0]}getKV(t){return new cs(t,this.unaryClient,this.frameClient)}async execRetrieve(t){const{ranges:e}=await v(this.unaryClient,Hp,t,Jp,Xp);return this.sugarMany(e)}async retrieveParent(t){const e=await this.ontologyClient.retrieveParents({key:t,type:"range"});if(e.length===0)return null;const r=e[0];return r.id.type!=="range"?null:await this.retrieve(r.id.key)}sugarOne(t){return new uc(t.name,t.timeRange,t.key,t.color,this.frameClient,new cs(t.key,this.unaryClient,this.frameClient),new Yp(t.key,this.frameClient,this.unaryClient),this.channels,this.labelClient,this.ontologyClient,this)}sugarMany(t){return t.map(e=>this.sugarOne(e))}async openTracker(){return await ct(this.frameClient,"sy_range_set","sy_range_delete",(t,e)=>t==="delete"?e.toStrings().map(r=>({variant:t,key:r,value:void 0})):this.sugarMany(e.parseJSON(sr)).map(r=>({variant:t,key:r.key,value:r})))}resourcesToRanges(t){return t.map(e=>this.resourceToRange(e))}resourceToRange(t){var e,r,n;return this.sugarOne({key:t.id.key,name:(e=t.data)==null?void 0:e.name,timeRange:new se((r=t.data)==null?void 0:r.timeRange),color:(n=t.data)==null?void 0:n.color})}};const Qp=s.z.object({ranges:sr.array()}),em=s.z.object({parent:ye.optional(),ranges:ac.array()}),tm=s.z.object({keys:fe.array()}),rm=s.z.object({}),nm=s.z.object({key:fe,name:s.z.string()}),sm=s.z.object({}),im="/range/create",am="/range/delete",om="/range/rename";let dc=class{constructor(t){l(this,"client"),this.client=t}async rename(t,e){await v(this.client,om,{key:t,name:e},nm,sm)}async create(t,e){return(await v(this.client,im,{ranges:t,...e},em,Qp)).ranges}async delete(t){await v(this.client,am,{keys:t},tm,rm)}};const cm=Object.freeze(Object.defineProperty({__proto__:null,ALIAS_ONTOLOGY_TYPE:lc,Client:hc,KV:cs,ONTOLOGY_TYPE:cc,Range:uc,Writer:dc,analyzeParams:oc,keyZ:fe,newPayloadZ:ac,payloadZ:sr,rangeAliasOntologyID:Cp,rangeOntologyID:xp},Symbol.toStringTag,{value:"Module"})),lm="/api/v1/";class um{constructor(e,r=!1){l(this,"url"),l(this,"unary"),l(this,"stream"),l(this,"secure"),this.secure=r,this.url=e.child(lm);const n=new ot.JSONCodec;this.unary=new Wh(this.url,n,this.secure),this.stream=new td(this.url,n,this.secure)}use(...e){this.unary.use(...e),this.stream.use(...e)}}const Ls=s.z.string().uuid(),_s=s.z.object({key:s.z.string(),name:s.z.string(),data:Es.or(s.z.string().transform(t=>JSON.parse(t)))}),hm=s.z.object({keys:s.z.string().array()}),dm=s.z.object({linePlots:_s.array()});let fm=class{constructor(t){l(this,"ENDPOINT","/workspace/lineplot/retrieve"),l(this,"client"),this.client=t}async retrieve(t){const e=T(t);return(await v(this.client,this.ENDPOINT,{keys:e},hm,dm)).linePlots}};const He=s.z.string().uuid(),fc=t=>JSON.parse(t),yc=s.z.object({name:s.z.string(),key:He,layout:Es.or(s.z.string().transform(t=>fc(t)))}),gc=yc.omit({layout:!0}).extend({layout:s.z.string().transform(t=>fc(t))}),ym=_s.partial({key:!0}).transform(t=>({...t,data:JSON.stringify(t.data)})),gm=s.z.object({workspace:He,linePlots:ym.array()}),pm=s.z.object({linePlots:_s.array()}),mm=s.z.object({keys:Ls.array()}),wm=s.z.object({}),bm=s.z.object({key:Ls,name:s.z.string()}),vm=s.z.object({}),Om=s.z.object({key:Ls,data:s.z.string()}),Tm=s.z.object({}),Sm="/workspace/lineplot/create",zm="/workspace/lineplot/delete",Nm="/workspace/lineplot/rename",Em="/workspace/lineplot/set-data";let Im=class{constructor(t){l(this,"client"),this.client=t}async create(t,e){const r={...e,data:JSON.stringify(e.data)};return(await v(this.client,Sm,{workspace:t,linePlots:[r]},gm,pm)).linePlots[0]}async delete(t){const e=T(t);await v(this.client,zm,{keys:e},mm,wm)}async rename(t,e){await v(this.client,Nm,{key:t,name:e},bm,vm)}async setData(t,e){await v(this.client,Em,{key:t,data:JSON.stringify(e)},Om,Tm)}},Am=class{constructor(t){l(this,"writer"),l(this,"retriever"),this.writer=new Im(t),this.retriever=new fm(t)}async create(t,e){return await this.writer.create(t,e)}async rename(t,e){await this.writer.rename(t,e)}async setData(t,e){await this.writer.setData(t,e)}async retrieve(t){const e=Array.isArray(t),r=await this.retriever.retrieve(t);return e?r:r[0]}async delete(t){await this.writer.delete(t)}};const km=s.z.object({keys:He.array().optional(),search:s.z.string().optional(),author:s.z.string().uuid().optional(),offset:s.z.number().optional(),limit:s.z.number().optional()}),xm=s.z.object({workspaces:pe(gc)});var dr;let Cm=(dr=class{constructor(t){l(this,"client"),this.client=t}async retrieve(t){const e=T(t);return await this.execute({keys:e})}async retrieveByAuthor(t){return await this.execute({author:t})}async search(t){return await this.execute({search:t})}async page(t,e){return await this.execute({offset:t,limit:e})}async execute(t){return(await v(this.client,dr.ENDPOINT,t,km,xm)).workspaces}},l(dr,"ENDPOINT","/workspace/retrieve"),dr);const wn=s.z.string().uuid(),$m=s.z.object({key:s.z.string(),name:s.z.string(),data:Es.or(s.z.string().transform(t=>JSON.parse(t))),snapshot:s.z.boolean()}),Ys=s.z.object({key:s.z.string(),name:s.z.string(),snapshot:s.z.boolean(),data:s.z.string().transform(t=>JSON.parse(t))}),Rm=s.z.object({keys:s.z.string().array()}),jm=s.z.object({schematics:Ys.array()});class Mm{constructor(e){l(this,"ENDPOINT","/workspace/schematic/retrieve"),l(this,"client"),this.client=e}async retrieve(e){return(await v(this.client,this.ENDPOINT,{keys:T(e)},Rm,jm)).schematics}}const Dm=$m.partial({key:!0,snapshot:!0}).transform(t=>({...t,data:JSON.stringify(t.data)})),Pm=s.z.object({workspace:He,schematics:Dm.array()}),Bm=s.z.object({schematics:Ys.array()}),Um=s.z.object({keys:wn.array()}),Lm=s.z.object({}),_m=s.z.object({key:wn,name:s.z.string()}),Xi=s.z.object({}),Ym=s.z.object({key:wn,data:s.z.string()});s.z.object({});const qm=s.z.object({key:wn,name:s.z.string(),snapshot:s.z.boolean()}),Fm=s.z.object({schematic:Ys}),Vm="/workspace/schematic/create",Wm="/workspace/schematic/delete",Gm="/workspace/schematic/rename",Zm="/workspace/schematic/set-data",Km="/workspace/schematic/copy";let Jm=class{constructor(t){l(this,"client"),this.client=t}async create(t,e){const r={...e,data:JSON.stringify(e.data)};return(await v(this.client,Vm,{workspace:t,schematics:[r]},Pm,Bm)).schematics[0]}async copy(t,e,r){return(await v(this.client,Km,{key:t,name:e,snapshot:r},qm,Fm)).schematic}async delete(t){const e=T(t);await v(this.client,Wm,{keys:e},Um,Lm)}async rename(t,e){await v(this.client,Gm,{key:t,name:e},_m,Xi)}async setData(t,e){await v(this.client,Zm,{key:t,data:JSON.stringify(e)},Ym,Xi)}},Hm=class{constructor(t){l(this,"writer"),l(this,"retriever"),this.writer=new Jm(t),this.retriever=new Mm(t)}async create(t,e){return await this.writer.create(t,e)}async rename(t,e){await this.writer.rename(t,e)}async setData(t,e){await this.writer.setData(t,e)}async retrieve(t){const e=Array.isArray(t),r=await this.retriever.retrieve(t);return e?r:r[0]}async delete(t){await this.writer.delete(t)}async copy(t,e,r){return await this.writer.copy(t,e,r)}};const Xm=yc.partial({key:!0}).transform(t=>({...t,layout:JSON.stringify(t.layout)})),Qm=s.z.object({workspaces:Xm.array()}),ew=s.z.object({workspaces:gc.array()}),tw=s.z.object({keys:He.array()}),rw=s.z.object({}),nw=s.z.object({key:He,name:s.z.string()}),sw=s.z.object({}),iw=s.z.object({key:He,layout:s.z.string()}),aw=s.z.object({}),ow="/workspace/create",cw="/workspace/delete",lw="/workspace/rename",uw="/workspace/set-layout";class hw{constructor(e){l(this,"client"),this.client=e}async create(e){return(await v(this.client,ow,{workspaces:T(e)},Qm,ew)).workspaces}async delete(e){await v(this.client,cw,{keys:T(e)},tw,rw)}async rename(e,r){await v(this.client,lw,{key:e,name:r},nw,sw)}async setLayout(e,r){await v(this.client,uw,{key:e,layout:JSON.stringify(r)},iw,aw)}}class dw{constructor(e){l(this,"type","workspace"),l(this,"schematic"),l(this,"linePlot"),l(this,"retriever"),l(this,"writer"),this.schematic=new Hm(e),this.linePlot=new Am(e),this.retriever=new Cm(e),this.writer=new hw(e)}async search(e){return await this.retriever.search(e)}async retrieveByAuthor(e){return await this.retriever.retrieveByAuthor(e)}async retrieve(e){const r=Array.isArray(e),n=await this.retriever.retrieve(e);return r?n:n[0]}async page(e,r){return await this.retriever.page(e,r)}async create(e){const r=Array.isArray(e),n=await this.writer.create(e);return r?n:n[0]}async rename(e,r){await this.writer.rename(e,r)}async setLayout(e,r){await this.writer.setLayout(e,r)}async delete(...e){await this.writer.delete(e)}}const pc=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:A.z.default(A.seconds(30)),secure:s.z.boolean().optional().default(!1),name:s.z.string().optional()});class mc extends Ng{constructor(e){const r=pc.parse(e),{host:n,port:i,username:a,password:o,connectivityPollFrequency:u,secure:c}=r,d=new um(new wf({host:n,port:Number(i)}),c);d.use(xf);let f;a!=null&&o!=null&&(f=new rg(d.unary,{username:a,password:o}),d.use(f.middleware()));const h=new xs(new ks(d.unary)),E=new Ho(d.unary,h);super(d.stream,d.unary,h),l(this,"createdAt"),l(this,"props"),l(this,"ranges"),l(this,"channels"),l(this,"auth"),l(this,"user"),l(this,"access"),l(this,"connectivity"),l(this,"ontology"),l(this,"workspaces"),l(this,"labels"),l(this,"hardware"),l(this,"control"),l(this,"transport"),l(this,"clientVersion","0.31.0"),this.createdAt=x.now(),this.props=r,this.auth=f,this.transport=d,this.channels=new Jo(this,h,d.unary,E),this.connectivity=new ec(d.unary,u,this.clientVersion,r.name),this.control=new sc(this),this.ontology=new Gf(d.unary,this);const P=new dc(this.transport.unary);this.labels=new Ap(this.transport.unary,this,this.ontology),this.ranges=new hc(this,P,this.transport.unary,h,this.labels,this.ontology),this.access=new cy(this.transport.unary),this.user=new Ky(this.transport.unary),this.workspaces=new dw(this.transport.unary);const ie=new Yg(this.transport.unary,this),M=new dp(this.transport.unary,this,this.ontology,this.ranges),Pc=new Jg(this.transport.unary,this,M);this.hardware=new Cg(M,Pc,ie)}get key(){return this.createdAt.valueOf().toString()}close(){this.connectivity.stopChecking()}}l(mc,"connectivity",ec);const fw=nt.Authority,ls=(t,e,r="")=>{try{return t.parse(e)}catch(n){if(n instanceof s.z.ZodError){const i=n.errors.map(a=>a.path.length===0?a.message:`${a.path.join(".")}: ${a.message}`);throw new Error(`${r} - ${i.join(`
|
|
66
|
-
`)}`)}else throw n}};var yw=Object.defineProperty,gw=(t,e,r)=>e in t?yw(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,ee=(t,e,r)=>gw(t,typeof e!="symbol"?e+"":e,r);const us=class wc{constructor(e,r,n="",i=!1){ee(this,"_noop",!1),ee(this,"key"),ee(this,"path"),ee(this,"serviceName"),this.key=e,this.path=r,this.serviceName=n,this._noop=i}child(e){return new wc(e,this.extendPath(e),this.serviceName,this.noop)}extendPath(e){return`${this.path}.${e}`}get noop(){return this._noop}};ee(us,"NOOP",new us("","",""));let qs=us;const hs=["debug","info","warn","error"],pw=t=>{const e=hs.indexOf(t);return({level:r})=>hs.indexOf(r)>=e},mw=t=>{const{include:e,exclude:r}=t;return({path:n})=>!(e!=null&&!e.some(i=>n.startsWith(i))||r!=null&&r.some(i=>n.startsWith(i)))},ds=class bc{constructor(e={}){ee(this,"meta",qs.NOOP),ee(this,"filters");const{filters:r=[]}=e;this.filters=r}filter(e){return!this.meta.noop&&this.filters.every(r=>r({key:this.meta.key,path:this.meta.path,level:e}))}child(e){const r=new bc({filters:this.filters});return r.meta=e,r}debug(e,r,n=!1){!this.filter("debug")&&!n||(r==null?console.log("%cDEBUG","color: #8c00f0;",this.meta.path,e):console.log("%cDEBUG","color: #8c00f0;",this.meta.path,e,fr(r)))}info(e,r,n=!1){!this.filter("info")&&!n||(r==null?console.log("%cINFO","color: #005eff;",this.meta.path,e):console.log("%cINFO","color: #005eff;",this.meta.path,e,fr(r)))}warn(e,r,n=!1){!this.filter("warn")&&!n||(r==null?console.warn("WARN",this.meta.path,e):console.warn("WARN",this.meta.path,e,fr(r)))}error(e,r,n=!1){!this.filter("error")&&!n||(r==null?console.error("ERROR",this.meta.path,e):console.error("ERROR",this.meta.path,e,fr(r)))}};ee(ds,"NOOP",new ds);let vc=ds;const fr=t=>typeof t=="function"?t():t;var ww=typeof globalThis=="object"?globalThis:typeof self=="object"?self:typeof window=="object"?window:typeof global=="object"?global:{},Ze="1.8.0",Qi=/^(\d+)\.(\d+)\.(\d+)(-(.+))?$/;function bw(t){var e=new Set([t]),r=new Set,n=t.match(Qi);if(!n)return function(){return!1};var i={major:+n[1],minor:+n[2],patch:+n[3],prerelease:n[4]};if(i.prerelease!=null)return function(u){return u===t};function a(u){return r.add(u),!1}function o(u){return e.add(u),!0}return function(u){if(e.has(u))return!0;if(r.has(u))return!1;var c=u.match(Qi);if(!c)return a(u);var d={major:+c[1],minor:+c[2],patch:+c[3],prerelease:c[4]};return d.prerelease!=null||i.major!==d.major?a(u):i.major===0?i.minor===d.minor&&i.patch<=d.patch?o(u):a(u):i.minor<=d.minor?o(u):a(u)}}var vw=bw(Ze),Ow=Ze.split(".")[0],Vt=Symbol.for("opentelemetry.js.api."+Ow),Wt=ww;function Fs(t,e,r,n){var i;n===void 0&&(n=!1);var a=Wt[Vt]=(i=Wt[Vt])!==null&&i!==void 0?i:{version:Ze};if(!n&&a[t]){var o=new Error("@opentelemetry/api: Attempted duplicate registration of API: "+t);return r.error(o.stack||o.message),!1}if(a.version!==Ze){var o=new Error("@opentelemetry/api: Registration of version v"+a.version+" for "+t+" does not match previously registered API v"+Ze);return r.error(o.stack||o.message),!1}return a[t]=e,r.debug("@opentelemetry/api: Registered a global for "+t+" v"+Ze+"."),!0}function Gt(t){var e,r,n=(e=Wt[Vt])===null||e===void 0?void 0:e.version;if(!(!n||!vw(n)))return(r=Wt[Vt])===null||r===void 0?void 0:r[t]}function Vs(t,e){e.debug("@opentelemetry/api: Unregistering a global for "+t+" v"+Ze+".");var r=Wt[Vt];r&&delete r[t]}var Tw=function(t,e){var r=typeof Symbol=="function"&&t[Symbol.iterator];if(!r)return t;var n=r.call(t),i,a=[],o;try{for(;(e===void 0||e-- >0)&&!(i=n.next()).done;)a.push(i.value)}catch(u){o={error:u}}finally{try{i&&!i.done&&(r=n.return)&&r.call(n)}finally{if(o)throw o.error}}return a},Sw=function(t,e,r){if(arguments.length===2)for(var n=0,i=e.length,a;n<i;n++)(a||!(n in e))&&(a||(a=Array.prototype.slice.call(e,0,n)),a[n]=e[n]);return t.concat(a||Array.prototype.slice.call(e))},zw=function(){function t(e){this._namespace=e.namespace||"DiagComponentLogger"}return t.prototype.debug=function(){for(var e=[],r=0;r<arguments.length;r++)e[r]=arguments[r];return gt("debug",this._namespace,e)},t.prototype.error=function(){for(var e=[],r=0;r<arguments.length;r++)e[r]=arguments[r];return gt("error",this._namespace,e)},t.prototype.info=function(){for(var e=[],r=0;r<arguments.length;r++)e[r]=arguments[r];return gt("info",this._namespace,e)},t.prototype.warn=function(){for(var e=[],r=0;r<arguments.length;r++)e[r]=arguments[r];return gt("warn",this._namespace,e)},t.prototype.verbose=function(){for(var e=[],r=0;r<arguments.length;r++)e[r]=arguments[r];return gt("verbose",this._namespace,e)},t}();function gt(t,e,r){var n=Gt("diag");if(n)return r.unshift(e),n[t].apply(n,Sw([],Tw(r),!1))}var ge;(function(t){t[t.NONE=0]="NONE",t[t.ERROR=30]="ERROR",t[t.WARN=50]="WARN",t[t.INFO=60]="INFO",t[t.DEBUG=70]="DEBUG",t[t.VERBOSE=80]="VERBOSE",t[t.ALL=9999]="ALL"})(ge||(ge={}));function Nw(t,e){t<ge.NONE?t=ge.NONE:t>ge.ALL&&(t=ge.ALL),e=e||{};function r(n,i){var a=e[n];return typeof a=="function"&&t>=i?a.bind(e):function(){}}return{error:r("error",ge.ERROR),warn:r("warn",ge.WARN),info:r("info",ge.INFO),debug:r("debug",ge.DEBUG),verbose:r("verbose",ge.VERBOSE)}}var Ew=function(t,e){var r=typeof Symbol=="function"&&t[Symbol.iterator];if(!r)return t;var n=r.call(t),i,a=[],o;try{for(;(e===void 0||e-- >0)&&!(i=n.next()).done;)a.push(i.value)}catch(u){o={error:u}}finally{try{i&&!i.done&&(r=n.return)&&r.call(n)}finally{if(o)throw o.error}}return a},Iw=function(t,e,r){if(arguments.length===2)for(var n=0,i=e.length,a;n<i;n++)(a||!(n in e))&&(a||(a=Array.prototype.slice.call(e,0,n)),a[n]=e[n]);return t.concat(a||Array.prototype.slice.call(e))},Aw="diag",Zt=function(){function t(){function e(i){return function(){for(var a=[],o=0;o<arguments.length;o++)a[o]=arguments[o];var u=Gt("diag");if(u)return u[i].apply(u,Iw([],Ew(a),!1))}}var r=this,n=function(i,a){var o,u,c;if(a===void 0&&(a={logLevel:ge.INFO}),i===r){var d=new Error("Cannot use diag as the logger for itself. Please use a DiagLogger implementation like ConsoleDiagLogger or a custom implementation");return r.error((o=d.stack)!==null&&o!==void 0?o:d.message),!1}typeof a=="number"&&(a={logLevel:a});var f=Gt("diag"),h=Nw((u=a.logLevel)!==null&&u!==void 0?u:ge.INFO,i);if(f&&!a.suppressOverrideMessage){var E=(c=new Error().stack)!==null&&c!==void 0?c:"<failed to generate stacktrace>";f.warn("Current logger will be overwritten from "+E),h.warn("Current logger will overwrite one already registered from "+E)}return Fs("diag",h,r,!0)};r.setLogger=n,r.disable=function(){Vs(Aw,r)},r.createComponentLogger=function(i){return new zw(i)},r.verbose=e("verbose"),r.debug=e("debug"),r.info=e("info"),r.warn=e("warn"),r.error=e("error")}return t.instance=function(){return this._instance||(this._instance=new t),this._instance},t}(),kw=function(t,e){var r=typeof Symbol=="function"&&t[Symbol.iterator];if(!r)return t;var n=r.call(t),i,a=[],o;try{for(;(e===void 0||e-- >0)&&!(i=n.next()).done;)a.push(i.value)}catch(u){o={error:u}}finally{try{i&&!i.done&&(r=n.return)&&r.call(n)}finally{if(o)throw o.error}}return a},xw=function(t){var e=typeof Symbol=="function"&&Symbol.iterator,r=e&&t[e],n=0;if(r)return r.call(t);if(t&&typeof t.length=="number")return{next:function(){return t&&n>=t.length&&(t=void 0),{value:t&&t[n++],done:!t}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")},Cw=function(){function t(e){this._entries=e?new Map(e):new Map}return t.prototype.getEntry=function(e){var r=this._entries.get(e);if(r)return Object.assign({},r)},t.prototype.getAllEntries=function(){return Array.from(this._entries.entries()).map(function(e){var r=kw(e,2),n=r[0],i=r[1];return[n,i]})},t.prototype.setEntry=function(e,r){var n=new t(this._entries);return n._entries.set(e,r),n},t.prototype.removeEntry=function(e){var r=new t(this._entries);return r._entries.delete(e),r},t.prototype.removeEntries=function(){for(var e,r,n=[],i=0;i<arguments.length;i++)n[i]=arguments[i];var a=new t(this._entries);try{for(var o=xw(n),u=o.next();!u.done;u=o.next()){var c=u.value;a._entries.delete(c)}}catch(d){e={error:d}}finally{try{u&&!u.done&&(r=o.return)&&r.call(o)}finally{if(e)throw e.error}}return a},t.prototype.clear=function(){return new t},t}();Zt.instance();function $w(t){return t===void 0&&(t={}),new Cw(new Map(Object.entries(t)))}function Rw(t){return Symbol.for(t)}var jw=function(){function t(e){var r=this;r._currentContext=e?new Map(e):new Map,r.getValue=function(n){return r._currentContext.get(n)},r.setValue=function(n,i){var a=new t(r._currentContext);return a._currentContext.set(n,i),a},r.deleteValue=function(n){var i=new t(r._currentContext);return i._currentContext.delete(n),i}}return t}(),Mw=new jw,Dw={get:function(t,e){if(t!=null)return t[e]},keys:function(t){return t==null?[]:Object.keys(t)}},Pw={set:function(t,e,r){t!=null&&(t[e]=r)}},Bw=function(t,e){var r=typeof Symbol=="function"&&t[Symbol.iterator];if(!r)return t;var n=r.call(t),i,a=[],o;try{for(;(e===void 0||e-- >0)&&!(i=n.next()).done;)a.push(i.value)}catch(u){o={error:u}}finally{try{i&&!i.done&&(r=n.return)&&r.call(n)}finally{if(o)throw o.error}}return a},Uw=function(t,e,r){if(arguments.length===2)for(var n=0,i=e.length,a;n<i;n++)(a||!(n in e))&&(a||(a=Array.prototype.slice.call(e,0,n)),a[n]=e[n]);return t.concat(a||Array.prototype.slice.call(e))},Lw=function(){function t(){}return t.prototype.active=function(){return Mw},t.prototype.with=function(e,r,n){for(var i=[],a=3;a<arguments.length;a++)i[a-3]=arguments[a];return r.call.apply(r,Uw([n],Bw(i),!1))},t.prototype.bind=function(e,r){return r},t.prototype.enable=function(){return this},t.prototype.disable=function(){return this},t}(),_w=function(t,e){var r=typeof Symbol=="function"&&t[Symbol.iterator];if(!r)return t;var n=r.call(t),i,a=[],o;try{for(;(e===void 0||e-- >0)&&!(i=n.next()).done;)a.push(i.value)}catch(u){o={error:u}}finally{try{i&&!i.done&&(r=n.return)&&r.call(n)}finally{if(o)throw o.error}}return a},Yw=function(t,e,r){if(arguments.length===2)for(var n=0,i=e.length,a;n<i;n++)(a||!(n in e))&&(a||(a=Array.prototype.slice.call(e,0,n)),a[n]=e[n]);return t.concat(a||Array.prototype.slice.call(e))},Yn="context",qw=new Lw,Oc=function(){function t(){}return t.getInstance=function(){return this._instance||(this._instance=new t),this._instance},t.prototype.setGlobalContextManager=function(e){return Fs(Yn,e,Zt.instance())},t.prototype.active=function(){return this._getContextManager().active()},t.prototype.with=function(e,r,n){for(var i,a=[],o=3;o<arguments.length;o++)a[o-3]=arguments[o];return(i=this._getContextManager()).with.apply(i,Yw([e,r,n],_w(a),!1))},t.prototype.bind=function(e,r){return this._getContextManager().bind(e,r)},t.prototype._getContextManager=function(){return Gt(Yn)||qw},t.prototype.disable=function(){this._getContextManager().disable(),Vs(Yn,Zt.instance())},t}(),fs;(function(t){t[t.UNSET=0]="UNSET",t[t.OK=1]="OK",t[t.ERROR=2]="ERROR"})(fs||(fs={}));var Fw=Oc.getInstance(),Vw=function(){function t(){}return t.prototype.inject=function(e,r){},t.prototype.extract=function(e,r){return e},t.prototype.fields=function(){return[]},t}(),Ws=Rw("OpenTelemetry Baggage Key");function Tc(t){return t.getValue(Ws)||void 0}function Ww(){return Tc(Oc.getInstance().active())}function Gw(t,e){return t.setValue(Ws,e)}function Zw(t){return t.deleteValue(Ws)}var qn="propagation",Kw=new Vw,Jw=function(){function t(){this.createBaggage=$w,this.getBaggage=Tc,this.getActiveBaggage=Ww,this.setBaggage=Gw,this.deleteBaggage=Zw}return t.getInstance=function(){return this._instance||(this._instance=new t),this._instance},t.prototype.setGlobalPropagator=function(e){return Fs(qn,e,Zt.instance())},t.prototype.inject=function(e,r,n){return n===void 0&&(n=Pw),this._getGlobalPropagator().inject(e,r,n)},t.prototype.extract=function(e,r,n){return n===void 0&&(n=Dw),this._getGlobalPropagator().extract(e,r,n)},t.prototype.fields=function(){return this._getGlobalPropagator().fields()},t.prototype.disable=function(){Vs(qn,Zt.instance())},t.prototype._getGlobalPropagator=function(){return Gt(qn)||Kw},t}(),Hw=Jw.getInstance();const ea=["bench","debug","prod"],Xw=t=>e=>ea.indexOf(e)>=ea.indexOf(t),ys=class Sc{constructor(e,r=Xw("debug")){ee(this,"meta",qs.NOOP),ee(this,"tracer"),ee(this,"filter"),this.tracer=e,this.filter=r}child(e){const r=new Sc(this.tracer,this.filter);return r.meta=e,r}debug(e,r){return this.trace(e,"debug",r)}bench(e,r){return this.trace(e,"bench",r)}prod(e,r){return this.trace(e,"prod",r)}trace(e,r,n){return this.meta.noop||!this.filter(r)?n(new Ec(e)):this.tracer.startActiveSpan(e,i=>{const a=new Nc(e,i),o=n(a);return i.end(),o})}propagate(e){if(this.meta.noop)return;const r=Fw.active();Hw.inject(r,e,{set:(n,i,a)=>{n[i]=a}})}};ee(ys,"NOOP",new ys);let zc=ys;class Nc{constructor(e,r){ee(this,"key"),ee(this,"otel"),this.key=e,this.otel=r}set(e,r){this.otel.setAttribute(e,r)}recordError(e){e!=null&&(this.otel.recordException(e),this.otel.setStatus({code:fs.ERROR}))}}class Ec{constructor(e){ee(this,"key"),this.key=e}set(){}recordError(e){}}const gs=class Ic{constructor({key:e="",serviceName:r="",logger:n=vc.NOOP,tracer:i=zc.NOOP,noop:a=!1,__meta:o}){ee(this,"meta"),ee(this,"T"),ee(this,"L"),this.meta=o??new qs(e,e,r,a),this.T=i.child(this.meta),this.L=n.child(this.meta)}child(e){const r=this.meta.child(e);return new Ic({__meta:r,tracer:this.T,logger:this.L})}};ee(gs,"NOOP",new gs({noop:!0}));let Gs=gs;const Qw=Gs.NOOP,Ac=Object.freeze(Object.defineProperty({__proto__:null,Instrumentation:Gs,LOG_LEVELS:hs,Logger:vc,NOOP:Qw,NoopSpan:Ec,Tracer:zc,_Span:Nc,logLevelKeyFiler:mw,logThresholdFilter:pw},Symbol.toStringTag,{value:"Module"})),eb=new Error("request for lock canceled");var tb=function(t,e,r,n){function i(a){return a instanceof r?a:new r(function(o){o(a)})}return new(r||(r=Promise))(function(a,o){function u(f){try{d(n.next(f))}catch(h){o(h)}}function c(f){try{d(n.throw(f))}catch(h){o(h)}}function d(f){f.done?a(f.value):i(f.value).then(u,c)}d((n=n.apply(t,e||[])).next())})};class rb{constructor(e,r=eb){this._value=e,this._cancelError=r,this._queue=[],this._weightedWaiters=[]}acquire(e=1,r=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:r},o=kc(this._queue,u=>r<=u.priority);o===-1&&e<=this._value?this._dispatchItem(a):this._queue.splice(o+1,0,a)})}runExclusive(e){return tb(this,arguments,void 0,function*(r,n=1,i=0){const[a,o]=yield this.acquire(n,i);try{return yield r(a)}finally{o()}})}waitForUnlock(e=1,r=0){if(e<=0)throw new Error(`invalid weight ${e}: must be positive`);return this._couldLockImmediately(e,r)?Promise.resolve():new Promise(n=>{this._weightedWaiters[e-1]||(this._weightedWaiters[e-1]=[]),nb(this._weightedWaiters[e-1],{resolve:n,priority:r})})}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 r=this._value;this._value-=e.weight,e.resolve([r,this._newReleaser(e.weight)])}_newReleaser(e){let r=!1;return()=>{r||(r=!0,this.release(e))}}_drainUnlockWaiters(){if(this._queue.length===0)for(let e=this._value;e>0;e--){const r=this._weightedWaiters[e-1];r&&(r.forEach(n=>n.resolve()),this._weightedWaiters[e-1]=[])}else{const e=this._queue[0].priority;for(let r=this._value;r>0;r--){const n=this._weightedWaiters[r-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,r){return(this._queue.length===0||this._queue[0].priority<r)&&e<=this._value}}function nb(t,e){const r=kc(t,n=>e.priority<=n.priority);t.splice(r+1,0,e)}function kc(t,e){for(let r=t.length-1;r>=0;r--)if(e(t[r]))return r;return-1}var sb=function(t,e,r,n){function i(a){return a instanceof r?a:new r(function(o){o(a)})}return new(r||(r=Promise))(function(a,o){function u(f){try{d(n.next(f))}catch(h){o(h)}}function c(f){try{d(n.throw(f))}catch(h){o(h)}}function d(f){f.done?a(f.value):i(f.value).then(u,c)}d((n=n.apply(t,e||[])).next())})};class xc{constructor(e){this._semaphore=new rb(1,e)}acquire(){return sb(this,arguments,void 0,function*(e=0){const[,r]=yield this._semaphore.acquire(1,e);return r})}runExclusive(e,r=0){return this._semaphore.runExclusive(()=>e(),1,r)}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()}}class bn{constructor(e,r,n=new Map){B(this,"providers");B(this,"registry");B(this,"sender");B(this,"changedKeys");this.providers=n,this.registry=r,this.changedKeys=[],this.sender=e}propagateState(e,r,n=[]){this.sender.send({key:e,state:r},n)}copyAndMerge(e){const r=new bn(this.sender,this.registry,new Map);return e==null||e.providers.forEach((n,i)=>r.providers.set(i,n)),this.providers.forEach((n,i)=>r.providers.set(i,n)),r.changedKeys=[],r}get changed(){return this.changedKeys.length>0}set(e,r,n=!0){this.providers.set(e,r),n&&this.changedKeys.push(e)}setIfNotHas(e,r){this.providers.has(e)||this.set(e,r)}async create(e){const r=this.registry[e.type];if(r==null)throw new Error(`[AetherRoot.create] - could not find component ${e.type}`);const n=new r(e);return await n.internalUpdate(e),n}getOptional(e){return this.providers.get(e)??null}has(e){return this.providers.has(e)}get(e){const r=this.getOptional(e);if(r==null)throw new Error(`[AetherRoot.get] - could not find provider ${e}`);return r}}class Zs{constructor(e){B(this,"type");B(this,"key");B(this,"_ctx");B(this,"_internalState");B(this,"_state");B(this,"_prevState");B(this,"_deleted",!1);B(this,"instrumentation");B(this,"schema");this.type=e.type,this.key=e.path[0],this._ctx=e.ctx,this._internalState={},this.instrumentation=e.instrumentation.child(`${this.type}(${this.key})`)}get _schema(){if(this.schema==null)throw new K(`[AetherLeaf] - expected subclass to define component schema, but none was found.
|
|
67
|
-
Make sure to defne a property 'schema' on the class.`);return this.schema}setState(e){const r=bs(e,this._state);this._prevState={...this._state},this._state=ls(this._schema,r,`${this.type}:${this.key}`),this.ctx.propagateState(this.key,r)}get ctx(){if(this._ctx==null)throw new we("context not defined");return this._ctx}get state(){if(this._state==null)throw new we("state not defined");return this._state}get internal(){return this._internalState}get prevState(){return this._prevState}get deleted(){return this._deleted}async internalUpdate({variant:e,path:r,ctx:n,state:i}){if(!this.deleted){if(this._ctx=n,e==="state"){this.validatePath(r);const a=ls(this._schema,i,`${this.type}:${this.key}`);this._state!=null?this.instrumentation.L.debug("updating state",()=>({diff:la.difference(this.state,a)})):this.instrumentation.L.debug("setting initial state",{state:i}),this._prevState=this._state??a,this._state=a}else this.instrumentation.L.debug("updating context");await this.afterUpdate()}}async internalDelete(e){this.validatePath(e),this._deleted=!0,await this.afterDelete()}beforeUpdate(){}async afterUpdate(){}async afterDelete(){}validatePath(e){if(e.length===0)throw new we(`[Leaf.setState] - ${this.type}:${this.key} received an empty path`);const r=e[e.length-1];if(e.length>1)throw new we(`[Leaf.setState] - ${this.type}:${this.key} received a subPath ${e.join(".")} but is a leaf`);if(r!==this.key)throw new we(`[Leaf.setState] - ${this.type}:${this.key} received a key ${r} but expected ${this.key}`)}}class ir extends Zs{constructor(r){super(r);B(this,"_children");this._children=new Map}get children(){return Array.from(this._children.values())}async internalUpdate(r){const{variant:n,path:i}=r;if(n==="context")return this._ctx=r.ctx.copyAndMerge(this._ctx),await this.updateContext({...r,ctx:this.ctx});const[a,o]=this.getRequiredKey(i),
|
|
62
|
+
`);const f=new Ge({data:r[u],dataType:d.dataType});o.push(d.key),l.push(f)}return new be(o,l)}if(e instanceof be||e instanceof Map){const o=new be(e);if(this.adapter==null)return o;let l=[];return l=o.columns.map(u=>{var d;const f=typeof u=="string"?(d=this.adapter)==null?void 0:d.get(u):u;if(f==null)throw new K(`
|
|
63
|
+
Channel ${u} was not provided in the list of channels when opening the writer
|
|
64
|
+
`);return f}),new be(l,o.series)}const n=[],i=[],a=Object.entries(e);for(let o=0;o<a.length;o++){const[l,u]=a[o],d=await this.fetchChannel(l),f=new Ge({data:u,dataType:d.dataType});n.push(d.key),i.push(f)}return new be(n,i)}}class Rs{constructor(e,r){c(this,"name"),c(this,"stream"),this.stream=r,this.name=e}async receive(){const[e,r]=await this.stream.receive();if(r!=null)throw r;return e}received(){return this.stream.received()}async closeAndAck(){for(this.stream.closeSend();;){const[e,r]=await this.stream.receive();if(e!=null&&console.warn(`${this.name} received unexpected response on closure.
|
|
65
|
+
Please report this error to the Synnax team. ${JSON.stringify(e)}`),r!=null){if(Ue.matches(r))return;throw r}}}closeSend(){this.stream.closeSend()}send(e){const r=this.stream.send(e);if(r!=null)throw r}}const Ji=new A(-1);var js=(t=>(t[t.Open=0]="Open",t[t.Next=1]="Next",t[t.Prev=2]="Prev",t[t.SeekFirst=3]="SeekFirst",t[t.SeekLast=4]="SeekLast",t[t.SeekLE=5]="SeekLE",t[t.SeekGE=6]="SeekGE",t[t.Valid=7]="Valid",t[t.Error=8]="Error",t))(js||{}),tc=(t=>(t[t.None=0]="None",t[t.Ack=1]="Ack",t[t.Data=2]="Data",t))(tc||{});const fg=s.z.object({command:s.z.nativeEnum(js),span:A.z.optional(),bounds:se.z.optional(),stamp:x.z.optional(),keys:s.z.number().array().optional(),chunkSize:s.z.number().optional()}),yg=s.z.object({variant:s.z.nativeEnum(tc),ack:s.z.boolean(),command:s.z.nativeEnum(js),error:Xt.optional().nullable(),frame:Cs.optional()}),rc=class os{constructor(e,r){c(this,"stream"),c(this,"adapter"),c(this,"value"),this.stream=new Rs("Iterator",e),this.value=new be,this.adapter=r}static async _open(e,r,n,i,a={}){const o=await fn.open(n,r),l=await i.stream(os.ENDPOINT,fg,yg),u=new os(l,o);return await u.execute({command:0,keys:o.keys,bounds:new se(e),chunkSize:a.chunkSize??1e5}),u}async next(e=Ji){return await this.execute({command:1,span:new A(e)})}async prev(e=Ji){return await this.execute({command:2,span:new A(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 x(e)})}async seekGE(e){return await this.execute({command:6,stamp:new x(e)})}async valid(){return await this.execute({command:7})}async close(){await this.stream.closeAndAck()}[Symbol.asyncIterator](){return new pg(this)}async execute(e){for(this.stream.send(e),this.value=new be;;){const r=await this.stream.receive();if(r.variant===1)return r.ack;this.value.push(this.adapter.adapt(new be(r.frame)))}}};c(rc,"ENDPOINT","/frame/iterate");let gg=rc;class pg{constructor(e){c(this,"iter"),c(this,"open",!1),this.iter=e}async next(){try{let e=!0;return this.open||(await this.iter.seekFirst()||(e=!1),this.open=!0),await this.iter.next()||(e=!1),e||await this.iter.close(),{done:!e,value:this.iter.value}}catch(e){throw await this.iter.close(),e}}}const mg=s.z.object({keys:s.z.number().array(),downsampleFactor:s.z.number()}),wg=s.z.object({frame:Cs,error:Xt.optional().nullable()}),bg="/frame/stream";class Ms{constructor(e,r){c(this,"stream"),c(this,"adapter"),c(this,"downsampleFactor"),this.stream=new Rs("Streamer",e),this.adapter=r,this.downsampleFactor=1}get keys(){return this.adapter.keys}static async _open(e,r,{channels:n,downsampleFactor:i}){const a=await fn.open(e,n),o=await r.stream(bg,mg,wg),l=new Ms(o,a);o.send({keys:a.keys,downsampleFactor:i??1});const[,u]=await o.receive();if(u!=null)throw u;return l}async next(){try{return{done:!1,value:await this.read()}}catch(e){if(Ue.matches(e))return{done:!0,value:void 0};throw e}}async read(){return this.adapter.adapt(new be((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 yn extends Je.Observer{constructor(e,r){super(r),c(this,"streamer"),c(this,"closePromise"),this.streamer=e,this.closePromise=this.stream()}async close(){this.streamer.close(),await this.closePromise}async stream(){for await(const e of this.streamer)this.notify(e)}}var Ds=(t=>(t[t.Open=0]="Open",t[t.Write=1]="Write",t[t.Commit=2]="Commit",t[t.Error=3]="Error",t[t.SetAuthority=4]="SetAuthority",t))(Ds||{}),Ft=(t=>(t[t.PersistStream=1]="PersistStream",t[t.Persist=2]="Persist",t[t.Stream=3]="Stream",t))(Ft||{});const vg=t=>{switch(t){case"persist":return 2;case"stream":return 3;case"persistStream":return 1;default:if(typeof t=="number"&&t in Ft)return t;throw new Error(`invalid writer mode: ${t}`)}};new A(-1);const Og=s.z.object({start:x.z.optional(),controlSubject:nt.subjectZ.optional(),keys:s.z.number().array().optional(),authorities:nt.Authority.z.array().optional(),mode:s.z.nativeEnum(Ft).optional(),errOnUnauthorized:s.z.boolean().optional(),enableAutoCommit:s.z.boolean().optional(),autoIndexPersistInterval:A.z.optional()}),Tg=s.z.object({command:s.z.nativeEnum(Ds),config:Og.optional(),frame:Cs.optional()}),Sg=s.z.object({ack:s.z.boolean(),command:s.z.nativeEnum(Ds),error:Xt.optional().nullable()});var yt;let zg=(yt=class{constructor(t,e){c(this,"stream"),c(this,"adapter"),this.stream=new Rs("Writer",t),this.adapter=e}static async _open(t,e,{channels:r,start:n=x.now(),authorities:i=nt.Authority.Absolute,controlSubject:a,mode:o=1,errOnUnauthorized:l=!1,enableAutoCommit:u=!1,autoIndexPersistInterval:d=A.SECOND}){const f=await $s.open(t,r),h=await e.stream(yt.ENDPOINT,Tg,Sg),E=new yt(h,f);return await E.execute({command:0,config:{start:new x(n),keys:f.keys,controlSubject:a,authorities:T(i),mode:vg(o),errOnUnauthorized:l,enableAutoCommit:u,autoIndexPersistInterval:d}}),E}async write(t,e){const r=await this.adapter.adapt(t,e);return this.stream.send({command:1,frame:r.toPayload()}),!0}async setAuthority(t,e){let r={keys:[],authorities:[]};if(typeof t=="number"&&e==null)r={keys:[],authorities:[t]};else{let n;typeof t=="string"||typeof t=="number"?n={[t]:e}:n=t,n=await this.adapter.adaptObjectKeys(n),r={keys:Object.keys(n).map(i=>Number(i)),authorities:Object.values(n)}}return(await this.execute({command:4,config:r})).ack}async commit(){return this.errorAccumulated?!1:(await this.execute({command:2})).ack}async error(){this.stream.send({command:3});const t=await this.execute({command:3});return t.error!=null?Ts(t.error):null}async close(){await this.stream.closeAndAck()}async execute(t){for(this.stream.send(t);;){const e=await this.stream.receive();if(e.command===t.command)return e;console.warn("writer received unexpected response",e)}}get errorAccumulated(){return this.stream.received()}},c(yt,"ENDPOINT","/frame/write"),yt),Ng=class{constructor(t,e,r){c(this,"streamClient"),c(this,"retriever"),c(this,"deleter"),this.streamClient=t,this.retriever=r,this.deleter=new ug(e)}async openIterator(t,e,r){return await gg._open(t,e,this.retriever,this.streamClient,r)}async openWriter(t){return(Array.isArray(t)||typeof t!="object")&&(t={channels:t}),await zg._open(this.retriever,this.streamClient,t)}async openStreamer(t){return(Array.isArray(t)||typeof t!="object")&&(t={channels:t,downsampleFactor:1}),await Ms._open(this.retriever,this.streamClient,t)}async write(t,e,r){if(r==null){const i=e,a=await this.openWriter({start:t,channels:Object.keys(i),mode:Ft.Persist});try{await a.write(i),await a.commit()}finally{await a.close()}return}const n=await this.openWriter({start:t,channels:e,mode:Ft.Persist,errOnUnauthorized:!0,enableAutoCommit:!0,autoIndexPersistInterval:A.MAX});try{await n.write(e,r)}finally{await n.close()}}async read(t,e){const{single:r}=De(e),n=await this.readFrame(t,e);return r?n.get(e):n}async readFrame(t,e){const r=await this.openIterator(t,e),n=new be;try{for await(const i of r)n.push(i)}finally{await r.close()}return n}async delete(t,e){const{normalized:r,variant:n}=De(t);return n==="keys"?await this.deleter.delete({keys:r,bounds:e}):await this.deleter.delete({names:r,bounds:e})}};const Eg=nt.Authority,Ig=nt.stateZ(s.z.number()),Ag=t=>{var e,r;return t.to==null?`${(e=t.from)==null?void 0:e.resource} - ${(r=t.from)==null?void 0:r.subject.name} -> released`:t.from==null?`${t.to.resource} - released -> ${t.to.subject.name} (${t.to.authority.toString()})`:`${t.to.resource} - ${t.from.subject.name} -> ${t.to.subject.name} (${t.to.authority.toString()})`};class nc extends yn{constructor(e){super(e,r=>{const n=this.codec.decode(r.series[0].buffer);return this.merge(n),[n.transfers,!0]}),c(this,"states"),c(this,"codec"),this.states=new Map,this.codec=new ot.JSONCodec}subjects(){const e=new Map;return this.states.forEach(r=>e.set(r.subject.key,r.subject)),Array.from(e.values())}merge(e){e.transfers.forEach(r=>{r.from==null&&r.to==null&&console.warn("Invalid transfer: ",r),r.to==null?this.states.delete(r.from.resource):this.states.set(r.to.resource,r.to)})}}const kg="sy_node_1_control";let sc=class{constructor(t){c(this,"framer"),this.framer=t}async openStateTracker(){const t=await this.framer.openStreamer(kg);return new nc(t)}};const xg=Object.freeze(Object.defineProperty({__proto__:null,Authority:Eg,Client:sc,StateTracker:nc,stateZ:Ig,transferString:Ag},Symbol.toStringTag,{value:"Module"}));let Cg=class{constructor(t,e,r){c(this,"tasks"),c(this,"racks"),c(this,"devices"),this.tasks=t,this.racks=e,this.devices=r}};const rr=s.z.number(),Ps=s.z.object({key:rr,name:s.z.string()}),$g=Ps.partial({key:!0}),Bs=s.z.string(),gn=s.z.object({key:Bs,rack:rr,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(t=>t===""?{}:ot.JSON_CODEC.decodeString(t)))}),Rg=gn.extend({properties:s.z.unknown().transform(t=>ot.JSON_CODEC.encodeString(t))}),ct=async(t,e,r,n)=>{const i=await t.openStreamer([e,r]),a=o=>{const l=[];return r!=null&&l.push(...o.get(r).series.flatMap(u=>n("delete",u))),e!=null&&l.push(...o.get(e).series.flatMap(u=>n("set",u))),[l,l.length>0]};return new yn(i,a)},jg="sy_device_set",Mg="sy_device_delete",jn="/hardware/device/retrieve",Dg="/hardware/device/create",Pg="/hardware/device/delete",Bg=s.z.object({devices:Rg.array()}),Ug=s.z.object({devices:gn.array()}),Lg=s.z.object({keys:Bs.array()}),_g=s.z.object({}),Mn=s.z.object({search:s.z.string().optional(),limit:s.z.number().optional(),offset:s.z.number().optional(),keys:Bs.array().optional(),names:s.z.string().array().optional(),makes:s.z.string().array().optional()}),Dn=s.z.object({devices:pe(gn)});let Yg=class{constructor(t,e){c(this,"type","device"),c(this,"client"),c(this,"frameClient"),this.client=t,this.frameClient=e}async retrieve(t,e){const r=!Array.isArray(t),n=await v(this.client,jn,{keys:T(t),...e},Mn,Dn);return hn("Device",t,n.devices,r),r?n.devices[0]:n.devices}async search(t,e){return(await v(this.client,jn,{search:t,...e},Mn,Dn)).devices}async page(t,e,r){return(await v(this.client,jn,{offset:t,limit:e,...r},Mn,Dn)).devices}async create(t){const e=!Array.isArray(t),r=await v(this.client,Dg,{devices:T(t)},Bg,Ug);return e?r.devices[0]:r.devices}async delete(t){await v(this.client,Pg,{keys:T(t)},Lg,_g)}async openDeviceTracker(){return await ct(this.frameClient,jg,Mg,qg)}newSearcherWithOptions(t){return{type:this.type,search:async e=>await this.search(e,t),retrieve:async e=>await this.retrieve(e,t),page:async(e,r)=>await this.page(e,r,t)}}};const qg=(t,e)=>t==="delete"?e.toStrings().map(r=>({variant:t,key:r,value:void 0})):e.parseJSON(gn).map(r=>({variant:t,key:r.key,value:r})),Pn="/hardware/rack/retrieve",Fg="/hardware/rack/create",Vg="/hardware/rack/delete",Bn=s.z.object({keys:rr.array().optional(),names:s.z.string().array().optional(),search:s.z.string().optional(),offset:s.z.number().optional(),limit:s.z.number().optional()}),Un=s.z.object({racks:pe(Ps)}),Wg=s.z.object({racks:$g.array()}),Gg=s.z.object({racks:Ps.array()}),Zg=s.z.object({keys:rr.array()}),Kg=s.z.object({});let Jg=class{constructor(t,e,r){c(this,"type","rack"),c(this,"client"),c(this,"frameClient"),c(this,"tasks"),this.client=t,this.frameClient=e,this.tasks=r}async delete(t){await v(this.client,Vg,{keys:T(t)},Zg,Kg)}async create(t){const e=!Array.isArray(t),r=await v(this.client,Fg,{racks:T(t)},Wg,Gg),n=this.sugar(r.racks);return e?n[0]:n}async search(t){const e=await v(this.client,Pn,{search:t},Bn,Un);return this.sugar(e.racks)}async page(t,e){const r=await v(this.client,Pn,{offset:t,limit:e},Bn,Un);return this.sugar(r.racks)}async retrieve(t){const{variant:e,normalized:r,single:n}=un(t,{string:"names",number:"keys"}),i=await v(this.client,Pn,{[e]:r},Bn,Un),a=this.sugar(i.racks);return hn("Rack",t,a,n),n?a[0]:a}sugar(t){return t.map(({key:e,name:r})=>new Hg(e,r,this.tasks))}};class Hg{constructor(e,r,n){c(this,"key"),c(this,"name"),c(this,"tasks"),this.key=e,this.name=r,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 lt=s.z.union([s.z.string(),s.z.bigint().transform(t=>t.toString()),s.z.number().transform(t=>t.toString())]),Hr=s.z.object({task:lt,variant:s.z.string(),key:s.z.string().optional(),details:s.z.record(s.z.unknown()).or(s.z.string().transform(t=>t===""?{}:JSON.parse(t))).or(s.z.array(s.z.unknown())).or(s.z.null())}),pn=s.z.object({key:lt,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(t=>t===""?{}:ot.JSON_CODEC.decodeString(t))),state:Hr.optional().nullable(),snapshot:s.z.boolean().optional()}),Xg=pn.omit({key:!0}).extend({key:lt.transform(t=>t.toString()).optional(),config:s.z.unknown().transform(t=>ot.JSON_CODEC.encodeString(t))});s.z.object({task:lt,type:s.z.string(),key:s.z.string(),args:s.z.record(s.z.unknown()).or(s.z.string().transform(t=>t===""?{}:JSON.parse(t)))});const _t="sy_task_state",Hi="sy_task_cmd",ur=new Error("Task not created");class Qg{constructor(e,r,n,i,a=!1,o=!1,l,u=null,d=null,f=null){c(this,"key"),c(this,"name"),c(this,"internal"),c(this,"type"),c(this,"config"),c(this,"snapshot"),c(this,"state"),c(this,"frameClient"),c(this,"ontologyClient"),c(this,"rangeClient"),this.key=e,this.name=r,this.type=n,this.config=i,this.internal=a,this.snapshot=o,l!==null&&(this.state=l),this.frameClient=u,this.ontologyClient=d,this.rangeClient=f}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 k({type:"task",key:this.key})}async executeCommand(e,r){if(this.frameClient==null)throw ur;const n=await this.frameClient.openWriter(Hi),i=Jd.id();return await n.write(Hi,[{task:this.key,type:e,key:i,args:r}]),await n.close(),i}async executeCommandSync(e,r,n){if(this.frameClient==null)throw ur;const i=await this.frameClient.openStreamer(_t),a=await this.executeCommand(e,r);let o;const l=new Promise(u=>setTimeout(()=>u(!1),new A(n).milliseconds));for(;;){const u=await Promise.any([i.read(),l]);if(u===!1)throw new Error("Command timed out");const d=Hr.safeParse(u.at(-1).sy_task_state);if(d.success){if(o=d.data,o.key===a)break}else console.error(d.error)}return i.close(),o}async openStateObserver(){if(this.frameClient==null)throw ur;return new yn(await this.frameClient.openStreamer(_t),e=>{const r=e.get(_t);if(r.length===0)return[null,!1];const n=Hr.safeParse(r.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 ur;if(!this.snapshot)return null;const e=await this.ontologyClient.retrieveParents(this.ontologyID);return e.length==0?null:e[0]}}const ep=s.z.object({rack:rr.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()}),tp=s.z.object({tasks:pe(pn)}),rp="/hardware/task/retrieve",np="/hardware/task/create",sp="/hardware/task/delete",ip="/hardware/task/copy",ap=s.z.object({tasks:Xg.array()}),op=s.z.object({tasks:pn.array()}),cp=s.z.object({keys:lt.array()}),lp=s.z.object({}),up=s.z.object({key:lt,name:s.z.string(),snapshot:s.z.boolean()}),hp=s.z.object({task:pn});let dp=class{constructor(t,e,r,n){c(this,"type","task"),c(this,"client"),c(this,"frameClient"),c(this,"ontologyClient"),c(this,"rangeClient"),this.client=t,this.frameClient=e,this.ontologyClient=r,this.rangeClient=n}async create(t){const e=!Array.isArray(t),r=await v(this.client,np,{tasks:T(t)},ap,op),n=this.sugar(r.tasks);return e?n[0]:n}async delete(t){await v(this.client,sp,{keys:T(t)},cp,lp)}async search(t){return await this.execRetrieve({keys:[t]})}async page(t,e){return await this.execRetrieve({offset:t,limit:e})}async list(t={}){return this.sugar(await this.execRetrieve(t))}async retrieve(t,e){const{single:r,normalized:n,variant:i}=un(t,{number:"rack",string:"keys"},{convertNumericStrings:!1}),a={...e};i==="rack"?a.rack=t:a.keys=n;const o=await this.execRetrieve(a),l=this.sugar(o);return r&&i!=="rack"?l[0]:l}async copy(t,e,r){const n=await v(this.client,ip,{key:t,name:e,snapshot:r},up,hp);return this.sugar([n.task])[0]}async retrieveByName(t,e){const r=await this.execRetrieve({names:[t],rack:e});return hn("Task",t,r,!0),this.sugar(r)[0]}async execRetrieve(t){return(await v(this.client,rp,t,ep,tp)).tasks}sugar(t){return t.map(({key:e,name:r,type:n,config:i,state:a,internal:o,snapshot:l})=>new Qg(e,r,n,i,o,l,a,this.frameClient,this.ontologyClient,this.rangeClient))}async openTracker(){return await ct(this.frameClient,"sy_task_set","sy_task_delete",(t,e)=>Array.from(e).map(r=>({variant:t,key:r.toString(),value:r.toString()})))}async openStateObserver(){return new yn(await this.frameClient.openStreamer(_t),t=>{const e=t.get(_t);if(e.length===0)return[null,!1];const r=Hr.safeParse(e.at(-1));return r.success?[r.data,!0]:[null,!1]})}};const nr=s.z.string().uuid(),mn=s.z.object({key:nr,name:s.z.string().min(1),color:s.z.string()}),fp=s.z.object({keys:nr.array().optional(),for:ye.optional(),search:s.z.string().optional(),offset:s.z.number().optional(),limit:s.z.number().optional()}),yp=s.z.object({labels:pe(mn)});var hr;let gp=(hr=class{constructor(t){c(this,"client"),this.client=t}async retrieve(t){const e=T(t);return await this.execute({keys:e})}async retrieveFor(t){return await this.execute({for:t})}async search(t){return await this.execute({search:t})}async page(t,e){return await this.execute({offset:t,limit:e})}async execute(t){const[e,r]=await this.client.send(hr.ENDPOINT,t,fp,yp);if(r!=null)throw r;return e.labels}},c(hr,"ENDPOINT","/label/retrieve"),hr);const pp=mn.extend({key:nr.optional()}),mp=s.z.object({labels:pp.array()}),wp=s.z.object({labels:mn.array()}),bp=s.z.object({keys:nr.array()}),ic=s.z.object({id:ye,labels:nr.array(),replace:s.z.boolean().optional()}),vp=ic.omit({replace:!0}),Ln=s.z.object({}),Op="/label/create",Tp="/label/delete",Sp="/label/set",zp="/label/remove";let Np=class{constructor(t){c(this,"client"),this.client=t}async create(t){return(await v(this.client,Op,{labels:T(t)},mp,wp)).labels}async delete(t){await v(this.client,Tp,{keys:T(t)},bp,Ln)}async set(t,e,{replace:r}={}){await v(this.client,Sp,{id:t,labels:e,replace:r},ic,Ln)}async remove(t,e){await v(this.client,zp,{id:t,labels:e},vp,Ln)}};const Ep="sy_label_set",Ip="sy_label_delete";let Ap=class{constructor(t,e,r){c(this,"type","label"),c(this,"retriever"),c(this,"writer"),c(this,"frameClient"),c(this,"ontology"),this.writer=new Np(t),this.retriever=new gp(t),this.frameClient=e,this.ontology=r}async search(t){return await this.retriever.search(t)}async retrieve(t){const e=Array.isArray(t),r=await this.retriever.retrieve(t);return e?r:r[0]}async retrieveFor(t){return await this.retriever.retrieveFor(new k(t))}async label(t,e,r={}){await this.writer.set(new k(t),e,r)}async removeLabels(t,e){await this.writer.remove(new k(t),e)}async page(t,e){return await this.retriever.page(t,e)}async create(t){const e=Array.isArray(t),r=await this.writer.create(t);return e?r:r[0]}async delete(t){await this.writer.delete(t)}async openChangeTracker(){return await ct(this.frameClient,Ep,Ip,kp)}async trackLabelsOf(t){const e=new Je.Observer,r=(await this.retrieveFor(t)).map(n=>({id:new k({key:n.key,type:"label"}),key:n.key,name:n.name,data:n}));return(await this.ontology.openDependentTracker({target:new k(t),dependents:r,relationshipType:"labeled_by"})).onChange(n=>e.notify(n.map(i=>{var a,o;return{key:i.id.key,color:(a=i.data)==null?void 0:a.color,name:(o=i.data)==null?void 0:o.name}}))),e}};const kp=(t,e)=>t==="delete"?e.toUUIDs().map(r=>({variant:t,key:r})):e.parseJSON(mn).map(r=>({variant:t,key:r.key,value:r})),fe=s.z.string().uuid(),sr=s.z.object({key:fe,name:s.z.string().min(1),timeRange:se.z,color:s.z.string().optional()}),ac=sr.extend({key:s.z.string().uuid().optional()}),oc=t=>{const e=T(t),r=e.length===0;let n=!1;return r||(n=fe.safeParse(e[0]).success),{single:!Array.isArray(t),variant:n?"keys":"names",normalized:e,actual:t,empty:r}},cc="range",lc="range-alias",xp=t=>new k({type:cc,key:t}),Cp=t=>new k({type:lc,key:t}),$p="sy_range_alias_set",Rp="sy_range_alias_delete",jp=s.z.object({range:fe,aliases:s.z.string().array()}),Mp=s.z.object({aliases:s.z.record(s.z.string(),_e)}),Dp=s.z.object({range:fe,aliases:s.z.record(_e.or(s.z.string()),s.z.string())}),Pp=s.z.unknown(),Bp=s.z.object({range:fe,channels:_e.array()}),Up=s.z.unknown(),Lp=s.z.object({range:fe}),_p=s.z.object({aliases:s.z.record(s.z.string(),s.z.string())}),Rt=class jt{constructor(e,r,n){c(this,"frameClient"),c(this,"cache",new Map),c(this,"client"),c(this,"rangeKey"),this.rangeKey=e,this.cache=new Map,this.client=n,this.frameClient=r}async resolve(e){const r=[],n=typeof e=="string",i={};if(n){const o=this.cache.get(e);if(o!=null)return o;r.push(e)}else e.forEach(o=>{const l=this.cache.get(o);l!=null?i[o]=l:r.push(o)});if(r.length===0)return i;const a=await v(this.client,jt.RESOLVE_ENDPOINT,{range:this.rangeKey,aliases:r},jp,Mp);return Object.entries(a.aliases).forEach(([o,l])=>this.cache.set(o,l)),n?a.aliases[r[0]]:{...i,...a.aliases}}async set(e){await v(this.client,jt.SET_ENDPOINT,{range:this.rangeKey,aliases:e},Dp,Pp)}async list(){return(await v(this.client,jt.LIST_ENDPOINT,{range:this.rangeKey},Lp,_p)).aliases}async delete(e){await v(this.client,jt.DELETE_ENDPOINT,{range:this.rangeKey,channels:e},Bp,Up)}async openChangeTracker(){return await ct(this.frameClient,$p,Rp,Vp(this.rangeKey))}};c(Rt,"SET_ENDPOINT","/range/alias/set"),c(Rt,"RESOLVE_ENDPOINT","/range/alias/resolve"),c(Rt,"LIST_ENDPOINT","/range/alias/list"),c(Rt,"DELETE_ENDPOINT","/range/alias/delete");let Yp=Rt;const qp=s.z.object({range:fe,channel:_e,alias:s.z.string()}),Fp="---",Vp=t=>(e,r)=>e==="delete"?r.toStrings().filter(n=>n.split(Fp)[0]===t).map(n=>({variant:e,key:n,value:void 0})):r.parseJSON(qp).map(n=>({variant:e,key:n.alias,value:n})),Wp=s.z.object({range:fe,keys:s.z.string().array()}),Us=s.z.object({range:fe,key:s.z.string(),value:s.z.string()}),Gp=s.z.object({pairs:pe(Us)}),Zp=s.z.object({range:fe,pairs:Us.array()}),Kp=s.z.object({range:fe,keys:s.z.string().array()}),Fr=class Vr{constructor(e,r,n){c(this,"rangeKey"),c(this,"client"),c(this,"frameClient"),this.rangeKey=e,this.client=r,this.frameClient=n}async get(e){const r=await v(this.client,Vr.GET_ENDPOINT,{range:this.rangeKey,keys:T(e)},Wp,Gp);return typeof e=="string"?r.pairs[0].value:Object.fromEntries(r.pairs.map(n=>[n.key,n.value]))}async list(){return this.get([])}async set(e,r=""){let n;Ss(e)?n=Object.entries(e).map(([i,a])=>({range:this.rangeKey,key:i,value:a})):n=[{range:this.rangeKey,key:e,value:r}],await v(this.client,Vr.SET_ENDPOINT,{range:this.rangeKey,pairs:n},Zp,s.z.unknown())}async delete(e){await v(this.client,Vr.DELETE_ENDPOINT,{range:this.rangeKey,keys:T(e)},Kp,s.z.unknown())}async openTracker(){return await ct(this.frameClient,"sy_range_kv_set","sy_range_kv_delete",(e,r)=>e==="delete"?r.toStrings().map(n=>{const[i,a]=n.split("<--->",2);return{variant:e,key:n,value:{range:i,key:a,value:""}}}):r.parseJSON(Us).map(n=>({variant:e,key:`${n.range}${n.key}`,value:n})))}};c(Fr,"GET_ENDPOINT","/range/kv/get"),c(Fr,"SET_ENDPOINT","/range/kv/set"),c(Fr,"DELETE_ENDPOINT","/range/kv/delete");let cs=Fr;const _n=t=>new k({type:"range",key:t});class uc{constructor(e,r=se.ZERO,n,i,a,o,l,u,d,f,h){c(this,"key"),c(this,"name"),c(this,"kv"),c(this,"timeRange"),c(this,"color"),c(this,"channels"),c(this,"aliaser"),c(this,"frameClient"),c(this,"labelClient"),c(this,"ontologyClient"),c(this,"rangeClient"),this.key=n,this.name=e,this.timeRange=r,this.frameClient=a,this.color=i,this.kv=o,this.aliaser=l,this.channels=u,this.labelClient=d,this.ontologyClient=f,this.rangeClient=h}get ontologyID(){return new k({key:this.key,type:"range"})}get payload(){return{key:this.key,name:this.name,timeRange:this.timeRange,color:this.color}}async setAlias(e,r){const n=await this.channels.retrieve(e);if(n.length===0)throw new ve(`Channel ${e} does not exist`);await this.aliaser.set({[n[0].key]:r})}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(r=>r.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(_n(this.key))}async addLabel(...e){await this.labelClient.label(_n(this.key),e)}async removeLabel(...e){await this.labelClient.removeLabels(_n(this.key),e)}async openChildRangeTracker(){const e=new Je.Observer,r=(await this.retrieveChildren()).map(i=>{const a=new k({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:r,resourceType:"range"});return n.onChange(i=>e.notify(this.rangeClient.resourcesToRanges(i))),e.setCloser(async()=>await n.close()),e}async openParentRangeTracker(){const e=new Je.Observer,r=await this.retrieveParent();if(r==null)return null;const n=new k({key:r.key,type:"range"}),i={id:n,key:n.toString(),name:r.name,data:r.payload},a=await this.ontologyClient.openDependentTracker({target:this.ontologyID,dependents:[i],relationshipDirection:"to"});return a.onChange(o=>{const l=this.rangeClient.resourcesToRanges(o);if(l.length===0)return;const u=l[0];e.notify(u)}),e.setCloser(async()=>await a.close()),e}}const Jp=s.z.object({keys:fe.array().optional(),names:s.z.array(s.z.string()).optional(),term:s.z.string().optional(),overlapsWith:se.z.optional(),limit:s.z.number().int().optional(),offset:s.z.number().int().optional()}),Hp="/range/retrieve",Xp=s.z.object({ranges:pe(sr)});let hc=class{constructor(t,e,r,n,i,a){c(this,"type","range"),c(this,"frameClient"),c(this,"writer"),c(this,"unaryClient"),c(this,"channels"),c(this,"labelClient"),c(this,"ontologyClient"),this.frameClient=t,this.writer=e,this.unaryClient=r,this.channels=n,this.labelClient=i,this.ontologyClient=a}async create(t,e){const r=!Array.isArray(t),n=this.sugarMany(await this.writer.create(T(t),e));return r?n[0]:n}async rename(t,e){await this.writer.rename(t,e)}async delete(t){await this.writer.delete(T(t))}async search(t){return this.sugarMany(await this.execRetrieve({term:t}))}async page(t,e){return this.sugarMany(await this.execRetrieve({offset:t,limit:e}))}async retrieve(t){if(typeof t=="object"&&"start"in t)return await this.execRetrieve({overlapsWith:new se(t)});const{single:e,actual:r,variant:n,normalized:i,empty:a}=oc(t);if(a)return[];const o=await this.execRetrieve({[n]:i});if(!e)return o;if(o.length===0)throw new st(`range matching ${r} not found`);if(o.length>1)throw new it(`multiple ranges matching ${r} found`);return o[0]}getKV(t){return new cs(t,this.unaryClient,this.frameClient)}async execRetrieve(t){const{ranges:e}=await v(this.unaryClient,Hp,t,Jp,Xp);return this.sugarMany(e)}async retrieveParent(t){const e=await this.ontologyClient.retrieveParents({key:t,type:"range"});if(e.length===0)return null;const r=e[0];return r.id.type!=="range"?null:await this.retrieve(r.id.key)}sugarOne(t){return new uc(t.name,t.timeRange,t.key,t.color,this.frameClient,new cs(t.key,this.unaryClient,this.frameClient),new Yp(t.key,this.frameClient,this.unaryClient),this.channels,this.labelClient,this.ontologyClient,this)}sugarMany(t){return t.map(e=>this.sugarOne(e))}async openTracker(){return await ct(this.frameClient,"sy_range_set","sy_range_delete",(t,e)=>t==="delete"?e.toStrings().map(r=>({variant:t,key:r,value:void 0})):this.sugarMany(e.parseJSON(sr)).map(r=>({variant:t,key:r.key,value:r})))}resourcesToRanges(t){return t.map(e=>this.resourceToRange(e))}resourceToRange(t){var e,r,n;return this.sugarOne({key:t.id.key,name:(e=t.data)==null?void 0:e.name,timeRange:new se((r=t.data)==null?void 0:r.timeRange),color:(n=t.data)==null?void 0:n.color})}};const Qp=s.z.object({ranges:sr.array()}),em=s.z.object({parent:ye.optional(),ranges:ac.array()}),tm=s.z.object({keys:fe.array()}),rm=s.z.object({}),nm=s.z.object({key:fe,name:s.z.string()}),sm=s.z.object({}),im="/range/create",am="/range/delete",om="/range/rename";let dc=class{constructor(t){c(this,"client"),this.client=t}async rename(t,e){await v(this.client,om,{key:t,name:e},nm,sm)}async create(t,e){return(await v(this.client,im,{ranges:t,...e},em,Qp)).ranges}async delete(t){await v(this.client,am,{keys:t},tm,rm)}};const cm=Object.freeze(Object.defineProperty({__proto__:null,ALIAS_ONTOLOGY_TYPE:lc,Client:hc,KV:cs,ONTOLOGY_TYPE:cc,Range:uc,Writer:dc,analyzeParams:oc,keyZ:fe,newPayloadZ:ac,payloadZ:sr,rangeAliasOntologyID:Cp,rangeOntologyID:xp},Symbol.toStringTag,{value:"Module"})),lm="/api/v1/";class um{constructor(e,r=!1){c(this,"url"),c(this,"unary"),c(this,"stream"),c(this,"secure"),this.secure=r,this.url=e.child(lm);const n=new ot.JSONCodec;this.unary=new Wh(this.url,n,this.secure),this.stream=new td(this.url,n,this.secure)}use(...e){this.unary.use(...e),this.stream.use(...e)}}const Ls=s.z.string().uuid(),_s=s.z.object({key:s.z.string(),name:s.z.string(),data:Es.or(s.z.string().transform(t=>JSON.parse(t)))}),hm=s.z.object({keys:s.z.string().array()}),dm=s.z.object({linePlots:_s.array()});let fm=class{constructor(t){c(this,"ENDPOINT","/workspace/lineplot/retrieve"),c(this,"client"),this.client=t}async retrieve(t){const e=T(t);return(await v(this.client,this.ENDPOINT,{keys:e},hm,dm)).linePlots}};const He=s.z.string().uuid(),fc=t=>JSON.parse(t),yc=s.z.object({name:s.z.string(),key:He,layout:Es.or(s.z.string().transform(t=>fc(t)))}),gc=yc.omit({layout:!0}).extend({layout:s.z.string().transform(t=>fc(t))}),ym=_s.partial({key:!0}).transform(t=>({...t,data:JSON.stringify(t.data)})),gm=s.z.object({workspace:He,linePlots:ym.array()}),pm=s.z.object({linePlots:_s.array()}),mm=s.z.object({keys:Ls.array()}),wm=s.z.object({}),bm=s.z.object({key:Ls,name:s.z.string()}),vm=s.z.object({}),Om=s.z.object({key:Ls,data:s.z.string()}),Tm=s.z.object({}),Sm="/workspace/lineplot/create",zm="/workspace/lineplot/delete",Nm="/workspace/lineplot/rename",Em="/workspace/lineplot/set-data";let Im=class{constructor(t){c(this,"client"),this.client=t}async create(t,e){const r={...e,data:JSON.stringify(e.data)};return(await v(this.client,Sm,{workspace:t,linePlots:[r]},gm,pm)).linePlots[0]}async delete(t){const e=T(t);await v(this.client,zm,{keys:e},mm,wm)}async rename(t,e){await v(this.client,Nm,{key:t,name:e},bm,vm)}async setData(t,e){await v(this.client,Em,{key:t,data:JSON.stringify(e)},Om,Tm)}},Am=class{constructor(t){c(this,"writer"),c(this,"retriever"),this.writer=new Im(t),this.retriever=new fm(t)}async create(t,e){return await this.writer.create(t,e)}async rename(t,e){await this.writer.rename(t,e)}async setData(t,e){await this.writer.setData(t,e)}async retrieve(t){const e=Array.isArray(t),r=await this.retriever.retrieve(t);return e?r:r[0]}async delete(t){await this.writer.delete(t)}};const km=s.z.object({keys:He.array().optional(),search:s.z.string().optional(),author:s.z.string().uuid().optional(),offset:s.z.number().optional(),limit:s.z.number().optional()}),xm=s.z.object({workspaces:pe(gc)});var dr;let Cm=(dr=class{constructor(t){c(this,"client"),this.client=t}async retrieve(t){const e=T(t);return await this.execute({keys:e})}async retrieveByAuthor(t){return await this.execute({author:t})}async search(t){return await this.execute({search:t})}async page(t,e){return await this.execute({offset:t,limit:e})}async execute(t){return(await v(this.client,dr.ENDPOINT,t,km,xm)).workspaces}},c(dr,"ENDPOINT","/workspace/retrieve"),dr);const wn=s.z.string().uuid(),$m=s.z.object({key:s.z.string(),name:s.z.string(),data:Es.or(s.z.string().transform(t=>JSON.parse(t))),snapshot:s.z.boolean()}),Ys=s.z.object({key:s.z.string(),name:s.z.string(),snapshot:s.z.boolean(),data:s.z.string().transform(t=>JSON.parse(t))}),Rm=s.z.object({keys:s.z.string().array()}),jm=s.z.object({schematics:Ys.array()});class Mm{constructor(e){c(this,"ENDPOINT","/workspace/schematic/retrieve"),c(this,"client"),this.client=e}async retrieve(e){return(await v(this.client,this.ENDPOINT,{keys:T(e)},Rm,jm)).schematics}}const Dm=$m.partial({key:!0,snapshot:!0}).transform(t=>({...t,data:JSON.stringify(t.data)})),Pm=s.z.object({workspace:He,schematics:Dm.array()}),Bm=s.z.object({schematics:Ys.array()}),Um=s.z.object({keys:wn.array()}),Lm=s.z.object({}),_m=s.z.object({key:wn,name:s.z.string()}),Xi=s.z.object({}),Ym=s.z.object({key:wn,data:s.z.string()});s.z.object({});const qm=s.z.object({key:wn,name:s.z.string(),snapshot:s.z.boolean()}),Fm=s.z.object({schematic:Ys}),Vm="/workspace/schematic/create",Wm="/workspace/schematic/delete",Gm="/workspace/schematic/rename",Zm="/workspace/schematic/set-data",Km="/workspace/schematic/copy";let Jm=class{constructor(t){c(this,"client"),this.client=t}async create(t,e){const r={...e,data:JSON.stringify(e.data)};return(await v(this.client,Vm,{workspace:t,schematics:[r]},Pm,Bm)).schematics[0]}async copy(t,e,r){return(await v(this.client,Km,{key:t,name:e,snapshot:r},qm,Fm)).schematic}async delete(t){const e=T(t);await v(this.client,Wm,{keys:e},Um,Lm)}async rename(t,e){await v(this.client,Gm,{key:t,name:e},_m,Xi)}async setData(t,e){await v(this.client,Zm,{key:t,data:JSON.stringify(e)},Ym,Xi)}},Hm=class{constructor(t){c(this,"writer"),c(this,"retriever"),this.writer=new Jm(t),this.retriever=new Mm(t)}async create(t,e){return await this.writer.create(t,e)}async rename(t,e){await this.writer.rename(t,e)}async setData(t,e){await this.writer.setData(t,e)}async retrieve(t){const e=Array.isArray(t),r=await this.retriever.retrieve(t);return e?r:r[0]}async delete(t){await this.writer.delete(t)}async copy(t,e,r){return await this.writer.copy(t,e,r)}};const Xm=yc.partial({key:!0}).transform(t=>({...t,layout:JSON.stringify(t.layout)})),Qm=s.z.object({workspaces:Xm.array()}),ew=s.z.object({workspaces:gc.array()}),tw=s.z.object({keys:He.array()}),rw=s.z.object({}),nw=s.z.object({key:He,name:s.z.string()}),sw=s.z.object({}),iw=s.z.object({key:He,layout:s.z.string()}),aw=s.z.object({}),ow="/workspace/create",cw="/workspace/delete",lw="/workspace/rename",uw="/workspace/set-layout";class hw{constructor(e){c(this,"client"),this.client=e}async create(e){return(await v(this.client,ow,{workspaces:T(e)},Qm,ew)).workspaces}async delete(e){await v(this.client,cw,{keys:T(e)},tw,rw)}async rename(e,r){await v(this.client,lw,{key:e,name:r},nw,sw)}async setLayout(e,r){await v(this.client,uw,{key:e,layout:JSON.stringify(r)},iw,aw)}}class dw{constructor(e){c(this,"type","workspace"),c(this,"schematic"),c(this,"linePlot"),c(this,"retriever"),c(this,"writer"),this.schematic=new Hm(e),this.linePlot=new Am(e),this.retriever=new Cm(e),this.writer=new hw(e)}async search(e){return await this.retriever.search(e)}async retrieveByAuthor(e){return await this.retriever.retrieveByAuthor(e)}async retrieve(e){const r=Array.isArray(e),n=await this.retriever.retrieve(e);return r?n:n[0]}async page(e,r){return await this.retriever.page(e,r)}async create(e){const r=Array.isArray(e),n=await this.writer.create(e);return r?n:n[0]}async rename(e,r){await this.writer.rename(e,r)}async setLayout(e,r){await this.writer.setLayout(e,r)}async delete(...e){await this.writer.delete(e)}}const pc=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:A.z.default(A.seconds(30)),secure:s.z.boolean().optional().default(!1),name:s.z.string().optional()});class mc extends Ng{constructor(e){const r=pc.parse(e),{host:n,port:i,username:a,password:o,connectivityPollFrequency:l,secure:u}=r,d=new um(new wf({host:n,port:Number(i)}),u);d.use(xf);let f;a!=null&&o!=null&&(f=new rg(d.unary,{username:a,password:o}),d.use(f.middleware()));const h=new xs(new ks(d.unary)),E=new Ho(d.unary,h);super(d.stream,d.unary,h),c(this,"createdAt"),c(this,"props"),c(this,"ranges"),c(this,"channels"),c(this,"auth"),c(this,"user"),c(this,"access"),c(this,"connectivity"),c(this,"ontology"),c(this,"workspaces"),c(this,"labels"),c(this,"hardware"),c(this,"control"),c(this,"transport"),c(this,"clientVersion","0.32.0"),this.createdAt=x.now(),this.props=r,this.auth=f,this.transport=d,this.channels=new Jo(this,h,d.unary,E),this.connectivity=new ec(d.unary,l,this.clientVersion,r.name),this.control=new sc(this),this.ontology=new Gf(d.unary,this);const P=new dc(this.transport.unary);this.labels=new Ap(this.transport.unary,this,this.ontology),this.ranges=new hc(this,P,this.transport.unary,h,this.labels,this.ontology),this.access=new cy(this.transport.unary),this.user=new Ky(this.transport.unary),this.workspaces=new dw(this.transport.unary);const ie=new Yg(this.transport.unary,this),M=new dp(this.transport.unary,this,this.ontology,this.ranges),Pc=new Jg(this.transport.unary,this,M);this.hardware=new Cg(M,Pc,ie)}get key(){return this.createdAt.valueOf().toString()}close(){this.connectivity.stopChecking()}}c(mc,"connectivity",ec);const fw=nt.Authority,ls=(t,e,r="")=>{try{return t.parse(e)}catch(n){if(n instanceof s.z.ZodError){const i=n.errors.map(a=>a.path.length===0?a.message:`${a.path.join(".")}: ${a.message}`);throw new Error(`${r} - ${i.join(`
|
|
66
|
+
`)}`)}else throw n}};var yw=Object.defineProperty,gw=(t,e,r)=>e in t?yw(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,ee=(t,e,r)=>gw(t,typeof e!="symbol"?e+"":e,r);const us=class wc{constructor(e,r,n="",i=!1){ee(this,"_noop",!1),ee(this,"key"),ee(this,"path"),ee(this,"serviceName"),this.key=e,this.path=r,this.serviceName=n,this._noop=i}child(e){return new wc(e,this.extendPath(e),this.serviceName,this.noop)}extendPath(e){return`${this.path}.${e}`}get noop(){return this._noop}};ee(us,"NOOP",new us("","",""));let qs=us;const hs=["debug","info","warn","error"],pw=t=>{const e=hs.indexOf(t);return({level:r})=>hs.indexOf(r)>=e},mw=t=>{const{include:e,exclude:r}=t;return({path:n})=>!(e!=null&&!e.some(i=>n.startsWith(i))||r!=null&&r.some(i=>n.startsWith(i)))},ds=class bc{constructor(e={}){ee(this,"meta",qs.NOOP),ee(this,"filters");const{filters:r=[]}=e;this.filters=r}filter(e){return!this.meta.noop&&this.filters.every(r=>r({key:this.meta.key,path:this.meta.path,level:e}))}child(e){const r=new bc({filters:this.filters});return r.meta=e,r}debug(e,r,n=!1){!this.filter("debug")&&!n||(r==null?console.log("%cDEBUG","color: #8c00f0;",this.meta.path,e):console.log("%cDEBUG","color: #8c00f0;",this.meta.path,e,fr(r)))}info(e,r,n=!1){!this.filter("info")&&!n||(r==null?console.log("%cINFO","color: #005eff;",this.meta.path,e):console.log("%cINFO","color: #005eff;",this.meta.path,e,fr(r)))}warn(e,r,n=!1){!this.filter("warn")&&!n||(r==null?console.warn("WARN",this.meta.path,e):console.warn("WARN",this.meta.path,e,fr(r)))}error(e,r,n=!1){!this.filter("error")&&!n||(r==null?console.error("ERROR",this.meta.path,e):console.error("ERROR",this.meta.path,e,fr(r)))}};ee(ds,"NOOP",new ds);let vc=ds;const fr=t=>typeof t=="function"?t():t;var ww=typeof globalThis=="object"?globalThis:typeof self=="object"?self:typeof window=="object"?window:typeof global=="object"?global:{},Ze="1.8.0",Qi=/^(\d+)\.(\d+)\.(\d+)(-(.+))?$/;function bw(t){var e=new Set([t]),r=new Set,n=t.match(Qi);if(!n)return function(){return!1};var i={major:+n[1],minor:+n[2],patch:+n[3],prerelease:n[4]};if(i.prerelease!=null)return function(l){return l===t};function a(l){return r.add(l),!1}function o(l){return e.add(l),!0}return function(l){if(e.has(l))return!0;if(r.has(l))return!1;var u=l.match(Qi);if(!u)return a(l);var d={major:+u[1],minor:+u[2],patch:+u[3],prerelease:u[4]};return d.prerelease!=null||i.major!==d.major?a(l):i.major===0?i.minor===d.minor&&i.patch<=d.patch?o(l):a(l):i.minor<=d.minor?o(l):a(l)}}var vw=bw(Ze),Ow=Ze.split(".")[0],Vt=Symbol.for("opentelemetry.js.api."+Ow),Wt=ww;function Fs(t,e,r,n){var i;n===void 0&&(n=!1);var a=Wt[Vt]=(i=Wt[Vt])!==null&&i!==void 0?i:{version:Ze};if(!n&&a[t]){var o=new Error("@opentelemetry/api: Attempted duplicate registration of API: "+t);return r.error(o.stack||o.message),!1}if(a.version!==Ze){var o=new Error("@opentelemetry/api: Registration of version v"+a.version+" for "+t+" does not match previously registered API v"+Ze);return r.error(o.stack||o.message),!1}return a[t]=e,r.debug("@opentelemetry/api: Registered a global for "+t+" v"+Ze+"."),!0}function Gt(t){var e,r,n=(e=Wt[Vt])===null||e===void 0?void 0:e.version;if(!(!n||!vw(n)))return(r=Wt[Vt])===null||r===void 0?void 0:r[t]}function Vs(t,e){e.debug("@opentelemetry/api: Unregistering a global for "+t+" v"+Ze+".");var r=Wt[Vt];r&&delete r[t]}var Tw=function(t,e){var r=typeof Symbol=="function"&&t[Symbol.iterator];if(!r)return t;var n=r.call(t),i,a=[],o;try{for(;(e===void 0||e-- >0)&&!(i=n.next()).done;)a.push(i.value)}catch(l){o={error:l}}finally{try{i&&!i.done&&(r=n.return)&&r.call(n)}finally{if(o)throw o.error}}return a},Sw=function(t,e,r){if(arguments.length===2)for(var n=0,i=e.length,a;n<i;n++)(a||!(n in e))&&(a||(a=Array.prototype.slice.call(e,0,n)),a[n]=e[n]);return t.concat(a||Array.prototype.slice.call(e))},zw=function(){function t(e){this._namespace=e.namespace||"DiagComponentLogger"}return t.prototype.debug=function(){for(var e=[],r=0;r<arguments.length;r++)e[r]=arguments[r];return gt("debug",this._namespace,e)},t.prototype.error=function(){for(var e=[],r=0;r<arguments.length;r++)e[r]=arguments[r];return gt("error",this._namespace,e)},t.prototype.info=function(){for(var e=[],r=0;r<arguments.length;r++)e[r]=arguments[r];return gt("info",this._namespace,e)},t.prototype.warn=function(){for(var e=[],r=0;r<arguments.length;r++)e[r]=arguments[r];return gt("warn",this._namespace,e)},t.prototype.verbose=function(){for(var e=[],r=0;r<arguments.length;r++)e[r]=arguments[r];return gt("verbose",this._namespace,e)},t}();function gt(t,e,r){var n=Gt("diag");if(n)return r.unshift(e),n[t].apply(n,Sw([],Tw(r),!1))}var ge;(function(t){t[t.NONE=0]="NONE",t[t.ERROR=30]="ERROR",t[t.WARN=50]="WARN",t[t.INFO=60]="INFO",t[t.DEBUG=70]="DEBUG",t[t.VERBOSE=80]="VERBOSE",t[t.ALL=9999]="ALL"})(ge||(ge={}));function Nw(t,e){t<ge.NONE?t=ge.NONE:t>ge.ALL&&(t=ge.ALL),e=e||{};function r(n,i){var a=e[n];return typeof a=="function"&&t>=i?a.bind(e):function(){}}return{error:r("error",ge.ERROR),warn:r("warn",ge.WARN),info:r("info",ge.INFO),debug:r("debug",ge.DEBUG),verbose:r("verbose",ge.VERBOSE)}}var Ew=function(t,e){var r=typeof Symbol=="function"&&t[Symbol.iterator];if(!r)return t;var n=r.call(t),i,a=[],o;try{for(;(e===void 0||e-- >0)&&!(i=n.next()).done;)a.push(i.value)}catch(l){o={error:l}}finally{try{i&&!i.done&&(r=n.return)&&r.call(n)}finally{if(o)throw o.error}}return a},Iw=function(t,e,r){if(arguments.length===2)for(var n=0,i=e.length,a;n<i;n++)(a||!(n in e))&&(a||(a=Array.prototype.slice.call(e,0,n)),a[n]=e[n]);return t.concat(a||Array.prototype.slice.call(e))},Aw="diag",Zt=function(){function t(){function e(i){return function(){for(var a=[],o=0;o<arguments.length;o++)a[o]=arguments[o];var l=Gt("diag");if(l)return l[i].apply(l,Iw([],Ew(a),!1))}}var r=this,n=function(i,a){var o,l,u;if(a===void 0&&(a={logLevel:ge.INFO}),i===r){var d=new Error("Cannot use diag as the logger for itself. Please use a DiagLogger implementation like ConsoleDiagLogger or a custom implementation");return r.error((o=d.stack)!==null&&o!==void 0?o:d.message),!1}typeof a=="number"&&(a={logLevel:a});var f=Gt("diag"),h=Nw((l=a.logLevel)!==null&&l!==void 0?l:ge.INFO,i);if(f&&!a.suppressOverrideMessage){var E=(u=new Error().stack)!==null&&u!==void 0?u:"<failed to generate stacktrace>";f.warn("Current logger will be overwritten from "+E),h.warn("Current logger will overwrite one already registered from "+E)}return Fs("diag",h,r,!0)};r.setLogger=n,r.disable=function(){Vs(Aw,r)},r.createComponentLogger=function(i){return new zw(i)},r.verbose=e("verbose"),r.debug=e("debug"),r.info=e("info"),r.warn=e("warn"),r.error=e("error")}return t.instance=function(){return this._instance||(this._instance=new t),this._instance},t}(),kw=function(t,e){var r=typeof Symbol=="function"&&t[Symbol.iterator];if(!r)return t;var n=r.call(t),i,a=[],o;try{for(;(e===void 0||e-- >0)&&!(i=n.next()).done;)a.push(i.value)}catch(l){o={error:l}}finally{try{i&&!i.done&&(r=n.return)&&r.call(n)}finally{if(o)throw o.error}}return a},xw=function(t){var e=typeof Symbol=="function"&&Symbol.iterator,r=e&&t[e],n=0;if(r)return r.call(t);if(t&&typeof t.length=="number")return{next:function(){return t&&n>=t.length&&(t=void 0),{value:t&&t[n++],done:!t}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")},Cw=function(){function t(e){this._entries=e?new Map(e):new Map}return t.prototype.getEntry=function(e){var r=this._entries.get(e);if(r)return Object.assign({},r)},t.prototype.getAllEntries=function(){return Array.from(this._entries.entries()).map(function(e){var r=kw(e,2),n=r[0],i=r[1];return[n,i]})},t.prototype.setEntry=function(e,r){var n=new t(this._entries);return n._entries.set(e,r),n},t.prototype.removeEntry=function(e){var r=new t(this._entries);return r._entries.delete(e),r},t.prototype.removeEntries=function(){for(var e,r,n=[],i=0;i<arguments.length;i++)n[i]=arguments[i];var a=new t(this._entries);try{for(var o=xw(n),l=o.next();!l.done;l=o.next()){var u=l.value;a._entries.delete(u)}}catch(d){e={error:d}}finally{try{l&&!l.done&&(r=o.return)&&r.call(o)}finally{if(e)throw e.error}}return a},t.prototype.clear=function(){return new t},t}();Zt.instance();function $w(t){return t===void 0&&(t={}),new Cw(new Map(Object.entries(t)))}function Rw(t){return Symbol.for(t)}var jw=function(){function t(e){var r=this;r._currentContext=e?new Map(e):new Map,r.getValue=function(n){return r._currentContext.get(n)},r.setValue=function(n,i){var a=new t(r._currentContext);return a._currentContext.set(n,i),a},r.deleteValue=function(n){var i=new t(r._currentContext);return i._currentContext.delete(n),i}}return t}(),Mw=new jw,Dw={get:function(t,e){if(t!=null)return t[e]},keys:function(t){return t==null?[]:Object.keys(t)}},Pw={set:function(t,e,r){t!=null&&(t[e]=r)}},Bw=function(t,e){var r=typeof Symbol=="function"&&t[Symbol.iterator];if(!r)return t;var n=r.call(t),i,a=[],o;try{for(;(e===void 0||e-- >0)&&!(i=n.next()).done;)a.push(i.value)}catch(l){o={error:l}}finally{try{i&&!i.done&&(r=n.return)&&r.call(n)}finally{if(o)throw o.error}}return a},Uw=function(t,e,r){if(arguments.length===2)for(var n=0,i=e.length,a;n<i;n++)(a||!(n in e))&&(a||(a=Array.prototype.slice.call(e,0,n)),a[n]=e[n]);return t.concat(a||Array.prototype.slice.call(e))},Lw=function(){function t(){}return t.prototype.active=function(){return Mw},t.prototype.with=function(e,r,n){for(var i=[],a=3;a<arguments.length;a++)i[a-3]=arguments[a];return r.call.apply(r,Uw([n],Bw(i),!1))},t.prototype.bind=function(e,r){return r},t.prototype.enable=function(){return this},t.prototype.disable=function(){return this},t}(),_w=function(t,e){var r=typeof Symbol=="function"&&t[Symbol.iterator];if(!r)return t;var n=r.call(t),i,a=[],o;try{for(;(e===void 0||e-- >0)&&!(i=n.next()).done;)a.push(i.value)}catch(l){o={error:l}}finally{try{i&&!i.done&&(r=n.return)&&r.call(n)}finally{if(o)throw o.error}}return a},Yw=function(t,e,r){if(arguments.length===2)for(var n=0,i=e.length,a;n<i;n++)(a||!(n in e))&&(a||(a=Array.prototype.slice.call(e,0,n)),a[n]=e[n]);return t.concat(a||Array.prototype.slice.call(e))},Yn="context",qw=new Lw,Oc=function(){function t(){}return t.getInstance=function(){return this._instance||(this._instance=new t),this._instance},t.prototype.setGlobalContextManager=function(e){return Fs(Yn,e,Zt.instance())},t.prototype.active=function(){return this._getContextManager().active()},t.prototype.with=function(e,r,n){for(var i,a=[],o=3;o<arguments.length;o++)a[o-3]=arguments[o];return(i=this._getContextManager()).with.apply(i,Yw([e,r,n],_w(a),!1))},t.prototype.bind=function(e,r){return this._getContextManager().bind(e,r)},t.prototype._getContextManager=function(){return Gt(Yn)||qw},t.prototype.disable=function(){this._getContextManager().disable(),Vs(Yn,Zt.instance())},t}(),fs;(function(t){t[t.UNSET=0]="UNSET",t[t.OK=1]="OK",t[t.ERROR=2]="ERROR"})(fs||(fs={}));var Fw=Oc.getInstance(),Vw=function(){function t(){}return t.prototype.inject=function(e,r){},t.prototype.extract=function(e,r){return e},t.prototype.fields=function(){return[]},t}(),Ws=Rw("OpenTelemetry Baggage Key");function Tc(t){return t.getValue(Ws)||void 0}function Ww(){return Tc(Oc.getInstance().active())}function Gw(t,e){return t.setValue(Ws,e)}function Zw(t){return t.deleteValue(Ws)}var qn="propagation",Kw=new Vw,Jw=function(){function t(){this.createBaggage=$w,this.getBaggage=Tc,this.getActiveBaggage=Ww,this.setBaggage=Gw,this.deleteBaggage=Zw}return t.getInstance=function(){return this._instance||(this._instance=new t),this._instance},t.prototype.setGlobalPropagator=function(e){return Fs(qn,e,Zt.instance())},t.prototype.inject=function(e,r,n){return n===void 0&&(n=Pw),this._getGlobalPropagator().inject(e,r,n)},t.prototype.extract=function(e,r,n){return n===void 0&&(n=Dw),this._getGlobalPropagator().extract(e,r,n)},t.prototype.fields=function(){return this._getGlobalPropagator().fields()},t.prototype.disable=function(){Vs(qn,Zt.instance())},t.prototype._getGlobalPropagator=function(){return Gt(qn)||Kw},t}(),Hw=Jw.getInstance();const ea=["bench","debug","prod"],Xw=t=>e=>ea.indexOf(e)>=ea.indexOf(t),ys=class Sc{constructor(e,r=Xw("debug")){ee(this,"meta",qs.NOOP),ee(this,"tracer"),ee(this,"filter"),this.tracer=e,this.filter=r}child(e){const r=new Sc(this.tracer,this.filter);return r.meta=e,r}debug(e,r){return this.trace(e,"debug",r)}bench(e,r){return this.trace(e,"bench",r)}prod(e,r){return this.trace(e,"prod",r)}trace(e,r,n){return this.meta.noop||!this.filter(r)?n(new Ec(e)):this.tracer.startActiveSpan(e,i=>{const a=new Nc(e,i),o=n(a);return i.end(),o})}propagate(e){if(this.meta.noop)return;const r=Fw.active();Hw.inject(r,e,{set:(n,i,a)=>{n[i]=a}})}};ee(ys,"NOOP",new ys);let zc=ys;class Nc{constructor(e,r){ee(this,"key"),ee(this,"otel"),this.key=e,this.otel=r}set(e,r){this.otel.setAttribute(e,r)}recordError(e){e!=null&&(this.otel.recordException(e),this.otel.setStatus({code:fs.ERROR}))}}class Ec{constructor(e){ee(this,"key"),this.key=e}set(){}recordError(e){}}const gs=class Ic{constructor({key:e="",serviceName:r="",logger:n=vc.NOOP,tracer:i=zc.NOOP,noop:a=!1,__meta:o}){ee(this,"meta"),ee(this,"T"),ee(this,"L"),this.meta=o??new qs(e,e,r,a),this.T=i.child(this.meta),this.L=n.child(this.meta)}child(e){const r=this.meta.child(e);return new Ic({__meta:r,tracer:this.T,logger:this.L})}};ee(gs,"NOOP",new gs({noop:!0}));let Gs=gs;const Qw=Gs.NOOP,Ac=Object.freeze(Object.defineProperty({__proto__:null,Instrumentation:Gs,LOG_LEVELS:hs,Logger:vc,NOOP:Qw,NoopSpan:Ec,Tracer:zc,_Span:Nc,logLevelKeyFiler:mw,logThresholdFilter:pw},Symbol.toStringTag,{value:"Module"})),eb=new Error("request for lock canceled");var tb=function(t,e,r,n){function i(a){return a instanceof r?a:new r(function(o){o(a)})}return new(r||(r=Promise))(function(a,o){function l(f){try{d(n.next(f))}catch(h){o(h)}}function u(f){try{d(n.throw(f))}catch(h){o(h)}}function d(f){f.done?a(f.value):i(f.value).then(l,u)}d((n=n.apply(t,e||[])).next())})};class rb{constructor(e,r=eb){this._value=e,this._cancelError=r,this._queue=[],this._weightedWaiters=[]}acquire(e=1,r=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:r},o=kc(this._queue,l=>r<=l.priority);o===-1&&e<=this._value?this._dispatchItem(a):this._queue.splice(o+1,0,a)})}runExclusive(e){return tb(this,arguments,void 0,function*(r,n=1,i=0){const[a,o]=yield this.acquire(n,i);try{return yield r(a)}finally{o()}})}waitForUnlock(e=1,r=0){if(e<=0)throw new Error(`invalid weight ${e}: must be positive`);return this._couldLockImmediately(e,r)?Promise.resolve():new Promise(n=>{this._weightedWaiters[e-1]||(this._weightedWaiters[e-1]=[]),nb(this._weightedWaiters[e-1],{resolve:n,priority:r})})}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 r=this._value;this._value-=e.weight,e.resolve([r,this._newReleaser(e.weight)])}_newReleaser(e){let r=!1;return()=>{r||(r=!0,this.release(e))}}_drainUnlockWaiters(){if(this._queue.length===0)for(let e=this._value;e>0;e--){const r=this._weightedWaiters[e-1];r&&(r.forEach(n=>n.resolve()),this._weightedWaiters[e-1]=[])}else{const e=this._queue[0].priority;for(let r=this._value;r>0;r--){const n=this._weightedWaiters[r-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,r){return(this._queue.length===0||this._queue[0].priority<r)&&e<=this._value}}function nb(t,e){const r=kc(t,n=>e.priority<=n.priority);t.splice(r+1,0,e)}function kc(t,e){for(let r=t.length-1;r>=0;r--)if(e(t[r]))return r;return-1}var sb=function(t,e,r,n){function i(a){return a instanceof r?a:new r(function(o){o(a)})}return new(r||(r=Promise))(function(a,o){function l(f){try{d(n.next(f))}catch(h){o(h)}}function u(f){try{d(n.throw(f))}catch(h){o(h)}}function d(f){f.done?a(f.value):i(f.value).then(l,u)}d((n=n.apply(t,e||[])).next())})};class xc{constructor(e){this._semaphore=new rb(1,e)}acquire(){return sb(this,arguments,void 0,function*(e=0){const[,r]=yield this._semaphore.acquire(1,e);return r})}runExclusive(e,r=0){return this._semaphore.runExclusive(()=>e(),1,r)}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()}}class bn{constructor(e,r,n=new Map){B(this,"providers");B(this,"registry");B(this,"sender");B(this,"changedKeys");this.providers=n,this.registry=r,this.changedKeys=[],this.sender=e}propagateState(e,r,n=[]){this.sender.send({key:e,state:r},n)}copyAndMerge(e){const r=new bn(this.sender,this.registry,new Map);return e==null||e.providers.forEach((n,i)=>r.providers.set(i,n)),this.providers.forEach((n,i)=>r.providers.set(i,n)),r.changedKeys=[],r}get changed(){return this.changedKeys.length>0}set(e,r,n=!0){this.providers.set(e,r),n&&this.changedKeys.push(e)}setIfNotHas(e,r){this.providers.has(e)||this.set(e,r)}async create(e){const r=this.registry[e.type];if(r==null)throw new Error(`[AetherRoot.create] - could not find component ${e.type}`);const n=new r(e);return await n.internalUpdate(e),n}getOptional(e){return this.providers.get(e)??null}has(e){return this.providers.has(e)}get(e){const r=this.getOptional(e);if(r==null)throw new Error(`[AetherRoot.get] - could not find provider ${e}`);return r}}class Zs{constructor(e){B(this,"type");B(this,"key");B(this,"_ctx");B(this,"_internalState");B(this,"_state");B(this,"_prevState");B(this,"_deleted",!1);B(this,"instrumentation");B(this,"schema");this.type=e.type,this.key=e.path[0],this._ctx=e.ctx,this._internalState={},this.instrumentation=e.instrumentation.child(`${this.type}(${this.key})`)}get _schema(){if(this.schema==null)throw new K(`[AetherLeaf] - expected subclass to define component schema, but none was found.
|
|
67
|
+
Make sure to defne a property 'schema' on the class.`);return this.schema}setState(e){const r=bs(e,this._state);this._prevState={...this._state},this._state=ls(this._schema,r,`${this.type}:${this.key}`),this.ctx.propagateState(this.key,r)}get ctx(){if(this._ctx==null)throw new we("context not defined");return this._ctx}get state(){if(this._state==null)throw new we("state not defined");return this._state}get internal(){return this._internalState}get prevState(){return this._prevState}get deleted(){return this._deleted}async internalUpdate({variant:e,path:r,ctx:n,state:i}){if(!this.deleted){if(this._ctx=n,e==="state"){this.validatePath(r);const a=ls(this._schema,i,`${this.type}:${this.key}`);this._state!=null?this.instrumentation.L.debug("updating state",()=>({diff:la.difference(this.state,a)})):this.instrumentation.L.debug("setting initial state",{state:i}),this._prevState=this._state??a,this._state=a}else this.instrumentation.L.debug("updating context");await this.afterUpdate()}}async internalDelete(e){this.validatePath(e),this._deleted=!0,await this.afterDelete()}beforeUpdate(){}async afterUpdate(){}async afterDelete(){}validatePath(e){if(e.length===0)throw new we(`[Leaf.setState] - ${this.type}:${this.key} received an empty path`);const r=e[e.length-1];if(e.length>1)throw new we(`[Leaf.setState] - ${this.type}:${this.key} received a subPath ${e.join(".")} but is a leaf`);if(r!==this.key)throw new we(`[Leaf.setState] - ${this.type}:${this.key} received a key ${r} but expected ${this.key}`)}}class ir extends Zs{constructor(r){super(r);B(this,"_children");this._children=new Map}get children(){return Array.from(this._children.values())}async internalUpdate(r){const{variant:n,path:i}=r;if(n==="context")return this._ctx=r.ctx.copyAndMerge(this._ctx),await this.updateContext({...r,ctx:this.ctx});const[a,o]=this.getRequiredKey(i),l={...r,ctx:this.ctx};return o.length===0?await this.updateThis(a,l):await this.updateChild(o,l)}async updateContext(r){await super.internalUpdate(r);for(const n of this.children)await n.internalUpdate({...r,ctx:this.ctx,variant:"context"})}async updateChild(r,n){const i=r[0],a=this.getChild(i);if(a!=null)return await a.internalUpdate({...n,path:r});if(r.length>1)throw new Error(`[Composite.setState] - ${this.type}:${this.key} could not find child with key ${i} while updating `);this._children.set(i,await n.ctx.create({...n,path:r}))}async updateThis(r,n){const i=n.ctx.copyAndMerge(this._ctx);if(r!==this.key)throw new we(`[Composite.update] - ${this.type}:${this.key} received a key ${r} but expected ${this.key}`);if(await super.internalUpdate({...n,ctx:i}),!!i.changed){this.instrumentation.L.debug("context changed",{changedKeys:i.changedKeys});for(const a of this.children)await a.internalUpdate({...n,ctx:this.ctx,variant:"context"})}}async internalDelete(r){const[n,i]=this.getRequiredKey(r);if(i.length===0){if(n!==this.key)throw new Error(`[Composite.delete] - ${this.type}:${this.key} received a key ${n} but expected ${this.key}`);const o=this.children;this._children=new Map;for(const l of o)await l.internalDelete([l.key]);await super.internalDelete([this.key])}const a=this.getChild(i[0]);a!=null&&(i.length>1?await a.internalDelete(i):(this._children.delete(a.key),await a.internalDelete(i)))}getRequiredKey(r,n){const[i,...a]=r;if(i==null)throw new Error(`Composite ${this.type}:${this.key} received an empty path`+(n!=null?` for ${n}`:""));return[i,a]}getChild(r){return this._children.get(r)??null}childrenOfType(...r){return this.children.filter(n=>r.includes(n.type))}}const ib=s.z.object({}),Ae=class Ae extends ir{constructor({worker:r,registry:n,instrumentation:i=Ac.Instrumentation.NOOP}){const o={ctx:new bn(r,n,new Map),...Ae.ZERO_UPDATE,instrumentation:i};super(o);B(this,"wrap");B(this,"schema",Ae.schema);B(this,"mu",new xc);this.mu.runExclusive(async()=>await this.internalUpdate(o)),this.wrap=r,this.wrap.handle(l=>{this.mu.runExclusive(async()=>await this.handle(l))})}async handle(r){if(r.variant==="delete")await this.internalDelete(r.path);else{const n={...r,variant:"state",ctx:this.ctx,instrumentation:this.instrumentation};await this.internalUpdate(n)}}};B(Ae,"TYPE","root"),B(Ae,"KEY","root"),B(Ae,"ZERO_UPDATE",{path:[Ae.KEY],type:Ae.TYPE,variant:"state",state:{}}),B(Ae,"schema",ib);let Xr=Ae;const Cc=t=>new Xr(t),ab=Object.freeze(Object.defineProperty({__proto__:null,Composite:ir,Context:bn,Leaf:Zs,Root:Xr,render:Cc},Symbol.toStringTag,{value:"Module"})),$c="pluto-theming-context",ob=s.z.object({theme:xa}),Yt=class Yt extends ir{constructor(){super(...arguments);B(this,"schema",Yt.z)}async afterUpdate(){this.ctx.set($c,this.state.theme)}};B(Yt,"TYPE","theming.Provider"),B(Yt,"z",ob);let Kt=Yt;const cb=t=>t.get($c),lb={[Kt.TYPE]:Kt},Rc=["success","error","warning","info","loading","disabled","secondary"],jc=s.z.enum(Rc),Mc=s.z.object({key:s.z.string(),variant:jc,message:s.z.string(),description:s.z.string().optional(),time:W.z,data:s.z.record(s.z.unknown()).optional()}),Dc=s.z.object({statuses:Mc.array()}),Ks="status.aggregator";class Qr extends ir{constructor(){super(...arguments);B(this,"schema",Dc)}async afterUpdate(){this.ctx.set(Ks,this)}add(r){this.setState(n=>({...n,statuses:[...n.statuses,{time:W.now(),key:fa.id(),...r}]}))}}B(Qr,"TYPE","status.Aggregator");const ub=t=>{const e=t.get(Ks);return e.add.bind(e)},hb=t=>{const e=t.getOptional(Ks);return e!=null?e.add.bind(e):()=>{}},db={[Qr.TYPE]:Qr};exports.A=Dl;exports.Aggregator=Qr;exports.B=Gs;exports.B$1=tt;exports.B$2=K;exports.B$3=Ql;exports.C=tn;exports.C$1=Hl;exports.ComponentSizeLevels=ka;exports.Composite=ir;exports.F=tl;exports.F$1=se;exports.Fd=pc;exports.H=su;exports.LEVELS=Aa;exports.Leaf=Zs;exports.LevelComponentSizes=uu;exports.Mutex=xc;exports.N=gl;exports.Nt=fa;exports.Provider=Kt;exports.Q=iu;exports.REGISTRY=lb;exports.REGISTRY$1=db;exports.Re=we;exports.Rf=xg;exports.S=A;exports.SYNNAX_DARK=$a;exports.SYNNAX_LIGHT=Ca;exports.SYNNAX_THEMES=bu;exports.St=Tl;exports.Tf=xy;exports.U=au;exports.VARIANTS=Rc;exports.Vd=mc;exports.Wf=cm;exports._=la;exports.aether=ab;exports.aggregatorStateZ=Dc;exports.b=le;exports.commonjsGlobal=Lc;exports.dimensions=du;exports.ep=fw;exports.executeInitialSetter=Ht;exports.executeSetter=bs;exports.fontString=Su;exports.g=Ac;exports.getAugmentedNamespace=Yc;exports.getDefaultExportFromCjs=_c;exports.h=j;exports.isSetter=ws;exports.k=x;exports.l=Fl;exports.levelZ=lu;exports.m=W;exports.n=Fn;exports.o=Pl;exports.o$1=rl;exports.prettyParse=ls;exports.q=Ol;exports.r=nl;exports.render=Cc;exports.specZ=Be;exports.specZ$1=Mc;exports.state=cu;exports.te=ve;exports.themeZ=xa;exports.use=cb;exports.useAggregate=ub;exports.useOptionalAggregate=hb;exports.usePassthrough=Ea;exports.usePurePassthrough=Ia;exports.variantZ=jc;exports.vt=xl;exports.w=ba;exports.w$1=Zc;exports.x=pa;exports.y=Z;
|