@synnaxlabs/client 0.27.0 → 0.29.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (83) hide show
  1. package/.turbo/turbo-build.log +7 -7
  2. package/CONTRIBUTING.md +47 -0
  3. package/README.md +17 -32
  4. package/api/client.api.md +57 -15
  5. package/dist/channel/client.d.ts +10 -8
  6. package/dist/channel/client.d.ts.map +1 -1
  7. package/dist/channel/retriever.d.ts +1 -1
  8. package/dist/channel/retriever.d.ts.map +1 -1
  9. package/dist/client.cjs +20 -16
  10. package/dist/client.d.ts +4 -0
  11. package/dist/client.d.ts.map +1 -1
  12. package/dist/client.js +1880 -1722
  13. package/dist/connection/checker.d.ts +21 -1
  14. package/dist/connection/checker.d.ts.map +1 -1
  15. package/dist/control/state.d.ts.map +1 -1
  16. package/dist/framer/client.d.ts.map +1 -1
  17. package/dist/framer/deleter.d.ts.map +1 -1
  18. package/dist/framer/frame.d.ts.map +1 -1
  19. package/dist/framer/streamer.d.ts +2 -4
  20. package/dist/framer/streamer.d.ts.map +1 -1
  21. package/dist/framer/writer.d.ts.map +1 -1
  22. package/dist/hardware/task/client.d.ts +12 -2
  23. package/dist/hardware/task/client.d.ts.map +1 -1
  24. package/dist/hardware/task/ni/types.d.ts +14495 -0
  25. package/dist/hardware/task/ni/types.d.ts.map +1 -0
  26. package/dist/hardware/task/payload.d.ts +6 -0
  27. package/dist/hardware/task/payload.d.ts.map +1 -1
  28. package/dist/label/retriever.d.ts +1 -1
  29. package/dist/ontology/client.d.ts +16 -5
  30. package/dist/ontology/client.d.ts.map +1 -1
  31. package/dist/ontology/group/payload.d.ts +1 -1
  32. package/dist/ontology/group/writer.d.ts.map +1 -1
  33. package/dist/ontology/payload.d.ts +1 -2
  34. package/dist/ontology/payload.d.ts.map +1 -1
  35. package/dist/ranger/client.d.ts +3 -1
  36. package/dist/ranger/client.d.ts.map +1 -1
  37. package/dist/ranger/payload.d.ts +25 -25
  38. package/dist/ranger/payload.d.ts.map +1 -1
  39. package/dist/ranger/writer.d.ts.map +1 -1
  40. package/dist/workspace/lineplot/client.d.ts +1 -1
  41. package/dist/workspace/lineplot/client.d.ts.map +1 -1
  42. package/dist/workspace/lineplot/retriever.d.ts +1 -1
  43. package/dist/workspace/lineplot/retriever.d.ts.map +1 -1
  44. package/dist/workspace/lineplot/writer.d.ts +3 -3
  45. package/dist/workspace/lineplot/writer.d.ts.map +1 -1
  46. package/dist/workspace/retriever.d.ts +1 -1
  47. package/dist/workspace/retriever.d.ts.map +1 -1
  48. package/dist/workspace/schematic/retriever.d.ts +1 -1
  49. package/dist/workspace/schematic/retriever.d.ts.map +1 -1
  50. package/dist/workspace/schematic/writer.d.ts +1 -1
  51. package/dist/workspace/schematic/writer.d.ts.map +1 -1
  52. package/package.json +24 -16
  53. package/src/channel/client.ts +10 -8
  54. package/src/channel/retriever.ts +2 -2
  55. package/src/client.ts +13 -5
  56. package/src/connection/checker.ts +58 -1
  57. package/src/connection/connection.spec.ts +43 -3
  58. package/src/framer/client.ts +2 -3
  59. package/src/framer/streamer.spec.ts +2 -7
  60. package/src/framer/streamer.ts +5 -10
  61. package/src/hardware/rack/client.ts +3 -4
  62. package/src/hardware/task/client.ts +82 -6
  63. package/src/hardware/task/ni/types.ts +1716 -0
  64. package/src/hardware/task/payload.ts +1 -0
  65. package/src/hardware/task/task.spec.ts +45 -30
  66. package/src/label/client.ts +5 -5
  67. package/src/label/retriever.ts +2 -2
  68. package/src/ontology/client.ts +43 -31
  69. package/src/ontology/group/payload.ts +4 -4
  70. package/src/ontology/group/writer.ts +10 -12
  71. package/src/ontology/ontology.spec.ts +3 -5
  72. package/src/ontology/payload.ts +1 -1
  73. package/src/ranger/client.ts +55 -49
  74. package/src/ranger/payload.ts +4 -4
  75. package/src/vite-env.d.ts +1 -1
  76. package/src/workspace/lineplot/client.ts +2 -2
  77. package/src/workspace/lineplot/linePlot.spec.ts +12 -12
  78. package/src/workspace/lineplot/retriever.ts +2 -2
  79. package/src/workspace/lineplot/writer.ts +8 -8
  80. package/src/workspace/retriever.ts +2 -2
  81. package/src/workspace/schematic/retriever.ts +2 -2
  82. package/src/workspace/schematic/writer.ts +8 -6
  83. package/vite.config.ts +5 -0
package/dist/client.cjs CHANGED
@@ -1,37 +1,41 @@
1
- "use strict";var Zi=Object.defineProperty;var Ui=(r,e,t)=>e in r?Zi(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t;var o=(r,e,t)=>Ui(r,typeof e!="symbol"?e+"":e,t);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const s=require("zod");var Bi=Object.defineProperty,Li=(r,e,t)=>e in r?Bi(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,k=(r,e,t)=>Li(r,typeof e!="symbol"?e+"":e,t);const qi=r=>{const e=r.replace(/_[a-z]/g,t=>t[1].toUpperCase());return e.length>1&&e[0]===e[0].toUpperCase()&&e[1]===e[1].toUpperCase()?e:e[0].toLowerCase()+e.slice(1)},Yn=r=>{const e=(t,n=Nr)=>{if(typeof t=="string")return r(t);if(Array.isArray(t))return t.map(c=>e(c,n));if(!lr(t))return t;n=Fi(n);const i={},a=t;return Object.keys(a).forEach(c=>{let l=a[c];const u=r(c);n.recursive&&(lr(l)?an(l,n.keepTypesOnRecursion)||(l=e(l,n)):n.recursiveInArray&&sn(l)&&(l=[...l].map(f=>{let g=f;return lr(f)?an(g,n.keepTypesOnRecursion)||(g=e(f,n)):sn(f)&&(g=e({key:f},n).key),g}))),i[u]=l}),i};return e},Yi=Yn(qi),Wi=r=>r.replace(/([a-z0-9])([A-Z])/g,(e,t,n)=>`${t}_${n.toLowerCase()}`),_i=Yn(Wi),Nr={recursive:!0,recursiveInArray:!0,keepTypesOnRecursion:[Number,String,Uint8Array]},Fi=(r=Nr)=>(r.recursive==null?r=Nr:r.recursiveInArray==null&&(r.recursiveInArray=!1),r),sn=r=>r!=null&&Array.isArray(r),lr=r=>r!=null&&typeof r=="object"&&!Array.isArray(r),an=(r,e)=>(e||[]).some(t=>r instanceof t),Wn=r=>r!=null&&typeof r=="object"&&!Array.isArray(r);var Ki=Object.defineProperty,Gi=(r,e,t)=>e in r?Ki(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,ut=(r,e,t)=>Gi(r,typeof e!="symbol"?e+"":e,t);let Vi=class{constructor(){ut(this,"contentType","application/json"),ut(this,"decoder"),ut(this,"encoder"),this.decoder=new TextDecoder,this.encoder=new TextEncoder}encode(e){return this.encoder.encode(this.encodeString(e)).buffer}decode(e,t){return this.decodeString(this.decoder.decode(e),t)}decodeString(e,t){const n=JSON.parse(e),i=Yi(n);return t!=null?t.parse(i):i}encodeString(e){const t=_i(e);return JSON.stringify(t,(n,i)=>ArrayBuffer.isView(i)?Array.from(i):Wn(i)&&"encode_value"in i?typeof i.value=="bigint"?i.value.toString():i.value:typeof i=="bigint"?i.toString():i)}static registerCustomType(){}},Ji=class{constructor(){ut(this,"contentType","text/csv")}encode(e){const t=this.encodeString(e);return new TextEncoder().encode(t).buffer}decode(e,t){const n=new TextDecoder().decode(e);return this.decodeString(n,t)}encodeString(e){if(!Array.isArray(e)||e.length===0||!Wn(e[0]))throw new Error("Payload must be an array of objects");const t=Object.keys(e[0]),n=[t.join(",")];return e.forEach(i=>{const a=t.map(c=>JSON.stringify(i[c]??""));n.push(a.join(","))}),n.join(`
1
+ "use strict";var Fi=Object.defineProperty;var Ki=(r,e,t)=>e in r?Fi(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t;var o=(r,e,t)=>Ki(r,typeof e!="symbol"?e+"":e,t);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const s=require("zod");var Gi=Object.defineProperty,Ji=(r,e,t)=>e in r?Gi(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,k=(r,e,t)=>Ji(r,typeof e!="symbol"?e+"":e,t);const Hi=r=>{const e=r.replace(/_[a-z]/g,t=>t[1].toUpperCase());return e.length>1&&e[0]===e[0].toUpperCase()&&e[1]===e[1].toUpperCase()?e:e[0].toLowerCase()+e.slice(1)},Xn=r=>{const e=(t,n=Rr)=>{if(typeof t=="string")return r(t);if(Array.isArray(t))return t.map(c=>e(c,n));if(!yr(t))return t;n=ta(n);const i={},a=t;return Object.keys(a).forEach(c=>{let l=a[c];const u=r(c);n.recursive&&(yr(l)?yn(l,n.keepTypesOnRecursion)||(l=e(l,n)):n.recursiveInArray&&hn(l)&&(l=[...l].map(h=>{let p=h;return yr(h)?yn(p,n.keepTypesOnRecursion)||(p=e(h,n)):hn(h)&&(p=e({key:h},n).key),p}))),i[u]=l}),i};return e},Xi=Xn(Hi),Qi=r=>r.replace(/([a-z0-9])([A-Z])/g,(e,t,n)=>`${t}_${n.toLowerCase()}`),ea=Xn(Qi),Rr={recursive:!0,recursiveInArray:!0,keepTypesOnRecursion:[Number,String,Uint8Array]},ta=(r=Rr)=>(r.recursive==null?r=Rr:r.recursiveInArray==null&&(r.recursiveInArray=!1),r),hn=r=>r!=null&&Array.isArray(r),yr=r=>r!=null&&typeof r=="object"&&!Array.isArray(r),yn=(r,e)=>(e||[]).some(t=>r instanceof t),Qn=r=>r!=null&&typeof r=="object"&&!Array.isArray(r);var ra=Object.defineProperty,na=(r,e,t)=>e in r?ra(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,ut=(r,e,t)=>na(r,typeof e!="symbol"?e+"":e,t);let sa=class{constructor(){ut(this,"contentType","application/json"),ut(this,"decoder"),ut(this,"encoder"),this.decoder=new TextDecoder,this.encoder=new TextEncoder}encode(e){return this.encoder.encode(this.encodeString(e)).buffer}decode(e,t){return this.decodeString(this.decoder.decode(e),t)}decodeString(e,t){const n=JSON.parse(e),i=Xi(n);return t!=null?t.parse(i):i}encodeString(e){const t=ea(e);return JSON.stringify(t,(n,i)=>ArrayBuffer.isView(i)?Array.from(i):Qn(i)&&"encode_value"in i?typeof i.value=="bigint"?i.value.toString():i.value:typeof i=="bigint"?i.toString():i)}static registerCustomType(){}},ia=class{constructor(){ut(this,"contentType","text/csv")}encode(e){const t=this.encodeString(e);return new TextEncoder().encode(t).buffer}decode(e,t){const n=new TextDecoder().decode(e);return this.decodeString(n,t)}encodeString(e){if(!Array.isArray(e)||e.length===0||!Qn(e[0]))throw new Error("Payload must be an array of objects");const t=Object.keys(e[0]),n=[t.join(",")];return e.forEach(i=>{const a=t.map(c=>JSON.stringify(i[c]??""));n.push(a.join(","))}),n.join(`
2
2
  `)}decodeString(e,t){const[n,...i]=e.trim().split(`
3
- `).map(l=>l.trim());if(n.length===0)return t!=null?t.parse({}):{};const a=n.split(",").map(l=>l.trim()),c={};return a.forEach(l=>{c[l]=[]}),i.forEach(l=>{const u=l.split(",").map(f=>f.trim());a.forEach((f,g)=>{const p=this.parseValue(u[g]);p!=null&&c[f].push(p)})}),t!=null?t.parse(c):c}parseValue(e){if(e==null||e.length===0)return null;const t=Number(e);return isNaN(t)?e.startsWith('"')&&e.endsWith('"')?e.slice(1,-1):e:t}static registerCustomType(){}},Hi=class{constructor(){ut(this,"contentType","text/plain")}encode(e){return new TextEncoder().encode(e).buffer}decode(e,t){const n=new TextDecoder().decode(e);return t!=null?t.parse(n):n}};new Vi;new Ji;new Hi;const Vt=s.z.tuple([s.z.number(),s.z.number()]);s.z.tuple([s.z.bigint(),s.z.bigint()]);const _n=s.z.object({width:s.z.number(),height:s.z.number()}),Xi=s.z.object({signedWidth:s.z.number(),signedHeight:s.z.number()}),Qi=["width","height"];s.z.enum(Qi);const ea=["start","center","end"],ta=["signedWidth","signedHeight"];s.z.enum(ta);const Yt=s.z.object({x:s.z.number(),y:s.z.number()}),ra=s.z.object({clientX:s.z.number(),clientY:s.z.number()}),na=["x","y"],Fn=s.z.enum(na),Kn=["top","right","bottom","left"];s.z.enum(Kn);const sa=["left","right"],Gn=s.z.enum(sa),ia=["top","bottom"],Vn=s.z.enum(ia),Jn=["center"],on=s.z.enum(Jn),aa=[...Kn,...Jn],Hn=s.z.enum(aa);s.z.enum(ea);const oa=["first","last"];s.z.enum(oa);const ca=s.z.object({lower:s.z.number(),upper:s.z.number()}),la=s.z.object({lower:s.z.bigint(),upper:s.z.bigint()});s.z.union([ca,Vt]);s.z.union([la,Vt]);s.z.union([Fn,Hn]);s.z.union([Fn,Hn,s.z.instanceof(String)]);const ur=(r,e)=>{const t={};if(typeof r=="number"||typeof r=="bigint")e!=null?(t.lower=r,t.upper=e):(t.lower=typeof r=="bigint"?0n:0,t.upper=r);else if(Array.isArray(r)){if(r.length!==2)throw new Error("bounds: expected array of length 2");[t.lower,t.upper]=r}else return cn(r);return cn(t)},cn=r=>r.lower>r.upper?{lower:r.upper,upper:r.lower}:r;s.z.object({x:Gn.or(on),y:Vn.or(on)});const ua=s.z.object({x:Gn,y:Vn}),ha=Object.freeze({x:"left",y:"top"}),ya=(r,e)=>r.x===e.x&&r.y===e.y,ln=s.z.union([s.z.number(),Yt,Vt,_n,Xi,ra]),da=(r,e)=>{if(typeof r=="string"){if(e===void 0)throw new Error("The y coordinate must be given.");return r==="x"?{x:e,y:0}:{x:0,y:e}}return typeof r=="number"?{x:r,y:e??r}:Array.isArray(r)?{x:r[0],y:r[1]}:"signedWidth"in r?{x:r.signedWidth,y:r.signedHeight}:"clientX"in r?{x:r.clientX,y:r.clientY}:"width"in r?{x:r.width,y:r.height}:{x:r.x,y:r.y}},un=Object.freeze({x:0,y:0}),At=s.z.union([s.z.number(),s.z.string()]);s.z.object({top:At,left:At,width:At,height:At});s.z.object({left:s.z.number(),top:s.z.number(),right:s.z.number(),bottom:s.z.number()});s.z.object({one:Yt,two:Yt,root:ua});const Zr=(r,e,t=0,n=0,i)=>{const a={one:{...un},two:{...un},root:i??ha};if(typeof r=="number"){if(typeof e!="number")throw new Error("Box constructor called with invalid arguments");return a.one={x:r,y:e},a.two={x:a.one.x+t,y:a.one.y+n},a}return"one"in r&&"two"in r&&"root"in r?{...r,root:i??r.root}:("getBoundingClientRect"in r&&(r=r.getBoundingClientRect()),"left"in r?(a.one={x:r.left,y:r.top},a.two={x:r.right,y:r.bottom},a):(a.one=r,e==null?a.two={x:a.one.x+t,y:a.one.y+n}:typeof e=="number"?a.two={x:a.one.x+e,y:a.one.y+t}:"width"in e?a.two={x:a.one.x+e.width,y:a.one.y+e.height}:"signedWidth"in e?a.two={x:a.one.x+e.signedWidth,y:a.one.y+e.signedHeight}:a.two=e,a))},hr=r=>{const e=Zr(r);return{lower:e.one.x,upper:e.two.x}},yr=r=>{const e=Zr(r);return{lower:e.one.y,upper:e.two.y}},fa=r=>typeof r!="object"||r==null?!1:"one"in r&&"two"in r&&"root"in r;var pa=Object.defineProperty,ga=(r,e,t)=>e in r?pa(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,ue=(r,e,t)=>ga(r,typeof e!="symbol"?e+"":e,t);const ma=(r,e,t)=>e!==void 0&&r<e?e:t!==void 0&&r>t?t:r;s.z.object({offset:ln,scale:ln});const wa=r=>(e,t,n,i)=>t==="dimension"?[e,n]:[e,i?n-r:n+r],ba=r=>(e,t,n,i)=>[e,i?n/r:n*r],va=r=>(e,t,n)=>{if(e===null)return[r,n];const{lower:i,upper:a}=e,{lower:c,upper:l}=r,u=a-i,f=l-c;if(t==="dimension")return[r,n*(f/u)];const g=(n-i)*(f/u)+c;return[r,g]},Ta=r=>(e,t,n)=>[r,n],Oa=()=>(r,e,t)=>{if(r===null)throw new Error("cannot invert without bounds");if(e==="dimension")return[r,t];const{lower:n,upper:i}=r;return[r,i-(t-n)]},za=r=>(e,t,n)=>{const{lower:i,upper:a}=r;return n=ma(n,i,a),[e,n]},Ir=class rt{constructor(){ue(this,"ops",[]),ue(this,"currBounds",null),ue(this,"currType",null),ue(this,"reversed",!1),this.ops=[]}static translate(e){return new rt().translate(e)}static magnify(e){return new rt().magnify(e)}static scale(e,t){return new rt().scale(e,t)}translate(e){const t=this.new(),n=wa(e);return n.type="translate",t.ops.push(n),t}magnify(e){const t=this.new(),n=ba(e);return n.type="magnify",t.ops.push(n),t}scale(e,t){const n=ur(e,t),i=this.new(),a=va(n);return a.type="scale",i.ops.push(a),i}clamp(e,t){const n=ur(e,t),i=this.new(),a=za(n);return a.type="clamp",i.ops.push(a),i}reBound(e,t){const n=ur(e,t),i=this.new(),a=Ta(n);return a.type="re-bound",i.ops.push(a),i}invert(){const e=Oa();e.type="invert";const t=this.new();return t.ops.push(e),t}pos(e){return this.exec("position",e)}dim(e){return this.exec("dimension",e)}new(){const e=new rt;return e.ops=this.ops.slice(),e.reversed=this.reversed,e}exec(e,t){return this.currBounds=null,this.ops.reduce(([n,i],a)=>a(n,e,i,this.reversed),[null,t])[1]}reverse(){const e=this.new();e.ops.reverse();const t=[];return e.ops.forEach((n,i)=>{if(n.type==="scale"||t.some(([c,l])=>i>=c&&i<=l))return;const a=e.ops.findIndex((c,l)=>c.type==="scale"&&l>i);a!==-1&&t.push([i,a])}),t.forEach(([n,i])=>{const a=e.ops.slice(n,i);a.unshift(e.ops[i]),e.ops.splice(n,i-n+1,...a)}),e.reversed=!e.reversed,e}};ue(Ir,"IDENTITY",new Ir);let hn=Ir;const yn=class oe{constructor(e=new hn,t=new hn,n=null){ue(this,"x"),ue(this,"y"),ue(this,"currRoot"),this.x=e,this.y=t,this.currRoot=n}static translate(e,t){return new oe().translate(e,t)}static translateX(e){return new oe().translateX(e)}static translateY(e){return new oe().translateY(e)}static clamp(e){return new oe().clamp(e)}static magnify(e){return new oe().magnify(e)}static scale(e){return new oe().scale(e)}static reBound(e){return new oe().reBound(e)}translate(e,t){const n=da(e,t),i=this.copy();return i.x=this.x.translate(n.x),i.y=this.y.translate(n.y),i}translateX(e){const t=this.copy();return t.x=this.x.translate(e),t}translateY(e){const t=this.copy();return t.y=this.y.translate(e),t}magnify(e){const t=this.copy();return t.x=this.x.magnify(e.x),t.y=this.y.magnify(e.y),t}scale(e){const t=this.copy();if(fa(e)){const n=this.currRoot;return t.currRoot=e.root,n!=null&&!ya(n,e.root)&&(n.x!==e.root.x&&(t.x=t.x.invert()),n.y!==e.root.y&&(t.y=t.y.invert())),t.x=t.x.scale(hr(e)),t.y=t.y.scale(yr(e)),t}return t.x=t.x.scale(e.width),t.y=t.y.scale(e.height),t}reBound(e){const t=this.copy();return t.x=this.x.reBound(hr(e)),t.y=this.y.reBound(yr(e)),t}clamp(e){const t=this.copy();return t.x=this.x.clamp(hr(e)),t.y=this.y.clamp(yr(e)),t}copy(){const e=new oe;return e.currRoot=this.currRoot,e.x=this.x,e.y=this.y,e}reverse(){const e=this.copy();return e.x=this.x.reverse(),e.y=this.y.reverse(),e}pos(e){return{x:this.x.pos(e.x),y:this.y.pos(e.y)}}box(e){return Zr(this.pos(e.one),this.pos(e.two),0,0,this.currRoot??e.root)}};ue(yn,"IDENTITY",new yn);const Ea=s.z.object({signedWidth:s.z.number(),signedHeight:s.z.number()});s.z.union([_n,Ea,Yt,Vt]);var Sa=Object.defineProperty,Na=(r,e,t)=>e in r?Sa(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,m=(r,e,t)=>Na(r,typeof e!="symbol"?e+"":e,t);const Xn=(r,e)=>{const t=new q(e);if(![Y.DAY,Y.HOUR,Y.MINUTE,Y.SECOND,Y.MILLISECOND,Y.MICROSECOND,Y.NANOSECOND].some(i=>i.equals(t)))throw new Error("Invalid argument for remainder. Must be an even TimeSpan or Timestamp");const n=r.valueOf()%t.valueOf();return r instanceof q?new q(n):new Y(n)},A=class b{constructor(e,t="UTC"){if(m(this,"value"),m(this,"encodeValue",!0),e==null)this.value=b.now().valueOf();else if(e instanceof Date)this.value=BigInt(e.getTime())*b.MILLISECOND.valueOf();else if(typeof e=="string")this.value=b.parseDateTimeString(e,t).valueOf();else if(Array.isArray(e))this.value=b.parseDate(e);else{let n=BigInt(0);e instanceof Number&&(e=e.valueOf()),t==="local"&&(n=b.utcOffset.valueOf()),typeof e=="number"&&(isFinite(e)?e=Math.trunc(e):(isNaN(e)&&(e=0),e===1/0?e=b.MAX:e=b.MIN)),this.value=BigInt(e.valueOf())+n}}static parseDate([e=1970,t=1,n=1]){const i=new Date(e,t-1,n,0,0,0,0);return new b(BigInt(i.getTime())*b.MILLISECOND.valueOf()).truncate(b.DAY).valueOf()}encode(){return this.value.toString()}valueOf(){return this.value}static parseTimeString(e,t="UTC"){const[n,i,a]=e.split(":");let c="00",l="00";a!=null&&([c,l]=a.split("."));let u=b.hours(parseInt(n??"00",10)).add(b.minutes(parseInt(i??"00",10))).add(b.seconds(parseInt(c??"00",10))).add(b.milliseconds(parseInt(l??"00",10)));return t==="local"&&(u=u.add(b.utcOffset)),u.valueOf()}static parseDateTimeString(e,t="UTC"){if(!e.includes("/")&&!e.includes("-"))return b.parseTimeString(e,t);const n=new Date(e);return e.includes(":")||n.setUTCHours(0,0,0,0),new b(BigInt(n.getTime())*b.MILLISECOND.valueOf(),t).valueOf()}fString(e="ISO",t="UTC"){switch(e){case"ISODate":return this.toISOString(t).slice(0,10);case"ISOTime":return this.toISOString(t).slice(11,23);case"time":return this.timeString(!1,t);case"preciseTime":return this.timeString(!0,t);case"date":return this.dateString();case"preciseDate":return`${this.dateString()} ${this.timeString(!0,t)}`;case"dateTime":return`${this.dateString()} ${this.timeString(!1,t)}`;default:return this.toISOString(t)}}toISOString(e="UTC"){return e==="UTC"?this.date().toISOString():this.sub(b.utcOffset).date().toISOString()}timeString(e=!1,t="UTC"){const n=this.toISOString(t);return e?n.slice(11,23):n.slice(11,19)}dateString(){const e=this.date(),t=e.toLocaleString("default",{month:"short"}),n=e.toLocaleString("default",{day:"numeric"});return`${t} ${n}`}static get utcOffset(){return new Y(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 Ia(this,e).makeValid()}spanRange(e){return this.range(this.add(e)).makeValid()}get isZero(){return this.valueOf()===BigInt(0)}after(e){return this.valueOf()>new 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(this.valueOf()+BigInt(e.valueOf()))}sub(e){return new b(this.valueOf()-BigInt(e.valueOf()))}milliseconds(){return Number(this.valueOf())/Number(b.MILLISECOND.valueOf())}toString(){return this.date().toISOString()}remainder(e){return Xn(this,e)}get isToday(){return this.truncate(Y.DAY).equals(b.now().truncate(Y.DAY))}truncate(e){return this.sub(this.remainder(e))}static now(){return new b(new Date)}static max(...e){let t=b.MIN;for(const n of e){const i=new b(n);i.after(t)&&(t=i)}return t}static min(...e){let t=b.MAX;for(const n of e){const i=new b(n);i.before(t)&&(t=i)}return t}static nanoseconds(e){return new b(e)}static microseconds(e){return b.nanoseconds(e*1e3)}static milliseconds(e){return b.microseconds(e*1e3)}static seconds(e){return b.milliseconds(e*1e3)}static minutes(e){return b.seconds(e*60)}static hours(e){return b.minutes(e*60)}static days(e){return b.hours(e*24)}};m(A,"NANOSECOND",A.nanoseconds(1)),m(A,"MICROSECOND",A.microseconds(1)),m(A,"MILLISECOND",A.milliseconds(1)),m(A,"SECOND",A.seconds(1)),m(A,"MINUTE",A.minutes(1)),m(A,"HOUR",A.hours(1)),m(A,"DAY",A.days(1)),m(A,"MAX",new A((1n<<63n)-1n)),m(A,"MIN",new A(0)),m(A,"ZERO",new A(0)),m(A,"z",s.z.union([s.z.object({value:s.z.bigint()}).transform(r=>new A(r.value)),s.z.string().transform(r=>new A(BigInt(r))),s.z.instanceof(Number).transform(r=>new A(r)),s.z.number().transform(r=>new A(r)),s.z.instanceof(A)]));let q=A;const $=class N{constructor(e){m(this,"value"),m(this,"encodeValue",!0),typeof e=="number"&&(e=Math.trunc(e.valueOf())),this.value=BigInt(e.valueOf())}encode(){return this.value.toString()}valueOf(){return this.value}lessThan(e){return this.valueOf()<new N(e).valueOf()}greaterThan(e){return this.valueOf()>new N(e).valueOf()}lessThanOrEqual(e){return this.valueOf()<=new N(e).valueOf()}greaterThanOrEqual(e){return this.valueOf()>=new N(e).valueOf()}remainder(e){return Xn(this,e)}truncate(e){return new N(BigInt(Math.trunc(Number(this.valueOf()/e.valueOf())))*e.valueOf())}toString(){const e=this.truncate(N.DAY),t=this.truncate(N.HOUR),n=this.truncate(N.MINUTE),i=this.truncate(N.SECOND),a=this.truncate(N.MILLISECOND),c=this.truncate(N.MICROSECOND),l=this.truncate(N.NANOSECOND),u=e,f=t.sub(e),g=n.sub(t),p=i.sub(n),j=a.sub(i),P=c.sub(a),X=l.sub(c);let D="";return u.isZero||(D+=`${u.days}d `),f.isZero||(D+=`${f.hours}h `),g.isZero||(D+=`${g.minutes}m `),p.isZero||(D+=`${p.seconds}s `),j.isZero||(D+=`${j.milliseconds}ms `),P.isZero||(D+=`${P.microseconds}µs `),X.isZero||(D+=`${X.nanoseconds}ns`),D.trim()}get days(){return Number(this.valueOf())/Number(N.DAY.valueOf())}get hours(){return Number(this.valueOf())/Number(N.HOUR.valueOf())}get minutes(){return Number(this.valueOf())/Number(N.MINUTE.valueOf())}get seconds(){return Number(this.valueOf())/Number(N.SECOND.valueOf())}get milliseconds(){return Number(this.valueOf())/Number(N.MILLISECOND.valueOf())}get microseconds(){return Number(this.valueOf())/Number(N.MICROSECOND.valueOf())}get nanoseconds(){return Number(this.valueOf())}get isZero(){return this.valueOf()===BigInt(0)}equals(e){return this.valueOf()===new N(e).valueOf()}add(e){return new N(this.valueOf()+new N(e).valueOf())}sub(e){return new N(this.valueOf()-new N(e).valueOf())}static nanoseconds(e=1){return new N(e)}static microseconds(e=1){return N.nanoseconds(e*1e3)}static milliseconds(e=1){return N.microseconds(e*1e3)}static seconds(e=1){return N.milliseconds(e*1e3)}static minutes(e){return N.seconds(e.valueOf()*60)}static hours(e){return N.minutes(e*60)}static days(e){return N.hours(e*24)}};m($,"NANOSECOND",$.nanoseconds(1)),m($,"MICROSECOND",$.microseconds(1)),m($,"MILLISECOND",$.milliseconds(1)),m($,"SECOND",$.seconds(1)),m($,"MINUTE",$.minutes(1)),m($,"HOUR",$.hours(1)),m($,"DAY",$.days(1)),m($,"MAX",new $((1n<<63n)-1n)),m($,"MIN",new $(0)),m($,"ZERO",new $(0)),m($,"z",s.z.union([s.z.object({value:s.z.bigint()}).transform(r=>new $(r.value)),s.z.string().transform(r=>new $(BigInt(r))),s.z.instanceof(Number).transform(r=>new $(r)),s.z.number().transform(r=>new $(r)),s.z.instanceof($)]));let Y=$;const $t=class xt extends Number{constructor(e){e instanceof Number?super(e.valueOf()):super(e)}toString(){return`${this.valueOf()} Hz`}equals(e){return this.valueOf()===new xt(e).valueOf()}get period(){return Y.seconds(1/this.valueOf())}sampleCount(e){return new Y(e).seconds*this.valueOf()}byteCount(e,t){return this.sampleCount(e)*new G(t).valueOf()}span(e){return Y.seconds(e/this.valueOf())}byteSpan(e,t){return this.span(e.valueOf()/t.valueOf())}static hz(e){return new xt(e)}static khz(e){return xt.hz(e*1e3)}};m($t,"z",s.z.union([s.z.number().transform(r=>new $t(r)),s.z.instanceof(Number).transform(r=>new $t(r)),s.z.instanceof($t)]));const B=class extends Number{constructor(e){e instanceof Number?super(e.valueOf()):super(e)}length(e){return e.valueOf()/this.valueOf()}size(e){return new ka(e*this.valueOf())}};m(B,"UNKNOWN",new B(0)),m(B,"BIT128",new B(16)),m(B,"BIT64",new B(8)),m(B,"BIT32",new B(4)),m(B,"BIT16",new B(2)),m(B,"BIT8",new B(1)),m(B,"z",s.z.union([s.z.number().transform(r=>new B(r)),s.z.instanceof(Number).transform(r=>new B(r)),s.z.instanceof(B)]));let G=B;const re=class Ct{constructor(e,t){m(this,"start"),m(this,"end"),typeof e=="object"&&"start"in e?(this.start=new q(e.start),this.end=new q(e.end)):(this.start=new q(e),this.end=new q(t))}get span(){return new Y(this.end.valueOf()-this.start.valueOf())}get isValid(){return this.start.valueOf()<=this.end.valueOf()}makeValid(){return this.isValid?this:this.swap()}get isZero(){return this.span.isZero}get numeric(){return{start:Number(this.start.valueOf()),end:Number(this.end.valueOf())}}swap(){return new Ct(this.end,this.start)}equals(e){return this.start.equals(e.start)&&this.end.equals(e.end)}toString(){return`${this.start.toString()} - ${this.end.toString()}`}toPrettyString(){return`${this.start.fString("preciseDate")} - ${this.span.toString()}`}overlapsWith(e,t=Y.ZERO){e=e.makeValid();const n=this.makeValid();if(this.equals(e))return!0;if(e.end.equals(n.start)||n.end.equals(e.start))return!1;const i=q.max(n.start,e.start),a=q.min(n.end,e.end);return a.before(i)?!1:new Y(a.sub(i)).greaterThanOrEqual(t)}roughlyEquals(e,t){let n=this.start.sub(e.start).valueOf(),i=this.end.sub(e.end).valueOf();return n<0&&(n=-n),i<0&&(i=-i),n<=t.valueOf()&&i<=t.valueOf()}contains(e){return e instanceof Ct?this.contains(e.start)&&this.contains(e.end):this.start.beforeEq(e)&&this.end.after(e)}boundBy(e){const t=new Ct(this.start,this.end);return e.start.after(this.start)&&(t.start=e.start),e.start.after(this.end)&&(t.end=e.start),e.end.before(this.end)&&(t.end=e.end),e.end.before(this.start)&&(t.start=e.end),t}};m(re,"MAX",new re(q.MIN,q.MAX)),m(re,"MIN",new re(q.MAX,q.MIN)),m(re,"ZERO",new re(q.ZERO,q.ZERO)),m(re,"z",s.z.union([s.z.object({start:q.z,end:q.z}).transform(r=>new re(r.start,r.end)),s.z.instanceof(re)]));let Ia=re;const y=class ne extends String{constructor(e){if(e instanceof ne||typeof e=="string"||typeof e.valueOf()=="string"){super(e.valueOf());return}else{const t=ne.ARRAY_CONSTRUCTOR_DATA_TYPES.get(e.constructor.name);if(t!=null){super(t.valueOf());return}}throw super(ne.UNKNOWN.valueOf()),new Error(`unable to find data type for ${e.toString()}`)}get Array(){const e=ne.ARRAY_CONSTRUCTORS.get(this.toString());if(e==null)throw new Error(`unable to find array constructor for ${this.valueOf()}`);return e}equals(e){return this.valueOf()===e.valueOf()}matches(...e){return e.some(t=>this.equals(t))}toString(){return this.valueOf()}get isVariable(){return this.equals(ne.JSON)||this.equals(ne.STRING)}get isNumeric(){return!this.isVariable&&!this.equals(ne.UUID)}get isInteger(){return this.toString().startsWith("int")}get isFloat(){return this.toString().startsWith("float")}get density(){const e=ne.DENSITIES.get(this.toString());if(e==null)throw new Error(`unable to find density for ${this.valueOf()}`);return e}canSafelyCastTo(e){return this.equals(e)?!0:this.isVariable&&!e.isVariable||!this.isVariable&&e.isVariable?!1:this.isFloat&&e.isInteger||this.isInteger&&e.isFloat?this.density.valueOf()<e.density.valueOf():this.isFloat&&e.isFloat||this.isInteger&&e.isInteger?this.density.valueOf()<=e.density.valueOf():!1}canCastTo(e){return this.isNumeric&&e.isNumeric?!0:this.equals(e)}checkArray(e){return e.constructor===this.Array}toJSON(){return this.toString()}get usesBigInt(){return ne.BIG_INT_TYPES.some(e=>e.equals(this))}};m(y,"UNKNOWN",new y("unknown")),m(y,"FLOAT64",new y("float64")),m(y,"FLOAT32",new y("float32")),m(y,"INT64",new y("int64")),m(y,"INT32",new y("int32")),m(y,"INT16",new y("int16")),m(y,"INT8",new y("int8")),m(y,"UINT64",new y("uint64")),m(y,"UINT32",new y("uint32")),m(y,"UINT16",new y("uint16")),m(y,"UINT8",new y("uint8")),m(y,"BOOLEAN",y.UINT8),m(y,"TIMESTAMP",new y("timestamp")),m(y,"UUID",new y("uuid")),m(y,"STRING",new y("string")),m(y,"JSON",new y("json")),m(y,"ARRAY_CONSTRUCTORS",new Map([[y.UINT8.toString(),Uint8Array],[y.UINT16.toString(),Uint16Array],[y.UINT32.toString(),Uint32Array],[y.UINT64.toString(),BigUint64Array],[y.FLOAT32.toString(),Float32Array],[y.FLOAT64.toString(),Float64Array],[y.INT8.toString(),Int8Array],[y.INT16.toString(),Int16Array],[y.INT32.toString(),Int32Array],[y.INT64.toString(),BigInt64Array],[y.TIMESTAMP.toString(),BigInt64Array],[y.STRING.toString(),Uint8Array],[y.JSON.toString(),Uint8Array],[y.UUID.toString(),Uint8Array]])),m(y,"ARRAY_CONSTRUCTOR_DATA_TYPES",new Map([[Uint8Array.name,y.UINT8],[Uint16Array.name,y.UINT16],[Uint32Array.name,y.UINT32],[BigUint64Array.name,y.UINT64],[Float32Array.name,y.FLOAT32],[Float64Array.name,y.FLOAT64],[Int8Array.name,y.INT8],[Int16Array.name,y.INT16],[Int32Array.name,y.INT32],[BigInt64Array.name,y.INT64]])),m(y,"DENSITIES",new Map([[y.UINT8.toString(),G.BIT8],[y.UINT16.toString(),G.BIT16],[y.UINT32.toString(),G.BIT32],[y.UINT64.toString(),G.BIT64],[y.FLOAT32.toString(),G.BIT32],[y.FLOAT64.toString(),G.BIT64],[y.INT8.toString(),G.BIT8],[y.INT16.toString(),G.BIT16],[y.INT32.toString(),G.BIT32],[y.INT64.toString(),G.BIT64],[y.TIMESTAMP.toString(),G.BIT64],[y.STRING.toString(),G.UNKNOWN],[y.JSON.toString(),G.UNKNOWN],[y.UUID.toString(),G.BIT128]])),m(y,"ALL",[y.UNKNOWN,y.FLOAT64,y.FLOAT32,y.INT64,y.INT32,y.INT16,y.INT8,y.UINT64,y.UINT32,y.UINT16,y.UINT8,y.TIMESTAMP,y.UUID,y.STRING,y.JSON]),m(y,"BIG_INT_TYPES",[y.INT64,y.UINT64,y.TIMESTAMP]),m(y,"z",s.z.union([s.z.string().transform(r=>new y(r)),s.z.instanceof(y)]));const _=class M extends Number{constructor(e){super(e.valueOf())}largerThan(e){return this.valueOf()>e.valueOf()}smallerThan(e){return this.valueOf()<e.valueOf()}add(e){return M.bytes(this.valueOf()+e.valueOf())}sub(e){return M.bytes(this.valueOf()-e.valueOf())}truncate(e){return new M(Math.trunc(this.valueOf()/e.valueOf())*e.valueOf())}remainder(e){return M.bytes(this.valueOf()%e.valueOf())}get gigabytes(){return this.valueOf()/M.GIGABYTE.valueOf()}get megabytes(){return this.valueOf()/M.MEGABYTE.valueOf()}get kilobytes(){return this.valueOf()/M.KILOBYTE.valueOf()}get terabytes(){return this.valueOf()/M.TERABYTE.valueOf()}toString(){const e=this.truncate(M.TERABYTE),t=this.truncate(M.GIGABYTE),n=this.truncate(M.MEGABYTE),i=this.truncate(M.KILOBYTE),a=this.truncate(M.BYTE),c=e,l=t.sub(e),u=n.sub(t),f=i.sub(n),g=a.sub(i);let p="";return c.isZero||(p+=`${c.terabytes}TB `),l.isZero||(p+=`${l.gigabytes}GB `),u.isZero||(p+=`${u.megabytes}MB `),f.isZero||(p+=`${f.kilobytes}KB `),(!g.isZero||p==="")&&(p+=`${g.valueOf()}B`),p.trim()}static bytes(e=1){return new M(e)}static kilobytes(e=1){return M.bytes(e.valueOf()*1e3)}static megabytes(e=1){return M.kilobytes(e.valueOf()*1e3)}static gigabytes(e=1){return M.megabytes(e.valueOf()*1e3)}static terabytes(e){return M.gigabytes(e.valueOf()*1e3)}get isZero(){return this.valueOf()===0}};m(_,"BYTE",new _(1)),m(_,"KILOBYTE",_.kilobytes(1)),m(_,"MEGABYTE",_.megabytes(1)),m(_,"GIGABYTE",_.gigabytes(1)),m(_,"TERABYTE",_.terabytes(1)),m(_,"ZERO",new _(0)),m(_,"z",s.z.union([s.z.number().transform(r=>new _(r)),s.z.instanceof(_)]));let ka=_;s.z.union([s.z.instanceof(Uint8Array),s.z.instanceof(Uint16Array),s.z.instanceof(Uint32Array),s.z.instanceof(BigUint64Array),s.z.instanceof(Float32Array),s.z.instanceof(Float64Array),s.z.instanceof(Int8Array),s.z.instanceof(Int16Array),s.z.instanceof(Int32Array),s.z.instanceof(BigInt64Array)]);s.z.object({key:s.z.string(),value:s.z.string()});s.z.record(s.z.union([s.z.number(),s.z.string(),s.z.symbol()]),s.z.unknown());const Qn=()=>typeof process<"u"&&process.versions!=null&&process.versions.node!=null?"node":typeof window>"u"||window.document===void 0?"webworker":"browser",Aa=Qn(),es=["MacOS","Windows","Linux","Docker"],$a=s.z.enum(es);let dr;const Ra=()=>{if(typeof window>"u")return;const r=window.navigator.userAgent.toLowerCase();if(r.includes("mac"))return"MacOS";if(r.includes("win"))return"Windows";if(r.includes("linux"))return"Linux"},xa=(r={})=>{const{force:e,default:t}=r;return e??dr??(dr=Ra(),dr??t)},ts=Object.freeze(Object.defineProperty({__proto__:null,OPERATING_SYSTEMS:es,RUNTIME:Aa,detect:Qn,getOS:xa,osZ:$a},Symbol.toStringTag,{value:"Module"}));var Ca=Object.defineProperty,Pa=(r,e,t)=>e in r?Ca(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,nt=(r,e,t)=>Pa(r,typeof e!="symbol"?e+"":e,t);const ja=(...r)=>r.map(rs).join(""),rs=r=>(r.endsWith("/")||(r+="/"),r.startsWith("/")&&(r=r.slice(1)),r),Da=r=>r.endsWith("/")?r.slice(0,-1):r,Ma=(r,e="")=>r===null?"":"?"+Object.entries(r).filter(([,t])=>t==null?!1:Array.isArray(t)?t.length>0:!0).map(([t,n])=>`${e}${t}=${n}`).join("&"),kr=class Ar{constructor({host:e,port:t,protocol:n="",pathPrefix:i=""}){nt(this,"protocol"),nt(this,"host"),nt(this,"port"),nt(this,"path"),this.protocol=n,this.host=e,this.port=t,this.path=rs(i)}replace(e){return new Ar({host:e.host??this.host,port:e.port??this.port,protocol:e.protocol??this.protocol,pathPrefix:e.pathPrefix??this.path})}child(e){return new Ar({...this,pathPrefix:ja(this.path,e)})}toString(){return Da(`${this.protocol}://${this.host}:${this.port}/${this.path}`)}};nt(kr,"UNKNOWN",new kr({host:"unknown",port:0}));let Za=kr;var Ua=Object.defineProperty,Ba=(r,e,t)=>e in r?Ua(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,Pt=(r,e,t)=>Ba(r,typeof e!="symbol"?e+"":e,t);const xe=class extends Number{};Pt(xe,"Absolute",255),Pt(xe,"Default",1),Pt(xe,"z",s.z.union([s.z.instanceof(xe),s.z.number().int().min(0).max(255).transform(r=>new xe(r)),s.z.instanceof(Number).transform(r=>new xe(r))]));s.z.object({name:s.z.string(),key:s.z.string()});const ns=class st extends Error{constructor(){super(st.MESSAGE)}matches(e){return typeof e=="string"?e.includes(st.MESSAGE):e instanceof st||e.message.includes(st.MESSAGE)}};Pt(ns,"MESSAGE","canceled");let La=ns;new La;s.z.string().regex(/^\d+\.\d+\.\d+$/);const J=r=>e=>e!=null&&typeof e=="object"&&"type"in e&&typeof e.type=="string"?e.type.includes(r):e instanceof Error?e.message.includes(r):typeof e!="string"?!1:e.includes(r);let te=class extends Error{constructor(e){super(e),k(this,"discriminator","FreighterError"),k(this,"type","")}};const qa=r=>{if(r==null||typeof r!="object")return!1;const e=r;if(e.discriminator!=="FreighterError")return!1;if(!("type"in e))throw new Error(`Freighter error is missing its type property: ${JSON.stringify(e)}`);return!0},dn="unknown",fn="nil",Ya="freighter",Ot=s.z.object({type:s.z.string(),data:s.z.string()});class Wa{constructor(){k(this,"providers",[])}register(e){this.providers.push(e)}encode(e){if(e==null)return{type:fn,data:""};if(qa(e))for(const t of this.providers){const n=t.encode(e);if(n!=null)return n}return{type:dn,data:JSON.stringify(e)}}decode(e){if(e==null||e.type===fn)return null;if(e.type===dn)return new pn(e.data);for(const t of this.providers){const n=t.decode(e);if(n!=null)return n}return new pn(e.data)}}const ss=new Wa,is=({encode:r,decode:e})=>ss.register({encode:r,decode:e}),Ur=r=>ss.decode(r);class pn extends te{constructor(e){super(e),k(this,"type","unknown")}}const Jt="freighter.",jt=class as extends te{constructor(){super("EOF"),k(this,"type",as.TYPE)}};k(jt,"TYPE",Jt+"eof"),k(jt,"matches",J(jt.TYPE));let ge=jt;const Dt=class os extends te{constructor(){super("StreamClosed"),k(this,"type",os.TYPE)}};k(Dt,"TYPE",Jt+"stream_closed"),k(Dt,"matches",J(Dt.TYPE));let Ge=Dt;const Mt=class cs extends te{constructor(e={}){const{message:t="Unreachable",url:n=Za.UNKNOWN}=e;super(t),k(this,"type",cs.TYPE),k(this,"url"),this.url=n}};k(Mt,"TYPE",Jt+"unreachable"),k(Mt,"matches",J(Mt.TYPE));let Ne=Mt;const _a=r=>{if(!r.type.startsWith(Ya))return null;if(ge.matches(r))return{type:ge.TYPE,data:"EOF"};if(Ge.matches(r))return{type:Ge.TYPE,data:"StreamClosed"};if(Ne.matches(r))return{type:Ne.TYPE,data:"Unreachable"};throw new Error(`Unknown error type: ${r.type}: ${r.message}`)},Fa=r=>{if(!r.type.startsWith(Jt))return null;switch(r.type){case ge.TYPE:return new ge;case Ge.TYPE:return new Ge;case Ne.TYPE:return new Ne;default:throw new Error(`Unknown error type: ${r.data}`)}};is({encode:_a,decode:Fa});class ls{constructor(){k(this,"middleware",[])}use(...e){this.middleware.push(...e)}async executeMiddleware(e,t){let n=0;const i=async a=>{if(n===this.middleware.length)return await t(a);const c=this.middleware[n];return n++,await c(a,i)};return await i(e)}}const us="Content-Type",gn=r=>{if(ts.RUNTIME!=="node")return fetch;const e=require("node-fetch");if(r==="http")return e;const t=require("https"),n=new t.Agent({rejectUnauthorized:!1});return async(i,a)=>await e(i,{...a,agent:n})};class Ka extends ls{constructor(e,t,n=!1){return super(),k(this,"endpoint"),k(this,"encoder"),k(this,"fetch"),this.endpoint=e.replace({protocol:n?"https":"http"}),this.encoder=t,this.fetch=gn(this.endpoint.protocol),new Proxy(this,{get:(i,a,c)=>a==="endpoint"?this.endpoint:Reflect.get(i,a,c)})}get headers(){return{[us]:this.encoder.contentType}}async send(e,t,n,i){t=n==null?void 0:n.parse(t);let a=null;const c=this.endpoint.child(e),l={};l.method="POST",l.body=this.encoder.encode(t??{});const[,u]=await this.executeMiddleware({target:c.toString(),protocol:this.endpoint.protocol,params:{},role:"client"},async f=>{const g={...f,params:{}};l.headers={...this.headers,...f.params};let p;try{p=await gn(f.protocol)(f.target,l)}catch(P){let X=P;return X.message==="Load failed"&&(X=new Ne({url:c})),[g,X]}const j=await p.arrayBuffer();if(p!=null&&p.ok)return i!=null&&(a=this.encoder.decode(j,i)),[g,null];try{if(p.status!==400)return[g,new Error(p.statusText)];const P=this.encoder.decode(j,Ot),X=Ur(P);return[g,X]}catch(P){return[g,new Error(`[freighter] - failed to decode error: ${p.statusText}: ${P.message}`)]}});return[a,u]}}const w=async(r,e,t,n,i)=>{const[a,c]=await r.send(e,t,n,i);if(c!=null)throw c;return a},Ga=()=>ts.RUNTIME!=="node"?r=>new WebSocket(r):r=>new(require("ws")).WebSocket(r,{rejectUnauthorized:!1}),Va=s.z.object({type:s.z.union([s.z.literal("data"),s.z.literal("close")]),payload:s.z.unknown().optional(),error:s.z.optional(Ot)});class Ja{constructor(e,t,n,i){k(this,"encoder"),k(this,"reqSchema"),k(this,"resSchema"),k(this,"ws"),k(this,"serverClosed"),k(this,"sendClosed"),k(this,"receiveDataQueue",[]),k(this,"receiveCallbacksQueue",[]),this.encoder=t,this.reqSchema=n,this.resSchema=i,this.ws=e,this.sendClosed=!1,this.serverClosed=null,this.listenForMessages()}send(e){if(this.serverClosed!=null)return new ge;if(this.sendClosed)throw new Ge;return this.ws.send(this.encoder.encode({type:"data",payload:e})),null}async receive(){if(this.serverClosed!=null)return[null,this.serverClosed];const e=await this.receiveMsg();if(e.type==="close"){if(e.error==null)throw new Error("Message error must be defined");return this.serverClosed=Ur(e.error),[null,this.serverClosed]}return[this.resSchema.parse(e.payload),null]}received(){return this.receiveDataQueue.length!==0}closeSend(){if(this.sendClosed||this.serverClosed!=null)return;const e={type:"close"};try{this.ws.send(this.encoder.encode(e))}finally{this.sendClosed=!0}}async receiveMsg(){return this.receiveDataQueue.shift()??await new Promise((t,n)=>this.receiveCallbacksQueue.push({resolve:t,reject:n}))}addMessage(e){const t=this.receiveCallbacksQueue.shift();t!=null?t.resolve(e):this.receiveDataQueue.push(e)}listenForMessages(){this.ws.onmessage=e=>this.addMessage(this.encoder.decode(e.data,Va)),this.ws.onclose=e=>this.addMessage({type:"close",error:{type:to(e)?ge.TYPE:Ge.TYPE,data:""}})}}const Ha="freighterctx",Xa=1e3,Qa=1001,eo=[Xa,Qa],to=r=>eo.includes(r.code),hs=class ys extends ls{constructor(e,t,n=!1){super(),k(this,"baseUrl"),k(this,"encoder"),this.baseUrl=e.replace({protocol:n?"wss":"ws"}),this.encoder=t}async stream(e,t,n){const i=Ga();let a;const[,c]=await this.executeMiddleware({target:e,protocol:"websocket",params:{},role:"client"},async l=>{const u=i(this.buildURL(e,l)),f={...l,params:{}};u.binaryType=ys.MESSAGE_TYPE;const g=await this.wrapSocket(u,t,n);return g instanceof Error?[f,g]:(a=g,[f,null])});if(c!=null)throw c;return a}buildURL(e,t){const n=Ma({[us]:this.encoder.contentType,...t.params},Ha);return this.baseUrl.child(e).toString()+n}async wrapSocket(e,t,n){return await new Promise(i=>{e.onopen=()=>{i(new Ja(e,this.encoder,t,n))},e.onerror=a=>{const c=a;i(new Error(c.message))}})}};k(hs,"MESSAGE_TYPE","arraybuffer");let ro=hs;const no=r=>{const e=r.replace(/_[a-z]/g,t=>t[1].toUpperCase());return e.length>1&&e[0]===e[0].toUpperCase()&&e[1]===e[1].toUpperCase()?e:e[0].toLowerCase()+e.slice(1)},ds=r=>{const e=(t,n=$r)=>{if(typeof t=="string")return r(t);if(Array.isArray(t))return t.map(c=>e(c,n));if(!fr(t))return t;n=ao(n);const i={},a=t;return Object.keys(a).forEach(c=>{let l=a[c];const u=r(c);n.recursive&&(fr(l)?wn(l,n.keepTypesOnRecursion)||(l=e(l,n)):n.recursiveInArray&&mn(l)&&(l=[...l].map(f=>{let g=f;return fr(f)?wn(g,n.keepTypesOnRecursion)||(g=e(f,n)):mn(f)&&(g=e({key:f},n).key),g}))),i[u]=l}),i};return e},fs=ds(no),so=r=>r.replace(/([a-z0-9])([A-Z])/g,(e,t,n)=>`${t}_${n.toLowerCase()}`),io=ds(so),$r={recursive:!0,recursiveInArray:!0,keepTypesOnRecursion:[Number,String,Uint8Array]},ao=(r=$r)=>(r.recursive==null?r=$r:r.recursiveInArray==null&&(r.recursiveInArray=!1),r),mn=r=>r!=null&&Array.isArray(r),fr=r=>r!=null&&typeof r=="object"&&!Array.isArray(r),wn=(r,e)=>(e||[]).some(t=>r instanceof t),Br=r=>r!=null&&typeof r=="object"&&!Array.isArray(r);var oo=Object.defineProperty,co=(r,e,t)=>e in r?oo(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,ht=(r,e,t)=>co(r,typeof e!="symbol"?e+"":e,t);let ps=class{constructor(){ht(this,"contentType","application/json"),ht(this,"decoder"),ht(this,"encoder"),this.decoder=new TextDecoder,this.encoder=new TextEncoder}encode(e){return this.encoder.encode(this.encodeString(e)).buffer}decode(e,t){return this.decodeString(this.decoder.decode(e),t)}decodeString(e,t){const n=JSON.parse(e),i=fs(n);return t!=null?t.parse(i):i}encodeString(e){const t=io(e);return JSON.stringify(t,(n,i)=>ArrayBuffer.isView(i)?Array.from(i):Br(i)&&"encode_value"in i?typeof i.value=="bigint"?i.value.toString():i.value:typeof i=="bigint"?i.toString():i)}static registerCustomType(){}},gs=class{constructor(){ht(this,"contentType","text/csv")}encode(e){const t=this.encodeString(e);return new TextEncoder().encode(t).buffer}decode(e,t){const n=new TextDecoder().decode(e);return this.decodeString(n,t)}encodeString(e){if(!Array.isArray(e)||e.length===0||!Br(e[0]))throw new Error("Payload must be an array of objects");const t=Object.keys(e[0]),n=[t.join(",")];return e.forEach(i=>{const a=t.map(c=>JSON.stringify(i[c]??""));n.push(a.join(","))}),n.join(`
3
+ `).map(l=>l.trim());if(n.length===0)return t!=null?t.parse({}):{};const a=n.split(",").map(l=>l.trim()),c={};return a.forEach(l=>{c[l]=[]}),i.forEach(l=>{const u=l.split(",").map(h=>h.trim());a.forEach((h,p)=>{const g=this.parseValue(u[p]);g!=null&&c[h].push(g)})}),t!=null?t.parse(c):c}parseValue(e){if(e==null||e.length===0)return null;const t=Number(e);return isNaN(t)?e.startsWith('"')&&e.endsWith('"')?e.slice(1,-1):e:t}static registerCustomType(){}},aa=class{constructor(){ut(this,"contentType","text/plain")}encode(e){return new TextEncoder().encode(e).buffer}decode(e,t){const n=new TextDecoder().decode(e);return t!=null?t.parse(n):n}};new sa;new ia;new aa;const Xt=s.z.tuple([s.z.number(),s.z.number()]);s.z.tuple([s.z.bigint(),s.z.bigint()]);const es=s.z.object({width:s.z.number(),height:s.z.number()}),oa=s.z.object({signedWidth:s.z.number(),signedHeight:s.z.number()}),ca=["width","height"];s.z.enum(ca);const la=["start","center","end"],ua=["signedWidth","signedHeight"];s.z.enum(ua);const Vt=s.z.object({x:s.z.number(),y:s.z.number()}),ha=s.z.object({clientX:s.z.number(),clientY:s.z.number()}),ya=["x","y"],ts=s.z.enum(ya),rs=["top","right","bottom","left"];s.z.enum(rs);const da=["left","right"],ns=s.z.enum(da),fa=["top","bottom"],ss=s.z.enum(fa),is=["center"],dn=s.z.enum(is),pa=[...rs,...is],as=s.z.enum(pa);s.z.enum(la);const ga=["first","last"];s.z.enum(ga);const ma=s.z.object({lower:s.z.number(),upper:s.z.number()}),wa=s.z.object({lower:s.z.bigint(),upper:s.z.bigint()});s.z.union([ma,Xt]);s.z.union([wa,Xt]);s.z.union([ts,as]);s.z.union([ts,as,s.z.instanceof(String)]);const dr=(r,e)=>{const t={};if(typeof r=="number"||typeof r=="bigint")e!=null?(t.lower=r,t.upper=e):(t.lower=typeof r=="bigint"?0n:0,t.upper=r);else if(Array.isArray(r)){if(r.length!==2)throw new Error("bounds: expected array of length 2");[t.lower,t.upper]=r}else return fn(r);return fn(t)},fn=r=>r.lower>r.upper?{lower:r.upper,upper:r.lower}:r;s.z.object({x:ns.or(dn),y:ss.or(dn)});const ba=s.z.object({x:ns,y:ss}),va=Object.freeze({x:"left",y:"top"}),Ta=(r,e)=>r.x===e.x&&r.y===e.y,pn=s.z.union([s.z.number(),Vt,Xt,es,oa,ha]),Oa=(r,e)=>{if(typeof r=="string"){if(e===void 0)throw new Error("The y coordinate must be given.");return r==="x"?{x:e,y:0}:{x:0,y:e}}return typeof r=="number"?{x:r,y:e??r}:Array.isArray(r)?{x:r[0],y:r[1]}:"signedWidth"in r?{x:r.signedWidth,y:r.signedHeight}:"clientX"in r?{x:r.clientX,y:r.clientY}:"width"in r?{x:r.width,y:r.height}:{x:r.x,y:r.y}},gn=Object.freeze({x:0,y:0}),Rt=s.z.union([s.z.number(),s.z.string()]);s.z.object({top:Rt,left:Rt,width:Rt,height:Rt});s.z.object({left:s.z.number(),top:s.z.number(),right:s.z.number(),bottom:s.z.number()});s.z.object({one:Vt,two:Vt,root:ba});const Wr=(r,e,t=0,n=0,i)=>{const a={one:{...gn},two:{...gn},root:i??va};if(typeof r=="number"){if(typeof e!="number")throw new Error("Box constructor called with invalid arguments");return a.one={x:r,y:e},a.two={x:a.one.x+t,y:a.one.y+n},a}return"one"in r&&"two"in r&&"root"in r?{...r,root:i??r.root}:("getBoundingClientRect"in r&&(r=r.getBoundingClientRect()),"left"in r?(a.one={x:r.left,y:r.top},a.two={x:r.right,y:r.bottom},a):(a.one=r,e==null?a.two={x:a.one.x+t,y:a.one.y+n}:typeof e=="number"?a.two={x:a.one.x+e,y:a.one.y+t}:"width"in e?a.two={x:a.one.x+e.width,y:a.one.y+e.height}:"signedWidth"in e?a.two={x:a.one.x+e.signedWidth,y:a.one.y+e.signedHeight}:a.two=e,a))},fr=r=>{const e=Wr(r);return{lower:e.one.x,upper:e.two.x}},pr=r=>{const e=Wr(r);return{lower:e.one.y,upper:e.two.y}},za=r=>typeof r!="object"||r==null?!1:"one"in r&&"two"in r&&"root"in r;var Ea=Object.defineProperty,Sa=(r,e,t)=>e in r?Ea(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,ue=(r,e,t)=>Sa(r,typeof e!="symbol"?e+"":e,t);const Na=(r,e,t)=>e!==void 0&&r<e?e:t!==void 0&&r>t?t:r;s.z.object({offset:pn,scale:pn});const Ia=r=>(e,t,n,i)=>t==="dimension"?[e,n]:[e,i?n-r:n+r],ka=r=>(e,t,n,i)=>[e,i?n/r:n*r],Aa=r=>(e,t,n)=>{if(e===null)return[r,n];const{lower:i,upper:a}=e,{lower:c,upper:l}=r,u=a-i,h=l-c;if(t==="dimension")return[r,n*(h/u)];const p=(n-i)*(h/u)+c;return[r,p]},$a=r=>(e,t,n)=>[r,n],Ra=()=>(r,e,t)=>{if(r===null)throw new Error("cannot invert without bounds");if(e==="dimension")return[r,t];const{lower:n,upper:i}=r;return[r,i-(t-n)]},Ca=r=>(e,t,n)=>{const{lower:i,upper:a}=r;return n=Na(n,i,a),[e,n]},Cr=class rt{constructor(){ue(this,"ops",[]),ue(this,"currBounds",null),ue(this,"currType",null),ue(this,"reversed",!1),this.ops=[]}static translate(e){return new rt().translate(e)}static magnify(e){return new rt().magnify(e)}static scale(e,t){return new rt().scale(e,t)}translate(e){const t=this.new(),n=Ia(e);return n.type="translate",t.ops.push(n),t}magnify(e){const t=this.new(),n=ka(e);return n.type="magnify",t.ops.push(n),t}scale(e,t){const n=dr(e,t),i=this.new(),a=Aa(n);return a.type="scale",i.ops.push(a),i}clamp(e,t){const n=dr(e,t),i=this.new(),a=Ca(n);return a.type="clamp",i.ops.push(a),i}reBound(e,t){const n=dr(e,t),i=this.new(),a=$a(n);return a.type="re-bound",i.ops.push(a),i}invert(){const e=Ra();e.type="invert";const t=this.new();return t.ops.push(e),t}pos(e){return this.exec("position",e)}dim(e){return this.exec("dimension",e)}new(){const e=new rt;return e.ops=this.ops.slice(),e.reversed=this.reversed,e}exec(e,t){return this.currBounds=null,this.ops.reduce(([n,i],a)=>a(n,e,i,this.reversed),[null,t])[1]}reverse(){const e=this.new();e.ops.reverse();const t=[];return e.ops.forEach((n,i)=>{if(n.type==="scale"||t.some(([c,l])=>i>=c&&i<=l))return;const a=e.ops.findIndex((c,l)=>c.type==="scale"&&l>i);a!==-1&&t.push([i,a])}),t.forEach(([n,i])=>{const a=e.ops.slice(n,i);a.unshift(e.ops[i]),e.ops.splice(n,i-n+1,...a)}),e.reversed=!e.reversed,e}};ue(Cr,"IDENTITY",new Cr);let mn=Cr;const wn=class oe{constructor(e=new mn,t=new mn,n=null){ue(this,"x"),ue(this,"y"),ue(this,"currRoot"),this.x=e,this.y=t,this.currRoot=n}static translate(e,t){return new oe().translate(e,t)}static translateX(e){return new oe().translateX(e)}static translateY(e){return new oe().translateY(e)}static clamp(e){return new oe().clamp(e)}static magnify(e){return new oe().magnify(e)}static scale(e){return new oe().scale(e)}static reBound(e){return new oe().reBound(e)}translate(e,t){const n=Oa(e,t),i=this.copy();return i.x=this.x.translate(n.x),i.y=this.y.translate(n.y),i}translateX(e){const t=this.copy();return t.x=this.x.translate(e),t}translateY(e){const t=this.copy();return t.y=this.y.translate(e),t}magnify(e){const t=this.copy();return t.x=this.x.magnify(e.x),t.y=this.y.magnify(e.y),t}scale(e){const t=this.copy();if(za(e)){const n=this.currRoot;return t.currRoot=e.root,n!=null&&!Ta(n,e.root)&&(n.x!==e.root.x&&(t.x=t.x.invert()),n.y!==e.root.y&&(t.y=t.y.invert())),t.x=t.x.scale(fr(e)),t.y=t.y.scale(pr(e)),t}return t.x=t.x.scale(e.width),t.y=t.y.scale(e.height),t}reBound(e){const t=this.copy();return t.x=this.x.reBound(fr(e)),t.y=this.y.reBound(pr(e)),t}clamp(e){const t=this.copy();return t.x=this.x.clamp(fr(e)),t.y=this.y.clamp(pr(e)),t}copy(){const e=new oe;return e.currRoot=this.currRoot,e.x=this.x,e.y=this.y,e}reverse(){const e=this.copy();return e.x=this.x.reverse(),e.y=this.y.reverse(),e}pos(e){return{x:this.x.pos(e.x),y:this.y.pos(e.y)}}box(e){return Wr(this.pos(e.one),this.pos(e.two),0,0,this.currRoot??e.root)}};ue(wn,"IDENTITY",new wn);const xa=s.z.object({signedWidth:s.z.number(),signedHeight:s.z.number()});s.z.union([es,xa,Vt,Xt]);var Pa=Object.defineProperty,Da=(r,e,t)=>e in r?Pa(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,m=(r,e,t)=>Da(r,typeof e!="symbol"?e+"":e,t);const os=(r,e)=>{const t=new q(e);if(![Y.DAY,Y.HOUR,Y.MINUTE,Y.SECOND,Y.MILLISECOND,Y.MICROSECOND,Y.NANOSECOND].some(i=>i.equals(t)))throw new Error("Invalid argument for remainder. Must be an even TimeSpan or Timestamp");const n=r.valueOf()%t.valueOf();return r instanceof q?new q(n):new Y(n)},A=class b{constructor(e,t="UTC"){if(m(this,"value"),m(this,"encodeValue",!0),e==null)this.value=b.now().valueOf();else if(e instanceof Date)this.value=BigInt(e.getTime())*b.MILLISECOND.valueOf();else if(typeof e=="string")this.value=b.parseDateTimeString(e,t).valueOf();else if(Array.isArray(e))this.value=b.parseDate(e);else{let n=BigInt(0);e instanceof Number&&(e=e.valueOf()),t==="local"&&(n=b.utcOffset.valueOf()),typeof e=="number"&&(isFinite(e)?e=Math.trunc(e):(isNaN(e)&&(e=0),e===1/0?e=b.MAX:e=b.MIN)),this.value=BigInt(e.valueOf())+n}}static parseDate([e=1970,t=1,n=1]){const i=new Date(e,t-1,n,0,0,0,0);return new b(BigInt(i.getTime())*b.MILLISECOND.valueOf()).truncate(b.DAY).valueOf()}encode(){return this.value.toString()}valueOf(){return this.value}static parseTimeString(e,t="UTC"){const[n,i,a]=e.split(":");let c="00",l="00";a!=null&&([c,l]=a.split("."));let u=b.hours(parseInt(n??"00",10)).add(b.minutes(parseInt(i??"00",10))).add(b.seconds(parseInt(c??"00",10))).add(b.milliseconds(parseInt(l??"00",10)));return t==="local"&&(u=u.add(b.utcOffset)),u.valueOf()}static parseDateTimeString(e,t="UTC"){if(!e.includes("/")&&!e.includes("-"))return b.parseTimeString(e,t);const n=new Date(e);return e.includes(":")||n.setUTCHours(0,0,0,0),new b(BigInt(n.getTime())*b.MILLISECOND.valueOf(),t).valueOf()}fString(e="ISO",t="UTC"){switch(e){case"ISODate":return this.toISOString(t).slice(0,10);case"ISOTime":return this.toISOString(t).slice(11,23);case"time":return this.timeString(!1,t);case"preciseTime":return this.timeString(!0,t);case"date":return this.dateString();case"preciseDate":return`${this.dateString()} ${this.timeString(!0,t)}`;case"dateTime":return`${this.dateString()} ${this.timeString(!1,t)}`;default:return this.toISOString(t)}}toISOString(e="UTC"){return e==="UTC"?this.date().toISOString():this.sub(b.utcOffset).date().toISOString()}timeString(e=!1,t="UTC"){const n=this.toISOString(t);return e?n.slice(11,23):n.slice(11,19)}dateString(){const e=this.date(),t=e.toLocaleString("default",{month:"short"}),n=e.toLocaleString("default",{day:"numeric"});return`${t} ${n}`}static get utcOffset(){return new Y(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 ja(this,e).makeValid()}spanRange(e){return this.range(this.add(e)).makeValid()}get isZero(){return this.valueOf()===BigInt(0)}after(e){return this.valueOf()>new 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(this.valueOf()+BigInt(e.valueOf()))}sub(e){return new b(this.valueOf()-BigInt(e.valueOf()))}milliseconds(){return Number(this.valueOf())/Number(b.MILLISECOND.valueOf())}toString(){return this.date().toISOString()}remainder(e){return os(this,e)}get isToday(){return this.truncate(Y.DAY).equals(b.now().truncate(Y.DAY))}truncate(e){return this.sub(this.remainder(e))}static now(){return new b(new Date)}static max(...e){let t=b.MIN;for(const n of e){const i=new b(n);i.after(t)&&(t=i)}return t}static min(...e){let t=b.MAX;for(const n of e){const i=new b(n);i.before(t)&&(t=i)}return t}static nanoseconds(e){return new b(e)}static microseconds(e){return b.nanoseconds(e*1e3)}static milliseconds(e){return b.microseconds(e*1e3)}static seconds(e){return b.milliseconds(e*1e3)}static minutes(e){return b.seconds(e*60)}static hours(e){return b.minutes(e*60)}static days(e){return b.hours(e*24)}};m(A,"NANOSECOND",A.nanoseconds(1)),m(A,"MICROSECOND",A.microseconds(1)),m(A,"MILLISECOND",A.milliseconds(1)),m(A,"SECOND",A.seconds(1)),m(A,"MINUTE",A.minutes(1)),m(A,"HOUR",A.hours(1)),m(A,"DAY",A.days(1)),m(A,"MAX",new A((1n<<63n)-1n)),m(A,"MIN",new A(0)),m(A,"ZERO",new A(0)),m(A,"z",s.z.union([s.z.object({value:s.z.bigint()}).transform(r=>new A(r.value)),s.z.string().transform(r=>new A(BigInt(r))),s.z.instanceof(Number).transform(r=>new A(r)),s.z.number().transform(r=>new A(r)),s.z.instanceof(A)]));let q=A;const $=class N{constructor(e){m(this,"value"),m(this,"encodeValue",!0),typeof e=="number"&&(e=Math.trunc(e.valueOf())),this.value=BigInt(e.valueOf())}encode(){return this.value.toString()}valueOf(){return this.value}lessThan(e){return this.valueOf()<new N(e).valueOf()}greaterThan(e){return this.valueOf()>new N(e).valueOf()}lessThanOrEqual(e){return this.valueOf()<=new N(e).valueOf()}greaterThanOrEqual(e){return this.valueOf()>=new N(e).valueOf()}remainder(e){return os(this,e)}truncate(e){return new N(BigInt(Math.trunc(Number(this.valueOf()/e.valueOf())))*e.valueOf())}toString(){const e=this.truncate(N.DAY),t=this.truncate(N.HOUR),n=this.truncate(N.MINUTE),i=this.truncate(N.SECOND),a=this.truncate(N.MILLISECOND),c=this.truncate(N.MICROSECOND),l=this.truncate(N.NANOSECOND),u=e,h=t.sub(e),p=n.sub(t),g=i.sub(n),D=a.sub(i),P=c.sub(a),X=l.sub(c);let j="";return u.isZero||(j+=`${u.days}d `),h.isZero||(j+=`${h.hours}h `),p.isZero||(j+=`${p.minutes}m `),g.isZero||(j+=`${g.seconds}s `),D.isZero||(j+=`${D.milliseconds}ms `),P.isZero||(j+=`${P.microseconds}µs `),X.isZero||(j+=`${X.nanoseconds}ns`),j.trim()}get days(){return Number(this.valueOf())/Number(N.DAY.valueOf())}get hours(){return Number(this.valueOf())/Number(N.HOUR.valueOf())}get minutes(){return Number(this.valueOf())/Number(N.MINUTE.valueOf())}get seconds(){return Number(this.valueOf())/Number(N.SECOND.valueOf())}get milliseconds(){return Number(this.valueOf())/Number(N.MILLISECOND.valueOf())}get microseconds(){return Number(this.valueOf())/Number(N.MICROSECOND.valueOf())}get nanoseconds(){return Number(this.valueOf())}get isZero(){return this.valueOf()===BigInt(0)}equals(e){return this.valueOf()===new N(e).valueOf()}add(e){return new N(this.valueOf()+new N(e).valueOf())}sub(e){return new N(this.valueOf()-new N(e).valueOf())}static nanoseconds(e=1){return new N(e)}static microseconds(e=1){return N.nanoseconds(e*1e3)}static milliseconds(e=1){return N.microseconds(e*1e3)}static seconds(e=1){return N.milliseconds(e*1e3)}static minutes(e){return N.seconds(e.valueOf()*60)}static hours(e){return N.minutes(e*60)}static days(e){return N.hours(e*24)}};m($,"NANOSECOND",$.nanoseconds(1)),m($,"MICROSECOND",$.microseconds(1)),m($,"MILLISECOND",$.milliseconds(1)),m($,"SECOND",$.seconds(1)),m($,"MINUTE",$.minutes(1)),m($,"HOUR",$.hours(1)),m($,"DAY",$.days(1)),m($,"MAX",new $((1n<<63n)-1n)),m($,"MIN",new $(0)),m($,"ZERO",new $(0)),m($,"z",s.z.union([s.z.object({value:s.z.bigint()}).transform(r=>new $(r.value)),s.z.string().transform(r=>new $(BigInt(r))),s.z.instanceof(Number).transform(r=>new $(r)),s.z.number().transform(r=>new $(r)),s.z.instanceof($)]));let Y=$;const Ct=class Dt extends Number{constructor(e){e instanceof Number?super(e.valueOf()):super(e)}toString(){return`${this.valueOf()} Hz`}equals(e){return this.valueOf()===new Dt(e).valueOf()}get period(){return Y.seconds(1/this.valueOf())}sampleCount(e){return new Y(e).seconds*this.valueOf()}byteCount(e,t){return this.sampleCount(e)*new K(t).valueOf()}span(e){return Y.seconds(e/this.valueOf())}byteSpan(e,t){return this.span(e.valueOf()/t.valueOf())}static hz(e){return new Dt(e)}static khz(e){return Dt.hz(e*1e3)}};m(Ct,"z",s.z.union([s.z.number().transform(r=>new Ct(r)),s.z.instanceof(Number).transform(r=>new Ct(r)),s.z.instanceof(Ct)]));const B=class extends Number{constructor(e){e instanceof Number?super(e.valueOf()):super(e)}length(e){return e.valueOf()/this.valueOf()}size(e){return new Ma(e*this.valueOf())}};m(B,"UNKNOWN",new B(0)),m(B,"BIT128",new B(16)),m(B,"BIT64",new B(8)),m(B,"BIT32",new B(4)),m(B,"BIT16",new B(2)),m(B,"BIT8",new B(1)),m(B,"z",s.z.union([s.z.number().transform(r=>new B(r)),s.z.instanceof(Number).transform(r=>new B(r)),s.z.instanceof(B)]));let K=B;const re=class jt{constructor(e,t){m(this,"start"),m(this,"end"),typeof e=="object"&&"start"in e?(this.start=new q(e.start),this.end=new q(e.end)):(this.start=new q(e),this.end=new q(t))}get span(){return new Y(this.end.valueOf()-this.start.valueOf())}get isValid(){return this.start.valueOf()<=this.end.valueOf()}makeValid(){return this.isValid?this:this.swap()}get isZero(){return this.span.isZero}get numeric(){return{start:Number(this.start.valueOf()),end:Number(this.end.valueOf())}}swap(){return new jt(this.end,this.start)}equals(e){return this.start.equals(e.start)&&this.end.equals(e.end)}toString(){return`${this.start.toString()} - ${this.end.toString()}`}toPrettyString(){return`${this.start.fString("preciseDate")} - ${this.span.toString()}`}overlapsWith(e,t=Y.ZERO){e=e.makeValid();const n=this.makeValid();if(this.equals(e))return!0;if(e.end.equals(n.start)||n.end.equals(e.start))return!1;const i=q.max(n.start,e.start),a=q.min(n.end,e.end);return a.before(i)?!1:new Y(a.sub(i)).greaterThanOrEqual(t)}roughlyEquals(e,t){let n=this.start.sub(e.start).valueOf(),i=this.end.sub(e.end).valueOf();return n<0&&(n=-n),i<0&&(i=-i),n<=t.valueOf()&&i<=t.valueOf()}contains(e){return e instanceof jt?this.contains(e.start)&&this.contains(e.end):this.start.beforeEq(e)&&this.end.after(e)}boundBy(e){const t=new jt(this.start,this.end);return e.start.after(this.start)&&(t.start=e.start),e.start.after(this.end)&&(t.end=e.start),e.end.before(this.end)&&(t.end=e.end),e.end.before(this.start)&&(t.start=e.end),t}};m(re,"MAX",new re(q.MIN,q.MAX)),m(re,"MIN",new re(q.MAX,q.MIN)),m(re,"ZERO",new re(q.ZERO,q.ZERO)),m(re,"z",s.z.union([s.z.object({start:q.z,end:q.z}).transform(r=>new re(r.start,r.end)),s.z.instanceof(re)]));let ja=re;const d=class ne extends String{constructor(e){if(e instanceof ne||typeof e=="string"||typeof e.valueOf()=="string"){super(e.valueOf());return}else{const t=ne.ARRAY_CONSTRUCTOR_DATA_TYPES.get(e.constructor.name);if(t!=null){super(t.valueOf());return}}throw super(ne.UNKNOWN.valueOf()),new Error(`unable to find data type for ${e.toString()}`)}get Array(){const e=ne.ARRAY_CONSTRUCTORS.get(this.toString());if(e==null)throw new Error(`unable to find array constructor for ${this.valueOf()}`);return e}equals(e){return this.valueOf()===e.valueOf()}matches(...e){return e.some(t=>this.equals(t))}toString(){return this.valueOf()}get isVariable(){return this.equals(ne.JSON)||this.equals(ne.STRING)}get isNumeric(){return!this.isVariable&&!this.equals(ne.UUID)}get isInteger(){return this.toString().startsWith("int")}get isFloat(){return this.toString().startsWith("float")}get density(){const e=ne.DENSITIES.get(this.toString());if(e==null)throw new Error(`unable to find density for ${this.valueOf()}`);return e}canSafelyCastTo(e){return this.equals(e)?!0:this.isVariable&&!e.isVariable||!this.isVariable&&e.isVariable?!1:this.isFloat&&e.isInteger||this.isInteger&&e.isFloat?this.density.valueOf()<e.density.valueOf():this.isFloat&&e.isFloat||this.isInteger&&e.isInteger?this.density.valueOf()<=e.density.valueOf():!1}canCastTo(e){return this.isNumeric&&e.isNumeric?!0:this.equals(e)}checkArray(e){return e.constructor===this.Array}toJSON(){return this.toString()}get usesBigInt(){return ne.BIG_INT_TYPES.some(e=>e.equals(this))}};m(d,"UNKNOWN",new d("unknown")),m(d,"FLOAT64",new d("float64")),m(d,"FLOAT32",new d("float32")),m(d,"INT64",new d("int64")),m(d,"INT32",new d("int32")),m(d,"INT16",new d("int16")),m(d,"INT8",new d("int8")),m(d,"UINT64",new d("uint64")),m(d,"UINT32",new d("uint32")),m(d,"UINT16",new d("uint16")),m(d,"UINT8",new d("uint8")),m(d,"BOOLEAN",d.UINT8),m(d,"TIMESTAMP",new d("timestamp")),m(d,"UUID",new d("uuid")),m(d,"STRING",new d("string")),m(d,"JSON",new d("json")),m(d,"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]])),m(d,"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]])),m(d,"DENSITIES",new Map([[d.UINT8.toString(),K.BIT8],[d.UINT16.toString(),K.BIT16],[d.UINT32.toString(),K.BIT32],[d.UINT64.toString(),K.BIT64],[d.FLOAT32.toString(),K.BIT32],[d.FLOAT64.toString(),K.BIT64],[d.INT8.toString(),K.BIT8],[d.INT16.toString(),K.BIT16],[d.INT32.toString(),K.BIT32],[d.INT64.toString(),K.BIT64],[d.TIMESTAMP.toString(),K.BIT64],[d.STRING.toString(),K.UNKNOWN],[d.JSON.toString(),K.UNKNOWN],[d.UUID.toString(),K.BIT128]])),m(d,"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]),m(d,"BIG_INT_TYPES",[d.INT64,d.UINT64,d.TIMESTAMP]),m(d,"z",s.z.union([s.z.string().transform(r=>new d(r)),s.z.instanceof(d)]));const _=class M extends Number{constructor(e){super(e.valueOf())}largerThan(e){return this.valueOf()>e.valueOf()}smallerThan(e){return this.valueOf()<e.valueOf()}add(e){return M.bytes(this.valueOf()+e.valueOf())}sub(e){return M.bytes(this.valueOf()-e.valueOf())}truncate(e){return new M(Math.trunc(this.valueOf()/e.valueOf())*e.valueOf())}remainder(e){return M.bytes(this.valueOf()%e.valueOf())}get gigabytes(){return this.valueOf()/M.GIGABYTE.valueOf()}get megabytes(){return this.valueOf()/M.MEGABYTE.valueOf()}get kilobytes(){return this.valueOf()/M.KILOBYTE.valueOf()}get terabytes(){return this.valueOf()/M.TERABYTE.valueOf()}toString(){const e=this.truncate(M.TERABYTE),t=this.truncate(M.GIGABYTE),n=this.truncate(M.MEGABYTE),i=this.truncate(M.KILOBYTE),a=this.truncate(M.BYTE),c=e,l=t.sub(e),u=n.sub(t),h=i.sub(n),p=a.sub(i);let g="";return c.isZero||(g+=`${c.terabytes}TB `),l.isZero||(g+=`${l.gigabytes}GB `),u.isZero||(g+=`${u.megabytes}MB `),h.isZero||(g+=`${h.kilobytes}KB `),(!p.isZero||g==="")&&(g+=`${p.valueOf()}B`),g.trim()}static bytes(e=1){return new M(e)}static kilobytes(e=1){return M.bytes(e.valueOf()*1e3)}static megabytes(e=1){return M.kilobytes(e.valueOf()*1e3)}static gigabytes(e=1){return M.megabytes(e.valueOf()*1e3)}static terabytes(e){return M.gigabytes(e.valueOf()*1e3)}get isZero(){return this.valueOf()===0}};m(_,"BYTE",new _(1)),m(_,"KILOBYTE",_.kilobytes(1)),m(_,"MEGABYTE",_.megabytes(1)),m(_,"GIGABYTE",_.gigabytes(1)),m(_,"TERABYTE",_.terabytes(1)),m(_,"ZERO",new _(0)),m(_,"z",s.z.union([s.z.number().transform(r=>new _(r)),s.z.instanceof(_)]));let Ma=_;s.z.union([s.z.instanceof(Uint8Array),s.z.instanceof(Uint16Array),s.z.instanceof(Uint32Array),s.z.instanceof(BigUint64Array),s.z.instanceof(Float32Array),s.z.instanceof(Float64Array),s.z.instanceof(Int8Array),s.z.instanceof(Int16Array),s.z.instanceof(Int32Array),s.z.instanceof(BigInt64Array)]);s.z.object({key:s.z.string(),value:s.z.string()});s.z.record(s.z.union([s.z.number(),s.z.string(),s.z.symbol()]),s.z.unknown());const cs=()=>typeof process<"u"&&process.versions!=null&&process.versions.node!=null?"node":typeof window>"u"||window.document===void 0?"webworker":"browser",Za=cs(),ls=["MacOS","Windows","Linux","Docker"],Ua=s.z.enum(ls);let gr;const Ba=()=>{if(typeof window>"u")return;const r=window.navigator.userAgent.toLowerCase();if(r.includes("mac"))return"MacOS";if(r.includes("win"))return"Windows";if(r.includes("linux"))return"Linux"},La=(r={})=>{const{force:e,default:t}=r;return e??gr??(gr=Ba(),gr??t)},us=Object.freeze(Object.defineProperty({__proto__:null,OPERATING_SYSTEMS:ls,RUNTIME:Za,detect:cs,getOS:La,osZ:Ua},Symbol.toStringTag,{value:"Module"}));var qa=Object.defineProperty,Ya=(r,e,t)=>e in r?qa(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,nt=(r,e,t)=>Ya(r,typeof e!="symbol"?e+"":e,t);const Wa=(...r)=>r.map(hs).join(""),hs=r=>(r.endsWith("/")||(r+="/"),r.startsWith("/")&&(r=r.slice(1)),r),_a=r=>r.endsWith("/")?r.slice(0,-1):r,Va=(r,e="")=>r===null?"":"?"+Object.entries(r).filter(([,t])=>t==null?!1:Array.isArray(t)?t.length>0:!0).map(([t,n])=>`${e}${t}=${n}`).join("&"),xr=class Pr{constructor({host:e,port:t,protocol:n="",pathPrefix:i=""}){nt(this,"protocol"),nt(this,"host"),nt(this,"port"),nt(this,"path"),this.protocol=n,this.host=e,this.port=t,this.path=hs(i)}replace(e){return new Pr({host:e.host??this.host,port:e.port??this.port,protocol:e.protocol??this.protocol,pathPrefix:e.pathPrefix??this.path})}child(e){return new Pr({...this,pathPrefix:Wa(this.path,e)})}toString(){return _a(`${this.protocol}://${this.host}:${this.port}/${this.path}`)}};nt(xr,"UNKNOWN",new xr({host:"unknown",port:0}));let Fa=xr;var Ka=Object.defineProperty,Ga=(r,e,t)=>e in r?Ka(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,Mt=(r,e,t)=>Ga(r,typeof e!="symbol"?e+"":e,t);const xe=class extends Number{};Mt(xe,"Absolute",255),Mt(xe,"Default",1),Mt(xe,"z",s.z.union([s.z.instanceof(xe),s.z.number().int().min(0).max(255).transform(r=>new xe(r)),s.z.instanceof(Number).transform(r=>new xe(r))]));s.z.object({name:s.z.string(),key:s.z.string()});const ys=class st extends Error{constructor(){super(st.MESSAGE)}matches(e){return typeof e=="string"?e.includes(st.MESSAGE):e instanceof st||e.message.includes(st.MESSAGE)}};Mt(ys,"MESSAGE","canceled");let Ja=ys;new Ja;s.z.string().regex(/^\d+\.\d+\.\d+$/);const J=r=>e=>e!=null&&typeof e=="object"&&"type"in e&&typeof e.type=="string"?e.type.includes(r):e instanceof Error?e.message.includes(r):typeof e!="string"?!1:e.includes(r);let te=class extends Error{constructor(e){super(e),k(this,"discriminator","FreighterError"),k(this,"type","")}};const Ha=r=>{if(r==null||typeof r!="object")return!1;const e=r;if(e.discriminator!=="FreighterError")return!1;if(!("type"in e))throw new Error(`Freighter error is missing its type property: ${JSON.stringify(e)}`);return!0},bn="unknown",vn="nil",Xa="freighter",Ot=s.z.object({type:s.z.string(),data:s.z.string()});class Qa{constructor(){k(this,"providers",[])}register(e){this.providers.push(e)}encode(e){if(e==null)return{type:vn,data:""};if(Ha(e))for(const t of this.providers){const n=t.encode(e);if(n!=null)return n}return{type:bn,data:JSON.stringify(e)}}decode(e){if(e==null||e.type===vn)return null;if(e.type===bn)return new Tn(e.data);for(const t of this.providers){const n=t.decode(e);if(n!=null)return n}return new Tn(e.data)}}const ds=new Qa,fs=({encode:r,decode:e})=>ds.register({encode:r,decode:e}),_r=r=>ds.decode(r);class Tn extends te{constructor(e){super(e),k(this,"type","unknown")}}const Qt="freighter.",Zt=class ps extends te{constructor(){super("EOF"),k(this,"type",ps.TYPE)}};k(Zt,"TYPE",Qt+"eof"),k(Zt,"matches",J(Zt.TYPE));let ge=Zt;const Ut=class gs extends te{constructor(){super("StreamClosed"),k(this,"type",gs.TYPE)}};k(Ut,"TYPE",Qt+"stream_closed"),k(Ut,"matches",J(Ut.TYPE));let Ge=Ut;const Bt=class ms extends te{constructor(e={}){const{message:t="Unreachable",url:n=Fa.UNKNOWN}=e;super(t),k(this,"type",ms.TYPE),k(this,"url"),this.url=n}};k(Bt,"TYPE",Qt+"unreachable"),k(Bt,"matches",J(Bt.TYPE));let Ne=Bt;const eo=r=>{if(!r.type.startsWith(Xa))return null;if(ge.matches(r))return{type:ge.TYPE,data:"EOF"};if(Ge.matches(r))return{type:Ge.TYPE,data:"StreamClosed"};if(Ne.matches(r))return{type:Ne.TYPE,data:"Unreachable"};throw new Error(`Unknown error type: ${r.type}: ${r.message}`)},to=r=>{if(!r.type.startsWith(Qt))return null;switch(r.type){case ge.TYPE:return new ge;case Ge.TYPE:return new Ge;case Ne.TYPE:return new Ne;default:throw new Error(`Unknown error type: ${r.data}`)}};fs({encode:eo,decode:to});class ws{constructor(){k(this,"middleware",[])}use(...e){this.middleware.push(...e)}async executeMiddleware(e,t){let n=0;const i=async a=>{if(n===this.middleware.length)return await t(a);const c=this.middleware[n];return n++,await c(a,i)};return await i(e)}}const bs="Content-Type",On=r=>{if(us.RUNTIME!=="node")return fetch;const e=require("node-fetch");if(r==="http")return e;const t=require("https"),n=new t.Agent({rejectUnauthorized:!1});return async(i,a)=>await e(i,{...a,agent:n})};class ro extends ws{constructor(e,t,n=!1){return super(),k(this,"endpoint"),k(this,"encoder"),k(this,"fetch"),this.endpoint=e.replace({protocol:n?"https":"http"}),this.encoder=t,this.fetch=On(this.endpoint.protocol),new Proxy(this,{get:(i,a,c)=>a==="endpoint"?this.endpoint:Reflect.get(i,a,c)})}get headers(){return{[bs]:this.encoder.contentType}}async send(e,t,n,i){t=n==null?void 0:n.parse(t);let a=null;const c=this.endpoint.child(e),l={};l.method="POST",l.body=this.encoder.encode(t??{});const[,u]=await this.executeMiddleware({target:c.toString(),protocol:this.endpoint.protocol,params:{},role:"client"},async h=>{const p={...h,params:{}};l.headers={...this.headers,...h.params};let g;try{g=await On(h.protocol)(h.target,l)}catch(P){let X=P;return X.message==="Load failed"&&(X=new Ne({url:c})),[p,X]}const D=await g.arrayBuffer();if(g!=null&&g.ok)return i!=null&&(a=this.encoder.decode(D,i)),[p,null];try{if(g.status!==400)return[p,new Error(g.statusText)];const P=this.encoder.decode(D,Ot),X=_r(P);return[p,X]}catch(P){return[p,new Error(`[freighter] - failed to decode error: ${g.statusText}: ${P.message}`)]}});return[a,u]}}const w=async(r,e,t,n,i)=>{const[a,c]=await r.send(e,t,n,i);if(c!=null)throw c;return a},no=()=>us.RUNTIME!=="node"?r=>new WebSocket(r):r=>new(require("ws")).WebSocket(r,{rejectUnauthorized:!1}),so=s.z.object({type:s.z.union([s.z.literal("data"),s.z.literal("close")]),payload:s.z.unknown().optional(),error:s.z.optional(Ot)});class io{constructor(e,t,n,i){k(this,"encoder"),k(this,"reqSchema"),k(this,"resSchema"),k(this,"ws"),k(this,"serverClosed"),k(this,"sendClosed"),k(this,"receiveDataQueue",[]),k(this,"receiveCallbacksQueue",[]),this.encoder=t,this.reqSchema=n,this.resSchema=i,this.ws=e,this.sendClosed=!1,this.serverClosed=null,this.listenForMessages()}send(e){if(this.serverClosed!=null)return new ge;if(this.sendClosed)throw new Ge;return this.ws.send(this.encoder.encode({type:"data",payload:e})),null}async receive(){if(this.serverClosed!=null)return[null,this.serverClosed];const e=await this.receiveMsg();if(e.type==="close"){if(e.error==null)throw new Error("Message error must be defined");return this.serverClosed=_r(e.error),[null,this.serverClosed]}return[this.resSchema.parse(e.payload),null]}received(){return this.receiveDataQueue.length!==0}closeSend(){if(this.sendClosed||this.serverClosed!=null)return;const e={type:"close"};try{this.ws.send(this.encoder.encode(e))}finally{this.sendClosed=!0}}async receiveMsg(){return this.receiveDataQueue.shift()??await new Promise((t,n)=>this.receiveCallbacksQueue.push({resolve:t,reject:n}))}addMessage(e){const t=this.receiveCallbacksQueue.shift();t!=null?t.resolve(e):this.receiveDataQueue.push(e)}listenForMessages(){this.ws.onmessage=e=>this.addMessage(this.encoder.decode(e.data,so)),this.ws.onclose=e=>this.addMessage({type:"close",error:{type:uo(e)?ge.TYPE:Ge.TYPE,data:""}})}}const ao="freighterctx",oo=1e3,co=1001,lo=[oo,co],uo=r=>lo.includes(r.code),vs=class Ts extends ws{constructor(e,t,n=!1){super(),k(this,"baseUrl"),k(this,"encoder"),this.baseUrl=e.replace({protocol:n?"wss":"ws"}),this.encoder=t}async stream(e,t,n){const i=no();let a;const[,c]=await this.executeMiddleware({target:e,protocol:"websocket",params:{},role:"client"},async l=>{const u=i(this.buildURL(e,l)),h={...l,params:{}};u.binaryType=Ts.MESSAGE_TYPE;const p=await this.wrapSocket(u,t,n);return p instanceof Error?[h,p]:(a=p,[h,null])});if(c!=null)throw c;return a}buildURL(e,t){const n=Va({[bs]:this.encoder.contentType,...t.params},ao);return this.baseUrl.child(e).toString()+n}async wrapSocket(e,t,n){return await new Promise(i=>{e.onopen=()=>{i(new io(e,this.encoder,t,n))},e.onerror=a=>{const c=a;i(new Error(c.message))}})}};k(vs,"MESSAGE_TYPE","arraybuffer");let ho=vs;const yo=r=>{const e=r.replace(/_[a-z]/g,t=>t[1].toUpperCase());return e.length>1&&e[0]===e[0].toUpperCase()&&e[1]===e[1].toUpperCase()?e:e[0].toLowerCase()+e.slice(1)},Os=r=>{const e=(t,n=Dr)=>{if(typeof t=="string")return r(t);if(Array.isArray(t))return t.map(c=>e(c,n));if(!mr(t))return t;n=go(n);const i={},a=t;return Object.keys(a).forEach(c=>{let l=a[c];const u=r(c);n.recursive&&(mr(l)?En(l,n.keepTypesOnRecursion)||(l=e(l,n)):n.recursiveInArray&&zn(l)&&(l=[...l].map(h=>{let p=h;return mr(h)?En(p,n.keepTypesOnRecursion)||(p=e(h,n)):zn(h)&&(p=e({key:h},n).key),p}))),i[u]=l}),i};return e},zs=Os(yo),fo=r=>r.replace(/([a-z0-9])([A-Z])/g,(e,t,n)=>`${t}_${n.toLowerCase()}`),po=Os(fo),Dr={recursive:!0,recursiveInArray:!0,keepTypesOnRecursion:[Number,String,Uint8Array]},go=(r=Dr)=>(r.recursive==null?r=Dr:r.recursiveInArray==null&&(r.recursiveInArray=!1),r),zn=r=>r!=null&&Array.isArray(r),mr=r=>r!=null&&typeof r=="object"&&!Array.isArray(r),En=(r,e)=>(e||[]).some(t=>r instanceof t),Vr=r=>r!=null&&typeof r=="object"&&!Array.isArray(r);var mo=Object.defineProperty,wo=(r,e,t)=>e in r?mo(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,ht=(r,e,t)=>wo(r,typeof e!="symbol"?e+"":e,t);let Es=class{constructor(){ht(this,"contentType","application/json"),ht(this,"decoder"),ht(this,"encoder"),this.decoder=new TextDecoder,this.encoder=new TextEncoder}encode(e){return this.encoder.encode(this.encodeString(e)).buffer}decode(e,t){return this.decodeString(this.decoder.decode(e),t)}decodeString(e,t){const n=JSON.parse(e),i=zs(n);return t!=null?t.parse(i):i}encodeString(e){const t=po(e);return JSON.stringify(t,(n,i)=>ArrayBuffer.isView(i)?Array.from(i):Vr(i)&&"encode_value"in i?typeof i.value=="bigint"?i.value.toString():i.value:typeof i=="bigint"?i.toString():i)}static registerCustomType(){}},Ss=class{constructor(){ht(this,"contentType","text/csv")}encode(e){const t=this.encodeString(e);return new TextEncoder().encode(t).buffer}decode(e,t){const n=new TextDecoder().decode(e);return this.decodeString(n,t)}encodeString(e){if(!Array.isArray(e)||e.length===0||!Vr(e[0]))throw new Error("Payload must be an array of objects");const t=Object.keys(e[0]),n=[t.join(",")];return e.forEach(i=>{const a=t.map(c=>JSON.stringify(i[c]??""));n.push(a.join(","))}),n.join(`
4
4
  `)}decodeString(e,t){const[n,...i]=e.trim().split(`
5
- `).map(l=>l.trim());if(n.length===0)return t!=null?t.parse({}):{};const a=n.split(",").map(l=>l.trim()),c={};return a.forEach(l=>{c[l]=[]}),i.forEach(l=>{const u=l.split(",").map(f=>f.trim());a.forEach((f,g)=>{const p=this.parseValue(u[g]);p!=null&&c[f].push(p)})}),t!=null?t.parse(c):c}parseValue(e){if(e==null||e.length===0)return null;const t=Number(e);return isNaN(t)?e.startsWith('"')&&e.endsWith('"')?e.slice(1,-1):e:t}static registerCustomType(){}},ms=class{constructor(){ht(this,"contentType","text/plain")}encode(e){return new TextEncoder().encode(e).buffer}decode(e,t){const n=new TextDecoder().decode(e);return t!=null?t.parse(n):n}};const Ke=new ps,lo=new gs,uo=new ms,ho=[Ke],Xe=Object.freeze(Object.defineProperty({__proto__:null,CSVCodec:gs,CSV_CODEC:lo,ENCODERS:ho,JSONCodec:ps,JSON_CODEC:Ke,TEXT_CODEC:uo,TextCodec:ms},Symbol.toStringTag,{value:"Module"})),yo=r=>r!=null&&typeof r=="object"&&"toString"in r,fo=(r,e=!1)=>{const t=yo(r)?"stringer":typeof r;let n;switch(t){case"string":n=(i,a)=>i.localeCompare(a);break;case"stringer":n=(i,a)=>i.toString().localeCompare(a.toString());break;case"number":n=(i,a)=>Number(i)-Number(a);break;case"bigint":n=(i,a)=>BigInt(i)-BigInt(a)>0n?1:-1;break;case"boolean":n=(i,a)=>Number(i)-Number(a);break;case"undefined":n=()=>0;break;default:return console.warn(`sortFunc: unknown type ${t}`),()=>-1}return e?po(n):n},po=r=>(e,t)=>r(t,e),Ht=s.z.tuple([s.z.number(),s.z.number()]);s.z.tuple([s.z.bigint(),s.z.bigint()]);const ws=s.z.object({width:s.z.number(),height:s.z.number()}),go=s.z.object({signedWidth:s.z.number(),signedHeight:s.z.number()}),mo=["width","height"];s.z.enum(mo);const wo=["start","center","end"],bo=["signedWidth","signedHeight"];s.z.enum(bo);const Wt=s.z.object({x:s.z.number(),y:s.z.number()}),vo=s.z.object({clientX:s.z.number(),clientY:s.z.number()}),To=["x","y"],bs=s.z.enum(To),vs=["top","right","bottom","left"];s.z.enum(vs);const Oo=["left","right"],Ts=s.z.enum(Oo),zo=["top","bottom"],Os=s.z.enum(zo),zs=["center"],bn=s.z.enum(zs),Eo=[...vs,...zs],Es=s.z.enum(Eo);s.z.enum(wo);const So=["first","last"];s.z.enum(So);const No=s.z.object({lower:s.z.number(),upper:s.z.number()}),Io=s.z.object({lower:s.z.bigint(),upper:s.z.bigint()});s.z.union([No,Ht]);s.z.union([Io,Ht]);s.z.union([bs,Es]);s.z.union([bs,Es,s.z.instanceof(String)]);const yt=(r,e)=>{const t={};if(typeof r=="number"||typeof r=="bigint")e!=null?(t.lower=r,t.upper=e):(t.lower=typeof r=="bigint"?0n:0,t.upper=r);else if(Array.isArray(r)){if(r.length!==2)throw new Error("bounds: expected array of length 2");[t.lower,t.upper]=r}else return vn(r);return vn(t)},vn=r=>r.lower>r.upper?{lower:r.upper,upper:r.lower}:r;s.z.object({x:Ts.or(bn),y:Os.or(bn)});const ko=s.z.object({x:Ts,y:Os}),Ao=Object.freeze({x:"left",y:"top"}),$o=(r,e)=>r.x===e.x&&r.y===e.y,Tn=s.z.union([s.z.number(),Wt,Ht,ws,go,vo]),Ro=(r,e)=>{if(typeof r=="string"){if(e===void 0)throw new Error("The y coordinate must be given.");return r==="x"?{x:e,y:0}:{x:0,y:e}}return typeof r=="number"?{x:r,y:e??r}:Array.isArray(r)?{x:r[0],y:r[1]}:"signedWidth"in r?{x:r.signedWidth,y:r.signedHeight}:"clientX"in r?{x:r.clientX,y:r.clientY}:"width"in r?{x:r.width,y:r.height}:{x:r.x,y:r.y}},On=Object.freeze({x:0,y:0}),Rt=s.z.union([s.z.number(),s.z.string()]);s.z.object({top:Rt,left:Rt,width:Rt,height:Rt});s.z.object({left:s.z.number(),top:s.z.number(),right:s.z.number(),bottom:s.z.number()});s.z.object({one:Wt,two:Wt,root:ko});const Lr=(r,e,t=0,n=0,i)=>{const a={one:{...On},two:{...On},root:i??Ao};if(typeof r=="number"){if(typeof e!="number")throw new Error("Box constructor called with invalid arguments");return a.one={x:r,y:e},a.two={x:a.one.x+t,y:a.one.y+n},a}return"one"in r&&"two"in r&&"root"in r?{...r,root:i??r.root}:("getBoundingClientRect"in r&&(r=r.getBoundingClientRect()),"left"in r?(a.one={x:r.left,y:r.top},a.two={x:r.right,y:r.bottom},a):(a.one=r,e==null?a.two={x:a.one.x+t,y:a.one.y+n}:typeof e=="number"?a.two={x:a.one.x+e,y:a.one.y+t}:"width"in e?a.two={x:a.one.x+e.width,y:a.one.y+e.height}:"signedWidth"in e?a.two={x:a.one.x+e.signedWidth,y:a.one.y+e.signedHeight}:a.two=e,a))},pr=r=>{const e=Lr(r);return{lower:e.one.x,upper:e.two.x}},gr=r=>{const e=Lr(r);return{lower:e.one.y,upper:e.two.y}},xo=r=>typeof r!="object"||r==null?!1:"one"in r&&"two"in r&&"root"in r,Co=s.z.object({signedWidth:s.z.number(),signedHeight:s.z.number()});s.z.union([ws,Co,Wt,Ht]);var Po=Object.defineProperty,jo=(r,e,t)=>e in r?Po(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,he=(r,e,t)=>jo(r,typeof e!="symbol"?e+"":e,t);const Do=(r,e,t)=>e!==void 0&&r<e?e:t!==void 0&&r>t?t:r;s.z.object({offset:Tn,scale:Tn});const Mo=r=>(e,t,n,i)=>t==="dimension"?[e,n]:[e,i?n-r:n+r],Zo=r=>(e,t,n,i)=>[e,i?n/r:n*r],Uo=r=>(e,t,n)=>{if(e===null)return[r,n];const{lower:i,upper:a}=e,{lower:c,upper:l}=r,u=a-i,f=l-c;if(t==="dimension")return[r,n*(f/u)];const g=(n-i)*(f/u)+c;return[r,g]},Bo=r=>(e,t,n)=>[r,n],Lo=()=>(r,e,t)=>{if(r===null)throw new Error("cannot invert without bounds");if(e==="dimension")return[r,t];const{lower:n,upper:i}=r;return[r,i-(t-n)]},qo=r=>(e,t,n)=>{const{lower:i,upper:a}=r;return n=Do(n,i,a),[e,n]},Rr=class it{constructor(){he(this,"ops",[]),he(this,"currBounds",null),he(this,"currType",null),he(this,"reversed",!1),this.ops=[]}static translate(e){return new it().translate(e)}static magnify(e){return new it().magnify(e)}static scale(e,t){return new it().scale(e,t)}translate(e){const t=this.new(),n=Mo(e);return n.type="translate",t.ops.push(n),t}magnify(e){const t=this.new(),n=Zo(e);return n.type="magnify",t.ops.push(n),t}scale(e,t){const n=yt(e,t),i=this.new(),a=Uo(n);return a.type="scale",i.ops.push(a),i}clamp(e,t){const n=yt(e,t),i=this.new(),a=qo(n);return a.type="clamp",i.ops.push(a),i}reBound(e,t){const n=yt(e,t),i=this.new(),a=Bo(n);return a.type="re-bound",i.ops.push(a),i}invert(){const e=Lo();e.type="invert";const t=this.new();return t.ops.push(e),t}pos(e){return this.exec("position",e)}dim(e){return this.exec("dimension",e)}new(){const e=new it;return e.ops=this.ops.slice(),e.reversed=this.reversed,e}exec(e,t){return this.currBounds=null,this.ops.reduce(([n,i],a)=>a(n,e,i,this.reversed),[null,t])[1]}reverse(){const e=this.new();e.ops.reverse();const t=[];return e.ops.forEach((n,i)=>{if(n.type==="scale"||t.some(([c,l])=>i>=c&&i<=l))return;const a=e.ops.findIndex((c,l)=>c.type==="scale"&&l>i);a!==-1&&t.push([i,a])}),t.forEach(([n,i])=>{const a=e.ops.slice(n,i);a.unshift(e.ops[i]),e.ops.splice(n,i-n+1,...a)}),e.reversed=!e.reversed,e}};he(Rr,"IDENTITY",new Rr);let zn=Rr;const En=class ce{constructor(e=new zn,t=new zn,n=null){he(this,"x"),he(this,"y"),he(this,"currRoot"),this.x=e,this.y=t,this.currRoot=n}static translate(e,t){return new ce().translate(e,t)}static translateX(e){return new ce().translateX(e)}static translateY(e){return new ce().translateY(e)}static clamp(e){return new ce().clamp(e)}static magnify(e){return new ce().magnify(e)}static scale(e){return new ce().scale(e)}static reBound(e){return new ce().reBound(e)}translate(e,t){const n=Ro(e,t),i=this.copy();return i.x=this.x.translate(n.x),i.y=this.y.translate(n.y),i}translateX(e){const t=this.copy();return t.x=this.x.translate(e),t}translateY(e){const t=this.copy();return t.y=this.y.translate(e),t}magnify(e){const t=this.copy();return t.x=this.x.magnify(e.x),t.y=this.y.magnify(e.y),t}scale(e){const t=this.copy();if(xo(e)){const n=this.currRoot;return t.currRoot=e.root,n!=null&&!$o(n,e.root)&&(n.x!==e.root.x&&(t.x=t.x.invert()),n.y!==e.root.y&&(t.y=t.y.invert())),t.x=t.x.scale(pr(e)),t.y=t.y.scale(gr(e)),t}return t.x=t.x.scale(e.width),t.y=t.y.scale(e.height),t}reBound(e){const t=this.copy();return t.x=this.x.reBound(pr(e)),t.y=this.y.reBound(gr(e)),t}clamp(e){const t=this.copy();return t.x=this.x.clamp(pr(e)),t.y=this.y.clamp(gr(e)),t}copy(){const e=new ce;return e.currRoot=this.currRoot,e.x=this.x,e.y=this.y,e}reverse(){const e=this.copy();return e.x=this.x.reverse(),e.y=this.y.reverse(),e}pos(e){return{x:this.x.pos(e.x),y:this.y.pos(e.y)}}box(e){return Lr(this.pos(e.one),this.pos(e.two),0,0,this.currRoot??e.root)}};he(En,"IDENTITY",new En);var Yo=Object.defineProperty,Wo=(r,e,t)=>e in r?Yo(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,d=(r,e,t)=>Wo(r,typeof e!="symbol"?e+"":e,t);let _o=(r,e=21)=>(t=e)=>{let n="",i=t;for(;i--;)n+=r[Math.random()*r.length|0];return n};const Fo="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",Ss=_o(Fo,11),Ko=Object.freeze(Object.defineProperty({__proto__:null,id:Ss},Symbol.toStringTag,{value:"Module"})),Ns=(r,e)=>{const t=new E(e);if(![S.DAY,S.HOUR,S.MINUTE,S.SECOND,S.MILLISECOND,S.MICROSECOND,S.NANOSECOND].some(i=>i.equals(t)))throw new Error("Invalid argument for remainder. Must be an even TimeSpan or Timestamp");const n=r.valueOf()%t.valueOf();return r instanceof E?new E(n):new S(n)},R=class v{constructor(e,t="UTC"){if(d(this,"value"),d(this,"encodeValue",!0),e==null)this.value=v.now().valueOf();else if(e instanceof Date)this.value=BigInt(e.getTime())*v.MILLISECOND.valueOf();else if(typeof e=="string")this.value=v.parseDateTimeString(e,t).valueOf();else if(Array.isArray(e))this.value=v.parseDate(e);else{let n=BigInt(0);e instanceof Number&&(e=e.valueOf()),t==="local"&&(n=v.utcOffset.valueOf()),typeof e=="number"&&(isFinite(e)?e=Math.trunc(e):(isNaN(e)&&(e=0),e===1/0?e=v.MAX:e=v.MIN)),this.value=BigInt(e.valueOf())+n}}static parseDate([e=1970,t=1,n=1]){const i=new Date(e,t-1,n,0,0,0,0);return new v(BigInt(i.getTime())*v.MILLISECOND.valueOf()).truncate(v.DAY).valueOf()}encode(){return this.value.toString()}valueOf(){return this.value}static parseTimeString(e,t="UTC"){const[n,i,a]=e.split(":");let c="00",l="00";a!=null&&([c,l]=a.split("."));let u=v.hours(parseInt(n??"00",10)).add(v.minutes(parseInt(i??"00",10))).add(v.seconds(parseInt(c??"00",10))).add(v.milliseconds(parseInt(l??"00",10)));return t==="local"&&(u=u.add(v.utcOffset)),u.valueOf()}static parseDateTimeString(e,t="UTC"){if(!e.includes("/")&&!e.includes("-"))return v.parseTimeString(e,t);const n=new Date(e);return e.includes(":")||n.setUTCHours(0,0,0,0),new v(BigInt(n.getTime())*v.MILLISECOND.valueOf(),t).valueOf()}fString(e="ISO",t="UTC"){switch(e){case"ISODate":return this.toISOString(t).slice(0,10);case"ISOTime":return this.toISOString(t).slice(11,23);case"time":return this.timeString(!1,t);case"preciseTime":return this.timeString(!0,t);case"date":return this.dateString();case"preciseDate":return`${this.dateString()} ${this.timeString(!0,t)}`;case"dateTime":return`${this.dateString()} ${this.timeString(!1,t)}`;default:return this.toISOString(t)}}toISOString(e="UTC"){return e==="UTC"?this.date().toISOString():this.sub(v.utcOffset).date().toISOString()}timeString(e=!1,t="UTC"){const n=this.toISOString(t);return e?n.slice(11,23):n.slice(11,19)}dateString(){const e=this.date(),t=e.toLocaleString("default",{month:"short"}),n=e.toLocaleString("default",{day:"numeric"});return`${t} ${n}`}static get utcOffset(){return new S(BigInt(new Date().getTimezoneOffset())*v.MINUTE.valueOf())}static since(e){return new v().span(e)}date(){return new Date(this.milliseconds())}equals(e){return this.valueOf()===new v(e).valueOf()}span(e){return this.range(e).span}range(e){return new W(this,e).makeValid()}spanRange(e){return this.range(this.add(e)).makeValid()}get isZero(){return this.valueOf()===BigInt(0)}after(e){return this.valueOf()>new v(e).valueOf()}afterEq(e){return this.valueOf()>=new v(e).valueOf()}before(e){return this.valueOf()<new v(e).valueOf()}beforeEq(e){return this.valueOf()<=new v(e).valueOf()}add(e){return new v(this.valueOf()+BigInt(e.valueOf()))}sub(e){return new v(this.valueOf()-BigInt(e.valueOf()))}milliseconds(){return Number(this.valueOf())/Number(v.MILLISECOND.valueOf())}toString(){return this.date().toISOString()}remainder(e){return Ns(this,e)}get isToday(){return this.truncate(S.DAY).equals(v.now().truncate(S.DAY))}truncate(e){return this.sub(this.remainder(e))}static now(){return new v(new Date)}static max(...e){let t=v.MIN;for(const n of e){const i=new v(n);i.after(t)&&(t=i)}return t}static min(...e){let t=v.MAX;for(const n of e){const i=new v(n);i.before(t)&&(t=i)}return t}static nanoseconds(e){return new v(e)}static microseconds(e){return v.nanoseconds(e*1e3)}static milliseconds(e){return v.microseconds(e*1e3)}static seconds(e){return v.milliseconds(e*1e3)}static minutes(e){return v.seconds(e*60)}static hours(e){return v.minutes(e*60)}static days(e){return v.hours(e*24)}};d(R,"NANOSECOND",R.nanoseconds(1)),d(R,"MICROSECOND",R.microseconds(1)),d(R,"MILLISECOND",R.milliseconds(1)),d(R,"SECOND",R.seconds(1)),d(R,"MINUTE",R.minutes(1)),d(R,"HOUR",R.hours(1)),d(R,"DAY",R.days(1)),d(R,"MAX",new R((1n<<63n)-1n)),d(R,"MIN",new R(0)),d(R,"ZERO",new R(0)),d(R,"z",s.z.union([s.z.object({value:s.z.bigint()}).transform(r=>new R(r.value)),s.z.string().transform(r=>new R(BigInt(r))),s.z.instanceof(Number).transform(r=>new R(r)),s.z.number().transform(r=>new R(r)),s.z.instanceof(R)]));let E=R;const x=class I{constructor(e){d(this,"value"),d(this,"encodeValue",!0),typeof e=="number"&&(e=Math.trunc(e.valueOf())),this.value=BigInt(e.valueOf())}encode(){return this.value.toString()}valueOf(){return this.value}lessThan(e){return this.valueOf()<new I(e).valueOf()}greaterThan(e){return this.valueOf()>new I(e).valueOf()}lessThanOrEqual(e){return this.valueOf()<=new I(e).valueOf()}greaterThanOrEqual(e){return this.valueOf()>=new I(e).valueOf()}remainder(e){return Ns(this,e)}truncate(e){return new I(BigInt(Math.trunc(Number(this.valueOf()/e.valueOf())))*e.valueOf())}toString(){const e=this.truncate(I.DAY),t=this.truncate(I.HOUR),n=this.truncate(I.MINUTE),i=this.truncate(I.SECOND),a=this.truncate(I.MILLISECOND),c=this.truncate(I.MICROSECOND),l=this.truncate(I.NANOSECOND),u=e,f=t.sub(e),g=n.sub(t),p=i.sub(n),j=a.sub(i),P=c.sub(a),X=l.sub(c);let D="";return u.isZero||(D+=`${u.days}d `),f.isZero||(D+=`${f.hours}h `),g.isZero||(D+=`${g.minutes}m `),p.isZero||(D+=`${p.seconds}s `),j.isZero||(D+=`${j.milliseconds}ms `),P.isZero||(D+=`${P.microseconds}µs `),X.isZero||(D+=`${X.nanoseconds}ns`),D.trim()}get days(){return Number(this.valueOf())/Number(I.DAY.valueOf())}get hours(){return Number(this.valueOf())/Number(I.HOUR.valueOf())}get minutes(){return Number(this.valueOf())/Number(I.MINUTE.valueOf())}get seconds(){return Number(this.valueOf())/Number(I.SECOND.valueOf())}get milliseconds(){return Number(this.valueOf())/Number(I.MILLISECOND.valueOf())}get microseconds(){return Number(this.valueOf())/Number(I.MICROSECOND.valueOf())}get nanoseconds(){return Number(this.valueOf())}get isZero(){return this.valueOf()===BigInt(0)}equals(e){return this.valueOf()===new I(e).valueOf()}add(e){return new I(this.valueOf()+new I(e).valueOf())}sub(e){return new I(this.valueOf()-new I(e).valueOf())}static nanoseconds(e=1){return new I(e)}static microseconds(e=1){return I.nanoseconds(e*1e3)}static milliseconds(e=1){return I.microseconds(e*1e3)}static seconds(e=1){return I.milliseconds(e*1e3)}static minutes(e){return I.seconds(e.valueOf()*60)}static hours(e){return I.minutes(e*60)}static days(e){return I.hours(e*24)}};d(x,"NANOSECOND",x.nanoseconds(1)),d(x,"MICROSECOND",x.microseconds(1)),d(x,"MILLISECOND",x.milliseconds(1)),d(x,"SECOND",x.seconds(1)),d(x,"MINUTE",x.minutes(1)),d(x,"HOUR",x.hours(1)),d(x,"DAY",x.days(1)),d(x,"MAX",new x((1n<<63n)-1n)),d(x,"MIN",new x(0)),d(x,"ZERO",new x(0)),d(x,"z",s.z.union([s.z.object({value:s.z.bigint()}).transform(r=>new x(r.value)),s.z.string().transform(r=>new x(BigInt(r))),s.z.instanceof(Number).transform(r=>new x(r)),s.z.number().transform(r=>new x(r)),s.z.instanceof(x)]));let S=x;const at=class Zt extends Number{constructor(e){e instanceof Number?super(e.valueOf()):super(e)}toString(){return`${this.valueOf()} Hz`}equals(e){return this.valueOf()===new Zt(e).valueOf()}get period(){return S.seconds(1/this.valueOf())}sampleCount(e){return new S(e).seconds*this.valueOf()}byteCount(e,t){return this.sampleCount(e)*new K(t).valueOf()}span(e){return S.seconds(e/this.valueOf())}byteSpan(e,t){return this.span(e.valueOf()/t.valueOf())}static hz(e){return new Zt(e)}static khz(e){return Zt.hz(e*1e3)}};d(at,"z",s.z.union([s.z.number().transform(r=>new at(r)),s.z.instanceof(Number).transform(r=>new at(r)),s.z.instanceof(at)]));let Xt=at;const L=class extends Number{constructor(e){e instanceof Number?super(e.valueOf()):super(e)}length(e){return e.valueOf()/this.valueOf()}size(e){return new pt(e*this.valueOf())}};d(L,"UNKNOWN",new L(0)),d(L,"BIT128",new L(16)),d(L,"BIT64",new L(8)),d(L,"BIT32",new L(4)),d(L,"BIT16",new L(2)),d(L,"BIT8",new L(1)),d(L,"z",s.z.union([s.z.number().transform(r=>new L(r)),s.z.instanceof(Number).transform(r=>new L(r)),s.z.instanceof(L)]));let K=L;const se=class Ut{constructor(e,t){d(this,"start"),d(this,"end"),typeof e=="object"&&"start"in e?(this.start=new E(e.start),this.end=new E(e.end)):(this.start=new E(e),this.end=new E(t))}get span(){return new S(this.end.valueOf()-this.start.valueOf())}get isValid(){return this.start.valueOf()<=this.end.valueOf()}makeValid(){return this.isValid?this:this.swap()}get isZero(){return this.span.isZero}get numeric(){return{start:Number(this.start.valueOf()),end:Number(this.end.valueOf())}}swap(){return new Ut(this.end,this.start)}equals(e){return this.start.equals(e.start)&&this.end.equals(e.end)}toString(){return`${this.start.toString()} - ${this.end.toString()}`}toPrettyString(){return`${this.start.fString("preciseDate")} - ${this.span.toString()}`}overlapsWith(e,t=S.ZERO){e=e.makeValid();const n=this.makeValid();if(this.equals(e))return!0;if(e.end.equals(n.start)||n.end.equals(e.start))return!1;const i=E.max(n.start,e.start),a=E.min(n.end,e.end);return a.before(i)?!1:new S(a.sub(i)).greaterThanOrEqual(t)}roughlyEquals(e,t){let n=this.start.sub(e.start).valueOf(),i=this.end.sub(e.end).valueOf();return n<0&&(n=-n),i<0&&(i=-i),n<=t.valueOf()&&i<=t.valueOf()}contains(e){return e instanceof Ut?this.contains(e.start)&&this.contains(e.end):this.start.beforeEq(e)&&this.end.after(e)}boundBy(e){const t=new Ut(this.start,this.end);return e.start.after(this.start)&&(t.start=e.start),e.start.after(this.end)&&(t.end=e.start),e.end.before(this.end)&&(t.end=e.end),e.end.before(this.start)&&(t.start=e.end),t}};d(se,"MAX",new se(E.MIN,E.MAX)),d(se,"MIN",new se(E.MAX,E.MIN)),d(se,"ZERO",new se(E.ZERO,E.ZERO)),d(se,"z",s.z.union([s.z.object({start:E.z,end:E.z}).transform(r=>new se(r.start,r.end)),s.z.instanceof(se)]));let W=se;const h=class ie extends String{constructor(e){if(e instanceof ie||typeof e=="string"||typeof e.valueOf()=="string"){super(e.valueOf());return}else{const t=ie.ARRAY_CONSTRUCTOR_DATA_TYPES.get(e.constructor.name);if(t!=null){super(t.valueOf());return}}throw super(ie.UNKNOWN.valueOf()),new Error(`unable to find data type for ${e.toString()}`)}get Array(){const e=ie.ARRAY_CONSTRUCTORS.get(this.toString());if(e==null)throw new Error(`unable to find array constructor for ${this.valueOf()}`);return e}equals(e){return this.valueOf()===e.valueOf()}matches(...e){return e.some(t=>this.equals(t))}toString(){return this.valueOf()}get isVariable(){return this.equals(ie.JSON)||this.equals(ie.STRING)}get isNumeric(){return!this.isVariable&&!this.equals(ie.UUID)}get isInteger(){return this.toString().startsWith("int")}get isFloat(){return this.toString().startsWith("float")}get density(){const e=ie.DENSITIES.get(this.toString());if(e==null)throw new Error(`unable to find density for ${this.valueOf()}`);return e}canSafelyCastTo(e){return this.equals(e)?!0:this.isVariable&&!e.isVariable||!this.isVariable&&e.isVariable?!1:this.isFloat&&e.isInteger||this.isInteger&&e.isFloat?this.density.valueOf()<e.density.valueOf():this.isFloat&&e.isFloat||this.isInteger&&e.isInteger?this.density.valueOf()<=e.density.valueOf():!1}canCastTo(e){return this.isNumeric&&e.isNumeric?!0:this.equals(e)}checkArray(e){return e.constructor===this.Array}toJSON(){return this.toString()}get usesBigInt(){return ie.BIG_INT_TYPES.some(e=>e.equals(this))}};d(h,"UNKNOWN",new h("unknown")),d(h,"FLOAT64",new h("float64")),d(h,"FLOAT32",new h("float32")),d(h,"INT64",new h("int64")),d(h,"INT32",new h("int32")),d(h,"INT16",new h("int16")),d(h,"INT8",new h("int8")),d(h,"UINT64",new h("uint64")),d(h,"UINT32",new h("uint32")),d(h,"UINT16",new h("uint16")),d(h,"UINT8",new h("uint8")),d(h,"BOOLEAN",h.UINT8),d(h,"TIMESTAMP",new h("timestamp")),d(h,"UUID",new h("uuid")),d(h,"STRING",new h("string")),d(h,"JSON",new h("json")),d(h,"ARRAY_CONSTRUCTORS",new Map([[h.UINT8.toString(),Uint8Array],[h.UINT16.toString(),Uint16Array],[h.UINT32.toString(),Uint32Array],[h.UINT64.toString(),BigUint64Array],[h.FLOAT32.toString(),Float32Array],[h.FLOAT64.toString(),Float64Array],[h.INT8.toString(),Int8Array],[h.INT16.toString(),Int16Array],[h.INT32.toString(),Int32Array],[h.INT64.toString(),BigInt64Array],[h.TIMESTAMP.toString(),BigInt64Array],[h.STRING.toString(),Uint8Array],[h.JSON.toString(),Uint8Array],[h.UUID.toString(),Uint8Array]])),d(h,"ARRAY_CONSTRUCTOR_DATA_TYPES",new Map([[Uint8Array.name,h.UINT8],[Uint16Array.name,h.UINT16],[Uint32Array.name,h.UINT32],[BigUint64Array.name,h.UINT64],[Float32Array.name,h.FLOAT32],[Float64Array.name,h.FLOAT64],[Int8Array.name,h.INT8],[Int16Array.name,h.INT16],[Int32Array.name,h.INT32],[BigInt64Array.name,h.INT64]])),d(h,"DENSITIES",new Map([[h.UINT8.toString(),K.BIT8],[h.UINT16.toString(),K.BIT16],[h.UINT32.toString(),K.BIT32],[h.UINT64.toString(),K.BIT64],[h.FLOAT32.toString(),K.BIT32],[h.FLOAT64.toString(),K.BIT64],[h.INT8.toString(),K.BIT8],[h.INT16.toString(),K.BIT16],[h.INT32.toString(),K.BIT32],[h.INT64.toString(),K.BIT64],[h.TIMESTAMP.toString(),K.BIT64],[h.STRING.toString(),K.UNKNOWN],[h.JSON.toString(),K.UNKNOWN],[h.UUID.toString(),K.BIT128]])),d(h,"ALL",[h.UNKNOWN,h.FLOAT64,h.FLOAT32,h.INT64,h.INT32,h.INT16,h.INT8,h.UINT64,h.UINT32,h.UINT16,h.UINT8,h.TIMESTAMP,h.UUID,h.STRING,h.JSON]),d(h,"BIG_INT_TYPES",[h.INT64,h.UINT64,h.TIMESTAMP]),d(h,"z",s.z.union([s.z.string().transform(r=>new h(r)),s.z.instanceof(h)]));let z=h;const F=class Z extends Number{constructor(e){super(e.valueOf())}largerThan(e){return this.valueOf()>e.valueOf()}smallerThan(e){return this.valueOf()<e.valueOf()}add(e){return Z.bytes(this.valueOf()+e.valueOf())}sub(e){return Z.bytes(this.valueOf()-e.valueOf())}truncate(e){return new Z(Math.trunc(this.valueOf()/e.valueOf())*e.valueOf())}remainder(e){return Z.bytes(this.valueOf()%e.valueOf())}get gigabytes(){return this.valueOf()/Z.GIGABYTE.valueOf()}get megabytes(){return this.valueOf()/Z.MEGABYTE.valueOf()}get kilobytes(){return this.valueOf()/Z.KILOBYTE.valueOf()}get terabytes(){return this.valueOf()/Z.TERABYTE.valueOf()}toString(){const e=this.truncate(Z.TERABYTE),t=this.truncate(Z.GIGABYTE),n=this.truncate(Z.MEGABYTE),i=this.truncate(Z.KILOBYTE),a=this.truncate(Z.BYTE),c=e,l=t.sub(e),u=n.sub(t),f=i.sub(n),g=a.sub(i);let p="";return c.isZero||(p+=`${c.terabytes}TB `),l.isZero||(p+=`${l.gigabytes}GB `),u.isZero||(p+=`${u.megabytes}MB `),f.isZero||(p+=`${f.kilobytes}KB `),(!g.isZero||p==="")&&(p+=`${g.valueOf()}B`),p.trim()}static bytes(e=1){return new Z(e)}static kilobytes(e=1){return Z.bytes(e.valueOf()*1e3)}static megabytes(e=1){return Z.kilobytes(e.valueOf()*1e3)}static gigabytes(e=1){return Z.megabytes(e.valueOf()*1e3)}static terabytes(e){return Z.gigabytes(e.valueOf()*1e3)}get isZero(){return this.valueOf()===0}};d(F,"BYTE",new F(1)),d(F,"KILOBYTE",F.kilobytes(1)),d(F,"MEGABYTE",F.megabytes(1)),d(F,"GIGABYTE",F.gigabytes(1)),d(F,"TERABYTE",F.terabytes(1)),d(F,"ZERO",new F(0)),d(F,"z",s.z.union([s.z.number().transform(r=>new F(r)),s.z.instanceof(F)]));let pt=F;s.z.union([s.z.instanceof(Uint8Array),s.z.instanceof(Uint16Array),s.z.instanceof(Uint32Array),s.z.instanceof(BigUint64Array),s.z.instanceof(Float32Array),s.z.instanceof(Float64Array),s.z.instanceof(Int8Array),s.z.instanceof(Int16Array),s.z.instanceof(Int32Array),s.z.instanceof(BigInt64Array)]);const Is=r=>{const e=typeof r;return e==="string"||e==="number"||e==="boolean"||e==="bigint"||r instanceof E||r instanceof S||r instanceof Date},Go=(r,e,t,n=0)=>r.usesBigInt&&!e.usesBigInt?Number(t)-Number(n):!r.usesBigInt&&e.usesBigInt?BigInt(t)-BigInt(n):ot(t,-n),Vo=r=>r==null?!1:Array.isArray(r)||r instanceof ArrayBuffer||ArrayBuffer.isView(r)&&!(r instanceof DataView)||r instanceof ze?!0:Is(r),Te=-1;let ze=class le{constructor(e){d(this,"key",""),d(this,"isSynnaxSeries",!0),d(this,"dataType"),d(this,"sampleOffset"),d(this,"gl"),d(this,"_data"),d(this,"_timeRange"),d(this,"alignment",0n),d(this,"_cachedMin"),d(this,"_cachedMax"),d(this,"writePos",Te),d(this,"_refCount",0),d(this,"_cachedLength"),Vo(e)&&(e={data:e});const{dataType:t,timeRange:n,sampleOffset:i=0,glBufferUsage:a="static",alignment:c=0n,key:l=Ss()}=e,{data:u}=e;if(u instanceof le||typeof u=="object"&&"isSynnaxSeries"in u&&u.isSynnaxSeries===!0){const p=u;this.key=p.key,this.dataType=p.dataType,this.sampleOffset=p.sampleOffset,this.gl=p.gl,this._data=p._data,this._timeRange=p._timeRange,this.alignment=p.alignment,this._cachedMin=p._cachedMin,this._cachedMax=p._cachedMax,this.writePos=p.writePos,this._refCount=p._refCount,this._cachedLength=p._cachedLength;return}const f=Is(u),g=Array.isArray(u);if(t!=null)this.dataType=new z(t);else{if(u instanceof ArrayBuffer)throw new Error("cannot infer data type from an ArrayBuffer instance when constructing a Series. Please provide a data type.");if(g||f){let p=u;if(!f){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.");p=u[0]}if(typeof p=="string")this.dataType=z.STRING;else if(typeof p=="number")this.dataType=z.FLOAT64;else if(typeof p=="bigint")this.dataType=z.INT64;else if(typeof p=="boolean")this.dataType=z.BOOLEAN;else if(p instanceof E||p instanceof Date||p instanceof E)this.dataType=z.TIMESTAMP;else if(typeof p=="object")this.dataType=z.JSON;else throw new Error(`cannot infer data type of ${typeof p} when constructing a Series from a JS array`)}else this.dataType=new z(u)}if(!g&&!f)this._data=u;else{let p=f?[u]:u;const j=p[0];(j instanceof E||j instanceof Date||j instanceof S)&&(p=p.map(P=>new E(P).valueOf())),this.dataType.equals(z.STRING)?(this._cachedLength=p.length,this._data=new TextEncoder().encode(p.join(`
5
+ `).map(l=>l.trim());if(n.length===0)return t!=null?t.parse({}):{};const a=n.split(",").map(l=>l.trim()),c={};return a.forEach(l=>{c[l]=[]}),i.forEach(l=>{const u=l.split(",").map(h=>h.trim());a.forEach((h,p)=>{const g=this.parseValue(u[p]);g!=null&&c[h].push(g)})}),t!=null?t.parse(c):c}parseValue(e){if(e==null||e.length===0)return null;const t=Number(e);return isNaN(t)?e.startsWith('"')&&e.endsWith('"')?e.slice(1,-1):e:t}static registerCustomType(){}},Ns=class{constructor(){ht(this,"contentType","text/plain")}encode(e){return new TextEncoder().encode(e).buffer}decode(e,t){const n=new TextDecoder().decode(e);return t!=null?t.parse(n):n}};const Ke=new Es,bo=new Ss,vo=new Ns,To=[Ke],Qe=Object.freeze(Object.defineProperty({__proto__:null,CSVCodec:Ss,CSV_CODEC:bo,ENCODERS:To,JSONCodec:Es,JSON_CODEC:Ke,TEXT_CODEC:vo,TextCodec:Ns},Symbol.toStringTag,{value:"Module"})),Oo=r=>r!=null&&typeof r=="object"&&"toString"in r,zo=(r,e=!1)=>{const t=Oo(r)?"stringer":typeof r;let n;switch(t){case"string":n=(i,a)=>i.localeCompare(a);break;case"stringer":n=(i,a)=>i.toString().localeCompare(a.toString());break;case"number":n=(i,a)=>Number(i)-Number(a);break;case"bigint":n=(i,a)=>BigInt(i)-BigInt(a)>0n?1:-1;break;case"boolean":n=(i,a)=>Number(i)-Number(a);break;case"undefined":n=()=>0;break;default:return console.warn(`sortFunc: unknown type ${t}`),()=>-1}return e?Eo(n):n},Eo=r=>(e,t)=>r(t,e),So=0,wr=-1,br=1,No=r=>r<0,Io=r=>r>0,ko=r=>r===0,er=s.z.tuple([s.z.number(),s.z.number()]);s.z.tuple([s.z.bigint(),s.z.bigint()]);const Is=s.z.object({width:s.z.number(),height:s.z.number()}),Ao=s.z.object({signedWidth:s.z.number(),signedHeight:s.z.number()}),$o=["width","height"];s.z.enum($o);const Ro=["start","center","end"],Co=["signedWidth","signedHeight"];s.z.enum(Co);const Ft=s.z.object({x:s.z.number(),y:s.z.number()}),xo=s.z.object({clientX:s.z.number(),clientY:s.z.number()}),Po=["x","y"],ks=s.z.enum(Po),As=["top","right","bottom","left"];s.z.enum(As);const Do=["left","right"],$s=s.z.enum(Do),jo=["top","bottom"],Rs=s.z.enum(jo),Cs=["center"],Sn=s.z.enum(Cs),Mo=[...As,...Cs],xs=s.z.enum(Mo);s.z.enum(Ro);const Zo=["first","last"];s.z.enum(Zo);const Uo=s.z.object({lower:s.z.number(),upper:s.z.number()}),Bo=s.z.object({lower:s.z.bigint(),upper:s.z.bigint()});s.z.union([Uo,er]);s.z.union([Bo,er]);s.z.union([ks,xs]);s.z.union([ks,xs,s.z.instanceof(String)]);const yt=(r,e)=>{const t={};if(typeof r=="number"||typeof r=="bigint")e!=null?(t.lower=r,t.upper=e):(t.lower=typeof r=="bigint"?0n:0,t.upper=r);else if(Array.isArray(r)){if(r.length!==2)throw new Error("bounds: expected array of length 2");[t.lower,t.upper]=r}else return Nn(r);return Nn(t)},Nn=r=>r.lower>r.upper?{lower:r.upper,upper:r.lower}:r;s.z.object({x:$s.or(Sn),y:Rs.or(Sn)});const Lo=s.z.object({x:$s,y:Rs}),qo=Object.freeze({x:"left",y:"top"}),Yo=(r,e)=>r.x===e.x&&r.y===e.y,In=s.z.union([s.z.number(),Ft,er,Is,Ao,xo]),Wo=(r,e)=>{if(typeof r=="string"){if(e===void 0)throw new Error("The y coordinate must be given.");return r==="x"?{x:e,y:0}:{x:0,y:e}}return typeof r=="number"?{x:r,y:e??r}:Array.isArray(r)?{x:r[0],y:r[1]}:"signedWidth"in r?{x:r.signedWidth,y:r.signedHeight}:"clientX"in r?{x:r.clientX,y:r.clientY}:"width"in r?{x:r.width,y:r.height}:{x:r.x,y:r.y}},kn=Object.freeze({x:0,y:0}),xt=s.z.union([s.z.number(),s.z.string()]);s.z.object({top:xt,left:xt,width:xt,height:xt});s.z.object({left:s.z.number(),top:s.z.number(),right:s.z.number(),bottom:s.z.number()});s.z.object({one:Ft,two:Ft,root:Lo});const Fr=(r,e,t=0,n=0,i)=>{const a={one:{...kn},two:{...kn},root:i??qo};if(typeof r=="number"){if(typeof e!="number")throw new Error("Box constructor called with invalid arguments");return a.one={x:r,y:e},a.two={x:a.one.x+t,y:a.one.y+n},a}return"one"in r&&"two"in r&&"root"in r?{...r,root:i??r.root}:("getBoundingClientRect"in r&&(r=r.getBoundingClientRect()),"left"in r?(a.one={x:r.left,y:r.top},a.two={x:r.right,y:r.bottom},a):(a.one=r,e==null?a.two={x:a.one.x+t,y:a.one.y+n}:typeof e=="number"?a.two={x:a.one.x+e,y:a.one.y+t}:"width"in e?a.two={x:a.one.x+e.width,y:a.one.y+e.height}:"signedWidth"in e?a.two={x:a.one.x+e.signedWidth,y:a.one.y+e.signedHeight}:a.two=e,a))},vr=r=>{const e=Fr(r);return{lower:e.one.x,upper:e.two.x}},Tr=r=>{const e=Fr(r);return{lower:e.one.y,upper:e.two.y}},_o=r=>typeof r!="object"||r==null?!1:"one"in r&&"two"in r&&"root"in r,Vo=s.z.object({signedWidth:s.z.number(),signedHeight:s.z.number()});s.z.union([Is,Vo,Ft,er]);var Fo=Object.defineProperty,Ko=(r,e,t)=>e in r?Fo(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,he=(r,e,t)=>Ko(r,typeof e!="symbol"?e+"":e,t);const Go=(r,e,t)=>e!==void 0&&r<e?e:t!==void 0&&r>t?t:r;s.z.object({offset:In,scale:In});const Jo=r=>(e,t,n,i)=>t==="dimension"?[e,n]:[e,i?n-r:n+r],Ho=r=>(e,t,n,i)=>[e,i?n/r:n*r],Xo=r=>(e,t,n)=>{if(e===null)return[r,n];const{lower:i,upper:a}=e,{lower:c,upper:l}=r,u=a-i,h=l-c;if(t==="dimension")return[r,n*(h/u)];const p=(n-i)*(h/u)+c;return[r,p]},Qo=r=>(e,t,n)=>[r,n],ec=()=>(r,e,t)=>{if(r===null)throw new Error("cannot invert without bounds");if(e==="dimension")return[r,t];const{lower:n,upper:i}=r;return[r,i-(t-n)]},tc=r=>(e,t,n)=>{const{lower:i,upper:a}=r;return n=Go(n,i,a),[e,n]},jr=class it{constructor(){he(this,"ops",[]),he(this,"currBounds",null),he(this,"currType",null),he(this,"reversed",!1),this.ops=[]}static translate(e){return new it().translate(e)}static magnify(e){return new it().magnify(e)}static scale(e,t){return new it().scale(e,t)}translate(e){const t=this.new(),n=Jo(e);return n.type="translate",t.ops.push(n),t}magnify(e){const t=this.new(),n=Ho(e);return n.type="magnify",t.ops.push(n),t}scale(e,t){const n=yt(e,t),i=this.new(),a=Xo(n);return a.type="scale",i.ops.push(a),i}clamp(e,t){const n=yt(e,t),i=this.new(),a=tc(n);return a.type="clamp",i.ops.push(a),i}reBound(e,t){const n=yt(e,t),i=this.new(),a=Qo(n);return a.type="re-bound",i.ops.push(a),i}invert(){const e=ec();e.type="invert";const t=this.new();return t.ops.push(e),t}pos(e){return this.exec("position",e)}dim(e){return this.exec("dimension",e)}new(){const e=new it;return e.ops=this.ops.slice(),e.reversed=this.reversed,e}exec(e,t){return this.currBounds=null,this.ops.reduce(([n,i],a)=>a(n,e,i,this.reversed),[null,t])[1]}reverse(){const e=this.new();e.ops.reverse();const t=[];return e.ops.forEach((n,i)=>{if(n.type==="scale"||t.some(([c,l])=>i>=c&&i<=l))return;const a=e.ops.findIndex((c,l)=>c.type==="scale"&&l>i);a!==-1&&t.push([i,a])}),t.forEach(([n,i])=>{const a=e.ops.slice(n,i);a.unshift(e.ops[i]),e.ops.splice(n,i-n+1,...a)}),e.reversed=!e.reversed,e}};he(jr,"IDENTITY",new jr);let An=jr;const $n=class ce{constructor(e=new An,t=new An,n=null){he(this,"x"),he(this,"y"),he(this,"currRoot"),this.x=e,this.y=t,this.currRoot=n}static translate(e,t){return new ce().translate(e,t)}static translateX(e){return new ce().translateX(e)}static translateY(e){return new ce().translateY(e)}static clamp(e){return new ce().clamp(e)}static magnify(e){return new ce().magnify(e)}static scale(e){return new ce().scale(e)}static reBound(e){return new ce().reBound(e)}translate(e,t){const n=Wo(e,t),i=this.copy();return i.x=this.x.translate(n.x),i.y=this.y.translate(n.y),i}translateX(e){const t=this.copy();return t.x=this.x.translate(e),t}translateY(e){const t=this.copy();return t.y=this.y.translate(e),t}magnify(e){const t=this.copy();return t.x=this.x.magnify(e.x),t.y=this.y.magnify(e.y),t}scale(e){const t=this.copy();if(_o(e)){const n=this.currRoot;return t.currRoot=e.root,n!=null&&!Yo(n,e.root)&&(n.x!==e.root.x&&(t.x=t.x.invert()),n.y!==e.root.y&&(t.y=t.y.invert())),t.x=t.x.scale(vr(e)),t.y=t.y.scale(Tr(e)),t}return t.x=t.x.scale(e.width),t.y=t.y.scale(e.height),t}reBound(e){const t=this.copy();return t.x=this.x.reBound(vr(e)),t.y=this.y.reBound(Tr(e)),t}clamp(e){const t=this.copy();return t.x=this.x.clamp(vr(e)),t.y=this.y.clamp(Tr(e)),t}copy(){const e=new ce;return e.currRoot=this.currRoot,e.x=this.x,e.y=this.y,e}reverse(){const e=this.copy();return e.x=this.x.reverse(),e.y=this.y.reverse(),e}pos(e){return{x:this.x.pos(e.x),y:this.y.pos(e.y)}}box(e){return Fr(this.pos(e.one),this.pos(e.two),0,0,this.currRoot??e.root)}};he($n,"IDENTITY",new $n);var rc=Object.defineProperty,nc=(r,e,t)=>e in r?rc(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,f=(r,e,t)=>nc(r,typeof e!="symbol"?e+"":e,t);let sc=(r,e=21)=>(t=e)=>{let n="",i=t;for(;i--;)n+=r[Math.random()*r.length|0];return n};const ic="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",Ps=sc(ic,11),ac=Object.freeze(Object.defineProperty({__proto__:null,id:Ps},Symbol.toStringTag,{value:"Module"})),Ds=(r,e)=>{const t=new S(e);if(![E.DAY,E.HOUR,E.MINUTE,E.SECOND,E.MILLISECOND,E.MICROSECOND,E.NANOSECOND].some(i=>i.equals(t)))throw new Error("Invalid argument for remainder. Must be an even TimeSpan or Timestamp");const n=r.valueOf()%t.valueOf();return r instanceof S?new S(n):new E(n)},R=class v{constructor(e,t="UTC"){if(f(this,"value"),f(this,"encodeValue",!0),e==null)this.value=v.now().valueOf();else if(e instanceof Date)this.value=BigInt(e.getTime())*v.MILLISECOND.valueOf();else if(typeof e=="string")this.value=v.parseDateTimeString(e,t).valueOf();else if(Array.isArray(e))this.value=v.parseDate(e);else{let n=BigInt(0);e instanceof Number&&(e=e.valueOf()),t==="local"&&(n=v.utcOffset.valueOf()),typeof e=="number"&&(isFinite(e)?e=Math.trunc(e):(isNaN(e)&&(e=0),e===1/0?e=v.MAX:e=v.MIN)),this.value=BigInt(e.valueOf())+n}}static parseDate([e=1970,t=1,n=1]){const i=new Date(e,t-1,n,0,0,0,0);return new v(BigInt(i.getTime())*v.MILLISECOND.valueOf()).truncate(v.DAY).valueOf()}encode(){return this.value.toString()}valueOf(){return this.value}static parseTimeString(e,t="UTC"){const[n,i,a]=e.split(":");let c="00",l="00";a!=null&&([c,l]=a.split("."));let u=v.hours(parseInt(n??"00",10)).add(v.minutes(parseInt(i??"00",10))).add(v.seconds(parseInt(c??"00",10))).add(v.milliseconds(parseInt(l??"00",10)));return t==="local"&&(u=u.add(v.utcOffset)),u.valueOf()}static parseDateTimeString(e,t="UTC"){if(!e.includes("/")&&!e.includes("-"))return v.parseTimeString(e,t);const n=new Date(e);return e.includes(":")||n.setUTCHours(0,0,0,0),new v(BigInt(n.getTime())*v.MILLISECOND.valueOf(),t).valueOf()}fString(e="ISO",t="UTC"){switch(e){case"ISODate":return this.toISOString(t).slice(0,10);case"ISOTime":return this.toISOString(t).slice(11,23);case"time":return this.timeString(!1,t);case"preciseTime":return this.timeString(!0,t);case"date":return this.dateString();case"preciseDate":return`${this.dateString()} ${this.timeString(!0,t)}`;case"dateTime":return`${this.dateString()} ${this.timeString(!1,t)}`;default:return this.toISOString(t)}}toISOString(e="UTC"){return e==="UTC"?this.date().toISOString():this.sub(v.utcOffset).date().toISOString()}timeString(e=!1,t="UTC"){const n=this.toISOString(t);return e?n.slice(11,23):n.slice(11,19)}dateString(){const e=this.date(),t=e.toLocaleString("default",{month:"short"}),n=e.toLocaleString("default",{day:"numeric"});return`${t} ${n}`}static get utcOffset(){return new E(BigInt(new Date().getTimezoneOffset())*v.MINUTE.valueOf())}static since(e){return new v().span(e)}date(){return new Date(this.milliseconds())}equals(e){return this.valueOf()===new v(e).valueOf()}span(e){return this.range(e).span}range(e){return new W(this,e).makeValid()}spanRange(e){return this.range(this.add(e)).makeValid()}get isZero(){return this.valueOf()===BigInt(0)}after(e){return this.valueOf()>new v(e).valueOf()}afterEq(e){return this.valueOf()>=new v(e).valueOf()}before(e){return this.valueOf()<new v(e).valueOf()}beforeEq(e){return this.valueOf()<=new v(e).valueOf()}add(e){return new v(this.valueOf()+BigInt(e.valueOf()))}sub(e){return new v(this.valueOf()-BigInt(e.valueOf()))}milliseconds(){return Number(this.valueOf())/Number(v.MILLISECOND.valueOf())}toString(){return this.date().toISOString()}remainder(e){return Ds(this,e)}get isToday(){return this.truncate(E.DAY).equals(v.now().truncate(E.DAY))}truncate(e){return this.sub(this.remainder(e))}static now(){return new v(new Date)}static max(...e){let t=v.MIN;for(const n of e){const i=new v(n);i.after(t)&&(t=i)}return t}static min(...e){let t=v.MAX;for(const n of e){const i=new v(n);i.before(t)&&(t=i)}return t}static nanoseconds(e){return new v(e)}static microseconds(e){return v.nanoseconds(e*1e3)}static milliseconds(e){return v.microseconds(e*1e3)}static seconds(e){return v.milliseconds(e*1e3)}static minutes(e){return v.seconds(e*60)}static hours(e){return v.minutes(e*60)}static days(e){return v.hours(e*24)}};f(R,"NANOSECOND",R.nanoseconds(1)),f(R,"MICROSECOND",R.microseconds(1)),f(R,"MILLISECOND",R.milliseconds(1)),f(R,"SECOND",R.seconds(1)),f(R,"MINUTE",R.minutes(1)),f(R,"HOUR",R.hours(1)),f(R,"DAY",R.days(1)),f(R,"MAX",new R((1n<<63n)-1n)),f(R,"MIN",new R(0)),f(R,"ZERO",new R(0)),f(R,"z",s.z.union([s.z.object({value:s.z.bigint()}).transform(r=>new R(r.value)),s.z.string().transform(r=>new R(BigInt(r))),s.z.instanceof(Number).transform(r=>new R(r)),s.z.number().transform(r=>new R(r)),s.z.instanceof(R)]));let S=R;const C=class I{constructor(e){f(this,"value"),f(this,"encodeValue",!0),typeof e=="number"&&(e=Math.trunc(e.valueOf())),this.value=BigInt(e.valueOf())}encode(){return this.value.toString()}valueOf(){return this.value}lessThan(e){return this.valueOf()<new I(e).valueOf()}greaterThan(e){return this.valueOf()>new I(e).valueOf()}lessThanOrEqual(e){return this.valueOf()<=new I(e).valueOf()}greaterThanOrEqual(e){return this.valueOf()>=new I(e).valueOf()}remainder(e){return Ds(this,e)}truncate(e){return new I(BigInt(Math.trunc(Number(this.valueOf()/e.valueOf())))*e.valueOf())}toString(){const e=this.truncate(I.DAY),t=this.truncate(I.HOUR),n=this.truncate(I.MINUTE),i=this.truncate(I.SECOND),a=this.truncate(I.MILLISECOND),c=this.truncate(I.MICROSECOND),l=this.truncate(I.NANOSECOND),u=e,h=t.sub(e),p=n.sub(t),g=i.sub(n),D=a.sub(i),P=c.sub(a),X=l.sub(c);let j="";return u.isZero||(j+=`${u.days}d `),h.isZero||(j+=`${h.hours}h `),p.isZero||(j+=`${p.minutes}m `),g.isZero||(j+=`${g.seconds}s `),D.isZero||(j+=`${D.milliseconds}ms `),P.isZero||(j+=`${P.microseconds}µs `),X.isZero||(j+=`${X.nanoseconds}ns`),j.trim()}get days(){return Number(this.valueOf())/Number(I.DAY.valueOf())}get hours(){return Number(this.valueOf())/Number(I.HOUR.valueOf())}get minutes(){return Number(this.valueOf())/Number(I.MINUTE.valueOf())}get seconds(){return Number(this.valueOf())/Number(I.SECOND.valueOf())}get milliseconds(){return Number(this.valueOf())/Number(I.MILLISECOND.valueOf())}get microseconds(){return Number(this.valueOf())/Number(I.MICROSECOND.valueOf())}get nanoseconds(){return Number(this.valueOf())}get isZero(){return this.valueOf()===BigInt(0)}equals(e){return this.valueOf()===new I(e).valueOf()}add(e){return new I(this.valueOf()+new I(e).valueOf())}sub(e){return new I(this.valueOf()-new I(e).valueOf())}static nanoseconds(e=1){return new I(e)}static microseconds(e=1){return I.nanoseconds(e*1e3)}static milliseconds(e=1){return I.microseconds(e*1e3)}static seconds(e=1){return I.milliseconds(e*1e3)}static minutes(e){return I.seconds(e.valueOf()*60)}static hours(e){return I.minutes(e*60)}static days(e){return I.hours(e*24)}};f(C,"NANOSECOND",C.nanoseconds(1)),f(C,"MICROSECOND",C.microseconds(1)),f(C,"MILLISECOND",C.milliseconds(1)),f(C,"SECOND",C.seconds(1)),f(C,"MINUTE",C.minutes(1)),f(C,"HOUR",C.hours(1)),f(C,"DAY",C.days(1)),f(C,"MAX",new C((1n<<63n)-1n)),f(C,"MIN",new C(0)),f(C,"ZERO",new C(0)),f(C,"z",s.z.union([s.z.object({value:s.z.bigint()}).transform(r=>new C(r.value)),s.z.string().transform(r=>new C(BigInt(r))),s.z.instanceof(Number).transform(r=>new C(r)),s.z.number().transform(r=>new C(r)),s.z.instanceof(C)]));let E=C;const at=class Lt extends Number{constructor(e){e instanceof Number?super(e.valueOf()):super(e)}toString(){return`${this.valueOf()} Hz`}equals(e){return this.valueOf()===new Lt(e).valueOf()}get period(){return E.seconds(1/this.valueOf())}sampleCount(e){return new E(e).seconds*this.valueOf()}byteCount(e,t){return this.sampleCount(e)*new F(t).valueOf()}span(e){return E.seconds(e/this.valueOf())}byteSpan(e,t){return this.span(e.valueOf()/t.valueOf())}static hz(e){return new Lt(e)}static khz(e){return Lt.hz(e*1e3)}};f(at,"z",s.z.union([s.z.number().transform(r=>new at(r)),s.z.instanceof(Number).transform(r=>new at(r)),s.z.instanceof(at)]));let tr=at;const L=class extends Number{constructor(e){e instanceof Number?super(e.valueOf()):super(e)}length(e){return e.valueOf()/this.valueOf()}size(e){return new pt(e*this.valueOf())}};f(L,"UNKNOWN",new L(0)),f(L,"BIT128",new L(16)),f(L,"BIT64",new L(8)),f(L,"BIT32",new L(4)),f(L,"BIT16",new L(2)),f(L,"BIT8",new L(1)),f(L,"z",s.z.union([s.z.number().transform(r=>new L(r)),s.z.instanceof(Number).transform(r=>new L(r)),s.z.instanceof(L)]));let F=L;const se=class qt{constructor(e,t){f(this,"start"),f(this,"end"),typeof e=="object"&&"start"in e?(this.start=new S(e.start),this.end=new S(e.end)):(this.start=new S(e),this.end=new S(t))}get span(){return new E(this.end.valueOf()-this.start.valueOf())}get isValid(){return this.start.valueOf()<=this.end.valueOf()}makeValid(){return this.isValid?this:this.swap()}get isZero(){return this.span.isZero}get numeric(){return{start:Number(this.start.valueOf()),end:Number(this.end.valueOf())}}swap(){return new qt(this.end,this.start)}equals(e){return this.start.equals(e.start)&&this.end.equals(e.end)}toString(){return`${this.start.toString()} - ${this.end.toString()}`}toPrettyString(){return`${this.start.fString("preciseDate")} - ${this.span.toString()}`}overlapsWith(e,t=E.ZERO){e=e.makeValid();const n=this.makeValid();if(this.equals(e))return!0;if(e.end.equals(n.start)||n.end.equals(e.start))return!1;const i=S.max(n.start,e.start),a=S.min(n.end,e.end);return a.before(i)?!1:new E(a.sub(i)).greaterThanOrEqual(t)}roughlyEquals(e,t){let n=this.start.sub(e.start).valueOf(),i=this.end.sub(e.end).valueOf();return n<0&&(n=-n),i<0&&(i=-i),n<=t.valueOf()&&i<=t.valueOf()}contains(e){return e instanceof qt?this.contains(e.start)&&this.contains(e.end):this.start.beforeEq(e)&&this.end.after(e)}boundBy(e){const t=new qt(this.start,this.end);return e.start.after(this.start)&&(t.start=e.start),e.start.after(this.end)&&(t.end=e.start),e.end.before(this.end)&&(t.end=e.end),e.end.before(this.start)&&(t.start=e.end),t}};f(se,"MAX",new se(S.MIN,S.MAX)),f(se,"MIN",new se(S.MAX,S.MIN)),f(se,"ZERO",new se(S.ZERO,S.ZERO)),f(se,"z",s.z.union([s.z.object({start:S.z,end:S.z}).transform(r=>new se(r.start,r.end)),s.z.instanceof(se)]));let W=se;const y=class ie extends String{constructor(e){if(e instanceof ie||typeof e=="string"||typeof e.valueOf()=="string"){super(e.valueOf());return}else{const t=ie.ARRAY_CONSTRUCTOR_DATA_TYPES.get(e.constructor.name);if(t!=null){super(t.valueOf());return}}throw super(ie.UNKNOWN.valueOf()),new Error(`unable to find data type for ${e.toString()}`)}get Array(){const e=ie.ARRAY_CONSTRUCTORS.get(this.toString());if(e==null)throw new Error(`unable to find array constructor for ${this.valueOf()}`);return e}equals(e){return this.valueOf()===e.valueOf()}matches(...e){return e.some(t=>this.equals(t))}toString(){return this.valueOf()}get isVariable(){return this.equals(ie.JSON)||this.equals(ie.STRING)}get isNumeric(){return!this.isVariable&&!this.equals(ie.UUID)}get isInteger(){return this.toString().startsWith("int")}get isFloat(){return this.toString().startsWith("float")}get density(){const e=ie.DENSITIES.get(this.toString());if(e==null)throw new Error(`unable to find density for ${this.valueOf()}`);return e}canSafelyCastTo(e){return this.equals(e)?!0:this.isVariable&&!e.isVariable||!this.isVariable&&e.isVariable?!1:this.isFloat&&e.isInteger||this.isInteger&&e.isFloat?this.density.valueOf()<e.density.valueOf():this.isFloat&&e.isFloat||this.isInteger&&e.isInteger?this.density.valueOf()<=e.density.valueOf():!1}canCastTo(e){return this.isNumeric&&e.isNumeric?!0:this.equals(e)}checkArray(e){return e.constructor===this.Array}toJSON(){return this.toString()}get usesBigInt(){return ie.BIG_INT_TYPES.some(e=>e.equals(this))}};f(y,"UNKNOWN",new y("unknown")),f(y,"FLOAT64",new y("float64")),f(y,"FLOAT32",new y("float32")),f(y,"INT64",new y("int64")),f(y,"INT32",new y("int32")),f(y,"INT16",new y("int16")),f(y,"INT8",new y("int8")),f(y,"UINT64",new y("uint64")),f(y,"UINT32",new y("uint32")),f(y,"UINT16",new y("uint16")),f(y,"UINT8",new y("uint8")),f(y,"BOOLEAN",y.UINT8),f(y,"TIMESTAMP",new y("timestamp")),f(y,"UUID",new y("uuid")),f(y,"STRING",new y("string")),f(y,"JSON",new y("json")),f(y,"ARRAY_CONSTRUCTORS",new Map([[y.UINT8.toString(),Uint8Array],[y.UINT16.toString(),Uint16Array],[y.UINT32.toString(),Uint32Array],[y.UINT64.toString(),BigUint64Array],[y.FLOAT32.toString(),Float32Array],[y.FLOAT64.toString(),Float64Array],[y.INT8.toString(),Int8Array],[y.INT16.toString(),Int16Array],[y.INT32.toString(),Int32Array],[y.INT64.toString(),BigInt64Array],[y.TIMESTAMP.toString(),BigInt64Array],[y.STRING.toString(),Uint8Array],[y.JSON.toString(),Uint8Array],[y.UUID.toString(),Uint8Array]])),f(y,"ARRAY_CONSTRUCTOR_DATA_TYPES",new Map([[Uint8Array.name,y.UINT8],[Uint16Array.name,y.UINT16],[Uint32Array.name,y.UINT32],[BigUint64Array.name,y.UINT64],[Float32Array.name,y.FLOAT32],[Float64Array.name,y.FLOAT64],[Int8Array.name,y.INT8],[Int16Array.name,y.INT16],[Int32Array.name,y.INT32],[BigInt64Array.name,y.INT64]])),f(y,"DENSITIES",new Map([[y.UINT8.toString(),F.BIT8],[y.UINT16.toString(),F.BIT16],[y.UINT32.toString(),F.BIT32],[y.UINT64.toString(),F.BIT64],[y.FLOAT32.toString(),F.BIT32],[y.FLOAT64.toString(),F.BIT64],[y.INT8.toString(),F.BIT8],[y.INT16.toString(),F.BIT16],[y.INT32.toString(),F.BIT32],[y.INT64.toString(),F.BIT64],[y.TIMESTAMP.toString(),F.BIT64],[y.STRING.toString(),F.UNKNOWN],[y.JSON.toString(),F.UNKNOWN],[y.UUID.toString(),F.BIT128]])),f(y,"ALL",[y.UNKNOWN,y.FLOAT64,y.FLOAT32,y.INT64,y.INT32,y.INT16,y.INT8,y.UINT64,y.UINT32,y.UINT16,y.UINT8,y.TIMESTAMP,y.UUID,y.STRING,y.JSON]),f(y,"BIG_INT_TYPES",[y.INT64,y.UINT64,y.TIMESTAMP]),f(y,"z",s.z.union([s.z.string().transform(r=>new y(r)),s.z.instanceof(y)]));let z=y;const V=class Z extends Number{constructor(e){super(e.valueOf())}largerThan(e){return this.valueOf()>e.valueOf()}smallerThan(e){return this.valueOf()<e.valueOf()}add(e){return Z.bytes(this.valueOf()+e.valueOf())}sub(e){return Z.bytes(this.valueOf()-e.valueOf())}truncate(e){return new Z(Math.trunc(this.valueOf()/e.valueOf())*e.valueOf())}remainder(e){return Z.bytes(this.valueOf()%e.valueOf())}get gigabytes(){return this.valueOf()/Z.GIGABYTE.valueOf()}get megabytes(){return this.valueOf()/Z.MEGABYTE.valueOf()}get kilobytes(){return this.valueOf()/Z.KILOBYTE.valueOf()}get terabytes(){return this.valueOf()/Z.TERABYTE.valueOf()}toString(){const e=this.truncate(Z.TERABYTE),t=this.truncate(Z.GIGABYTE),n=this.truncate(Z.MEGABYTE),i=this.truncate(Z.KILOBYTE),a=this.truncate(Z.BYTE),c=e,l=t.sub(e),u=n.sub(t),h=i.sub(n),p=a.sub(i);let g="";return c.isZero||(g+=`${c.terabytes}TB `),l.isZero||(g+=`${l.gigabytes}GB `),u.isZero||(g+=`${u.megabytes}MB `),h.isZero||(g+=`${h.kilobytes}KB `),(!p.isZero||g==="")&&(g+=`${p.valueOf()}B`),g.trim()}static bytes(e=1){return new Z(e)}static kilobytes(e=1){return Z.bytes(e.valueOf()*1e3)}static megabytes(e=1){return Z.kilobytes(e.valueOf()*1e3)}static gigabytes(e=1){return Z.megabytes(e.valueOf()*1e3)}static terabytes(e){return Z.gigabytes(e.valueOf()*1e3)}get isZero(){return this.valueOf()===0}};f(V,"BYTE",new V(1)),f(V,"KILOBYTE",V.kilobytes(1)),f(V,"MEGABYTE",V.megabytes(1)),f(V,"GIGABYTE",V.gigabytes(1)),f(V,"TERABYTE",V.terabytes(1)),f(V,"ZERO",new V(0)),f(V,"z",s.z.union([s.z.number().transform(r=>new V(r)),s.z.instanceof(V)]));let pt=V;s.z.union([s.z.instanceof(Uint8Array),s.z.instanceof(Uint16Array),s.z.instanceof(Uint32Array),s.z.instanceof(BigUint64Array),s.z.instanceof(Float32Array),s.z.instanceof(Float64Array),s.z.instanceof(Int8Array),s.z.instanceof(Int16Array),s.z.instanceof(Int32Array),s.z.instanceof(BigInt64Array)]);const js=r=>{const e=typeof r;return e==="string"||e==="number"||e==="boolean"||e==="bigint"||r instanceof S||r instanceof E||r instanceof Date},oc=(r,e,t,n=0)=>r.usesBigInt&&!e.usesBigInt?Number(t)-Number(n):!r.usesBigInt&&e.usesBigInt?BigInt(t)-BigInt(n):ot(t,-n),cc=r=>r==null?!1:Array.isArray(r)||r instanceof ArrayBuffer||ArrayBuffer.isView(r)&&!(r instanceof DataView)||r instanceof ze?!0:js(r),Te=-1;let ze=class le{constructor(e){f(this,"key",""),f(this,"isSynnaxSeries",!0),f(this,"dataType"),f(this,"sampleOffset"),f(this,"gl"),f(this,"_data"),f(this,"_timeRange"),f(this,"alignment",0n),f(this,"_cachedMin"),f(this,"_cachedMax"),f(this,"writePos",Te),f(this,"_refCount",0),f(this,"_cachedLength"),cc(e)&&(e={data:e});const{dataType:t,timeRange:n,sampleOffset:i=0,glBufferUsage:a="static",alignment:c=0n,key:l=Ps()}=e,{data:u}=e;if(u instanceof le||typeof u=="object"&&"isSynnaxSeries"in u&&u.isSynnaxSeries===!0){const g=u;this.key=g.key,this.dataType=g.dataType,this.sampleOffset=g.sampleOffset,this.gl=g.gl,this._data=g._data,this._timeRange=g._timeRange,this.alignment=g.alignment,this._cachedMin=g._cachedMin,this._cachedMax=g._cachedMax,this.writePos=g.writePos,this._refCount=g._refCount,this._cachedLength=g._cachedLength;return}const h=js(u),p=Array.isArray(u);if(t!=null)this.dataType=new z(t);else{if(u instanceof ArrayBuffer)throw new Error("cannot infer data type from an ArrayBuffer instance when constructing a Series. Please provide a data type.");if(p||h){let g=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.");g=u[0]}if(typeof g=="string")this.dataType=z.STRING;else if(typeof g=="number")this.dataType=z.FLOAT64;else if(typeof g=="bigint")this.dataType=z.INT64;else if(typeof g=="boolean")this.dataType=z.BOOLEAN;else if(g instanceof S||g instanceof Date||g instanceof S)this.dataType=z.TIMESTAMP;else if(typeof g=="object")this.dataType=z.JSON;else throw new Error(`cannot infer data type of ${typeof g} when constructing a Series from a JS array`)}else this.dataType=new z(u)}if(!p&&!h)this._data=u;else{let g=h?[u]:u;const D=g[0];(D instanceof S||D instanceof Date||D instanceof E)&&(g=g.map(P=>new S(P).valueOf())),this.dataType.equals(z.STRING)?(this._cachedLength=g.length,this._data=new TextEncoder().encode(g.join(`
6
6
  `)+`
7
- `)):this.dataType.equals(z.JSON)?(this._cachedLength=p.length,this._data=new TextEncoder().encode(p.map(P=>Ke.encodeString(P)).join(`
7
+ `)):this.dataType.equals(z.JSON)?(this._cachedLength=g.length,this._data=new TextEncoder().encode(g.map(P=>Ke.encodeString(P)).join(`
8
8
  `)+`
9
- `)):this._data=new this.dataType.Array(p).buffer}this.key=l,this.alignment=c,this.sampleOffset=i??0,this._timeRange=n,this.gl={control:null,buffer:null,prevBuffer:0,bufferUsage:a}}static alloc({capacity:e,dataType:t,...n}){if(e===0)throw new Error("[Series] - cannot allocate an array of length 0");const i=new new z(t).Array(e),a=new le({data:i.buffer,dataType:t,...n});return a.writePos=0,a}static generateTimestamps(e,t,n){const i=n.spanRange(t.span(e)),a=new BigInt64Array(e);for(let c=0;c<e;c++)a[c]=BigInt(n.add(t.span(c)).valueOf());return new le({data:a,dataType:z.TIMESTAMP,timeRange:i})}get refCount(){return this._refCount}static fromStrings(e,t){const n=new TextEncoder().encode(e.join(`
9
+ `)):this._data=new this.dataType.Array(g).buffer}this.key=l,this.alignment=c,this.sampleOffset=i??0,this._timeRange=n,this.gl={control:null,buffer:null,prevBuffer:0,bufferUsage:a}}static alloc({capacity:e,dataType:t,...n}){if(e===0)throw new Error("[Series] - cannot allocate an array of length 0");const i=new new z(t).Array(e),a=new le({data:i.buffer,dataType:t,...n});return a.writePos=0,a}static generateTimestamps(e,t,n){const i=n.spanRange(t.span(e)),a=new BigInt64Array(e);for(let c=0;c<e;c++)a[c]=BigInt(n.add(t.span(c)).valueOf());return new le({data:a,dataType:z.TIMESTAMP,timeRange:i})}get refCount(){return this._refCount}static fromStrings(e,t){const n=new TextEncoder().encode(e.join(`
10
10
  `)+`
11
11
  `);return new le({data:n,dataType:z.STRING,timeRange:t})}static fromJSON(e,t){const n=new TextEncoder().encode(e.map(i=>Ke.encodeString(i)).join(`
12
12
  `)+`
13
13
  `);return new le({data:n,dataType:z.JSON,timeRange:t})}acquire(e){this._refCount++,e!=null&&this.updateGLBuffer(e)}release(){if(this._refCount--,this._refCount===0&&this.gl.control!=null)this.maybeGarbageCollectGLBuffer(this.gl.control);else if(this._refCount<0)throw new Error("cannot release an array with a negative reference count")}write(e){if(!e.dataType.equals(this.dataType))throw new Error("buffer must be of the same type as this array");if(this.writePos===Te)return 0;const t=this.capacity-this.writePos,n=t<e.length?e.slice(0,t):e;return this.underlyingData.set(n.data,this.writePos),this.maybeRecomputeMinMax(n),this._cachedLength=void 0,this.writePos+=n.length,n.length}get buffer(){return this._data}get underlyingData(){return new this.dataType.Array(this._data)}get data(){return this.writePos===Te?this.underlyingData:new this.dataType.Array(this._data,0,this.writePos)}toStrings(){if(!this.dataType.matches(z.STRING,z.UUID))throw new Error("cannot convert non-string series to strings");return new TextDecoder().decode(this.buffer).split(`
14
14
  `).slice(0,-1)}toUUIDs(){if(!this.dataType.equals(z.UUID))throw new Error("cannot convert non-uuid series to uuids");const e=z.UUID.density.valueOf(),t=Array(this.length);for(let n=0;n<this.length;n++){const i=this.buffer.slice(n*e,(n+1)*e),a=Array.from(new Uint8Array(i),c=>c.toString(16).padStart(2,"0")).join("").replace(/(.{8})(.{4})(.{4})(.{4})(.{12})/,"$1-$2-$3-$4-$5");t[n]=a}return t}parseJSON(e){if(!this.dataType.equals(z.JSON))throw new Error("cannot convert non-string series to strings");return new TextDecoder().decode(this.buffer).split(`
15
- `).slice(0,-1).map(t=>e.parse(Ke.decodeString(t)))}get timeRange(){if(this._timeRange==null)throw new Error("time range not set on series");return this._timeRange}get byteCapacity(){return new pt(this.buffer.byteLength)}get capacity(){return this.dataType.density.length(this.byteCapacity)}get byteLength(){return this.writePos===Te?this.byteCapacity:this.dataType.density.size(this.writePos)}get length(){return this._cachedLength!=null?this._cachedLength:this.dataType.isVariable?this.calculateCachedLength():this.writePos===Te?this.data.length:this.writePos}calculateCachedLength(){if(!this.dataType.isVariable)throw new Error("cannot calculate length of a non-variable length data type");let e=0;return this.data.forEach(t=>{t===10&&e++}),this._cachedLength=e,e}convert(e,t=0){if(this.dataType.equals(e))return this;const n=new e.Array(this.length);for(let i=0;i<this.length;i++)n[i]=Go(this.dataType,e,this.data[i],t);return new le({data:n.buffer,dataType:e,timeRange:this._timeRange,sampleOffset:t,glBufferUsage:this.gl.bufferUsage,alignment:this.alignment})}calcRawMax(){if(this.length===0)return-1/0;if(this.dataType.equals(z.TIMESTAMP))this._cachedMax=this.data[this.data.length-1];else if(this.dataType.usesBigInt){const e=this.data;this._cachedMax=e.reduce((t,n)=>t>n?t:n)}else{const e=this.data;this._cachedMax=e.reduce((t,n)=>t>n?t:n)}return this._cachedMax}get max(){if(this.dataType.isVariable)throw new Error("cannot calculate maximum on a variable length data type");return this.writePos===0?-1/0:(this._cachedMax==null&&(this._cachedMax=this.calcRawMax()),ot(this._cachedMax,this.sampleOffset))}calcRawMin(){if(this.length===0)return 1/0;if(this.dataType.equals(z.TIMESTAMP))this._cachedMin=this.data[0];else if(this.dataType.usesBigInt){const e=this.data;this._cachedMin=e.reduce((t,n)=>t<n?t:n)}else{const e=this.data;this._cachedMin=e.reduce((t,n)=>t<n?t:n)}return this._cachedMin}get min(){if(this.dataType.isVariable)throw new Error("cannot calculate minimum on a variable length data type");return this.writePos===0?1/0:(this._cachedMin==null&&(this._cachedMin=this.calcRawMin()),ot(this._cachedMin,this.sampleOffset))}get bounds(){return yt(Number(this.min),Number(this.max))}maybeRecomputeMinMax(e){if(this._cachedMin!=null){const t=e._cachedMin??e.calcRawMin();t<this._cachedMin&&(this._cachedMin=t)}if(this._cachedMax!=null){const t=e._cachedMax??e.calcRawMax();t>this._cachedMax&&(this._cachedMax=t)}}enrich(){this.max,this.min}get range(){return ot(this.max,-this.min)}at(e,t){if(this.dataType.isVariable)return this.atVariable(e,t??!1);e<0&&(e=this.length+e);const n=this.data[e];if(n==null){if(t===!0)throw new Error(`[series] - no value at index ${e}`);return}return ot(n,this.sampleOffset)}atVariable(e,t){e<0&&(e=this.length+e);let n=0,i=0;for(let c=0;c<this.data.length;c++)if(this.data[c]===10){if(e===0){i=c;break}n=c+1,e--}if(i===0&&(i=this.data.length),n>=i||e>0){if(t)throw new Error(`[series] - no value at index ${e}`);return}const a=this.data.slice(n,i);return this.dataType.equals(z.STRING)?new TextDecoder().decode(a):fs(JSON.parse(new TextDecoder().decode(a)))}binarySearch(e){let t=0,n=this.length-1;const i=fo(e);for(;t<=n;){const a=Math.floor((t+n)/2),c=i(this.at(a,!0),e);if(c===0)return a;c<0?t=a+1:n=a-1}return t}updateGLBuffer(e){if(this.gl.control=e,!this.dataType.equals(z.FLOAT32))throw new Error("Only FLOAT32 arrays can be used in WebGL");const{buffer:t,bufferUsage:n,prevBuffer:i}=this.gl;if(t==null&&(this.gl.buffer=e.createBuffer()),this.writePos!==i)if(e.bindBuffer(e.ARRAY_BUFFER,this.gl.buffer),this.writePos!==Te){i===0&&e.bufferData(e.ARRAY_BUFFER,this.byteCapacity.valueOf(),e.STATIC_DRAW);const a=this.dataType.density.size(i).valueOf(),c=this.underlyingData.slice(this.gl.prevBuffer,this.writePos);e.bufferSubData(e.ARRAY_BUFFER,a,c.buffer),this.gl.prevBuffer=this.writePos}else e.bufferData(e.ARRAY_BUFFER,this.buffer,n==="static"?e.STATIC_DRAW:e.DYNAMIC_DRAW),this.gl.prevBuffer=Te}as(e){if(e==="string"){if(!this.dataType.equals(z.STRING))throw new Error(`cannot convert series of type ${this.dataType.toString()} to string`);return this}if(e==="number"){if(!this.dataType.isNumeric)throw new Error(`cannot convert series of type ${this.dataType.toString()} to number`);return this}if(e==="bigint"){if(!this.dataType.equals(z.INT64))throw new Error(`cannot convert series of type ${this.dataType.toString()} to bigint`);return this}throw new Error(`cannot convert series to ${e}`)}get digest(){var e;return{key:this.key,dataType:this.dataType.toString(),sampleOffset:this.sampleOffset,alignment:this.alignmentBounds,timeRange:(e=this._timeRange)==null?void 0:e.toString(),length:this.length,capacity:this.capacity}}get memInfo(){return{key:this.key,length:this.length,byteLength:this.byteLength,glBuffer:this.gl.buffer!=null}}get alignmentBounds(){return yt(this.alignment,this.alignment+BigInt(this.length))}maybeGarbageCollectGLBuffer(e){this.gl.buffer!=null&&(e.deleteBuffer(this.gl.buffer),this.gl.buffer=null,this.gl.prevBuffer=0,this.gl.control=null)}get glBuffer(){if(this.gl.buffer==null)throw new Error("gl buffer not initialized");return this.gl.prevBuffer!==this.writePos&&console.warn("buffer not updated"),this.gl.buffer}[Symbol.iterator](){if(this.dataType.isVariable){const e=new Jo(this);return this.dataType.equals(z.JSON)?new Ho(e):e}return new Xo(this)}slice(e,t){if(e<=0&&(t==null||t>=this.length))return this;const n=this.data.slice(e,t);return new le({data:n,dataType:this.dataType,timeRange:this._timeRange,sampleOffset:this.sampleOffset,glBufferUsage:this.gl.bufferUsage,alignment:this.alignment+BigInt(e)})}reAlign(e){return new le({data:this.buffer,dataType:this.dataType,timeRange:W.ZERO,sampleOffset:this.sampleOffset,glBufferUsage:"static",alignment:e})}};class Jo{constructor(e){if(d(this,"series"),d(this,"index"),d(this,"decoder"),!e.dataType.isVariable)throw new Error("cannot create a variable series iterator for a non-variable series");this.series=e,this.index=0,this.decoder=new TextDecoder}next(){const e=this.index,t=this.series.data;for(;this.index<t.length&&t[this.index]!==10;)this.index++;const n=this.index;return e===n?{done:!0,value:void 0}:(this.index++,{done:!1,value:this.decoder.decode(this.series.buffer.slice(e,n))})}[Symbol.iterator](){return this}}var Sn,Nn;class Ho{constructor(e){d(this,"wrapped"),d(this,Sn,"JSONSeriesIterator"),this.wrapped=e}next(){const e=this.wrapped.next();return e.done===!0?{done:!0,value:void 0}:{done:!1,value:Ke.decodeString(e.value)}}[(Nn=Symbol.iterator,Sn=Symbol.toStringTag,Nn)](){return this}}var In,kn;class Xo{constructor(e){d(this,"series"),d(this,"index"),d(this,In,"SeriesIterator"),this.series=e,this.index=0}next(){return this.index>=this.series.length?{done:!0,value:void 0}:{done:!1,value:this.series.at(this.index++,!0)}}[(kn=Symbol.iterator,In=Symbol.toStringTag,kn)](){return this}}const ot=(r,e)=>typeof r=="bigint"&&typeof e=="bigint"||typeof r=="number"&&typeof e=="number"?r+e:e===0?r:r===0?e:Number(r)+Number(e);class ks{constructor(e){if(d(this,"series"),e.length!==0){const t=e[0].dataType;for(let n=1;n<e.length;n++)if(!e[n].dataType.equals(t))throw new Error("[multi-series] - series must have the same data type")}this.series=e}as(e){if(!new z(e).equals(this.dataType))throw new Error(`cannot convert series of type ${this.dataType.toString()} to ${e.toString()}`);return this}get dataType(){return this.series.length===0?z.UNKNOWN:this.series[0].dataType}get timeRange(){return this.series.length===0?W.ZERO:new W(this.series[0].timeRange.start,this.series[this.series.length-1].timeRange.end)}push(e){this.series.push(e)}get length(){return this.series.reduce((e,t)=>e+t.length,0)}at(e,t=!1){e<0&&(e=this.length+e);for(const n of this.series){if(e<n.length)return n.at(e,t);e-=n.length}if(t)throw new Error(`[series] - no value at index ${e}`)}get byteLength(){return new pt(this.series.reduce((e,t)=>e+t.byteLength.valueOf(),0))}get data(){const e=new this.dataType.Array(this.length);let t=0;for(const n of this.series)e.set(n.data,t),t+=n.length;return new this.dataType.Array(e)}[Symbol.iterator](){return this.series.length===0?{next(){return{done:!0,value:void 0}}}:new Qo(this.series)}}var An,$n;class Qo{constructor(e){d(this,"series"),d(this,"seriesIndex"),d(this,"internal"),d(this,An,"MultiSeriesIterator"),this.series=e,this.seriesIndex=0,this.internal=e[0][Symbol.iterator]()}next(){const e=this.internal.next();return e.done===!1?e:this.seriesIndex===this.series.length-1?{done:!0,value:void 0}:(this.internal=this.series[++this.seriesIndex][Symbol.iterator](),this.next())}[($n=Symbol.iterator,An=Symbol.toStringTag,$n)](){return this}}const O=r=>Array.isArray(r)?r:[r],ec=(r,e)=>{let t=null;return e===0?r:(...n)=>{t!==null&&(clearTimeout(t),t=null),t=setTimeout(()=>r(...n),e)}};s.z.object({key:s.z.string(),value:s.z.string()});var tc=Object.defineProperty,rc=(r,e,t)=>e in r?tc(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,Bt=(r,e,t)=>rc(r,typeof e!="symbol"?e+"":e,t);let nc=class{constructor(e,t){Bt(this,"handlers"),Bt(this,"transform"),Bt(this,"closer"),this.transform=e,this.handlers=t??new Map}onChange(e){return this.handlers.set(e,null),()=>this.handlers.delete(e)}notify(e){let t=e;if(this.transform!=null){const[n,i]=this.transform(e);if(!i)return;t=n}this.handlers.forEach((n,i)=>i(t))}setCloser(e){this.closer=e}async close(){var e;return await((e=this.closer)==null?void 0:e.call(this))}},sc=class{constructor(e){Bt(this,"handlers"),this.handlers=e??new Map}onChange(e){return this.handlers.set(e,null),()=>this.handlers.delete(e)}notify(e){this.handlers.forEach((t,n)=>n(e))}};const Ie=Object.freeze(Object.defineProperty({__proto__:null,BaseObserver:sc,Observer:nc},Symbol.toStringTag,{value:"Module"})),qr=s.z.record(s.z.union([s.z.number(),s.z.string(),s.z.symbol()]),s.z.unknown()),ic=()=>typeof process<"u"&&process.versions!=null&&process.versions.node!=null?"node":typeof window>"u"||window.document===void 0?"webworker":"browser";ic();const ac=["MacOS","Windows","Linux","Docker"];s.z.enum(ac);const Rn=r=>[...new Set(r)];var oc=Object.defineProperty,cc=(r,e,t)=>e in r?oc(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,ct=(r,e,t)=>cc(r,typeof e!="symbol"?e+"":e,t);const lc=(...r)=>r.map(As).join(""),As=r=>(r.endsWith("/")||(r+="/"),r.startsWith("/")&&(r=r.slice(1)),r),uc=r=>r.endsWith("/")?r.slice(0,-1):r,xr=class Cr{constructor({host:e,port:t,protocol:n="",pathPrefix:i=""}){ct(this,"protocol"),ct(this,"host"),ct(this,"port"),ct(this,"path"),this.protocol=n,this.host=e,this.port=t,this.path=As(i)}replace(e){return new Cr({host:e.host??this.host,port:e.port??this.port,protocol:e.protocol??this.protocol,pathPrefix:e.pathPrefix??this.path})}child(e){return new Cr({...this,pathPrefix:lc(this.path,e)})}toString(){return uc(`${this.protocol}://${this.host}:${this.port}/${this.path}`)}};ct(xr,"UNKNOWN",new xr({host:"unknown",port:0}));let hc=xr;var yc=Object.defineProperty,dc=(r,e,t)=>e in r?yc(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,Lt=(r,e,t)=>dc(r,typeof e!="symbol"?e+"":e,t);const Oe=class extends Number{};Lt(Oe,"Absolute",255),Lt(Oe,"Default",1),Lt(Oe,"z",s.z.union([s.z.instanceof(Oe),s.z.number().int().min(0).max(255).transform(r=>new Oe(r)),s.z.instanceof(Number).transform(r=>new Oe(r))]));let $s=Oe;const Rs=s.z.object({name:s.z.string(),key:s.z.string()}),fc=r=>s.z.object({subject:Rs,resource:r,authority:$s.z}),pc=(...r)=>e=>e.filter(t=>{let n=!1;return t.to!=null&&(n=r.includes(t.to.resource)),t.from!=null&&!n&&(n=r.includes(t.from.resource)),n}),Ve=Object.freeze(Object.defineProperty({__proto__:null,Authority:$s,filterTransfersByChannelKey:pc,stateZ:fc,subjectZ:Rs},Symbol.toStringTag,{value:"Module"})),xs=class lt extends Error{constructor(){super(lt.MESSAGE)}matches(e){return typeof e=="string"?e.includes(lt.MESSAGE):e instanceof lt||e.message.includes(lt.MESSAGE)}};Lt(xs,"MESSAGE","canceled");let gc=xs;new gc;s.z.string().regex(/^\d+\.\d+\.\d+$/);const me="sy.",Ce=class Ce extends te{constructor(){super(...arguments);o(this,"type",Ce.TYPE)}};o(Ce,"TYPE",me+"validation"),o(Ce,"matches",J(Ce.TYPE));let C=Ce;const Pe=class Pe extends C{constructor(t,n){super(t+": "+n);o(this,"type",Pe.TYPE);o(this,"field");o(this,"message");this.field=t,this.message=n}};o(Pe,"TYPE",C.TYPE+".field"),o(Pe,"matches",J(Pe.TYPE));let _t=Pe;const je=class je extends te{constructor(){super(...arguments);o(this,"type",je.TYPE)}};o(je,"TYPE",me+"auth"),o(je,"matches",J(je.TYPE));let ke=je;const De=class De extends ke{constructor(){super(...arguments);o(this,"type",De.TYPE)}};o(De,"TYPE",ke.TYPE+".invalid-token"),o(De,"matches",J(De.TYPE));let gt=De;const Me=class Me extends te{constructor(t){super(`
15
+ `).slice(0,-1).map(t=>e.parse(Ke.decodeString(t)))}get timeRange(){if(this._timeRange==null)throw new Error("time range not set on series");return this._timeRange}get byteCapacity(){return new pt(this.buffer.byteLength)}get capacity(){return this.dataType.density.length(this.byteCapacity)}get byteLength(){return this.writePos===Te?this.byteCapacity:this.dataType.density.size(this.writePos)}get length(){return this._cachedLength!=null?this._cachedLength:this.dataType.isVariable?this.calculateCachedLength():this.writePos===Te?this.data.length:this.writePos}calculateCachedLength(){if(!this.dataType.isVariable)throw new Error("cannot calculate length of a non-variable length data type");let e=0;return this.data.forEach(t=>{t===10&&e++}),this._cachedLength=e,e}convert(e,t=0){if(this.dataType.equals(e))return this;const n=new e.Array(this.length);for(let i=0;i<this.length;i++)n[i]=oc(this.dataType,e,this.data[i],t);return new le({data:n.buffer,dataType:e,timeRange:this._timeRange,sampleOffset:t,glBufferUsage:this.gl.bufferUsage,alignment:this.alignment})}calcRawMax(){if(this.length===0)return-1/0;if(this.dataType.equals(z.TIMESTAMP))this._cachedMax=this.data[this.data.length-1];else if(this.dataType.usesBigInt){const e=this.data;this._cachedMax=e.reduce((t,n)=>t>n?t:n)}else{const e=this.data;this._cachedMax=e.reduce((t,n)=>t>n?t:n)}return this._cachedMax}get max(){if(this.dataType.isVariable)throw new Error("cannot calculate maximum on a variable length data type");return this.writePos===0?-1/0:(this._cachedMax==null&&(this._cachedMax=this.calcRawMax()),ot(this._cachedMax,this.sampleOffset))}calcRawMin(){if(this.length===0)return 1/0;if(this.dataType.equals(z.TIMESTAMP))this._cachedMin=this.data[0];else if(this.dataType.usesBigInt){const e=this.data;this._cachedMin=e.reduce((t,n)=>t<n?t:n)}else{const e=this.data;this._cachedMin=e.reduce((t,n)=>t<n?t:n)}return this._cachedMin}get min(){if(this.dataType.isVariable)throw new Error("cannot calculate minimum on a variable length data type");return this.writePos===0?1/0:(this._cachedMin==null&&(this._cachedMin=this.calcRawMin()),ot(this._cachedMin,this.sampleOffset))}get bounds(){return yt(Number(this.min),Number(this.max))}maybeRecomputeMinMax(e){if(this._cachedMin!=null){const t=e._cachedMin??e.calcRawMin();t<this._cachedMin&&(this._cachedMin=t)}if(this._cachedMax!=null){const t=e._cachedMax??e.calcRawMax();t>this._cachedMax&&(this._cachedMax=t)}}enrich(){this.max,this.min}get range(){return ot(this.max,-this.min)}at(e,t){if(this.dataType.isVariable)return this.atVariable(e,t??!1);e<0&&(e=this.length+e);const n=this.data[e];if(n==null){if(t===!0)throw new Error(`[series] - no value at index ${e}`);return}return ot(n,this.sampleOffset)}atVariable(e,t){e<0&&(e=this.length+e);let n=0,i=0;for(let c=0;c<this.data.length;c++)if(this.data[c]===10){if(e===0){i=c;break}n=c+1,e--}if(i===0&&(i=this.data.length),n>=i||e>0){if(t)throw new Error(`[series] - no value at index ${e}`);return}const a=this.data.slice(n,i);return this.dataType.equals(z.STRING)?new TextDecoder().decode(a):zs(JSON.parse(new TextDecoder().decode(a)))}binarySearch(e){let t=0,n=this.length-1;const i=zo(e);for(;t<=n;){const a=Math.floor((t+n)/2),c=i(this.at(a,!0),e);if(c===0)return a;c<0?t=a+1:n=a-1}return t}updateGLBuffer(e){if(this.gl.control=e,!this.dataType.equals(z.FLOAT32))throw new Error("Only FLOAT32 arrays can be used in WebGL");const{buffer:t,bufferUsage:n,prevBuffer:i}=this.gl;if(t==null&&(this.gl.buffer=e.createBuffer()),this.writePos!==i)if(e.bindBuffer(e.ARRAY_BUFFER,this.gl.buffer),this.writePos!==Te){i===0&&e.bufferData(e.ARRAY_BUFFER,this.byteCapacity.valueOf(),e.STATIC_DRAW);const a=this.dataType.density.size(i).valueOf(),c=this.underlyingData.slice(this.gl.prevBuffer,this.writePos);e.bufferSubData(e.ARRAY_BUFFER,a,c.buffer),this.gl.prevBuffer=this.writePos}else e.bufferData(e.ARRAY_BUFFER,this.buffer,n==="static"?e.STATIC_DRAW:e.DYNAMIC_DRAW),this.gl.prevBuffer=Te}as(e){if(e==="string"){if(!this.dataType.equals(z.STRING))throw new Error(`cannot convert series of type ${this.dataType.toString()} to string`);return this}if(e==="number"){if(!this.dataType.isNumeric)throw new Error(`cannot convert series of type ${this.dataType.toString()} to number`);return this}if(e==="bigint"){if(!this.dataType.equals(z.INT64))throw new Error(`cannot convert series of type ${this.dataType.toString()} to bigint`);return this}throw new Error(`cannot convert series to ${e}`)}get digest(){var e;return{key:this.key,dataType:this.dataType.toString(),sampleOffset:this.sampleOffset,alignment:this.alignmentBounds,timeRange:(e=this._timeRange)==null?void 0:e.toString(),length:this.length,capacity:this.capacity}}get memInfo(){return{key:this.key,length:this.length,byteLength:this.byteLength,glBuffer:this.gl.buffer!=null}}get alignmentBounds(){return yt(this.alignment,this.alignment+BigInt(this.length))}maybeGarbageCollectGLBuffer(e){this.gl.buffer!=null&&(e.deleteBuffer(this.gl.buffer),this.gl.buffer=null,this.gl.prevBuffer=0,this.gl.control=null)}get glBuffer(){if(this.gl.buffer==null)throw new Error("gl buffer not initialized");return this.gl.prevBuffer!==this.writePos&&console.warn("buffer not updated"),this.gl.buffer}[Symbol.iterator](){if(this.dataType.isVariable){const e=new lc(this);return this.dataType.equals(z.JSON)?new uc(e):e}return new hc(this)}slice(e,t){if(e<=0&&(t==null||t>=this.length))return this;const n=this.data.slice(e,t);return new le({data:n,dataType:this.dataType,timeRange:this._timeRange,sampleOffset:this.sampleOffset,glBufferUsage:this.gl.bufferUsage,alignment:this.alignment+BigInt(e)})}reAlign(e){return new le({data:this.buffer,dataType:this.dataType,timeRange:W.ZERO,sampleOffset:this.sampleOffset,glBufferUsage:"static",alignment:e})}};class lc{constructor(e){if(f(this,"series"),f(this,"index"),f(this,"decoder"),!e.dataType.isVariable)throw new Error("cannot create a variable series iterator for a non-variable series");this.series=e,this.index=0,this.decoder=new TextDecoder}next(){const e=this.index,t=this.series.data;for(;this.index<t.length&&t[this.index]!==10;)this.index++;const n=this.index;return e===n?{done:!0,value:void 0}:(this.index++,{done:!1,value:this.decoder.decode(this.series.buffer.slice(e,n))})}[Symbol.iterator](){return this}}var Rn,Cn;class uc{constructor(e){f(this,"wrapped"),f(this,Rn,"JSONSeriesIterator"),this.wrapped=e}next(){const e=this.wrapped.next();return e.done===!0?{done:!0,value:void 0}:{done:!1,value:Ke.decodeString(e.value)}}[(Cn=Symbol.iterator,Rn=Symbol.toStringTag,Cn)](){return this}}var xn,Pn;class hc{constructor(e){f(this,"series"),f(this,"index"),f(this,xn,"SeriesIterator"),this.series=e,this.index=0}next(){return this.index>=this.series.length?{done:!0,value:void 0}:{done:!1,value:this.series.at(this.index++,!0)}}[(Pn=Symbol.iterator,xn=Symbol.toStringTag,Pn)](){return this}}const ot=(r,e)=>typeof r=="bigint"&&typeof e=="bigint"||typeof r=="number"&&typeof e=="number"?r+e:e===0?r:r===0?e:Number(r)+Number(e);class Ms{constructor(e){if(f(this,"series"),e.length!==0){const t=e[0].dataType;for(let n=1;n<e.length;n++)if(!e[n].dataType.equals(t))throw new Error("[multi-series] - series must have the same data type")}this.series=e}as(e){if(!new z(e).equals(this.dataType))throw new Error(`cannot convert series of type ${this.dataType.toString()} to ${e.toString()}`);return this}get dataType(){return this.series.length===0?z.UNKNOWN:this.series[0].dataType}get timeRange(){return this.series.length===0?W.ZERO:new W(this.series[0].timeRange.start,this.series[this.series.length-1].timeRange.end)}push(e){this.series.push(e)}get length(){return this.series.reduce((e,t)=>e+t.length,0)}at(e,t=!1){e<0&&(e=this.length+e);for(const n of this.series){if(e<n.length)return n.at(e,t);e-=n.length}if(t)throw new Error(`[series] - no value at index ${e}`)}get byteLength(){return new pt(this.series.reduce((e,t)=>e+t.byteLength.valueOf(),0))}get data(){const e=new this.dataType.Array(this.length);let t=0;for(const n of this.series)e.set(n.data,t),t+=n.length;return new this.dataType.Array(e)}[Symbol.iterator](){return this.series.length===0?{next(){return{done:!0,value:void 0}}}:new yc(this.series)}}var Dn,jn;class yc{constructor(e){f(this,"series"),f(this,"seriesIndex"),f(this,"internal"),f(this,Dn,"MultiSeriesIterator"),this.series=e,this.seriesIndex=0,this.internal=e[0][Symbol.iterator]()}next(){const e=this.internal.next();return e.done===!1?e:this.seriesIndex===this.series.length-1?{done:!0,value:void 0}:(this.internal=this.series[++this.seriesIndex][Symbol.iterator](),this.next())}[(jn=Symbol.iterator,Dn=Symbol.toStringTag,jn)](){return this}}const O=r=>Array.isArray(r)?r:[r],dc=(r,e)=>{let t=null;return e===0?r:(...n)=>{t!==null&&(clearTimeout(t),t=null),t=setTimeout(()=>r(...n),e)}};s.z.object({key:s.z.string(),value:s.z.string()});var fc=Object.defineProperty,pc=(r,e,t)=>e in r?fc(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,Yt=(r,e,t)=>pc(r,typeof e!="symbol"?e+"":e,t);let gc=class{constructor(e,t){Yt(this,"handlers"),Yt(this,"transform"),Yt(this,"closer"),this.transform=e,this.handlers=t??new Map}onChange(e){return this.handlers.set(e,null),()=>this.handlers.delete(e)}notify(e){let t=e;if(this.transform!=null){const[n,i]=this.transform(e);if(!i)return;t=n}this.handlers.forEach((n,i)=>i(t))}setCloser(e){this.closer=e}async close(){var e;return await((e=this.closer)==null?void 0:e.call(this))}},mc=class{constructor(e){Yt(this,"handlers"),this.handlers=e??new Map}onChange(e){return this.handlers.set(e,null),()=>this.handlers.delete(e)}notify(e){this.handlers.forEach((t,n)=>n(e))}};const Ie=Object.freeze(Object.defineProperty({__proto__:null,BaseObserver:mc,Observer:gc},Symbol.toStringTag,{value:"Module"})),Kr=s.z.record(s.z.union([s.z.number(),s.z.string(),s.z.symbol()]),s.z.unknown()),wc=()=>typeof process<"u"&&process.versions!=null&&process.versions.node!=null?"node":typeof window>"u"||window.document===void 0?"webworker":"browser";wc();const bc=["MacOS","Windows","Linux","Docker"];s.z.enum(bc);const Mn=r=>[...new Set(r)];var vc=Object.defineProperty,Tc=(r,e,t)=>e in r?vc(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,ct=(r,e,t)=>Tc(r,typeof e!="symbol"?e+"":e,t);const Oc=(...r)=>r.map(Zs).join(""),Zs=r=>(r.endsWith("/")||(r+="/"),r.startsWith("/")&&(r=r.slice(1)),r),zc=r=>r.endsWith("/")?r.slice(0,-1):r,Mr=class Zr{constructor({host:e,port:t,protocol:n="",pathPrefix:i=""}){ct(this,"protocol"),ct(this,"host"),ct(this,"port"),ct(this,"path"),this.protocol=n,this.host=e,this.port=t,this.path=Zs(i)}replace(e){return new Zr({host:e.host??this.host,port:e.port??this.port,protocol:e.protocol??this.protocol,pathPrefix:e.pathPrefix??this.path})}child(e){return new Zr({...this,pathPrefix:Oc(this.path,e)})}toString(){return zc(`${this.protocol}://${this.host}:${this.port}/${this.path}`)}};ct(Mr,"UNKNOWN",new Mr({host:"unknown",port:0}));let Ec=Mr;var Sc=Object.defineProperty,Nc=(r,e,t)=>e in r?Sc(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,Wt=(r,e,t)=>Nc(r,typeof e!="symbol"?e+"":e,t);const Oe=class extends Number{};Wt(Oe,"Absolute",255),Wt(Oe,"Default",1),Wt(Oe,"z",s.z.union([s.z.instanceof(Oe),s.z.number().int().min(0).max(255).transform(r=>new Oe(r)),s.z.instanceof(Number).transform(r=>new Oe(r))]));let Us=Oe;const Bs=s.z.object({name:s.z.string(),key:s.z.string()}),Ic=r=>s.z.object({subject:Bs,resource:r,authority:Us.z}),kc=(...r)=>e=>e.filter(t=>{let n=!1;return t.to!=null&&(n=r.includes(t.to.resource)),t.from!=null&&!n&&(n=r.includes(t.from.resource)),n}),Je=Object.freeze(Object.defineProperty({__proto__:null,Authority:Us,filterTransfersByChannelKey:kc,stateZ:Ic,subjectZ:Bs},Symbol.toStringTag,{value:"Module"})),Ls=class lt extends Error{constructor(){super(lt.MESSAGE)}matches(e){return typeof e=="string"?e.includes(lt.MESSAGE):e instanceof lt||e.message.includes(lt.MESSAGE)}};Wt(Ls,"MESSAGE","canceled");let Ac=Ls;new Ac;const Ur=s.z.string().regex(/^\d+\.\d+\.\d+$/),zt=(r,e,t={})=>{t.checkMajor??(t.checkMajor=!0),t.checkMinor??(t.checkMinor=!0),t.checkPatch??(t.checkPatch=!0);const n=Ur.parse(r),i=Ur.parse(e),[a,c,l]=n.split(".").map(Number),[u,h,p]=i.split(".").map(Number);if(t.checkMajor){if(a<u)return wr;if(a>u)return br}if(t.checkMinor){if(c<h)return wr;if(c>h)return br}if(t.checkPatch){if(l<p)return wr;if(l>p)return br}return So},$c=(r,e,t={})=>ko(zt(r,e,t)),qs=(r,e,t={})=>Io(zt(r,e,t)),Rc=(r,e,t={})=>No(zt(r,e,t)),Cc=({name:r,migrate:e})=>t=>{try{const n=e(t);return console.log(`${r} migrated: ${t.version} -> ${n.version}`),n}catch(n){throw console.log(`${r} failed to migrate from ${t.version}`),console.error(n),n}},xc=({name:r,migrations:e,targetSchema:t,def:n})=>{const i=Object.keys(e).sort(zt).pop();if(i==null)return u=>{if(u.version!==n.version)return console.log(`${r} version ${u.version} is newer than latest version of ${n.version}.
16
+ Returning default instead.
17
+ `),n;try{return t!=null?t.parse(u):u}catch(h){return console.log(`${r} failed to parse default. Exiting with default`),console.error(h),n}};const a=Object.keys(e).length;let c=!1;const l=u=>{try{if(a===0||qs(u.version,i))return console.log(c?`${r} ${u.version} now up to date`:`${r} version ${u.version} is up to date with target version ${n.version}`),u;const h=u.version,p=e[h],g=p(u);return c=!0,l(g)}catch(h){return console.log(`${r} failed to migrate from ${u.version} to ${i}`),console.error(h),n}};return u=>{try{return l(u)}catch(h){return console.log(`${r} failed to parse final result. Exiting with default`),console.error(h),n}}},Zn=Object.freeze(Object.defineProperty({__proto__:null,compareSemVer:zt,createMigration:Cc,migrator:xc,semVerNewer:qs,semVerOlder:Rc,semVerZ:Ur,versionsEqual:$c},Symbol.toStringTag,{value:"Module"})),me="sy.",Pe=class Pe extends te{constructor(){super(...arguments);o(this,"type",Pe.TYPE)}};o(Pe,"TYPE",me+"validation"),o(Pe,"matches",J(Pe.TYPE));let x=Pe;const De=class De extends x{constructor(t,n){super(t+": "+n);o(this,"type",De.TYPE);o(this,"field");o(this,"message");this.field=t,this.message=n}};o(De,"TYPE",x.TYPE+".field"),o(De,"matches",J(De.TYPE));let Kt=De;const je=class je extends te{constructor(){super(...arguments);o(this,"type",je.TYPE)}};o(je,"TYPE",me+"auth"),o(je,"matches",J(je.TYPE));let ke=je;const Me=class Me extends ke{constructor(){super(...arguments);o(this,"type",Me.TYPE)}};o(Me,"TYPE",ke.TYPE+".invalid-token"),o(Me,"matches",J(Me.TYPE));let gt=Me;const Ze=class Ze extends te{constructor(t){super(`
16
18
  Unexpected error encountered:
17
19
 
18
20
  ${t}
19
21
 
20
22
  Please report this to the Synnax team.
21
- `);o(this,"type",Me.TYPE)}};o(Me,"TYPE",me+"unexpected"),o(Me,"matches",J(Me.TYPE));let pe=Me;const Ze=class Ze extends te{constructor(){super(...arguments);o(this,"type",Ze.TYPE)}};o(Ze,"TYPE",me+"query"),o(Ze,"matches",J(Ze.TYPE));let Q=Ze;const Ue=class Ue extends Q{constructor(){super(...arguments);o(this,"type",Ue.TYPE)}};o(Ue,"TYPE",Q.TYPE+".not_found"),o(Ue,"matches",J(Ue.TYPE));let Ae=Ue;const Be=class Be extends Q{constructor(){super(...arguments);o(this,"type",Be.TYPE)}};o(Be,"TYPE",Q.TYPE+".multiple_results"),o(Be,"matches",J(Be.TYPE));let $e=Be;const Le=class Le extends te{constructor(t,n){super(t);o(this,"type",Le.TYPE);o(this,"path");this.path=n}};o(Le,"TYPE",me+"route"),o(Le,"matches",J(Le.TYPE));let mt=Le;const qe=class qe extends te{constructor(){super(...arguments);o(this,"type",qe.TYPE)}};o(qe,"TYPE",me+"control"),o(qe,"matches",J(qe.TYPE));let Je=qe;const Ye=class Ye extends Je{constructor(){super(...arguments);o(this,"type",Ye.TYPE)}};o(Ye,"TYPE",Je.TYPE+".unauthorized"),o(Ye,"matches",J(Ye.TYPE));let Ft=Ye;const We=class We extends te{constructor(){super(...arguments);o(this,"type",We.TYPE)}};o(We,"TYPE",me+"contiguity"),o(We,"matches",J(We.TYPE));let Pr=We;const mc=r=>{if(!r.type.startsWith(me))return null;if(r.type.startsWith(C.TYPE)){if(r.type===_t.TYPE){const e=r.data.split(": ");return e.length<2?new C(r.data):new _t(e[0],e[1])}return new C(r.data)}return r.type.startsWith(ke.TYPE)?r.type.startsWith(gt.TYPE)?new gt(r.data):new ke(r.data):r.type.startsWith(pe.TYPE)?new pe(r.data):r.type.startsWith(Q.TYPE)?r.type.startsWith(Ae.TYPE)?new Ae(r.data):r.type.startsWith($e.TYPE)?new $e(r.data):new Q(r.data):r.type.startsWith(Je.TYPE)?r.type.startsWith(Ft.TYPE)?new Ft(r.data):new Je(r.data):r.type.startsWith(mt.TYPE)?new mt(r.data,r.data):new pe(r.data)},wc=()=>{throw new Error("Not implemented")};is({encode:wc,decode:mc});const bc=async(r,e)=>{const[t,n]=await e(r);return n==null?[t,n]:n instanceof Ne?[t,new Ne({message:`Cannot reach cluster at ${n.url.host}:${n.url.port}`,url:n.url})]:[t,n]};class Cs{constructor(e,t){o(this,"key");o(this,"name");this.key=t,this.name=e}get ontologyID(){return new T({type:"group",key:this.key})}}const vc=s.z.string().uuid(),Ps=s.z.object({key:vc,name:s.z.string()}),js=s.z.union([s.z.literal("label"),s.z.literal("builtin"),s.z.literal("cluster"),s.z.literal("channel"),s.z.literal("node"),s.z.literal("group"),s.z.literal("range"),s.z.literal("range-alias"),s.z.literal("user"),s.z.literal("workspace"),s.z.literal("schematic"),s.z.literal("lineplot"),s.z.literal("rack"),s.z.literal("device"),s.z.literal("task"),s.z.literal("policy")]),Tc="builtin",Oc="cluster",zc="node",V=s.z.object({type:js,key:s.z.string()}),Ds=s.z.string().transform(r=>{const[e,t]=r.split(":");return{type:e,key:t}}),Ms=s.z.union([Ds,V]),_e=class _e{constructor(e){o(this,"type");o(this,"key");if(e instanceof _e)this.type=e.type,this.key=e.key;else if(typeof e=="string"){const[t,n]=e.split(":");this.type=t,this.key=n}else this.type=e.type,this.key=e.key}toString(){return`${this.type}:${this.key}`}get payload(){return{type:this.type,key:this.key}}};o(_e,"z",s.z.union([Ms,s.z.instanceof(_e)]).transform(e=>new _e(e)));let T=_e;const Ec=new T({type:"builtin",key:"root"}),Zs=s.z.object({type:s.z.number()}),Us=s.z.object({type:js,fields:s.z.record(Zs)}),Bs=s.z.object({id:T.z,name:s.z.string(),schema:Us.optional().nullable(),data:s.z.record(s.z.unknown()).optional().nullable()}).transform(r=>({key:r.id.toString(),...r})),Sc=s.z.object({from:T.z,type:s.z.string(),to:T.z}),jr=r=>{const[e,t,n]=r.split("->");return{from:new T(e),type:t,to:new T(n)}},Nc=s.z.object({group:Ps}),Ic=s.z.object({parent:V,key:s.z.string().uuid().optional(),name:s.z.string()}),kc=s.z.object({key:s.z.string(),name:s.z.string()}),Ac=s.z.object({keys:s.z.array(s.z.string())});var ee;let $c=(ee=class{constructor(e){o(this,"client");this.client=e}async create(e,t,n){const[i,a]=await this.client.send(ee.ENDPOINT,{parent:e,name:t,key:n},Ic,Nc);if(a!=null)throw a;return i.group}async rename(e,t){const n={key:e,name:t},[,i]=await this.client.send(ee.ENDPOINT_RENAME,n,kc,s.z.object({}));if(i!=null)throw i}async delete(e){const t={keys:e},[,n]=await this.client.send(ee.ENDPOINT_DELETE,t,Ac,s.z.object({}));if(n!=null)throw n}},o(ee,"ENDPOINT","/ontology/create-group"),o(ee,"ENDPOINT_RENAME","/ontology/rename-group"),o(ee,"ENDPOINT_DELETE","/ontology/delete-group"),ee),Rc=class{constructor(e){o(this,"creator");this.creator=new $c(e)}async create(e,t,n){return this.sugar(await this.creator.create(e,t,n))}async rename(e,t){return await this.creator.rename(e,t)}async delete(...e){return await this.creator.delete(e)}sugar(e){return new Cs(e.name,e.key)}};const mr={ADD_CHILDREN:"/ontology/add-children",REMOVE_CHILDREN:"/ontology/remove-children",MOVE_CHILDREN:"/ontology/move-children"},xn=s.z.object({id:V,children:V.array()}),xc=s.z.object({from:V,to:V,children:V.array()});let Cc=class{constructor(e){o(this,"client");this.client=e}async addChildren(e,...t){await w(this.client,mr.ADD_CHILDREN,{id:new T(e).payload,children:t.map(n=>new T(n).payload)},xn,s.z.object({}))}async removeChildren(e,...t){await w(this.client,mr.REMOVE_CHILDREN,{id:new T(e).payload,children:t.map(n=>new T(n).payload)},xn,s.z.object({}))}async moveChildren(e,t,...n){const i={from:new T(e).payload,to:new T(t).payload,children:n.map(a=>new T(a).payload)};await w(this.client,mr.MOVE_CHILDREN,i,xc,s.z.object({}))}};const Pc="/ontology/retrieve",jc=s.z.object({ids:V.array().optional(),children:s.z.boolean().optional(),parents:s.z.boolean().optional(),includeSchema:s.z.boolean().optional(),excludeFieldData:s.z.boolean().optional(),term:s.z.string().optional(),limit:s.z.number().optional(),offset:s.z.number().optional()}),Dc=s.z.object({resources:Bs.array()}),qt=r=>O(r).map(e=>new T(e).payload);let Ls=class{constructor(e,t){o(this,"type","ontology");o(this,"groups");o(this,"client");o(this,"writer");o(this,"framer");this.client=e,this.writer=new Cc(e),this.groups=new Rc(e),this.framer=t}async search(e,t){return await this.execRetrieve({term:e,...t})}async retrieve(e,t){const n=await this.execRetrieve({ids:qt(e),...t});if(Array.isArray(e))return n;if(n.length===0)throw new Q(`No resource found with ID ${e.toString()}`);return n[0]}async page(e,t,n){return await this.execRetrieve({offset:e,limit:t,...n})}async retrieveChildren(e,t){return await this.execRetrieve({ids:qt(e),children:!0,...t})}async retrieveParents(e,t){return await this.execRetrieve({ids:qt(e),parents:!0,...t})}async addChildren(e,...t){return await this.writer.addChildren(e,...t)}async removeChildren(e,...t){return await this.writer.removeChildren(e,...t)}async moveChildren(e,t,...n){return await this.writer.moveChildren(e,t,...n)}async openChangeTracker(){return await zt.open(this.framer,this)}async openDependentTracker(e,t,n="parent",i="from"){return await Qt.open(e,this,this.framer,t,n,i)}newSearcherWithOptions(e){return{type:this.type,search:t=>this.search(t,e),retrieve:t=>this.retrieve(t,e),page:(t,n)=>this.page(t,n,e)}}async execRetrieve(e){const{resources:t}=await w(this.client,Pc,e,jc,Dc);return t}};const Cn="sy_ontology_resource_set",Pn="sy_ontology_resource_delete",jn="sy_ontology_relationship_set",Dn="sy_ontology_relationship_delete";class zt{constructor(e,t){o(this,"relationships");o(this,"resources");o(this,"resourceObs");o(this,"relationshipObs");o(this,"streamer");o(this,"client");o(this,"closePromise");this.relationshipObs=new Ie.Observer,this.relationships=this.relationshipObs,this.resourceObs=new Ie.Observer,this.resources=this.resourceObs,this.client=t,this.streamer=e,this.closePromise=this.start()}async close(){this.streamer.close(),await this.closePromise}async start(){for await(const e of this.streamer)await this.update(e)}async update(e){const t=await this.parseResourceSets(e),n=this.parseResourceDeletes(e);t.concat(n).length>0&&this.resourceObs.notify(t.concat(n));const a=this.parseRelationshipSets(e),c=this.parseRelationshipDeletes(e);a.concat(c).length>0&&this.relationshipObs.notify(a.concat(c))}parseRelationshipSets(e){const t=e.get(jn);return t.length===0?[]:Array.from(t.as("string")).map(n=>({variant:"set",key:jr(n),value:void 0}))}parseRelationshipDeletes(e){const t=e.get(Dn);return t.length===0?[]:Array.from(t.as("string")).map(n=>({variant:"delete",key:jr(n)}))}async parseResourceSets(e){const t=e.get(Cn);if(t.length===0)return[];const n=Array.from(t.as("string")).map(i=>new T(i));try{return(await this.client.retrieve(n)).map(a=>({variant:"set",key:a.id,value:a}))}catch(i){if(i instanceof Q)return[];throw i}}parseResourceDeletes(e){const t=e.get(Pn);return t.length===0?[]:Array.from(t.as("string")).map(n=>({variant:"delete",key:new T(n)}))}static async open(e,t){const n=await e.openStreamer([Cn,Pn,jn,Dn]);return new zt(n,t)}}class Qt extends Ie.Observer{constructor(t,n,i,a,c="parent",l="from"){super();o(this,"internal");o(this,"target");o(this,"direction");o(this,"dependents");o(this,"client");o(this,"type");o(this,"handleResourceChange",t=>{this.dependents=this.dependents.map(n=>{const i=t.find(a=>a.key.toString()==n.id.toString());return i==null||i.variant==="delete"?n:i.value}),this.notify(this.dependents)});o(this,"handleRelationshipChange",t=>{const n=t.filter(a=>a.variant==="delete"&&a.key[this.direction].toString()===this.target.toString());this.dependents=this.dependents.filter(a=>!n.some(c=>c.key.to.toString()===a.id.toString()&&c.key.type===this.type));const i=t.filter(a=>a.variant==="set"&&a.key.type===this.type&&a.key[this.direction].toString()===this.target.toString());if(i.length===0)return this.notify(this.dependents);this.client.retrieve(i.map(a=>a.key.to)).then(a=>{this.dependents=this.dependents.concat(a),this.notify(this.dependents)})});this.internal=n,this.target=t,this.dependents=i,this.client=a,this.type=c,this.direction=l,this.internal.resources.onChange(this.handleResourceChange),this.internal.relationships.onChange(this.handleRelationshipChange)}static async open(t,n,i,a,c="parent",l="from"){const u=await zt.open(i,n);return new Qt(t,u,a,n,c,l)}async close(){await this.internal.close()}}const Mc=Object.freeze(Object.defineProperty({__proto__:null,BuiltinOntologyType:Tc,ChangeTracker:zt,Client:Ls,ClusterOntologyType:Oc,DependentTracker:Qt,ID:T,NodeOntologyType:zc,Root:Ec,crudeIDZ:Ms,idZ:V,parseIDs:qt,parseRelationship:jr,relationshipSchemaZ:Sc,resourceSchemaZ:Bs,schemaFieldZ:Zs,schemaZ:Us,stringIDZ:Ds},Symbol.toStringTag,{value:"Module"})),we=s.z.number(),Et=s.z.object({name:s.z.string(),key:s.z.number(),rate:Xt.z,dataType:z.z,leaseholder:s.z.number(),index:s.z.number(),isIndex:s.z.boolean(),internal:s.z.boolean(),virtual:s.z.boolean(),alias:s.z.string().optional()}),qs=Et.extend({key:s.z.number().optional(),leaseholder:s.z.number().optional(),index:s.z.number().optional(),rate:Xt.z.optional().default(0),isIndex:s.z.boolean().optional(),internal:s.z.boolean().optional().default(!1),virtual:s.z.boolean().optional().default(!1)}),Ys="channel",Zc=r=>new T({type:Ys,key:r.toString()}),Uc=new Error("request for lock canceled");var Bc=function(r,e,t,n){function i(a){return a instanceof t?a:new t(function(c){c(a)})}return new(t||(t=Promise))(function(a,c){function l(g){try{f(n.next(g))}catch(p){c(p)}}function u(g){try{f(n.throw(g))}catch(p){c(p)}}function f(g){g.done?a(g.value):i(g.value).then(l,u)}f((n=n.apply(r,e||[])).next())})};class Lc{constructor(e,t=Uc){this._value=e,this._cancelError=t,this._queue=[],this._weightedWaiters=[]}acquire(e=1,t=0){if(e<=0)throw new Error(`invalid weight ${e}: must be positive`);return new Promise((n,i)=>{const a={resolve:n,reject:i,weight:e,priority:t},c=Ws(this._queue,l=>t<=l.priority);c===-1&&e<=this._value?this._dispatchItem(a):this._queue.splice(c+1,0,a)})}runExclusive(e){return Bc(this,arguments,void 0,function*(t,n=1,i=0){const[a,c]=yield this.acquire(n,i);try{return yield t(a)}finally{c()}})}waitForUnlock(e=1,t=0){if(e<=0)throw new Error(`invalid weight ${e}: must be positive`);return this._couldLockImmediately(e,t)?Promise.resolve():new Promise(n=>{this._weightedWaiters[e-1]||(this._weightedWaiters[e-1]=[]),qc(this._weightedWaiters[e-1],{resolve:n,priority:t})})}isLocked(){return this._value<=0}getValue(){return this._value}setValue(e){this._value=e,this._dispatchQueue()}release(e=1){if(e<=0)throw new Error(`invalid weight ${e}: must be positive`);this._value+=e,this._dispatchQueue()}cancel(){this._queue.forEach(e=>e.reject(this._cancelError)),this._queue=[]}_dispatchQueue(){for(this._drainUnlockWaiters();this._queue.length>0&&this._queue[0].weight<=this._value;)this._dispatchItem(this._queue.shift()),this._drainUnlockWaiters()}_dispatchItem(e){const t=this._value;this._value-=e.weight,e.resolve([t,this._newReleaser(e.weight)])}_newReleaser(e){let t=!1;return()=>{t||(t=!0,this.release(e))}}_drainUnlockWaiters(){if(this._queue.length===0)for(let e=this._value;e>0;e--){const t=this._weightedWaiters[e-1];t&&(t.forEach(n=>n.resolve()),this._weightedWaiters[e-1]=[])}else{const e=this._queue[0].priority;for(let t=this._value;t>0;t--){const n=this._weightedWaiters[t-1];if(!n)continue;const i=n.findIndex(a=>a.priority<=e);(i===-1?n:n.splice(0,i)).forEach(a=>a.resolve())}}}_couldLockImmediately(e,t){return(this._queue.length===0||this._queue[0].priority<t)&&e<=this._value}}function qc(r,e){const t=Ws(r,n=>e.priority<=n.priority);r.splice(t+1,0,e)}function Ws(r,e){for(let t=r.length-1;t>=0;t--)if(e(r[t]))return t;return-1}var Yc=function(r,e,t,n){function i(a){return a instanceof t?a:new t(function(c){c(a)})}return new(t||(t=Promise))(function(a,c){function l(g){try{f(n.next(g))}catch(p){c(p)}}function u(g){try{f(n.throw(g))}catch(p){c(p)}}function f(g){g.done?a(g.value):i(g.value).then(l,u)}f((n=n.apply(r,e||[])).next())})};class Wc{constructor(e){this._semaphore=new Lc(1,e)}acquire(){return Yc(this,arguments,void 0,function*(e=0){const[,t]=yield this._semaphore.acquire(1,e);return t})}runExclusive(e,t=0){return this._semaphore.runExclusive(()=>e(),1,t)}isLocked(){return this._semaphore.isLocked()}waitForUnlock(e=0){return this._semaphore.waitForUnlock(1,e)}release(){this._semaphore.isLocked()&&this._semaphore.release()}cancel(){return this._semaphore.cancel()}}const er=(r,e,{convertNumericStrings:t=!0}={})=>{const n=!Array.isArray(r);let i=O(r);const a=i[0],c=typeof a;let l;return c==="string"&&t&&!isNaN(parseInt(a))&&"number"in e?(l=e.number,i=i.map(u=>parseInt(u))):l=e[c],{single:n,variant:l,normalized:i,actual:r}},tr=(r,e,t,n)=>{if(n){if(t.length===0)throw new Ae(`${r} not found matching ${JSON.stringify(e)}`);if(t.length>1)throw new $e(`Expected one ${r} matching ${JSON.stringify(e)}, but found ${t.length}`)}},be=r=>s.z.union([s.z.null().transform(()=>[]),r.array()]),_c=s.z.object({leaseholder:s.z.number().optional(),keys:s.z.number().array().optional(),names:s.z.string().array().optional(),search:s.z.string().optional(),rangeKey:s.z.string().optional(),limit:s.z.number().optional(),offset:s.z.number().optional(),dataTypes:z.z.array().optional(),notDataTypes:z.z.array().optional(),virtual:s.z.boolean().optional(),isIndex:s.z.boolean().optional(),internal:s.z.boolean().optional()}),Fc=s.z.object({channels:be(Et)}),ye=r=>er(r,{number:"keys",string:"names"}),Gt=class Gt{constructor(e){o(this,"client");this.client=e}async search(e,t){return await this.execute({search:e,...t})}async retrieve(e,t){const n=ye(e),{variant:i}=n;let{normalized:a}=n;return i==="keys"&&a.indexOf(0)!==-1&&(a=a.filter(c=>c!==0)),a.length===0?[]:await this.execute({[i]:a,...t})}async page(e,t,n){return await this.execute({offset:e,limit:t,...n})}async execute(e){const[t,n]=await this.client.send(Gt.ENDPOINT,e,_c,Fc);if(n!=null)throw n;return t.channels}};o(Gt,"ENDPOINT","/channel/retrieve");let wt=Gt;class Yr{constructor(e){o(this,"cache");o(this,"namesToKeys");o(this,"wrapped");this.cache=new Map,this.namesToKeys=new Map,this.wrapped=e}async search(e,t){return await this.wrapped.search(e,t)}async page(e,t,n){return await this.wrapped.page(e,t,n)}async retrieve(e,t){const{normalized:n}=er(e,{string:"names",number:"keys"}),i=[],a=[];if(n.forEach(l=>{const u=this.get(l);u!=null?i.push(...u):a.push(l)}),a.length===0)return i;const c=await this.wrapped.retrieve(a,t);return this.set(c),i.concat(c)}delete(e){const{variant:t,normalized:n}=ye(e);t==="names"?n.forEach(i=>{const a=this.namesToKeys.get(i);a!=null&&(a.forEach(c=>this.cache.delete(c)),this.namesToKeys.delete(i))}):n.forEach(i=>{const a=this.cache.get(i);a!=null&&(this.cache.delete(i),this.namesToKeys.delete(a.name))})}rename(e,t){e.forEach((n,i)=>{const a=t[i],c=this.cache.get(n);if(c==null)return;this.cache.delete(n);const l=this.namesToKeys.get(c.name);l!=null&&(l.delete(n),l.size===0&&this.namesToKeys.delete(c.name)),c.name=a,this.cache.set(n,c);const u=this.namesToKeys.get(a);u==null?this.namesToKeys.set(a,new Set([n])):u.add(n)})}set(e){e.forEach(t=>{this.cache.set(t.key,t);const n=this.namesToKeys.get(t.name);n==null?this.namesToKeys.set(t.name,new Set([t.key])):n.add(t.key)})}get(e){if(typeof e=="number"){const i=this.cache.get(e);return i==null?void 0:[i]}const t=this.namesToKeys.get(e);if(t==null)return;const n=[];if(t.forEach(i=>{const a=this.cache.get(i);a!=null&&n.push(a)}),n.length!==0)return n}}class _s{constructor(e,t){o(this,"mu",new Wc);o(this,"requests",new Map);o(this,"wrapped");o(this,"debouncedRun");this.wrapped=e,this.debouncedRun=ec(()=>{this.run()},t)}async search(e,t){return await this.wrapped.search(e,t)}async page(e,t,n){return await this.wrapped.page(e,t,n)}async retrieve(e){const{normalized:t,variant:n}=ye(e);return n==="names"?await this.wrapped.retrieve(t):await new Promise((a,c)=>{this.mu.runExclusive(()=>{this.requests.set(t,{resolve:a,reject:c}),this.debouncedRun()})})}async run(){await this.mu.runExclusive(async()=>{const e=new Set;this.requests.forEach((t,n)=>n.forEach(i=>e.add(i)));try{const t=await this.wrapped.retrieve(Array.from(e));this.requests.forEach((n,i)=>n.resolve(t.filter(a=>i.includes(a.key))))}catch(t){this.requests.forEach(n=>n.reject(t))}finally{this.requests.clear()}})}}const Fs=async(r,e)=>{const{normalized:t}=ye(e),n=await r.retrieve(t),i=[];if(t.forEach(a=>{n.find(c=>c.name===a||c.key===a)==null&&i.push(a)}),i.length>0)throw new Q(`Could not find channels: ${JSON.stringify(i)}`);return n};class Wr{constructor({dataType:e,rate:t,name:n,leaseholder:i=0,key:a=0,isIndex:c=!1,index:l=0,internal:u=!1,virtual:f=!1,frameClient:g,alias:p}){o(this,"_frameClient");o(this,"key");o(this,"name");o(this,"rate");o(this,"dataType");o(this,"leaseholder");o(this,"index");o(this,"isIndex");o(this,"internal");o(this,"alias");o(this,"virtual");this.key=a,this.name=n,this.rate=new Xt(t??0),this.dataType=new z(e),this.leaseholder=i,this.index=l,this.isIndex=c,this.internal=u,this.alias=p,this.virtual=f,this._frameClient=g??null}get framer(){if(this._frameClient==null)throw new C("cannot read from a channel that has not been created");return this._frameClient}get payload(){return Et.parse({key:this.key,name:this.name,rate:this.rate.valueOf(),dataType:this.dataType.valueOf(),leaseholder:this.leaseholder,index:this.index,isIndex:this.isIndex,internal:this.internal})}get ontologyID(){return new T({type:"channel",key:this.key.toString()})}async read(e){return await this.framer.read(e,this.key)}async write(e,t){return await this.framer.write(e,this.key,t)}}const Kc="/channel/retrieve-group",Gc=s.z.object({}),Vc=s.z.object({group:Ps});let Ks=class{constructor(e,t,n,i){o(this,"type","channel");o(this,"frameClient");o(this,"client");o(this,"retriever");o(this,"writer");this.frameClient=e,this.retriever=t,this.client=n,this.writer=i}async create(e,t={}){const{retrieveIfNameExists:n=!1}=t,i=!Array.isArray(e);let a=O(e),c=[];if(n){const l=await this.retriever.retrieve(a.map(f=>f.name)),u=new Set(l.map(f=>f.name));a=a.filter(f=>!u.has(f.name)),c=this.sugar(l)}return c=c.concat(this.sugar(await this.writer.create(a))),i?c[0]:c}async retrieve(e,t){const n=!Array.isArray(e),i=this.sugar(await this.retriever.retrieve(e,t));return tr("channel",e,i,n),n?i[0]:i}async search(e,t){return this.sugar(await this.retriever.search(e,t))}async delete(e){const{normalized:t,variant:n}=ye(e);return n==="keys"?await this.writer.delete({keys:t}):await this.writer.delete({names:t})}async rename(e,t){return await this.writer.rename(O(e),O(t))}newSearcherWithOptions(e){return{type:this.type,search:async t=>await this.search(t,e),retrieve:async t=>await this.retrieve(t,e),page:async(t,n)=>await this.page(t,n,e)}}async page(e,t,n){return this.sugar(await this.retriever.page(e,t,n))}createDebouncedBatchRetriever(e=10){return new Yr(new _s(new wt(this.client),e))}sugar(e){const{frameClient:t}=this;return e.map(n=>new Wr({...n,frameClient:t}))}async retrieveGroup(){const e=await w(this.client,Kc,{},Gc,Vc);return new Cs(e.group.name,e.group.key)}};const Jc=s.z.object({channels:qs.array()}),Hc=s.z.object({channels:Et.array()}),Xc=s.z.object({keys:we.array().optional(),names:s.z.string().array().optional()}),Qc=s.z.object({}),el=s.z.object({keys:we.array(),names:s.z.string().array()}),tl=s.z.object({}),rl="/channel/create",nl="/channel/delete",sl="/channel/rename";let Gs=class{constructor(e,t){o(this,"client");o(this,"cache");this.client=e,this.cache=t}async create(e){const{channels:t}=await w(this.client,rl,{channels:e},Jc,Hc);return this.cache.set(t),t}async delete(e){await w(this.client,nl,e,Xc,Qc),e.keys!=null&&this.cache.delete(e.keys),e.names!=null&&this.cache.delete(e.names)}async rename(e,t){await w(this.client,sl,{keys:e,names:t},el,tl),this.cache.rename(e,t)}};const il=Object.freeze(Object.defineProperty({__proto__:null,CacheRetriever:Yr,Channel:Wr,ChannelOntologyType:Ys,Client:Ks,ClusterRetriever:wt,DebouncedBatchRetriever:_s,Writer:Gs,analyzeChannelParams:ye,keyZ:we,newPayload:qs,ontologyID:Zc,payload:Et,retrieveRequired:Fs},Symbol.toStringTag,{value:"Module"})),_r=s.z.string().uuid(),Fr=s.z.object({key:_r,subjects:V.array(),objects:V.array(),actions:s.z.string().array()}),al=Fr.extend({key:_r.optional()}),ol="/access/policy/create",cl="/access/policy/delete",ll="/access/policy/retrieve",ul=s.z.object({policies:al.array()}),hl=s.z.object({policies:Fr.array()}),yl=s.z.object({keys:_r.array()}),dl=s.z.object({}),fl=s.z.object({subject:V}),pl=s.z.object({policies:Fr.array().optional().default([])});let gl=class{constructor(e){o(this,"client");this.client=e}async create(e){const t=!Array.isArray(e),{policies:n}=await w(this.client,ol,{policies:O(e)},ul,hl);return t?n[0]:n}async retrieve(e){const{policies:t}=await w(this.client,ll,{subject:e},fl,pl);return t}async delete(e){await w(this.client,cl,{keys:O(e)},yl,dl)}};const ml="/user/register";let wl=class{constructor(e){o(this,"client");this.client=e}async register(e,t){const{user:n}=await w(this.client,ml,{username:e,password:t},Vs,Js);return n}};s.z.string().uuid();const bl=s.z.object({key:s.z.string(),username:s.z.string()}),Vs=s.z.object({username:s.z.string(),password:s.z.string()}),Js=s.z.object({token:s.z.string(),user:bl}),Mn="/auth/login",vl=3;let Tl=class{constructor(e,t){o(this,"token");o(this,"client");o(this,"credentials");o(this,"authenticating");o(this,"authenticated");o(this,"user");o(this,"retryCount");this.client=e,this.authenticated=!1,this.credentials=t,this.retryCount=0}middleware(){const e=async(t,n)=>{if(!this.authenticated&&!t.target.endsWith(Mn)){this.authenticating==null&&(this.authenticating=new Promise((l,u)=>{this.client.send(Mn,this.credentials,Vs,Js).then(([f,g])=>{if(g!=null)return l(g);this.token=f==null?void 0:f.token,this.user=f==null?void 0:f.user,this.authenticated=!0,l(null)}).catch(u)}));const c=await this.authenticating;if(c!=null)return[t,c]}t.params.Authorization=`Bearer ${this.token}`;const[i,a]=await n(t);return gt.matches(a)&&this.retryCount<vl?(this.authenticated=!1,this.authenticating=void 0,this.retryCount+=1,e(t,n)):(this.retryCount=0,[i,a])};return e}};const Ol=["disconnected","connecting","connected","failed"],Hs=s.z.enum(Ol),Xs=s.z.object({status:Hs,error:s.z.instanceof(Error).optional(),message:s.z.string().optional(),clusterKey:s.z.string()}),zl=s.z.object({clusterKey:s.z.string()}),Zn={clusterKey:"",status:"disconnected",error:void 0,message:"Disconnected"},Fe=class Fe{constructor(e,t=S.seconds(30),n){o(this,"_state");o(this,"pollFrequency",S.seconds(30));o(this,"client");o(this,"name");o(this,"interval");o(this,"onChangeHandlers",[]);this._state={...Zn},this.client=e,this.pollFrequency=t,this.name=n,this.check(),this.startChecking()}stopChecking(){this.interval!=null&&clearInterval(this.interval)}async check(){var t;const e=this._state.status;try{const[n,i]=await this.client.send(Fe.ENDPOINT,{},s.z.object({}),zl);if(i!=null)throw i;this._state.status="connected",this._state.message=`Connected to ${this.name??"cluster"}`,this._state.clusterKey=n.clusterKey}catch(n){this._state.status="failed",this._state.error=n,this._state.message=(t=this.state.error)==null?void 0:t.message}return this.onChangeHandlers.length>0&&e!==this._state.status&&this.onChangeHandlers.forEach(n=>n(this.state)),this.state}get state(){return{...this._state}}onChange(e){this.onChangeHandlers.push(e)}startChecking(){this.interval=setInterval(()=>{this.check()},this.pollFrequency.milliseconds)}};o(Fe,"ENDPOINT","/connectivity/check"),o(Fe,"DEFAULT",Zn),o(Fe,"connectionStateZ",Xs);let bt=Fe;const El=Object.freeze(Object.defineProperty({__proto__:null,Checker:bt,state:Xs,status:Hs},Symbol.toStringTag,{value:"Module"})),Sl=s.z.object({keys:we.array().optional(),bounds:W.z,names:s.z.string().array().optional()}),Nl=s.z.object({}),Il="/frame/delete";class kl{constructor(e){o(this,"client");this.client=e}async delete(e){await w(this.client,Il,e,Sl,Nl)}}const Un=r=>{const e=O(r);return e.length===0?null:typeof e[0]=="number"||!isNaN(parseInt(e[0]))?"key":"name"},Bn=(r,e)=>{const t=O(r);if(t.length===e.length)return;const n=Un(r);throw Un===null?new C("[Frame] - channel keys or names must be provided when constructing a frame."):new C(`[Frame] - ${n}s and series must be the same length.
22
- Got ${t.length} ${n}s and ${e.length} series.`)};class U{constructor(e=[],t=[]){o(this,"columns",[]);o(this,"series",[]);if(e instanceof U){this.columns=e.columns,this.series=e.series;return}if(e instanceof Map){e.forEach((i,a)=>this.push(a,...O(i)));return}if(typeof e=="object"&&!Array.isArray(e)){if("keys"in e&&"series"in e){const i=e,a=i.series.map(c=>ei(c));Bn(i.keys,a),i.keys.forEach((c,l)=>this.push(c,a[l]))}else Object.entries(e).forEach(([i,a])=>{const c=parseInt(i);if(isNaN(c))this.push(i,...O(a));else return this.push(c,...O(a))});return}if(Array.isArray(e)||["string","number"].includes(typeof e)){const i=O(t),a=O(e);Bn(a,i),i.forEach((c,l)=>this.push(a[l],c));return}throw new C(`[Frame] - invalid frame construction parameters. data parameter ust be a frame
23
+ `);o(this,"type",Ze.TYPE)}};o(Ze,"TYPE",me+"unexpected"),o(Ze,"matches",J(Ze.TYPE));let pe=Ze;const Ue=class Ue extends te{constructor(){super(...arguments);o(this,"type",Ue.TYPE)}};o(Ue,"TYPE",me+"query"),o(Ue,"matches",J(Ue.TYPE));let Q=Ue;const Be=class Be extends Q{constructor(){super(...arguments);o(this,"type",Be.TYPE)}};o(Be,"TYPE",Q.TYPE+".not_found"),o(Be,"matches",J(Be.TYPE));let Ae=Be;const Le=class Le extends Q{constructor(){super(...arguments);o(this,"type",Le.TYPE)}};o(Le,"TYPE",Q.TYPE+".multiple_results"),o(Le,"matches",J(Le.TYPE));let $e=Le;const qe=class qe extends te{constructor(t,n){super(t);o(this,"type",qe.TYPE);o(this,"path");this.path=n}};o(qe,"TYPE",me+"route"),o(qe,"matches",J(qe.TYPE));let mt=qe;const Ye=class Ye extends te{constructor(){super(...arguments);o(this,"type",Ye.TYPE)}};o(Ye,"TYPE",me+"control"),o(Ye,"matches",J(Ye.TYPE));let He=Ye;const We=class We extends He{constructor(){super(...arguments);o(this,"type",We.TYPE)}};o(We,"TYPE",He.TYPE+".unauthorized"),o(We,"matches",J(We.TYPE));let Gt=We;const _e=class _e extends te{constructor(){super(...arguments);o(this,"type",_e.TYPE)}};o(_e,"TYPE",me+"contiguity"),o(_e,"matches",J(_e.TYPE));let Br=_e;const Pc=r=>{if(!r.type.startsWith(me))return null;if(r.type.startsWith(x.TYPE)){if(r.type===Kt.TYPE){const e=r.data.split(": ");return e.length<2?new x(r.data):new Kt(e[0],e[1])}return new x(r.data)}return r.type.startsWith(ke.TYPE)?r.type.startsWith(gt.TYPE)?new gt(r.data):new ke(r.data):r.type.startsWith(pe.TYPE)?new pe(r.data):r.type.startsWith(Q.TYPE)?r.type.startsWith(Ae.TYPE)?new Ae(r.data):r.type.startsWith($e.TYPE)?new $e(r.data):new Q(r.data):r.type.startsWith(He.TYPE)?r.type.startsWith(Gt.TYPE)?new Gt(r.data):new He(r.data):r.type.startsWith(mt.TYPE)?new mt(r.data,r.data):new pe(r.data)},Dc=()=>{throw new Error("Not implemented")};fs({encode:Dc,decode:Pc});const jc=async(r,e)=>{const[t,n]=await e(r);return n==null?[t,n]:n instanceof Ne?[t,new Ne({message:`Cannot reach cluster at ${n.url.host}:${n.url.port}`,url:n.url})]:[t,n]};class Ys{constructor(e,t){o(this,"key");o(this,"name");this.key=t,this.name=e}get ontologyID(){return new T({type:"group",key:this.key})}}const Mc=s.z.string().uuid(),Ws=s.z.object({key:Mc,name:s.z.string()}),rr=s.z.union([s.z.literal("label"),s.z.literal("builtin"),s.z.literal("cluster"),s.z.literal("channel"),s.z.literal("node"),s.z.literal("group"),s.z.literal("range"),s.z.literal("range-alias"),s.z.literal("user"),s.z.literal("workspace"),s.z.literal("schematic"),s.z.literal("lineplot"),s.z.literal("rack"),s.z.literal("device"),s.z.literal("task"),s.z.literal("policy")]),Zc="builtin",Uc="cluster",Bc="node",G=s.z.object({type:rr,key:s.z.string()}),_s=s.z.string().transform(r=>{const[e,t]=r.split(":");return{type:e,key:t}}),Vs=s.z.union([_s,G]),Ve=class Ve{constructor(e){o(this,"type");o(this,"key");if(e instanceof Ve)this.type=e.type,this.key=e.key;else if(typeof e=="string"){const[t,n]=e.split(":");this.type=t,this.key=n}else this.type=e.type,this.key=e.key}toString(){return`${this.type}:${this.key}`}get payload(){return{type:this.type,key:this.key}}};o(Ve,"z",s.z.union([Vs,s.z.instanceof(Ve)]).transform(e=>new Ve(e)));let T=Ve;const Lc=new T({type:"builtin",key:"root"}),Fs=s.z.object({type:s.z.number()}),Ks=s.z.object({type:rr,fields:s.z.record(Fs)}),Gs=s.z.object({id:T.z,name:s.z.string(),schema:Ks.optional().nullable(),data:s.z.record(s.z.unknown()).optional().nullable()}).transform(r=>({key:r.id.toString(),...r})),qc=s.z.object({from:T.z,type:s.z.string(),to:T.z}),Lr=r=>{const[e,t,n]=r.split("->");return{from:new T(e),type:t,to:new T(n)}},Yc=s.z.object({group:Ws}),Wc=s.z.object({parent:G,key:s.z.string().uuid().optional(),name:s.z.string()}),_c=s.z.object({key:s.z.string(),name:s.z.string()}),Vc=s.z.object({keys:s.z.array(s.z.string())});var ee;let Fc=(ee=class{constructor(e){o(this,"client");this.client=e}async create(e,t,n){return(await w(this.client,ee.ENDPOINT,{parent:e,name:t,key:n},Wc,Yc)).group}async rename(e,t){await w(this.client,ee.ENDPOINT_RENAME,{key:e,name:t},_c,s.z.object({}))}async delete(e){await w(this.client,ee.ENDPOINT_DELETE,{keys:e},Vc,s.z.object({}))}},o(ee,"ENDPOINT","/ontology/create-group"),o(ee,"ENDPOINT_RENAME","/ontology/rename-group"),o(ee,"ENDPOINT_DELETE","/ontology/delete-group"),ee),Kc=class{constructor(e){o(this,"creator");this.creator=new Fc(e)}async create(e,t,n){return this.sugar(await this.creator.create(e,t,n))}async rename(e,t){return await this.creator.rename(e,t)}async delete(...e){return await this.creator.delete(e)}sugar(e){return new Ys(e.name,e.key)}};const Or={ADD_CHILDREN:"/ontology/add-children",REMOVE_CHILDREN:"/ontology/remove-children",MOVE_CHILDREN:"/ontology/move-children"},Un=s.z.object({id:G,children:G.array()}),Gc=s.z.object({from:G,to:G,children:G.array()});let Jc=class{constructor(e){o(this,"client");this.client=e}async addChildren(e,...t){await w(this.client,Or.ADD_CHILDREN,{id:new T(e).payload,children:t.map(n=>new T(n).payload)},Un,s.z.object({}))}async removeChildren(e,...t){await w(this.client,Or.REMOVE_CHILDREN,{id:new T(e).payload,children:t.map(n=>new T(n).payload)},Un,s.z.object({}))}async moveChildren(e,t,...n){const i={from:new T(e).payload,to:new T(t).payload,children:n.map(a=>new T(a).payload)};await w(this.client,Or.MOVE_CHILDREN,i,Gc,s.z.object({}))}};const Hc="/ontology/retrieve",Xc=s.z.object({ids:G.array().optional(),children:s.z.boolean().optional(),parents:s.z.boolean().optional(),includeSchema:s.z.boolean().optional(),excludeFieldData:s.z.boolean().optional(),term:s.z.string().optional(),limit:s.z.number().optional(),offset:s.z.number().optional(),types:rr.array().optional()}),Qc=s.z.object({resources:Gs.array()}),_t=r=>O(r).map(e=>new T(e).payload);let Js=class{constructor(e,t){o(this,"type","ontology");o(this,"groups");o(this,"client");o(this,"writer");o(this,"framer");this.client=e,this.writer=new Jc(e),this.groups=new Kc(e),this.framer=t}async search(e,t){return await this.execRetrieve({term:e,...t})}async retrieve(e,t){const n=await this.execRetrieve({ids:_t(e),...t});if(Array.isArray(e))return n;if(n.length===0)throw new Q(`No resource found with ID ${e.toString()}`);return n[0]}async page(e,t,n){return await this.execRetrieve({offset:e,limit:t,...n})}async retrieveChildren(e,t){return await this.execRetrieve({ids:_t(e),children:!0,...t})}async retrieveParents(e,t){return await this.execRetrieve({ids:_t(e),parents:!0,...t})}async addChildren(e,...t){return await this.writer.addChildren(e,...t)}async removeChildren(e,...t){return await this.writer.removeChildren(e,...t)}async moveChildren(e,t,...n){return await this.writer.moveChildren(e,t,...n)}async openChangeTracker(){return await Et.open(this.framer,this)}async openDependentTracker(e){return await nr.open(e,this.framer,this)}newSearcherWithOptions(e){return{type:this.type,search:t=>this.search(t,e),retrieve:t=>this.retrieve(t,e),page:(t,n)=>this.page(t,n,e)}}async execRetrieve(e){const{resources:t}=await w(this.client,Hc,e,Xc,Qc);return t}};const Bn="sy_ontology_resource_set",Ln="sy_ontology_resource_delete",qn="sy_ontology_relationship_set",Yn="sy_ontology_relationship_delete";class Et{constructor(e,t){o(this,"relationships");o(this,"resources");o(this,"resourceObs");o(this,"relationshipObs");o(this,"streamer");o(this,"client");o(this,"closePromise");this.relationshipObs=new Ie.Observer,this.relationships=this.relationshipObs,this.resourceObs=new Ie.Observer,this.resources=this.resourceObs,this.client=t,this.streamer=e,this.closePromise=this.start()}async close(){this.streamer.close(),await this.closePromise}async start(){for await(const e of this.streamer)await this.update(e)}async update(e){const t=await this.parseResourceSets(e),n=this.parseResourceDeletes(e);t.concat(n).length>0&&this.resourceObs.notify(t.concat(n));const a=this.parseRelationshipSets(e),c=this.parseRelationshipDeletes(e);a.concat(c).length>0&&this.relationshipObs.notify(a.concat(c))}parseRelationshipSets(e){const t=e.get(qn);return t.length===0?[]:Array.from(t.as("string")).map(n=>({variant:"set",key:Lr(n),value:void 0}))}parseRelationshipDeletes(e){const t=e.get(Yn);return t.length===0?[]:Array.from(t.as("string")).map(n=>({variant:"delete",key:Lr(n)}))}async parseResourceSets(e){const t=e.get(Bn);if(t.length===0)return[];const n=Array.from(t.as("string")).map(i=>new T(i));try{return(await this.client.retrieve(n)).map(a=>({variant:"set",key:a.id,value:a}))}catch(i){if(i instanceof Q)return[];throw i}}parseResourceDeletes(e){const t=e.get(Ln);return t.length===0?[]:Array.from(t.as("string")).map(n=>({variant:"delete",key:new T(n)}))}static async open(e,t){const n=await e.openStreamer([Bn,Ln,qn,Yn]);return new Et(n,t)}}const Wn=r=>r==="from"?"to":"from";class nr extends Ie.Observer{constructor({target:t,dependents:n,relationshipType:i="parent",relationshipDirection:a="from",resourceType:c},l,u){super();o(this,"internal");o(this,"target");o(this,"relDir");o(this,"resourceType");o(this,"dependents");o(this,"client");o(this,"relType");o(this,"handleResourceChange",t=>{this.dependents=this.dependents.map(n=>{const i=t.find(a=>a.key.toString()==n.id.toString());return i==null||i.variant==="delete"?n:i.value}),this.notify(this.dependents)});o(this,"handleRelationshipChange",t=>{const n=t.filter(a=>a.variant==="delete"&&a.key[this.relDir].toString()===this.target.toString()&&(this.resourceType==null||a.key[Wn(this.relDir)].type===this.resourceType));this.dependents=this.dependents.filter(a=>!n.some(c=>c.key.to.toString()===a.id.toString()&&c.key.type===this.relType));const i=t.filter(a=>a.variant==="set"&&a.key.type===this.relType&&a.key[this.relDir].toString()===this.target.toString()&&(this.resourceType==null||a.key[Wn(this.relDir)].type===this.resourceType));if(i.length===0)return this.notify(this.dependents);this.client.retrieve(i.map(a=>a.key.to)).then(a=>{this.dependents=this.dependents.concat(a),this.notify(this.dependents)})});this.resourceType=c,this.internal=l,this.target=t,this.dependents=n,this.resourceType!=null&&(this.dependents=this.dependents.filter(h=>h.id.type===this.resourceType)),this.client=u,this.relType=i,this.relDir=a,this.internal.resources.onChange(this.handleResourceChange),this.internal.relationships.onChange(this.handleRelationshipChange)}static async open(t,n,i){const a=await Et.open(n,i);return new nr(t,a,i)}async close(){await this.internal.close()}}const el=Object.freeze(Object.defineProperty({__proto__:null,BuiltinOntologyType:Zc,ChangeTracker:Et,Client:Js,ClusterOntologyType:Uc,DependentTracker:nr,ID:T,NodeOntologyType:Bc,Root:Lc,crudeIDZ:Vs,idZ:G,parseIDs:_t,parseRelationship:Lr,relationshipSchemaZ:qc,resourceSchemaZ:Gs,resourceTypeZ:rr,schemaFieldZ:Fs,schemaZ:Ks,stringIDZ:_s},Symbol.toStringTag,{value:"Module"})),we=s.z.number(),St=s.z.object({name:s.z.string(),key:s.z.number(),rate:tr.z,dataType:z.z,leaseholder:s.z.number(),index:s.z.number(),isIndex:s.z.boolean(),internal:s.z.boolean(),virtual:s.z.boolean(),alias:s.z.string().optional()}),Hs=St.extend({key:s.z.number().optional(),leaseholder:s.z.number().optional(),index:s.z.number().optional(),rate:tr.z.optional().default(0),isIndex:s.z.boolean().optional(),internal:s.z.boolean().optional().default(!1),virtual:s.z.boolean().optional().default(!1)}),Xs="channel",tl=r=>new T({type:Xs,key:r.toString()}),rl=new Error("request for lock canceled");var nl=function(r,e,t,n){function i(a){return a instanceof t?a:new t(function(c){c(a)})}return new(t||(t=Promise))(function(a,c){function l(p){try{h(n.next(p))}catch(g){c(g)}}function u(p){try{h(n.throw(p))}catch(g){c(g)}}function h(p){p.done?a(p.value):i(p.value).then(l,u)}h((n=n.apply(r,e||[])).next())})};class sl{constructor(e,t=rl){this._value=e,this._cancelError=t,this._queue=[],this._weightedWaiters=[]}acquire(e=1,t=0){if(e<=0)throw new Error(`invalid weight ${e}: must be positive`);return new Promise((n,i)=>{const a={resolve:n,reject:i,weight:e,priority:t},c=Qs(this._queue,l=>t<=l.priority);c===-1&&e<=this._value?this._dispatchItem(a):this._queue.splice(c+1,0,a)})}runExclusive(e){return nl(this,arguments,void 0,function*(t,n=1,i=0){const[a,c]=yield this.acquire(n,i);try{return yield t(a)}finally{c()}})}waitForUnlock(e=1,t=0){if(e<=0)throw new Error(`invalid weight ${e}: must be positive`);return this._couldLockImmediately(e,t)?Promise.resolve():new Promise(n=>{this._weightedWaiters[e-1]||(this._weightedWaiters[e-1]=[]),il(this._weightedWaiters[e-1],{resolve:n,priority:t})})}isLocked(){return this._value<=0}getValue(){return this._value}setValue(e){this._value=e,this._dispatchQueue()}release(e=1){if(e<=0)throw new Error(`invalid weight ${e}: must be positive`);this._value+=e,this._dispatchQueue()}cancel(){this._queue.forEach(e=>e.reject(this._cancelError)),this._queue=[]}_dispatchQueue(){for(this._drainUnlockWaiters();this._queue.length>0&&this._queue[0].weight<=this._value;)this._dispatchItem(this._queue.shift()),this._drainUnlockWaiters()}_dispatchItem(e){const t=this._value;this._value-=e.weight,e.resolve([t,this._newReleaser(e.weight)])}_newReleaser(e){let t=!1;return()=>{t||(t=!0,this.release(e))}}_drainUnlockWaiters(){if(this._queue.length===0)for(let e=this._value;e>0;e--){const t=this._weightedWaiters[e-1];t&&(t.forEach(n=>n.resolve()),this._weightedWaiters[e-1]=[])}else{const e=this._queue[0].priority;for(let t=this._value;t>0;t--){const n=this._weightedWaiters[t-1];if(!n)continue;const i=n.findIndex(a=>a.priority<=e);(i===-1?n:n.splice(0,i)).forEach(a=>a.resolve())}}}_couldLockImmediately(e,t){return(this._queue.length===0||this._queue[0].priority<t)&&e<=this._value}}function il(r,e){const t=Qs(r,n=>e.priority<=n.priority);r.splice(t+1,0,e)}function Qs(r,e){for(let t=r.length-1;t>=0;t--)if(e(r[t]))return t;return-1}var al=function(r,e,t,n){function i(a){return a instanceof t?a:new t(function(c){c(a)})}return new(t||(t=Promise))(function(a,c){function l(p){try{h(n.next(p))}catch(g){c(g)}}function u(p){try{h(n.throw(p))}catch(g){c(g)}}function h(p){p.done?a(p.value):i(p.value).then(l,u)}h((n=n.apply(r,e||[])).next())})};class ol{constructor(e){this._semaphore=new sl(1,e)}acquire(){return al(this,arguments,void 0,function*(e=0){const[,t]=yield this._semaphore.acquire(1,e);return t})}runExclusive(e,t=0){return this._semaphore.runExclusive(()=>e(),1,t)}isLocked(){return this._semaphore.isLocked()}waitForUnlock(e=0){return this._semaphore.waitForUnlock(1,e)}release(){this._semaphore.isLocked()&&this._semaphore.release()}cancel(){return this._semaphore.cancel()}}const sr=(r,e,{convertNumericStrings:t=!0}={})=>{const n=!Array.isArray(r);let i=O(r);const a=i[0],c=typeof a;let l;return c==="string"&&t&&!isNaN(parseInt(a))&&"number"in e?(l=e.number,i=i.map(u=>parseInt(u))):l=e[c],{single:n,variant:l,normalized:i,actual:r}},ir=(r,e,t,n)=>{if(n){if(t.length===0)throw new Ae(`${r} not found matching ${JSON.stringify(e)}`);if(t.length>1)throw new $e(`Expected one ${r} matching ${JSON.stringify(e)}, but found ${t.length}`)}},be=r=>s.z.union([s.z.null().transform(()=>[]),r.array()]),cl=s.z.object({leaseholder:s.z.number().optional(),keys:s.z.number().array().optional(),names:s.z.string().array().optional(),search:s.z.string().optional(),rangeKey:s.z.string().optional(),limit:s.z.number().optional(),offset:s.z.number().optional(),dataTypes:z.z.array().optional(),notDataTypes:z.z.array().optional(),virtual:s.z.boolean().optional(),isIndex:s.z.boolean().optional(),internal:s.z.boolean().optional()}),ll=s.z.object({channels:be(St)}),ye=r=>sr(r,{number:"keys",string:"names"}),Ht=class Ht{constructor(e){o(this,"client");this.client=e}async search(e,t){return await this.execute({search:e,...t})}async retrieve(e,t){const n=ye(e),{variant:i}=n;let{normalized:a}=n;return i==="keys"&&a.indexOf(0)!==-1&&(a=a.filter(c=>c!==0)),a.length===0?[]:await this.execute({[i]:a,...t})}async page(e,t,n){return await this.execute({offset:e,limit:t,...n})}async execute(e){const[t,n]=await this.client.send(Ht.ENDPOINT,e,cl,ll);if(n!=null)throw n;return t.channels}};o(Ht,"ENDPOINT","/channel/retrieve");let wt=Ht;class Gr{constructor(e){o(this,"cache");o(this,"namesToKeys");o(this,"wrapped");this.cache=new Map,this.namesToKeys=new Map,this.wrapped=e}async search(e,t){return await this.wrapped.search(e,t)}async page(e,t,n){return await this.wrapped.page(e,t,n)}async retrieve(e,t){const{normalized:n}=sr(e,{string:"names",number:"keys"}),i=[],a=[];if(n.forEach(l=>{const u=this.get(l);u!=null?i.push(...u):a.push(l)}),a.length===0)return i;const c=await this.wrapped.retrieve(a,t);return this.set(c),i.concat(c)}delete(e){const{variant:t,normalized:n}=ye(e);t==="names"?n.forEach(i=>{const a=this.namesToKeys.get(i);a!=null&&(a.forEach(c=>this.cache.delete(c)),this.namesToKeys.delete(i))}):n.forEach(i=>{const a=this.cache.get(i);a!=null&&(this.cache.delete(i),this.namesToKeys.delete(a.name))})}rename(e,t){e.forEach((n,i)=>{const a=t[i],c=this.cache.get(n);if(c==null)return;this.cache.delete(n);const l=this.namesToKeys.get(c.name);l!=null&&(l.delete(n),l.size===0&&this.namesToKeys.delete(c.name)),c.name=a,this.cache.set(n,c);const u=this.namesToKeys.get(a);u==null?this.namesToKeys.set(a,new Set([n])):u.add(n)})}set(e){e.forEach(t=>{this.cache.set(t.key,t);const n=this.namesToKeys.get(t.name);n==null?this.namesToKeys.set(t.name,new Set([t.key])):n.add(t.key)})}get(e){if(typeof e=="number"){const i=this.cache.get(e);return i==null?void 0:[i]}const t=this.namesToKeys.get(e);if(t==null)return;const n=[];if(t.forEach(i=>{const a=this.cache.get(i);a!=null&&n.push(a)}),n.length!==0)return n}}class ei{constructor(e,t){o(this,"mu",new ol);o(this,"requests",new Map);o(this,"wrapped");o(this,"debouncedRun");this.wrapped=e,this.debouncedRun=dc(()=>{this.run()},t)}async search(e,t){return await this.wrapped.search(e,t)}async page(e,t,n){return await this.wrapped.page(e,t,n)}async retrieve(e){const{normalized:t,variant:n}=ye(e);return n==="names"?await this.wrapped.retrieve(t):await new Promise((a,c)=>{this.mu.runExclusive(()=>{this.requests.set(t,{resolve:a,reject:c}),this.debouncedRun()})})}async run(){await this.mu.runExclusive(async()=>{const e=new Set;this.requests.forEach((t,n)=>n.forEach(i=>e.add(i)));try{const t=await this.wrapped.retrieve(Array.from(e));this.requests.forEach((n,i)=>n.resolve(t.filter(a=>i.includes(a.key))))}catch(t){this.requests.forEach(n=>n.reject(t))}finally{this.requests.clear()}})}}const ti=async(r,e)=>{const{normalized:t}=ye(e),n=await r.retrieve(t),i=[];if(t.forEach(a=>{n.find(c=>c.name===a||c.key===a)==null&&i.push(a)}),i.length>0)throw new Q(`Could not find channels: ${JSON.stringify(i)}`);return n};class Jr{constructor({dataType:e,rate:t,name:n,leaseholder:i=0,key:a=0,isIndex:c=!1,index:l=0,internal:u=!1,virtual:h=!1,frameClient:p,alias:g}){o(this,"_frameClient");o(this,"key");o(this,"name");o(this,"rate");o(this,"dataType");o(this,"leaseholder");o(this,"index");o(this,"isIndex");o(this,"internal");o(this,"alias");o(this,"virtual");this.key=a,this.name=n,this.rate=new tr(t??0),this.dataType=new z(e),this.leaseholder=i,this.index=l,this.isIndex=c,this.internal=u,this.alias=g,this.virtual=h,this._frameClient=p??null}get framer(){if(this._frameClient==null)throw new x("cannot read from a channel that has not been created");return this._frameClient}get payload(){return St.parse({key:this.key,name:this.name,rate:this.rate.valueOf(),dataType:this.dataType.valueOf(),leaseholder:this.leaseholder,index:this.index,isIndex:this.isIndex,internal:this.internal})}get ontologyID(){return new T({type:"channel",key:this.key.toString()})}async read(e){return await this.framer.read(e,this.key)}async write(e,t){return await this.framer.write(e,this.key,t)}}const ul="/channel/retrieve-group",hl=s.z.object({}),yl=s.z.object({group:Ws});let ri=class{constructor(e,t,n,i){o(this,"type","channel");o(this,"frameClient");o(this,"client");o(this,"retriever");o(this,"writer");this.frameClient=e,this.retriever=t,this.client=n,this.writer=i}async create(e,t={}){const{retrieveIfNameExists:n=!1}=t,i=!Array.isArray(e);let a=O(e),c=[];if(n){const l=await this.retriever.retrieve(a.map(h=>h.name)),u=new Set(l.map(h=>h.name));a=a.filter(h=>!u.has(h.name)),c=this.sugar(l)}return c=c.concat(this.sugar(await this.writer.create(a))),i?c[0]:c}async retrieve(e,t){const n=!Array.isArray(e),i=this.sugar(await this.retriever.retrieve(e,t));return ir("channel",e,i,n),n?i[0]:i}async search(e,t){return this.sugar(await this.retriever.search(e,t))}async delete(e){const{normalized:t,variant:n}=ye(e);return n==="keys"?await this.writer.delete({keys:t}):await this.writer.delete({names:t})}async rename(e,t){return await this.writer.rename(O(e),O(t))}newSearcherWithOptions(e){return{type:this.type,search:async t=>await this.search(t,e),retrieve:async t=>await this.retrieve(t,e),page:async(t,n)=>await this.page(t,n,e)}}async page(e,t,n){return this.sugar(await this.retriever.page(e,t,n))}createDebouncedBatchRetriever(e=10){return new Gr(new ei(new wt(this.client),e))}sugar(e){const{frameClient:t}=this;return e.map(n=>new Jr({...n,frameClient:t}))}async retrieveGroup(){const e=await w(this.client,ul,{},hl,yl);return new Ys(e.group.name,e.group.key)}};const dl=s.z.object({channels:Hs.array()}),fl=s.z.object({channels:St.array()}),pl=s.z.object({keys:we.array().optional(),names:s.z.string().array().optional()}),gl=s.z.object({}),ml=s.z.object({keys:we.array(),names:s.z.string().array()}),wl=s.z.object({}),bl="/channel/create",vl="/channel/delete",Tl="/channel/rename";let ni=class{constructor(e,t){o(this,"client");o(this,"cache");this.client=e,this.cache=t}async create(e){const{channels:t}=await w(this.client,bl,{channels:e},dl,fl);return this.cache.set(t),t}async delete(e){await w(this.client,vl,e,pl,gl),e.keys!=null&&this.cache.delete(e.keys),e.names!=null&&this.cache.delete(e.names)}async rename(e,t){await w(this.client,Tl,{keys:e,names:t},ml,wl),this.cache.rename(e,t)}};const Ol=Object.freeze(Object.defineProperty({__proto__:null,CacheRetriever:Gr,Channel:Jr,ChannelOntologyType:Xs,Client:ri,ClusterRetriever:wt,DebouncedBatchRetriever:ei,Writer:ni,analyzeChannelParams:ye,keyZ:we,newPayload:Hs,ontologyID:tl,payload:St,retrieveRequired:ti},Symbol.toStringTag,{value:"Module"})),Hr=s.z.string().uuid(),Xr=s.z.object({key:Hr,subjects:G.array(),objects:G.array(),actions:s.z.string().array()}),zl=Xr.extend({key:Hr.optional()}),El="/access/policy/create",Sl="/access/policy/delete",Nl="/access/policy/retrieve",Il=s.z.object({policies:zl.array()}),kl=s.z.object({policies:Xr.array()}),Al=s.z.object({keys:Hr.array()}),$l=s.z.object({}),Rl=s.z.object({subject:G}),Cl=s.z.object({policies:Xr.array().optional().default([])});let xl=class{constructor(e){o(this,"client");this.client=e}async create(e){const t=!Array.isArray(e),{policies:n}=await w(this.client,El,{policies:O(e)},Il,kl);return t?n[0]:n}async retrieve(e){const{policies:t}=await w(this.client,Nl,{subject:e},Rl,Cl);return t}async delete(e){await w(this.client,Sl,{keys:O(e)},Al,$l)}};const Pl="/user/register";let Dl=class{constructor(e){o(this,"client");this.client=e}async register(e,t){const{user:n}=await w(this.client,Pl,{username:e,password:t},si,ii);return n}};s.z.string().uuid();const jl=s.z.object({key:s.z.string(),username:s.z.string()}),si=s.z.object({username:s.z.string(),password:s.z.string()}),ii=s.z.object({token:s.z.string(),user:jl}),_n="/auth/login",Ml=3;let Zl=class{constructor(e,t){o(this,"token");o(this,"client");o(this,"credentials");o(this,"authenticating");o(this,"authenticated");o(this,"user");o(this,"retryCount");this.client=e,this.authenticated=!1,this.credentials=t,this.retryCount=0}middleware(){const e=async(t,n)=>{if(!this.authenticated&&!t.target.endsWith(_n)){this.authenticating==null&&(this.authenticating=new Promise((l,u)=>{this.client.send(_n,this.credentials,si,ii).then(([h,p])=>{if(p!=null)return l(p);this.token=h==null?void 0:h.token,this.user=h==null?void 0:h.user,this.authenticated=!0,l(null)}).catch(u)}));const c=await this.authenticating;if(c!=null)return[t,c]}t.params.Authorization=`Bearer ${this.token}`;const[i,a]=await n(t);return gt.matches(a)&&this.retryCount<Ml?(this.authenticated=!1,this.authenticating=void 0,this.retryCount+=1,e(t,n)):(this.retryCount=0,[i,a])};return e}};const Ul=["disconnected","connecting","connected","failed"],ai=s.z.enum(Ul),oi=s.z.object({status:ai,error:s.z.instanceof(Error).optional(),message:s.z.string().optional(),clusterKey:s.z.string(),clientVersion:s.z.string(),clientServerCompatible:s.z.boolean(),nodeVersion:s.z.string().optional()}),Bl=s.z.object({clusterKey:s.z.string(),nodeVersion:s.z.string().optional()}),Vn={clusterKey:"",status:"disconnected",error:void 0,message:"Disconnected",clientServerCompatible:!1,clientVersion:"0.29.0"},Fn=(r,e,t)=>{const n=t?"cluster":"client";return`Synnax cluster node version ${r!=null?r+" ":""}is too ${t?"old":"new"} for client version ${e}.
24
+ This may cause compatibility issues. We recommend updating the ${n}. For more information, see
25
+ https://docs.synnaxlabs.com/reference/typescript-client/troubleshooting#old-${n}-version`},Fe=class Fe{constructor(e,t=E.seconds(30),n,i){o(this,"_state");o(this,"pollFrequency",E.seconds(30));o(this,"client");o(this,"name");o(this,"interval");o(this,"clientVersion");o(this,"onChangeHandlers",[]);o(this,"versionWarned",!1);this._state={...Vn},this.client=e,this.pollFrequency=t,this.clientVersion=n,this.name=i,this.check(),this.startChecking()}stopChecking(){this.interval!=null&&clearInterval(this.interval)}async check(){var t;const e=this._state.status;try{const[n,i]=await this.client.send(Fe.ENDPOINT,{},s.z.object({}),Bl);if(i!=null)throw i;const a=n.nodeVersion,c=this.clientVersion,l=this.versionWarned;a==null?(this._state.clientServerCompatible=!1,l||(console.warn(Fn(null,c,!0)),this.versionWarned=!0)):Zn.versionsEqual(c,a,{checkMajor:!0,checkMinor:!0,checkPatch:!1})?this._state.clientServerCompatible=!0:(this._state.clientServerCompatible=!1,l||(console.warn(Fn(a,c,Zn.semVerNewer(c,a))),this.versionWarned=!0)),this._state.status="connected",this._state.message=`Connected to ${this.name??"cluster"}`,this._state.clusterKey=n.clusterKey,this._state.nodeVersion=n.nodeVersion,this._state.clientVersion=this.clientVersion}catch(n){this._state.status="failed",this._state.error=n,this._state.message=(t=this.state.error)==null?void 0:t.message}return this.onChangeHandlers.length>0&&e!==this._state.status&&this.onChangeHandlers.forEach(n=>n(this.state)),this.state}get state(){return{...this._state}}onChange(e){this.onChangeHandlers.push(e)}startChecking(){this.interval=setInterval(()=>{this.check()},this.pollFrequency.milliseconds)}};o(Fe,"ENDPOINT","/connectivity/check"),o(Fe,"DEFAULT",Vn),o(Fe,"connectionStateZ",oi);let bt=Fe;const Ll=Object.freeze(Object.defineProperty({__proto__:null,Checker:bt,state:oi,status:ai},Symbol.toStringTag,{value:"Module"})),ql=s.z.object({keys:we.array().optional(),bounds:W.z,names:s.z.string().array().optional()}),Yl=s.z.object({}),Wl="/frame/delete";class _l{constructor(e){o(this,"client");this.client=e}async delete(e){await w(this.client,Wl,e,ql,Yl)}}const Kn=r=>{const e=O(r);return e.length===0?null:typeof e[0]=="number"||!isNaN(parseInt(e[0]))?"key":"name"},Gn=(r,e)=>{const t=O(r);if(t.length===e.length)return;const n=Kn(r);throw Kn===null?new x("[Frame] - channel keys or names must be provided when constructing a frame."):new x(`[Frame] - ${n}s and series must be the same length.
26
+ Got ${t.length} ${n}s and ${e.length} series.`)};class U{constructor(e=[],t=[]){o(this,"columns",[]);o(this,"series",[]);if(e instanceof U){this.columns=e.columns,this.series=e.series;return}if(e instanceof Map){e.forEach((i,a)=>this.push(a,...O(i)));return}if(typeof e=="object"&&!Array.isArray(e)){if("keys"in e&&"series"in e){const i=e,a=i.series.map(c=>li(c));Gn(i.keys,a),i.keys.forEach((c,l)=>this.push(c,a[l]))}else Object.entries(e).forEach(([i,a])=>{const c=parseInt(i);if(isNaN(c))this.push(i,...O(a));else return this.push(c,...O(a))});return}if(Array.isArray(e)||["string","number"].includes(typeof e)){const i=O(t),a=O(e);Gn(a,i),i.forEach((c,l)=>this.push(a[l],c));return}throw new x(`[Frame] - invalid frame construction parameters. data parameter ust be a frame
23
27
  payload, a list of lazy series, a lazy array, a map, or a record keyed by channel
24
- 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 pe("colType is not key");return this.columns??[]}get uniqueKeys(){return Rn(this.keys)}get names(){if(this.colType==="key")throw new pe("colType is not name");return this.columns??[]}get uniqueNames(){return Rn(this.names)}get uniqueColumns(){return this.colType==="key"?this.uniqueKeys:this.uniqueNames}toPayload(){return{series:this.series.map(e=>ti(e)),keys:this.keys}}get isVertical(){return this.uniqueColumns.length===this.columns.length}get isHorizontal(){return this.uniqueColumns.length===1}get isSquare(){return this.isHorizontal&&this.isVertical}get isWeaklyAligned(){if(this.columns.length<=1)return!0;const e=this.timeRanges;return e.every(t=>t.equals(e[0]))}timeRange(e){if(e==null){if(this.columns.length===0)return W.ZERO;const n=E.min(...this.series.map(a=>a.timeRange.start)),i=E.max(...this.series.map(a=>a.timeRange.end));return new W(n,i)}const t=this.get(e);return t==null?W.ZERO:t.timeRange}latest(){return this.at(-1)}get timeRanges(){return this.uniqueColumns.map(e=>this.timeRange(e))}get(e){return Array.isArray(e)?this.filter(t=>e.includes(t)):new ks(this.series.filter((t,n)=>this.columns[n]===e))}push(e,...t){if(e instanceof U){if(this.colType!==null&&e.colType!==this.colType)throw new C("keyVariant must match");this.series.push(...e.series),this.columns.push(...e.columns)}else{if(this.series.push(...t),typeof e=="string"&&this.colType==="key")throw new C("keyVariant must match");if(typeof e!="string"&&this.colType==="name")throw new C("keyVariant must match");this.columns.push(...Array.from({length:t.length},()=>e))}}concat(e){return new U([...this.columns,...e.columns],[...this.series,...e.series])}has(e){return typeof e=="string"&&this.colType==="key"||typeof e=="number"&&this.colType==="name"?!1:this.columns.includes(e)}map(e){const t=new U;return this.forEach((n,i,a)=>t.push(...e(n,i,a))),t}forEach(e){this.columns.forEach((t,n)=>{const i=this.series[n];e(t,i,n)})}at(e,t=!1){const n={};return this.uniqueColumns.forEach(i=>{n[i]=this.get(i).at(e,t)}),n}filter(e){const t=new U;return this.columns.forEach((n,i)=>{const a=this.series[i];e(n,a,i)&&t.push(n,a)}),t}get byteLength(){return new pt(this.series.reduce((e,t)=>e.add(t.byteLength),pt.ZERO))}get length(){return this.series.reduce((e,t)=>e+t.length,0)}}const Qs=s.z.object({timeRange:W.z.optional(),alignment:s.z.bigint().or(s.z.string().transform(r=>BigInt(r))).optional(),dataType:z.z,data:s.z.string().transform(r=>new Uint8Array(atob(r).split("").map(e=>e.charCodeAt(0))).buffer)}),rr=s.z.object({keys:s.z.union([s.z.null().transform(()=>[]),s.z.number().array().optional().default([])]),series:s.z.union([s.z.null().transform(()=>[]),Qs.array().optional().default([])])}),ei=r=>{const{dataType:e,data:t,timeRange:n,alignment:i}=r;return new ze({data:t,dataType:e,timeRange:n,glBufferUsage:"static",alignment:i})},ti=r=>({timeRange:r._timeRange,dataType:r.dataType,data:new Uint8Array(r.data.buffer),alignment:r.alignment});class nr{constructor(e){o(this,"adapter");o(this,"retriever");o(this,"keys");this.retriever=e,this.adapter=null,this.keys=[]}static async open(e,t){const n=new nr(e);return await n.update(t),n}async update(e){const{variant:t,normalized:n}=ye(e);if(t==="keys"){this.adapter=null,this.keys=n;return}const i=await this.retriever.retrieve(n),a=new Map;this.adapter=a,n.forEach(c=>{const l=i.find(u=>u.name===c);if(l==null)throw new Error(`Channel ${c} not found`);a.set(l.key,l.name)}),this.keys=Array.from(this.adapter.keys())}adapt(e){if(this.adapter==null)return e;const t=this.adapter;return e.map((n,i)=>{if(typeof n=="number"){const a=t.get(n);if(a==null)throw new Error(`Channel ${n} not found`);return[a,i]}return[n,i]})}}class Kr{constructor(e){o(this,"adapter");o(this,"retriever");o(this,"keys");this.retriever=e,this.adapter=null,this.keys=[]}static async open(e,t){const n=new Kr(e);return await n.update(t),n}async adaptObjectKeys(e){const t={};for(const[n,i]of Object.entries(e))t[await this.adaptToKey(n)]=i;return t}async update(e){const t=await Fs(this.retriever,e);this.adapter=new Map(t.map(n=>[n.name,n.key])),this.keys=t.map(n=>n.key)}async fetchChannel(e){const t=await this.retriever.retrieve(e);if(t.length===0)throw new Error(`Channel ${e} not found`);return t[0]}async adaptToKey(e){return typeof e=="number"?e:(await this.fetchChannel(e)).key}async adapt(e,t){if(typeof e=="string"||typeof e=="number"){if(t==null)throw new C(`
28
+ 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 pe("colType is not key");return this.columns??[]}get uniqueKeys(){return Mn(this.keys)}get names(){if(this.colType==="key")throw new pe("colType is not name");return this.columns??[]}get uniqueNames(){return Mn(this.names)}get uniqueColumns(){return this.colType==="key"?this.uniqueKeys:this.uniqueNames}toPayload(){return{series:this.series.map(e=>ui(e)),keys:this.keys}}get isVertical(){return this.uniqueColumns.length===this.columns.length}get isHorizontal(){return this.uniqueColumns.length===1}get isSquare(){return this.isHorizontal&&this.isVertical}get isWeaklyAligned(){if(this.columns.length<=1)return!0;const e=this.timeRanges;return e.every(t=>t.equals(e[0]))}timeRange(e){if(e==null){if(this.columns.length===0)return W.ZERO;const n=S.min(...this.series.map(a=>a.timeRange.start)),i=S.max(...this.series.map(a=>a.timeRange.end));return new W(n,i)}const t=this.get(e);return t==null?W.ZERO:t.timeRange}latest(){return this.at(-1)}get timeRanges(){return this.uniqueColumns.map(e=>this.timeRange(e))}get(e){return Array.isArray(e)?this.filter(t=>e.includes(t)):new Ms(this.series.filter((t,n)=>this.columns[n]===e))}push(e,...t){if(e instanceof U){if(this.colType!==null&&e.colType!==this.colType)throw new x("keyVariant must match");this.series.push(...e.series),this.columns.push(...e.columns)}else{if(this.series.push(...t),typeof e=="string"&&this.colType==="key")throw new x("keyVariant must match");if(typeof e!="string"&&this.colType==="name")throw new x("keyVariant must match");this.columns.push(...Array.from({length:t.length},()=>e))}}concat(e){return new U([...this.columns,...e.columns],[...this.series,...e.series])}has(e){return typeof e=="string"&&this.colType==="key"||typeof e=="number"&&this.colType==="name"?!1:this.columns.includes(e)}map(e){const t=new U;return this.forEach((n,i,a)=>t.push(...e(n,i,a))),t}forEach(e){this.columns.forEach((t,n)=>{const i=this.series[n];e(t,i,n)})}at(e,t=!1){const n={};return this.uniqueColumns.forEach(i=>{n[i]=this.get(i).at(e,t)}),n}filter(e){const t=new U;return this.columns.forEach((n,i)=>{const a=this.series[i];e(n,a,i)&&t.push(n,a)}),t}get byteLength(){return new pt(this.series.reduce((e,t)=>e.add(t.byteLength),pt.ZERO))}get length(){return this.series.reduce((e,t)=>e+t.length,0)}}const ci=s.z.object({timeRange:W.z.optional(),alignment:s.z.bigint().or(s.z.string().transform(r=>BigInt(r))).optional(),dataType:z.z,data:s.z.string().transform(r=>new Uint8Array(atob(r).split("").map(e=>e.charCodeAt(0))).buffer)}),ar=s.z.object({keys:s.z.union([s.z.null().transform(()=>[]),s.z.number().array().optional().default([])]),series:s.z.union([s.z.null().transform(()=>[]),ci.array().optional().default([])])}),li=r=>{const{dataType:e,data:t,timeRange:n,alignment:i}=r;return new ze({data:t,dataType:e,timeRange:n,glBufferUsage:"static",alignment:i})},ui=r=>({timeRange:r._timeRange,dataType:r.dataType,data:new Uint8Array(r.data.buffer),alignment:r.alignment});class or{constructor(e){o(this,"adapter");o(this,"retriever");o(this,"keys");this.retriever=e,this.adapter=null,this.keys=[]}static async open(e,t){const n=new or(e);return await n.update(t),n}async update(e){const{variant:t,normalized:n}=ye(e);if(t==="keys"){this.adapter=null,this.keys=n;return}const i=await this.retriever.retrieve(n),a=new Map;this.adapter=a,n.forEach(c=>{const l=i.find(u=>u.name===c);if(l==null)throw new Error(`Channel ${c} not found`);a.set(l.key,l.name)}),this.keys=Array.from(this.adapter.keys())}adapt(e){if(this.adapter==null)return e;const t=this.adapter;return e.map((n,i)=>{if(typeof n=="number"){const a=t.get(n);if(a==null)throw new Error(`Channel ${n} not found`);return[a,i]}return[n,i]})}}class Qr{constructor(e){o(this,"adapter");o(this,"retriever");o(this,"keys");this.retriever=e,this.adapter=null,this.keys=[]}static async open(e,t){const n=new Qr(e);return await n.update(t),n}async adaptObjectKeys(e){const t={};for(const[n,i]of Object.entries(e))t[await this.adaptToKey(n)]=i;return t}async update(e){const t=await ti(this.retriever,e);this.adapter=new Map(t.map(n=>[n.name,n.key])),this.keys=t.map(n=>n.key)}async fetchChannel(e){const t=await this.retriever.retrieve(e);if(t.length===0)throw new Error(`Channel ${e} not found`);return t[0]}async adaptToKey(e){return typeof e=="number"?e:(await this.fetchChannel(e)).key}async adapt(e,t){if(typeof e=="string"||typeof e=="number"){if(t==null)throw new x(`
25
29
  Received a single channel name or key but no series.
26
- `);if(Array.isArray(t)){if(t.some(u=>u instanceof ze||Array.isArray(u)))throw new C(`
30
+ `);if(Array.isArray(t)){if(t.some(u=>u instanceof ze||Array.isArray(u)))throw new x(`
27
31
  Received a single channel name or key but multiple series.
28
- `);t=t}const c=await this.fetchChannel(e),l=new ze({data:t,dataType:c.dataType});return new U(c.key,l)}if(Array.isArray(e)){if(t==null)throw new C(`
32
+ `);t=t}const c=await this.fetchChannel(e),l=new ze({data:t,dataType:c.dataType});return new U(c.key,l)}if(Array.isArray(e)){if(t==null)throw new x(`
29
33
  Received an array of channel names or keys but no series.
30
- `);if(!Array.isArray(t))throw new C(`
34
+ `);if(!Array.isArray(t))throw new x(`
31
35
  Received an array of channel names or keys but no array of series.
32
- `);const c=[],l=[];for(let u=0;u<e.length;u++){const f=await this.fetchChannel(e[u]);if(u>=t.length)throw new C(`
36
+ `);const c=[],l=[];for(let u=0;u<e.length;u++){const h=await this.fetchChannel(e[u]);if(u>=t.length)throw new x(`
33
37
  Received an array of channel names or keys but not enough series.
34
- `);const g=new ze({data:t[u],dataType:f.dataType});c.push(f.key),l.push(g)}return new U(c,l)}if(e instanceof U||e instanceof Map){const c=new U(e);if(this.adapter==null)return c;let l=[];return l=c.columns.map(u=>{var g;const f=typeof u=="string"?(g=this.adapter)==null?void 0:g.get(u):u;if(f==null)throw new C(`
38
+ `);const p=new ze({data:t[u],dataType:h.dataType});c.push(h.key),l.push(p)}return new U(c,l)}if(e instanceof U||e instanceof Map){const c=new U(e);if(this.adapter==null)return c;let l=[];return l=c.columns.map(u=>{var p;const h=typeof u=="string"?(p=this.adapter)==null?void 0:p.get(u):u;if(h==null)throw new x(`
35
39
  Channel ${u} was not provided in the list of channels when opening the writer
36
- `);return f}),new U(l,c.series)}const n=[],i=[],a=Object.entries(e);for(let c=0;c<a.length;c++){const[l,u]=a[c],f=await this.fetchChannel(l),g=new ze({data:u,dataType:f.dataType});n.push(f.key),i.push(g)}return new U(n,i)}}class Gr{constructor(e,t){o(this,"name");o(this,"stream");this.stream=t,this.name=e}async receive(){const[e,t]=await this.stream.receive();if(t!=null)throw t;return e}received(){return this.stream.received()}async closeAndAck(){for(this.stream.closeSend();;){const[e,t]=await this.stream.receive();if(e!=null&&console.warn(`${this.name} received unexpected response on closure.
37
- Please report this error to the Synnax team. ${JSON.stringify(e)}`),t!=null){if(ge.matches(t))return;throw t}}}closeSend(){this.stream.closeSend()}send(e){const t=this.stream.send(e);if(t!=null)throw t}}const Dr=new S(-1);var Vr=(r=>(r[r.Open=0]="Open",r[r.Next=1]="Next",r[r.Prev=2]="Prev",r[r.SeekFirst=3]="SeekFirst",r[r.SeekLast=4]="SeekLast",r[r.SeekLE=5]="SeekLE",r[r.SeekGE=6]="SeekGE",r[r.Valid=7]="Valid",r[r.Error=8]="Error",r))(Vr||{}),ri=(r=>(r[r.None=0]="None",r[r.Ack=1]="Ack",r[r.Data=2]="Data",r))(ri||{});const Al=s.z.object({command:s.z.nativeEnum(Vr),span:S.z.optional(),bounds:W.z.optional(),stamp:E.z.optional(),keys:s.z.number().array().optional(),chunkSize:s.z.number().optional()}),$l=s.z.object({variant:s.z.nativeEnum(ri),ack:s.z.boolean(),command:s.z.nativeEnum(Vr),error:Ot.optional().nullable(),frame:rr.optional()}),ft=class ft{constructor(e,t){o(this,"stream");o(this,"adapter");o(this,"value");this.stream=new Gr("Iterator",e),this.value=new U,this.adapter=t}static async _open(e,t,n,i,a={}){const c=await nr.open(n,t),l=await i.stream(ft.ENDPOINT,Al,$l),u=new ft(l,c);return await u.execute({command:0,keys:c.keys,bounds:new W(e),chunkSize:a.chunkSize??1e5}),u}async next(e=Dr){return await this.execute({command:1,span:new S(e)})}async prev(e=Dr){return await this.execute({command:2,span:new S(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 E(e)})}async seekGE(e){return await this.execute({command:6,stamp:new E(e)})}async valid(){return await this.execute({command:7})}async close(){await this.stream.closeAndAck()}[Symbol.asyncIterator](){return new Rl(this)}async execute(e){for(this.stream.send(e),this.value=new U;;){const t=await this.stream.receive();if(t.variant===1)return t.ack;this.value.push(this.adapter.adapt(new U(t.frame)))}}};o(ft,"ENDPOINT","/frame/iterate");let Kt=ft;class Rl{constructor(e){o(this,"iter");o(this,"open",!1);this.iter=e}async next(){try{let e=!0;return this.open||(await this.iter.seekFirst()||(e=!1),this.open=!0),await this.iter.next()||(e=!1),e||await this.iter.close(),{done:!e,value:this.iter.value}}catch(e){throw await this.iter.close(),e}}}const xl=s.z.object({start:E.z.optional(),keys:s.z.number().array()}),Cl=s.z.object({frame:rr,error:Ot.optional().nullable()}),Pl="/frame/stream";class sr{constructor(e,t){o(this,"stream");o(this,"adapter");this.stream=new Gr("Streamer",e),this.adapter=t}get keys(){return this.adapter.keys}static async _open(e,t,{channels:n,from:i}){const a=await nr.open(e,n),c=await t.stream(Pl,xl,Cl),l=new sr(c,a);return c.send({start:new E(i),keys:a.keys}),l}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 U((await this.stream.receive()).frame))}async update(e){await this.adapter.update(e),this.stream.send({keys:this.adapter.keys})}close(){this.stream.closeSend()}[Symbol.asyncIterator](){return this}}class St extends Ie.Observer{constructor(t,n){super(n);o(this,"streamer");o(this,"closePromise");this.streamer=t,this.closePromise=this.stream()}async close(){this.streamer.close(),await this.closePromise}async stream(){for await(const t of this.streamer)this.notify(t)}}var Jr=(r=>(r[r.Open=0]="Open",r[r.Write=1]="Write",r[r.Commit=2]="Commit",r[r.Error=3]="Error",r[r.SetAuthority=4]="SetAuthority",r))(Jr||{}),He=(r=>(r[r.PersistStream=1]="PersistStream",r[r.Persist=2]="Persist",r[r.Stream=3]="Stream",r))(He||{});const jl=r=>{switch(r){case"persist":return 2;case"stream":return 3;case"persistStream":return 1;default:if(typeof r=="number"&&r in He)return r;throw new Error(`invalid writer mode: ${r}`)}},Dl=new S(-1),Ml=s.z.object({start:E.z.optional(),controlSubject:Ve.subjectZ.optional(),keys:s.z.number().array().optional(),authorities:Ve.Authority.z.array().optional(),mode:s.z.nativeEnum(He).optional(),errOnUnauthorized:s.z.boolean().optional(),enableAutoCommit:s.z.boolean().optional(),autoIndexPersistInterval:S.z.optional()}),Zl=s.z.object({command:s.z.nativeEnum(Jr),config:Ml.optional(),frame:rr.optional()}),Ul=s.z.object({ack:s.z.boolean(),command:s.z.nativeEnum(Jr),error:Ot.optional().nullable()});var fe;let ni=(fe=class{constructor(e,t){o(this,"stream");o(this,"adapter");this.stream=new Gr("Writer",e),this.adapter=t}static async _open(e,t,{channels:n,start:i=E.now(),authorities:a=Ve.Authority.Absolute,controlSubject:c,mode:l=1,errOnUnauthorized:u=!1,enableAutoCommit:f=!1,autoIndexPersistInterval:g=S.SECOND}){const p=await Kr.open(e,n),j=await t.stream(fe.ENDPOINT,Zl,Ul),P=new fe(j,p);return await P.execute({command:0,config:{start:new E(i),keys:p.keys,controlSubject:c,authorities:O(a),mode:jl(l),errOnUnauthorized:u,enableAutoCommit:f,autoIndexPersistInterval:g}}),P}async write(e,t){const n=await this.adapter.adapt(e,t);return this.stream.send({command:1,frame:n.toPayload()}),!0}async setAuthority(e,t){let n={keys:[],authorities:[]};if(typeof e=="number"&&t==null)n={keys:[],authorities:[e]};else{let a;typeof e=="string"||typeof e=="number"?a={[e]:t}:a=e,a=await this.adapter.adaptObjectKeys(a),n={keys:Object.keys(a).map(c=>Number(c)),authorities:Object.values(a)}}return(await this.execute({command:4,config:n})).ack}async commit(){return this.errorAccumulated?!1:(await this.execute({command:2})).ack}async error(){this.stream.send({command:3});const e=await this.execute({command:3});return e.error!=null?Ur(e.error):null}async close(){await this.stream.closeAndAck()}async execute(e){for(this.stream.send(e);;){const t=await this.stream.receive();if(t.command===e.command)return t;console.warn("writer received unexpected response",t)}}get errorAccumulated(){return this.stream.received()}},o(fe,"ENDPOINT","/frame/write"),fe),si=class{constructor(e,t,n){o(this,"streamClient");o(this,"retriever");o(this,"deleter");this.streamClient=e,this.retriever=n,this.deleter=new kl(t)}async openIterator(e,t,n){return await Kt._open(e,t,this.retriever,this.streamClient,n)}async openWriter(e){return(Array.isArray(e)||typeof e!="object")&&(e={channels:e}),await ni._open(this.retriever,this.streamClient,e)}async openStreamer(e){return(Array.isArray(e)||typeof e!="object")&&(e={channels:e}),await sr._open(this.retriever,this.streamClient,e)}async write(e,t,n){if(n==null){const a=t,c=await this.openWriter({start:e,channels:Object.keys(a),mode:He.Persist});try{await c.write(a),await c.commit()}finally{await c.close()}return}const i=await this.openWriter({start:e,channels:t,mode:He.Persist,errOnUnauthorized:!0,enableAutoCommit:!0,autoIndexPersistInterval:S.MAX});try{await i.write(t,n)}finally{await i.close()}}async read(e,t){const{single:n}=ye(t),i=await this.readFrame(e,t);return n?i.get(t):i}async readFrame(e,t){const n=await this.openIterator(e,t),i=new U;try{for await(const a of n)i.push(a)}finally{await n.close()}return i}async delete(e,t){const{normalized:n,variant:i}=ye(e);return i==="keys"?await this.deleter.delete({keys:n,bounds:t}):await this.deleter.delete({names:n,bounds:t})}};const Bl=Object.freeze(Object.defineProperty({__proto__:null,ALWAYS_INDEX_PERSIST_ON_AUTO_COMMIT:Dl,AUTO_SPAN:Dr,Client:si,Frame:U,Iterator:Kt,ObservableStreamer:St,Streamer:sr,Writer:ni,WriterMode:He,frameZ:rr,series:Qs,seriesFromPayload:ei,seriesToPayload:ti},Symbol.toStringTag,{value:"Module"})),Ll=Ve.Authority,ql=Ve.stateZ(s.z.number()),Yl=r=>{var e,t;return r.to==null?`${(e=r.from)==null?void 0:e.resource} - ${(t=r.from)==null?void 0:t.subject.name} -> released`:r.from==null?`${r.to.resource} - released -> ${r.to.subject.name} (${r.to.authority.toString()})`:`${r.to.resource} - ${r.from.subject.name} -> ${r.to.subject.name} (${r.to.authority.toString()})`};class ii extends St{constructor(t){super(t,n=>{const i=this.codec.decode(n.series[0].buffer);return this.merge(i),[i.transfers,!0]});o(this,"states");o(this,"codec");this.states=new Map,this.codec=new Xe.JSONCodec}subjects(){const t=new Map;return this.states.forEach(n=>t.set(n.subject.key,n.subject)),Array.from(t.values())}merge(t){t.transfers.forEach(n=>{n.from==null&&n.to==null&&console.warn("Invalid transfer: ",n),n.to==null?this.states.delete(n.from.resource):this.states.set(n.to.resource,n.to)})}}const Wl="sy_node_1_control";let ai=class{constructor(e){o(this,"framer");this.framer=e}async openStateTracker(){const e=await this.framer.openStreamer(Wl);return new ii(e)}};const _l=Object.freeze(Object.defineProperty({__proto__:null,Authority:Ll,Client:ai,StateTracker:ii,stateZ:ql,transferString:Yl},Symbol.toStringTag,{value:"Module"}));let oi=class{constructor(e,t,n){o(this,"tasks");o(this,"racks");o(this,"devices");this.tasks=e,this.racks=t,this.devices=n}};const Fl=Object.freeze(Object.defineProperty({__proto__:null,Client:oi},Symbol.toStringTag,{value:"Module"})),Qe=s.z.number(),ir=s.z.object({key:Qe,name:s.z.string()}),ci=ir.partial({key:!0}),li="rack",Kl=r=>new T({type:li,key:r.toString()}),ar=s.z.string(),Nt=s.z.object({key:ar,rack:Qe,name:s.z.string(),make:s.z.string(),model:s.z.string(),location:s.z.string(),configured:s.z.boolean().optional(),properties:s.z.record(s.z.unknown()).or(s.z.string().transform(r=>r===""?{}:Xe.JSON_CODEC.decodeString(r)))}),ui=Nt.extend({properties:s.z.unknown().transform(r=>Xe.JSON_CODEC.encodeString(r))}),hi="device",Gl=r=>new T({type:hi,key:r.toString()}),Re=async(r,e,t,n)=>{const i=await r.openStreamer([e,t]),a=c=>{const l=[];return t!=null&&l.push(...c.get(t).series.flatMap(u=>n("delete",u))),e!=null&&l.push(...c.get(e).series.flatMap(u=>n("set",u))),[l,l.length>0]};return new St(i,a)},Vl=Object.freeze(Object.defineProperty({__proto__:null,openObservable:Re},Symbol.toStringTag,{value:"Module"})),Jl="sy_device_set",Hl="sy_device_delete",wr="/hardware/device/retrieve",Xl="/hardware/device/create",Ql="/hardware/device/delete",eu=s.z.object({devices:ui.array()}),tu=s.z.object({devices:Nt.array()}),ru=s.z.object({keys:ar.array()}),nu=s.z.object({}),br=s.z.object({search:s.z.string().optional(),limit:s.z.number().optional(),offset:s.z.number().optional(),keys:ar.array().optional(),names:s.z.string().array().optional(),makes:s.z.string().array().optional()}),vr=s.z.object({devices:be(Nt)});let yi=class{constructor(e,t){o(this,"type","device");o(this,"client");o(this,"frameClient");this.client=e,this.frameClient=t}async retrieve(e,t){const n=!Array.isArray(e),i=await w(this.client,wr,{keys:O(e),...t},br,vr);return tr("Device",e,i.devices,n),n?i.devices[0]:i.devices}async search(e,t){return(await w(this.client,wr,{search:e,...t},br,vr)).devices}async page(e,t,n){return(await w(this.client,wr,{offset:e,limit:t,...n},br,vr)).devices}async create(e){const t=!Array.isArray(e),n=await w(this.client,Xl,{devices:O(e)},eu,tu);return t?n.devices[0]:n.devices}async delete(e){await w(this.client,Ql,{keys:O(e)},ru,nu)}async openDeviceTracker(){return await Re(this.frameClient,Jl,Hl,su)}newSearcherWithOptions(e){return{type:this.type,search:async t=>await this.search(t,e),retrieve:async t=>await this.retrieve(t,e),page:async(t,n)=>await this.page(t,n,e)}}};const su=(r,e)=>r==="delete"?e.toStrings().map(t=>({variant:r,key:t,value:void 0})):e.parseJSON(Nt).map(t=>({variant:r,key:t.key,value:t})),iu=Object.freeze(Object.defineProperty({__proto__:null,Client:yi,DeviceOntologyType:hi,deviceKeyZ:ar,deviceZ:Nt,newDeviceZ:ui,ontologyID:Gl},Symbol.toStringTag,{value:"Module"})),Tr="/hardware/rack/retrieve",au="/hardware/rack/create",ou="/hardware/rack/delete",Or=s.z.object({keys:Qe.array().optional(),names:s.z.string().array().optional(),search:s.z.string().optional(),offset:s.z.number().optional(),limit:s.z.number().optional()}),zr=s.z.object({racks:be(ir)}),cu=s.z.object({racks:ci.array()}),lu=s.z.object({racks:ir.array()}),uu=s.z.object({keys:Qe.array()}),hu=s.z.object({});let di=class{constructor(e,t,n){o(this,"type","rack");o(this,"client");o(this,"frameClient");o(this,"tasks");this.client=e,this.frameClient=t,this.tasks=n}async delete(e){await w(this.client,ou,{keys:O(e)},uu,hu)}async create(e){const t=!Array.isArray(e),n=await w(this.client,au,{racks:O(e)},cu,lu),i=this.sugar(n.racks);return t?i[0]:i}async search(e){const t=await w(this.client,Tr,{search:e},Or,zr);return this.sugar(t.racks)}async page(e,t){const n=await w(this.client,Tr,{offset:e,limit:t},Or,zr);return this.sugar(n.racks)}async retrieve(e){const{variant:t,normalized:n,single:i}=er(e,{string:"names",number:"keys"}),a=await w(this.client,Tr,{[t]:n},Or,zr),c=this.sugar(a.racks);return tr("Rack",e,c,i),i?c[0]:c}sugar(e){return e.map(({key:t,name:n})=>new fi(t,n,this.tasks))}};class fi{constructor(e,t,n){o(this,"key");o(this,"name");o(this,"tasks");this.key=e,this.name=t,this.tasks=n}async listTasks(){return await this.tasks.retrieve(this.key)}async retrieveTaskByName(e){return await this.tasks.retrieveByName(e,this.key)}async createTask(e){return e.key=((BigInt(this.key)<<32n)+(BigInt(e.key??0)&0xffffffffn)).toString(),await this.tasks.create(e)}async deleteTask(e){await this.tasks.delete([e])}}const yu=Object.freeze(Object.defineProperty({__proto__:null,Client:di,Rack:fi,RackOntologyType:li,newRackZ:ci,ontologyID:Kl,rackKeyZ:Qe,rackZ:ir},Symbol.toStringTag,{value:"Module"})),et=s.z.union([s.z.string(),s.z.bigint().transform(r=>r.toString()),s.z.number().transform(r=>r.toString())]),vt=s.z.object({task:et,variant:s.z.string(),key:s.z.string().optional(),details:s.z.record(s.z.unknown()).or(s.z.string().transform(r=>r===""?{}:JSON.parse(r))).or(s.z.array(s.z.unknown())).or(s.z.null())}),or=s.z.object({key:et,name:s.z.string(),type:s.z.string(),internal:s.z.boolean().optional(),config:s.z.record(s.z.unknown()).or(s.z.string().transform(r=>r===""?{}:Xe.JSON_CODEC.decodeString(r))),state:vt.optional().nullable()}),pi=or.omit({key:!0}).extend({key:et.transform(r=>r.toString()).optional(),config:s.z.unknown().transform(r=>Xe.JSON_CODEC.encodeString(r))}),du=s.z.object({task:et,type:s.z.string(),key:s.z.string(),args:s.z.record(s.z.unknown()).or(s.z.string().transform(r=>r===""?{}:JSON.parse(r)))}),gi="task",fu=r=>new T({type:gi,key:r.toString()}),dt="sy_task_state",Ln="sy_task_cmd";class mi{constructor(e,t,n,i,a,c=!1,l){o(this,"key");o(this,"name");o(this,"internal");o(this,"type");o(this,"config");o(this,"state");o(this,"frameClient");this.key=e,this.name=t,this.type=n,this.config=i,this.internal=c,l!==null&&(this.state=l),this.frameClient=a}get payload(){return{key:this.key,name:this.name,type:this.type,config:this.config,state:this.state,internal:this.internal}}async executeCommand(e,t){const n=await this.frameClient.openWriter(Ln),i=Ko.id();return await n.write(Ln,[{task:this.key,type:e,key:i,args:t}]),await n.close(),i}async executeCommandSync(e,t,n){const i=await this.frameClient.openStreamer(dt),a=await this.executeCommand(e,t);let c;const l=new Promise(u=>setTimeout(()=>u(!1),new S(n).milliseconds));for(;;){const u=await Promise.any([i.read(),l]);if(u===!1)throw new Error("Command timed out");const f=vt.safeParse(u.at(-1).sy_task_state);if(f.success){if(c=f.data,c.key===a)break}else console.error(f.error)}return i.close(),c}async openStateObserver(){return new St(await this.frameClient.openStreamer(dt),e=>{const t=e.get(dt);if(t.length===0)return[null,!1];const n=vt.safeParse(t.at(-1));if(!n.success)return[null,!1];const i=n.data;return i.task!==this.key?[null,!1]:[i,!0]})}}const pu=s.z.object({rack:Qe.optional(),keys:s.z.string().array().optional(),names:s.z.string().array().optional(),offset:s.z.number().optional(),limit:s.z.number().optional(),includeState:s.z.boolean().optional()}),gu=s.z.object({tasks:be(or)}),mu="/hardware/task/retrieve",wu="/hardware/task/create",bu="/hardware/task/delete",vu=s.z.object({tasks:pi.array()}),Tu=s.z.object({tasks:or.array()}),Ou=s.z.object({keys:et.array()}),zu=s.z.object({});let wi=class{constructor(e,t){o(this,"type","task");o(this,"client");o(this,"frameClient");this.client=e,this.frameClient=t}async create(e){const t=!Array.isArray(e),n=await w(this.client,wu,{tasks:O(e)},vu,Tu),i=this.sugar(n.tasks);return t?i[0]:i}async delete(e){await w(this.client,bu,{keys:O(e)},Ou,zu)}async search(e){return await this.execRetrieve({keys:[e]})}async page(e,t){return await this.execRetrieve({offset:e,limit:t})}async list(e={}){return this.sugar(await this.execRetrieve(e))}async retrieve(e,t){const{single:n,normalized:i,variant:a}=er(e,{number:"rack",string:"keys"},{convertNumericStrings:!1}),c={...t};a==="rack"?c.rack=e:c.keys=i;const l=await this.execRetrieve(c),u=this.sugar(l);return n&&a!=="rack"?u[0]:u}async retrieveByName(e,t){const n=await this.execRetrieve({names:[e],rack:t});return tr("Task",e,n,!0),this.sugar(n)[0]}async execRetrieve(e){return(await w(this.client,mu,e,pu,gu)).tasks}sugar(e){return e.map(({key:t,name:n,type:i,config:a,state:c,internal:l})=>new mi(t,n,i,a,this.frameClient,l,c))}async openTracker(){return await Re(this.frameClient,"sy_task_set","sy_task_delete",(e,t)=>Array.from(t).map(n=>({variant:e,key:n.toString(),value:n.toString()})))}async openStateObserver(){return new St(await this.frameClient.openStreamer(dt),e=>{const t=e.get(dt);if(t.length===0)return[null,!1];const n=vt.safeParse(t.at(-1));return n.success?[n.data,!0]:[null,!1]})}};const Eu=Object.freeze(Object.defineProperty({__proto__:null,Client:wi,DeviceOntologyType:gi,Task:mi,commandZ:du,newTaskZ:pi,ontologyID:fu,stateZ:vt,taskKeyZ:et,taskZ:or},Symbol.toStringTag,{value:"Module"})),tt=s.z.string().uuid(),It=s.z.object({key:tt,name:s.z.string().min(1),color:s.z.string()}),bi="label",Su=r=>new T({type:bi,key:r}),Nu=s.z.object({keys:tt.array().optional(),for:V.optional(),search:s.z.string().optional(),offset:s.z.number().optional(),limit:s.z.number().optional()}),Iu=s.z.object({labels:be(It)});var Ee;let vi=(Ee=class{constructor(e){o(this,"client");this.client=e}async retrieve(e){const t=O(e);return await this.execute({keys:t})}async retrieveFor(e){return await this.execute({for:e})}async search(e){return await this.execute({search:e})}async page(e,t){return await this.execute({offset:e,limit:t})}async execute(e){const[t,n]=await this.client.send(Ee.ENDPOINT,e,Nu,Iu);if(n!=null)throw n;return t.labels}},o(Ee,"ENDPOINT","/label/retrieve"),Ee);const Ti=It.extend({key:tt.optional()}),ku=s.z.object({labels:Ti.array()}),Au=s.z.object({labels:It.array()}),$u=s.z.object({keys:tt.array()}),Oi=s.z.object({id:V,labels:tt.array(),replace:s.z.boolean().optional()}),Ru=Oi.omit({replace:!0}),Er=s.z.object({}),xu="/label/create",Cu="/label/delete",Pu="/label/set",ju="/label/remove";let zi=class{constructor(e){o(this,"client");this.client=e}async create(e){return(await w(this.client,xu,{labels:O(e)},ku,Au)).labels}async delete(e){await w(this.client,Cu,{keys:O(e)},$u,Er)}async set(e,t,{replace:n}={}){await w(this.client,Pu,{id:e,labels:t,replace:n},Oi,Er)}async remove(e,t){await w(this.client,ju,{id:e,labels:t},Ru,Er)}};const Du="sy_label_set",Mu="sy_label_delete";let Ei=class{constructor(e,t,n){o(this,"type","label");o(this,"retriever");o(this,"writer");o(this,"frameClient");o(this,"ontology");this.writer=new zi(e),this.retriever=new vi(e),this.frameClient=t,this.ontology=n}async search(e){return await this.retriever.search(e)}async retrieve(e){const t=Array.isArray(e),n=await this.retriever.retrieve(e);return t?n:n[0]}async retrieveFor(e){return await this.retriever.retrieveFor(new T(e))}async label(e,t,n={}){await this.writer.set(new T(e),t,n)}async removeLabels(e,t){await this.writer.remove(new T(e),t)}async page(e,t){return await this.retriever.page(e,t)}async create(e){const t=Array.isArray(e),n=await this.writer.create(e);return t?n:n[0]}async delete(e){await this.writer.delete(e)}async openChangeTracker(){return await Re(this.frameClient,Du,Mu,Zu)}async trackLabelsOf(e){const t=new Ie.Observer,n=(await this.retrieveFor(e)).map(a=>({id:new T({key:a.key,type:"label"}),key:a.key,name:a.name,data:a}));return(await this.ontology.openDependentTracker(new T(e),n,"labeled_by")).onChange(a=>t.notify(a.map(c=>{var l,u;return{key:c.id.key,color:(l=c.data)==null?void 0:l.color,name:(u=c.data)==null?void 0:u.name}}))),t}};const Zu=(r,e)=>r==="delete"?e.toUUIDs().map(t=>({variant:r,key:t})):e.parseJSON(It).map(t=>({variant:r,key:t.key,value:t})),Uu=Object.freeze(Object.defineProperty({__proto__:null,Client:Ei,LabelOntologyType:bi,Retriever:vi,Writer:zi,keyZ:tt,labelZ:It,newLabelPayloadZ:Ti,ontologyID:Su},Symbol.toStringTag,{value:"Module"})),H=s.z.string().uuid(),kt=s.z.object({key:H,name:s.z.string().min(1),timeRange:W.z,color:s.z.string().optional()}),Si=kt.extend({key:s.z.string().uuid().optional()}),Ni=r=>{const e=O(r),t=e.length===0;let n=!1;return t||(n=H.safeParse(e[0]).success),{single:!Array.isArray(r),variant:n?"keys":"names",normalized:e,actual:r,empty:t}},Ii="range",ki="range-alias",Bu=r=>new T({type:Ii,key:r}),Lu=r=>new T({type:ki,key:r}),qu="sy_range_alias_set",Yu="sy_range_alias_delete",Wu=s.z.object({range:H,aliases:s.z.string().array()}),_u=s.z.object({aliases:s.z.record(s.z.string(),we)}),Fu=s.z.object({range:H,aliases:s.z.record(we.or(s.z.string()),s.z.string())}),Ku=s.z.unknown(),Gu=s.z.object({range:H,channels:we.array()}),Vu=s.z.unknown(),Ju=s.z.object({range:H}),Hu=s.z.object({aliases:s.z.record(s.z.string(),s.z.string())}),ae=class ae{constructor(e,t,n){o(this,"frameClient");o(this,"cache",new Map);o(this,"client");o(this,"rangeKey");this.rangeKey=e,this.cache=new Map,this.client=n,this.frameClient=t}async resolve(e){const t=[],n=typeof e=="string",i={};if(n){const c=this.cache.get(e);if(c!=null)return c;t.push(e)}else e.forEach(c=>{const l=this.cache.get(c);l!=null?i[c]=l:t.push(c)});if(t.length===0)return i;const a=await w(this.client,ae.RESOLVE_ENDPOINT,{range:this.rangeKey,aliases:t},Wu,_u);return Object.entries(a.aliases).forEach(([c,l])=>this.cache.set(c,l)),n?a.aliases[t[0]]:{...i,...a.aliases}}async set(e){await w(this.client,ae.SET_ENDPOINT,{range:this.rangeKey,aliases:e},Fu,Ku)}async list(){return(await w(this.client,ae.LIST_ENDPOINT,{range:this.rangeKey},Ju,Hu)).aliases}async delete(e){await w(this.client,ae.DELETE_ENDPOINT,{range:this.rangeKey,channels:e},Gu,Vu)}async openChangeTracker(){return await Re(this.frameClient,qu,Yu,eh(this.rangeKey))}};o(ae,"SET_ENDPOINT","/range/alias/set"),o(ae,"RESOLVE_ENDPOINT","/range/alias/resolve"),o(ae,"LIST_ENDPOINT","/range/alias/list"),o(ae,"DELETE_ENDPOINT","/range/alias/delete");let Mr=ae;const Xu=s.z.object({range:H,channel:we,alias:s.z.string()}),Qu="---",eh=r=>(e,t)=>e==="delete"?t.toStrings().filter(n=>n.split(Qu)[0]===r).map(n=>({variant:e,key:n,value:void 0})):t.parseJSON(Xu).map(n=>({variant:e,key:n.alias,value:n})),th=s.z.object({range:H,keys:s.z.string().array()}),Hr=s.z.object({range:H,key:s.z.string(),value:s.z.string()}),rh=s.z.object({pairs:be(Hr)}),nh=s.z.object({range:H,pairs:Hr.array()}),sh=s.z.object({range:H,keys:s.z.string().array()}),de=class de{constructor(e,t,n){o(this,"rangeKey");o(this,"client");o(this,"frameClient");this.rangeKey=e,this.client=t,this.frameClient=n}async get(e){const t=await w(this.client,de.GET_ENDPOINT,{range:this.rangeKey,keys:O(e)},th,rh);return typeof e=="string"?t.pairs[0].value:Object.fromEntries(t.pairs.map(n=>[n.key,n.value]))}async list(){return this.get([])}async set(e,t=""){let n;Br(e)?n=Object.entries(e).map(([i,a])=>({range:this.rangeKey,key:i,value:a})):n=[{range:this.rangeKey,key:e,value:t}],await w(this.client,de.SET_ENDPOINT,{range:this.rangeKey,pairs:n},nh,s.z.unknown())}async delete(e){await w(this.client,de.DELETE_ENDPOINT,{range:this.rangeKey,keys:O(e)},sh,s.z.unknown())}async openTracker(){return await Re(this.frameClient,"sy_range_kv_set","sy_range_kv_delete",(e,t)=>e==="delete"?t.toStrings().map(n=>{const[i,a]=n.split("<--->",2);return{variant:e,key:n,value:{range:i,key:a,value:""}}}):t.parseJSON(Hr).map(n=>({variant:e,key:`${n.range}${n.key}`,value:n})))}};o(de,"GET_ENDPOINT","/range/kv/get"),o(de,"SET_ENDPOINT","/range/kv/set"),o(de,"DELETE_ENDPOINT","/range/kv/delete");let Tt=de;const Sr=r=>new T({type:"range",key:r});class Ai{constructor(e,t=W.ZERO,n,i,a,c,l,u,f,g,p){o(this,"key");o(this,"name");o(this,"kv");o(this,"timeRange");o(this,"color");o(this,"channels");o(this,"aliaser");o(this,"frameClient");o(this,"labelClient");o(this,"ontologyClient");o(this,"rangeClient");this.key=n,this.name=e,this.timeRange=t,this.frameClient=a,this.color=i,this.kv=c,this.aliaser=l,this.channels=u,this.labelClient=f,this.ontologyClient=g,this.rangeClient=p}get ontologyID(){return new T({key:this.key,type:"range"})}get payload(){return{key:this.key,name:this.name,timeRange:this.timeRange,color:this.color}}async setAlias(e,t){const n=await this.channels.retrieve(e);if(n.length===0)throw new Q(`Channel ${e} does not exist`);await this.aliaser.set({[n[0].key]:t})}async deleteAlias(...e){await this.aliaser.delete(e)}async listAliases(){return await this.aliaser.list()}async resolveAlias(e){return await this.aliaser.resolve(e)}async openAliasTracker(){return await this.aliaser.openChangeTracker()}async retrieveParent(){return this.rangeClient.retrieveParent(this.key)}async retrieveChildren(){const e=(await this.ontologyClient.retrieveChildren(this.ontologyID,{excludeFieldData:!0})).map(t=>t.id.key);return await this.rangeClient.retrieve(e)}async read(e){return await this.frameClient.read(this.timeRange,e)}async labels(){return await this.labelClient.retrieveFor(Sr(this.key))}async addLabel(...e){await this.labelClient.label(Sr(this.key),e)}async removeLabel(...e){await this.labelClient.removeLabels(Sr(this.key),e)}async openChildRangeTracker(){const e=new Ie.Observer,t=(await this.retrieveChildren()).map(i=>{const a=new T({key:i.key,type:"range"});return{id:a,key:a.toString(),name:i.name,data:i.payload}}),n=await this.ontologyClient.openDependentTracker(this.ontologyID,t);return n.onChange(i=>e.notify(this.rangeClient.resourcesToRanges(i))),e.setCloser(async()=>await n.close()),e}async openParentRangeTracker(){const e=new Ie.Observer,t=await this.retrieveParent();if(t==null)return null;const n=new T({key:t.key,type:"range"}),i={id:n,key:n.toString(),name:t.name,data:t.payload},a=await this.ontologyClient.openDependentTracker(this.ontologyID,[i],"parent","to");return a.onChange(c=>{const l=this.rangeClient.resourcesToRanges(c);if(l.length===0)return;const u=l[0];e.notify(u)}),e.setCloser(async()=>await a.close()),e}}const ih=s.z.object({keys:H.array().optional(),names:s.z.array(s.z.string()).optional(),term:s.z.string().optional(),overlapsWith:W.z.optional(),limit:s.z.number().int().optional(),offset:s.z.number().int().optional()}),ah="/range/retrieve",oh=s.z.object({ranges:be(kt)});let $i=class{constructor(e,t,n,i,a,c){o(this,"type","range");o(this,"frameClient");o(this,"writer");o(this,"unaryClient");o(this,"channels");o(this,"labelClient");o(this,"ontologyClient");this.frameClient=e,this.writer=t,this.unaryClient=n,this.channels=i,this.labelClient=a,this.ontologyClient=c}async create(e,t){const n=!Array.isArray(e),i=this.sugar(await this.writer.create(O(e),t));return n?i[0]:i}async rename(e,t){await this.writer.rename(e,t)}async delete(e){await this.writer.delete(O(e))}async search(e){return this.sugar(await this.execRetrieve({term:e}))}async page(e,t){return this.sugar(await this.execRetrieve({offset:e,limit:t}))}async retrieve(e){if(typeof e=="object"&&"start"in e)return await this.execRetrieve({overlapsWith:new W(e)});const{single:t,actual:n,variant:i,normalized:a,empty:c}=Ni(e);if(c)return[];const l=await this.execRetrieve({[i]:a});if(!t)return l;if(l.length===0)throw new Ae(`range matching ${n} not found`);if(l.length>1)throw new $e(`multiple ranges matching ${n} found`);return l[0]}getKV(e){return new Tt(e,this.unaryClient,this.frameClient)}async execRetrieve(e){const{ranges:t}=await w(this.unaryClient,ah,e,ih,oh);return this.sugar(t)}async retrieveParent(e){const t=await this.ontologyClient.retrieveParents({key:e,type:"range"});if(t.length===0)return null;const n=t[0];return n.id.type!=="range"?null:await this.retrieve(n.id.key)}sugar(e){return e.map(t=>new Ai(t.name,t.timeRange,t.key,t.color,this.frameClient,new Tt(t.key,this.unaryClient,this.frameClient),new Mr(t.key,this.frameClient,this.unaryClient),this.channels,this.labelClient,this.ontologyClient,this))}async openTracker(){return await Re(this.frameClient,"sy_range_set","sy_range_delete",(e,t)=>e==="delete"?t.toStrings().map(i=>({variant:e,key:i,value:void 0})):this.sugar(t.parseJSON(kt)).map(i=>({variant:e,key:i.key,value:i})))}resourcesToRanges(e){return this.sugar(e.map(t=>{var n,i;return{key:t.id.key,name:(n=t.data)==null?void 0:n.name,timeRange:new W((i=t.data)==null?void 0:i.timeRange)}}))}};const ch=s.z.object({ranges:kt.array()}),lh=s.z.object({parent:V.optional(),ranges:Si.array()}),uh=s.z.object({keys:H.array()}),hh=s.z.object({}),yh=s.z.object({key:H,name:s.z.string()}),dh=s.z.object({}),fh="/range/create",ph="/range/delete",gh="/range/rename";let Ri=class{constructor(e){o(this,"client");this.client=e}async rename(e,t){await w(this.client,gh,{key:e,name:t},yh,dh)}async create(e,t){return(await w(this.client,fh,{ranges:e,...t},lh,ch)).ranges}async delete(e){await w(this.client,ph,{keys:e},uh,hh)}};const mh=Object.freeze(Object.defineProperty({__proto__:null,Client:$i,KV:Tt,Range:Ai,RangeAliasOntologyType:ki,RangeOntologyType:Ii,Writer:Ri,analyzeParams:Ni,keyZ:H,newPayloadZ:Si,payloadZ:kt,rangeAliasOntologyID:Lu,rangeOntologyID:Bu},Symbol.toStringTag,{value:"Module"})),wh="/api/v1/";class bh{constructor(e,t=!1){o(this,"url");o(this,"unary");o(this,"stream");o(this,"secure");this.secure=t,this.url=e.child(wh);const n=new Xe.JSONCodec;this.unary=new Ka(this.url,n,this.secure),this.stream=new ro(this.url,n,this.secure)}use(...e){this.unary.use(...e),this.stream.use(...e)}}const Xr=s.z.string().uuid(),Qr=s.z.object({key:s.z.string(),name:s.z.string(),data:qr.or(s.z.string().transform(r=>JSON.parse(r)))}),vh=s.z.object({keys:s.z.string().array()}),Th=s.z.object({linePlots:Qr.array()});let Oh=class{constructor(e){o(this,"ENDPOINT","/workspace/lineplot/retrieve");o(this,"client");this.client=e}async retrieve(e){const t=O(e);return(await w(this.client,this.ENDPOINT,{keys:t},vh,Th)).linePlots}};const ve=s.z.string().uuid(),xi=r=>JSON.parse(r),en=s.z.object({name:s.z.string(),key:ve,layout:qr.or(s.z.string().transform(r=>xi(r)))}),tn=en.omit({layout:!0}).extend({layout:s.z.string().transform(r=>xi(r))}),Ci="workspace",zh=r=>new T({type:Ci,key:r}),Eh=Qr.partial({key:!0}).transform(r=>({...r,data:JSON.stringify(r.data)})),Sh=s.z.object({workspace:ve,linePlots:Eh.array()}),Nh=s.z.object({linePlots:Qr.array()}),Ih=s.z.object({keys:Xr.array()}),kh=s.z.object({}),Ah=s.z.object({key:Xr,name:s.z.string()}),$h=s.z.object({}),Rh=s.z.object({key:Xr,data:s.z.string()}),xh=s.z.object({}),Ch="/workspace/lineplot/create",Ph="/workspace/lineplot/delete",jh="/workspace/lineplot/rename",Dh="/workspace/lineplot/set-data";let Mh=class{constructor(e){o(this,"client");this.client=e}async create(e,t){const n={...t,data:JSON.stringify(t.data)};return(await w(this.client,Ch,{workspace:e,linePlots:[n]},Sh,Nh)).linePlots[0]}async delete(e){const t=O(e);await w(this.client,Ph,{keys:t},Ih,kh)}async rename(e,t){await w(this.client,jh,{key:e,name:t},Ah,$h)}async setData(e,t){await w(this.client,Dh,{key:e,data:JSON.stringify(t)},Rh,xh)}},Zh=class{constructor(e){o(this,"writer");o(this,"retriever");this.writer=new Mh(e),this.retriever=new Oh(e)}async create(e,t){return await this.writer.create(e,t)}async rename(e,t){await this.writer.rename(e,t)}async setData(e,t){await this.writer.setData(e,t)}async retrieve(e){const t=Array.isArray(e),n=await this.retriever.retrieve(e);return t?n:n[0]}async delete(e){await this.writer.delete(e)}};const Uh=s.z.object({keys:ve.array().optional(),search:s.z.string().optional(),author:s.z.string().uuid().optional(),offset:s.z.number().optional(),limit:s.z.number().optional()}),Bh=s.z.object({workspaces:be(tn)});var Se;let Lh=(Se=class{constructor(e){o(this,"client");this.client=e}async retrieve(e){const t=O(e);return await this.execute({keys:t})}async retrieveByAuthor(e){return await this.execute({author:e})}async search(e){return await this.execute({search:e})}async page(e,t){return await this.execute({offset:e,limit:t})}async execute(e){return(await w(this.client,Se.ENDPOINT,e,Uh,Bh)).workspaces}},o(Se,"ENDPOINT","/workspace/retrieve"),Se);const cr=s.z.string().uuid(),qh=s.z.object({key:s.z.string(),name:s.z.string(),data:qr.or(s.z.string().transform(r=>JSON.parse(r))),snapshot:s.z.boolean()}),rn=s.z.object({key:s.z.string(),name:s.z.string(),snapshot:s.z.boolean(),data:s.z.string().transform(r=>JSON.parse(r))}),Yh=s.z.object({keys:s.z.string().array()}),Wh=s.z.object({schematics:rn.array()});class _h{constructor(e){o(this,"ENDPOINT","/workspace/schematic/retrieve");o(this,"client");this.client=e}async retrieve(e){return(await w(this.client,this.ENDPOINT,{keys:O(e)},Yh,Wh)).schematics}}const Fh=qh.partial({key:!0,snapshot:!0}).transform(r=>({...r,data:JSON.stringify(r.data)})),Kh=s.z.object({workspace:ve,schematics:Fh.array()}),Gh=s.z.object({schematics:rn.array()}),Vh=s.z.object({keys:cr.array()}),Jh=s.z.object({}),Hh=s.z.object({key:cr,name:s.z.string()}),qn=s.z.object({}),Xh=s.z.object({key:cr,data:s.z.string()});s.z.object({});const Qh=s.z.object({key:cr,name:s.z.string(),snapshot:s.z.boolean()}),ey=s.z.object({schematic:rn}),ty="/workspace/schematic/create",ry="/workspace/schematic/delete",ny="/workspace/schematic/rename",sy="/workspace/schematic/set-data",iy="/workspace/schematic/copy";let ay=class{constructor(e){o(this,"client");this.client=e}async create(e,t){const n={...t,data:JSON.stringify(t.data)};return(await w(this.client,ty,{workspace:e,schematics:[n]},Kh,Gh)).schematics[0]}async copy(e,t,n){return(await w(this.client,iy,{key:e,name:t,snapshot:n},Qh,ey)).schematic}async delete(e){const t=O(e);await w(this.client,ry,{keys:t},Vh,Jh)}async rename(e,t){await w(this.client,ny,{key:e,name:t},Hh,qn)}async setData(e,t){await w(this.client,sy,{key:e,data:JSON.stringify(t)},Xh,qn)}},oy=class{constructor(e){o(this,"writer");o(this,"retriever");this.writer=new ay(e),this.retriever=new _h(e)}async create(e,t){return await this.writer.create(e,t)}async rename(e,t){await this.writer.rename(e,t)}async setData(e,t){await this.writer.setData(e,t)}async retrieve(e){const t=Array.isArray(e),n=await this.retriever.retrieve(e);return t?n:n[0]}async delete(e){await this.writer.delete(e)}async copy(e,t,n){return await this.writer.copy(e,t,n)}};const cy=en.partial({key:!0}).transform(r=>({...r,layout:JSON.stringify(r.layout)})),ly=s.z.object({workspaces:cy.array()}),uy=s.z.object({workspaces:tn.array()}),hy=s.z.object({keys:ve.array()}),yy=s.z.object({}),dy=s.z.object({key:ve,name:s.z.string()}),fy=s.z.object({}),py=s.z.object({key:ve,layout:s.z.string()}),gy=s.z.object({}),my="/workspace/create",wy="/workspace/delete",by="/workspace/rename",vy="/workspace/set-layout";class Ty{constructor(e){o(this,"client");this.client=e}async create(e){return(await w(this.client,my,{workspaces:O(e)},ly,uy)).workspaces}async delete(e){await w(this.client,wy,{keys:O(e)},hy,yy)}async rename(e,t){await w(this.client,by,{key:e,name:t},dy,fy)}async setLayout(e,t){await w(this.client,vy,{key:e,layout:JSON.stringify(t)},py,gy)}}class Pi{constructor(e){o(this,"type","workspace");o(this,"schematic");o(this,"linePlot");o(this,"retriever");o(this,"writer");this.schematic=new oy(e),this.linePlot=new Zh(e),this.retriever=new Lh(e),this.writer=new Ty(e)}async search(e){return await this.retriever.search(e)}async retrieveByAuthor(e){return await this.retriever.retrieveByAuthor(e)}async retrieve(e){const t=Array.isArray(e),n=await this.retriever.retrieve(e);return t?n:n[0]}async page(e,t){return await this.retriever.page(e,t)}async create(e){const t=Array.isArray(e),n=await this.writer.create(e);return t?n:n[0]}async rename(e,t){await this.writer.rename(e,t)}async setLayout(e,t){await this.writer.setLayout(e,t)}async delete(...e){await this.writer.delete(e)}}const Oy=Object.freeze(Object.defineProperty({__proto__:null,Client:Pi,WorkspaceOntologyType:Ci,keyZ:ve,ontologyID:zh,workspaceRemoteZ:tn,workspaceZ:en},Symbol.toStringTag,{value:"Module"})),ji=s.z.object({host:s.z.string({required_error:"Host is required"}).min(1,"Host is required"),port:s.z.number({required_error:"Port is required"}).or(s.z.string({required_error:"Port is required"})),username:s.z.string().min(1,"Username is required"),password:s.z.string().min(1,"Password is required"),connectivityPollFrequency:S.z.default(S.seconds(30)),secure:s.z.boolean().optional().default(!1),name:s.z.string().optional()});class Di extends si{constructor(t){const n=ji.parse(t),{host:i,port:a,username:c,password:l,connectivityPollFrequency:u,secure:f}=n,g=new bh(new hc({host:i,port:Number(a)}),f);g.use(bc);let p;c!=null&&l!=null&&(p=new Tl(g.unary,{username:c,password:l}),g.use(p.middleware()));const j=new Yr(new wt(g.unary)),P=new Gs(g.unary,j);super(g.stream,g.unary,j);o(this,"createdAt");o(this,"props");o(this,"ranges");o(this,"channels");o(this,"auth");o(this,"user");o(this,"access");o(this,"connectivity");o(this,"ontology");o(this,"workspaces");o(this,"labels");o(this,"hardware");o(this,"control");o(this,"transport");this.createdAt=E.now(),this.props=n,this.auth=p,this.transport=g,this.channels=new Ks(this,j,g.unary,P),this.connectivity=new bt(g.unary,u,n.name),this.control=new ai(this),this.ontology=new Ls(g.unary,this);const X=new Ri(this.transport.unary);this.labels=new Ei(this.transport.unary,this,this.ontology),this.ranges=new $i(this,X,this.transport.unary,j,this.labels,this.ontology),this.access=new gl(this.transport.unary),this.user=new wl(this.transport.unary),this.workspaces=new Pi(this.transport.unary);const D=new yi(this.transport.unary,this),nn=new wi(this.transport.unary,this),Mi=new di(this.transport.unary,this,nn);this.hardware=new oi(nn,Mi,D)}get key(){return this.createdAt.valueOf().toString()}close(){this.connectivity.stopChecking()}}o(Di,"connectivity",bt);const zy=Ve.Authority;exports.AuthError=ke;exports.Authority=zy;exports.Channel=Wr;exports.ContiguityError=Pr;exports.DataType=z;exports.Density=K;exports.Frame=U;exports.MultiSeries=ks;exports.MultipleFoundError=$e;exports.NotFoundError=Ae;exports.QueryError=Q;exports.Rate=Xt;exports.RouteError=mt;exports.Series=ze;exports.Synnax=Di;exports.TimeRange=W;exports.TimeSpan=S;exports.TimeStamp=E;exports.UnexpectedError=pe;exports.ValidationError=C;exports.channel=il;exports.connection=El;exports.control=_l;exports.device=iu;exports.framer=Bl;exports.hardware=Fl;exports.label=Uu;exports.ontology=Mc;exports.rack=yu;exports.ranger=mh;exports.signals=Vl;exports.synnaxPropsZ=ji;exports.task=Eu;exports.workspace=Oy;
40
+ `);return h}),new U(l,c.series)}const n=[],i=[],a=Object.entries(e);for(let c=0;c<a.length;c++){const[l,u]=a[c],h=await this.fetchChannel(l),p=new ze({data:u,dataType:h.dataType});n.push(h.key),i.push(p)}return new U(n,i)}}class en{constructor(e,t){o(this,"name");o(this,"stream");this.stream=t,this.name=e}async receive(){const[e,t]=await this.stream.receive();if(t!=null)throw t;return e}received(){return this.stream.received()}async closeAndAck(){for(this.stream.closeSend();;){const[e,t]=await this.stream.receive();if(e!=null&&console.warn(`${this.name} received unexpected response on closure.
41
+ Please report this error to the Synnax team. ${JSON.stringify(e)}`),t!=null){if(ge.matches(t))return;throw t}}}closeSend(){this.stream.closeSend()}send(e){const t=this.stream.send(e);if(t!=null)throw t}}const qr=new E(-1);var tn=(r=>(r[r.Open=0]="Open",r[r.Next=1]="Next",r[r.Prev=2]="Prev",r[r.SeekFirst=3]="SeekFirst",r[r.SeekLast=4]="SeekLast",r[r.SeekLE=5]="SeekLE",r[r.SeekGE=6]="SeekGE",r[r.Valid=7]="Valid",r[r.Error=8]="Error",r))(tn||{}),hi=(r=>(r[r.None=0]="None",r[r.Ack=1]="Ack",r[r.Data=2]="Data",r))(hi||{});const Vl=s.z.object({command:s.z.nativeEnum(tn),span:E.z.optional(),bounds:W.z.optional(),stamp:S.z.optional(),keys:s.z.number().array().optional(),chunkSize:s.z.number().optional()}),Fl=s.z.object({variant:s.z.nativeEnum(hi),ack:s.z.boolean(),command:s.z.nativeEnum(tn),error:Ot.optional().nullable(),frame:ar.optional()}),ft=class ft{constructor(e,t){o(this,"stream");o(this,"adapter");o(this,"value");this.stream=new en("Iterator",e),this.value=new U,this.adapter=t}static async _open(e,t,n,i,a={}){const c=await or.open(n,t),l=await i.stream(ft.ENDPOINT,Vl,Fl),u=new ft(l,c);return await u.execute({command:0,keys:c.keys,bounds:new W(e),chunkSize:a.chunkSize??1e5}),u}async next(e=qr){return await this.execute({command:1,span:new E(e)})}async prev(e=qr){return await this.execute({command:2,span:new E(e)})}async seekFirst(){return await this.execute({command:3})}async seekLast(){return await this.execute({command:4})}async seekLE(e){return await this.execute({command:5,stamp:new S(e)})}async seekGE(e){return await this.execute({command:6,stamp:new S(e)})}async valid(){return await this.execute({command:7})}async close(){await this.stream.closeAndAck()}[Symbol.asyncIterator](){return new Kl(this)}async execute(e){for(this.stream.send(e),this.value=new U;;){const t=await this.stream.receive();if(t.variant===1)return t.ack;this.value.push(this.adapter.adapt(new U(t.frame)))}}};o(ft,"ENDPOINT","/frame/iterate");let Jt=ft;class Kl{constructor(e){o(this,"iter");o(this,"open",!1);this.iter=e}async next(){try{let e=!0;return this.open||(await this.iter.seekFirst()||(e=!1),this.open=!0),await this.iter.next()||(e=!1),e||await this.iter.close(),{done:!e,value:this.iter.value}}catch(e){throw await this.iter.close(),e}}}const Gl=s.z.object({keys:s.z.number().array()}),Jl=s.z.object({frame:ar,error:Ot.optional().nullable()}),Hl="/frame/stream";class cr{constructor(e,t){o(this,"stream");o(this,"adapter");this.stream=new en("Streamer",e),this.adapter=t}get keys(){return this.adapter.keys}static async _open(e,t,{channels:n}){const i=await or.open(e,n),a=await t.stream(Hl,Gl,Jl),c=new cr(a,i);return a.send({keys:i.keys}),c}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 U((await this.stream.receive()).frame))}async update(e){await this.adapter.update(e),this.stream.send({keys:this.adapter.keys})}close(){this.stream.closeSend()}[Symbol.asyncIterator](){return this}}class Nt extends Ie.Observer{constructor(t,n){super(n);o(this,"streamer");o(this,"closePromise");this.streamer=t,this.closePromise=this.stream()}async close(){this.streamer.close(),await this.closePromise}async stream(){for await(const t of this.streamer)this.notify(t)}}var rn=(r=>(r[r.Open=0]="Open",r[r.Write=1]="Write",r[r.Commit=2]="Commit",r[r.Error=3]="Error",r[r.SetAuthority=4]="SetAuthority",r))(rn||{}),Xe=(r=>(r[r.PersistStream=1]="PersistStream",r[r.Persist=2]="Persist",r[r.Stream=3]="Stream",r))(Xe||{});const Xl=r=>{switch(r){case"persist":return 2;case"stream":return 3;case"persistStream":return 1;default:if(typeof r=="number"&&r in Xe)return r;throw new Error(`invalid writer mode: ${r}`)}},Ql=new E(-1),eu=s.z.object({start:S.z.optional(),controlSubject:Je.subjectZ.optional(),keys:s.z.number().array().optional(),authorities:Je.Authority.z.array().optional(),mode:s.z.nativeEnum(Xe).optional(),errOnUnauthorized:s.z.boolean().optional(),enableAutoCommit:s.z.boolean().optional(),autoIndexPersistInterval:E.z.optional()}),tu=s.z.object({command:s.z.nativeEnum(rn),config:eu.optional(),frame:ar.optional()}),ru=s.z.object({ack:s.z.boolean(),command:s.z.nativeEnum(rn),error:Ot.optional().nullable()});var fe;let yi=(fe=class{constructor(e,t){o(this,"stream");o(this,"adapter");this.stream=new en("Writer",e),this.adapter=t}static async _open(e,t,{channels:n,start:i=S.now(),authorities:a=Je.Authority.Absolute,controlSubject:c,mode:l=1,errOnUnauthorized:u=!1,enableAutoCommit:h=!1,autoIndexPersistInterval:p=E.SECOND}){const g=await Qr.open(e,n),D=await t.stream(fe.ENDPOINT,tu,ru),P=new fe(D,g);return await P.execute({command:0,config:{start:new S(i),keys:g.keys,controlSubject:c,authorities:O(a),mode:Xl(l),errOnUnauthorized:u,enableAutoCommit:h,autoIndexPersistInterval:p}}),P}async write(e,t){const n=await this.adapter.adapt(e,t);return this.stream.send({command:1,frame:n.toPayload()}),!0}async setAuthority(e,t){let n={keys:[],authorities:[]};if(typeof e=="number"&&t==null)n={keys:[],authorities:[e]};else{let a;typeof e=="string"||typeof e=="number"?a={[e]:t}:a=e,a=await this.adapter.adaptObjectKeys(a),n={keys:Object.keys(a).map(c=>Number(c)),authorities:Object.values(a)}}return(await this.execute({command:4,config:n})).ack}async commit(){return this.errorAccumulated?!1:(await this.execute({command:2})).ack}async error(){this.stream.send({command:3});const e=await this.execute({command:3});return e.error!=null?_r(e.error):null}async close(){await this.stream.closeAndAck()}async execute(e){for(this.stream.send(e);;){const t=await this.stream.receive();if(t.command===e.command)return t;console.warn("writer received unexpected response",t)}}get errorAccumulated(){return this.stream.received()}},o(fe,"ENDPOINT","/frame/write"),fe),di=class{constructor(e,t,n){o(this,"streamClient");o(this,"retriever");o(this,"deleter");this.streamClient=e,this.retriever=n,this.deleter=new _l(t)}async openIterator(e,t,n){return await Jt._open(e,t,this.retriever,this.streamClient,n)}async openWriter(e){return(Array.isArray(e)||typeof e!="object")&&(e={channels:e}),await yi._open(this.retriever,this.streamClient,e)}async openStreamer(e){return(Array.isArray(e)||typeof e!="object")&&(e={channels:e}),await cr._open(this.retriever,this.streamClient,e)}async write(e,t,n){if(n==null){const a=t,c=await this.openWriter({start:e,channels:Object.keys(a),mode:Xe.Persist});try{await c.write(a),await c.commit()}finally{await c.close()}return}const i=await this.openWriter({start:e,channels:t,mode:Xe.Persist,errOnUnauthorized:!0,enableAutoCommit:!0,autoIndexPersistInterval:E.MAX});try{await i.write(t,n)}finally{await i.close()}}async read(e,t){const{single:n}=ye(t),i=await this.readFrame(e,t);return n?i.get(t):i}async readFrame(e,t){const n=await this.openIterator(e,t),i=new U;try{for await(const a of n)i.push(a)}finally{await n.close()}return i}async delete(e,t){const{normalized:n,variant:i}=ye(e);return i==="keys"?await this.deleter.delete({keys:n,bounds:t}):await this.deleter.delete({names:n,bounds:t})}};const nu=Object.freeze(Object.defineProperty({__proto__:null,ALWAYS_INDEX_PERSIST_ON_AUTO_COMMIT:Ql,AUTO_SPAN:qr,Client:di,Frame:U,Iterator:Jt,ObservableStreamer:Nt,Streamer:cr,Writer:yi,WriterMode:Xe,frameZ:ar,series:ci,seriesFromPayload:li,seriesToPayload:ui},Symbol.toStringTag,{value:"Module"})),su=Je.Authority,iu=Je.stateZ(s.z.number()),au=r=>{var e,t;return r.to==null?`${(e=r.from)==null?void 0:e.resource} - ${(t=r.from)==null?void 0:t.subject.name} -> released`:r.from==null?`${r.to.resource} - released -> ${r.to.subject.name} (${r.to.authority.toString()})`:`${r.to.resource} - ${r.from.subject.name} -> ${r.to.subject.name} (${r.to.authority.toString()})`};class fi extends Nt{constructor(t){super(t,n=>{const i=this.codec.decode(n.series[0].buffer);return this.merge(i),[i.transfers,!0]});o(this,"states");o(this,"codec");this.states=new Map,this.codec=new Qe.JSONCodec}subjects(){const t=new Map;return this.states.forEach(n=>t.set(n.subject.key,n.subject)),Array.from(t.values())}merge(t){t.transfers.forEach(n=>{n.from==null&&n.to==null&&console.warn("Invalid transfer: ",n),n.to==null?this.states.delete(n.from.resource):this.states.set(n.to.resource,n.to)})}}const ou="sy_node_1_control";let pi=class{constructor(e){o(this,"framer");this.framer=e}async openStateTracker(){const e=await this.framer.openStreamer(ou);return new fi(e)}};const cu=Object.freeze(Object.defineProperty({__proto__:null,Authority:su,Client:pi,StateTracker:fi,stateZ:iu,transferString:au},Symbol.toStringTag,{value:"Module"}));let gi=class{constructor(e,t,n){o(this,"tasks");o(this,"racks");o(this,"devices");this.tasks=e,this.racks=t,this.devices=n}};const lu=Object.freeze(Object.defineProperty({__proto__:null,Client:gi},Symbol.toStringTag,{value:"Module"})),et=s.z.number(),lr=s.z.object({key:et,name:s.z.string()}),mi=lr.partial({key:!0}),wi="rack",uu=r=>new T({type:wi,key:r.toString()}),ur=s.z.string(),It=s.z.object({key:ur,rack:et,name:s.z.string(),make:s.z.string(),model:s.z.string(),location:s.z.string(),configured:s.z.boolean().optional(),properties:s.z.record(s.z.unknown()).or(s.z.string().transform(r=>r===""?{}:Qe.JSON_CODEC.decodeString(r)))}),bi=It.extend({properties:s.z.unknown().transform(r=>Qe.JSON_CODEC.encodeString(r))}),vi="device",hu=r=>new T({type:vi,key:r.toString()}),Re=async(r,e,t,n)=>{const i=await r.openStreamer([e,t]),a=c=>{const l=[];return t!=null&&l.push(...c.get(t).series.flatMap(u=>n("delete",u))),e!=null&&l.push(...c.get(e).series.flatMap(u=>n("set",u))),[l,l.length>0]};return new Nt(i,a)},yu=Object.freeze(Object.defineProperty({__proto__:null,openObservable:Re},Symbol.toStringTag,{value:"Module"})),du="sy_device_set",fu="sy_device_delete",zr="/hardware/device/retrieve",pu="/hardware/device/create",gu="/hardware/device/delete",mu=s.z.object({devices:bi.array()}),wu=s.z.object({devices:It.array()}),bu=s.z.object({keys:ur.array()}),vu=s.z.object({}),Er=s.z.object({search:s.z.string().optional(),limit:s.z.number().optional(),offset:s.z.number().optional(),keys:ur.array().optional(),names:s.z.string().array().optional(),makes:s.z.string().array().optional()}),Sr=s.z.object({devices:be(It)});let Ti=class{constructor(e,t){o(this,"type","device");o(this,"client");o(this,"frameClient");this.client=e,this.frameClient=t}async retrieve(e,t){const n=!Array.isArray(e),i=await w(this.client,zr,{keys:O(e),...t},Er,Sr);return ir("Device",e,i.devices,n),n?i.devices[0]:i.devices}async search(e,t){return(await w(this.client,zr,{search:e,...t},Er,Sr)).devices}async page(e,t,n){return(await w(this.client,zr,{offset:e,limit:t,...n},Er,Sr)).devices}async create(e){const t=!Array.isArray(e),n=await w(this.client,pu,{devices:O(e)},mu,wu);return t?n.devices[0]:n.devices}async delete(e){await w(this.client,gu,{keys:O(e)},bu,vu)}async openDeviceTracker(){return await Re(this.frameClient,du,fu,Tu)}newSearcherWithOptions(e){return{type:this.type,search:async t=>await this.search(t,e),retrieve:async t=>await this.retrieve(t,e),page:async(t,n)=>await this.page(t,n,e)}}};const Tu=(r,e)=>r==="delete"?e.toStrings().map(t=>({variant:r,key:t,value:void 0})):e.parseJSON(It).map(t=>({variant:r,key:t.key,value:t})),Ou=Object.freeze(Object.defineProperty({__proto__:null,Client:Ti,DeviceOntologyType:vi,deviceKeyZ:ur,deviceZ:It,newDeviceZ:bi,ontologyID:hu},Symbol.toStringTag,{value:"Module"})),Nr="/hardware/rack/retrieve",zu="/hardware/rack/create",Eu="/hardware/rack/delete",Ir=s.z.object({keys:et.array().optional(),names:s.z.string().array().optional(),search:s.z.string().optional(),offset:s.z.number().optional(),limit:s.z.number().optional()}),kr=s.z.object({racks:be(lr)}),Su=s.z.object({racks:mi.array()}),Nu=s.z.object({racks:lr.array()}),Iu=s.z.object({keys:et.array()}),ku=s.z.object({});let Oi=class{constructor(e,t,n){o(this,"type","rack");o(this,"client");o(this,"frameClient");o(this,"tasks");this.client=e,this.frameClient=t,this.tasks=n}async delete(e){await w(this.client,Eu,{keys:O(e)},Iu,ku)}async create(e){const t=!Array.isArray(e),n=await w(this.client,zu,{racks:O(e)},Su,Nu),i=this.sugar(n.racks);return t?i[0]:i}async search(e){const t=await w(this.client,Nr,{search:e},Ir,kr);return this.sugar(t.racks)}async page(e,t){const n=await w(this.client,Nr,{offset:e,limit:t},Ir,kr);return this.sugar(n.racks)}async retrieve(e){const{variant:t,normalized:n,single:i}=sr(e,{string:"names",number:"keys"}),a=await w(this.client,Nr,{[t]:n},Ir,kr),c=this.sugar(a.racks);return ir("Rack",e,c,i),i?c[0]:c}sugar(e){return e.map(({key:t,name:n})=>new zi(t,n,this.tasks))}};class zi{constructor(e,t,n){o(this,"key");o(this,"name");o(this,"tasks");this.key=e,this.name=t,this.tasks=n}async listTasks(){return await this.tasks.retrieve(this.key)}async retrieveTaskByName(e){return await this.tasks.retrieveByName(e,this.key)}async createTask(e){return e.key=((BigInt(this.key)<<32n)+(BigInt(e.key??0)&0xffffffffn)).toString(),await this.tasks.create(e)}async deleteTask(e){await this.tasks.delete([e])}}const Au=Object.freeze(Object.defineProperty({__proto__:null,Client:Oi,Rack:zi,RackOntologyType:wi,newRackZ:mi,ontologyID:uu,rackKeyZ:et,rackZ:lr},Symbol.toStringTag,{value:"Module"})),Ce=s.z.union([s.z.string(),s.z.bigint().transform(r=>r.toString()),s.z.number().transform(r=>r.toString())]),vt=s.z.object({task:Ce,variant:s.z.string(),key:s.z.string().optional(),details:s.z.record(s.z.unknown()).or(s.z.string().transform(r=>r===""?{}:JSON.parse(r))).or(s.z.array(s.z.unknown())).or(s.z.null())}),kt=s.z.object({key:Ce,name:s.z.string(),type:s.z.string(),internal:s.z.boolean().optional(),config:s.z.record(s.z.unknown()).or(s.z.string().transform(r=>r===""?{}:Qe.JSON_CODEC.decodeString(r))),state:vt.optional().nullable(),snapshot:s.z.boolean().optional()}),Ei=kt.omit({key:!0}).extend({key:Ce.transform(r=>r.toString()).optional(),config:s.z.unknown().transform(r=>Qe.JSON_CODEC.encodeString(r))}),$u=s.z.object({task:Ce,type:s.z.string(),key:s.z.string(),args:s.z.record(s.z.unknown()).or(s.z.string().transform(r=>r===""?{}:JSON.parse(r)))}),Si="task",Ru=r=>new T({type:Si,key:r.toString()}),dt="sy_task_state",Jn="sy_task_cmd",Pt=new Error("Task not created");class Ni{constructor(e,t,n,i,a=!1,c=!1,l,u=null,h=null,p=null){o(this,"key");o(this,"name");o(this,"internal");o(this,"type");o(this,"config");o(this,"snapshot");o(this,"state");o(this,"frameClient");o(this,"ontologyClient");o(this,"rangeClient");this.key=e,this.name=t,this.type=n,this.config=i,this.internal=a,this.snapshot=c,l!==null&&(this.state=l),this.frameClient=u,this.ontologyClient=h,this.rangeClient=p}get payload(){return{key:this.key,name:this.name,type:this.type,config:this.config,state:this.state,internal:this.internal}}get ontologyID(){return new T({type:"task",key:this.key})}async executeCommand(e,t){if(this.frameClient==null)throw Pt;const n=await this.frameClient.openWriter(Jn),i=ac.id();return await n.write(Jn,[{task:this.key,type:e,key:i,args:t}]),await n.close(),i}async executeCommandSync(e,t,n){if(this.frameClient==null)throw Pt;const i=await this.frameClient.openStreamer(dt),a=await this.executeCommand(e,t);let c;const l=new Promise(u=>setTimeout(()=>u(!1),new E(n).milliseconds));for(;;){const u=await Promise.any([i.read(),l]);if(u===!1)throw new Error("Command timed out");const h=vt.safeParse(u.at(-1).sy_task_state);if(h.success){if(c=h.data,c.key===a)break}else console.error(h.error)}return i.close(),c}async openStateObserver(){if(this.frameClient==null)throw Pt;return new Nt(await this.frameClient.openStreamer(dt),e=>{const t=e.get(dt);if(t.length===0)return[null,!1];const n=vt.safeParse(t.at(-1));if(!n.success)return[null,!1];const i=n.data;return i.task!==this.key?[null,!1]:[i,!0]})}async snapshottedTo(){if(this.ontologyClient==null||this.rangeClient==null)throw Pt;if(!this.snapshot)return null;const e=await this.ontologyClient.retrieveParents(this.ontologyID);return e.length==0?null:e[0]}}const Cu=s.z.object({rack:et.optional(),keys:s.z.string().array().optional(),names:s.z.string().array().optional(),offset:s.z.number().optional(),limit:s.z.number().optional(),includeState:s.z.boolean().optional()}),xu=s.z.object({tasks:be(kt)}),Pu="/hardware/task/retrieve",Du="/hardware/task/create",ju="/hardware/task/delete",Mu="/hardware/task/copy",Zu=s.z.object({tasks:Ei.array()}),Uu=s.z.object({tasks:kt.array()}),Bu=s.z.object({keys:Ce.array()}),Lu=s.z.object({}),qu=s.z.object({key:Ce,name:s.z.string(),snapshot:s.z.boolean()}),Yu=s.z.object({task:kt});let Ii=class{constructor(e,t,n,i){o(this,"type","task");o(this,"client");o(this,"frameClient");o(this,"ontologyClient");o(this,"rangeClient");this.client=e,this.frameClient=t,this.ontologyClient=n,this.rangeClient=i}async create(e){const t=!Array.isArray(e),n=await w(this.client,Du,{tasks:O(e)},Zu,Uu),i=this.sugar(n.tasks);return t?i[0]:i}async delete(e){await w(this.client,ju,{keys:O(e)},Bu,Lu)}async search(e){return await this.execRetrieve({keys:[e]})}async page(e,t){return await this.execRetrieve({offset:e,limit:t})}async list(e={}){return this.sugar(await this.execRetrieve(e))}async retrieve(e,t){const{single:n,normalized:i,variant:a}=sr(e,{number:"rack",string:"keys"},{convertNumericStrings:!1}),c={...t};a==="rack"?c.rack=e:c.keys=i;const l=await this.execRetrieve(c),u=this.sugar(l);return n&&a!=="rack"?u[0]:u}async copy(e,t,n){const i=await w(this.client,Mu,{key:e,name:t,snapshot:n},qu,Yu);return this.sugar([i.task])[0]}async retrieveByName(e,t){const n=await this.execRetrieve({names:[e],rack:t});return ir("Task",e,n,!0),this.sugar(n)[0]}async execRetrieve(e){return(await w(this.client,Pu,e,Cu,xu)).tasks}sugar(e){return e.map(({key:t,name:n,type:i,config:a,state:c,internal:l,snapshot:u})=>new Ni(t,n,i,a,l,u,c,this.frameClient,this.ontologyClient,this.rangeClient))}async openTracker(){return await Re(this.frameClient,"sy_task_set","sy_task_delete",(e,t)=>Array.from(t).map(n=>({variant:e,key:n.toString(),value:n.toString()})))}async openStateObserver(){return new Nt(await this.frameClient.openStreamer(dt),e=>{const t=e.get(dt);if(t.length===0)return[null,!1];const n=vt.safeParse(t.at(-1));return n.success?[n.data,!0]:[null,!1]})}};const Wu=Object.freeze(Object.defineProperty({__proto__:null,Client:Ii,DeviceOntologyType:Si,Task:Ni,commandZ:$u,newTaskZ:Ei,ontologyID:Ru,stateZ:vt,taskKeyZ:Ce,taskZ:kt},Symbol.toStringTag,{value:"Module"})),tt=s.z.string().uuid(),At=s.z.object({key:tt,name:s.z.string().min(1),color:s.z.string()}),ki="label",_u=r=>new T({type:ki,key:r}),Vu=s.z.object({keys:tt.array().optional(),for:G.optional(),search:s.z.string().optional(),offset:s.z.number().optional(),limit:s.z.number().optional()}),Fu=s.z.object({labels:be(At)});var Ee;let Ai=(Ee=class{constructor(e){o(this,"client");this.client=e}async retrieve(e){const t=O(e);return await this.execute({keys:t})}async retrieveFor(e){return await this.execute({for:e})}async search(e){return await this.execute({search:e})}async page(e,t){return await this.execute({offset:e,limit:t})}async execute(e){const[t,n]=await this.client.send(Ee.ENDPOINT,e,Vu,Fu);if(n!=null)throw n;return t.labels}},o(Ee,"ENDPOINT","/label/retrieve"),Ee);const $i=At.extend({key:tt.optional()}),Ku=s.z.object({labels:$i.array()}),Gu=s.z.object({labels:At.array()}),Ju=s.z.object({keys:tt.array()}),Ri=s.z.object({id:G,labels:tt.array(),replace:s.z.boolean().optional()}),Hu=Ri.omit({replace:!0}),Ar=s.z.object({}),Xu="/label/create",Qu="/label/delete",eh="/label/set",th="/label/remove";let Ci=class{constructor(e){o(this,"client");this.client=e}async create(e){return(await w(this.client,Xu,{labels:O(e)},Ku,Gu)).labels}async delete(e){await w(this.client,Qu,{keys:O(e)},Ju,Ar)}async set(e,t,{replace:n}={}){await w(this.client,eh,{id:e,labels:t,replace:n},Ri,Ar)}async remove(e,t){await w(this.client,th,{id:e,labels:t},Hu,Ar)}};const rh="sy_label_set",nh="sy_label_delete";let xi=class{constructor(e,t,n){o(this,"type","label");o(this,"retriever");o(this,"writer");o(this,"frameClient");o(this,"ontology");this.writer=new Ci(e),this.retriever=new Ai(e),this.frameClient=t,this.ontology=n}async search(e){return await this.retriever.search(e)}async retrieve(e){const t=Array.isArray(e),n=await this.retriever.retrieve(e);return t?n:n[0]}async retrieveFor(e){return await this.retriever.retrieveFor(new T(e))}async label(e,t,n={}){await this.writer.set(new T(e),t,n)}async removeLabels(e,t){await this.writer.remove(new T(e),t)}async page(e,t){return await this.retriever.page(e,t)}async create(e){const t=Array.isArray(e),n=await this.writer.create(e);return t?n:n[0]}async delete(e){await this.writer.delete(e)}async openChangeTracker(){return await Re(this.frameClient,rh,nh,sh)}async trackLabelsOf(e){const t=new Ie.Observer,n=(await this.retrieveFor(e)).map(a=>({id:new T({key:a.key,type:"label"}),key:a.key,name:a.name,data:a}));return(await this.ontology.openDependentTracker({target:new T(e),dependents:n,relationshipType:"labeled_by"})).onChange(a=>t.notify(a.map(c=>{var l,u;return{key:c.id.key,color:(l=c.data)==null?void 0:l.color,name:(u=c.data)==null?void 0:u.name}}))),t}};const sh=(r,e)=>r==="delete"?e.toUUIDs().map(t=>({variant:r,key:t})):e.parseJSON(At).map(t=>({variant:r,key:t.key,value:t})),ih=Object.freeze(Object.defineProperty({__proto__:null,Client:xi,LabelOntologyType:ki,Retriever:Ai,Writer:Ci,keyZ:tt,labelZ:At,newLabelPayloadZ:$i,ontologyID:_u},Symbol.toStringTag,{value:"Module"})),H=s.z.string().uuid(),$t=s.z.object({key:H,name:s.z.string().min(1),timeRange:W.z,color:s.z.string().optional()}),Pi=$t.extend({key:s.z.string().uuid().optional()}),Di=r=>{const e=O(r),t=e.length===0;let n=!1;return t||(n=H.safeParse(e[0]).success),{single:!Array.isArray(r),variant:n?"keys":"names",normalized:e,actual:r,empty:t}},ji="range",Mi="range-alias",ah=r=>new T({type:ji,key:r}),oh=r=>new T({type:Mi,key:r}),ch="sy_range_alias_set",lh="sy_range_alias_delete",uh=s.z.object({range:H,aliases:s.z.string().array()}),hh=s.z.object({aliases:s.z.record(s.z.string(),we)}),yh=s.z.object({range:H,aliases:s.z.record(we.or(s.z.string()),s.z.string())}),dh=s.z.unknown(),fh=s.z.object({range:H,channels:we.array()}),ph=s.z.unknown(),gh=s.z.object({range:H}),mh=s.z.object({aliases:s.z.record(s.z.string(),s.z.string())}),ae=class ae{constructor(e,t,n){o(this,"frameClient");o(this,"cache",new Map);o(this,"client");o(this,"rangeKey");this.rangeKey=e,this.cache=new Map,this.client=n,this.frameClient=t}async resolve(e){const t=[],n=typeof e=="string",i={};if(n){const c=this.cache.get(e);if(c!=null)return c;t.push(e)}else e.forEach(c=>{const l=this.cache.get(c);l!=null?i[c]=l:t.push(c)});if(t.length===0)return i;const a=await w(this.client,ae.RESOLVE_ENDPOINT,{range:this.rangeKey,aliases:t},uh,hh);return Object.entries(a.aliases).forEach(([c,l])=>this.cache.set(c,l)),n?a.aliases[t[0]]:{...i,...a.aliases}}async set(e){await w(this.client,ae.SET_ENDPOINT,{range:this.rangeKey,aliases:e},yh,dh)}async list(){return(await w(this.client,ae.LIST_ENDPOINT,{range:this.rangeKey},gh,mh)).aliases}async delete(e){await w(this.client,ae.DELETE_ENDPOINT,{range:this.rangeKey,channels:e},fh,ph)}async openChangeTracker(){return await Re(this.frameClient,ch,lh,vh(this.rangeKey))}};o(ae,"SET_ENDPOINT","/range/alias/set"),o(ae,"RESOLVE_ENDPOINT","/range/alias/resolve"),o(ae,"LIST_ENDPOINT","/range/alias/list"),o(ae,"DELETE_ENDPOINT","/range/alias/delete");let Yr=ae;const wh=s.z.object({range:H,channel:we,alias:s.z.string()}),bh="---",vh=r=>(e,t)=>e==="delete"?t.toStrings().filter(n=>n.split(bh)[0]===r).map(n=>({variant:e,key:n,value:void 0})):t.parseJSON(wh).map(n=>({variant:e,key:n.alias,value:n})),Th=s.z.object({range:H,keys:s.z.string().array()}),nn=s.z.object({range:H,key:s.z.string(),value:s.z.string()}),Oh=s.z.object({pairs:be(nn)}),zh=s.z.object({range:H,pairs:nn.array()}),Eh=s.z.object({range:H,keys:s.z.string().array()}),de=class de{constructor(e,t,n){o(this,"rangeKey");o(this,"client");o(this,"frameClient");this.rangeKey=e,this.client=t,this.frameClient=n}async get(e){const t=await w(this.client,de.GET_ENDPOINT,{range:this.rangeKey,keys:O(e)},Th,Oh);return typeof e=="string"?t.pairs[0].value:Object.fromEntries(t.pairs.map(n=>[n.key,n.value]))}async list(){return this.get([])}async set(e,t=""){let n;Vr(e)?n=Object.entries(e).map(([i,a])=>({range:this.rangeKey,key:i,value:a})):n=[{range:this.rangeKey,key:e,value:t}],await w(this.client,de.SET_ENDPOINT,{range:this.rangeKey,pairs:n},zh,s.z.unknown())}async delete(e){await w(this.client,de.DELETE_ENDPOINT,{range:this.rangeKey,keys:O(e)},Eh,s.z.unknown())}async openTracker(){return await Re(this.frameClient,"sy_range_kv_set","sy_range_kv_delete",(e,t)=>e==="delete"?t.toStrings().map(n=>{const[i,a]=n.split("<--->",2);return{variant:e,key:n,value:{range:i,key:a,value:""}}}):t.parseJSON(nn).map(n=>({variant:e,key:`${n.range}${n.key}`,value:n})))}};o(de,"GET_ENDPOINT","/range/kv/get"),o(de,"SET_ENDPOINT","/range/kv/set"),o(de,"DELETE_ENDPOINT","/range/kv/delete");let Tt=de;const $r=r=>new T({type:"range",key:r});class Zi{constructor(e,t=W.ZERO,n,i,a,c,l,u,h,p,g){o(this,"key");o(this,"name");o(this,"kv");o(this,"timeRange");o(this,"color");o(this,"channels");o(this,"aliaser");o(this,"frameClient");o(this,"labelClient");o(this,"ontologyClient");o(this,"rangeClient");this.key=n,this.name=e,this.timeRange=t,this.frameClient=a,this.color=i,this.kv=c,this.aliaser=l,this.channels=u,this.labelClient=h,this.ontologyClient=p,this.rangeClient=g}get ontologyID(){return new T({key:this.key,type:"range"})}get payload(){return{key:this.key,name:this.name,timeRange:this.timeRange,color:this.color}}async setAlias(e,t){const n=await this.channels.retrieve(e);if(n.length===0)throw new Q(`Channel ${e} does not exist`);await this.aliaser.set({[n[0].key]:t})}async deleteAlias(...e){await this.aliaser.delete(e)}async listAliases(){return await this.aliaser.list()}async resolveAlias(e){return await this.aliaser.resolve(e)}async openAliasTracker(){return await this.aliaser.openChangeTracker()}async retrieveParent(){return this.rangeClient.retrieveParent(this.key)}async retrieveChildren(){const e=(await this.ontologyClient.retrieveChildren(this.ontologyID,{excludeFieldData:!0,types:["range"]})).map(t=>t.id.key);return await this.rangeClient.retrieve(e)}async read(e){return await this.frameClient.read(this.timeRange,e)}async labels(){return await this.labelClient.retrieveFor($r(this.key))}async addLabel(...e){await this.labelClient.label($r(this.key),e)}async removeLabel(...e){await this.labelClient.removeLabels($r(this.key),e)}async openChildRangeTracker(){const e=new Ie.Observer,t=(await this.retrieveChildren()).map(i=>{const a=new T({key:i.key,type:"range"});return{id:a,key:a.toString(),name:i.name,data:i.payload}}),n=await this.ontologyClient.openDependentTracker({target:this.ontologyID,dependents:t,resourceType:"range"});return n.onChange(i=>e.notify(this.rangeClient.resourcesToRanges(i))),e.setCloser(async()=>await n.close()),e}async openParentRangeTracker(){const e=new Ie.Observer,t=await this.retrieveParent();if(t==null)return null;const n=new T({key:t.key,type:"range"}),i={id:n,key:n.toString(),name:t.name,data:t.payload},a=await this.ontologyClient.openDependentTracker({target:this.ontologyID,dependents:[i],relationshipDirection:"to"});return a.onChange(c=>{const l=this.rangeClient.resourcesToRanges(c);if(l.length===0)return;const u=l[0];e.notify(u)}),e.setCloser(async()=>await a.close()),e}}const Sh=s.z.object({keys:H.array().optional(),names:s.z.array(s.z.string()).optional(),term:s.z.string().optional(),overlapsWith:W.z.optional(),limit:s.z.number().int().optional(),offset:s.z.number().int().optional()}),Nh="/range/retrieve",Ih=s.z.object({ranges:be($t)});let Ui=class{constructor(e,t,n,i,a,c){o(this,"type","range");o(this,"frameClient");o(this,"writer");o(this,"unaryClient");o(this,"channels");o(this,"labelClient");o(this,"ontologyClient");this.frameClient=e,this.writer=t,this.unaryClient=n,this.channels=i,this.labelClient=a,this.ontologyClient=c}async create(e,t){const n=!Array.isArray(e),i=this.sugarMany(await this.writer.create(O(e),t));return n?i[0]:i}async rename(e,t){await this.writer.rename(e,t)}async delete(e){await this.writer.delete(O(e))}async search(e){return this.sugarMany(await this.execRetrieve({term:e}))}async page(e,t){return this.sugarMany(await this.execRetrieve({offset:e,limit:t}))}async retrieve(e){if(typeof e=="object"&&"start"in e)return await this.execRetrieve({overlapsWith:new W(e)});const{single:t,actual:n,variant:i,normalized:a,empty:c}=Di(e);if(c)return[];const l=await this.execRetrieve({[i]:a});if(!t)return l;if(l.length===0)throw new Ae(`range matching ${n} not found`);if(l.length>1)throw new $e(`multiple ranges matching ${n} found`);return l[0]}getKV(e){return new Tt(e,this.unaryClient,this.frameClient)}async execRetrieve(e){const{ranges:t}=await w(this.unaryClient,Nh,e,Sh,Ih);return this.sugarMany(t)}async retrieveParent(e){const t=await this.ontologyClient.retrieveParents({key:e,type:"range"});if(t.length===0)return null;const n=t[0];return n.id.type!=="range"?null:await this.retrieve(n.id.key)}sugarOne(e){return new Zi(e.name,e.timeRange,e.key,e.color,this.frameClient,new Tt(e.key,this.unaryClient,this.frameClient),new Yr(e.key,this.frameClient,this.unaryClient),this.channels,this.labelClient,this.ontologyClient,this)}sugarMany(e){return e.map(t=>this.sugarOne(t))}async openTracker(){return await Re(this.frameClient,"sy_range_set","sy_range_delete",(e,t)=>e==="delete"?t.toStrings().map(i=>({variant:e,key:i,value:void 0})):this.sugarMany(t.parseJSON($t)).map(i=>({variant:e,key:i.key,value:i})))}resourcesToRanges(e){return e.map(t=>this.resourceToRange(t))}resourceToRange(e){var t,n,i;return this.sugarOne({key:e.id.key,name:(t=e.data)==null?void 0:t.name,timeRange:new W((n=e.data)==null?void 0:n.timeRange),color:(i=e.data)==null?void 0:i.color})}};const kh=s.z.object({ranges:$t.array()}),Ah=s.z.object({parent:G.optional(),ranges:Pi.array()}),$h=s.z.object({keys:H.array()}),Rh=s.z.object({}),Ch=s.z.object({key:H,name:s.z.string()}),xh=s.z.object({}),Ph="/range/create",Dh="/range/delete",jh="/range/rename";let Bi=class{constructor(e){o(this,"client");this.client=e}async rename(e,t){await w(this.client,jh,{key:e,name:t},Ch,xh)}async create(e,t){return(await w(this.client,Ph,{ranges:e,...t},Ah,kh)).ranges}async delete(e){await w(this.client,Dh,{keys:e},$h,Rh)}};const Mh=Object.freeze(Object.defineProperty({__proto__:null,Client:Ui,KV:Tt,Range:Zi,RangeAliasOntologyType:Mi,RangeOntologyType:ji,Writer:Bi,analyzeParams:Di,keyZ:H,newPayloadZ:Pi,payloadZ:$t,rangeAliasOntologyID:oh,rangeOntologyID:ah},Symbol.toStringTag,{value:"Module"})),Zh="/api/v1/";class Uh{constructor(e,t=!1){o(this,"url");o(this,"unary");o(this,"stream");o(this,"secure");this.secure=t,this.url=e.child(Zh);const n=new Qe.JSONCodec;this.unary=new ro(this.url,n,this.secure),this.stream=new ho(this.url,n,this.secure)}use(...e){this.unary.use(...e),this.stream.use(...e)}}const sn=s.z.string().uuid(),an=s.z.object({key:s.z.string(),name:s.z.string(),data:Kr.or(s.z.string().transform(r=>JSON.parse(r)))}),Bh=s.z.object({keys:s.z.string().array()}),Lh=s.z.object({linePlots:an.array()});let qh=class{constructor(e){o(this,"ENDPOINT","/workspace/lineplot/retrieve");o(this,"client");this.client=e}async retrieve(e){const t=O(e);return(await w(this.client,this.ENDPOINT,{keys:t},Bh,Lh)).linePlots}};const ve=s.z.string().uuid(),Li=r=>JSON.parse(r),on=s.z.object({name:s.z.string(),key:ve,layout:Kr.or(s.z.string().transform(r=>Li(r)))}),cn=on.omit({layout:!0}).extend({layout:s.z.string().transform(r=>Li(r))}),qi="workspace",Yh=r=>new T({type:qi,key:r}),Wh=an.partial({key:!0}).transform(r=>({...r,data:JSON.stringify(r.data)})),_h=s.z.object({workspace:ve,linePlots:Wh.array()}),Vh=s.z.object({linePlots:an.array()}),Fh=s.z.object({keys:sn.array()}),Kh=s.z.object({}),Gh=s.z.object({key:sn,name:s.z.string()}),Jh=s.z.object({}),Hh=s.z.object({key:sn,data:s.z.string()}),Xh=s.z.object({}),Qh="/workspace/lineplot/create",ey="/workspace/lineplot/delete",ty="/workspace/lineplot/rename",ry="/workspace/lineplot/set-data";let ny=class{constructor(e){o(this,"client");this.client=e}async create(e,t){const n={...t,data:JSON.stringify(t.data)};return(await w(this.client,Qh,{workspace:e,linePlots:[n]},_h,Vh)).linePlots[0]}async delete(e){const t=O(e);await w(this.client,ey,{keys:t},Fh,Kh)}async rename(e,t){await w(this.client,ty,{key:e,name:t},Gh,Jh)}async setData(e,t){await w(this.client,ry,{key:e,data:JSON.stringify(t)},Hh,Xh)}},sy=class{constructor(e){o(this,"writer");o(this,"retriever");this.writer=new ny(e),this.retriever=new qh(e)}async create(e,t){return await this.writer.create(e,t)}async rename(e,t){await this.writer.rename(e,t)}async setData(e,t){await this.writer.setData(e,t)}async retrieve(e){const t=Array.isArray(e),n=await this.retriever.retrieve(e);return t?n:n[0]}async delete(e){await this.writer.delete(e)}};const iy=s.z.object({keys:ve.array().optional(),search:s.z.string().optional(),author:s.z.string().uuid().optional(),offset:s.z.number().optional(),limit:s.z.number().optional()}),ay=s.z.object({workspaces:be(cn)});var Se;let oy=(Se=class{constructor(e){o(this,"client");this.client=e}async retrieve(e){const t=O(e);return await this.execute({keys:t})}async retrieveByAuthor(e){return await this.execute({author:e})}async search(e){return await this.execute({search:e})}async page(e,t){return await this.execute({offset:e,limit:t})}async execute(e){return(await w(this.client,Se.ENDPOINT,e,iy,ay)).workspaces}},o(Se,"ENDPOINT","/workspace/retrieve"),Se);const hr=s.z.string().uuid(),cy=s.z.object({key:s.z.string(),name:s.z.string(),data:Kr.or(s.z.string().transform(r=>JSON.parse(r))),snapshot:s.z.boolean()}),ln=s.z.object({key:s.z.string(),name:s.z.string(),snapshot:s.z.boolean(),data:s.z.string().transform(r=>JSON.parse(r))}),ly=s.z.object({keys:s.z.string().array()}),uy=s.z.object({schematics:ln.array()});class hy{constructor(e){o(this,"ENDPOINT","/workspace/schematic/retrieve");o(this,"client");this.client=e}async retrieve(e){return(await w(this.client,this.ENDPOINT,{keys:O(e)},ly,uy)).schematics}}const yy=cy.partial({key:!0,snapshot:!0}).transform(r=>({...r,data:JSON.stringify(r.data)})),dy=s.z.object({workspace:ve,schematics:yy.array()}),fy=s.z.object({schematics:ln.array()}),py=s.z.object({keys:hr.array()}),gy=s.z.object({}),my=s.z.object({key:hr,name:s.z.string()}),Hn=s.z.object({}),wy=s.z.object({key:hr,data:s.z.string()});s.z.object({});const by=s.z.object({key:hr,name:s.z.string(),snapshot:s.z.boolean()}),vy=s.z.object({schematic:ln}),Ty="/workspace/schematic/create",Oy="/workspace/schematic/delete",zy="/workspace/schematic/rename",Ey="/workspace/schematic/set-data",Sy="/workspace/schematic/copy";let Ny=class{constructor(e){o(this,"client");this.client=e}async create(e,t){const n={...t,data:JSON.stringify(t.data)};return(await w(this.client,Ty,{workspace:e,schematics:[n]},dy,fy)).schematics[0]}async copy(e,t,n){return(await w(this.client,Sy,{key:e,name:t,snapshot:n},by,vy)).schematic}async delete(e){const t=O(e);await w(this.client,Oy,{keys:t},py,gy)}async rename(e,t){await w(this.client,zy,{key:e,name:t},my,Hn)}async setData(e,t){await w(this.client,Ey,{key:e,data:JSON.stringify(t)},wy,Hn)}},Iy=class{constructor(e){o(this,"writer");o(this,"retriever");this.writer=new Ny(e),this.retriever=new hy(e)}async create(e,t){return await this.writer.create(e,t)}async rename(e,t){await this.writer.rename(e,t)}async setData(e,t){await this.writer.setData(e,t)}async retrieve(e){const t=Array.isArray(e),n=await this.retriever.retrieve(e);return t?n:n[0]}async delete(e){await this.writer.delete(e)}async copy(e,t,n){return await this.writer.copy(e,t,n)}};const ky=on.partial({key:!0}).transform(r=>({...r,layout:JSON.stringify(r.layout)})),Ay=s.z.object({workspaces:ky.array()}),$y=s.z.object({workspaces:cn.array()}),Ry=s.z.object({keys:ve.array()}),Cy=s.z.object({}),xy=s.z.object({key:ve,name:s.z.string()}),Py=s.z.object({}),Dy=s.z.object({key:ve,layout:s.z.string()}),jy=s.z.object({}),My="/workspace/create",Zy="/workspace/delete",Uy="/workspace/rename",By="/workspace/set-layout";class Ly{constructor(e){o(this,"client");this.client=e}async create(e){return(await w(this.client,My,{workspaces:O(e)},Ay,$y)).workspaces}async delete(e){await w(this.client,Zy,{keys:O(e)},Ry,Cy)}async rename(e,t){await w(this.client,Uy,{key:e,name:t},xy,Py)}async setLayout(e,t){await w(this.client,By,{key:e,layout:JSON.stringify(t)},Dy,jy)}}class Yi{constructor(e){o(this,"type","workspace");o(this,"schematic");o(this,"linePlot");o(this,"retriever");o(this,"writer");this.schematic=new Iy(e),this.linePlot=new sy(e),this.retriever=new oy(e),this.writer=new Ly(e)}async search(e){return await this.retriever.search(e)}async retrieveByAuthor(e){return await this.retriever.retrieveByAuthor(e)}async retrieve(e){const t=Array.isArray(e),n=await this.retriever.retrieve(e);return t?n:n[0]}async page(e,t){return await this.retriever.page(e,t)}async create(e){const t=Array.isArray(e),n=await this.writer.create(e);return t?n:n[0]}async rename(e,t){await this.writer.rename(e,t)}async setLayout(e,t){await this.writer.setLayout(e,t)}async delete(...e){await this.writer.delete(e)}}const qy=Object.freeze(Object.defineProperty({__proto__:null,Client:Yi,WorkspaceOntologyType:qi,keyZ:ve,ontologyID:Yh,workspaceRemoteZ:cn,workspaceZ:on},Symbol.toStringTag,{value:"Module"})),Wi=s.z.object({host:s.z.string({required_error:"Host is required"}).min(1,"Host is required"),port:s.z.number({required_error:"Port is required"}).or(s.z.string({required_error:"Port is required"})),username:s.z.string().min(1,"Username is required"),password:s.z.string().min(1,"Password is required"),connectivityPollFrequency:E.z.default(E.seconds(30)),secure:s.z.boolean().optional().default(!1),name:s.z.string().optional()});class _i extends di{constructor(t){const n=Wi.parse(t),{host:i,port:a,username:c,password:l,connectivityPollFrequency:u,secure:h}=n,p=new Uh(new Ec({host:i,port:Number(a)}),h);p.use(jc);let g;c!=null&&l!=null&&(g=new Zl(p.unary,{username:c,password:l}),p.use(g.middleware()));const D=new Gr(new wt(p.unary)),P=new ni(p.unary,D);super(p.stream,p.unary,D);o(this,"createdAt");o(this,"props");o(this,"ranges");o(this,"channels");o(this,"auth");o(this,"user");o(this,"access");o(this,"connectivity");o(this,"ontology");o(this,"workspaces");o(this,"labels");o(this,"hardware");o(this,"control");o(this,"transport");o(this,"clientVersion","0.29.0");this.createdAt=S.now(),this.props=n,this.auth=g,this.transport=p,this.channels=new ri(this,D,p.unary,P),this.connectivity=new bt(p.unary,u,this.clientVersion,n.name),this.control=new pi(this),this.ontology=new Js(p.unary,this);const X=new Bi(this.transport.unary);this.labels=new xi(this.transport.unary,this,this.ontology),this.ranges=new Ui(this,X,this.transport.unary,D,this.labels,this.ontology),this.access=new xl(this.transport.unary),this.user=new Dl(this.transport.unary),this.workspaces=new Yi(this.transport.unary);const j=new Ti(this.transport.unary,this),un=new Ii(this.transport.unary,this,this.ontology,this.ranges),Vi=new Oi(this.transport.unary,this,un);this.hardware=new gi(un,Vi,j)}get key(){return this.createdAt.valueOf().toString()}close(){this.connectivity.stopChecking()}}o(_i,"connectivity",bt);const Yy=Je.Authority;exports.AuthError=ke;exports.Authority=Yy;exports.Channel=Jr;exports.ContiguityError=Br;exports.DataType=z;exports.Density=F;exports.Frame=U;exports.MultiSeries=Ms;exports.MultipleFoundError=$e;exports.NotFoundError=Ae;exports.QueryError=Q;exports.Rate=tr;exports.RouteError=mt;exports.Series=ze;exports.Synnax=_i;exports.TimeRange=W;exports.TimeSpan=E;exports.TimeStamp=S;exports.UnexpectedError=pe;exports.ValidationError=x;exports.channel=Ol;exports.connection=Ll;exports.control=cu;exports.device=Ou;exports.framer=nu;exports.hardware=lu;exports.label=ih;exports.ontology=el;exports.rack=Au;exports.ranger=Mh;exports.signals=yu;exports.synnaxPropsZ=Wi;exports.task=Wu;exports.workspace=qy;