@synnaxlabs/client 0.49.0 → 0.49.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/client.cjs CHANGED
@@ -1,63 +1,65 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const i=require("zod"),Gl=t=>{const e=t.replace(/_[a-z]/g,n=>n[1].toUpperCase());return e.length>1&&e[0]===e[0].toUpperCase()&&e[1]===e[1].toUpperCase()||e.length===0?e:e[0].toLowerCase()+e.slice(1)},pa=t=>{const e=(n,r=Or)=>{if(typeof n=="string")return t(n);if(Array.isArray(n))return n.map(o=>e(o,r));if(!sr(n))return n;r=Xl(r);const s={},a=n;return"toJSON"in a&&typeof a.toJSON=="function"?e(a.toJSON(),r):(Object.keys(a).forEach(o=>{let c=a[o];const l=t(o);r.recursive&&(sr(c)?di(c)||(c=e(c,r)):r.recursiveInArray&&fi(c)&&(c=[...c].map(u=>{let h=u;return sr(u)?di(h)||(h=e(u,r)):fi(u)&&(h=e({key:u},r).key),h}))),s[l]=c}),s)};return e},ma=pa(Gl),Wl=t=>t.replace(/([a-z0-9])([A-Z])/g,(e,n,r)=>`${n}_${r.toLowerCase()}`),Kl=pa(Wl),Jl=[Number,String,Uint8Array],Or={recursive:!0,recursiveInArray:!0},Xl=(t=Or)=>(t.recursive==null?t=Or:t.recursiveInArray??=!1,t),fi=t=>t!=null&&Array.isArray(t),sr=t=>t!=null&&typeof t=="object"&&!Array.isArray(t),di=t=>Jl.some(e=>t instanceof e);let Ql=class{contentType="application/json";decoder;encoder;constructor(){this.decoder=new TextDecoder,this.encoder=new TextEncoder}encode(e){return this.encoder.encode(this.encodeString(e))}decode(e,n){return this.decodeString(this.decoder.decode(e),n)}decodeString(e,n){const r=JSON.parse(e),s=ma(r);return n!=null?n.parse(s):s}encodeString(e){const n=Kl(e);return JSON.stringify(n,(r,s)=>ArrayBuffer.isView(s)?Array.from(s):typeof s=="bigint"?s.toString():s)}};const Er=new Ql,ie=t=>t!=null&&typeof t=="object"&&"value"in t;class kt{value;constructor(e){this.value=e}valueOf(){return this.value}toJSON(){return this.value}toString(){return this.value.toString()}}const eh=t=>t!=null&&typeof t=="object"&&"toString"in t,th=(t,e=!1)=>{const n=eh(t)?"stringer":typeof t;let r;switch(n){case"string":r=(s,a)=>s.localeCompare(a);break;case"stringer":r=(s,a)=>s.toString().localeCompare(a.toString());break;case"number":r=(s,a)=>Number(s)-Number(a);break;case"bigint":r=(s,a)=>BigInt(s)-BigInt(a)>0n?1:-1;break;case"boolean":r=(s,a)=>Number(s)-Number(a);break;case"undefined":r=()=>0;break;default:return console.warn(`sortFunc: unknown type ${n}`),()=>-1}return e?nh(r):r},nh=t=>(e,n)=>t(n,e);let ga=(t,e=21)=>(n=e)=>{let r="",s=n|0;for(;s--;)r+=t[Math.random()*t.length|0];return r};const wa="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",rh=`0123456789${wa}`,sh=11,ih=ga(wa,1),ah=ga(rh,sh-1),oh=()=>`${ih()}${ah()}`,ch=(t,e)=>n=>n instanceof e||typeof n=="object"&&n!==null&&"discriminator"in n&&n.discriminator===t,uh=2**12-1,Nr=2n**63n-1n,lh=2**63-1,_n=t=>(e,n)=>{if(typeof e=="bigint"){if(hh(n))return t(e,BigInt(n));const r=t(Number(e),Number(n));return typeof r=="number"?BigInt(Math.round(r)):r}return t(Number(e),Number(n))},Wt=_n((t,e)=>t-e),Qe=_n((t,e)=>t+e),hh=t=>typeof t=="bigint"?!0:Number.isInteger(t),be=_n((t,e)=>t*e),Mn=_n((t,e)=>t/e),ba=i.z.tuple([i.z.number(),i.z.number()]),va=i.z.object({width:i.z.number(),height:i.z.number()}),fh=i.z.object({signedWidth:i.z.number(),signedHeight:i.z.number()}),dh=["start","center","end"],Dt=i.z.object({x:i.z.number(),y:i.z.number()}),yh=i.z.object({clientX:i.z.number(),clientY:i.z.number()}),ph=["x","y"],za=i.z.enum(ph),Ta=["top","right","bottom","left"];i.z.enum(Ta);const mh=["left","right"],Oa=i.z.enum(mh),gh=["top","bottom"],Ea=i.z.enum(gh),Na=["center"],yi=i.z.enum(Na),wh=[...Ta,...Na],Sa=i.z.enum(wh);i.z.enum(dh);const bh=["first","last"];i.z.enum(bh);i.z.object({lower:i.z.number(),upper:i.z.number()});i.z.enum([...za.options,...Sa.options]);i.z.union([za,Sa,i.z.instanceof(String)]);const et=(t,e,n)=>{const r={};if(typeof e=="object"&&(n=e,e=void 0),n={makeValid:!0,...n},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 r.lower=t.lower,r.upper=t.upper;return n?.makeValid?vh(r):r},vh=t=>t.lower>t.upper?{lower:t.upper,upper:t.lower}:t,pi=(t,e)=>{const n=et(t);return e<n.lower?n.lower:e>=n.upper?n.upper-(typeof n.upper=="number"?1:1n):e};i.z.object({x:Oa.or(yi),y:Ea.or(yi)});const ka=i.z.object({x:Oa,y:Ea}),zh=Object.freeze({x:"left",y:"top"}),Th=(t,e)=>t.x===e.x&&t.y===e.y,mi=i.z.union([i.z.number(),Dt,ba,va,fh,yh]),Oh=(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}},gi=Object.freeze({x:0,y:0}),yn=i.z.union([i.z.number(),i.z.string()]);i.z.object({top:yn,left:yn,width:yn,height:yn});i.z.object({left:i.z.number(),top:i.z.number(),right:i.z.number(),bottom:i.z.number()});i.z.object({one:Dt,two:Dt,root:ka});const ss=(t,e,n=0,r=0,s)=>{const a={one:{...gi},two:{...gi},root:s??zh};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+n,y:a.one.y+r},a}return"one"in t&&"two"in t&&"root"in t?{...t,root:s??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+n,y:a.one.y+r}:typeof e=="number"?a.two={x:a.one.x+e,y:a.one.y+n}:"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))},ir=t=>{const e=ss(t);return{lower:e.one.x,upper:e.two.x}},ar=t=>{const e=ss(t);return{lower:e.one.y,upper:e.two.y}},Eh=t=>typeof t!="object"||t==null?!1:"one"in t&&"two"in t&&"root"in t,Nh=i.z.object({signedWidth:i.z.number(),signedHeight:i.z.number()});i.z.union([va,Nh,Dt,ba]);const Sh=(t,e,n)=>e!==void 0&&t<e?e:n!==void 0&&t>n?n:t;i.z.object({offset:mi,scale:mi});i.z.object({offset:i.z.number(),scale:i.z.number()});const kh=t=>(e,n,r,s)=>n==="dimension"?[e,r]:[e,s?r-t:r+t],Ah=t=>(e,n,r,s)=>[e,s?r/t:r*t],$h=t=>(e,n,r)=>{if(e===null)return[t,r];const{lower:s,upper:a}=e,{lower:o,upper:c}=t,l=a-s,u=c-o;if(n==="dimension")return[t,r*(u/l)];const h=(r-s)*(u/l)+o;return[t,h]},Ih=t=>(e,n,r)=>[t,r],Zh=()=>(t,e,n)=>{if(t===null)throw new Error("cannot invert without bounds");if(e==="dimension")return[t,n];const{lower:r,upper:s}=t;return[t,s-(n-r)]},xh=t=>(e,n,r)=>{const{lower:s,upper:a}=t;return r=Sh(r,s,a),[e,r]};class De{ops=[];currBounds=null;currType=null;reversed=!1;constructor(){this.ops=[]}static translate(e){return new De().translate(e)}static magnify(e){return new De().magnify(e)}static scale(e,n){return new De().scale(e,n)}translate(e){const n=this.new(),r=kh(e);return r.type="translate",n.ops.push(r),n}magnify(e){const n=this.new(),r=Ah(e);return r.type="magnify",n.ops.push(r),n}scale(e,n){const r=et(e,n),s=this.new(),a=$h(r);return a.type="scale",s.ops.push(a),s}clamp(e,n){const r=et(e,n),s=this.new(),a=xh(r);return a.type="clamp",s.ops.push(a),s}reBound(e,n){const r=et(e,n),s=this.new(),a=Ih(r);return a.type="re-bound",s.ops.push(a),s}invert(){const e=Zh();e.type="invert";const n=this.new();return n.ops.push(e),n}pos(e){return this.exec("position",e)}dim(e){return this.exec("dimension",e)}new(){const e=new De;return e.ops=this.ops.slice(),e.reversed=this.reversed,e}exec(e,n){return this.currBounds=null,this.ops.reduce(([r,s],a)=>a(r,e,s,this.reversed),[null,n])[1]}reverse(){const e=this.new();e.ops.reverse();const n=[];return e.ops.forEach((r,s)=>{if(r.type==="scale"||n.some(([o,c])=>s>=o&&s<=c))return;const a=e.ops.findIndex((o,c)=>o.type==="scale"&&c>s);a!==-1&&n.push([s,a])}),n.forEach(([r,s])=>{const a=e.ops.slice(r,s);a.unshift(e.ops[s]),e.ops.splice(r,s-r+1,...a)}),e.reversed=!e.reversed,e}get transform(){return{scale:this.dim(1),offset:this.pos(0)}}static IDENTITY=new De}class me{x;y;currRoot;constructor(e=new De,n=new De,r=null){this.x=e,this.y=n,this.currRoot=r}static translate(e,n){return new me().translate(e,n)}static translateX(e){return new me().translateX(e)}static translateY(e){return new me().translateY(e)}static clamp(e){return new me().clamp(e)}static magnify(e){return new me().magnify(e)}static scale(e){return new me().scale(e)}static reBound(e){return new me().reBound(e)}translate(e,n){const r=Oh(e,n),s=this.copy();return s.x=this.x.translate(r.x),s.y=this.y.translate(r.y),s}translateX(e){const n=this.copy();return n.x=this.x.translate(e),n}translateY(e){const n=this.copy();return n.y=this.y.translate(e),n}magnify(e){const n=this.copy();return n.x=this.x.magnify(e.x),n.y=this.y.magnify(e.y),n}scale(e){const n=this.copy();if(Eh(e)){const r=this.currRoot;return n.currRoot=e.root,r!=null&&!Th(r,e.root)&&(r.x!==e.root.x&&(n.x=n.x.invert()),r.y!==e.root.y&&(n.y=n.y.invert())),n.x=n.x.scale(ir(e)),n.y=n.y.scale(ar(e)),n}return n.x=n.x.scale(e.width),n.y=n.y.scale(e.height),n}reBound(e){const n=this.copy();return n.x=this.x.reBound(ir(e)),n.y=this.y.reBound(ar(e)),n}clamp(e){const n=this.copy();return n.x=this.x.clamp(ir(e)),n.y=this.y.clamp(ar(e)),n}copy(){const e=new me;return e.currRoot=this.currRoot,e.x=this.x,e.y=this.y,e}reverse(){const e=this.copy();return e.x=this.x.reverse(),e.y=this.y.reverse(),e}pos(e){return{x:this.x.pos(e.x),y:this.y.pos(e.y)}}dim(e){return{x:this.x.dim(e.x),y:this.y.dim(e.y)}}box(e){return ss(this.pos(e.one),this.pos(e.two),0,0,this.currRoot??e.root)}get transform(){return{scale:this.dim({x:1,y:1}),offset:this.pos({x:0,y:0})}}static IDENTITY=new me}const Ch=Dt.extend({root:ka,units:i.object({x:i.enum(["px","decimal"]),y:i.enum(["px","decimal"])})});Ch.partial({root:!0,units:!0});const Rh=i.z.enum(["static","dynamic"]),wi=365,pn=30,_h=i.z.union([i.z.tuple([i.z.int()]),i.z.tuple([i.z.int(),i.z.int().min(1).max(12)]),i.z.tuple([i.z.int(),i.z.int().min(1).max(12),i.z.int().min(1).max(31)])]),Aa=(t,e)=>{const n=new b(e);if(![v.DAY,v.HOUR,v.MINUTE,v.SECOND,v.MILLISECOND,v.MICROSECOND,v.NANOSECOND].some(s=>s.equals(n)))throw new Error("Invalid argument for remainder. Must be an even TimeSpan or Timestamp");const r=t.valueOf()%n.valueOf();return t instanceof b?new b(r):new v(r)};class b extends kt{constructor(e,n="UTC"){if(e==null)super(b.now().valueOf());else if(e instanceof Date)super(BigInt(e.getTime())*b.MILLISECOND.valueOf());else if(typeof e=="string")super(b.parseDateTimeString(e,n).valueOf());else if(Array.isArray(e))super(b.parseDate(e));else{let r=0n;e instanceof Number&&(e=e.valueOf()),n==="local"&&(r=b.utcOffset.valueOf()),typeof e=="number"&&(isFinite(e)?e===lh?e=Nr:e=Math.trunc(e):(isNaN(e)&&(e=0),e===1/0?e=b.MAX:e=b.MIN)),ie(e)&&(e=e.value),super(BigInt(e.valueOf())+r)}}static parseDate([e=1970,n=1,r=1]){const s=new Date(e,n-1,r,0,0,0,0);return new b(BigInt(s.getTime())*b.MILLISECOND.valueOf()).truncate(b.DAY).valueOf()}valueOf(){return this.value}static parseTimeString(e,n="UTC"){const[r,s,a]=e.split(":");let o="00",c="00";a!=null&&([o,c]=a.split("."));let l=b.hours(parseInt(r??"00")).add(b.minutes(parseInt(s??"00"))).add(b.seconds(parseInt(o??"00"))).add(b.milliseconds(parseInt(c??"00")));return n==="local"&&(l=l.add(b.utcOffset)),l.valueOf()}static parseDateTimeString(e,n="UTC"){if(!e.includes("/")&&!e.includes("-"))return b.parseTimeString(e,n);if(e.match(/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d{1,3})?$/)!=null){let s=e,a=0;if(e.includes(".")){const u=e.split(".");s=u[0];const h=u[1]||"0";a=parseInt(h.padEnd(3,"0").slice(0,3))}const o=n==="local"?new Date(s.replace("T"," ")):new Date(`${s}Z`),c=BigInt(o.getTime())*b.MILLISECOND.valueOf(),l=BigInt(a)*b.MILLISECOND.valueOf();return c+l}const r=new Date(e);return e.includes(":")||r.setUTCHours(0,0,0,0),new b(BigInt(r.getTime())*b.MILLISECOND.valueOf(),n).valueOf()}toISOString(e="UTC"){return e==="UTC"?this.date().toISOString():this.sub(b.utcOffset).date().toISOString()}timeString(e=!1,n="UTC"){const r=this.toISOString(n);return e?r.slice(11,23):r.slice(11,19)}dateString(){const e=this.date(),n=e.toLocaleString("default",{month:"short"}),r=e.toLocaleString("default",{day:"numeric"});return`${n} ${r}`}static get utcOffset(){return new v(BigInt(new Date().getTimezoneOffset())*b.MINUTE.valueOf())}static since(e){return new b().span(e)}date(){return new Date(this.milliseconds)}equals(e){return this.valueOf()===new b(e).valueOf()}span(e){return this.range(e).span}range(e){return new Ct(this,e).makeValid()}spanRange(e){return this.range(this.add(e)).makeValid()}get isZero(){return this.valueOf()===0n}after(e){return this.valueOf()>new b(e).valueOf()}afterEq(e){return this.valueOf()>=new b(e).valueOf()}before(e){return this.valueOf()<new b(e).valueOf()}beforeEq(e){return this.valueOf()<=new b(e).valueOf()}add(e){return new b(Qe(this.valueOf(),new v(e).valueOf()))}sub(e){return new b(Wt(this.valueOf(),new v(e).valueOf()))}get hours(){return Number(this.valueOf())/Number(v.HOUR.valueOf())}get minutes(){return Number(this.valueOf())/Number(v.MINUTE.valueOf())}get days(){return Number(this.valueOf())/Number(v.DAY.valueOf())}get seconds(){return Number(this.valueOf())/Number(v.SECOND.valueOf())}get milliseconds(){return Number(this.valueOf())/Number(b.MILLISECOND.valueOf())}get microseconds(){return Number(this.valueOf())/Number(b.MICROSECOND.valueOf())}get nanoseconds(){return Number(this.valueOf())}get year(){return this.date().getUTCFullYear()}setYear(e){const n=this.date();return n.setUTCFullYear(e),new b(n)}get month(){return this.date().getUTCMonth()}setMonth(e){const n=this.date();return n.setUTCMonth(e),new b(n)}get day(){return this.date().getUTCDate()}setDay(e){const n=this.date();return n.setUTCDate(e),new b(n)}get hour(){return this.date().getUTCHours()}get localHour(){return this.date().getHours()}setLocalHour(e){const n=this.date();return n.setHours(e),new b(n)}setHour(e){const n=this.date();return n.setUTCHours(e),new b(n)}get minute(){return this.date().getUTCMinutes()}setMinute(e){const n=this.date();return n.setUTCMinutes(e),new b(n)}get second(){return this.date().getUTCSeconds()}setSecond(e){const n=this.date();return n.setUTCSeconds(e),new b(n)}get millisecond(){return this.date().getUTCMilliseconds()}setMillisecond(e){const n=this.date();return n.setUTCMilliseconds(e),new b(n)}toString(e="ISO",n="UTC"){switch(e){case"ISODate":return this.toISOString(n).slice(0,10);case"ISOTime":return this.toISOString(n).slice(11,23);case"time":return this.timeString(!1,n);case"preciseTime":return this.timeString(!0,n);case"date":return this.dateString();case"preciseDate":return`${this.dateString()} ${this.timeString(!0,n)}`;case"dateTime":return`${this.dateString()} ${this.timeString(!1,n)}`;default:return this.toISOString(n)}}remainder(e){return Aa(this,e)}get isToday(){return this.truncate(v.DAY).equals(b.now().truncate(v.DAY))}truncate(e){return this.sub(this.remainder(e))}formatBySpan(e){return e.greaterThanOrEqual(v.days(30))?"shortDate":e.greaterThanOrEqual(v.DAY)?"dateTime":e.greaterThanOrEqual(v.HOUR)?"time":e.greaterThanOrEqual(v.SECOND)?"preciseTime":"ISOTime"}static now(){return new b(new Date)}static max(...e){let n=b.MIN;for(const r of e){const s=new b(r);s.after(n)&&(n=s)}return n}static min(...e){let n=b.MAX;for(const r of e){const s=new b(r);s.before(n)&&(n=s)}return n}static nanoseconds(e,n="UTC"){return new b(e,n)}static NANOSECOND=b.nanoseconds(1);static microseconds(e,n="UTC"){return b.nanoseconds(e*1e3,n)}static MICROSECOND=b.microseconds(1);static milliseconds(e,n="UTC"){return b.microseconds(e*1e3,n)}static MILLISECOND=b.milliseconds(1);static seconds(e,n="UTC"){return b.milliseconds(e*1e3,n)}static SECOND=b.seconds(1);static minutes(e,n="UTC"){return b.seconds(e*60,n)}static MINUTE=b.minutes(1);static hours(e,n="UTC"){return b.minutes(e*60,n)}static HOUR=b.hours(1);static days(e,n="UTC"){return b.hours(e*24,n)}static DAY=b.days(1);static MAX=new b(Nr);static MIN=new b(0);static ZERO=new b(0);static z=i.z.union([i.z.instanceof(b),i.z.object({value:i.z.bigint()}).transform(e=>new b(e.value)),i.z.string().transform(e=>new b(BigInt(e))),i.z.number().transform(e=>new b(e)),i.z.bigint().transform(e=>new b(e)),i.z.date().transform(e=>new b(e)),i.z.custom(e=>e instanceof v).transform(e=>new b(e)),_h.transform(e=>new b(e))]);static sort(e,n){return Number(e.valueOf()-n.valueOf())}}class v extends kt{constructor(e){typeof e=="number"&&(e=Math.trunc(e.valueOf())),ie(e)&&(e=e.value),super(BigInt(e.valueOf()))}static fromSeconds(e){return e instanceof v?e:e instanceof or?e.period:e instanceof b?new v(e):(ie(e)&&(e=e.value),["number","bigint"].includes(typeof e)?v.seconds(e):new v(e))}static fromMilliseconds(e){return e instanceof v?e:e instanceof or?e.period:e instanceof b?new v(e):(ie(e)&&(e=e.value),["number","bigint"].includes(typeof e)?v.milliseconds(e):new v(e))}valueOf(){return this.value}lessThan(e){return this.valueOf()<new v(e).valueOf()}greaterThan(e){return this.valueOf()>new v(e).valueOf()}lessThanOrEqual(e){return this.valueOf()<=new v(e).valueOf()}greaterThanOrEqual(e){return this.valueOf()>=new v(e).valueOf()}remainder(e){return Aa(this,e)}truncate(e){return new v(BigInt(Math.trunc(Number(this.valueOf()/e.valueOf())))*e.valueOf())}toString(e="full"){if(e==="semantic")return this.toSemanticString();const n=this.truncate(v.DAY),r=this.truncate(v.HOUR),s=this.truncate(v.MINUTE),a=this.truncate(v.SECOND),o=this.truncate(v.MILLISECOND),c=this.truncate(v.MICROSECOND),l=this.truncate(v.NANOSECOND),u=n,h=r.sub(n),y=s.sub(r),f=a.sub(s),T=o.sub(a),S=c.sub(o),x=l.sub(c);let O="";return u.isZero||(O+=`${u.days}d `),h.isZero||(O+=`${h.hours}h `),y.isZero||(O+=`${y.minutes}m `),f.isZero||(O+=`${f.seconds}s `),T.isZero||(O+=`${T.milliseconds}ms `),S.isZero||(O+=`${S.microseconds}µs `),x.isZero||(O+=`${x.nanoseconds}ns`),O.trim()}toSemanticString(){const e=this.valueOf()<0n?-this.valueOf():this.valueOf(),n=new v(e),r=this.valueOf()<0n;if(n.valueOf()===0n)return"0s";if(n.lessThan(v.SECOND))return"< 1s";const s=n.days,a=n.hours,o=n.minutes,c=n.seconds,l=Math.floor(s/wi),u=Math.floor(s/pn),h=Math.floor(s/7),y=Math.floor(s),f=Math.floor(a),T=Math.floor(o),S=Math.floor(c),x=r?"-":"";if(l>=1){let O=`${l}y`;if(l<2){const N=Math.floor(s%wi/pn);N>0&&(O+=` ${N}mo`)}return x+O}if(h>=1&&s<pn&&s%7===0){let O=`${h}w`;const N=Math.floor(s%7),$=Math.floor(a-h*7*24);return h<2&&(N>0?O+=` ${N}d`:$>0&&$<24&&(O+=` ${$}h`)),x+O}if(u>=1){let O=`${u}mo`;if(u<3){const N=Math.floor(s%pn);N>0&&(O+=` ${N}d`)}return x+O}if(h>=1){let O=`${h}w`;const N=Math.floor(s%7),$=Math.floor(a-h*7*24);return h<2&&(N>0?O+=` ${N}d`:$>0&&$<24&&(O+=` ${$}h`)),x+O}if(y>=1){let O=`${y}d`;const N=Math.floor(a-y*24);return y<2&&N>0&&(O+=` ${N}h`),x+O}if(f>=1){let O=`${f}h`;if(f<3){const N=Math.floor(o-f*60);N>0&&(O+=` ${N}m`)}return x+O}if(T>=1){let O=`${T}m`;if(T<5){const N=Math.floor(c-T*60);N>0&&(O+=` ${N}s`)}return x+O}return`${x}${S}s`}mult(e){return new v(be(this.valueOf(),e))}div(e){return new v(Mn(this.valueOf(),e))}get days(){return Number(this.valueOf())/Number(v.DAY.valueOf())}get hours(){return Number(this.valueOf())/Number(v.HOUR.valueOf())}get minutes(){return Number(this.valueOf())/Number(v.MINUTE.valueOf())}get seconds(){return Number(this.valueOf())/Number(v.SECOND.valueOf())}get milliseconds(){return Number(this.valueOf())/Number(v.MILLISECOND.valueOf())}get microseconds(){return Number(this.valueOf())/Number(v.MICROSECOND.valueOf())}get nanoseconds(){return Number(this.valueOf())}get isZero(){return this.valueOf()===0n}equals(e){return this.valueOf()===new v(e).valueOf()}add(e){return new v(this.valueOf()+new v(e).valueOf())}sub(e){return new v(this.valueOf()-new v(e).valueOf())}static nanoseconds(e=1){return new v(e)}static NANOSECOND=v.nanoseconds(1);static microseconds(e=1){return v.nanoseconds(be(e,1e3))}static MICROSECOND=v.microseconds(1);static milliseconds(e=1){return v.microseconds(be(e,1e3))}static MILLISECOND=v.milliseconds(1);static seconds(e=1){return v.milliseconds(be(e,1e3))}static SECOND=v.seconds(1);static minutes(e=1){return v.seconds(be(e,60))}static MINUTE=v.minutes(1);static hours(e){return v.minutes(be(e,60))}static HOUR=v.hours(1);static days(e){return v.hours(be(e,24))}static DAY=v.days(1);static MAX=new v(Nr);static MIN=new v(0);static ZERO=new v(0);static z=i.z.union([i.z.object({value:i.z.bigint()}).transform(e=>new v(e.value)),i.z.string().transform(e=>new v(BigInt(e))),i.z.number().transform(e=>new v(e)),i.z.bigint().transform(e=>new v(e)),i.z.instanceof(v),i.z.instanceof(b).transform(e=>new v(e)),i.z.custom(e=>e instanceof or).transform(e=>new v(e))])}let or=class se extends kt{constructor(e){ie(e)&&(e=e.value),super(e.valueOf())}toString(){return`${this.valueOf()} Hz`}equals(e){return this.valueOf()===new se(e).valueOf()}get period(){return v.seconds(1/this.valueOf())}sampleCount(e){return new v(e).seconds*this.valueOf()}byteCount(e,n){return this.sampleCount(e)*new R(n).valueOf()}span(e){return v.seconds(e/this.valueOf())}byteSpan(e,n){return this.span(e.valueOf()/new R(n).valueOf())}add(e){return new se(Qe(this.valueOf(),new se(e).valueOf()))}sub(e){return new se(Wt(this.valueOf(),new se(e).valueOf()))}mult(e){return new se(be(this.valueOf(),e))}div(e){return new se(Mn(this.valueOf(),e))}static hz(e){return new se(e)}static khz(e){return se.hz(e*1e3)}static z=i.z.union([i.z.number().transform(e=>new se(e)),i.z.instanceof(se)])};class R extends kt{constructor(e){ie(e)&&(e=e.value),super(e.valueOf())}length(e){return e.valueOf()/this.valueOf()}size(e){return new I(e*this.valueOf())}add(e){return new R(Qe(this.valueOf(),new R(e).valueOf()))}sub(e){return new R(Wt(this.valueOf(),new R(e).valueOf()))}mult(e){return new R(be(this.valueOf(),e))}div(e){return new R(Mn(this.valueOf(),e))}static UNKNOWN=new R(0);static BIT128=new R(16);static BIT64=new R(8);static BIT32=new R(4);static BIT16=new R(2);static BIT8=new R(1);static z=i.z.union([i.z.number().transform(e=>new R(e)),i.z.instanceof(R)])}let Ct=class ge{start;end;constructor(e,n){typeof e=="object"&&"start"in e?(this.start=new b(e.start),this.end=new b(e.end)):(this.start=new b(e),this.end=new b(n))}get span(){return new v(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.start.isZero&&this.end.isZero}get numeric(){return{start:Number(this.start.valueOf()),end:Number(this.end.valueOf())}}swap(){return new ge(this.end,this.start)}get numericBounds(){return{lower:Number(this.start.valueOf()),upper:Number(this.end.valueOf())}}equals(e,n=v.ZERO){if(n.isZero)return this.start.equals(e.start)&&this.end.equals(e.end);let r=this.start.sub(e.start).valueOf(),s=this.end.sub(e.end).valueOf();return r<0&&(r=-r),s<0&&(s=-s),r<=n.valueOf()&&s<=n.valueOf()}toString(){return`${this.start.toString()} - ${this.end.toString()}`}toPrettyString(){return`${this.start.toString("preciseDate")} - ${this.span.toString()}`}overlapsWith(e,n=v.ZERO){e=e.makeValid();const r=this.makeValid();if(this.equals(e))return!0;if(e.end.equals(r.start)||r.end.equals(e.start))return!1;const s=b.max(r.start,e.start),a=b.min(r.end,e.end);return a.before(s)?!1:new v(a.sub(s)).greaterThanOrEqual(n)}contains(e){return e instanceof ge?this.contains(e.start)&&this.contains(e.end):this.start.beforeEq(e)&&this.end.after(e)}boundBy(e){const n=new ge(this.start,this.end);return e.start.after(this.start)&&(n.start=e.start),e.start.after(this.end)&&(n.end=e.start),e.end.before(this.end)&&(n.end=e.end),e.end.before(this.start)&&(n.start=e.end),n}static max(...e){return new ge(b.min(...e.map(n=>n.start)),b.max(...e.map(n=>n.end)))}static MAX=new ge(b.MIN,b.MAX);static ZERO=new ge(b.ZERO,b.ZERO);static z=i.z.union([i.z.object({start:b.z,end:b.z}).transform(e=>new ge(e.start,e.end)),i.z.instanceof(ge)]);static sort(e,n){return b.sort(e.start,n.start)||b.sort(e.end,n.end)}static simplify(e){return e.map(n=>n.makeValid()).sort((n,r)=>ge.sort(n,r)).reduce((n,r)=>{if(r.span.isZero)return n;if(n.length===0)return n.push(r),n;const s=n[n.length-1];return s.overlapsWith(r)||s.end.equals(r.start)?s.end=b.max(s.end,r.end):n.push(r),n},[])}};class p extends kt{constructor(e){if(ie(e)&&(e=e.value),e instanceof p||typeof e=="string"||typeof e.valueOf()=="string")super(e.valueOf());else{const n=p.ARRAY_CONSTRUCTOR_DATA_TYPES.get(e.constructor.name);if(n==null)throw new Error(`unable to find data type for ${e.toString()}`);super(n.valueOf())}}get Array(){const e=p.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(n=>this.equals(n))}toString(e=!1){return e?p.SHORT_STRINGS.get(this.valueOf())??this.valueOf():this.valueOf()}get isVariable(){return this.equals(p.JSON)||this.equals(p.STRING)}get isNumeric(){return!this.isVariable&&!this.equals(p.UUID)}get isInteger(){const e=this.toString();return e.startsWith("int")||e.startsWith("uint")}get isFloat(){return this.toString().startsWith("float")}get density(){const e=p.DENSITIES.get(this.toString());if(e==null)throw new Error(`unable to find density for ${this.valueOf()}`);return e}get isUnsignedInteger(){return this.equals(p.UINT8)||this.equals(p.UINT16)||this.equals(p.UINT32)||this.equals(p.UINT64)}get isSignedInteger(){return this.equals(p.INT8)||this.equals(p.INT16)||this.equals(p.INT32)||this.equals(p.INT64)}canSafelyCastTo(e){return this.equals(e)?!0:!this.isNumeric||!e.isNumeric||this.isVariable||e.isVariable||this.isUnsignedInteger&&e.isSignedInteger?!1:this.isFloat?e.isFloat&&this.density.valueOf()<=e.density.valueOf():this.equals(p.INT32)&&e.equals(p.FLOAT64)||this.equals(p.INT8)&&e.equals(p.FLOAT32)?!0:this.isInteger&&e.isInteger?this.density.valueOf()<=e.density.valueOf()&&this.isUnsignedInteger===e.isUnsignedInteger:!1}canCastTo(e){return this.isNumeric&&e.isNumeric?!0:this.equals(e)}checkArray(e){return e.constructor===this.Array}get usesBigInt(){return p.BIG_INT_TYPES.some(e=>e.equals(this))}static UNKNOWN=new p("unknown");static FLOAT64=new p("float64");static FLOAT32=new p("float32");static INT64=new p("int64");static INT32=new p("int32");static INT16=new p("int16");static INT8=new p("int8");static UINT64=new p("uint64");static UINT32=new p("uint32");static UINT16=new p("uint16");static UINT8=new p("uint8");static BOOLEAN=new p("boolean");static TIMESTAMP=new p("timestamp");static UUID=new p("uuid");static STRING=new p("string");static JSON=new p("json");static 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]]);static 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]]);static DENSITIES=new Map([[p.UINT8.toString(),R.BIT8],[p.UINT16.toString(),R.BIT16],[p.UINT32.toString(),R.BIT32],[p.UINT64.toString(),R.BIT64],[p.FLOAT32.toString(),R.BIT32],[p.FLOAT64.toString(),R.BIT64],[p.INT8.toString(),R.BIT8],[p.INT16.toString(),R.BIT16],[p.INT32.toString(),R.BIT32],[p.INT64.toString(),R.BIT64],[p.TIMESTAMP.toString(),R.BIT64],[p.STRING.toString(),R.UNKNOWN],[p.JSON.toString(),R.UNKNOWN],[p.UUID.toString(),R.BIT128]]);static 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];static SHORT_STRINGS=new Map([[p.UINT8.toString(),"u8"],[p.UINT16.toString(),"u16"],[p.UINT32.toString(),"u32"],[p.UINT64.toString(),"u64"],[p.INT8.toString(),"i8"],[p.INT16.toString(),"i16"],[p.INT32.toString(),"i32"],[p.INT64.toString(),"i64"],[p.FLOAT32.toString(),"f32"],[p.FLOAT64.toString(),"f64"],[p.BOOLEAN.toString(),"bool"],[p.TIMESTAMP.toString(),"ts"],[p.UUID.toString(),"uuid"],[p.STRING.toString(),"str"],[p.JSON.toString(),"json"]]);static BIG_INT_TYPES=[p.INT64,p.UINT64,p.TIMESTAMP];static z=i.z.union([i.z.string().transform(e=>new p(e)),i.z.instanceof(p)])}class I extends kt{constructor(e){ie(e)&&(e=e.value),super(e.valueOf())}largerThan(e){return ie(e)&&(e=e.value),this.valueOf()>e.valueOf()}smallerThan(e){return ie(e)&&(e=e.value),this.valueOf()<e.valueOf()}add(e){return ie(e)&&(e=e.value),new I(Qe(this.valueOf(),e.valueOf()))}sub(e){return ie(e)&&(e=e.value),new I(Wt(this.valueOf(),e.valueOf()))}mult(e){return new I(be(this.valueOf(),e))}div(e){return new I(Mn(this.valueOf(),e))}truncate(e){return new I(Math.trunc(this.valueOf()/new I(e).valueOf())*new I(e).valueOf())}remainder(e){return I.bytes(this.valueOf()%new I(e).valueOf())}get gigabytes(){return this.valueOf()/I.GIGABYTE.valueOf()}get megabytes(){return this.valueOf()/I.MEGABYTE.valueOf()}get kilobytes(){return this.valueOf()/I.KILOBYTE.valueOf()}get terabytes(){return this.valueOf()/I.TERABYTE.valueOf()}toString(){const e=this.truncate(I.TERABYTE),n=this.truncate(I.GIGABYTE),r=this.truncate(I.MEGABYTE),s=this.truncate(I.KILOBYTE),a=this.truncate(I.BYTE),o=e,c=n.sub(e),l=r.sub(n),u=s.sub(r),h=a.sub(s);let y="";return o.isZero||(y+=`${o.terabytes}TB `),c.isZero||(y+=`${c.gigabytes}GB `),l.isZero||(y+=`${l.megabytes}MB `),u.isZero||(y+=`${u.kilobytes}KB `),(!h.isZero||y==="")&&(y+=`${h.valueOf()}B`),y.trim()}static bytes(e=1){return new I(e)}static BYTE=new I(1);static kilobytes(e=1){return I.bytes(new I(e).valueOf()*1e3)}static KILOBYTE=I.kilobytes(1);static megabytes(e=1){return I.kilobytes(new I(e).valueOf()*1e3)}static MEGABYTE=I.megabytes(1);static gigabytes(e=1){return I.megabytes(new I(e).valueOf()*1e3)}static GIGABYTE=I.gigabytes(1);static terabytes(e){return I.gigabytes(new I(e).valueOf()*1e3)}static TERABYTE=I.terabytes(1);static ZERO=new I(0);static z=i.z.union([i.z.number().transform(e=>new I(e)),i.z.instanceof(I)]);get isZero(){return this.valueOf()===0}}i.z.object({start:i.z.number(),end:i.z.number()});i.z.union([i.z.instanceof(Uint8Array),i.z.instanceof(Uint16Array),i.z.instanceof(Uint32Array),i.z.instanceof(BigUint64Array),i.z.instanceof(Float32Array),i.z.instanceof(Float64Array),i.z.instanceof(Int8Array),i.z.instanceof(Int16Array),i.z.instanceof(Int32Array),i.z.instanceof(BigInt64Array)]);const $a=t=>{const e=typeof t;return e==="string"||e==="number"||e==="boolean"||e==="bigint"||t instanceof b||t instanceof v||t instanceof Date},Mh=(t,e,n,r=0)=>t.usesBigInt&&!e.usesBigInt?Number(n)-Number(r):!t.usesBigInt&&e.usesBigInt?BigInt(n.valueOf())-BigInt(r.valueOf()):Wt(n,r),jh=/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/i;function Uh(t){return typeof t=="string"&&jh.test(t)}const J=[];for(let t=0;t<256;++t)J.push((t+256).toString(16).slice(1));function Dh(t,e=0){return(J[t[e+0]]+J[t[e+1]]+J[t[e+2]]+J[t[e+3]]+"-"+J[t[e+4]]+J[t[e+5]]+"-"+J[t[e+6]]+J[t[e+7]]+"-"+J[t[e+8]]+J[t[e+9]]+"-"+J[t[e+10]]+J[t[e+11]]+J[t[e+12]]+J[t[e+13]]+J[t[e+14]]+J[t[e+15]]).toLowerCase()}function Lh(t,e=0){const n=Dh(t,e);if(!Uh(n))throw TypeError("Stringified UUID is invalid");return n}typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto);const Ia=(t,e)=>Lh(t,e),Re=-1,Ph=i.z.string().transform(t=>new Uint8Array(atob(t).split("").map(e=>e.charCodeAt(0))).buffer),Bh=i.z.union([i.z.null(),i.z.undefined()]).transform(()=>new Uint8Array().buffer),Sr=10,qh=(t,e)=>{if(t==="number"&&!e.isNumeric)throw new Error(`cannot convert series of type ${e.toString()} to number`);if(t==="bigint"&&!e.usesBigInt)throw new Error(`cannot convert series of type ${e.toString()} to bigint`)},Za="sy_x_telem_series";let xa=class Ue{key;discriminator=Za;dataType;sampleOffset;gl;_data;timeRange=Ct.ZERO;alignment=0n;alignmentMultiple=1n;cachedMin;cachedMax;writePos=Re;_refCount=0;cachedLength;_cachedIndexes;static crudeZ=i.z.object({timeRange:Ct.z.optional(),dataType:p.z,alignment:i.z.coerce.bigint().optional(),data:i.z.union([Ph,Bh,i.z.instanceof(ArrayBuffer),i.z.instanceof(Uint8Array)]),glBufferUsage:Rh.default("static").optional()});static z=Ue.crudeZ.transform(e=>new Ue(e));constructor(e){Fh(e)&&(e={data:e}),e.data??=[];const{dataType:n,timeRange:r,sampleOffset:s=0,glBufferUsage:a="static",alignment:o=0n,alignmentMultiple:c=1n,key:l=oh(),data:u}=e;if(Yh(u)){const f=u;this.key=f.key,this.dataType=f.dataType,this.sampleOffset=f.sampleOffset,this.gl=f.gl,this._data=f._data,this.timeRange=f.timeRange,this.alignment=f.alignment,this.alignmentMultiple=f.alignmentMultiple,this.cachedMin=f.cachedMin,this.cachedMax=f.cachedMax,this.writePos=f.writePos,this._refCount=f._refCount,this.cachedLength=f.cachedLength;return}const h=$a(u),y=Array.isArray(u);if(n!=null)this.dataType=new p(n);else{if(u instanceof ArrayBuffer)throw new Error("cannot infer data type from an ArrayBuffer instance when constructing a Series. Please provide a data type.");if(y||h){let f=u;if(!h){if(u.length===0)throw new Error("cannot infer data type from a zero length JS array when constructing a Series. Please provide a data type.");f=u[0]}if(typeof f=="string")this.dataType=p.STRING;else if(typeof f=="number")this.dataType=p.FLOAT64;else if(typeof f=="bigint")this.dataType=p.INT64;else if(typeof f=="boolean")this.dataType=p.BOOLEAN;else if(f instanceof b||f instanceof Date||f instanceof b)this.dataType=p.TIMESTAMP;else if(typeof f=="object")this.dataType=p.JSON;else throw new Error(`cannot infer data type of ${typeof f} when constructing a Series from a JS array`)}else this.dataType=new p(u)}if(!y&&!h)this._data=u;else if(y&&u.length===0)this._data=new this.dataType.Array([]).buffer;else{let f=h?[u]:u;const T=f[0];(T instanceof b||T instanceof Date||T instanceof v)&&(f=f.map(S=>new b(S).valueOf())),this.dataType.equals(p.STRING)?(this.cachedLength=f.length,this._data=new TextEncoder().encode(`${f.join(`
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const i=require("zod"),nh=t=>{const e=t.replace(/_[a-z]/g,n=>n[1].toUpperCase());return e.length>1&&e[0]===e[0].toUpperCase()&&e[1]===e[1].toUpperCase()||e.length===0?e:e[0].toLowerCase()+e.slice(1)},va=t=>{const e=(n,r=Sr)=>{if(typeof n=="string")return t(n);if(Array.isArray(n))return n.map(o=>e(o,r));if(!ir(n))return n;r=ah(r);const s={},a=n;return"toJSON"in a&&typeof a.toJSON=="function"?e(a.toJSON(),r):(Object.keys(a).forEach(o=>{let c=a[o];const l=t(o);r.recursive&&(ir(c)?pi(c)||(c=e(c,r)):r.recursiveInArray&&yi(c)&&(c=[...c].map(u=>{let h=u;return ir(u)?pi(h)||(h=e(u,r)):yi(u)&&(h=e({key:u},r).key),h}))),s[l]=c}),s)};return e},za=va(nh),rh=t=>t.replace(/([a-z0-9])([A-Z])/g,(e,n,r)=>`${n}_${r.toLowerCase()}`),sh=va(rh),ih=[Number,String,Uint8Array],Sr={recursive:!0,recursiveInArray:!0},ah=(t=Sr)=>(t.recursive==null?t=Sr:t.recursiveInArray??=!1,t),yi=t=>t!=null&&Array.isArray(t),ir=t=>t!=null&&typeof t=="object"&&!Array.isArray(t),pi=t=>ih.some(e=>t instanceof e);let oh=class{contentType="application/json";decoder;encoder;constructor(){this.decoder=new TextDecoder,this.encoder=new TextEncoder}encode(e){return this.encoder.encode(this.encodeString(e))}decode(e,n){return this.decodeString(this.decoder.decode(e),n)}decodeString(e,n){const r=JSON.parse(e),s=za(r);return n!=null?n.parse(s):s}encodeString(e){const n=sh(e);return JSON.stringify(n,(r,s)=>ArrayBuffer.isView(s)?Array.from(s):typeof s=="bigint"?s.toString():s)}};const Er=new oh,ue=t=>t!=null&&typeof t=="object"&&"value"in t;class $t{value;constructor(e){this.value=e}valueOf(){return this.value}toJSON(){return this.value}toString(){return this.value.toString()}}const ch=t=>t!=null&&typeof t=="object"&&"toString"in t,uh=(t,e=!1)=>{const n=ch(t)?"stringer":typeof t;let r;switch(n){case"string":r=(s,a)=>s.localeCompare(a);break;case"stringer":r=(s,a)=>s.toString().localeCompare(a.toString());break;case"number":r=(s,a)=>Number(s)-Number(a);break;case"bigint":r=(s,a)=>BigInt(s)-BigInt(a)>0n?1:-1;break;case"boolean":r=(s,a)=>Number(s)-Number(a);break;case"undefined":r=()=>0;break;default:return console.warn(`sortFunc: unknown type ${n}`),()=>-1}return e?lh(r):r},lh=t=>(e,n)=>t(n,e);let Ta=(t,e=21)=>(n=e)=>{let r="",s=n|0;for(;s--;)r+=t[Math.random()*t.length|0];return r};const Oa="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",hh=`0123456789${Oa}`,fh=11,dh=Ta(Oa,1),yh=Ta(hh,fh-1),ph=()=>`${dh()}${yh()}`,mh=(t,e)=>n=>n instanceof e||typeof n=="object"&&n!==null&&"discriminator"in n&&n.discriminator===t,gh=2**12-1,kr=2n**63n-1n,wh=2**63-1,jn=t=>(e,n)=>{if(typeof e=="bigint"){if(bh(n))return t(e,BigInt(n));const r=t(Number(e),Number(n));return typeof r=="number"?BigInt(Math.round(r)):r}return t(Number(e),Number(n))},Jt=jn((t,e)=>t-e),tt=jn((t,e)=>t+e),bh=t=>typeof t=="bigint"?!0:Number.isInteger(t),Oe=jn((t,e)=>t*e),Un=jn((t,e)=>t/e),Na=i.z.tuple([i.z.number(),i.z.number()]),Sa=i.z.object({width:i.z.number(),height:i.z.number()}),vh=i.z.object({signedWidth:i.z.number(),signedHeight:i.z.number()}),zh=["start","center","end"],Lt=i.z.object({x:i.z.number(),y:i.z.number()}),Th=i.z.object({clientX:i.z.number(),clientY:i.z.number()}),Oh=["x","y"],Ea=i.z.enum(Oh),ka=["top","right","bottom","left"];i.z.enum(ka);const Nh=["left","right"],Aa=i.z.enum(Nh),Sh=["top","bottom"],$a=i.z.enum(Sh),Ia=["center"],mi=i.z.enum(Ia),Eh=[...ka,...Ia],Za=i.z.enum(Eh);i.z.enum(zh);const kh=["first","last"];i.z.enum(kh);i.z.object({lower:i.z.number(),upper:i.z.number()});i.z.enum([...Ea.options,...Za.options]);i.z.union([Ea,Za,i.z.instanceof(String)]);const nt=(t,e,n)=>{const r={};if(typeof e=="object"&&(n=e,e=void 0),n={makeValid:!0,...n},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 r.lower=t.lower,r.upper=t.upper;return n?.makeValid?Ah(r):r},Ah=t=>t.lower>t.upper?{lower:t.upper,upper:t.lower}:t,gi=(t,e)=>{const n=nt(t);return e<n.lower?n.lower:e>=n.upper?n.upper-(typeof n.upper=="number"?1:1n):e};i.z.object({x:Aa.or(mi),y:$a.or(mi)});const xa=i.z.object({x:Aa,y:$a}),$h=Object.freeze({x:"left",y:"top"}),Ih=(t,e)=>t.x===e.x&&t.y===e.y,wi=i.z.union([i.z.number(),Lt,Na,Sa,vh,Th]),Zh=(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}},bi=Object.freeze({x:0,y:0}),mn=i.z.union([i.z.number(),i.z.string()]);i.z.object({top:mn,left:mn,width:mn,height:mn});i.z.object({left:i.z.number(),top:i.z.number(),right:i.z.number(),bottom:i.z.number()});i.z.object({one:Lt,two:Lt,root:xa});const as=(t,e,n=0,r=0,s)=>{const a={one:{...bi},two:{...bi},root:s??$h};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+n,y:a.one.y+r},a}return"one"in t&&"two"in t&&"root"in t?{...t,root:s??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+n,y:a.one.y+r}:typeof e=="number"?a.two={x:a.one.x+e,y:a.one.y+n}:"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))},ar=t=>{const e=as(t);return{lower:e.one.x,upper:e.two.x}},or=t=>{const e=as(t);return{lower:e.one.y,upper:e.two.y}},xh=t=>typeof t!="object"||t==null?!1:"one"in t&&"two"in t&&"root"in t,Ch=i.z.object({signedWidth:i.z.number(),signedHeight:i.z.number()});i.z.union([Sa,Ch,Lt,Na]);const Rh=(t,e,n)=>e!==void 0&&t<e?e:n!==void 0&&t>n?n:t;i.z.object({offset:wi,scale:wi});i.z.object({offset:i.z.number(),scale:i.z.number()});const _h=t=>(e,n,r,s)=>n==="dimension"?[e,r]:[e,s?r-t:r+t],Mh=t=>(e,n,r,s)=>[e,s?r/t:r*t],jh=t=>(e,n,r)=>{if(e===null)return[t,r];const{lower:s,upper:a}=e,{lower:o,upper:c}=t,l=a-s,u=c-o;if(n==="dimension")return[t,r*(u/l)];const h=(r-s)*(u/l)+o;return[t,h]},Uh=t=>(e,n,r)=>[t,r],Dh=()=>(t,e,n)=>{if(t===null)throw new Error("cannot invert without bounds");if(e==="dimension")return[t,n];const{lower:r,upper:s}=t;return[t,s-(n-r)]},Ph=t=>(e,n,r)=>{const{lower:s,upper:a}=t;return r=Rh(r,s,a),[e,r]};class qe{ops=[];currBounds=null;currType=null;reversed=!1;constructor(){this.ops=[]}static translate(e){return new qe().translate(e)}static magnify(e){return new qe().magnify(e)}static scale(e,n){return new qe().scale(e,n)}translate(e){const n=this.new(),r=_h(e);return r.type="translate",n.ops.push(r),n}magnify(e){const n=this.new(),r=Mh(e);return r.type="magnify",n.ops.push(r),n}scale(e,n){const r=nt(e,n),s=this.new(),a=jh(r);return a.type="scale",s.ops.push(a),s}clamp(e,n){const r=nt(e,n),s=this.new(),a=Ph(r);return a.type="clamp",s.ops.push(a),s}reBound(e,n){const r=nt(e,n),s=this.new(),a=Uh(r);return a.type="re-bound",s.ops.push(a),s}invert(){const e=Dh();e.type="invert";const n=this.new();return n.ops.push(e),n}pos(e){return this.exec("position",e)}dim(e){return this.exec("dimension",e)}new(){const e=new qe;return e.ops=this.ops.slice(),e.reversed=this.reversed,e}exec(e,n){return this.currBounds=null,this.ops.reduce(([r,s],a)=>a(r,e,s,this.reversed),[null,n])[1]}reverse(){const e=this.new();e.ops.reverse();const n=[];return e.ops.forEach((r,s)=>{if(r.type==="scale"||n.some(([o,c])=>s>=o&&s<=c))return;const a=e.ops.findIndex((o,c)=>o.type==="scale"&&c>s);a!==-1&&n.push([s,a])}),n.forEach(([r,s])=>{const a=e.ops.slice(r,s);a.unshift(e.ops[s]),e.ops.splice(r,s-r+1,...a)}),e.reversed=!e.reversed,e}get transform(){return{scale:this.dim(1),offset:this.pos(0)}}static IDENTITY=new qe}class ze{x;y;currRoot;constructor(e=new qe,n=new qe,r=null){this.x=e,this.y=n,this.currRoot=r}static translate(e,n){return new ze().translate(e,n)}static translateX(e){return new ze().translateX(e)}static translateY(e){return new ze().translateY(e)}static clamp(e){return new ze().clamp(e)}static magnify(e){return new ze().magnify(e)}static scale(e){return new ze().scale(e)}static reBound(e){return new ze().reBound(e)}translate(e,n){const r=Zh(e,n),s=this.copy();return s.x=this.x.translate(r.x),s.y=this.y.translate(r.y),s}translateX(e){const n=this.copy();return n.x=this.x.translate(e),n}translateY(e){const n=this.copy();return n.y=this.y.translate(e),n}magnify(e){const n=this.copy();return n.x=this.x.magnify(e.x),n.y=this.y.magnify(e.y),n}scale(e){const n=this.copy();if(xh(e)){const r=this.currRoot;return n.currRoot=e.root,r!=null&&!Ih(r,e.root)&&(r.x!==e.root.x&&(n.x=n.x.invert()),r.y!==e.root.y&&(n.y=n.y.invert())),n.x=n.x.scale(ar(e)),n.y=n.y.scale(or(e)),n}return n.x=n.x.scale(e.width),n.y=n.y.scale(e.height),n}reBound(e){const n=this.copy();return n.x=this.x.reBound(ar(e)),n.y=this.y.reBound(or(e)),n}clamp(e){const n=this.copy();return n.x=this.x.clamp(ar(e)),n.y=this.y.clamp(or(e)),n}copy(){const e=new ze;return e.currRoot=this.currRoot,e.x=this.x,e.y=this.y,e}reverse(){const e=this.copy();return e.x=this.x.reverse(),e.y=this.y.reverse(),e}pos(e){return{x:this.x.pos(e.x),y:this.y.pos(e.y)}}dim(e){return{x:this.x.dim(e.x),y:this.y.dim(e.y)}}box(e){return as(this.pos(e.one),this.pos(e.two),0,0,this.currRoot??e.root)}get transform(){return{scale:this.dim({x:1,y:1}),offset:this.pos({x:0,y:0})}}static IDENTITY=new ze}const Lh=Lt.extend({root:xa,units:i.object({x:i.enum(["px","decimal"]),y:i.enum(["px","decimal"])})});Lh.partial({root:!0,units:!0});const Bh=i.z.enum(["static","dynamic"]),vi=365,gn=30,qh=i.z.union([i.z.tuple([i.z.int()]),i.z.tuple([i.z.int(),i.z.int().min(1).max(12)]),i.z.tuple([i.z.int(),i.z.int().min(1).max(12),i.z.int().min(1).max(31)])]),Ca=(t,e)=>{const n=new b(e);if(![v.DAY,v.HOUR,v.MINUTE,v.SECOND,v.MILLISECOND,v.MICROSECOND,v.NANOSECOND].some(s=>s.equals(n)))throw new Error("Invalid argument for remainder. Must be an even TimeSpan or Timestamp");const r=t.valueOf()%n.valueOf();return t instanceof b?new b(r):new v(r)};class b extends $t{constructor(e,n="UTC"){if(e==null)super(b.now().valueOf());else if(e instanceof Date)super(BigInt(e.getTime())*b.MILLISECOND.valueOf());else if(typeof e=="string")super(b.parseDateTimeString(e,n).valueOf());else if(Array.isArray(e))super(b.parseDate(e));else{let r=0n;e instanceof Number&&(e=e.valueOf()),n==="local"&&(r=b.utcOffset.valueOf()),typeof e=="number"&&(isFinite(e)?e===wh?e=kr:e=Math.trunc(e):(isNaN(e)&&(e=0),e===1/0?e=b.MAX:e=b.MIN)),ue(e)&&(e=e.value),super(BigInt(e.valueOf())+r)}}static parseDate([e=1970,n=1,r=1]){const s=new Date(e,n-1,r,0,0,0,0);return new b(BigInt(s.getTime())*b.MILLISECOND.valueOf()).truncate(b.DAY).valueOf()}valueOf(){return this.value}static parseTimeString(e,n="UTC"){const[r,s,a]=e.split(":");let o="00",c="00";a!=null&&([o,c]=a.split("."));let l=b.hours(parseInt(r??"00")).add(b.minutes(parseInt(s??"00"))).add(b.seconds(parseInt(o??"00"))).add(b.milliseconds(parseInt(c??"00")));return n==="local"&&(l=l.add(b.utcOffset)),l.valueOf()}static parseDateTimeString(e,n="UTC"){if(!e.includes("/")&&!e.includes("-"))return b.parseTimeString(e,n);if(e.match(/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d{1,3})?$/)!=null){let s=e,a=0;if(e.includes(".")){const u=e.split(".");s=u[0];const h=u[1]||"0";a=parseInt(h.padEnd(3,"0").slice(0,3))}const o=n==="local"?new Date(s.replace("T"," ")):new Date(`${s}Z`),c=BigInt(o.getTime())*b.MILLISECOND.valueOf(),l=BigInt(a)*b.MILLISECOND.valueOf();return c+l}const r=new Date(e);return e.includes(":")||r.setUTCHours(0,0,0,0),new b(BigInt(r.getTime())*b.MILLISECOND.valueOf(),n).valueOf()}toISOString(e="UTC"){return e==="UTC"?this.date().toISOString():this.sub(b.utcOffset).date().toISOString()}timeString(e=!1,n="UTC"){const r=this.toISOString(n);return e?r.slice(11,23):r.slice(11,19)}dateString(){const e=this.date(),n=e.toLocaleString("default",{month:"short"}),r=e.toLocaleString("default",{day:"numeric"});return`${n} ${r}`}static get utcOffset(){return new v(BigInt(new Date().getTimezoneOffset())*b.MINUTE.valueOf())}static since(e){return new b().span(e)}date(){return new Date(this.milliseconds)}equals(e){return this.valueOf()===new b(e).valueOf()}span(e){return this.range(e).span}range(e){return new _t(this,e).makeValid()}spanRange(e){return this.range(this.add(e)).makeValid()}get isZero(){return this.valueOf()===0n}after(e){return this.valueOf()>new b(e).valueOf()}afterEq(e){return this.valueOf()>=new b(e).valueOf()}before(e){return this.valueOf()<new b(e).valueOf()}beforeEq(e){return this.valueOf()<=new b(e).valueOf()}add(e){return new b(tt(this.valueOf(),new v(e).valueOf()))}sub(e){return new b(Jt(this.valueOf(),new v(e).valueOf()))}get hours(){return Number(this.valueOf())/Number(v.HOUR.valueOf())}get minutes(){return Number(this.valueOf())/Number(v.MINUTE.valueOf())}get days(){return Number(this.valueOf())/Number(v.DAY.valueOf())}get seconds(){return Number(this.valueOf())/Number(v.SECOND.valueOf())}get milliseconds(){return Number(this.valueOf())/Number(b.MILLISECOND.valueOf())}get microseconds(){return Number(this.valueOf())/Number(b.MICROSECOND.valueOf())}get nanoseconds(){return Number(this.valueOf())}get year(){return this.date().getUTCFullYear()}setYear(e){const n=this.date();return n.setUTCFullYear(e),new b(n)}get month(){return this.date().getUTCMonth()}setMonth(e){const n=this.date();return n.setUTCMonth(e),new b(n)}get day(){return this.date().getUTCDate()}setDay(e){const n=this.date();return n.setUTCDate(e),new b(n)}get hour(){return this.date().getUTCHours()}get localHour(){return this.date().getHours()}setLocalHour(e){const n=this.date();return n.setHours(e),new b(n)}setHour(e){const n=this.date();return n.setUTCHours(e),new b(n)}get minute(){return this.date().getUTCMinutes()}setMinute(e){const n=this.date();return n.setUTCMinutes(e),new b(n)}get second(){return this.date().getUTCSeconds()}setSecond(e){const n=this.date();return n.setUTCSeconds(e),new b(n)}get millisecond(){return this.date().getUTCMilliseconds()}setMillisecond(e){const n=this.date();return n.setUTCMilliseconds(e),new b(n)}toString(e="ISO",n="UTC"){switch(e){case"ISODate":return this.toISOString(n).slice(0,10);case"ISOTime":return this.toISOString(n).slice(11,23);case"time":return this.timeString(!1,n);case"preciseTime":return this.timeString(!0,n);case"date":return this.dateString();case"preciseDate":return`${this.dateString()} ${this.timeString(!0,n)}`;case"dateTime":return`${this.dateString()} ${this.timeString(!1,n)}`;default:return this.toISOString(n)}}remainder(e){return Ca(this,e)}get isToday(){return this.truncate(v.DAY).equals(b.now().truncate(v.DAY))}truncate(e){return this.sub(this.remainder(e))}formatBySpan(e){return e.greaterThanOrEqual(v.days(30))?"shortDate":e.greaterThanOrEqual(v.DAY)?"dateTime":e.greaterThanOrEqual(v.HOUR)?"time":e.greaterThanOrEqual(v.SECOND)?"preciseTime":"ISOTime"}static now(){return new b(new Date)}static max(...e){let n=b.MIN;for(const r of e){const s=new b(r);s.after(n)&&(n=s)}return n}static min(...e){let n=b.MAX;for(const r of e){const s=new b(r);s.before(n)&&(n=s)}return n}static nanoseconds(e,n="UTC"){return new b(e,n)}static NANOSECOND=b.nanoseconds(1);static microseconds(e,n="UTC"){return b.nanoseconds(e*1e3,n)}static MICROSECOND=b.microseconds(1);static milliseconds(e,n="UTC"){return b.microseconds(e*1e3,n)}static MILLISECOND=b.milliseconds(1);static seconds(e,n="UTC"){return b.milliseconds(e*1e3,n)}static SECOND=b.seconds(1);static minutes(e,n="UTC"){return b.seconds(e*60,n)}static MINUTE=b.minutes(1);static hours(e,n="UTC"){return b.minutes(e*60,n)}static HOUR=b.hours(1);static days(e,n="UTC"){return b.hours(e*24,n)}static DAY=b.days(1);static MAX=new b(kr);static MIN=new b(0);static ZERO=new b(0);static z=i.z.union([i.z.instanceof(b),i.z.object({value:i.z.bigint()}).transform(e=>new b(e.value)),i.z.string().transform(e=>new b(BigInt(e))),i.z.number().transform(e=>new b(e)),i.z.bigint().transform(e=>new b(e)),i.z.date().transform(e=>new b(e)),i.z.custom(e=>e instanceof v).transform(e=>new b(e)),qh.transform(e=>new b(e))]);static sort(e,n){return Number(e.valueOf()-n.valueOf())}}class v extends $t{constructor(e){typeof e=="number"&&(e=Math.trunc(e.valueOf())),ue(e)&&(e=e.value),super(BigInt(e.valueOf()))}static fromSeconds(e){return e instanceof v?e:e instanceof cr?e.period:e instanceof b?new v(e):(ue(e)&&(e=e.value),["number","bigint"].includes(typeof e)?v.seconds(e):new v(e))}static fromMilliseconds(e){return e instanceof v?e:e instanceof cr?e.period:e instanceof b?new v(e):(ue(e)&&(e=e.value),["number","bigint"].includes(typeof e)?v.milliseconds(e):new v(e))}valueOf(){return this.value}lessThan(e){return this.valueOf()<new v(e).valueOf()}greaterThan(e){return this.valueOf()>new v(e).valueOf()}lessThanOrEqual(e){return this.valueOf()<=new v(e).valueOf()}greaterThanOrEqual(e){return this.valueOf()>=new v(e).valueOf()}remainder(e){return Ca(this,e)}truncate(e){return new v(BigInt(Math.trunc(Number(this.valueOf()/e.valueOf())))*e.valueOf())}toString(e="full"){if(e==="semantic")return this.toSemanticString();const n=this.truncate(v.DAY),r=this.truncate(v.HOUR),s=this.truncate(v.MINUTE),a=this.truncate(v.SECOND),o=this.truncate(v.MILLISECOND),c=this.truncate(v.MICROSECOND),l=this.truncate(v.NANOSECOND),u=n,h=r.sub(n),d=s.sub(r),f=a.sub(s),O=o.sub(a),E=c.sub(o),Z=l.sub(c);let z="";return u.isZero||(z+=`${u.days}d `),h.isZero||(z+=`${h.hours}h `),d.isZero||(z+=`${d.minutes}m `),f.isZero||(z+=`${f.seconds}s `),O.isZero||(z+=`${O.milliseconds}ms `),E.isZero||(z+=`${E.microseconds}µs `),Z.isZero||(z+=`${Z.nanoseconds}ns`),z.trim()}toSemanticString(){const e=this.valueOf()<0n?-this.valueOf():this.valueOf(),n=new v(e),r=this.valueOf()<0n;if(n.valueOf()===0n)return"0s";if(n.lessThan(v.SECOND))return"< 1s";const s=n.days,a=n.hours,o=n.minutes,c=n.seconds,l=Math.floor(s/vi),u=Math.floor(s/gn),h=Math.floor(s/7),d=Math.floor(s),f=Math.floor(a),O=Math.floor(o),E=Math.floor(c),Z=r?"-":"";if(l>=1){let z=`${l}y`;if(l<2){const N=Math.floor(s%vi/gn);N>0&&(z+=` ${N}mo`)}return Z+z}if(h>=1&&s<gn&&s%7===0){let z=`${h}w`;const N=Math.floor(s%7),A=Math.floor(a-h*7*24);return h<2&&(N>0?z+=` ${N}d`:A>0&&A<24&&(z+=` ${A}h`)),Z+z}if(u>=1){let z=`${u}mo`;if(u<3){const N=Math.floor(s%gn);N>0&&(z+=` ${N}d`)}return Z+z}if(h>=1){let z=`${h}w`;const N=Math.floor(s%7),A=Math.floor(a-h*7*24);return h<2&&(N>0?z+=` ${N}d`:A>0&&A<24&&(z+=` ${A}h`)),Z+z}if(d>=1){let z=`${d}d`;const N=Math.floor(a-d*24);return d<2&&N>0&&(z+=` ${N}h`),Z+z}if(f>=1){let z=`${f}h`;if(f<3){const N=Math.floor(o-f*60);N>0&&(z+=` ${N}m`)}return Z+z}if(O>=1){let z=`${O}m`;if(O<5){const N=Math.floor(c-O*60);N>0&&(z+=` ${N}s`)}return Z+z}return`${Z}${E}s`}mult(e){return new v(Oe(this.valueOf(),e))}div(e){return new v(Un(this.valueOf(),e))}get days(){return Number(this.valueOf())/Number(v.DAY.valueOf())}get hours(){return Number(this.valueOf())/Number(v.HOUR.valueOf())}get minutes(){return Number(this.valueOf())/Number(v.MINUTE.valueOf())}get seconds(){return Number(this.valueOf())/Number(v.SECOND.valueOf())}get milliseconds(){return Number(this.valueOf())/Number(v.MILLISECOND.valueOf())}get microseconds(){return Number(this.valueOf())/Number(v.MICROSECOND.valueOf())}get nanoseconds(){return Number(this.valueOf())}get isZero(){return this.valueOf()===0n}equals(e){return this.valueOf()===new v(e).valueOf()}add(e){return new v(this.valueOf()+new v(e).valueOf())}sub(e){return new v(this.valueOf()-new v(e).valueOf())}static nanoseconds(e=1){return new v(e)}static NANOSECOND=v.nanoseconds(1);static microseconds(e=1){return v.nanoseconds(Oe(e,1e3))}static MICROSECOND=v.microseconds(1);static milliseconds(e=1){return v.microseconds(Oe(e,1e3))}static MILLISECOND=v.milliseconds(1);static seconds(e=1){return v.milliseconds(Oe(e,1e3))}static SECOND=v.seconds(1);static minutes(e=1){return v.seconds(Oe(e,60))}static MINUTE=v.minutes(1);static hours(e){return v.minutes(Oe(e,60))}static HOUR=v.hours(1);static days(e){return v.hours(Oe(e,24))}static DAY=v.days(1);static MAX=new v(kr);static MIN=new v(0);static ZERO=new v(0);static z=i.z.union([i.z.object({value:i.z.bigint()}).transform(e=>new v(e.value)),i.z.string().transform(e=>new v(BigInt(e))),i.z.number().transform(e=>new v(e)),i.z.bigint().transform(e=>new v(e)),i.z.instanceof(v),i.z.instanceof(b).transform(e=>new v(e)),i.z.custom(e=>e instanceof cr).transform(e=>new v(e))])}let cr=class ce extends $t{constructor(e){ue(e)&&(e=e.value),super(e.valueOf())}toString(){return`${this.valueOf()} Hz`}equals(e){return this.valueOf()===new ce(e).valueOf()}get period(){return v.seconds(1/this.valueOf())}sampleCount(e){return new v(e).seconds*this.valueOf()}byteCount(e,n){return this.sampleCount(e)*new te(n).valueOf()}span(e){return v.seconds(e/this.valueOf())}byteSpan(e,n){return this.span(e.valueOf()/new te(n).valueOf())}add(e){return new ce(tt(this.valueOf(),new ce(e).valueOf()))}sub(e){return new ce(Jt(this.valueOf(),new ce(e).valueOf()))}mult(e){return new ce(Oe(this.valueOf(),e))}div(e){return new ce(Un(this.valueOf(),e))}static hz(e){return new ce(e)}static khz(e){return ce.hz(e*1e3)}static z=i.z.union([i.z.number().transform(e=>new ce(e)),i.z.instanceof(ce)])},te=class ne extends $t{constructor(e){ue(e)&&(e=e.value),super(e.valueOf())}length(e){return e.valueOf()/this.valueOf()}size(e){return new I(e*this.valueOf())}add(e){return new ne(tt(this.valueOf(),new ne(e).valueOf()))}sub(e){return new ne(Jt(this.valueOf(),new ne(e).valueOf()))}mult(e){return new ne(Oe(this.valueOf(),e))}div(e){return new ne(Un(this.valueOf(),e))}static UNKNOWN=new ne(0);static BIT128=new ne(16);static BIT64=new ne(8);static BIT32=new ne(4);static BIT16=new ne(2);static BIT8=new ne(1);static z=i.z.union([i.z.number().transform(e=>new ne(e)),i.z.instanceof(ne)])},_t=class ye{start;end;constructor(e,n){typeof e=="object"&&"start"in e?(this.start=new b(e.start),this.end=new b(e.end)):(this.start=new b(e),this.end=new b(n))}get span(){return new v(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.start.isZero&&this.end.isZero}get numeric(){return{start:Number(this.start.valueOf()),end:Number(this.end.valueOf())}}swap(){return new ye(this.end,this.start)}get numericBounds(){return{lower:Number(this.start.valueOf()),upper:Number(this.end.valueOf())}}equals(e,n=v.ZERO){if(n.isZero)return this.start.equals(e.start)&&this.end.equals(e.end);let r=this.start.sub(e.start).valueOf(),s=this.end.sub(e.end).valueOf();return r<0&&(r=-r),s<0&&(s=-s),r<=n.valueOf()&&s<=n.valueOf()}toString(){return`${this.start.toString()} - ${this.end.toString()}`}toPrettyString(){return`${this.start.toString("preciseDate")} - ${this.span.toString()}`}overlapsWith(e,n=v.ZERO){e=e.makeValid();const r=this.makeValid();if(this.equals(e))return!0;if(e.end.equals(r.start)||r.end.equals(e.start))return!1;const s=b.max(r.start,e.start),a=b.min(r.end,e.end);return a.before(s)?!1:new v(a.sub(s)).greaterThanOrEqual(n)}contains(e){return e instanceof ye?this.contains(e.start)&&this.contains(e.end):this.start.beforeEq(e)&&this.end.after(e)}boundBy(e){const n=new ye(this.start,this.end);return e.start.after(this.start)&&(n.start=e.start),e.start.after(this.end)&&(n.end=e.start),e.end.before(this.end)&&(n.end=e.end),e.end.before(this.start)&&(n.start=e.end),n}static max(...e){return new ye(b.min(...e.map(n=>n.start)),b.max(...e.map(n=>n.end)))}static MAX=new ye(b.MIN,b.MAX);static ZERO=new ye(b.ZERO,b.ZERO);static z=i.z.union([i.z.object({start:b.z,end:b.z}).transform(e=>new ye(e.start,e.end)),i.z.instanceof(ye)]);static sort(e,n){return b.sort(e.start,n.start)||b.sort(e.end,n.end)}static merge(...e){return ye.max(...e.map(n=>new ye(n).makeValid()))}};class p extends $t{constructor(e){if(ue(e)&&(e=e.value),e instanceof p||typeof e=="string"||typeof e.valueOf()=="string")super(e.valueOf());else{const n=p.ARRAY_CONSTRUCTOR_DATA_TYPES.get(e.constructor.name);if(n==null)throw new Error(`unable to find data type for ${e.toString()}`);super(n.valueOf())}}get Array(){const e=p.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(n=>this.equals(n))}toString(e=!1){return e?p.SHORT_STRINGS.get(this.valueOf())??this.valueOf():this.valueOf()}get isVariable(){return this.equals(p.JSON)||this.equals(p.STRING)}get isNumeric(){return!this.isVariable&&!this.equals(p.UUID)}get isInteger(){const e=this.toString();return e.startsWith("int")||e.startsWith("uint")}get isFloat(){return this.toString().startsWith("float")}get density(){const e=p.DENSITIES.get(this.toString());if(e==null)throw new Error(`unable to find density for ${this.valueOf()}`);return e}get isUnsignedInteger(){return this.equals(p.UINT8)||this.equals(p.UINT16)||this.equals(p.UINT32)||this.equals(p.UINT64)}get isSignedInteger(){return this.equals(p.INT8)||this.equals(p.INT16)||this.equals(p.INT32)||this.equals(p.INT64)}canSafelyCastTo(e){return this.equals(e)?!0:!this.isNumeric||!e.isNumeric||this.isVariable||e.isVariable||this.isUnsignedInteger&&e.isSignedInteger?!1:this.isFloat?e.isFloat&&this.density.valueOf()<=e.density.valueOf():this.equals(p.INT32)&&e.equals(p.FLOAT64)||this.equals(p.INT8)&&e.equals(p.FLOAT32)?!0:this.isInteger&&e.isInteger?this.density.valueOf()<=e.density.valueOf()&&this.isUnsignedInteger===e.isUnsignedInteger:!1}canCastTo(e){return this.isNumeric&&e.isNumeric?!0:this.equals(e)}checkArray(e){return e.constructor===this.Array}get usesBigInt(){return p.BIG_INT_TYPES.some(e=>e.equals(this))}static UNKNOWN=new p("unknown");static FLOAT64=new p("float64");static FLOAT32=new p("float32");static INT64=new p("int64");static INT32=new p("int32");static INT16=new p("int16");static INT8=new p("int8");static UINT64=new p("uint64");static UINT32=new p("uint32");static UINT16=new p("uint16");static UINT8=new p("uint8");static BOOLEAN=new p("boolean");static TIMESTAMP=new p("timestamp");static UUID=new p("uuid");static STRING=new p("string");static JSON=new p("json");static 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]]);static 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]]);static DENSITIES=new Map([[p.UINT8.toString(),te.BIT8],[p.UINT16.toString(),te.BIT16],[p.UINT32.toString(),te.BIT32],[p.UINT64.toString(),te.BIT64],[p.FLOAT32.toString(),te.BIT32],[p.FLOAT64.toString(),te.BIT64],[p.INT8.toString(),te.BIT8],[p.INT16.toString(),te.BIT16],[p.INT32.toString(),te.BIT32],[p.INT64.toString(),te.BIT64],[p.TIMESTAMP.toString(),te.BIT64],[p.STRING.toString(),te.UNKNOWN],[p.JSON.toString(),te.UNKNOWN],[p.UUID.toString(),te.BIT128]]);static 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];static SHORT_STRINGS=new Map([[p.UINT8.toString(),"u8"],[p.UINT16.toString(),"u16"],[p.UINT32.toString(),"u32"],[p.UINT64.toString(),"u64"],[p.INT8.toString(),"i8"],[p.INT16.toString(),"i16"],[p.INT32.toString(),"i32"],[p.INT64.toString(),"i64"],[p.FLOAT32.toString(),"f32"],[p.FLOAT64.toString(),"f64"],[p.BOOLEAN.toString(),"bool"],[p.TIMESTAMP.toString(),"ts"],[p.UUID.toString(),"uuid"],[p.STRING.toString(),"str"],[p.JSON.toString(),"json"]]);static BIG_INT_TYPES=[p.INT64,p.UINT64,p.TIMESTAMP];static z=i.z.union([i.z.string().transform(e=>new p(e)),i.z.instanceof(p)])}class I extends $t{constructor(e){ue(e)&&(e=e.value),super(e.valueOf())}largerThan(e){return ue(e)&&(e=e.value),this.valueOf()>e.valueOf()}smallerThan(e){return ue(e)&&(e=e.value),this.valueOf()<e.valueOf()}add(e){return ue(e)&&(e=e.value),new I(tt(this.valueOf(),e.valueOf()))}sub(e){return ue(e)&&(e=e.value),new I(Jt(this.valueOf(),e.valueOf()))}mult(e){return new I(Oe(this.valueOf(),e))}div(e){return new I(Un(this.valueOf(),e))}truncate(e){return new I(Math.trunc(this.valueOf()/new I(e).valueOf())*new I(e).valueOf())}remainder(e){return I.bytes(this.valueOf()%new I(e).valueOf())}get gigabytes(){return this.valueOf()/I.GIGABYTE.valueOf()}get megabytes(){return this.valueOf()/I.MEGABYTE.valueOf()}get kilobytes(){return this.valueOf()/I.KILOBYTE.valueOf()}get terabytes(){return this.valueOf()/I.TERABYTE.valueOf()}toString(){const e=this.truncate(I.TERABYTE),n=this.truncate(I.GIGABYTE),r=this.truncate(I.MEGABYTE),s=this.truncate(I.KILOBYTE),a=this.truncate(I.BYTE),o=e,c=n.sub(e),l=r.sub(n),u=s.sub(r),h=a.sub(s);let d="";return o.isZero||(d+=`${o.terabytes}TB `),c.isZero||(d+=`${c.gigabytes}GB `),l.isZero||(d+=`${l.megabytes}MB `),u.isZero||(d+=`${u.kilobytes}KB `),(!h.isZero||d==="")&&(d+=`${h.valueOf()}B`),d.trim()}static bytes(e=1){return new I(e)}static BYTE=new I(1);static kilobytes(e=1){return I.bytes(new I(e).valueOf()*1e3)}static KILOBYTE=I.kilobytes(1);static megabytes(e=1){return I.kilobytes(new I(e).valueOf()*1e3)}static MEGABYTE=I.megabytes(1);static gigabytes(e=1){return I.megabytes(new I(e).valueOf()*1e3)}static GIGABYTE=I.gigabytes(1);static terabytes(e){return I.gigabytes(new I(e).valueOf()*1e3)}static TERABYTE=I.terabytes(1);static ZERO=new I(0);static z=i.z.union([i.z.number().transform(e=>new I(e)),i.z.instanceof(I)]);get isZero(){return this.valueOf()===0}}i.z.object({start:i.z.number(),end:i.z.number()});i.z.union([i.z.instanceof(Uint8Array),i.z.instanceof(Uint16Array),i.z.instanceof(Uint32Array),i.z.instanceof(BigUint64Array),i.z.instanceof(Float32Array),i.z.instanceof(Float64Array),i.z.instanceof(Int8Array),i.z.instanceof(Int16Array),i.z.instanceof(Int32Array),i.z.instanceof(BigInt64Array)]);const Ra=t=>{const e=typeof t;return e==="string"||e==="number"||e==="boolean"||e==="bigint"||t instanceof b||t instanceof v||t instanceof Date},Fh=(t,e,n,r=0)=>t.usesBigInt&&!e.usesBigInt?Number(n)-Number(r):!t.usesBigInt&&e.usesBigInt?BigInt(n.valueOf())-BigInt(r.valueOf()):Jt(n,r),Yh=/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/i;function Vh(t){return typeof t=="string"&&Yh.test(t)}const J=[];for(let t=0;t<256;++t)J.push((t+256).toString(16).slice(1));function Gh(t,e=0){return(J[t[e+0]]+J[t[e+1]]+J[t[e+2]]+J[t[e+3]]+"-"+J[t[e+4]]+J[t[e+5]]+"-"+J[t[e+6]]+J[t[e+7]]+"-"+J[t[e+8]]+J[t[e+9]]+"-"+J[t[e+10]]+J[t[e+11]]+J[t[e+12]]+J[t[e+13]]+J[t[e+14]]+J[t[e+15]]).toLowerCase()}function Hh(t,e=0){const n=Gh(t,e);if(!Vh(n))throw TypeError("Stringified UUID is invalid");return n}typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto);const _a=(t,e)=>Hh(t,e),Ue=-1,Wh=i.z.string().transform(t=>new Uint8Array(atob(t).split("").map(e=>e.charCodeAt(0))).buffer),Kh=i.z.union([i.z.null(),i.z.undefined()]).transform(()=>new Uint8Array().buffer),Ar=10,Jh=(t,e)=>{if(t==="number"&&!e.isNumeric)throw new Error(`cannot convert series of type ${e.toString()} to number`);if(t==="bigint"&&!e.usesBigInt)throw new Error(`cannot convert series of type ${e.toString()} to bigint`)},Ma="sy_x_telem_series";let ja=class Be{key;discriminator=Ma;dataType;sampleOffset;gl;_data;timeRange=_t.ZERO;alignment=0n;alignmentMultiple=1n;cachedMin;cachedMax;writePos=Ue;_refCount=0;cachedLength;_cachedIndexes;static crudeZ=i.z.object({timeRange:_t.z.optional(),dataType:p.z,alignment:i.z.coerce.bigint().optional(),data:i.z.union([Wh,Kh,i.z.instanceof(ArrayBuffer),i.z.instanceof(Uint8Array)]),glBufferUsage:Bh.default("static").optional()});static z=Be.crudeZ.transform(e=>new Be(e));constructor(e){Xh(e)&&(e={data:e}),e.data??=[];const{dataType:n,timeRange:r,sampleOffset:s=0,glBufferUsage:a="static",alignment:o=0n,alignmentMultiple:c=1n,key:l=ph(),data:u}=e;if(Qh(u)){const f=u;this.key=f.key,this.dataType=f.dataType,this.sampleOffset=f.sampleOffset,this.gl=f.gl,this._data=f._data,this.timeRange=f.timeRange,this.alignment=f.alignment,this.alignmentMultiple=f.alignmentMultiple,this.cachedMin=f.cachedMin,this.cachedMax=f.cachedMax,this.writePos=f.writePos,this._refCount=f._refCount,this.cachedLength=f.cachedLength;return}const h=Ra(u),d=Array.isArray(u);if(n!=null)this.dataType=new p(n);else{if(u instanceof ArrayBuffer)throw new Error("cannot infer data type from an ArrayBuffer instance when constructing a Series. Please provide a data type.");if(d||h){let f=u;if(!h){if(u.length===0)throw new Error("cannot infer data type from a zero length JS array when constructing a Series. Please provide a data type.");f=u[0]}if(typeof f=="string")this.dataType=p.STRING;else if(typeof f=="number")this.dataType=p.FLOAT64;else if(typeof f=="bigint")this.dataType=p.INT64;else if(typeof f=="boolean")this.dataType=p.BOOLEAN;else if(f instanceof b||f instanceof Date||f instanceof b)this.dataType=p.TIMESTAMP;else if(typeof f=="object")this.dataType=p.JSON;else throw new Error(`cannot infer data type of ${typeof f} when constructing a Series from a JS array`)}else this.dataType=new p(u)}if(!d&&!h)this._data=u;else if(d&&u.length===0)this._data=new this.dataType.Array([]).buffer;else{let f=h?[u]:u;const O=f[0];(O instanceof b||O instanceof Date||O instanceof v)&&(f=f.map(E=>new b(E).valueOf())),this.dataType.equals(p.STRING)?(this.cachedLength=f.length,this._data=new TextEncoder().encode(`${f.join(`
2
2
  `)}
3
- `).buffer):this.dataType.equals(p.JSON)?(this.cachedLength=f.length,this._data=new TextEncoder().encode(`${f.map(S=>Er.encodeString(S)).join(`
3
+ `).buffer):this.dataType.equals(p.JSON)?(this.cachedLength=f.length,this._data=new TextEncoder().encode(`${f.map(E=>Er.encodeString(E)).join(`
4
4
  `)}
5
- `).buffer):this.dataType.usesBigInt&&typeof T=="number"?this._data=new this.dataType.Array(f.map(S=>BigInt(Math.round(S)))).buffer:!this.dataType.usesBigInt&&typeof T=="bigint"?this._data=new this.dataType.Array(f.map(Number)).buffer:this._data=new this.dataType.Array(f).buffer}this.key=l,this.alignment=o,this.alignmentMultiple=c,this.sampleOffset=s??0,this.timeRange=r??Ct.ZERO,this.gl={control:null,buffer:null,prevBuffer:0,bufferUsage:a}}static alloc({capacity:e,dataType:n,...r}){if(e===0)throw new Error("[Series] - cannot allocate an array of length 0");const s=new new p(n).Array(e),a=new Ue({data:s.buffer,dataType:n,...r});return a.writePos=0,a}get refCount(){return this._refCount}acquire(e){this._refCount++,e!=null&&this.updateGLBuffer(e)}release(){this._refCount--,this.refCount===0&&this.gl.control!=null?this.maybeGarbageCollectGLBuffer(this.gl.control):this.refCount<0&&console.warn("cannot release a series with a negative reference count")}write(e){if(!e.dataType.equals(this.dataType))throw new Error("buffer must be of the same type as this array");return this.dataType.isVariable?this.writeVariable(e):this.writeFixed(e)}writeVariable(e){if(this.writePos===Re)return 0;const n=this.byteCapacity.valueOf()-this.writePos,r=e.subBytes(0,n);return this.writeToUnderlyingData(r),this.writePos+=r.byteLength.valueOf(),this.cachedLength!=null&&(this.cachedLength+=r.length,this.calculateCachedLength()),r.length}writeFixed(e){if(this.writePos===Re)return 0;const n=this.capacity-this.writePos,r=e.sub(0,n);return this.writeToUnderlyingData(r),this.cachedLength=void 0,this.maybeRecomputeMinMax(r),this.writePos+=r.length,r.length}writeToUnderlyingData(e){this.underlyingData.set(e.data,this.writePos)}get buffer(){return typeof this._data=="object"&&"buffer"in this._data?this._data.buffer:this._data}get underlyingData(){return new this.dataType.Array(this._data)}get data(){return this.writePos===Re?this.underlyingData:new this.dataType.Array(this._data,0,this.writePos)}toStrings(){return this.dataType.isVariable?new TextDecoder().decode(this.underlyingData).split(`
6
- `).slice(0,-1):Array.from(this).map(e=>e.toString())}parseJSON(e){if(!this.dataType.equals(p.JSON))throw new Error("cannot parse non-JSON series as JSON");return this.toStrings().map(n=>e.parse(Er.decodeString(n)))}get byteCapacity(){return new I(this.underlyingData.byteLength)}get capacity(){return this.dataType.isVariable?this.byteCapacity.valueOf():this.dataType.density.length(this.byteCapacity)}get byteLength(){return this.writePos===Re?this.byteCapacity:this.dataType.isVariable?new I(this.writePos):this.dataType.density.size(this.writePos)}get length(){return this.cachedLength!=null?this.cachedLength:this.dataType.isVariable?this.calculateCachedLength():this.writePos===Re?this.byteCapacity.valueOf()/this.dataType.density.valueOf():this.writePos}calculateCachedLength(){if(!this.dataType.isVariable)throw new Error("cannot calculate length of a non-variable length data type");let e=0;const n=[0];return this.data.forEach((r,s)=>{r===Sr&&(e++,n.push(s+1))}),this._cachedIndexes=n,this.cachedLength=e,e}convert(e,n=0){if(this.dataType.equals(e))return this;const r=new e.Array(this.length);for(let s=0;s<this.length;s++)r[s]=Mh(this.dataType,e,this.data[s],n);return new Ue({data:r.buffer,dataType:e,timeRange:this.timeRange,sampleOffset:n,glBufferUsage:this.gl.bufferUsage,alignment:this.alignment})}calcRawMax(){if(this.length===0)return-1/0;if(this.dataType.equals(p.TIMESTAMP))this.cachedMax=this.data[this.data.length-1];else if(this.dataType.usesBigInt){const e=this.data;this.cachedMax=e.reduce((n,r)=>n>r?n:r)}else{const e=this.data;this.cachedMax=e.reduce((n,r)=>n>r?n:r)}return this.cachedMax}get max(){return this.calcMax()}calcMax(){if(this.dataType.isVariable)throw new Error("cannot calculate maximum on a variable length data type");return this.writePos===0?-1/0:(this.cachedMax??=this.calcRawMax(),Qe(this.cachedMax,this.sampleOffset))}calcRawMin(){if(this.length===0)return 1/0;if(this.dataType.equals(p.TIMESTAMP))this.cachedMin=this.data[0];else if(this.dataType.usesBigInt){const e=this.data;this.cachedMin=e.reduce((n,r)=>n<r?n:r)}else{const e=this.data;this.cachedMin=e.reduce((n,r)=>n<r?n:r)}return this.cachedMin}get min(){return this.calcMin()}calcMin(){if(this.dataType.isVariable)throw new Error("cannot calculate minimum on a variable length data type");return this.writePos===0?1/0:(this.cachedMin??=this.calcRawMin(),Qe(this.cachedMin,this.sampleOffset))}get bounds(){return et(Number(this.min),Number(this.max),{makeValid:!1})}maybeRecomputeMinMax(e){if(this.cachedMin!=null){const n=e.cachedMin??e.calcRawMin();n<this.cachedMin&&(this.cachedMin=n)}if(this.cachedMax!=null){const n=e.cachedMax??e.calcRawMax();n>this.cachedMax&&(this.cachedMax=n)}}atAlignment(e,n){const r=Number((e-this.alignment)/this.alignmentMultiple);if(r<0||r>=this.length){if(n===!0)throw new Error(`[series] - no value at index ${r}`);return}return this.at(r,n)}at(e,n=!1){if(this.dataType.isVariable)return this.atVariable(e,n??!1);if(this.dataType.equals(p.UUID))return this.atUUID(e,n);e<0&&(e=this.length+e);const r=this.data[e];if(r==null){if(n===!0)throw new Error(`[series] - no value at index ${e}`);return}return Qe(r,this.sampleOffset)}atUUID(e,n){e<0&&(e=this.length+e);const r=Ia(new Uint8Array(this.buffer,e*this.dataType.density.valueOf()));if(r==null){if(n)throw new Error(`[series] - no value at index ${e}`);return}return r}atVariable(e,n){let r=0,s=0;if(this._cachedIndexes!=null)r=this._cachedIndexes[e],s=this._cachedIndexes[e+1]-1;else{e<0&&(e=this.length+e);for(let o=0;o<this.data.length;o++)if(this.data[o]===Sr){if(e===0){s=o;break}r=o+1,e--}if(s===0&&(s=this.data.length),r>=s||e>0){if(n)throw new Error(`[series] - no value at index ${e}`);return}}const a=this.data.slice(r,s);return this.dataType.equals(p.STRING)?new TextDecoder().decode(a):ma(JSON.parse(new TextDecoder().decode(a)))}binarySearch(e){let n=0,r=this.length-1;const s=th(e);for(;n<=r;){const a=Math.floor((n+r)/2),o=s(this.at(a,!0),e);if(o===0)return a;o<0?n=a+1:r=a-1}return n}updateGLBuffer(e){if(this.gl.control=e,!this.dataType.equals(p.FLOAT32)&&!this.dataType.equals(p.UINT8))throw new Error("Only FLOAT32 and UINT8 arrays can be used in WebGL");const{buffer:n,bufferUsage:r,prevBuffer:s}=this.gl;if(n==null&&(this.gl.buffer=e.createBuffer()),this.writePos!==s)if(e.bindBuffer(e.ARRAY_BUFFER,this.gl.buffer),this.writePos!==Re){s===0&&e.bufferData(e.ARRAY_BUFFER,this.byteCapacity.valueOf(),e.STATIC_DRAW);const a=this.dataType.density.size(s).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,r==="static"?e.STATIC_DRAW:e.DYNAMIC_DRAW),this.gl.prevBuffer=Re}as(e){return qh(e,this.dataType),this}get digest(){return{key:this.key,dataType:this.dataType.toString(),sampleOffset:this.sampleOffset,alignment:{lower:vi(this.alignmentBounds.lower),upper:vi(this.alignmentBounds.upper),multiple:this.alignmentMultiple},timeRange:this.timeRange.toString(),length:this.length,capacity:this.capacity}}get alignmentBounds(){return et(this.alignment,this.alignment+BigInt(this.length)*this.alignmentMultiple)}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 Hh(this);return this.dataType.equals(p.JSON)?new is(e):e}return this.dataType.equals(p.UUID)?new Vh(this):new Gh(this)}slice(e,n){return this.sliceSub(!1,e,n)}sub(e,n){return this.sliceSub(!0,e,n)}subIterator(e,n){return new bi(this,e,n??this.length)}subAlignmentIterator(e,n){const r=Math.ceil(Number(e-this.alignment)/Number(this.alignmentMultiple)),s=Math.ceil(Number(n-this.alignment)/Number(this.alignmentMultiple));return new bi(this,r,s)}subBytes(e,n){if(e>=0&&(n==null||n>=this.byteLength.valueOf()))return this;const r=this.data.subarray(e,n);return new Ue({data:r,dataType:this.dataType,timeRange:this.timeRange,sampleOffset:this.sampleOffset,glBufferUsage:this.gl.bufferUsage,alignment:this.alignment+BigInt(e)})}sliceSub(e,n,r){if(n<=0&&(r==null||r>=this.length))return this;let s;return e?s=this.data.subarray(n,r):s=this.data.slice(n,r),new Ue({data:s,dataType:this.dataType,timeRange:this.timeRange,sampleOffset:this.sampleOffset,glBufferUsage:this.gl.bufferUsage,alignment:this.alignment+BigInt(n)})}reAlign(e){return new Ue({data:this.buffer,dataType:this.dataType,timeRange:Ct.ZERO,sampleOffset:this.sampleOffset,glBufferUsage:"static",alignment:e})}toString(){let e=`Series(${this.dataType.toString()} ${this.length} [`;if(this.length<=10)e+=Array.from(this).map(n=>n.toString());else{for(let n=0;n<5;n++)e+=`${this.at(n)?.toString()}`,e+=",";e+="...,";for(let n=-5;n<0;n++)e+=this.at(n)?.toString(),n<-1&&(e+=",")}return e+="])",e}};const Fh=t=>t==null?!1:Array.isArray(t)||t instanceof ArrayBuffer||ArrayBuffer.isView(t)&&!(t instanceof DataView)||t instanceof xa?!0:$a(t),Yh=ch(Za,xa);class bi{series;end;index;constructor(e,n,r){this.series=e;const s=et(0,e.length+1);this.end=pi(s,r),this.index=pi(s,n)}next(){return this.index>=this.end?{done:!0,value:void 0}:{done:!1,value:this.series.at(this.index++,!0)}}}class Hh{series;index;decoder;constructor(e){if(!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,n=this.series.data;for(;this.index<n.length&&n[this.index]!==Sr;)this.index++;const r=this.index;return e===r?{done:!0,value:void 0}:(this.index++,{done:!1,value:this.decoder.decode(this.series.buffer.slice(e,r))})}}class is{wrapped;static schema=i.z.record(i.z.string(),i.z.unknown());constructor(e){this.wrapped=e}next(){const e=this.wrapped.next();return e.done===!0?{done:!0,value:void 0}:{done:!1,value:Er.decodeString(e.value,is.schema)}}}let Vh=class{series;index;data;density;constructor(e){if(!e.dataType.equals(p.UUID))throw new Error("cannot create a UUID series iterator for a non-UUID series");this.series=e,this.index=0,this.data=new Uint8Array(e.buffer),this.density=p.UUID.density.valueOf()}next(){if(this.index>=this.series.length)return{done:!0,value:void 0};const e=Ia(this.data,this.index*this.density);return this.index++,{done:!1,value:e}}};class Gh{series;index;constructor(e){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)}}}const vi=t=>{const e=t>>32n,n=t&0xffffffffn;return{domain:e,sample:n}},Wh=async t=>await new Promise(e=>setTimeout(e,v.fromMilliseconds(t).milliseconds));let Kh=class{config;retries;interval;constructor(e){this.config={baseInterval:new v(e?.baseInterval??v.seconds(1)),maxRetries:e?.maxRetries??5,scale:e?.scale??1,sleepFn:e?.sleepFn??Wh},this.retries=0,this.interval=new v(this.config.baseInterval)}async wait(){const{maxRetries:e,scale:n,sleepFn:r}=this.config;return this.retries>=e?!1:(await r(this.interval),this.interval=this.interval.mult(n),this.retries++,!0)}get retryMessage(){return`breaker triggered ${this.retries+1}/${this.config.maxRetries} times, retrying in ${this.interval.toString()}`}reset(){this.retries=0,this.interval=this.config.baseInterval}};const Jh=i.z.object({baseInterval:v.z.optional(),maxRetries:i.z.number().optional(),scale:i.z.number().optional()}),Xh=Object.freeze(Object.defineProperty({__proto__:null,Breaker:Kh,breakerConfigZ:Jh},Symbol.toStringTag,{value:"Module"})),Qh=/^#?([0-9a-f]{6}|[0-9a-f]{8})$/i,Ca=i.z.string().regex(Qh),wt=i.z.number().min(0).max(255),Ra=i.z.number().min(0).max(1),_a=i.z.tuple([wt,wt,wt,Ra]),ef=i.z.tuple([wt,wt,wt]),tf=i.z.object({rgba255:_a}),nf=i.z.number().min(0).max(360),rf=i.z.number().min(0).max(100),sf=i.z.number().min(0).max(100),af=i.z.tuple([nf,rf,sf,Ra]),as=i.z.union([Ca,ef,_a,af,tf]),of=as.transform(t=>os(t)),os=(t,e=1)=>{if(t=as.parse(t),typeof t=="string")return cf(t,e);if(Array.isArray(t)){if(t.length<3||t.length>4)throw new Error(`Invalid color: [${t.join(", ")}]`);return t.length===3?[...t,e]:t}return t.rgba255},cf=(t,e=1)=>(t=Ca.parse(t),t=uf(t),[mn(t,0),mn(t,2),mn(t,4),t.length===8?mn(t,6)/255:e]),mn=(t,e)=>parseInt(t.slice(e,e+2),16),uf=t=>t.startsWith("#")?t.slice(1):t;os("#000000");os("#ffffff");const lf=i.z.object({key:i.z.string(),color:as,position:i.z.number(),switched:i.z.boolean().optional()});i.z.array(lf);const hf=i.z.object({key:i.z.string(),name:i.z.string(),color:of});i.z.object({key:i.z.string(),name:i.z.string(),swatches:i.z.array(hf)});i.z.int().min(0).max(255);i.z.object({name:i.z.string(),key:i.z.string()});const ff=t=>Object.getOwnPropertySymbols(globalThis).includes(t),df=(t,e)=>{const n=Symbol.for(t);if(!ff(n)){const r=e();Object.defineProperty(globalThis,n,{value:r})}return()=>globalThis[n]},Ma="sy_x_error",yf=t=>e=>e!=null&&typeof e=="object"&&"type"in e&&typeof e.type=="string"?e.type.startsWith(t):e instanceof Error?e.message.startsWith(t):typeof e!="string"?!1:e.startsWith(t),Kt=t=>class Rt extends Error{static discriminator=Ma;discriminator=Rt.discriminator;static TYPE=t;type=Rt.TYPE;static matches=yf(t);matches=Rt.matches;constructor(n,r){super(n,r),this.name=Rt.TYPE}static sub(n){return Kt(`${t}.${n}`)}},ja=t=>{if(t==null||typeof t!="object")return!1;const e=t;if(e.discriminator!==Ma)return!1;if(!("type"in e))throw new Error(`X Error is missing its type property: ${JSON.stringify(e)}`);return!0},pt="unknown",kr="nil";class pf{providers=[];register(e){this.providers.push(e)}encode(e){if(e==null)return{type:kr,data:""};if(ja(e))for(const n of this.providers){const r=n.encode(e);if(r!=null)return r}if(e instanceof Error)return{type:pt,data:e.message};if(typeof e=="string")return{type:pt,data:e};try{return{type:pt,data:JSON.stringify(e)}}catch{return{type:pt,data:"unable to encode error information"}}}decode(e){if(e==null||e.type===kr)return null;if(e.type===pt)return new Ar(e.data);for(const n of this.providers){const r=n.decode(e);if(r!=null)return r}return new Ar(e.data)}}const cs=df("synnax-error-registry",()=>new pf),mf=({encode:t,decode:e})=>cs().register({encode:t,decode:e}),gf=t=>cs().encode(t),wf=t=>t==null?null:cs().decode(t);let Ar=class extends Kt("unknown"){};const bf=i.z.object({type:i.z.string(),data:i.z.string()});class vf extends Kt("canceled"){}let zf=class extends Kt("not_implemented"){};const Pe=Object.freeze(Object.defineProperty({__proto__:null,Canceled:vf,NONE:kr,NotImplemented:zf,UNKNOWN:pt,Unknown:Ar,createTyped:Kt,decode:wf,encode:gf,isTyped:ja,payloadZ:bf,register:mf},Symbol.toStringTag,{value:"Module"})),Tf=i.object({jsonrpc:i.literal("2.0"),method:i.string(),params:i.any().optional(),id:i.union([i.string(),i.number(),i.null()]).optional()}),Ua=i.object({jsonrpc:i.literal("2.0"),id:i.union([i.string(),i.number(),i.null()])}),Of=Ua.extend({result:i.json()}),Ef=Ua.extend({error:i.object({code:i.number().int(),message:i.string().optional(),data:i.json().optional()})}),Nf=i.union([Of,Ef]);i.union([Tf,Nf]);i.z.object({key:i.z.string(),value:i.z.string()});const Sf=i.uuid();i.object({key:Sf,name:i.string().min(1),color:i.string()});i.z.string().regex(/^\d+\.\d+\.\d+(-[0-9A-Za-z-]+(\.[0-9A-Za-z-]+)*)?$/);const kf=["standard","scientific","engineering"];i.z.enum(kf);i.z.record(i.z.union([i.z.number(),i.z.string(),i.z.symbol()]),i.z.unknown());const Af=()=>typeof process<"u"&&process.versions!=null&&process.versions.node!=null?"node":typeof window>"u"||window.document===void 0?"webworker":"browser";Af();const $f=["macOS","Windows","Linux"],If=["macos","windows","linux"],Zf={macos:"macOS",windows:"Windows",linux:"Linux"};i.z.enum($f).or(i.z.enum(If).transform(t=>Zf[t]));i.z.enum(["success","info","warning","error","loading","disabled"]);i.z.object({stack:i.z.string(),error:i.z.instanceof(Error)});const xf=(...t)=>t.map(Da).join(""),Da=t=>(t.endsWith("/")||(t+="/"),t.startsWith("/")&&(t=t.slice(1)),t),Cf=t=>t.endsWith("/")?t.slice(0,-1):t,Rf=(t,e="")=>t===null?"":`?${Object.entries(t).filter(([,n])=>n==null?!1:Array.isArray(n)?n.length>0:!0).map(([n,r])=>`${e}${n}=${r}`).join("&")}`;let _f=class En{protocol;host;port;path;constructor({host:e,port:n,protocol:r="",pathPrefix:s=""}){this.protocol=r,this.host=e,this.port=n,this.path=Da(s)}replace(e){return new En({host:e.host??this.host,port:e.port??this.port,protocol:e.protocol??this.protocol,pathPrefix:e.pathPrefix??this.path})}child(e){return new En({...this,pathPrefix:xf(this.path,e)})}toString(){return Cf(`${this.protocol}://${this.host}:${this.port}/${this.path}`)}static UNKNOWN=new En({host:"unknown",port:0})};i.z.int().min(0).max(uh);class Jt extends Pe.createTyped("freighter"){}let fe=class extends Jt.sub("eof"){constructor(){super("EOF")}},Ot=class extends Jt.sub("stream_closed"){constructor(){super("StreamClosed")}},Be=class extends Jt.sub("unreachable"){url;constructor(e={}){const{message:n="Unreachable",url:r=_f.UNKNOWN}=e;super(n),this.url=r}};const Mf=t=>{if(!t.type.startsWith(Jt.TYPE))return null;if(fe.matches(t))return{type:fe.TYPE,data:"EOF"};if(Ot.matches(t))return{type:Ot.TYPE,data:"StreamClosed"};if(Be.matches(t))return{type:Be.TYPE,data:"Unreachable"};throw new Error(`Unknown error type: ${t.type}: ${t.message}`)},jf=t=>{if(!t.type.startsWith(Jt.TYPE))return null;switch(t.type){case fe.TYPE:return new fe;case Ot.TYPE:return new Ot;case Be.TYPE:return new Be;default:throw new Pe.Unknown(`Unknown error type: ${t.data}`)}};Pe.register({encode:Mf,decode:jf});let La=class{middleware=[];use(...e){this.middleware.push(...e)}async executeMiddleware(e,n){let r=0;const s=async a=>{if(r===this.middleware.length)return await n(a);const o=this.middleware[r];return r++,await o(a,s)};return await s(e)}};const Pa="Content-Type",Uf=new Set(["ECONNREFUSED","ECONNRESET","ETIMEDOUT","EPIPE","UND_ERR_CONNECT_TIMEOUT","UND_ERR_SOCKET"]),Df=t=>{const e=t?.cause?.code??t?.code??t?.errno;if(typeof e=="string"&&Uf.has(e))return!0;if(t.name==="TypeError"){const n=String(t.message||"").toLowerCase();if(/load failed|failed to fetch|networkerror|network error/.test(n))return!0}return t?.name==="AbortError"||t?.code,!1},Lf=400;let Pf=class extends La{endpoint;encoder;constructor(e,n,r=!1){return super(),this.endpoint=e.replace({protocol:r?"https":"http"}),this.encoder=n,new Proxy(this,{get:(s,a,o)=>a==="endpoint"?this.endpoint:Reflect.get(s,a,o)})}get headers(){return{[Pa]:this.encoder.contentType}}async send(e,n,r,s){n=r?.parse(n);let a=null;const o=this.endpoint.child(e),c={};c.method="POST",c.body=this.encoder.encode(n??{});const[,l]=await this.executeMiddleware({target:o.toString(),protocol:this.endpoint.protocol,params:{},role:"client"},async u=>{const h={...u,params:{}};c.headers={...this.headers,...u.params};let y;try{y=await fetch(u.target,c)}catch(T){if(!(T instanceof Error))throw T;return[h,Df(T)?new Be({url:o}):T]}const f=await y.arrayBuffer();if(y?.ok)return s!=null&&(a=this.encoder.decode(f,s)),[h,null];try{if(y.status!==Lf)return[h,new Error(y.statusText)];const T=this.encoder.decode(f,Pe.payloadZ),S=Pe.decode(T);return[h,S]}catch(T){return[h,new Error(`[freighter] - failed to decode error: ${y.statusText}: ${T.message}`)]}});if(l!=null)return[null,l];if(a==null)throw new Error("Response must be defined");return[a,null]}};const Bf=(t,e)=>{class n{wrapped;constructor(s){this.wrapped=s}use(...s){this.wrapped.use(...s)}async send(s,a,o,c){const l=new Xh.Breaker(e);do{const[u,h]=await this.wrapped.send(s,a,o,c);if(h==null)return[u,null];if(!Be.matches(h))return[null,h];if(console.warn(`[freighter] ${l.retryMessage}`,h),!await l.wait())return[u,h]}while(!0)}}return new n(t)},z=async(t,e,n,r,s)=>{const[a,o]=await t.send(e,n,r,s);if(o!=null)throw o;return a},qf=i.z.object({type:i.z.enum(["data","close","open"]),payload:i.z.unknown(),error:i.z.optional(Pe.payloadZ)});let Ff=class{codec;reqSchema;resSchema;ws;serverClosed;sendClosed;receiveDataQueue=[];receiveCallbacksQueue=[];constructor(e,n,r,s){this.codec=n,this.reqSchema=r,this.resSchema=s,this.ws=e,this.sendClosed=!1,this.serverClosed=null,this.listenForMessages()}async receiveOpenAck(){const e=await this.receiveMsg();if(e.type!=="open"){if(e.error==null)throw new Error("Message error must be defined");return Pe.decode(e.error)}return null}send(e){if(this.serverClosed!=null)return new fe;if(this.sendClosed)throw new Ot;return this.ws.send(this.codec.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");if(this.serverClosed=Pe.decode(e.error),this.serverClosed==null)throw new Error("Message error must be defined");return[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.codec.encode(e))}finally{this.sendClosed=!0}}async receiveMsg(){return this.receiveDataQueue.shift()??await new Promise((n,r)=>this.receiveCallbacksQueue.push({resolve:n,reject:r}))}addMessage(e){const n=this.receiveCallbacksQueue.shift();n!=null?n.resolve(e):this.receiveDataQueue.push(e)}listenForMessages(){this.ws.onmessage=this.onMessage.bind(this),this.ws.onclose=this.onClose.bind(this)}onMessage(e){this.addMessage(this.codec.decode(e.data,qf))}onClose(e){this.addMessage({type:"close",error:{type:e.code===Hf?fe.TYPE:Ot.TYPE,data:""}})}};const Yf="freighterctx",Hf=1e3;let Vf=class $r extends La{baseUrl;encoder;secure;static MESSAGE_TYPE="arraybuffer";constructor(e,n,r=!1){super(),this.secure=r,this.baseUrl=e.replace({protocol:r?"wss":"ws"}),this.encoder=n}withCodec(e){const n=new $r(this.baseUrl,e,this.secure);return n.use(...this.middleware),n}async stream(e,n,r){let s;const[,a]=await this.executeMiddleware({target:e,protocol:"websocket",params:{},role:"client"},async o=>{const c=new WebSocket(this.buildURL(e,o)),l={...o,params:{}};c.binaryType=$r.MESSAGE_TYPE;const u=await this.wrapSocket(c,n,r);return u instanceof Error?[l,u]:(s=u,[l,null])});if(a!=null)throw a;return s}buildURL(e,n){const r=Rf({[Pa]:this.encoder.contentType,...n.params},Yf);return this.baseUrl.child(e).toString()+r}async wrapSocket(e,n,r){return await new Promise(s=>{e.onopen=()=>{const a=new Ff(e,this.encoder,n,r);a.receiveOpenAck().then(o=>{o!=null?s(o):s(a)}).catch(o=>s(o))},e.onerror=a=>{const o=a;s(new Error(o.message))}})}};const Ba=t=>i.union([i.union([i.null(),i.undefined()]).transform(()=>[]),t.array()]),Gf=t=>Array.isArray(t)?t:t==null?[]:[t],qa=(t,e)=>{if(Array.isArray(e))return e.reduce((s,a)=>qa(s,a),t??[]);if(t==null)return[e];const n=t.findIndex(s=>s==e),r=[...t];return n===-1?r.push(e):r[n]=e,r},Wf=((t,e)=>{if(t!=null)return Array.isArray(e)?t.filter(n=>!e.includes(n)):t.filter(n=>n!=e)}),Fa=(t,e)=>{if(Array.isArray(e))return e.reduce((s,a)=>Fa(s,a),t??[]);if(t==null)return[e];const n=t.findIndex(s=>s.key===e.key),r=[...t];return n===-1?r.push(e):r[n]=e,r},Kf=((t,e)=>{if(t!=null)return Array.isArray(e)?t.filter(n=>!e.includes(n.key)):t.filter(n=>n.key!==e)}),E=Object.freeze(Object.defineProperty({__proto__:null,nullableZ:Ba,remove:Wf,removeKeyed:Kf,toArray:Gf,upsert:qa,upsertKeyed:Fa},Symbol.toStringTag,{value:"Module"})),Jf=t=>{const e=t.replace(/_[a-z]/g,n=>n[1].toUpperCase());return e.length>1&&e[0]===e[0].toUpperCase()&&e[1]===e[1].toUpperCase()||e.length===0?e:e[0].toLowerCase()+e.slice(1)},jn=t=>{const e=(n,r=Ir)=>{if(typeof n=="string")return t(n);if(Array.isArray(n))return n.map(o=>e(o,r));if(!cr(n))return n;r=ed(r);const s={},a=n;return"toJSON"in a&&typeof a.toJSON=="function"?e(a.toJSON(),r):(Object.keys(a).forEach(o=>{let c=a[o];const l=t(o);r.recursive&&(cr(c)?Ti(c)||(c=e(c,r)):r.recursiveInArray&&zi(c)&&(c=[...c].map(u=>{let h=u;return cr(u)?Ti(h)||(h=e(u,r)):zi(u)&&(h=e({key:u},r).key),h}))),s[l]=c}),s)};return e},us=jn(Jf),Xf=t=>t.replace(/([a-z0-9])([A-Z])/g,(e,n,r)=>`${n}_${r.toLowerCase()}`),Ya=jn(Xf),Ha=t=>t.length===0?t:t[0].toUpperCase()+t.slice(1),Qf=[Number,String,Uint8Array],Ir={recursive:!0,recursiveInArray:!0},ed=(t=Ir)=>(t.recursive==null?t=Ir:t.recursiveInArray??=!1,t),zi=t=>t!=null&&Array.isArray(t),cr=t=>t!=null&&typeof t=="object"&&!Array.isArray(t),Ti=t=>Qf.some(e=>t instanceof e),td=t=>t.replace(/[\s_]+/g,"-").replace(/([a-z0-9])([A-Z])/g,(e,n,r)=>`${n}-${r.toLowerCase()}`).toLowerCase(),nd=jn(td),rd=t=>{if(t.length===0)return t;let e=t.replace(/[_-]/g," ");return e=e.replace(/([a-z0-9])([A-Z])/g,(n,r,s)=>`${r} ${s}`),e=e.replace(/([A-Z]+)([A-Z][a-z])/g,(n,r,s)=>`${r} ${s}`),e=e.replace(/\s+/g," ").trim(),e=e.replace(/\b\w/g,n=>n.toUpperCase()),e},sd=jn(rd),id=Object.freeze(Object.defineProperty({__proto__:null,camelToSnake:Ya,capitalize:Ha,snakeToCamel:us,toKebab:nd,toProperNoun:sd},Symbol.toStringTag,{value:"Module"})),ad=t=>t!=null&&typeof t=="object"&&!Array.isArray(t);class Va{contentType="application/json";decoder;encoder;constructor(){this.decoder=new TextDecoder,this.encoder=new TextEncoder}encode(e){return this.encoder.encode(this.encodeString(e))}decode(e,n){return this.decodeString(this.decoder.decode(e),n)}decodeString(e,n){const r=JSON.parse(e),s=us(r);return n!=null?n.parse(s):s}encodeString(e){const n=Ya(e);return JSON.stringify(n,(r,s)=>ArrayBuffer.isView(s)?Array.from(s):typeof s=="bigint"?s.toString():s)}}class Ga{contentType="text/csv";encode(e){const n=this.encodeString(e);return new TextEncoder().encode(n)}decode(e,n){const r=new TextDecoder().decode(e);return this.decodeString(r,n)}encodeString(e){if(!Array.isArray(e)||e.length===0||!ad(e[0]))throw new Error("Payload must be an array of objects");const n=Object.keys(e[0]),r=[n.join(",")];return e.forEach(s=>{const a=n.map(o=>JSON.stringify(s[o]??""));r.push(a.join(","))}),r.join(`
5
+ `).buffer):this.dataType.usesBigInt&&typeof O=="number"?this._data=new this.dataType.Array(f.map(E=>BigInt(Math.round(E)))).buffer:!this.dataType.usesBigInt&&typeof O=="bigint"?this._data=new this.dataType.Array(f.map(Number)).buffer:this._data=new this.dataType.Array(f).buffer}this.key=l,this.alignment=o,this.alignmentMultiple=c,this.sampleOffset=s??0,this.timeRange=r??_t.ZERO,this.gl={control:null,buffer:null,prevBuffer:0,bufferUsage:a}}static alloc({capacity:e,dataType:n,...r}){if(e===0)throw new Error("[Series] - cannot allocate an array of length 0");const s=new new p(n).Array(e),a=new Be({data:s.buffer,dataType:n,...r});return a.writePos=0,a}get refCount(){return this._refCount}acquire(e){this._refCount++,e!=null&&this.updateGLBuffer(e)}release(){this._refCount--,this.refCount===0&&this.gl.control!=null?this.maybeGarbageCollectGLBuffer(this.gl.control):this.refCount<0&&console.warn("cannot release a series with a negative reference count")}write(e){if(!e.dataType.equals(this.dataType))throw new Error("buffer must be of the same type as this array");return this.dataType.isVariable?this.writeVariable(e):this.writeFixed(e)}writeVariable(e){if(this.writePos===Ue)return 0;const n=this.byteCapacity.valueOf()-this.writePos,r=e.subBytes(0,n);return this.writeToUnderlyingData(r),this.writePos+=r.byteLength.valueOf(),this.cachedLength!=null&&(this.cachedLength+=r.length,this.calculateCachedLength()),r.length}writeFixed(e){if(this.writePos===Ue)return 0;const n=this.capacity-this.writePos,r=e.sub(0,n);return this.writeToUnderlyingData(r),this.cachedLength=void 0,this.maybeRecomputeMinMax(r),this.writePos+=r.length,r.length}writeToUnderlyingData(e){this.underlyingData.set(e.data,this.writePos)}get buffer(){return typeof this._data=="object"&&"buffer"in this._data?this._data.buffer:this._data}get underlyingData(){return new this.dataType.Array(this._data)}get data(){return this.writePos===Ue?this.underlyingData:new this.dataType.Array(this._data,0,this.writePos)}toStrings(){return this.dataType.isVariable?new TextDecoder().decode(this.underlyingData).split(`
6
+ `).slice(0,-1):Array.from(this).map(e=>e.toString())}parseJSON(e){if(!this.dataType.equals(p.JSON))throw new Error("cannot parse non-JSON series as JSON");return this.toStrings().map(n=>e.parse(Er.decodeString(n)))}get byteCapacity(){return new I(this.underlyingData.byteLength)}get capacity(){return this.dataType.isVariable?this.byteCapacity.valueOf():this.dataType.density.length(this.byteCapacity)}get byteLength(){return this.writePos===Ue?this.byteCapacity:this.dataType.isVariable?new I(this.writePos):this.dataType.density.size(this.writePos)}get length(){return this.cachedLength!=null?this.cachedLength:this.dataType.isVariable?this.calculateCachedLength():this.writePos===Ue?this.byteCapacity.valueOf()/this.dataType.density.valueOf():this.writePos}calculateCachedLength(){if(!this.dataType.isVariable)throw new Error("cannot calculate length of a non-variable length data type");let e=0;const n=[0];return this.data.forEach((r,s)=>{r===Ar&&(e++,n.push(s+1))}),this._cachedIndexes=n,this.cachedLength=e,e}convert(e,n=0){if(this.dataType.equals(e))return this;const r=new e.Array(this.length);for(let s=0;s<this.length;s++)r[s]=Fh(this.dataType,e,this.data[s],n);return new Be({data:r.buffer,dataType:e,timeRange:this.timeRange,sampleOffset:n,glBufferUsage:this.gl.bufferUsage,alignment:this.alignment})}calcRawMax(){if(this.length===0)return-1/0;if(this.dataType.equals(p.TIMESTAMP))this.cachedMax=this.data[this.data.length-1];else if(this.dataType.usesBigInt){const e=this.data;this.cachedMax=e.reduce((n,r)=>n>r?n:r)}else{const e=this.data;this.cachedMax=e.reduce((n,r)=>n>r?n:r)}return this.cachedMax}get max(){return this.calcMax()}calcMax(){if(this.dataType.isVariable)throw new Error("cannot calculate maximum on a variable length data type");return this.writePos===0?-1/0:(this.cachedMax??=this.calcRawMax(),tt(this.cachedMax,this.sampleOffset))}calcRawMin(){if(this.length===0)return 1/0;if(this.dataType.equals(p.TIMESTAMP))this.cachedMin=this.data[0];else if(this.dataType.usesBigInt){const e=this.data;this.cachedMin=e.reduce((n,r)=>n<r?n:r)}else{const e=this.data;this.cachedMin=e.reduce((n,r)=>n<r?n:r)}return this.cachedMin}get min(){return this.calcMin()}calcMin(){if(this.dataType.isVariable)throw new Error("cannot calculate minimum on a variable length data type");return this.writePos===0?1/0:(this.cachedMin??=this.calcRawMin(),tt(this.cachedMin,this.sampleOffset))}get bounds(){return nt(Number(this.min),Number(this.max),{makeValid:!1})}maybeRecomputeMinMax(e){if(this.cachedMin!=null){const n=e.cachedMin??e.calcRawMin();n<this.cachedMin&&(this.cachedMin=n)}if(this.cachedMax!=null){const n=e.cachedMax??e.calcRawMax();n>this.cachedMax&&(this.cachedMax=n)}}atAlignment(e,n){const r=Number((e-this.alignment)/this.alignmentMultiple);if(r<0||r>=this.length){if(n===!0)throw new Error(`[series] - no value at index ${r}`);return}return this.at(r,n)}at(e,n=!1){if(this.dataType.isVariable)return this.atVariable(e,n??!1);if(this.dataType.equals(p.UUID))return this.atUUID(e,n);e<0&&(e=this.length+e);const r=this.data[e];if(r==null){if(n===!0)throw new Error(`[series] - no value at index ${e}`);return}return tt(r,this.sampleOffset)}atUUID(e,n){e<0&&(e=this.length+e);const r=_a(new Uint8Array(this.buffer,e*this.dataType.density.valueOf()));if(r==null){if(n)throw new Error(`[series] - no value at index ${e}`);return}return r}atVariable(e,n){let r=0,s=0;if(this._cachedIndexes!=null)r=this._cachedIndexes[e],s=this._cachedIndexes[e+1]-1;else{e<0&&(e=this.length+e);for(let o=0;o<this.data.length;o++)if(this.data[o]===Ar){if(e===0){s=o;break}r=o+1,e--}if(s===0&&(s=this.data.length),r>=s||e>0){if(n)throw new Error(`[series] - no value at index ${e}`);return}}const a=this.data.slice(r,s);return this.dataType.equals(p.STRING)?new TextDecoder().decode(a):za(JSON.parse(new TextDecoder().decode(a)))}binarySearch(e){let n=0,r=this.length-1;const s=uh(e);for(;n<=r;){const a=Math.floor((n+r)/2),o=s(this.at(a,!0),e);if(o===0)return a;o<0?n=a+1:r=a-1}return n}updateGLBuffer(e){if(this.gl.control=e,!this.dataType.equals(p.FLOAT32)&&!this.dataType.equals(p.UINT8))throw new Error("Only FLOAT32 and UINT8 arrays can be used in WebGL");const{buffer:n,bufferUsage:r,prevBuffer:s}=this.gl;if(n==null&&(this.gl.buffer=e.createBuffer()),this.writePos!==s)if(e.bindBuffer(e.ARRAY_BUFFER,this.gl.buffer),this.writePos!==Ue){s===0&&e.bufferData(e.ARRAY_BUFFER,this.byteCapacity.valueOf(),e.STATIC_DRAW);const a=this.dataType.density.size(s).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,r==="static"?e.STATIC_DRAW:e.DYNAMIC_DRAW),this.gl.prevBuffer=Ue}as(e){return Jh(e,this.dataType),this}get digest(){return{key:this.key,dataType:this.dataType.toString(),sampleOffset:this.sampleOffset,alignment:{lower:Ti(this.alignmentBounds.lower),upper:Ti(this.alignmentBounds.upper),multiple:this.alignmentMultiple},timeRange:this.timeRange.toString(),length:this.length,capacity:this.capacity}}get alignmentBounds(){return nt(this.alignment,this.alignment+BigInt(this.length)*this.alignmentMultiple)}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 ef(this);return this.dataType.equals(p.JSON)?new os(e):e}return this.dataType.equals(p.UUID)?new tf(this):new nf(this)}slice(e,n){return this.sliceSub(!1,e,n)}sub(e,n){return this.sliceSub(!0,e,n)}subIterator(e,n){return new zi(this,e,n??this.length)}subAlignmentIterator(e,n){const r=Math.ceil(Number(e-this.alignment)/Number(this.alignmentMultiple)),s=Math.ceil(Number(n-this.alignment)/Number(this.alignmentMultiple));return new zi(this,r,s)}subBytes(e,n){if(e>=0&&(n==null||n>=this.byteLength.valueOf()))return this;const r=this.data.subarray(e,n);return new Be({data:r,dataType:this.dataType,timeRange:this.timeRange,sampleOffset:this.sampleOffset,glBufferUsage:this.gl.bufferUsage,alignment:this.alignment+BigInt(e)})}sliceSub(e,n,r){if(n<=0&&(r==null||r>=this.length))return this;let s;return e?s=this.data.subarray(n,r):s=this.data.slice(n,r),new Be({data:s,dataType:this.dataType,timeRange:this.timeRange,sampleOffset:this.sampleOffset,glBufferUsage:this.gl.bufferUsage,alignment:this.alignment+BigInt(n)})}reAlign(e){return new Be({data:this.buffer,dataType:this.dataType,timeRange:_t.ZERO,sampleOffset:this.sampleOffset,glBufferUsage:"static",alignment:e})}toString(){let e=`Series(${this.dataType.toString()} ${this.length} [`;if(this.length<=10)e+=Array.from(this).map(n=>n.toString());else{for(let n=0;n<5;n++)e+=`${this.at(n)?.toString()}`,e+=",";e+="...,";for(let n=-5;n<0;n++)e+=this.at(n)?.toString(),n<-1&&(e+=",")}return e+="])",e}};const Xh=t=>t==null?!1:Array.isArray(t)||t instanceof ArrayBuffer||ArrayBuffer.isView(t)&&!(t instanceof DataView)||t instanceof ja?!0:Ra(t),Qh=mh(Ma,ja);let zi=class{series;end;index;constructor(e,n,r){this.series=e;const s=nt(0,e.length+1);this.end=gi(s,r),this.index=gi(s,n)}next(){return this.index>=this.end?{done:!0,value:void 0}:{done:!1,value:this.series.at(this.index++,!0)}}};class ef{series;index;decoder;constructor(e){if(!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,n=this.series.data;for(;this.index<n.length&&n[this.index]!==Ar;)this.index++;const r=this.index;return e===r?{done:!0,value:void 0}:(this.index++,{done:!1,value:this.decoder.decode(this.series.buffer.slice(e,r))})}}class os{wrapped;static schema=i.z.record(i.z.string(),i.z.unknown());constructor(e){this.wrapped=e}next(){const e=this.wrapped.next();return e.done===!0?{done:!0,value:void 0}:{done:!1,value:Er.decodeString(e.value,os.schema)}}}let tf=class{series;index;data;density;constructor(e){if(!e.dataType.equals(p.UUID))throw new Error("cannot create a UUID series iterator for a non-UUID series");this.series=e,this.index=0,this.data=new Uint8Array(e.buffer),this.density=p.UUID.density.valueOf()}next(){if(this.index>=this.series.length)return{done:!0,value:void 0};const e=_a(this.data,this.index*this.density);return this.index++,{done:!1,value:e}}};class nf{series;index;constructor(e){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)}}}const Ti=t=>{const e=t>>32n,n=t&0xffffffffn;return{domain:e,sample:n}},rf=async t=>await new Promise(e=>setTimeout(e,v.fromMilliseconds(t).milliseconds));let sf=class{config;retries;interval;constructor(e){this.config={baseInterval:new v(e?.baseInterval??v.seconds(1)),maxRetries:e?.maxRetries??5,scale:e?.scale??1,sleepFn:e?.sleepFn??rf},this.retries=0,this.interval=new v(this.config.baseInterval)}async wait(){const{maxRetries:e,scale:n,sleepFn:r}=this.config;return this.retries>=e?!1:(await r(this.interval),this.interval=this.interval.mult(n),this.retries++,!0)}get retryMessage(){return`breaker triggered ${this.retries+1}/${this.config.maxRetries} times, retrying in ${this.interval.toString()}`}reset(){this.retries=0,this.interval=this.config.baseInterval}};const af=i.z.object({baseInterval:v.z.optional(),maxRetries:i.z.number().optional(),scale:i.z.number().optional()}),of=Object.freeze(Object.defineProperty({__proto__:null,Breaker:sf,breakerConfigZ:af},Symbol.toStringTag,{value:"Module"})),cf=/^#?([0-9a-f]{6}|[0-9a-f]{8})$/i,Ua=i.z.string().regex(cf),zt=i.z.number().min(0).max(255),Da=i.z.number().min(0).max(1),Pa=i.z.tuple([zt,zt,zt,Da]),uf=i.z.tuple([zt,zt,zt]),lf=i.z.object({rgba255:Pa}),hf=i.z.number().min(0).max(360),ff=i.z.number().min(0).max(100),df=i.z.number().min(0).max(100),yf=i.z.tuple([hf,ff,df,Da]),cs=i.z.union([Ua,uf,Pa,yf,lf]),pf=cs.transform(t=>us(t)),us=(t,e=1)=>{if(t=cs.parse(t),typeof t=="string")return mf(t,e);if(Array.isArray(t)){if(t.length<3||t.length>4)throw new Error(`Invalid color: [${t.join(", ")}]`);return t.length===3?[...t,e]:t}return t.rgba255},mf=(t,e=1)=>(t=Ua.parse(t),t=gf(t),[wn(t,0),wn(t,2),wn(t,4),t.length===8?wn(t,6)/255:e]),wn=(t,e)=>parseInt(t.slice(e,e+2),16),gf=t=>t.startsWith("#")?t.slice(1):t;us("#000000");us("#ffffff");const wf=i.z.object({key:i.z.string(),color:cs,position:i.z.number(),switched:i.z.boolean().optional()});i.z.array(wf);const bf=i.z.object({key:i.z.string(),name:i.z.string(),color:pf});i.z.object({key:i.z.string(),name:i.z.string(),swatches:i.z.array(bf)});i.z.int().min(0).max(255);i.z.object({name:i.z.string(),key:i.z.string()});const vf=t=>Object.getOwnPropertySymbols(globalThis).includes(t),zf=(t,e)=>{const n=Symbol.for(t);if(!vf(n)){const r=e();Object.defineProperty(globalThis,n,{value:r})}return()=>globalThis[n]},La="sy_x_error",Tf=t=>e=>e!=null&&typeof e=="object"&&"type"in e&&typeof e.type=="string"?e.type.startsWith(t):e instanceof Error?e.message.startsWith(t):typeof e!="string"?!1:e.startsWith(t),Xt=t=>class Mt extends Error{static discriminator=La;discriminator=Mt.discriminator;static TYPE=t;type=Mt.TYPE;static matches=Tf(t);matches=Mt.matches;constructor(n,r){super(n,r),this.name=Mt.TYPE}static sub(n){return Xt(`${t}.${n}`)}},Ba=t=>{if(t==null||typeof t!="object")return!1;const e=t;if(e.discriminator!==La)return!1;if(!("type"in e))throw new Error(`X Error is missing its type property: ${JSON.stringify(e)}`);return!0},wt="unknown",$r="nil";class Of{providers=[];register(e){this.providers.push(e)}encode(e){if(e==null)return{type:$r,data:""};if(Ba(e))for(const n of this.providers){const r=n.encode(e);if(r!=null)return r}if(e instanceof Error)return{type:wt,data:e.message};if(typeof e=="string")return{type:wt,data:e};try{return{type:wt,data:JSON.stringify(e)}}catch{return{type:wt,data:"unable to encode error information"}}}decode(e){if(e==null||e.type===$r)return null;if(e.type===wt)return new Ir(e.data);for(const n of this.providers){const r=n.decode(e);if(r!=null)return r}return new Ir(e.data)}}const ls=zf("synnax-error-registry",()=>new Of),Nf=({encode:t,decode:e})=>ls().register({encode:t,decode:e}),Sf=t=>ls().encode(t),Ef=t=>t==null?null:ls().decode(t);let Ir=class extends Xt("unknown"){};const kf=i.z.object({type:i.z.string(),data:i.z.string()});let Af=class extends Xt("canceled"){},$f=class extends Xt("not_implemented"){};const Ye=Object.freeze(Object.defineProperty({__proto__:null,Canceled:Af,NONE:$r,NotImplemented:$f,UNKNOWN:wt,Unknown:Ir,createTyped:Xt,decode:Ef,encode:Sf,isTyped:Ba,payloadZ:kf,register:Nf},Symbol.toStringTag,{value:"Module"})),If=i.object({jsonrpc:i.literal("2.0"),method:i.string(),params:i.any().optional(),id:i.union([i.string(),i.number(),i.null()]).optional()}),qa=i.object({jsonrpc:i.literal("2.0"),id:i.union([i.string(),i.number(),i.null()])}),Zf=qa.extend({result:i.json()}),xf=qa.extend({error:i.object({code:i.number().int(),message:i.string().optional(),data:i.json().optional()})}),Cf=i.union([Zf,xf]);i.union([If,Cf]);i.z.object({key:i.z.string(),value:i.z.string()});const Rf=i.uuid();i.object({key:Rf,name:i.string().min(1),color:i.string()});i.z.string().regex(/^\d+\.\d+\.\d+(-[0-9A-Za-z-]+(\.[0-9A-Za-z-]+)*)?$/);const _f=["standard","scientific","engineering"];i.z.enum(_f);i.z.record(i.z.union([i.z.number(),i.z.string(),i.z.symbol()]),i.z.unknown());const Mf=()=>typeof process<"u"&&process.versions!=null&&process.versions.node!=null?"node":typeof window>"u"||window.document===void 0?"webworker":"browser";Mf();const jf=["macOS","Windows","Linux"],Uf=["macos","windows","linux"],Df={macos:"macOS",windows:"Windows",linux:"Linux"};i.z.enum(jf).or(i.z.enum(Uf).transform(t=>Df[t]));i.z.enum(["success","info","warning","error","loading","disabled"]);i.z.object({stack:i.z.string(),error:i.z.instanceof(Error)});const Pf=(...t)=>t.map(Fa).join(""),Fa=t=>(t.endsWith("/")||(t+="/"),t.startsWith("/")&&(t=t.slice(1)),t),Lf=t=>t.endsWith("/")?t.slice(0,-1):t,Bf=(t,e="")=>t===null?"":`?${Object.entries(t).filter(([,n])=>n==null?!1:Array.isArray(n)?n.length>0:!0).map(([n,r])=>`${e}${n}=${r}`).join("&")}`;let qf=class En{protocol;host;port;path;constructor({host:e,port:n,protocol:r="",pathPrefix:s=""}){this.protocol=r,this.host=e,this.port=n,this.path=Fa(s)}replace(e){return new En({host:e.host??this.host,port:e.port??this.port,protocol:e.protocol??this.protocol,pathPrefix:e.pathPrefix??this.path})}child(e){return new En({...this,pathPrefix:Pf(this.path,e)})}toString(){return Lf(`${this.protocol}://${this.host}:${this.port}/${this.path}`)}static UNKNOWN=new En({host:"unknown",port:0})};i.z.int().min(0).max(gh);class Qt extends Ye.createTyped("freighter"){}let ge=class extends Qt.sub("eof"){constructor(){super("EOF")}},St=class extends Qt.sub("stream_closed"){constructor(){super("StreamClosed")}},Ve=class extends Qt.sub("unreachable"){url;constructor(e={}){const{message:n="Unreachable",url:r=qf.UNKNOWN}=e;super(n),this.url=r}};const Ff=t=>{if(!t.type.startsWith(Qt.TYPE))return null;if(ge.matches(t))return{type:ge.TYPE,data:"EOF"};if(St.matches(t))return{type:St.TYPE,data:"StreamClosed"};if(Ve.matches(t))return{type:Ve.TYPE,data:"Unreachable"};throw new Error(`Unknown error type: ${t.type}: ${t.message}`)},Yf=t=>{if(!t.type.startsWith(Qt.TYPE))return null;switch(t.type){case ge.TYPE:return new ge;case St.TYPE:return new St;case Ve.TYPE:return new Ve;default:throw new Ye.Unknown(`Unknown error type: ${t.data}`)}};Ye.register({encode:Ff,decode:Yf});let Ya=class{middleware=[];use(...e){this.middleware.push(...e)}async executeMiddleware(e,n){let r=0;const s=async a=>{if(r===this.middleware.length)return await n(a);const o=this.middleware[r];return r++,await o(a,s)};return await s(e)}};const Va="Content-Type",Vf=new Set(["ECONNREFUSED","ECONNRESET","ETIMEDOUT","EPIPE","UND_ERR_CONNECT_TIMEOUT","UND_ERR_SOCKET"]),Gf=t=>{const e=t?.cause?.code??t?.code??t?.errno;if(typeof e=="string"&&Vf.has(e))return!0;if(t.name==="TypeError"){const n=String(t.message||"").toLowerCase();if(/load failed|failed to fetch|networkerror|network error/.test(n))return!0}return t?.name==="AbortError"||t?.code,!1},Hf=400;let Wf=class extends Ya{endpoint;encoder;constructor(e,n,r=!1){return super(),this.endpoint=e.replace({protocol:r?"https":"http"}),this.encoder=n,new Proxy(this,{get:(s,a,o)=>a==="endpoint"?this.endpoint:Reflect.get(s,a,o)})}get headers(){return{[Va]:this.encoder.contentType}}async send(e,n,r,s){n=r?.parse(n);let a=null;const o=this.endpoint.child(e),c={};c.method="POST",c.body=this.encoder.encode(n??{});const[,l]=await this.executeMiddleware({target:o.toString(),protocol:this.endpoint.protocol,params:{},role:"client"},async u=>{const h={...u,params:{}};c.headers={...this.headers,...u.params};let d;try{d=await fetch(u.target,c)}catch(O){if(!(O instanceof Error))throw O;return[h,Gf(O)?new Ve({url:o}):O]}const f=await d.arrayBuffer();if(d?.ok)return s!=null&&(a=this.encoder.decode(f,s)),[h,null];try{if(d.status!==Hf)return[h,new Error(d.statusText)];const O=this.encoder.decode(f,Ye.payloadZ),E=Ye.decode(O);return[h,E]}catch(O){return[h,new Error(`[freighter] - failed to decode error: ${d.statusText}: ${O.message}`)]}});if(l!=null)return[null,l];if(a==null)throw new Error("Response must be defined");return[a,null]}};const Kf=(t,e)=>{class n{wrapped;constructor(s){this.wrapped=s}use(...s){this.wrapped.use(...s)}async send(s,a,o,c){const l=new of.Breaker(e);do{const[u,h]=await this.wrapped.send(s,a,o,c);if(h==null)return[u,null];if(!Ve.matches(h))return[null,h];if(console.warn(`[freighter] ${l.retryMessage}`,h),!await l.wait())return[u,h]}while(!0)}}return new n(t)},T=async(t,e,n,r,s)=>{const[a,o]=await t.send(e,n,r,s);if(o!=null)throw o;return a},Jf=i.z.object({type:i.z.enum(["data","close","open"]),payload:i.z.unknown(),error:i.z.optional(Ye.payloadZ)});let Xf=class{codec;reqSchema;resSchema;ws;serverClosed;sendClosed;receiveDataQueue=[];receiveCallbacksQueue=[];constructor(e,n,r,s){this.codec=n,this.reqSchema=r,this.resSchema=s,this.ws=e,this.sendClosed=!1,this.serverClosed=null,this.listenForMessages()}async receiveOpenAck(){const e=await this.receiveMsg();if(e.type!=="open"){if(e.error==null)throw new Error("Message error must be defined");return Ye.decode(e.error)}return null}send(e){if(this.serverClosed!=null)return new ge;if(this.sendClosed)throw new St;return this.ws.send(this.codec.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");if(this.serverClosed=Ye.decode(e.error),this.serverClosed==null)throw new Error("Message error must be defined");return[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.codec.encode(e))}finally{this.sendClosed=!0}}async receiveMsg(){return this.receiveDataQueue.shift()??await new Promise((n,r)=>this.receiveCallbacksQueue.push({resolve:n,reject:r}))}addMessage(e){const n=this.receiveCallbacksQueue.shift();n!=null?n.resolve(e):this.receiveDataQueue.push(e)}listenForMessages(){this.ws.onmessage=this.onMessage.bind(this),this.ws.onclose=this.onClose.bind(this)}onMessage(e){this.addMessage(this.codec.decode(e.data,Jf))}onClose(e){this.addMessage({type:"close",error:{type:e.code===ed?ge.TYPE:St.TYPE,data:""}})}};const Qf="freighterctx",ed=1e3;let td=class Zr extends Ya{baseUrl;encoder;secure;static MESSAGE_TYPE="arraybuffer";constructor(e,n,r=!1){super(),this.secure=r,this.baseUrl=e.replace({protocol:r?"wss":"ws"}),this.encoder=n}withCodec(e){const n=new Zr(this.baseUrl,e,this.secure);return n.use(...this.middleware),n}async stream(e,n,r){let s;const[,a]=await this.executeMiddleware({target:e,protocol:"websocket",params:{},role:"client"},async o=>{const c=new WebSocket(this.buildURL(e,o)),l={...o,params:{}};c.binaryType=Zr.MESSAGE_TYPE;const u=await this.wrapSocket(c,n,r);return u instanceof Error?[l,u]:(s=u,[l,null])});if(a!=null)throw a;return s}buildURL(e,n){const r=Bf({[Va]:this.encoder.contentType,...n.params},Qf);return this.baseUrl.child(e).toString()+r}async wrapSocket(e,n,r){return await new Promise(s=>{e.onopen=()=>{const a=new Xf(e,this.encoder,n,r);a.receiveOpenAck().then(o=>{o!=null?s(o):s(a)}).catch(o=>s(o))},e.onerror=a=>{const o=a;s(new Error(o.message))}})}};const Ga=t=>i.union([i.union([i.null(),i.undefined()]).transform(()=>[]),t.array()]),nd=t=>Array.isArray(t)?t:t==null?[]:[t],Ha=(t,e)=>{if(Array.isArray(e))return e.reduce((s,a)=>Ha(s,a),t??[]);if(t==null)return[e];const n=t.findIndex(s=>s==e),r=[...t];return n===-1?r.push(e):r[n]=e,r},rd=((t,e)=>{if(t!=null)return Array.isArray(e)?t.filter(n=>!e.includes(n)):t.filter(n=>n!=e)}),Wa=(t,e)=>{if(Array.isArray(e))return e.reduce((s,a)=>Wa(s,a),t??[]);if(t==null)return[e];const n=t.findIndex(s=>s.key===e.key),r=[...t];return n===-1?r.push(e):r[n]=e,r},sd=((t,e)=>{if(t!=null)return Array.isArray(e)?t.filter(n=>!e.includes(n.key)):t.filter(n=>n.key!==e)}),S=Object.freeze(Object.defineProperty({__proto__:null,nullableZ:Ga,remove:rd,removeKeyed:sd,toArray:nd,upsert:Ha,upsertKeyed:Wa},Symbol.toStringTag,{value:"Module"})),id=t=>{const e=t.replace(/_[a-z]/g,n=>n[1].toUpperCase());return e.length>1&&e[0]===e[0].toUpperCase()&&e[1]===e[1].toUpperCase()||e.length===0?e:e[0].toLowerCase()+e.slice(1)},Dn=t=>{const e=(n,r=xr)=>{if(typeof n=="string")return t(n);if(Array.isArray(n))return n.map(o=>e(o,r));if(!ur(n))return n;r=cd(r);const s={},a=n;return"toJSON"in a&&typeof a.toJSON=="function"?e(a.toJSON(),r):(Object.keys(a).forEach(o=>{let c=a[o];const l=t(o);r.recursive&&(ur(c)?Ni(c)||(c=e(c,r)):r.recursiveInArray&&Oi(c)&&(c=[...c].map(u=>{let h=u;return ur(u)?Ni(h)||(h=e(u,r)):Oi(u)&&(h=e({key:u},r).key),h}))),s[l]=c}),s)};return e},hs=Dn(id),ad=t=>t.replace(/([a-z0-9])([A-Z])/g,(e,n,r)=>`${n}_${r.toLowerCase()}`),Ka=Dn(ad),Ja=t=>t.length===0?t:t[0].toUpperCase()+t.slice(1),od=[Number,String,Uint8Array],xr={recursive:!0,recursiveInArray:!0},cd=(t=xr)=>(t.recursive==null?t=xr:t.recursiveInArray??=!1,t),Oi=t=>t!=null&&Array.isArray(t),ur=t=>t!=null&&typeof t=="object"&&!Array.isArray(t),Ni=t=>od.some(e=>t instanceof e),ud=t=>t.replace(/[\s_]+/g,"-").replace(/([a-z0-9])([A-Z])/g,(e,n,r)=>`${n}-${r.toLowerCase()}`).toLowerCase(),ld=Dn(ud),hd=t=>{if(t.length===0)return t;let e=t.replace(/[_-]/g," ");return e=e.replace(/([a-z0-9])([A-Z])/g,(n,r,s)=>`${r} ${s}`),e=e.replace(/([A-Z]+)([A-Z][a-z])/g,(n,r,s)=>`${r} ${s}`),e=e.replace(/\s+/g," ").trim(),e=e.replace(/\b\w/g,n=>n.toUpperCase()),e},fd=Dn(hd),dd=Object.freeze(Object.defineProperty({__proto__:null,camelToSnake:Ka,capitalize:Ja,snakeToCamel:hs,toKebab:ld,toProperNoun:fd},Symbol.toStringTag,{value:"Module"})),yd=t=>t!=null&&typeof t=="object"&&!Array.isArray(t);class Xa{contentType="application/json";decoder;encoder;constructor(){this.decoder=new TextDecoder,this.encoder=new TextEncoder}encode(e){return this.encoder.encode(this.encodeString(e))}decode(e,n){return this.decodeString(this.decoder.decode(e),n)}decodeString(e,n){const r=JSON.parse(e),s=hs(r);return n!=null?n.parse(s):s}encodeString(e){const n=Ka(e);return JSON.stringify(n,(r,s)=>ArrayBuffer.isView(s)?Array.from(s):typeof s=="bigint"?s.toString():s)}}class Qa{contentType="text/csv";encode(e){const n=this.encodeString(e);return new TextEncoder().encode(n)}decode(e,n){const r=new TextDecoder().decode(e);return this.decodeString(r,n)}encodeString(e){if(!Array.isArray(e)||e.length===0||!yd(e[0]))throw new Error("Payload must be an array of objects");const n=Object.keys(e[0]),r=[n.join(",")];return e.forEach(s=>{const a=n.map(o=>JSON.stringify(s[o]??""));r.push(a.join(","))}),r.join(`
7
7
  `)}decodeString(e,n){const[r,...s]=e.trim().split(`
8
- `).map(c=>c.trim());if(r.length===0)return n!=null?n.parse({}):{};const a=r.split(",").map(c=>c.trim()),o={};return a.forEach(c=>{o[c]=[]}),s.forEach(c=>{const l=c.split(",").map(u=>u.trim());a.forEach((u,h)=>{const y=this.parseValue(l[h]);y!=null&&o[u].push(y)})}),n!=null?n.parse(o):o}parseValue(e){if(e==null||e.length===0)return null;const n=Number(e);return isNaN(n)?e.startsWith('"')&&e.endsWith('"')?e.slice(1,-1):e:n}}class Wa{contentType="text/plain";encode(e){if(typeof e!="string")throw new Error("TextCodec.encode payload must be a string");return new TextEncoder().encode(e)}decode(e,n){const r=new TextDecoder().decode(e);return n!=null?n.parse(r):r}}const Lt=new Va,od=new Ga,cd=new Wa,ud=[Lt],it=Object.freeze(Object.defineProperty({__proto__:null,CSVCodec:Ga,CSV_CODEC:od,ENCODERS:ud,JSONCodec:Va,JSON_CODEC:Lt,TEXT_CODEC:cd,TextCodec:Wa},Symbol.toStringTag,{value:"Module"})),ne=t=>t!=null&&typeof t=="object"&&"value"in t;class at{value;constructor(e){this.value=e}valueOf(){return this.value}toJSON(){return this.value}toString(){return this.value.toString()}}const ls=t=>t!=null&&typeof t=="object"&&"toString"in t,Ka=t=>{if(ls(t))return 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;default:return!1}},ld=t=>!Ka(t),hd=Object.freeze(Object.defineProperty({__proto__:null,ValueExtension:at,isCrudeValueExtension:ne,isNonZero:ld,isStringer:ls,isZero:Ka},Symbol.toStringTag,{value:"Module"})),Zr=t=>[...new Set(t)],fd=(t,e,n=!0)=>{const r=new Map;return t.forEach(s=>{const a=e(s);if(r.has(a)){if(n)return;r.delete(a)}r.set(a,s)}),Array.from(r.values())},Oi=Object.freeze(Object.defineProperty({__proto__:null,by:fd,unique:Zr},Symbol.toStringTag,{value:"Module"})),Xt=(t,e=!1)=>{const n=ls(t)?"stringer":typeof t;let r;switch(n){case"string":r=(s,a)=>s.localeCompare(a);break;case"stringer":r=(s,a)=>s.toString().localeCompare(a.toString());break;case"number":r=(s,a)=>Number(s)-Number(a);break;case"bigint":r=(s,a)=>BigInt(s)-BigInt(a)>0n?1:-1;break;case"boolean":r=(s,a)=>Number(s)-Number(a);break;case"undefined":r=()=>0;break;default:return console.warn(`sortFunc: unknown type ${n}`),()=>-1}return e?Xa(r):r},dd=(t,e,n)=>{const r=Xt(e[t],n);return(s,a)=>r(s[t],a[t])},yd=(t,e)=>t.length!==e.length?t.length-e.length:t.every((n,r)=>n===e[r])?0:-1,Ja=(t,e)=>{if(t.length!==e.length)return t.length-e.length;if(t.length===0)return 0;const n=Xt(t[0]),r=[...t].sort(n),s=[...e].sort(n);return r.every((a,o)=>a===s[o])?0:-1},pd=(t,e)=>{const n=Zr(t),r=Zr(e);return Ja(n,r)},md=(t,e)=>t===e?0:t==="first"&&e==="last"?1:-1,Xa=t=>(e,n)=>t(n,e),ot=0,Se=-1,ke=1,Qa=t=>t<ot,eo=t=>t>ot,gd=t=>t>=ot,to=t=>t===ot,wd=(t,e)=>{const n=/([a-zA-Z]+)|(\d+)/g,r=t.replace(/[\s_.-]+/g,"").match(n),s=e.replace(/[\s_.-]+/g,"").match(n);if(!r||!s)return 0;for(let a=0;a<Math.min(r.length,s.length);a++){const o=r[a],c=s[a];if(isNaN(Number(o))&&isNaN(Number(c))){const l=o.localeCompare(c);if(l!==0)return l}else if(!isNaN(Number(o))&&!isNaN(Number(c))){const l=Number(o)-Number(c);if(l!==0)return l}else return isNaN(Number(o))?-1:1}return r.length-s.length},no=(t,e,n)=>{let r=0,s=t.length;const a=n??Xt(e);for(;r<s;){const o=Math.floor((r+s)/2),c=a(t[o],e);if(c===0)return o;c<0?r=o+1:s=o}return r},bd=(t,e,n)=>{const r=no(t,e,n);t.splice(r,0,e)},Ei=Object.freeze(Object.defineProperty({__proto__:null,EQUAL:ot,GREATER_THAN:ke,LESS_THAN:Se,insert:bd,isEqualTo:to,isGreaterThan:eo,isGreaterThanEqual:gd,isLessThan:Qa,newF:Xt,newFieldF:dd,order:md,primitiveArrays:yd,reverseF:Xa,search:no,stringsWithNumbers:wd,uniqueUnorderedPrimitiveArrays:pd,unorderedPrimitiveArrays:Ja},Symbol.toStringTag,{value:"Module"}));let ro=(t,e=21)=>(n=e)=>{let r="",s=n|0;for(;s--;)r+=t[Math.random()*t.length|0];return r};const so="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",vd=`0123456789${so}`,io=11,zd=ro(so,1),Td=ro(vd,io-1),hs=()=>`${zd()}${Td()}`,ao=Object.freeze(Object.defineProperty({__proto__:null,LENGTH:io,create:hs},Symbol.toStringTag,{value:"Module"})),Od=(t,e)=>n=>n instanceof e||typeof n=="object"&&n!==null&&"discriminator"in n&&n.discriminator===t,Ed=2**8-1,oo=2**12-1,Nd=2**16-1,Sd=2**32-1,kd=2n**64n-1n,Ad=2**64-1,$d=-128,Id=2**7-1,Zd=-32768,xd=2**15-1,Cd=-2147483648,Rd=2**31-1,_d=-(2n**63n),Sn=2n**63n-1n,Md=-9223372036854776e3,co=2**63-1,At=t=>(e,n)=>{if(typeof e=="bigint"){if(kn(n))return t(e,BigInt(n));const r=t(Number(e),Number(n));return typeof r=="number"?BigInt(Math.round(r)):r}return t(Number(e),Number(n))},Ae=At((t,e)=>t-e),$e=At((t,e)=>t+e),jd=(t,e,n=1e-4)=>Math.abs(t-e)<n,xr=(t,e)=>{const n=typeof t=="bigint",r=typeof e=="bigint";return n&&r?t===e:n&&kn(e)?t===BigInt(e):r&&kn(t)?e===BigInt(t):t===e},Ud=t=>{const e=10**Math.floor(Math.log10(t));return Math.round(t/e)*e},uo=At((t,e)=>t<=e?t:e),kn=t=>typeof t=="bigint"?!0:Number.isInteger(t),Dd=At((t,e)=>t>=e?t:e),lo=t=>typeof t=="bigint"?t<0n?-t:t:t<0?-t:t,le=At((t,e)=>t*e),Qt=At((t,e)=>t/e),ho=i.z.tuple([i.z.number(),i.z.number()]),fo=i.z.object({width:i.z.number(),height:i.z.number()}),Ld=i.z.object({signedWidth:i.z.number(),signedHeight:i.z.number()}),Pd=["start","center","end"],Et=i.z.object({x:i.z.number(),y:i.z.number()}),yo=i.z.object({clientX:i.z.number(),clientY:i.z.number()}),fs=["x","y"],po=i.z.enum(fs),ds=["top","right","bottom","left"],Bd=i.z.enum(ds),mo=["left","right"],ys=i.z.enum(mo),ps=["top","bottom"],ms=i.z.enum(ps),gs=["center"],Cr=i.z.enum(gs),qd=[...ds,...gs],ws=i.z.enum(qd);i.z.enum(Pd);const Fd=["first","last"];i.z.enum(Fd);i.z.object({lower:i.z.number(),upper:i.z.number()});i.z.enum([...po.options,...ws.options]);const Yd=i.z.union([po,ws,i.z.instanceof(String)]),W=(t,e,n)=>{const r={};if(typeof e=="object"&&(n=e,e=void 0),n={makeValid:!0,...n},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 r.lower=t.lower,r.upper=t.upper;return n?.makeValid?Hd(r):r},Hd=t=>t.lower>t.upper?{lower:t.upper,upper:t.lower}:t,Ni=(t,e)=>{const n=W(t);return e<n.lower?n.lower:e>=n.upper?n.upper-(typeof n.upper=="number"?1:1n):e},gn=(t,e)=>{const n=W(t);if(typeof e=="number"||typeof e=="bigint")return e>=n.lower&&e<n.upper;const r=W(e);return r.lower>=n.lower&&r.upper<=n.upper},go=t=>{const e=W(t);return e.upper-e.lower},Vd=t=>({lower:Math.min(...t.map(e=>W(e).lower)),upper:Math.max(...t.map(e=>W(e).upper))}),Gd=(t,e,n)=>{const r=t.map(c=>W(c)),s=n>0?1:n<0?-1:0;if(s===0)return e;let a=n,o=e;for(;xr(a,0)===!1;){const c=r.findIndex(l=>s>0?o>=l.lower&&o<l.upper:o>l.lower&&o<=l.upper);if(c!==-1){const l=r[c];let u;if(s>0?u=Ae(l.upper,o):u=Ae(o,l.lower),u>0){const h=uo(lo(a),u);if(o=$e(o,s>0?h:-h),a=Ae(a,s>0?h:-h),xr(a,0))return o;continue}}if(s>0){const l=r.filter(u=>u.lower>o);if(l.length>0)o=l[0].lower;else return o}else{const l=r.filter(u=>u.upper<o);if(l.length>0)o=l[l.length-1].upper;else return o}}return o},Wd=(t,e,n)=>{const r=t.map(o=>W(o));if(e===n)return typeof e=="bigint"?0n:0;const s=e<n?W([e,n]):W([n,e]);let a=typeof e=="bigint"?0n:0;for(const o of r){const c=o.lower>s.lower?o.lower:s.lower,l=o.upper<s.upper?o.upper:s.upper;if(c<l){const u=l-c;a=a+u}}return a},Rr=2,_r=3,wo=2,Kd=(t,e)=>{if(Number.isNaN(t)||!Number.isFinite(t))return t;const n=go(e);if(n==0)return t;let r;n>=1e3?r=Rr:n>=1?r=_r:r=Math.ceil(-Math.log10(n))+wo;const s=10**r;return Math.round(t*s)/s},Jd=5,Xd=1e-10,Qd=(t,e)=>{if(Number.isNaN(t)||!Number.isFinite(t))return t;const n=Math.abs(t);if(n===0)return 0;let r=!1,s=0;if(e!=null){s=go(e);const c=s/n;r=s>0&&c>Xd}if(r){let c;s>=1e3?c=Rr:s>=1?c=_r:c=Math.ceil(-Math.log10(s))+wo;const l=10**c;return Math.round(t*l)/l}if(n>=1e3){const c=10**Rr;return Math.round(t*c)/c}if(n>=1){const c=10**_r;return Math.round(t*c)/c}const a=Math.floor(Math.log10(n)),o=10**(Jd-a-1);return Math.round(t*o)/o},Mr=Object.freeze(Object.defineProperty({__proto__:null,MAX_INT16:xd,MAX_INT32:Rd,MAX_INT64:Sn,MAX_INT64_NUMBER:co,MAX_INT8:Id,MAX_UINT12:oo,MAX_UINT16:Nd,MAX_UINT32:Sd,MAX_UINT64:kd,MAX_UINT64_NUMBER:Ad,MAX_UINT8:Ed,MIN_INT16:Zd,MIN_INT32:Cd,MIN_INT64:_d,MIN_INT64_NUMBER:Md,MIN_INT8:$d,abs:lo,add:$e,closeTo:jd,div:Qt,equal:xr,isInteger:kn,max:Dd,min:uo,mult:le,roundBySpan:Kd,roundToNearestMagnitude:Ud,smartRound:Qd,sub:Ae},Symbol.toStringTag,{value:"Module"})),ey=t=>fs.includes(t)?t:ps.includes(t)?"y":"x",ty=ys,ny=ms,ry=Cr,sy={top:"bottom",right:"left",bottom:"top",left:"right",center:"center"},iy={top:{clockwise:"left",counterclockwise:"right"},right:{clockwise:"top",counterclockwise:"bottom"},bottom:{clockwise:"right",counterclockwise:"left"},left:{clockwise:"bottom",counterclockwise:"top"}},ay=Yd,tt=t=>t instanceof String||!fs.includes(t)?t:t==="x"?"left":"top",oy=t=>sy[tt(t)],cy=(t,e)=>iy[t][e],Pt=t=>{const e=tt(t);return e==="top"||e==="bottom"?"y":"x"},uy=i.z.object({x:ys.or(Cr),y:ms.or(Cr)}),bs=i.z.object({x:ys,y:ms}),vs=Object.freeze({x:"left",y:"top"}),bo=Object.freeze({x:"right",y:"top"}),vo=Object.freeze({x:"left",y:"bottom"}),zo=Object.freeze({x:"right",y:"bottom"}),zs=Object.freeze({x:"center",y:"center"}),To=Object.freeze({x:"center",y:"top"}),Oo=Object.freeze({x:"center",y:"bottom"}),Eo=Object.freeze({x:"right",y:"center"}),No=Object.freeze({x:"left",y:"center"}),ly=Object.freeze([No,Eo,To,Oo,vs,bo,vo,zo,zs]),So=(t,e)=>t.x===e.x&&t.y===e.y,hy=(t,e)=>{if(typeof e=="object"){let n=!0;return"x"in e&&(t.x===e.x||(n=!1)),"y"in e&&(t.y===e.y||(n=!1)),n}return t.x===e||t.y===e},fy=t=>[t.x,t.y],Nn=t=>Pt(tt(t))==="x",dy=t=>Pt(tt(t))==="y",yy=t=>`${t.x}${Ha(t.y)}`,py=(t,e)=>{let n,r;if(typeof t=="object"&&"x"in t?(n=t.x,r=t.y):(n=tt(t),r=tt(e??t)),Pt(n)===Pt(r)&&n!=="center"&&r!=="center")throw new Error(`[XYLocation] - encountered two locations with the same direction: ${n.toString()} - ${r.toString()}`);const s={...zs};return n==="center"?Nn(r)?[s.x,s.y]=[r,n]:[s.x,s.y]=[n,r]:r==="center"?Nn(n)?[s.x,s.y]=[n,r]:[s.x,s.y]=[r,n]:Nn(n)?[s.x,s.y]=[n,r]:[s.x,s.y]=[r,n],s},my=Object.freeze(Object.defineProperty({__proto__:null,BOTTOM_CENTER:Oo,BOTTOM_LEFT:vo,BOTTOM_RIGHT:zo,CENTER:zs,CENTER_LEFT:No,CENTER_LOCATIONS:gs,CENTER_RIGHT:Eo,OUTER_LOCATIONS:ds,TOP_CENTER:To,TOP_LEFT:vs,TOP_RIGHT:bo,XY_LOCATIONS:ly,X_LOCATIONS:mo,Y_LOCATIONS:ps,center:ry,construct:tt,constructXY:py,corner:bs,crude:ay,direction:Pt,isX:Nn,isY:dy,location:ws,outer:Bd,rotate:cy,swap:oy,x:ty,xy:uy,xyCouple:fy,xyEquals:So,xyMatches:hy,xyToString:yy,y:ny},Symbol.toStringTag,{value:"Module"})),jr=i.z.union([i.z.number(),Et,ho,fo,Ld,yo]),_=(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}},nt=Object.freeze({x:0,y:0}),gy=Object.freeze({x:1,y:1}),wy=Object.freeze({x:1/0,y:1/0}),by=Object.freeze({x:NaN,y:NaN}),ko=(t,e,n=0)=>{const r=_(t),s=_(e);return n===0?r.x===s.x&&r.y===s.y:Math.abs(r.x-s.x)<=n&&Math.abs(r.y-s.y)<=n},vy=t=>ko(t,nt),Ts=(t,e,n)=>{const r=_(t),s=_(e,n);return{x:r.x*s.x,y:r.y*s.y}},Ao=(t,e)=>{const n=_(t);return{x:n.x+e,y:n.y}},$o=(t,e)=>{const n=_(t);return{x:n.x,y:n.y+e}},Io=(t,e,n,...r)=>{if(typeof e=="string"){if(typeof n!="number")throw new Error("The value must be a number.");return e==="x"?Ao(t,n):$o(t,n)}if(typeof e=="object"&&"x"in e&&typeof e.x=="string"){const s=_(n),a=_(t);return e.x==="left"?s.x=-s.x:e.x==="center"&&(s.x=0),e.y==="top"?s.y=-s.y:e.y==="center"&&(s.y=0),{x:a.x+s.x,y:a.y+s.y}}return[t,e,n??nt,...r].reduce((s,a)=>{const o=_(a);return{x:s.x+o.x,y:s.y+o.y}},nt)},zy=(t,e,n)=>{const r=_(t);return ey(e)==="x"?{x:n,y:r.y}:{x:r.x,y:n}},Ty=(t,e)=>{const n=_(t),r=_(e);return Math.sqrt((n.x-r.x)**2+(n.y-r.y)**2)},Oy=(t,e)=>{const n=_(t),r=_(e);return{x:r.x-n.x,y:r.y-n.y}},Ey=t=>{const e=_(t);return Number.isNaN(e.x)||Number.isNaN(e.y)},Ny=t=>{const e=_(t);return Number.isFinite(e.x)&&Number.isFinite(e.y)},Sy=t=>{const e=_(t);return[e.x,e.y]},ky=t=>{const e=_(t);return{left:e.x,top:e.y}},Ay=(t,e=0)=>{const n=_(t);return{x:Number(n.x.toFixed(e)),y:Number(n.y.toFixed(e))}},_t=(t,e)=>{const n=_(t),r=_(e);return{x:n.x-r.x,y:n.y-r.y}},Mt=t=>{const e=_(t),n=Math.hypot(e.x,e.y);return n===0?{x:0,y:0}:{x:-e.y/n,y:e.x/n}},Zo=t=>{const e=_(t),n=Math.hypot(e.x,e.y);return n===0?{x:0,y:0}:{x:e.x/n,y:e.y/n}},xo=(...t)=>{const e=t.reduce((n,r)=>Io(n,r),nt);return Ts(e,1/t.length)},$y=(t,e)=>{const n=[];for(let r=0;r<t.length;r++){const s=t[r];let a,o,c,l;if(r===0){const u=t[r+1],h=_t(u,s);o=Mt(h),c=o,l=e}else if(r===t.length-1){const u=t[r-1],h=_t(s,u);a=Mt(h),c=a,l=e}else{const u=t[r-1],h=t[r+1],y=_t(s,u),f=_t(h,s);a=Mt(y),o=Mt(f);const T=Math.acos((y.x*f.x+y.y*f.y)/(Math.hypot(y.x,y.y)*Math.hypot(f.x,f.y))),S=Math.sin(T/2);S===0?l=e:l=e/S,c=Zo(xo(a,o))}n.push(Ts(c,l))}return n},Iy=t=>{const e=_(t);return{x:e.y,y:e.x}},Zy=t=>{const e=_(t);return{x:Math.round(e.x),y:Math.round(e.y)}},xy=t=>{const e=_(t);return{x:1/e.x,y:1/e.y}},Cy=(t,e,n)=>{const r=_(t),s=_(e),a=n==="clockwise"?Math.PI/2:-Math.PI/2,o=r.x-s.x,c=r.y-s.y,l=o*Math.cos(a)-c*Math.sin(a),u=o*Math.sin(a)+c*Math.cos(a);return{x:l+s.x,y:u+s.y}},Os=Object.freeze(Object.defineProperty({__proto__:null,INFINITY:wy,NAN:by,ONE:gy,ZERO:nt,average:xo,calculateMiters:$y,clientXY:yo,construct:_,couple:Sy,crudeZ:jr,css:ky,distance:Ty,equals:ko,isFinite:Ny,isNan:Ey,isZero:vy,normal:Mt,normalize:Zo,reciprocal:xy,rotate:Cy,round:Zy,scale:Ts,set:zy,sub:_t,swap:Iy,translate:Io,translateX:Ao,translateY:$o,translation:Oy,truncate:Ay,xy:Et},Symbol.toStringTag,{value:"Module"})),wn=i.z.union([i.z.number(),i.z.string()]);i.z.object({top:wn,left:wn,width:wn,height:wn});i.z.object({left:i.z.number(),top:i.z.number(),right:i.z.number(),bottom:i.z.number()});i.z.object({one:Et,two:Et,root:bs});const Es=(t,e,n=0,r=0,s)=>{const a={one:{...nt},two:{...nt},root:s??vs};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+n,y:a.one.y+r},a}return"one"in t&&"two"in t&&"root"in t?{...t,root:s??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+n,y:a.one.y+r}:typeof e=="number"?a.two={x:a.one.x+e,y:a.one.y+n}:"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))},ur=t=>{const e=Es(t);return{lower:e.one.x,upper:e.two.x}},lr=t=>{const e=Es(t);return{lower:e.one.y,upper:e.two.y}},Ry=t=>typeof t!="object"||t==null?!1:"one"in t&&"two"in t&&"root"in t,_y=i.z.object({signedWidth:i.z.number(),signedHeight:i.z.number()});i.z.union([fo,_y,Et,ho]);const My=(t,e,n)=>e!==void 0&&t<e?e:n!==void 0&&t>n?n:t;i.z.object({offset:jr,scale:jr});i.z.object({offset:i.z.number(),scale:i.z.number()});const jy=t=>(e,n,r,s)=>n==="dimension"?[e,r]:[e,s?r-t:r+t],Uy=t=>(e,n,r,s)=>[e,s?r/t:r*t],Dy=t=>(e,n,r)=>{if(e===null)return[t,r];const{lower:s,upper:a}=e,{lower:o,upper:c}=t,l=a-s,u=c-o;if(n==="dimension")return[t,r*(u/l)];const h=(r-s)*(u/l)+o;return[t,h]},Ly=t=>(e,n,r)=>[t,r],Py=()=>(t,e,n)=>{if(t===null)throw new Error("cannot invert without bounds");if(e==="dimension")return[t,n];const{lower:r,upper:s}=t;return[t,s-(n-r)]},By=t=>(e,n,r)=>{const{lower:s,upper:a}=t;return r=My(r,s,a),[e,r]};class Le{ops=[];currBounds=null;currType=null;reversed=!1;constructor(){this.ops=[]}static translate(e){return new Le().translate(e)}static magnify(e){return new Le().magnify(e)}static scale(e,n){return new Le().scale(e,n)}translate(e){const n=this.new(),r=jy(e);return r.type="translate",n.ops.push(r),n}magnify(e){const n=this.new(),r=Uy(e);return r.type="magnify",n.ops.push(r),n}scale(e,n){const r=W(e,n),s=this.new(),a=Dy(r);return a.type="scale",s.ops.push(a),s}clamp(e,n){const r=W(e,n),s=this.new(),a=By(r);return a.type="clamp",s.ops.push(a),s}reBound(e,n){const r=W(e,n),s=this.new(),a=Ly(r);return a.type="re-bound",s.ops.push(a),s}invert(){const e=Py();e.type="invert";const n=this.new();return n.ops.push(e),n}pos(e){return this.exec("position",e)}dim(e){return this.exec("dimension",e)}new(){const e=new Le;return e.ops=this.ops.slice(),e.reversed=this.reversed,e}exec(e,n){return this.currBounds=null,this.ops.reduce(([r,s],a)=>a(r,e,s,this.reversed),[null,n])[1]}reverse(){const e=this.new();e.ops.reverse();const n=[];return e.ops.forEach((r,s)=>{if(r.type==="scale"||n.some(([o,c])=>s>=o&&s<=c))return;const a=e.ops.findIndex((o,c)=>o.type==="scale"&&c>s);a!==-1&&n.push([s,a])}),n.forEach(([r,s])=>{const a=e.ops.slice(r,s);a.unshift(e.ops[s]),e.ops.splice(r,s-r+1,...a)}),e.reversed=!e.reversed,e}get transform(){return{scale:this.dim(1),offset:this.pos(0)}}static IDENTITY=new Le}class we{x;y;currRoot;constructor(e=new Le,n=new Le,r=null){this.x=e,this.y=n,this.currRoot=r}static translate(e,n){return new we().translate(e,n)}static translateX(e){return new we().translateX(e)}static translateY(e){return new we().translateY(e)}static clamp(e){return new we().clamp(e)}static magnify(e){return new we().magnify(e)}static scale(e){return new we().scale(e)}static reBound(e){return new we().reBound(e)}translate(e,n){const r=_(e,n),s=this.copy();return s.x=this.x.translate(r.x),s.y=this.y.translate(r.y),s}translateX(e){const n=this.copy();return n.x=this.x.translate(e),n}translateY(e){const n=this.copy();return n.y=this.y.translate(e),n}magnify(e){const n=this.copy();return n.x=this.x.magnify(e.x),n.y=this.y.magnify(e.y),n}scale(e){const n=this.copy();if(Ry(e)){const r=this.currRoot;return n.currRoot=e.root,r!=null&&!So(r,e.root)&&(r.x!==e.root.x&&(n.x=n.x.invert()),r.y!==e.root.y&&(n.y=n.y.invert())),n.x=n.x.scale(ur(e)),n.y=n.y.scale(lr(e)),n}return n.x=n.x.scale(e.width),n.y=n.y.scale(e.height),n}reBound(e){const n=this.copy();return n.x=this.x.reBound(ur(e)),n.y=this.y.reBound(lr(e)),n}clamp(e){const n=this.copy();return n.x=this.x.clamp(ur(e)),n.y=this.y.clamp(lr(e)),n}copy(){const e=new we;return e.currRoot=this.currRoot,e.x=this.x,e.y=this.y,e}reverse(){const e=this.copy();return e.x=this.x.reverse(),e.y=this.y.reverse(),e}pos(e){return{x:this.x.pos(e.x),y:this.y.pos(e.y)}}dim(e){return{x:this.x.dim(e.x),y:this.y.dim(e.y)}}box(e){return Es(this.pos(e.one),this.pos(e.two),0,0,this.currRoot??e.root)}get transform(){return{scale:this.dim({x:1,y:1}),offset:this.pos({x:0,y:0})}}static IDENTITY=new we}const qy=Et.extend({root:bs,units:i.object({x:i.enum(["px","decimal"]),y:i.enum(["px","decimal"])})});qy.partial({root:!0,units:!0});const Fy=i.z.enum(["static","dynamic"]),Si=365,bn=30,Yy=i.z.union([i.z.tuple([i.z.int()]),i.z.tuple([i.z.int(),i.z.int().min(1).max(12)]),i.z.tuple([i.z.int(),i.z.int().min(1).max(12),i.z.int().min(1).max(31)])]),Co=(t,e)=>{const n=new m(e);if(![g.DAY,g.HOUR,g.MINUTE,g.SECOND,g.MILLISECOND,g.MICROSECOND,g.NANOSECOND].some(s=>s.equals(n)))throw new Error("Invalid argument for remainder. Must be an even TimeSpan or Timestamp");const r=t.valueOf()%n.valueOf();return t instanceof m?new m(r):new g(r)};class m extends at{constructor(e,n="UTC"){if(e==null)super(m.now().valueOf());else if(e instanceof Date)super(BigInt(e.getTime())*m.MILLISECOND.valueOf());else if(typeof e=="string")super(m.parseDateTimeString(e,n).valueOf());else if(Array.isArray(e))super(m.parseDate(e));else{let r=0n;e instanceof Number&&(e=e.valueOf()),n==="local"&&(r=m.utcOffset.valueOf()),typeof e=="number"&&(isFinite(e)?e===co?e=Sn:e=Math.trunc(e):(isNaN(e)&&(e=0),e===1/0?e=m.MAX:e=m.MIN)),ne(e)&&(e=e.value),super(BigInt(e.valueOf())+r)}}static parseDate([e=1970,n=1,r=1]){const s=new Date(e,n-1,r,0,0,0,0);return new m(BigInt(s.getTime())*m.MILLISECOND.valueOf()).truncate(m.DAY).valueOf()}valueOf(){return this.value}static parseTimeString(e,n="UTC"){const[r,s,a]=e.split(":");let o="00",c="00";a!=null&&([o,c]=a.split("."));let l=m.hours(parseInt(r??"00")).add(m.minutes(parseInt(s??"00"))).add(m.seconds(parseInt(o??"00"))).add(m.milliseconds(parseInt(c??"00")));return n==="local"&&(l=l.add(m.utcOffset)),l.valueOf()}static parseDateTimeString(e,n="UTC"){if(!e.includes("/")&&!e.includes("-"))return m.parseTimeString(e,n);if(e.match(/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d{1,3})?$/)!=null){let s=e,a=0;if(e.includes(".")){const u=e.split(".");s=u[0];const h=u[1]||"0";a=parseInt(h.padEnd(3,"0").slice(0,3))}const o=n==="local"?new Date(s.replace("T"," ")):new Date(`${s}Z`),c=BigInt(o.getTime())*m.MILLISECOND.valueOf(),l=BigInt(a)*m.MILLISECOND.valueOf();return c+l}const r=new Date(e);return e.includes(":")||r.setUTCHours(0,0,0,0),new m(BigInt(r.getTime())*m.MILLISECOND.valueOf(),n).valueOf()}toISOString(e="UTC"){return e==="UTC"?this.date().toISOString():this.sub(m.utcOffset).date().toISOString()}timeString(e=!1,n="UTC"){const r=this.toISOString(n);return e?r.slice(11,23):r.slice(11,19)}dateString(){const e=this.date(),n=e.toLocaleString("default",{month:"short"}),r=e.toLocaleString("default",{day:"numeric"});return`${n} ${r}`}static get utcOffset(){return new g(BigInt(new Date().getTimezoneOffset())*m.MINUTE.valueOf())}static since(e){return new m().span(e)}date(){return new Date(this.milliseconds)}equals(e){return this.valueOf()===new m(e).valueOf()}span(e){return this.range(e).span}range(e){return new Z(this,e).makeValid()}spanRange(e){return this.range(this.add(e)).makeValid()}get isZero(){return this.valueOf()===0n}after(e){return this.valueOf()>new m(e).valueOf()}afterEq(e){return this.valueOf()>=new m(e).valueOf()}before(e){return this.valueOf()<new m(e).valueOf()}beforeEq(e){return this.valueOf()<=new m(e).valueOf()}add(e){return new m($e(this.valueOf(),new g(e).valueOf()))}sub(e){return new m(Ae(this.valueOf(),new g(e).valueOf()))}get hours(){return Number(this.valueOf())/Number(g.HOUR.valueOf())}get minutes(){return Number(this.valueOf())/Number(g.MINUTE.valueOf())}get days(){return Number(this.valueOf())/Number(g.DAY.valueOf())}get seconds(){return Number(this.valueOf())/Number(g.SECOND.valueOf())}get milliseconds(){return Number(this.valueOf())/Number(m.MILLISECOND.valueOf())}get microseconds(){return Number(this.valueOf())/Number(m.MICROSECOND.valueOf())}get nanoseconds(){return Number(this.valueOf())}get year(){return this.date().getUTCFullYear()}setYear(e){const n=this.date();return n.setUTCFullYear(e),new m(n)}get month(){return this.date().getUTCMonth()}setMonth(e){const n=this.date();return n.setUTCMonth(e),new m(n)}get day(){return this.date().getUTCDate()}setDay(e){const n=this.date();return n.setUTCDate(e),new m(n)}get hour(){return this.date().getUTCHours()}get localHour(){return this.date().getHours()}setLocalHour(e){const n=this.date();return n.setHours(e),new m(n)}setHour(e){const n=this.date();return n.setUTCHours(e),new m(n)}get minute(){return this.date().getUTCMinutes()}setMinute(e){const n=this.date();return n.setUTCMinutes(e),new m(n)}get second(){return this.date().getUTCSeconds()}setSecond(e){const n=this.date();return n.setUTCSeconds(e),new m(n)}get millisecond(){return this.date().getUTCMilliseconds()}setMillisecond(e){const n=this.date();return n.setUTCMilliseconds(e),new m(n)}toString(e="ISO",n="UTC"){switch(e){case"ISODate":return this.toISOString(n).slice(0,10);case"ISOTime":return this.toISOString(n).slice(11,23);case"time":return this.timeString(!1,n);case"preciseTime":return this.timeString(!0,n);case"date":return this.dateString();case"preciseDate":return`${this.dateString()} ${this.timeString(!0,n)}`;case"dateTime":return`${this.dateString()} ${this.timeString(!1,n)}`;default:return this.toISOString(n)}}remainder(e){return Co(this,e)}get isToday(){return this.truncate(g.DAY).equals(m.now().truncate(g.DAY))}truncate(e){return this.sub(this.remainder(e))}formatBySpan(e){return e.greaterThanOrEqual(g.days(30))?"shortDate":e.greaterThanOrEqual(g.DAY)?"dateTime":e.greaterThanOrEqual(g.HOUR)?"time":e.greaterThanOrEqual(g.SECOND)?"preciseTime":"ISOTime"}static now(){return new m(new Date)}static max(...e){let n=m.MIN;for(const r of e){const s=new m(r);s.after(n)&&(n=s)}return n}static min(...e){let n=m.MAX;for(const r of e){const s=new m(r);s.before(n)&&(n=s)}return n}static nanoseconds(e,n="UTC"){return new m(e,n)}static NANOSECOND=m.nanoseconds(1);static microseconds(e,n="UTC"){return m.nanoseconds(e*1e3,n)}static MICROSECOND=m.microseconds(1);static milliseconds(e,n="UTC"){return m.microseconds(e*1e3,n)}static MILLISECOND=m.milliseconds(1);static seconds(e,n="UTC"){return m.milliseconds(e*1e3,n)}static SECOND=m.seconds(1);static minutes(e,n="UTC"){return m.seconds(e*60,n)}static MINUTE=m.minutes(1);static hours(e,n="UTC"){return m.minutes(e*60,n)}static HOUR=m.hours(1);static days(e,n="UTC"){return m.hours(e*24,n)}static DAY=m.days(1);static MAX=new m(Sn);static MIN=new m(0);static ZERO=new m(0);static z=i.z.union([i.z.instanceof(m),i.z.object({value:i.z.bigint()}).transform(e=>new m(e.value)),i.z.string().transform(e=>new m(BigInt(e))),i.z.number().transform(e=>new m(e)),i.z.bigint().transform(e=>new m(e)),i.z.date().transform(e=>new m(e)),i.z.custom(e=>e instanceof g).transform(e=>new m(e)),Yy.transform(e=>new m(e))]);static sort(e,n){return Number(e.valueOf()-n.valueOf())}}class g extends at{constructor(e){typeof e=="number"&&(e=Math.trunc(e.valueOf())),ne(e)&&(e=e.value),super(BigInt(e.valueOf()))}static fromSeconds(e){return e instanceof g?e:e instanceof F?e.period:e instanceof m?new g(e):(ne(e)&&(e=e.value),["number","bigint"].includes(typeof e)?g.seconds(e):new g(e))}static fromMilliseconds(e){return e instanceof g?e:e instanceof F?e.period:e instanceof m?new g(e):(ne(e)&&(e=e.value),["number","bigint"].includes(typeof e)?g.milliseconds(e):new g(e))}valueOf(){return this.value}lessThan(e){return this.valueOf()<new g(e).valueOf()}greaterThan(e){return this.valueOf()>new g(e).valueOf()}lessThanOrEqual(e){return this.valueOf()<=new g(e).valueOf()}greaterThanOrEqual(e){return this.valueOf()>=new g(e).valueOf()}remainder(e){return Co(this,e)}truncate(e){return new g(BigInt(Math.trunc(Number(this.valueOf()/e.valueOf())))*e.valueOf())}toString(e="full"){if(e==="semantic")return this.toSemanticString();const n=this.truncate(g.DAY),r=this.truncate(g.HOUR),s=this.truncate(g.MINUTE),a=this.truncate(g.SECOND),o=this.truncate(g.MILLISECOND),c=this.truncate(g.MICROSECOND),l=this.truncate(g.NANOSECOND),u=n,h=r.sub(n),y=s.sub(r),f=a.sub(s),T=o.sub(a),S=c.sub(o),x=l.sub(c);let O="";return u.isZero||(O+=`${u.days}d `),h.isZero||(O+=`${h.hours}h `),y.isZero||(O+=`${y.minutes}m `),f.isZero||(O+=`${f.seconds}s `),T.isZero||(O+=`${T.milliseconds}ms `),S.isZero||(O+=`${S.microseconds}µs `),x.isZero||(O+=`${x.nanoseconds}ns`),O.trim()}toSemanticString(){const e=this.valueOf()<0n?-this.valueOf():this.valueOf(),n=new g(e),r=this.valueOf()<0n;if(n.valueOf()===0n)return"0s";if(n.lessThan(g.SECOND))return"< 1s";const s=n.days,a=n.hours,o=n.minutes,c=n.seconds,l=Math.floor(s/Si),u=Math.floor(s/bn),h=Math.floor(s/7),y=Math.floor(s),f=Math.floor(a),T=Math.floor(o),S=Math.floor(c),x=r?"-":"";if(l>=1){let O=`${l}y`;if(l<2){const N=Math.floor(s%Si/bn);N>0&&(O+=` ${N}mo`)}return x+O}if(h>=1&&s<bn&&s%7===0){let O=`${h}w`;const N=Math.floor(s%7),$=Math.floor(a-h*7*24);return h<2&&(N>0?O+=` ${N}d`:$>0&&$<24&&(O+=` ${$}h`)),x+O}if(u>=1){let O=`${u}mo`;if(u<3){const N=Math.floor(s%bn);N>0&&(O+=` ${N}d`)}return x+O}if(h>=1){let O=`${h}w`;const N=Math.floor(s%7),$=Math.floor(a-h*7*24);return h<2&&(N>0?O+=` ${N}d`:$>0&&$<24&&(O+=` ${$}h`)),x+O}if(y>=1){let O=`${y}d`;const N=Math.floor(a-y*24);return y<2&&N>0&&(O+=` ${N}h`),x+O}if(f>=1){let O=`${f}h`;if(f<3){const N=Math.floor(o-f*60);N>0&&(O+=` ${N}m`)}return x+O}if(T>=1){let O=`${T}m`;if(T<5){const N=Math.floor(c-T*60);N>0&&(O+=` ${N}s`)}return x+O}return`${x}${S}s`}mult(e){return new g(le(this.valueOf(),e))}div(e){return new g(Qt(this.valueOf(),e))}get days(){return Number(this.valueOf())/Number(g.DAY.valueOf())}get hours(){return Number(this.valueOf())/Number(g.HOUR.valueOf())}get minutes(){return Number(this.valueOf())/Number(g.MINUTE.valueOf())}get seconds(){return Number(this.valueOf())/Number(g.SECOND.valueOf())}get milliseconds(){return Number(this.valueOf())/Number(g.MILLISECOND.valueOf())}get microseconds(){return Number(this.valueOf())/Number(g.MICROSECOND.valueOf())}get nanoseconds(){return Number(this.valueOf())}get isZero(){return this.valueOf()===0n}equals(e){return this.valueOf()===new g(e).valueOf()}add(e){return new g(this.valueOf()+new g(e).valueOf())}sub(e){return new g(this.valueOf()-new g(e).valueOf())}static nanoseconds(e=1){return new g(e)}static NANOSECOND=g.nanoseconds(1);static microseconds(e=1){return g.nanoseconds(le(e,1e3))}static MICROSECOND=g.microseconds(1);static milliseconds(e=1){return g.microseconds(le(e,1e3))}static MILLISECOND=g.milliseconds(1);static seconds(e=1){return g.milliseconds(le(e,1e3))}static SECOND=g.seconds(1);static minutes(e=1){return g.seconds(le(e,60))}static MINUTE=g.minutes(1);static hours(e){return g.minutes(le(e,60))}static HOUR=g.hours(1);static days(e){return g.hours(le(e,24))}static DAY=g.days(1);static MAX=new g(Sn);static MIN=new g(0);static ZERO=new g(0);static z=i.z.union([i.z.object({value:i.z.bigint()}).transform(e=>new g(e.value)),i.z.string().transform(e=>new g(BigInt(e))),i.z.number().transform(e=>new g(e)),i.z.bigint().transform(e=>new g(e)),i.z.instanceof(g),i.z.instanceof(m).transform(e=>new g(e)),i.z.custom(e=>e instanceof F).transform(e=>new g(e))])}class F extends at{constructor(e){ne(e)&&(e=e.value),super(e.valueOf())}toString(){return`${this.valueOf()} Hz`}equals(e){return this.valueOf()===new F(e).valueOf()}get period(){return g.seconds(1/this.valueOf())}sampleCount(e){return new g(e).seconds*this.valueOf()}byteCount(e,n){return this.sampleCount(e)*new C(n).valueOf()}span(e){return g.seconds(e/this.valueOf())}byteSpan(e,n){return this.span(e.valueOf()/new C(n).valueOf())}add(e){return new F($e(this.valueOf(),new F(e).valueOf()))}sub(e){return new F(Ae(this.valueOf(),new F(e).valueOf()))}mult(e){return new F(le(this.valueOf(),e))}div(e){return new F(Qt(this.valueOf(),e))}static hz(e){return new F(e)}static khz(e){return F.hz(e*1e3)}static z=i.z.union([i.z.number().transform(e=>new F(e)),i.z.instanceof(F)])}class C extends at{constructor(e){ne(e)&&(e=e.value),super(e.valueOf())}length(e){return e.valueOf()/this.valueOf()}size(e){return new A(e*this.valueOf())}add(e){return new C($e(this.valueOf(),new C(e).valueOf()))}sub(e){return new C(Ae(this.valueOf(),new C(e).valueOf()))}mult(e){return new C(le(this.valueOf(),e))}div(e){return new C(Qt(this.valueOf(),e))}static UNKNOWN=new C(0);static BIT128=new C(16);static BIT64=new C(8);static BIT32=new C(4);static BIT16=new C(2);static BIT8=new C(1);static z=i.z.union([i.z.number().transform(e=>new C(e)),i.z.instanceof(C)])}class Z{start;end;constructor(e,n){typeof e=="object"&&"start"in e?(this.start=new m(e.start),this.end=new m(e.end)):(this.start=new m(e),this.end=new m(n))}get span(){return new g(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.start.isZero&&this.end.isZero}get numeric(){return{start:Number(this.start.valueOf()),end:Number(this.end.valueOf())}}swap(){return new Z(this.end,this.start)}get numericBounds(){return{lower:Number(this.start.valueOf()),upper:Number(this.end.valueOf())}}equals(e,n=g.ZERO){if(n.isZero)return this.start.equals(e.start)&&this.end.equals(e.end);let r=this.start.sub(e.start).valueOf(),s=this.end.sub(e.end).valueOf();return r<0&&(r=-r),s<0&&(s=-s),r<=n.valueOf()&&s<=n.valueOf()}toString(){return`${this.start.toString()} - ${this.end.toString()}`}toPrettyString(){return`${this.start.toString("preciseDate")} - ${this.span.toString()}`}overlapsWith(e,n=g.ZERO){e=e.makeValid();const r=this.makeValid();if(this.equals(e))return!0;if(e.end.equals(r.start)||r.end.equals(e.start))return!1;const s=m.max(r.start,e.start),a=m.min(r.end,e.end);return a.before(s)?!1:new g(a.sub(s)).greaterThanOrEqual(n)}contains(e){return e instanceof Z?this.contains(e.start)&&this.contains(e.end):this.start.beforeEq(e)&&this.end.after(e)}boundBy(e){const n=new Z(this.start,this.end);return e.start.after(this.start)&&(n.start=e.start),e.start.after(this.end)&&(n.end=e.start),e.end.before(this.end)&&(n.end=e.end),e.end.before(this.start)&&(n.start=e.end),n}static max(...e){return new Z(m.min(...e.map(n=>n.start)),m.max(...e.map(n=>n.end)))}static MAX=new Z(m.MIN,m.MAX);static ZERO=new Z(m.ZERO,m.ZERO);static z=i.z.union([i.z.object({start:m.z,end:m.z}).transform(e=>new Z(e.start,e.end)),i.z.instanceof(Z)]);static sort(e,n){return m.sort(e.start,n.start)||m.sort(e.end,n.end)}static simplify(e){return e.map(n=>n.makeValid()).sort((n,r)=>Z.sort(n,r)).reduce((n,r)=>{if(r.span.isZero)return n;if(n.length===0)return n.push(r),n;const s=n[n.length-1];return s.overlapsWith(r)||s.end.equals(r.start)?s.end=m.max(s.end,r.end):n.push(r),n},[])}}class d extends at{constructor(e){if(ne(e)&&(e=e.value),e instanceof d||typeof e=="string"||typeof e.valueOf()=="string")super(e.valueOf());else{const n=d.ARRAY_CONSTRUCTOR_DATA_TYPES.get(e.constructor.name);if(n==null)throw new Error(`unable to find data type for ${e.toString()}`);super(n.valueOf())}}get Array(){const e=d.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(n=>this.equals(n))}toString(e=!1){return e?d.SHORT_STRINGS.get(this.valueOf())??this.valueOf():this.valueOf()}get isVariable(){return this.equals(d.JSON)||this.equals(d.STRING)}get isNumeric(){return!this.isVariable&&!this.equals(d.UUID)}get isInteger(){const e=this.toString();return e.startsWith("int")||e.startsWith("uint")}get isFloat(){return this.toString().startsWith("float")}get density(){const e=d.DENSITIES.get(this.toString());if(e==null)throw new Error(`unable to find density for ${this.valueOf()}`);return e}get isUnsignedInteger(){return this.equals(d.UINT8)||this.equals(d.UINT16)||this.equals(d.UINT32)||this.equals(d.UINT64)}get isSignedInteger(){return this.equals(d.INT8)||this.equals(d.INT16)||this.equals(d.INT32)||this.equals(d.INT64)}canSafelyCastTo(e){return this.equals(e)?!0:!this.isNumeric||!e.isNumeric||this.isVariable||e.isVariable||this.isUnsignedInteger&&e.isSignedInteger?!1:this.isFloat?e.isFloat&&this.density.valueOf()<=e.density.valueOf():this.equals(d.INT32)&&e.equals(d.FLOAT64)||this.equals(d.INT8)&&e.equals(d.FLOAT32)?!0:this.isInteger&&e.isInteger?this.density.valueOf()<=e.density.valueOf()&&this.isUnsignedInteger===e.isUnsignedInteger:!1}canCastTo(e){return this.isNumeric&&e.isNumeric?!0:this.equals(e)}checkArray(e){return e.constructor===this.Array}get usesBigInt(){return d.BIG_INT_TYPES.some(e=>e.equals(this))}static UNKNOWN=new d("unknown");static FLOAT64=new d("float64");static FLOAT32=new d("float32");static INT64=new d("int64");static INT32=new d("int32");static INT16=new d("int16");static INT8=new d("int8");static UINT64=new d("uint64");static UINT32=new d("uint32");static UINT16=new d("uint16");static UINT8=new d("uint8");static BOOLEAN=new d("boolean");static TIMESTAMP=new d("timestamp");static UUID=new d("uuid");static STRING=new d("string");static JSON=new d("json");static ARRAY_CONSTRUCTORS=new Map([[d.UINT8.toString(),Uint8Array],[d.UINT16.toString(),Uint16Array],[d.UINT32.toString(),Uint32Array],[d.UINT64.toString(),BigUint64Array],[d.FLOAT32.toString(),Float32Array],[d.FLOAT64.toString(),Float64Array],[d.INT8.toString(),Int8Array],[d.INT16.toString(),Int16Array],[d.INT32.toString(),Int32Array],[d.INT64.toString(),BigInt64Array],[d.TIMESTAMP.toString(),BigInt64Array],[d.STRING.toString(),Uint8Array],[d.JSON.toString(),Uint8Array],[d.UUID.toString(),Uint8Array]]);static ARRAY_CONSTRUCTOR_DATA_TYPES=new Map([[Uint8Array.name,d.UINT8],[Uint16Array.name,d.UINT16],[Uint32Array.name,d.UINT32],[BigUint64Array.name,d.UINT64],[Float32Array.name,d.FLOAT32],[Float64Array.name,d.FLOAT64],[Int8Array.name,d.INT8],[Int16Array.name,d.INT16],[Int32Array.name,d.INT32],[BigInt64Array.name,d.INT64]]);static DENSITIES=new Map([[d.UINT8.toString(),C.BIT8],[d.UINT16.toString(),C.BIT16],[d.UINT32.toString(),C.BIT32],[d.UINT64.toString(),C.BIT64],[d.FLOAT32.toString(),C.BIT32],[d.FLOAT64.toString(),C.BIT64],[d.INT8.toString(),C.BIT8],[d.INT16.toString(),C.BIT16],[d.INT32.toString(),C.BIT32],[d.INT64.toString(),C.BIT64],[d.TIMESTAMP.toString(),C.BIT64],[d.STRING.toString(),C.UNKNOWN],[d.JSON.toString(),C.UNKNOWN],[d.UUID.toString(),C.BIT128]]);static ALL=[d.UNKNOWN,d.FLOAT64,d.FLOAT32,d.INT64,d.INT32,d.INT16,d.INT8,d.UINT64,d.UINT32,d.UINT16,d.UINT8,d.TIMESTAMP,d.UUID,d.STRING,d.JSON];static SHORT_STRINGS=new Map([[d.UINT8.toString(),"u8"],[d.UINT16.toString(),"u16"],[d.UINT32.toString(),"u32"],[d.UINT64.toString(),"u64"],[d.INT8.toString(),"i8"],[d.INT16.toString(),"i16"],[d.INT32.toString(),"i32"],[d.INT64.toString(),"i64"],[d.FLOAT32.toString(),"f32"],[d.FLOAT64.toString(),"f64"],[d.BOOLEAN.toString(),"bool"],[d.TIMESTAMP.toString(),"ts"],[d.UUID.toString(),"uuid"],[d.STRING.toString(),"str"],[d.JSON.toString(),"json"]]);static BIG_INT_TYPES=[d.INT64,d.UINT64,d.TIMESTAMP];static z=i.z.union([i.z.string().transform(e=>new d(e)),i.z.instanceof(d)])}class A extends at{constructor(e){ne(e)&&(e=e.value),super(e.valueOf())}largerThan(e){return ne(e)&&(e=e.value),this.valueOf()>e.valueOf()}smallerThan(e){return ne(e)&&(e=e.value),this.valueOf()<e.valueOf()}add(e){return ne(e)&&(e=e.value),new A($e(this.valueOf(),e.valueOf()))}sub(e){return ne(e)&&(e=e.value),new A(Ae(this.valueOf(),e.valueOf()))}mult(e){return new A(le(this.valueOf(),e))}div(e){return new A(Qt(this.valueOf(),e))}truncate(e){return new A(Math.trunc(this.valueOf()/new A(e).valueOf())*new A(e).valueOf())}remainder(e){return A.bytes(this.valueOf()%new A(e).valueOf())}get gigabytes(){return this.valueOf()/A.GIGABYTE.valueOf()}get megabytes(){return this.valueOf()/A.MEGABYTE.valueOf()}get kilobytes(){return this.valueOf()/A.KILOBYTE.valueOf()}get terabytes(){return this.valueOf()/A.TERABYTE.valueOf()}toString(){const e=this.truncate(A.TERABYTE),n=this.truncate(A.GIGABYTE),r=this.truncate(A.MEGABYTE),s=this.truncate(A.KILOBYTE),a=this.truncate(A.BYTE),o=e,c=n.sub(e),l=r.sub(n),u=s.sub(r),h=a.sub(s);let y="";return o.isZero||(y+=`${o.terabytes}TB `),c.isZero||(y+=`${c.gigabytes}GB `),l.isZero||(y+=`${l.megabytes}MB `),u.isZero||(y+=`${u.kilobytes}KB `),(!h.isZero||y==="")&&(y+=`${h.valueOf()}B`),y.trim()}static bytes(e=1){return new A(e)}static BYTE=new A(1);static kilobytes(e=1){return A.bytes(new A(e).valueOf()*1e3)}static KILOBYTE=A.kilobytes(1);static megabytes(e=1){return A.kilobytes(new A(e).valueOf()*1e3)}static MEGABYTE=A.megabytes(1);static gigabytes(e=1){return A.megabytes(new A(e).valueOf()*1e3)}static GIGABYTE=A.gigabytes(1);static terabytes(e){return A.gigabytes(new A(e).valueOf()*1e3)}static TERABYTE=A.terabytes(1);static ZERO=new A(0);static z=i.z.union([i.z.number().transform(e=>new A(e)),i.z.instanceof(A)]);get isZero(){return this.valueOf()===0}}i.z.object({start:i.z.number(),end:i.z.number()});i.z.union([i.z.instanceof(Uint8Array),i.z.instanceof(Uint16Array),i.z.instanceof(Uint32Array),i.z.instanceof(BigUint64Array),i.z.instanceof(Float32Array),i.z.instanceof(Float64Array),i.z.instanceof(Int8Array),i.z.instanceof(Int16Array),i.z.instanceof(Int32Array),i.z.instanceof(BigInt64Array)]);const Ro=t=>{const e=typeof t;return e==="string"||e==="number"||e==="boolean"||e==="bigint"||t instanceof m||t instanceof g||t instanceof Date},Hy=(t,e,n,r=0)=>t.usesBigInt&&!e.usesBigInt?Number(n)-Number(r):!t.usesBigInt&&e.usesBigInt?BigInt(n.valueOf())-BigInt(r.valueOf()):Ae(n,r),Vy=/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/i;function Gy(t){return typeof t=="string"&&Vy.test(t)}const X=[];for(let t=0;t<256;++t)X.push((t+256).toString(16).slice(1));function Wy(t,e=0){return(X[t[e+0]]+X[t[e+1]]+X[t[e+2]]+X[t[e+3]]+"-"+X[t[e+4]]+X[t[e+5]]+"-"+X[t[e+6]]+X[t[e+7]]+"-"+X[t[e+8]]+X[t[e+9]]+"-"+X[t[e+10]]+X[t[e+11]]+X[t[e+12]]+X[t[e+13]]+X[t[e+14]]+X[t[e+15]]).toLowerCase()}function Ky(t,e=0){const n=Wy(t,e);if(!Gy(n))throw TypeError("Stringified UUID is invalid");return n}typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto);const _o=(t,e)=>Ky(t,e),_e=-1,Ur={[Symbol.iterator]:()=>Ur,next:()=>({done:!0,value:void 0})},Jy=i.z.string().transform(t=>new Uint8Array(atob(t).split("").map(e=>e.charCodeAt(0))).buffer),Xy=i.z.union([i.z.null(),i.z.undefined()]).transform(()=>new Uint8Array().buffer),Dr=10,Mo=(t,e)=>{if(t==="number"&&!e.isNumeric)throw new Error(`cannot convert series of type ${e.toString()} to number`);if(t==="bigint"&&!e.usesBigInt)throw new Error(`cannot convert series of type ${e.toString()} to bigint`)},jo="sy_x_telem_series";class Q{key;discriminator=jo;dataType;sampleOffset;gl;_data;timeRange=Z.ZERO;alignment=0n;alignmentMultiple=1n;cachedMin;cachedMax;writePos=_e;_refCount=0;cachedLength;_cachedIndexes;static crudeZ=i.z.object({timeRange:Z.z.optional(),dataType:d.z,alignment:i.z.coerce.bigint().optional(),data:i.z.union([Jy,Xy,i.z.instanceof(ArrayBuffer),i.z.instanceof(Uint8Array)]),glBufferUsage:Fy.default("static").optional()});static z=Q.crudeZ.transform(e=>new Q(e));constructor(e){Qy(e)&&(e={data:e}),e.data??=[];const{dataType:n,timeRange:r,sampleOffset:s=0,glBufferUsage:a="static",alignment:o=0n,alignmentMultiple:c=1n,key:l=hs(),data:u}=e;if(Uo(u)){const f=u;this.key=f.key,this.dataType=f.dataType,this.sampleOffset=f.sampleOffset,this.gl=f.gl,this._data=f._data,this.timeRange=f.timeRange,this.alignment=f.alignment,this.alignmentMultiple=f.alignmentMultiple,this.cachedMin=f.cachedMin,this.cachedMax=f.cachedMax,this.writePos=f.writePos,this._refCount=f._refCount,this.cachedLength=f.cachedLength;return}const h=Ro(u),y=Array.isArray(u);if(n!=null)this.dataType=new d(n);else{if(u instanceof ArrayBuffer)throw new Error("cannot infer data type from an ArrayBuffer instance when constructing a Series. Please provide a data type.");if(y||h){let f=u;if(!h){if(u.length===0)throw new Error("cannot infer data type from a zero length JS array when constructing a Series. Please provide a data type.");f=u[0]}if(typeof f=="string")this.dataType=d.STRING;else if(typeof f=="number")this.dataType=d.FLOAT64;else if(typeof f=="bigint")this.dataType=d.INT64;else if(typeof f=="boolean")this.dataType=d.BOOLEAN;else if(f instanceof m||f instanceof Date||f instanceof m)this.dataType=d.TIMESTAMP;else if(typeof f=="object")this.dataType=d.JSON;else throw new Error(`cannot infer data type of ${typeof f} when constructing a Series from a JS array`)}else this.dataType=new d(u)}if(!y&&!h)this._data=u;else if(y&&u.length===0)this._data=new this.dataType.Array([]).buffer;else{let f=h?[u]:u;const T=f[0];(T instanceof m||T instanceof Date||T instanceof g)&&(f=f.map(S=>new m(S).valueOf())),this.dataType.equals(d.STRING)?(this.cachedLength=f.length,this._data=new TextEncoder().encode(`${f.join(`
8
+ `).map(c=>c.trim());if(r.length===0)return n!=null?n.parse({}):{};const a=r.split(",").map(c=>c.trim()),o={};return a.forEach(c=>{o[c]=[]}),s.forEach(c=>{const l=c.split(",").map(u=>u.trim());a.forEach((u,h)=>{const d=this.parseValue(l[h]);d!=null&&o[u].push(d)})}),n!=null?n.parse(o):o}parseValue(e){if(e==null||e.length===0)return null;const n=Number(e);return isNaN(n)?e.startsWith('"')&&e.endsWith('"')?e.slice(1,-1):e:n}}class eo{contentType="text/plain";encode(e){if(typeof e!="string")throw new Error("TextCodec.encode payload must be a string");return new TextEncoder().encode(e)}decode(e,n){const r=new TextDecoder().decode(e);return n!=null?n.parse(r):r}}const Bt=new Xa,pd=new Qa,md=new eo,gd=[Bt],ct=Object.freeze(Object.defineProperty({__proto__:null,CSVCodec:Qa,CSV_CODEC:pd,ENCODERS:gd,JSONCodec:Xa,JSON_CODEC:Bt,TEXT_CODEC:md,TextCodec:eo},Symbol.toStringTag,{value:"Module"})),se=t=>t!=null&&typeof t=="object"&&"value"in t;class ut{value;constructor(e){this.value=e}valueOf(){return this.value}toJSON(){return this.value}toString(){return this.value.toString()}}const fs=t=>t!=null&&typeof t=="object"&&"toString"in t,to=t=>{if(fs(t))return 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;default:return!1}},wd=t=>!to(t),bd=Object.freeze(Object.defineProperty({__proto__:null,ValueExtension:ut,isCrudeValueExtension:se,isNonZero:wd,isStringer:fs,isZero:to},Symbol.toStringTag,{value:"Module"})),Cr=t=>[...new Set(t)],vd=(t,e,n=!0)=>{const r=new Map;return t.forEach(s=>{const a=e(s);if(r.has(a)){if(n)return;r.delete(a)}r.set(a,s)}),Array.from(r.values())},Si=Object.freeze(Object.defineProperty({__proto__:null,by:vd,unique:Cr},Symbol.toStringTag,{value:"Module"})),en=(t,e=!1)=>{const n=fs(t)?"stringer":typeof t;let r;switch(n){case"string":r=(s,a)=>s.localeCompare(a);break;case"stringer":r=(s,a)=>s.toString().localeCompare(a.toString());break;case"number":r=(s,a)=>Number(s)-Number(a);break;case"bigint":r=(s,a)=>BigInt(s)-BigInt(a)>0n?1:-1;break;case"boolean":r=(s,a)=>Number(s)-Number(a);break;case"undefined":r=()=>0;break;default:return console.warn(`sortFunc: unknown type ${n}`),()=>-1}return e?ro(r):r},zd=(t,e,n)=>{const r=en(e[t],n);return(s,a)=>r(s[t],a[t])},Td=(t,e)=>t.length!==e.length?t.length-e.length:t.every((n,r)=>n===e[r])?0:-1,no=(t,e)=>{if(t.length!==e.length)return t.length-e.length;if(t.length===0)return 0;const n=en(t[0]),r=[...t].sort(n),s=[...e].sort(n);return r.every((a,o)=>a===s[o])?0:-1},Od=(t,e)=>{const n=Cr(t),r=Cr(e);return no(n,r)},Nd=(t,e)=>t===e?0:t==="first"&&e==="last"?1:-1,ro=t=>(e,n)=>t(n,e),lt=0,Ie=-1,Ze=1,so=t=>t<lt,io=t=>t>lt,Sd=t=>t>=lt,ao=t=>t===lt,Ed=(t,e)=>{const n=/([a-zA-Z]+)|(\d+)/g,r=t.replace(/[\s_.-]+/g,"").match(n),s=e.replace(/[\s_.-]+/g,"").match(n);if(!r||!s)return 0;for(let a=0;a<Math.min(r.length,s.length);a++){const o=r[a],c=s[a];if(isNaN(Number(o))&&isNaN(Number(c))){const l=o.localeCompare(c);if(l!==0)return l}else if(!isNaN(Number(o))&&!isNaN(Number(c))){const l=Number(o)-Number(c);if(l!==0)return l}else return isNaN(Number(o))?-1:1}return r.length-s.length},oo=(t,e,n)=>{let r=0,s=t.length;const a=n??en(e);for(;r<s;){const o=Math.floor((r+s)/2),c=a(t[o],e);if(c===0)return o;c<0?r=o+1:s=o}return r},kd=(t,e,n)=>{const r=oo(t,e,n);t.splice(r,0,e)},Ei=Object.freeze(Object.defineProperty({__proto__:null,EQUAL:lt,GREATER_THAN:Ze,LESS_THAN:Ie,insert:kd,isEqualTo:ao,isGreaterThan:io,isGreaterThanEqual:Sd,isLessThan:so,newF:en,newFieldF:zd,order:Nd,primitiveArrays:Td,reverseF:ro,search:oo,stringsWithNumbers:Ed,uniqueUnorderedPrimitiveArrays:Od,unorderedPrimitiveArrays:no},Symbol.toStringTag,{value:"Module"}));let co=(t,e=21)=>(n=e)=>{let r="",s=n|0;for(;s--;)r+=t[Math.random()*t.length|0];return r};const uo="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",Ad=`0123456789${uo}`,lo=11,$d=co(uo,1),Id=co(Ad,lo-1),ds=()=>`${$d()}${Id()}`,ho=Object.freeze(Object.defineProperty({__proto__:null,LENGTH:lo,create:ds},Symbol.toStringTag,{value:"Module"})),Zd=(t,e)=>n=>n instanceof e||typeof n=="object"&&n!==null&&"discriminator"in n&&n.discriminator===t,xd=2**8-1,fo=2**12-1,Cd=2**16-1,Rd=2**32-1,_d=2n**64n-1n,Md=2**64-1,jd=-128,Ud=2**7-1,Dd=-32768,Pd=2**15-1,Ld=-2147483648,Bd=2**31-1,qd=-(2n**63n),An=2n**63n-1n,Fd=-9223372036854776e3,yo=2**63-1,It=t=>(e,n)=>{if(typeof e=="bigint"){if($n(n))return t(e,BigInt(n));const r=t(Number(e),Number(n));return typeof r=="number"?BigInt(Math.round(r)):r}return t(Number(e),Number(n))},xe=It((t,e)=>t-e),Ce=It((t,e)=>t+e),Yd=(t,e,n=1e-4)=>Math.abs(t-e)<n,Rr=(t,e)=>{const n=typeof t=="bigint",r=typeof e=="bigint";return n&&r?t===e:n&&$n(e)?t===BigInt(e):r&&$n(t)?e===BigInt(t):t===e},Vd=t=>{const e=10**Math.floor(Math.log10(t));return Math.round(t/e)*e},po=It((t,e)=>t<=e?t:e),$n=t=>typeof t=="bigint"?!0:Number.isInteger(t),Gd=It((t,e)=>t>=e?t:e),mo=t=>typeof t=="bigint"?t<0n?-t:t:t<0?-t:t,pe=It((t,e)=>t*e),tn=It((t,e)=>t/e),go=i.z.tuple([i.z.number(),i.z.number()]),wo=i.z.object({width:i.z.number(),height:i.z.number()}),Hd=i.z.object({signedWidth:i.z.number(),signedHeight:i.z.number()}),Wd=["start","center","end"],Et=i.z.object({x:i.z.number(),y:i.z.number()}),bo=i.z.object({clientX:i.z.number(),clientY:i.z.number()}),ys=["x","y"],vo=i.z.enum(ys),ps=["top","right","bottom","left"],Kd=i.z.enum(ps),zo=["left","right"],ms=i.z.enum(zo),gs=["top","bottom"],ws=i.z.enum(gs),bs=["center"],_r=i.z.enum(bs),Jd=[...ps,...bs],vs=i.z.enum(Jd);i.z.enum(Wd);const Xd=["first","last"];i.z.enum(Xd);i.z.object({lower:i.z.number(),upper:i.z.number()});i.z.enum([...vo.options,...vs.options]);const Qd=i.z.union([vo,vs,i.z.instanceof(String)]),W=(t,e,n)=>{const r={};if(typeof e=="object"&&(n=e,e=void 0),n={makeValid:!0,...n},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 r.lower=t.lower,r.upper=t.upper;return n?.makeValid?ey(r):r},ey=t=>t.lower>t.upper?{lower:t.upper,upper:t.lower}:t,ki=(t,e)=>{const n=W(t);return e<n.lower?n.lower:e>=n.upper?n.upper-(typeof n.upper=="number"?1:1n):e},bn=(t,e)=>{const n=W(t);if(typeof e=="number"||typeof e=="bigint")return e>=n.lower&&e<n.upper;const r=W(e);return r.lower>=n.lower&&r.upper<=n.upper},To=t=>{const e=W(t);return e.upper-e.lower},ty=t=>({lower:Math.min(...t.map(e=>W(e).lower)),upper:Math.max(...t.map(e=>W(e).upper))}),ny=(t,e,n)=>{const r=t.map(c=>W(c)),s=n>0?1:n<0?-1:0;if(s===0)return e;let a=n,o=e;for(;Rr(a,0)===!1;){const c=r.findIndex(l=>s>0?o>=l.lower&&o<l.upper:o>l.lower&&o<=l.upper);if(c!==-1){const l=r[c];let u;if(s>0?u=xe(l.upper,o):u=xe(o,l.lower),u>0){const h=po(mo(a),u);if(o=Ce(o,s>0?h:-h),a=xe(a,s>0?h:-h),Rr(a,0))return o;continue}}if(s>0){const l=r.filter(u=>u.lower>o);if(l.length>0)o=l[0].lower;else return o}else{const l=r.filter(u=>u.upper<o);if(l.length>0)o=l[l.length-1].upper;else return o}}return o},ry=(t,e,n)=>{const r=t.map(o=>W(o));if(e===n)return typeof e=="bigint"?0n:0;const s=e<n?W([e,n]):W([n,e]);let a=typeof e=="bigint"?0n:0;for(const o of r){const c=o.lower>s.lower?o.lower:s.lower,l=o.upper<s.upper?o.upper:s.upper;if(c<l){const u=l-c;a=a+u}}return a},Mr=2,jr=3,Oo=2,sy=(t,e)=>{if(Number.isNaN(t)||!Number.isFinite(t))return t;const n=To(e);if(n==0)return t;let r;n>=1e3?r=Mr:n>=1?r=jr:r=Math.ceil(-Math.log10(n))+Oo;const s=10**r;return Math.round(t*s)/s},iy=5,ay=1e-10,oy=(t,e)=>{if(Number.isNaN(t)||!Number.isFinite(t))return t;const n=Math.abs(t);if(n===0)return 0;let r=!1,s=0;if(e!=null){s=To(e);const c=s/n;r=s>0&&c>ay}if(r){let c;s>=1e3?c=Mr:s>=1?c=jr:c=Math.ceil(-Math.log10(s))+Oo;const l=10**c;return Math.round(t*l)/l}if(n>=1e3){const c=10**Mr;return Math.round(t*c)/c}if(n>=1){const c=10**jr;return Math.round(t*c)/c}const a=Math.floor(Math.log10(n)),o=10**(iy-a-1);return Math.round(t*o)/o},Ur=Object.freeze(Object.defineProperty({__proto__:null,MAX_INT16:Pd,MAX_INT32:Bd,MAX_INT64:An,MAX_INT64_NUMBER:yo,MAX_INT8:Ud,MAX_UINT12:fo,MAX_UINT16:Cd,MAX_UINT32:Rd,MAX_UINT64:_d,MAX_UINT64_NUMBER:Md,MAX_UINT8:xd,MIN_INT16:Dd,MIN_INT32:Ld,MIN_INT64:qd,MIN_INT64_NUMBER:Fd,MIN_INT8:jd,abs:mo,add:Ce,closeTo:Yd,div:tn,equal:Rr,isInteger:$n,max:Gd,min:po,mult:pe,roundBySpan:sy,roundToNearestMagnitude:Vd,smartRound:oy,sub:xe},Symbol.toStringTag,{value:"Module"})),cy=t=>ys.includes(t)?t:gs.includes(t)?"y":"x",uy=ms,ly=ws,hy=_r,fy={top:"bottom",right:"left",bottom:"top",left:"right",center:"center"},dy={top:{clockwise:"left",counterclockwise:"right"},right:{clockwise:"top",counterclockwise:"bottom"},bottom:{clockwise:"right",counterclockwise:"left"},left:{clockwise:"bottom",counterclockwise:"top"}},yy=Qd,st=t=>t instanceof String||!ys.includes(t)?t:t==="x"?"left":"top",py=t=>fy[st(t)],my=(t,e)=>dy[t][e],qt=t=>{const e=st(t);return e==="top"||e==="bottom"?"y":"x"},gy=i.z.object({x:ms.or(_r),y:ws.or(_r)}),zs=i.z.object({x:ms,y:ws}),Ts=Object.freeze({x:"left",y:"top"}),No=Object.freeze({x:"right",y:"top"}),So=Object.freeze({x:"left",y:"bottom"}),Eo=Object.freeze({x:"right",y:"bottom"}),Os=Object.freeze({x:"center",y:"center"}),ko=Object.freeze({x:"center",y:"top"}),Ao=Object.freeze({x:"center",y:"bottom"}),$o=Object.freeze({x:"right",y:"center"}),Io=Object.freeze({x:"left",y:"center"}),wy=Object.freeze([Io,$o,ko,Ao,Ts,No,So,Eo,Os]),Zo=(t,e)=>t.x===e.x&&t.y===e.y,by=(t,e)=>{if(typeof e=="object"){let n=!0;return"x"in e&&(t.x===e.x||(n=!1)),"y"in e&&(t.y===e.y||(n=!1)),n}return t.x===e||t.y===e},vy=t=>[t.x,t.y],kn=t=>qt(st(t))==="x",zy=t=>qt(st(t))==="y",Ty=t=>`${t.x}${Ja(t.y)}`,Oy=(t,e)=>{let n,r;if(typeof t=="object"&&"x"in t?(n=t.x,r=t.y):(n=st(t),r=st(e??t)),qt(n)===qt(r)&&n!=="center"&&r!=="center")throw new Error(`[XYLocation] - encountered two locations with the same direction: ${n.toString()} - ${r.toString()}`);const s={...Os};return n==="center"?kn(r)?[s.x,s.y]=[r,n]:[s.x,s.y]=[n,r]:r==="center"?kn(n)?[s.x,s.y]=[n,r]:[s.x,s.y]=[r,n]:kn(n)?[s.x,s.y]=[n,r]:[s.x,s.y]=[r,n],s},Ny=Object.freeze(Object.defineProperty({__proto__:null,BOTTOM_CENTER:Ao,BOTTOM_LEFT:So,BOTTOM_RIGHT:Eo,CENTER:Os,CENTER_LEFT:Io,CENTER_LOCATIONS:bs,CENTER_RIGHT:$o,OUTER_LOCATIONS:ps,TOP_CENTER:ko,TOP_LEFT:Ts,TOP_RIGHT:No,XY_LOCATIONS:wy,X_LOCATIONS:zo,Y_LOCATIONS:gs,center:hy,construct:st,constructXY:Oy,corner:zs,crude:yy,direction:qt,isX:kn,isY:zy,location:vs,outer:Kd,rotate:my,swap:py,x:uy,xy:gy,xyCouple:vy,xyEquals:Zo,xyMatches:by,xyToString:Ty,y:ly},Symbol.toStringTag,{value:"Module"})),Dr=i.z.union([i.z.number(),Et,go,wo,Hd,bo]),_=(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}},it=Object.freeze({x:0,y:0}),Sy=Object.freeze({x:1,y:1}),Ey=Object.freeze({x:1/0,y:1/0}),ky=Object.freeze({x:NaN,y:NaN}),xo=(t,e,n=0)=>{const r=_(t),s=_(e);return n===0?r.x===s.x&&r.y===s.y:Math.abs(r.x-s.x)<=n&&Math.abs(r.y-s.y)<=n},Ay=t=>xo(t,it),Ns=(t,e,n)=>{const r=_(t),s=_(e,n);return{x:r.x*s.x,y:r.y*s.y}},Co=(t,e)=>{const n=_(t);return{x:n.x+e,y:n.y}},Ro=(t,e)=>{const n=_(t);return{x:n.x,y:n.y+e}},_o=(t,e,n,...r)=>{if(typeof e=="string"){if(typeof n!="number")throw new Error("The value must be a number.");return e==="x"?Co(t,n):Ro(t,n)}if(typeof e=="object"&&"x"in e&&typeof e.x=="string"){const s=_(n),a=_(t);return e.x==="left"?s.x=-s.x:e.x==="center"&&(s.x=0),e.y==="top"?s.y=-s.y:e.y==="center"&&(s.y=0),{x:a.x+s.x,y:a.y+s.y}}return[t,e,n??it,...r].reduce((s,a)=>{const o=_(a);return{x:s.x+o.x,y:s.y+o.y}},it)},$y=(t,e,n)=>{const r=_(t);return cy(e)==="x"?{x:n,y:r.y}:{x:r.x,y:n}},Iy=(t,e)=>{const n=_(t),r=_(e);return Math.sqrt((n.x-r.x)**2+(n.y-r.y)**2)},Zy=(t,e)=>{const n=_(t),r=_(e);return{x:r.x-n.x,y:r.y-n.y}},xy=t=>{const e=_(t);return Number.isNaN(e.x)||Number.isNaN(e.y)},Cy=t=>{const e=_(t);return Number.isFinite(e.x)&&Number.isFinite(e.y)},Ry=t=>{const e=_(t);return[e.x,e.y]},_y=t=>{const e=_(t);return{left:e.x,top:e.y}},My=(t,e=0)=>{const n=_(t);return{x:Number(n.x.toFixed(e)),y:Number(n.y.toFixed(e))}},jt=(t,e)=>{const n=_(t),r=_(e);return{x:n.x-r.x,y:n.y-r.y}},Ut=t=>{const e=_(t),n=Math.hypot(e.x,e.y);return n===0?{x:0,y:0}:{x:-e.y/n,y:e.x/n}},Mo=t=>{const e=_(t),n=Math.hypot(e.x,e.y);return n===0?{x:0,y:0}:{x:e.x/n,y:e.y/n}},jo=(...t)=>{const e=t.reduce((n,r)=>_o(n,r),it);return Ns(e,1/t.length)},jy=(t,e)=>{const n=[];for(let r=0;r<t.length;r++){const s=t[r];let a,o,c,l;if(r===0){const u=t[r+1],h=jt(u,s);o=Ut(h),c=o,l=e}else if(r===t.length-1){const u=t[r-1],h=jt(s,u);a=Ut(h),c=a,l=e}else{const u=t[r-1],h=t[r+1],d=jt(s,u),f=jt(h,s);a=Ut(d),o=Ut(f);const O=Math.acos((d.x*f.x+d.y*f.y)/(Math.hypot(d.x,d.y)*Math.hypot(f.x,f.y))),E=Math.sin(O/2);E===0?l=e:l=e/E,c=Mo(jo(a,o))}n.push(Ns(c,l))}return n},Uy=t=>{const e=_(t);return{x:e.y,y:e.x}},Dy=t=>{const e=_(t);return{x:Math.round(e.x),y:Math.round(e.y)}},Py=t=>{const e=_(t);return{x:1/e.x,y:1/e.y}},Ly=(t,e,n)=>{const r=_(t),s=_(e),a=n==="clockwise"?Math.PI/2:-Math.PI/2,o=r.x-s.x,c=r.y-s.y,l=o*Math.cos(a)-c*Math.sin(a),u=o*Math.sin(a)+c*Math.cos(a);return{x:l+s.x,y:u+s.y}},Ss=Object.freeze(Object.defineProperty({__proto__:null,INFINITY:Ey,NAN:ky,ONE:Sy,ZERO:it,average:jo,calculateMiters:jy,clientXY:bo,construct:_,couple:Ry,crudeZ:Dr,css:_y,distance:Iy,equals:xo,isFinite:Cy,isNan:xy,isZero:Ay,normal:Ut,normalize:Mo,reciprocal:Py,rotate:Ly,round:Dy,scale:Ns,set:$y,sub:jt,swap:Uy,translate:_o,translateX:Co,translateY:Ro,translation:Zy,truncate:My,xy:Et},Symbol.toStringTag,{value:"Module"})),vn=i.z.union([i.z.number(),i.z.string()]);i.z.object({top:vn,left:vn,width:vn,height:vn});i.z.object({left:i.z.number(),top:i.z.number(),right:i.z.number(),bottom:i.z.number()});i.z.object({one:Et,two:Et,root:zs});const Es=(t,e,n=0,r=0,s)=>{const a={one:{...it},two:{...it},root:s??Ts};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+n,y:a.one.y+r},a}return"one"in t&&"two"in t&&"root"in t?{...t,root:s??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+n,y:a.one.y+r}:typeof e=="number"?a.two={x:a.one.x+e,y:a.one.y+n}:"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))},lr=t=>{const e=Es(t);return{lower:e.one.x,upper:e.two.x}},hr=t=>{const e=Es(t);return{lower:e.one.y,upper:e.two.y}},By=t=>typeof t!="object"||t==null?!1:"one"in t&&"two"in t&&"root"in t,qy=i.z.object({signedWidth:i.z.number(),signedHeight:i.z.number()});i.z.union([wo,qy,Et,go]);const Fy=(t,e,n)=>e!==void 0&&t<e?e:n!==void 0&&t>n?n:t;i.z.object({offset:Dr,scale:Dr});i.z.object({offset:i.z.number(),scale:i.z.number()});const Yy=t=>(e,n,r,s)=>n==="dimension"?[e,r]:[e,s?r-t:r+t],Vy=t=>(e,n,r,s)=>[e,s?r/t:r*t],Gy=t=>(e,n,r)=>{if(e===null)return[t,r];const{lower:s,upper:a}=e,{lower:o,upper:c}=t,l=a-s,u=c-o;if(n==="dimension")return[t,r*(u/l)];const h=(r-s)*(u/l)+o;return[t,h]},Hy=t=>(e,n,r)=>[t,r],Wy=()=>(t,e,n)=>{if(t===null)throw new Error("cannot invert without bounds");if(e==="dimension")return[t,n];const{lower:r,upper:s}=t;return[t,s-(n-r)]},Ky=t=>(e,n,r)=>{const{lower:s,upper:a}=t;return r=Fy(r,s,a),[e,r]};class Fe{ops=[];currBounds=null;currType=null;reversed=!1;constructor(){this.ops=[]}static translate(e){return new Fe().translate(e)}static magnify(e){return new Fe().magnify(e)}static scale(e,n){return new Fe().scale(e,n)}translate(e){const n=this.new(),r=Yy(e);return r.type="translate",n.ops.push(r),n}magnify(e){const n=this.new(),r=Vy(e);return r.type="magnify",n.ops.push(r),n}scale(e,n){const r=W(e,n),s=this.new(),a=Gy(r);return a.type="scale",s.ops.push(a),s}clamp(e,n){const r=W(e,n),s=this.new(),a=Ky(r);return a.type="clamp",s.ops.push(a),s}reBound(e,n){const r=W(e,n),s=this.new(),a=Hy(r);return a.type="re-bound",s.ops.push(a),s}invert(){const e=Wy();e.type="invert";const n=this.new();return n.ops.push(e),n}pos(e){return this.exec("position",e)}dim(e){return this.exec("dimension",e)}new(){const e=new Fe;return e.ops=this.ops.slice(),e.reversed=this.reversed,e}exec(e,n){return this.currBounds=null,this.ops.reduce(([r,s],a)=>a(r,e,s,this.reversed),[null,n])[1]}reverse(){const e=this.new();e.ops.reverse();const n=[];return e.ops.forEach((r,s)=>{if(r.type==="scale"||n.some(([o,c])=>s>=o&&s<=c))return;const a=e.ops.findIndex((o,c)=>o.type==="scale"&&c>s);a!==-1&&n.push([s,a])}),n.forEach(([r,s])=>{const a=e.ops.slice(r,s);a.unshift(e.ops[s]),e.ops.splice(r,s-r+1,...a)}),e.reversed=!e.reversed,e}get transform(){return{scale:this.dim(1),offset:this.pos(0)}}static IDENTITY=new Fe}class Te{x;y;currRoot;constructor(e=new Fe,n=new Fe,r=null){this.x=e,this.y=n,this.currRoot=r}static translate(e,n){return new Te().translate(e,n)}static translateX(e){return new Te().translateX(e)}static translateY(e){return new Te().translateY(e)}static clamp(e){return new Te().clamp(e)}static magnify(e){return new Te().magnify(e)}static scale(e){return new Te().scale(e)}static reBound(e){return new Te().reBound(e)}translate(e,n){const r=_(e,n),s=this.copy();return s.x=this.x.translate(r.x),s.y=this.y.translate(r.y),s}translateX(e){const n=this.copy();return n.x=this.x.translate(e),n}translateY(e){const n=this.copy();return n.y=this.y.translate(e),n}magnify(e){const n=this.copy();return n.x=this.x.magnify(e.x),n.y=this.y.magnify(e.y),n}scale(e){const n=this.copy();if(By(e)){const r=this.currRoot;return n.currRoot=e.root,r!=null&&!Zo(r,e.root)&&(r.x!==e.root.x&&(n.x=n.x.invert()),r.y!==e.root.y&&(n.y=n.y.invert())),n.x=n.x.scale(lr(e)),n.y=n.y.scale(hr(e)),n}return n.x=n.x.scale(e.width),n.y=n.y.scale(e.height),n}reBound(e){const n=this.copy();return n.x=this.x.reBound(lr(e)),n.y=this.y.reBound(hr(e)),n}clamp(e){const n=this.copy();return n.x=this.x.clamp(lr(e)),n.y=this.y.clamp(hr(e)),n}copy(){const e=new Te;return e.currRoot=this.currRoot,e.x=this.x,e.y=this.y,e}reverse(){const e=this.copy();return e.x=this.x.reverse(),e.y=this.y.reverse(),e}pos(e){return{x:this.x.pos(e.x),y:this.y.pos(e.y)}}dim(e){return{x:this.x.dim(e.x),y:this.y.dim(e.y)}}box(e){return Es(this.pos(e.one),this.pos(e.two),0,0,this.currRoot??e.root)}get transform(){return{scale:this.dim({x:1,y:1}),offset:this.pos({x:0,y:0})}}static IDENTITY=new Te}const Jy=Et.extend({root:zs,units:i.object({x:i.enum(["px","decimal"]),y:i.enum(["px","decimal"])})});Jy.partial({root:!0,units:!0});const Xy=i.z.enum(["static","dynamic"]),Ai=365,zn=30,Qy=i.z.union([i.z.tuple([i.z.int()]),i.z.tuple([i.z.int(),i.z.int().min(1).max(12)]),i.z.tuple([i.z.int(),i.z.int().min(1).max(12),i.z.int().min(1).max(31)])]),Uo=(t,e)=>{const n=new g(e);if(![m.DAY,m.HOUR,m.MINUTE,m.SECOND,m.MILLISECOND,m.MICROSECOND,m.NANOSECOND].some(s=>s.equals(n)))throw new Error("Invalid argument for remainder. Must be an even TimeSpan or Timestamp");const r=t.valueOf()%n.valueOf();return t instanceof g?new g(r):new m(r)};class g extends ut{constructor(e,n="UTC"){if(e==null)super(g.now().valueOf());else if(e instanceof Date)super(BigInt(e.getTime())*g.MILLISECOND.valueOf());else if(typeof e=="string")super(g.parseDateTimeString(e,n).valueOf());else if(Array.isArray(e))super(g.parseDate(e));else{let r=0n;e instanceof Number&&(e=e.valueOf()),n==="local"&&(r=g.utcOffset.valueOf()),typeof e=="number"&&(isFinite(e)?e===yo?e=An:e=Math.trunc(e):(isNaN(e)&&(e=0),e===1/0?e=g.MAX:e=g.MIN)),se(e)&&(e=e.value),super(BigInt(e.valueOf())+r)}}static parseDate([e=1970,n=1,r=1]){const s=new Date(e,n-1,r,0,0,0,0);return new g(BigInt(s.getTime())*g.MILLISECOND.valueOf()).truncate(g.DAY).valueOf()}valueOf(){return this.value}static parseTimeString(e,n="UTC"){const[r,s,a]=e.split(":");let o="00",c="00";a!=null&&([o,c]=a.split("."));let l=g.hours(parseInt(r??"00")).add(g.minutes(parseInt(s??"00"))).add(g.seconds(parseInt(o??"00"))).add(g.milliseconds(parseInt(c??"00")));return n==="local"&&(l=l.add(g.utcOffset)),l.valueOf()}static parseDateTimeString(e,n="UTC"){if(!e.includes("/")&&!e.includes("-"))return g.parseTimeString(e,n);if(e.match(/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d{1,3})?$/)!=null){let s=e,a=0;if(e.includes(".")){const u=e.split(".");s=u[0];const h=u[1]||"0";a=parseInt(h.padEnd(3,"0").slice(0,3))}const o=n==="local"?new Date(s.replace("T"," ")):new Date(`${s}Z`),c=BigInt(o.getTime())*g.MILLISECOND.valueOf(),l=BigInt(a)*g.MILLISECOND.valueOf();return c+l}const r=new Date(e);return e.includes(":")||r.setUTCHours(0,0,0,0),new g(BigInt(r.getTime())*g.MILLISECOND.valueOf(),n).valueOf()}toISOString(e="UTC"){return e==="UTC"?this.date().toISOString():this.sub(g.utcOffset).date().toISOString()}timeString(e=!1,n="UTC"){const r=this.toISOString(n);return e?r.slice(11,23):r.slice(11,19)}dateString(){const e=this.date(),n=e.toLocaleString("default",{month:"short"}),r=e.toLocaleString("default",{day:"numeric"});return`${n} ${r}`}static get utcOffset(){return new m(BigInt(new Date().getTimezoneOffset())*g.MINUTE.valueOf())}static since(e){return new g().span(e)}date(){return new Date(this.milliseconds)}equals(e){return this.valueOf()===new g(e).valueOf()}span(e){return this.range(e).span}range(e){return new x(this,e).makeValid()}spanRange(e){return this.range(this.add(e)).makeValid()}get isZero(){return this.valueOf()===0n}after(e){return this.valueOf()>new g(e).valueOf()}afterEq(e){return this.valueOf()>=new g(e).valueOf()}before(e){return this.valueOf()<new g(e).valueOf()}beforeEq(e){return this.valueOf()<=new g(e).valueOf()}add(e){return new g(Ce(this.valueOf(),new m(e).valueOf()))}sub(e){return new g(xe(this.valueOf(),new m(e).valueOf()))}get hours(){return Number(this.valueOf())/Number(m.HOUR.valueOf())}get minutes(){return Number(this.valueOf())/Number(m.MINUTE.valueOf())}get days(){return Number(this.valueOf())/Number(m.DAY.valueOf())}get seconds(){return Number(this.valueOf())/Number(m.SECOND.valueOf())}get milliseconds(){return Number(this.valueOf())/Number(g.MILLISECOND.valueOf())}get microseconds(){return Number(this.valueOf())/Number(g.MICROSECOND.valueOf())}get nanoseconds(){return Number(this.valueOf())}get year(){return this.date().getUTCFullYear()}setYear(e){const n=this.date();return n.setUTCFullYear(e),new g(n)}get month(){return this.date().getUTCMonth()}setMonth(e){const n=this.date();return n.setUTCMonth(e),new g(n)}get day(){return this.date().getUTCDate()}setDay(e){const n=this.date();return n.setUTCDate(e),new g(n)}get hour(){return this.date().getUTCHours()}get localHour(){return this.date().getHours()}setLocalHour(e){const n=this.date();return n.setHours(e),new g(n)}setHour(e){const n=this.date();return n.setUTCHours(e),new g(n)}get minute(){return this.date().getUTCMinutes()}setMinute(e){const n=this.date();return n.setUTCMinutes(e),new g(n)}get second(){return this.date().getUTCSeconds()}setSecond(e){const n=this.date();return n.setUTCSeconds(e),new g(n)}get millisecond(){return this.date().getUTCMilliseconds()}setMillisecond(e){const n=this.date();return n.setUTCMilliseconds(e),new g(n)}toString(e="ISO",n="UTC"){switch(e){case"ISODate":return this.toISOString(n).slice(0,10);case"ISOTime":return this.toISOString(n).slice(11,23);case"time":return this.timeString(!1,n);case"preciseTime":return this.timeString(!0,n);case"date":return this.dateString();case"preciseDate":return`${this.dateString()} ${this.timeString(!0,n)}`;case"dateTime":return`${this.dateString()} ${this.timeString(!1,n)}`;default:return this.toISOString(n)}}remainder(e){return Uo(this,e)}get isToday(){return this.truncate(m.DAY).equals(g.now().truncate(m.DAY))}truncate(e){return this.sub(this.remainder(e))}formatBySpan(e){return e.greaterThanOrEqual(m.days(30))?"shortDate":e.greaterThanOrEqual(m.DAY)?"dateTime":e.greaterThanOrEqual(m.HOUR)?"time":e.greaterThanOrEqual(m.SECOND)?"preciseTime":"ISOTime"}static now(){return new g(new Date)}static max(...e){let n=g.MIN;for(const r of e){const s=new g(r);s.after(n)&&(n=s)}return n}static min(...e){let n=g.MAX;for(const r of e){const s=new g(r);s.before(n)&&(n=s)}return n}static nanoseconds(e,n="UTC"){return new g(e,n)}static NANOSECOND=g.nanoseconds(1);static microseconds(e,n="UTC"){return g.nanoseconds(e*1e3,n)}static MICROSECOND=g.microseconds(1);static milliseconds(e,n="UTC"){return g.microseconds(e*1e3,n)}static MILLISECOND=g.milliseconds(1);static seconds(e,n="UTC"){return g.milliseconds(e*1e3,n)}static SECOND=g.seconds(1);static minutes(e,n="UTC"){return g.seconds(e*60,n)}static MINUTE=g.minutes(1);static hours(e,n="UTC"){return g.minutes(e*60,n)}static HOUR=g.hours(1);static days(e,n="UTC"){return g.hours(e*24,n)}static DAY=g.days(1);static MAX=new g(An);static MIN=new g(0);static ZERO=new g(0);static z=i.z.union([i.z.instanceof(g),i.z.object({value:i.z.bigint()}).transform(e=>new g(e.value)),i.z.string().transform(e=>new g(BigInt(e))),i.z.number().transform(e=>new g(e)),i.z.bigint().transform(e=>new g(e)),i.z.date().transform(e=>new g(e)),i.z.custom(e=>e instanceof m).transform(e=>new g(e)),Qy.transform(e=>new g(e))]);static sort(e,n){return Number(e.valueOf()-n.valueOf())}}class m extends ut{constructor(e){typeof e=="number"&&(e=Math.trunc(e.valueOf())),se(e)&&(e=e.value),super(BigInt(e.valueOf()))}static fromSeconds(e){return e instanceof m?e:e instanceof Y?e.period:e instanceof g?new m(e):(se(e)&&(e=e.value),["number","bigint"].includes(typeof e)?m.seconds(e):new m(e))}static fromMilliseconds(e){return e instanceof m?e:e instanceof Y?e.period:e instanceof g?new m(e):(se(e)&&(e=e.value),["number","bigint"].includes(typeof e)?m.milliseconds(e):new m(e))}valueOf(){return this.value}lessThan(e){return this.valueOf()<new m(e).valueOf()}greaterThan(e){return this.valueOf()>new m(e).valueOf()}lessThanOrEqual(e){return this.valueOf()<=new m(e).valueOf()}greaterThanOrEqual(e){return this.valueOf()>=new m(e).valueOf()}remainder(e){return Uo(this,e)}truncate(e){return new m(BigInt(Math.trunc(Number(this.valueOf()/e.valueOf())))*e.valueOf())}toString(e="full"){if(e==="semantic")return this.toSemanticString();const n=this.truncate(m.DAY),r=this.truncate(m.HOUR),s=this.truncate(m.MINUTE),a=this.truncate(m.SECOND),o=this.truncate(m.MILLISECOND),c=this.truncate(m.MICROSECOND),l=this.truncate(m.NANOSECOND),u=n,h=r.sub(n),d=s.sub(r),f=a.sub(s),O=o.sub(a),E=c.sub(o),Z=l.sub(c);let z="";return u.isZero||(z+=`${u.days}d `),h.isZero||(z+=`${h.hours}h `),d.isZero||(z+=`${d.minutes}m `),f.isZero||(z+=`${f.seconds}s `),O.isZero||(z+=`${O.milliseconds}ms `),E.isZero||(z+=`${E.microseconds}µs `),Z.isZero||(z+=`${Z.nanoseconds}ns`),z.trim()}toSemanticString(){const e=this.valueOf()<0n?-this.valueOf():this.valueOf(),n=new m(e),r=this.valueOf()<0n;if(n.valueOf()===0n)return"0s";if(n.lessThan(m.SECOND))return"< 1s";const s=n.days,a=n.hours,o=n.minutes,c=n.seconds,l=Math.floor(s/Ai),u=Math.floor(s/zn),h=Math.floor(s/7),d=Math.floor(s),f=Math.floor(a),O=Math.floor(o),E=Math.floor(c),Z=r?"-":"";if(l>=1){let z=`${l}y`;if(l<2){const N=Math.floor(s%Ai/zn);N>0&&(z+=` ${N}mo`)}return Z+z}if(h>=1&&s<zn&&s%7===0){let z=`${h}w`;const N=Math.floor(s%7),A=Math.floor(a-h*7*24);return h<2&&(N>0?z+=` ${N}d`:A>0&&A<24&&(z+=` ${A}h`)),Z+z}if(u>=1){let z=`${u}mo`;if(u<3){const N=Math.floor(s%zn);N>0&&(z+=` ${N}d`)}return Z+z}if(h>=1){let z=`${h}w`;const N=Math.floor(s%7),A=Math.floor(a-h*7*24);return h<2&&(N>0?z+=` ${N}d`:A>0&&A<24&&(z+=` ${A}h`)),Z+z}if(d>=1){let z=`${d}d`;const N=Math.floor(a-d*24);return d<2&&N>0&&(z+=` ${N}h`),Z+z}if(f>=1){let z=`${f}h`;if(f<3){const N=Math.floor(o-f*60);N>0&&(z+=` ${N}m`)}return Z+z}if(O>=1){let z=`${O}m`;if(O<5){const N=Math.floor(c-O*60);N>0&&(z+=` ${N}s`)}return Z+z}return`${Z}${E}s`}mult(e){return new m(pe(this.valueOf(),e))}div(e){return new m(tn(this.valueOf(),e))}get days(){return Number(this.valueOf())/Number(m.DAY.valueOf())}get hours(){return Number(this.valueOf())/Number(m.HOUR.valueOf())}get minutes(){return Number(this.valueOf())/Number(m.MINUTE.valueOf())}get seconds(){return Number(this.valueOf())/Number(m.SECOND.valueOf())}get milliseconds(){return Number(this.valueOf())/Number(m.MILLISECOND.valueOf())}get microseconds(){return Number(this.valueOf())/Number(m.MICROSECOND.valueOf())}get nanoseconds(){return Number(this.valueOf())}get isZero(){return this.valueOf()===0n}equals(e){return this.valueOf()===new m(e).valueOf()}add(e){return new m(this.valueOf()+new m(e).valueOf())}sub(e){return new m(this.valueOf()-new m(e).valueOf())}static nanoseconds(e=1){return new m(e)}static NANOSECOND=m.nanoseconds(1);static microseconds(e=1){return m.nanoseconds(pe(e,1e3))}static MICROSECOND=m.microseconds(1);static milliseconds(e=1){return m.microseconds(pe(e,1e3))}static MILLISECOND=m.milliseconds(1);static seconds(e=1){return m.milliseconds(pe(e,1e3))}static SECOND=m.seconds(1);static minutes(e=1){return m.seconds(pe(e,60))}static MINUTE=m.minutes(1);static hours(e){return m.minutes(pe(e,60))}static HOUR=m.hours(1);static days(e){return m.hours(pe(e,24))}static DAY=m.days(1);static MAX=new m(An);static MIN=new m(0);static ZERO=new m(0);static z=i.z.union([i.z.object({value:i.z.bigint()}).transform(e=>new m(e.value)),i.z.string().transform(e=>new m(BigInt(e))),i.z.number().transform(e=>new m(e)),i.z.bigint().transform(e=>new m(e)),i.z.instanceof(m),i.z.instanceof(g).transform(e=>new m(e)),i.z.custom(e=>e instanceof Y).transform(e=>new m(e))])}class Y extends ut{constructor(e){se(e)&&(e=e.value),super(e.valueOf())}toString(){return`${this.valueOf()} Hz`}equals(e){return this.valueOf()===new Y(e).valueOf()}get period(){return m.seconds(1/this.valueOf())}sampleCount(e){return new m(e).seconds*this.valueOf()}byteCount(e,n){return this.sampleCount(e)*new C(n).valueOf()}span(e){return m.seconds(e/this.valueOf())}byteSpan(e,n){return this.span(e.valueOf()/new C(n).valueOf())}add(e){return new Y(Ce(this.valueOf(),new Y(e).valueOf()))}sub(e){return new Y(xe(this.valueOf(),new Y(e).valueOf()))}mult(e){return new Y(pe(this.valueOf(),e))}div(e){return new Y(tn(this.valueOf(),e))}static hz(e){return new Y(e)}static khz(e){return Y.hz(e*1e3)}static z=i.z.union([i.z.number().transform(e=>new Y(e)),i.z.instanceof(Y)])}class C extends ut{constructor(e){se(e)&&(e=e.value),super(e.valueOf())}length(e){return e.valueOf()/this.valueOf()}size(e){return new $(e*this.valueOf())}add(e){return new C(Ce(this.valueOf(),new C(e).valueOf()))}sub(e){return new C(xe(this.valueOf(),new C(e).valueOf()))}mult(e){return new C(pe(this.valueOf(),e))}div(e){return new C(tn(this.valueOf(),e))}static UNKNOWN=new C(0);static BIT128=new C(16);static BIT64=new C(8);static BIT32=new C(4);static BIT16=new C(2);static BIT8=new C(1);static z=i.z.union([i.z.number().transform(e=>new C(e)),i.z.instanceof(C)])}class x{start;end;constructor(e,n){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(n))}get span(){return new m(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.start.isZero&&this.end.isZero}get numeric(){return{start:Number(this.start.valueOf()),end:Number(this.end.valueOf())}}swap(){return new x(this.end,this.start)}get numericBounds(){return{lower:Number(this.start.valueOf()),upper:Number(this.end.valueOf())}}equals(e,n=m.ZERO){if(n.isZero)return this.start.equals(e.start)&&this.end.equals(e.end);let r=this.start.sub(e.start).valueOf(),s=this.end.sub(e.end).valueOf();return r<0&&(r=-r),s<0&&(s=-s),r<=n.valueOf()&&s<=n.valueOf()}toString(){return`${this.start.toString()} - ${this.end.toString()}`}toPrettyString(){return`${this.start.toString("preciseDate")} - ${this.span.toString()}`}overlapsWith(e,n=m.ZERO){e=e.makeValid();const r=this.makeValid();if(this.equals(e))return!0;if(e.end.equals(r.start)||r.end.equals(e.start))return!1;const s=g.max(r.start,e.start),a=g.min(r.end,e.end);return a.before(s)?!1:new m(a.sub(s)).greaterThanOrEqual(n)}contains(e){return e instanceof x?this.contains(e.start)&&this.contains(e.end):this.start.beforeEq(e)&&this.end.after(e)}boundBy(e){const n=new x(this.start,this.end);return e.start.after(this.start)&&(n.start=e.start),e.start.after(this.end)&&(n.end=e.start),e.end.before(this.end)&&(n.end=e.end),e.end.before(this.start)&&(n.start=e.end),n}static max(...e){return new x(g.min(...e.map(n=>n.start)),g.max(...e.map(n=>n.end)))}static MAX=new x(g.MIN,g.MAX);static ZERO=new x(g.ZERO,g.ZERO);static z=i.z.union([i.z.object({start:g.z,end:g.z}).transform(e=>new x(e.start,e.end)),i.z.instanceof(x)]);static sort(e,n){return g.sort(e.start,n.start)||g.sort(e.end,n.end)}static merge(...e){return x.max(...e.map(n=>new x(n).makeValid()))}}class y extends ut{constructor(e){if(se(e)&&(e=e.value),e instanceof y||typeof e=="string"||typeof e.valueOf()=="string")super(e.valueOf());else{const n=y.ARRAY_CONSTRUCTOR_DATA_TYPES.get(e.constructor.name);if(n==null)throw new Error(`unable to find data type for ${e.toString()}`);super(n.valueOf())}}get Array(){const e=y.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(n=>this.equals(n))}toString(e=!1){return e?y.SHORT_STRINGS.get(this.valueOf())??this.valueOf():this.valueOf()}get isVariable(){return this.equals(y.JSON)||this.equals(y.STRING)}get isNumeric(){return!this.isVariable&&!this.equals(y.UUID)}get isInteger(){const e=this.toString();return e.startsWith("int")||e.startsWith("uint")}get isFloat(){return this.toString().startsWith("float")}get density(){const e=y.DENSITIES.get(this.toString());if(e==null)throw new Error(`unable to find density for ${this.valueOf()}`);return e}get isUnsignedInteger(){return this.equals(y.UINT8)||this.equals(y.UINT16)||this.equals(y.UINT32)||this.equals(y.UINT64)}get isSignedInteger(){return this.equals(y.INT8)||this.equals(y.INT16)||this.equals(y.INT32)||this.equals(y.INT64)}canSafelyCastTo(e){return this.equals(e)?!0:!this.isNumeric||!e.isNumeric||this.isVariable||e.isVariable||this.isUnsignedInteger&&e.isSignedInteger?!1:this.isFloat?e.isFloat&&this.density.valueOf()<=e.density.valueOf():this.equals(y.INT32)&&e.equals(y.FLOAT64)||this.equals(y.INT8)&&e.equals(y.FLOAT32)?!0:this.isInteger&&e.isInteger?this.density.valueOf()<=e.density.valueOf()&&this.isUnsignedInteger===e.isUnsignedInteger:!1}canCastTo(e){return this.isNumeric&&e.isNumeric?!0:this.equals(e)}checkArray(e){return e.constructor===this.Array}get usesBigInt(){return y.BIG_INT_TYPES.some(e=>e.equals(this))}static UNKNOWN=new y("unknown");static FLOAT64=new y("float64");static FLOAT32=new y("float32");static INT64=new y("int64");static INT32=new y("int32");static INT16=new y("int16");static INT8=new y("int8");static UINT64=new y("uint64");static UINT32=new y("uint32");static UINT16=new y("uint16");static UINT8=new y("uint8");static BOOLEAN=new y("boolean");static TIMESTAMP=new y("timestamp");static UUID=new y("uuid");static STRING=new y("string");static JSON=new y("json");static 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]]);static 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]]);static DENSITIES=new Map([[y.UINT8.toString(),C.BIT8],[y.UINT16.toString(),C.BIT16],[y.UINT32.toString(),C.BIT32],[y.UINT64.toString(),C.BIT64],[y.FLOAT32.toString(),C.BIT32],[y.FLOAT64.toString(),C.BIT64],[y.INT8.toString(),C.BIT8],[y.INT16.toString(),C.BIT16],[y.INT32.toString(),C.BIT32],[y.INT64.toString(),C.BIT64],[y.TIMESTAMP.toString(),C.BIT64],[y.STRING.toString(),C.UNKNOWN],[y.JSON.toString(),C.UNKNOWN],[y.UUID.toString(),C.BIT128]]);static 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];static SHORT_STRINGS=new Map([[y.UINT8.toString(),"u8"],[y.UINT16.toString(),"u16"],[y.UINT32.toString(),"u32"],[y.UINT64.toString(),"u64"],[y.INT8.toString(),"i8"],[y.INT16.toString(),"i16"],[y.INT32.toString(),"i32"],[y.INT64.toString(),"i64"],[y.FLOAT32.toString(),"f32"],[y.FLOAT64.toString(),"f64"],[y.BOOLEAN.toString(),"bool"],[y.TIMESTAMP.toString(),"ts"],[y.UUID.toString(),"uuid"],[y.STRING.toString(),"str"],[y.JSON.toString(),"json"]]);static BIG_INT_TYPES=[y.INT64,y.UINT64,y.TIMESTAMP];static z=i.z.union([i.z.string().transform(e=>new y(e)),i.z.instanceof(y)])}class $ extends ut{constructor(e){se(e)&&(e=e.value),super(e.valueOf())}largerThan(e){return se(e)&&(e=e.value),this.valueOf()>e.valueOf()}smallerThan(e){return se(e)&&(e=e.value),this.valueOf()<e.valueOf()}add(e){return se(e)&&(e=e.value),new $(Ce(this.valueOf(),e.valueOf()))}sub(e){return se(e)&&(e=e.value),new $(xe(this.valueOf(),e.valueOf()))}mult(e){return new $(pe(this.valueOf(),e))}div(e){return new $(tn(this.valueOf(),e))}truncate(e){return new $(Math.trunc(this.valueOf()/new $(e).valueOf())*new $(e).valueOf())}remainder(e){return $.bytes(this.valueOf()%new $(e).valueOf())}get gigabytes(){return this.valueOf()/$.GIGABYTE.valueOf()}get megabytes(){return this.valueOf()/$.MEGABYTE.valueOf()}get kilobytes(){return this.valueOf()/$.KILOBYTE.valueOf()}get terabytes(){return this.valueOf()/$.TERABYTE.valueOf()}toString(){const e=this.truncate($.TERABYTE),n=this.truncate($.GIGABYTE),r=this.truncate($.MEGABYTE),s=this.truncate($.KILOBYTE),a=this.truncate($.BYTE),o=e,c=n.sub(e),l=r.sub(n),u=s.sub(r),h=a.sub(s);let d="";return o.isZero||(d+=`${o.terabytes}TB `),c.isZero||(d+=`${c.gigabytes}GB `),l.isZero||(d+=`${l.megabytes}MB `),u.isZero||(d+=`${u.kilobytes}KB `),(!h.isZero||d==="")&&(d+=`${h.valueOf()}B`),d.trim()}static bytes(e=1){return new $(e)}static BYTE=new $(1);static kilobytes(e=1){return $.bytes(new $(e).valueOf()*1e3)}static KILOBYTE=$.kilobytes(1);static megabytes(e=1){return $.kilobytes(new $(e).valueOf()*1e3)}static MEGABYTE=$.megabytes(1);static gigabytes(e=1){return $.megabytes(new $(e).valueOf()*1e3)}static GIGABYTE=$.gigabytes(1);static terabytes(e){return $.gigabytes(new $(e).valueOf()*1e3)}static TERABYTE=$.terabytes(1);static ZERO=new $(0);static z=i.z.union([i.z.number().transform(e=>new $(e)),i.z.instanceof($)]);get isZero(){return this.valueOf()===0}}i.z.object({start:i.z.number(),end:i.z.number()});i.z.union([i.z.instanceof(Uint8Array),i.z.instanceof(Uint16Array),i.z.instanceof(Uint32Array),i.z.instanceof(BigUint64Array),i.z.instanceof(Float32Array),i.z.instanceof(Float64Array),i.z.instanceof(Int8Array),i.z.instanceof(Int16Array),i.z.instanceof(Int32Array),i.z.instanceof(BigInt64Array)]);const Do=t=>{const e=typeof t;return e==="string"||e==="number"||e==="boolean"||e==="bigint"||t instanceof g||t instanceof m||t instanceof Date},ep=(t,e,n,r=0)=>t.usesBigInt&&!e.usesBigInt?Number(n)-Number(r):!t.usesBigInt&&e.usesBigInt?BigInt(n.valueOf())-BigInt(r.valueOf()):xe(n,r),tp=/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/i;function np(t){return typeof t=="string"&&tp.test(t)}const X=[];for(let t=0;t<256;++t)X.push((t+256).toString(16).slice(1));function rp(t,e=0){return(X[t[e+0]]+X[t[e+1]]+X[t[e+2]]+X[t[e+3]]+"-"+X[t[e+4]]+X[t[e+5]]+"-"+X[t[e+6]]+X[t[e+7]]+"-"+X[t[e+8]]+X[t[e+9]]+"-"+X[t[e+10]]+X[t[e+11]]+X[t[e+12]]+X[t[e+13]]+X[t[e+14]]+X[t[e+15]]).toLowerCase()}function sp(t,e=0){const n=rp(t,e);if(!np(n))throw TypeError("Stringified UUID is invalid");return n}typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto);const Po=(t,e)=>sp(t,e),De=-1,Pr={[Symbol.iterator]:()=>Pr,next:()=>({done:!0,value:void 0})},ip=i.z.string().transform(t=>new Uint8Array(atob(t).split("").map(e=>e.charCodeAt(0))).buffer),ap=i.z.union([i.z.null(),i.z.undefined()]).transform(()=>new Uint8Array().buffer),Lr=10,Lo=(t,e)=>{if(t==="number"&&!e.isNumeric)throw new Error(`cannot convert series of type ${e.toString()} to number`);if(t==="bigint"&&!e.usesBigInt)throw new Error(`cannot convert series of type ${e.toString()} to bigint`)},Bo="sy_x_telem_series";class Q{key;discriminator=Bo;dataType;sampleOffset;gl;_data;timeRange=x.ZERO;alignment=0n;alignmentMultiple=1n;cachedMin;cachedMax;writePos=De;_refCount=0;cachedLength;_cachedIndexes;static crudeZ=i.z.object({timeRange:x.z.optional(),dataType:y.z,alignment:i.z.coerce.bigint().optional(),data:i.z.union([ip,ap,i.z.instanceof(ArrayBuffer),i.z.instanceof(Uint8Array)]),glBufferUsage:Xy.default("static").optional()});static z=Q.crudeZ.transform(e=>new Q(e));constructor(e){op(e)&&(e={data:e}),e.data??=[];const{dataType:n,timeRange:r,sampleOffset:s=0,glBufferUsage:a="static",alignment:o=0n,alignmentMultiple:c=1n,key:l=ds(),data:u}=e;if(qo(u)){const f=u;this.key=f.key,this.dataType=f.dataType,this.sampleOffset=f.sampleOffset,this.gl=f.gl,this._data=f._data,this.timeRange=f.timeRange,this.alignment=f.alignment,this.alignmentMultiple=f.alignmentMultiple,this.cachedMin=f.cachedMin,this.cachedMax=f.cachedMax,this.writePos=f.writePos,this._refCount=f._refCount,this.cachedLength=f.cachedLength;return}const h=Do(u),d=Array.isArray(u);if(n!=null)this.dataType=new y(n);else{if(u instanceof ArrayBuffer)throw new Error("cannot infer data type from an ArrayBuffer instance when constructing a Series. Please provide a data type.");if(d||h){let f=u;if(!h){if(u.length===0)throw new Error("cannot infer data type from a zero length JS array when constructing a Series. Please provide a data type.");f=u[0]}if(typeof f=="string")this.dataType=y.STRING;else if(typeof f=="number")this.dataType=y.FLOAT64;else if(typeof f=="bigint")this.dataType=y.INT64;else if(typeof f=="boolean")this.dataType=y.BOOLEAN;else if(f instanceof g||f instanceof Date||f instanceof g)this.dataType=y.TIMESTAMP;else if(typeof f=="object")this.dataType=y.JSON;else throw new Error(`cannot infer data type of ${typeof f} when constructing a Series from a JS array`)}else this.dataType=new y(u)}if(!d&&!h)this._data=u;else if(d&&u.length===0)this._data=new this.dataType.Array([]).buffer;else{let f=h?[u]:u;const O=f[0];(O instanceof g||O instanceof Date||O instanceof m)&&(f=f.map(E=>new g(E).valueOf())),this.dataType.equals(y.STRING)?(this.cachedLength=f.length,this._data=new TextEncoder().encode(`${f.join(`
9
9
  `)}
10
- `).buffer):this.dataType.equals(d.JSON)?(this.cachedLength=f.length,this._data=new TextEncoder().encode(`${f.map(S=>Lt.encodeString(S)).join(`
10
+ `).buffer):this.dataType.equals(y.JSON)?(this.cachedLength=f.length,this._data=new TextEncoder().encode(`${f.map(E=>Bt.encodeString(E)).join(`
11
11
  `)}
12
- `).buffer):this.dataType.usesBigInt&&typeof T=="number"?this._data=new this.dataType.Array(f.map(S=>BigInt(Math.round(S)))).buffer:!this.dataType.usesBigInt&&typeof T=="bigint"?this._data=new this.dataType.Array(f.map(Number)).buffer:this._data=new this.dataType.Array(f).buffer}this.key=l,this.alignment=o,this.alignmentMultiple=c,this.sampleOffset=s??0,this.timeRange=r??Z.ZERO,this.gl={control:null,buffer:null,prevBuffer:0,bufferUsage:a}}static alloc({capacity:e,dataType:n,...r}){if(e===0)throw new Error("[Series] - cannot allocate an array of length 0");const s=new new d(n).Array(e),a=new Q({data:s.buffer,dataType:n,...r});return a.writePos=0,a}get refCount(){return this._refCount}acquire(e){this._refCount++,e!=null&&this.updateGLBuffer(e)}release(){this._refCount--,this.refCount===0&&this.gl.control!=null?this.maybeGarbageCollectGLBuffer(this.gl.control):this.refCount<0&&console.warn("cannot release a series with a negative reference count")}write(e){if(!e.dataType.equals(this.dataType))throw new Error("buffer must be of the same type as this array");return this.dataType.isVariable?this.writeVariable(e):this.writeFixed(e)}writeVariable(e){if(this.writePos===_e)return 0;const n=this.byteCapacity.valueOf()-this.writePos,r=e.subBytes(0,n);return this.writeToUnderlyingData(r),this.writePos+=r.byteLength.valueOf(),this.cachedLength!=null&&(this.cachedLength+=r.length,this.calculateCachedLength()),r.length}writeFixed(e){if(this.writePos===_e)return 0;const n=this.capacity-this.writePos,r=e.sub(0,n);return this.writeToUnderlyingData(r),this.cachedLength=void 0,this.maybeRecomputeMinMax(r),this.writePos+=r.length,r.length}writeToUnderlyingData(e){this.underlyingData.set(e.data,this.writePos)}get buffer(){return typeof this._data=="object"&&"buffer"in this._data?this._data.buffer:this._data}get underlyingData(){return new this.dataType.Array(this._data)}get data(){return this.writePos===_e?this.underlyingData:new this.dataType.Array(this._data,0,this.writePos)}toStrings(){return this.dataType.isVariable?new TextDecoder().decode(this.underlyingData).split(`
13
- `).slice(0,-1):Array.from(this).map(e=>e.toString())}parseJSON(e){if(!this.dataType.equals(d.JSON))throw new Error("cannot parse non-JSON series as JSON");return this.toStrings().map(n=>e.parse(Lt.decodeString(n)))}get byteCapacity(){return new A(this.underlyingData.byteLength)}get capacity(){return this.dataType.isVariable?this.byteCapacity.valueOf():this.dataType.density.length(this.byteCapacity)}get byteLength(){return this.writePos===_e?this.byteCapacity:this.dataType.isVariable?new A(this.writePos):this.dataType.density.size(this.writePos)}get length(){return this.cachedLength!=null?this.cachedLength:this.dataType.isVariable?this.calculateCachedLength():this.writePos===_e?this.byteCapacity.valueOf()/this.dataType.density.valueOf():this.writePos}calculateCachedLength(){if(!this.dataType.isVariable)throw new Error("cannot calculate length of a non-variable length data type");let e=0;const n=[0];return this.data.forEach((r,s)=>{r===Dr&&(e++,n.push(s+1))}),this._cachedIndexes=n,this.cachedLength=e,e}convert(e,n=0){if(this.dataType.equals(e))return this;const r=new e.Array(this.length);for(let s=0;s<this.length;s++)r[s]=Hy(this.dataType,e,this.data[s],n);return new Q({data:r.buffer,dataType:e,timeRange:this.timeRange,sampleOffset:n,glBufferUsage:this.gl.bufferUsage,alignment:this.alignment})}calcRawMax(){if(this.length===0)return-1/0;if(this.dataType.equals(d.TIMESTAMP))this.cachedMax=this.data[this.data.length-1];else if(this.dataType.usesBigInt){const e=this.data;this.cachedMax=e.reduce((n,r)=>n>r?n:r)}else{const e=this.data;this.cachedMax=e.reduce((n,r)=>n>r?n:r)}return this.cachedMax}get max(){return this.calcMax()}calcMax(){if(this.dataType.isVariable)throw new Error("cannot calculate maximum on a variable length data type");return this.writePos===0?-1/0:(this.cachedMax??=this.calcRawMax(),$e(this.cachedMax,this.sampleOffset))}calcRawMin(){if(this.length===0)return 1/0;if(this.dataType.equals(d.TIMESTAMP))this.cachedMin=this.data[0];else if(this.dataType.usesBigInt){const e=this.data;this.cachedMin=e.reduce((n,r)=>n<r?n:r)}else{const e=this.data;this.cachedMin=e.reduce((n,r)=>n<r?n:r)}return this.cachedMin}get min(){return this.calcMin()}calcMin(){if(this.dataType.isVariable)throw new Error("cannot calculate minimum on a variable length data type");return this.writePos===0?1/0:(this.cachedMin??=this.calcRawMin(),$e(this.cachedMin,this.sampleOffset))}get bounds(){return W(Number(this.min),Number(this.max),{makeValid:!1})}maybeRecomputeMinMax(e){if(this.cachedMin!=null){const n=e.cachedMin??e.calcRawMin();n<this.cachedMin&&(this.cachedMin=n)}if(this.cachedMax!=null){const n=e.cachedMax??e.calcRawMax();n>this.cachedMax&&(this.cachedMax=n)}}atAlignment(e,n){const r=Number((e-this.alignment)/this.alignmentMultiple);if(r<0||r>=this.length){if(n===!0)throw new Error(`[series] - no value at index ${r}`);return}return this.at(r,n)}at(e,n=!1){if(this.dataType.isVariable)return this.atVariable(e,n??!1);if(this.dataType.equals(d.UUID))return this.atUUID(e,n);e<0&&(e=this.length+e);const r=this.data[e];if(r==null){if(n===!0)throw new Error(`[series] - no value at index ${e}`);return}return $e(r,this.sampleOffset)}atUUID(e,n){e<0&&(e=this.length+e);const r=_o(new Uint8Array(this.buffer,e*this.dataType.density.valueOf()));if(r==null){if(n)throw new Error(`[series] - no value at index ${e}`);return}return r}atVariable(e,n){let r=0,s=0;if(this._cachedIndexes!=null)r=this._cachedIndexes[e],s=this._cachedIndexes[e+1]-1;else{e<0&&(e=this.length+e);for(let o=0;o<this.data.length;o++)if(this.data[o]===Dr){if(e===0){s=o;break}r=o+1,e--}if(s===0&&(s=this.data.length),r>=s||e>0){if(n)throw new Error(`[series] - no value at index ${e}`);return}}const a=this.data.slice(r,s);return this.dataType.equals(d.STRING)?new TextDecoder().decode(a):us(JSON.parse(new TextDecoder().decode(a)))}binarySearch(e){let n=0,r=this.length-1;const s=Xt(e);for(;n<=r;){const a=Math.floor((n+r)/2),o=s(this.at(a,!0),e);if(o===0)return a;o<0?n=a+1:r=a-1}return n}updateGLBuffer(e){if(this.gl.control=e,!this.dataType.equals(d.FLOAT32)&&!this.dataType.equals(d.UINT8))throw new Error("Only FLOAT32 and UINT8 arrays can be used in WebGL");const{buffer:n,bufferUsage:r,prevBuffer:s}=this.gl;if(n==null&&(this.gl.buffer=e.createBuffer()),this.writePos!==s)if(e.bindBuffer(e.ARRAY_BUFFER,this.gl.buffer),this.writePos!==_e){s===0&&e.bufferData(e.ARRAY_BUFFER,this.byteCapacity.valueOf(),e.STATIC_DRAW);const a=this.dataType.density.size(s).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,r==="static"?e.STATIC_DRAW:e.DYNAMIC_DRAW),this.gl.prevBuffer=_e}as(e){return Mo(e,this.dataType),this}get digest(){return{key:this.key,dataType:this.dataType.toString(),sampleOffset:this.sampleOffset,alignment:{lower:Ai(this.alignmentBounds.lower),upper:Ai(this.alignmentBounds.upper),multiple:this.alignmentMultiple},timeRange:this.timeRange.toString(),length:this.length,capacity:this.capacity}}get alignmentBounds(){return W(this.alignment,this.alignment+BigInt(this.length)*this.alignmentMultiple)}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 ep(this);return this.dataType.equals(d.JSON)?new Ns(e):e}return this.dataType.equals(d.UUID)?new tp(this):new np(this)}slice(e,n){return this.sliceSub(!1,e,n)}sub(e,n){return this.sliceSub(!0,e,n)}subIterator(e,n){return new ki(this,e,n??this.length)}subAlignmentIterator(e,n){const r=Math.ceil(Number(e-this.alignment)/Number(this.alignmentMultiple)),s=Math.ceil(Number(n-this.alignment)/Number(this.alignmentMultiple));return new ki(this,r,s)}subBytes(e,n){if(e>=0&&(n==null||n>=this.byteLength.valueOf()))return this;const r=this.data.subarray(e,n);return new Q({data:r,dataType:this.dataType,timeRange:this.timeRange,sampleOffset:this.sampleOffset,glBufferUsage:this.gl.bufferUsage,alignment:this.alignment+BigInt(e)})}sliceSub(e,n,r){if(n<=0&&(r==null||r>=this.length))return this;let s;return e?s=this.data.subarray(n,r):s=this.data.slice(n,r),new Q({data:s,dataType:this.dataType,timeRange:this.timeRange,sampleOffset:this.sampleOffset,glBufferUsage:this.gl.bufferUsage,alignment:this.alignment+BigInt(n)})}reAlign(e){return new Q({data:this.buffer,dataType:this.dataType,timeRange:Z.ZERO,sampleOffset:this.sampleOffset,glBufferUsage:"static",alignment:e})}toString(){let e=`Series(${this.dataType.toString()} ${this.length} [`;if(this.length<=10)e+=Array.from(this).map(n=>n.toString());else{for(let n=0;n<5;n++)e+=`${this.at(n)?.toString()}`,e+=",";e+="...,";for(let n=-5;n<0;n++)e+=this.at(n)?.toString(),n<-1&&(e+=",")}return e+="])",e}}const Qy=t=>t==null?!1:Array.isArray(t)||t instanceof ArrayBuffer||ArrayBuffer.isView(t)&&!(t instanceof DataView)||t instanceof Q?!0:Ro(t),Uo=Od(jo,Q);class ki{series;end;index;constructor(e,n,r){this.series=e;const s=W(0,e.length+1);this.end=Ni(s,r),this.index=Ni(s,n)}next(){return this.index>=this.end?{done:!0,value:void 0}:{done:!1,value:this.series.at(this.index++,!0)}}}class ep{series;index;decoder;constructor(e){if(!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,n=this.series.data;for(;this.index<n.length&&n[this.index]!==Dr;)this.index++;const r=this.index;return e===r?{done:!0,value:void 0}:(this.index++,{done:!1,value:this.decoder.decode(this.series.buffer.slice(e,r))})}}class Ns{wrapped;static schema=i.z.record(i.z.string(),i.z.unknown());constructor(e){this.wrapped=e}next(){const e=this.wrapped.next();return e.done===!0?{done:!0,value:void 0}:{done:!1,value:Lt.decodeString(e.value,Ns.schema)}}}class tp{series;index;data;density;constructor(e){if(!e.dataType.equals(d.UUID))throw new Error("cannot create a UUID series iterator for a non-UUID series");this.series=e,this.index=0,this.data=new Uint8Array(e.buffer),this.density=d.UUID.density.valueOf()}next(){if(this.index>=this.series.length)return{done:!0,value:void 0};const e=_o(this.data,this.index*this.density);return this.index++,{done:!1,value:e}}}class np{series;index;constructor(e){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)}}}class Do{series;constructor(e=[]){if(e.length!==0){const n=e[0].dataType;for(let r=1;r<e.length;r++)if(!e[r].dataType.equals(n))throw new Error("[multi-series] - series must have the same data type")}this.series=e}as(e){return Mo(e,this.dataType),this}get dataType(){return this.series.length===0?d.UNKNOWN:this.series[0].dataType}get timeRange(){return this.series.length===0?Z.ZERO:new Z(this.series[0].timeRange.start,this.series[this.series.length-1].timeRange.end)}get alignment(){return this.series.length===0?0n:this.series[0].alignment}get alignmentBounds(){return this.series.length===0?W(0n,0n):W(this.series[0].alignmentBounds.lower,this.series[this.series.length-1].alignmentBounds.upper)}push(e){const n=()=>new Error(`cannot push a ${e.dataType.toString()} series to a ${this.dataType.toString()} multi-series`),r=e.dataType.equals(this.dataType);if(Uo(e)){if(this.series.length!==0&&!r)throw n();this.series.push(e)}else{if(this.series.length!==0&&e.series.length!==0&&!r)throw n();this.series.push(...e.series)}}get length(){return this.series.reduce((e,n)=>e+n.length,0)}atAlignment(e,n){for(const r of this.series)if(gn(r.alignmentBounds,e))return r.atAlignment(e,n);if(n)throw new Error(`[series] - no value at alignment ${e}`)}at(e,n=!1){e<0&&(e=this.length+e);for(const r of this.series){if(e<r.length)return r.at(e,n);e-=r.length}if(n)throw new Error(`[series] - no value at index ${e}`)}subIterator(e,n){return new hr(this,e,n??this.length)}subAlignmentIterator(e,n){if(e>=this.alignmentBounds.upper||n<=this.alignmentBounds.lower)return Ur;let r=0;for(let a=0;a<this.series.length;a++){const o=this.series[a];if(e<o.alignment)break;if(e>=o.alignmentBounds.upper)r+=o.length;else if(gn(o.alignmentBounds,e)){r+=Math.ceil(Number(e-o.alignment)/Number(o.alignmentMultiple));break}}let s=0;for(let a=0;a<this.series.length;a++){const o=this.series[a];if(n<o.alignment)break;if(n>=o.alignmentBounds.upper)s+=o.length;else if(gn(o.alignmentBounds,n)){s+=Math.ceil(Number(n-o.alignment)/Number(o.alignmentMultiple));break}}return new hr(this,r,s)}subAlignmentSpanIterator(e,n){if(e>=this.alignmentBounds.upper)return Ur;n=Math.min(n,Number(this.distance(e,this.alignmentBounds.upper)));let r=0;for(let s=0;s<this.series.length;s++){const a=this.series[s];if(e<a.alignment)break;if(e>=a.alignmentBounds.upper)r+=a.length;else if(gn(a.alignmentBounds,e)){r+=Number(e-a.alignment);break}}return new hr(this,r,r+n)}updateGLBuffer(e){this.series.forEach(n=>n.updateGLBuffer(e))}get bounds(){return Vd(this.series.map(e=>e.bounds))}get byteLength(){return new A(this.series.reduce((e,n)=>e+n.byteLength.valueOf(),0))}get data(){const e=new this.dataType.Array(this.length);let n=0;for(const r of this.series)e.set(r.data,n),n+=r.length;return new this.dataType.Array(e.buffer)}traverseAlignment(e,n){const r=this.series.map(s=>s.alignmentBounds);return Gd(r,e,n)}acquire(e){this.series.forEach(n=>n.acquire(e))}release(){this.series.forEach(e=>e.release())}distance(e,n){const r=this.series.map(s=>s.alignmentBounds);return Wd(r,e,n)}parseJSON(e){if(!this.dataType.equals(d.JSON))throw new Error("cannot parse non-JSON series as JSON");return this.series.flatMap(n=>n.parseJSON(e))}[Symbol.iterator](){return this.series.length===0?{next(){return{done:!0,value:void 0}}}:new rp(this.series)}toStrings(){return this.series.flatMap(e=>e.toStrings())}}class rp{series;seriesIndex;internal;constructor(e){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())}[Symbol.iterator](){return this}}class hr{series;index;end;constructor(e,n,r){this.series=e,this.end=r,this.index=n}next(){return this.index>=this.end?{done:!0,value:void 0}:{done:!1,value:this.series.at(this.index++,!0)}}[Symbol.iterator](){return this}}const Ai=t=>{const e=t>>32n,n=t&0xffffffffn;return{domain:e,sample:n}},sp=async t=>await new Promise(e=>setTimeout(e,g.fromMilliseconds(t).milliseconds));class ip{config;retries;interval;constructor(e){this.config={baseInterval:new g(e?.baseInterval??g.seconds(1)),maxRetries:e?.maxRetries??5,scale:e?.scale??1,sleepFn:e?.sleepFn??sp},this.retries=0,this.interval=new g(this.config.baseInterval)}async wait(){const{maxRetries:e,scale:n,sleepFn:r}=this.config;return this.retries>=e?!1:(await r(this.interval),this.interval=this.interval.mult(n),this.retries++,!0)}get retryMessage(){return`breaker triggered ${this.retries+1}/${this.config.maxRetries} times, retrying in ${this.interval.toString()}`}reset(){this.retries=0,this.interval=this.config.baseInterval}}const ap=i.z.object({baseInterval:g.z.optional(),maxRetries:i.z.number().optional(),scale:i.z.number().optional()}),Ss=Object.freeze(Object.defineProperty({__proto__:null,Breaker:ip,breakerConfigZ:ap},Symbol.toStringTag,{value:"Module"})),op=/^#?([0-9a-f]{6}|[0-9a-f]{8})$/i,Lo=i.z.string().regex(op),bt=i.z.number().min(0).max(255),Po=i.z.number().min(0).max(1),Bo=i.z.tuple([bt,bt,bt,Po]),cp=i.z.tuple([bt,bt,bt]),up=i.z.object({rgba255:Bo}),lp=i.z.number().min(0).max(360),hp=i.z.number().min(0).max(100),fp=i.z.number().min(0).max(100),dp=i.z.tuple([lp,hp,fp,Po]),ks=i.z.union([Lo,cp,Bo,dp,up]),yp=ks.transform(t=>As(t)),As=(t,e=1)=>{if(t=ks.parse(t),typeof t=="string")return pp(t,e);if(Array.isArray(t)){if(t.length<3||t.length>4)throw new Error(`Invalid color: [${t.join(", ")}]`);return t.length===3?[...t,e]:t}return t.rgba255},pp=(t,e=1)=>(t=Lo.parse(t),t=mp(t),[vn(t,0),vn(t,2),vn(t,4),t.length===8?vn(t,6)/255:e]),vn=(t,e)=>parseInt(t.slice(e,e+2),16),mp=t=>t.startsWith("#")?t.slice(1):t;As("#000000");As("#ffffff");const gp=i.z.object({key:i.z.string(),color:ks,position:i.z.number(),switched:i.z.boolean().optional()});i.z.array(gp);const wp=i.z.object({key:i.z.string(),name:i.z.string(),color:yp});i.z.object({key:i.z.string(),name:i.z.string(),swatches:i.z.array(wp)});const qo=i.z.int().min(0).max(255),Fo=255,Yo=0,bp={lower:Yo,upper:Fo+1},Ho=i.z.object({name:i.z.string(),key:i.z.string()}),Bt=t=>i.z.object({subject:Ho,resource:t,authority:qo}),vp=(...t)=>e=>e.filter(n=>{let r=!1;return n.to!=null&&(r=t.includes(n.to.resource)),n.from!=null&&!r&&(r=t.includes(n.from.resource)),r}),Vo=t=>i.z.object({from:Bt(t),to:i.z.null()}),Go=t=>i.z.object({from:i.z.null(),to:Bt(t)}),zp=t=>i.z.union([Vo(t),Go(t),i.z.object({from:Bt(t),to:Bt(t)})]),ae=Object.freeze(Object.defineProperty({__proto__:null,ABSOLUTE_AUTHORITY:Fo,AUTHORITY_BOUNDS:bp,ZERO_AUTHORITY:Yo,acquireZ:Go,authorityZ:qo,filterTransfersByChannelKey:vp,releaseZ:Vo,stateZ:Bt,subjectZ:Ho,transferZ:zp},Symbol.toStringTag,{value:"Module"})),Tp=(t,e)=>{let n=null;return e===0?t:(...r)=>{n!==null&&(clearTimeout(n),n=null),n=setTimeout(()=>t(...r),e)}},Lr=".",Op=(t,e,n=Lr)=>{const r=t.split(n);return r.map((s,a)=>{const o=e(s,a,r);return o==null?null:typeof o=="string"?o:o.join(n)}).filter(s=>s!=null).join(n)},Ep=(t,e)=>{if(!Array.isArray(t))return t[e];const n=t[e];if(n!=null||t.length==0)return n;const r=t[0];if(typeof r=="object"&&"key"in r)return t.find(s=>s.key===e)},Np=((t,e,n={optional:!1})=>{const{optional:r,getter:s=Ep}=n;if(e==="")return t;const a=e.split(Lr);if(a.length===1){const c=s(t,a[0]);if(c===void 0){if(r)return null;throw new Error(`Path ${e} does not exist. ${a[0]} is undefined`)}return c}const o=(c,l)=>{if(l>=a.length)return c;for(let u=a.length-l;u>=1;u--){const h=a.slice(l,l+u).join(Lr),y=s(c,h);if(y!==void 0){if(l+u===a.length)return y;if(y===null){if(r)return null;throw new Error(`Path ${e} does not exist. ${h} is null`)}return o(y,l+u)}}if(r)return null;throw new Error(`Path ${e} does not exist. ${a[l]} is undefined`)};return o(t,0)}),Sp=t=>Object.getOwnPropertySymbols(globalThis).includes(t),kp=(t,e)=>{const n=Symbol.for(t);if(!Sp(n)){const r=e();Object.defineProperty(globalThis,n,{value:r})}return()=>globalThis[n]},Wo="sy_x_error",Ap=t=>e=>e!=null&&typeof e=="object"&&"type"in e&&typeof e.type=="string"?e.type.startsWith(t):e instanceof Error?e.message.startsWith(t):typeof e!="string"?!1:e.startsWith(t),en=t=>class jt extends Error{static discriminator=Wo;discriminator=jt.discriminator;static TYPE=t;type=jt.TYPE;static matches=Ap(t);matches=jt.matches;constructor(n,r){super(n,r),this.name=jt.TYPE}static sub(n){return en(`${t}.${n}`)}},Ko=t=>{if(t==null||typeof t!="object")return!1;const e=t;if(e.discriminator!==Wo)return!1;if(!("type"in e))throw new Error(`X Error is missing its type property: ${JSON.stringify(e)}`);return!0},mt="unknown",Pr="nil";class $p{providers=[];register(e){this.providers.push(e)}encode(e){if(e==null)return{type:Pr,data:""};if(Ko(e))for(const n of this.providers){const r=n.encode(e);if(r!=null)return r}if(e instanceof Error)return{type:mt,data:e.message};if(typeof e=="string")return{type:mt,data:e};try{return{type:mt,data:JSON.stringify(e)}}catch{return{type:mt,data:"unable to encode error information"}}}decode(e){if(e==null||e.type===Pr)return null;if(e.type===mt)return new Br(e.data);for(const n of this.providers){const r=n.decode(e);if(r!=null)return r}return new Br(e.data)}}const $s=kp("synnax-error-registry",()=>new $p),Ip=({encode:t,decode:e})=>$s().register({encode:t,decode:e}),Zp=t=>$s().encode(t),xp=t=>t==null?null:$s().decode(t);class Br extends en("unknown"){}const Cp=i.z.object({type:i.z.string(),data:i.z.string()});class Rp extends en("canceled"){}class _p extends en("not_implemented"){}const Ze=Object.freeze(Object.defineProperty({__proto__:null,Canceled:Rp,NONE:Pr,NotImplemented:_p,UNKNOWN:mt,Unknown:Br,createTyped:en,decode:xp,encode:Zp,isTyped:Ko,payloadZ:Cp,register:Ip},Symbol.toStringTag,{value:"Module"})),Mp=i.object({jsonrpc:i.literal("2.0"),method:i.string(),params:i.any().optional(),id:i.union([i.string(),i.number(),i.null()]).optional()}),Jo=i.object({jsonrpc:i.literal("2.0"),id:i.union([i.string(),i.number(),i.null()])}),jp=Jo.extend({result:i.json()}),Up=Jo.extend({error:i.object({code:i.number().int(),message:i.string().optional(),data:i.json().optional()})}),Dp=i.union([jp,Up]);i.union([Mp,Dp]);i.z.object({key:i.z.string(),value:i.z.string()});const Xo=i.uuid(),Qo=i.object({key:Xo,name:i.string().min(1),color:i.string()}),ec=Object.freeze(Object.defineProperty({__proto__:null,keyZ:Xo,labelZ:Qo},Symbol.toStringTag,{value:"Module"})),qr=i.z.string().regex(/^\d+\.\d+\.\d+(-[0-9A-Za-z-]+(\.[0-9A-Za-z-]+)*)?$/),Lp=(t,e)=>{const n=t.split("."),r=e.split("."),s=Math.max(n.length,r.length);for(let a=0;a<s;a++){const o=n[a],c=r[a];if(o===void 0)return Se;if(c===void 0)return ke;const l=/^\d+$/.test(o),u=/^\d+$/.test(c);if(l&&!u)return Se;if(!l&&u)return ke;if(l&&u){const h=parseInt(o),y=parseInt(c);if(h<y)return Se;if(h>y)return ke}else{if(o<c)return Se;if(o>c)return ke}}return ot},tn=((t,e,n={})=>{n.checkMajor??=!0,n.checkMinor??=!0,n.checkPatch??=!0;const r=qr.parse(t),s=qr.parse(e),[a,o]=r.split("-"),[c,l]=s.split("-"),[u,h,y]=a.split(".").map(Number),[f,T,S]=c.split(".").map(Number);if(n.checkMajor){if(u<f)return Se;if(u>f)return ke}if(n.checkMinor){if(h<T)return Se;if(h>T)return ke}if(n.checkPatch){if(y<S)return Se;if(y>S)return ke}return o===void 0&&l===void 0?ot:o===void 0?ke:l===void 0?Se:Lp(o,l)}),Pp=(t,e,n={})=>to(tn(t,e,n)),tc=(t,e,n={})=>eo(tn(t,e,n)),Bp=(t,e,n={})=>Qa(tn(t,e,n)),qp=({name:t,migrate:e})=>n=>{try{const r=e(n);return console.log(`${t} migrated: ${n.version} -> ${r.version}`),r}catch(r){throw console.log(`${t} failed to migrate from ${n.version}`),console.error(r),r}},Fp=({name:t,migrations:e,targetSchema:n,defaultVersion:r,def:s})=>{const a=Object.keys(e).sort(tn).pop();if(a==null)return u=>{if(u.version??=r,u.version!==s.version)return console.log(`${t} version ${u.version} is newer than latest version of ${s.version}.
12
+ `).buffer):this.dataType.usesBigInt&&typeof O=="number"?this._data=new this.dataType.Array(f.map(E=>BigInt(Math.round(E)))).buffer:!this.dataType.usesBigInt&&typeof O=="bigint"?this._data=new this.dataType.Array(f.map(Number)).buffer:this._data=new this.dataType.Array(f).buffer}this.key=l,this.alignment=o,this.alignmentMultiple=c,this.sampleOffset=s??0,this.timeRange=r??x.ZERO,this.gl={control:null,buffer:null,prevBuffer:0,bufferUsage:a}}static alloc({capacity:e,dataType:n,...r}){if(e===0)throw new Error("[Series] - cannot allocate an array of length 0");const s=new new y(n).Array(e),a=new Q({data:s.buffer,dataType:n,...r});return a.writePos=0,a}get refCount(){return this._refCount}acquire(e){this._refCount++,e!=null&&this.updateGLBuffer(e)}release(){this._refCount--,this.refCount===0&&this.gl.control!=null?this.maybeGarbageCollectGLBuffer(this.gl.control):this.refCount<0&&console.warn("cannot release a series with a negative reference count")}write(e){if(!e.dataType.equals(this.dataType))throw new Error("buffer must be of the same type as this array");return this.dataType.isVariable?this.writeVariable(e):this.writeFixed(e)}writeVariable(e){if(this.writePos===De)return 0;const n=this.byteCapacity.valueOf()-this.writePos,r=e.subBytes(0,n);return this.writeToUnderlyingData(r),this.writePos+=r.byteLength.valueOf(),this.cachedLength!=null&&(this.cachedLength+=r.length,this.calculateCachedLength()),r.length}writeFixed(e){if(this.writePos===De)return 0;const n=this.capacity-this.writePos,r=e.sub(0,n);return this.writeToUnderlyingData(r),this.cachedLength=void 0,this.maybeRecomputeMinMax(r),this.writePos+=r.length,r.length}writeToUnderlyingData(e){this.underlyingData.set(e.data,this.writePos)}get buffer(){return typeof this._data=="object"&&"buffer"in this._data?this._data.buffer:this._data}get underlyingData(){return new this.dataType.Array(this._data)}get data(){return this.writePos===De?this.underlyingData:new this.dataType.Array(this._data,0,this.writePos)}toStrings(){return this.dataType.isVariable?new TextDecoder().decode(this.underlyingData).split(`
13
+ `).slice(0,-1):Array.from(this).map(e=>e.toString())}parseJSON(e){if(!this.dataType.equals(y.JSON))throw new Error("cannot parse non-JSON series as JSON");return this.toStrings().map(n=>e.parse(Bt.decodeString(n)))}get byteCapacity(){return new $(this.underlyingData.byteLength)}get capacity(){return this.dataType.isVariable?this.byteCapacity.valueOf():this.dataType.density.length(this.byteCapacity)}get byteLength(){return this.writePos===De?this.byteCapacity:this.dataType.isVariable?new $(this.writePos):this.dataType.density.size(this.writePos)}get length(){return this.cachedLength!=null?this.cachedLength:this.dataType.isVariable?this.calculateCachedLength():this.writePos===De?this.byteCapacity.valueOf()/this.dataType.density.valueOf():this.writePos}calculateCachedLength(){if(!this.dataType.isVariable)throw new Error("cannot calculate length of a non-variable length data type");let e=0;const n=[0];return this.data.forEach((r,s)=>{r===Lr&&(e++,n.push(s+1))}),this._cachedIndexes=n,this.cachedLength=e,e}convert(e,n=0){if(this.dataType.equals(e))return this;const r=new e.Array(this.length);for(let s=0;s<this.length;s++)r[s]=ep(this.dataType,e,this.data[s],n);return new Q({data:r.buffer,dataType:e,timeRange:this.timeRange,sampleOffset:n,glBufferUsage:this.gl.bufferUsage,alignment:this.alignment})}calcRawMax(){if(this.length===0)return-1/0;if(this.dataType.equals(y.TIMESTAMP))this.cachedMax=this.data[this.data.length-1];else if(this.dataType.usesBigInt){const e=this.data;this.cachedMax=e.reduce((n,r)=>n>r?n:r)}else{const e=this.data;this.cachedMax=e.reduce((n,r)=>n>r?n:r)}return this.cachedMax}get max(){return this.calcMax()}calcMax(){if(this.dataType.isVariable)throw new Error("cannot calculate maximum on a variable length data type");return this.writePos===0?-1/0:(this.cachedMax??=this.calcRawMax(),Ce(this.cachedMax,this.sampleOffset))}calcRawMin(){if(this.length===0)return 1/0;if(this.dataType.equals(y.TIMESTAMP))this.cachedMin=this.data[0];else if(this.dataType.usesBigInt){const e=this.data;this.cachedMin=e.reduce((n,r)=>n<r?n:r)}else{const e=this.data;this.cachedMin=e.reduce((n,r)=>n<r?n:r)}return this.cachedMin}get min(){return this.calcMin()}calcMin(){if(this.dataType.isVariable)throw new Error("cannot calculate minimum on a variable length data type");return this.writePos===0?1/0:(this.cachedMin??=this.calcRawMin(),Ce(this.cachedMin,this.sampleOffset))}get bounds(){return W(Number(this.min),Number(this.max),{makeValid:!1})}maybeRecomputeMinMax(e){if(this.cachedMin!=null){const n=e.cachedMin??e.calcRawMin();n<this.cachedMin&&(this.cachedMin=n)}if(this.cachedMax!=null){const n=e.cachedMax??e.calcRawMax();n>this.cachedMax&&(this.cachedMax=n)}}atAlignment(e,n){const r=Number((e-this.alignment)/this.alignmentMultiple);if(r<0||r>=this.length){if(n===!0)throw new Error(`[series] - no value at index ${r}`);return}return this.at(r,n)}at(e,n=!1){if(this.dataType.isVariable)return this.atVariable(e,n??!1);if(this.dataType.equals(y.UUID))return this.atUUID(e,n);e<0&&(e=this.length+e);const r=this.data[e];if(r==null){if(n===!0)throw new Error(`[series] - no value at index ${e}`);return}return Ce(r,this.sampleOffset)}atUUID(e,n){e<0&&(e=this.length+e);const r=Po(new Uint8Array(this.buffer,e*this.dataType.density.valueOf()));if(r==null){if(n)throw new Error(`[series] - no value at index ${e}`);return}return r}atVariable(e,n){let r=0,s=0;if(this._cachedIndexes!=null)r=this._cachedIndexes[e],s=this._cachedIndexes[e+1]-1;else{e<0&&(e=this.length+e);for(let o=0;o<this.data.length;o++)if(this.data[o]===Lr){if(e===0){s=o;break}r=o+1,e--}if(s===0&&(s=this.data.length),r>=s||e>0){if(n)throw new Error(`[series] - no value at index ${e}`);return}}const a=this.data.slice(r,s);return this.dataType.equals(y.STRING)?new TextDecoder().decode(a):hs(JSON.parse(new TextDecoder().decode(a)))}binarySearch(e){let n=0,r=this.length-1;const s=en(e);for(;n<=r;){const a=Math.floor((n+r)/2),o=s(this.at(a,!0),e);if(o===0)return a;o<0?n=a+1:r=a-1}return n}updateGLBuffer(e){if(this.gl.control=e,!this.dataType.equals(y.FLOAT32)&&!this.dataType.equals(y.UINT8))throw new Error("Only FLOAT32 and UINT8 arrays can be used in WebGL");const{buffer:n,bufferUsage:r,prevBuffer:s}=this.gl;if(n==null&&(this.gl.buffer=e.createBuffer()),this.writePos!==s)if(e.bindBuffer(e.ARRAY_BUFFER,this.gl.buffer),this.writePos!==De){s===0&&e.bufferData(e.ARRAY_BUFFER,this.byteCapacity.valueOf(),e.STATIC_DRAW);const a=this.dataType.density.size(s).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,r==="static"?e.STATIC_DRAW:e.DYNAMIC_DRAW),this.gl.prevBuffer=De}as(e){return Lo(e,this.dataType),this}get digest(){return{key:this.key,dataType:this.dataType.toString(),sampleOffset:this.sampleOffset,alignment:{lower:Ii(this.alignmentBounds.lower),upper:Ii(this.alignmentBounds.upper),multiple:this.alignmentMultiple},timeRange:this.timeRange.toString(),length:this.length,capacity:this.capacity}}get alignmentBounds(){return W(this.alignment,this.alignment+BigInt(this.length)*this.alignmentMultiple)}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 cp(this);return this.dataType.equals(y.JSON)?new ks(e):e}return this.dataType.equals(y.UUID)?new up(this):new lp(this)}slice(e,n){return this.sliceSub(!1,e,n)}sub(e,n){return this.sliceSub(!0,e,n)}subIterator(e,n){return new $i(this,e,n??this.length)}subAlignmentIterator(e,n){const r=Math.ceil(Number(e-this.alignment)/Number(this.alignmentMultiple)),s=Math.ceil(Number(n-this.alignment)/Number(this.alignmentMultiple));return new $i(this,r,s)}subBytes(e,n){if(e>=0&&(n==null||n>=this.byteLength.valueOf()))return this;const r=this.data.subarray(e,n);return new Q({data:r,dataType:this.dataType,timeRange:this.timeRange,sampleOffset:this.sampleOffset,glBufferUsage:this.gl.bufferUsage,alignment:this.alignment+BigInt(e)})}sliceSub(e,n,r){if(n<=0&&(r==null||r>=this.length))return this;let s;return e?s=this.data.subarray(n,r):s=this.data.slice(n,r),new Q({data:s,dataType:this.dataType,timeRange:this.timeRange,sampleOffset:this.sampleOffset,glBufferUsage:this.gl.bufferUsage,alignment:this.alignment+BigInt(n)})}reAlign(e){return new Q({data:this.buffer,dataType:this.dataType,timeRange:x.ZERO,sampleOffset:this.sampleOffset,glBufferUsage:"static",alignment:e})}toString(){let e=`Series(${this.dataType.toString()} ${this.length} [`;if(this.length<=10)e+=Array.from(this).map(n=>n.toString());else{for(let n=0;n<5;n++)e+=`${this.at(n)?.toString()}`,e+=",";e+="...,";for(let n=-5;n<0;n++)e+=this.at(n)?.toString(),n<-1&&(e+=",")}return e+="])",e}}const op=t=>t==null?!1:Array.isArray(t)||t instanceof ArrayBuffer||ArrayBuffer.isView(t)&&!(t instanceof DataView)||t instanceof Q?!0:Do(t),qo=Zd(Bo,Q);class $i{series;end;index;constructor(e,n,r){this.series=e;const s=W(0,e.length+1);this.end=ki(s,r),this.index=ki(s,n)}next(){return this.index>=this.end?{done:!0,value:void 0}:{done:!1,value:this.series.at(this.index++,!0)}}}class cp{series;index;decoder;constructor(e){if(!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,n=this.series.data;for(;this.index<n.length&&n[this.index]!==Lr;)this.index++;const r=this.index;return e===r?{done:!0,value:void 0}:(this.index++,{done:!1,value:this.decoder.decode(this.series.buffer.slice(e,r))})}}class ks{wrapped;static schema=i.z.record(i.z.string(),i.z.unknown());constructor(e){this.wrapped=e}next(){const e=this.wrapped.next();return e.done===!0?{done:!0,value:void 0}:{done:!1,value:Bt.decodeString(e.value,ks.schema)}}}class up{series;index;data;density;constructor(e){if(!e.dataType.equals(y.UUID))throw new Error("cannot create a UUID series iterator for a non-UUID series");this.series=e,this.index=0,this.data=new Uint8Array(e.buffer),this.density=y.UUID.density.valueOf()}next(){if(this.index>=this.series.length)return{done:!0,value:void 0};const e=Po(this.data,this.index*this.density);return this.index++,{done:!1,value:e}}}class lp{series;index;constructor(e){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)}}}class Fo{series;constructor(e=[]){if(e.length!==0){const n=e[0].dataType;for(let r=1;r<e.length;r++)if(!e[r].dataType.equals(n))throw new Error("[multi-series] - series must have the same data type")}this.series=e}as(e){return Lo(e,this.dataType),this}get dataType(){return this.series.length===0?y.UNKNOWN:this.series[0].dataType}get timeRange(){return this.series.length===0?x.ZERO:new x(this.series[0].timeRange.start,this.series[this.series.length-1].timeRange.end)}get alignment(){return this.series.length===0?0n:this.series[0].alignment}get alignmentBounds(){return this.series.length===0?W(0n,0n):W(this.series[0].alignmentBounds.lower,this.series[this.series.length-1].alignmentBounds.upper)}push(e){const n=()=>new Error(`cannot push a ${e.dataType.toString()} series to a ${this.dataType.toString()} multi-series`),r=e.dataType.equals(this.dataType);if(qo(e)){if(this.series.length!==0&&!r)throw n();this.series.push(e)}else{if(this.series.length!==0&&e.series.length!==0&&!r)throw n();this.series.push(...e.series)}}get length(){return this.series.reduce((e,n)=>e+n.length,0)}atAlignment(e,n){for(const r of this.series)if(bn(r.alignmentBounds,e))return r.atAlignment(e,n);if(n)throw new Error(`[series] - no value at alignment ${e}`)}at(e,n=!1){e<0&&(e=this.length+e);for(const r of this.series){if(e<r.length)return r.at(e,n);e-=r.length}if(n)throw new Error(`[series] - no value at index ${e}`)}subIterator(e,n){return new fr(this,e,n??this.length)}subAlignmentIterator(e,n){if(e>=this.alignmentBounds.upper||n<=this.alignmentBounds.lower)return Pr;let r=0;for(let a=0;a<this.series.length;a++){const o=this.series[a];if(e<o.alignment)break;if(e>=o.alignmentBounds.upper)r+=o.length;else if(bn(o.alignmentBounds,e)){r+=Math.ceil(Number(e-o.alignment)/Number(o.alignmentMultiple));break}}let s=0;for(let a=0;a<this.series.length;a++){const o=this.series[a];if(n<o.alignment)break;if(n>=o.alignmentBounds.upper)s+=o.length;else if(bn(o.alignmentBounds,n)){s+=Math.ceil(Number(n-o.alignment)/Number(o.alignmentMultiple));break}}return new fr(this,r,s)}subAlignmentSpanIterator(e,n){if(e>=this.alignmentBounds.upper)return Pr;n=Math.min(n,Number(this.distance(e,this.alignmentBounds.upper)));let r=0;for(let s=0;s<this.series.length;s++){const a=this.series[s];if(e<a.alignment)break;if(e>=a.alignmentBounds.upper)r+=a.length;else if(bn(a.alignmentBounds,e)){r+=Number(e-a.alignment);break}}return new fr(this,r,r+n)}updateGLBuffer(e){this.series.forEach(n=>n.updateGLBuffer(e))}get bounds(){return ty(this.series.map(e=>e.bounds))}get byteLength(){return new $(this.series.reduce((e,n)=>e+n.byteLength.valueOf(),0))}get data(){const e=new this.dataType.Array(this.length);let n=0;for(const r of this.series)e.set(r.data,n),n+=r.length;return new this.dataType.Array(e.buffer)}traverseAlignment(e,n){const r=this.series.map(s=>s.alignmentBounds);return ny(r,e,n)}acquire(e){this.series.forEach(n=>n.acquire(e))}release(){this.series.forEach(e=>e.release())}distance(e,n){const r=this.series.map(s=>s.alignmentBounds);return ry(r,e,n)}parseJSON(e){if(!this.dataType.equals(y.JSON))throw new Error("cannot parse non-JSON series as JSON");return this.series.flatMap(n=>n.parseJSON(e))}[Symbol.iterator](){return this.series.length===0?{next(){return{done:!0,value:void 0}}}:new hp(this.series)}toStrings(){return this.series.flatMap(e=>e.toStrings())}}class hp{series;seriesIndex;internal;constructor(e){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())}[Symbol.iterator](){return this}}class fr{series;index;end;constructor(e,n,r){this.series=e,this.end=r,this.index=n}next(){return this.index>=this.end?{done:!0,value:void 0}:{done:!1,value:this.series.at(this.index++,!0)}}[Symbol.iterator](){return this}}const Ii=t=>{const e=t>>32n,n=t&0xffffffffn;return{domain:e,sample:n}},fp=async t=>await new Promise(e=>setTimeout(e,m.fromMilliseconds(t).milliseconds));class dp{config;retries;interval;constructor(e){this.config={baseInterval:new m(e?.baseInterval??m.seconds(1)),maxRetries:e?.maxRetries??5,scale:e?.scale??1,sleepFn:e?.sleepFn??fp},this.retries=0,this.interval=new m(this.config.baseInterval)}async wait(){const{maxRetries:e,scale:n,sleepFn:r}=this.config;return this.retries>=e?!1:(await r(this.interval),this.interval=this.interval.mult(n),this.retries++,!0)}get retryMessage(){return`breaker triggered ${this.retries+1}/${this.config.maxRetries} times, retrying in ${this.interval.toString()}`}reset(){this.retries=0,this.interval=this.config.baseInterval}}const yp=i.z.object({baseInterval:m.z.optional(),maxRetries:i.z.number().optional(),scale:i.z.number().optional()}),As=Object.freeze(Object.defineProperty({__proto__:null,Breaker:dp,breakerConfigZ:yp},Symbol.toStringTag,{value:"Module"})),pp=/^#?([0-9a-f]{6}|[0-9a-f]{8})$/i,Yo=i.z.string().regex(pp),Tt=i.z.number().min(0).max(255),Vo=i.z.number().min(0).max(1),Go=i.z.tuple([Tt,Tt,Tt,Vo]),mp=i.z.tuple([Tt,Tt,Tt]),gp=i.z.object({rgba255:Go}),wp=i.z.number().min(0).max(360),bp=i.z.number().min(0).max(100),vp=i.z.number().min(0).max(100),zp=i.z.tuple([wp,bp,vp,Vo]),$s=i.z.union([Yo,mp,Go,zp,gp]),Tp=$s.transform(t=>Is(t)),Is=(t,e=1)=>{if(t=$s.parse(t),typeof t=="string")return Op(t,e);if(Array.isArray(t)){if(t.length<3||t.length>4)throw new Error(`Invalid color: [${t.join(", ")}]`);return t.length===3?[...t,e]:t}return t.rgba255},Op=(t,e=1)=>(t=Yo.parse(t),t=Np(t),[Tn(t,0),Tn(t,2),Tn(t,4),t.length===8?Tn(t,6)/255:e]),Tn=(t,e)=>parseInt(t.slice(e,e+2),16),Np=t=>t.startsWith("#")?t.slice(1):t;Is("#000000");Is("#ffffff");const Sp=i.z.object({key:i.z.string(),color:$s,position:i.z.number(),switched:i.z.boolean().optional()});i.z.array(Sp);const Ep=i.z.object({key:i.z.string(),name:i.z.string(),color:Tp});i.z.object({key:i.z.string(),name:i.z.string(),swatches:i.z.array(Ep)});const Ho=i.z.int().min(0).max(255),Wo=255,Ko=0,kp={lower:Ko,upper:Wo+1},Jo=i.z.object({name:i.z.string(),key:i.z.string()}),Ft=t=>i.z.object({subject:Jo,resource:t,authority:Ho}),Ap=(...t)=>e=>e.filter(n=>{let r=!1;return n.to!=null&&(r=t.includes(n.to.resource)),n.from!=null&&!r&&(r=t.includes(n.from.resource)),r}),Xo=t=>i.z.object({from:Ft(t),to:i.z.null()}),Qo=t=>i.z.object({from:i.z.null(),to:Ft(t)}),$p=t=>i.z.union([Xo(t),Qo(t),i.z.object({from:Ft(t),to:Ft(t)})]),le=Object.freeze(Object.defineProperty({__proto__:null,ABSOLUTE_AUTHORITY:Wo,AUTHORITY_BOUNDS:kp,ZERO_AUTHORITY:Ko,acquireZ:Qo,authorityZ:Ho,filterTransfersByChannelKey:Ap,releaseZ:Xo,stateZ:Ft,subjectZ:Jo,transferZ:$p},Symbol.toStringTag,{value:"Module"})),Ip=t=>{switch(typeof t){case"bigint":case"number":return t.toString();case"boolean":return t?"1":"0";case"undefined":return"";case"string":case"symbol":case"function":return Zi(t.toString());case"object":return t==null?"":Zi(JSON.stringify(t))}},Zp=/[",\n]/,Zi=t=>Zp.test(t)?`"${t.replace(/"/g,'""')}"`:t,xi=Object.freeze(Object.defineProperty({__proto__:null,formatValue:Ip},Symbol.toStringTag,{value:"Module"})),xp=(t,e)=>{let n=null;return e===0?t:(...r)=>{n!==null&&(clearTimeout(n),n=null),n=setTimeout(()=>t(...r),e)}},Br=".",Cp=(t,e,n=Br)=>{const r=t.split(n);return r.map((s,a)=>{const o=e(s,a,r);return o==null?null:typeof o=="string"?o:o.join(n)}).filter(s=>s!=null).join(n)},Rp=(t,e)=>{if(!Array.isArray(t))return t[e];const n=t[e];if(n!=null||t.length==0)return n;const r=t[0];if(typeof r=="object"&&"key"in r)return t.find(s=>s.key===e)},_p=((t,e,n={optional:!1})=>{const{optional:r,getter:s=Rp}=n;if(e==="")return t;const a=e.split(Br);if(a.length===1){const c=s(t,a[0]);if(c===void 0){if(r)return null;throw new Error(`Path ${e} does not exist. ${a[0]} is undefined`)}return c}const o=(c,l)=>{if(l>=a.length)return c;for(let u=a.length-l;u>=1;u--){const h=a.slice(l,l+u).join(Br),d=s(c,h);if(d!==void 0){if(l+u===a.length)return d;if(d===null){if(r)return null;throw new Error(`Path ${e} does not exist. ${h} is null`)}return o(d,l+u)}}if(r)return null;throw new Error(`Path ${e} does not exist. ${a[l]} is undefined`)};return o(t,0)}),Mp=t=>Object.getOwnPropertySymbols(globalThis).includes(t),jp=(t,e)=>{const n=Symbol.for(t);if(!Mp(n)){const r=e();Object.defineProperty(globalThis,n,{value:r})}return()=>globalThis[n]},ec="sy_x_error",Up=t=>e=>e!=null&&typeof e=="object"&&"type"in e&&typeof e.type=="string"?e.type.startsWith(t):e instanceof Error?e.message.startsWith(t):typeof e!="string"?!1:e.startsWith(t),nn=t=>class Dt extends Error{static discriminator=ec;discriminator=Dt.discriminator;static TYPE=t;type=Dt.TYPE;static matches=Up(t);matches=Dt.matches;constructor(n,r){super(n,r),this.name=Dt.TYPE}static sub(n){return nn(`${t}.${n}`)}},tc=t=>{if(t==null||typeof t!="object")return!1;const e=t;if(e.discriminator!==ec)return!1;if(!("type"in e))throw new Error(`X Error is missing its type property: ${JSON.stringify(e)}`);return!0},bt="unknown",qr="nil";class Dp{providers=[];register(e){this.providers.push(e)}encode(e){if(e==null)return{type:qr,data:""};if(tc(e))for(const n of this.providers){const r=n.encode(e);if(r!=null)return r}if(e instanceof Error)return{type:bt,data:e.message};if(typeof e=="string")return{type:bt,data:e};try{return{type:bt,data:JSON.stringify(e)}}catch{return{type:bt,data:"unable to encode error information"}}}decode(e){if(e==null||e.type===qr)return null;if(e.type===bt)return new Fr(e.data);for(const n of this.providers){const r=n.decode(e);if(r!=null)return r}return new Fr(e.data)}}const Zs=jp("synnax-error-registry",()=>new Dp),Pp=({encode:t,decode:e})=>Zs().register({encode:t,decode:e}),Lp=t=>Zs().encode(t),Bp=t=>t==null?null:Zs().decode(t);class Fr extends nn("unknown"){}const qp=i.z.object({type:i.z.string(),data:i.z.string()});class Fp extends nn("canceled"){}class Yp extends nn("not_implemented"){}const _e=Object.freeze(Object.defineProperty({__proto__:null,Canceled:Fp,NONE:qr,NotImplemented:Yp,UNKNOWN:bt,Unknown:Fr,createTyped:nn,decode:Bp,encode:Lp,isTyped:tc,payloadZ:qp,register:Pp},Symbol.toStringTag,{value:"Module"})),Vp=i.object({jsonrpc:i.literal("2.0"),method:i.string(),params:i.any().optional(),id:i.union([i.string(),i.number(),i.null()]).optional()}),nc=i.object({jsonrpc:i.literal("2.0"),id:i.union([i.string(),i.number(),i.null()])}),Gp=nc.extend({result:i.json()}),Hp=nc.extend({error:i.object({code:i.number().int(),message:i.string().optional(),data:i.json().optional()})}),Wp=i.union([Gp,Hp]);i.union([Vp,Wp]);i.z.object({key:i.z.string(),value:i.z.string()});const rc=i.uuid(),sc=i.object({key:rc,name:i.string().min(1),color:i.string()}),ic=Object.freeze(Object.defineProperty({__proto__:null,keyZ:rc,labelZ:sc},Symbol.toStringTag,{value:"Module"})),Yr=i.z.string().regex(/^\d+\.\d+\.\d+(-[0-9A-Za-z-]+(\.[0-9A-Za-z-]+)*)?$/),Kp=(t,e)=>{const n=t.split("."),r=e.split("."),s=Math.max(n.length,r.length);for(let a=0;a<s;a++){const o=n[a],c=r[a];if(o===void 0)return Ie;if(c===void 0)return Ze;const l=/^\d+$/.test(o),u=/^\d+$/.test(c);if(l&&!u)return Ie;if(!l&&u)return Ze;if(l&&u){const h=parseInt(o),d=parseInt(c);if(h<d)return Ie;if(h>d)return Ze}else{if(o<c)return Ie;if(o>c)return Ze}}return lt},rn=((t,e,n={})=>{n.checkMajor??=!0,n.checkMinor??=!0,n.checkPatch??=!0;const r=Yr.parse(t),s=Yr.parse(e),[a,o]=r.split("-"),[c,l]=s.split("-"),[u,h,d]=a.split(".").map(Number),[f,O,E]=c.split(".").map(Number);if(n.checkMajor){if(u<f)return Ie;if(u>f)return Ze}if(n.checkMinor){if(h<O)return Ie;if(h>O)return Ze}if(n.checkPatch){if(d<E)return Ie;if(d>E)return Ze}return o===void 0&&l===void 0?lt:o===void 0?Ze:l===void 0?Ie:Kp(o,l)}),Jp=(t,e,n={})=>ao(rn(t,e,n)),ac=(t,e,n={})=>io(rn(t,e,n)),Xp=(t,e,n={})=>so(rn(t,e,n)),Qp=({name:t,migrate:e})=>n=>{try{const r=e(n);return console.log(`${t} migrated: ${n.version} -> ${r.version}`),r}catch(r){throw console.log(`${t} failed to migrate from ${n.version}`),console.error(r),r}},em=({name:t,migrations:e,targetSchema:n,defaultVersion:r,def:s})=>{const a=Object.keys(e).sort(rn).pop();if(a==null)return u=>{if(u.version??=r,u.version!==s.version)return console.log(`${t} version ${u.version} is newer than latest version of ${s.version}.
14
14
  Returning default instead.
15
- `),s;try{return n!=null?n.parse(u):u}catch(h){return console.log(`${t} failed to parse default. Exiting with default`),console.error(h),s}};const o=Object.keys(e).length;let c=!1;const l=u=>{try{if(o===0||tc(u.version,a))return console.log(c?`${t} ${u.version} now up to date`:`${t} version ${u.version} is up to date with target version ${s.version}`),u;const h=u.version,y=e[h],f=y(u);return c=!0,l(f)}catch(h){return console.log(`${t} failed to migrate from ${u.version} to ${a}`),console.error(h),s}};return u=>{try{if(u.version==null)if(r!=null)console.log(`${t} version is null. Setting version to default of ${r}`),u.version=r;else return console.log(`${t} version is null and no default version set. Exiting with default`),s;return l(u)}catch(h){return console.log(`${t} failed to parse final result. Exiting with default`),console.error(h),s}}},$i=Object.freeze(Object.defineProperty({__proto__:null,compareSemVer:tn,createMigration:qp,migrator:Fp,semVerNewer:tc,semVerOlder:Bp,semVerZ:qr,versionsEqual:Pp},Symbol.toStringTag,{value:"Module"})),Yp=["standard","scientific","engineering"];i.z.enum(Yp);class Hp{handlers;transform;closer;constructor(e,n){this.transform=e,this.handlers=n??new Map}onChange(e){return this.handlers.set(e,null),()=>this.handlers.delete(e)}notify(e){let n=e;if(this.transform!=null){const[r,s]=this.transform(e);if(!s)return;n=r}this.handlers.forEach((r,s)=>s(n))}setCloser(e){this.closer=e}async close(){return await this.closer?.()}}class Vp{handlers;constructor(e){this.handlers=e??new Map}onChange(e){return this.handlers.set(e,null),()=>this.handlers.delete(e)}notify(e){this.handlers.forEach((n,r)=>r(e))}}const Gp=Object.freeze(Object.defineProperty({__proto__:null,BaseObserver:Vp,Observer:Hp},Symbol.toStringTag,{value:"Module"})),Wp=i.z.record(i.z.union([i.z.number(),i.z.string(),i.z.symbol()]),i.z.unknown()),Is=t=>Object.entries(t),Kp=(t,e)=>Object.fromEntries(Is(t).map(([n,r])=>[n,e(r,n)])),Jp=t=>Object.fromEntries(Is(t).filter(([e,n])=>n!==void 0)),Xp=(t,...e)=>{const n={...t};for(const r of e)delete n[r];return n},de=Object.freeze(Object.defineProperty({__proto__:null,entries:Is,map:Kp,omit:Xp,purgeUndefined:Jp,unknownZ:Wp},Symbol.toStringTag,{value:"Module"})),Qp=()=>typeof process<"u"&&process.versions!=null&&process.versions.node!=null?"node":typeof window>"u"||window.document===void 0?"webworker":"browser";Qp();const em=["macOS","Windows","Linux"],tm=["macos","windows","linux"],nm={macos:"macOS",windows:"Windows",linux:"Linux"};i.z.enum(em).or(i.z.enum(tm).transform(t=>nm[t]));const nc=i.z.enum(["success","info","warning","error","loading","disabled"]),rm=t=>i.z.object({key:i.z.string(),name:i.z.string().default(""),variant:nc,message:i.z.string(),description:i.z.string().optional(),time:m.z,labels:Ba(Qo).optional(),details:t??i.z.unknown().optional()}),sm=i.z.object({stack:i.z.string(),error:i.z.instanceof(Error)}),im=(t,e)=>{if(!(t instanceof Error))throw t;return rc({variant:"error",message:e??t.message,description:e!=null?t.message:void 0,details:{stack:t.stack??"",error:t}})},rc=t=>({key:hs(),time:m.now(),name:"",...t}),am=(t,e=[])=>{if(t!=null)return Array.isArray(e)?e.includes(t)?t:void 0:e===t?t:void 0},om=(t,e=[])=>{if(t!=null)return Array.isArray(e)?e.includes(t)?void 0:t:e===t?void 0:t},ct=Object.freeze(Object.defineProperty({__proto__:null,create:rc,exceptionDetailsSchema:sm,fromException:im,keepVariants:am,removeVariants:om,statusZ:rm,variantZ:nc},Symbol.toStringTag,{value:"Module"})),cm=(t,e)=>{if(!e.has(t))return t;let n=t,r=1,s=t;for(;e.has(s);){const a=s.match(um);a?(n=s.slice(0,a.index).trim(),r=parseInt(a[1])+1):(n=s,r=1),s=`${n} (${r})`}return s},um=/\((\d+)\)$/,lm=(t,e="")=>{if(typeof t=="string")return t;const n=t.length;return n===0?e:n===1?t[0]:n===2?`${t[0]} and ${t[1]}`:`${t.slice(0,-1).join(", ")}, and ${t[n-1]}`},hm=t=>{const e=t.split(" "),n=new Set,r=e.map(o=>o.charAt(0).toLowerCase()).join("");n.add(r.replace(/-/g,"_")),n.add(r.replace(/(.)(.)/g,"$1_$2").replace(/-/g,"_"));const s=/\d+/g;t.match(s)&&e.forEach((o,c)=>{if(s.test(o)){const l=e.map((u,h)=>h!==c?u.charAt(0).toLowerCase():u).join("");n.add(l.replace(/-/g,"_")),n.add(l.replace(/(.)(.)/g,"$1_$2").replace(/-/g,"_"))}});const a=e.map(o=>(o.length>3?o.substring(0,3):o).toLowerCase());return n.add(a.join("").replace(/-/g,"_")),n.add(a.join("_").replace(/-/g,"_")),Array.from(n).filter(o=>o.length>=2&&o.length<=12&&!/^\d/.test(o))},fm=(t,e)=>t.startsWith(e)?t.slice(e.length):t,Fr=Object.freeze(Object.defineProperty({__proto__:null,createShortIdentifiers:hm,deduplicateFileName:cm,naturalLanguageJoin:lm,trimPrefix:fm},Symbol.toStringTag,{value:"Module"})),dm=(...t)=>t.map(sc).join(""),sc=t=>(t.endsWith("/")||(t+="/"),t.startsWith("/")&&(t=t.slice(1)),t),ym=t=>t.endsWith("/")?t.slice(0,-1):t;class vt{protocol;host;port;path;constructor({host:e,port:n,protocol:r="",pathPrefix:s=""}){this.protocol=r,this.host=e,this.port=n,this.path=sc(s)}replace(e){return new vt({host:e.host??this.host,port:e.port??this.port,protocol:e.protocol??this.protocol,pathPrefix:e.pathPrefix??this.path})}child(e){return new vt({...this,pathPrefix:dm(this.path,e)})}toString(){return ym(`${this.protocol}://${this.host}:${this.port}/${this.path}`)}static UNKNOWN=new vt({host:"unknown",port:0})}const pm=t=>t.nullable().transform(e=>e===null?void 0:e).optional(),mm=i.z.int().min(0).max(oo),gm=t=>i.array(t).or(t.transform(e=>[e])),ic=t=>Op(t,(e,n,r)=>{const s=n===r.length-1,a=!isNaN(parseInt(e)),o=!isNaN(parseInt(r[n+1]));return a&&(e="element"),s||o?e:[e,"shape"]}),Ii=(t,e)=>{if(t==null)return null;const n=t[e];return n==null&&typeof t=="object"&&"sourceType"in t?t.sourceType()[e]:n},wm=((t,e,n)=>e===""?t:Np(Ii(t,"shape"),ic(e),{...n,getter:Ii})),ze=Object.freeze(Object.defineProperty({__proto__:null,getFieldSchema:wm,getFieldSchemaPath:ic,nullToUndefined:pm,toArray:gm,uint12:mm},Symbol.toStringTag,{value:"Module"})),Zs=i.z.enum(["create","delete","retrieve","update"]);class Te extends Ze.createTyped("sy"){}class Y extends Te.sub("validation"){}class qt extends Y.sub("path"){path;error;static encodedSchema=i.z.object({path:i.z.string().array(),error:Ze.payloadZ});constructor(e,n){const r=E.toArray(e);super(`${r.join(".")}: ${n.message}`),this.path=r.flatMap(s=>s.split(".")),this.error=n}static decode(e){const n=qt.encodedSchema.parse(JSON.parse(e.data));return new qt(n.path,Ze.decode(n.error))}}class Nt extends Te.sub("auth"){}class Yr extends Nt.sub("invalid_token"){}class Hr extends Nt.sub("expired_token"){}class FS extends Nt.sub("access_denied"){}class zt extends Te.sub("unexpected"){constructor(e){super(`
15
+ `),s;try{return n!=null?n.parse(u):u}catch(h){return console.log(`${t} failed to parse default. Exiting with default`),console.error(h),s}};const o=Object.keys(e).length;let c=!1;const l=u=>{try{if(o===0||ac(u.version,a))return console.log(c?`${t} ${u.version} now up to date`:`${t} version ${u.version} is up to date with target version ${s.version}`),u;const h=u.version,d=e[h],f=d(u);return c=!0,l(f)}catch(h){return console.log(`${t} failed to migrate from ${u.version} to ${a}`),console.error(h),s}};return u=>{try{if(u.version==null)if(r!=null)console.log(`${t} version is null. Setting version to default of ${r}`),u.version=r;else return console.log(`${t} version is null and no default version set. Exiting with default`),s;return l(u)}catch(h){return console.log(`${t} failed to parse final result. Exiting with default`),console.error(h),s}}},Ci=Object.freeze(Object.defineProperty({__proto__:null,compareSemVer:rn,createMigration:Qp,migrator:em,semVerNewer:ac,semVerOlder:Xp,semVerZ:Yr,versionsEqual:Jp},Symbol.toStringTag,{value:"Module"})),tm=["standard","scientific","engineering"];i.z.enum(tm);class nm{handlers;transform;closer;constructor(e,n){this.transform=e,this.handlers=n??new Map}onChange(e){return this.handlers.set(e,null),()=>this.handlers.delete(e)}notify(e){let n=e;if(this.transform!=null){const[r,s]=this.transform(e);if(!s)return;n=r}this.handlers.forEach((r,s)=>s(n))}setCloser(e){this.closer=e}async close(){return await this.closer?.()}}class rm{handlers;constructor(e){this.handlers=e??new Map}onChange(e){return this.handlers.set(e,null),()=>this.handlers.delete(e)}notify(e){this.handlers.forEach((n,r)=>r(e))}}const sm=Object.freeze(Object.defineProperty({__proto__:null,BaseObserver:rm,Observer:nm},Symbol.toStringTag,{value:"Module"})),im=i.z.record(i.z.union([i.z.number(),i.z.string(),i.z.symbol()]),i.z.unknown()),xs=t=>Object.entries(t),am=(t,e)=>Object.fromEntries(xs(t).map(([n,r])=>[n,e(r,n)])),om=t=>Object.fromEntries(xs(t).filter(([e,n])=>n!==void 0)),cm=(t,...e)=>{const n={...t};for(const r of e)delete n[r];return n},we=Object.freeze(Object.defineProperty({__proto__:null,entries:xs,map:am,omit:cm,purgeUndefined:om,unknownZ:im},Symbol.toStringTag,{value:"Module"})),oc=()=>typeof process<"u"&&process.versions!=null&&process.versions.node!=null?"node":typeof window>"u"||window.document===void 0?"webworker":"browser",um=oc(),cc=["macOS","Windows","Linux"],lm=["macos","windows","linux"],hm={macos:"macOS",windows:"Windows",linux:"Linux"},fm=i.z.enum(cc).or(i.z.enum(lm).transform(t=>hm[t])),dm=()=>{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"};let dr;const ym=((t={})=>{const{force:e,default:n}=t;return e??dr??(dr=dm(),dr??n)}),pm=Object.freeze(Object.defineProperty({__proto__:null,OPERATING_SYSTEMS:cc,RUNTIME:um,detect:oc,getOS:ym,osZ:fm},Symbol.toStringTag,{value:"Module"})),uc=i.z.enum(["success","info","warning","error","loading","disabled"]),mm=t=>i.z.object({key:i.z.string(),name:i.z.string().default(""),variant:uc,message:i.z.string(),description:i.z.string().optional(),time:g.z,labels:Ga(sc).optional(),details:t??i.z.unknown().optional()}),gm=i.z.object({stack:i.z.string(),error:i.z.instanceof(Error)}),wm=(t,e)=>{if(!(t instanceof Error))throw t;return lc({variant:"error",message:e??t.message,description:e!=null?t.message:void 0,details:{stack:t.stack??"",error:t}})},lc=t=>({key:ds(),time:g.now(),name:"",...t}),bm=(t,e=[])=>{if(t!=null)return Array.isArray(e)?e.includes(t)?t:void 0:e===t?t:void 0},vm=(t,e=[])=>{if(t!=null)return Array.isArray(e)?e.includes(t)?void 0:t:e===t?void 0:t},ht=Object.freeze(Object.defineProperty({__proto__:null,create:lc,exceptionDetailsSchema:gm,fromException:wm,keepVariants:bm,removeVariants:vm,statusZ:mm,variantZ:uc},Symbol.toStringTag,{value:"Module"})),zm=(t,e)=>{if(!e.has(t))return t;let n=t,r=1,s=t;for(;e.has(s);){const a=s.match(Tm);a?(n=s.slice(0,a.index).trim(),r=parseInt(a[1])+1):(n=s,r=1),s=`${n} (${r})`}return s},Tm=/\((\d+)\)$/,Om=(t,e="")=>{if(typeof t=="string")return t;const n=t.length;return n===0?e:n===1?t[0]:n===2?`${t[0]} and ${t[1]}`:`${t.slice(0,-1).join(", ")}, and ${t[n-1]}`},Nm=t=>{const e=t.split(" "),n=new Set,r=e.map(o=>o.charAt(0).toLowerCase()).join("");n.add(r.replace(/-/g,"_")),n.add(r.replace(/(.)(.)/g,"$1_$2").replace(/-/g,"_"));const s=/\d+/g;t.match(s)&&e.forEach((o,c)=>{if(s.test(o)){const l=e.map((u,h)=>h!==c?u.charAt(0).toLowerCase():u).join("");n.add(l.replace(/-/g,"_")),n.add(l.replace(/(.)(.)/g,"$1_$2").replace(/-/g,"_"))}});const a=e.map(o=>(o.length>3?o.substring(0,3):o).toLowerCase());return n.add(a.join("").replace(/-/g,"_")),n.add(a.join("_").replace(/-/g,"_")),Array.from(n).filter(o=>o.length>=2&&o.length<=12&&!/^\d/.test(o))},Sm=(t,e)=>t.startsWith(e)?t.slice(e.length):t,Vr=Object.freeze(Object.defineProperty({__proto__:null,createShortIdentifiers:Nm,deduplicateFileName:zm,naturalLanguageJoin:Om,trimPrefix:Sm},Symbol.toStringTag,{value:"Module"})),Em=(...t)=>t.map(hc).join(""),hc=t=>(t.endsWith("/")||(t+="/"),t.startsWith("/")&&(t=t.slice(1)),t),km=t=>t.endsWith("/")?t.slice(0,-1):t;class Ot{protocol;host;port;path;constructor({host:e,port:n,protocol:r="",pathPrefix:s=""}){this.protocol=r,this.host=e,this.port=n,this.path=hc(s)}replace(e){return new Ot({host:e.host??this.host,port:e.port??this.port,protocol:e.protocol??this.protocol,pathPrefix:e.pathPrefix??this.path})}child(e){return new Ot({...this,pathPrefix:Em(this.path,e)})}toString(){return km(`${this.protocol}://${this.host}:${this.port}/${this.path}`)}static UNKNOWN=new Ot({host:"unknown",port:0})}const Am=t=>t.nullable().transform(e=>e===null?void 0:e).optional(),$m=i.z.int().min(0).max(fo),Im=t=>i.array(t).or(t.transform(e=>[e])),fc=t=>Cp(t,(e,n,r)=>{const s=n===r.length-1,a=!isNaN(parseInt(e)),o=!isNaN(parseInt(r[n+1]));return a&&(e="element"),s||o?e:[e,"shape"]}),Ri=(t,e)=>{if(t==null)return null;const n=t[e];return n==null&&typeof t=="object"&&"sourceType"in t?t.sourceType()[e]:n},Zm=((t,e,n)=>e===""?t:_p(Ri(t,"shape"),fc(e),{...n,getter:Ri})),Se=Object.freeze(Object.defineProperty({__proto__:null,getFieldSchema:Zm,getFieldSchemaPath:fc,nullToUndefined:Am,toArray:Im,uint12:$m},Symbol.toStringTag,{value:"Module"})),Cs=i.z.enum(["create","delete","retrieve","update"]);class Ee extends _e.createTyped("sy"){}class V extends Ee.sub("validation"){}class Yt extends V.sub("path"){path;error;static encodedSchema=i.z.object({path:i.z.string().array(),error:_e.payloadZ});constructor(e,n){const r=S.toArray(e);super(`${r.join(".")}: ${n.message}`),this.path=r.flatMap(s=>s.split(".")),this.error=n}static decode(e){const n=Yt.encodedSchema.parse(JSON.parse(e.data));return new Yt(n.path,_e.decode(n.error))}}class kt extends Ee.sub("auth"){}class Gr extends kt.sub("invalid_token"){}class Hr extends kt.sub("expired_token"){}class uk extends kt.sub("access_denied"){}class rt extends Ee.sub("unexpected"){constructor(e){super(`
16
16
  Unexpected error encountered:
17
17
 
18
18
  ${e}
19
19
 
20
20
  Please report this to the Synnax team.
21
- `)}}class qe extends Te.sub("query"){}class Ft extends qe.sub("not_found"){}class Yt extends qe.sub("multiple_results"){}class Vr extends Te.sub("route"){path;constructor(e,n){super(e),this.path=n}}class Gr extends Te.sub("control"){}class Zi extends Gr.sub("unauthorized"){}class bm extends Te.sub("disconnected"){constructor(e="Operation failed because no Core is connected."){super(e)}}class vm extends Te.sub("contiguity"){}const zm=t=>t.type.startsWith(Te.TYPE)?t.type.startsWith(Y.TYPE)?t.type===qt.TYPE?qt.decode(t):new Y(t.data):t.type.startsWith(Nt.TYPE)?t.type.startsWith(Yr.TYPE)?new Yr(t.data):t.type.startsWith(Hr.TYPE)?new Hr(t.data):new Nt(t.data):t.type.startsWith(zt.TYPE)?new zt(t.data):t.type.startsWith(qe.TYPE)?t.type.startsWith(Ft.TYPE)?new Ft(t.data):t.type.startsWith(Yt.TYPE)?new Yt(t.data):new qe(t.data):t.type.startsWith(Gr.TYPE)?t.type.startsWith(Zi.TYPE)?new Zi(t.data):new Gr(t.data):t.type.startsWith(Vr.TYPE)?new Vr(t.data,t.data):new zt(t.data):null,Tm=()=>{throw new Ze.NotImplemented};Ze.register({encode:Tm,decode:zm});const Om=async(t,e)=>{const[n,r]=await e(t);return r==null?[n,r]:r instanceof Be?[n,new Be({message:`Cannot reach Core at ${r.url.host}:${r.url.port}`,url:r.url})]:[n,r]},Un=i.z.enum(["label","log","builtin","cluster","channel","node","group","range","framer","range-alias","user","workspace","schematic","lineplot","rack","device","task","policy","role","table","arc","schematic_symbol","status"]),ac=i.z.string().transform(t=>{const[e,n]=t.split(":");return{type:Un.parse(e),key:n??""}}),U=i.z.object({type:Un,key:i.z.string()}).or(ac),Em={type:"builtin",key:"root"},H=t=>{const e=n=>({type:t,key:hd.isZero(n)?"":n.toString()});return(n=>Array.isArray(n)?n.map(e):e(n))},xe=(t=>(typeof t=="string"&&(t=ac.parse(t)),Array.isArray(t)?t.map(e=>xe(e)):`${t.type}:${t.key}`)),Nm=(t,e)=>t.type===e.type&&t.key===e.key,oc=t=>{const e=E.toArray(t);return e.length===0?[]:typeof e[0]=="object"&&"id"in e[0]?e.map(({id:n})=>n):e.map(n=>U.parse(n))},cc=i.z.object({id:U,name:i.z.string(),data:de.unknownZ.optional().nullable()}).transform(t=>({key:xe(t.id),...t})),Sm=t=>t==="to"?"from":"to",km=i.z.object({from:U,type:i.z.string(),to:U}).or(i.z.string().transform(t=>{const[e,n,r]=t.split("->");return{from:U.parse(e),type:n,to:U.parse(r)}})),Am=t=>`${xe(t.from)}->${t.type}->${xe(t.to)}`,$m="parent",Im=(t,e)=>!(e.type!=null&&e.type!==t.type||e.from?.type!=null&&e.from.type!==t.from.type||e.to?.type!=null&&e.to.type!==t.to.type||e.from?.key!=null&&e.from.key!==t.from.key||e.to?.key!=null&&e.to.key!==t.to.key),nn=i.z.uuid(),uc=i.z.string(),Dn=i.z.object({key:nn,name:uc}),Zm=H("group"),xm="sy_group_set",Cm="sy_group_delete",Rm=i.object({group:Dn}),_m=i.object({parent:U,key:nn.optional(),name:i.string()}),Mm=i.object({key:nn,name:i.string()}),jm=i.object({keys:i.array(nn)});let lc=class{client;constructor(e){this.client=e}async create(e){return(await z(this.client,"/ontology/create-group",e,_m,Rm)).group}async rename(e,n){await z(this.client,"/ontology/rename-group",{key:e,name:n},Mm,i.object({}))}async delete(e){await z(this.client,"/ontology/delete-group",{keys:E.toArray(e)},jm,i.object({}))}};const Um=Object.freeze(Object.defineProperty({__proto__:null,Client:lc,DELETE_CHANNEL_NAME:Cm,SET_CHANNEL_NAME:xm,groupZ:Dn,keyZ:nn,nameZ:uc,ontologyID:Zm},Symbol.toStringTag,{value:"Module"})),xi=i.z.object({id:U,children:U.array()}),Dm=i.z.object({from:U,to:U,children:U.array()}),fr=i.z.object({});let Lm=class{client;constructor(e){this.client=e}async addChildren(e,...n){await z(this.client,"/ontology/add-children",{id:e,children:n},xi,fr)}async removeChildren(e,...n){await z(this.client,"/ontology/remove-children",{id:e,children:n},xi,fr)}async moveChildren(e,n,...r){await z(this.client,"/ontology/move-children",{from:e,to:n,children:r},Dm,fr)}};const Pm=i.z.object({ids:U.array().optional(),children:i.z.boolean().optional(),parents:i.z.boolean().optional(),excludeFieldData:i.z.boolean().optional(),types:Un.array().optional(),searchTerm:i.z.string().optional(),limit:i.z.int().optional(),offset:i.z.int().optional()}),Bm=i.z.object({resources:cc.array()});let hc=class{type="ontology";groups;client;writer;framer;constructor(e,n){this.client=e,this.writer=new Lm(e),this.groups=new lc(e),this.framer=n}async retrieve(e,n){if(!Array.isArray(e)&&typeof e=="object"&&!("key"in e))return this.execRetrieve(e);const r=oc(e),s=await this.execRetrieve({ids:r,...n});if(Array.isArray(e))return s;if(s.length===0)throw new qe(`No resource found with ID ${Fr.naturalLanguageJoin(r.map(a=>xe(a)))}`);return s[0]}async retrieveChildren(e,n){return await this.execRetrieve({ids:E.toArray(e),children:!0,...n})}async retrieveParents(e,n){return await this.execRetrieve({ids:E.toArray(e),parents:!0,...n})}async addChildren(e,...n){return await this.writer.addChildren(e,...n)}async removeChildren(e,...n){return await this.writer.removeChildren(e,...n)}async moveChildren(e,n,...r){return await this.writer.moveChildren(e,n,...r)}async execRetrieve(e){const{resources:n}=await z(this.client,"/ontology/retrieve",e,Pm,Bm);return n}};const qm="sy_ontology_resource_set",Fm="sy_ontology_resource_delete",Ym="sy_ontology_relationship_set",Hm="sy_ontology_relationship_delete",Vm=Object.freeze(Object.defineProperty({__proto__:null,Client:hc,PARENT_OF_RELATIONSHIP_TYPE:$m,RELATIONSHIP_DELETE_CHANNEL_NAME:Hm,RELATIONSHIP_SET_CHANNEL_NAME:Ym,RESOURCE_DELETE_CHANNEL_NAME:Fm,RESOURCE_SET_CHANNEL_NAME:qm,ROOT_ID:Em,createIDFactory:H,idToString:xe,idZ:U,idsEqual:Nm,matchRelationship:Im,oppositeRelationshipDirection:Sm,parseIDs:oc,relationshipToString:Am,relationshipZ:km,resourceTypeZ:Un,resourceZ:cc},Symbol.toStringTag,{value:"Module"})),$t=i.z.uuid(),xs=i.z.object({key:$t,name:i.z.string(),objects:E.nullableZ(U),actions:E.nullableZ(Zs),internal:i.z.boolean()}),Cs=i.z.object({key:$t.optional(),name:i.z.string(),objects:ze.toArray(U),actions:ze.toArray(Zs)}),Rs=H("policy"),Gm=Rs(""),Wm="sy_policy_set",Km="sy_policy_delete",Jm=i.z.object({keys:$t.array().optional(),subjects:U.array().optional(),limit:i.z.number().optional(),offset:i.z.number().optional(),internal:i.z.boolean().optional()}),Xm=i.z.object({key:$t}).transform(({key:t})=>({keys:[t]})),Qm=i.z.union([i.z.object({for:U}).transform(({for:t})=>({subjects:[t]})),i.z.object({for:U.array()}).transform(({for:t})=>({subjects:t})),Jm]),eg=i.z.union([Xm,Qm]),tg=i.z.object({policies:E.nullableZ(xs)}),ng=Cs.transform(t=>({policies:[t]})),fc=Cs.array().transform(t=>({policies:t})),dc=i.z.union([ng,fc]),rg=i.z.object({policies:xs.array()}),sg=i.z.object({keys:$t.array()}),ig=i.z.object({});let yc=class{client;constructor(e){this.client=e}async create(e){const n=Array.isArray(e),r=await z(this.client,"/access/policy/create",e,dc,rg);return n?r.policies:r.policies[0]}async retrieve(e){const n="key"in e,r=await z(this.client,"/access/policy/retrieve",e,eg,tg);return n?r.policies[0]:r.policies}async delete(e){await z(this.client,"/access/policy/delete",{keys:E.toArray(e)},sg,ig)}};const ag=Object.freeze(Object.defineProperty({__proto__:null,Client:yc,DELETE_CHANNEL_NAME:Km,SET_CHANNEL_NAME:Wm,TYPE_ONTOLOGY_ID:Gm,createArgsZ:dc,keyZ:$t,multipleCreateArgsZ:fc,newZ:Cs,ontologyID:Rs,policyZ:xs},Symbol.toStringTag,{value:"Module"})),Fe=i.z.uuid(),Ln=i.z.object({key:Fe,name:i.z.string(),description:i.z.string().optional(),internal:i.z.boolean().optional()}),_s=Ln.partial({key:!0}),Ms=H("role"),og=Ms(""),Oe=i.z.uuid(),rn=i.z.object({key:Oe,username:i.z.string().min(1,"Username is required"),firstName:i.z.string().default(""),lastName:i.z.string().default(""),rootUser:i.z.boolean().default(!1)}),pc=rn.omit({rootUser:!0}).partial({key:!0,firstName:!0,lastName:!0}).extend({password:i.z.string().min(1)}),cg=i.z.object({keys:Oe.array().optional(),usernames:i.z.string().array().optional()}),ug=i.z.object({key:Oe}).transform(({key:t})=>({keys:[t]})),lg=i.z.object({username:i.z.string()}).transform(({username:t})=>({usernames:[t]})),hg=i.z.object({usernames:i.z.string().array()}).transform(({usernames:t})=>({usernames:t})),fg=i.z.union([ug,lg,hg,cg]),dg=i.z.object({users:E.nullableZ(rn)}),yg=i.z.object({users:pc.array()}),pg=i.z.object({users:rn.array()}),mg=i.z.object({key:Oe,username:i.z.string().min(1)}),gg=i.z.object({}),wg=i.z.object({key:Oe,firstName:i.z.string().optional(),lastName:i.z.string().optional()}),bg=i.z.object({}),vg=i.z.object({keys:Oe.array()}),zg=i.z.object({}),Tg="sy_user_set",Og="sy_user_delete";let mc=class{client;constructor(e){this.client=e}async create(e){const n=Array.isArray(e),r=await z(this.client,"/user/create",{users:E.toArray(e)},yg,pg);return n?r.users:r.users[0]}async changeUsername(e,n){await z(this.client,"/user/change-username",{key:e,username:n},mg,gg)}async retrieve(e){const n="key"in e||"username"in e,r=await z(this.client,"/user/retrieve",e,fg,dg);if(!n)return r.users;if(r.users.length===0){const s="key"in e?`key ${e.key}`:`username ${e.username}`;throw new Ft(`No user with ${s} found`)}if(r.users.length>1){const s="key"in e?`key ${e.key}`:`username ${e.username}`;throw new Yt(`Multiple users found with ${s}`)}return r.users[0]}async rename(e,n,r){await z(this.client,"/user/rename",{key:e,firstName:n,lastName:r},wg,bg)}async delete(e){await z(this.client,"/user/delete",{keys:E.toArray(e)},vg,zg)}};const gc=H("user"),Eg=gc(""),Ng=Object.freeze(Object.defineProperty({__proto__:null,Client:mc,DELETE_CHANNEL_NAME:Og,SET_CHANNEL_NAME:Tg,TYPE_ONTOLOGY_ID:Eg,keyZ:Oe,newZ:pc,ontologyID:gc,userZ:rn},Symbol.toStringTag,{value:"Module"})),Sg=i.z.object({keys:Fe.array().optional(),limit:i.z.number().optional(),offset:i.z.number().optional(),internal:i.z.boolean().optional()}),kg=i.z.object({key:Fe}).transform(({key:t})=>({keys:[t]})),Ag=_s.transform(t=>({roles:[t]})),wc=_s.array().transform(t=>({roles:t})),bc=i.z.union([Ag,wc]),$g=i.z.object({roles:Ln.array()}),Ig=i.z.object({roles:E.nullableZ(Ln)}),vc=i.z.union([kg,Sg]),Zg=i.z.object({}),xg=Fe.transform(t=>({keys:[t]})).or(Fe.array().transform(t=>({keys:t}))),Cg=i.z.object({user:Oe,role:Fe}),Rg=i.z.object({}),_g=i.z.object({user:Oe,role:Fe}),Mg=i.z.object({}),jg="sy_role_set",Ug="sy_role_delete";let zc=class{client;constructor(e){this.client=e}async create(e){const n=Array.isArray(e),r=await z(this.client,"/access/role/create",e,bc,$g);return n?r.roles:r.roles[0]}async retrieve(e){const n="key"in e,r=await z(this.client,"/access/role/retrieve",e,vc,Ig);return n?r.roles[0]:r.roles}async delete(e){await z(this.client,"/access/role/delete",e,xg,Zg)}async assign(e){await z(this.client,"/access/role/assign",e,Cg,Rg)}async unassign(e){await z(this.client,"/access/role/unassign",e,_g,Mg)}};const Dg=Object.freeze(Object.defineProperty({__proto__:null,Client:zc,DELETE_CHANNEL_NAME:Ug,SET_CHANNEL_NAME:jg,TYPE_ONTOLOGY_ID:og,createArgsZ:bc,keyZ:Fe,multipleCreateArgsZ:wc,newZ:_s,ontologyID:Ms,retrieveArgsZ:vc,roleZ:Ln},Symbol.toStringTag,{value:"Module"}));let Tc=class{policies;roles;constructor(e){this.policies=new yc(e),this.roles=new zc(e)}};const Lg=(t,e)=>{const n=E.toArray(t.objects),{action:r}=t;for(const s of n){let a=!1;for(const o of e)if(o.actions.includes(r)){for(const l of o.objects)if(l.key===""){if(l.type===s.type){a=!0;break}}else if(l.type===s.type&&l.key===s.key){a=!0;break}if(a)break}if(!a)return!1}return!0},Pg=Object.freeze(Object.defineProperty({__proto__:null,Client:Tc,actionZ:Zs,allowRequest:Lg,policy:ag,role:Dg},Symbol.toStringTag,{value:"Module"}));function w(t,e,n){function r(c,l){var u;Object.defineProperty(c,"_zod",{value:c._zod??{},enumerable:!1}),(u=c._zod).traits??(u.traits=new Set),c._zod.traits.add(t),e(c,l);for(const h in o.prototype)h in c||Object.defineProperty(c,h,{value:o.prototype[h].bind(c)});c._zod.constr=o,c._zod.def=l}const s=n?.Parent??Object;class a extends s{}Object.defineProperty(a,"name",{value:t});function o(c){var l;const u=n?.Parent?new a:this;r(u,c),(l=u._zod).deferred??(l.deferred=[]);for(const h of u._zod.deferred)h();return u}return Object.defineProperty(o,"init",{value:r}),Object.defineProperty(o,Symbol.hasInstance,{value:c=>n?.Parent&&c instanceof n.Parent?!0:c?._zod?.traits?.has(t)}),Object.defineProperty(o,"name",{value:t}),o}class Tt extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}class Oc extends Error{constructor(e){super(`Encountered unidirectional transform during encode: ${e}`),this.name="ZodEncodeError"}}const Ec={};function rt(t){return Ec}function Bg(t){const e=Object.values(t).filter(r=>typeof r=="number");return Object.entries(t).filter(([r,s])=>e.indexOf(+r)===-1).map(([r,s])=>s)}function Wr(t,e){return typeof e=="bigint"?e.toString():e}function js(t){return{get value(){{const e=t();return Object.defineProperty(this,"value",{value:e}),e}}}}function Us(t){return t==null}function Ds(t){const e=t.startsWith("^")?1:0,n=t.endsWith("$")?t.length-1:t.length;return t.slice(e,n)}function qg(t,e){const n=(t.toString().split(".")[1]||"").length,r=e.toString();let s=(r.split(".")[1]||"").length;if(s===0&&/\d?e-\d?/.test(r)){const l=r.match(/\d?e-(\d?)/);l?.[1]&&(s=Number.parseInt(l[1]))}const a=n>s?n:s,o=Number.parseInt(t.toFixed(a).replace(".","")),c=Number.parseInt(e.toFixed(a).replace(".",""));return o%c/10**a}const Ci=Symbol("evaluating");function j(t,e,n){let r;Object.defineProperty(t,e,{get(){if(r!==Ci)return r===void 0&&(r=Ci,r=n()),r},set(s){Object.defineProperty(t,e,{value:s})},configurable:!0})}function ut(t,e,n){Object.defineProperty(t,e,{value:n,writable:!0,enumerable:!0,configurable:!0})}function lt(...t){const e={};for(const n of t){const r=Object.getOwnPropertyDescriptors(n);Object.assign(e,r)}return Object.defineProperties({},e)}function Ri(t){return JSON.stringify(t)}const Nc="captureStackTrace"in Error?Error.captureStackTrace:(...t)=>{};function An(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}const Fg=js(()=>{if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{const t=Function;return new t(""),!0}catch{return!1}});function Ht(t){if(An(t)===!1)return!1;const e=t.constructor;if(e===void 0)return!0;const n=e.prototype;return!(An(n)===!1||Object.prototype.hasOwnProperty.call(n,"isPrototypeOf")===!1)}function Sc(t){return Ht(t)?{...t}:Array.isArray(t)?[...t]:t}const Yg=new Set(["string","number","symbol"]);function Pn(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Ye(t,e,n){const r=new t._zod.constr(e??t._zod.def);return(!e||n?.parent)&&(r._zod.parent=t),r}function k(t){const e=t;if(!e)return{};if(typeof e=="string")return{error:()=>e};if(e?.message!==void 0){if(e?.error!==void 0)throw new Error("Cannot specify both `message` and `error` params");e.error=e.message}return delete e.message,typeof e.error=="string"?{...e,error:()=>e.error}:e}function Hg(t){return Object.keys(t).filter(e=>t[e]._zod.optin==="optional"&&t[e]._zod.optout==="optional")}const Vg={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]};function Gg(t,e){const n=t._zod.def,r=lt(t._zod.def,{get shape(){const s={};for(const a in e){if(!(a in n.shape))throw new Error(`Unrecognized key: "${a}"`);e[a]&&(s[a]=n.shape[a])}return ut(this,"shape",s),s},checks:[]});return Ye(t,r)}function Wg(t,e){const n=t._zod.def,r=lt(t._zod.def,{get shape(){const s={...t._zod.def.shape};for(const a in e){if(!(a in n.shape))throw new Error(`Unrecognized key: "${a}"`);e[a]&&delete s[a]}return ut(this,"shape",s),s},checks:[]});return Ye(t,r)}function Kg(t,e){if(!Ht(e))throw new Error("Invalid input to extend: expected a plain object");const n=t._zod.def.checks;if(n&&n.length>0)throw new Error("Object schemas containing refinements cannot be extended. Use `.safeExtend()` instead.");const s=lt(t._zod.def,{get shape(){const a={...t._zod.def.shape,...e};return ut(this,"shape",a),a},checks:[]});return Ye(t,s)}function Jg(t,e){if(!Ht(e))throw new Error("Invalid input to safeExtend: expected a plain object");const n={...t._zod.def,get shape(){const r={...t._zod.def.shape,...e};return ut(this,"shape",r),r},checks:t._zod.def.checks};return Ye(t,n)}function Xg(t,e){const n=lt(t._zod.def,{get shape(){const r={...t._zod.def.shape,...e._zod.def.shape};return ut(this,"shape",r),r},get catchall(){return e._zod.def.catchall},checks:[]});return Ye(t,n)}function Qg(t,e,n){const r=lt(e._zod.def,{get shape(){const s=e._zod.def.shape,a={...s};if(n)for(const o in n){if(!(o in s))throw new Error(`Unrecognized key: "${o}"`);n[o]&&(a[o]=t?new t({type:"optional",innerType:s[o]}):s[o])}else for(const o in s)a[o]=t?new t({type:"optional",innerType:s[o]}):s[o];return ut(this,"shape",a),a},checks:[]});return Ye(e,r)}function ew(t,e,n){const r=lt(e._zod.def,{get shape(){const s=e._zod.def.shape,a={...s};if(n)for(const o in n){if(!(o in a))throw new Error(`Unrecognized key: "${o}"`);n[o]&&(a[o]=new t({type:"nonoptional",innerType:s[o]}))}else for(const o in s)a[o]=new t({type:"nonoptional",innerType:s[o]});return ut(this,"shape",a),a},checks:[]});return Ye(e,r)}function gt(t,e=0){if(t.aborted===!0)return!0;for(let n=e;n<t.issues.length;n++)if(t.issues[n]?.continue!==!0)return!0;return!1}function kc(t,e){return e.map(n=>{var r;return(r=n).path??(r.path=[]),n.path.unshift(t),n})}function zn(t){return typeof t=="string"?t:t?.message}function st(t,e,n){const r={...t,path:t.path??[]};if(!t.message){const s=zn(t.inst?._zod.def?.error?.(t))??zn(e?.error?.(t))??zn(n.customError?.(t))??zn(n.localeError?.(t))??"Invalid input";r.message=s}return delete r.inst,delete r.continue,e?.reportInput||delete r.input,r}function Ls(t){return Array.isArray(t)?"array":typeof t=="string"?"string":"unknown"}function Vt(...t){const[e,n,r]=t;return typeof e=="string"?{message:e,code:"custom",input:n,inst:r}:{...e}}const Ac=(t,e)=>{t.name="$ZodError",Object.defineProperty(t,"_zod",{value:t._zod,enumerable:!1}),Object.defineProperty(t,"issues",{value:e,enumerable:!1}),t.message=JSON.stringify(e,Wr,2),Object.defineProperty(t,"toString",{value:()=>t.message,enumerable:!1})},$c=w("$ZodError",Ac),Ic=w("$ZodError",Ac,{Parent:Error});function tw(t,e=n=>n.message){const n={},r=[];for(const s of t.issues)s.path.length>0?(n[s.path[0]]=n[s.path[0]]||[],n[s.path[0]].push(e(s))):r.push(e(s));return{formErrors:r,fieldErrors:n}}function nw(t,e=n=>n.message){const n={_errors:[]},r=s=>{for(const a of s.issues)if(a.code==="invalid_union"&&a.errors.length)a.errors.map(o=>r({issues:o}));else if(a.code==="invalid_key")r({issues:a.issues});else if(a.code==="invalid_element")r({issues:a.issues});else if(a.path.length===0)n._errors.push(e(a));else{let o=n,c=0;for(;c<a.path.length;){const l=a.path[c];c===a.path.length-1?(o[l]=o[l]||{_errors:[]},o[l]._errors.push(e(a))):o[l]=o[l]||{_errors:[]},o=o[l],c++}}};return r(t),n}const Ps=t=>(e,n,r,s)=>{const a=r?Object.assign(r,{async:!1}):{async:!1},o=e._zod.run({value:n,issues:[]},a);if(o instanceof Promise)throw new Tt;if(o.issues.length){const c=new(s?.Err??t)(o.issues.map(l=>st(l,a,rt())));throw Nc(c,s?.callee),c}return o.value},Bs=t=>async(e,n,r,s)=>{const a=r?Object.assign(r,{async:!0}):{async:!0};let o=e._zod.run({value:n,issues:[]},a);if(o instanceof Promise&&(o=await o),o.issues.length){const c=new(s?.Err??t)(o.issues.map(l=>st(l,a,rt())));throw Nc(c,s?.callee),c}return o.value},Bn=t=>(e,n,r)=>{const s=r?{...r,async:!1}:{async:!1},a=e._zod.run({value:n,issues:[]},s);if(a instanceof Promise)throw new Tt;return a.issues.length?{success:!1,error:new(t??$c)(a.issues.map(o=>st(o,s,rt())))}:{success:!0,data:a.value}},rw=Bn(Ic),qn=t=>async(e,n,r)=>{const s=r?Object.assign(r,{async:!0}):{async:!0};let a=e._zod.run({value:n,issues:[]},s);return a instanceof Promise&&(a=await a),a.issues.length?{success:!1,error:new t(a.issues.map(o=>st(o,s,rt())))}:{success:!0,data:a.value}},sw=qn(Ic),iw=t=>(e,n,r)=>{const s=r?Object.assign(r,{direction:"backward"}):{direction:"backward"};return Ps(t)(e,n,s)},aw=t=>(e,n,r)=>Ps(t)(e,n,r),ow=t=>async(e,n,r)=>{const s=r?Object.assign(r,{direction:"backward"}):{direction:"backward"};return Bs(t)(e,n,s)},cw=t=>async(e,n,r)=>Bs(t)(e,n,r),uw=t=>(e,n,r)=>{const s=r?Object.assign(r,{direction:"backward"}):{direction:"backward"};return Bn(t)(e,n,s)},lw=t=>(e,n,r)=>Bn(t)(e,n,r),hw=t=>async(e,n,r)=>{const s=r?Object.assign(r,{direction:"backward"}):{direction:"backward"};return qn(t)(e,n,s)},fw=t=>async(e,n,r)=>qn(t)(e,n,r),dw=/^[cC][^\s-]{8,}$/,yw=/^[0-9a-z]+$/,pw=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,mw=/^[0-9a-vA-V]{20}$/,gw=/^[A-Za-z0-9]{27}$/,ww=/^[a-zA-Z0-9_-]{21}$/,bw=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,vw=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,_i=t=>t?new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${t}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`):/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/,zw=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,Tw="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function Ow(){return new RegExp(Tw,"u")}const Ew=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,Nw=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))$/,Sw=/^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/,kw=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,Aw=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,Zc=/^[A-Za-z0-9_-]*$/,$w=/^(?=.{1,253}\.?$)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[-0-9a-zA-Z]{0,61}[0-9a-zA-Z])?)*\.?$/,Iw=/^\+(?:[0-9]){6,14}[0-9]$/,xc="(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))",Zw=new RegExp(`^${xc}$`);function Cc(t){const e="(?:[01]\\d|2[0-3]):[0-5]\\d";return typeof t.precision=="number"?t.precision===-1?`${e}`:t.precision===0?`${e}:[0-5]\\d`:`${e}:[0-5]\\d\\.\\d{${t.precision}}`:`${e}(?::[0-5]\\d(?:\\.\\d+)?)?`}function xw(t){return new RegExp(`^${Cc(t)}$`)}function Cw(t){const e=Cc({precision:t.precision}),n=["Z"];t.local&&n.push(""),t.offset&&n.push("([+-](?:[01]\\d|2[0-3]):[0-5]\\d)");const r=`${e}(?:${n.join("|")})`;return new RegExp(`^${xc}T(?:${r})$`)}const Rw=t=>{const e=t?`[\\s\\S]{${t?.minimum??0},${t?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${e}$`)},_w=/^-?\d+$/,Mw=/^-?\d+(?:\.\d+)?/,jw=/^(?:true|false)$/i,Uw=/^[^A-Z]*$/,Dw=/^[^a-z]*$/,te=w("$ZodCheck",(t,e)=>{var n;t._zod??(t._zod={}),t._zod.def=e,(n=t._zod).onattach??(n.onattach=[])}),Rc={number:"number",bigint:"bigint",object:"date"},_c=w("$ZodCheckLessThan",(t,e)=>{te.init(t,e);const n=Rc[typeof e.value];t._zod.onattach.push(r=>{const s=r._zod.bag,a=(e.inclusive?s.maximum:s.exclusiveMaximum)??Number.POSITIVE_INFINITY;e.value<a&&(e.inclusive?s.maximum=e.value:s.exclusiveMaximum=e.value)}),t._zod.check=r=>{(e.inclusive?r.value<=e.value:r.value<e.value)||r.issues.push({origin:n,code:"too_big",maximum:e.value,input:r.value,inclusive:e.inclusive,inst:t,continue:!e.abort})}}),Mc=w("$ZodCheckGreaterThan",(t,e)=>{te.init(t,e);const n=Rc[typeof e.value];t._zod.onattach.push(r=>{const s=r._zod.bag,a=(e.inclusive?s.minimum:s.exclusiveMinimum)??Number.NEGATIVE_INFINITY;e.value>a&&(e.inclusive?s.minimum=e.value:s.exclusiveMinimum=e.value)}),t._zod.check=r=>{(e.inclusive?r.value>=e.value:r.value>e.value)||r.issues.push({origin:n,code:"too_small",minimum:e.value,input:r.value,inclusive:e.inclusive,inst:t,continue:!e.abort})}}),Lw=w("$ZodCheckMultipleOf",(t,e)=>{te.init(t,e),t._zod.onattach.push(n=>{var r;(r=n._zod.bag).multipleOf??(r.multipleOf=e.value)}),t._zod.check=n=>{if(typeof n.value!=typeof e.value)throw new Error("Cannot mix number and bigint in multiple_of check.");(typeof n.value=="bigint"?n.value%e.value===BigInt(0):qg(n.value,e.value)===0)||n.issues.push({origin:typeof n.value,code:"not_multiple_of",divisor:e.value,input:n.value,inst:t,continue:!e.abort})}}),Pw=w("$ZodCheckNumberFormat",(t,e)=>{te.init(t,e),e.format=e.format||"float64";const n=e.format?.includes("int"),r=n?"int":"number",[s,a]=Vg[e.format];t._zod.onattach.push(o=>{const c=o._zod.bag;c.format=e.format,c.minimum=s,c.maximum=a,n&&(c.pattern=_w)}),t._zod.check=o=>{const c=o.value;if(n){if(!Number.isInteger(c)){o.issues.push({expected:r,format:e.format,code:"invalid_type",continue:!1,input:c,inst:t});return}if(!Number.isSafeInteger(c)){c>0?o.issues.push({input:c,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:t,origin:r,continue:!e.abort}):o.issues.push({input:c,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:t,origin:r,continue:!e.abort});return}}c<s&&o.issues.push({origin:"number",input:c,code:"too_small",minimum:s,inclusive:!0,inst:t,continue:!e.abort}),c>a&&o.issues.push({origin:"number",input:c,code:"too_big",maximum:a,inst:t})}}),Bw=w("$ZodCheckMaxLength",(t,e)=>{var n;te.init(t,e),(n=t._zod.def).when??(n.when=r=>{const s=r.value;return!Us(s)&&s.length!==void 0}),t._zod.onattach.push(r=>{const s=r._zod.bag.maximum??Number.POSITIVE_INFINITY;e.maximum<s&&(r._zod.bag.maximum=e.maximum)}),t._zod.check=r=>{const s=r.value;if(s.length<=e.maximum)return;const o=Ls(s);r.issues.push({origin:o,code:"too_big",maximum:e.maximum,inclusive:!0,input:s,inst:t,continue:!e.abort})}}),qw=w("$ZodCheckMinLength",(t,e)=>{var n;te.init(t,e),(n=t._zod.def).when??(n.when=r=>{const s=r.value;return!Us(s)&&s.length!==void 0}),t._zod.onattach.push(r=>{const s=r._zod.bag.minimum??Number.NEGATIVE_INFINITY;e.minimum>s&&(r._zod.bag.minimum=e.minimum)}),t._zod.check=r=>{const s=r.value;if(s.length>=e.minimum)return;const o=Ls(s);r.issues.push({origin:o,code:"too_small",minimum:e.minimum,inclusive:!0,input:s,inst:t,continue:!e.abort})}}),Fw=w("$ZodCheckLengthEquals",(t,e)=>{var n;te.init(t,e),(n=t._zod.def).when??(n.when=r=>{const s=r.value;return!Us(s)&&s.length!==void 0}),t._zod.onattach.push(r=>{const s=r._zod.bag;s.minimum=e.length,s.maximum=e.length,s.length=e.length}),t._zod.check=r=>{const s=r.value,a=s.length;if(a===e.length)return;const o=Ls(s),c=a>e.length;r.issues.push({origin:o,...c?{code:"too_big",maximum:e.length}:{code:"too_small",minimum:e.length},inclusive:!0,exact:!0,input:r.value,inst:t,continue:!e.abort})}}),Fn=w("$ZodCheckStringFormat",(t,e)=>{var n,r;te.init(t,e),t._zod.onattach.push(s=>{const a=s._zod.bag;a.format=e.format,e.pattern&&(a.patterns??(a.patterns=new Set),a.patterns.add(e.pattern))}),e.pattern?(n=t._zod).check??(n.check=s=>{e.pattern.lastIndex=0,!e.pattern.test(s.value)&&s.issues.push({origin:"string",code:"invalid_format",format:e.format,input:s.value,...e.pattern?{pattern:e.pattern.toString()}:{},inst:t,continue:!e.abort})}):(r=t._zod).check??(r.check=()=>{})}),Yw=w("$ZodCheckRegex",(t,e)=>{Fn.init(t,e),t._zod.check=n=>{e.pattern.lastIndex=0,!e.pattern.test(n.value)&&n.issues.push({origin:"string",code:"invalid_format",format:"regex",input:n.value,pattern:e.pattern.toString(),inst:t,continue:!e.abort})}}),Hw=w("$ZodCheckLowerCase",(t,e)=>{e.pattern??(e.pattern=Uw),Fn.init(t,e)}),Vw=w("$ZodCheckUpperCase",(t,e)=>{e.pattern??(e.pattern=Dw),Fn.init(t,e)}),Gw=w("$ZodCheckIncludes",(t,e)=>{te.init(t,e);const n=Pn(e.includes),r=new RegExp(typeof e.position=="number"?`^.{${e.position}}${n}`:n);e.pattern=r,t._zod.onattach.push(s=>{const a=s._zod.bag;a.patterns??(a.patterns=new Set),a.patterns.add(r)}),t._zod.check=s=>{s.value.includes(e.includes,e.position)||s.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:e.includes,input:s.value,inst:t,continue:!e.abort})}}),Ww=w("$ZodCheckStartsWith",(t,e)=>{te.init(t,e);const n=new RegExp(`^${Pn(e.prefix)}.*`);e.pattern??(e.pattern=n),t._zod.onattach.push(r=>{const s=r._zod.bag;s.patterns??(s.patterns=new Set),s.patterns.add(n)}),t._zod.check=r=>{r.value.startsWith(e.prefix)||r.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:e.prefix,input:r.value,inst:t,continue:!e.abort})}}),Kw=w("$ZodCheckEndsWith",(t,e)=>{te.init(t,e);const n=new RegExp(`.*${Pn(e.suffix)}$`);e.pattern??(e.pattern=n),t._zod.onattach.push(r=>{const s=r._zod.bag;s.patterns??(s.patterns=new Set),s.patterns.add(n)}),t._zod.check=r=>{r.value.endsWith(e.suffix)||r.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:e.suffix,input:r.value,inst:t,continue:!e.abort})}}),Jw=w("$ZodCheckOverwrite",(t,e)=>{te.init(t,e),t._zod.check=n=>{n.value=e.tx(n.value)}});class Xw{constructor(e=[]){this.content=[],this.indent=0,this&&(this.args=e)}indented(e){this.indent+=1,e(this),this.indent-=1}write(e){if(typeof e=="function"){e(this,{execution:"sync"}),e(this,{execution:"async"});return}const r=e.split(`
21
+ `)}}class Ge extends Ee.sub("query"){}class Vt extends Ge.sub("not_found"){}class Gt extends Ge.sub("multiple_results"){}class Wr extends Ee.sub("route"){path;constructor(e,n){super(e),this.path=n}}class Kr extends Ee.sub("control"){}class _i extends Kr.sub("unauthorized"){}class xm extends Ee.sub("disconnected"){constructor(e="Operation failed because no Core is connected."){super(e)}}class Cm extends Ee.sub("contiguity"){}const Rm=t=>t.type.startsWith(Ee.TYPE)?t.type.startsWith(V.TYPE)?t.type===Yt.TYPE?Yt.decode(t):new V(t.data):t.type.startsWith(kt.TYPE)?t.type.startsWith(Gr.TYPE)?new Gr(t.data):t.type.startsWith(Hr.TYPE)?new Hr(t.data):new kt(t.data):t.type.startsWith(rt.TYPE)?new rt(t.data):t.type.startsWith(Ge.TYPE)?t.type.startsWith(Vt.TYPE)?new Vt(t.data):t.type.startsWith(Gt.TYPE)?new Gt(t.data):new Ge(t.data):t.type.startsWith(Kr.TYPE)?t.type.startsWith(_i.TYPE)?new _i(t.data):new Kr(t.data):t.type.startsWith(Wr.TYPE)?new Wr(t.data,t.data):new rt(t.data):null,_m=()=>{throw new _e.NotImplemented};_e.register({encode:_m,decode:Rm});const Mm=async(t,e)=>{const[n,r]=await e(t);return r==null?[n,r]:r instanceof Ve?[n,new Ve({message:`Cannot reach Core at ${r.url.host}:${r.url.port}`,url:r.url})]:[n,r]},Pn=i.z.enum(["label","log","builtin","cluster","channel","node","group","range","framer","range-alias","user","workspace","schematic","lineplot","rack","device","task","policy","role","table","arc","schematic_symbol","status"]),dc=i.z.string().transform(t=>{const[e,n]=t.split(":");return{type:Pn.parse(e),key:n??""}}),P=i.z.object({type:Pn,key:i.z.string()}).or(dc),jm={type:"builtin",key:"root"},G=t=>{const e=n=>({type:t,key:bd.isZero(n)?"":n.toString()});return(n=>Array.isArray(n)?n.map(e):e(n))},Me=(t=>(typeof t=="string"&&(t=dc.parse(t)),Array.isArray(t)?t.map(e=>Me(e)):`${t.type}:${t.key}`)),Um=(t,e)=>t.type===e.type&&t.key===e.key,yc=t=>{const e=S.toArray(t);return e.length===0?[]:typeof e[0]=="object"&&"id"in e[0]?e.map(({id:n})=>n):e.map(n=>P.parse(n))},pc=i.z.object({id:P,name:i.z.string(),data:we.unknownZ.optional().nullable()}).transform(t=>({key:Me(t.id),...t})),Dm=t=>t==="to"?"from":"to",Pm=i.z.object({from:P,type:i.z.string(),to:P}).or(i.z.string().transform(t=>{const[e,n,r]=t.split("->");return{from:P.parse(e),type:n,to:P.parse(r)}})),Lm=t=>`${Me(t.from)}->${t.type}->${Me(t.to)}`,Bm="parent",qm=(t,e)=>!(e.type!=null&&e.type!==t.type||e.from?.type!=null&&e.from.type!==t.from.type||e.to?.type!=null&&e.to.type!==t.to.type||e.from?.key!=null&&e.from.key!==t.from.key||e.to?.key!=null&&e.to.key!==t.to.key),sn=i.z.uuid(),mc=i.z.string(),Ln=i.z.object({key:sn,name:mc}),Fm=G("group"),Ym="sy_group_set",Vm="sy_group_delete",Gm=i.object({group:Ln}),Hm=i.object({parent:P,key:sn.optional(),name:i.string()}),Wm=i.object({key:sn,name:i.string()}),Km=i.object({keys:i.array(sn)});let gc=class{client;constructor(e){this.client=e}async create(e){return(await T(this.client,"/ontology/create-group",e,Hm,Gm)).group}async rename(e,n){await T(this.client,"/ontology/rename-group",{key:e,name:n},Wm,i.object({}))}async delete(e){await T(this.client,"/ontology/delete-group",{keys:S.toArray(e)},Km,i.object({}))}};const Jm=Object.freeze(Object.defineProperty({__proto__:null,Client:gc,DELETE_CHANNEL_NAME:Vm,SET_CHANNEL_NAME:Ym,groupZ:Ln,keyZ:sn,nameZ:mc,ontologyID:Fm},Symbol.toStringTag,{value:"Module"})),Mi=i.z.object({id:P,children:P.array()}),Xm=i.z.object({from:P,to:P,children:P.array()}),yr=i.z.object({});let Qm=class{client;constructor(e){this.client=e}async addChildren(e,...n){await T(this.client,"/ontology/add-children",{id:e,children:n},Mi,yr)}async removeChildren(e,...n){await T(this.client,"/ontology/remove-children",{id:e,children:n},Mi,yr)}async moveChildren(e,n,...r){await T(this.client,"/ontology/move-children",{from:e,to:n,children:r},Xm,yr)}};const eg=i.z.object({ids:P.array().optional(),children:i.z.boolean().optional(),parents:i.z.boolean().optional(),excludeFieldData:i.z.boolean().optional(),types:Pn.array().optional(),searchTerm:i.z.string().optional(),limit:i.z.int().optional(),offset:i.z.int().optional()}),tg=i.z.object({resources:pc.array()});let wc=class{type="ontology";groups;client;writer;framer;constructor(e,n){this.client=e,this.writer=new Qm(e),this.groups=new gc(e),this.framer=n}async retrieve(e,n){if(!Array.isArray(e)&&typeof e=="object"&&!("key"in e))return this.execRetrieve(e);const r=yc(e),s=await this.execRetrieve({ids:r,...n});if(Array.isArray(e))return s;if(s.length===0)throw new Ge(`No resource found with ID ${Vr.naturalLanguageJoin(r.map(a=>Me(a)))}`);return s[0]}async retrieveChildren(e,n){return await this.execRetrieve({ids:S.toArray(e),children:!0,...n})}async retrieveParents(e,n){return await this.execRetrieve({ids:S.toArray(e),parents:!0,...n})}async addChildren(e,...n){return await this.writer.addChildren(e,...n)}async removeChildren(e,...n){return await this.writer.removeChildren(e,...n)}async moveChildren(e,n,...r){return await this.writer.moveChildren(e,n,...r)}async execRetrieve(e){const{resources:n}=await T(this.client,"/ontology/retrieve",e,eg,tg);return n}};const ng="sy_ontology_resource_set",rg="sy_ontology_resource_delete",sg="sy_ontology_relationship_set",ig="sy_ontology_relationship_delete",ag=Object.freeze(Object.defineProperty({__proto__:null,Client:wc,PARENT_OF_RELATIONSHIP_TYPE:Bm,RELATIONSHIP_DELETE_CHANNEL_NAME:ig,RELATIONSHIP_SET_CHANNEL_NAME:sg,RESOURCE_DELETE_CHANNEL_NAME:rg,RESOURCE_SET_CHANNEL_NAME:ng,ROOT_ID:jm,createIDFactory:G,idToString:Me,idZ:P,idsEqual:Um,matchRelationship:qm,oppositeRelationshipDirection:Dm,parseIDs:yc,relationshipToString:Lm,relationshipZ:Pm,resourceTypeZ:Pn,resourceZ:pc},Symbol.toStringTag,{value:"Module"})),Zt=i.z.uuid(),Rs=i.z.object({key:Zt,name:i.z.string(),objects:S.nullableZ(P),actions:S.nullableZ(Cs),internal:i.z.boolean()}),_s=i.z.object({key:Zt.optional(),name:i.z.string(),objects:Se.toArray(P),actions:Se.toArray(Cs)}),Ms=G("policy"),og=Ms(""),cg="sy_policy_set",ug="sy_policy_delete",lg=i.z.object({keys:Zt.array().optional(),subjects:P.array().optional(),limit:i.z.number().optional(),offset:i.z.number().optional(),internal:i.z.boolean().optional()}),hg=i.z.object({key:Zt}).transform(({key:t})=>({keys:[t]})),fg=i.z.union([i.z.object({for:P}).transform(({for:t})=>({subjects:[t]})),i.z.object({for:P.array()}).transform(({for:t})=>({subjects:t})),lg]),dg=i.z.union([hg,fg]),yg=i.z.object({policies:S.nullableZ(Rs)}),pg=_s.transform(t=>({policies:[t]})),bc=_s.array().transform(t=>({policies:t})),vc=i.z.union([pg,bc]),mg=i.z.object({policies:Rs.array()}),gg=i.z.object({keys:Zt.array()}),wg=i.z.object({});let zc=class{client;constructor(e){this.client=e}async create(e){const n=Array.isArray(e),r=await T(this.client,"/access/policy/create",e,vc,mg);return n?r.policies:r.policies[0]}async retrieve(e){const n="key"in e,r=await T(this.client,"/access/policy/retrieve",e,dg,yg);return n?r.policies[0]:r.policies}async delete(e){await T(this.client,"/access/policy/delete",{keys:S.toArray(e)},gg,wg)}};const bg=Object.freeze(Object.defineProperty({__proto__:null,Client:zc,DELETE_CHANNEL_NAME:ug,SET_CHANNEL_NAME:cg,TYPE_ONTOLOGY_ID:og,createArgsZ:vc,keyZ:Zt,multipleCreateArgsZ:bc,newZ:_s,ontologyID:Ms,policyZ:Rs},Symbol.toStringTag,{value:"Module"})),He=i.z.uuid(),Bn=i.z.object({key:He,name:i.z.string(),description:i.z.string().optional(),internal:i.z.boolean().optional()}),js=Bn.partial({key:!0}),Us=G("role"),vg=Us(""),ke=i.z.uuid(),an=i.z.object({key:ke,username:i.z.string().min(1,"Username is required"),firstName:i.z.string().default(""),lastName:i.z.string().default(""),rootUser:i.z.boolean().default(!1)}),Tc=an.omit({rootUser:!0}).partial({key:!0,firstName:!0,lastName:!0}).extend({password:i.z.string().min(1)}),zg=i.z.object({keys:ke.array().optional(),usernames:i.z.string().array().optional()}),Tg=i.z.object({key:ke}).transform(({key:t})=>({keys:[t]})),Og=i.z.object({username:i.z.string()}).transform(({username:t})=>({usernames:[t]})),Ng=i.z.object({usernames:i.z.string().array()}).transform(({usernames:t})=>({usernames:t})),Sg=i.z.union([Tg,Og,Ng,zg]),Eg=i.z.object({users:S.nullableZ(an)}),kg=i.z.object({users:Tc.array()}),Ag=i.z.object({users:an.array()}),$g=i.z.object({key:ke,username:i.z.string().min(1)}),Ig=i.z.object({}),Zg=i.z.object({key:ke,firstName:i.z.string().optional(),lastName:i.z.string().optional()}),xg=i.z.object({}),Cg=i.z.object({keys:ke.array()}),Rg=i.z.object({}),_g="sy_user_set",Mg="sy_user_delete";let Oc=class{client;constructor(e){this.client=e}async create(e){const n=Array.isArray(e),r=await T(this.client,"/user/create",{users:S.toArray(e)},kg,Ag);return n?r.users:r.users[0]}async changeUsername(e,n){await T(this.client,"/user/change-username",{key:e,username:n},$g,Ig)}async retrieve(e){const n="key"in e||"username"in e,r=await T(this.client,"/user/retrieve",e,Sg,Eg);if(!n)return r.users;if(r.users.length===0){const s="key"in e?`key ${e.key}`:`username ${e.username}`;throw new Vt(`No user with ${s} found`)}if(r.users.length>1){const s="key"in e?`key ${e.key}`:`username ${e.username}`;throw new Gt(`Multiple users found with ${s}`)}return r.users[0]}async rename(e,n,r){await T(this.client,"/user/rename",{key:e,firstName:n,lastName:r},Zg,xg)}async delete(e){await T(this.client,"/user/delete",{keys:S.toArray(e)},Cg,Rg)}};const Nc=G("user"),jg=Nc(""),Ug=Object.freeze(Object.defineProperty({__proto__:null,Client:Oc,DELETE_CHANNEL_NAME:Mg,SET_CHANNEL_NAME:_g,TYPE_ONTOLOGY_ID:jg,keyZ:ke,newZ:Tc,ontologyID:Nc,userZ:an},Symbol.toStringTag,{value:"Module"})),Dg=i.z.object({keys:He.array().optional(),limit:i.z.number().optional(),offset:i.z.number().optional(),internal:i.z.boolean().optional()}),Pg=i.z.object({key:He}).transform(({key:t})=>({keys:[t]})),Lg=js.transform(t=>({roles:[t]})),Sc=js.array().transform(t=>({roles:t})),Ec=i.z.union([Lg,Sc]),Bg=i.z.object({roles:Bn.array()}),qg=i.z.object({roles:S.nullableZ(Bn)}),kc=i.z.union([Pg,Dg]),Fg=i.z.object({}),Yg=He.transform(t=>({keys:[t]})).or(He.array().transform(t=>({keys:t}))),Vg=i.z.object({user:ke,role:He}),Gg=i.z.object({}),Hg=i.z.object({user:ke,role:He}),Wg=i.z.object({}),Kg="sy_role_set",Jg="sy_role_delete";let Ac=class{client;constructor(e){this.client=e}async create(e){const n=Array.isArray(e),r=await T(this.client,"/access/role/create",e,Ec,Bg);return n?r.roles:r.roles[0]}async retrieve(e){const n="key"in e,r=await T(this.client,"/access/role/retrieve",e,kc,qg);return n?r.roles[0]:r.roles}async delete(e){await T(this.client,"/access/role/delete",e,Yg,Fg)}async assign(e){await T(this.client,"/access/role/assign",e,Vg,Gg)}async unassign(e){await T(this.client,"/access/role/unassign",e,Hg,Wg)}};const Xg=Object.freeze(Object.defineProperty({__proto__:null,Client:Ac,DELETE_CHANNEL_NAME:Jg,SET_CHANNEL_NAME:Kg,TYPE_ONTOLOGY_ID:vg,createArgsZ:Ec,keyZ:He,multipleCreateArgsZ:Sc,newZ:js,ontologyID:Us,retrieveArgsZ:kc,roleZ:Bn},Symbol.toStringTag,{value:"Module"}));let $c=class{policies;roles;constructor(e){this.policies=new zc(e),this.roles=new Ac(e)}};const Qg=(t,e)=>{const n=S.toArray(t.objects),{action:r}=t;for(const s of n){let a=!1;for(const o of e)if(o.actions.includes(r)){for(const l of o.objects)if(l.key===""){if(l.type===s.type){a=!0;break}}else if(l.type===s.type&&l.key===s.key){a=!0;break}if(a)break}if(!a)return!1}return!0},ew=Object.freeze(Object.defineProperty({__proto__:null,Client:$c,actionZ:Cs,allowRequest:Qg,policy:bg,role:Xg},Symbol.toStringTag,{value:"Module"}));function w(t,e,n){function r(c,l){var u;Object.defineProperty(c,"_zod",{value:c._zod??{},enumerable:!1}),(u=c._zod).traits??(u.traits=new Set),c._zod.traits.add(t),e(c,l);for(const h in o.prototype)h in c||Object.defineProperty(c,h,{value:o.prototype[h].bind(c)});c._zod.constr=o,c._zod.def=l}const s=n?.Parent??Object;class a extends s{}Object.defineProperty(a,"name",{value:t});function o(c){var l;const u=n?.Parent?new a:this;r(u,c),(l=u._zod).deferred??(l.deferred=[]);for(const h of u._zod.deferred)h();return u}return Object.defineProperty(o,"init",{value:r}),Object.defineProperty(o,Symbol.hasInstance,{value:c=>n?.Parent&&c instanceof n.Parent?!0:c?._zod?.traits?.has(t)}),Object.defineProperty(o,"name",{value:t}),o}class Nt extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}class Ic extends Error{constructor(e){super(`Encountered unidirectional transform during encode: ${e}`),this.name="ZodEncodeError"}}const Zc={};function at(t){return Zc}function tw(t){const e=Object.values(t).filter(r=>typeof r=="number");return Object.entries(t).filter(([r,s])=>e.indexOf(+r)===-1).map(([r,s])=>s)}function Jr(t,e){return typeof e=="bigint"?e.toString():e}function Ds(t){return{get value(){{const e=t();return Object.defineProperty(this,"value",{value:e}),e}}}}function Ps(t){return t==null}function Ls(t){const e=t.startsWith("^")?1:0,n=t.endsWith("$")?t.length-1:t.length;return t.slice(e,n)}function nw(t,e){const n=(t.toString().split(".")[1]||"").length,r=e.toString();let s=(r.split(".")[1]||"").length;if(s===0&&/\d?e-\d?/.test(r)){const l=r.match(/\d?e-(\d?)/);l?.[1]&&(s=Number.parseInt(l[1]))}const a=n>s?n:s,o=Number.parseInt(t.toFixed(a).replace(".","")),c=Number.parseInt(e.toFixed(a).replace(".",""));return o%c/10**a}const ji=Symbol("evaluating");function U(t,e,n){let r;Object.defineProperty(t,e,{get(){if(r!==ji)return r===void 0&&(r=ji,r=n()),r},set(s){Object.defineProperty(t,e,{value:s})},configurable:!0})}function ft(t,e,n){Object.defineProperty(t,e,{value:n,writable:!0,enumerable:!0,configurable:!0})}function dt(...t){const e={};for(const n of t){const r=Object.getOwnPropertyDescriptors(n);Object.assign(e,r)}return Object.defineProperties({},e)}function Ui(t){return JSON.stringify(t)}const xc="captureStackTrace"in Error?Error.captureStackTrace:(...t)=>{};function In(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}const rw=Ds(()=>{if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{const t=Function;return new t(""),!0}catch{return!1}});function Ht(t){if(In(t)===!1)return!1;const e=t.constructor;if(e===void 0)return!0;const n=e.prototype;return!(In(n)===!1||Object.prototype.hasOwnProperty.call(n,"isPrototypeOf")===!1)}function Cc(t){return Ht(t)?{...t}:Array.isArray(t)?[...t]:t}const sw=new Set(["string","number","symbol"]);function qn(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function We(t,e,n){const r=new t._zod.constr(e??t._zod.def);return(!e||n?.parent)&&(r._zod.parent=t),r}function k(t){const e=t;if(!e)return{};if(typeof e=="string")return{error:()=>e};if(e?.message!==void 0){if(e?.error!==void 0)throw new Error("Cannot specify both `message` and `error` params");e.error=e.message}return delete e.message,typeof e.error=="string"?{...e,error:()=>e.error}:e}function iw(t){return Object.keys(t).filter(e=>t[e]._zod.optin==="optional"&&t[e]._zod.optout==="optional")}const aw={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]};function ow(t,e){const n=t._zod.def,r=dt(t._zod.def,{get shape(){const s={};for(const a in e){if(!(a in n.shape))throw new Error(`Unrecognized key: "${a}"`);e[a]&&(s[a]=n.shape[a])}return ft(this,"shape",s),s},checks:[]});return We(t,r)}function cw(t,e){const n=t._zod.def,r=dt(t._zod.def,{get shape(){const s={...t._zod.def.shape};for(const a in e){if(!(a in n.shape))throw new Error(`Unrecognized key: "${a}"`);e[a]&&delete s[a]}return ft(this,"shape",s),s},checks:[]});return We(t,r)}function uw(t,e){if(!Ht(e))throw new Error("Invalid input to extend: expected a plain object");const n=t._zod.def.checks;if(n&&n.length>0)throw new Error("Object schemas containing refinements cannot be extended. Use `.safeExtend()` instead.");const s=dt(t._zod.def,{get shape(){const a={...t._zod.def.shape,...e};return ft(this,"shape",a),a},checks:[]});return We(t,s)}function lw(t,e){if(!Ht(e))throw new Error("Invalid input to safeExtend: expected a plain object");const n={...t._zod.def,get shape(){const r={...t._zod.def.shape,...e};return ft(this,"shape",r),r},checks:t._zod.def.checks};return We(t,n)}function hw(t,e){const n=dt(t._zod.def,{get shape(){const r={...t._zod.def.shape,...e._zod.def.shape};return ft(this,"shape",r),r},get catchall(){return e._zod.def.catchall},checks:[]});return We(t,n)}function fw(t,e,n){const r=dt(e._zod.def,{get shape(){const s=e._zod.def.shape,a={...s};if(n)for(const o in n){if(!(o in s))throw new Error(`Unrecognized key: "${o}"`);n[o]&&(a[o]=t?new t({type:"optional",innerType:s[o]}):s[o])}else for(const o in s)a[o]=t?new t({type:"optional",innerType:s[o]}):s[o];return ft(this,"shape",a),a},checks:[]});return We(e,r)}function dw(t,e,n){const r=dt(e._zod.def,{get shape(){const s=e._zod.def.shape,a={...s};if(n)for(const o in n){if(!(o in a))throw new Error(`Unrecognized key: "${o}"`);n[o]&&(a[o]=new t({type:"nonoptional",innerType:s[o]}))}else for(const o in s)a[o]=new t({type:"nonoptional",innerType:s[o]});return ft(this,"shape",a),a},checks:[]});return We(e,r)}function vt(t,e=0){if(t.aborted===!0)return!0;for(let n=e;n<t.issues.length;n++)if(t.issues[n]?.continue!==!0)return!0;return!1}function Rc(t,e){return e.map(n=>{var r;return(r=n).path??(r.path=[]),n.path.unshift(t),n})}function On(t){return typeof t=="string"?t:t?.message}function ot(t,e,n){const r={...t,path:t.path??[]};if(!t.message){const s=On(t.inst?._zod.def?.error?.(t))??On(e?.error?.(t))??On(n.customError?.(t))??On(n.localeError?.(t))??"Invalid input";r.message=s}return delete r.inst,delete r.continue,e?.reportInput||delete r.input,r}function Bs(t){return Array.isArray(t)?"array":typeof t=="string"?"string":"unknown"}function Wt(...t){const[e,n,r]=t;return typeof e=="string"?{message:e,code:"custom",input:n,inst:r}:{...e}}const _c=(t,e)=>{t.name="$ZodError",Object.defineProperty(t,"_zod",{value:t._zod,enumerable:!1}),Object.defineProperty(t,"issues",{value:e,enumerable:!1}),t.message=JSON.stringify(e,Jr,2),Object.defineProperty(t,"toString",{value:()=>t.message,enumerable:!1})},Mc=w("$ZodError",_c),jc=w("$ZodError",_c,{Parent:Error});function yw(t,e=n=>n.message){const n={},r=[];for(const s of t.issues)s.path.length>0?(n[s.path[0]]=n[s.path[0]]||[],n[s.path[0]].push(e(s))):r.push(e(s));return{formErrors:r,fieldErrors:n}}function pw(t,e=n=>n.message){const n={_errors:[]},r=s=>{for(const a of s.issues)if(a.code==="invalid_union"&&a.errors.length)a.errors.map(o=>r({issues:o}));else if(a.code==="invalid_key")r({issues:a.issues});else if(a.code==="invalid_element")r({issues:a.issues});else if(a.path.length===0)n._errors.push(e(a));else{let o=n,c=0;for(;c<a.path.length;){const l=a.path[c];c===a.path.length-1?(o[l]=o[l]||{_errors:[]},o[l]._errors.push(e(a))):o[l]=o[l]||{_errors:[]},o=o[l],c++}}};return r(t),n}const qs=t=>(e,n,r,s)=>{const a=r?Object.assign(r,{async:!1}):{async:!1},o=e._zod.run({value:n,issues:[]},a);if(o instanceof Promise)throw new Nt;if(o.issues.length){const c=new(s?.Err??t)(o.issues.map(l=>ot(l,a,at())));throw xc(c,s?.callee),c}return o.value},Fs=t=>async(e,n,r,s)=>{const a=r?Object.assign(r,{async:!0}):{async:!0};let o=e._zod.run({value:n,issues:[]},a);if(o instanceof Promise&&(o=await o),o.issues.length){const c=new(s?.Err??t)(o.issues.map(l=>ot(l,a,at())));throw xc(c,s?.callee),c}return o.value},Fn=t=>(e,n,r)=>{const s=r?{...r,async:!1}:{async:!1},a=e._zod.run({value:n,issues:[]},s);if(a instanceof Promise)throw new Nt;return a.issues.length?{success:!1,error:new(t??Mc)(a.issues.map(o=>ot(o,s,at())))}:{success:!0,data:a.value}},mw=Fn(jc),Yn=t=>async(e,n,r)=>{const s=r?Object.assign(r,{async:!0}):{async:!0};let a=e._zod.run({value:n,issues:[]},s);return a instanceof Promise&&(a=await a),a.issues.length?{success:!1,error:new t(a.issues.map(o=>ot(o,s,at())))}:{success:!0,data:a.value}},gw=Yn(jc),ww=t=>(e,n,r)=>{const s=r?Object.assign(r,{direction:"backward"}):{direction:"backward"};return qs(t)(e,n,s)},bw=t=>(e,n,r)=>qs(t)(e,n,r),vw=t=>async(e,n,r)=>{const s=r?Object.assign(r,{direction:"backward"}):{direction:"backward"};return Fs(t)(e,n,s)},zw=t=>async(e,n,r)=>Fs(t)(e,n,r),Tw=t=>(e,n,r)=>{const s=r?Object.assign(r,{direction:"backward"}):{direction:"backward"};return Fn(t)(e,n,s)},Ow=t=>(e,n,r)=>Fn(t)(e,n,r),Nw=t=>async(e,n,r)=>{const s=r?Object.assign(r,{direction:"backward"}):{direction:"backward"};return Yn(t)(e,n,s)},Sw=t=>async(e,n,r)=>Yn(t)(e,n,r),Ew=/^[cC][^\s-]{8,}$/,kw=/^[0-9a-z]+$/,Aw=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,$w=/^[0-9a-vA-V]{20}$/,Iw=/^[A-Za-z0-9]{27}$/,Zw=/^[a-zA-Z0-9_-]{21}$/,xw=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,Cw=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,Di=t=>t?new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${t}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`):/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/,Rw=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,_w="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function Mw(){return new RegExp(_w,"u")}const jw=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,Uw=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))$/,Dw=/^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/,Pw=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,Lw=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,Uc=/^[A-Za-z0-9_-]*$/,Bw=/^(?=.{1,253}\.?$)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[-0-9a-zA-Z]{0,61}[0-9a-zA-Z])?)*\.?$/,qw=/^\+(?:[0-9]){6,14}[0-9]$/,Dc="(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))",Fw=new RegExp(`^${Dc}$`);function Pc(t){const e="(?:[01]\\d|2[0-3]):[0-5]\\d";return typeof t.precision=="number"?t.precision===-1?`${e}`:t.precision===0?`${e}:[0-5]\\d`:`${e}:[0-5]\\d\\.\\d{${t.precision}}`:`${e}(?::[0-5]\\d(?:\\.\\d+)?)?`}function Yw(t){return new RegExp(`^${Pc(t)}$`)}function Vw(t){const e=Pc({precision:t.precision}),n=["Z"];t.local&&n.push(""),t.offset&&n.push("([+-](?:[01]\\d|2[0-3]):[0-5]\\d)");const r=`${e}(?:${n.join("|")})`;return new RegExp(`^${Dc}T(?:${r})$`)}const Gw=t=>{const e=t?`[\\s\\S]{${t?.minimum??0},${t?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${e}$`)},Hw=/^-?\d+$/,Ww=/^-?\d+(?:\.\d+)?/,Kw=/^(?:true|false)$/i,Jw=/^[^A-Z]*$/,Xw=/^[^a-z]*$/,re=w("$ZodCheck",(t,e)=>{var n;t._zod??(t._zod={}),t._zod.def=e,(n=t._zod).onattach??(n.onattach=[])}),Lc={number:"number",bigint:"bigint",object:"date"},Bc=w("$ZodCheckLessThan",(t,e)=>{re.init(t,e);const n=Lc[typeof e.value];t._zod.onattach.push(r=>{const s=r._zod.bag,a=(e.inclusive?s.maximum:s.exclusiveMaximum)??Number.POSITIVE_INFINITY;e.value<a&&(e.inclusive?s.maximum=e.value:s.exclusiveMaximum=e.value)}),t._zod.check=r=>{(e.inclusive?r.value<=e.value:r.value<e.value)||r.issues.push({origin:n,code:"too_big",maximum:e.value,input:r.value,inclusive:e.inclusive,inst:t,continue:!e.abort})}}),qc=w("$ZodCheckGreaterThan",(t,e)=>{re.init(t,e);const n=Lc[typeof e.value];t._zod.onattach.push(r=>{const s=r._zod.bag,a=(e.inclusive?s.minimum:s.exclusiveMinimum)??Number.NEGATIVE_INFINITY;e.value>a&&(e.inclusive?s.minimum=e.value:s.exclusiveMinimum=e.value)}),t._zod.check=r=>{(e.inclusive?r.value>=e.value:r.value>e.value)||r.issues.push({origin:n,code:"too_small",minimum:e.value,input:r.value,inclusive:e.inclusive,inst:t,continue:!e.abort})}}),Qw=w("$ZodCheckMultipleOf",(t,e)=>{re.init(t,e),t._zod.onattach.push(n=>{var r;(r=n._zod.bag).multipleOf??(r.multipleOf=e.value)}),t._zod.check=n=>{if(typeof n.value!=typeof e.value)throw new Error("Cannot mix number and bigint in multiple_of check.");(typeof n.value=="bigint"?n.value%e.value===BigInt(0):nw(n.value,e.value)===0)||n.issues.push({origin:typeof n.value,code:"not_multiple_of",divisor:e.value,input:n.value,inst:t,continue:!e.abort})}}),eb=w("$ZodCheckNumberFormat",(t,e)=>{re.init(t,e),e.format=e.format||"float64";const n=e.format?.includes("int"),r=n?"int":"number",[s,a]=aw[e.format];t._zod.onattach.push(o=>{const c=o._zod.bag;c.format=e.format,c.minimum=s,c.maximum=a,n&&(c.pattern=Hw)}),t._zod.check=o=>{const c=o.value;if(n){if(!Number.isInteger(c)){o.issues.push({expected:r,format:e.format,code:"invalid_type",continue:!1,input:c,inst:t});return}if(!Number.isSafeInteger(c)){c>0?o.issues.push({input:c,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:t,origin:r,continue:!e.abort}):o.issues.push({input:c,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:t,origin:r,continue:!e.abort});return}}c<s&&o.issues.push({origin:"number",input:c,code:"too_small",minimum:s,inclusive:!0,inst:t,continue:!e.abort}),c>a&&o.issues.push({origin:"number",input:c,code:"too_big",maximum:a,inst:t})}}),tb=w("$ZodCheckMaxLength",(t,e)=>{var n;re.init(t,e),(n=t._zod.def).when??(n.when=r=>{const s=r.value;return!Ps(s)&&s.length!==void 0}),t._zod.onattach.push(r=>{const s=r._zod.bag.maximum??Number.POSITIVE_INFINITY;e.maximum<s&&(r._zod.bag.maximum=e.maximum)}),t._zod.check=r=>{const s=r.value;if(s.length<=e.maximum)return;const o=Bs(s);r.issues.push({origin:o,code:"too_big",maximum:e.maximum,inclusive:!0,input:s,inst:t,continue:!e.abort})}}),nb=w("$ZodCheckMinLength",(t,e)=>{var n;re.init(t,e),(n=t._zod.def).when??(n.when=r=>{const s=r.value;return!Ps(s)&&s.length!==void 0}),t._zod.onattach.push(r=>{const s=r._zod.bag.minimum??Number.NEGATIVE_INFINITY;e.minimum>s&&(r._zod.bag.minimum=e.minimum)}),t._zod.check=r=>{const s=r.value;if(s.length>=e.minimum)return;const o=Bs(s);r.issues.push({origin:o,code:"too_small",minimum:e.minimum,inclusive:!0,input:s,inst:t,continue:!e.abort})}}),rb=w("$ZodCheckLengthEquals",(t,e)=>{var n;re.init(t,e),(n=t._zod.def).when??(n.when=r=>{const s=r.value;return!Ps(s)&&s.length!==void 0}),t._zod.onattach.push(r=>{const s=r._zod.bag;s.minimum=e.length,s.maximum=e.length,s.length=e.length}),t._zod.check=r=>{const s=r.value,a=s.length;if(a===e.length)return;const o=Bs(s),c=a>e.length;r.issues.push({origin:o,...c?{code:"too_big",maximum:e.length}:{code:"too_small",minimum:e.length},inclusive:!0,exact:!0,input:r.value,inst:t,continue:!e.abort})}}),Vn=w("$ZodCheckStringFormat",(t,e)=>{var n,r;re.init(t,e),t._zod.onattach.push(s=>{const a=s._zod.bag;a.format=e.format,e.pattern&&(a.patterns??(a.patterns=new Set),a.patterns.add(e.pattern))}),e.pattern?(n=t._zod).check??(n.check=s=>{e.pattern.lastIndex=0,!e.pattern.test(s.value)&&s.issues.push({origin:"string",code:"invalid_format",format:e.format,input:s.value,...e.pattern?{pattern:e.pattern.toString()}:{},inst:t,continue:!e.abort})}):(r=t._zod).check??(r.check=()=>{})}),sb=w("$ZodCheckRegex",(t,e)=>{Vn.init(t,e),t._zod.check=n=>{e.pattern.lastIndex=0,!e.pattern.test(n.value)&&n.issues.push({origin:"string",code:"invalid_format",format:"regex",input:n.value,pattern:e.pattern.toString(),inst:t,continue:!e.abort})}}),ib=w("$ZodCheckLowerCase",(t,e)=>{e.pattern??(e.pattern=Jw),Vn.init(t,e)}),ab=w("$ZodCheckUpperCase",(t,e)=>{e.pattern??(e.pattern=Xw),Vn.init(t,e)}),ob=w("$ZodCheckIncludes",(t,e)=>{re.init(t,e);const n=qn(e.includes),r=new RegExp(typeof e.position=="number"?`^.{${e.position}}${n}`:n);e.pattern=r,t._zod.onattach.push(s=>{const a=s._zod.bag;a.patterns??(a.patterns=new Set),a.patterns.add(r)}),t._zod.check=s=>{s.value.includes(e.includes,e.position)||s.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:e.includes,input:s.value,inst:t,continue:!e.abort})}}),cb=w("$ZodCheckStartsWith",(t,e)=>{re.init(t,e);const n=new RegExp(`^${qn(e.prefix)}.*`);e.pattern??(e.pattern=n),t._zod.onattach.push(r=>{const s=r._zod.bag;s.patterns??(s.patterns=new Set),s.patterns.add(n)}),t._zod.check=r=>{r.value.startsWith(e.prefix)||r.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:e.prefix,input:r.value,inst:t,continue:!e.abort})}}),ub=w("$ZodCheckEndsWith",(t,e)=>{re.init(t,e);const n=new RegExp(`.*${qn(e.suffix)}$`);e.pattern??(e.pattern=n),t._zod.onattach.push(r=>{const s=r._zod.bag;s.patterns??(s.patterns=new Set),s.patterns.add(n)}),t._zod.check=r=>{r.value.endsWith(e.suffix)||r.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:e.suffix,input:r.value,inst:t,continue:!e.abort})}}),lb=w("$ZodCheckOverwrite",(t,e)=>{re.init(t,e),t._zod.check=n=>{n.value=e.tx(n.value)}});class hb{constructor(e=[]){this.content=[],this.indent=0,this&&(this.args=e)}indented(e){this.indent+=1,e(this),this.indent-=1}write(e){if(typeof e=="function"){e(this,{execution:"sync"}),e(this,{execution:"async"});return}const r=e.split(`
22
22
  `).filter(o=>o),s=Math.min(...r.map(o=>o.length-o.trimStart().length)),a=r.map(o=>o.slice(s)).map(o=>" ".repeat(this.indent*2)+o);for(const o of a)this.content.push(o)}compile(){const e=Function,n=this?.args,s=[...(this?.content??[""]).map(a=>` ${a}`)];return new e(...n,s.join(`
23
- `))}}const Qw={major:4,minor:1,patch:12},B=w("$ZodType",(t,e)=>{var n;t??(t={}),t._zod.def=e,t._zod.bag=t._zod.bag||{},t._zod.version=Qw;const r=[...t._zod.def.checks??[]];t._zod.traits.has("$ZodCheck")&&r.unshift(t);for(const s of r)for(const a of s._zod.onattach)a(t);if(r.length===0)(n=t._zod).deferred??(n.deferred=[]),t._zod.deferred?.push(()=>{t._zod.run=t._zod.parse});else{const s=(o,c,l)=>{let u=gt(o),h;for(const y of c){if(y._zod.def.when){if(!y._zod.def.when(o))continue}else if(u)continue;const f=o.issues.length,T=y._zod.check(o);if(T instanceof Promise&&l?.async===!1)throw new Tt;if(h||T instanceof Promise)h=(h??Promise.resolve()).then(async()=>{await T,o.issues.length!==f&&(u||(u=gt(o,f)))});else{if(o.issues.length===f)continue;u||(u=gt(o,f))}}return h?h.then(()=>o):o},a=(o,c,l)=>{if(gt(o))return o.aborted=!0,o;const u=s(c,r,l);if(u instanceof Promise){if(l.async===!1)throw new Tt;return u.then(h=>t._zod.parse(h,l))}return t._zod.parse(u,l)};t._zod.run=(o,c)=>{if(c.skipChecks)return t._zod.parse(o,c);if(c.direction==="backward"){const u=t._zod.parse({value:o.value,issues:[]},{...c,skipChecks:!0});return u instanceof Promise?u.then(h=>a(h,o,c)):a(u,o,c)}const l=t._zod.parse(o,c);if(l instanceof Promise){if(c.async===!1)throw new Tt;return l.then(u=>s(u,r,c))}return s(l,r,c)}}t["~standard"]={validate:s=>{try{const a=rw(t,s);return a.success?{value:a.data}:{issues:a.error?.issues}}catch{return sw(t,s).then(o=>o.success?{value:o.data}:{issues:o.error?.issues})}},vendor:"zod",version:1}}),qs=w("$ZodString",(t,e)=>{B.init(t,e),t._zod.pattern=[...t?._zod.bag?.patterns??[]].pop()??Rw(t._zod.bag),t._zod.parse=(n,r)=>{if(e.coerce)try{n.value=String(n.value)}catch{}return typeof n.value=="string"||n.issues.push({expected:"string",code:"invalid_type",input:n.value,inst:t}),n}}),D=w("$ZodStringFormat",(t,e)=>{Fn.init(t,e),qs.init(t,e)}),eb=w("$ZodGUID",(t,e)=>{e.pattern??(e.pattern=vw),D.init(t,e)}),tb=w("$ZodUUID",(t,e)=>{if(e.version){const r={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[e.version];if(r===void 0)throw new Error(`Invalid UUID version: "${e.version}"`);e.pattern??(e.pattern=_i(r))}else e.pattern??(e.pattern=_i());D.init(t,e)}),nb=w("$ZodEmail",(t,e)=>{e.pattern??(e.pattern=zw),D.init(t,e)}),rb=w("$ZodURL",(t,e)=>{D.init(t,e),t._zod.check=n=>{try{const r=n.value.trim(),s=new URL(r);e.hostname&&(e.hostname.lastIndex=0,e.hostname.test(s.hostname)||n.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:$w.source,input:n.value,inst:t,continue:!e.abort})),e.protocol&&(e.protocol.lastIndex=0,e.protocol.test(s.protocol.endsWith(":")?s.protocol.slice(0,-1):s.protocol)||n.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:e.protocol.source,input:n.value,inst:t,continue:!e.abort})),e.normalize?n.value=s.href:n.value=r;return}catch{n.issues.push({code:"invalid_format",format:"url",input:n.value,inst:t,continue:!e.abort})}}}),sb=w("$ZodEmoji",(t,e)=>{e.pattern??(e.pattern=Ow()),D.init(t,e)}),ib=w("$ZodNanoID",(t,e)=>{e.pattern??(e.pattern=ww),D.init(t,e)}),ab=w("$ZodCUID",(t,e)=>{e.pattern??(e.pattern=dw),D.init(t,e)}),ob=w("$ZodCUID2",(t,e)=>{e.pattern??(e.pattern=yw),D.init(t,e)}),cb=w("$ZodULID",(t,e)=>{e.pattern??(e.pattern=pw),D.init(t,e)}),ub=w("$ZodXID",(t,e)=>{e.pattern??(e.pattern=mw),D.init(t,e)}),lb=w("$ZodKSUID",(t,e)=>{e.pattern??(e.pattern=gw),D.init(t,e)}),hb=w("$ZodISODateTime",(t,e)=>{e.pattern??(e.pattern=Cw(e)),D.init(t,e)}),fb=w("$ZodISODate",(t,e)=>{e.pattern??(e.pattern=Zw),D.init(t,e)}),db=w("$ZodISOTime",(t,e)=>{e.pattern??(e.pattern=xw(e)),D.init(t,e)}),yb=w("$ZodISODuration",(t,e)=>{e.pattern??(e.pattern=bw),D.init(t,e)}),pb=w("$ZodIPv4",(t,e)=>{e.pattern??(e.pattern=Ew),D.init(t,e),t._zod.onattach.push(n=>{const r=n._zod.bag;r.format="ipv4"})}),mb=w("$ZodIPv6",(t,e)=>{e.pattern??(e.pattern=Nw),D.init(t,e),t._zod.onattach.push(n=>{const r=n._zod.bag;r.format="ipv6"}),t._zod.check=n=>{try{new URL(`http://[${n.value}]`)}catch{n.issues.push({code:"invalid_format",format:"ipv6",input:n.value,inst:t,continue:!e.abort})}}}),gb=w("$ZodCIDRv4",(t,e)=>{e.pattern??(e.pattern=Sw),D.init(t,e)}),wb=w("$ZodCIDRv6",(t,e)=>{e.pattern??(e.pattern=kw),D.init(t,e),t._zod.check=n=>{const r=n.value.split("/");try{if(r.length!==2)throw new Error;const[s,a]=r;if(!a)throw new Error;const o=Number(a);if(`${o}`!==a)throw new Error;if(o<0||o>128)throw new Error;new URL(`http://[${s}]`)}catch{n.issues.push({code:"invalid_format",format:"cidrv6",input:n.value,inst:t,continue:!e.abort})}}});function jc(t){if(t==="")return!0;if(t.length%4!==0)return!1;try{return atob(t),!0}catch{return!1}}const bb=w("$ZodBase64",(t,e)=>{e.pattern??(e.pattern=Aw),D.init(t,e),t._zod.onattach.push(n=>{n._zod.bag.contentEncoding="base64"}),t._zod.check=n=>{jc(n.value)||n.issues.push({code:"invalid_format",format:"base64",input:n.value,inst:t,continue:!e.abort})}});function vb(t){if(!Zc.test(t))return!1;const e=t.replace(/[-_]/g,r=>r==="-"?"+":"/"),n=e.padEnd(Math.ceil(e.length/4)*4,"=");return jc(n)}const zb=w("$ZodBase64URL",(t,e)=>{e.pattern??(e.pattern=Zc),D.init(t,e),t._zod.onattach.push(n=>{n._zod.bag.contentEncoding="base64url"}),t._zod.check=n=>{vb(n.value)||n.issues.push({code:"invalid_format",format:"base64url",input:n.value,inst:t,continue:!e.abort})}}),Tb=w("$ZodE164",(t,e)=>{e.pattern??(e.pattern=Iw),D.init(t,e)});function Ob(t,e=null){try{const n=t.split(".");if(n.length!==3)return!1;const[r]=n;if(!r)return!1;const s=JSON.parse(atob(r));return!("typ"in s&&s?.typ!=="JWT"||!s.alg||e&&(!("alg"in s)||s.alg!==e))}catch{return!1}}const Eb=w("$ZodJWT",(t,e)=>{D.init(t,e),t._zod.check=n=>{Ob(n.value,e.alg)||n.issues.push({code:"invalid_format",format:"jwt",input:n.value,inst:t,continue:!e.abort})}}),Uc=w("$ZodNumber",(t,e)=>{B.init(t,e),t._zod.pattern=t._zod.bag.pattern??Mw,t._zod.parse=(n,r)=>{if(e.coerce)try{n.value=Number(n.value)}catch{}const s=n.value;if(typeof s=="number"&&!Number.isNaN(s)&&Number.isFinite(s))return n;const a=typeof s=="number"?Number.isNaN(s)?"NaN":Number.isFinite(s)?void 0:"Infinity":void 0;return n.issues.push({expected:"number",code:"invalid_type",input:s,inst:t,...a?{received:a}:{}}),n}}),Nb=w("$ZodNumber",(t,e)=>{Pw.init(t,e),Uc.init(t,e)}),Sb=w("$ZodBoolean",(t,e)=>{B.init(t,e),t._zod.pattern=jw,t._zod.parse=(n,r)=>{if(e.coerce)try{n.value=!!n.value}catch{}const s=n.value;return typeof s=="boolean"||n.issues.push({expected:"boolean",code:"invalid_type",input:s,inst:t}),n}}),kb=w("$ZodUnknown",(t,e)=>{B.init(t,e),t._zod.parse=n=>n}),Ab=w("$ZodNever",(t,e)=>{B.init(t,e),t._zod.parse=(n,r)=>(n.issues.push({expected:"never",code:"invalid_type",input:n.value,inst:t}),n)});function Mi(t,e,n){t.issues.length&&e.issues.push(...kc(n,t.issues)),e.value[n]=t.value}const $b=w("$ZodArray",(t,e)=>{B.init(t,e),t._zod.parse=(n,r)=>{const s=n.value;if(!Array.isArray(s))return n.issues.push({expected:"array",code:"invalid_type",input:s,inst:t}),n;n.value=Array(s.length);const a=[];for(let o=0;o<s.length;o++){const c=s[o],l=e.element._zod.run({value:c,issues:[]},r);l instanceof Promise?a.push(l.then(u=>Mi(u,n,o))):Mi(l,n,o)}return a.length?Promise.all(a).then(()=>n):n}});function $n(t,e,n,r){t.issues.length&&e.issues.push(...kc(n,t.issues)),t.value===void 0?n in r&&(e.value[n]=void 0):e.value[n]=t.value}function Dc(t){const e=Object.keys(t.shape);for(const r of e)if(!t.shape?.[r]?._zod?.traits?.has("$ZodType"))throw new Error(`Invalid element at key "${r}": expected a Zod schema`);const n=Hg(t.shape);return{...t,keys:e,keySet:new Set(e),numKeys:e.length,optionalKeys:new Set(n)}}function Lc(t,e,n,r,s,a){const o=[],c=s.keySet,l=s.catchall._zod,u=l.def.type;for(const h of Object.keys(e)){if(c.has(h))continue;if(u==="never"){o.push(h);continue}const y=l.run({value:e[h],issues:[]},r);y instanceof Promise?t.push(y.then(f=>$n(f,n,h,e))):$n(y,n,h,e)}return o.length&&n.issues.push({code:"unrecognized_keys",keys:o,input:e,inst:a}),t.length?Promise.all(t).then(()=>n):n}const Ib=w("$ZodObject",(t,e)=>{if(B.init(t,e),!Object.getOwnPropertyDescriptor(e,"shape")?.get){const c=e.shape;Object.defineProperty(e,"shape",{get:()=>{const l={...c};return Object.defineProperty(e,"shape",{value:l}),l}})}const r=js(()=>Dc(e));j(t._zod,"propValues",()=>{const c=e.shape,l={};for(const u in c){const h=c[u]._zod;if(h.values){l[u]??(l[u]=new Set);for(const y of h.values)l[u].add(y)}}return l});const s=An,a=e.catchall;let o;t._zod.parse=(c,l)=>{o??(o=r.value);const u=c.value;if(!s(u))return c.issues.push({expected:"object",code:"invalid_type",input:u,inst:t}),c;c.value={};const h=[],y=o.shape;for(const f of o.keys){const S=y[f]._zod.run({value:u[f],issues:[]},l);S instanceof Promise?h.push(S.then(x=>$n(x,c,f,u))):$n(S,c,f,u)}return a?Lc(h,u,c,l,r.value,t):h.length?Promise.all(h).then(()=>c):c}}),Zb=w("$ZodObjectJIT",(t,e)=>{Ib.init(t,e);const n=t._zod.parse,r=js(()=>Dc(e)),s=f=>{const T=new Xw(["shape","payload","ctx"]),S=r.value,x=G=>{const q=Ri(G);return`shape[${q}]._zod.run({ value: input[${q}], issues: [] }, ctx)`};T.write("const input = payload.value;");const O=Object.create(null);let N=0;for(const G of S.keys)O[G]=`key_${N++}`;T.write("const newResult = {};");for(const G of S.keys){const q=O[G],ue=Ri(G);T.write(`const ${q} = ${x(G)};`),T.write(`
24
- if (${q}.issues.length) {
25
- payload.issues = payload.issues.concat(${q}.issues.map(iss => ({
23
+ `))}}const fb={major:4,minor:1,patch:12},F=w("$ZodType",(t,e)=>{var n;t??(t={}),t._zod.def=e,t._zod.bag=t._zod.bag||{},t._zod.version=fb;const r=[...t._zod.def.checks??[]];t._zod.traits.has("$ZodCheck")&&r.unshift(t);for(const s of r)for(const a of s._zod.onattach)a(t);if(r.length===0)(n=t._zod).deferred??(n.deferred=[]),t._zod.deferred?.push(()=>{t._zod.run=t._zod.parse});else{const s=(o,c,l)=>{let u=vt(o),h;for(const d of c){if(d._zod.def.when){if(!d._zod.def.when(o))continue}else if(u)continue;const f=o.issues.length,O=d._zod.check(o);if(O instanceof Promise&&l?.async===!1)throw new Nt;if(h||O instanceof Promise)h=(h??Promise.resolve()).then(async()=>{await O,o.issues.length!==f&&(u||(u=vt(o,f)))});else{if(o.issues.length===f)continue;u||(u=vt(o,f))}}return h?h.then(()=>o):o},a=(o,c,l)=>{if(vt(o))return o.aborted=!0,o;const u=s(c,r,l);if(u instanceof Promise){if(l.async===!1)throw new Nt;return u.then(h=>t._zod.parse(h,l))}return t._zod.parse(u,l)};t._zod.run=(o,c)=>{if(c.skipChecks)return t._zod.parse(o,c);if(c.direction==="backward"){const u=t._zod.parse({value:o.value,issues:[]},{...c,skipChecks:!0});return u instanceof Promise?u.then(h=>a(h,o,c)):a(u,o,c)}const l=t._zod.parse(o,c);if(l instanceof Promise){if(c.async===!1)throw new Nt;return l.then(u=>s(u,r,c))}return s(l,r,c)}}t["~standard"]={validate:s=>{try{const a=mw(t,s);return a.success?{value:a.data}:{issues:a.error?.issues}}catch{return gw(t,s).then(o=>o.success?{value:o.data}:{issues:o.error?.issues})}},vendor:"zod",version:1}}),Ys=w("$ZodString",(t,e)=>{F.init(t,e),t._zod.pattern=[...t?._zod.bag?.patterns??[]].pop()??Gw(t._zod.bag),t._zod.parse=(n,r)=>{if(e.coerce)try{n.value=String(n.value)}catch{}return typeof n.value=="string"||n.issues.push({expected:"string",code:"invalid_type",input:n.value,inst:t}),n}}),L=w("$ZodStringFormat",(t,e)=>{Vn.init(t,e),Ys.init(t,e)}),db=w("$ZodGUID",(t,e)=>{e.pattern??(e.pattern=Cw),L.init(t,e)}),yb=w("$ZodUUID",(t,e)=>{if(e.version){const r={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[e.version];if(r===void 0)throw new Error(`Invalid UUID version: "${e.version}"`);e.pattern??(e.pattern=Di(r))}else e.pattern??(e.pattern=Di());L.init(t,e)}),pb=w("$ZodEmail",(t,e)=>{e.pattern??(e.pattern=Rw),L.init(t,e)}),mb=w("$ZodURL",(t,e)=>{L.init(t,e),t._zod.check=n=>{try{const r=n.value.trim(),s=new URL(r);e.hostname&&(e.hostname.lastIndex=0,e.hostname.test(s.hostname)||n.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:Bw.source,input:n.value,inst:t,continue:!e.abort})),e.protocol&&(e.protocol.lastIndex=0,e.protocol.test(s.protocol.endsWith(":")?s.protocol.slice(0,-1):s.protocol)||n.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:e.protocol.source,input:n.value,inst:t,continue:!e.abort})),e.normalize?n.value=s.href:n.value=r;return}catch{n.issues.push({code:"invalid_format",format:"url",input:n.value,inst:t,continue:!e.abort})}}}),gb=w("$ZodEmoji",(t,e)=>{e.pattern??(e.pattern=Mw()),L.init(t,e)}),wb=w("$ZodNanoID",(t,e)=>{e.pattern??(e.pattern=Zw),L.init(t,e)}),bb=w("$ZodCUID",(t,e)=>{e.pattern??(e.pattern=Ew),L.init(t,e)}),vb=w("$ZodCUID2",(t,e)=>{e.pattern??(e.pattern=kw),L.init(t,e)}),zb=w("$ZodULID",(t,e)=>{e.pattern??(e.pattern=Aw),L.init(t,e)}),Tb=w("$ZodXID",(t,e)=>{e.pattern??(e.pattern=$w),L.init(t,e)}),Ob=w("$ZodKSUID",(t,e)=>{e.pattern??(e.pattern=Iw),L.init(t,e)}),Nb=w("$ZodISODateTime",(t,e)=>{e.pattern??(e.pattern=Vw(e)),L.init(t,e)}),Sb=w("$ZodISODate",(t,e)=>{e.pattern??(e.pattern=Fw),L.init(t,e)}),Eb=w("$ZodISOTime",(t,e)=>{e.pattern??(e.pattern=Yw(e)),L.init(t,e)}),kb=w("$ZodISODuration",(t,e)=>{e.pattern??(e.pattern=xw),L.init(t,e)}),Ab=w("$ZodIPv4",(t,e)=>{e.pattern??(e.pattern=jw),L.init(t,e),t._zod.onattach.push(n=>{const r=n._zod.bag;r.format="ipv4"})}),$b=w("$ZodIPv6",(t,e)=>{e.pattern??(e.pattern=Uw),L.init(t,e),t._zod.onattach.push(n=>{const r=n._zod.bag;r.format="ipv6"}),t._zod.check=n=>{try{new URL(`http://[${n.value}]`)}catch{n.issues.push({code:"invalid_format",format:"ipv6",input:n.value,inst:t,continue:!e.abort})}}}),Ib=w("$ZodCIDRv4",(t,e)=>{e.pattern??(e.pattern=Dw),L.init(t,e)}),Zb=w("$ZodCIDRv6",(t,e)=>{e.pattern??(e.pattern=Pw),L.init(t,e),t._zod.check=n=>{const r=n.value.split("/");try{if(r.length!==2)throw new Error;const[s,a]=r;if(!a)throw new Error;const o=Number(a);if(`${o}`!==a)throw new Error;if(o<0||o>128)throw new Error;new URL(`http://[${s}]`)}catch{n.issues.push({code:"invalid_format",format:"cidrv6",input:n.value,inst:t,continue:!e.abort})}}});function Fc(t){if(t==="")return!0;if(t.length%4!==0)return!1;try{return atob(t),!0}catch{return!1}}const xb=w("$ZodBase64",(t,e)=>{e.pattern??(e.pattern=Lw),L.init(t,e),t._zod.onattach.push(n=>{n._zod.bag.contentEncoding="base64"}),t._zod.check=n=>{Fc(n.value)||n.issues.push({code:"invalid_format",format:"base64",input:n.value,inst:t,continue:!e.abort})}});function Cb(t){if(!Uc.test(t))return!1;const e=t.replace(/[-_]/g,r=>r==="-"?"+":"/"),n=e.padEnd(Math.ceil(e.length/4)*4,"=");return Fc(n)}const Rb=w("$ZodBase64URL",(t,e)=>{e.pattern??(e.pattern=Uc),L.init(t,e),t._zod.onattach.push(n=>{n._zod.bag.contentEncoding="base64url"}),t._zod.check=n=>{Cb(n.value)||n.issues.push({code:"invalid_format",format:"base64url",input:n.value,inst:t,continue:!e.abort})}}),_b=w("$ZodE164",(t,e)=>{e.pattern??(e.pattern=qw),L.init(t,e)});function Mb(t,e=null){try{const n=t.split(".");if(n.length!==3)return!1;const[r]=n;if(!r)return!1;const s=JSON.parse(atob(r));return!("typ"in s&&s?.typ!=="JWT"||!s.alg||e&&(!("alg"in s)||s.alg!==e))}catch{return!1}}const jb=w("$ZodJWT",(t,e)=>{L.init(t,e),t._zod.check=n=>{Mb(n.value,e.alg)||n.issues.push({code:"invalid_format",format:"jwt",input:n.value,inst:t,continue:!e.abort})}}),Yc=w("$ZodNumber",(t,e)=>{F.init(t,e),t._zod.pattern=t._zod.bag.pattern??Ww,t._zod.parse=(n,r)=>{if(e.coerce)try{n.value=Number(n.value)}catch{}const s=n.value;if(typeof s=="number"&&!Number.isNaN(s)&&Number.isFinite(s))return n;const a=typeof s=="number"?Number.isNaN(s)?"NaN":Number.isFinite(s)?void 0:"Infinity":void 0;return n.issues.push({expected:"number",code:"invalid_type",input:s,inst:t,...a?{received:a}:{}}),n}}),Ub=w("$ZodNumber",(t,e)=>{eb.init(t,e),Yc.init(t,e)}),Db=w("$ZodBoolean",(t,e)=>{F.init(t,e),t._zod.pattern=Kw,t._zod.parse=(n,r)=>{if(e.coerce)try{n.value=!!n.value}catch{}const s=n.value;return typeof s=="boolean"||n.issues.push({expected:"boolean",code:"invalid_type",input:s,inst:t}),n}}),Pb=w("$ZodUnknown",(t,e)=>{F.init(t,e),t._zod.parse=n=>n}),Lb=w("$ZodNever",(t,e)=>{F.init(t,e),t._zod.parse=(n,r)=>(n.issues.push({expected:"never",code:"invalid_type",input:n.value,inst:t}),n)});function Pi(t,e,n){t.issues.length&&e.issues.push(...Rc(n,t.issues)),e.value[n]=t.value}const Bb=w("$ZodArray",(t,e)=>{F.init(t,e),t._zod.parse=(n,r)=>{const s=n.value;if(!Array.isArray(s))return n.issues.push({expected:"array",code:"invalid_type",input:s,inst:t}),n;n.value=Array(s.length);const a=[];for(let o=0;o<s.length;o++){const c=s[o],l=e.element._zod.run({value:c,issues:[]},r);l instanceof Promise?a.push(l.then(u=>Pi(u,n,o))):Pi(l,n,o)}return a.length?Promise.all(a).then(()=>n):n}});function Zn(t,e,n,r){t.issues.length&&e.issues.push(...Rc(n,t.issues)),t.value===void 0?n in r&&(e.value[n]=void 0):e.value[n]=t.value}function Vc(t){const e=Object.keys(t.shape);for(const r of e)if(!t.shape?.[r]?._zod?.traits?.has("$ZodType"))throw new Error(`Invalid element at key "${r}": expected a Zod schema`);const n=iw(t.shape);return{...t,keys:e,keySet:new Set(e),numKeys:e.length,optionalKeys:new Set(n)}}function Gc(t,e,n,r,s,a){const o=[],c=s.keySet,l=s.catchall._zod,u=l.def.type;for(const h of Object.keys(e)){if(c.has(h))continue;if(u==="never"){o.push(h);continue}const d=l.run({value:e[h],issues:[]},r);d instanceof Promise?t.push(d.then(f=>Zn(f,n,h,e))):Zn(d,n,h,e)}return o.length&&n.issues.push({code:"unrecognized_keys",keys:o,input:e,inst:a}),t.length?Promise.all(t).then(()=>n):n}const qb=w("$ZodObject",(t,e)=>{if(F.init(t,e),!Object.getOwnPropertyDescriptor(e,"shape")?.get){const c=e.shape;Object.defineProperty(e,"shape",{get:()=>{const l={...c};return Object.defineProperty(e,"shape",{value:l}),l}})}const r=Ds(()=>Vc(e));U(t._zod,"propValues",()=>{const c=e.shape,l={};for(const u in c){const h=c[u]._zod;if(h.values){l[u]??(l[u]=new Set);for(const d of h.values)l[u].add(d)}}return l});const s=In,a=e.catchall;let o;t._zod.parse=(c,l)=>{o??(o=r.value);const u=c.value;if(!s(u))return c.issues.push({expected:"object",code:"invalid_type",input:u,inst:t}),c;c.value={};const h=[],d=o.shape;for(const f of o.keys){const E=d[f]._zod.run({value:u[f],issues:[]},l);E instanceof Promise?h.push(E.then(Z=>Zn(Z,c,f,u))):Zn(E,c,f,u)}return a?Gc(h,u,c,l,r.value,t):h.length?Promise.all(h).then(()=>c):c}}),Fb=w("$ZodObjectJIT",(t,e)=>{qb.init(t,e);const n=t._zod.parse,r=Ds(()=>Vc(e)),s=f=>{const O=new hb(["shape","payload","ctx"]),E=r.value,Z=D=>{const R=Ui(D);return`shape[${R}]._zod.run({ value: input[${R}], issues: [] }, ctx)`};O.write("const input = payload.value;");const z=Object.create(null);let N=0;for(const D of E.keys)z[D]=`key_${N++}`;O.write("const newResult = {};");for(const D of E.keys){const R=z[D],M=Ui(D);O.write(`const ${R} = ${Z(D)};`),O.write(`
24
+ if (${R}.issues.length) {
25
+ payload.issues = payload.issues.concat(${R}.issues.map(iss => ({
26
26
  ...iss,
27
- path: iss.path ? [${ue}, ...iss.path] : [${ue}]
27
+ path: iss.path ? [${M}, ...iss.path] : [${M}]
28
28
  })));
29
29
  }
30
30
 
31
31
 
32
- if (${q}.value === undefined) {
33
- if (${ue} in input) {
34
- newResult[${ue}] = undefined;
32
+ if (${R}.value === undefined) {
33
+ if (${M} in input) {
34
+ newResult[${M}] = undefined;
35
35
  }
36
36
  } else {
37
- newResult[${ue}] = ${q}.value;
37
+ newResult[${M}] = ${R}.value;
38
38
  }
39
39
 
40
- `)}T.write("payload.value = newResult;"),T.write("return payload;");const $=T.compile();return(G,q)=>$(f,G,q)};let a;const o=An,c=!Ec.jitless,u=c&&Fg.value,h=e.catchall;let y;t._zod.parse=(f,T)=>{y??(y=r.value);const S=f.value;return o(S)?c&&u&&T?.async===!1&&T.jitless!==!0?(a||(a=s(e.shape)),f=a(f,T),h?Lc([],S,f,T,y,t):f):n(f,T):(f.issues.push({expected:"object",code:"invalid_type",input:S,inst:t}),f)}});function ji(t,e,n,r){for(const a of t)if(a.issues.length===0)return e.value=a.value,e;const s=t.filter(a=>!gt(a));return s.length===1?(e.value=s[0].value,s[0]):(e.issues.push({code:"invalid_union",input:e.value,inst:n,errors:t.map(a=>a.issues.map(o=>st(o,r,rt())))}),e)}const xb=w("$ZodUnion",(t,e)=>{B.init(t,e),j(t._zod,"optin",()=>e.options.some(s=>s._zod.optin==="optional")?"optional":void 0),j(t._zod,"optout",()=>e.options.some(s=>s._zod.optout==="optional")?"optional":void 0),j(t._zod,"values",()=>{if(e.options.every(s=>s._zod.values))return new Set(e.options.flatMap(s=>Array.from(s._zod.values)))}),j(t._zod,"pattern",()=>{if(e.options.every(s=>s._zod.pattern)){const s=e.options.map(a=>a._zod.pattern);return new RegExp(`^(${s.map(a=>Ds(a.source)).join("|")})$`)}});const n=e.options.length===1,r=e.options[0]._zod.run;t._zod.parse=(s,a)=>{if(n)return r(s,a);let o=!1;const c=[];for(const l of e.options){const u=l._zod.run({value:s.value,issues:[]},a);if(u instanceof Promise)c.push(u),o=!0;else{if(u.issues.length===0)return u;c.push(u)}}return o?Promise.all(c).then(l=>ji(l,s,t,a)):ji(c,s,t,a)}}),Cb=w("$ZodIntersection",(t,e)=>{B.init(t,e),t._zod.parse=(n,r)=>{const s=n.value,a=e.left._zod.run({value:s,issues:[]},r),o=e.right._zod.run({value:s,issues:[]},r);return a instanceof Promise||o instanceof Promise?Promise.all([a,o]).then(([l,u])=>Ui(n,l,u)):Ui(n,a,o)}});function Kr(t,e){if(t===e)return{valid:!0,data:t};if(t instanceof Date&&e instanceof Date&&+t==+e)return{valid:!0,data:t};if(Ht(t)&&Ht(e)){const n=Object.keys(e),r=Object.keys(t).filter(a=>n.indexOf(a)!==-1),s={...t,...e};for(const a of r){const o=Kr(t[a],e[a]);if(!o.valid)return{valid:!1,mergeErrorPath:[a,...o.mergeErrorPath]};s[a]=o.data}return{valid:!0,data:s}}if(Array.isArray(t)&&Array.isArray(e)){if(t.length!==e.length)return{valid:!1,mergeErrorPath:[]};const n=[];for(let r=0;r<t.length;r++){const s=t[r],a=e[r],o=Kr(s,a);if(!o.valid)return{valid:!1,mergeErrorPath:[r,...o.mergeErrorPath]};n.push(o.data)}return{valid:!0,data:n}}return{valid:!1,mergeErrorPath:[]}}function Ui(t,e,n){if(e.issues.length&&t.issues.push(...e.issues),n.issues.length&&t.issues.push(...n.issues),gt(t))return t;const r=Kr(e.value,n.value);if(!r.valid)throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(r.mergeErrorPath)}`);return t.value=r.data,t}const Rb=w("$ZodEnum",(t,e)=>{B.init(t,e);const n=Bg(e.entries),r=new Set(n);t._zod.values=r,t._zod.pattern=new RegExp(`^(${n.filter(s=>Yg.has(typeof s)).map(s=>typeof s=="string"?Pn(s):s.toString()).join("|")})$`),t._zod.parse=(s,a)=>{const o=s.value;return r.has(o)||s.issues.push({code:"invalid_value",values:n,input:o,inst:t}),s}}),_b=w("$ZodTransform",(t,e)=>{B.init(t,e),t._zod.parse=(n,r)=>{if(r.direction==="backward")throw new Oc(t.constructor.name);const s=e.transform(n.value,n);if(r.async)return(s instanceof Promise?s:Promise.resolve(s)).then(o=>(n.value=o,n));if(s instanceof Promise)throw new Tt;return n.value=s,n}});function Di(t,e){return t.issues.length&&e===void 0?{issues:[],value:void 0}:t}const Mb=w("$ZodOptional",(t,e)=>{B.init(t,e),t._zod.optin="optional",t._zod.optout="optional",j(t._zod,"values",()=>e.innerType._zod.values?new Set([...e.innerType._zod.values,void 0]):void 0),j(t._zod,"pattern",()=>{const n=e.innerType._zod.pattern;return n?new RegExp(`^(${Ds(n.source)})?$`):void 0}),t._zod.parse=(n,r)=>{if(e.innerType._zod.optin==="optional"){const s=e.innerType._zod.run(n,r);return s instanceof Promise?s.then(a=>Di(a,n.value)):Di(s,n.value)}return n.value===void 0?n:e.innerType._zod.run(n,r)}}),jb=w("$ZodNullable",(t,e)=>{B.init(t,e),j(t._zod,"optin",()=>e.innerType._zod.optin),j(t._zod,"optout",()=>e.innerType._zod.optout),j(t._zod,"pattern",()=>{const n=e.innerType._zod.pattern;return n?new RegExp(`^(${Ds(n.source)}|null)$`):void 0}),j(t._zod,"values",()=>e.innerType._zod.values?new Set([...e.innerType._zod.values,null]):void 0),t._zod.parse=(n,r)=>n.value===null?n:e.innerType._zod.run(n,r)}),Ub=w("$ZodDefault",(t,e)=>{B.init(t,e),t._zod.optin="optional",j(t._zod,"values",()=>e.innerType._zod.values),t._zod.parse=(n,r)=>{if(r.direction==="backward")return e.innerType._zod.run(n,r);if(n.value===void 0)return n.value=e.defaultValue,n;const s=e.innerType._zod.run(n,r);return s instanceof Promise?s.then(a=>Li(a,e)):Li(s,e)}});function Li(t,e){return t.value===void 0&&(t.value=e.defaultValue),t}const Db=w("$ZodPrefault",(t,e)=>{B.init(t,e),t._zod.optin="optional",j(t._zod,"values",()=>e.innerType._zod.values),t._zod.parse=(n,r)=>(r.direction==="backward"||n.value===void 0&&(n.value=e.defaultValue),e.innerType._zod.run(n,r))}),Lb=w("$ZodNonOptional",(t,e)=>{B.init(t,e),j(t._zod,"values",()=>{const n=e.innerType._zod.values;return n?new Set([...n].filter(r=>r!==void 0)):void 0}),t._zod.parse=(n,r)=>{const s=e.innerType._zod.run(n,r);return s instanceof Promise?s.then(a=>Pi(a,t)):Pi(s,t)}});function Pi(t,e){return!t.issues.length&&t.value===void 0&&t.issues.push({code:"invalid_type",expected:"nonoptional",input:t.value,inst:e}),t}const Pb=w("$ZodCatch",(t,e)=>{B.init(t,e),j(t._zod,"optin",()=>e.innerType._zod.optin),j(t._zod,"optout",()=>e.innerType._zod.optout),j(t._zod,"values",()=>e.innerType._zod.values),t._zod.parse=(n,r)=>{if(r.direction==="backward")return e.innerType._zod.run(n,r);const s=e.innerType._zod.run(n,r);return s instanceof Promise?s.then(a=>(n.value=a.value,a.issues.length&&(n.value=e.catchValue({...n,error:{issues:a.issues.map(o=>st(o,r,rt()))},input:n.value}),n.issues=[]),n)):(n.value=s.value,s.issues.length&&(n.value=e.catchValue({...n,error:{issues:s.issues.map(a=>st(a,r,rt()))},input:n.value}),n.issues=[]),n)}}),Bb=w("$ZodPipe",(t,e)=>{B.init(t,e),j(t._zod,"values",()=>e.in._zod.values),j(t._zod,"optin",()=>e.in._zod.optin),j(t._zod,"optout",()=>e.out._zod.optout),j(t._zod,"propValues",()=>e.in._zod.propValues),t._zod.parse=(n,r)=>{if(r.direction==="backward"){const a=e.out._zod.run(n,r);return a instanceof Promise?a.then(o=>Tn(o,e.in,r)):Tn(a,e.in,r)}const s=e.in._zod.run(n,r);return s instanceof Promise?s.then(a=>Tn(a,e.out,r)):Tn(s,e.out,r)}});function Tn(t,e,n){return t.issues.length?(t.aborted=!0,t):e._zod.run({value:t.value,issues:t.issues},n)}const qb=w("$ZodReadonly",(t,e)=>{B.init(t,e),j(t._zod,"propValues",()=>e.innerType._zod.propValues),j(t._zod,"values",()=>e.innerType._zod.values),j(t._zod,"optin",()=>e.innerType._zod.optin),j(t._zod,"optout",()=>e.innerType._zod.optout),t._zod.parse=(n,r)=>{if(r.direction==="backward")return e.innerType._zod.run(n,r);const s=e.innerType._zod.run(n,r);return s instanceof Promise?s.then(Bi):Bi(s)}});function Bi(t){return t.value=Object.freeze(t.value),t}const Fb=w("$ZodCustom",(t,e)=>{te.init(t,e),B.init(t,e),t._zod.parse=(n,r)=>n,t._zod.check=n=>{const r=n.value,s=e.fn(r);if(s instanceof Promise)return s.then(a=>qi(a,n,r,t));qi(s,n,r,t)}});function qi(t,e,n,r){if(!t){const s={code:"custom",input:n,inst:r,path:[...r._zod.def.path??[]],continue:!r._zod.def.abort};r._zod.def.params&&(s.params=r._zod.def.params),e.issues.push(Vt(s))}}class Yb{constructor(){this._map=new WeakMap,this._idmap=new Map}add(e,...n){const r=n[0];if(this._map.set(e,r),r&&typeof r=="object"&&"id"in r){if(this._idmap.has(r.id))throw new Error(`ID ${r.id} already exists in the registry`);this._idmap.set(r.id,e)}return this}clear(){return this._map=new WeakMap,this._idmap=new Map,this}remove(e){const n=this._map.get(e);return n&&typeof n=="object"&&"id"in n&&this._idmap.delete(n.id),this._map.delete(e),this}get(e){const n=e._zod.parent;if(n){const r={...this.get(n)??{}};delete r.id;const s={...r,...this._map.get(e)};return Object.keys(s).length?s:void 0}return this._map.get(e)}has(e){return this._map.has(e)}}function Hb(){return new Yb}const On=Hb();function Vb(t,e){return new t({type:"string",...k(e)})}function Gb(t,e){return new t({type:"string",format:"email",check:"string_format",abort:!1,...k(e)})}function Fi(t,e){return new t({type:"string",format:"guid",check:"string_format",abort:!1,...k(e)})}function Pc(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,...k(e)})}function Wb(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...k(e)})}function Kb(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...k(e)})}function Jb(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...k(e)})}function Xb(t,e){return new t({type:"string",format:"url",check:"string_format",abort:!1,...k(e)})}function Qb(t,e){return new t({type:"string",format:"emoji",check:"string_format",abort:!1,...k(e)})}function ev(t,e){return new t({type:"string",format:"nanoid",check:"string_format",abort:!1,...k(e)})}function tv(t,e){return new t({type:"string",format:"cuid",check:"string_format",abort:!1,...k(e)})}function nv(t,e){return new t({type:"string",format:"cuid2",check:"string_format",abort:!1,...k(e)})}function rv(t,e){return new t({type:"string",format:"ulid",check:"string_format",abort:!1,...k(e)})}function sv(t,e){return new t({type:"string",format:"xid",check:"string_format",abort:!1,...k(e)})}function iv(t,e){return new t({type:"string",format:"ksuid",check:"string_format",abort:!1,...k(e)})}function av(t,e){return new t({type:"string",format:"ipv4",check:"string_format",abort:!1,...k(e)})}function ov(t,e){return new t({type:"string",format:"ipv6",check:"string_format",abort:!1,...k(e)})}function cv(t,e){return new t({type:"string",format:"cidrv4",check:"string_format",abort:!1,...k(e)})}function uv(t,e){return new t({type:"string",format:"cidrv6",check:"string_format",abort:!1,...k(e)})}function lv(t,e){return new t({type:"string",format:"base64",check:"string_format",abort:!1,...k(e)})}function hv(t,e){return new t({type:"string",format:"base64url",check:"string_format",abort:!1,...k(e)})}function fv(t,e){return new t({type:"string",format:"e164",check:"string_format",abort:!1,...k(e)})}function dv(t,e){return new t({type:"string",format:"jwt",check:"string_format",abort:!1,...k(e)})}function yv(t,e){return new t({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...k(e)})}function pv(t,e){return new t({type:"string",format:"date",check:"string_format",...k(e)})}function mv(t,e){return new t({type:"string",format:"time",check:"string_format",precision:null,...k(e)})}function gv(t,e){return new t({type:"string",format:"duration",check:"string_format",...k(e)})}function wv(t,e){return new t({type:"number",check:"number_format",abort:!1,format:"safeint",...k(e)})}function bv(t,e){return new t({type:"boolean",...k(e)})}function vv(t){return new t({type:"unknown"})}function zv(t,e){return new t({type:"never",...k(e)})}function Yi(t,e){return new _c({check:"less_than",...k(e),value:t,inclusive:!1})}function dr(t,e){return new _c({check:"less_than",...k(e),value:t,inclusive:!0})}function Hi(t,e){return new Mc({check:"greater_than",...k(e),value:t,inclusive:!1})}function yr(t,e){return new Mc({check:"greater_than",...k(e),value:t,inclusive:!0})}function Vi(t,e){return new Lw({check:"multiple_of",...k(e),value:t})}function Bc(t,e){return new Bw({check:"max_length",...k(e),maximum:t})}function In(t,e){return new qw({check:"min_length",...k(e),minimum:t})}function qc(t,e){return new Fw({check:"length_equals",...k(e),length:t})}function Tv(t,e){return new Yw({check:"string_format",format:"regex",...k(e),pattern:t})}function Ov(t){return new Hw({check:"string_format",format:"lowercase",...k(t)})}function Ev(t){return new Vw({check:"string_format",format:"uppercase",...k(t)})}function Nv(t,e){return new Gw({check:"string_format",format:"includes",...k(e),includes:t})}function Sv(t,e){return new Ww({check:"string_format",format:"starts_with",...k(e),prefix:t})}function kv(t,e){return new Kw({check:"string_format",format:"ends_with",...k(e),suffix:t})}function sn(t){return new Jw({check:"overwrite",tx:t})}function Av(t){return sn(e=>e.normalize(t))}function $v(){return sn(t=>t.trim())}function Iv(){return sn(t=>t.toLowerCase())}function Zv(){return sn(t=>t.toUpperCase())}function xv(t,e,n){return new t({type:"array",element:e,...k(n)})}function Cv(t,e,n){return new t({type:"custom",check:"custom",fn:e,...k(n)})}function Rv(t){const e=_v(n=>(n.addIssue=r=>{if(typeof r=="string")n.issues.push(Vt(r,n.value,e._zod.def));else{const s=r;s.fatal&&(s.continue=!1),s.code??(s.code="custom"),s.input??(s.input=n.value),s.inst??(s.inst=e),s.continue??(s.continue=!e._zod.def.abort),n.issues.push(Vt(s))}},t(n.value,n)));return e}function _v(t,e){const n=new te({check:"custom",...k(e)});return n._zod.check=t,n}const Mv=w("ZodISODateTime",(t,e)=>{hb.init(t,e),L.init(t,e)});function jv(t){return yv(Mv,t)}const Uv=w("ZodISODate",(t,e)=>{fb.init(t,e),L.init(t,e)});function Dv(t){return pv(Uv,t)}const Lv=w("ZodISOTime",(t,e)=>{db.init(t,e),L.init(t,e)});function Pv(t){return mv(Lv,t)}const Bv=w("ZodISODuration",(t,e)=>{yb.init(t,e),L.init(t,e)});function qv(t){return gv(Bv,t)}const Fv=(t,e)=>{$c.init(t,e),t.name="ZodError",Object.defineProperties(t,{format:{value:n=>nw(t,n)},flatten:{value:n=>tw(t,n)},addIssue:{value:n=>{t.issues.push(n),t.message=JSON.stringify(t.issues,Wr,2)}},addIssues:{value:n=>{t.issues.push(...n),t.message=JSON.stringify(t.issues,Wr,2)}},isEmpty:{get(){return t.issues.length===0}}})},ce=w("ZodError",Fv,{Parent:Error}),Yv=Ps(ce),Hv=Bs(ce),Vv=Bn(ce),Gv=qn(ce),Wv=iw(ce),Kv=aw(ce),Jv=ow(ce),Xv=cw(ce),Qv=uw(ce),ez=lw(ce),tz=hw(ce),nz=fw(ce),V=w("ZodType",(t,e)=>(B.init(t,e),t.def=e,t.type=e.type,Object.defineProperty(t,"_def",{value:e}),t.check=(...n)=>t.clone(lt(e,{checks:[...e.checks??[],...n.map(r=>typeof r=="function"?{_zod:{check:r,def:{check:"custom"},onattach:[]}}:r)]})),t.clone=(n,r)=>Ye(t,n,r),t.brand=()=>t,t.register=((n,r)=>(n.add(t,r),t)),t.parse=(n,r)=>Yv(t,n,r,{callee:t.parse}),t.safeParse=(n,r)=>Vv(t,n,r),t.parseAsync=async(n,r)=>Hv(t,n,r,{callee:t.parseAsync}),t.safeParseAsync=async(n,r)=>Gv(t,n,r),t.spa=t.safeParseAsync,t.encode=(n,r)=>Wv(t,n,r),t.decode=(n,r)=>Kv(t,n,r),t.encodeAsync=async(n,r)=>Jv(t,n,r),t.decodeAsync=async(n,r)=>Xv(t,n,r),t.safeEncode=(n,r)=>Qv(t,n,r),t.safeDecode=(n,r)=>ez(t,n,r),t.safeEncodeAsync=async(n,r)=>tz(t,n,r),t.safeDecodeAsync=async(n,r)=>nz(t,n,r),t.refine=(n,r)=>t.check(Wz(n,r)),t.superRefine=n=>t.check(Kz(n)),t.overwrite=n=>t.check(sn(n)),t.optional=()=>Ki(t),t.nullable=()=>Ji(t),t.nullish=()=>Ki(Ji(t)),t.nonoptional=n=>Bz(t,n),t.array=()=>$z(t),t.or=n=>Fs([t,n]),t.and=n=>Cz(t,n),t.transform=n=>Xi(t,Mz(n)),t.default=n=>Dz(t,n),t.prefault=n=>Pz(t,n),t.catch=n=>Fz(t,n),t.pipe=n=>Xi(t,n),t.readonly=()=>Vz(t),t.describe=n=>{const r=t.clone();return On.add(r,{description:n}),r},Object.defineProperty(t,"description",{get(){return On.get(t)?.description},configurable:!0}),t.meta=(...n)=>{if(n.length===0)return On.get(t);const r=t.clone();return On.add(r,n[0]),r},t.isOptional=()=>t.safeParse(void 0).success,t.isNullable=()=>t.safeParse(null).success,t)),Fc=w("_ZodString",(t,e)=>{qs.init(t,e),V.init(t,e);const n=t._zod.bag;t.format=n.format??null,t.minLength=n.minimum??null,t.maxLength=n.maximum??null,t.regex=(...r)=>t.check(Tv(...r)),t.includes=(...r)=>t.check(Nv(...r)),t.startsWith=(...r)=>t.check(Sv(...r)),t.endsWith=(...r)=>t.check(kv(...r)),t.min=(...r)=>t.check(In(...r)),t.max=(...r)=>t.check(Bc(...r)),t.length=(...r)=>t.check(qc(...r)),t.nonempty=(...r)=>t.check(In(1,...r)),t.lowercase=r=>t.check(Ov(r)),t.uppercase=r=>t.check(Ev(r)),t.trim=()=>t.check($v()),t.normalize=(...r)=>t.check(Av(...r)),t.toLowerCase=()=>t.check(Iv()),t.toUpperCase=()=>t.check(Zv())}),rz=w("ZodString",(t,e)=>{qs.init(t,e),Fc.init(t,e),t.email=n=>t.check(Gb(sz,n)),t.url=n=>t.check(Xb(az,n)),t.jwt=n=>t.check(dv(zz,n)),t.emoji=n=>t.check(Qb(oz,n)),t.guid=n=>t.check(Fi(Gi,n)),t.uuid=n=>t.check(Pc(Ut,n)),t.uuidv4=n=>t.check(Wb(Ut,n)),t.uuidv6=n=>t.check(Kb(Ut,n)),t.uuidv7=n=>t.check(Jb(Ut,n)),t.nanoid=n=>t.check(ev(cz,n)),t.guid=n=>t.check(Fi(Gi,n)),t.cuid=n=>t.check(tv(uz,n)),t.cuid2=n=>t.check(nv(lz,n)),t.ulid=n=>t.check(rv(hz,n)),t.base64=n=>t.check(lv(wz,n)),t.base64url=n=>t.check(hv(bz,n)),t.xid=n=>t.check(sv(fz,n)),t.ksuid=n=>t.check(iv(dz,n)),t.ipv4=n=>t.check(av(yz,n)),t.ipv6=n=>t.check(ov(pz,n)),t.cidrv4=n=>t.check(cv(mz,n)),t.cidrv6=n=>t.check(uv(gz,n)),t.e164=n=>t.check(fv(vz,n)),t.datetime=n=>t.check(jv(n)),t.date=n=>t.check(Dv(n)),t.time=n=>t.check(Pv(n)),t.duration=n=>t.check(qv(n))});function oe(t){return Vb(rz,t)}const L=w("ZodStringFormat",(t,e)=>{D.init(t,e),Fc.init(t,e)}),sz=w("ZodEmail",(t,e)=>{nb.init(t,e),L.init(t,e)}),Gi=w("ZodGUID",(t,e)=>{eb.init(t,e),L.init(t,e)}),Ut=w("ZodUUID",(t,e)=>{tb.init(t,e),L.init(t,e)});function iz(t){return Pc(Ut,t)}const az=w("ZodURL",(t,e)=>{rb.init(t,e),L.init(t,e)}),oz=w("ZodEmoji",(t,e)=>{sb.init(t,e),L.init(t,e)}),cz=w("ZodNanoID",(t,e)=>{ib.init(t,e),L.init(t,e)}),uz=w("ZodCUID",(t,e)=>{ab.init(t,e),L.init(t,e)}),lz=w("ZodCUID2",(t,e)=>{ob.init(t,e),L.init(t,e)}),hz=w("ZodULID",(t,e)=>{cb.init(t,e),L.init(t,e)}),fz=w("ZodXID",(t,e)=>{ub.init(t,e),L.init(t,e)}),dz=w("ZodKSUID",(t,e)=>{lb.init(t,e),L.init(t,e)}),yz=w("ZodIPv4",(t,e)=>{pb.init(t,e),L.init(t,e)}),pz=w("ZodIPv6",(t,e)=>{mb.init(t,e),L.init(t,e)}),mz=w("ZodCIDRv4",(t,e)=>{gb.init(t,e),L.init(t,e)}),gz=w("ZodCIDRv6",(t,e)=>{wb.init(t,e),L.init(t,e)}),wz=w("ZodBase64",(t,e)=>{bb.init(t,e),L.init(t,e)}),bz=w("ZodBase64URL",(t,e)=>{zb.init(t,e),L.init(t,e)}),vz=w("ZodE164",(t,e)=>{Tb.init(t,e),L.init(t,e)}),zz=w("ZodJWT",(t,e)=>{Eb.init(t,e),L.init(t,e)}),Tz=w("ZodNumber",(t,e)=>{Uc.init(t,e),V.init(t,e),t.gt=(r,s)=>t.check(Hi(r,s)),t.gte=(r,s)=>t.check(yr(r,s)),t.min=(r,s)=>t.check(yr(r,s)),t.lt=(r,s)=>t.check(Yi(r,s)),t.lte=(r,s)=>t.check(dr(r,s)),t.max=(r,s)=>t.check(dr(r,s)),t.int=r=>t.check(Zn(r)),t.safe=r=>t.check(Zn(r)),t.positive=r=>t.check(Hi(0,r)),t.nonnegative=r=>t.check(yr(0,r)),t.negative=r=>t.check(Yi(0,r)),t.nonpositive=r=>t.check(dr(0,r)),t.multipleOf=(r,s)=>t.check(Vi(r,s)),t.step=(r,s)=>t.check(Vi(r,s)),t.finite=()=>t;const n=t._zod.bag;t.minValue=Math.max(n.minimum??Number.NEGATIVE_INFINITY,n.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,t.maxValue=Math.min(n.maximum??Number.POSITIVE_INFINITY,n.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,t.isInt=(n.format??"").includes("int")||Number.isSafeInteger(n.multipleOf??.5),t.isFinite=!0,t.format=n.format??null}),Oz=w("ZodNumberFormat",(t,e)=>{Nb.init(t,e),Tz.init(t,e)});function Zn(t){return wv(Oz,t)}const Ez=w("ZodBoolean",(t,e)=>{Sb.init(t,e),V.init(t,e)});function an(t){return bv(Ez,t)}const Nz=w("ZodUnknown",(t,e)=>{kb.init(t,e),V.init(t,e)});function Wi(){return vv(Nz)}const Sz=w("ZodNever",(t,e)=>{Ab.init(t,e),V.init(t,e)});function kz(t){return zv(Sz,t)}const Az=w("ZodArray",(t,e)=>{$b.init(t,e),V.init(t,e),t.element=e.element,t.min=(n,r)=>t.check(In(n,r)),t.nonempty=n=>t.check(In(1,n)),t.max=(n,r)=>t.check(Bc(n,r)),t.length=(n,r)=>t.check(qc(n,r)),t.unwrap=()=>t.element});function $z(t,e){return xv(Az,t,e)}const Iz=w("ZodObject",(t,e)=>{Zb.init(t,e),V.init(t,e),j(t,"shape",()=>e.shape),t.keyof=()=>Rz(Object.keys(t._zod.def.shape)),t.catchall=n=>t.clone({...t._zod.def,catchall:n}),t.passthrough=()=>t.clone({...t._zod.def,catchall:Wi()}),t.loose=()=>t.clone({...t._zod.def,catchall:Wi()}),t.strict=()=>t.clone({...t._zod.def,catchall:kz()}),t.strip=()=>t.clone({...t._zod.def,catchall:void 0}),t.extend=n=>Kg(t,n),t.safeExtend=n=>Jg(t,n),t.merge=n=>Xg(t,n),t.pick=n=>Gg(t,n),t.omit=n=>Wg(t,n),t.partial=(...n)=>Qg(Yc,t,n[0]),t.required=(...n)=>ew(Hc,t,n[0])});function ee(t,e){const n={type:"object",shape:t??{},...k(e)};return new Iz(n)}const Zz=w("ZodUnion",(t,e)=>{xb.init(t,e),V.init(t,e),t.options=e.options});function Fs(t,e){return new Zz({type:"union",options:t,...k(e)})}const xz=w("ZodIntersection",(t,e)=>{Cb.init(t,e),V.init(t,e)});function Cz(t,e){return new xz({type:"intersection",left:t,right:e})}const Jr=w("ZodEnum",(t,e)=>{Rb.init(t,e),V.init(t,e),t.enum=e.entries,t.options=Object.values(e.entries);const n=new Set(Object.keys(e.entries));t.extract=(r,s)=>{const a={};for(const o of r)if(n.has(o))a[o]=e.entries[o];else throw new Error(`Key ${o} not found in enum`);return new Jr({...e,checks:[],...k(s),entries:a})},t.exclude=(r,s)=>{const a={...e.entries};for(const o of r)if(n.has(o))delete a[o];else throw new Error(`Key ${o} not found in enum`);return new Jr({...e,checks:[],...k(s),entries:a})}});function Rz(t,e){const n=Array.isArray(t)?Object.fromEntries(t.map(r=>[r,r])):t;return new Jr({type:"enum",entries:n,...k(e)})}const _z=w("ZodTransform",(t,e)=>{_b.init(t,e),V.init(t,e),t._zod.parse=(n,r)=>{if(r.direction==="backward")throw new Oc(t.constructor.name);n.addIssue=a=>{if(typeof a=="string")n.issues.push(Vt(a,n.value,e));else{const o=a;o.fatal&&(o.continue=!1),o.code??(o.code="custom"),o.input??(o.input=n.value),o.inst??(o.inst=t),n.issues.push(Vt(o))}};const s=e.transform(n.value,n);return s instanceof Promise?s.then(a=>(n.value=a,n)):(n.value=s,n)}});function Mz(t){return new _z({type:"transform",transform:t})}const Yc=w("ZodOptional",(t,e)=>{Mb.init(t,e),V.init(t,e),t.unwrap=()=>t._zod.def.innerType});function Ki(t){return new Yc({type:"optional",innerType:t})}const jz=w("ZodNullable",(t,e)=>{jb.init(t,e),V.init(t,e),t.unwrap=()=>t._zod.def.innerType});function Ji(t){return new jz({type:"nullable",innerType:t})}const Uz=w("ZodDefault",(t,e)=>{Ub.init(t,e),V.init(t,e),t.unwrap=()=>t._zod.def.innerType,t.removeDefault=t.unwrap});function Dz(t,e){return new Uz({type:"default",innerType:t,get defaultValue(){return typeof e=="function"?e():Sc(e)}})}const Lz=w("ZodPrefault",(t,e)=>{Db.init(t,e),V.init(t,e),t.unwrap=()=>t._zod.def.innerType});function Pz(t,e){return new Lz({type:"prefault",innerType:t,get defaultValue(){return typeof e=="function"?e():Sc(e)}})}const Hc=w("ZodNonOptional",(t,e)=>{Lb.init(t,e),V.init(t,e),t.unwrap=()=>t._zod.def.innerType});function Bz(t,e){return new Hc({type:"nonoptional",innerType:t,...k(e)})}const qz=w("ZodCatch",(t,e)=>{Pb.init(t,e),V.init(t,e),t.unwrap=()=>t._zod.def.innerType,t.removeCatch=t.unwrap});function Fz(t,e){return new qz({type:"catch",innerType:t,catchValue:typeof e=="function"?e:()=>e})}const Yz=w("ZodPipe",(t,e)=>{Bb.init(t,e),V.init(t,e),t.in=e.in,t.out=e.out});function Xi(t,e){return new Yz({type:"pipe",in:t,out:e})}const Hz=w("ZodReadonly",(t,e)=>{qb.init(t,e),V.init(t,e),t.unwrap=()=>t._zod.def.innerType});function Vz(t){return new Hz({type:"readonly",innerType:t})}const Gz=w("ZodCustom",(t,e)=>{Fb.init(t,e),V.init(t,e)});function Wz(t,e={}){return Cv(Gz,t,e)}function Kz(t){return Rv(t)}const Yn=i.z.string(),on=t=>ct.statusZ(t),Vc=t=>on(t).omit({labels:!0}).partial({key:!0}),Xr="sy_status_set",Jz="sy_status_delete",Gc=H("status"),Xz=Gc(""),Ee=t=>t?JSON.parse(t):{},Ys=ee({key:oe(),type:oe(),config:de.unknownZ.or(oe().transform(Ee))}),Wc=Ys.extend({position:Os.xy}),Qr=ee({param:oe(),node:oe()}),Hs=ee({source:Qr,target:Qr}),Qz=ee({nodes:Ys.array(),edges:Hs.array()}),Kc=ee({nodes:Wc.array(),edges:Hs.array()}),Jc=ee({raw:oe()}),cn=iz(),Xc=ee({running:an()}),Qc=on(Xc),Hn=ee({key:cn,name:oe(),graph:Kc,text:Jc,deploy:an(),version:oe(),status:Qc.optional().nullable()}),eu=Hn.partial({key:!0}).omit({status:!0}),eT="arc",tu=H("arc"),tT=tu(""),nT=(t,e,{convertNumericStrings:n=!0}={})=>{const r=!Array.isArray(t);let s=E.toArray(t);const a=s[0],o=typeof a;let c;return o==="string"&&n&&!isNaN(parseInt(a))&&"number"in e?(c=e.number,s=s.map(l=>parseInt(l))):c=e[o],{single:r,variant:c,normalized:s,actual:t}},re=(t,e,n,r)=>{if(r){if(n.length===0)throw new Ft(`${t} not found matching ${JSON.stringify(e)}`);if(n.length>1)throw new Yt(`Expected one ${t} matching ${JSON.stringify(e)}, but found ${n.length}`)}},rT="sy_arc_set",sT="sy_arc_delete",iT=ee({keys:cn.array().optional(),names:oe().array().optional(),searchTerm:oe().optional(),limit:Zn().optional(),offset:Zn().optional(),includeStatus:an().optional()}),aT=ee({arcs:eu.array()}),oT=ee({keys:cn.array()}),cT=ee({arcs:E.nullableZ(Hn)}),uT=ee({arcs:Hn.array()}),lT=ee({}),es=ee({content:oe()}),hT=ee({key:cn,includeStatus:an().optional()}).transform(({key:t,includeStatus:e})=>({keys:[t],includeStatus:e})),fT=ee({name:oe(),includeStatus:an().optional()}).transform(({name:t,includeStatus:e})=>({names:[t],includeStatus:e})),nu=Fs([hT,fT]),dT=Fs([nu,iT]);let ru=class{client;streamClient;constructor(e,n){this.client=e,this.streamClient=n}async create(e){const n=Array.isArray(e),r=await z(this.client,"/arc/create",{arcs:E.toArray(e)},aT,uT);return n?r.arcs:r.arcs[0]}async retrieve(e){const n="key"in e||"name"in e,r=await z(this.client,"/arc/retrieve",e,dT,cT);return re("Arc",e,r.arcs,n),n?r.arcs[0]:r.arcs}async delete(e){await z(this.client,"/arc/delete",{keys:E.toArray(e)},oT,lT)}async openLSP(){return await this.streamClient.stream("/arc/lsp",es,es)}};const yT=Object.freeze(Object.defineProperty({__proto__:null,Client:ru,DELETE_CHANNEL_NAME:sT,ONTOLOGY_TYPE:eT,SET_CHANNEL_NAME:rT,TYPE_ONTOLOGY_ID:tT,arcZ:Hn,edgeZ:Hs,graphNodeZ:Wc,graphZ:Kc,handleZ:Qr,irNodeZ:Ys,irZ:Qz,keyZ:cn,lspMessageZ:es,newZ:eu,ontologyID:tu,singleRetrieveArgsZ:nu,statusDetailsZ:Xc,statusZ:Qc,textZ:Jc},Symbol.toStringTag,{value:"Module"})),Qi="Channel key must be a valid uint32.",M=i.z.uint32().or(i.z.string().refine(t=>!isNaN(Number(t)),{message:Qi}).transform(Number).refine(t=>t<Mr.MAX_UINT32,{message:Qi})),su=/^[a-zA-Z_][a-zA-Z0-9_]*$/,Ie=i.z.string().min(1,"Name must not be empty").regex(su,"Name can only contain letters, digits, and underscores, and cannot start with a digit"),iu=["min","max","avg","none"],au=i.z.enum(iu),Vs=i.z.object({type:au,resetChannel:M.optional(),duration:g.z.optional()}),ou=ct.statusZ(),It=i.z.object({name:i.z.string(),key:M,dataType:d.z,leaseholder:ze.uint12,index:M,isIndex:i.z.boolean(),internal:i.z.boolean(),virtual:i.z.boolean(),alias:i.z.string().optional(),expression:i.z.string().default(""),status:ou.optional(),operations:E.nullableZ(Vs),requires:E.nullableZ(M)}),cu=It.extend({key:M.optional(),name:Ie,leaseholder:ze.uint12.optional(),index:M.optional(),isIndex:i.z.boolean().optional(),internal:i.z.boolean().default(!1),virtual:i.z.boolean().default(!1),expression:i.z.string().default(""),operations:E.nullableZ(Vs).optional(),requires:E.nullableZ(M).optional()}),ht=i.z.union([ze.toArray(M),ze.toArray(Ie),ze.toArray(It).transform(t=>t.map(e=>e.key))]),Gs=H("channel"),pT=Gs(0),mT=/[a-zA-Z0-9_]/,gT=(t,e=!1)=>{if(t==="")return e?"_":"";if(t.match(su))return t;let n="";for(const r of t)r.match(mT)?n+=r:n+="_";return n[0].match(/^\d/)&&(n=`_${n}`),n},wT=new Error("request for lock canceled");var bT=function(t,e,n,r){function s(a){return a instanceof n?a:new n(function(o){o(a)})}return new(n||(n=Promise))(function(a,o){function c(h){try{u(r.next(h))}catch(y){o(y)}}function l(h){try{u(r.throw(h))}catch(y){o(y)}}function u(h){h.done?a(h.value):s(h.value).then(c,l)}u((r=r.apply(t,e||[])).next())})};class vT{constructor(e,n=wT){this._value=e,this._cancelError=n,this._queue=[],this._weightedWaiters=[]}acquire(e=1,n=0){if(e<=0)throw new Error(`invalid weight ${e}: must be positive`);return new Promise((r,s)=>{const a={resolve:r,reject:s,weight:e,priority:n},o=uu(this._queue,c=>n<=c.priority);o===-1&&e<=this._value?this._dispatchItem(a):this._queue.splice(o+1,0,a)})}runExclusive(e){return bT(this,arguments,void 0,function*(n,r=1,s=0){const[a,o]=yield this.acquire(r,s);try{return yield n(a)}finally{o()}})}waitForUnlock(e=1,n=0){if(e<=0)throw new Error(`invalid weight ${e}: must be positive`);return this._couldLockImmediately(e,n)?Promise.resolve():new Promise(r=>{this._weightedWaiters[e-1]||(this._weightedWaiters[e-1]=[]),zT(this._weightedWaiters[e-1],{resolve:r,priority:n})})}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 n=this._value;this._value-=e.weight,e.resolve([n,this._newReleaser(e.weight)])}_newReleaser(e){let n=!1;return()=>{n||(n=!0,this.release(e))}}_drainUnlockWaiters(){if(this._queue.length===0)for(let e=this._value;e>0;e--){const n=this._weightedWaiters[e-1];n&&(n.forEach(r=>r.resolve()),this._weightedWaiters[e-1]=[])}else{const e=this._queue[0].priority;for(let n=this._value;n>0;n--){const r=this._weightedWaiters[n-1];if(!r)continue;const s=r.findIndex(a=>a.priority<=e);(s===-1?r:r.splice(0,s)).forEach((a=>a.resolve()))}}}_couldLockImmediately(e,n){return(this._queue.length===0||this._queue[0].priority<n)&&e<=this._value}}function zT(t,e){const n=uu(t,r=>e.priority<=r.priority);t.splice(n+1,0,e)}function uu(t,e){for(let n=t.length-1;n>=0;n--)if(e(t[n]))return n;return-1}var TT=function(t,e,n,r){function s(a){return a instanceof n?a:new n(function(o){o(a)})}return new(n||(n=Promise))(function(a,o){function c(h){try{u(r.next(h))}catch(y){o(y)}}function l(h){try{u(r.throw(h))}catch(y){o(y)}}function u(h){h.done?a(h.value):s(h.value).then(c,l)}u((r=r.apply(t,e||[])).next())})};class OT{constructor(e){this._semaphore=new vT(1,e)}acquire(){return TT(this,arguments,void 0,function*(e=0){const[,n]=yield this._semaphore.acquire(1,e);return n})}runExclusive(e,n=0){return this._semaphore.runExclusive(()=>e(),1,n)}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 He=ec.keyZ,un=ec.labelZ,ET="labeled_by",NT="sy_label_set",ST="sy_label_delete",lu=un.extend({key:He.optional()}),kT=i.object({labels:lu.array()}),AT=i.object({labels:un.array()}),$T=i.object({keys:He.array()}),hu=i.object({id:U,labels:He.array(),replace:i.boolean().optional()}),IT=hu.omit({replace:!0}),pr=i.object({}),ZT=i.object({keys:He.array().optional(),names:i.string().array().optional(),for:U.optional(),searchTerm:i.string().optional(),offset:i.int().optional(),limit:i.int().optional()}),xT=i.object({key:He}).transform(({key:t})=>({keys:[t]})),CT=i.union([xT,ZT]),RT=i.object({labels:E.nullableZ(un)});let fu=class{type="label";client;constructor(e){this.client=e}async retrieve(e){const n="key"in e,r=await z(this.client,"/label/retrieve",e,CT,RT);return re("Label",e,r.labels,n),n?r.labels[0]:r.labels}async label(e,n,r={}){await z(this.client,"/label/set",{id:e,labels:n,replace:r.replace},hu,pr)}async remove(e,n){await z(this.client,"/label/remove",{id:e,labels:n},IT,pr)}async create(e){const n=Array.isArray(e),r=await z(this.client,"/label/create",{labels:E.toArray(e)},kT,AT);return n?r.labels:r.labels[0]}async delete(e){await z(this.client,"/label/delete",{keys:E.toArray(e)},$T,pr)}};const du=H("label"),_T=du(""),MT=Object.freeze(Object.defineProperty({__proto__:null,Client:fu,DELETE_CHANNEL_NAME:ST,LABELED_BY_ONTOLOGY_RELATIONSHIP_TYPE:ET,SET_CHANNEL_NAME:NT,TYPE_ONTOLOGY_ID:_T,keyZ:He,labelZ:un,newZ:lu,ontologyID:du},Symbol.toStringTag,{value:"Module"})),K=i.z.uuid(),Ws=i.z.string().min(1),ln=i.z.object({key:K,name:Ws,timeRange:Z.z.refine(({isValid:t})=>t,{error:"Time range start time must be before or equal to time range end time"}).refine(({end:t})=>t.valueOf()<=Mr.MAX_INT64,{error:"Time range end time must be less than or equal to the maximum value of an int64"}).refine(({start:t})=>t.valueOf()>=Mr.MIN_INT64,{error:"Time range start time must be greater than or equal to the minimum value of an int64"}),color:i.z.string().optional(),labels:un.array().or(i.z.null().transform(()=>{})).optional(),get parent(){return ln.optional().nullable().transform(t=>t===void 0?null:t)}}),yu=ln.omit({parent:!0,labels:!0}).partial({key:!0}),jT=i.z.object({nodeKey:ze.uint12.optional(),keys:M.array().optional(),names:i.z.string().array().optional(),searchTerm:i.z.string().optional(),rangeKey:K.optional(),limit:i.z.int().optional(),offset:i.z.int().optional(),dataTypes:d.z.array().optional(),notDataTypes:d.z.array().optional(),virtual:i.z.boolean().optional(),isIndex:i.z.boolean().optional(),internal:i.z.boolean().optional(),legacyCalculated:i.z.boolean().optional()}),UT=i.z.object({channels:E.nullableZ(It)}),he=t=>(Array.isArray(t)&&t.length>0&&typeof t[0]=="object"?t=t.map(e=>e.key):typeof t=="object"&&"key"in t&&(t=[t.key]),nT(t,{number:"keys",string:"names"}));class Ks{client;constructor(e){this.client=e}async retrieve(e,n){if(!Array.isArray(e)&&typeof e=="object")return await this.execute(e);const r=he(e),{variant:s}=r;let{normalized:a}=r;return s==="keys"&&a.indexOf(0)!==-1&&(a=a.filter(o=>o!==0)),a.length===0?[]:await this.execute({[s]:a,...n})}async execute(e){return(await z(this.client,"/channel/retrieve",e,jT,UT)).channels}}class Js{cache;namesToKeys;wrapped;constructor(e){this.cache=new Map,this.namesToKeys=new Map,this.wrapped=e}async retrieve(e,n){if(!Array.isArray(e)&&typeof e=="object")return await this.wrapped.retrieve(e);const{normalized:r}=he(e),s=[],a=[];if(r.forEach(c=>{const l=this.get(c);l!=null?s.push(...l):a.push(c)}),a.length===0)return s;const o=await this.wrapped.retrieve(a,n);return this.set(o),s.concat(o)}delete(e){const{variant:n,normalized:r}=he(e);n==="names"?r.forEach(s=>{const a=this.namesToKeys.get(s);a!=null&&(a.forEach(o=>this.cache.delete(o)),this.namesToKeys.delete(s))}):r.forEach(s=>{const a=this.cache.get(s);a!=null&&(this.cache.delete(s),this.namesToKeys.delete(a.name))})}rename(e,n){e.forEach((r,s)=>{const a=n[s],o=this.cache.get(r);if(o==null)return;this.cache.delete(r);const c=this.namesToKeys.get(o.name);c!=null&&(c.delete(r),c.size===0&&this.namesToKeys.delete(o.name)),o.name=a,this.cache.set(r,o);const l=this.namesToKeys.get(a);l==null?this.namesToKeys.set(a,new Set([r])):l.add(r)})}set(e){e.forEach(n=>{this.cache.set(n.key,n);const r=this.namesToKeys.get(n.name);r==null?this.namesToKeys.set(n.name,new Set([n.key])):r.add(n.key)})}get(e){if(typeof e=="number"){const s=this.cache.get(e);return s==null?void 0:[s]}const n=this.namesToKeys.get(e);if(n==null)return;const r=[];if(n.forEach(s=>{const a=this.cache.get(s);a!=null&&r.push(a)}),r.length!==0)return r}}class pu{mu=new OT;requests=new Map;wrapped;debouncedRun;constructor(e,n){this.wrapped=e,this.debouncedRun=Tp(()=>{this.run()},n)}async retrieve(e){if(!Array.isArray(e)&&typeof e=="object")return await this.wrapped.retrieve(e);const{normalized:n,variant:r}=he(e);return r==="names"?await this.wrapped.retrieve(n):await new Promise((a,o)=>{this.mu.runExclusive(()=>{this.requests.set(n,{resolve:a,reject:o}),this.debouncedRun()})})}async run(){await this.mu.runExclusive(async()=>{const e=new Set;this.requests.forEach((n,r)=>r.forEach(s=>e.add(s)));try{const n=await this.wrapped.retrieve(Array.from(e));this.requests.forEach((r,s)=>r.resolve(n.filter(a=>s.includes(a.key))))}catch(n){this.requests.forEach(r=>r.reject(n))}finally{this.requests.clear()}})}}const mu=async(t,e)=>{const{normalized:n}=he(e),r=await t.retrieve(n),s=[];if(n.forEach(a=>{r.find(o=>o.name===a||o.key===a)==null&&s.push(a)}),s.length>0)throw new qe(`Could not find channels: ${JSON.stringify(s)}`);return r},DT="sy_channel_set",LT="sy_channel_delete";class xn{_frameClient;key;name;dataType;leaseholder;index;isIndex;internal;alias;virtual;expression;operations;requires;status;constructor({dataType:e,name:n,leaseholder:r=0,key:s=0,isIndex:a=!1,index:o=0,internal:c=!1,virtual:l=!1,frameClient:u,alias:h,status:y,expression:f="",operations:T=[],requires:S=[]}){this.key=M.parse(s),this.name=n,this.dataType=new d(e),this.leaseholder=r,this.index=M.parse(o),this.isIndex=a,this.internal=c,this.alias=h,this.virtual=l,this.expression=f,this.operations=T,this.requires=S,y!=null&&(this.status=ct.create(y)),this._frameClient=u??null}get framer(){if(this._frameClient==null)throw new Y("cannot read from a channel that has not been created");return this._frameClient}get payload(){return It.parse({key:this.key,name:this.name,dataType:this.dataType.valueOf(),leaseholder:this.leaseholder,index:this.index,isIndex:this.isIndex,internal:this.internal,virtual:this.virtual,requires:this.requires,expression:this.expression,status:this.status,operations:this.operations})}get isCalculated(){return St(this.payload)}get ontologyID(){return Gs(this.key)}async read(e){return await this.framer.read(e,this.key)}async write(e,n){return await this.framer.write(e,this.key,n)}}const PT="sy_calculation_status",BT=i.z.object({}),qT=i.z.object({group:Dn});let gu=class{frameClient;client;retriever;writer;constructor(e,n,r,s){this.frameClient=e,this.retriever=n,this.client=r,this.writer=s}async create(e,n={}){const{retrieveIfNameExists:r=!1}=n,s=!Array.isArray(e);let a=E.toArray(e),o=[];if(r){const c=await this.retriever.retrieve(a.map(u=>u.name)),l=new Set(c.map(u=>u.name));a=a.filter(u=>!l.has(u.name)),o=this.sugar(c)}return o=o.concat(this.sugar(await this.writer.create(a))),s?o[0]:o}async retrieve(e,n){if(typeof e=="object"&&!Array.isArray(e))return this.sugar(await this.retriever.retrieve(e));const r=!Array.isArray(e),s=this.sugar(await this.retriever.retrieve(e,n));return re("channel",e,s,r),r?s[0]:s}async delete(e){const{normalized:n,variant:r}=he(e);return r==="keys"?await this.writer.delete({keys:n}):await this.writer.delete({names:n})}async rename(e,n){return await this.writer.rename(E.toArray(e),E.toArray(n))}createDebouncedBatchRetriever(e=10){return new Js(new pu(new Ks(this.client),e))}sugar(e){const{frameClient:n}=this;return Array.isArray(e)?e.map(r=>new xn({...r,frameClient:n})):new xn({...e,frameClient:n})}async retrieveGroup(){return(await z(this.client,"/channel/retrieve-group",{},BT,qT)).group}};const St=({virtual:t,expression:e})=>t&&e!=="",FT=t=>St(t)&&t.requires.length>0,wu=async(t,e)=>{if(!St(e))return e.index;for(const n of e.requires){const r=await t(n);if(r==null)return null;if(!r.virtual)return r.index}for(const n of e.requires){const r=await t(n);if(r==null)return null;if(St(r)){const s=await wu(t,r);if(s!=null)return s}}return null},YT=i.z.object({channels:cu.array()}),HT=i.z.object({channels:It.array()}),VT=i.z.object({keys:M.array().optional(),names:Ie.array().optional()}),GT=i.z.object({}),WT=i.z.object({keys:M.array(),names:Ie.array()}),KT=i.z.object({});let bu=class{client;cache;constructor(e,n){this.client=e,this.cache=n}async create(e){const{channels:n}=await z(this.client,"/channel/create",{channels:e.map(r=>({...r,dataType:r.dataType}))},YT,HT);return this.cache.set(n),n}async delete(e){const n=M.array().parse(e.keys??[]);await z(this.client,"/channel/delete",e,VT,GT),n.length>0&&this.cache.delete(n),e.names!=null&&this.cache.delete(e.names)}async rename(e,n){await z(this.client,"/channel/rename",{keys:e,names:n},WT,KT),this.cache.rename(e,n)}};const JT=Object.freeze(Object.defineProperty({__proto__:null,CALCULATION_STATUS_CHANNEL_NAME:PT,CacheRetriever:Js,Channel:xn,Client:gu,ClusterRetriever:Ks,DELETE_CHANNEL_NAME:LT,DebouncedBatchRetriever:pu,OPERATION_TYPES:iu,SET_CHANNEL_NAME:DT,TYPE_ONTOLOGY_ID:pT,Writer:bu,analyzeParams:he,escapeInvalidName:gT,isCalculated:St,isLegacyCalculated:FT,keyZ:M,nameZ:Ie,newZ:cu,ontologyID:Gs,operationType:au,operationZ:Vs,paramsZ:ht,payloadZ:It,resolveLegacyCalculatedIndex:wu,retrieveRequired:mu,statusZ:ou},Symbol.toStringTag,{value:"Module"})),XT=i.z.object({username:i.z.string(),password:i.z.string()}),QT=i.z.object({token:i.z.string(),user:rn}),ea="/auth/login",eO=3,tO=i.z.object({username:i.z.string(),password:i.z.string(),newPassword:i.z.string().min(1)}),nO=i.z.object({}),rO=[Yr,Hr];let sO=class{client;credentials;authState={authenticated:!1};authenticating;retryCount;constructor(e,n){this.client=e,this.credentials=n,this.retryCount=0}get authenticated(){return this.authState.authenticated}get user(){return this.authState.authenticated?this.authState.user:void 0}get token(){return this.authState.authenticated?this.authState.token:void 0}async retrieveUser(){this.authState.authenticated||await this.authenticating;const{authState:e}=this;if(!e.authenticated)throw new Error("Authentication failed: user not available");return e.user}async changePassword(e){if(!this.authenticated)throw new Error("Not authenticated");await z(this.client,"/auth/change-password",{username:this.credentials.username,password:this.credentials.password,newPassword:e},tO,nO),this.credentials.password=e}middleware(){const e=async(n,r)=>{if(!this.authenticated&&!n.target.endsWith(ea)){this.authenticating??=new Promise((c,l)=>{this.client.send(ea,this.credentials,XT,QT).then(([u,h])=>{if(h!=null)return c(h);if(u==null)return c(new Error("No response from login"));this.authState={authenticated:!0,user:u.user,token:u.token},c(null)}).catch(l)});const o=await this.authenticating;if(o!=null)return[n,o]}n.params.Authorization=`Bearer ${this.token}`;const[s,a]=await r(n);return rO.some(o=>o.matches(a))&&this.retryCount<eO?(this.authState={authenticated:!1},this.authenticating=void 0,this.retryCount+=1,e(n,r)):(this.retryCount=0,[s,a])};return e}};const vu=i.z.enum(["disconnected","connecting","connected","failed"]),zu=i.z.object({status:vu,error:i.z.instanceof(Error).optional(),message:i.z.string().optional(),clusterKey:i.z.string(),clientVersion:i.z.string(),clientServerCompatible:i.z.boolean(),nodeVersion:i.z.string().optional()}),iO=i.z.object({clusterKey:i.z.string(),nodeVersion:i.z.string().optional()}),aO=i.z.void(),ta={clusterKey:"",status:"disconnected",error:void 0,message:"Disconnected",clientServerCompatible:!1,clientVersion:"0.49.0"},na=(t,e,n)=>{const r=n?"Core":"client";return`Synnax Core version ${t!=null?`${t} `:""}is too ${n?"old":"new"} for client version ${e}.
40
+ `)}O.write("payload.value = newResult;"),O.write("return payload;");const A=O.compile();return(D,R)=>A(f,D,R)};let a;const o=In,c=!Zc.jitless,u=c&&rw.value,h=e.catchall;let d;t._zod.parse=(f,O)=>{d??(d=r.value);const E=f.value;return o(E)?c&&u&&O?.async===!1&&O.jitless!==!0?(a||(a=s(e.shape)),f=a(f,O),h?Gc([],E,f,O,d,t):f):n(f,O):(f.issues.push({expected:"object",code:"invalid_type",input:E,inst:t}),f)}});function Li(t,e,n,r){for(const a of t)if(a.issues.length===0)return e.value=a.value,e;const s=t.filter(a=>!vt(a));return s.length===1?(e.value=s[0].value,s[0]):(e.issues.push({code:"invalid_union",input:e.value,inst:n,errors:t.map(a=>a.issues.map(o=>ot(o,r,at())))}),e)}const Yb=w("$ZodUnion",(t,e)=>{F.init(t,e),U(t._zod,"optin",()=>e.options.some(s=>s._zod.optin==="optional")?"optional":void 0),U(t._zod,"optout",()=>e.options.some(s=>s._zod.optout==="optional")?"optional":void 0),U(t._zod,"values",()=>{if(e.options.every(s=>s._zod.values))return new Set(e.options.flatMap(s=>Array.from(s._zod.values)))}),U(t._zod,"pattern",()=>{if(e.options.every(s=>s._zod.pattern)){const s=e.options.map(a=>a._zod.pattern);return new RegExp(`^(${s.map(a=>Ls(a.source)).join("|")})$`)}});const n=e.options.length===1,r=e.options[0]._zod.run;t._zod.parse=(s,a)=>{if(n)return r(s,a);let o=!1;const c=[];for(const l of e.options){const u=l._zod.run({value:s.value,issues:[]},a);if(u instanceof Promise)c.push(u),o=!0;else{if(u.issues.length===0)return u;c.push(u)}}return o?Promise.all(c).then(l=>Li(l,s,t,a)):Li(c,s,t,a)}}),Vb=w("$ZodIntersection",(t,e)=>{F.init(t,e),t._zod.parse=(n,r)=>{const s=n.value,a=e.left._zod.run({value:s,issues:[]},r),o=e.right._zod.run({value:s,issues:[]},r);return a instanceof Promise||o instanceof Promise?Promise.all([a,o]).then(([l,u])=>Bi(n,l,u)):Bi(n,a,o)}});function Xr(t,e){if(t===e)return{valid:!0,data:t};if(t instanceof Date&&e instanceof Date&&+t==+e)return{valid:!0,data:t};if(Ht(t)&&Ht(e)){const n=Object.keys(e),r=Object.keys(t).filter(a=>n.indexOf(a)!==-1),s={...t,...e};for(const a of r){const o=Xr(t[a],e[a]);if(!o.valid)return{valid:!1,mergeErrorPath:[a,...o.mergeErrorPath]};s[a]=o.data}return{valid:!0,data:s}}if(Array.isArray(t)&&Array.isArray(e)){if(t.length!==e.length)return{valid:!1,mergeErrorPath:[]};const n=[];for(let r=0;r<t.length;r++){const s=t[r],a=e[r],o=Xr(s,a);if(!o.valid)return{valid:!1,mergeErrorPath:[r,...o.mergeErrorPath]};n.push(o.data)}return{valid:!0,data:n}}return{valid:!1,mergeErrorPath:[]}}function Bi(t,e,n){if(e.issues.length&&t.issues.push(...e.issues),n.issues.length&&t.issues.push(...n.issues),vt(t))return t;const r=Xr(e.value,n.value);if(!r.valid)throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(r.mergeErrorPath)}`);return t.value=r.data,t}const Gb=w("$ZodEnum",(t,e)=>{F.init(t,e);const n=tw(e.entries),r=new Set(n);t._zod.values=r,t._zod.pattern=new RegExp(`^(${n.filter(s=>sw.has(typeof s)).map(s=>typeof s=="string"?qn(s):s.toString()).join("|")})$`),t._zod.parse=(s,a)=>{const o=s.value;return r.has(o)||s.issues.push({code:"invalid_value",values:n,input:o,inst:t}),s}}),Hb=w("$ZodTransform",(t,e)=>{F.init(t,e),t._zod.parse=(n,r)=>{if(r.direction==="backward")throw new Ic(t.constructor.name);const s=e.transform(n.value,n);if(r.async)return(s instanceof Promise?s:Promise.resolve(s)).then(o=>(n.value=o,n));if(s instanceof Promise)throw new Nt;return n.value=s,n}});function qi(t,e){return t.issues.length&&e===void 0?{issues:[],value:void 0}:t}const Wb=w("$ZodOptional",(t,e)=>{F.init(t,e),t._zod.optin="optional",t._zod.optout="optional",U(t._zod,"values",()=>e.innerType._zod.values?new Set([...e.innerType._zod.values,void 0]):void 0),U(t._zod,"pattern",()=>{const n=e.innerType._zod.pattern;return n?new RegExp(`^(${Ls(n.source)})?$`):void 0}),t._zod.parse=(n,r)=>{if(e.innerType._zod.optin==="optional"){const s=e.innerType._zod.run(n,r);return s instanceof Promise?s.then(a=>qi(a,n.value)):qi(s,n.value)}return n.value===void 0?n:e.innerType._zod.run(n,r)}}),Kb=w("$ZodNullable",(t,e)=>{F.init(t,e),U(t._zod,"optin",()=>e.innerType._zod.optin),U(t._zod,"optout",()=>e.innerType._zod.optout),U(t._zod,"pattern",()=>{const n=e.innerType._zod.pattern;return n?new RegExp(`^(${Ls(n.source)}|null)$`):void 0}),U(t._zod,"values",()=>e.innerType._zod.values?new Set([...e.innerType._zod.values,null]):void 0),t._zod.parse=(n,r)=>n.value===null?n:e.innerType._zod.run(n,r)}),Jb=w("$ZodDefault",(t,e)=>{F.init(t,e),t._zod.optin="optional",U(t._zod,"values",()=>e.innerType._zod.values),t._zod.parse=(n,r)=>{if(r.direction==="backward")return e.innerType._zod.run(n,r);if(n.value===void 0)return n.value=e.defaultValue,n;const s=e.innerType._zod.run(n,r);return s instanceof Promise?s.then(a=>Fi(a,e)):Fi(s,e)}});function Fi(t,e){return t.value===void 0&&(t.value=e.defaultValue),t}const Xb=w("$ZodPrefault",(t,e)=>{F.init(t,e),t._zod.optin="optional",U(t._zod,"values",()=>e.innerType._zod.values),t._zod.parse=(n,r)=>(r.direction==="backward"||n.value===void 0&&(n.value=e.defaultValue),e.innerType._zod.run(n,r))}),Qb=w("$ZodNonOptional",(t,e)=>{F.init(t,e),U(t._zod,"values",()=>{const n=e.innerType._zod.values;return n?new Set([...n].filter(r=>r!==void 0)):void 0}),t._zod.parse=(n,r)=>{const s=e.innerType._zod.run(n,r);return s instanceof Promise?s.then(a=>Yi(a,t)):Yi(s,t)}});function Yi(t,e){return!t.issues.length&&t.value===void 0&&t.issues.push({code:"invalid_type",expected:"nonoptional",input:t.value,inst:e}),t}const ev=w("$ZodCatch",(t,e)=>{F.init(t,e),U(t._zod,"optin",()=>e.innerType._zod.optin),U(t._zod,"optout",()=>e.innerType._zod.optout),U(t._zod,"values",()=>e.innerType._zod.values),t._zod.parse=(n,r)=>{if(r.direction==="backward")return e.innerType._zod.run(n,r);const s=e.innerType._zod.run(n,r);return s instanceof Promise?s.then(a=>(n.value=a.value,a.issues.length&&(n.value=e.catchValue({...n,error:{issues:a.issues.map(o=>ot(o,r,at()))},input:n.value}),n.issues=[]),n)):(n.value=s.value,s.issues.length&&(n.value=e.catchValue({...n,error:{issues:s.issues.map(a=>ot(a,r,at()))},input:n.value}),n.issues=[]),n)}}),tv=w("$ZodPipe",(t,e)=>{F.init(t,e),U(t._zod,"values",()=>e.in._zod.values),U(t._zod,"optin",()=>e.in._zod.optin),U(t._zod,"optout",()=>e.out._zod.optout),U(t._zod,"propValues",()=>e.in._zod.propValues),t._zod.parse=(n,r)=>{if(r.direction==="backward"){const a=e.out._zod.run(n,r);return a instanceof Promise?a.then(o=>Nn(o,e.in,r)):Nn(a,e.in,r)}const s=e.in._zod.run(n,r);return s instanceof Promise?s.then(a=>Nn(a,e.out,r)):Nn(s,e.out,r)}});function Nn(t,e,n){return t.issues.length?(t.aborted=!0,t):e._zod.run({value:t.value,issues:t.issues},n)}const nv=w("$ZodReadonly",(t,e)=>{F.init(t,e),U(t._zod,"propValues",()=>e.innerType._zod.propValues),U(t._zod,"values",()=>e.innerType._zod.values),U(t._zod,"optin",()=>e.innerType._zod.optin),U(t._zod,"optout",()=>e.innerType._zod.optout),t._zod.parse=(n,r)=>{if(r.direction==="backward")return e.innerType._zod.run(n,r);const s=e.innerType._zod.run(n,r);return s instanceof Promise?s.then(Vi):Vi(s)}});function Vi(t){return t.value=Object.freeze(t.value),t}const rv=w("$ZodCustom",(t,e)=>{re.init(t,e),F.init(t,e),t._zod.parse=(n,r)=>n,t._zod.check=n=>{const r=n.value,s=e.fn(r);if(s instanceof Promise)return s.then(a=>Gi(a,n,r,t));Gi(s,n,r,t)}});function Gi(t,e,n,r){if(!t){const s={code:"custom",input:n,inst:r,path:[...r._zod.def.path??[]],continue:!r._zod.def.abort};r._zod.def.params&&(s.params=r._zod.def.params),e.issues.push(Wt(s))}}class sv{constructor(){this._map=new WeakMap,this._idmap=new Map}add(e,...n){const r=n[0];if(this._map.set(e,r),r&&typeof r=="object"&&"id"in r){if(this._idmap.has(r.id))throw new Error(`ID ${r.id} already exists in the registry`);this._idmap.set(r.id,e)}return this}clear(){return this._map=new WeakMap,this._idmap=new Map,this}remove(e){const n=this._map.get(e);return n&&typeof n=="object"&&"id"in n&&this._idmap.delete(n.id),this._map.delete(e),this}get(e){const n=e._zod.parent;if(n){const r={...this.get(n)??{}};delete r.id;const s={...r,...this._map.get(e)};return Object.keys(s).length?s:void 0}return this._map.get(e)}has(e){return this._map.has(e)}}function iv(){return new sv}const Sn=iv();function av(t,e){return new t({type:"string",...k(e)})}function ov(t,e){return new t({type:"string",format:"email",check:"string_format",abort:!1,...k(e)})}function Hi(t,e){return new t({type:"string",format:"guid",check:"string_format",abort:!1,...k(e)})}function Hc(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,...k(e)})}function cv(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...k(e)})}function uv(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...k(e)})}function lv(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...k(e)})}function hv(t,e){return new t({type:"string",format:"url",check:"string_format",abort:!1,...k(e)})}function fv(t,e){return new t({type:"string",format:"emoji",check:"string_format",abort:!1,...k(e)})}function dv(t,e){return new t({type:"string",format:"nanoid",check:"string_format",abort:!1,...k(e)})}function yv(t,e){return new t({type:"string",format:"cuid",check:"string_format",abort:!1,...k(e)})}function pv(t,e){return new t({type:"string",format:"cuid2",check:"string_format",abort:!1,...k(e)})}function mv(t,e){return new t({type:"string",format:"ulid",check:"string_format",abort:!1,...k(e)})}function gv(t,e){return new t({type:"string",format:"xid",check:"string_format",abort:!1,...k(e)})}function wv(t,e){return new t({type:"string",format:"ksuid",check:"string_format",abort:!1,...k(e)})}function bv(t,e){return new t({type:"string",format:"ipv4",check:"string_format",abort:!1,...k(e)})}function vv(t,e){return new t({type:"string",format:"ipv6",check:"string_format",abort:!1,...k(e)})}function zv(t,e){return new t({type:"string",format:"cidrv4",check:"string_format",abort:!1,...k(e)})}function Tv(t,e){return new t({type:"string",format:"cidrv6",check:"string_format",abort:!1,...k(e)})}function Ov(t,e){return new t({type:"string",format:"base64",check:"string_format",abort:!1,...k(e)})}function Nv(t,e){return new t({type:"string",format:"base64url",check:"string_format",abort:!1,...k(e)})}function Sv(t,e){return new t({type:"string",format:"e164",check:"string_format",abort:!1,...k(e)})}function Ev(t,e){return new t({type:"string",format:"jwt",check:"string_format",abort:!1,...k(e)})}function kv(t,e){return new t({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...k(e)})}function Av(t,e){return new t({type:"string",format:"date",check:"string_format",...k(e)})}function $v(t,e){return new t({type:"string",format:"time",check:"string_format",precision:null,...k(e)})}function Iv(t,e){return new t({type:"string",format:"duration",check:"string_format",...k(e)})}function Zv(t,e){return new t({type:"number",check:"number_format",abort:!1,format:"safeint",...k(e)})}function xv(t,e){return new t({type:"boolean",...k(e)})}function Cv(t){return new t({type:"unknown"})}function Rv(t,e){return new t({type:"never",...k(e)})}function Wi(t,e){return new Bc({check:"less_than",...k(e),value:t,inclusive:!1})}function pr(t,e){return new Bc({check:"less_than",...k(e),value:t,inclusive:!0})}function Ki(t,e){return new qc({check:"greater_than",...k(e),value:t,inclusive:!1})}function mr(t,e){return new qc({check:"greater_than",...k(e),value:t,inclusive:!0})}function Ji(t,e){return new Qw({check:"multiple_of",...k(e),value:t})}function Wc(t,e){return new tb({check:"max_length",...k(e),maximum:t})}function xn(t,e){return new nb({check:"min_length",...k(e),minimum:t})}function Kc(t,e){return new rb({check:"length_equals",...k(e),length:t})}function _v(t,e){return new sb({check:"string_format",format:"regex",...k(e),pattern:t})}function Mv(t){return new ib({check:"string_format",format:"lowercase",...k(t)})}function jv(t){return new ab({check:"string_format",format:"uppercase",...k(t)})}function Uv(t,e){return new ob({check:"string_format",format:"includes",...k(e),includes:t})}function Dv(t,e){return new cb({check:"string_format",format:"starts_with",...k(e),prefix:t})}function Pv(t,e){return new ub({check:"string_format",format:"ends_with",...k(e),suffix:t})}function on(t){return new lb({check:"overwrite",tx:t})}function Lv(t){return on(e=>e.normalize(t))}function Bv(){return on(t=>t.trim())}function qv(){return on(t=>t.toLowerCase())}function Fv(){return on(t=>t.toUpperCase())}function Yv(t,e,n){return new t({type:"array",element:e,...k(n)})}function Vv(t,e,n){return new t({type:"custom",check:"custom",fn:e,...k(n)})}function Gv(t){const e=Hv(n=>(n.addIssue=r=>{if(typeof r=="string")n.issues.push(Wt(r,n.value,e._zod.def));else{const s=r;s.fatal&&(s.continue=!1),s.code??(s.code="custom"),s.input??(s.input=n.value),s.inst??(s.inst=e),s.continue??(s.continue=!e._zod.def.abort),n.issues.push(Wt(s))}},t(n.value,n)));return e}function Hv(t,e){const n=new re({check:"custom",...k(e)});return n._zod.check=t,n}const Wv=w("ZodISODateTime",(t,e)=>{Nb.init(t,e),B.init(t,e)});function Kv(t){return kv(Wv,t)}const Jv=w("ZodISODate",(t,e)=>{Sb.init(t,e),B.init(t,e)});function Xv(t){return Av(Jv,t)}const Qv=w("ZodISOTime",(t,e)=>{Eb.init(t,e),B.init(t,e)});function ez(t){return $v(Qv,t)}const tz=w("ZodISODuration",(t,e)=>{kb.init(t,e),B.init(t,e)});function nz(t){return Iv(tz,t)}const rz=(t,e)=>{Mc.init(t,e),t.name="ZodError",Object.defineProperties(t,{format:{value:n=>pw(t,n)},flatten:{value:n=>yw(t,n)},addIssue:{value:n=>{t.issues.push(n),t.message=JSON.stringify(t.issues,Jr,2)}},addIssues:{value:n=>{t.issues.push(...n),t.message=JSON.stringify(t.issues,Jr,2)}},isEmpty:{get(){return t.issues.length===0}}})},fe=w("ZodError",rz,{Parent:Error}),sz=qs(fe),iz=Fs(fe),az=Fn(fe),oz=Yn(fe),cz=ww(fe),uz=bw(fe),lz=vw(fe),hz=zw(fe),fz=Tw(fe),dz=Ow(fe),yz=Nw(fe),pz=Sw(fe),H=w("ZodType",(t,e)=>(F.init(t,e),t.def=e,t.type=e.type,Object.defineProperty(t,"_def",{value:e}),t.check=(...n)=>t.clone(dt(e,{checks:[...e.checks??[],...n.map(r=>typeof r=="function"?{_zod:{check:r,def:{check:"custom"},onattach:[]}}:r)]})),t.clone=(n,r)=>We(t,n,r),t.brand=()=>t,t.register=((n,r)=>(n.add(t,r),t)),t.parse=(n,r)=>sz(t,n,r,{callee:t.parse}),t.safeParse=(n,r)=>az(t,n,r),t.parseAsync=async(n,r)=>iz(t,n,r,{callee:t.parseAsync}),t.safeParseAsync=async(n,r)=>oz(t,n,r),t.spa=t.safeParseAsync,t.encode=(n,r)=>cz(t,n,r),t.decode=(n,r)=>uz(t,n,r),t.encodeAsync=async(n,r)=>lz(t,n,r),t.decodeAsync=async(n,r)=>hz(t,n,r),t.safeEncode=(n,r)=>fz(t,n,r),t.safeDecode=(n,r)=>dz(t,n,r),t.safeEncodeAsync=async(n,r)=>yz(t,n,r),t.safeDecodeAsync=async(n,r)=>pz(t,n,r),t.refine=(n,r)=>t.check(cT(n,r)),t.superRefine=n=>t.check(uT(n)),t.overwrite=n=>t.check(on(n)),t.optional=()=>ea(t),t.nullable=()=>ta(t),t.nullish=()=>ea(ta(t)),t.nonoptional=n=>tT(t,n),t.array=()=>Bz(t),t.or=n=>Vs([t,n]),t.and=n=>Vz(t,n),t.transform=n=>na(t,Wz(n)),t.default=n=>Xz(t,n),t.prefault=n=>eT(t,n),t.catch=n=>rT(t,n),t.pipe=n=>na(t,n),t.readonly=()=>aT(t),t.describe=n=>{const r=t.clone();return Sn.add(r,{description:n}),r},Object.defineProperty(t,"description",{get(){return Sn.get(t)?.description},configurable:!0}),t.meta=(...n)=>{if(n.length===0)return Sn.get(t);const r=t.clone();return Sn.add(r,n[0]),r},t.isOptional=()=>t.safeParse(void 0).success,t.isNullable=()=>t.safeParse(null).success,t)),Jc=w("_ZodString",(t,e)=>{Ys.init(t,e),H.init(t,e);const n=t._zod.bag;t.format=n.format??null,t.minLength=n.minimum??null,t.maxLength=n.maximum??null,t.regex=(...r)=>t.check(_v(...r)),t.includes=(...r)=>t.check(Uv(...r)),t.startsWith=(...r)=>t.check(Dv(...r)),t.endsWith=(...r)=>t.check(Pv(...r)),t.min=(...r)=>t.check(xn(...r)),t.max=(...r)=>t.check(Wc(...r)),t.length=(...r)=>t.check(Kc(...r)),t.nonempty=(...r)=>t.check(xn(1,...r)),t.lowercase=r=>t.check(Mv(r)),t.uppercase=r=>t.check(jv(r)),t.trim=()=>t.check(Bv()),t.normalize=(...r)=>t.check(Lv(...r)),t.toLowerCase=()=>t.check(qv()),t.toUpperCase=()=>t.check(Fv())}),mz=w("ZodString",(t,e)=>{Ys.init(t,e),Jc.init(t,e),t.email=n=>t.check(ov(gz,n)),t.url=n=>t.check(hv(bz,n)),t.jwt=n=>t.check(Ev(Rz,n)),t.emoji=n=>t.check(fv(vz,n)),t.guid=n=>t.check(Hi(Xi,n)),t.uuid=n=>t.check(Hc(Pt,n)),t.uuidv4=n=>t.check(cv(Pt,n)),t.uuidv6=n=>t.check(uv(Pt,n)),t.uuidv7=n=>t.check(lv(Pt,n)),t.nanoid=n=>t.check(dv(zz,n)),t.guid=n=>t.check(Hi(Xi,n)),t.cuid=n=>t.check(yv(Tz,n)),t.cuid2=n=>t.check(pv(Oz,n)),t.ulid=n=>t.check(mv(Nz,n)),t.base64=n=>t.check(Ov(Zz,n)),t.base64url=n=>t.check(Nv(xz,n)),t.xid=n=>t.check(gv(Sz,n)),t.ksuid=n=>t.check(wv(Ez,n)),t.ipv4=n=>t.check(bv(kz,n)),t.ipv6=n=>t.check(vv(Az,n)),t.cidrv4=n=>t.check(zv($z,n)),t.cidrv6=n=>t.check(Tv(Iz,n)),t.e164=n=>t.check(Sv(Cz,n)),t.datetime=n=>t.check(Kv(n)),t.date=n=>t.check(Xv(n)),t.time=n=>t.check(ez(n)),t.duration=n=>t.check(nz(n))});function he(t){return av(mz,t)}const B=w("ZodStringFormat",(t,e)=>{L.init(t,e),Jc.init(t,e)}),gz=w("ZodEmail",(t,e)=>{pb.init(t,e),B.init(t,e)}),Xi=w("ZodGUID",(t,e)=>{db.init(t,e),B.init(t,e)}),Pt=w("ZodUUID",(t,e)=>{yb.init(t,e),B.init(t,e)});function wz(t){return Hc(Pt,t)}const bz=w("ZodURL",(t,e)=>{mb.init(t,e),B.init(t,e)}),vz=w("ZodEmoji",(t,e)=>{gb.init(t,e),B.init(t,e)}),zz=w("ZodNanoID",(t,e)=>{wb.init(t,e),B.init(t,e)}),Tz=w("ZodCUID",(t,e)=>{bb.init(t,e),B.init(t,e)}),Oz=w("ZodCUID2",(t,e)=>{vb.init(t,e),B.init(t,e)}),Nz=w("ZodULID",(t,e)=>{zb.init(t,e),B.init(t,e)}),Sz=w("ZodXID",(t,e)=>{Tb.init(t,e),B.init(t,e)}),Ez=w("ZodKSUID",(t,e)=>{Ob.init(t,e),B.init(t,e)}),kz=w("ZodIPv4",(t,e)=>{Ab.init(t,e),B.init(t,e)}),Az=w("ZodIPv6",(t,e)=>{$b.init(t,e),B.init(t,e)}),$z=w("ZodCIDRv4",(t,e)=>{Ib.init(t,e),B.init(t,e)}),Iz=w("ZodCIDRv6",(t,e)=>{Zb.init(t,e),B.init(t,e)}),Zz=w("ZodBase64",(t,e)=>{xb.init(t,e),B.init(t,e)}),xz=w("ZodBase64URL",(t,e)=>{Rb.init(t,e),B.init(t,e)}),Cz=w("ZodE164",(t,e)=>{_b.init(t,e),B.init(t,e)}),Rz=w("ZodJWT",(t,e)=>{jb.init(t,e),B.init(t,e)}),_z=w("ZodNumber",(t,e)=>{Yc.init(t,e),H.init(t,e),t.gt=(r,s)=>t.check(Ki(r,s)),t.gte=(r,s)=>t.check(mr(r,s)),t.min=(r,s)=>t.check(mr(r,s)),t.lt=(r,s)=>t.check(Wi(r,s)),t.lte=(r,s)=>t.check(pr(r,s)),t.max=(r,s)=>t.check(pr(r,s)),t.int=r=>t.check(Cn(r)),t.safe=r=>t.check(Cn(r)),t.positive=r=>t.check(Ki(0,r)),t.nonnegative=r=>t.check(mr(0,r)),t.negative=r=>t.check(Wi(0,r)),t.nonpositive=r=>t.check(pr(0,r)),t.multipleOf=(r,s)=>t.check(Ji(r,s)),t.step=(r,s)=>t.check(Ji(r,s)),t.finite=()=>t;const n=t._zod.bag;t.minValue=Math.max(n.minimum??Number.NEGATIVE_INFINITY,n.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,t.maxValue=Math.min(n.maximum??Number.POSITIVE_INFINITY,n.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,t.isInt=(n.format??"").includes("int")||Number.isSafeInteger(n.multipleOf??.5),t.isFinite=!0,t.format=n.format??null}),Mz=w("ZodNumberFormat",(t,e)=>{Ub.init(t,e),_z.init(t,e)});function Cn(t){return Zv(Mz,t)}const jz=w("ZodBoolean",(t,e)=>{Db.init(t,e),H.init(t,e)});function cn(t){return xv(jz,t)}const Uz=w("ZodUnknown",(t,e)=>{Pb.init(t,e),H.init(t,e)});function Qi(){return Cv(Uz)}const Dz=w("ZodNever",(t,e)=>{Lb.init(t,e),H.init(t,e)});function Pz(t){return Rv(Dz,t)}const Lz=w("ZodArray",(t,e)=>{Bb.init(t,e),H.init(t,e),t.element=e.element,t.min=(n,r)=>t.check(xn(n,r)),t.nonempty=n=>t.check(xn(1,n)),t.max=(n,r)=>t.check(Wc(n,r)),t.length=(n,r)=>t.check(Kc(n,r)),t.unwrap=()=>t.element});function Bz(t,e){return Yv(Lz,t,e)}const qz=w("ZodObject",(t,e)=>{Fb.init(t,e),H.init(t,e),U(t,"shape",()=>e.shape),t.keyof=()=>Gz(Object.keys(t._zod.def.shape)),t.catchall=n=>t.clone({...t._zod.def,catchall:n}),t.passthrough=()=>t.clone({...t._zod.def,catchall:Qi()}),t.loose=()=>t.clone({...t._zod.def,catchall:Qi()}),t.strict=()=>t.clone({...t._zod.def,catchall:Pz()}),t.strip=()=>t.clone({...t._zod.def,catchall:void 0}),t.extend=n=>uw(t,n),t.safeExtend=n=>lw(t,n),t.merge=n=>hw(t,n),t.pick=n=>ow(t,n),t.omit=n=>cw(t,n),t.partial=(...n)=>fw(Xc,t,n[0]),t.required=(...n)=>dw(Qc,t,n[0])});function ee(t,e){const n={type:"object",shape:t??{},...k(e)};return new qz(n)}const Fz=w("ZodUnion",(t,e)=>{Yb.init(t,e),H.init(t,e),t.options=e.options});function Vs(t,e){return new Fz({type:"union",options:t,...k(e)})}const Yz=w("ZodIntersection",(t,e)=>{Vb.init(t,e),H.init(t,e)});function Vz(t,e){return new Yz({type:"intersection",left:t,right:e})}const Qr=w("ZodEnum",(t,e)=>{Gb.init(t,e),H.init(t,e),t.enum=e.entries,t.options=Object.values(e.entries);const n=new Set(Object.keys(e.entries));t.extract=(r,s)=>{const a={};for(const o of r)if(n.has(o))a[o]=e.entries[o];else throw new Error(`Key ${o} not found in enum`);return new Qr({...e,checks:[],...k(s),entries:a})},t.exclude=(r,s)=>{const a={...e.entries};for(const o of r)if(n.has(o))delete a[o];else throw new Error(`Key ${o} not found in enum`);return new Qr({...e,checks:[],...k(s),entries:a})}});function Gz(t,e){const n=Array.isArray(t)?Object.fromEntries(t.map(r=>[r,r])):t;return new Qr({type:"enum",entries:n,...k(e)})}const Hz=w("ZodTransform",(t,e)=>{Hb.init(t,e),H.init(t,e),t._zod.parse=(n,r)=>{if(r.direction==="backward")throw new Ic(t.constructor.name);n.addIssue=a=>{if(typeof a=="string")n.issues.push(Wt(a,n.value,e));else{const o=a;o.fatal&&(o.continue=!1),o.code??(o.code="custom"),o.input??(o.input=n.value),o.inst??(o.inst=t),n.issues.push(Wt(o))}};const s=e.transform(n.value,n);return s instanceof Promise?s.then(a=>(n.value=a,n)):(n.value=s,n)}});function Wz(t){return new Hz({type:"transform",transform:t})}const Xc=w("ZodOptional",(t,e)=>{Wb.init(t,e),H.init(t,e),t.unwrap=()=>t._zod.def.innerType});function ea(t){return new Xc({type:"optional",innerType:t})}const Kz=w("ZodNullable",(t,e)=>{Kb.init(t,e),H.init(t,e),t.unwrap=()=>t._zod.def.innerType});function ta(t){return new Kz({type:"nullable",innerType:t})}const Jz=w("ZodDefault",(t,e)=>{Jb.init(t,e),H.init(t,e),t.unwrap=()=>t._zod.def.innerType,t.removeDefault=t.unwrap});function Xz(t,e){return new Jz({type:"default",innerType:t,get defaultValue(){return typeof e=="function"?e():Cc(e)}})}const Qz=w("ZodPrefault",(t,e)=>{Xb.init(t,e),H.init(t,e),t.unwrap=()=>t._zod.def.innerType});function eT(t,e){return new Qz({type:"prefault",innerType:t,get defaultValue(){return typeof e=="function"?e():Cc(e)}})}const Qc=w("ZodNonOptional",(t,e)=>{Qb.init(t,e),H.init(t,e),t.unwrap=()=>t._zod.def.innerType});function tT(t,e){return new Qc({type:"nonoptional",innerType:t,...k(e)})}const nT=w("ZodCatch",(t,e)=>{ev.init(t,e),H.init(t,e),t.unwrap=()=>t._zod.def.innerType,t.removeCatch=t.unwrap});function rT(t,e){return new nT({type:"catch",innerType:t,catchValue:typeof e=="function"?e:()=>e})}const sT=w("ZodPipe",(t,e)=>{tv.init(t,e),H.init(t,e),t.in=e.in,t.out=e.out});function na(t,e){return new sT({type:"pipe",in:t,out:e})}const iT=w("ZodReadonly",(t,e)=>{nv.init(t,e),H.init(t,e),t.unwrap=()=>t._zod.def.innerType});function aT(t){return new iT({type:"readonly",innerType:t})}const oT=w("ZodCustom",(t,e)=>{rv.init(t,e),H.init(t,e)});function cT(t,e={}){return Vv(oT,t,e)}function uT(t){return Gv(t)}const Gn=i.z.string(),un=t=>ht.statusZ(t),eu=t=>un(t).omit({labels:!0}).partial({key:!0}),es="sy_status_set",lT="sy_status_delete",tu=G("status"),hT=tu(""),Ae=t=>t?JSON.parse(t):{},Gs=ee({key:he(),type:he(),config:we.unknownZ.or(he().transform(Ae))}),nu=Gs.extend({position:Ss.xy}),ts=ee({param:he(),node:he()}),Hs=ee({source:ts,target:ts}),fT=ee({nodes:Gs.array(),edges:Hs.array()}),ru=ee({nodes:nu.array(),edges:Hs.array()}),su=ee({raw:he()}),ln=wz(),iu=ee({running:cn()}),au=un(iu),Hn=ee({key:ln,name:he(),graph:ru,text:su,deploy:cn(),version:he(),status:au.optional().nullable()}),ou=Hn.partial({key:!0}).omit({status:!0}),dT="arc",cu=G("arc"),yT=cu(""),pT=(t,e,{convertNumericStrings:n=!0}={})=>{const r=!Array.isArray(t);let s=S.toArray(t);const a=s[0],o=typeof a;let c;return o==="string"&&n&&!isNaN(parseInt(a))&&"number"in e?(c=e.number,s=s.map(l=>parseInt(l))):c=e[o],{single:r,variant:c,normalized:s,actual:t}},ie=(t,e,n,r)=>{if(r){if(n.length===0)throw new Vt(`${t} not found matching ${JSON.stringify(e)}`);if(n.length>1)throw new Gt(`Expected one ${t} matching ${JSON.stringify(e)}, but found ${n.length}`)}},mT="sy_arc_set",gT="sy_arc_delete",wT=ee({keys:ln.array().optional(),names:he().array().optional(),searchTerm:he().optional(),limit:Cn().optional(),offset:Cn().optional(),includeStatus:cn().optional()}),bT=ee({arcs:ou.array()}),vT=ee({keys:ln.array()}),zT=ee({arcs:S.nullableZ(Hn)}),TT=ee({arcs:Hn.array()}),OT=ee({}),ns=ee({content:he()}),NT=ee({key:ln,includeStatus:cn().optional()}).transform(({key:t,includeStatus:e})=>({keys:[t],includeStatus:e})),ST=ee({name:he(),includeStatus:cn().optional()}).transform(({name:t,includeStatus:e})=>({names:[t],includeStatus:e})),uu=Vs([NT,ST]),ET=Vs([uu,wT]);let lu=class{client;streamClient;constructor(e,n){this.client=e,this.streamClient=n}async create(e){const n=Array.isArray(e),r=await T(this.client,"/arc/create",{arcs:S.toArray(e)},bT,TT);return n?r.arcs:r.arcs[0]}async retrieve(e){const n="key"in e||"name"in e,r=await T(this.client,"/arc/retrieve",e,ET,zT);return ie("Arc",e,r.arcs,n),n?r.arcs[0]:r.arcs}async delete(e){await T(this.client,"/arc/delete",{keys:S.toArray(e)},vT,OT)}async openLSP(){return await this.streamClient.stream("/arc/lsp",ns,ns)}};const kT=Object.freeze(Object.defineProperty({__proto__:null,Client:lu,DELETE_CHANNEL_NAME:gT,ONTOLOGY_TYPE:dT,SET_CHANNEL_NAME:mT,TYPE_ONTOLOGY_ID:yT,arcZ:Hn,edgeZ:Hs,graphNodeZ:nu,graphZ:ru,handleZ:ts,irNodeZ:Gs,irZ:fT,keyZ:ln,lspMessageZ:ns,newZ:ou,ontologyID:cu,singleRetrieveArgsZ:uu,statusDetailsZ:iu,statusZ:au,textZ:su},Symbol.toStringTag,{value:"Module"})),ra="Channel key must be a valid uint32.",j=i.z.uint32().or(i.z.string().refine(t=>!isNaN(Number(t)),{message:ra}).transform(Number).refine(t=>t<Ur.MAX_UINT32,{message:ra})),hu=/^[a-zA-Z_][a-zA-Z0-9_]*$/,Re=i.z.string().min(1,"Name must not be empty").regex(hu,"Name can only contain letters, digits, and underscores, and cannot start with a digit"),fu=["min","max","avg","none"],du=i.z.enum(fu),Ws=i.z.object({type:du,resetChannel:j.optional(),duration:m.z.optional()}),yu=ht.statusZ(),xt=i.z.object({name:i.z.string(),key:j,dataType:y.z,leaseholder:Se.uint12,index:j,isIndex:i.z.boolean(),internal:i.z.boolean(),virtual:i.z.boolean(),alias:i.z.string().optional(),expression:i.z.string().default(""),status:yu.optional(),operations:S.nullableZ(Ws),requires:S.nullableZ(j)}),pu=xt.extend({key:j.optional(),name:Re,leaseholder:Se.uint12.optional(),index:j.optional(),isIndex:i.z.boolean().optional(),internal:i.z.boolean().default(!1),virtual:i.z.boolean().default(!1),expression:i.z.string().default(""),operations:S.nullableZ(Ws).optional(),requires:S.nullableZ(j).optional()}),yt=i.z.union([Se.toArray(j),Se.toArray(Re),Se.toArray(xt).transform(t=>t.map(e=>e.key))]),Ks=G("channel"),AT=Ks(0),$T=/[a-zA-Z0-9_]/,IT=(t,e=!1)=>{if(t==="")return e?"_":"";if(t.match(hu))return t;let n="";for(const r of t)r.match($T)?n+=r:n+="_";return n[0].match(/^\d/)&&(n=`_${n}`),n},ZT=new Error("request for lock canceled");var xT=function(t,e,n,r){function s(a){return a instanceof n?a:new n(function(o){o(a)})}return new(n||(n=Promise))(function(a,o){function c(h){try{u(r.next(h))}catch(d){o(d)}}function l(h){try{u(r.throw(h))}catch(d){o(d)}}function u(h){h.done?a(h.value):s(h.value).then(c,l)}u((r=r.apply(t,e||[])).next())})};class CT{constructor(e,n=ZT){this._value=e,this._cancelError=n,this._queue=[],this._weightedWaiters=[]}acquire(e=1,n=0){if(e<=0)throw new Error(`invalid weight ${e}: must be positive`);return new Promise((r,s)=>{const a={resolve:r,reject:s,weight:e,priority:n},o=mu(this._queue,c=>n<=c.priority);o===-1&&e<=this._value?this._dispatchItem(a):this._queue.splice(o+1,0,a)})}runExclusive(e){return xT(this,arguments,void 0,function*(n,r=1,s=0){const[a,o]=yield this.acquire(r,s);try{return yield n(a)}finally{o()}})}waitForUnlock(e=1,n=0){if(e<=0)throw new Error(`invalid weight ${e}: must be positive`);return this._couldLockImmediately(e,n)?Promise.resolve():new Promise(r=>{this._weightedWaiters[e-1]||(this._weightedWaiters[e-1]=[]),RT(this._weightedWaiters[e-1],{resolve:r,priority:n})})}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 n=this._value;this._value-=e.weight,e.resolve([n,this._newReleaser(e.weight)])}_newReleaser(e){let n=!1;return()=>{n||(n=!0,this.release(e))}}_drainUnlockWaiters(){if(this._queue.length===0)for(let e=this._value;e>0;e--){const n=this._weightedWaiters[e-1];n&&(n.forEach(r=>r.resolve()),this._weightedWaiters[e-1]=[])}else{const e=this._queue[0].priority;for(let n=this._value;n>0;n--){const r=this._weightedWaiters[n-1];if(!r)continue;const s=r.findIndex(a=>a.priority<=e);(s===-1?r:r.splice(0,s)).forEach((a=>a.resolve()))}}}_couldLockImmediately(e,n){return(this._queue.length===0||this._queue[0].priority<n)&&e<=this._value}}function RT(t,e){const n=mu(t,r=>e.priority<=r.priority);t.splice(n+1,0,e)}function mu(t,e){for(let n=t.length-1;n>=0;n--)if(e(t[n]))return n;return-1}var _T=function(t,e,n,r){function s(a){return a instanceof n?a:new n(function(o){o(a)})}return new(n||(n=Promise))(function(a,o){function c(h){try{u(r.next(h))}catch(d){o(d)}}function l(h){try{u(r.throw(h))}catch(d){o(d)}}function u(h){h.done?a(h.value):s(h.value).then(c,l)}u((r=r.apply(t,e||[])).next())})};class MT{constructor(e){this._semaphore=new CT(1,e)}acquire(){return _T(this,arguments,void 0,function*(e=0){const[,n]=yield this._semaphore.acquire(1,e);return n})}runExclusive(e,n=0){return this._semaphore.runExclusive(()=>e(),1,n)}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 Ke=ic.keyZ,hn=ic.labelZ,jT="labeled_by",UT="sy_label_set",DT="sy_label_delete",gu=hn.extend({key:Ke.optional()}),PT=i.object({labels:gu.array()}),LT=i.object({labels:hn.array()}),BT=i.object({keys:Ke.array()}),wu=i.object({id:P,labels:Ke.array(),replace:i.boolean().optional()}),qT=wu.omit({replace:!0}),gr=i.object({}),FT=i.object({keys:Ke.array().optional(),names:i.string().array().optional(),for:P.optional(),searchTerm:i.string().optional(),offset:i.int().optional(),limit:i.int().optional()}),YT=i.object({key:Ke}).transform(({key:t})=>({keys:[t]})),VT=i.union([YT,FT]),GT=i.object({labels:S.nullableZ(hn)});let bu=class{type="label";client;constructor(e){this.client=e}async retrieve(e){const n="key"in e,r=await T(this.client,"/label/retrieve",e,VT,GT);return ie("Label",e,r.labels,n),n?r.labels[0]:r.labels}async label(e,n,r={}){await T(this.client,"/label/set",{id:e,labels:n,replace:r.replace},wu,gr)}async remove(e,n){await T(this.client,"/label/remove",{id:e,labels:n},qT,gr)}async create(e){const n=Array.isArray(e),r=await T(this.client,"/label/create",{labels:S.toArray(e)},PT,LT);return n?r.labels:r.labels[0]}async delete(e){await T(this.client,"/label/delete",{keys:S.toArray(e)},BT,gr)}};const vu=G("label"),HT=vu(""),WT=Object.freeze(Object.defineProperty({__proto__:null,Client:bu,DELETE_CHANNEL_NAME:DT,LABELED_BY_ONTOLOGY_RELATIONSHIP_TYPE:jT,SET_CHANNEL_NAME:UT,TYPE_ONTOLOGY_ID:HT,keyZ:Ke,labelZ:hn,newZ:gu,ontologyID:vu},Symbol.toStringTag,{value:"Module"})),K=i.z.uuid(),Js=i.z.string().min(1),fn=i.z.object({key:K,name:Js,timeRange:x.z.refine(({isValid:t})=>t,{error:"Time range start time must be before or equal to time range end time"}).refine(({end:t})=>t.valueOf()<=Ur.MAX_INT64,{error:"Time range end time must be less than or equal to the maximum value of an int64"}).refine(({start:t})=>t.valueOf()>=Ur.MIN_INT64,{error:"Time range start time must be greater than or equal to the minimum value of an int64"}),color:i.z.string().optional(),labels:hn.array().or(i.z.null().transform(()=>{})).optional(),get parent(){return fn.optional().nullable().transform(t=>t===void 0?null:t)}}),zu=fn.omit({parent:!0,labels:!0}).partial({key:!0}),KT=i.z.object({nodeKey:Se.uint12.optional(),keys:j.array().optional(),names:i.z.string().array().optional(),searchTerm:i.z.string().optional(),rangeKey:K.optional(),limit:i.z.int().optional(),offset:i.z.int().optional(),dataTypes:y.z.array().optional(),notDataTypes:y.z.array().optional(),virtual:i.z.boolean().optional(),isIndex:i.z.boolean().optional(),internal:i.z.boolean().optional(),legacyCalculated:i.z.boolean().optional()}),JT=i.z.object({channels:S.nullableZ(xt)}),me=t=>(Array.isArray(t)&&t.length>0&&typeof t[0]=="object"?t=t.map(e=>e.key):typeof t=="object"&&"key"in t&&(t=[t.key]),pT(t,{number:"keys",string:"names"}));class Xs{client;constructor(e){this.client=e}async retrieve(e,n){if(!Array.isArray(e)&&typeof e=="object")return await this.execute(e);const r=me(e),{variant:s}=r;let{normalized:a}=r;return s==="keys"&&a.indexOf(0)!==-1&&(a=a.filter(o=>o!==0)),a.length===0?[]:await this.execute({[s]:a,...n})}async execute(e){return(await T(this.client,"/channel/retrieve",e,KT,JT)).channels}}class Qs{cache;namesToKeys;wrapped;constructor(e){this.cache=new Map,this.namesToKeys=new Map,this.wrapped=e}async retrieve(e,n){if(!Array.isArray(e)&&typeof e=="object")return await this.wrapped.retrieve(e);const{normalized:r}=me(e),s=[],a=[];if(r.forEach(c=>{const l=this.get(c);l!=null?s.push(...l):a.push(c)}),a.length===0)return s;const o=await this.wrapped.retrieve(a,n);return this.set(o),s.concat(o)}delete(e){const{variant:n,normalized:r}=me(e);n==="names"?r.forEach(s=>{const a=this.namesToKeys.get(s);a!=null&&(a.forEach(o=>this.cache.delete(o)),this.namesToKeys.delete(s))}):r.forEach(s=>{const a=this.cache.get(s);a!=null&&(this.cache.delete(s),this.namesToKeys.delete(a.name))})}rename(e,n){e.forEach((r,s)=>{const a=n[s],o=this.cache.get(r);if(o==null)return;this.cache.delete(r);const c=this.namesToKeys.get(o.name);c!=null&&(c.delete(r),c.size===0&&this.namesToKeys.delete(o.name)),o.name=a,this.cache.set(r,o);const l=this.namesToKeys.get(a);l==null?this.namesToKeys.set(a,new Set([r])):l.add(r)})}set(e){e.forEach(n=>{this.cache.set(n.key,n);const r=this.namesToKeys.get(n.name);r==null?this.namesToKeys.set(n.name,new Set([n.key])):r.add(n.key)})}get(e){if(typeof e=="number"){const s=this.cache.get(e);return s==null?void 0:[s]}const n=this.namesToKeys.get(e);if(n==null)return;const r=[];if(n.forEach(s=>{const a=this.cache.get(s);a!=null&&r.push(a)}),r.length!==0)return r}}class Tu{mu=new MT;requests=new Map;wrapped;debouncedRun;constructor(e,n){this.wrapped=e,this.debouncedRun=xp(()=>{this.run()},n)}async retrieve(e){if(!Array.isArray(e)&&typeof e=="object")return await this.wrapped.retrieve(e);const{normalized:n,variant:r}=me(e);return r==="names"?await this.wrapped.retrieve(n):await new Promise((a,o)=>{this.mu.runExclusive(()=>{this.requests.set(n,{resolve:a,reject:o}),this.debouncedRun()})})}async run(){await this.mu.runExclusive(async()=>{const e=new Set;this.requests.forEach((n,r)=>r.forEach(s=>e.add(s)));try{const n=await this.wrapped.retrieve(Array.from(e));this.requests.forEach((r,s)=>r.resolve(n.filter(a=>s.includes(a.key))))}catch(n){this.requests.forEach(r=>r.reject(n))}finally{this.requests.clear()}})}}const Ou=async(t,e)=>{const{normalized:n}=me(e),r=await t.retrieve(n),s=[];if(n.forEach(a=>{r.find(o=>o.name===a||o.key===a)==null&&s.push(a)}),s.length>0)throw new Ge(`Could not find channels: ${JSON.stringify(s)}`);return r},XT="sy_channel_set",QT="sy_channel_delete";class Rn{_frameClient;key;name;dataType;leaseholder;index;isIndex;internal;alias;virtual;expression;operations;requires;status;constructor({dataType:e,name:n,leaseholder:r=0,key:s=0,isIndex:a=!1,index:o=0,internal:c=!1,virtual:l=!1,frameClient:u,alias:h,status:d,expression:f="",operations:O=[],requires:E=[]}){this.key=j.parse(s),this.name=n,this.dataType=new y(e),this.leaseholder=r,this.index=j.parse(o),this.isIndex=a,this.internal=c,this.alias=h,this.virtual=l,this.expression=f,this.operations=O,this.requires=E,d!=null&&(this.status=ht.create(d)),this._frameClient=u??null}get framer(){if(this._frameClient==null)throw new V("cannot read from a channel that has not been created");return this._frameClient}get payload(){return xt.parse({key:this.key,name:this.name,dataType:this.dataType.valueOf(),leaseholder:this.leaseholder,index:this.index,isIndex:this.isIndex,internal:this.internal,virtual:this.virtual,requires:this.requires,expression:this.expression,status:this.status,operations:this.operations})}get isCalculated(){return At(this.payload)}get ontologyID(){return Ks(this.key)}async read(e){return await this.framer.read(e,this.key)}async write(e,n){return await this.framer.write(e,this.key,n)}}const eO="sy_calculation_status",tO=i.z.object({}),nO=i.z.object({group:Ln});let Nu=class{frameClient;client;retriever;writer;constructor(e,n,r,s){this.frameClient=e,this.retriever=n,this.client=r,this.writer=s}async create(e,n={}){const{retrieveIfNameExists:r=!1}=n,s=!Array.isArray(e);let a=S.toArray(e),o=[];if(r){const c=await this.retriever.retrieve(a.map(u=>u.name)),l=new Set(c.map(u=>u.name));a=a.filter(u=>!l.has(u.name)),o=this.sugar(c)}return o=o.concat(this.sugar(await this.writer.create(a))),s?o[0]:o}async retrieve(e,n){if(typeof e=="object"&&!Array.isArray(e))return this.sugar(await this.retriever.retrieve(e));const r=!Array.isArray(e),s=this.sugar(await this.retriever.retrieve(e,n));return ie("channel",e,s,r),r?s[0]:s}async delete(e){const{normalized:n,variant:r}=me(e);return r==="keys"?await this.writer.delete({keys:n}):await this.writer.delete({names:n})}async rename(e,n){return await this.writer.rename(S.toArray(e),S.toArray(n))}createDebouncedBatchRetriever(e=10){return new Qs(new Tu(new Xs(this.client),e))}sugar(e){const{frameClient:n}=this;return Array.isArray(e)?e.map(r=>new Rn({...r,frameClient:n})):new Rn({...e,frameClient:n})}async retrieveGroup(){return(await T(this.client,"/channel/retrieve-group",{},tO,nO)).group}};const At=({virtual:t,expression:e})=>t&&e!=="",rO=t=>At(t)&&t.requires.length>0,Su=async(t,e)=>{if(!At(e))return e.index;for(const n of e.requires){const r=await t(n);if(r==null)return null;if(!r.virtual)return r.index}for(const n of e.requires){const r=await t(n);if(r==null)return null;if(At(r)){const s=await Su(t,r);if(s!=null)return s}}return null},sO=i.z.object({channels:pu.array()}),iO=i.z.object({channels:xt.array()}),aO=i.z.object({keys:j.array().optional(),names:Re.array().optional()}),oO=i.z.object({}),cO=i.z.object({keys:j.array(),names:Re.array()}),uO=i.z.object({});let Eu=class{client;cache;constructor(e,n){this.client=e,this.cache=n}async create(e){const{channels:n}=await T(this.client,"/channel/create",{channels:e.map(r=>({...r,dataType:r.dataType}))},sO,iO);return this.cache.set(n),n}async delete(e){const n=j.array().parse(e.keys??[]);await T(this.client,"/channel/delete",e,aO,oO),n.length>0&&this.cache.delete(n),e.names!=null&&this.cache.delete(e.names)}async rename(e,n){await T(this.client,"/channel/rename",{keys:e,names:n},cO,uO),this.cache.rename(e,n)}};const lO=Object.freeze(Object.defineProperty({__proto__:null,CALCULATION_STATUS_CHANNEL_NAME:eO,CacheRetriever:Qs,Channel:Rn,Client:Nu,ClusterRetriever:Xs,DELETE_CHANNEL_NAME:QT,DebouncedBatchRetriever:Tu,OPERATION_TYPES:fu,SET_CHANNEL_NAME:XT,TYPE_ONTOLOGY_ID:AT,Writer:Eu,analyzeParams:me,escapeInvalidName:IT,isCalculated:At,isLegacyCalculated:rO,keyZ:j,nameZ:Re,newZ:pu,ontologyID:Ks,operationType:du,operationZ:Ws,paramsZ:yt,payloadZ:xt,resolveLegacyCalculatedIndex:Su,retrieveRequired:Ou,statusZ:yu},Symbol.toStringTag,{value:"Module"})),hO=i.z.object({username:i.z.string(),password:i.z.string()}),fO=i.z.object({token:i.z.string(),user:an}),sa="/auth/login",dO=3,yO=i.z.object({username:i.z.string(),password:i.z.string(),newPassword:i.z.string().min(1)}),pO=i.z.object({}),mO=[Gr,Hr];let gO=class{client;credentials;authState={authenticated:!1};authenticating;retryCount;constructor(e,n){this.client=e,this.credentials=n,this.retryCount=0}get authenticated(){return this.authState.authenticated}get user(){return this.authState.authenticated?this.authState.user:void 0}get token(){return this.authState.authenticated?this.authState.token:void 0}async retrieveUser(){this.authState.authenticated||await this.authenticating;const{authState:e}=this;if(!e.authenticated)throw new Error("Authentication failed: user not available");return e.user}async changePassword(e){if(!this.authenticated)throw new Error("Not authenticated");await T(this.client,"/auth/change-password",{username:this.credentials.username,password:this.credentials.password,newPassword:e},yO,pO),this.credentials.password=e}middleware(){const e=async(n,r)=>{if(!this.authenticated&&!n.target.endsWith(sa)){this.authenticating??=new Promise((c,l)=>{this.client.send(sa,this.credentials,hO,fO).then(([u,h])=>{if(h!=null)return c(h);if(u==null)return c(new Error("No response from login"));this.authState={authenticated:!0,user:u.user,token:u.token},c(null)}).catch(l)});const o=await this.authenticating;if(o!=null)return[n,o]}n.params.Authorization=`Bearer ${this.token}`;const[s,a]=await r(n);return mO.some(o=>o.matches(a))&&this.retryCount<dO?(this.authState={authenticated:!1},this.authenticating=void 0,this.retryCount+=1,e(n,r)):(this.retryCount=0,[s,a])};return e}};const ku=i.z.enum(["disconnected","connecting","connected","failed"]),Au=i.z.object({status:ku,error:i.z.instanceof(Error).optional(),message:i.z.string().optional(),clusterKey:i.z.string(),clientVersion:i.z.string(),clientServerCompatible:i.z.boolean(),nodeVersion:i.z.string().optional()}),wO=i.z.object({clusterKey:i.z.string(),nodeVersion:i.z.string().optional()}),bO=i.z.void(),ia={clusterKey:"",status:"disconnected",error:void 0,message:"Disconnected",clientServerCompatible:!1,clientVersion:"0.49.3"},aa=(t,e,n)=>{const r=n?"Core":"client";return`Synnax Core version ${t!=null?`${t} `:""}is too ${n?"old":"new"} for client version ${e}.
41
41
  This may cause compatibility issues. We recommend updating the ${r}. For more information, see
42
- https://docs.synnaxlabs.com/reference/typescript-client/troubleshooting#old-${r}-version`};class Cn{static DEFAULT=ta;_state;pollFrequency=g.seconds(30);client;name;interval;clientVersion;onChangeHandlers=[];static connectionStateZ=zu;versionWarned=!1;constructor(e,n=g.seconds(30),r,s){this._state={...ta},this.client=e,this.pollFrequency=n,this.clientVersion=r,this.name=s,this.check(),this.start()}stop(){this.interval!=null&&clearInterval(this.interval)}async check(){const e=this._state.status;try{const n=await z(this.client,"/connectivity/check",void 0,aO,iO),r=n.nodeVersion,s=this.clientVersion,a=this.versionWarned;r==null?(this._state.clientServerCompatible=!1,a||(console.warn(na(null,s,!0)),this.versionWarned=!0)):$i.versionsEqual(s,r,{checkMajor:!0,checkMinor:!0,checkPatch:!1})?this._state.clientServerCompatible=!0:(this._state.clientServerCompatible=!1,a||(console.warn(na(r,s,$i.semVerNewer(s,r))),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=this.state.error?.message}return this.onChangeHandlers.length>0&&e!==this._state.status&&this.onChangeHandlers.forEach(n=>n(this.state)),this.state}get state(){return{...this._state}}onChange(e){this.onChangeHandlers.push(e)}start(){this.interval=setInterval(()=>{this.check()},this.pollFrequency.milliseconds)}}const oO=Object.freeze(Object.defineProperty({__proto__:null,Checker:Cn,stateZ:zu,statusZ:vu},Symbol.toStringTag,{value:"Module"})),cO=i.z.object({keys:M.array().optional(),bounds:Z.z,names:Ie.array().optional()}),uO=i.z.object({});class lO{client;constructor(e){this.client=e}async delete(e){await z(this.client,"/frame/delete",e,cO,uO)}}const ra=t=>{const e=E.toArray(t);return e.length===0?null:typeof e[0]=="number"||!isNaN(parseInt(e[0]))?"key":"name"},sa=(t,e)=>{const n=E.toArray(t);if(n.length===e.length)return;const r=ra(t);throw ra===null?new Y("[Frame] - channel keys or names must be provided when constructing a frame."):new Y(`[Frame] - ${r}s and series must be the same length.
43
- Got ${n.length} ${r}s and ${e.length} series.`)};class P{columns=[];series=[];constructor(e=[],n=[]){if(e instanceof P){this.columns=e.columns,this.series=e.series;return}if(e instanceof Map){e.forEach((s,a)=>this.push(a,...E.toArray(s)));return}if(typeof e=="object"&&!Array.isArray(e)){if("keys"in e&&"series"in e){const s=e;s.series??=[],s.keys??=[];const a=s.series.map(o=>Tu(o));sa(s.keys,a),s.keys.forEach((o,c)=>this.push(o,a[c]))}else Object.entries(e).forEach(([s,a])=>{const o=parseInt(s);if(!isNaN(o))return this.push(o,...E.toArray(a));this.push(s,...E.toArray(a))});return}if(Array.isArray(e)||["string","number"].includes(typeof e)){const s=E.toArray(n),a=E.toArray(e);sa(a,s),s.forEach((o,c)=>this.push(a[c],o));return}throw new Y(`[Frame] - invalid frame construction parameters. data parameter ust be a frame
42
+ https://docs.synnaxlabs.com/reference/typescript-client/troubleshooting#old-${r}-version`};class _n{static DEFAULT=ia;_state;pollFrequency=m.seconds(30);client;name;interval;clientVersion;onChangeHandlers=[];static connectionStateZ=Au;versionWarned=!1;constructor(e,n=m.seconds(30),r,s){this._state={...ia},this.client=e,this.pollFrequency=n,this.clientVersion=r,this.name=s,this.check(),this.start()}stop(){this.interval!=null&&clearInterval(this.interval)}async check(){const e=this._state.status;try{const n=await T(this.client,"/connectivity/check",void 0,bO,wO),r=n.nodeVersion,s=this.clientVersion,a=this.versionWarned;r==null?(this._state.clientServerCompatible=!1,a||(console.warn(aa(null,s,!0)),this.versionWarned=!0)):Ci.versionsEqual(s,r,{checkMajor:!0,checkMinor:!0,checkPatch:!1})?this._state.clientServerCompatible=!0:(this._state.clientServerCompatible=!1,a||(console.warn(aa(r,s,Ci.semVerNewer(s,r))),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=this.state.error?.message}return this.onChangeHandlers.length>0&&e!==this._state.status&&this.onChangeHandlers.forEach(n=>n(this.state)),this.state}get state(){return{...this._state}}onChange(e){this.onChangeHandlers.push(e)}start(){this.interval=setInterval(()=>{this.check()},this.pollFrequency.milliseconds)}}const vO=Object.freeze(Object.defineProperty({__proto__:null,Checker:_n,stateZ:Au,statusZ:ku},Symbol.toStringTag,{value:"Module"})),zO=i.z.object({keys:j.array().optional(),bounds:x.z,names:Re.array().optional()}),TO=i.z.object({});class OO{client;constructor(e){this.client=e}async delete(e){await T(this.client,"/frame/delete",e,zO,TO)}}const oa=t=>{const e=S.toArray(t);return e.length===0?null:typeof e[0]=="number"||!isNaN(parseInt(e[0]))?"key":"name"},ca=(t,e)=>{const n=S.toArray(t);if(n.length===e.length)return;const r=oa(t);throw oa===null?new V("[Frame] - channel keys or names must be provided when constructing a frame."):new V(`[Frame] - ${r}s and series must be the same length.
43
+ Got ${n.length} ${r}s and ${e.length} series.`)};class q{columns=[];series=[];constructor(e=[],n=[]){if(e instanceof q){this.columns=e.columns,this.series=e.series;return}if(e instanceof Map){e.forEach((s,a)=>this.push(a,...S.toArray(s)));return}if(typeof e=="object"&&!Array.isArray(e)){if("keys"in e&&"series"in e){const s=e;s.series??=[],s.keys??=[];const a=s.series.map(o=>$u(o));ca(s.keys,a),s.keys.forEach((o,c)=>this.push(o,a[c]))}else Object.entries(e).forEach(([s,a])=>{const o=parseInt(s);if(!isNaN(o))return this.push(o,...S.toArray(a));this.push(s,...S.toArray(a))});return}if(Array.isArray(e)||["string","number"].includes(typeof e)){const s=S.toArray(n),a=S.toArray(e);ca(a,s),s.forEach((o,c)=>this.push(a[c],o));return}throw new V(`[Frame] - invalid frame construction parameters. data parameter ust be a frame
44
44
  payload, a list of lazy series, a lazy array, a map, or a record keyed by channel
45
- 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 zt("colType is not key");return this.columns??[]}get uniqueKeys(){return Oi.unique(this.keys)}get names(){if(this.colType==="key")throw new zt("colType is not name");return this.columns??[]}get uniqueNames(){return Oi.unique(this.names)}get uniqueColumns(){return this.colType==="key"?this.uniqueKeys:this.uniqueNames}toPayload(){return{series:this.series.map(e=>Ou(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(n=>n.equals(e[0]))}timeRange(e){if(e==null){if(this.columns.length===0)return Z.ZERO;const r=m.min(...this.series.map(a=>a.timeRange.start)),s=m.max(...this.series.map(a=>a.timeRange.end));return new Z(r,s)}const n=this.get(e);return n==null?Z.ZERO:n.timeRange}latest(){return this.at(-1)}get timeRanges(){return this.uniqueColumns.map(e=>this.timeRange(e))}get(e){return Array.isArray(e)?this.filter(n=>e.includes(n)):new Do(this.series.filter((n,r)=>this.columns[r]===e))}push(e,...n){if(e instanceof P){if(e.colType!=null&&this.colType!==null&&e.colType!==this.colType)throw new Y("keyVariant must match");this.series.push(...e.series),this.columns.push(...e.columns)}else{if(this.series.push(...n),typeof e=="string"&&this.colType==="key")throw new Y("keyVariant must match");if(typeof e!="string"&&this.colType==="name")throw new Y("keyVariant must match");this.columns.push(...Array.from({length:n.length},()=>e))}}concat(e){return new P([...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 n=new P;return this.forEach((r,s,a)=>n.push(...e(r,s,a))),n}mapFilter(e){const n=new P;return this.forEach((r,s,a)=>{const[o,c,l]=e(r,s,a);l&&n.push(o,c)}),n}forEach(e){this.columns.forEach((n,r)=>{const s=this.series[r];e(n,s,r)})}forEachUnique(e){this.uniqueColumns.forEach((n,r)=>e(n,this.get(n),r))}at(e,n=!1){const r={};return this.uniqueColumns.forEach(s=>{r[s]=this.get(s).at(e,n)}),r}filter(e){const n=new P;return this.columns.forEach((r,s)=>{const a=this.series[s];e(r,a,s)&&n.push(r,a)}),n}get byteLength(){return new A(this.series.reduce((e,n)=>e.add(n.byteLength),A.ZERO))}get digest(){const e={};return this.keys.forEach((n,r)=>{const s=this.series[r].digest;n in e?e[n].push(s):e[n]=[s]}),e}get length(){return this.series.reduce((e,n)=>e+n.length,0)}toString(){let e=`Frame{
45
+ 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 rt("colType is not key");return this.columns??[]}get uniqueKeys(){return Si.unique(this.keys)}get names(){if(this.colType==="key")throw new rt("colType is not name");return this.columns??[]}get uniqueNames(){return Si.unique(this.names)}get uniqueColumns(){return this.colType==="key"?this.uniqueKeys:this.uniqueNames}toPayload(){return{series:this.series.map(e=>Iu(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(n=>n.equals(e[0]))}timeRange(e){if(e==null){if(this.columns.length===0)return x.ZERO;const r=g.min(...this.series.map(a=>a.timeRange.start)),s=g.max(...this.series.map(a=>a.timeRange.end));return new x(r,s)}const n=this.get(e);return n==null?x.ZERO:n.timeRange}latest(){return this.at(-1)}get timeRanges(){return this.uniqueColumns.map(e=>this.timeRange(e))}get(e){return Array.isArray(e)?this.filter(n=>e.includes(n)):new Fo(this.series.filter((n,r)=>this.columns[r]===e))}push(e,...n){if(e instanceof q){if(e.colType!=null&&this.colType!==null&&e.colType!==this.colType)throw new V("keyVariant must match");this.series.push(...e.series),this.columns.push(...e.columns)}else{if(this.series.push(...n),typeof e=="string"&&this.colType==="key")throw new V("keyVariant must match");if(typeof e!="string"&&this.colType==="name")throw new V("keyVariant must match");this.columns.push(...Array.from({length:n.length},()=>e))}}concat(e){return new q([...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 n=new q;return this.forEach((r,s,a)=>n.push(...e(r,s,a))),n}mapFilter(e){const n=new q;return this.forEach((r,s,a)=>{const[o,c,l]=e(r,s,a);l&&n.push(o,c)}),n}forEach(e){this.columns.forEach((n,r)=>{const s=this.series[r];e(n,s,r)})}forEachUnique(e){this.uniqueColumns.forEach((n,r)=>e(n,this.get(n),r))}at(e,n=!1){const r={};return this.uniqueColumns.forEach(s=>{r[s]=this.get(s).at(e,n)}),r}filter(e){const n=new q;return this.columns.forEach((r,s)=>{const a=this.series[s];e(r,a,s)&&n.push(r,a)}),n}get byteLength(){return new $(this.series.reduce((e,n)=>e.add(n.byteLength),$.ZERO))}get digest(){const e={};return this.keys.forEach((n,r)=>{const s=this.series[r].digest;n in e?e[n].push(s):e[n]=[s]}),e}get length(){return this.series.reduce((e,n)=>e+n.length,0)}toString(){let e=`Frame{
46
46
  `;return this.uniqueColumns.forEach(n=>{e+=` ${n}: ${this.get(n).series.map(r=>r.toString()).join(",")}
47
- `}),e+="}",e}}const Vn=i.z.object({keys:i.z.union([i.z.null().transform(()=>[]),i.z.number().array().default([])]),series:i.z.union([i.z.null().transform(()=>[]),Q.crudeZ.array().default([])])}),Tu=t=>{const{dataType:e,data:n,timeRange:r,alignment:s}=t;return new Q({data:n,dataType:e,timeRange:r,glBufferUsage:"static",alignment:s})},Ou=t=>({timeRange:t.timeRange,dataType:t.dataType,data:new Uint8Array(t.data.buffer),alignment:t.alignment});var ve=(t=>(t[t.Open=0]="Open",t[t.Write=1]="Write",t[t.Commit=2]="Commit",t[t.SetAuthority=3]="SetAuthority",t))(ve||{});const ia=t=>t.data.byteLength/t.dataType.density.valueOf(),hO=t=>{const{keys:e,series:n}=t;e.forEach((r,s)=>{n[s].key=r}),n.sort((r,s)=>r.key-s.key),e.sort((r,s)=>r-s),n.forEach(r=>delete r.key)},aa=5,oa=4,ca=3,ua=2,la=1,ha=0,pe=d.TIMESTAMP.density.valueOf(),Me=8,je=4,mr=4,gr=4,fO=1;class Eu{contentType="application/sy-framer";states=new Map;currState;seqNum=0;constructor(e=[],n=[]){(e.length>0||n.length>0)&&this.update(e,n)}update(e,n){this.seqNum++;const r={keys:e,keyDataTypes:new Map,hasVariableDataTypes:!1};e.forEach((s,a)=>{const o=n[a];r.keyDataTypes.set(s,o),o.isVariable&&(r.hasVariableDataTypes=!0)}),r.keys.sort(),this.states.set(this.seqNum,r),this.currState=r}throwIfNotUpdated(e){if(this.seqNum<1)throw new Y(`
47
+ `}),e+="}",e}}const Wn=i.z.object({keys:i.z.union([i.z.null().transform(()=>[]),i.z.number().array().default([])]),series:i.z.union([i.z.null().transform(()=>[]),Q.crudeZ.array().default([])])}),$u=t=>{const{dataType:e,data:n,timeRange:r,alignment:s}=t;return new Q({data:n,dataType:e,timeRange:r,glBufferUsage:"static",alignment:s})},Iu=t=>({timeRange:t.timeRange,dataType:t.dataType,data:new Uint8Array(t.data.buffer),alignment:t.alignment});var Ne=(t=>(t[t.Open=0]="Open",t[t.Write=1]="Write",t[t.Commit=2]="Commit",t[t.SetAuthority=3]="SetAuthority",t))(Ne||{});const ua=t=>t.data.byteLength/t.dataType.density.valueOf(),NO=t=>{const{keys:e,series:n}=t;e.forEach((r,s)=>{n[s].key=r}),n.sort((r,s)=>r.key-s.key),e.sort((r,s)=>r-s),n.forEach(r=>delete r.key)},la=5,ha=4,fa=3,da=2,ya=1,pa=0,ve=y.TIMESTAMP.density.valueOf(),Pe=8,Le=4,wr=4,br=4,SO=1;class Zu{contentType="application/sy-framer";states=new Map;currState;seqNum=0;constructor(e=[],n=[]){(e.length>0||n.length>0)&&this.update(e,n)}update(e,n){this.seqNum++;const r={keys:e,keyDataTypes:new Map,hasVariableDataTypes:!1};e.forEach((s,a)=>{const o=n[a];r.keyDataTypes.set(s,o),o.isVariable&&(r.hasVariableDataTypes=!0)}),r.keys.sort(),this.states.set(this.seqNum,r),this.currState=r}throwIfNotUpdated(e){if(this.seqNum<1)throw new V(`
48
48
  The codec has not been updated with a list of channels and data types.
49
49
  Please call the update method before calling ${e}.
50
- `)}encode(e,n=0){this.throwIfNotUpdated("encode");let r=e;e!=null&&typeof e=="object"&&"toPayload"in e&&(r=e.toPayload()),hO(r);let s=-1,a,o,c,l=n+fO+gr,u=!this.currState?.hasVariableDataTypes,h=!0,y=!0,f=!0,T=!0,S=!0;r.keys.length!==this.currState?.keys.length&&(f=!1,l+=r.keys.length*mr),r.series.forEach(($,G)=>{const q=ia($),ue=r.keys[G],Ge=this.currState?.keyDataTypes.get(ue);if(Ge==null)throw new Y(`Channel ${ue} was not provided in the list of channels when opening the writer`);if(!Ge.equals($.dataType))throw new Y(`Series data type of ${$.dataType.toString()} does not match the data type of ${Ge.toString()} for channel ${ue}`);if(l+=$.data.byteLength,s===-1){s=q,a=$.timeRange?.start,o=$.timeRange?.end,c=BigInt($.alignment??0n);return}s!==q&&(u=!1),(a?.valueOf()!==$.timeRange?.start.valueOf()||o?.valueOf()!==$.timeRange?.end.valueOf())&&(h=!1),c!==BigInt($.alignment??0)&&(T=!1)}),y=h&&a==null&&o==null,S=T&&(c===void 0||c===0n),u?l+=je:l+=r.keys.length*je,y||(h?l+=pe*2:l+=r.keys.length*pe*2),S||(T?l+=Me:l+=r.keys.length*Me);const x=new Uint8Array(l),O=new DataView(x.buffer);let N=n;return x[N]=Number(S)<<aa|Number(T)<<oa|Number(u)<<ca|Number(h)<<ua|Number(y)<<la|Number(f)<<ha,N++,O.setUint32(N,this.seqNum,!0),N+=gr,u&&(O.setUint32(N,s,!0),N+=je),h&&!y&&(O.setBigUint64(N,a?.valueOf()??0n,!0),O.setBigUint64(N,o?.valueOf()??0n,!0),N+=pe*2),T&&!S&&(O.setBigUint64(N,c??0n,!0),N+=Me),r.series.forEach(($,G)=>{if(f||(O.setUint32(N,r.keys[G],!0),N+=mr),!u){let q=$.data.byteLength;$.dataType.isVariable||(q=ia($)),O.setUint32(N,q,!0),N+=je}x.set(new Uint8Array($.data),N),N+=$.data.byteLength,!h&&!y&&(O.setBigUint64(N,$.timeRange?.start.valueOf()??0n,!0),O.setBigUint64(N,$.timeRange?.end.valueOf()??0n,!0),N+=pe*2),!T&&!S&&(O.setBigUint64(N,$.alignment??0n,!0),N+=Me)}),x}decode(e,n=0){this.throwIfNotUpdated("decode");const r=e instanceof Uint8Array?e:new Uint8Array(e),s={keys:[],series:[]};let a=n,o=0,c=0,l,u,h;const y=new DataView(r.buffer,r.byteOffset,r.byteLength),f=!!(r[a]>>aa&1),T=!!(r[a]>>oa&1),S=!!(r[a]>>ca&1),x=!!(r[a]>>ua&1),O=!!(r[a]>>la&1),N=!!(r[a]>>ha&1);a++;const $=y.getUint32(a,!0);a+=gr;const G=this.states.get($);if(G==null)return s;if(S){if(a+je>y.byteLength)return s;o=y.getUint32(a,!0),a+=je}if(x&&!O){if(a+pe>y.byteLength)return s;l=new m(y.getBigUint64(a,!0)),a+=pe,u=new m(y.getBigUint64(a,!0)),a+=pe}if(T&&!f){if(a+Me>y.byteLength)return s;h=y.getBigUint64(a,!0),a+=Me}return N&&(s.keys=[...G.keys]),G.keys.forEach((q,ue)=>{if(!N){if(a>=y.byteLength||y.getUint32(a,!0)!==q)return;a+=mr,s.keys.push(q)}const Ge=G.keyDataTypes.get(q);if(c=0,S)c=o;else{if(a+je>y.byteLength)return;c=y.getUint32(a,!0),a+=je}let dn=c;if(Ge.isVariable||(dn*=Ge.density.valueOf()),a+dn>y.byteLength){s.keys.splice(ue,1);return}const We={dataType:Ge,data:r.slice(a,a+dn).buffer};if(a+=dn,!x&&!O){if(a+pe*2>y.byteLength)return;const hi=y.getBigUint64(a,!0);a+=pe;const Vl=y.getBigUint64(a,!0);a+=pe,We.timeRange=new Z({start:hi,end:Vl})}else O?We.timeRange=new Z({start:0n,end:0n}):We.timeRange=new Z({start:l?.valueOf()??0n,end:u?.valueOf()??0n});if(!T&&!f){if(a+Me>y.byteLength)return;h=y.getBigUint64(a,!0),a+=Me,We.alignment=h}else f?We.alignment=0n:We.alignment=h;s.series.push(We)}),s}}const Xs=254,dO=new Uint8Array([Xs]),yO=255,pO=new Uint8Array([yO]),Nu="application/sy-framer";class mO{contentType=Nu;base;lowPerfCodec;constructor(e){this.base=e,this.lowPerfCodec=it.JSON_CODEC}encode(e){const n=e;if(n.type=="close"||n.payload?.command!=ve.Write){const s=this.lowPerfCodec.encode(n),a=new Uint8Array({length:s.byteLength+1});return a.set(dO,0),a.set(new Uint8Array(s),1),a}const r=this.base.encode(n.payload?.frame,1);return r.set(pO,0),r}decode(e,n){if(new DataView(e instanceof Uint8Array?e.buffer:e).getUint8(0)===Xs)return this.lowPerfCodec.decode(e.slice(1),n);const a={type:"data"},o=this.base.decode(e,1);return a.payload={command:ve.Write,frame:o},a}}class gO{contentType=Nu;base;lowPerfCodec;constructor(e){this.base=e,this.lowPerfCodec=it.JSON_CODEC}encode(e){return this.lowPerfCodec.encode(e)}decode(e,n){return new DataView(e instanceof Uint8Array?e.buffer:e).getUint8(0)===Xs?this.lowPerfCodec.decode(e.slice(1),n):{type:"data",payload:{frame:this.base.decode(e,1)}}}}class Gn{adapter;retriever;keys;codec;constructor(e){this.retriever=e,this.adapter=null,this.keys=new Set,this.codec=new Eu}static async open(e,n){const r=new Gn(e);return await r.update(n),r}async update(e){const{variant:n,normalized:r}=he(e),s=await this.retriever.retrieve(r),a=s.map(c=>c.key);if(Ei.uniqueUnorderedPrimitiveArrays(Array.from(this.keys),a)===Ei.EQUAL)return!1;if(this.codec.update(a,s.map(c=>c.dataType)),n==="keys")return this.adapter=null,this.keys=new Set(r),!0;const o=new Map;return this.adapter=o,r.forEach(c=>{const l=s.find(u=>u.name===c);if(l==null)throw new Error(`Channel ${c} not found`);o.set(l.key,l.name)}),this.keys=new Set(this.adapter.keys()),!0}adapt(e){if(this.adapter==null){let r=!1;return e.forEach(s=>{this.keys.has(s)||(r=!0)}),r?e.filter(s=>this.keys.has(s)):e}const n=this.adapter;return e.mapFilter((r,s)=>{if(typeof r=="number"){const a=n.get(r);return a==null?[r,s,!1]:[a,s,!0]}return[r,s,!0]})}}class Qs{adapter;retriever;keys;codec;constructor(e){this.retriever=e,this.adapter=null,this.keys=[],this.codec=new Eu}static async open(e,n){const r=new Qs(e);return await r.update(n),r}async adaptParams(e){const n=ht.parse(e);return await Promise.all(n.map(async s=>await this.adaptToKey(s)))}async update(e){const n=await mu(this.retriever,e),r=n.map(u=>u.key),s=new Set(this.keys),a=new Set(r),o=!a.isSubsetOf(s),c=!s.isSubsetOf(a);return o||c?(this.adapter=new Map(n.map(u=>[u.name,u.key])),this.keys=r,this.codec.update(this.keys,n.map(u=>u.dataType)),!0):!1}async fetchChannel(e){const n=await this.retriever.retrieve(e);if(n.length===0)throw new Error(`Channel ${JSON.stringify(e)} not found`);return n[0]}async adaptToKey(e){return typeof e=="number"?e:(await this.fetchChannel(e)).key}encode(e){return this.codec.encode(e.toPayload())}async adapt(e,n){if(typeof e=="string"||typeof e=="number"){if(n==null)throw new Y(`
50
+ `)}encode(e,n=0){this.throwIfNotUpdated("encode");let r=e;e!=null&&typeof e=="object"&&"toPayload"in e&&(r=e.toPayload()),NO(r);let s=-1,a,o,c,l=n+SO+br,u=!this.currState?.hasVariableDataTypes,h=!0,d=!0,f=!0,O=!0,E=!0;r.keys.length!==this.currState?.keys.length&&(f=!1,l+=r.keys.length*wr),r.series.forEach((A,D)=>{const R=ua(A),M=r.keys[D],ae=this.currState?.keyDataTypes.get(M);if(ae==null)throw new V(`Channel ${M} was not provided in the list of channels when opening the writer`);if(!ae.equals(A.dataType))throw new V(`Series data type of ${A.dataType.toString()} does not match the data type of ${ae.toString()} for channel ${M}`);if(l+=A.data.byteLength,s===-1){s=R,a=A.timeRange?.start,o=A.timeRange?.end,c=BigInt(A.alignment??0n);return}s!==R&&(u=!1),(a?.valueOf()!==A.timeRange?.start.valueOf()||o?.valueOf()!==A.timeRange?.end.valueOf())&&(h=!1),c!==BigInt(A.alignment??0)&&(O=!1)}),d=h&&a==null&&o==null,E=O&&(c===void 0||c===0n),u?l+=Le:l+=r.keys.length*Le,d||(h?l+=ve*2:l+=r.keys.length*ve*2),E||(O?l+=Pe:l+=r.keys.length*Pe);const Z=new Uint8Array(l),z=new DataView(Z.buffer);let N=n;return Z[N]=Number(E)<<la|Number(O)<<ha|Number(u)<<fa|Number(h)<<da|Number(d)<<ya|Number(f)<<pa,N++,z.setUint32(N,this.seqNum,!0),N+=br,u&&(z.setUint32(N,s,!0),N+=Le),h&&!d&&(z.setBigUint64(N,a?.valueOf()??0n,!0),z.setBigUint64(N,o?.valueOf()??0n,!0),N+=ve*2),O&&!E&&(z.setBigUint64(N,c??0n,!0),N+=Pe),r.series.forEach((A,D)=>{if(f||(z.setUint32(N,r.keys[D],!0),N+=wr),!u){let R=A.data.byteLength;A.dataType.isVariable||(R=ua(A)),z.setUint32(N,R,!0),N+=Le}Z.set(new Uint8Array(A.data),N),N+=A.data.byteLength,!h&&!d&&(z.setBigUint64(N,A.timeRange?.start.valueOf()??0n,!0),z.setBigUint64(N,A.timeRange?.end.valueOf()??0n,!0),N+=ve*2),!O&&!E&&(z.setBigUint64(N,A.alignment??0n,!0),N+=Pe)}),Z}decode(e,n=0){this.throwIfNotUpdated("decode");const r=e instanceof Uint8Array?e:new Uint8Array(e),s={keys:[],series:[]};let a=n,o=0,c=0,l,u,h;const d=new DataView(r.buffer,r.byteOffset,r.byteLength),f=!!(r[a]>>la&1),O=!!(r[a]>>ha&1),E=!!(r[a]>>fa&1),Z=!!(r[a]>>da&1),z=!!(r[a]>>ya&1),N=!!(r[a]>>pa&1);a++;const A=d.getUint32(a,!0);a+=br;const D=this.states.get(A);if(D==null)return s;if(E){if(a+Le>d.byteLength)return s;o=d.getUint32(a,!0),a+=Le}if(Z&&!z){if(a+ve>d.byteLength)return s;l=new g(d.getBigUint64(a,!0)),a+=ve,u=new g(d.getBigUint64(a,!0)),a+=ve}if(O&&!f){if(a+Pe>d.byteLength)return s;h=d.getBigUint64(a,!0),a+=Pe}return N&&(s.keys=[...D.keys]),D.keys.forEach((R,M)=>{if(!N){if(a>=d.byteLength||d.getUint32(a,!0)!==R)return;a+=wr,s.keys.push(R)}const ae=D.keyDataTypes.get(R);if(c=0,E)c=o;else{if(a+Le>d.byteLength)return;c=d.getUint32(a,!0),a+=Le}let oe=c;if(ae.isVariable||(oe*=ae.density.valueOf()),a+oe>d.byteLength){s.keys.splice(M,1);return}const de={dataType:ae,data:r.slice(a,a+oe).buffer};if(a+=oe,!Z&&!z){if(a+ve*2>d.byteLength)return;const di=d.getBigUint64(a,!0);a+=ve;const th=d.getBigUint64(a,!0);a+=ve,de.timeRange=new x({start:di,end:th})}else z?de.timeRange=new x({start:0n,end:0n}):de.timeRange=new x({start:l?.valueOf()??0n,end:u?.valueOf()??0n});if(!O&&!f){if(a+Pe>d.byteLength)return;h=d.getBigUint64(a,!0),a+=Pe,de.alignment=h}else f?de.alignment=0n:de.alignment=h;s.series.push(de)}),s}}const ei=254,EO=new Uint8Array([ei]),kO=255,AO=new Uint8Array([kO]),xu="application/sy-framer";class $O{contentType=xu;base;lowPerfCodec;constructor(e){this.base=e,this.lowPerfCodec=ct.JSON_CODEC}encode(e){const n=e;if(n.type=="close"||n.payload?.command!=Ne.Write){const s=this.lowPerfCodec.encode(n),a=new Uint8Array({length:s.byteLength+1});return a.set(EO,0),a.set(new Uint8Array(s),1),a}const r=this.base.encode(n.payload?.frame,1);return r.set(AO,0),r}decode(e,n){if(new DataView(e instanceof Uint8Array?e.buffer:e).getUint8(0)===ei)return this.lowPerfCodec.decode(e.slice(1),n);const a={type:"data"},o=this.base.decode(e,1);return a.payload={command:Ne.Write,frame:o},a}}class IO{contentType=xu;base;lowPerfCodec;constructor(e){this.base=e,this.lowPerfCodec=ct.JSON_CODEC}encode(e){return this.lowPerfCodec.encode(e)}decode(e,n){return new DataView(e instanceof Uint8Array?e.buffer:e).getUint8(0)===ei?this.lowPerfCodec.decode(e.slice(1),n):{type:"data",payload:{frame:this.base.decode(e,1)}}}}class Kn{adapter;retriever;keys;codec;constructor(e){this.retriever=e,this.adapter=null,this.keys=new Set,this.codec=new Zu}static async open(e,n){const r=new Kn(e);return await r.update(n),r}async update(e){const{variant:n,normalized:r}=me(e),s=await this.retriever.retrieve(r),a=s.map(c=>c.key);if(Ei.uniqueUnorderedPrimitiveArrays(Array.from(this.keys),a)===Ei.EQUAL)return!1;if(this.codec.update(a,s.map(c=>c.dataType)),n==="keys")return this.adapter=null,this.keys=new Set(r),!0;const o=new Map;return this.adapter=o,r.forEach(c=>{const l=s.find(u=>u.name===c);if(l==null)throw new Error(`Channel ${c} not found`);o.set(l.key,l.name)}),this.keys=new Set(this.adapter.keys()),!0}adapt(e){if(this.adapter==null){let r=!1;return e.forEach(s=>{this.keys.has(s)||(r=!0)}),r?e.filter(s=>this.keys.has(s)):e}const n=this.adapter;return e.mapFilter((r,s)=>{if(typeof r=="number"){const a=n.get(r);return a==null?[r,s,!1]:[a,s,!0]}return[r,s,!0]})}}class ti{adapter;retriever;keys;codec;constructor(e){this.retriever=e,this.adapter=null,this.keys=[],this.codec=new Zu}static async open(e,n){const r=new ti(e);return await r.update(n),r}async adaptParams(e){const n=yt.parse(e);return await Promise.all(n.map(async s=>await this.adaptToKey(s)))}async update(e){const n=await Ou(this.retriever,e),r=n.map(u=>u.key),s=new Set(this.keys),a=new Set(r),o=!a.isSubsetOf(s),c=!s.isSubsetOf(a);return o||c?(this.adapter=new Map(n.map(u=>[u.name,u.key])),this.keys=r,this.codec.update(this.keys,n.map(u=>u.dataType)),!0):!1}async fetchChannel(e){const n=await this.retriever.retrieve(e);if(n.length===0)throw new Error(`Channel ${JSON.stringify(e)} not found`);return n[0]}async adaptToKey(e){return typeof e=="number"?e:(await this.fetchChannel(e)).key}encode(e){return this.codec.encode(e.toPayload())}async adapt(e,n){if(typeof e=="string"||typeof e=="number"){if(n==null)throw new V(`
51
51
  Received a single channel name or key but no series.
52
- `);if(Array.isArray(n)){if(n.some(l=>l instanceof Q||Array.isArray(l)))throw new Y(`
52
+ `);if(Array.isArray(n)){if(n.some(l=>l instanceof Q||Array.isArray(l)))throw new V(`
53
53
  Received a single channel name or key but multiple series.
54
- `);n=n}const o=await this.fetchChannel(e),c=new Q({data:n,dataType:o.dataType});return new P(o.key,c)}if(Array.isArray(e)){if(n==null)throw new Y(`
54
+ `);n=n}const o=await this.fetchChannel(e),c=new Q({data:n,dataType:o.dataType});return new q(o.key,c)}if(Array.isArray(e)){if(n==null)throw new V(`
55
55
  Received an array of channel names or keys but no series.
56
- `);if(!Array.isArray(n))throw new Y(`
56
+ `);if(!Array.isArray(n))throw new V(`
57
57
  Received an array of channel names or keys but no array of series.
58
- `);const o=[],c=[];for(let l=0;l<e.length;l++){const u=await this.fetchChannel(e[l]);if(l>=n.length)throw new Y(`
58
+ `);const o=[],c=[];for(let l=0;l<e.length;l++){const u=await this.fetchChannel(e[l]);if(l>=n.length)throw new V(`
59
59
  Received an array of channel names or keys but not enough series.
60
- `);const h=new Q({data:n[l],dataType:u.dataType});o.push(u.key),c.push(h)}return new P(o,c)}if(e instanceof P||e instanceof Map){const o=new P(e);if(this.adapter==null)return o;const c=o.columns.map(l=>{const u=typeof l=="string"?this.adapter?.get(l):l;if(u==null)throw new Y(`
60
+ `);const h=new Q({data:n[l],dataType:u.dataType});o.push(u.key),c.push(h)}return new q(o,c)}if(e instanceof q||e instanceof Map){const o=new q(e);if(this.adapter==null)return o;const c=o.columns.map(l=>{const u=typeof l=="string"?this.adapter?.get(l):l;if(u==null)throw new V(`
61
61
  Channel ${l} was not provided in the list of channels when opening the writer
62
- `);return u});return new P(c,o.series)}const r=[],s=[],a=Object.entries(e);for(let o=0;o<a.length;o++){const[c,l]=a[o],u=await this.fetchChannel(c),h=new Q({data:l,dataType:u.dataType});r.push(u.key),s.push(h)}return new P(r,s)}}class Su{name;stream;constructor(e,n){this.stream=n,this.name=e}async receive(){const[e,n]=await this.stream.receive();if(n!=null)throw n;return e}received(){return this.stream.received()}async closeAndAck(){for(this.stream.closeSend();;){const[e,n]=await this.stream.receive();if(e!=null&&console.warn(`${this.name} received unexpected response on ${JSON.stringify(e)} closure.
63
- Please report this error to the Synnax team.`),n!=null){if(fe.matches(n))return;throw n}}}closeSend(){this.stream.closeSend()}send(e){const n=this.stream.send(e);if(n!=null)throw n}}const Rn=new g(-1);var ei=(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))(ei||{}),ku=(t=>(t[t.None=0]="None",t[t.Ack=1]="Ack",t[t.Data=2]="Data",t))(ku||{});const wO=i.z.object({command:i.z.enum(ei),span:g.z.optional(),bounds:Z.z.optional(),stamp:m.z.optional(),keys:M.array().optional(),chunkSize:i.z.number().optional()}),bO=i.z.object({variant:i.z.enum(ku),ack:i.z.boolean(),command:i.z.enum(ei),error:Ze.payloadZ.optional().nullable(),frame:Vn.optional()});class Wn{stream;adapter;value;constructor(e,n){this.stream=new Su("Iterator",e),this.value=new P,this.adapter=n}static async _open(e,n,r,s,a={}){const o=await Gn.open(r,n),c=await s.stream("/frame/iterate",wO,bO),l=new Wn(c,o);return await l.execute({command:0,keys:Array.from(o.keys),bounds:new Z(e),chunkSize:a.chunkSize??1e5}),l}async next(e=Rn){return await this.execute({command:1,span:new g(e)})}async prev(e=Rn){return await this.execute({command:2,span:new g(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 m(e)})}async seekGE(e){return await this.execute({command:6,stamp:new m(e)})}async valid(){return await this.execute({command:7})}async close(){await this.stream.closeAndAck()}[Symbol.asyncIterator](){return new vO(this)}async execute(e){for(this.stream.send(e),this.value=new P;;){const n=await this.stream.receive();if(n.variant===1)return n.ack;this.value.push(this.adapter.adapt(new P(n.frame)))}}}class vO{iter;open=!1;constructor(e){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 zO=i.z.object({keys:i.z.number().array(),downsampleFactor:i.z.int(),throttleRate:F.z.optional()}),TO=i.z.object({frame:Vn}),fa=i.z.object({channels:ht,downsampleFactor:i.z.int().default(1),throttleRate:F.z.default(new F(0)),useHighPerformanceCodec:i.z.boolean().default(!0)}),ti=fa.or(ht.transform(t=>fa.parse({channels:t}))),Au=(t,e)=>async n=>{const r=ti.parse(n),s=await Gn.open(t,r.channels);r.useHighPerformanceCodec&&(e=e.withCodec(new gO(s.codec)));const a=await e.stream("/frame/stream",zO,TO),o=new OO(a,s,r.downsampleFactor,r.throttleRate);a.send({keys:Array.from(s.keys),downsampleFactor:r.downsampleFactor,throttleRate:r.throttleRate});const[,c]=await a.receive();if(c!=null)throw c;return o},$u=async(t,e,n)=>await Au(t,e)(n);class OO{stream;adapter;downsampleFactor;throttleRate;constructor(e,n,r=1,s=new F(0)){this.stream=new Su("Streamer",e),this.adapter=n,this.downsampleFactor=r,this.throttleRate=s}get keys(){return Array.from(this.adapter.keys)}async next(){try{return{done:!1,value:await this.read()}}catch(e){if(fe.matches(e))return{done:!0,value:void 0};throw e}}async read(){return this.adapter.adapt(new P((await this.stream.receive()).frame))}async update(e){await this.adapter.update(e)&&this.stream.send({keys:Array.from(this.adapter.keys),downsampleFactor:this.downsampleFactor,throttleRate:this.throttleRate})}close(){this.stream.closeSend()}[Symbol.asyncIterator](){return this}}class Kn{wrapped_=null;breaker;opener;config;constructor(e,n,r={}){this.opener=e,this.config=ti.parse(n);const{maxRetries:s=5e3,baseInterval:a=g.seconds(1),scale:o=1}=r??{};this.breaker=new Ss.Breaker({maxRetries:s,baseInterval:a,scale:o})}static async open(e,n,r){const s=new Kn(e,n,r);return await s.runStreamer(),s}async runStreamer(){for(;;)try{this.wrapped_!=null&&this.wrapped_.close(),this.wrapped_=await this.opener(this.config),this.breaker.reset();return}catch(e){if(this.wrapped_=null,!await this.breaker.wait())throw e;console.error("failed to open streamer",e);continue}}get wrapped(){if(this.wrapped_==null)throw new Error("stream closed");return this.wrapped_}async update(e){this.config.channels=ht.parse(e);try{await this.wrapped.update(e)}catch{return await this.runStreamer(),await this.update(e)}}async next(){try{return{done:!1,value:await this.read()}}catch(e){if(fe.matches(e))return{done:!0,value:void 0};throw e}}async read(){try{const e=await this.wrapped.read();return this.breaker.reset(),e}catch(e){if(fe.matches(e))throw e;return await this.runStreamer(),await this.read()}}close(){this.wrapped.close()}get keys(){return this.wrapped.keys}[Symbol.asyncIterator](){return this}}class Iu extends Gp.Observer{streamer;closePromise;constructor(e,n){super(n),this.streamer=e,this.closePromise=this.stream()}async update(e){await this.streamer.update(e)}async close(){this.streamer.close(),await this.closePromise}async stream(){for await(const e of this.streamer)this.notify(e)}}var Gt=(t=>(t[t.PersistStream=1]="PersistStream",t[t.Persist=2]="Persist",t[t.Stream=3]="Stream",t))(Gt||{});const EO=new g(-1);class ts extends Te.sub("writer_closed"){constructor(){super("WriterClosed")}}const NO=i.z.enum(Gt).or(i.z.enum(["persist","stream","persistStream"]).transform(t=>{switch(t){case"persist":return 2;case"stream":return 3;case"persistStream":return 1}})),Zu=i.z.object({start:m.z.optional(),controlSubject:ae.subjectZ.optional(),authorities:i.z.union([ae.authorityZ.transform(t=>[t]),ae.authorityZ.array()]).default([ae.ABSOLUTE_AUTHORITY]),mode:NO.default(1),errOnUnauthorized:i.z.boolean().default(!1),enableAutoCommit:i.z.boolean().default(!0),autoIndexPersistInterval:g.z.default(g.SECOND),useHighPerformanceCodec:i.z.boolean().default(!0)}),SO=Zu.extend({keys:M.array().optional()}),da=Zu.extend({channels:ht}),xu=da.or(ht.transform(t=>da.parse({channels:t,start:m.now()}))),kO=i.z.object({command:i.z.enum(ve),config:SO.optional(),frame:Vn.optional(),buffer:i.z.instanceof(Uint8Array).optional()}),AO=i.z.object({command:i.z.enum(ve),end:m.z,err:Ze.payloadZ.optional()}),$O=i.z.tuple([i.z.union([i.z.record(M.or(Ie),ae.authorityZ),M.or(Ie),ae.authorityZ]),ae.authorityZ.optional()]).transform(([t,e])=>{if(ae.authorityZ.safeParse(t).success)return{keys:[],authorities:[t]};if(M.or(Ie).safeParse(t).success){if(e==null)throw new Error("authority is required when setting authority for a single channel");return{keys:[t],authorities:[e]}}const n=t;return{keys:Object.keys(n),authorities:Object.values(n)}});let Cu=class Ru{stream;adapter;closeErr=null;constructor(e,n){this.stream=e,this.adapter=n}static async _open(e,n,r){const s=xu.parse(r),a=await Qs.open(e,s.channels);s.useHighPerformanceCodec&&(n=n.withCodec(new mO(a.codec)));const o=await n.stream("/frame/write",kO,AO),c=new Ru(o,a);return await c.execute({command:ve.Open,config:{...s,keys:a.keys}}),c}async write(e,n){if(this.closeErr!=null)throw this.closeErr;if(this.stream.received())return await this.close();const r=await this.adapter.adapt(e,n);this.stream.send({command:ve.Write,frame:r.toPayload()})}async setAuthority(e,n){if(this.closeErr!=null)throw this.closeErr;const r=$O.parse([e,n]),s={keys:await this.adapter.adaptParams(r.keys),authorities:r.authorities};await this.execute({command:ve.SetAuthority,config:s})}async commit(){if(this.closeErr!=null)throw this.closeErr;return this.stream.received()?(await this.closeInternal(null),m.ZERO):(await this.execute({command:ve.Commit})).end}async close(){await this.closeInternal(null)}async closeInternal(e){if(this.closeErr!=null)throw this.closeErr;for(this.closeErr=e,this.stream.closeSend();;){if(this.closeErr!=null){if(ts.matches(this.closeErr))return null;throw this.closeErr}const[n,r]=await this.stream.receive();r!=null?this.closeErr=fe.matches(r)?new ts:r:this.closeErr=Ze.decode(n?.err)}}async execute(e){const n=this.stream.send(e);for(n!=null&&await this.closeInternal(n);;){const[r,s]=await this.stream.receive();s!=null&&await this.closeInternal(s);const a=Ze.decode(r?.err);if(a!=null&&await this.closeInternal(a),r?.command==e.command)return r}}};const _u=H("framer"),IO=_u("");let Mu=class{streamClient;retriever;deleter;constructor(e,n,r){this.streamClient=e,this.retriever=r,this.deleter=new lO(n)}async openIterator(e,n,r){return await Wn._open(e,n,this.retriever,this.streamClient,r)}async openWriter(e){return await Cu._open(this.retriever,this.streamClient,e)}async openStreamer(e){return await $u(this.retriever,this.streamClient,e)}async write(e,n,r){if(r==null){const a=n,o=await this.openWriter({start:e,channels:Object.keys(a),mode:Gt.Persist,errOnUnauthorized:!0,autoIndexPersistInterval:g.MAX});return await o.write(a),await o.close()}const s=await this.openWriter({start:e,channels:n,mode:Gt.Persist,errOnUnauthorized:!0,autoIndexPersistInterval:g.MAX});await s.write(n,r),await s.close()}async read(e,n){const{single:r}=he(n),s=await this.readFrame(e,n);return r?s.get(n):s}async readFrame(e,n){const r=await this.openIterator(e,n),s=new P;try{for await(const a of r)s.push(a)}finally{await r.close()}return s}async readLatest(e,n=1){const{single:r}=he(e),s=await this.readLatestNFrame(e,n);return r?s.get(e):s}async readLatestNFrame(e,n){const r=await this.openIterator(Z.MAX,e,{chunkSize:n}),s=new P;if(n>0)try{await r.seekLast(),await r.prev(Rn),s.push(r.value)}finally{await r.close()}return s}async delete(e,n){const{normalized:r,variant:s}=he(e),a=new Z(n);return s==="keys"?await this.deleter.delete({keys:r,bounds:a}):await this.deleter.delete({names:r,bounds:a})}};const ZO=Object.freeze(Object.defineProperty({__proto__:null,ALWAYS_INDEX_PERSIST_ON_AUTO_COMMIT:EO,AUTO_SPAN:Rn,Client:Mu,Frame:P,HardenedStreamer:Kn,Iterator:Wn,ObservableStreamer:Iu,TYPE_ONTOLOGY_ID:IO,Writer:Cu,WriterClosedError:ts,WriterCommand:ve,WriterMode:Gt,createStreamOpener:Au,frameZ:Vn,ontologyID:_u,openStreamer:$u,seriesFromPayload:Tu,seriesToPayload:Ou,streamerConfigZ:ti,writerConfigZ:xu},Symbol.toStringTag,{value:"Module"})),xO=ae.ABSOLUTE_AUTHORITY,CO=ae.ZERO_AUTHORITY,RO=ae.stateZ(i.z.number()),_O=t=>t.to==null?`${t.from?.resource} - ${t.from?.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()})`,MO=i.z.object({transfers:i.z.array(ae.transferZ(M))});class ju extends Iu{states;codec;constructor(e){super(e,n=>{const r=this.codec.decode(n.series[0].buffer,MO);return this.merge(r),[r.transfers,!0]}),this.states=new Map,this.codec=new it.JSONCodec}subjects(){const e=new Map;return this.states.forEach(n=>e.set(n.subject.key,n.subject)),Array.from(e.values())}merge(e){e.transfers.forEach(n=>{n.from==null&&n.to==null&&console.warn("Invalid transfer: ",n),n.to==null?this.states.delete(n.from.resource):this.states.set(n.to.resource,n.to)})}}const Uu="sy_node_1_control";let Du=class{framer;constructor(e){this.framer=e}async openStateTracker(){const e=await Kn.open(async n=>await this.framer.openStreamer(n),Uu);return new ju(e)}};const jO=Object.freeze(Object.defineProperty({__proto__:null,ABSOLUTE_AUTHORITY:xO,CONTROL_STATE_CHANNEL_NAME:Uu,Client:Du,StateTracker:ju,ZERO_AUTHORITY:CO,stateZ:RO,transferString:_O},Symbol.toStringTag,{value:"Module"})),ye=i.z.uint32(),Lu=i.z.object({rack:ye}),Pu=ct.statusZ(Lu),Jn=i.z.object({key:ye,name:i.z.string(),status:ze.nullToUndefined(Pu)}),Bu=Jn.partial({key:!0}),qu=t=>t?it.JSON_CODEC.decodeString(t,de.unknownZ):{},Zt=i.z.string(),Fu=i.z.object({rack:ye,device:Zt}),Yu=ct.statusZ(Fu),Xn=i.z.object({key:Zt,rack:ye.min(1,"Must select a location to connect from"),name:i.z.string().min(1,"Name is required"),make:i.z.string().min(1,"Make is required"),model:i.z.string().min(1,"Model is required"),location:i.z.string().min(1,"Location is required"),configured:i.z.boolean().optional(),properties:de.unknownZ.or(i.z.string().transform(qu)),status:ze.nullToUndefined(Yu)}),Hu=Xn.extend({properties:i.z.unknown().transform(t=>it.JSON_CODEC.encodeString(t))}),UO="sy_device_set",DO="sy_device_delete",LO=i.z.object({devices:Hu.array()}),PO=i.z.object({devices:Xn.array()}),BO=i.z.object({keys:Zt.array()}),qO=i.z.object({}),FO=i.z.object({keys:Zt.array().optional(),names:i.z.string().array().optional(),makes:i.z.string().array().optional(),models:i.z.string().array().optional(),locations:i.z.string().array().optional(),racks:ye.array().optional(),searchTerm:i.z.string().optional(),limit:i.z.int().optional(),offset:i.z.int().optional(),includeStatus:i.z.boolean().optional()}),YO=i.z.object({devices:E.nullableZ(Xn)}),HO=i.z.object({key:Zt,includeStatus:i.z.boolean().optional()}).transform(({key:t,includeStatus:e})=>({keys:[t],includeStatus:e})),VO=i.z.union([HO,FO]);let Vu=class{client;constructor(e){this.client=e}async retrieve(e){const n=typeof e=="object"&&"key"in e,r=await z(this.client,"/device/retrieve",e,VO,YO);re("Device",e,r.devices,n);const s=r.devices;return n?s[0]:s}async create(e){const n=!Array.isArray(e),s=(await z(this.client,"/device/create",{devices:E.toArray(e)},LO,PO)).devices;return n?s[0]:s}async delete(e){await z(this.client,"/device/delete",{keys:E.toArray(e)},BO,qO)}};const ni=H("device"),GO=ni(""),WO=t=>xe(ni(t)),KO=Object.freeze(Object.defineProperty({__proto__:null,Client:Vu,DELETE_CHANNEL_NAME:DO,SET_CHANNEL_NAME:UO,TYPE_ONTOLOGY_ID:GO,deviceZ:Xn,keyZ:Zt,newZ:Hu,ontologyID:ni,statusDetailsZ:Fu,statusKey:WO,statusZ:Yu},Symbol.toStringTag,{value:"Module"})),JO="sy_rack_set",XO="sy_rack_delete",QO=i.z.object({keys:ye.array().optional(),names:i.z.string().array().optional(),searchTerm:i.z.string().optional(),embedded:i.z.boolean().optional(),hostIsNode:i.z.boolean().optional(),limit:i.z.int().optional(),offset:i.z.int().optional(),includeStatus:i.z.boolean().optional()}),eE=i.z.object({racks:E.nullableZ(Jn)}),tE=i.z.union([i.z.object({key:ye,includeStatus:i.z.boolean().optional()}).transform(({key:t,includeStatus:e})=>({keys:[t],includeStatus:e})),i.z.object({name:i.z.string(),includeStatus:i.z.boolean().optional()}).transform(({name:t,includeStatus:e})=>({names:[t],includeStatus:e}))]),nE=QO,rE=i.z.union([tE,nE]),sE=i.z.object({racks:Bu.array()}),iE=i.z.object({racks:Jn.array()}),aE=i.z.object({keys:ye.array()}),oE=i.z.object({});let Gu=class{client;tasks;constructor(e,n){this.client=e,this.tasks=n}async delete(e){await z(this.client,"/rack/delete",{keys:E.toArray(e)},aE,oE)}async create(e){const n=!Array.isArray(e),r=await z(this.client,"/rack/create",{racks:E.toArray(e)},sE,iE),s=this.sugar(r.racks);return n?s[0]:s}async retrieve(e){const n="key"in e||"name"in e,r=await z(this.client,"/rack/retrieve",e,rE,eE),s=this.sugar(r.racks);return re("Rack",e,s,n),n?s[0]:s}sugar(e){const n=!Array.isArray(e),r=E.toArray(e).map(({key:s,name:a,status:o})=>new Wu(s,a,this.tasks,o));return n?r[0]:r}};class Wu{key;name;status;tasks;constructor(e,n,r,s){this.key=e,this.name=n,this.tasks=r,this.status=s}async listTasks(){return await this.tasks.retrieve({rack:this.key})}async createTask(e,n){return e.key=((BigInt(this.key)<<32n)+(BigInt(e.key??0)&0xffffffffn)).toString(),await this.tasks.create(e,n)}async deleteTask(e){await this.tasks.delete([e])}get payload(){return{key:this.key,name:this.name,status:this.status}}}const ri=H("rack"),cE=ri(0),uE=t=>xe(ri(t)),lE=Object.freeze(Object.defineProperty({__proto__:null,Client:Gu,DELETE_CHANNEL_NAME:XO,Rack:Wu,SET_CHANNEL_NAME:JO,TYPE_ONTOLOGY_ID:cE,keyZ:ye,newZ:Bu,ontologyID:ri,rackZ:Jn,statusDetailsZ:Lu,statusKey:uE,statusZ:Pu},Symbol.toStringTag,{value:"Module"})),hE="sy_range_alias_set",fE="sy_range_alias_delete",dE=i.z.object({range:K,aliases:i.z.string().array()}),yE=i.z.object({aliases:i.z.record(i.z.string(),M)}),pE=i.z.object({range:K,aliases:i.z.record(M,i.z.string())}),mE=i.z.unknown(),gE=i.z.object({range:K,channels:M.array()}),wE=i.z.unknown(),bE=i.z.object({range:K}),vE=i.z.object({aliases:i.z.record(i.z.string(),i.z.string())}),zE=i.z.object({range:K,channels:M.array()}),TE=i.z.object({aliases:i.z.record(i.z.string(),i.z.string())});class Ke{cache=new Map;client;rangeKey;constructor(e,n){this.rangeKey=e,this.cache=new Map,this.client=n}async resolve(e){const n=[],r=typeof e=="string",s={};if(r){const o=this.cache.get(e);if(o!=null)return o;n.push(e)}else e.forEach(o=>{const c=this.cache.get(o);c!=null?s[o]=c:n.push(o)});if(n.length===0)return s;const a=await z(this.client,"/range/alias/resolve",{range:this.rangeKey,aliases:n},dE,yE);return Object.entries(a.aliases).forEach(([o,c])=>this.cache.set(o,c)),r?a.aliases[n[0]]:{...s,...a.aliases}}async set(e){await z(this.client,"/range/alias/set",{range:this.rangeKey,aliases:e},pE,mE)}async list(){return(await z(this.client,"/range/alias/list",{range:this.rangeKey},bE,vE)).aliases}async retrieve(e){const n=typeof e=="number",r=await z(this.client,"/range/alias/retrieve",{range:this.rangeKey,channels:E.toArray(e)},zE,TE);return n?r.aliases[e]:r.aliases}async delete(e){await z(this.client,"/range/alias/delete",{range:this.rangeKey,channels:E.toArray(e)},gE,wE)}}const OE=i.z.object({alias:i.z.string().optional(),channel:M,range:K}),Ku="---",EE=t=>`${t.range}${Ku}${t.channel}`,NE=t=>{const[e,n]=t.split(Ku);return{range:e,channel:Number(n)}},SE="sy_range_kv_set",kE="sy_range_kv_delete",si=i.z.object({range:K,key:i.z.string(),value:i.z.string()}),AE=({range:t,key:e})=>`${t}<--->${e}`,$E=i.z.object({range:K,keys:i.z.string().array()}),IE=i.z.object({pairs:E.nullableZ(si)}),ZE=i.z.object({range:K,pairs:si.array()}),xE=i.z.object({range:K,keys:i.z.string().array()});class ns{rangeKey;client;constructor(e,n){this.rangeKey=e,this.client=n}async get(e){const n=await z(this.client,"/range/kv/get",{range:this.rangeKey,keys:E.toArray(e)},$E,IE);return typeof e=="string"?n.pairs[0].value:Object.fromEntries(n.pairs.map(r=>[r.key,r.value]))}async list(){return this.get([])}async set(e,n=""){let r;typeof e=="string"?r=[{range:this.rangeKey,key:e,value:n}]:r=Object.entries(e).map(([s,a])=>({range:this.rangeKey,key:s,value:a})),await z(this.client,"/range/kv/set",{range:this.rangeKey,pairs:r},ZE,i.z.unknown())}async delete(e){await z(this.client,"/range/kv/delete",{range:this.rangeKey,keys:E.toArray(e)},xE,i.z.unknown())}}const CE="sy_range_set",RE="sy_range_delete";class Ju{key;name;kv;timeRange;color;parent;labels;channels;aliaser;frameClient;labelClient;ontologyClient;rangeClient;constructor({name:e,timeRange:n=Z.ZERO,key:r,color:s,parent:a,labels:o},{frameClient:c,kv:l,aliaser:u,channels:h,labelClient:y,ontologyClient:f,rangeClient:T}){this.key=r,this.name=e,this.timeRange=n,this.parent=a,this.labels=o,this.frameClient=c,this.color=s,this.kv=l,this.aliaser=u,this.channels=h,this.labelClient=y,this.ontologyClient=f,this.rangeClient=T}get ontologyID(){return Je(this.key)}get payload(){let e=null;return this.parent!=null&&("payload"in this.parent?e=this.parent.payload:e=this.parent),{key:this.key,name:this.name,timeRange:this.timeRange,color:this.color,labels:this.labels,parent:e}}async setAlias(e,n){const r=await this.channels.retrieve(e);if(r.length===0)throw new qe(`Channel ${e} does not exist`);await this.aliaser.set({[r[0].key]:n})}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 retrieveParent(){return this.rangeClient.retrieveParent(this.key)}async retrieveChildren(){const e=(await this.ontologyClient.retrieveChildren(this.ontologyID,{excludeFieldData:!0,types:["range"]})).map(n=>n.id.key);return await this.rangeClient.retrieve(e)}async read(e){return await this.frameClient.read(this.timeRange,e)}async retrieveLabels(){return await this.labelClient.retrieve({for:Je(this.key)})}async addLabel(...e){await this.labelClient.label(Je(this.key),e)}async removeLabel(...e){await this.labelClient.remove(Je(this.key),e)}static sort(e,n){return Z.sort(e.timeRange,n.timeRange)}}const _E=i.z.object({keys:K.array().optional(),names:i.z.string().array().optional(),searchTerm:i.z.string().optional(),overlapsWith:Z.z.optional(),hasLabels:He.array().optional(),limit:i.z.int().optional(),offset:i.z.int().optional(),includeLabels:i.z.boolean().optional(),includeParent:i.z.boolean().optional()}),ME=_E.or(K.array().transform(t=>({keys:t}))).or(K.transform(t=>({keys:[t]}))).or(i.z.string().transform(t=>({names:[t]}))).or(i.z.string().array().transform(t=>({names:t}))).or(Z.z.transform(t=>({overlapsWith:t}))),jE=i.z.object({ranges:E.nullableZ(ln)});let Xu=class{type="range";frameClient;writer;unaryClient;channels;labelClient;ontologyClient;constructor(e,n,r,s,a,o){this.frameClient=e,this.writer=n,this.unaryClient=r,this.channels=s,this.labelClient=a,this.ontologyClient=o}async create(e,n){const r=!Array.isArray(e),s=this.sugarMany(await this.writer.create(E.toArray(e),n));return r?s[0]:s}async rename(e,n){await this.writer.rename(e,n)}async delete(e){await this.writer.delete(E.toArray(e))}async retrieve(e){const n=typeof e=="string",{ranges:r}=await z(this.unaryClient,"/range/retrieve",e,ME,jE);return re("Range",e,r,n),n?this.sugarMany(r)[0]:this.sugarMany(r)}getKV(e){return new ns(e,this.unaryClient)}async retrieveParent(e){const n=await this.ontologyClient.retrieveParents(Je(e));if(n.length===0)return null;const r=n[0];return r.id.type!=="range"?null:await this.retrieve(r.id.key)}sugarOntologyResource(e){return this.sugarOne(Qu(e))}async retrieveAlias(e,n){return await new Ke(e,this.unaryClient).retrieve(n)}async retrieveAliases(e,n){return await new Ke(e,this.unaryClient).retrieve(n)}async listAliases(e){return await new Ke(e,this.unaryClient).list()}async setAlias(e,n,r){await new Ke(e,this.unaryClient).set({[n]:r})}async deleteAlias(e,n){await new Ke(e,this.unaryClient).delete(n)}sugarOne(e){return new Ju(e,{frameClient:this.frameClient,kv:new ns(e.key,this.unaryClient),aliaser:new Ke(e.key,this.unaryClient),channels:this.channels,labelClient:this.labelClient,ontologyClient:this.ontologyClient,rangeClient:this})}sugarMany(e){return e.map(n=>this.sugarOne(n))}resourceToRange(e){return this.sugarOne({key:e.id.key,name:e.data?.name,timeRange:new Z(e.data?.timeRange),color:e.data?.color,labels:[],parent:null})}};const Je=H("range"),UE=Je(""),DE=t=>({type:"range-alias",key:t}),Qu=({data:t,id:{key:e},name:n})=>{const r=Z.z.parse(t?.timeRange);return{key:e,name:n,timeRange:r,color:typeof t?.color=="string"?t.color:void 0,labels:[],parent:null}},LE=i.z.object({ranges:ln.array()}),PE=i.z.object({parent:U.optional(),ranges:yu.array()}),BE=i.z.object({keys:K.array()}),qE=i.z.object({}),FE=i.z.object({key:K,name:Ws}),YE=i.z.object({});class el{client;constructor(e){this.client=e}async rename(e,n){await z(this.client,"/range/rename",{key:e,name:n},FE,YE)}async create(e,n){return(await z(this.client,"/range/create",{ranges:e,...n},PE,LE)).ranges}async delete(e){await z(this.client,"/range/delete",{keys:e},BE,qE)}}const HE=Object.freeze(Object.defineProperty({__proto__:null,Aliaser:Ke,Client:Xu,DELETE_ALIAS_CHANNEL_NAME:fE,DELETE_CHANNEL_NAME:RE,KV:ns,KV_DELETE_CHANNEL:kE,KV_SET_CHANNEL:SE,Range:Ju,SET_ALIAS_CHANNEL_NAME:hE,SET_CHANNEL_NAME:CE,TYPE_ONTOLOGY_ID:UE,Writer:el,aliasKey:EE,aliasOntologyID:DE,aliasZ:OE,convertOntologyResourceToPayload:Qu,decodeDeleteAliasChange:NE,keyZ:K,kvPairKey:AE,kvPairZ:si,nameZ:Ws,newZ:yu,ontologyID:Je,payloadZ:ln},Symbol.toStringTag,{value:"Module"})),VE=t=>i.object({parent:U.optional(),statuses:Vc(t).array()}),GE=t=>i.object({statuses:on(t).array()}),WE=i.object({keys:Yn.array()}),KE=i.object({}),JE=i.object({keys:Yn.array().optional(),searchTerm:i.string().optional(),offset:i.int().optional(),limit:i.int().optional(),includeLabels:i.boolean().optional(),hasLabels:He.array().optional()}),XE=i.object({key:Yn,includeLabels:i.boolean().optional()}).transform(({key:t,includeLabels:e})=>({keys:[t],includeLabels:e})),QE=i.union([XE,JE]),eN=t=>i.object({statuses:E.nullableZ(on(t))});let tl=class{type="status";client;constructor(e){this.client=e}async retrieve(e){const n="key"in e,r=await z(this.client,"/status/retrieve",e,QE,eN(e.detailsSchema));re("Status",e,r.statuses,n);const s=r.statuses;return n?s[0]:s}async set(e,n={}){const r=Array.isArray(e),a=(await z(this.client,"/status/set",{statuses:E.toArray(e),parent:n.parent},VE(n.detailsSchema),GE(n.detailsSchema))).statuses;return r?a:a[0]}async delete(e){await z(this.client,"/status/delete",{keys:E.toArray(e)},WE,KE)}};const tN=Object.freeze(Object.defineProperty({__proto__:null,Client:tl,DELETE_CHANNEL_NAME:Jz,SET_CHANNEL_NAME:Xr,TYPE_ONTOLOGY_ID:Xz,keyZ:Yn,newZ:Vc,ontologyID:Gc,statusZ:on},Symbol.toStringTag,{value:"Module"})),Ce=i.z.union([i.z.string(),i.z.bigint().transform(t=>t.toString()),i.z.number().transform(t=>t.toString())]),ii=t=>i.z.object({task:Ce,running:i.z.boolean(),data:t,cmd:i.z.string().optional()}),ai=t=>ct.statusZ(ii(t)),nN=t=>ii(t).partial({task:!0}),nl=t=>ct.statusZ(nN(t)).partial({key:!0,name:!0}),hn=(t={typeSchema:i.z.string(),configSchema:i.z.unknown(),statusDataSchema:i.z.unknown()})=>i.z.object({key:Ce,name:i.z.string(),type:t.typeSchema,internal:i.z.boolean().optional(),config:i.z.string().transform(qu).or(t.configSchema),status:ai(t.statusDataSchema).optional().nullable(),snapshot:i.z.boolean().optional()}),rl=t=>hn(t).omit({key:!0,status:!0}).extend({key:Ce.transform(e=>e.toString()).optional(),config:i.z.unknown().transform(e=>it.JSON_CODEC.encodeString(e)),status:nl(t?.statusDataSchema??i.z.unknown()).optional().nullable()}),rN=i.z.object({task:Ce,type:i.z.string(),key:i.z.string(),args:de.unknownZ.or(i.z.string().transform(Ee)).or(i.z.array(i.z.unknown())).or(i.z.null()).optional()}),sN=t=>Number(BigInt(t)>>32n),rs="sy_task_cmd",iN="sy_task_set",aN="sy_task_delete",Xe=new Error("Task not created"),sl=async(t,e)=>{const n=await e.retrieveParents(fn(t));return n.length===0?null:n[0]};class il{key;name;internal;type;snapshot;config;status;schemas;frameClient_;ontologyClient_;rangeClient_;get frameClient(){if(this.frameClient_==null)throw Xe;return this.frameClient_}get ontologyClient(){if(this.ontologyClient_==null)throw Xe;return this.ontologyClient_}get rangeClient(){if(this.rangeClient_==null)throw Xe;return this.rangeClient_}constructor({key:e,type:n,name:r,config:s,internal:a=!1,snapshot:o=!1,status:c},l,u,h,y){this.key=e,this.name=r,this.type=n,this.config=s,this.schemas=l??{typeSchema:i.z.string(),configSchema:i.z.unknown(),statusDataSchema:i.z.unknown()},this.internal=a,this.snapshot=o,this.status=c,this.frameClient_=u,this.ontologyClient_=h,this.rangeClient_=y}get payload(){return{key:this.key,name:this.name,type:this.type,config:this.config,status:this.status,internal:this.internal}}get ontologyID(){return fn(this.key)}async executeCommand(e){return await cl({...e,frameClient:this.frameClient,task:this.key})}async executeCommandSync(e){return await ul({...e,frameClient:this.frameClient,task:this.key,name:this.name,statusDataZ:this.schemas?.statusDataSchema})}async start(){await this.executeCommand({type:"start"})}async stop(){await this.executeCommand({type:"stop"})}async run(e){await this.start();try{return await e()}finally{await this.stop()}}async snapshottedTo(){if(this.ontologyClient==null||this.rangeClient==null)throw Xe;return this.snapshot?await sl(this.key,this.ontologyClient):null}}const oN=i.z.object({rack:ye.optional(),keys:Ce.array().optional(),names:i.z.string().array().optional(),types:i.z.string().array().optional(),includeStatus:i.z.boolean().optional(),internal:i.z.boolean().optional(),snapshot:i.z.boolean().optional(),searchTerm:i.z.string().optional(),offset:i.z.int().optional(),limit:i.z.int().optional()}),al=i.z.union([i.z.object({key:Ce,includeStatus:i.z.boolean().optional()}).transform(({key:t,includeStatus:e})=>({keys:[t],includeStatus:e})),i.z.object({name:i.z.string(),includeStatus:i.z.boolean().optional()}).transform(({name:t,includeStatus:e})=>({names:[t],includeStatus:e})),i.z.object({type:i.z.string(),rack:ye.optional()}).transform(({type:t,rack:e})=>({types:[t],rack:e}))]),cN=oN,uN=i.z.union([al,cN]),lN=t=>i.z.object({tasks:E.nullableZ(hn(t))}),hN=t=>i.z.object({tasks:rl(t).array()}),fN=t=>i.z.object({tasks:hn(t).array()}),dN=i.z.object({keys:Ce.array()}),yN=i.z.object({}),pN=i.z.object({key:Ce,name:i.z.string(),snapshot:i.z.boolean()}),mN=t=>i.z.object({task:hn(t)});let ol=class{type="task";client;frameClient;ontologyClient;rangeClient;constructor(e,n,r,s){this.client=e,this.frameClient=n,this.ontologyClient=r,this.rangeClient=s}async create(e,n){const r=!Array.isArray(e),s=hN(n),a=fN(n),o=await z(this.client,"/task/create",{tasks:E.toArray(e)},s,a),c=this.sugar(o.tasks,n);return r?c[0]:c}async delete(e){await z(this.client,"/task/delete",{keys:E.toArray(e)},dN,yN)}async retrieve({schemas:e,...n}){const r=al.safeParse(n).success,a=(await z(this.client,"/task/retrieve",n,uN,lN(e))).tasks,o=this.sugar(a,e);return re("Task",n,o,r),r?o[0]:o}async copy(e,n,r){const s=mN(),a=await z(this.client,"/task/copy",{key:e,name:n,snapshot:r},pN,s);return this.sugar(a.task)}async list(e){const n={internal:!1};return e!==void 0&&(n.rack=e),await this.retrieve(n)}async retrieveSnapshottedTo(e){if(this.ontologyClient==null)throw Xe;return await sl(e,this.ontologyClient)}sugar(e,n){const r=!Array.isArray(e),s=E.toArray(e).map(({key:a,name:o,type:c,config:l,status:u,internal:h,snapshot:y})=>new il({key:a,name:o,type:c,config:l,internal:h,snapshot:y,status:u},n,this.frameClient,this.ontologyClient,this.rangeClient));return r?s[0]:s}async executeCommand(e){return"commands"in e?await oi({...e,frameClient:this.frameClient}):await cl({...e,frameClient:this.frameClient})}async executeCommandSync(e){if("commands"in e){const r=async()=>{const{commands:s}=e;return(await this.retrieve({keys:s.map(o=>o.task)})).map(o=>o.name)};return await ll({...e,frameClient:this.frameClient,name:r})}const n=async()=>{const{task:r}=e;return(await this.retrieve({key:r})).name};return await ul({frameClient:this.frameClient,name:n,...e})}};const fn=H("task"),gN=fn(""),wN=t=>xe(fn(t)),cl=async({frameClient:t,task:e,type:n,args:r})=>(await oi({frameClient:t,commands:[{args:r,task:e,type:n}]}))[0],oi=async({frameClient:t,commands:e})=>{if(t==null)throw Xe;const n=await t.openWriter(rs),r=e.map(s=>({...s,key:ao.create()}));return await n.write(rs,r),await n.close(),r.map(s=>s.key)},ul=async({frameClient:t,task:e,type:n,timeout:r,name:s,statusDataZ:a,args:o})=>(await ll({frameClient:t,commands:[{args:o,task:e,type:n}],timeout:r,statusDataZ:a,name:s}))[0],ll=async({frameClient:t,commands:e,timeout:n=g.seconds(10),statusDataZ:r,name:s})=>{if(t==null)throw Xe;const a=await t.openStreamer(Xr),o=await oi({frameClient:t,commands:e}),c=new g(n);let l=[],u;const h=new Promise((y,f)=>{u=setTimeout(()=>{(async()=>{const T=e.map(S=>S.task);f(await bN("command",s,c,T))})()},c.milliseconds)});try{for(;;){const y=await Promise.race([a.read(),h]),f=ai(r).safeParse(y.at(-1)[Xr]);if(!f.success)continue;const T=f.data;if(!(T.details.cmd==null||!o.includes(T.details.cmd))&&(l=[...l.filter(S=>S.key!==T.key),T],l.length===o.length))return l}}finally{clearTimeout(u),a.close()}},bN=async(t,e,n,r)=>{const s=id.capitalize(t),a=n.toString();try{let o;typeof e=="string"?o=[e]:Array.isArray(e)?o=e:o=E.toArray(await e());const c=Fr.naturalLanguageJoin(o);return new Error(`${s} command to ${c} timed out after ${a}`)}catch(o){return console.error("Failed to retrieve task name for timeout error:",o),new Error(`${s} command to task with key ${Fr.naturalLanguageJoin(r)} timed out after ${a}`)}},vN=Object.freeze(Object.defineProperty({__proto__:null,COMMAND_CHANNEL_NAME:rs,Client:ol,DELETE_CHANNEL_NAME:aN,SET_CHANNEL_NAME:iN,TYPE_ONTOLOGY_ID:gN,Task:il,commandZ:rN,keyZ:Ce,newStatusZ:nl,newZ:rl,ontologyID:fn,rackKey:sN,statusDetailsZ:ii,statusKey:wN,statusZ:ai,taskZ:hn},Symbol.toStringTag,{value:"Module"}));class hl{url;unary;stream;secure;constructor(e,n={},r=!1){this.secure=r,this.url=e.child("/api/v1/");const s=new it.JSONCodec;this.unary=Bf(new Pf(this.url,s,this.secure),n),this.stream=new Vf(this.url,s,this.secure)}use(...e){this.unary.use(...e),this.stream.use(...e)}}const ft=i.z.uuid(),Qn=i.z.object({key:ft,name:i.z.string(),data:de.unknownZ.or(i.z.string().transform(Ee))}),fl=Qn.partial({key:!0}).transform(t=>({...t,data:JSON.stringify(t.data)})),Ne=i.z.uuid(),er=i.z.object({key:Ne,name:i.z.string().min(1,"Name is required"),layout:de.unknownZ.or(i.z.string().transform(Ee))}),dl=er.partial({key:!0}).transform(t=>({...t,layout:JSON.stringify(t.layout)})),yl=er.omit({layout:!0}).extend({layout:i.z.string().transform(Ee)}),zN=i.z.object({key:ft,name:i.z.string()}),TN=i.z.object({key:ft,data:i.z.string()}),ON=i.z.object({keys:ft.array()}),EN=i.z.object({keys:ft.array()}),pl=i.z.object({key:ft}).transform(({key:t})=>({keys:[t]})),ml=i.z.union([pl,EN]),NN=i.z.object({linePlots:E.nullableZ(Qn)}),SN=i.z.object({workspace:Ne,linePlots:fl.array()}),kN=i.z.object({linePlots:Qn.array()}),wr=i.z.object({});let gl=class{client;constructor(e){this.client=e}async create(e,n){const r=Array.isArray(n),s=await z(this.client,"/workspace/lineplot/create",{workspace:e,linePlots:E.toArray(n)},SN,kN);return r?s.linePlots:s.linePlots[0]}async rename(e,n){await z(this.client,"/workspace/lineplot/rename",{key:e,name:n},zN,wr)}async setData(e,n){await z(this.client,"/workspace/lineplot/set-data",{key:e,data:JSON.stringify(n)},TN,wr)}async retrieve(e){const n=pl.safeParse(e).success,r=await z(this.client,"/workspace/lineplot/retrieve",e,ml,NN);return re("LinePlot",e,r.linePlots,n),n?r.linePlots[0]:r.linePlots}async delete(e){await z(this.client,"/workspace/lineplot/delete",{keys:E.toArray(e)},ON,wr)}};const wl=H("lineplot"),AN=wl(""),$N=Object.freeze(Object.defineProperty({__proto__:null,Client:gl,TYPE_ONTOLOGY_ID:AN,keyZ:ft,linePlotZ:Qn,newZ:fl,ontologyID:wl,retrieveArgsZ:ml},Symbol.toStringTag,{value:"Module"})),dt=i.z.uuid(),tr=i.z.object({key:dt,name:i.z.string(),data:de.unknownZ.or(i.z.string().transform(Ee))}),bl=tr.partial({key:!0}).transform(t=>({...t,data:JSON.stringify(t.data)})),IN=i.z.object({key:dt,name:i.z.string()}),ZN=i.z.object({key:dt,data:i.z.string()}),xN=i.z.object({keys:dt.array()}),CN=i.z.object({keys:dt.array()}),vl=i.z.object({key:dt}).transform(({key:t})=>({keys:[t]})),zl=i.z.union([vl,CN]),RN=i.z.object({logs:E.nullableZ(tr)}),_N=i.z.object({workspace:Ne,logs:bl.array()}),MN=i.z.object({logs:tr.array()}),br=i.z.object({});let Tl=class{client;constructor(e){this.client=e}async create(e,n){const r=Array.isArray(n),s=await z(this.client,"/workspace/log/create",{workspace:e,logs:E.toArray(n)},_N,MN);return r?s.logs:s.logs[0]}async rename(e,n){await z(this.client,"/workspace/log/rename",{key:e,name:n},IN,br)}async setData(e,n){await z(this.client,"/workspace/log/set-data",{key:e,data:JSON.stringify(n)},ZN,br)}async retrieve(e){const n=vl.safeParse(e).success,r=await z(this.client,"/workspace/log/retrieve",e,zl,RN);return re("Log",e,r.logs,n),n?r.logs[0]:r.logs}async delete(e){await z(this.client,"/workspace/log/delete",{keys:E.toArray(e)},xN,br)}};const Ol=H("log"),jN=Ol(""),UN=Object.freeze(Object.defineProperty({__proto__:null,Client:Tl,TYPE_ONTOLOGY_ID:jN,keyZ:dt,logZ:tr,newZ:bl,ontologyID:Ol,retrieveArgsZ:zl},Symbol.toStringTag,{value:"Module"})),Ve=i.z.uuid(),nr=i.z.object({key:Ve,name:i.z.string(),data:de.unknownZ.or(i.z.string().transform(Ee)),snapshot:i.z.boolean()}),El=nr.partial({key:!0,snapshot:!0}).transform(t=>({...t,data:JSON.stringify(t.data)})),ci=nr.extend({data:i.z.string().transform(Ee)}),xt=i.z.uuid(),Nl=i.z.object({key:i.z.string(),name:i.z.string(),selectors:i.z.string().array().default([]),strokeColor:i.z.string().optional(),fillColor:i.z.string().optional()}),Sl=i.z.object({key:i.z.string(),name:i.z.string(),regions:Nl.array()}),kl=i.z.object({key:i.z.string(),position:Os.xy,orientation:my.outer}),DN=i.z.object({zoom:i.z.number().positive().default(1),position:Os.xy}),Al=i.z.object({svg:i.z.string().min(1,"SVG is required"),states:Sl.array(),variant:i.z.string().min(1,"Variant is required"),handles:kl.array(),scale:i.z.number().positive().default(1),scaleStroke:i.z.boolean().default(!1),previewViewport:DN.default({zoom:1,position:{x:0,y:0}})}),rr=i.z.object({key:xt,version:i.z.literal(1).default(1),name:i.z.string().min(1,"Name is required"),data:Al}),$l=rr.partial({key:!0}),LN=i.z.object({symbols:$l.array(),parent:U}),PN=i.z.object({key:xt,name:i.z.string()}),BN=i.z.object({keys:xt.array()}),qN=i.z.object({keys:xt.array().optional(),searchTerm:i.z.string().optional()}),FN=i.z.object({key:xt}).transform(({key:t})=>({keys:[t]})),YN=i.z.union([FN,qN]),HN=i.z.object({symbols:E.nullableZ(rr)}),VN=i.z.object({symbols:rr.array()}),ya=i.z.object({}),GN=i.z.object({}),WN=i.z.object({group:Dn}),KN="sy_schematic_symbol_set",JN="sy_schematic_symbol_delete";let Il=class{client;constructor(e){this.client=e}async create(e){const n="symbols"in e,r=n?e.symbols:[e],s=await z(this.client,"/workspace/schematic/symbol/create",{symbols:r,parent:e.parent},LN,VN);return n?s.symbols:s.symbols[0]}async rename(e,n){await z(this.client,"/workspace/schematic/symbol/rename",{key:e,name:n},PN,ya)}async retrieve(e){const n="key"in e,r=await z(this.client,"/workspace/schematic/symbol/retrieve",e,YN,HN);return re("Schematic Symbol",e,r.symbols,n),n?r.symbols[0]:r.symbols}async delete(e){await z(this.client,"/workspace/schematic/symbol/delete",{keys:E.toArray(e)},BN,ya)}async retrieveGroup(){return(await z(this.client,"/workspace/schematic/symbol/retrieve_group",{},GN,WN)).group}};const XN=H("schematic_symbol"),QN=Object.freeze(Object.defineProperty({__proto__:null,Client:Il,DELETE_CHANNEL_NAME:JN,SET_CHANNEL_NAME:KN,handleZ:kl,keyZ:xt,newZ:$l,ontologyID:XN,regionZ:Nl,specZ:Al,stateZ:Sl,symbolZ:rr},Symbol.toStringTag,{value:"Module"})),eS=i.z.object({key:Ve,name:i.z.string()}),tS=i.z.object({key:Ve,data:i.z.string()}),nS=i.z.object({keys:Ve.array()}),rS=i.z.object({key:Ve,name:i.z.string(),snapshot:i.z.boolean()}),sS=i.z.object({keys:Ve.array()}),Zl=i.z.object({key:Ve}).transform(({key:t})=>({keys:[t]})),xl=i.z.union([Zl,sS]),iS=i.z.object({schematics:E.nullableZ(ci)}),aS=i.z.object({workspace:Ne,schematics:El.array()}),oS=i.z.object({schematics:ci.array()}),cS=i.z.object({schematic:nr}),vr=i.z.object({});let Cl=class{symbols;client;constructor(e){this.client=e,this.symbols=new Il(e)}async create(e,n){const r=Array.isArray(n),s=await z(this.client,"/workspace/schematic/create",{workspace:e,schematics:E.toArray(n)},aS,oS);return r?s.schematics:s.schematics[0]}async rename(e,n){await z(this.client,"/workspace/schematic/rename",{key:e,name:n},eS,vr)}async setData(e,n){await z(this.client,"/workspace/schematic/set-data",{key:e,data:JSON.stringify(n)},tS,vr)}async retrieve(e){const n=Zl.safeParse(e).success,r=await z(this.client,"/workspace/schematic/retrieve",e,xl,iS);return re("Schematic",e,r.schematics,n),n?r.schematics[0]:r.schematics}async delete(e){await z(this.client,"/workspace/schematic/delete",{keys:E.toArray(e)},nS,vr)}async copy(e){return(await z(this.client,"/workspace/schematic/copy",e,rS,cS)).schematic}};const Rl=H("schematic"),uS=Rl(""),lS=Object.freeze(Object.defineProperty({__proto__:null,Client:Cl,TYPE_ONTOLOGY_ID:uS,keyZ:Ve,newZ:El,ontologyID:Rl,remoteZ:ci,retrieveArgsZ:xl,schematicZ:nr,symbol:QN},Symbol.toStringTag,{value:"Module"})),yt=i.z.uuid(),ui=i.z.object({key:yt,name:i.z.string(),data:de.unknownZ.or(i.z.string().transform(Ee))}),_l=ui.partial({key:!0}).transform(t=>({...t,data:JSON.stringify(t.data)})),li=ui.extend({data:i.z.string().transform(Ee)}),hS=i.z.object({key:yt,name:i.z.string()}),fS=i.z.object({key:yt,data:i.z.string()}),dS=i.z.object({keys:yt.array()}),yS=i.z.object({keys:yt.array()}),Ml=i.z.object({key:yt}).transform(({key:t})=>({keys:[t]})),jl=i.z.union([Ml,yS]),pS=i.z.object({tables:E.nullableZ(li)}),mS=i.z.object({workspace:Ne,tables:_l.array()}),gS=i.z.object({tables:li.array()}),zr=i.z.object({});let Ul=class{client;constructor(e){this.client=e}async create(e,n){const r=Array.isArray(n),s=await z(this.client,"/workspace/table/create",{workspace:e,tables:E.toArray(n)},mS,gS);return r?s.tables:s.tables[0]}async rename(e,n){await z(this.client,"/workspace/table/rename",{key:e,name:n},hS,zr)}async setData(e,n){await z(this.client,"/workspace/table/set-data",{key:e,data:JSON.stringify(n)},fS,zr)}async retrieve(e){const n=Ml.safeParse(e).success,r=await z(this.client,"/workspace/table/retrieve",e,jl,pS);return re("Table",e,r.tables,n),n?r.tables[0]:r.tables}async delete(e){await z(this.client,"/workspace/table/delete",{keys:E.toArray(e)},dS,zr)}};const Dl=H("table"),wS=Dl(""),bS=Object.freeze(Object.defineProperty({__proto__:null,Client:Ul,TYPE_ONTOLOGY_ID:wS,keyZ:yt,newZ:_l,ontologyID:Dl,remoteZ:li,retrieveArgsZ:jl,tableZ:ui},Symbol.toStringTag,{value:"Module"})),vS=i.z.object({keys:Ne.array().optional(),searchTerm:i.z.string().optional(),author:Oe.optional(),offset:i.z.int().optional(),limit:i.z.int().optional()}),zS=i.z.object({workspaces:dl.array()}),TS=i.z.object({key:Ne,name:i.z.string()}),OS=i.z.object({key:Ne,layout:de.unknownZ.transform(t=>JSON.stringify(t))}),ES=i.z.object({keys:Ne.array()}),NS=i.z.object({workspaces:E.nullableZ(er)}),SS=i.z.object({workspaces:yl.array()}),Tr=i.z.object({}),kS="sy_workspace_set",AS="sy_workspace_delete";class Ll{schematics;lineplots;logs;tables;client;constructor(e){this.client=e,this.schematics=new Cl(e),this.lineplots=new gl(e),this.logs=new Tl(e),this.tables=new Ul(e)}async create(e){const n=Array.isArray(e),r=await z(this.client,"/workspace/create",{workspaces:E.toArray(e)},zS,SS);return n?r.workspaces:r.workspaces[0]}async rename(e,n){await z(this.client,"/workspace/rename",{key:e,name:n},TS,Tr)}async setLayout(e,n){await z(this.client,"/workspace/set-layout",{key:e,layout:n},OS,Tr)}async retrieve(e){let n;const r=typeof e!="string";typeof e=="string"||Array.isArray(e)?n={keys:E.toArray(e)}:n=e;const s=await z(this.client,"/workspace/retrieve",n,vS,NS);return r?s.workspaces:s.workspaces[0]}async delete(e){await z(this.client,"/workspace/delete",{keys:E.toArray(e)},ES,Tr)}}const Pl=H("workspace"),$S=Pl(""),IS=Object.freeze(Object.defineProperty({__proto__:null,Client:Ll,DELETE_CHANNEL_NAME:AS,SET_CHANNEL_NAME:kS,TYPE_ONTOLOGY_ID:$S,keyZ:Ne,newZ:dl,ontologyID:Pl,remoteZ:yl,workspaceZ:er},Symbol.toStringTag,{value:"Module"})),Bl=i.z.object({host:i.z.string({error:"Host is required"}).min(1,"Host is required"),port:i.z.number({error:"Port is required"}).or(i.z.string({error:"Port is required"})),username:i.z.string().min(1,"Username is required"),password:i.z.string().min(1,"Password is required"),connectivityPollFrequency:g.z.default(g.seconds(30)),secure:i.z.boolean().default(!1),name:i.z.string().optional(),retry:Ss.breakerConfigZ.optional()});class ql extends Mu{createdAt;params;ranges;channels;auth;users;access;connectivity;ontology;workspaces;labels;statuses;tasks;racks;devices;control;arcs;static connectivity=Cn;transport;clientVersion="0.49.0";constructor(e){const n=Bl.parse(e),{host:r,port:s,username:a,password:o,connectivityPollFrequency:c,secure:l,retry:u}=n,h=new hl(new vt({host:r,port:Number(s)}),u,l);h.use(Om);const y=new Js(new Ks(h.unary));super(h.stream,h.unary,y),this.auth=new sO(h.unary,{username:a,password:o}),h.use(this.auth.middleware());const f=new bu(h.unary,y);this.createdAt=m.now(),this.params=n,this.transport=h,this.channels=new gu(this,y,h.unary,f),this.connectivity=new Cn(h.unary,c,this.clientVersion,n.name),this.control=new Du(this),this.ontology=new hc(h.unary,this);const T=new el(this.transport.unary);this.labels=new fu(this.transport.unary),this.statuses=new tl(this.transport.unary),this.ranges=new Xu(this,T,this.transport.unary,y,this.labels,this.ontology),this.access=new Tc(this.transport.unary),this.users=new mc(this.transport.unary),this.workspaces=new Ll(this.transport.unary),this.tasks=new ol(this.transport.unary,this,this.ontology,this.ranges),this.racks=new Gu(this.transport.unary,this.tasks),this.devices=new Vu(this.transport.unary),this.arcs=new ru(this.transport.unary,this.transport.stream)}get key(){return this.createdAt.valueOf().toString()}close(){this.connectivity.stop()}}const ZS=async t=>await Fl(t).check(),Fl=t=>{const{host:e,port:n,secure:r,name:s,retry:a}=t,o=Ss.breakerConfigZ.optional().parse(a),c=new vt({host:e,port:Number(n)}),l=new hl(c,o,r);return new Cn(l.unary,void 0,"0.49.0",s)},Yl={host:"localhost",port:9090,username:"synnax",password:"seldon",retry:{maxRetries:4,baseInterval:g.seconds(1),scale:1.5}},Hl=t=>new ql({...Yl,...t}),xS=async(t,e)=>{const n=ao.create(),r=await t.users.create({username:n,password:"test",firstName:"test",lastName:"test"}),s=await t.access.policies.create(e),a=await t.access.roles.create({name:"test",description:"test"});return await t.ontology.addChildren(Ms(a.key),Rs(s.key)),await t.access.roles.assign({user:r.key,role:a.key}),Hl({username:n,password:"test"})};exports.AuthError=Nt;exports.Channel=xn;exports.ContiguityError=vm;exports.DataType=d;exports.Density=C;exports.DisconnectedError=bm;exports.Frame=P;exports.MultiSeries=Do;exports.MultipleFoundError=Yt;exports.NotFoundError=Ft;exports.QueryError=qe;exports.Rate=F;exports.RouteError=Vr;exports.Series=Q;exports.Synnax=ql;exports.TEST_CLIENT_PARAMS=Yl;exports.TimeRange=Z;exports.TimeSpan=g;exports.TimeStamp=m;exports.UnexpectedError=zt;exports.ValidationError=Y;exports.access=Pg;exports.arc=yT;exports.channel=JT;exports.checkConnection=ZS;exports.connection=oO;exports.control=jO;exports.createTestClient=Hl;exports.createTestClientWithPolicy=xS;exports.device=KO;exports.framer=ZO;exports.group=Um;exports.isCalculated=St;exports.label=MT;exports.lineplot=$N;exports.log=UN;exports.newConnectionChecker=Fl;exports.ontology=Vm;exports.rack=lE;exports.ranger=HE;exports.schematic=lS;exports.status=tN;exports.synnaxParamsZ=Bl;exports.table=bS;exports.task=vN;exports.user=Ng;exports.workspace=IS;
62
+ `);return u});return new q(c,o.series)}const r=[],s=[],a=Object.entries(e);for(let o=0;o<a.length;o++){const[c,l]=a[o],u=await this.fetchChannel(c),h=new Q({data:l,dataType:u.dataType});r.push(u.key),s.push(h)}return new q(r,s)}}class Cu{name;stream;constructor(e,n){this.stream=n,this.name=e}async receive(){const[e,n]=await this.stream.receive();if(n!=null)throw n;return e}received(){return this.stream.received()}async closeAndAck(){for(this.stream.closeSend();;){const[e,n]=await this.stream.receive();if(e!=null&&console.warn(`${this.name} received unexpected response on ${JSON.stringify(e)} closure.
63
+ Please report this error to the Synnax team.`),n!=null){if(ge.matches(n))return;throw n}}}closeSend(){this.stream.closeSend()}send(e){const n=this.stream.send(e);if(n!=null)throw n}}const Mn=new m(-1);var ni=(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))(ni||{}),Ru=(t=>(t[t.None=0]="None",t[t.Ack=1]="Ack",t[t.Data=2]="Data",t))(Ru||{});const ZO=i.z.object({command:i.z.enum(ni),span:m.z.optional(),bounds:x.z.optional(),stamp:g.z.optional(),keys:j.array().optional(),chunkSize:i.z.number().optional(),downsampleFactor:i.z.int().optional()}),xO=i.z.object({variant:i.z.enum(Ru),ack:i.z.boolean(),command:i.z.enum(ni),error:_e.payloadZ.optional().nullable(),frame:Wn.optional()});class dn{stream;adapter;value;constructor(e,n){this.stream=new Cu("Iterator",e),this.value=new q,this.adapter=n}static async _open(e,n,r,s,a={}){const o=await Kn.open(r,n),c=await s.stream("/frame/iterate",ZO,xO),l=new dn(c,o);return await l.execute({command:0,keys:Array.from(o.keys),bounds:new x(e),chunkSize:a.chunkSize??1e5,downsampleFactor:a.downsampleFactor??1}),l}async next(e=Mn){return await this.execute({command:1,span:new m(e)})}async prev(e=Mn){return await this.execute({command:2,span:new m(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 g(e)})}async seekGE(e){return await this.execute({command:6,stamp:new g(e)})}async valid(){return await this.execute({command:7})}async close(){await this.stream.closeAndAck()}[Symbol.asyncIterator](){return new CO(this)}async execute(e){for(this.stream.send(e),this.value=new q;;){const n=await this.stream.receive();if(n.variant===1)return n.ack;this.value.push(this.adapter.adapt(new q(n.frame)))}}}class CO{iter;open=!1;constructor(e){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}}}class _u{retriever;streamClient;constructor(e,n){this.retriever=e,this.streamClient=n}async read(e){const{channels:n,timeRange:r,channelNames:s,iteratorConfig:a}=e,o=await this.retriever.retrieve(n),c=new Set;o.forEach(h=>{c.add(h.key),h.index!==0&&c.add(h.index)});const l=Array.from(c).filter(h=>!o.some(d=>d.key===h));if(l.length>0){const h=await this.retriever.retrieve(l);o.push(...h)}const u=await dn._open(r,Array.from(c),this.retriever,this.streamClient,a);return RO({iterator:u,channelPayloads:o,headers:s})}}const RO=({iterator:t,channelPayloads:e,headers:n})=>{const r=pm.getOS()==="Windows"?`\r
64
+ `:`
65
+ `,s=new TextEncoder;let a=!1,o=!1;const c=_O(e),{columns:l,columnsByIndexKey:u,emptyGroupStrings:h}=MO(e,c,n);let d=[],f=0,O=[];const E=z=>{for(const[N]of c){const A=z.get(N);if(A.length===0)continue;const R=(u.get(N)??[]).map(M=>z.get(M.key));for(let M=0;M<A.length;M++){const ae=A.at(M,!0),oe=R.map(de=>xi.formatValue(de.at(M,!0)));O.push({time:ae,values:oe,indexKey:N})}}},Z=(z,N=!1)=>{O.length>0&&(O.sort((R,M)=>Number(R.time-M.time)),f>0&&(d=d.slice(f),f=0),d=jO(d,O),O=[]);const A=[],D=d.length;for(;f<D&&A.length<z;){const R=d[f].time;if(!N&&d[D-1].time===R)break;const M=new Map;for(;f<D&&d[f].time===R;){const oe=d[f++];M.set(oe.indexKey,oe)}const ae=[];for(const[oe]of c){const de=M.get(oe);ae.push(de?.values.join(",")??h.get(oe)??"")}A.push(ae.join(","))}return A};return new ReadableStream({async pull(z){try{if(o||(await t.seekFirst(),o=!0),!a){const R=l.map(M=>xi.formatValue(M.header)).join(",");z.enqueue(s.encode(`${R}${r}`)),a=!0}d.length-f+O.length<ma&&await t.next()&&E(t.value);const A=Z(ma);if(A.length>0&&z.enqueue(s.encode(`${A.join(r)}${r}`)),d.length-f===0||O.length===0){if(!await t.next()){const M=Z(1/0,!0);M.length>0&&z.enqueue(s.encode(`${M.join(r)}${r}`)),await t.close(),z.close();return}E(t.value)}}catch(N){await t.close(),z.error(N)}},async cancel(){await t.close()}})},_O=t=>{const e=new Map;for(const n of t){if(n.index===0)continue;let r=e.get(n.index);r==null&&(r=[n.index],e.set(n.index,r)),!n.isIndex&&!r.includes(n.key)&&r.push(n.key)}return e},MO=(t,e,n)=>{const r=new Map(t.map(c=>[c.key,c])),s=[],a=new Map,o=new Map;for(const[c,l]of e){const u=[];for(const h of l){const d=r.get(h);if(d==null)throw new rt(`Channel ${h} not found`);const f={key:h,header:n?.[h]??n?.[d.name]??d.name};s.push(f),u.push(f)}a.set(c,u),o.set(c,",".repeat(u.length-1))}return{columns:s,columnsByIndexKey:a,emptyGroupStrings:o}},jO=(t,e)=>{const n=[];let r=0,s=0;for(;r<t.length&&s<e.length;)t[r].time<=e[s].time?n.push(t[r++]):n.push(e[s++]);return n.push(...t.slice(r),...e.slice(s)),n},ma=1e3,UO=i.z.object({keys:i.z.number().array(),downsampleFactor:i.z.int(),throttleRate:Y.z.optional()}),DO=i.z.object({frame:Wn}),ga=i.z.object({channels:yt,downsampleFactor:i.z.int().default(1),throttleRate:Y.z.default(new Y(0)),useHighPerformanceCodec:i.z.boolean().default(!0)}),ri=ga.or(yt.transform(t=>ga.parse({channels:t}))),Mu=(t,e)=>async n=>{const r=ri.parse(n),s=await Kn.open(t,r.channels);r.useHighPerformanceCodec&&(e=e.withCodec(new IO(s.codec)));const a=await e.stream("/frame/stream",UO,DO),o=new PO(a,s,r.downsampleFactor,r.throttleRate);a.send({keys:Array.from(s.keys),downsampleFactor:r.downsampleFactor,throttleRate:r.throttleRate});const[,c]=await a.receive();if(c!=null)throw c;return o},ju=async(t,e,n)=>await Mu(t,e)(n);class PO{stream;adapter;downsampleFactor;throttleRate;constructor(e,n,r=1,s=new Y(0)){this.stream=new Cu("Streamer",e),this.adapter=n,this.downsampleFactor=r,this.throttleRate=s}get keys(){return Array.from(this.adapter.keys)}async next(){try{return{done:!1,value:await this.read()}}catch(e){if(ge.matches(e))return{done:!0,value:void 0};throw e}}async read(){return this.adapter.adapt(new q((await this.stream.receive()).frame))}async update(e){await this.adapter.update(e)&&this.stream.send({keys:Array.from(this.adapter.keys),downsampleFactor:this.downsampleFactor,throttleRate:this.throttleRate})}close(){this.stream.closeSend()}[Symbol.asyncIterator](){return this}}class Jn{wrapped_=null;breaker;opener;config;constructor(e,n,r={}){this.opener=e,this.config=ri.parse(n);const{maxRetries:s=5e3,baseInterval:a=m.seconds(1),scale:o=1}=r??{};this.breaker=new As.Breaker({maxRetries:s,baseInterval:a,scale:o})}static async open(e,n,r){const s=new Jn(e,n,r);return await s.runStreamer(),s}async runStreamer(){for(;;)try{this.wrapped_!=null&&this.wrapped_.close(),this.wrapped_=await this.opener(this.config),this.breaker.reset();return}catch(e){if(this.wrapped_=null,!await this.breaker.wait())throw e;console.error("failed to open streamer",e);continue}}get wrapped(){if(this.wrapped_==null)throw new Error("stream closed");return this.wrapped_}async update(e){this.config.channels=yt.parse(e);try{await this.wrapped.update(e)}catch{return await this.runStreamer(),await this.update(e)}}async next(){try{return{done:!1,value:await this.read()}}catch(e){if(ge.matches(e))return{done:!0,value:void 0};throw e}}async read(){try{const e=await this.wrapped.read();return this.breaker.reset(),e}catch(e){if(ge.matches(e))throw e;return await this.runStreamer(),await this.read()}}close(){this.wrapped.close()}get keys(){return this.wrapped.keys}[Symbol.asyncIterator](){return this}}class Uu extends sm.Observer{streamer;closePromise;constructor(e,n){super(n),this.streamer=e,this.closePromise=this.stream()}async update(e){await this.streamer.update(e)}async close(){this.streamer.close(),await this.closePromise}async stream(){for await(const e of this.streamer)this.notify(e)}}var Kt=(t=>(t[t.PersistStream=1]="PersistStream",t[t.Persist=2]="Persist",t[t.Stream=3]="Stream",t))(Kt||{});const LO=new m(-1);class rs extends Ee.sub("writer_closed"){constructor(){super("WriterClosed")}}const BO=i.z.enum(Kt).or(i.z.enum(["persist","stream","persistStream"]).transform(t=>{switch(t){case"persist":return 2;case"stream":return 3;case"persistStream":return 1}})),Du=i.z.object({start:g.z.optional(),controlSubject:le.subjectZ.optional(),authorities:i.z.union([le.authorityZ.transform(t=>[t]),le.authorityZ.array()]).default([le.ABSOLUTE_AUTHORITY]),mode:BO.default(1),errOnUnauthorized:i.z.boolean().default(!1),enableAutoCommit:i.z.boolean().default(!0),autoIndexPersistInterval:m.z.default(m.SECOND),useHighPerformanceCodec:i.z.boolean().default(!0)}),qO=Du.extend({keys:j.array().optional()}),wa=Du.extend({channels:yt}),Pu=wa.or(yt.transform(t=>wa.parse({channels:t,start:g.now()}))),FO=i.z.object({command:i.z.enum(Ne),config:qO.optional(),frame:Wn.optional(),buffer:i.z.instanceof(Uint8Array).optional()}),YO=i.z.object({command:i.z.enum(Ne),end:g.z,err:_e.payloadZ.optional()}),VO=i.z.tuple([i.z.union([i.z.record(j.or(Re),le.authorityZ),j.or(Re),le.authorityZ]),le.authorityZ.optional()]).transform(([t,e])=>{if(le.authorityZ.safeParse(t).success)return{keys:[],authorities:[t]};if(j.or(Re).safeParse(t).success){if(e==null)throw new Error("authority is required when setting authority for a single channel");return{keys:[t],authorities:[e]}}const n=t;return{keys:Object.keys(n),authorities:Object.values(n)}});let Lu=class Bu{stream;adapter;closeErr=null;constructor(e,n){this.stream=e,this.adapter=n}static async _open(e,n,r){const s=Pu.parse(r),a=await ti.open(e,s.channels);s.useHighPerformanceCodec&&(n=n.withCodec(new $O(a.codec)));const o=await n.stream("/frame/write",FO,YO),c=new Bu(o,a);return await c.execute({command:Ne.Open,config:{...s,keys:a.keys}}),c}async write(e,n){if(this.closeErr!=null)throw this.closeErr;if(this.stream.received())return await this.close();const r=await this.adapter.adapt(e,n);this.stream.send({command:Ne.Write,frame:r.toPayload()})}async setAuthority(e,n){if(this.closeErr!=null)throw this.closeErr;const r=VO.parse([e,n]),s={keys:await this.adapter.adaptParams(r.keys),authorities:r.authorities};await this.execute({command:Ne.SetAuthority,config:s})}async commit(){if(this.closeErr!=null)throw this.closeErr;return this.stream.received()?(await this.closeInternal(null),g.ZERO):(await this.execute({command:Ne.Commit})).end}async close(){await this.closeInternal(null)}async closeInternal(e){if(this.closeErr!=null)throw this.closeErr;for(this.closeErr=e,this.stream.closeSend();;){if(this.closeErr!=null){if(rs.matches(this.closeErr))return null;throw this.closeErr}const[n,r]=await this.stream.receive();r!=null?this.closeErr=ge.matches(r)?new rs:r:this.closeErr=_e.decode(n?.err)}}async execute(e){const n=this.stream.send(e);for(n!=null&&await this.closeInternal(n);;){const[r,s]=await this.stream.receive();s!=null&&await this.closeInternal(s);const a=_e.decode(r?.err);if(a!=null&&await this.closeInternal(a),r?.command==e.command)return r}}};const qu=G("framer"),GO=qu("");let Fu=class{streamClient;retriever;deleter;reader;constructor(e,n,r){this.streamClient=e,this.retriever=r,this.deleter=new OO(n),this.reader=new _u(r,e)}async openIterator(e,n,r){return await dn._open(e,n,this.retriever,this.streamClient,r)}async openWriter(e){return await Lu._open(this.retriever,this.streamClient,e)}async openStreamer(e){return await ju(this.retriever,this.streamClient,e)}async write(e,n,r){if(r==null){const a=n,o=await this.openWriter({start:e,channels:Object.keys(a),mode:Kt.Persist,errOnUnauthorized:!0,autoIndexPersistInterval:m.MAX});return await o.write(a),await o.close()}const s=await this.openWriter({start:e,channels:n,mode:Kt.Persist,errOnUnauthorized:!0,autoIndexPersistInterval:m.MAX});await s.write(n,r),await s.close()}async read(e,n){if(!("start"in e))return this.reader.read(e);const{single:r}=me(n),s=await this.readFrame(e,n);return r?s.get(n):s}async readFrame(e,n){const r=await this.openIterator(e,n),s=new q;try{for await(const a of r)s.push(a)}finally{await r.close()}return s}async readLatest(e,n=1){const{single:r}=me(e),s=await this.readLatestNFrame(e,n);return r?s.get(e):s}async readLatestNFrame(e,n){const r=await this.openIterator(x.MAX,e,{chunkSize:n}),s=new q;if(n>0)try{await r.seekLast(),await r.prev(Mn),s.push(r.value)}finally{await r.close()}return s}async delete(e,n){const{normalized:r,variant:s}=me(e),a=new x(n);return s==="keys"?await this.deleter.delete({keys:r,bounds:a}):await this.deleter.delete({names:r,bounds:a})}};const HO=Object.freeze(Object.defineProperty({__proto__:null,ALWAYS_INDEX_PERSIST_ON_AUTO_COMMIT:LO,AUTO_SPAN:Mn,Client:Fu,Frame:q,HardenedStreamer:Jn,Iterator:dn,ObservableStreamer:Uu,Reader:_u,TYPE_ONTOLOGY_ID:GO,Writer:Lu,WriterClosedError:rs,WriterCommand:Ne,WriterMode:Kt,createStreamOpener:Mu,frameZ:Wn,ontologyID:qu,openStreamer:ju,seriesFromPayload:$u,seriesToPayload:Iu,streamerConfigZ:ri,writerConfigZ:Pu},Symbol.toStringTag,{value:"Module"})),WO=le.ABSOLUTE_AUTHORITY,KO=le.ZERO_AUTHORITY,JO=le.stateZ(i.z.number()),XO=t=>t.to==null?`${t.from?.resource} - ${t.from?.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()})`,QO=i.z.object({transfers:i.z.array(le.transferZ(j))});class Yu extends Uu{states;codec;constructor(e){super(e,n=>{const r=this.codec.decode(n.series[0].buffer,QO);return this.merge(r),[r.transfers,!0]}),this.states=new Map,this.codec=new ct.JSONCodec}subjects(){const e=new Map;return this.states.forEach(n=>e.set(n.subject.key,n.subject)),Array.from(e.values())}merge(e){e.transfers.forEach(n=>{n.from==null&&n.to==null&&console.warn("Invalid transfer: ",n),n.to==null?this.states.delete(n.from.resource):this.states.set(n.to.resource,n.to)})}}const Vu="sy_node_1_control";let Gu=class{framer;constructor(e){this.framer=e}async openStateTracker(){const e=await Jn.open(async n=>await this.framer.openStreamer(n),Vu);return new Yu(e)}};const eN=Object.freeze(Object.defineProperty({__proto__:null,ABSOLUTE_AUTHORITY:WO,CONTROL_STATE_CHANNEL_NAME:Vu,Client:Gu,StateTracker:Yu,ZERO_AUTHORITY:KO,stateZ:JO,transferString:XO},Symbol.toStringTag,{value:"Module"})),be=i.z.uint32(),Hu=i.z.object({rack:be}),Wu=ht.statusZ(Hu),Xn=i.z.object({key:be,name:i.z.string(),status:Se.nullToUndefined(Wu)}),Ku=Xn.partial({key:!0}),Ju=t=>t?ct.JSON_CODEC.decodeString(t,we.unknownZ):{},Ct=i.z.string(),Xu=i.z.object({rack:be,device:Ct}),Qu=ht.statusZ(Xu),Qn=i.z.object({key:Ct,rack:be.min(1,"Must select a location to connect from"),name:i.z.string().min(1,"Name is required"),make:i.z.string().min(1,"Make is required"),model:i.z.string().min(1,"Model is required"),location:i.z.string().min(1,"Location is required"),configured:i.z.boolean().optional(),properties:we.unknownZ.or(i.z.string().transform(Ju)),status:Se.nullToUndefined(Qu)}),el=Qn.extend({properties:i.z.unknown().transform(t=>ct.JSON_CODEC.encodeString(t))}),tN="sy_device_set",nN="sy_device_delete",rN=i.z.object({devices:el.array()}),sN=i.z.object({devices:Qn.array()}),iN=i.z.object({keys:Ct.array()}),aN=i.z.object({}),oN=i.z.object({keys:Ct.array().optional(),names:i.z.string().array().optional(),makes:i.z.string().array().optional(),models:i.z.string().array().optional(),locations:i.z.string().array().optional(),racks:be.array().optional(),searchTerm:i.z.string().optional(),limit:i.z.int().optional(),offset:i.z.int().optional(),includeStatus:i.z.boolean().optional()}),cN=i.z.object({devices:S.nullableZ(Qn)}),uN=i.z.object({key:Ct,includeStatus:i.z.boolean().optional()}).transform(({key:t,includeStatus:e})=>({keys:[t],includeStatus:e})),lN=i.z.union([uN,oN]);let tl=class{client;constructor(e){this.client=e}async retrieve(e){const n=typeof e=="object"&&"key"in e,r=await T(this.client,"/device/retrieve",e,lN,cN);ie("Device",e,r.devices,n);const s=r.devices;return n?s[0]:s}async create(e){const n=!Array.isArray(e),s=(await T(this.client,"/device/create",{devices:S.toArray(e)},rN,sN)).devices;return n?s[0]:s}async delete(e){await T(this.client,"/device/delete",{keys:S.toArray(e)},iN,aN)}};const si=G("device"),hN=si(""),fN=t=>Me(si(t)),dN=Object.freeze(Object.defineProperty({__proto__:null,Client:tl,DELETE_CHANNEL_NAME:nN,SET_CHANNEL_NAME:tN,TYPE_ONTOLOGY_ID:hN,deviceZ:Qn,keyZ:Ct,newZ:el,ontologyID:si,statusDetailsZ:Xu,statusKey:fN,statusZ:Qu},Symbol.toStringTag,{value:"Module"})),yN="sy_rack_set",pN="sy_rack_delete",mN=i.z.object({keys:be.array().optional(),names:i.z.string().array().optional(),searchTerm:i.z.string().optional(),embedded:i.z.boolean().optional(),hostIsNode:i.z.boolean().optional(),limit:i.z.int().optional(),offset:i.z.int().optional(),includeStatus:i.z.boolean().optional()}),gN=i.z.object({racks:S.nullableZ(Xn)}),wN=i.z.union([i.z.object({key:be,includeStatus:i.z.boolean().optional()}).transform(({key:t,includeStatus:e})=>({keys:[t],includeStatus:e})),i.z.object({name:i.z.string(),includeStatus:i.z.boolean().optional()}).transform(({name:t,includeStatus:e})=>({names:[t],includeStatus:e}))]),bN=mN,vN=i.z.union([wN,bN]),zN=i.z.object({racks:Ku.array()}),TN=i.z.object({racks:Xn.array()}),ON=i.z.object({keys:be.array()}),NN=i.z.object({});let nl=class{client;tasks;constructor(e,n){this.client=e,this.tasks=n}async delete(e){await T(this.client,"/rack/delete",{keys:S.toArray(e)},ON,NN)}async create(e){const n=!Array.isArray(e),r=await T(this.client,"/rack/create",{racks:S.toArray(e)},zN,TN),s=this.sugar(r.racks);return n?s[0]:s}async retrieve(e){const n="key"in e||"name"in e,r=await T(this.client,"/rack/retrieve",e,vN,gN),s=this.sugar(r.racks);return ie("Rack",e,s,n),n?s[0]:s}sugar(e){const n=!Array.isArray(e),r=S.toArray(e).map(({key:s,name:a,status:o})=>new rl(s,a,this.tasks,o));return n?r[0]:r}};class rl{key;name;status;tasks;constructor(e,n,r,s){this.key=e,this.name=n,this.tasks=r,this.status=s}async listTasks(){return await this.tasks.retrieve({rack:this.key})}async createTask(e,n){return e.key=((BigInt(this.key)<<32n)+(BigInt(e.key??0)&0xffffffffn)).toString(),await this.tasks.create(e,n)}async deleteTask(e){await this.tasks.delete([e])}get payload(){return{key:this.key,name:this.name,status:this.status}}}const ii=G("rack"),SN=ii(0),EN=t=>Me(ii(t)),kN=Object.freeze(Object.defineProperty({__proto__:null,Client:nl,DELETE_CHANNEL_NAME:pN,Rack:rl,SET_CHANNEL_NAME:yN,TYPE_ONTOLOGY_ID:SN,keyZ:be,newZ:Ku,ontologyID:ii,rackZ:Xn,statusDetailsZ:Hu,statusKey:EN,statusZ:Wu},Symbol.toStringTag,{value:"Module"})),AN="sy_range_alias_set",$N="sy_range_alias_delete",IN=i.z.object({range:K,aliases:i.z.string().array()}),ZN=i.z.object({aliases:i.z.record(i.z.string(),j)}),xN=i.z.object({range:K,aliases:i.z.record(j,i.z.string())}),CN=i.z.unknown(),RN=i.z.object({range:K,channels:j.array()}),_N=i.z.unknown(),MN=i.z.object({range:K}),jN=i.z.object({aliases:i.z.record(i.z.string(),i.z.string())}),UN=i.z.object({range:K,channels:j.array()}),DN=i.z.object({aliases:i.z.record(i.z.string(),i.z.string())});class Xe{cache=new Map;client;rangeKey;constructor(e,n){this.rangeKey=e,this.cache=new Map,this.client=n}async resolve(e){const n=[],r=typeof e=="string",s={};if(r){const o=this.cache.get(e);if(o!=null)return o;n.push(e)}else e.forEach(o=>{const c=this.cache.get(o);c!=null?s[o]=c:n.push(o)});if(n.length===0)return s;const a=await T(this.client,"/range/alias/resolve",{range:this.rangeKey,aliases:n},IN,ZN);return Object.entries(a.aliases).forEach(([o,c])=>this.cache.set(o,c)),r?a.aliases[n[0]]:{...s,...a.aliases}}async set(e){await T(this.client,"/range/alias/set",{range:this.rangeKey,aliases:e},xN,CN)}async list(){return(await T(this.client,"/range/alias/list",{range:this.rangeKey},MN,jN)).aliases}async retrieve(e){const n=typeof e=="number",r=await T(this.client,"/range/alias/retrieve",{range:this.rangeKey,channels:S.toArray(e)},UN,DN);return n?r.aliases[e]:r.aliases}async delete(e){await T(this.client,"/range/alias/delete",{range:this.rangeKey,channels:S.toArray(e)},RN,_N)}}const PN=i.z.object({alias:i.z.string().optional(),channel:j,range:K}),sl="---",LN=t=>`${t.range}${sl}${t.channel}`,BN=t=>{const[e,n]=t.split(sl);return{range:e,channel:Number(n)}},qN="sy_range_kv_set",FN="sy_range_kv_delete",ai=i.z.object({range:K,key:i.z.string(),value:i.z.string()}),YN=({range:t,key:e})=>`${t}<--->${e}`,VN=i.z.object({range:K,keys:i.z.string().array()}),GN=i.z.object({pairs:S.nullableZ(ai)}),HN=i.z.object({range:K,pairs:ai.array()}),WN=i.z.object({range:K,keys:i.z.string().array()});class ss{rangeKey;client;constructor(e,n){this.rangeKey=e,this.client=n}async get(e){const n=await T(this.client,"/range/kv/get",{range:this.rangeKey,keys:S.toArray(e)},VN,GN);return typeof e=="string"?n.pairs[0].value:Object.fromEntries(n.pairs.map(r=>[r.key,r.value]))}async list(){return this.get([])}async set(e,n=""){let r;typeof e=="string"?r=[{range:this.rangeKey,key:e,value:n}]:r=Object.entries(e).map(([s,a])=>({range:this.rangeKey,key:s,value:a})),await T(this.client,"/range/kv/set",{range:this.rangeKey,pairs:r},HN,i.z.unknown())}async delete(e){await T(this.client,"/range/kv/delete",{range:this.rangeKey,keys:S.toArray(e)},WN,i.z.unknown())}}const KN="sy_range_set",JN="sy_range_delete";class il{key;name;kv;timeRange;color;parent;labels;channels;aliaser;frameClient;labelClient;ontologyClient;rangeClient;constructor({name:e,timeRange:n=x.ZERO,key:r,color:s,parent:a,labels:o},{frameClient:c,kv:l,aliaser:u,channels:h,labelClient:d,ontologyClient:f,rangeClient:O}){this.key=r,this.name=e,this.timeRange=n,this.parent=a,this.labels=o,this.frameClient=c,this.color=s,this.kv=l,this.aliaser=u,this.channels=h,this.labelClient=d,this.ontologyClient=f,this.rangeClient=O}get ontologyID(){return Qe(this.key)}get payload(){let e=null;return this.parent!=null&&("payload"in this.parent?e=this.parent.payload:e=this.parent),{key:this.key,name:this.name,timeRange:this.timeRange,color:this.color,labels:this.labels,parent:e}}async setAlias(e,n){const r=await this.channels.retrieve(e);if(r.length===0)throw new Ge(`Channel ${e} does not exist`);await this.aliaser.set({[r[0].key]:n})}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 retrieveParent(){return this.rangeClient.retrieveParent(this.key)}async retrieveChildren(){const e=(await this.ontologyClient.retrieveChildren(this.ontologyID,{excludeFieldData:!0,types:["range"]})).map(n=>n.id.key);return await this.rangeClient.retrieve(e)}async read(e){return await this.frameClient.read(this.timeRange,e)}async retrieveLabels(){return await this.labelClient.retrieve({for:Qe(this.key)})}async addLabel(...e){await this.labelClient.label(Qe(this.key),e)}async removeLabel(...e){await this.labelClient.remove(Qe(this.key),e)}static sort(e,n){return x.sort(e.timeRange,n.timeRange)}}const XN=i.z.object({keys:K.array().optional(),names:i.z.string().array().optional(),searchTerm:i.z.string().optional(),overlapsWith:x.z.optional(),hasLabels:Ke.array().optional(),limit:i.z.int().optional(),offset:i.z.int().optional(),includeLabels:i.z.boolean().optional(),includeParent:i.z.boolean().optional()}),QN=XN.or(K.array().transform(t=>({keys:t}))).or(K.transform(t=>({keys:[t]}))).or(i.z.string().transform(t=>({names:[t]}))).or(i.z.string().array().transform(t=>({names:t}))).or(x.z.transform(t=>({overlapsWith:t}))),eS=i.z.object({ranges:S.nullableZ(fn)});let al=class{type="range";frameClient;writer;unaryClient;channels;labelClient;ontologyClient;constructor(e,n,r,s,a,o){this.frameClient=e,this.writer=n,this.unaryClient=r,this.channels=s,this.labelClient=a,this.ontologyClient=o}async create(e,n){const r=!Array.isArray(e),s=this.sugarMany(await this.writer.create(S.toArray(e),n));return r?s[0]:s}async rename(e,n){await this.writer.rename(e,n)}async delete(e){await this.writer.delete(S.toArray(e))}async retrieve(e){const n=typeof e=="string",{ranges:r}=await T(this.unaryClient,"/range/retrieve",e,QN,eS);return ie("Range",e,r,n),n?this.sugarMany(r)[0]:this.sugarMany(r)}getKV(e){return new ss(e,this.unaryClient)}async retrieveParent(e){const n=await this.ontologyClient.retrieveParents(Qe(e));if(n.length===0)return null;const r=n[0];return r.id.type!=="range"?null:await this.retrieve(r.id.key)}sugarOntologyResource(e){return this.sugarOne(ol(e))}async retrieveAlias(e,n){return await new Xe(e,this.unaryClient).retrieve(n)}async retrieveAliases(e,n){return await new Xe(e,this.unaryClient).retrieve(n)}async listAliases(e){return await new Xe(e,this.unaryClient).list()}async setAlias(e,n,r){await new Xe(e,this.unaryClient).set({[n]:r})}async deleteAlias(e,n){await new Xe(e,this.unaryClient).delete(n)}sugarOne(e){return new il(e,{frameClient:this.frameClient,kv:new ss(e.key,this.unaryClient),aliaser:new Xe(e.key,this.unaryClient),channels:this.channels,labelClient:this.labelClient,ontologyClient:this.ontologyClient,rangeClient:this})}sugarMany(e){return e.map(n=>this.sugarOne(n))}resourceToRange(e){return this.sugarOne({key:e.id.key,name:e.data?.name,timeRange:new x(e.data?.timeRange),color:e.data?.color,labels:[],parent:null})}};const Qe=G("range"),tS=Qe(""),nS=t=>({type:"range-alias",key:t}),ol=({data:t,id:{key:e},name:n})=>{const r=x.z.parse(t?.timeRange);return{key:e,name:n,timeRange:r,color:typeof t?.color=="string"?t.color:void 0,labels:[],parent:null}},rS=i.z.object({ranges:fn.array()}),sS=i.z.object({parent:P.optional(),ranges:zu.array()}),iS=i.z.object({keys:K.array()}),aS=i.z.object({}),oS=i.z.object({key:K,name:Js}),cS=i.z.object({});class cl{client;constructor(e){this.client=e}async rename(e,n){await T(this.client,"/range/rename",{key:e,name:n},oS,cS)}async create(e,n){return(await T(this.client,"/range/create",{ranges:e,...n},sS,rS)).ranges}async delete(e){await T(this.client,"/range/delete",{keys:e},iS,aS)}}const uS=Object.freeze(Object.defineProperty({__proto__:null,Aliaser:Xe,Client:al,DELETE_ALIAS_CHANNEL_NAME:$N,DELETE_CHANNEL_NAME:JN,KV:ss,KV_DELETE_CHANNEL:FN,KV_SET_CHANNEL:qN,Range:il,SET_ALIAS_CHANNEL_NAME:AN,SET_CHANNEL_NAME:KN,TYPE_ONTOLOGY_ID:tS,Writer:cl,aliasKey:LN,aliasOntologyID:nS,aliasZ:PN,convertOntologyResourceToPayload:ol,decodeDeleteAliasChange:BN,keyZ:K,kvPairKey:YN,kvPairZ:ai,nameZ:Js,newZ:zu,ontologyID:Qe,payloadZ:fn},Symbol.toStringTag,{value:"Module"})),lS=t=>i.object({parent:P.optional(),statuses:eu(t).array()}),hS=t=>i.object({statuses:un(t).array()}),fS=i.object({keys:Gn.array()}),dS=i.object({}),yS=i.object({keys:Gn.array().optional(),searchTerm:i.string().optional(),offset:i.int().optional(),limit:i.int().optional(),includeLabels:i.boolean().optional(),hasLabels:Ke.array().optional()}),pS=i.object({key:Gn,includeLabels:i.boolean().optional()}).transform(({key:t,includeLabels:e})=>({keys:[t],includeLabels:e})),mS=i.union([pS,yS]),gS=t=>i.object({statuses:S.nullableZ(un(t))});let ul=class{type="status";client;constructor(e){this.client=e}async retrieve(e){const n="key"in e,r=await T(this.client,"/status/retrieve",e,mS,gS(e.detailsSchema));ie("Status",e,r.statuses,n);const s=r.statuses;return n?s[0]:s}async set(e,n={}){const r=Array.isArray(e),a=(await T(this.client,"/status/set",{statuses:S.toArray(e),parent:n.parent},lS(n.detailsSchema),hS(n.detailsSchema))).statuses;return r?a:a[0]}async delete(e){await T(this.client,"/status/delete",{keys:S.toArray(e)},fS,dS)}};const wS=Object.freeze(Object.defineProperty({__proto__:null,Client:ul,DELETE_CHANNEL_NAME:lT,SET_CHANNEL_NAME:es,TYPE_ONTOLOGY_ID:hT,keyZ:Gn,newZ:eu,ontologyID:tu,statusZ:un},Symbol.toStringTag,{value:"Module"})),je=i.z.union([i.z.string(),i.z.bigint().transform(t=>t.toString()),i.z.number().transform(t=>t.toString())]),oi=t=>i.z.object({task:je,running:i.z.boolean(),data:t,cmd:i.z.string().optional()}),ci=t=>ht.statusZ(oi(t)),bS=t=>oi(t).partial({task:!0}),ll=t=>ht.statusZ(bS(t)).partial({key:!0,name:!0}),yn=(t={typeSchema:i.z.string(),configSchema:i.z.unknown(),statusDataSchema:i.z.unknown()})=>i.z.object({key:je,name:i.z.string(),type:t.typeSchema,internal:i.z.boolean().optional(),config:i.z.string().transform(Ju).or(t.configSchema),status:ci(t.statusDataSchema).optional().nullable(),snapshot:i.z.boolean().optional()}),hl=t=>yn(t).omit({key:!0,status:!0}).extend({key:je.transform(e=>e.toString()).optional(),config:i.z.unknown().transform(e=>ct.JSON_CODEC.encodeString(e)),status:ll(t?.statusDataSchema??i.z.unknown()).optional().nullable()}),vS=i.z.object({task:je,type:i.z.string(),key:i.z.string(),args:we.unknownZ.or(i.z.string().transform(Ae)).or(i.z.array(i.z.unknown())).or(i.z.null()).optional()}),zS=t=>Number(BigInt(t)>>32n),is="sy_task_cmd",TS="sy_task_set",OS="sy_task_delete",et=new Error("Task not created"),fl=async(t,e)=>{const n=await e.retrieveParents(pn(t));return n.length===0?null:n[0]};class dl{key;name;internal;type;snapshot;config;status;schemas;frameClient_;ontologyClient_;rangeClient_;get frameClient(){if(this.frameClient_==null)throw et;return this.frameClient_}get ontologyClient(){if(this.ontologyClient_==null)throw et;return this.ontologyClient_}get rangeClient(){if(this.rangeClient_==null)throw et;return this.rangeClient_}constructor({key:e,type:n,name:r,config:s,internal:a=!1,snapshot:o=!1,status:c},l,u,h,d){this.key=e,this.name=r,this.type=n,this.config=s,this.schemas=l??{typeSchema:i.z.string(),configSchema:i.z.unknown(),statusDataSchema:i.z.unknown()},this.internal=a,this.snapshot=o,this.status=c,this.frameClient_=u,this.ontologyClient_=h,this.rangeClient_=d}get payload(){return{key:this.key,name:this.name,type:this.type,config:this.config,status:this.status,internal:this.internal}}get ontologyID(){return pn(this.key)}async executeCommand(e){return await ml({...e,frameClient:this.frameClient,task:this.key})}async executeCommandSync(e){return await gl({...e,frameClient:this.frameClient,task:this.key,name:this.name,statusDataZ:this.schemas?.statusDataSchema})}async start(){await this.executeCommand({type:"start"})}async stop(){await this.executeCommand({type:"stop"})}async run(e){await this.start();try{return await e()}finally{await this.stop()}}async snapshottedTo(){if(this.ontologyClient==null||this.rangeClient==null)throw et;return this.snapshot?await fl(this.key,this.ontologyClient):null}}const NS=i.z.object({rack:be.optional(),keys:je.array().optional(),names:i.z.string().array().optional(),types:i.z.string().array().optional(),includeStatus:i.z.boolean().optional(),internal:i.z.boolean().optional(),snapshot:i.z.boolean().optional(),searchTerm:i.z.string().optional(),offset:i.z.int().optional(),limit:i.z.int().optional()}),yl=i.z.union([i.z.object({key:je,includeStatus:i.z.boolean().optional()}).transform(({key:t,includeStatus:e})=>({keys:[t],includeStatus:e})),i.z.object({name:i.z.string(),includeStatus:i.z.boolean().optional()}).transform(({name:t,includeStatus:e})=>({names:[t],includeStatus:e})),i.z.object({type:i.z.string(),rack:be.optional()}).transform(({type:t,rack:e})=>({types:[t],rack:e}))]),SS=NS,ES=i.z.union([yl,SS]),kS=t=>i.z.object({tasks:S.nullableZ(yn(t))}),AS=t=>i.z.object({tasks:hl(t).array()}),$S=t=>i.z.object({tasks:yn(t).array()}),IS=i.z.object({keys:je.array()}),ZS=i.z.object({}),xS=i.z.object({key:je,name:i.z.string(),snapshot:i.z.boolean()}),CS=t=>i.z.object({task:yn(t)});let pl=class{type="task";client;frameClient;ontologyClient;rangeClient;constructor(e,n,r,s){this.client=e,this.frameClient=n,this.ontologyClient=r,this.rangeClient=s}async create(e,n){const r=!Array.isArray(e),s=AS(n),a=$S(n),o=await T(this.client,"/task/create",{tasks:S.toArray(e)},s,a),c=this.sugar(o.tasks,n);return r?c[0]:c}async delete(e){await T(this.client,"/task/delete",{keys:S.toArray(e)},IS,ZS)}async retrieve({schemas:e,...n}){const r=yl.safeParse(n).success,a=(await T(this.client,"/task/retrieve",n,ES,kS(e))).tasks,o=this.sugar(a,e);return ie("Task",n,o,r),r?o[0]:o}async copy(e,n,r){const s=CS(),a=await T(this.client,"/task/copy",{key:e,name:n,snapshot:r},xS,s);return this.sugar(a.task)}async list(e){const n={internal:!1};return e!==void 0&&(n.rack=e),await this.retrieve(n)}async retrieveSnapshottedTo(e){if(this.ontologyClient==null)throw et;return await fl(e,this.ontologyClient)}sugar(e,n){const r=!Array.isArray(e),s=S.toArray(e).map(({key:a,name:o,type:c,config:l,status:u,internal:h,snapshot:d})=>new dl({key:a,name:o,type:c,config:l,internal:h,snapshot:d,status:u},n,this.frameClient,this.ontologyClient,this.rangeClient));return r?s[0]:s}async executeCommand(e){return"commands"in e?await ui({...e,frameClient:this.frameClient}):await ml({...e,frameClient:this.frameClient})}async executeCommandSync(e){if("commands"in e){const r=async()=>{const{commands:s}=e;return(await this.retrieve({keys:s.map(o=>o.task)})).map(o=>o.name)};return await wl({...e,frameClient:this.frameClient,name:r})}const n=async()=>{const{task:r}=e;return(await this.retrieve({key:r})).name};return await gl({frameClient:this.frameClient,name:n,...e})}};const pn=G("task"),RS=pn(""),_S=t=>Me(pn(t)),ml=async({frameClient:t,task:e,type:n,args:r})=>(await ui({frameClient:t,commands:[{args:r,task:e,type:n}]}))[0],ui=async({frameClient:t,commands:e})=>{if(t==null)throw et;const n=await t.openWriter(is),r=e.map(s=>({...s,key:ho.create()}));return await n.write(is,r),await n.close(),r.map(s=>s.key)},gl=async({frameClient:t,task:e,type:n,timeout:r,name:s,statusDataZ:a,args:o})=>(await wl({frameClient:t,commands:[{args:o,task:e,type:n}],timeout:r,statusDataZ:a,name:s}))[0],wl=async({frameClient:t,commands:e,timeout:n=m.seconds(10),statusDataZ:r,name:s})=>{if(t==null)throw et;const a=await t.openStreamer(es),o=await ui({frameClient:t,commands:e}),c=new m(n);let l=[],u;const h=new Promise((d,f)=>{u=setTimeout(()=>{(async()=>{const O=e.map(E=>E.task);f(await MS("command",s,c,O))})()},c.milliseconds)});try{for(;;){const d=await Promise.race([a.read(),h]),f=ci(r).safeParse(d.at(-1)[es]);if(!f.success)continue;const O=f.data;if(!(O.details.cmd==null||!o.includes(O.details.cmd))&&(l=[...l.filter(E=>E.key!==O.key),O],l.length===o.length))return l}}finally{clearTimeout(u),a.close()}},MS=async(t,e,n,r)=>{const s=dd.capitalize(t),a=n.toString();try{let o;typeof e=="string"?o=[e]:Array.isArray(e)?o=e:o=S.toArray(await e());const c=Vr.naturalLanguageJoin(o);return new Error(`${s} command to ${c} timed out after ${a}`)}catch(o){return console.error("Failed to retrieve task name for timeout error:",o),new Error(`${s} command to task with key ${Vr.naturalLanguageJoin(r)} timed out after ${a}`)}},jS=Object.freeze(Object.defineProperty({__proto__:null,COMMAND_CHANNEL_NAME:is,Client:pl,DELETE_CHANNEL_NAME:OS,SET_CHANNEL_NAME:TS,TYPE_ONTOLOGY_ID:RS,Task:dl,commandZ:vS,keyZ:je,newStatusZ:ll,newZ:hl,ontologyID:pn,rackKey:zS,statusDetailsZ:oi,statusKey:_S,statusZ:ci,taskZ:yn},Symbol.toStringTag,{value:"Module"}));class bl{url;unary;stream;secure;constructor(e,n={},r=!1){this.secure=r,this.url=e.child("/api/v1/");const s=new ct.JSONCodec;this.unary=Kf(new Wf(this.url,s,this.secure),n),this.stream=new td(this.url,s,this.secure)}use(...e){this.unary.use(...e),this.stream.use(...e)}}const pt=i.z.uuid(),er=i.z.object({key:pt,name:i.z.string(),data:we.unknownZ.or(i.z.string().transform(Ae))}),vl=er.partial({key:!0}).transform(t=>({...t,data:JSON.stringify(t.data)})),$e=i.z.uuid(),tr=i.z.object({key:$e,name:i.z.string().min(1,"Name is required"),layout:we.unknownZ.or(i.z.string().transform(Ae))}),zl=tr.partial({key:!0}).transform(t=>({...t,layout:JSON.stringify(t.layout)})),Tl=tr.omit({layout:!0}).extend({layout:i.z.string().transform(Ae)}),US=i.z.object({key:pt,name:i.z.string()}),DS=i.z.object({key:pt,data:i.z.string()}),PS=i.z.object({keys:pt.array()}),LS=i.z.object({keys:pt.array()}),Ol=i.z.object({key:pt}).transform(({key:t})=>({keys:[t]})),Nl=i.z.union([Ol,LS]),BS=i.z.object({linePlots:S.nullableZ(er)}),qS=i.z.object({workspace:$e,linePlots:vl.array()}),FS=i.z.object({linePlots:er.array()}),vr=i.z.object({});let Sl=class{client;constructor(e){this.client=e}async create(e,n){const r=Array.isArray(n),s=await T(this.client,"/workspace/lineplot/create",{workspace:e,linePlots:S.toArray(n)},qS,FS);return r?s.linePlots:s.linePlots[0]}async rename(e,n){await T(this.client,"/workspace/lineplot/rename",{key:e,name:n},US,vr)}async setData(e,n){await T(this.client,"/workspace/lineplot/set-data",{key:e,data:JSON.stringify(n)},DS,vr)}async retrieve(e){const n=Ol.safeParse(e).success,r=await T(this.client,"/workspace/lineplot/retrieve",e,Nl,BS);return ie("LinePlot",e,r.linePlots,n),n?r.linePlots[0]:r.linePlots}async delete(e){await T(this.client,"/workspace/lineplot/delete",{keys:S.toArray(e)},PS,vr)}};const El=G("lineplot"),YS=El(""),VS=Object.freeze(Object.defineProperty({__proto__:null,Client:Sl,TYPE_ONTOLOGY_ID:YS,keyZ:pt,linePlotZ:er,newZ:vl,ontologyID:El,retrieveArgsZ:Nl},Symbol.toStringTag,{value:"Module"})),mt=i.z.uuid(),nr=i.z.object({key:mt,name:i.z.string(),data:we.unknownZ.or(i.z.string().transform(Ae))}),kl=nr.partial({key:!0}).transform(t=>({...t,data:JSON.stringify(t.data)})),GS=i.z.object({key:mt,name:i.z.string()}),HS=i.z.object({key:mt,data:i.z.string()}),WS=i.z.object({keys:mt.array()}),KS=i.z.object({keys:mt.array()}),Al=i.z.object({key:mt}).transform(({key:t})=>({keys:[t]})),$l=i.z.union([Al,KS]),JS=i.z.object({logs:S.nullableZ(nr)}),XS=i.z.object({workspace:$e,logs:kl.array()}),QS=i.z.object({logs:nr.array()}),zr=i.z.object({});let Il=class{client;constructor(e){this.client=e}async create(e,n){const r=Array.isArray(n),s=await T(this.client,"/workspace/log/create",{workspace:e,logs:S.toArray(n)},XS,QS);return r?s.logs:s.logs[0]}async rename(e,n){await T(this.client,"/workspace/log/rename",{key:e,name:n},GS,zr)}async setData(e,n){await T(this.client,"/workspace/log/set-data",{key:e,data:JSON.stringify(n)},HS,zr)}async retrieve(e){const n=Al.safeParse(e).success,r=await T(this.client,"/workspace/log/retrieve",e,$l,JS);return ie("Log",e,r.logs,n),n?r.logs[0]:r.logs}async delete(e){await T(this.client,"/workspace/log/delete",{keys:S.toArray(e)},WS,zr)}};const Zl=G("log"),eE=Zl(""),tE=Object.freeze(Object.defineProperty({__proto__:null,Client:Il,TYPE_ONTOLOGY_ID:eE,keyZ:mt,logZ:nr,newZ:kl,ontologyID:Zl,retrieveArgsZ:$l},Symbol.toStringTag,{value:"Module"})),Je=i.z.uuid(),rr=i.z.object({key:Je,name:i.z.string(),data:we.unknownZ.or(i.z.string().transform(Ae)),snapshot:i.z.boolean()}),xl=rr.partial({key:!0,snapshot:!0}).transform(t=>({...t,data:JSON.stringify(t.data)})),li=rr.extend({data:i.z.string().transform(Ae)}),Rt=i.z.uuid(),Cl=i.z.object({key:i.z.string(),name:i.z.string(),selectors:i.z.string().array().default([]),strokeColor:i.z.string().optional(),fillColor:i.z.string().optional()}),Rl=i.z.object({key:i.z.string(),name:i.z.string(),regions:Cl.array()}),_l=i.z.object({key:i.z.string(),position:Ss.xy,orientation:Ny.outer}),nE=i.z.object({zoom:i.z.number().positive().default(1),position:Ss.xy}),Ml=i.z.object({svg:i.z.string().min(1,"SVG is required"),states:Rl.array(),variant:i.z.string().min(1,"Variant is required"),handles:_l.array(),scale:i.z.number().positive().default(1),scaleStroke:i.z.boolean().default(!1),previewViewport:nE.default({zoom:1,position:{x:0,y:0}})}),sr=i.z.object({key:Rt,version:i.z.literal(1).default(1),name:i.z.string().min(1,"Name is required"),data:Ml}),jl=sr.partial({key:!0}),rE=i.z.object({symbols:jl.array(),parent:P}),sE=i.z.object({key:Rt,name:i.z.string()}),iE=i.z.object({keys:Rt.array()}),aE=i.z.object({keys:Rt.array().optional(),searchTerm:i.z.string().optional()}),oE=i.z.object({key:Rt}).transform(({key:t})=>({keys:[t]})),cE=i.z.union([oE,aE]),uE=i.z.object({symbols:S.nullableZ(sr)}),lE=i.z.object({symbols:sr.array()}),ba=i.z.object({}),hE=i.z.object({}),fE=i.z.object({group:Ln}),dE="sy_schematic_symbol_set",yE="sy_schematic_symbol_delete";let Ul=class{client;constructor(e){this.client=e}async create(e){const n="symbols"in e,r=n?e.symbols:[e],s=await T(this.client,"/workspace/schematic/symbol/create",{symbols:r,parent:e.parent},rE,lE);return n?s.symbols:s.symbols[0]}async rename(e,n){await T(this.client,"/workspace/schematic/symbol/rename",{key:e,name:n},sE,ba)}async retrieve(e){const n="key"in e,r=await T(this.client,"/workspace/schematic/symbol/retrieve",e,cE,uE);return ie("Schematic Symbol",e,r.symbols,n),n?r.symbols[0]:r.symbols}async delete(e){await T(this.client,"/workspace/schematic/symbol/delete",{keys:S.toArray(e)},iE,ba)}async retrieveGroup(){return(await T(this.client,"/workspace/schematic/symbol/retrieve_group",{},hE,fE)).group}};const pE=G("schematic_symbol"),mE=Object.freeze(Object.defineProperty({__proto__:null,Client:Ul,DELETE_CHANNEL_NAME:yE,SET_CHANNEL_NAME:dE,handleZ:_l,keyZ:Rt,newZ:jl,ontologyID:pE,regionZ:Cl,specZ:Ml,stateZ:Rl,symbolZ:sr},Symbol.toStringTag,{value:"Module"})),gE=i.z.object({key:Je,name:i.z.string()}),wE=i.z.object({key:Je,data:i.z.string()}),bE=i.z.object({keys:Je.array()}),vE=i.z.object({key:Je,name:i.z.string(),snapshot:i.z.boolean()}),zE=i.z.object({keys:Je.array()}),Dl=i.z.object({key:Je}).transform(({key:t})=>({keys:[t]})),Pl=i.z.union([Dl,zE]),TE=i.z.object({schematics:S.nullableZ(li)}),OE=i.z.object({workspace:$e,schematics:xl.array()}),NE=i.z.object({schematics:li.array()}),SE=i.z.object({schematic:rr}),Tr=i.z.object({});let Ll=class{symbols;client;constructor(e){this.client=e,this.symbols=new Ul(e)}async create(e,n){const r=Array.isArray(n),s=await T(this.client,"/workspace/schematic/create",{workspace:e,schematics:S.toArray(n)},OE,NE);return r?s.schematics:s.schematics[0]}async rename(e,n){await T(this.client,"/workspace/schematic/rename",{key:e,name:n},gE,Tr)}async setData(e,n){await T(this.client,"/workspace/schematic/set-data",{key:e,data:JSON.stringify(n)},wE,Tr)}async retrieve(e){const n=Dl.safeParse(e).success,r=await T(this.client,"/workspace/schematic/retrieve",e,Pl,TE);return ie("Schematic",e,r.schematics,n),n?r.schematics[0]:r.schematics}async delete(e){await T(this.client,"/workspace/schematic/delete",{keys:S.toArray(e)},bE,Tr)}async copy(e){return(await T(this.client,"/workspace/schematic/copy",e,vE,SE)).schematic}};const Bl=G("schematic"),EE=Bl(""),kE=Object.freeze(Object.defineProperty({__proto__:null,Client:Ll,TYPE_ONTOLOGY_ID:EE,keyZ:Je,newZ:xl,ontologyID:Bl,remoteZ:li,retrieveArgsZ:Pl,schematicZ:rr,symbol:mE},Symbol.toStringTag,{value:"Module"})),gt=i.z.uuid(),hi=i.z.object({key:gt,name:i.z.string(),data:we.unknownZ.or(i.z.string().transform(Ae))}),ql=hi.partial({key:!0}).transform(t=>({...t,data:JSON.stringify(t.data)})),fi=hi.extend({data:i.z.string().transform(Ae)}),AE=i.z.object({key:gt,name:i.z.string()}),$E=i.z.object({key:gt,data:i.z.string()}),IE=i.z.object({keys:gt.array()}),ZE=i.z.object({keys:gt.array()}),Fl=i.z.object({key:gt}).transform(({key:t})=>({keys:[t]})),Yl=i.z.union([Fl,ZE]),xE=i.z.object({tables:S.nullableZ(fi)}),CE=i.z.object({workspace:$e,tables:ql.array()}),RE=i.z.object({tables:fi.array()}),Or=i.z.object({});let Vl=class{client;constructor(e){this.client=e}async create(e,n){const r=Array.isArray(n),s=await T(this.client,"/workspace/table/create",{workspace:e,tables:S.toArray(n)},CE,RE);return r?s.tables:s.tables[0]}async rename(e,n){await T(this.client,"/workspace/table/rename",{key:e,name:n},AE,Or)}async setData(e,n){await T(this.client,"/workspace/table/set-data",{key:e,data:JSON.stringify(n)},$E,Or)}async retrieve(e){const n=Fl.safeParse(e).success,r=await T(this.client,"/workspace/table/retrieve",e,Yl,xE);return ie("Table",e,r.tables,n),n?r.tables[0]:r.tables}async delete(e){await T(this.client,"/workspace/table/delete",{keys:S.toArray(e)},IE,Or)}};const Gl=G("table"),_E=Gl(""),ME=Object.freeze(Object.defineProperty({__proto__:null,Client:Vl,TYPE_ONTOLOGY_ID:_E,keyZ:gt,newZ:ql,ontologyID:Gl,remoteZ:fi,retrieveArgsZ:Yl,tableZ:hi},Symbol.toStringTag,{value:"Module"})),jE=i.z.object({keys:$e.array().optional(),searchTerm:i.z.string().optional(),author:ke.optional(),offset:i.z.int().optional(),limit:i.z.int().optional()}),UE=i.z.object({workspaces:zl.array()}),DE=i.z.object({key:$e,name:i.z.string()}),PE=i.z.object({key:$e,layout:we.unknownZ.transform(t=>JSON.stringify(t))}),LE=i.z.object({keys:$e.array()}),BE=i.z.object({workspaces:S.nullableZ(tr)}),qE=i.z.object({workspaces:Tl.array()}),Nr=i.z.object({}),FE="sy_workspace_set",YE="sy_workspace_delete";class Hl{schematics;lineplots;logs;tables;client;constructor(e){this.client=e,this.schematics=new Ll(e),this.lineplots=new Sl(e),this.logs=new Il(e),this.tables=new Vl(e)}async create(e){const n=Array.isArray(e),r=await T(this.client,"/workspace/create",{workspaces:S.toArray(e)},UE,qE);return n?r.workspaces:r.workspaces[0]}async rename(e,n){await T(this.client,"/workspace/rename",{key:e,name:n},DE,Nr)}async setLayout(e,n){await T(this.client,"/workspace/set-layout",{key:e,layout:n},PE,Nr)}async retrieve(e){let n;const r=typeof e!="string";typeof e=="string"||Array.isArray(e)?n={keys:S.toArray(e)}:n=e;const s=await T(this.client,"/workspace/retrieve",n,jE,BE);return r?s.workspaces:s.workspaces[0]}async delete(e){await T(this.client,"/workspace/delete",{keys:S.toArray(e)},LE,Nr)}}const Wl=G("workspace"),VE=Wl(""),GE=Object.freeze(Object.defineProperty({__proto__:null,Client:Hl,DELETE_CHANNEL_NAME:YE,SET_CHANNEL_NAME:FE,TYPE_ONTOLOGY_ID:VE,keyZ:$e,newZ:zl,ontologyID:Wl,remoteZ:Tl,workspaceZ:tr},Symbol.toStringTag,{value:"Module"})),Kl=i.z.object({host:i.z.string({error:"Host is required"}).min(1,"Host is required"),port:i.z.number({error:"Port is required"}).or(i.z.string({error:"Port is required"})),username:i.z.string().min(1,"Username is required"),password:i.z.string().min(1,"Password is required"),connectivityPollFrequency:m.z.default(m.seconds(30)),secure:i.z.boolean().default(!1),name:i.z.string().optional(),retry:As.breakerConfigZ.optional()});class Jl extends Fu{createdAt;params;ranges;channels;auth;users;access;connectivity;ontology;workspaces;labels;statuses;tasks;racks;devices;control;arcs;static connectivity=_n;transport;clientVersion="0.49.3";constructor(e){const n=Kl.parse(e),{host:r,port:s,username:a,password:o,connectivityPollFrequency:c,secure:l,retry:u}=n,h=new bl(new Ot({host:r,port:Number(s)}),u,l);h.use(Mm);const d=new Qs(new Xs(h.unary));super(h.stream,h.unary,d),this.auth=new gO(h.unary,{username:a,password:o}),h.use(this.auth.middleware());const f=new Eu(h.unary,d);this.createdAt=g.now(),this.params=n,this.transport=h,this.channels=new Nu(this,d,h.unary,f),this.connectivity=new _n(h.unary,c,this.clientVersion,n.name),this.control=new Gu(this),this.ontology=new wc(h.unary,this);const O=new cl(this.transport.unary);this.labels=new bu(this.transport.unary),this.statuses=new ul(this.transport.unary),this.ranges=new al(this,O,this.transport.unary,d,this.labels,this.ontology),this.access=new $c(this.transport.unary),this.users=new Oc(this.transport.unary),this.workspaces=new Hl(this.transport.unary),this.tasks=new pl(this.transport.unary,this,this.ontology,this.ranges),this.racks=new nl(this.transport.unary,this.tasks),this.devices=new tl(this.transport.unary),this.arcs=new lu(this.transport.unary,this.transport.stream)}get key(){return this.createdAt.valueOf().toString()}close(){this.connectivity.stop()}}const HE=async t=>await Xl(t).check(),Xl=t=>{const{host:e,port:n,secure:r,name:s,retry:a}=t,o=As.breakerConfigZ.optional().parse(a),c=new Ot({host:e,port:Number(n)}),l=new bl(c,o,r);return new _n(l.unary,void 0,"0.49.3",s)},Ql={host:"localhost",port:9090,username:"synnax",password:"seldon",retry:{maxRetries:4,baseInterval:m.seconds(1),scale:1.5}},eh=t=>new Jl({...Ql,...t}),WE=async(t,e)=>{const n=ho.create(),r=await t.users.create({username:n,password:"test",firstName:"test",lastName:"test"}),s=await t.access.policies.create(e),a=await t.access.roles.create({name:"test",description:"test"});return await t.ontology.addChildren(Us(a.key),Ms(s.key)),await t.access.roles.assign({user:r.key,role:a.key}),eh({username:n,password:"test"})};exports.AuthError=kt;exports.Channel=Rn;exports.ContiguityError=Cm;exports.DataType=y;exports.Density=C;exports.DisconnectedError=xm;exports.Frame=q;exports.MultiSeries=Fo;exports.MultipleFoundError=Gt;exports.NotFoundError=Vt;exports.QueryError=Ge;exports.Rate=Y;exports.RouteError=Wr;exports.Series=Q;exports.Synnax=Jl;exports.TEST_CLIENT_PARAMS=Ql;exports.TimeRange=x;exports.TimeSpan=m;exports.TimeStamp=g;exports.UnexpectedError=rt;exports.ValidationError=V;exports.access=ew;exports.arc=kT;exports.channel=lO;exports.checkConnection=HE;exports.connection=vO;exports.control=eN;exports.createTestClient=eh;exports.createTestClientWithPolicy=WE;exports.device=dN;exports.framer=HO;exports.group=Jm;exports.isCalculated=At;exports.label=WT;exports.lineplot=VS;exports.log=tE;exports.newConnectionChecker=Xl;exports.ontology=ag;exports.rack=kN;exports.ranger=uS;exports.schematic=kE;exports.status=wS;exports.synnaxParamsZ=Kl;exports.table=ME;exports.task=jS;exports.user=Ug;exports.workspace=GE;